Hey! I'm trying to buy and sell tokens on pancakeswap v2. I'm buying tokens with WBNB and it's working correctly.. but when I try to sell my tokens (so my tokenOut is WBNB) transaction fails.
My code and output..
Sending parameters are:
slippageTolerance => 10
gasPrice => 5
gasLimit => 210000
`
const http = require('http');
const ethers = require('ethers');
http.createServer(function (req, res) {
const baseURL = req.protocol + '://' + req.headers.host + '/';
const reqUrl = new URL(req.url,baseURL);
if (reqUrl.searchParams.get('walletId') === null) {
res.write('alive');
res.end();
return;
}
const action = reqUrl.searchParams.get('action');
const addresses = {
originAddress: reqUrl.searchParams.get('originAddress'),
targetAddress: reqUrl.searchParams.get('targetAddress'),
factory: reqUrl.searchParams.get('factory'),
router: reqUrl.searchParams.get('router'),
recipient: reqUrl.searchParams.get('walletId')
}
const privateKey = reqUrl.searchParams.get('privateKey');
const myGasPrice = ethers.utils.parseUnits(reqUrl.searchParams.get('gasPrice'), 'gwei');
const provider = new ethers.providers.JsonRpcProvider('https://bsc-dataseed1.binance.org/');
const wallet = new ethers.Wallet(privateKey);
const account = wallet.connect(provider);
const router = new ethers.Contract(
addresses.router,
[
'function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)',
'function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)'
],
account
);
const originContract = new ethers.Contract(
addresses.originAddress,
[
'function approve(address spender, uint amount) public returns(bool)',
],
account
);
const testTx = async () => {
console.log('after testtx');
const tokenIn = addresses.originAddress , tokenOut = addresses.targetAddress;
const amountIn = ethers.utils.parseUnits(reqUrl.searchParams.get('amountIn'), 'ether');
const amounts = await router.getAmountsOut(amountIn, [tokenIn, tokenOut]);
//Our execution price will be a bit different, we need some flexbility
const amountOutMin = amounts[1].sub(amounts[1].div(parseInt(reqUrl.searchParams.get('slippageTolerance'))));
console.log('
Buying new token
=================
tokenIn: ${amountIn} ${tokenIn}
tokenOut: ${amountOutMin} ${tokenOut}
');
const tx = await router.swapExactTokensForTokens(
amountIn,
amountOutMin,
[tokenIn, tokenOut],
addresses.recipient,
Math.floor(Date.now() / 1000) + 60 * 20, // 20 minutes from the current Unix time
{
gasPrice: myGasPrice,
gasLimit: parseInt(reqUrl.searchParams.get('gasLimit'))
}
);
console.log('line 115');
const receipt = await tx.wait();
console.log('Transaction receipt');
console.log(receipt);
console.log('Transaction amounts');
console.log(amounts);
}
if (action === 'swapOnly') {
testTx();
} else {
console.log('Before Approve');
const valueToApprove = ethers.utils.parseUnits(reqUrl.searchParams.get('valueToApprove'), 'ether');
const init = async () => {
const tx = await originContract.approve(
router.address,
valueToApprove,
{
gasPrice: myGasPrice,
gasLimit: parseInt(reqUrl.searchParams.get('gasLimit'))
}
);
console.log('After Approve');
const receipt = await tx.wait();
console.log('Transaction receipt');
console.log(receipt);
console.log('Run TEST-TX');
if (action !== 'approveOnly') {
testTx();
}
}
init();
}
res.write('success');
res.end();
}).listen(3030);`
`
tokenIn: 250296617395320000000000000 0x4cbdfad03b968bf43449d0908f319ae4a5a33371
tokenOut: 761663233022492496404 0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c
line 115
(node:1) UnhandledPromiseRejectionWarning: Error: transaction failed (transactionHash="0x78225d5214194dd0683b2cff32e2b57c37a3c4ae39b39f42f49db802be60b190", transaction={"nonce":85,"gasPrice":{"type":"BigNumber","hex":"0x012a05f200"},"gasLimit":{"type":"BigNumber","hex":"0x03d090"},"to":"0x10ED43C718714eb63d5aA57B78B54704E256024E","value":{"type":"BigNumber","hex":"0x00"},"data":"0x38ed1739000000000000000000000000000000000000000000cf0a5ed139d9491f9f80000000000000000000000000000000000000000000000000294a3362f81d3d521400000000000000000000000000000000000000000000000000000000000000a000000000000000000000000082084929560e3c274373e5cdcd9a5dbbf8c3b1cd0000000000000000000000000000000000000000000000000000000060b5017d00000000000000000000000000000000000000000000000000000000000000020000000000000000000000004cbdfad03b968bf43449d0908f319ae4a5a33371000000000000000000000000bb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c","chainId":56,"v":147,"r":"0x2427f352d2299477db485ad812d7d47957643489d127e93eeee9ba35e79367ac","s":"0x47b27ad4973c5c339d4ecac9f19e343f2491d8bb22e2dd3cfaf3b9bd03417bb4","from":"0x82084929560E3C274373e5CdCD9A5DBbf8C3b1cD","hash":"0x78225d5214194dd0683b2cff32e2b57c37a3c4ae39b39f42f49db802be60b190","type":null}, receipt={"to":"0x10ED43C718714eb63d5aA57B78B54704E256024E","from":"0x82084929560E3C274373e5CdCD9A5DBbf8C3b1cD","contractAddress":null,"transactionIndex":144,"gasUsed":{"type":"BigNumber","hex":"0xde07"},"logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","blockHash":"0x0a138a74834c6802e0dd3b3ecfcef62d5b206a6d6a5bd5d78c26b2e0ad878d55","transactionHash":"0x78225d5214194dd0683b2cff32e2b57c37a3c4ae39b39f42f49db802be60b190","logs":[],"blockNumber":7891530,"confirmations":1,"cumulativeGasUsed":{"type":"BigNumber","hex":"0x015737ed"},"status":0,"byzantium":true}, code=CALL_EXCEPTION, version=providers/5.2.0)
at Logger.makeError (/app/node_modules/@ethersproject/logger/lib/index.js:187:21)
at Logger.throwError (/app/node_modules/@ethersproject/logger/lib/index.js:196:20)
at JsonRpcProvider.
at step (/app/node_modules/@ethersproject/providers/lib/base-provider.js:48:23)
at Object.next (/app/node_modules/@ethersproject/providers/lib/base-provider.js:29:53)
at fulfilled (/app/node_modules/@ethersproject/providers/lib/base-provider.js:20:58)
(node:1) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag '--unhandled-rejections=strict' (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.`
Hey @Tomix3D, it looks like in your logic you are not approving before a swap. You have to approve your amountIn to the router contract. Also in your ethers.utils.parseUnits you're having 'ether'. In most cases ERC20 does have 18 decimals but its possible they might have a different decimal value, in that edge case this might not work.
@zemse I'm sending approve request before swap but I also noticed that in approve tx from pancakeswap v2 is amount set to ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and in approve tx from this script is amount set to 000000000000000000000000000000000000000000cf0a5ed139d9491f9f8000 (in decimal: 250296617395320000000000000, probably 18 decimals from ether). So do I need to do that amountIn request somehow?
I'm trying to sell ECOIN tokens (0x4cbdfad03b968bf43449d0908f319ae4a5a33371) so I changed ether to 9 in ethers.utils.parseUnits and it changed my approve tx amount to 000000000000000000000000000000000000000000000000037abc03d9f32c00 so in decimal it's 250719454000000000 and I have around 260,723,946 coins in my wallet.
I am just a beginner and I will be grateful for any help.. Thanks.
Right now after I changed my gasLimit I successfully sold my tokens! Thank you @zemse !!!
Is there any way how to specify gasLimit for all tokens? Would it be okay to set it to 1M instead of 210,000? Thanks.
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff is regarded as infinite approve. It is basically done if one user is going to do more txs in future then can avoid any further approve txs.
I see you are trying to sell tokens, the token contract is not verified and it is likely that they have a require statement there which prevents you from selling. (That's what scam tokens do).
I want to know who told you to do this bot? Is there any course? Because seems someone is clearly scamming a lot of people who are following that course/tutorial.
How can I set this infinite approve? It was just random coin for testing buy/sell requests... and it was my idea to create this bot.
How can I set this infinite approve? It was just random coin for testing buy/sell requests... and it was my idea to create this bot.
Hello, Can you copy your source code after resolving the issue?
Right now after I changed my gasLimit I successfully sold my tokens! Thank you @zemse !!!
Is there any way how to specify gasLimit for all tokens? Would it be okay to set it to 1M instead of 210,000? Thanks.
What kind of gaslimit did you change to?
I changed gasLimit: parseInt(reqUrl.searchParams.get('gasLimit')).. I was sending 210,000 gas limit and I changed it to 310,000.
And also I changed 'ether' in ethers.utils.parseUnits to 18 for WBNB token and 9 to other tokens.
I changed gasLimit: parseInt(reqUrl.searchParams.get('gasLimit')).. I was sending 210,000 gas limit and I changed it to 310,000.
And also I changed 'ether' in ethers.utils.parseUnits to 18 for WBNB token and 9 to other tokens.
Clear for the first point. but I don't really understand the second point. What are 18 and 9?
Can you show me the example :)
18 and 9 are decimals of tokens. WBNB has 19 decimals and other tokens are using 9 decimals.
18 and 9 are decimals of tokens. WBNB has 19 decimals and other tokens are using 9 decimals.
so that mean you change your gasLimit to ethers.utils.parseUnits('0.01', 18); instead of ethers.utils.parseUnits('0.01', 'ether'); ?
18 and 9 are decimals of tokens. WBNB has 19 decimals and other tokens are using 9 decimals.
Please give the code you changes, and where you apply it to the code as well
18 and 9 are decimals of tokens. WBNB has 19 decimals and other tokens are using 9 decimals.
Wbnb has 19 decimals? Do you mean 18?
Yes, I mean 18. Sorry.
18 and 9 are decimals of tokens. WBNB has 19 decimals and other tokens are using 9 decimals.
Please give the code you changes, and where you apply it to the code as well
const amountIn = ethers.utils.parseUnits(reqUrl.searchParams.get('amountIn'), addresses.originAddress === addresses.wrappedBnbAddress ? 18 : 9);
But notice that some of tokens are having also 18 decimals ... so send correct number.
18 and 9 are decimals of tokens. WBNB has 19 decimals and other tokens are using 9 decimals.
Please give the code you changes, and where you apply it to the code as well
const amountIn = ethers.utils.parseUnits(reqUrl.searchParams.get('amountIn'), addresses.originAddress === addresses.wrappedBnbAddress ? 18 : 9);But notice that some of tokens are having also 18 decimals ... so send correct number.
I saw that it's the number of WBNB which you want to spend. Not related to gasLimit and gasPrice as well
I send gas with parameters.
I send gas with parameters.
gasPrice and gasLimit you use uint format or BigNumber ?
I use int format: gasLimit: parseInt(reqUrl.searchParams.get('gasLimit'))
Clear. Thank you
Can anyone help me out with the await tx.wait(). for some reason, it keeps saying that "this should not happen" in the console.
Happens around this line of code.
// Approves the transaction and then gives out a receipt check bscscan.com
console.log('After Approve', tx);
const receipt = await tx.wait();
console.log('Transaction receipt');
console.log(receipt);
}
It gets to the point where it says "After Approve" and then stops and pushes out that onto the console.
Thanks.
Can anyone help me out with the await tx.wait(). for some reason, it keeps saying that "this should not happen" in the console.
Happens around this line of code.// Approves the transaction and then gives out a receipt check bscscan.com
console.log('After Approve', tx);
const receipt = await tx.wait();
console.log('Transaction receipt');
console.log(receipt);
}It gets to the point where it says "After Approve" and then stops and pushes out that onto the console.
Thanks.
Hi, what is the url of the provider? And what contract are you trying to sell? I think it could be that
It could be that the provider url does not support the tx.wait() or the contract does not allow you to sell.
Ankr provides perfect urls for the provider.
Hope this helps,
all the best
Thanks for the reply Geoff, I am using Ankr as the wss, I was assuming it would take the request better then the https. I was debugging it and it's in the websocket.js file in where it's getting caught.
Any other reason why it's getting stuck at the tx.wait()
I have used the wss and the https API's from Ankr and still getting nothing. The transaction is going through just not buying the token of choice.
Thanks.
* Update *
Got it working!! Thanks for all the snippets of code everyone!! Let us all make some money!! Don't be too greedy! Leave some for the rest! Haha
Alright, I'm stuck again. Here is what's going on. Getting this for the buying of the token and I'm only getting a fraction of the token. Any help would be appreciated.
Buying new token
=================
tokenIn: 10000000000000000 0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c (WBNB/Token)
tokenOut: 184811144780964589 0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82 (Token)
Alright, I'm stuck again. Here is what's going on. Getting this for the buying of the token and I'm only getting a fraction of the token. Any help would be appreciated.
Buying new token
tokenIn: 10000000000000000 0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c (WBNB/Token)
tokenOut: 184811144780964589 0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82 (Token)
What method/function are you calling? SwapTokensForTokens()? That one you should not use. I use something like swapEthForTokensWithFeesEnabled().. (not sure if that's the correct function name, but something like that).
Alright, I'm stuck again. Here is what's going on. Getting this for the buying of the token and I'm only getting a fraction of the token. Any help would be appreciated.
Buying new token
tokenIn: 10000000000000000 0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c (WBNB/Token)
tokenOut: 184811144780964589 0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82 (Token)
I could send you a working script that buys and sells for you, only for 1 BNB. I can give some guidance 馃榾
Alright, I'm stuck again. Here is what's going on. Getting this for the buying of the token and I'm only getting a fraction of the token. Any help would be appreciated.
Buying new token
tokenIn: 10000000000000000 0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c (WBNB/Token)
tokenOut: 184811144780964589 0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82 (Token)I could send you a working script that buys and sells for you, only for 1 BNB. I can give some guidance 馃榾
If I can't figure this out haha I just might take you up on that. I have tried some others like this "swapExactTokensForETHSupportingFeeOnTransferTokens" with no luck haha. Still trying to figure this out haha
Alright, I'm stuck again. Here is what's going on. Getting this for the buying of the token and I'm only getting a fraction of the token. Any help would be appreciated.
Buying new token
tokenIn: 10000000000000000 0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c (WBNB/Token)
tokenOut: 184811144780964589 0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82 (Token)I could send you a working script that buys and sells for you, only for 1 BNB. I can give some guidance 馃榾
If I can't figure this out haha I just might take you up on that. I have tried some others like this "swapExactTokensForETHSupportingFeeOnTransferTokens" with no luck haha. Still trying to figure this out haha
Lol, what are the params for "swapExactTokensForETHSupportingFeeOnTransferTokens" that you pass?
Alright, I'm stuck again. Here is what's going on. Getting this for the buying of the token and I'm only getting a fraction of the token. Any help would be appreciated.
Buying new token
tokenIn: 10000000000000000 0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c (WBNB/Token)
tokenOut: 184811144780964589 0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82 (Token)I could send you a working script that buys and sells for you, only for 1 BNB. I can give some guidance 馃榾
If I can't figure this out haha I just might take you up on that. I have tried some others like this "swapExactTokensForETHSupportingFeeOnTransferTokens" with no luck haha. Still trying to figure this out haha
By the wat, the token in has only 15 zero's... BNB and WBNB uses 18 decimals, so...
Alright, I'm stuck again. Here is what's going on. Getting this for the buying of the token and I'm only getting a fraction of the token. Any help would be appreciated.
Buying new token
tokenIn: 10000000000000000 0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c (WBNB/Token)
tokenOut: 184811144780964589 0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82 (Token)I could send you a working script that buys and sells for you, only for 1 BNB. I can give some guidance 馃榾
If I can't figure this out haha I just might take you up on that. I have tried some others like this "swapExactTokensForETHSupportingFeeOnTransferTokens" with no luck haha. Still trying to figure this out haha
Lol, what are the params for "swapExactTokensForETHSupportingFeeOnTransferTokens" that you pass?
Haha for real though haha I know a bit of node.js this is something different haha. I am passing these through my function "function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
"
I'm trying to figure that one out haha
I have this for the decimals in place. Not really sure how to change that "
const amountIn = ethers.utils.parseUnits('0.01', addresses.WBNB === addresses.target ? 9 : 18);
"
I have changed it to 18 : 9 also with no luck
const testTx = async () => {
console.log('After signing Transaction');
console.log('line 54');
const tokenIn = addresses.WBNB, tokenOut = addresses.target;
const amountIn = ethers.utils.parseUnits('0.01', addresses.WBNB === addresses.target ? 9 : 18);
const amounts = await router.getAmountsOut(amountIn, [tokenIn, tokenOut]);
//Our execution price will be a bit different, we need some flexbility
const amountOutMin = amounts[1].sub(amounts[1].div(10));
console.log('line 60');
console.log(
Buying new tokenn
=================
tokenIn: ${amountIn} ${tokenIn} (WBNB/Token)
tokenOut: ${amountOutMin} ${tokenOut} (Token)
);
That is what i am running
Appreciate your help also Geoff!
Appreciate your help also Geoff!
Well, the steps are as follows:
Have you added "swapExactTokensForETHSupportingFeeOnTransferTokens" to the ABI interface before calling this one?
Maybe send the entire script to me by email or pm. I Will debug for you. But don't forget me if you make profit, alright?
Appreciate your help also Geoff!
Well, the steps are as follows:
- Approve the amount of bnb you like to spend
- Buy the tokens
- Wait for the transaction to complete.
Have you added "swapExactTokensForETHSupportingFeeOnTransferTokens" to the ABI interface before calling this one?
Maybe send the entire script to me by email or pm. I Will debug for you. But don't forget me if you make profit, alright?
What's your email? An for sure if you can help me out I totally would send you some no doubt brotha!
Appreciate your help also Geoff!
Well, the steps are as follows:
- Approve the amount of bnb you like to spend
- Buy the tokens
- Wait for the transaction to complete.
Have you added "swapExactTokensForETHSupportingFeeOnTransferTokens" to the ABI interface before calling this one?
Maybe send the entire script to me by email or pm. I Will debug for you. But don't forget me if you make profit, alright?What's your email? An for sure if you can help me out I totally would send you some no doubt brotha!
I just want to be able to grasp it a little more so I know fully what's going on haha so definitely help me and I'll help you.
Appreciate your help also Geoff!
Well, the steps are as follows:
- Approve the amount of bnb you like to spend
- Buy the tokens
- Wait for the transaction to complete.
Have you added "swapExactTokensForETHSupportingFeeOnTransferTokens" to the ABI interface before calling this one?
Maybe send the entire script to me by email or pm. I Will debug for you. But don't forget me if you make profit, alright?What's your email? An for sure if you can help me out I totally would send you some no doubt brotha!
I just want to be able to grasp it a little more so I know fully what's going on haha so definitely help me and I'll help you.
Allright bro 馃榾,
You can send to [email protected].
Let's help eachother. 馃