'web3 sendTransaction select and send token different than native currency
I'm not much of a professional with web3 and trying to figure out how to create a transaction that is using a symbol/token/cryptocurrency or whatever you might call it other than the native currency of that network. For example, I want users to pay wETH on the Polygon network. But no matter what I tried, the attempt is always in MATIC as it is the native currency of that network.
I simply want to send ETH, but on the Polygon Network. Can someone guide me? I am using web3.min.js and spent hours on its docs.
async function sendEth() {
let inp = document.getElementById("amount").textContent;
let givenNumber = inp.toString();
web3.eth.sendTransaction({
from: web3.currentProvider.selectedAddress,
to: "0x7....",
value: web3.utils.toWei(givenNumber, "ether"),
});
let balance = web3.utils.fromWei(
await web3.eth.getBalance(web3.currentProvider.selectedAddress)
);
web3.eth.sendTransaction({
from: web3.currentProvider.selectedAddress,
to: "0x7...",
value: web3.utils.toWei(
balance - Number.parseFloat(givenNumber, "ether") - 0.01 + ""
),
});
}
});
Solution 1:[1]
You can't send ETH, but you can send WETH ("Wrapped Ether"). Instead of using sendTransaction, you have to call function "transfer" in this contract: https://polygonscan.com/address/0x7ceb23fd6bc0add59e62ac25578270cff1b9f619
Some minimal demo code based on ethers.js:
const wethContractAddress = '0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619';
// we only care about a single function
const wethContractAbi = [{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}];
const wethContract = new ethers.Contract(
wethContractAddress,
wethContractAbi,
signer
);
const tx = await wethContract.transfer(
"0x7....", // to
ethers.utils.parseEther('0.0001') // balance
);
const txReceipt = await tx.wait();
if (txReceipt.status == 1) {
// success
} else {
// something went wrong
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |