Created
February 8, 2021 16:24
-
-
Save riordant/4410cec8cf870acb7137010d951881ab to your computer and use it in GitHub Desktop.
ethers DSMath - perform decimal precision operations with ethers BigNumber. Adapted from Solidity DSMath library.
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
const { ethers } = require("ethers"); | |
BigNumber = ethers.BigNumber | |
module.exports = { | |
WAD: ethers.utils.parseUnits('1'), | |
//rounds to zero if x*y < WAD / 2 | |
wmul: function(x, y) { | |
return x.mul(y).add(WAD.div(2)).div(WAD); | |
}, | |
//rounds to zero if x*y < WAD / 2 | |
wdiv: function(x, y) { | |
return x.mul(WAD).add(y.div(2)).div(y); | |
}, | |
wpow: function(x, n) { | |
z = (!n.mod(2).eq(0)) ? x : WAD; | |
for (n = n.div(2); !n.eq(0); n = n.div(2)) { | |
x = this.wmul(x, x); | |
if (!n.mod(2).eq(0)) { | |
z = this.wmul(z, x); | |
} | |
} | |
return z; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment