web3 / web3.js

Collection of comprehensive TypeScript libraries for Interaction with the Ethereum JSON RPC API and utility functions.
https://web3js.org/
Other
19.25k stars 4.93k forks source link

React Native: insufficient funds for gas * price + value in BSC testnet chain. ONLY Release, Debug work great. I have 0.3 BNB enough for transaction #6218

Closed huuanhopp closed 1 year ago

huuanhopp commented 1 year ago
"@ethersproject/abi": "5.4.0",
"@ethersproject/contracts": "5.4.1",
"@ethersproject/providers": "5.4.4",
"@ethersproject/shims": "5.4.0",
"web3": "^1.7.5",
"@ethereumjs/common": "^2.6.5",
"@ethereumjs/tx": "^3.5.2",

Please help me! This is my code:

` let sendAmount = new BigNumber(amountIn).multipliedBy(Math.pow(10, 18)); // Set up the signer using the private key tronLog({amountIn, slip}); const sendAmountWithSlip = ethers.utils.parseUnits( (amountIn * (1 - slip / 100)).toString(), 18, ); const gasPrice = await BscService.getGasPrice();

  const gasPricePriority = priorityEst(1, gasPrice);

  const routerContract = new mWeb3.eth.Contract(abiPancake, routerAddress);

  // Get the pair address
  // const pairAddress = await factoryContract.getPair(
  //   tokenInAddress,
  //   tokenOutAddress,
  // );

  // tronLog({pairAddress});z
  // Get the pair contract instance
  // const pairContract = new ethers.Contract(
  //   pairAddress,
  //   [
  //     'function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast)',
  //     'function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external',
  //   ],
  //   provider,
  // );

  // tronLog({pairContract});
  // // Get the BNB and BUSD reserves
  // const [reserveBNB, reserveBUSD] = await pairContract.getReserves();
  // tronLog({reserveBUSD});

  let getAmountOut = await routerContract.methods
    ?.getAmountsOut(sendAmountWithSlip, [tokenInAddress, tokenOutAddress])
    .call();
  // tronLog({getAmountOutBnb});
  // Calculate the amount of BUSD to receive

  let amountOut = getAmountOut[1];
  const amountOutWithSlippage = ethers.utils.parseUnits(
    amountOut.toString(),
    0,
  );
  tronLog({amountOut});

  // return;
  // Set up the path for the swap (BNB -> BUSD)
  const path = [tokenInAddress, tokenOutAddress];

  // Set the deadline to 5 minutes from now
  const deadline = Math.floor(Date.now() / 1000) + 300;
  tronLog({sendAmount});

  const data = routerContract.methods?.swapExactETHForTokens(
    amountOutWithSlippage,
    path,
    recipientAddress,
    deadline,
  );
  // Set up the transaction

  const transaction = {
    nonce: mWeb3.utils.toHex(
      await mWeb3.eth.getTransactionCount(recipientAddress, 'pending'),
    ),
    to: routerAddress,
    gasPrice: gasPricePriority,
    gasLimit: 500000,
    value: Web3.utils.toHex(sendAmount),
    data: data.encodeABI(),
  };

  // tronLog({transaction});
  // tronLog({common})
  const key = Buffer.from(privateKey, 'hex');
  const common = Common.custom({chainId: chainId});
  const tx = Transaction.fromTxData(transaction, {
    common: common,
  });
  const signedTx = tx.sign(key);
  const serializedTx = signedTx.serialize();
  // mWeb3.eth.
  mWeb3.eth
    .sendSignedTransaction(
      '0x' + serializedTx.toString('hex'),
      function (err, hash) {
        if (!err && hash) {
          tronLog('hash: ', hash);
          resolve(hash);
        } else {
          alert(err);
          tronLog('err depositToken2: ', err);
          reject(err);
        }
      },
    )
    .once('confirmation', () => {
      tronLog('confirmation');
      // reLoadBalance(params?.wallet);
    });`
huuanhopp commented 1 year ago

j just fixed this bug! I'm really sorry, this bug because i using ethers.utils.parseUnits to caculate amount out with slip :v lol, it took me 2 weeks LOLL hahaha thankssssss