Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error: invalid BigNumber string from PancakeSwap trading bot #58

Open
beejaz opened this issue May 13, 2021 · 29 comments
Open

Error: invalid BigNumber string from PancakeSwap trading bot #58

beejaz opened this issue May 13, 2021 · 29 comments

Comments

@beejaz
Copy link

beejaz commented May 13, 2021

Hi,

Following your latest youtube video with PancakeSwap trading bot, I get this error and can't seem to find why or where it happens:

(node:21378) UnhandledPromiseRejectionWarning: Error: invalid BigNumber string (argument="value", value="0.1", code=INVALID_ARGUMENT, version=bignumber/5.1.1)
    at Logger.makeError (/home/pancake-trading-bot/node_modules/@ethersproject/logger/lib/index.js:180:21)
    at Logger.throwError (/home/pancake-trading-bot/node_modules/@ethersproject/logger/lib/index.js:189:20)
    at Logger.throwArgumentError (/home//pancake-trading-bot/node_modules/@ethersproject/logger/lib/index.js:192:21)
    at Function.BigNumber.from (/home/pancake-trading-bot/node_modules/@ethersproject/bignumber/lib/bignumber.js:201:27)
    at NumberCoder.encode (/home/pancake-trading-bot/node_modules/@ethersproject/abi/lib/coders/number.js:36:39)
    at /home/pancake-trading-bot/node_modules/@ethersproject/abi/lib/coders/array.js:74:19
    at Array.forEach (<anonymous>)
    at Object.pack (/home/pancake-trading-bot/node_modules/@ethersproject/abi/lib/coders/array.js:60:12)
    at TupleCoder.encode (/home/pancake-trading-bot/node_modules/@ethersproject/abi/lib/coders/tuple.js:71:24)
    at AbiCoder.encode (/home/pancake-trading-bot/node_modules/@ethersproject/abi/lib/abi-coder.js:93:15)
(node:21378) 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(). (rejection id: 1)
(node:21378) [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.

Any idea?

@DeVoresyah
Copy link

same here

@beejaz
Copy link
Author

beejaz commented May 13, 2021

Okay, so I got this error because if this line
https://github.com/jklepatch/eattheblocks/blob/master/screencast/348-pancakeswap-trading-bot/bot.js#L41

I had to use '1' or larger amount on approve. But now I get this error instead:

(node:21550) UnhandledPromiseRejectionWarning: TypeError: tx.wait is not a function
    at init (/home/pancake-trading-bot/bot.js:44:28)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:21550) 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(). (rejection id: 1)
(node:21550) [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.

Which I dont understand either because wbnb.approve returns bool so tx = true, there is no function called wait

@DeVoresyah
Copy link

Okay, so I got this error because if this line
https://github.com/jklepatch/eattheblocks/blob/master/screencast/348-pancakeswap-trading-bot/bot.js#L41

I had to use '1' or larger amount on approve. But now I get this error instead:

(node:21550) UnhandledPromiseRejectionWarning: TypeError: tx.wait is not a function
    at init (/home/pancake-trading-bot/bot.js:44:28)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:21550) 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(). (rejection id: 1)
(node:21550) [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.

Which I dont understand either because wbnb.approve returns bool so tx = true, there is no function called wait

I already solved my previous problem above, but I got this error

UnhandledPromiseRejectionWarning: Error: cannot estimate gas; transaction may fail or may require manual gas limit (error={"reason":"cannot estimate gas; transaction may fail or may require manual gas limit","code":"UNPREDICTABLE_GAS_LIMIT"

@ozgurk78
Copy link

I have same problem , What can we do?

(node:15408) UnhandledPromiseRejectionWarning: Error: invalid BigNumber string (argument="value", value="replace by amount covering several trades", code=INVALID_ARGUMENT, version=bignumber/5.0.15)

@ivekivek
Copy link

ivekivek commented May 17, 2021

I have same problem , What can we do?

(node:15408) UnhandledPromiseRejectionWarning: Error: invalid BigNumber string (argument="value", value="replace by amount covering several trades", code=INVALID_ARGUMENT, version=bignumber/5.0.15)

You need to replace "replace by amount covering several trades" with value, put "1" or more.
Anyway after solving this one, I got "tx.wait() is not function" and solve this, but can see he solve it too yesterday. After that we need to figure out how to solve gas estimate error. I think it should work with this, not sure, but it worked with Uniswap.

We need to set gas price and limit manual.

const tx = await router.swapExactTokensForTokens(
    amountIn,
    amountOutMin,
    [tokenIn, tokenOut],
    addresses.recipient,
    {
      value: '0',
      gasPrice: ethers.BigNumber.from(1000000).toHexString(),
      gasLimit: ethers.BigNumber.from(1000000).toHexString() 
    },
    Date.now() + 1000 * 60 * 10, // 10 minutes
); 

@thekooldev1232
Copy link

Yea this is the error where I am stuck too !! Hope this helps 🤘

@ivekivek
Copy link

Yea this is the error where I am stuck too !! Hope this helps 🤘

Try it and let know

@DioLorenzo
Copy link

Promise {
ReferenceError: wbnb is not defined
at init (REPL45:2:14)
at REPL415:1:1
at Script.runInThisContext (vm.js:133:18)
at REPLServer.defaultEval (repl.js:486:29)
at bound (domain.js:416:15)
at REPLServer.runBound [as eval] (domain.js:427:12)
at REPLServer.onLine (repl.js:819:10)
at REPLServer.emit (events.js:388:22)
at REPLServer.emit (domain.js:470:12)
at REPLServer.Interface._onLine (readline.js:342:10)
}

(node:76719) UnhandledPromiseRejectionWarning: ReferenceError: wbnb is not defined
at init (REPL45:2:14)
at REPL415:1:1
at Script.runInThisContext (vm.js:133:18)
at REPLServer.defaultEval (repl.js:486:29)
at bound (domain.js:416:15)
at REPLServer.runBound [as eval] (domain.js:427:12)
at REPLServer.onLine (repl.js:819:10)
at REPLServer.emit (events.js:388:22)
at REPLServer.emit (domain.js:470:12)
at REPLServer.Interface._onLine (readline.js:342:10)
(node:76719) 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: 4)

I have this error, how I can solve it?

@mujahidazamcsm
Copy link

Hello Everyone..

Getting this error.. any idea how to fix this?

events.js:174 throw er; // unhandled 'error' event

@ivekivek
Copy link

Promise {
ReferenceError: wbnb is not defined
at init (REPL45:2:14)
at REPL415:1:1
at Script.runInThisContext (vm.js:133:18)
at REPLServer.defaultEval (repl.js:486:29)
at bound (domain.js:416:15)
at REPLServer.runBound [as eval] (domain.js:427:12)
at REPLServer.onLine (repl.js:819:10)
at REPLServer.emit (events.js:388:22)
at REPLServer.emit (domain.js:470:12)
at REPLServer.Interface._onLine (readline.js:342:10)
}

(node:76719) UnhandledPromiseRejectionWarning: ReferenceError: wbnb is not defined
at init (REPL45:2:14)
at REPL415:1:1
at Script.runInThisContext (vm.js:133:18)
at REPLServer.defaultEval (repl.js:486:29)
at bound (domain.js:416:15)
at REPLServer.runBound [as eval] (domain.js:427:12)
at REPLServer.onLine (repl.js:819:10)
at REPLServer.emit (events.js:388:22)
at REPLServer.emit (domain.js:470:12)
at REPLServer.Interface._onLine (readline.js:342:10)
(node:76719) 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: 4)

I have this error, how I can solve it?

Can you share your code?

@ivekivek
Copy link

Hello Everyone..

Getting this error.. any idea how to fix this?

events.js:174 throw er; // unhandled 'error' event

Can you share code?

@DioLorenzo
Copy link

Hello Everyone..
Getting this error.. any idea how to fix this?
events.js:174 throw er; // unhandled 'error' event

Can you share code?

const provider = new ethers.providers.WebSocketProvider('my url here in https not wss')
const account = wallet.connect(provider);
const factory = new ethers.Contract(
addresses.factory,
['event PairCreated(address indexed token0, address indexed token1, address pair, uint)'],
account
);
const router = new ethers.Contract(
addresses.router,
[
'function getAmountsOut(uint amountIn, address[] memory path) public returns (uint[] memory amounts)',
'function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)'
],
account
);

const wbnb = new ethers.Contract(
addresses.WBNB,
[
'function approve(address spender, uint amount) public returns(bool)',
],
account
);

const init = async () => {
const tx = await wbnb.approve(
router.address,
'10'
);
const receipt = await tx.wait();
console.log('Transaction receipt');
console.log(receipt);
}

factory.on('PairCreated', async (token0, token1, pairAddress) => {
console.log(New pair detected ================= token0: ${token0} token1: ${token1} pairAddress: ${pairAddress});

//The quote currency needs to be WBNB (we will pay with WBNB)
let tokenIn, tokenOut;
if(token0 === addresses.WBNB) {
tokenIn = token0;
tokenOut = token1;
}

if(token1 == addresses.WBNB) {
tokenIn = token1;
tokenOut = token0;
}

//The quote currency is not WBNB
if(typeof tokenIn === 'undefined') {
return;
}

//We buy for 0.1 BNB of the new token
//ethers was originally created for Ethereum, both also work for BSC
//'ether' === 'bnb' on BSC
const amountIn = ethers.utils.parseUnits('0.001', '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(10));
console.log(Buying new token ================= tokenIn: ${amountIn.toString()} ${tokenIn} (WBNB) tokenOut: ${amounOutMin.toString()} ${tokenOut});
const tx = await router.swapExactTokensForTokens(
amountIn,
amountOutMin,
[tokenIn, tokenOut],
addresses.recipient,
{
value: '0',
gasPrice: ethers.BigNumber.from(1000000).toHexString(),
gasLimit: ethers.BigNumber.from(1000000).toHexString()
},
Date.now() + 1000 * 60 * 10, // 10 minutes
);
const receipt = await tx.wait();
console.log('Transaction receipt');
console.log(receipt);
});

init();

@mujahidazamcsm
Copy link

Hello Everyone..
Getting this error.. any idea how to fix this?
events.js:174 throw er; // unhandled 'error' event

Can you share code?

Hi @ivekivek,

It is pretty much the stock code.. just commented out a few lines as I dont want to make a purchase or approve WBNB.. added logs.. to see where it is failing.. let me know if u r able to get it to work

const ethers = require('ethers');

const addresses = {
WBNB: '0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c',
factory: '0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73',
router: '0x10ED43C718714eb63d5aA57B78B54704E256024E',
recipient: '- put ur address here'
}

//First address of this mnemonic must have enough BNB to pay for tx fess
const mnemonic = '- put ur mnemonic here'

const provider = new ethers.providers.WebSocketProvider('wss://apis.ankr.com/wss/....'); //Ankr websocket url to mainnet
console.log('provider');
//console.log(provider);
const wallet = ethers.Wallet.fromMnemonic(mnemonic);
console.log('wallet');
//console.log(wallet);
const account = wallet.connect(provider);
console.log('account');
//console.log(account);
const factory = new ethers.Contract(
addresses.factory,
['event PairCreated(address indexed token0, address indexed token1, address pair, uint)'],
account
);
console.log('factory');
//console.log(factory);
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
);
console.log('router');
//console.log(router);
const wbnb = new ethers.Contract(
addresses.WBNB,
[
'function approve(address spender, uint amount) public returns(bool)',
],
account
);
console.log('wbnb');
//console.log(wbnb);
const init = async () => {
/*const tx = await wbnb.approve(
router.address,
'replace by amount covering several trades'
);
const receipt = await tx.wait(); */

console.log('Transaction receipt11');
//console.log(receipt);
}
console.log('PairCreated');

factory.on('error', function(err){
console.log('onerror');
console.log(err);
});

factory.on('PairCreated', async (token0, token1, pairAddress) => {

console.log('on PairCreated');

console.log(New pair detected ================= token0: ${token0} token1: ${token1} pairAddress: ${pairAddress});

//The quote currency needs to be WBNB (we will pay with WBNB)
let tokenIn, tokenOut;
if(token0 === addresses.WBNB) {
tokenIn = token0;
tokenOut = token1;
}

if(token1 == addresses.WBNB) {
tokenIn = token1;
tokenOut = token0;
}

//The quote currency is not WBNB
if(typeof tokenIn === 'undefined') {
return;
}

//We buy for 0.1 BNB of the new token
//ethers was originally created for Ethereum, both also work for BSC
//'ether' === 'bnb' on BSC
const amountIn = ethers.utils.parseUnits('0.01', '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(10));
console.log(Buying new token ================= tokenIn: ${amountIn.toString()} ${tokenIn} (WBNB) tokenOut: ${amounOutMin.toString()} ${tokenOut});

/* const tx = await router.swapExactTokensForTokens(
amountIn,
amountOutMin,
[tokenIn, tokenOut],
addresses.recipient,
Date.now() + 1000 * 60 * 10 //10 minutes
);

const receipt = await tx.wait();
*/
console.log('Transaction receipt');
console.log(receipt);
});

init();

@thekooldev1232
Copy link

You

I have same problem , What can we do?
(node:15408) UnhandledPromiseRejectionWarning: Error: invalid BigNumber string (argument="value", value="replace by amount covering several trades", code=INVALID_ARGUMENT, version=bignumber/5.0.15)

You need to replace "replace by amount covering several trades" with value, put "1" or more.
Anyway after solving this one, I got "tx.wait() is not function" and solve this, but can see he solve it too yesterday. After that we need to figure out how to solve gas estimate error. I think it should work with this, not sure, but it worked with Uniswap.

We need to set gas price and limit manual.

const tx = await router.swapExactTokensForTokens(
    amountIn,
    amountOutMin,
    [tokenIn, tokenOut],
    addresses.recipient,
    {
      value: '0',
      gasPrice: ethers.BigNumber.from(1000000).toHexString(),
      gasLimit: ethers.BigNumber.from(1000000).toHexString() 
    },
    Date.now() + 1000 * 60 * 10, // 10 minutes
); 

this doesn't work dude! still issue persist

@agoralive
Copy link

Really looking forward to hopefully fixing this issue guys :)

@thekooldev1232
Copy link

add nounce inside the tx object

@ivekivek
Copy link

add nounce inside the tx object

It is working like that?

@agoralive
Copy link

@thekooldev1232

Code example?

@tuxforensics
Copy link

// i added the line below this comment to solve my issues for the approve.
const valueToapprove = ethers.utils.parseUnits('0.05', 'ether');
const init = async () => {
const tx = await wbnb.approve(
router.address,
valueToapprove
// valueToapprove is the constant before this block
);

Now I need help with setting gas limit and gas because estimation isn't working and i don't know where to put them for the transaction

@hbtj123
Copy link

hbtj123 commented May 25, 2021

Hi All,
I have something similar.

Can anyone advise here?

transaction failed (transactionHash="", transaction={"nonce":,"gasPrice":{"type":"BigNumber","hex":""},"gasLimit":{"type":"BigNumber","hex":"0x061a80"},"to":"","value":{"type":"BigNumber","hex":"0x00"},"data":"0xa5be382e000000000000000000000000000000000000000000000000000009184e72a000000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000b083653f11a5133868d56dacd723b837e27b7d17000000000000000000000000000000000000000000000000000001799a15a8690000000000000000000000000000000000000000000000000000000000000002000000000000000000000000bb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c000000000000000000000000b3225ac90b741f762beca76dea1ead278ef26a96","chainId":56,"v":148,"r":"","s":"","from":"","hash":""}, receipt={"to":"","from":"","contractAddress":null,"transactionIndex":324,"gasUsed":{"type":"BigNumber","hex":"0x5a8b"},"logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","blockHash":"0x2ee5c5c282a605193f282aa34e31fa18c62ff3fdc6cd996e1592be49cdb60e03","transactionHash":"0x35bb3f987f4f99fab4572db341886220a400f791cb68bce401dcf00fd5099396","logs":[],"blockNumber":7663738,"confirmations":1,"cumulativeGasUsed":{"type":"BigNumber","hex":"0x02bf7565"},"status":0,"byzantium":true}, code=CALL_EXCEPTION, version=providers/5.0.24)
at Logger.makeError (\trading-bot\node_modules@ethersproject\logger\lib\index.js:180:21)
at Logger.throwError (\trading-bot\node_modules@ethersproject\logger\lib\index.js:189:20)
at WebSocketProvider. (\trading-bot\node_modules@ethersproject\providers\lib\base-provider.js:1162:36)

@mestan998
Copy link

Hey After Fixing all the above issues I am getting error

Unexpected server response: 200
Emitted 'error' event on WebSocket instance at:
at abortHandshake (/home/shady/Projects/Tokens/PancakeBot/node_modules/ws/lib/websocket.js:698:15)
at ClientRequest. (/home/shady/Projects/Tokens/PancakeBot/node_modules/ws/lib/websocket.js:580:7)
[... lines matching original stack trace ...]

@henrykash
Copy link

Okay, so I got this error because if this line
https://github.com/jklepatch/eattheblocks/blob/master/screencast/348-pancakeswap-trading-bot/bot.js#L41
I had to use '1' or larger amount on approve. But now I get this error instead:

(node:21550) UnhandledPromiseRejectionWarning: TypeError: tx.wait is not a function
    at init (/home/pancake-trading-bot/bot.js:44:28)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:21550) 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(). (rejection id: 1)
(node:21550) [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.

Which I dont understand either because wbnb.approve returns bool so tx = true, there is no function called wait

I already solved my previous problem above, but I got this error

UnhandledPromiseRejectionWarning: Error: cannot estimate gas; transaction may fail or may require manual gas limit (error={"reason":"cannot estimate gas; transaction may fail or may require manual gas limit","code":"UNPREDICTABLE_GAS_LIMIT"

you can try hardcode the gasLimit it will solve the issue

const tx = await wbnb.approve(
router.address,
valueToapprove,
{
gasLimit:100000
}
);

@henrykash
Copy link

you can try hardcode the gasLimit

@GianluBLockchain-DEV
Copy link

same here

Hey After Fixing all the above issues I am getting error

Unexpected server response: 200 Emitted 'error' event on WebSocket instance at: at abortHandshake (/home/shady/Projects/Tokens/PancakeBot/node_modules/ws/lib/websocket.js:698:15) at ClientRequest. (/home/shady/Projects/Tokens/PancakeBot/node_modules/ws/lib/websocket.js:580:7) [... lines matching original stack trace ...]

i have same error how did you fix this?

@SloboZjalic
Copy link

SloboZjalic commented Nov 21, 2022 via email

@henrykash
Copy link

henrykash commented Nov 21, 2022 via email

@SloboZjalic
Copy link

SloboZjalic commented Nov 21, 2022 via email

@henrykash
Copy link

henrykash commented Nov 21, 2022 via email

@henrykash
Copy link

henrykash commented Nov 21, 2022

Alright so instead of using wait( ) function you can use the waitForTransaction function from ethers, which takes in the transaction hash of the transaction broadcasted , number of confirmation and timeout in milliseconds ...assuming that the tx returns a successful transaction hash and that it's accessed as tx.data : you can do the following example


const tx = await wbnb.approve(
router.address,
valueToapprove,
{
gasLimit:100000
}
);
const provider = new ethers.providers.WebSocketProvider('wss://apis.ankr.com/wss/....');
const receipt =  await  provider.waitForTransaction(tx.data, 1, 60000);

  if (receipt && receipt.status == 1) {

           //TODO: you can proceed with your code execution                                                   
    })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

15 participants