I'm having a hard time finding the keywords to search for this online.
I've created a class with safe math functions. Each function takes 2 arguments and after being evaluated by an assertion, it returns the result.
Example:
class SafeMath {
static add(x: number, y: number) {
let z: number = x + y;
assert(z >= x, 'ds-math-add-overflow');
return z;
}
static sub(x: number, y: number) {
let z: number = x - y;
assert(z <= x, 'ds-math-sub-underflow');
return z;
}
static mul(x: number, y: number) {
let z: number = x * y;
assert(y == 0 || z / y == x, 'ds-math-mul-overflow');
return z;
}
static div(x: number, y: number) {
let z: number = x / y;
assert(x > 0 || y > 0, 'ds-math-div-by-zero');
return z;
}
}
console.log(SafeMath.add(2,2)); // 4
console.log(SafeMath.sub(2,2)); // 0
console.log(SafeMath.mul(2,2)); // 4
console.log(SafeMath.div(2,2)); // 1
My goal was to have these functions work like this, for example:
let balance0: number = 1;
let balance1: number = 1;
let amount0In: number = 10;
let amount1In: number = 10;
let balance0Adjusted: number = balance0.mul(1000).sub(amount0In.mul(3));
let balance1Adjusted: number = balance1.mul(1000).sub(amount1In.mul(3));
...the functions would take in y
and use the previous number as x
.