Skip to content

Instantly share code, notes, and snippets.

@dbeal-eth
Last active September 21, 2022 03:57
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbeal-eth/fd16c8605051d7fb03151f5a2f0121bc to your computer and use it in GitHub Desktop.
Save dbeal-eth/fd16c8605051d7fb03151f5a2f0121bc to your computer and use it in GitHub Desktop.
Wei.js and bignumber.js
import { ethers } from 'ethers';
// import
import BigNumber from 'bignumber.js';
import Wei, { wei } from '@synthetixio/wei';
// construction (string)
let bigNum = new BigNumber('100000000000000000');
let weiNum = wei('1');
// construction (number)
bigNum = new BigNumber(ethers.utils.formatEther(1).toString(), 10);
weiNum = wei(1);
// construction (Ethers.BigNumber)
const ethersBigNum = ethers.utils.parseEther('1');
bigNum = new BigNumber(ethersBigNum.toString());
weiNum = wei(ethersBigNum) // imported as-is (unscaled)
// construction (unscaled BigNumber)
let unscaledBigNum = new BigNumber(123);
let unscaledWeiNum = wei(123, 0);
bigNum = new BigNumber(ethersBigNum.toString());
weiNum = wei(ethersBigNum);
// formatted print
console.log(bigNum.dividedBy(bigNum).precision(2).toString());
console.log(weiNum.toString(2));
// addition/subtraction
bigNum = bigNum.plus(bigNum);
weiNum = weiNum.add(weiNum);
// tip: weiNum = weiNum.plus(1) also works too!
// multiplication/division
bigNum = bigNum.multipliedBy(bigNum).dividedBy(ethers.utils.formatEther(1).toString());
weiNum = weiNum.mul(weiNum);
// conversion to ethers.BigNumber
const bnEthersBignum = ethers.BigNumber.from(bigNum.toString());
const weiEthersBigNum = weiNum.toBN();
// handling invalid input
bigNum = new BigNumber('bad input'); // = NaN
try {
weiNum = wei('bad input'); // exception
} catch (err) {
// handle gracefully
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment