1

What is the best practice when working with numbers with web3.js when interacting with smart contracts? For instance is best practice when working with numbers when interacting with smart contracts with web3.js library to use the utils whilst saving the variable or afterword's when using the variable? or use 10**18 or to use big Number or what?

This is whilst saving the number with the web3 utils in variable option:

  const tkns = document.getElementById("avTkn");
  const balance = await window.contract.methods.balanceOf(ethereum.selectedAddress).call().then((balance) => {return balance}); 
  tkns.innerText = w3.utils.fromWei(balance);

And this is after for example:

  const tkns = document.getElementById("avTkn");
  const balance = await window.contract.methods.balanceOf(ethereum.selectedAddress).call().then((balance) => {return w3.utils.fromWei(balance)}); 
  tkns.innerText = balance;

Is there any difference at all, or it's just programmer preference? Is anyone using a better way recommended by best practices when using numbers with web3.js that is universally accepted?

FYI: (This example uses a contract with 18 decimal points).

1 Answer 1

0

I store contract numeric (Number) data in the string (In this way I don't loose a single bit of that number) format in the wei unit. Because I found it the best way to deal when you want to do manupulations on that data like math operations (+-*/). I've created a function to do all that calculation stuffs on big number.

bnCal: (operator: string = '', a, b, returnString: boolean = false) => {
    let result = undefined;
    a = web3Helper.strToBn(a);
    b = web3Helper.strToBn(b);
    if(operator === 'add') result =  a.add(b);
    if(operator === 'sub') result =  a.sub(b);
    if(operator === 'mul') result =  a.mul(b);
    if(operator === 'div') result =  a.div(b);
    if(operator === 'gt') result =  a.gt(b);       
    if(operator === 'gte') result =  a.gte(b);       
    if(operator === 'lt') result =  a.lt(b);        
    if(operator === 'lte') result =  a.lte(b);
    return returnString ? (result).toString() : result;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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