javascriptblockchainsmartcontractscryptocurrencymetamask

Unable to calculate number of bnb in metamask wallet


I am trying to add an option to my webapp where user can add number of coins they want to buy using their bnb. It connects with metamask and execute the order. Problem is- value of my 1 coin is 0.0001 BNB, when I select 1 coin it should ideally execute order for 0.0001 BNB but it executes order for 0.07205759 BNB.

Below is the js-

    <script type="text/javascript">
    let web3;
    let userAddress = null;

    // Initialize Web3
    if (typeof window.ethereum !== 'undefined') {
        web3 = new Web3(window.ethereum);  // Initialize Web3 with MetaMask
    } else {
        alert('MetaMask or another compatible wallet is not installed. Please install it and try again.');
    }

    // Connect Wallet Logic
    document.getElementById('connect').addEventListener('click', async () => {
        if (web3) {
            try {
                const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
                userAddress = accounts[0];
                document.getElementById('bnb_address').value = userAddress;
                alert("Wallet connected: " + userAddress);
            } catch (error) {
                console.error("User denied account access or connection failed:", error);
                alert("Failed to connect wallet. Please try again.");
            }
        }
    });

    document.getElementById('buyButton').addEventListener('click', async () => {
        try {
            if (!userAddress) {
                alert('Please connect your wallet first.');
                return;
            }

            // Ensure the user is connected to Binance Smart Chain
            const chainId = await window.ethereum.request({ method: 'eth_chainId' });
            const bscChainId = '0x38'; // 56 in hexadecimal, the chain ID for BSC mainnet

            if (chainId !== bscChainId) {
                alert('Please switch your network to Binance Smart Chain.');
                return;
            }

            const tokenAmount = parseFloat(document.getElementById('token_amount').value);
            if (isNaN(tokenAmount) || tokenAmount <= 0) {
                alert('Please enter a valid number of tokens.');
                return;
            }

            // Correct BNB amount calculation
            const tokenPriceInBNB = 0.0001; // 1 token = 0.0001 BNB
            const bnbAmount = tokenPriceInBNB * tokenAmount; // Calculate the correct BNB amount

            // Convert BNB to Wei
            const bnbAmountInWei = web3.utils.toWei(bnbAmount.toFixed(18), 'ether');

            console.log(`Token Amount: ${tokenAmount}`);
            console.log(`BNB Amount (before conversion to Wei): ${bnbAmount}`);
            console.log(`BNB Amount in Wei (to be sent): ${bnbAmountInWei}`);

            const transactionParameters = {
                to: '{{ receiving_address }}', // The address to send to
                from: userAddress, // The user's active address
                value: bnbAmountInWei, // Pass the correct value in Wei
                gas: '210000', // Temporarily increased gas limit for testing
            };

            try {
                const txHash = await window.ethereum.request({
                    method: 'eth_sendTransaction',
                    params: [transactionParameters],
                });
                alert("Transaction sent! Hash: " + txHash);
            } catch (error) {
                console.error("Transaction failed during send:", error);
                alert("Transaction failed during send: " + error.message);
            }
        } catch (error) {
            console.error("Transaction preparation failed:", error);
            alert("Transaction preparation failed: " + error.message);
        }
    });
</script>

Solution

  • You need to send the number in hex but you are just using the decimal value.

    I could see this by converting the 1000000000000000 you confirmed was the value being sent from hex to decimal and this comes to 72057594037927936

    Probably a good idea to read the documentation which states that values are passed as hex.