Skip to content

Conversation

sodii
Copy link

@sodii sodii commented Jul 5, 2024

Description

I've changed the SignedWadMath.wadLn to use a precomputed table for calculating integer part.

assembly {
    r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
    r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
    r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
    r := or(r, shl(4, lt(0xffff, shr(r, x))))
    r := or(r, shl(3, lt(0xff, shr(r, x))))
    r := or(r, shl(2, lt(0xf, shr(r, x))))
    
    // I've changed the two lines below:
    // r := or(r, shl(1, lt(0x3, shr(r, x))))
    // r := or(r, lt(0x1, shr(r, x)))

    // into:
    r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030303000000000000000000000000000000))
}

This saves 45 gas.

To measure gas savings of the change, I've also implemented a crude test for wadLn and wadExp:

function testWadLnExp(uint256 x) public {
    x = bound(x, 0, 135305999368893231588 + 10e18);

    int256 xPrime = int256(x) - 10e18;
    int256 diff = wadLn(wadExp(xPrime)) - xPrime;

    assertLe(diff < 0 ? -diff : diff, 100000);
}

The tested range is -10e18 <= x <= 135305999368893231588.
135305999368893231588 is the largest integer where wadExp(x) doesn't overflow.
-10e18 is somewhat arbitariliy chosen because the test was failing for -20e18.

Checklist

Ensure you completed all of the steps below before submitting your pull request:

  • Ran forge snapshot?
  • Ran npm run lint?
  • Ran forge test?

Pull requests with an incomplete checklist will be thrown out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant