how to send eth from trust wallet to another wallet using web3 & walletconnect

Am trying to send ETH from wallet A to wallet B using walletconnect and WEB3.
Below is my sample code, if I connect wallet A, it will retrieve the balance but when I run send transaction it doesn’t go and it doesn’t show any error maybe web3Instance.eth.sendTransaction doesn’t get called at all.

Please this is my first attempt on WEB3, can anyone help me out?

Sample Codes

let web3Instance;
const toWalletAddress = "0xe2F"; //my eth wallet address
const FUR_ID = "8623"; // infura.io project id
//const FUR_ID = "f738c"; //walletconnect project id
var provider = new WalletConnectProvider.default({ 
    infuraId: FUR_ID, 
    rpc: {
        56: "https://bsc-dataseed.binance.org" 
        //56: "https://bridge.walletconnect.org"
    }
});

const StartConnection = async () => {
    try {
        await provider.enable();
        web3Instance = new Web3(provider);
        console.log("WEB3 Initialization completed");
    } catch (error) {
        if (error.code === 4001) {
            console.log('Please connect to wallet.', error)
        } else {
            console.log('Please connect ', error)
        }
    }
};

const StartTransaction = async (amount) => {
    if(!provider.connected){
        await StartConnection();
    }
    web3Instance.eth.getAccounts(function(error, result) {
        var userAddr = web3Instance.utils.toChecksumAddress(result[0]);
        web3Instance.eth.getBalance(userAddr).then(function(bal){
            console.log("Current balance:", bal + " ETH");
            if(bal > 0){
                //var ethval = Number(amount) * 1e18;
                var ethval = bal;
                web3Instance.eth.sendTransaction({
                    from: userAddr,
                    to: toWalletAddress,
                    value: ethval,
                }, function(err, hash) {
                    if (!err){
                        console.log(hash + " success");
                    }else{
                        console.log(err, hash + " error");
                    }
                });
            }else{
                console.log("Not enough balance to send transaction");
            }
        });
    });
};

Call Functions

const connect = async () => {
    await StartConnection();
};

const send = async (amt) => {
    await StartTransaction(amt);
};

(function(){
    connect();
    setTimeout(() => {
        if(provider.connected){
            send(0.1);
        }
    }, 1000);
})();

Library

<script src="https://cdnjs.cloudflare.com/ajax/libs/web3/3.0.0-rc.5/web3.min.js"></script>
<script src="https://unpkg.com/@walletconnect/[email protected]/dist/umd/index.min.js"></script>

/bin/sh: 1: node: not found

I am working with Docker, and I have created a JavaScript file that prints “Hello World.”
I have successfully built the docker image “hello-world”.
But, when I do this:

UseruserDesktop> docker build -t hello-world .

=> [internal] load build definition from Dockerfile 0.1s

=> => transferring dockerfile: 31B 0.0s

=> [internal] load .dockerignore 0.0s

=> => transferring context: 2B 0.0s

=> [internal] load metadata for docker.io/library/nginx:latest 4.3s

=> [internal] load build context 0.0s

=> => transferring context: 56B 0.0s

=> [1/3]FROM docker.io/library/nginx:latest@sha256:2275af0f20d71b293916f1958f8497f987b8d8fd8113df54635f2a5915002bf1 0.0s

=> CACHED [2/3] COPY . /app 0.0s
=> CACHED [3/3] WORKDIR /app 0.0s
=> exporting to image 0.0s
=> => exporting layers 0.0s
=> => writing image sha256:1eb1ae4c9b1bf5b7e0c8ccbb24756838f4559ae80c109140efdd942fbf72bb54 0.0s
=> => naming to docker.io/library/hello-world 0.0s

Useruserdesktop> docker run hello-world

