Reputation: 3
I created a token using openzepplin + remix, I want to link it to web3, when checking the balance, everything is fine, when I make transferFrom, an error pops up, as if the balance is zero. What could be the problem? Error: Returned error: execution reverted: ERC20: transfer amount exceeds allowance
const Web3 = require('web3')
const Apk = require('./build/contracts/APKTEST.json')
let web3 = new Web3(new Web3.providers.HttpProvider('https://ropsten.infura.io/v3/id'))
var defaultAccount = web3.eth.defaultAccount;
web3.eth.defaultAccount = '0x6a6447CB492186a334ca2A51561D2D70659Ab0B1';
let contractAbi = new web3.eth.Contract(Apk.abi, '0xc45701C31357F0b5a9a22015E2b2601C9cA59A86');
contractAbi.methods.balanceOf('0x6a6447CB492186a334ca2A51561D2D70659Ab0B1').call(function (err, res) {
if (err) {
console.log("An error occured", err)
return
}
console.log("The balance is: ", res)
})
contractAbi.methods.transferFrom('0x6a6447CB492186a334ca2A51561D2D70659Ab0B1','0x5B38Da6a701c568545dCfcB03FcB875f56beddC4', 100).call(function (err, res) {
console.log(err)
})
Upvotes: 0
Views: 1880
Reputation: 43581
You need to use the .send() web3js method to execute the transferFrom()
contract function.
Based on the rest of the code, you also probably want to use the transfer()
contract function, not the transferFrom()
. transferFrom()
is used for transferring tokens that belong to other address than the transaction sender, after they executed the approve()
method giving you permission to spend their tokens.
Since you're using Infura provider, there's no unlocked account, so you'll need to pass your web3 a private key to the account that you want to use to send()
the transaction.
// add the private key (corresponding to the `0x6a64...` address) to your local web3 instance
web3.eth.accounts.wallet.add(privateKey);
// transfer 100 tokens from `0x6a64...` to `0x5B38...`
contractAbi.methods.transfer('0x5B38...', 100).send({from: '0x6a64...'}, function (err, res) {
});
Note: You already have a few callback functions in your code. Plus you'll need to move the transfer()
inside of the balanceOf()
callback to execute the transfer after you've gotten the balance.
contractAbi.methods.balanceOf(...).call(function (err, res) {
contractAbi.methods.transfer(...).send({...}, function (err, res) {
})
})
If your code stayed the same as in your question, both functions would execute in parallel. So sometimes you would get the balance result first, sometimes you would get the transfer first - depending on how fast your computer and the node can process the requests.
Consider using async/await approach if you don't want to fall into the callback hell. :-)
Upvotes: 2