Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Increase the life-time of exponential gradient orders #160

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 41 additions & 11 deletions contracts/utility/Trade.sol
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ library Trade {
error InitialRateTooHigh();
error MultiFactorTooHigh();

uint256 private constant EXP_ONE = 0x0080000000000000000000000000000000; // 1
uint256 private constant EXP_MID = 0x0400000000000000000000000000000000; // 8
uint256 private constant EXP_MAX = 0x2cb53f09f05cc627c85ddebfccfeb72758; // ceil(ln2) * 129
uint256 private constant EXP_LN2 = 0x0058b90bfbe8e7bcd5e4f1d9cc01f97b58; // ceil(ln2)

uint256 private constant R_ONE = 1 << 48; // = 2 ^ 48
uint256 private constant M_ONE = 1 << 24; // = 2 ^ 24

uint256 private constant EXP_ONE = 1 << 127; // = 2 ^ 127
uint256 private constant MAX_VAL = 1 << 131; // = 2 ^ 131

uint256 private constant RR = R_ONE * R_ONE; // = 2 ^ 96
uint256 private constant MM = M_ONE * M_ONE; // = 2 ^ 48

Expand Down Expand Up @@ -70,8 +72,8 @@ library Trade {
* | linear | decrease | r * (1 - m * t) | m * t < 1 (ensure a finite-positive rate) |
* | linear-inverse | increase | r / (1 - m * t) | m * t < 1 (ensure a finite-positive rate) |
* | linear-inverse | decrease | r / (1 + m * t) | |
* | exponential | increase | r * e ^ (m * t) | m * t < 16 (due to computational limitation) |
* | exponential | decrease | r / e ^ (m * t) | m * t < 16 (due to computational limitation) |
* | exponential | increase | r * e ^ (m * t) | m * t < 129 * ln2 (computational limitation) |
* | exponential | decrease | r / e ^ (m * t) | m * t < 129 * ln2 (computational limitation) |
* +----------------+-----------+-----------------+----------------------------------------------+
*/
function calcCurrentRate(
Expand Down Expand Up @@ -146,32 +148,60 @@ library Trade {
}
}

/**
* @dev Ensure a finite positive rate
*/
function sub(uint256 one, uint256 mt) internal pure returns (uint256) {
unchecked {
if (one <= mt) {
// non-finite or non-positive
revert InvalidRate();
}
// finite and positive
return one - mt;
}
}

/**
* @dev Compute e ^ (x / EXP_ONE) * EXP_ONE
* Input range: 0 <= x <= MAX_VAL - 1
* Input range: 0 <= x <= EXP_MAX - 1
* Detailed description:
* - For x < EXP_MID, this function computes e ^ x
* - For x < EXP_MAX, this function computes e ^ mod(x, ln2) * 2 ^ div(x, ln2)
* - The latter relies on the following identity:
* e ^ x =
* e ^ x * 2 ^ k / 2 ^ k =
* e ^ x * 2 ^ k / e ^ (k * ln2) =
* e ^ x / e ^ (k * ln2) * 2 ^ k =
* e ^ (x - k * ln2) * 2 ^ k
* - Replacing k with div(x, ln2) gives the solution above
* - The value of ln2 is represented as ceil(ln2 * EXP_ONE)
*/
function exp(uint256 x) internal pure returns (uint256) {
unchecked {
if (x < EXP_MID) {
return _exp(x); // slightly more accurate
}
if (x < EXP_MAX) {
return _exp(x % EXP_LN2) << (x / EXP_LN2);
}
revert ExpOverflow();
}
}

/**
* @dev Compute e ^ (x / EXP_ONE) * EXP_ONE
* Input range: 0 <= x <= EXP_ONE * 16 - 1
* Detailed description:
* - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible
* - The exponentiation of each binary exponent is given (pre-calculated)
* - The exponentiation of r is calculated via Taylor series for e^x, where x = r
* - The exponentiation of the input is calculated by multiplying the intermediate results above
* - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859
*/
function exp(uint256 x) internal pure returns (uint256) {
function _exp(uint256 x) private pure returns (uint256) {
// prettier-ignore
unchecked {
if (x >= MAX_VAL) {
revert ExpOverflow();
}

uint256 res = 0;

uint256 y;
Expand Down
134 changes: 99 additions & 35 deletions test/carbon/accuracy/gradient_strategies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ const M_SHIFT = 24;
const ONE = new Decimal(1);
const TWO = new Decimal(2);

const EXP_ONE = new Decimal(2).pow(127);
const MAX_VAL = new Decimal(2).pow(131);
const EXP_ONE = TWO.pow(127);
const EXP_MAX = EXP_ONE.mul(TWO.ln()).ceil().mul(129);

const BnToDec = (x: BigNumber) => new Decimal(x.toString());
const DecToBn = (x: Decimal) => BigNumber.from(x.toFixed());
Expand Down Expand Up @@ -135,33 +135,42 @@ function testConfiguration(
});
}

function testExp(n: number, d: number, maxError: string) {
it(`testExp(${n} / ${d})`, async () => {
const f = new Decimal(n).div(d);
const funcCall = contract.exp(DecToBn(f.mul(EXP_ONE).floor()));
if (f.lt(MAX_VAL.div(EXP_ONE))) {
const actual = BnToDec(await funcCall);
const expected = f.exp().mul(EXP_ONE);
if (!actual.eq(expected)) {
expect(actual.lt(expected)).to.be.equal(
true,
`\n- expected = ${expected.toFixed()}` +
`\n- actual = ${actual.toFixed()}`
);
const error = actual.div(expected).sub(1).abs();
expect(error.lte(maxError)).to.be.equal(
true,
`\n- expected = ${expected.toFixed()}` +
`\n- actual = ${actual.toFixed()}` +
`\n- error = ${error.toFixed()}`
);
}
} else {
await expect(funcCall).to.revertedWithError('ExpOverflow');
}
function testExpNative(n: number, d: number, maxError: string) {
it(`testExpNative(${n} / ${d})`, async () => {
const x = EXP_ONE.mul(n).div(d).floor();
await testExp(x, maxError);
});
}

function testExpScaled(x: Decimal, maxError: string) {
it(`testExpScaled(${x.toHex()})`, async () => {
await testExp(x, maxError);
});
}

async function testExp(x: Decimal, maxError: string) {
if (x.lt(EXP_MAX)) {
const actual = BnToDec(await contract.exp(DecToBn(x)));
const expected = x.div(EXP_ONE).exp().mul(EXP_ONE);
if (!actual.eq(expected)) {
expect(actual.lt(expected)).to.be.equal(
true,
`\n- expected = ${expected.toFixed()}` +
`\n- actual = ${actual.toFixed()}`
);
const error = actual.div(expected).sub(1).abs();
expect(error.lte(maxError)).to.be.equal(
true,
`\n- expected = ${expected.toFixed()}` +
`\n- actual = ${actual.toFixed()}` +
`\n- error = ${error.toFixed()}`
);
}
} else {
await expect(contract.exp(DecToBn(x))).to.revertedWithError('ExpOverflow');
}
}

describe('Gradient strategies accuracy stress test', () => {
before(async () => {
contract = await Contracts.TestTrade.deploy();
Expand Down Expand Up @@ -189,15 +198,48 @@ describe('Gradient strategies accuracy stress test', () => {
const initialRate = new Decimal(10).pow(a);
const multiFactor = new Decimal(10).pow(b);
const timeElapsed = Decimal.min(
MAX_VAL.div(EXP_ONE).div(multiFactor).sub(1).ceil(),
TWO.pow(4).div(multiFactor).sub(1).ceil(),
TWO.pow(25).sub(1)
).mul(c).div(10).ceil();
testCurrentRate(0, initialRate, multiFactor, timeElapsed, '0');
testCurrentRate(1, initialRate, multiFactor, timeElapsed, '0');
testCurrentRate(2, initialRate, multiFactor, timeElapsed, '0');
testCurrentRate(3, initialRate, multiFactor, timeElapsed, '0');
testCurrentRate(4, initialRate, multiFactor, timeElapsed, '0.000000000000000000000000000000000002');
testCurrentRate(5, initialRate, multiFactor, timeElapsed, '0.000000000000000000000000000000000002');
testCurrentRate(4, initialRate, multiFactor, timeElapsed, '0.00000000000000000000000000000000000006');
testCurrentRate(5, initialRate, multiFactor, timeElapsed, '0.00000000000000000000000000000000000006');
}
}
}

for (const a of [-27, -10, 0, 10, 27]) {
for (const b of [-14, -9, -6, -1]) {
for (const c of [1, 4, 7, 10]) {
const initialRate = new Decimal(10).pow(a);
const multiFactor = new Decimal(10).pow(b);
const timeElapsed = Decimal.min(
EXP_MAX.div(EXP_ONE).div(multiFactor).sub(1).ceil(),
TWO.pow(25).sub(1)
).mul(c).div(10).ceil();
testCurrentRate(0, initialRate, multiFactor, timeElapsed, '0');
testCurrentRate(1, initialRate, multiFactor, timeElapsed, '0');
testCurrentRate(2, initialRate, multiFactor, timeElapsed, '0');
testCurrentRate(3, initialRate, multiFactor, timeElapsed, '0');
testCurrentRate(4, initialRate, multiFactor, timeElapsed, '0.000000000004');
testCurrentRate(5, initialRate, multiFactor, timeElapsed, '0.0000000000000000000000000000000000003');
}
}
}

for (const a of [-27, -10, 0, 10, 27]) {
for (const b of [-14, -9, -6, -1]) {
for (const c of [19, 24, 29]) {
const initialRate = new Decimal(10).pow(a);
const multiFactor = new Decimal(10).pow(b);
const timeElapsed = new Decimal(2).pow(c).sub(1);
testCurrentRate(0, initialRate, multiFactor, timeElapsed, '0.0000000000000000000000000000000000000000003');
testCurrentRate(1, initialRate, multiFactor, timeElapsed, '0');
testCurrentRate(2, initialRate, multiFactor, timeElapsed, '0');
testCurrentRate(3, initialRate, multiFactor, timeElapsed, '0');
}
}
}
Expand All @@ -222,23 +264,45 @@ describe('Gradient strategies accuracy stress test', () => {
testConfiguration('multiFactor', multiFactor, multiFactorEncoded, multiFactorDecoded, '0.000000000000004', '0.00000007');
}

for (let n = 1; n <= 25; n++) {
for (let d = 1; d <= 25; d++) {
testExp(n, d, '0.000000000000000000000000000000000002');
for (let n = 1; n <= 100; n++) {
for (let d = 1; d <= 100; d++) {
testExpNative(n, d, '0.0000000000000000000000000000000000003');
}
}

for (let d = 1000; d <= 1000000000; d *= 10) {
for (let n = d - 10; n <= d + 10; n++) {
testExp(n, d, '0.00000000000000000000000000000000000003');
testExpNative(n, d, '0.00000000000000000000000000000000000002');
}
}

for (let n = 1; n < 1000; n++) {
testExp(n, 1000, '0.00000000000000000000000000000000000003');
testExpNative(n, 1000, '0.00000000000000000000000000000000000002');
}

for (let d = 1; d < 1000; d++) {
testExp(1, d, '0.00000000000000000000000000000000000002');
testExpNative(1, d, '0.00000000000000000000000000000000000002');
}

for (let i = 0; i < 10; i++) {
for (const j of [-1, 0, +1]) {
testExpScaled(EXP_ONE.mul(TWO.pow(i + 1).ln()).floor().add(j), '0.00000000000000000000000000000000000003');
}
}

for (let i = 0; i < 10; i++) {
for (const j of [-1, 0, +1]) {
testExpScaled(EXP_ONE.mul(TWO.ln().pow(i + 2)).floor().add(j), '0.00000000000000000000000000000000000002');
}
}

for (let i = 0; i < 10; i++) {
for (const j of [-1, 0, +1]) {
testExpScaled(EXP_ONE.mul(TWO.pow(i - 3)).add(j), '0.0000000000000000000000000000000000003');
}
}

for (let i = 0; i < 10; i++) {
testExpScaled(EXP_MAX.add(i - 10), '0.0000000000000000000000000000000000003');
}
});
Loading