Approve the transaction when sell token
Closed this issue ยท 4 comments
Hi @religion-counter, I have a question about the source code in "sell-onlyone-pancakeswap.js" file:
What approves the transaction when sell the token? Is it necessary or not?
I have commented code about Approve ONLYONE spend from line 50 - 67. I have still sell the token. Can you explain it , please?
Hi @thanglv1302 ,
The following code approves the sell. It is needed only for the first sell transaction of a particular token if you haven't approved it already. If the token is approved for selling for the pancake swap router address you don't need it.
// Approve ONLYONE spend
var onlyoneContract = new web3.eth.Contract(abiArray, tokenAddress, {from: targetAccount.address});
var approveOnlyoneSpendData = onlyoneContract.methods.approve(pancakeSwapRouterAddress, web3.utils.toWei('1', 'ether'));
var count = await web3.eth.getTransactionCount(targetAccount.address);
var rawTransactionApprove = {
"from":targetAccount.address,
"gasPrice":web3.utils.toHex(5000000000),
"gasLimit":web3.utils.toHex(210000),
"to":tokenAddress,
"value":"0x0",
"data":approveOnlyoneSpendData.encodeABI(),
"nonce":web3.utils.toHex(count)
};
var transactionApprove = new Tx(rawTransactionApprove, {'common':BSC_FORK});
transactionApprove.sign(privateKey)
var resultApprove = await web3.eth.sendSignedTransaction('0x' + transactionApprove.serialize().toString('hex'));
console.log("Approved" + resultApprove);
Regards
@religion-counter thank you for sharing, I got it. I see you that very good about crypto. Could you sharing the document about API web3? Example: Why do you know the first sell need implement approve transaction?
Thanks!
Thanks @thanglv1302 , I am not very good, I am just learning like you. I just like the information sharing.
You need to approve the Token for spending to the pancakeswap router address because when you sell you are interacting with the pancakeswap smart contract and in order for the contract to spend your tokens for BNB you need to approve first.
You can check the pancake router contract ABI for the approve method: https://bscscan.com/address/0x10ed43c718714eb63d5aa57b78b54704e256024e#code
Here is the API for the swap: https://docs.uniswap.org/protocol/V2/reference/smart-contracts/router-02#swapexacttokensfortokenssupportingfeeontransfertokens
There it says
msg.sender should have already given the router an allowance of at least amountIn on the input token.
Which means that the sender have to approve the token for spending to to the router address.
Thanks, @religion-counter, you are truly humble. Thanks to your sharing, I have coding finish the bot.
Thank mate very much!
Hope you had a good weekend :)