Search code examples
javascriptethereumweb3jsmetamaskbinance-smart-chain

Metamask (web3) connect wallet and send transaction - how to change blockchain to Bianance smart chain (BEP-20) network instead of Ethereum?


there is simple source code in HTML and JS about button to connecting wallet as a web3 and loading ETH transaction in Metamask.

javascript

const ethereumButton = document.querySelector('.enableEthereumButton');
const sendEthButton = document.querySelector('.sendEthButton');

let accounts = [];

//Sending Ethereum to an address
sendEthButton.addEventListener('click', () => {
  ethereum
    .request({
      method: 'eth_sendTransaction',
      params: [
        {
          from: accounts[0],
          to: '0x2f318C334780961FB129D2a6c30D0763d9a5C970',
          value: '0x29a2241af62c0000',
          gasPrice: '0x09184e72a000',
          gas: '0x2710',
        },
      ],
    })
    .then((txHash) => console.log(txHash))
    .catch((error) => console.error);
});

ethereumButton.addEventListener('click', () => {
  getAccount();
});

async function getAccount() {
  accounts = await ethereum.request({ method: 'eth_requestAccounts' });
}

HTML

<button class="enableEthereumButton btn">Enable Ethereum</button>
<button class="sendEthButton btn">Send Eth</button>

I would like to ask, how to change code to determine loading of Binance smart chain network (BEP-20) instead of ETH. I tried to find and change ETH contract which would be changed to BEP-20 contract but I don´t see contract there.

Second problem there is that this code contains value of 3 ETH which are loaded for transaction.

I would like to ask where is value set up to 3?


Solution

  • how to change code to determine loading of Binance smart chain network (BEP-20) instead of ETH

    You can send a wallet_switchEthereumChain request to MetaMask. Code example in the linked documentation. BSC chain ID is 56 (decimal), which is 0x38 in hex, and the mainnet RPC URL is https://bsc-dataseed.binance.org/ (source).

    where is value set up to 3?

    It's the value param of the eth_sendTransaction method. 0x29a2241af62c0000 in hex is 3000000000000000000 in decimal, the amount of wei.