@gmx-io/sdk 2.9.0 → 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/__tests__/subaccount.spec.js +2 -2
- package/build/cjs/src/clients/v2/__tests__/testUtil.js +8 -8
- 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/gmxAccountApi/api.js +4 -4
- package/build/cjs/src/utils/http/__tests__/chainPins.spec.js +3 -3
- 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/orderTransactions/api.js +6 -6
- 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/subaccount/api.js +2 -2
- 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/__tests__/subaccount.spec.js +2 -2
- package/build/esm/src/clients/v2/__tests__/testUtil.js +8 -8
- 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/gmxAccountApi/api.js +4 -4
- package/build/esm/src/utils/http/__tests__/chainPins.spec.js +3 -3
- 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/orderTransactions/api.js +6 -6
- 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/subaccount/api.js +2 -2
- 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,160 @@
|
|
|
1
|
+
import fetch, { Response } from "cross-fetch";
|
|
2
|
+
import { decodeFunctionData } from "viem";
|
|
3
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
4
|
+
import ERC20ABI from "../../abis/Token";
|
|
5
|
+
import { ARBITRUM, AVALANCHE, SOLANA_NETWORK_ID } from "../../configs/chains";
|
|
6
|
+
import { getContract } from "../../configs/contracts";
|
|
7
|
+
import { HttpClientWithFallback } from "../../utils/http/httpFallback";
|
|
8
|
+
import { parseFeeDiscount } from "../../utils/referrals/api";
|
|
9
|
+
import { GmxApiSdk } from "./index";
|
|
10
|
+
vi.mock("cross-fetch", async (importOriginal) => ({
|
|
11
|
+
...(await importOriginal()),
|
|
12
|
+
default: vi.fn(),
|
|
13
|
+
}));
|
|
14
|
+
const address = "So11111111111111111111111111111111111111112";
|
|
15
|
+
const amount = "1234567890123456789012345678901";
|
|
16
|
+
const fee = (overrides = {}) => ({
|
|
17
|
+
userReferralCode: "RefErRaL",
|
|
18
|
+
userReferralCodeString: "MyCode",
|
|
19
|
+
referralCodeForTxn: "TxCoDe",
|
|
20
|
+
affiliate: address,
|
|
21
|
+
attachedOnChain: true,
|
|
22
|
+
tierId: 2,
|
|
23
|
+
totalRebate: amount,
|
|
24
|
+
totalRebateFactor: amount,
|
|
25
|
+
discountShare: amount,
|
|
26
|
+
discountFactor: amount,
|
|
27
|
+
orderFeeDiscountFactor: amount,
|
|
28
|
+
updatedAt: 123,
|
|
29
|
+
...overrides,
|
|
30
|
+
});
|
|
31
|
+
const response = (body, slot) => new Response(JSON.stringify(body), {
|
|
32
|
+
headers: slot === undefined ? {} : { "X-Solana-Slot": slot },
|
|
33
|
+
});
|
|
34
|
+
afterEach(() => {
|
|
35
|
+
vi.restoreAllMocks();
|
|
36
|
+
vi.mocked(fetch).mockReset();
|
|
37
|
+
});
|
|
38
|
+
describe("Solana API reads", () => {
|
|
39
|
+
it("uses the current chain for approvals and rejects Solana EVM operations", () => {
|
|
40
|
+
for (const chainId of [ARBITRUM, SOLANA_NETWORK_ID]) {
|
|
41
|
+
for (const update of ["field", "context", "spread"]) {
|
|
42
|
+
const sdk = new GmxApiSdk({ chainId });
|
|
43
|
+
if (update === "context") {
|
|
44
|
+
sdk.ctx = { chainId: AVALANCHE, api: sdk.ctx.api };
|
|
45
|
+
}
|
|
46
|
+
else if (update === "spread") {
|
|
47
|
+
sdk.ctx = { ...sdk.ctx, chainId: AVALANCHE };
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
sdk.ctx.chainId = AVALANCHE;
|
|
51
|
+
}
|
|
52
|
+
const params = {
|
|
53
|
+
tokenAddress: "0x0000000000000000000000000000000000000001",
|
|
54
|
+
spender: "router",
|
|
55
|
+
amount: 1n,
|
|
56
|
+
};
|
|
57
|
+
const transaction = sdk.buildApproveTransaction(params);
|
|
58
|
+
const decoded = decodeFunctionData({ abi: ERC20ABI, data: transaction.data });
|
|
59
|
+
expect(decoded.functionName).toBe("approve");
|
|
60
|
+
expect(decoded.args).toEqual([getContract(AVALANCHE, "SyntheticsRouter"), 1n]);
|
|
61
|
+
expect(sdk.ctx.chainId).toBe(AVALANCHE);
|
|
62
|
+
sdk.ctx.chainId = SOLANA_NETWORK_ID;
|
|
63
|
+
expect(sdk.ctx.chainId).toBe(SOLANA_NETWORK_ID);
|
|
64
|
+
expect(() => sdk.buildApproveTransaction(params)).toThrow("EVM operations require an EVM chainId");
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
it("preserves referral case and fee precision, rejecting malformed required fields", async () => {
|
|
69
|
+
const sdk = new GmxApiSdk({ chainId: SOLANA_NETWORK_ID });
|
|
70
|
+
const fields = ["totalRebate", "totalRebateFactor", "discountShare", "discountFactor", "orderFeeDiscountFactor"];
|
|
71
|
+
for (const value of [amount, 0]) {
|
|
72
|
+
vi.mocked(fetch).mockResolvedValueOnce(response(fee(Object.fromEntries(fields.map((key) => [key, value])))));
|
|
73
|
+
expect(await sdk.fetchFeeDiscount({ address })).toEqual({
|
|
74
|
+
userReferralInfo: {
|
|
75
|
+
userReferralCode: "RefErRaL",
|
|
76
|
+
userReferralCodeString: "MyCode",
|
|
77
|
+
referralCodeForTxn: "TxCoDe",
|
|
78
|
+
affiliate: address,
|
|
79
|
+
attachedOnChain: true,
|
|
80
|
+
tierId: 2,
|
|
81
|
+
totalRebate: BigInt(value),
|
|
82
|
+
totalRebateFactor: BigInt(value),
|
|
83
|
+
discountShare: BigInt(value),
|
|
84
|
+
discountFactor: BigInt(value),
|
|
85
|
+
},
|
|
86
|
+
orderFeeDiscountFactor: BigInt(value),
|
|
87
|
+
updatedAt: 123,
|
|
88
|
+
});
|
|
89
|
+
expect(new URL(String(vi.mocked(fetch).mock.lastCall[0])).searchParams.get("address")).toBe(address);
|
|
90
|
+
}
|
|
91
|
+
for (const raw of [
|
|
92
|
+
null,
|
|
93
|
+
[],
|
|
94
|
+
{},
|
|
95
|
+
fee({ attachedOnChain: "true" }),
|
|
96
|
+
fee({ tierId: 1.5 }),
|
|
97
|
+
...["userReferralCode", "userReferralCodeString", "referralCodeForTxn", "affiliate"].map((key) => fee({ [key]: undefined })),
|
|
98
|
+
...fields.flatMap((key) => [undefined, null, true, "", "-1", "1.5", "0x10", 1.5, -1, Number.MAX_SAFE_INTEGER + 1].map((value) => fee({ [key]: value }))),
|
|
99
|
+
])
|
|
100
|
+
expect(() => parseFeeDiscount(raw)).toThrow("/v1/fee-discount");
|
|
101
|
+
});
|
|
102
|
+
it("passes slot floors and returns each response slot without changing account data", async () => {
|
|
103
|
+
const sdk = new GmxApiSdk({ chainId: SOLANA_NETWORK_ID });
|
|
104
|
+
const headers = [undefined, "", "-1", "1.5", "9007199254740992", "invalid", "0", "123"];
|
|
105
|
+
for (const method of ["fetchOrders", "fetchPositionsInfo"]) {
|
|
106
|
+
for (const minContextSlot of [undefined, 0, 123]) {
|
|
107
|
+
for (const header of headers) {
|
|
108
|
+
const slot = header === "0" ? 0 : header === "123" ? 123 : undefined;
|
|
109
|
+
const includeRelatedOrders = minContextSlot === 123;
|
|
110
|
+
const body = [{ account: address, positionValueInUsd: amount }];
|
|
111
|
+
let metadata;
|
|
112
|
+
vi.mocked(fetch).mockResolvedValueOnce(response(body, header));
|
|
113
|
+
const result = await sdk[method]({
|
|
114
|
+
address,
|
|
115
|
+
minContextSlot,
|
|
116
|
+
includeRelatedOrders,
|
|
117
|
+
onResponse: (value) => (metadata = value),
|
|
118
|
+
});
|
|
119
|
+
expect(result).toEqual([{ account: address, positionValueInUsd: BigInt(amount) }]);
|
|
120
|
+
expect(metadata).toEqual({ slot });
|
|
121
|
+
const url = new URL(String(vi.mocked(fetch).mock.lastCall[0]));
|
|
122
|
+
expect(url.pathname).toBe(method === "fetchOrders" ? "/v1/orders" : "/v1/positions");
|
|
123
|
+
expect(Object.fromEntries(url.searchParams)).toEqual({
|
|
124
|
+
address,
|
|
125
|
+
...(minContextSlot === undefined ? {} : { minContextSlot: String(minContextSlot) }),
|
|
126
|
+
...(method === "fetchPositionsInfo" && includeRelatedOrders ? { includeRelatedOrders: "true" } : {}),
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
it("keeps response metadata local when account reads finish out of order", async () => {
|
|
133
|
+
const sdk = new GmxApiSdk({
|
|
134
|
+
chainId: SOLANA_NETWORK_ID,
|
|
135
|
+
api: new HttpClientWithFallback(["https://first.example", "https://second.example"]),
|
|
136
|
+
});
|
|
137
|
+
let resolveFirst;
|
|
138
|
+
const slots = [];
|
|
139
|
+
vi.mocked(fetch)
|
|
140
|
+
.mockImplementationOnce(() => new Promise((resolve) => (resolveFirst = resolve)))
|
|
141
|
+
.mockResolvedValueOnce(response([{ positionValueInUsd: amount }], "202"));
|
|
142
|
+
const first = sdk.fetchOrders({ address, onResponse: ({ slot }) => (slots[0] = slot) });
|
|
143
|
+
const second = await sdk.fetchPositionsInfo({ address, onResponse: ({ slot }) => (slots[1] = slot) });
|
|
144
|
+
expect(second).toEqual([{ positionValueInUsd: BigInt(amount) }]);
|
|
145
|
+
resolveFirst(response([{ account: address }], "101"));
|
|
146
|
+
expect(await first).toEqual([{ account: address }]);
|
|
147
|
+
expect(slots).toEqual([101, 202]);
|
|
148
|
+
});
|
|
149
|
+
it("does not retry a successful read when its response callback throws", async () => {
|
|
150
|
+
const api = new HttpClientWithFallback(["https://first.example", "https://second.example"]);
|
|
151
|
+
const error = new Error("Consumer failed");
|
|
152
|
+
vi.mocked(fetch).mockResolvedValue(response({ account: address }, "123"));
|
|
153
|
+
await expect(api.fetchJson("/v1/orders", {
|
|
154
|
+
onResponse: () => {
|
|
155
|
+
throw error;
|
|
156
|
+
},
|
|
157
|
+
})).rejects.toBe(error);
|
|
158
|
+
expect(vi.mocked(fetch)).toHaveBeenCalledTimes(1);
|
|
159
|
+
});
|
|
160
|
+
});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ARBITRUM, ARBITRUM_SEPOLIA, AVALANCHE, AVALANCHE_FUJI, MEGAETH } from "./chains";
|
|
1
|
+
import { ARBITRUM, ARBITRUM_SEPOLIA, AVALANCHE, AVALANCHE_FUJI, MEGAETH, SOLANA_NETWORK_ID } from "./chains";
|
|
2
2
|
const API_URLS = {
|
|
3
3
|
production: {
|
|
4
4
|
[ARBITRUM]: "https://arbitrum.gmxapi.io",
|
|
@@ -6,6 +6,7 @@ const API_URLS = {
|
|
|
6
6
|
[AVALANCHE_FUJI]: undefined,
|
|
7
7
|
[ARBITRUM_SEPOLIA]: "https://arbitrum-sepolia-test.gmxapi.ai",
|
|
8
8
|
[MEGAETH]: "https://megaeth.gmxapi.io",
|
|
9
|
+
[SOLANA_NETWORK_ID]: "https://solana.gmxapi.io",
|
|
9
10
|
},
|
|
10
11
|
test: {
|
|
11
12
|
[ARBITRUM]: "https://arbitrum-test.gmxapi.ai",
|
|
@@ -13,6 +14,7 @@ const API_URLS = {
|
|
|
13
14
|
[AVALANCHE_FUJI]: undefined,
|
|
14
15
|
[ARBITRUM_SEPOLIA]: "https://arbitrum-sepolia-test.gmxapi.ai",
|
|
15
16
|
[MEGAETH]: undefined,
|
|
17
|
+
[SOLANA_NETWORK_ID]: undefined,
|
|
16
18
|
},
|
|
17
19
|
};
|
|
18
20
|
const API_FALLBACK_URLS = {
|
|
@@ -22,6 +24,7 @@ const API_FALLBACK_URLS = {
|
|
|
22
24
|
[AVALANCHE_FUJI]: [],
|
|
23
25
|
[ARBITRUM_SEPOLIA]: [],
|
|
24
26
|
[MEGAETH]: [],
|
|
27
|
+
[SOLANA_NETWORK_ID]: [],
|
|
25
28
|
},
|
|
26
29
|
test: {
|
|
27
30
|
[ARBITRUM]: [],
|
|
@@ -29,6 +32,7 @@ const API_FALLBACK_URLS = {
|
|
|
29
32
|
[AVALANCHE_FUJI]: [],
|
|
30
33
|
[ARBITRUM_SEPOLIA]: [],
|
|
31
34
|
[MEGAETH]: [],
|
|
35
|
+
[SOLANA_NETWORK_ID]: [],
|
|
32
36
|
},
|
|
33
37
|
};
|
|
34
38
|
export function getApiUrl(chainId, environment = "production") {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { HIGH_PRICE_IMPACT_BPS } from "../../configs/factors";
|
|
2
2
|
import { bigMath } from "../bigmath";
|
|
3
|
+
import { getGmsolUsdAmount } from "../gmsol";
|
|
3
4
|
import { getOpenInterestForBalance } from "../markets";
|
|
4
5
|
import { applyFactor, getBasisPoints, PRECISION } from "../numbers";
|
|
5
6
|
import { SwapPricingType } from "../orders/types";
|
|
@@ -25,11 +26,16 @@ export function getSwapFee(marketInfo, swapAmount, balanceWasImproved, swapPrici
|
|
|
25
26
|
}
|
|
26
27
|
return applyFactor(swapAmount, factor);
|
|
27
28
|
}
|
|
28
|
-
export function getPositionFee(marketInfo, sizeDeltaUsd, balanceWasImproved, referralInfo, uiFeeFactor, proDiscountFactor) {
|
|
29
|
+
export function getPositionFee(marketInfo, sizeDeltaUsd, balanceWasImproved, referralInfo, uiFeeFactor, proDiscountFactor, feeDiscountFactor) {
|
|
29
30
|
const factor = balanceWasImproved
|
|
30
31
|
? marketInfo.positionFeeFactorForBalanceWasImproved
|
|
31
32
|
: marketInfo.positionFeeFactorForBalanceWasNotImproved;
|
|
32
33
|
let positionFeeUsd = applyFactor(sizeDeltaUsd, factor);
|
|
34
|
+
if (marketInfo.tradeMath === "gmsol") {
|
|
35
|
+
positionFeeUsd = getGmsolUsdAmount(positionFeeUsd);
|
|
36
|
+
const discountUsd = getGmsolUsdAmount(applyFactor(positionFeeUsd, bigMath.min(PRECISION, bigMath.max(0n, feeDiscountFactor ?? 0n))));
|
|
37
|
+
return { positionFeeUsd: positionFeeUsd - discountUsd, discountUsd, totalRebateUsd: 0n, uiFeeUsd: 0n };
|
|
38
|
+
}
|
|
33
39
|
const uiFeeUsd = applyFactor(sizeDeltaUsd, uiFeeFactor ?? 0n);
|
|
34
40
|
const totalRebateUsd = referralInfo ? applyFactor(positionFeeUsd, referralInfo.totalRebateFactor) : 0n;
|
|
35
41
|
let discountUsd = referralInfo ? applyFactor(totalRebateUsd, referralInfo.discountFactor) : 0n;
|
|
@@ -1,8 +1,17 @@
|
|
|
1
1
|
import { zeroHash } from "viem";
|
|
2
2
|
import { bigMath } from "../bigmath";
|
|
3
|
+
import { getGmsolMidPrice, getGmsolUsdAmount } from "../gmsol";
|
|
4
|
+
import { GMSOL_MAX_IMPACT_EXPONENT, GMSOL_MAX_SIGNED, GMSOL_MAX_UNSIGNED, GMSOL_PRECISION, GMSOL_PRECISION_SCALE, } from "../gmsol/constants";
|
|
5
|
+
import { getGmsolFractionalPower } from "../gmsol/numbers";
|
|
3
6
|
import { getOpenInterestForBalance, getTokenPoolType } from "../markets";
|
|
4
|
-
import { applyExponentFactor, applyFactor, BASIS_POINTS_DECIMALS, expandDecimals, getBasisPoints, PRECISION_DECIMALS, roundUpMagnitudeDivision, } from "../numbers";
|
|
7
|
+
import { applyExponentFactor, applyFactor, BASIS_POINTS_DECIMALS, expandDecimals, getBasisPoints, PRECISION, PRECISION_DECIMALS, roundUpMagnitudeDivision, } from "../numbers";
|
|
5
8
|
import { convertToTokenAmount, convertToTokenAmountForIncrease, convertToUsd, getMidPrice } from "../tokens/utils";
|
|
9
|
+
export class GmsolPriceImpactError extends Error {
|
|
10
|
+
constructor() {
|
|
11
|
+
super(...arguments);
|
|
12
|
+
this.name = "GmsolPriceImpactError";
|
|
13
|
+
}
|
|
14
|
+
}
|
|
6
15
|
export function getPriceImpactByAcceptablePrice(p) {
|
|
7
16
|
const { sizeDeltaUsd, acceptablePrice, indexPrice: markPrice, isLong, isIncrease } = p;
|
|
8
17
|
const shouldFlipPriceDiff = isIncrease ? !isLong : isLong;
|
|
@@ -44,12 +53,18 @@ export function applySwapImpactWithCap(marketInfo, token, priceImpactDeltaUsd) {
|
|
|
44
53
|
return { impactDeltaAmount, cappedDiffUsd };
|
|
45
54
|
}
|
|
46
55
|
export function getCappedPositionImpactUsd(marketInfo, sizeDeltaUsd, isLong, isIncrease, opts = {}) {
|
|
56
|
+
if (marketInfo.tradeMath === "gmsol") {
|
|
57
|
+
sizeDeltaUsd = getGmsolUsdAmount(sizeDeltaUsd);
|
|
58
|
+
}
|
|
47
59
|
sizeDeltaUsd = isIncrease ? sizeDeltaUsd : sizeDeltaUsd * -1n;
|
|
48
60
|
const { priceImpactDeltaUsd, balanceWasImproved } = getPriceImpactForPosition(marketInfo, sizeDeltaUsd, isLong, opts);
|
|
49
61
|
if (priceImpactDeltaUsd < 0 && !opts.shouldCapNegativeImpact) {
|
|
50
62
|
return { priceImpactDeltaUsd, balanceWasImproved };
|
|
51
63
|
}
|
|
52
|
-
|
|
64
|
+
let cappedImpactUsd = capPositionImpactUsdByMaxPriceImpactFactor(marketInfo, sizeDeltaUsd, priceImpactDeltaUsd);
|
|
65
|
+
if (marketInfo.tradeMath === "gmsol") {
|
|
66
|
+
cappedImpactUsd = capPositionImpactUsdByMaxImpactPool(marketInfo, cappedImpactUsd);
|
|
67
|
+
}
|
|
53
68
|
return {
|
|
54
69
|
priceImpactDeltaUsd: cappedImpactUsd,
|
|
55
70
|
balanceWasImproved,
|
|
@@ -70,7 +85,8 @@ export function capPositionImpactUsdByMaxImpactPool(marketInfo, positionImpactDe
|
|
|
70
85
|
export function capPositionImpactUsdByMaxPriceImpactFactor(marketInfo, sizeDeltaUsd, positionImpactDeltaUsd) {
|
|
71
86
|
const { maxPositiveImpactFactor, maxNegativeImpactFactor } = getMaxPositionImpactFactors(marketInfo);
|
|
72
87
|
const maxPriceImapctFactor = positionImpactDeltaUsd > 0 ? maxPositiveImpactFactor : maxNegativeImpactFactor;
|
|
73
|
-
const
|
|
88
|
+
const maxImpactUsd = applyFactor(bigMath.abs(sizeDeltaUsd), maxPriceImapctFactor);
|
|
89
|
+
const maxPriceImpactUsdBasedOnMaxPriceImpactFactor = marketInfo.tradeMath === "gmsol" ? getGmsolUsdAmount(maxImpactUsd) : maxImpactUsd;
|
|
74
90
|
if (bigMath.abs(positionImpactDeltaUsd) > maxPriceImpactUsdBasedOnMaxPriceImpactFactor) {
|
|
75
91
|
positionImpactDeltaUsd = maxPriceImpactUsdBasedOnMaxPriceImpactFactor * (positionImpactDeltaUsd > 0 ? 1n : -1n);
|
|
76
92
|
}
|
|
@@ -79,16 +95,19 @@ export function capPositionImpactUsdByMaxPriceImpactFactor(marketInfo, sizeDelta
|
|
|
79
95
|
export function getMaxPositionImpactFactors(marketInfo) {
|
|
80
96
|
let maxPositiveImpactFactor = marketInfo.maxPositionImpactFactorPositive;
|
|
81
97
|
const maxNegativeImpactFactor = marketInfo.maxPositionImpactFactorNegative;
|
|
82
|
-
if (maxPositiveImpactFactor > maxNegativeImpactFactor) {
|
|
98
|
+
if (marketInfo.tradeMath !== "gmsol" && maxPositiveImpactFactor > maxNegativeImpactFactor) {
|
|
83
99
|
maxPositiveImpactFactor = maxNegativeImpactFactor;
|
|
84
100
|
}
|
|
85
101
|
return { maxPositiveImpactFactor, maxNegativeImpactFactor };
|
|
86
102
|
}
|
|
87
103
|
export function getPriceImpactForPosition(marketInfo, sizeDeltaUsd, isLong, opts = {}) {
|
|
104
|
+
if (marketInfo.tradeMath === "gmsol") {
|
|
105
|
+
sizeDeltaUsd = getGmsolUsdAmount(sizeDeltaUsd);
|
|
106
|
+
}
|
|
88
107
|
const longInterestUsd = getOpenInterestForBalance(marketInfo, true);
|
|
89
108
|
const shortInterestUsd = getOpenInterestForBalance(marketInfo, false);
|
|
90
109
|
let effectiveUsdDelta = sizeDeltaUsd;
|
|
91
|
-
if (marketInfo.useOpenInterestInTokensForBalance) {
|
|
110
|
+
if (marketInfo.tradeMath !== "gmsol" && marketInfo.useOpenInterestInTokensForBalance) {
|
|
92
111
|
if (sizeDeltaUsd < 0n && opts.sizeDeltaInTokens === undefined) {
|
|
93
112
|
throw new Error(`Missing sizeDeltaInTokens for token-OI decrease market ${marketInfo.marketTokenAddress}`);
|
|
94
113
|
}
|
|
@@ -121,6 +140,7 @@ export function getPriceImpactForPosition(marketInfo, sizeDeltaUsd, isLong, opts
|
|
|
121
140
|
exponentFactorPositive: marketInfo.positionImpactExponentFactorPositive,
|
|
122
141
|
exponentFactorNegative: marketInfo.positionImpactExponentFactorNegative,
|
|
123
142
|
fallbackToZero: opts.fallbackToZero,
|
|
143
|
+
tradeMath: marketInfo.tradeMath,
|
|
124
144
|
});
|
|
125
145
|
if (priceImpactDeltaUsd >= 0n) {
|
|
126
146
|
return {
|
|
@@ -150,6 +170,7 @@ export function getPriceImpactForPosition(marketInfo, sizeDeltaUsd, isLong, opts
|
|
|
150
170
|
exponentFactorPositive: marketInfo.positionImpactExponentFactorPositive,
|
|
151
171
|
exponentFactorNegative: marketInfo.positionImpactExponentFactorNegative,
|
|
152
172
|
fallbackToZero: opts.fallbackToZero,
|
|
173
|
+
tradeMath: marketInfo.tradeMath,
|
|
153
174
|
});
|
|
154
175
|
if (priceImpactUsdForVirtualInventory < priceImpactDeltaUsd) {
|
|
155
176
|
return {
|
|
@@ -168,7 +189,7 @@ function getVirtualInventoryForPositionImpact(marketInfo) {
|
|
|
168
189
|
return { hasVirtualInventory: false, virtualInventory: 0n };
|
|
169
190
|
}
|
|
170
191
|
let virtualInventory = marketInfo.virtualInventoryForPositions;
|
|
171
|
-
if (marketInfo.useOpenInterestInTokensForBalance) {
|
|
192
|
+
if (marketInfo.tradeMath !== "gmsol" && marketInfo.useOpenInterestInTokensForBalance) {
|
|
172
193
|
if (typeof marketInfo.virtualInventoryForPositionsInTokens !== "bigint") {
|
|
173
194
|
throw new Error(`Missing virtualInventoryForPositionsInTokens for token-OI market ${marketInfo.marketTokenAddress}`);
|
|
174
195
|
}
|
|
@@ -203,6 +224,7 @@ export function getPriceImpactForSwap(marketInfo, tokenA, tokenB, usdDeltaTokenA
|
|
|
203
224
|
shortPoolAmount: marketInfo.shortPoolAmount,
|
|
204
225
|
longDeltaUsd,
|
|
205
226
|
shortDeltaUsd,
|
|
227
|
+
tradeMath: marketInfo.tradeMath,
|
|
206
228
|
});
|
|
207
229
|
const { priceImpactDeltaUsd, balanceWasImproved } = getPriceImpactUsd({
|
|
208
230
|
currentLongUsd: longPoolUsd,
|
|
@@ -214,6 +236,7 @@ export function getPriceImpactForSwap(marketInfo, tokenA, tokenB, usdDeltaTokenA
|
|
|
214
236
|
exponentFactorPositive: marketInfo.swapImpactExponentFactor,
|
|
215
237
|
exponentFactorNegative: marketInfo.swapImpactExponentFactor,
|
|
216
238
|
fallbackToZero: opts.fallbackToZero,
|
|
239
|
+
tradeMath: marketInfo.tradeMath,
|
|
217
240
|
});
|
|
218
241
|
if (priceImpactDeltaUsd > 0) {
|
|
219
242
|
return {
|
|
@@ -236,6 +259,7 @@ export function getPriceImpactForSwap(marketInfo, tokenA, tokenB, usdDeltaTokenA
|
|
|
236
259
|
shortPoolAmount: virtualInventoryShort,
|
|
237
260
|
longDeltaUsd,
|
|
238
261
|
shortDeltaUsd,
|
|
262
|
+
tradeMath: marketInfo.tradeMath,
|
|
239
263
|
});
|
|
240
264
|
const { priceImpactDeltaUsd: priceImpactUsdForVirtualInventory } = getPriceImpactUsd({
|
|
241
265
|
currentLongUsd: virtualInventoryParams.longPoolUsd,
|
|
@@ -247,6 +271,7 @@ export function getPriceImpactForSwap(marketInfo, tokenA, tokenB, usdDeltaTokenA
|
|
|
247
271
|
exponentFactorPositive: marketInfo.swapImpactExponentFactor,
|
|
248
272
|
exponentFactorNegative: marketInfo.swapImpactExponentFactor,
|
|
249
273
|
fallbackToZero: opts.fallbackToZero,
|
|
274
|
+
tradeMath: marketInfo.tradeMath,
|
|
250
275
|
});
|
|
251
276
|
return {
|
|
252
277
|
priceImpactDeltaUsd: priceImpactUsdForVirtualInventory < priceImpactDeltaUsd
|
|
@@ -296,8 +321,8 @@ function getNextOpenInterestParams(p) {
|
|
|
296
321
|
}
|
|
297
322
|
export function getNextPoolAmountsParams(p) {
|
|
298
323
|
const { longToken, shortToken, longPoolAmount, shortPoolAmount, longDeltaUsd, shortDeltaUsd } = p;
|
|
299
|
-
const longPrice = getMidPrice(longToken.prices);
|
|
300
|
-
const shortPrice = getMidPrice(shortToken.prices);
|
|
324
|
+
const longPrice = p.tradeMath === "gmsol" ? getGmsolMidPrice(longToken) : getMidPrice(longToken.prices);
|
|
325
|
+
const shortPrice = p.tradeMath === "gmsol" ? getGmsolMidPrice(shortToken) : getMidPrice(shortToken.prices);
|
|
301
326
|
const longPoolUsd = convertToUsd(longPoolAmount, longToken.decimals, longPrice);
|
|
302
327
|
const shortPoolUsd = convertToUsd(shortPoolAmount, shortToken.decimals, shortPrice);
|
|
303
328
|
const nextLongPoolUsd = longPoolUsd + longDeltaUsd;
|
|
@@ -340,6 +365,7 @@ export function getPriceImpactUsd(p) {
|
|
|
340
365
|
hasPositiveImpact,
|
|
341
366
|
factor,
|
|
342
367
|
exponentFactor,
|
|
368
|
+
tradeMath: p.tradeMath,
|
|
343
369
|
});
|
|
344
370
|
}
|
|
345
371
|
else {
|
|
@@ -350,6 +376,7 @@ export function getPriceImpactUsd(p) {
|
|
|
350
376
|
factorNegative: p.factorNegative,
|
|
351
377
|
exponentFactorPositive: p.exponentFactorPositive,
|
|
352
378
|
exponentFactorNegative: p.exponentFactorNegative,
|
|
379
|
+
tradeMath: p.tradeMath,
|
|
353
380
|
});
|
|
354
381
|
}
|
|
355
382
|
return {
|
|
@@ -362,9 +389,22 @@ export function getPriceImpactUsd(p) {
|
|
|
362
389
|
*/
|
|
363
390
|
export function calculateImpactForSameSideRebalance(p) {
|
|
364
391
|
const { currentDiff, nextDiff, hasPositiveImpact, factor, exponentFactor } = p;
|
|
365
|
-
const currentImpact =
|
|
366
|
-
|
|
392
|
+
const currentImpact = applyMarketImpactFactor({
|
|
393
|
+
diff: currentDiff,
|
|
394
|
+
factor,
|
|
395
|
+
exponent: exponentFactor,
|
|
396
|
+
tradeMath: p.tradeMath,
|
|
397
|
+
});
|
|
398
|
+
const nextImpact = applyMarketImpactFactor({
|
|
399
|
+
diff: nextDiff,
|
|
400
|
+
factor,
|
|
401
|
+
exponent: exponentFactor,
|
|
402
|
+
tradeMath: p.tradeMath,
|
|
403
|
+
});
|
|
367
404
|
const deltaDiff = bigMath.abs(currentImpact - nextImpact);
|
|
405
|
+
if (p.tradeMath === "gmsol" && deltaDiff > GMSOL_MAX_SIGNED * GMSOL_PRECISION_SCALE) {
|
|
406
|
+
throw new GmsolPriceImpactError("Solana price impact exceeds native signed range");
|
|
407
|
+
}
|
|
368
408
|
return hasPositiveImpact ? deltaDiff : -deltaDiff;
|
|
369
409
|
}
|
|
370
410
|
/**
|
|
@@ -372,11 +412,70 @@ export function calculateImpactForSameSideRebalance(p) {
|
|
|
372
412
|
*/
|
|
373
413
|
export function calculateImpactForCrossoverRebalance(p) {
|
|
374
414
|
const { currentDiff, nextDiff, factorNegative, factorPositive, exponentFactorPositive, exponentFactorNegative } = p;
|
|
375
|
-
const positiveImpact =
|
|
376
|
-
|
|
415
|
+
const positiveImpact = applyMarketImpactFactor({
|
|
416
|
+
diff: currentDiff,
|
|
417
|
+
factor: factorPositive,
|
|
418
|
+
exponent: exponentFactorPositive,
|
|
419
|
+
tradeMath: p.tradeMath,
|
|
420
|
+
});
|
|
421
|
+
const negativeImpactUsd = applyMarketImpactFactor({
|
|
422
|
+
diff: nextDiff,
|
|
423
|
+
factor: factorNegative,
|
|
424
|
+
exponent: exponentFactorNegative,
|
|
425
|
+
tradeMath: p.tradeMath,
|
|
426
|
+
});
|
|
377
427
|
const deltaDiffUsd = bigMath.abs(positiveImpact - negativeImpactUsd);
|
|
428
|
+
if (p.tradeMath === "gmsol" && deltaDiffUsd > GMSOL_MAX_SIGNED * GMSOL_PRECISION_SCALE) {
|
|
429
|
+
throw new GmsolPriceImpactError("Solana price impact exceeds native signed range");
|
|
430
|
+
}
|
|
378
431
|
return positiveImpact > negativeImpactUsd ? deltaDiffUsd : -deltaDiffUsd;
|
|
379
432
|
}
|
|
433
|
+
function applyMarketImpactFactor(p) {
|
|
434
|
+
if (p.tradeMath !== "gmsol") {
|
|
435
|
+
return applyImpactFactor(p.diff, p.factor, p.exponent);
|
|
436
|
+
}
|
|
437
|
+
for (const value of [p.diff, p.factor, p.exponent]) {
|
|
438
|
+
if (value < 0n || value % GMSOL_PRECISION_SCALE !== 0n || value > GMSOL_MAX_UNSIGNED * GMSOL_PRECISION_SCALE) {
|
|
439
|
+
throw new GmsolPriceImpactError("Solana impact input is outside native precision or range");
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
const base = bigMath.mulDiv(p.diff, 1n, GMSOL_PRECISION_SCALE);
|
|
443
|
+
const factor = bigMath.mulDiv(p.factor, 1n, GMSOL_PRECISION_SCALE);
|
|
444
|
+
const power = getGmsolImpactPower(base, p.exponent);
|
|
445
|
+
const impact = bigMath.mulDiv(power, factor, GMSOL_PRECISION);
|
|
446
|
+
if (impact > GMSOL_MAX_UNSIGNED) {
|
|
447
|
+
throw new GmsolPriceImpactError("Solana impact factor exceeds native range");
|
|
448
|
+
}
|
|
449
|
+
return impact * GMSOL_PRECISION_SCALE;
|
|
450
|
+
}
|
|
451
|
+
function getGmsolImpactPower(base, exponent) {
|
|
452
|
+
if (base < GMSOL_PRECISION) {
|
|
453
|
+
return 0n;
|
|
454
|
+
}
|
|
455
|
+
if (base === GMSOL_PRECISION || exponent === 0n) {
|
|
456
|
+
return GMSOL_PRECISION;
|
|
457
|
+
}
|
|
458
|
+
const hasFractionalExponent = exponent % PRECISION !== 0n;
|
|
459
|
+
if (hasFractionalExponent) {
|
|
460
|
+
try {
|
|
461
|
+
return getGmsolFractionalPower(base, exponent / GMSOL_PRECISION_SCALE);
|
|
462
|
+
}
|
|
463
|
+
catch (error) {
|
|
464
|
+
throw new GmsolPriceImpactError(error instanceof Error ? error.message : "Solana fractional power failed");
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
if (exponent > GMSOL_MAX_IMPACT_EXPONENT) {
|
|
468
|
+
throw new GmsolPriceImpactError("Solana impact exponent is unsupported for exact calculation");
|
|
469
|
+
}
|
|
470
|
+
let power = GMSOL_PRECISION;
|
|
471
|
+
for (let remaining = exponent; remaining > 0n; remaining -= PRECISION) {
|
|
472
|
+
power = bigMath.mulDiv(power, base, GMSOL_PRECISION);
|
|
473
|
+
if (power > GMSOL_MAX_UNSIGNED) {
|
|
474
|
+
throw new GmsolPriceImpactError("Solana impact power exceeds native range");
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
return power;
|
|
478
|
+
}
|
|
380
479
|
export function applyImpactFactor(diff, factor, exponent) {
|
|
381
480
|
try {
|
|
382
481
|
return applyFactor(applyExponentFactor(diff, exponent), factor);
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { PRECISION } from "../numbers";
|
|
2
|
+
export const GMSOL_PRECISION = 10n ** 20n;
|
|
3
|
+
export const GMSOL_PRECISION_SCALE = PRECISION / GMSOL_PRECISION;
|
|
4
|
+
export const GMSOL_MAX_UNSIGNED = (1n << 128n) - 1n;
|
|
5
|
+
export const GMSOL_MAX_SIGNED = (1n << 127n) - 1n;
|
|
6
|
+
export const GMSOL_MAX_IMPACT_EXPONENT = 128n * PRECISION;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { bigMath } from "../bigmath";
|
|
2
|
+
import { expandDecimals, roundUpMagnitudeDivision } from "../numbers";
|
|
3
|
+
import { GMSOL_PRECISION_SCALE } from "./constants";
|
|
4
|
+
export { GMSOL_PRECISION_SCALE } from "./constants";
|
|
5
|
+
export { getGmsolFractionalPower } from "./numbers";
|
|
6
|
+
export function getGmsolUsdAmount(value) {
|
|
7
|
+
return bigMath.mulDiv(value, 1n, GMSOL_PRECISION_SCALE) * GMSOL_PRECISION_SCALE;
|
|
8
|
+
}
|
|
9
|
+
export function getGmsolMidPrice(token) {
|
|
10
|
+
const scale = expandDecimals(1, token.decimals) * GMSOL_PRECISION_SCALE;
|
|
11
|
+
return bigMath.mulDiv(token.prices.minPrice + token.prices.maxPrice, 1n, 2n * scale) * scale;
|
|
12
|
+
}
|
|
13
|
+
/** The impact is settled in the entry size; it never becomes pending collateral. 0 means the order fills no tokens. */
|
|
14
|
+
export function getGmsolIncreaseSizeDeltaInTokens(p) {
|
|
15
|
+
const { baseSizeDeltaInTokens, priceImpactDeltaUsd, indexToken, isLong } = p;
|
|
16
|
+
const unit = expandDecimals(1, indexToken.decimals);
|
|
17
|
+
const impactAmount = priceImpactDeltaUsd > 0n
|
|
18
|
+
? bigMath.mulDiv(priceImpactDeltaUsd, unit, indexToken.prices.maxPrice)
|
|
19
|
+
: roundUpMagnitudeDivision(priceImpactDeltaUsd * unit, indexToken.prices.minPrice);
|
|
20
|
+
return bigMath.max(baseSizeDeltaInTokens + (isLong ? impactAmount : -impactAmount), 0n);
|
|
21
|
+
}
|
|
22
|
+
/** Rent is a refundable deposit. The maximum keeper fee can be spent even on a cancelled execution. */
|
|
23
|
+
export function getGmsolExecutionFee(p) {
|
|
24
|
+
const { maxExecutionLamports, orderRentLamports, escrowRentLamports, solPrice } = p;
|
|
25
|
+
if ([maxExecutionLamports, orderRentLamports, escrowRentLamports, solPrice].some((value) => value < 0n)) {
|
|
26
|
+
throw new Error("Execution fee inputs must be nonnegative");
|
|
27
|
+
}
|
|
28
|
+
const keeperFeeLamports = bigMath.max(300000n, maxExecutionLamports);
|
|
29
|
+
const refundableRentLamports = orderRentLamports + escrowRentLamports;
|
|
30
|
+
return {
|
|
31
|
+
keeperFeeLamports,
|
|
32
|
+
keeperFeeUsd: bigMath.mulDiv(keeperFeeLamports, solPrice, 1000000000n),
|
|
33
|
+
refundableRentLamports,
|
|
34
|
+
refundableRentUsd: bigMath.mulDiv(refundableRentLamports, solPrice, 1000000000n),
|
|
35
|
+
requiredLamports: keeperFeeLamports + refundableRentLamports,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
export function getGmsolExecutionFeeRefund(p) {
|
|
39
|
+
const spent = p.ownerCancelledBeforeExecution
|
|
40
|
+
? 0n
|
|
41
|
+
: bigMath.min(p.keeperFeeLamports, bigMath.max(0n, p.executionLamportsSpent));
|
|
42
|
+
return { keeperCostLamports: spent, refundLamports: p.refundableRentLamports + p.keeperFeeLamports - spent };
|
|
43
|
+
}
|