jklepatch / eattheblocks

Source code for Eat The Blocks, a screencast for Ethereum Dapp Developers

Home Page:https://eattheblocks.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Selling tokens is not working

Tomix3D opened this issue · comments

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. (/app/node_modules/@ethersproject/providers/lib/base-provider.js:1301:36)
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.`

What is the originContract address? Did you use the pairaddress or the token address?
And is the valueToApprove the amount of BNB's to approve or is the amount of tokens to approve?

Hey, thanks for replay! I already fixed it. I had a problem with 'ether'.. I was not using 9 decimals for selling tokens.

Awesome!

You mean you replaced 'ether' with '9' in ethers.utils.parseUnits(reqUrl.searchParams.get('amountIn'), 'ether'); ?

Could you please share the code? I am facing the same issue codewise.

Many thanks in advance!

Yes, this line is now: const amountIn = ethers.utils.parseUnits(reqUrl.searchParams.get('amountIn'), addresses.originAddress === addresses.wrappedBnbAddress ? 18 : 9);

But I noticed today that some of tokens are having also 18 decimals so you need to send correct decimals count.

I'm just beginner but I'm using this function function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts) for selling tokens. (Not swapExactTokensForTokens)

I'm just beginner but I'm using this function function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts) for selling tokens. (Not swapExactTokensForTokens)

Yes! That did the trick!

Thanks you very much for all the hints!

I'm just beginner but I'm using this function function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts) for selling tokens. (Not swapExactTokensForTokens)

can you give me all your royalties