@gmx-io/sdk 2.9.1 → 2.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/src/clients/v2/index.js +61 -41
- package/build/cjs/src/clients/v2/solana.spec.js +188 -0
- package/build/cjs/src/configs/api.js +4 -0
- package/build/cjs/src/utils/fees/index.js +7 -1
- package/build/cjs/src/utils/fees/priceImpact.js +118 -18
- package/build/cjs/src/utils/gmsol/constants.js +9 -0
- package/build/cjs/src/utils/gmsol/index.js +53 -0
- package/build/cjs/src/utils/gmsol/numbers.js +176 -0
- package/build/cjs/src/utils/gmsol/types.js +2 -0
- package/build/cjs/src/utils/http/http.js +3 -4
- package/build/cjs/src/utils/http/httpFallback.js +11 -1
- package/build/cjs/src/utils/http/solana.js +17 -0
- package/build/cjs/src/utils/http/validation.js +21 -1
- package/build/cjs/src/utils/http/validation.spec.js +45 -0
- package/build/cjs/src/utils/markets/__tests__/api.spec.js +53 -0
- package/build/cjs/src/utils/markets/api.js +5 -0
- package/build/cjs/src/utils/markets/utils.js +25 -9
- package/build/cjs/src/utils/orders/api.js +3 -0
- package/build/cjs/src/utils/positions/__tests__/liquidationPrice.spec.js +64 -0
- package/build/cjs/src/utils/positions/api.js +3 -0
- package/build/cjs/src/utils/positions/utils.js +88 -19
- package/build/cjs/src/utils/prices/utils.js +69 -14
- package/build/cjs/src/utils/referrals/api.js +41 -0
- package/build/cjs/src/utils/swap/swapRouting.js +4 -0
- package/build/cjs/src/utils/swap/swapStats.js +6 -1
- package/build/cjs/src/utils/trade/__tests__/gmsolTradeMath.spec.js +1012 -0
- package/build/cjs/src/utils/trade/decrease.js +266 -56
- package/build/cjs/src/utils/trade/decreaseMarginCheck.js +23 -4
- package/build/cjs/src/utils/trade/increase.js +86 -28
- package/build/cjs/src/utils/trade/increaseMarginCheck.js +51 -9
- package/build/cjs/src/utils/trade/twapIncreaseMarginCheck.js +8 -3
- package/build/esm/src/clients/v2/index.js +39 -19
- package/build/esm/src/clients/v2/solana.spec.js +160 -0
- package/build/esm/src/configs/api.js +5 -1
- package/build/esm/src/utils/fees/index.js +7 -1
- package/build/esm/src/utils/fees/priceImpact.js +111 -12
- package/build/esm/src/utils/gmsol/constants.js +6 -0
- package/build/esm/src/utils/gmsol/index.js +43 -0
- package/build/esm/src/utils/gmsol/numbers.js +172 -0
- package/build/esm/src/utils/gmsol/types.js +1 -0
- package/build/esm/src/utils/http/http.js +3 -4
- package/build/esm/src/utils/http/httpFallback.js +11 -1
- package/build/esm/src/utils/http/solana.js +12 -0
- package/build/esm/src/utils/http/validation.js +18 -0
- package/build/esm/src/utils/http/validation.spec.js +43 -0
- package/build/esm/src/utils/markets/__tests__/api.spec.js +53 -0
- package/build/esm/src/utils/markets/api.js +6 -1
- package/build/esm/src/utils/markets/utils.js +23 -8
- package/build/esm/src/utils/orders/api.js +3 -0
- package/build/esm/src/utils/positions/__tests__/liquidationPrice.spec.js +62 -0
- package/build/esm/src/utils/positions/api.js +3 -0
- package/build/esm/src/utils/positions/utils.js +89 -20
- package/build/esm/src/utils/prices/utils.js +70 -15
- package/build/esm/src/utils/referrals/api.js +36 -0
- package/build/esm/src/utils/swap/swapRouting.js +4 -0
- package/build/esm/src/utils/swap/swapStats.js +7 -2
- package/build/esm/src/utils/trade/__tests__/gmsolTradeMath.spec.js +1010 -0
- package/build/esm/src/utils/trade/decrease.js +266 -56
- package/build/esm/src/utils/trade/decreaseMarginCheck.js +23 -4
- package/build/esm/src/utils/trade/increase.js +86 -28
- package/build/esm/src/utils/trade/increaseMarginCheck.js +53 -11
- package/build/esm/src/utils/trade/twapIncreaseMarginCheck.js +8 -3
- package/build/tsconfig.tsbuildinfo +1 -1
- package/build/types/src/clients/v2/index.d.ts +21 -12
- package/build/types/src/clients/v2/solana.spec.d.ts +1 -0
- package/build/types/src/utils/fees/index.d.ts +1 -1
- package/build/types/src/utils/fees/priceImpact.d.ts +7 -0
- package/build/types/src/utils/gmsol/constants.d.ts +5 -0
- package/build/types/src/utils/gmsol/index.d.ts +35 -0
- package/build/types/src/utils/gmsol/numbers.d.ts +1 -0
- package/build/types/src/utils/gmsol/types.d.ts +9 -0
- package/build/types/src/utils/http/http.d.ts +2 -5
- package/build/types/src/utils/http/httpFallback.d.ts +2 -5
- package/build/types/src/utils/http/solana.d.ts +4 -0
- package/build/types/src/utils/http/types.d.ts +17 -4
- package/build/types/src/utils/http/validation.d.ts +8 -0
- package/build/types/src/utils/http/validation.spec.d.ts +1 -0
- package/build/types/src/utils/markets/hashKeys.d.ts +1 -1
- package/build/types/src/utils/markets/types.d.ts +3 -2
- package/build/types/src/utils/markets/utils.d.ts +6 -2
- package/build/types/src/utils/orders/api.d.ts +2 -2
- package/build/types/src/utils/positions/__tests__/liquidationPrice.spec.d.ts +1 -0
- package/build/types/src/utils/positions/api.d.ts +2 -2
- package/build/types/src/utils/positions/types.d.ts +1 -0
- package/build/types/src/utils/positions/utils.d.ts +6 -1
- package/build/types/src/utils/prices/types.d.ts +16 -0
- package/build/types/src/utils/prices/utils.d.ts +3 -11
- package/build/types/src/utils/referrals/api.d.ts +8 -0
- package/build/types/src/utils/referrals/types.d.ts +5 -0
- package/build/types/src/utils/rpc/createViemRpc.d.ts +25 -3
- package/build/types/src/utils/trade/__tests__/gmsolTradeMath.spec.d.ts +1 -0
- package/build/types/src/utils/trade/decrease.d.ts +5 -0
- package/build/types/src/utils/trade/decreaseMarginCheck.d.ts +2 -0
- package/build/types/src/utils/trade/increase.d.ts +2 -0
- package/build/types/src/utils/trade/increaseMarginCheck.d.ts +2 -0
- package/build/types/src/utils/trade/twapIncreaseMarginCheck.d.ts +1 -0
- package/build/types/src/utils/trade/types.d.ts +6 -0
- package/package.json +10 -1
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { GMSOL_PRECISION } from "./constants";
|
|
2
|
+
const MAX_COEFFICIENT = (1n << 96n) - 1n;
|
|
3
|
+
const MAX_U64 = (1n << 64n) - 1n;
|
|
4
|
+
const MAX_I64 = (1n << 63n) - 1n;
|
|
5
|
+
const UNIT = 1000000000n;
|
|
6
|
+
const INPUT_SCALE = GMSOL_PRECISION / UNIT;
|
|
7
|
+
const ONE = { coefficient: 1n, scale: 0 };
|
|
8
|
+
const E = { coefficient: 27182818284590452353602874714n, scale: 28 };
|
|
9
|
+
const INVERSE_E = { coefficient: 3678794411714423215955237702n, scale: 28 };
|
|
10
|
+
function roundEven(numerator, denominator) {
|
|
11
|
+
const quotient = numerator / denominator;
|
|
12
|
+
const twiceRemainder = (numerator % denominator) * 2n;
|
|
13
|
+
return (quotient + (twiceRemainder > denominator || (twiceRemainder === denominator && quotient % 2n !== 0n) ? 1n : 0n));
|
|
14
|
+
}
|
|
15
|
+
function fit(coefficient, scale) {
|
|
16
|
+
const sign = coefficient < 0n ? -1n : 1n;
|
|
17
|
+
let magnitude = coefficient * sign;
|
|
18
|
+
let removed = Math.max(0, scale - 28);
|
|
19
|
+
while (magnitude / 10n ** BigInt(removed) > MAX_COEFFICIENT) {
|
|
20
|
+
removed++;
|
|
21
|
+
}
|
|
22
|
+
if (removed > scale) {
|
|
23
|
+
throw new Error("Solana decimal overflow");
|
|
24
|
+
}
|
|
25
|
+
magnitude = roundEven(magnitude, 10n ** BigInt(removed));
|
|
26
|
+
scale -= removed;
|
|
27
|
+
if (magnitude > MAX_COEFFICIENT) {
|
|
28
|
+
if (scale === 0)
|
|
29
|
+
throw new Error("Solana decimal overflow");
|
|
30
|
+
magnitude = roundEven(magnitude, 10n);
|
|
31
|
+
scale--;
|
|
32
|
+
}
|
|
33
|
+
return { coefficient: magnitude * sign, scale };
|
|
34
|
+
}
|
|
35
|
+
function add(left, right) {
|
|
36
|
+
if (left.coefficient === 0n)
|
|
37
|
+
return right;
|
|
38
|
+
if (right.coefficient === 0n)
|
|
39
|
+
return left;
|
|
40
|
+
const scale = Math.max(left.scale, right.scale);
|
|
41
|
+
return fit(left.coefficient * 10n ** BigInt(scale - left.scale) + right.coefficient * 10n ** BigInt(scale - right.scale), scale);
|
|
42
|
+
}
|
|
43
|
+
function subtract(left, right) {
|
|
44
|
+
return add(left, { coefficient: -right.coefficient, scale: right.scale });
|
|
45
|
+
}
|
|
46
|
+
function multiply(left, right) {
|
|
47
|
+
return fit(left.coefficient * right.coefficient, left.scale + right.scale);
|
|
48
|
+
}
|
|
49
|
+
function compare(left, right) {
|
|
50
|
+
const scale = Math.max(left.scale, right.scale);
|
|
51
|
+
const difference = left.coefficient * 10n ** BigInt(scale - left.scale) - right.coefficient * 10n ** BigInt(scale - right.scale);
|
|
52
|
+
return difference < 0n ? -1 : difference > 0n ? 1 : 0;
|
|
53
|
+
}
|
|
54
|
+
function divideByInteger(value, divisor) {
|
|
55
|
+
let scale = value.scale;
|
|
56
|
+
let coefficient = value.coefficient / divisor;
|
|
57
|
+
let remainder = value.coefficient % divisor;
|
|
58
|
+
const fractional = remainder !== 0n;
|
|
59
|
+
while (remainder !== 0n && scale < 28 && coefficient * 10n <= MAX_COEFFICIENT) {
|
|
60
|
+
let digits = Math.min(9, 28 - scale);
|
|
61
|
+
while (coefficient * 10n ** BigInt(digits) > MAX_COEFFICIENT)
|
|
62
|
+
digits--;
|
|
63
|
+
const multiplier = 10n ** BigInt(digits);
|
|
64
|
+
coefficient = coefficient * multiplier + (remainder * multiplier) / divisor;
|
|
65
|
+
remainder = (remainder * multiplier) % divisor;
|
|
66
|
+
scale += digits;
|
|
67
|
+
if (coefficient > MAX_COEFFICIENT) {
|
|
68
|
+
const lastDigit = coefficient % 10n;
|
|
69
|
+
coefficient /= 10n;
|
|
70
|
+
if (lastDigit > 5n || (lastDigit === 5n && (remainder !== 0n || coefficient % 2n !== 0n)))
|
|
71
|
+
coefficient++;
|
|
72
|
+
scale--;
|
|
73
|
+
remainder = 0n;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (remainder !== 0n) {
|
|
77
|
+
coefficient = roundEven(coefficient * divisor + remainder, divisor);
|
|
78
|
+
}
|
|
79
|
+
const result = fit(coefficient, scale);
|
|
80
|
+
if (fractional) {
|
|
81
|
+
while (result.scale >= 8 && (result.coefficient & 0xffffffffn) === 0n && result.coefficient % 100000000n === 0n) {
|
|
82
|
+
result.coefficient /= 100000000n;
|
|
83
|
+
result.scale -= 8;
|
|
84
|
+
}
|
|
85
|
+
for (const digits of [4, 2, 1]) {
|
|
86
|
+
const divisor = 10n ** BigInt(digits);
|
|
87
|
+
if (result.scale >= digits && result.coefficient % divisor === 0n) {
|
|
88
|
+
result.coefficient /= divisor;
|
|
89
|
+
result.scale -= digits;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return result;
|
|
94
|
+
}
|
|
95
|
+
function logarithm(value) {
|
|
96
|
+
let x = value;
|
|
97
|
+
let count = 0n;
|
|
98
|
+
while (compare(x, ONE) >= 0) {
|
|
99
|
+
x = multiply(x, INVERSE_E);
|
|
100
|
+
count++;
|
|
101
|
+
}
|
|
102
|
+
while (compare(x, INVERSE_E) <= 0) {
|
|
103
|
+
x = multiply(x, E);
|
|
104
|
+
count--;
|
|
105
|
+
}
|
|
106
|
+
x = subtract(ONE, x);
|
|
107
|
+
let result = { coefficient: 0n, scale: 0 };
|
|
108
|
+
let term = ONE;
|
|
109
|
+
for (let iteration = 1n; iteration <= 100n; iteration++) {
|
|
110
|
+
term = multiply(term, x);
|
|
111
|
+
const next = add(result, divideByInteger(term, iteration));
|
|
112
|
+
if (compare(next, result) === 0)
|
|
113
|
+
break;
|
|
114
|
+
result = next;
|
|
115
|
+
}
|
|
116
|
+
return subtract({ coefficient: count, scale: 0 }, result);
|
|
117
|
+
}
|
|
118
|
+
function exponential(value) {
|
|
119
|
+
let term = value;
|
|
120
|
+
let result = add(value, ONE);
|
|
121
|
+
let factorial = 1n;
|
|
122
|
+
for (let iteration = 2n; iteration <= 27n; iteration++) {
|
|
123
|
+
factorial *= iteration;
|
|
124
|
+
term = multiply(value, term);
|
|
125
|
+
const next = add(result, divideByInteger(term, factorial));
|
|
126
|
+
const difference = subtract(next, result);
|
|
127
|
+
result = next;
|
|
128
|
+
if (compare(difference, { coefficient: 2n, scale: 7 }) <= 0)
|
|
129
|
+
break;
|
|
130
|
+
}
|
|
131
|
+
return result;
|
|
132
|
+
}
|
|
133
|
+
export function getGmsolFractionalPower(base20, exponent20) {
|
|
134
|
+
const base = base20 / INPUT_SCALE;
|
|
135
|
+
const exponent = exponent20 / INPUT_SCALE;
|
|
136
|
+
if (base < UNIT || base > MAX_U64 || exponent < 0n || exponent > MAX_U64) {
|
|
137
|
+
throw new Error("Solana fractional power input exceeds native range");
|
|
138
|
+
}
|
|
139
|
+
let result;
|
|
140
|
+
if (exponent % UNIT === 0n) {
|
|
141
|
+
result = UNIT;
|
|
142
|
+
if (base !== UNIT) {
|
|
143
|
+
if (exponent > 128n * UNIT)
|
|
144
|
+
throw new Error("Solana impact exponent exceeds calculation limit");
|
|
145
|
+
for (let remaining = exponent; remaining > 0n; remaining -= UNIT) {
|
|
146
|
+
result = (result * base) / UNIT;
|
|
147
|
+
if (result > MAX_U64)
|
|
148
|
+
throw new Error("Solana fractional power exceeds native range");
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
if (base > MAX_I64 || exponent > MAX_I64) {
|
|
154
|
+
throw new Error("Solana decimal input exceeds native range");
|
|
155
|
+
}
|
|
156
|
+
const power = base === UNIT
|
|
157
|
+
? ONE
|
|
158
|
+
: exponential(multiply(logarithm({ coefficient: base, scale: 9 }), { coefficient: exponent, scale: 9 }));
|
|
159
|
+
if (power.scale > 9) {
|
|
160
|
+
const divisor = 10n ** BigInt(power.scale - 9);
|
|
161
|
+
result = power.coefficient / divisor + ((power.coefficient % divisor) * 2n >= divisor ? 1n : 0n);
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
result = power.coefficient;
|
|
165
|
+
for (let scale = power.scale; scale < 9 && result * 10n <= MAX_COEFFICIENT; scale++)
|
|
166
|
+
result *= 10n;
|
|
167
|
+
}
|
|
168
|
+
if (result < 0n || result > MAX_U64)
|
|
169
|
+
throw new Error("Solana fractional power exceeds native range");
|
|
170
|
+
}
|
|
171
|
+
return result * INPUT_SCALE;
|
|
172
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -52,10 +52,9 @@ export class HttpClient {
|
|
|
52
52
|
throwHttpError(response.status, response.statusText, errorBody);
|
|
53
53
|
}
|
|
54
54
|
const json = await response.json();
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
return json;
|
|
55
|
+
const result = opts?.transform ? opts.transform(json) : json;
|
|
56
|
+
opts?.onResponse?.({ headers: response.headers });
|
|
57
|
+
return result;
|
|
59
58
|
}
|
|
60
59
|
finally {
|
|
61
60
|
clearTimeout(timeoutId);
|
|
@@ -20,7 +20,17 @@ export class HttpClientWithFallback {
|
|
|
20
20
|
return this.clients[this.primaryIndex].url;
|
|
21
21
|
}
|
|
22
22
|
async fetchJson(path, opts) {
|
|
23
|
-
|
|
23
|
+
let metadata;
|
|
24
|
+
const result = await this.withFallback((client) => client.fetchJson(path, {
|
|
25
|
+
...opts,
|
|
26
|
+
onResponse: (response) => {
|
|
27
|
+
metadata = response;
|
|
28
|
+
},
|
|
29
|
+
}));
|
|
30
|
+
if (metadata) {
|
|
31
|
+
opts?.onResponse?.(metadata);
|
|
32
|
+
}
|
|
33
|
+
return result;
|
|
24
34
|
}
|
|
25
35
|
async postJson(path, body, opts) {
|
|
26
36
|
return (await this.postJsonWith(path, body, opts)).result;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export function parseSolanaSlotHeader(value) {
|
|
2
|
+
if (value === null || value.trim() === "") {
|
|
3
|
+
return undefined;
|
|
4
|
+
}
|
|
5
|
+
const slot = Number(value);
|
|
6
|
+
return Number.isSafeInteger(slot) && slot >= 0 ? slot : undefined;
|
|
7
|
+
}
|
|
8
|
+
export function getSolanaResponseHandler(onResponse) {
|
|
9
|
+
return onResponse
|
|
10
|
+
? ({ headers }) => onResponse({ slot: parseSolanaSlotHeader(headers.get("x-solana-slot")) })
|
|
11
|
+
: undefined;
|
|
12
|
+
}
|
|
@@ -1,3 +1,21 @@
|
|
|
1
|
+
import { getString } from "../objects";
|
|
2
|
+
export function readApiString({ record, name, endpoint }) {
|
|
3
|
+
const value = getString(record[name]);
|
|
4
|
+
if (value === undefined) {
|
|
5
|
+
throw new Error(`${endpoint}: expected string field "${name}"`);
|
|
6
|
+
}
|
|
7
|
+
return value;
|
|
8
|
+
}
|
|
9
|
+
export function readApiUnsignedBigInt({ record, name, endpoint }) {
|
|
10
|
+
const value = record[name];
|
|
11
|
+
if (typeof value === "string" && /^\d+$/.test(value)) {
|
|
12
|
+
return BigInt(value);
|
|
13
|
+
}
|
|
14
|
+
if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) {
|
|
15
|
+
return BigInt(value);
|
|
16
|
+
}
|
|
17
|
+
throw new Error(`${endpoint}: expected bigint field "${name}"`);
|
|
18
|
+
}
|
|
1
19
|
export function assertApiRecords(value, endpoint) {
|
|
2
20
|
if (!Array.isArray(value)) {
|
|
3
21
|
throw new Error(`Invalid ${endpoint} response: expected an array`);
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { expect, it } from "vitest";
|
|
2
|
+
import { readApiUnsignedBigInt } from "./validation";
|
|
3
|
+
it("reads unsigned API amounts without losing precision or accepting coercible values", () => {
|
|
4
|
+
const name = "amount";
|
|
5
|
+
const endpoint = "/v1/example";
|
|
6
|
+
const largeAmount = 1n << 256n;
|
|
7
|
+
const accepted = [
|
|
8
|
+
["0", 0n],
|
|
9
|
+
["000123", 123n],
|
|
10
|
+
[largeAmount.toString(), largeAmount],
|
|
11
|
+
[0, 0n],
|
|
12
|
+
[-0, 0n],
|
|
13
|
+
[Number.MAX_SAFE_INTEGER, BigInt(Number.MAX_SAFE_INTEGER)],
|
|
14
|
+
];
|
|
15
|
+
for (const [value, expected] of accepted) {
|
|
16
|
+
expect(readApiUnsignedBigInt({ record: { amount: value }, name, endpoint })).toBe(expected);
|
|
17
|
+
}
|
|
18
|
+
for (const value of [
|
|
19
|
+
undefined,
|
|
20
|
+
null,
|
|
21
|
+
true,
|
|
22
|
+
false,
|
|
23
|
+
"",
|
|
24
|
+
" ",
|
|
25
|
+
" 1",
|
|
26
|
+
"1 ",
|
|
27
|
+
"+1",
|
|
28
|
+
"-1",
|
|
29
|
+
"1.0",
|
|
30
|
+
"1e3",
|
|
31
|
+
"0x10",
|
|
32
|
+
-1,
|
|
33
|
+
1.5,
|
|
34
|
+
NaN,
|
|
35
|
+
Infinity,
|
|
36
|
+
Number.MAX_SAFE_INTEGER + 1,
|
|
37
|
+
0n,
|
|
38
|
+
[],
|
|
39
|
+
{},
|
|
40
|
+
]) {
|
|
41
|
+
expect(() => readApiUnsignedBigInt({ record: { amount: value }, name, endpoint })).toThrow('/v1/example: expected bigint field "amount"');
|
|
42
|
+
}
|
|
43
|
+
});
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { ARBITRUM, AVALANCHE } from "../../../configs/chains";
|
|
3
|
+
import { getNativeToken, getWrappedToken } from "../../../configs/tokens";
|
|
2
4
|
import { fetchApiMarketsConfig, fetchApiMarketsInfo, fetchApiMarketsValues } from "../api";
|
|
5
|
+
import { composeFullMarketsInfoData } from "../utils";
|
|
3
6
|
const MARKET_ADDRESS = "0x1111111111111111111111111111111111111111";
|
|
4
7
|
const VIRTUAL_INDEX_TOKEN_ID = "0x2222222222222222222222222222222222222222222222222222222222222222";
|
|
5
8
|
const CONFIG_FIELD_CASES = [
|
|
@@ -100,6 +103,56 @@ describe("market API validation", () => {
|
|
|
100
103
|
});
|
|
101
104
|
});
|
|
102
105
|
describe("fetchApiMarketsConfig", () => {
|
|
106
|
+
it("preserves per-market minimums without requiring them from EVM FESOL-52", async () => {
|
|
107
|
+
for (const field of ["minCollateralUsd", "minPositionSizeUsd"]) {
|
|
108
|
+
for (const value of ["0", "50000000000000000000000000000000", 0, 5]) {
|
|
109
|
+
const [market] = await fetchApiMarketsConfig({ api: createApi([createMarketConfig({ [field]: value })]) });
|
|
110
|
+
expect(market[field]).toBe(BigInt(value));
|
|
111
|
+
}
|
|
112
|
+
const [evmMarket] = await fetchApiMarketsConfig({ api: createApi([createMarketConfig()]) });
|
|
113
|
+
expect(evmMarket[field]).toBeUndefined();
|
|
114
|
+
for (const value of [null, true, -1, "-1", "1.5", "invalid"]) {
|
|
115
|
+
await expect(fetchApiMarketsConfig({ api: createApi([createMarketConfig({ [field]: value })]) })).rejects.toThrow(field);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
it("keeps Solana mints and existing EVM native-token hydration FESOL-52", () => {
|
|
120
|
+
const solanaToken = {
|
|
121
|
+
address: "So11111111111111111111111111111111111111112",
|
|
122
|
+
name: "Wrapped SOL",
|
|
123
|
+
symbol: "WSOL",
|
|
124
|
+
decimals: 9,
|
|
125
|
+
};
|
|
126
|
+
for (const chainId of [ARBITRUM, AVALANCHE, undefined]) {
|
|
127
|
+
const wrappedToken = chainId === undefined ? solanaToken : getWrappedToken(chainId);
|
|
128
|
+
const indexToken = chainId === undefined ? solanaToken : getNativeToken(chainId);
|
|
129
|
+
const prices = { minPrice: 1n, maxPrice: 1n };
|
|
130
|
+
const tokensData = {
|
|
131
|
+
[wrappedToken.address]: { ...wrappedToken, prices },
|
|
132
|
+
[indexToken.address]: { ...indexToken, prices },
|
|
133
|
+
};
|
|
134
|
+
const rawMarket = {
|
|
135
|
+
marketTokenAddress: MARKET_ADDRESS,
|
|
136
|
+
indexTokenAddress: wrappedToken.address,
|
|
137
|
+
longTokenAddress: wrappedToken.address,
|
|
138
|
+
shortTokenAddress: wrappedToken.address,
|
|
139
|
+
minCollateralUsd: 5n,
|
|
140
|
+
minPositionSizeUsd: 0n,
|
|
141
|
+
};
|
|
142
|
+
const result = composeFullMarketsInfoData({
|
|
143
|
+
chainId,
|
|
144
|
+
marketsAddresses: [MARKET_ADDRESS],
|
|
145
|
+
rawMarketsInfoData: { [MARKET_ADDRESS]: rawMarket },
|
|
146
|
+
tokensData,
|
|
147
|
+
});
|
|
148
|
+
expect(result[MARKET_ADDRESS]).toMatchObject({
|
|
149
|
+
...rawMarket,
|
|
150
|
+
indexToken: tokensData[indexToken.address],
|
|
151
|
+
longToken: tokensData[wrappedToken.address],
|
|
152
|
+
shortToken: tokensData[wrappedToken.address],
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
});
|
|
103
156
|
it("deserializes required v2.2c bigint fields", async () => {
|
|
104
157
|
const result = await fetchApiMarketsConfig({
|
|
105
158
|
api: createApi([createMarketConfig()]),
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { assertApiFields, assertApiRecords } from "../http/validation";
|
|
1
|
+
import { assertApiFields, assertApiRecords, readApiUnsignedBigInt } from "../http/validation";
|
|
2
2
|
import { deserializeBigIntsInObject, isUint256, parseUint256DecimalString } from "../numbers";
|
|
3
3
|
import { getString, isRecord } from "../objects";
|
|
4
4
|
const MARKET_CONFIG_V22C_FIELDS = [
|
|
@@ -26,6 +26,11 @@ function parseApiRecords(raw, endpoint, fields) {
|
|
|
26
26
|
return raw.map((record, index) => {
|
|
27
27
|
const parsed = deserializeBigIntsInObject(record, { handleInts: true });
|
|
28
28
|
assertApiFields(parsed, fields, endpoint, index);
|
|
29
|
+
for (const name of ["minCollateralUsd", "minPositionSizeUsd"]) {
|
|
30
|
+
if (name in record) {
|
|
31
|
+
parsed[name] = readApiUnsignedBigInt({ record, name, endpoint });
|
|
32
|
+
}
|
|
33
|
+
}
|
|
29
34
|
return parsed;
|
|
30
35
|
});
|
|
31
36
|
}
|
|
@@ -4,6 +4,7 @@ import { UI_MAX_LEVERAGE_BY_MARKET } from "../../configs/markets";
|
|
|
4
4
|
import { convertTokenAddress, getTokenVisualMultiplier, NATIVE_TOKEN_ADDRESS } from "../../configs/tokens";
|
|
5
5
|
import { bigMath } from "../bigmath";
|
|
6
6
|
import { applySwapImpactWithCap, getBorrowingFactorPerPeriod, getFundingFactorPerPeriod } from "../fees";
|
|
7
|
+
import { getGmsolUsdAmount } from "../gmsol";
|
|
7
8
|
import { applyFactor, expandDecimals, PRECISION } from "../numbers";
|
|
8
9
|
import { getByKey } from "../objects";
|
|
9
10
|
import { periodToSeconds } from "../time";
|
|
@@ -81,7 +82,8 @@ export function getCappedPoolPnl(p) {
|
|
|
81
82
|
return poolPnl;
|
|
82
83
|
}
|
|
83
84
|
const maxPnlFactor = isLong ? marketInfo.maxPnlFactorForTradersLong : marketInfo.maxPnlFactorForTradersShort;
|
|
84
|
-
const
|
|
85
|
+
const maxPnlUsd = applyFactor(poolUsd, maxPnlFactor);
|
|
86
|
+
const maxPnl = marketInfo.tradeMath === "gmsol" ? getGmsolUsdAmount(maxPnlUsd) : maxPnlUsd;
|
|
85
87
|
return poolPnl > maxPnl ? maxPnl : poolPnl;
|
|
86
88
|
}
|
|
87
89
|
/**
|
|
@@ -197,7 +199,9 @@ export function getMarketPnl(marketInfo, isLong, forMaxPoolValue) {
|
|
|
197
199
|
const maximize = !forMaxPoolValue;
|
|
198
200
|
const openInterestUsd = getOpenInterestUsd(marketInfo, isLong);
|
|
199
201
|
const openInterestInTokens = getOpenInterestInTokens(marketInfo, isLong);
|
|
200
|
-
if (
|
|
202
|
+
if (marketInfo.tradeMath === "gmsol"
|
|
203
|
+
? openInterestUsd === 0n && openInterestInTokens === 0n
|
|
204
|
+
: openInterestUsd === 0n || openInterestInTokens === 0n) {
|
|
201
205
|
return 0n;
|
|
202
206
|
}
|
|
203
207
|
const price = getPriceForPnl(marketInfo.indexToken.prices, isLong, maximize);
|
|
@@ -228,7 +232,9 @@ function getMarketPnlByCollateralToken(marketInfo, isLong, isLongCollateral, for
|
|
|
228
232
|
if (openInterestUsd === undefined || openInterestInTokens === undefined) {
|
|
229
233
|
return undefined;
|
|
230
234
|
}
|
|
231
|
-
if (
|
|
235
|
+
if (marketInfo.tradeMath === "gmsol"
|
|
236
|
+
? openInterestUsd === 0n && openInterestInTokens === 0n
|
|
237
|
+
: openInterestUsd === 0n || openInterestInTokens === 0n) {
|
|
232
238
|
return 0n;
|
|
233
239
|
}
|
|
234
240
|
const price = getPriceForPnl(marketInfo.indexToken.prices, isLong, maximize);
|
|
@@ -298,7 +304,7 @@ export function getMarketInfoWithOpenInterestDelta({ marketInfo, collateralToken
|
|
|
298
304
|
? marketInfo.virtualInventoryForPositionsInTokens !== 0n
|
|
299
305
|
: marketInfo.virtualInventoryForPositions !== 0n;
|
|
300
306
|
if (hasVirtualInventory) {
|
|
301
|
-
if (marketInfo.useOpenInterestInTokensForBalance) {
|
|
307
|
+
if (marketInfo.tradeMath !== "gmsol" && marketInfo.useOpenInterestInTokensForBalance) {
|
|
302
308
|
next.virtualInventoryForPositionsInTokens =
|
|
303
309
|
marketInfo.virtualInventoryForPositionsInTokens + (isLong ? -sizeDeltaInTokens : sizeDeltaInTokens);
|
|
304
310
|
}
|
|
@@ -353,7 +359,7 @@ export function getMarketInfoWithSwapDelta(marketInfo, swapStep) {
|
|
|
353
359
|
return next;
|
|
354
360
|
}
|
|
355
361
|
export function getOpenInterestForBalance(marketInfo, isLong) {
|
|
356
|
-
if (marketInfo.useOpenInterestInTokensForBalance) {
|
|
362
|
+
if (marketInfo.tradeMath !== "gmsol" && marketInfo.useOpenInterestInTokensForBalance) {
|
|
357
363
|
const interestInTokens = isLong ? marketInfo.longInterestInTokens : marketInfo.shortInterestInTokens;
|
|
358
364
|
const indexTokenPrice = getMidPrice(marketInfo.indexToken.prices);
|
|
359
365
|
return convertToUsd(interestInTokens, marketInfo.indexToken.decimals, indexTokenPrice);
|
|
@@ -484,7 +490,10 @@ export function mergeMarketsConfigValues(configs, values) {
|
|
|
484
490
|
export function hydrateMarketInfo({ chainId, rawMarketInfo, tokensData, claimableFundingData, }) {
|
|
485
491
|
const longToken = getByKey(tokensData, rawMarketInfo.longTokenAddress);
|
|
486
492
|
const shortToken = getByKey(tokensData, rawMarketInfo.shortTokenAddress);
|
|
487
|
-
const
|
|
493
|
+
const indexTokenAddress = chainId === undefined
|
|
494
|
+
? rawMarketInfo.indexTokenAddress
|
|
495
|
+
: convertTokenAddress(chainId, rawMarketInfo.indexTokenAddress, "native");
|
|
496
|
+
const indexToken = getByKey(tokensData, indexTokenAddress);
|
|
488
497
|
if (!longToken || !shortToken || !indexToken) {
|
|
489
498
|
return undefined;
|
|
490
499
|
}
|
|
@@ -515,6 +524,12 @@ export function composeFullMarketsInfoData({ chainId, marketsAddresses, rawMarke
|
|
|
515
524
|
}
|
|
516
525
|
return data;
|
|
517
526
|
}
|
|
527
|
+
export function getMarketPositionLimits(market, defaults) {
|
|
528
|
+
return {
|
|
529
|
+
minCollateralUsd: market?.minCollateralUsd ?? defaults?.minCollateralUsd,
|
|
530
|
+
minPositionSizeUsd: market?.minPositionSizeUsd ?? defaults?.minPositionSizeUsd,
|
|
531
|
+
};
|
|
532
|
+
}
|
|
518
533
|
export function getMarketWithTiers(marketInfo, constants) {
|
|
519
534
|
const maxLeverage = getMaxLeverageByMinCollateralFactor(marketInfo.minCollateralFactor, marketInfo.marketTokenAddress);
|
|
520
535
|
const maxLeverageBigint = BigInt(maxLeverage);
|
|
@@ -535,8 +550,8 @@ export function getMarketWithTiers(marketInfo, constants) {
|
|
|
535
550
|
listingDate: undefined,
|
|
536
551
|
isSpotOnly: marketInfo.isSpotOnly,
|
|
537
552
|
leverageTiers,
|
|
538
|
-
minPositionSizeUsd: constants.minPositionSizeUsd,
|
|
539
|
-
minCollateralUsd: constants.minCollateralUsd,
|
|
553
|
+
minPositionSizeUsd: marketInfo.minPositionSizeUsd ?? constants.minPositionSizeUsd,
|
|
554
|
+
minCollateralUsd: marketInfo.minCollateralUsd ?? constants.minCollateralUsd,
|
|
540
555
|
};
|
|
541
556
|
}
|
|
542
557
|
export function getMarketAddressByName(marketsInfoData, name) {
|
|
@@ -1,9 +1,12 @@
|
|
|
1
|
+
import { getSolanaResponseHandler } from "../http/solana";
|
|
1
2
|
import { deserializeBigIntsInObject } from "../numbers";
|
|
2
3
|
export async function fetchApiOrders(ctx, params) {
|
|
3
4
|
const orders = await ctx.api.fetchJson("/v1/orders", {
|
|
4
5
|
query: {
|
|
5
6
|
address: params.address,
|
|
7
|
+
minContextSlot: params.minContextSlot,
|
|
6
8
|
},
|
|
9
|
+
onResponse: getSolanaResponseHandler(params.onResponse),
|
|
7
10
|
});
|
|
8
11
|
return orders.map((o) => deserializeBigIntsInObject(o, { handleInts: true }));
|
|
9
12
|
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { parseUnits } from "viem";
|
|
2
|
+
import { describe, expect, it } from "vitest";
|
|
3
|
+
import { mockMarginCheckMarketInfo, mockTokensData } from "../../../test/mock";
|
|
4
|
+
import { PRECISION } from "../../numbers";
|
|
5
|
+
import { getLiquidationPrice } from "..";
|
|
6
|
+
describe("gmsol liquidation price", () => {
|
|
7
|
+
it("solves index collateral funding at the liquidation price without changing EVM math FESOL-57", () => {
|
|
8
|
+
// Rust 8af1e70c: $1,000 size / 10 tokens, $5 floor, $2 borrowing and $0.60 close fee.
|
|
9
|
+
for (const [isLong, collateral, funding, expected] of [
|
|
10
|
+
[true, 10n, 1n, parseUnits("53.03157894736842", 30)],
|
|
11
|
+
[false, 10n, 1n, parseUnits("992.4", 30)],
|
|
12
|
+
[true, 10n, 0n, parseUnits("50.38", 30)],
|
|
13
|
+
[false, 10n, 0n, undefined],
|
|
14
|
+
[false, 11n, 1n, undefined],
|
|
15
|
+
[false, 12n, 1n, undefined],
|
|
16
|
+
[true, 10n, 20n, undefined],
|
|
17
|
+
]) {
|
|
18
|
+
for (const price of [100n, 120n]) {
|
|
19
|
+
const marketInfo = {
|
|
20
|
+
...mockMarginCheckMarketInfo(mockTokensData({
|
|
21
|
+
BTC: { decimals: 6, prices: { minPrice: price * PRECISION, maxPrice: price * PRECISION } },
|
|
22
|
+
}), {
|
|
23
|
+
longInterestUsd: 20000n * PRECISION,
|
|
24
|
+
shortInterestUsd: 10000n * PRECISION,
|
|
25
|
+
positionFeeFactorForBalanceWasImproved: 6n * 10n ** 26n,
|
|
26
|
+
positionFeeFactorForBalanceWasNotImproved: 6n * 10n ** 26n,
|
|
27
|
+
}),
|
|
28
|
+
tradeMath: "gmsol",
|
|
29
|
+
minCollateralUsd: 5n * PRECISION,
|
|
30
|
+
};
|
|
31
|
+
const params = {
|
|
32
|
+
marketInfo,
|
|
33
|
+
collateralToken: marketInfo.indexToken,
|
|
34
|
+
collateralAmount: collateral * 1000000n,
|
|
35
|
+
collateralUsd: collateral * price * PRECISION,
|
|
36
|
+
sizeInUsd: 1000n * PRECISION,
|
|
37
|
+
sizeInTokens: 10000000n,
|
|
38
|
+
pendingFundingFeesUsd: funding * price * PRECISION,
|
|
39
|
+
pendingBorrowingFeesUsd: 2n * PRECISION,
|
|
40
|
+
pendingImpactAmount: 0n,
|
|
41
|
+
minCollateralUsd: PRECISION,
|
|
42
|
+
isLong,
|
|
43
|
+
userReferralInfo: undefined,
|
|
44
|
+
};
|
|
45
|
+
for (const fundingFeeAmount of [undefined, funding * 1000000n]) {
|
|
46
|
+
const actual = getLiquidationPrice({ ...params, fundingFeeAmount });
|
|
47
|
+
if (expected === undefined)
|
|
48
|
+
expect(actual).toBeUndefined();
|
|
49
|
+
else {
|
|
50
|
+
expect(actual).toBeDefined();
|
|
51
|
+
// One Rust unit-price step for a token with six decimals.
|
|
52
|
+
expect(actual - expected).toBeGreaterThanOrEqual(0n);
|
|
53
|
+
expect(actual - expected).toBeLessThan(10n ** 16n);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
if (isLong && collateral === 10n && funding === 1n) {
|
|
57
|
+
expect(getLiquidationPrice({ ...params, marketInfo: { ...marketInfo, tradeMath: undefined } })).toBe(parseUnits(price === 100n ? "55.38" : "56.38", 30));
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
});
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { getSolanaResponseHandler } from "../http/solana";
|
|
1
2
|
import { assertApiFields, assertApiRecords } from "../http/validation";
|
|
2
3
|
import { deserializeBigIntsInObject } from "../numbers";
|
|
3
4
|
export async function fetchApiPositionsInfo(ctx, params) {
|
|
@@ -5,7 +6,9 @@ export async function fetchApiPositionsInfo(ctx, params) {
|
|
|
5
6
|
query: {
|
|
6
7
|
address: params.address,
|
|
7
8
|
includeRelatedOrders: params.includeRelatedOrders || undefined,
|
|
9
|
+
minContextSlot: params.minContextSlot,
|
|
8
10
|
},
|
|
11
|
+
onResponse: getSolanaResponseHandler(params.onResponse),
|
|
9
12
|
});
|
|
10
13
|
assertApiRecords(positions, "/v1/positions");
|
|
11
14
|
return positions.map((position, index) => {
|