Search code examples
web3js

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


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")
                }
            }
            )
        }

        )
    }

Solution

  • 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.