Skip to content

Instantly share code, notes, and snippets.

@riordant
Created February 8, 2021 16:24
Show Gist options
  • Save riordant/4410cec8cf870acb7137010d951881ab to your computer and use it in GitHub Desktop.
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.
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