How to send transaction from Polygon test network using web3.js?

Viewed 26

I am trying to integrate transaction using Polygon test network by Web3.js. The same code is working fine for ethereum. But how to send transaction using Polygon test network? Do I need to modify any code ? I have created the polygon mumbai test network in Metamask.

    const initPayButton = () =>{
        
            sendTransaction({
                to: paymentAddress,
                value: toWei(amountEth, 'ether')
            }, (err, transactionId)=>{
                if(err){
                    console.log("Payment Failed", err)
                    $('#status').html("Payment failed")
                }else{
                    console.log("Payment Successful", transactionId)
                    $('#status').html("Payment Successful")
                }
            }
            )
        }

        )
    }
2 Answers

Here is my code to send MATIC.(This is code snippet of my React Native Project)

window.ethersProvider = new ethers.getDefaultProvider()

function send_token(
    contract_address,(Matic Contract address : 0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0)
    send_token_amount,
    recipentAddress,
    send_account,
    private_key
  ) {
    console.log("send transaction");
    let wallet = new ethers.Wallet(private_key)
    let walletSigner = wallet.connect(window.ethersProvider)

    window.ethersProvider.getGasPrice().then((currentGasPrice) => {
      let gas_price = ethers.utils.hexlify(parseInt(currentGasPrice))
      console.log(`gas_price: ${gas_price}`)

      if (contract_address) {
        // general token send
        let contract = new ethers.Contract(
          contract_address,
          send_abi,
          walletSigner
        )

        // How many tokens?
        let numberOfTokens = ethers.utils.parseUnits(send_token_amount, 18)
        console.log(`numberOfTokens: ${numberOfTokens}`)

        // Send tokens
        contract.transfer(recipentAddress, numberOfTokens).then((transferResult) => {
          console.dir(transferResult)
          alert("sent token")
        })
      } // ether send
      else {
        const tx = {
          from: send_account,
          to: recipentAddress,
          value: ethers.utils.parseEther(send_token_amount),
          nonce: window.ethersProvider.getTransactionCount(
            send_account,
            "latest"
          ),
          gasLimit: ethers.utils.hexlify(gas_limit), // 100000
          gasPrice: gas_price,
        }
        console.log(tx)
        try {
          walletSigner.sendTransaction(tx).then((transaction) => {
            console.log(transaction)
            alert("Send finished!")
          })
        } catch (error) {
          alert("failed to send!!")
        }
      }
    })
  }

You need to first switch network of your wallet. So, before sending a transation, do this:

try {
    await window.ethereum.request({
       method: 'wallet_switchEthereumChain',
       params: [{ chainId: "0x13881" }],
    })
} catch (e) {
    console.log(e)
} 

This will make MetaMask ask you to switch network to Polygon Testnet. After this, you can make your transaction.

Related