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.