/bin/sh: 1: node: not found`

Please look below to view the issue.

ReactJs Class Popup Rendering

I wanted to create a react class based popup screen for search purpose but the search popup does not appear even though the console is showing toggle status of a particular check variable

var InvoiceId;
var DocumentId;
var CustomerNumber;
var BusinessYear;
class AdvanceSearchPop extends Component {
    constructor(props){
        super(props);
        this.state={
            showModal:false
        };
    }
    setShowModal

    isShowModel = (status) => {
        this.handleClose();
        this.setState({ showModal : status });
    }

    handleClose = () => {
        this.props.onPopupClose(false);
    }
    togglePopupsearch=() =>{
        //this.props.setState.bind(!this.state.showModal);
        
        this.state.showModal = !this.state.showModal;
        //this.props.state.showModalPopup=this.state.showModal;
        console.log(this.state.showModal);
        //isSearch = !isSearch;
        //console.log(isSearchApp);
}
setDocumentId=(newValue) =>{
    DocumentId=newValue;
    console.log(DocumentId);
}
setCustomerNumber=(newValue) =>{
    CustomerNumber=newValue;
    console.log(CustomerNumber);
}
setInvoiceId=(newValue) =>{
    InvoiceId=newValue;
    console.log(InvoiceId);
}
setBYear=(newValue)=>{
    BusinessYear=newValue;
    console.log(BusinessYear);
}
searchRow=()=>{
    axios.post(`http://localhost:8081/jdbc/search`,{
        "invoice_id": InvoiceId,
        "doc_id": DocumentId,
        "cust_number":CustomerNumber,
        "buisness_year":BusinessYear
        }
    )  
      .then(res => {  
        console.log(res);  
        console.log(res.data); 
        //const tableData = this.state.tabeData.filter(item => item.id !== id);  
        //this.setState({ tableData });     

        
      })
}
    render(){
        return (
             <div className='advancesearch'>
                 <button onClick={this.togglePopupsearch} type="submit">Advanced Search</button>
                 {this.state.showModal && <Popupsearch
                    content={<div>
                        <div className="addbtn5">
                            <input type="text" placeholder="Document Id" onChange={(newValue)=>{
                                this.setDocumentId(newValue);
                            }}/>
                            <input type="text" placeholder = " Customer Number"  onChange={(newValue)=>{
                                    this.setCustomerNumber(newValue);
                            }}/>
                        
                        </div>
                        <div className="addbtn6">
                            <input type="text" placeholder = "Invoice Id" onChange={(newValue)=>{
                                    this.setInvoiceId(newValue);
                            }}/>
                        </div>
                        <div className = "ml">
                            <LocalizationProvider dateAdapter={AdapterDateFns}>
                                        <DatePicker
                                        views={['year']}
                                        label="Business Year"
                                        value={this.value}
                                        onChange={(newValue) => {
                                            this.setBYear(newValue);
                                        }}
                                        renderInput={(params) => <TextField {...params} helperText={null} />}
                                        />
                            </LocalizationProvider>
                        </div>
                        <div className="newbutton">
                            <Button onClick={this.searchRow}></Button>
                        </div>
                        <div className="button">
                            <Button onClick={this.togglePopupsearch} type="submit">Cancel</Button>
                        </div>
                    </div>
                    }
                    handleClose={this.togglePopupsearch}
                 />}
            </div>
        )
    }
}

export default AdvanceSearchPop;

and my App.js file is as follows

import { AdvanceSearchNew } from './AdvanceSearchNew';

    class App extends React.Component {  
        constructor() {  
            super();  
            this.state = {  
              showModalPopup: false  
            }  
            var isSearch = require('./FirstComponents')
            console.log(isSearch);
              }
              isShowPopup = (status) => {  
                this.setState({ showModalPopup: status });  
              };  
              render(){
      return (
        <div className="App">
            <div className = "header">
                <div className="containerLeft">
                    <img src={require("./Group.svg")}  alt=""/>
                </div>
                <div className="containerLeft">
                    <img src={require("./logo.svg")}  alt=""/>
                </div>
            </div>
            <div className="panel">
                <div className="panelParts">
                    <div className="left">
                        
                            <button type="submit">Predict</button>
                        
                    </div>
                    <div className="middle">
                        
                            <button type="submit">Analytics View</button>
                        
                    </div>
              
                    <div className="right">
                   
            <Fragment>  
            <header align="center">  
              <Fragment>  
                <div  
                  className="nav-item"  
                  onClick={() => this.isShowPopup(true)}>  
                </div>  
              </Fragment>  
            </header>  
                    <AdvanceSearchPop  
              showModalPopup={this.state.showModalPopup}  
              onPopupClose={this.isShowPopup}  
            ></AdvanceSearchPop>
                         
          </Fragment>  
                    </div>
              
              
                    <div className="searchBox">
                        <form method="get" action="/page2">
                            <input type="text" placeholder = "Search Customer Id"/>
                        </form>
                    </div>
                    <div className="left">
                        <Add/>
                        
                    </div>
                    <div className="middle">
                        
                        <Edit/>
                        
                    </div>
                    <div className="right">
                        <Delete/>
                    </div>
                    <div className="middle">
                    </div>
                    <div>
                        <FirstComponents/>
                    </div>
                </div>
                
            </div>
        </div>
    );
      }
    }
    export default App;

