religion-counter/onlyone

Error: Returned error: insufficient funds for gas * price + value

Closed this issue · 3 comments

Hi, first of all thanks a lot for this content, it's hard to find this kind of code to let us know how things work under the hood.
I'm trying to buy a token (RUSD) with BUSD. The fact is i'm always getting that i have not enough funds on my wallet, even if i have enough BNB (0.5) to pay the transaction fee.

I'm using your code, just changed a few things for my needs:

var fs = require('fs')
var Tx = require('ethereumjs-tx').Transaction;
var Web3 = require('web3')
var Common = require('ethereumjs-common').default;

var web3 = new Web3(new Web3.providers.HttpProvider('https://bsc-dataseed.binance.org/'))
var BSC_FORK = Common.forCustomChain(
    'mainnet',
    {
        name: 'Binance Smart Chain Mainnet',
        networkId: 56,
        chainId: 56,
        url: 'https://bsc-dataseed.binance.org/'
    },
    'istanbul',
);

// Amount to buy
const execSync = require('child_process').execSync;
const originalAmountToBuyWith = execSync('node getTokensBalance.js busd', { encoding: 'utf-8' }).replace(/\s+/g, ' ').trim();

var busdAmount = web3.utils.toWei(originalAmountToBuyWith, 'ether');

var config = JSON.parse(fs.readFileSync('config.json', 'utf-8'));

console.log(`Buying RUSD for ${originalAmountToBuyWith} BUSD from pancakeswap for address ${config.walletAddress}`);

var res = buyRUSD(config.walletAddress, busdAmount);
console.log(res);

async function buyRUSD(walletAddress, amount) {

    var amountToBuyWith = web3.utils.toHex(amount);
    var privateKey = Buffer.from(config.privateKey, 'hex')  ;

    var amountOutMin = '100' + Math.random().toString().slice(2,6);

    var routerAbi = JSON.parse(fs.readFileSync('pancake-router-abi.json', 'utf-8'));
    var contract = new web3.eth.Contract(routerAbi, config.pancakeSwapRouterAddress, {from: walletAddress});
    var data = contract.methods.swapExactETHForTokens(
        web3.utils.toHex(amountOutMin),
        [config.busdAddress,
         config.rusdAddress],
        walletAddress,
        web3.utils.toHex(Math.round(Date.now()/1000)+60*20),
    );

    var count = await web3.eth.getTransactionCount(walletAddress);

    var rawTransaction = {
        "from":walletAddress,
        "gasPrice": web3.utils.toHex(web3.utils.toWei('5', 'gwei')),
        "gasLimit": 100000,
        "to":config.pancakeSwapRouterAddress,
        "value":web3.utils.toHex(amountToBuyWith),
        "data":data.encodeABI(),
        "nonce":web3.utils.toHex(count)
    };

    var transaction = new Tx(rawTransaction, { 'common': BSC_FORK });
    transaction.sign(privateKey);

    var result = await web3.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'));
    return result;
}

I always get (node:327974) UnhandledPromiseRejectionWarning: Error: Returned error: insufficient funds for gas * price + value. I'm using my metamask wallet, i'm sure the wallet address is good, also the privatekey associated.

Another point, how are you sure you won't spend too much transaction fees if there is some congestion ? gasLimit i suppose.

Thanks again mate if you have any idea!
Gabriel.

Beginning of an answer, i changed;

const busdAmount = web3.utils.toWei(originalAmountToBuyWith, 'ether');

with;

const busdAmount = Math.floor(originalAmountToBuyWith);

(in fact i have 17 BUSD i try to swap into RUSD).

Now the tx has been reverted, got Fail with error 'PancakeRouter: INVALID_PATH' (0x4bd551cd835cd17ac71458cc61faeb3569bafd19e607df2feb3c0b7f0b131e32). Don't know if i have to play with amountOutMin.

Hi phackt,

There are a couple of problems with your transaction: https://bscscan.com/tx/0x4bd551cd835cd17ac71458cc61faeb3569bafd19e607df2feb3c0b7f0b131e32

First you try to exchange BUSD for rUSD with swapExactETHForTokens method. This method is used only if you try to exchange BNB for tokens. For exchanging token for token you should use swapExactTokensForTokens method.
When you swap tokens for tokens you should set transaction value to 0 and set the value in the amountIn parameter.

Also I see the value is 17 wei which is 0.00000000000000000000017 BUSD. You should first convert the original amount with web3.utils.toWei(originalAmountToBuyWith, 'ether'); method.

The easiest way to create transaction is to first try to do the thing you want to do on pancakeswap.finance website. Check the transaction on bscscan.com and after that try to simulate it with code.

Hi @religion-counter, yes you are totally right i can now figure out what my mistakes are ! After fixing with what you said it works like a charm ! Thanks for your sharing it helps a lot !!