Last active
September 21, 2022 03:57
-
-
Save dbeal-eth/fd16c8605051d7fb03151f5a2f0121bc to your computer and use it in GitHub Desktop.
Wei.js and bignumber.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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