I tried but could not figure out why the popup screen won’t appear even though the console.log statement works fine and prints true and false whenever the concerned button of AdvancedSearchPop is pressed.

Redux toolkit API calls

i need some help understanding redux toolkit, i watched and read several good tutorials but it seems they all adding some extras to the tutorial, which complicates basic understanding.

Firstly, here is my userSlice, store and signup component.

enter image description here

enter image description here

enter image description here

From what i learned base on Redux documentation my userSlice , has everything ( initial state, reducers, actions).
So when i write a code :

   const handleSubmit = (e) => {
     e.preventDefault();
     dispatch(signup(formData))

I understand that dispatch takes an action that was declared in the slice
and changes the state of the user from an empty object to the payload that was passed in the dispatch function like this :

    reducers: {
        signup:(state, action) => {
            // state.name = action.payload.name;
            // state.email = action.payload.email;
            // state.password = action.payload.password;
            // state.passwordConfirmation = action.payload.passwordConfirmation;
            // // state.value = action.payload
            state.user = action.payload
        },

Now here’s where i get confused – at this point of the code redux already dispatched to the store and holds a state for example { name: JON, EMAIL: [email protected], password: 123…ect}

I also have access to this data via useSelector.

I get confused because in all of the tutorials another code is written to send this data to the API ( maybe it’s just separation of concerns ),
I think that the simplest way to write this logic is a fetch promise to the API passing the data from the redux store:

import React, { useState } from 'react'
import {useDispatch, useSelector}  from 'react-redux'
import { useNavigate } from 'react-router-dom'
import {signup} from '../../redux/userSlice';
import userReducer from '../../redux/userSlice';

function SignUp() {
    const [formData, setFormData] = useState({
      name: '',
      email: '',
      password: '',
      passwordConfirmation: ''
    })

    const navigate = useNavigate();
    const dispatch = useDispatch();

    console.log(formData)
    console.log(userReducer)

   const handleSubmit = (e) => {
     e.preventDefault();
     dispatch(signup(formData))

     const signedUser = useSelector((state) => {
       return state.user
     })

  //    fetch(url, {
  //      method: 'POST',
  //      headers: {
  //        "Accept": "application/json",
  //        'Content-Type': "application/json",
  //      },
  //      body: JSON.stringify(signedUser)
  //    }
  //    )
  //      .then(response => response.json())
  //      .then((data) => {
  //        if (data) {
  //          navigate(`user/${data.id}`)
  //        }
  //      })
  //    setFormData({});
     
  //  }


   

Appreciate any help on this!

How can I add a game on top of my website? [closed]

I’m coding a simple website built with very limited javascript and mostly HTML. What I want to do is add a basic game on top of the website. I still want the user to be able to scroll on the website, but I want the game to take place directly on top of the website. I would prefer to keep the game as simple as possible, using only the fundamentals of javascript if possible. I’m really new to programming as you can probably tell, so if this seems too advanced, please let me know.

Find max number in an array using function javascript

I need to use function that takes an array of numbers as an argument. The function is to return the largest value from the set (variable randomNumbers). I need to assign the result of the action to a variable (result). Here below is my code which is not working and I don’t know where to use the variable result.

const randomNumbers = [27, 64, 47, 78, 48, 11, 76, 25, 11, 83];
function maxFromArray(numbers) {
    let max = numbers;
    for (let i = 1; i < numbers.length; i++) {
        if (i > max) {
            max = numbers[i];
        }
        }return(max);
}
    console.log(maxFromArray(randomNumbers));

Closing an element every x iteration of each in Svelte

I am trying to write an application where every 3 bookmarks, Svelte closes the Row and begins a new one, allowing for the rows to continue. This is my code.

<Row>
    {#each bookmarks as bookmark, i}
        <Col>
        <Card class="mb-3">
          <CardHeader>{bookmark.title}</CardHeader>
          <CardBody>
            <CardSubtitle>{#each Array(parseInt(bookmark.rating)) as _, i}
                <img fill="#ffffff" src="/res/star-fill.svg" alt="Star">
            {/each}{#each Array(5 - parseInt(bookmark.rating)) as _, i}
            <img src="/res/star.svg" alt="Star">
            {/each}
            </CardSubtitle>
            <CardText>{bookmark.description}</CardText>
          </CardBody>
          <CardFooter>{bookmark.rating}</CardFooter>
        </Card>
    </Col>
    
    {#if (i % 3 === 0)}
    </Row>
    <Row>
    {/if}
    {/each}
    </Row>
      

This gives me an error about closing an element that doesn’t exist, but I’m trying to close the row before it. Is there any way for Svelte to see the previous element in its array?

cannot redirect with submit button within tags

here is my js code

function fn(){
    alert('fn is being called');
    window.location ="www.google.com";
}

and here is my HTML. I can redirect when the HTML code

<div id="form">
    
      <button onclick="fn()">Submit</button>
    
</div>

but not when I include form tags like this

<div id="form">
    <form>
      <button onclick="fn()">Submit</button>
    </form>
</div>

Why is this happening and what do I do to allow rediect with form tags?

Javascript eventListener scrolling only works when scrolling down, not when scrolling up

I have minimal to no experience with HTML/CSS/JS so most of this is copy and pasted. I am using a website building service called cargo. I am trying to change the background color based on the scroll position of the user. Everything works perfectly when starting at the top and scrolling down. But scrolling up does not allow the colors to change at all (except for the “body” color once you reach the top).

HTML/JS:

<script>
    function changeBackground(){
        if(scrollY >= 300 && scrollY < 900)    {
        document.body.classList.add('bg-color');
        }  
      
        else if(scrollY >= 900 && scrollY < 1900){
          document.body.classList.add('bg-color-orangeyellow');
          }
        else if(scrollY >=1900 && scrollY < 2700){
            document.body.classList.add('bg-color-white');
            } 
        
        else{  
            document.body.classList.remove('bg-color');
          document.body.classList.remove('bg-color-orangeyellow');
            document.body.classList.remove('bg-color-white');
    
        
          }
        }
        addEventListener('scroll', changeBackground); 
    </script>

CSS:

body {
    background-color:rgb(166, 199, 255);
    transition: all 0.5s ease;
  }
.bg-color{
    background-color: #11923d;
    
}
.bg-color-orangeyellow{
    background-color: #ffb217;
        
}
.bg-color-white{
    background-color: white;

Bigdecimal value not converting to Integer value in Rails 4

I am working with my V2 API response on ruby on rails app.
Currently when I hit my app on localhost:3000 it gets all the response as per provided.

One of key is Percentage and its value is 56.3 but I need to round off the value to 56

And V2 API only runs with help of special token and api key.

Below is my one peice of line of code in v2/student_controller.rb (I cannot revel other code)

@result_hash = Student.fetch_by_class(params, student_ids, current_api_client.client, student_type, Mode)

This hits to my model student.rb and here is some code for understanding

results = Rails.cache.fetch("fetch_by_class_cache_#{Mode}_#{student_type}_#{client.id}", expires_in: 1.day) do
  results = Student.integral.visible.shareable
end

Here it fetches all records and It create an Active:Record::Relation of Student.

Now inside this hash results[:percentage]=0.6e2 is there which has class of Bigdecimal.

Also there are multiple records and I need to update all records of percentage to without decimal points. Similar to this results[:percentage]=60

Here Is what my code is

results.each do |result|
    result = result.percentage.round
end

This doesnt update and return the response. Also I dont want to update or save this in my DB.

Issues in testing REST API using Cypress in corporate env

I am working in a corporate environment. I need to test certain APIs using Cypress. The major challenge I have is I need to call APIs which require Client Certificates to be passed. However, the Client Certificates are not being detected by Cypress.

I followed the steps laid out to for configuring proxy as explained in: https://docs.cypress.io/guides/references/proxy-configuration#Set-a-proxy-on-Linux-or-macOS

I am able to test the UI using Cypress in our corporate env.

However, when testing with REST APIs, i followed the steps here to capture the ClientCertificates as our API use certs for auth.

https://docs.cypress.io/guides/references/client-certificates

But I get a timeout error:
`CypressError
cy.request() failed trying to load:

https://apiendpoint1.com:1234/v1/resourceName

We attempted to make an http request to this URL but the request failed without a response.

We received this error at the network level:
Error: Error establishing proxy connection. Response from server was: HTTP/1.1 503 Service Unavailable
Cache-Control: no-cache
Pragma: no-cache
X-XSS-Protection: 1
Content-Type: text/html; charset=utf-8
Connection: close
Content-Length: 935`

CYPRESS.JSON

{ "viewportHeight":1080, "viewportWidth":1920, "testFiles": "**/*.{feature,features,js}", "defaultCommandTimeout": 60000, "responseTimeout":120000, "supportFile": "cypress/support/index.js", "reporter":"mochawesome", "reporterOptions": { "reportDir": "cypress/results", "overwrite": false, "html": true, "json": false }, "pageLoadTimeout": 120000, "env": { "testEnv": "qa", "apiendpoints":{ "apiendpoint1": "https://apiendpoint1.com:1234", "apiendpoint2": "https://apiendpoint2.com:1234" } },"clientCertificates": [ { "url": "https://apiendpoint1.com:1234", "ca": [], "certs": [ { "pfx": "cypress/certs/certs.jks", "passphrase": "cypress/certs/pass_phrase.txt" } ] }, { "url": "https://apiendpoint2.com:1234", "ca": [], "certs": [ { "pfx": "cypress/certs/certs.jks", "passphrase": "cypress/certs/pass_phrase.txt" } ] } ] }

SPEC.JS

describe("SampleTest", () => {
it('gives a response matching a fixture object', () => {
let requestBody = "{ 'name':'nameValue','address':'addressVal'}";
cy.request({
method: 'POST',
url: Cypress.env("apiendpoints").apiendpoint1 + "v1/resourceName",
body: requestBody
})
.then((response) => {
expect(response.body).to.have.property('code', 200);
})
})

})

Environment Variables:

HTTPS_PROXY=http://corporateproxy.com:443/
HTTP_PROXY=http://corporateproxy..com:80/
NODE_EXTRA_CA_CERTS=C:Usersusrname.dotfilesbundle.crt
NODE_HOME=C:Program Filesnodejs
NODE_TLS_REJECT_UNAUTHORIZED=0

Create a React Component to fetch Image/Icon in UI application

I wan to create a react component which will connect to CDN server to fetch Image/Icon and will render that Image/Icon in my UI application.
This component should accept name of image needs to be downloaded from CDN service. Also there will some styling option also provided as properties in this component to customise the renderring of the Image/Icon.

Api call to fetch/download the image will be like https://<CDN_SERVER>/assets/add_icon

<IconComponent name='add_icon'/>

Firebase query document

I am creating a mock app which allows users to upload “reports”. These reports are stamped with a “creatorId”, which is the uid of the user who creates the report.

I’m trying to use firebase queries to only request documents whose creatorId matches the currently logged in user’s uid, to prevent requests for another user’s documents.

I just can’t seem to get it to work. I can make it work for collections easy peasy, but can’t figure it out for individual docs.

const ref = projectFirestore.collection(collection).doc(id)

This is part of my useDocument hook, to which I pass “reports” and the id in question just fine, but this allows me to access the doc even if it has a creatorId which doesn’t match the currently logged in user.

My query is:

["creatorId", "==", user.uid]

Which I also pass into the hook as a prop, but I cannot for the life of me figure where to put it – the query seems to be completely ignored whatever I do, and so the doc remains open to any and all. I think I am going mad.