0

i have this snippet i fixed the hex and suggested in the comments. Console error is here https://ibb.co/LShTFxX Metamask is still throwing large number


console.log('the conversion factor is', conversionFactor);

if(conversionFactor != null){
    const networkStatus = await checkNetwork('ethereum'); 
    if(networkStatus){
        console.log('its okay to send transaction we are on the correct network');
        transactionInProgress = true;
        const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
        const userWallet = accounts[0];
        const recipientWallet = RoysWallet; 
        const weiParameter = amountToSendFloat;//*conversionFactor;
        const desiredDecimalPlaces = 7; 
        let weiParameterStr = weiParameter.toString();
        let decimalIndex = weiParameterStr.indexOf('.');

        if (decimalIndex !== -1) {
          let decimalPlaces = weiParameterStr.length - decimalIndex - 1;
          if (decimalPlaces > desiredDecimalPlaces) {
            weiParameterStr = weiParameterStr.slice(0, decimalIndex + desiredDecimalPlaces + 1);
          }
        }

        const finalWeiParameter = parseFloat(weiParameterStr);
        //console.log(finalWeiParameter.toString());
        const amountInWei = web3.utils.toWei(finalWeiParameter.toString(), 'ether');
        //const amountInWei = web3.utils.toWei(amountToSendString, 'ether');
        // Convert Wei to Hex
        const amountInHex = web3.utils.toHex(amountInWei);
        // might not be hexing correctly test individually
        console.log(`Amount in Hex: ${amountInHex}`); 
        const transactionObject = {
            from: userWallet, 
            to: recipientWallet,
            value: amountInHex
        };
        console.log('trying to send string:', amountToSendString);
        console.log('final Wei paramater', finalWeiParameter);
        console.log('amount to send float', amountToSendFloat);
        console.log('in WEI', amountInWei);
        console.log('in hex', amountInHex);

        const response = await window.ethereum.request({
            method: 'eth_sendTransaction',
            params: [transactionObject]
        });
    }
}else{
    
}```

1 Answer 1

1

const amountInWei = web3.utils.toWei(amountToSendFloat, 'ether') ^ You don't need conversionFactor. Simply replace with this snippet. Provide amountToSendFloat as a string .

The problem with providing amountToSendFloat as float is that decimal places are harder to represent in binary (that's how they are stored to save space) so it will automatically be approximated if decimals go deep.

There is one important thing to keep in mind if your amountToSendFloat has more than 18 decimals you need to do something with the decimals after the 18th decimal. Either truncate, round up to 18th place or round down to 18th place. eg. 5.1234567891234567891 has 19 decimals you need to do something with the final value 1.

EDIT

        function manipulateDecimals(strNum){ 

            // Decimal Manipulation logic here ...
            // returned value should be string
            return strNum 

        }

        // Removed `if(conversionFactor != null)`
        const networkStatus = await checkNetwork('ethereum'); 
        
        // Let the input amount be in string and not float to avoid rounnding errors
        let amountToSendStr = "1.23432432132"

        // Manipulate `amountToSendStr` to your desired decimal place  keep result in string . 
        amountToSendStr=manipulateDecimals(amountToSendStr)

         

        if(networkStatus){
            console.log('its okay to send transaction we are on the correct network');
            transactionInProgress = true;
            const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
            const userWallet = accounts[0];
            const recipientWallet = RoysWallet; 
            
            // Removed multiplication by conversion factor const weiParameter = amountToSendFloat*conversionFactor;
            // Replaced with correct code snippet 
            const amountInWei = web3.utils.toWei(amountToSendStr, 'ether')// Convert amount to wei
            
            // Print and check amount in wei . Simply pass this to your `transactionObject` as  `value`
            console.log("amountInWei: ", amountInWei)

        }

EDIT2 Use

const transactionObject = {
    from: userWallet, // deprecated in firefox window.ethereum.selectedAddress,
    to: recipientWallet,
    value: web3.utils.toHex(amountInWei)
};

Metamask expects value field in HEX . web3.utils.toHex(amountInWei) does the job https://docs.metamask.io/wallet/reference/eth_sendtransaction/

Complete snippet -

        function manipulateDecimals(strNum){ 

            // Decimal Manipulation logic here ...
            // returned value should be string
            return strNum 

        }

        // Removed `if(conversionFactor != null)`
        const networkStatus = await checkNetwork('ethereum'); 

        // Let the input amount be in string and not float to avoid rounnding errors
        let amountToSendStr = "1.23432432132"

        // Manipulate `amountToSendStr` to your desired decimal place  keep result in string . 
        amountToSendStr=manipulateDecimals(amountToSendStr)



        if(networkStatus){
            console.log('its okay to send transaction we are on the correct network');
            transactionInProgress = true;
            const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
            const userWallet = accounts[0];
            const recipientWallet = RoysWallet; 

            // Removed multiplication by conversion factor const weiParameter = amountToSendFloat*conversionFactor;
            // Replaced with correct code snippet 
            const amountInWei = web3.utils.toWei(amountToSendStr, 'ether')// Convert amount to wei

            // Print and check amount in wei . Simply pass this to your `transactionObject` as  `value`
            console.log("amountInWei: ", amountInWei)

        }
    const transactionObject = {
    from: userWallet, // deprecated in firefox window.ethereum.selectedAddress,
    to: recipientWallet,
    value: web3.utils.toHex(amountInWei) // Converting to HEX !!!
};
// Proceed to broadcast transaction object

EDIT 3 Here's my complete code . It triggers metamask and sends 0.23432432132 eth on confirmation . Exactly equal to the amount that I have mentioned in the code . https://sepolia.etherscan.io/tx/0x1a81e02e65a35cc0ceec1ad94c6c908ac0bf959b7bb24a9247dee6f2b8b1ec81

  • List item
<!DOCTYPE html>
<html>
<head>
    <title>MetaMask Transaction Example</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/web3.min.js"></script>
</head>
<body>
    <script>
async function connectToMetaMask(){
const web3 = new Web3(window.ethereum);  // Replace with your Ethereum node URL

function manipulateDecimals(strNum){ 

    // Decimal Manipulation logic here ...
    // returned value should be string
    return strNum 

}


// Let the input amount be in string and not float to avoid rounnding errors
let amountToSendStr = "0.23432432132"

// Manipulate `amountToSendStr` to your desired decimal place  keep result in string . 
amountToSendStr=manipulateDecimals(amountToSendStr)

console.log('its okay to send transaction we are on the correct network');
transactionInProgress = true;
let accounts 
if (typeof window.ethereum !== 'undefined') {

accounts = await window.ethereum.request({ method: 'eth_requestAccounts' })

}


const userWallet = accounts[0];
const recipientWallet = userWallet;

// Removed multiplication by conversion factor const weiParameter = amountToSendFloat*conversionFactor;
// Replaced with correct code snippet 
const amountInWei = web3.utils.toWei(amountToSendStr, 'ether')// Convert amount to wei

// Print and check amount in wei . Simply pass this to your `transactionObject` as  `value`
console.log("amountInWei: ", amountInWei)

const transactionObject = {
    from: userWallet, // deprecated in firefox window.ethereum.selectedAddress,
    to: recipientWallet,
    value: web3.utils.toHex(amountInWei)
};
console.log('trying to send', amountToSendStr);
console.log('in WEI', amountInWei);

// Send the transaction using MetaMask
const response = await window.ethereum.request({
    method: 'eth_sendTransaction',
    params: [transactionObject]
});
}
alert("DONE ")


// Automatically attempt to connect to MetaMask when the page is loaded
window.addEventListener('load', () => {
    connectToMetaMask();
})


    </script>
</body>
</html>
24
  • okay i will change to string and see what happens.
    – ROY BURSON
    Commented Jun 29 at 22:54
  • it did not work. If i send 1.4 for example it gives me a lot more like i need to convert it
    – ROY BURSON
    Commented Jun 29 at 23:18
  • @RoyBUrson Paste the code snippet on pastebin and share the link
    – shadow
    Commented Jun 30 at 15:20
  • the code is publicly available at github.com/bursonskullz/Web3-Art-Website/blob/main/… the metamask transaction is on line 5155 or you can search using Ctl+F and search for conversion factor. The code is also running online at bursonskullz.com in my private server using this conversion factor I just made everything like 1.4-1.6 ethereum
    – ROY BURSON
    Commented Jul 1 at 0:46
  • @ROYBURSON Just like 1$ = 100 cents , 1 eth = 10^18 wei there is nothing more to the problem than this . I have editted my answer, read the comments I have posted in the editted code carefully .
    – shadow
    Commented Jul 1 at 2:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.