@gmx-io/sdk 2.9.1 → 2.9.3

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.
Files changed (112) hide show
  1. package/build/cjs/src/clients/v2/index.js +61 -41
  2. package/build/cjs/src/clients/v2/solana.spec.js +188 -0
  3. package/build/cjs/src/configs/api.js +4 -0
  4. package/build/cjs/src/utils/fees/index.js +7 -1
  5. package/build/cjs/src/utils/fees/priceImpact.js +118 -18
  6. package/build/cjs/src/utils/gmsol/__tests__/fixtures/nativeMath.json +3171 -0
  7. package/build/cjs/src/utils/gmsol/__tests__/nativeMath.spec.js +213 -0
  8. package/build/cjs/src/utils/gmsol/constants.js +12 -0
  9. package/build/cjs/src/utils/gmsol/fees.js +19 -0
  10. package/build/cjs/src/utils/gmsol/index.js +66 -0
  11. package/build/cjs/src/utils/gmsol/markets.js +206 -0
  12. package/build/cjs/src/utils/gmsol/numbers.js +230 -0
  13. package/build/cjs/src/utils/gmsol/positions.js +152 -0
  14. package/build/cjs/src/utils/gmsol/types.js +2 -0
  15. package/build/cjs/src/utils/http/http.js +3 -4
  16. package/build/cjs/src/utils/http/httpFallback.js +11 -1
  17. package/build/cjs/src/utils/http/solana.js +17 -0
  18. package/build/cjs/src/utils/http/validation.js +21 -1
  19. package/build/cjs/src/utils/http/validation.spec.js +45 -0
  20. package/build/cjs/src/utils/markets/__tests__/api.spec.js +53 -0
  21. package/build/cjs/src/utils/markets/api.js +5 -0
  22. package/build/cjs/src/utils/markets/utils.js +25 -9
  23. package/build/cjs/src/utils/orders/api.js +3 -0
  24. package/build/cjs/src/utils/positions/__tests__/liquidationPrice.spec.js +64 -0
  25. package/build/cjs/src/utils/positions/api.js +3 -0
  26. package/build/cjs/src/utils/positions/utils.js +88 -19
  27. package/build/cjs/src/utils/prices/utils.js +69 -14
  28. package/build/cjs/src/utils/referrals/api.js +41 -0
  29. package/build/cjs/src/utils/swap/swapRouting.js +4 -0
  30. package/build/cjs/src/utils/swap/swapStats.js +6 -1
  31. package/build/cjs/src/utils/trade/__tests__/gmsolTradeMath.spec.js +1012 -0
  32. package/build/cjs/src/utils/trade/decrease.js +266 -56
  33. package/build/cjs/src/utils/trade/decreaseMarginCheck.js +23 -4
  34. package/build/cjs/src/utils/trade/increase.js +86 -28
  35. package/build/cjs/src/utils/trade/increaseMarginCheck.js +51 -9
  36. package/build/cjs/src/utils/trade/twapIncreaseMarginCheck.js +8 -3
  37. package/build/esm/src/clients/v2/index.js +39 -19
  38. package/build/esm/src/clients/v2/solana.spec.js +160 -0
  39. package/build/esm/src/configs/api.js +5 -1
  40. package/build/esm/src/utils/fees/index.js +7 -1
  41. package/build/esm/src/utils/fees/priceImpact.js +111 -12
  42. package/build/esm/src/utils/gmsol/__tests__/fixtures/nativeMath.json +3171 -0
  43. package/build/esm/src/utils/gmsol/__tests__/nativeMath.spec.js +208 -0
  44. package/build/esm/src/utils/gmsol/constants.js +9 -0
  45. package/build/esm/src/utils/gmsol/fees.js +15 -0
  46. package/build/esm/src/utils/gmsol/index.js +46 -0
  47. package/build/esm/src/utils/gmsol/markets.js +193 -0
  48. package/build/esm/src/utils/gmsol/numbers.js +226 -0
  49. package/build/esm/src/utils/gmsol/positions.js +148 -0
  50. package/build/esm/src/utils/gmsol/types.js +1 -0
  51. package/build/esm/src/utils/http/http.js +3 -4
  52. package/build/esm/src/utils/http/httpFallback.js +11 -1
  53. package/build/esm/src/utils/http/solana.js +12 -0
  54. package/build/esm/src/utils/http/validation.js +18 -0
  55. package/build/esm/src/utils/http/validation.spec.js +43 -0
  56. package/build/esm/src/utils/markets/__tests__/api.spec.js +53 -0
  57. package/build/esm/src/utils/markets/api.js +6 -1
  58. package/build/esm/src/utils/markets/utils.js +23 -8
  59. package/build/esm/src/utils/orders/api.js +3 -0
  60. package/build/esm/src/utils/positions/__tests__/liquidationPrice.spec.js +62 -0
  61. package/build/esm/src/utils/positions/api.js +3 -0
  62. package/build/esm/src/utils/positions/utils.js +89 -20
  63. package/build/esm/src/utils/prices/utils.js +70 -15
  64. package/build/esm/src/utils/referrals/api.js +36 -0
  65. package/build/esm/src/utils/swap/swapRouting.js +4 -0
  66. package/build/esm/src/utils/swap/swapStats.js +7 -2
  67. package/build/esm/src/utils/trade/__tests__/gmsolTradeMath.spec.js +1010 -0
  68. package/build/esm/src/utils/trade/decrease.js +266 -56
  69. package/build/esm/src/utils/trade/decreaseMarginCheck.js +23 -4
  70. package/build/esm/src/utils/trade/increase.js +86 -28
  71. package/build/esm/src/utils/trade/increaseMarginCheck.js +53 -11
  72. package/build/esm/src/utils/trade/twapIncreaseMarginCheck.js +8 -3
  73. package/build/tsconfig.tsbuildinfo +1 -1
  74. package/build/types/src/clients/v2/index.d.ts +21 -12
  75. package/build/types/src/clients/v2/solana.spec.d.ts +1 -0
  76. package/build/types/src/utils/fees/index.d.ts +1 -1
  77. package/build/types/src/utils/fees/priceImpact.d.ts +7 -0
  78. package/build/types/src/utils/gmsol/__tests__/nativeMath.spec.d.ts +1 -0
  79. package/build/types/src/utils/gmsol/constants.d.ts +9 -0
  80. package/build/types/src/utils/gmsol/fees.d.ts +6 -0
  81. package/build/types/src/utils/gmsol/index.d.ts +38 -0
  82. package/build/types/src/utils/gmsol/markets.d.ts +49 -0
  83. package/build/types/src/utils/gmsol/numbers.d.ts +11 -0
  84. package/build/types/src/utils/gmsol/positions.d.ts +7 -0
  85. package/build/types/src/utils/gmsol/types.d.ts +105 -0
  86. package/build/types/src/utils/http/http.d.ts +2 -5
  87. package/build/types/src/utils/http/httpFallback.d.ts +2 -5
  88. package/build/types/src/utils/http/solana.d.ts +4 -0
  89. package/build/types/src/utils/http/types.d.ts +17 -4
  90. package/build/types/src/utils/http/validation.d.ts +8 -0
  91. package/build/types/src/utils/http/validation.spec.d.ts +1 -0
  92. package/build/types/src/utils/markets/hashKeys.d.ts +1 -1
  93. package/build/types/src/utils/markets/types.d.ts +3 -2
  94. package/build/types/src/utils/markets/utils.d.ts +6 -2
  95. package/build/types/src/utils/orders/api.d.ts +2 -2
  96. package/build/types/src/utils/positions/__tests__/liquidationPrice.spec.d.ts +1 -0
  97. package/build/types/src/utils/positions/api.d.ts +2 -2
  98. package/build/types/src/utils/positions/types.d.ts +1 -0
  99. package/build/types/src/utils/positions/utils.d.ts +6 -1
  100. package/build/types/src/utils/prices/types.d.ts +16 -0
  101. package/build/types/src/utils/prices/utils.d.ts +3 -11
  102. package/build/types/src/utils/referrals/api.d.ts +8 -0
  103. package/build/types/src/utils/referrals/types.d.ts +5 -0
  104. package/build/types/src/utils/rpc/createViemRpc.d.ts +25 -3
  105. package/build/types/src/utils/trade/__tests__/gmsolTradeMath.spec.d.ts +1 -0
  106. package/build/types/src/utils/trade/decrease.d.ts +5 -0
  107. package/build/types/src/utils/trade/decreaseMarginCheck.d.ts +2 -0
  108. package/build/types/src/utils/trade/increase.d.ts +2 -0
  109. package/build/types/src/utils/trade/increaseMarginCheck.d.ts +2 -0
  110. package/build/types/src/utils/trade/twapIncreaseMarginCheck.d.ts +1 -0
  111. package/build/types/src/utils/trade/types.d.ts +6 -0
  112. package/package.json +10 -1
@@ -0,0 +1,208 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { GMSOL_LONG, GMSOL_PRECISION, GMSOL_SHORT, GMSOL_SIDES } from "../constants";
3
+ import { getGmsolOrderFeeDiscountFactor } from "../fees";
4
+ import { getGmsolBorrowingFactorPerSecond, getGmsolMarketStatus, getGmsolNextFunding, getGmsolPendingPnl, getGmsolPoolValue, getGmsolPoolValueWithoutPnl, getGmsolReservedValue, } from "../markets";
5
+ import { gmsolMath } from "../numbers";
6
+ import { getGmsolPendingPositionFees } from "../positions";
7
+ // mainnet market and position states decoded from the API fixtures in provenance, with their recorded native results
8
+ import fixture from "./fixtures/nativeMath.json";
9
+ const UNIT = GMSOL_PRECISION;
10
+ const IDENTIFIER_KEYS = [
11
+ "name",
12
+ "marketTokenMint",
13
+ "longTokenMint",
14
+ "shortTokenMint",
15
+ "store",
16
+ "owner",
17
+ "marketToken",
18
+ "collateralToken",
19
+ ];
20
+ // get_market_token_price per entry, in the order of each market view's pricesExpected
21
+ const PRICE_VIEWS = [
22
+ ["maxForTrader", true],
23
+ ["maxForTrader", false],
24
+ ["maxAfterDeposit", true],
25
+ ["maxAfterWithdrawal", false],
26
+ ];
27
+ // the program prices one whole GM token, which has 9 decimals, and returns $1 while the supply is 0
28
+ const GM_TOKEN_UNIT = 10n ** 9n;
29
+ const positionMarkets = new Map(fixture.positions.markets.map((entry) => [entry.name, entry]));
30
+ function parseBigints(value, key = "") {
31
+ if (Array.isArray(value)) {
32
+ return value.map((item) => parseBigints(item));
33
+ }
34
+ if (value !== null && typeof value === "object") {
35
+ return Object.fromEntries(Object.entries(value).map(([field, item]) => [field, parseBigints(item, field)]));
36
+ }
37
+ return (typeof value === "string" && !IDENTIFIER_KEYS.includes(key) ? BigInt(value) : value);
38
+ }
39
+ function getGmPrice(value, supply) {
40
+ return supply === 0n ? UNIT : gmsolMath.mulDiv(value, GM_TOKEN_UNIT, supply, "gm price");
41
+ }
42
+ describe("gmsol market math matches the store program", () => {
43
+ it("matches native borrowing and funding with fractional exponents FESOL-109", () => {
44
+ const base = parseBigints(fixture.marketViews[0].market);
45
+ const prices = {
46
+ index: { min: UNIT / 10n ** 9n, max: UNIT / 10n ** 9n },
47
+ long: { min: UNIT / 10n ** 6n, max: UNIT / 10n ** 6n },
48
+ short: { min: UNIT / 10n ** 6n, max: UNIT / 10n ** 6n },
49
+ };
50
+ for (const [exponent, borrowing, funding] of [
51
+ [UNIT / 2n, 2828427123200n, 33333333316666n],
52
+ [(UNIT * 3n) / 2n, 565685410479800n, 3333333328793333n],
53
+ [(UNIT * 7n) / 4n, 2127317204904000n, 10540925175750000n],
54
+ [UNIT, 40000000000000n, 333333333333333n],
55
+ [UNIT * 2n, 8000000000000000n, 33333333333333333n],
56
+ ]) {
57
+ const market = {
58
+ ...base,
59
+ primary: [500000000000n, 500000000000n],
60
+ openInterest: [100n * UNIT, 200n * UNIT],
61
+ openInterestInTokens: [100000000000n, 200000000000n],
62
+ skipBorrowingFeeForSmallerSide: true,
63
+ borrowingFeeOptimalUsageFactor: [0n, 0n],
64
+ borrowingFeeExponent: [exponent, exponent],
65
+ borrowingFeeFactor: [UNIT / 1000n, UNIT / 1000n],
66
+ funding: {
67
+ ...base.funding,
68
+ exponent,
69
+ factor: UNIT / 100000n,
70
+ increaseFactorPerSecond: 0n,
71
+ maxFactorPerSecond: UNIT,
72
+ },
73
+ };
74
+ expect(getGmsolBorrowingFactorPerSecond({ market, prices, side: GMSOL_LONG })).toBe(0n);
75
+ expect(getGmsolBorrowingFactorPerSecond({ market, prices, side: GMSOL_SHORT })).toBe(borrowing);
76
+ expect(getGmsolNextFunding(market, 0)).toEqual({ factor: funding, longsPayShorts: false });
77
+ }
78
+ });
79
+ it.each(fixture.marketViews)("$name", (view) => {
80
+ const market = parseBigints(view.market);
81
+ const prices = parseBigints(view.prices);
82
+ // get_market_status with both maximize flags true, then both false
83
+ for (const { maximize, borrowing, pnl, reserved, poolWithoutPnl } of view.status) {
84
+ for (const side of GMSOL_SIDES) {
85
+ expect(getGmsolBorrowingFactorPerSecond({ market, prices, side })).toBe(BigInt(borrowing[side]));
86
+ expect(getGmsolPendingPnl({ market, indexPrice: prices.index, side, maximize })).toBe(BigInt(pnl[side]));
87
+ expect(getGmsolReservedValue({ market, prices, side })).toBe(BigInt(reserved[side]));
88
+ expect(getGmsolPoolValueWithoutPnl({ market, prices, side, maximize })).toBe(BigInt(poolWithoutPnl[side]));
89
+ }
90
+ }
91
+ PRICE_VIEWS.forEach(([pnlFactorKind, maximize], i) => {
92
+ const poolValue = getGmsolPoolValue({ market, prices, now: view.now, pnlFactorKind, maximize });
93
+ expect(getGmPrice(poolValue, BigInt(view.supply))).toBe(BigInt(view.pricesExpected[i]));
94
+ });
95
+ // the view returns the stored funding factor, so the next one is checked against the SDK
96
+ const long = BigInt(view.sdkNextFunding.long);
97
+ const short = BigInt(view.sdkNextFunding.short);
98
+ const funding = getGmsolNextFunding(market, view.now);
99
+ expect(funding.factor).toBe(long > 0n ? long : short > 0n ? short : 0n);
100
+ if (funding.factor > 0n) {
101
+ expect(funding.longsPayShorts).toBe(long > 0n);
102
+ }
103
+ });
104
+ });
105
+ describe("getGmsolMarketStatus matches the gmsol SDK", () => {
106
+ it.each([
107
+ ["SOL/USD[USDC-USDC]", "longs pay"],
108
+ ["WTI/USD[USDC-USDC]", "shorts pay, the factor at its max"],
109
+ ["LINK/USD[WSOL-USDC]", "shorts pay, liquidity capped by max open interest"],
110
+ ["ETH/USD[WETH-WETH]", "a skew under $1 counts as none, so the min factor applies"],
111
+ ["ASTER/USD[USDT-USDT]", "no open interest, so no funding"],
112
+ ["NATGAS/USD[USDC-USDC]", "reserved value above the max reserve leaves no long liquidity"],
113
+ ["AAPL/USD[USDC-USDC]", "closed stock session"],
114
+ ])("%s: %s", (name) => {
115
+ const { market, prices, expected } = fixture.marketStatus.markets.find((entry) => entry.name === name);
116
+ const status = getGmsolMarketStatus({
117
+ market: parseBigints(market),
118
+ prices: parseBigints(prices),
119
+ now: fixture.marketStatus.now,
120
+ });
121
+ // the SDK gives each side's rate, positive for the side that pays
122
+ const long = BigInt(expected.fundingRatePerSecondForLong);
123
+ const short = BigInt(expected.fundingRatePerSecondForShort);
124
+ expect(status.fundingFactorPerSecond).toBe(long > 0n ? long : short > 0n ? short : 0n);
125
+ if (status.fundingFactorPerSecond > 0n) {
126
+ expect(status.longsPayShorts).toBe(long > 0n);
127
+ }
128
+ expect(status.liquidityForLong).toBe(BigInt(expected.liquidityForLong));
129
+ expect(status.liquidityForShort).toBe(BigInt(expected.liquidityForShort));
130
+ });
131
+ });
132
+ describe("getGmsolPendingPositionFees matches gmsol", () => {
133
+ it.each(fixture.positions.positions)("$picked", ({ market, position, expected }) => {
134
+ const { market: state, prices } = positionMarkets.get(market);
135
+ const fees = getGmsolPendingPositionFees({
136
+ market: parseBigints(state),
137
+ prices: parseBigints(prices),
138
+ now: fixture.positions.now,
139
+ position: parseBigints(position),
140
+ });
141
+ expect(fees).toEqual(parseBigints(expected));
142
+ });
143
+ });
144
+ function getBasisPointFactor(value) {
145
+ return (GMSOL_PRECISION / 10000n) * value;
146
+ }
147
+ function createDiscountConfig(byRank, referredUser = 0n) {
148
+ return { maxRank: 9, byRank: Array.from({ length: 16 }, (_, rank) => byRank[rank] ?? 0n), referredUser };
149
+ }
150
+ describe("gmsol order fee discount", () => {
151
+ // the cases of gmsol's own tests in crates/programs/src/utils/store.rs at 8af1e70c
152
+ it.each([
153
+ { name: "rank 0", store: createDiscountConfig({}), rank: 0, referred: false, factor: 0n },
154
+ {
155
+ name: "rank 1",
156
+ store: createDiscountConfig({ 1: getBasisPointFactor(250n) }),
157
+ rank: 1,
158
+ referred: false,
159
+ factor: getBasisPointFactor(250n),
160
+ },
161
+ {
162
+ name: "referred at rank 0",
163
+ store: createDiscountConfig({}, getBasisPointFactor(1000n)),
164
+ rank: 0,
165
+ referred: true,
166
+ factor: getBasisPointFactor(1000n),
167
+ },
168
+ {
169
+ name: "referred at rank 1",
170
+ store: createDiscountConfig({ 1: getBasisPointFactor(250n) }, getBasisPointFactor(1000n)),
171
+ rank: 1,
172
+ referred: true,
173
+ factor: getBasisPointFactor(1225n),
174
+ },
175
+ {
176
+ name: "max rank",
177
+ store: createDiscountConfig({ 9: getBasisPointFactor(2250n) }),
178
+ rank: 9,
179
+ referred: false,
180
+ factor: getBasisPointFactor(2250n),
181
+ },
182
+ {
183
+ name: "referred at rank 5",
184
+ store: createDiscountConfig({ 5: getBasisPointFactor(1250n) }, getBasisPointFactor(1000n)),
185
+ rank: 5,
186
+ referred: true,
187
+ factor: getBasisPointFactor(2125n),
188
+ },
189
+ {
190
+ name: "high discounts",
191
+ store: createDiscountConfig({ 0: getBasisPointFactor(5000n) }, getBasisPointFactor(4000n)),
192
+ rank: 0,
193
+ referred: true,
194
+ factor: getBasisPointFactor(7000n),
195
+ },
196
+ ])("$name", ({ store, rank, referred, factor }) => {
197
+ expect(getGmsolOrderFeeDiscountFactor({ config: store, rank, isReferred: referred })).toBe(factor);
198
+ });
199
+ it("rejects a rank above the max rank", () => {
200
+ expect(() => getGmsolOrderFeeDiscountFactor({ config: createDiscountConfig({}), rank: 10, isReferred: false })).toThrow("exceeds the max rank");
201
+ });
202
+ it("matches the native Store discounts", () => {
203
+ const config = parseBigints(fixture.feeDiscount.config);
204
+ for (const { rank, referred, factor } of fixture.feeDiscount.expected) {
205
+ expect(getGmsolOrderFeeDiscountFactor({ config, rank, isReferred: referred })).toBe(BigInt(factor));
206
+ }
207
+ });
208
+ });
@@ -0,0 +1,9 @@
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;
7
+ export const GMSOL_LONG = 0;
8
+ export const GMSOL_SHORT = 1;
9
+ export const GMSOL_SIDES = [GMSOL_LONG, GMSOL_SHORT];
@@ -0,0 +1,15 @@
1
+ import { GMSOL_PRECISION } from "./constants";
2
+ import { gmsolMath } from "./numbers";
3
+ export function getGmsolOrderFeeDiscountFactor({ config, rank, isReferred, }) {
4
+ const byRank = config.byRank[rank];
5
+ if (rank > config.maxRank || byRank === undefined) {
6
+ throw new Error(`rank ${rank} exceeds the max rank ${config.maxRank}`);
7
+ }
8
+ if (!isReferred) {
9
+ return byRank;
10
+ }
11
+ if (config.referredUser > GMSOL_PRECISION) {
12
+ throw new Error("the referred user discount is above 1");
13
+ }
14
+ return gmsolMath.toUnsigned(config.referredUser + gmsolMath.applyFactor(byRank, GMSOL_PRECISION - config.referredUser, "fee discount"), "fee discount");
15
+ }
@@ -0,0 +1,46 @@
1
+ import { bigMath } from "../bigmath";
2
+ import { expandDecimals, roundUpMagnitudeDivision } from "../numbers";
3
+ import { GMSOL_PRECISION_SCALE } from "./constants";
4
+ export { GMSOL_PRECISION, GMSOL_PRECISION_SCALE } from "./constants";
5
+ export { getGmsolOrderFeeDiscountFactor } from "./fees";
6
+ export { getGmsolBorrowingFactorPerSecond, getGmsolMarketStatus, getGmsolNextFunding, getGmsolNextPositionImpactPoolAmount, getGmsolPendingBorrowingFees, getGmsolPoolValue, } from "./markets";
7
+ export { getGmsolFractionalPower, gmsolMath } from "./numbers";
8
+ export { getGmsolPendingPositionFees } from "./positions";
9
+ export function getGmsolUsdAmount(value) {
10
+ return bigMath.mulDiv(value, 1n, GMSOL_PRECISION_SCALE) * GMSOL_PRECISION_SCALE;
11
+ }
12
+ export function getGmsolMidPrice(token) {
13
+ const scale = expandDecimals(1, token.decimals) * GMSOL_PRECISION_SCALE;
14
+ return bigMath.mulDiv(token.prices.minPrice + token.prices.maxPrice, 1n, 2n * scale) * scale;
15
+ }
16
+ /** The impact is settled in the entry size; it never becomes pending collateral. 0 means the order fills no tokens. */
17
+ export function getGmsolIncreaseSizeDeltaInTokens(p) {
18
+ const { baseSizeDeltaInTokens, priceImpactDeltaUsd, indexToken, isLong } = p;
19
+ const unit = expandDecimals(1, indexToken.decimals);
20
+ const impactAmount = priceImpactDeltaUsd > 0n
21
+ ? bigMath.mulDiv(priceImpactDeltaUsd, unit, indexToken.prices.maxPrice)
22
+ : roundUpMagnitudeDivision(priceImpactDeltaUsd * unit, indexToken.prices.minPrice);
23
+ return bigMath.max(baseSizeDeltaInTokens + (isLong ? impactAmount : -impactAmount), 0n);
24
+ }
25
+ /** Rent is a refundable deposit. The maximum keeper fee can be spent even on a cancelled execution. */
26
+ export function getGmsolExecutionFee(p) {
27
+ const { maxExecutionLamports, orderRentLamports, escrowRentLamports, solPrice } = p;
28
+ if ([maxExecutionLamports, orderRentLamports, escrowRentLamports, solPrice].some((value) => value < 0n)) {
29
+ throw new Error("Execution fee inputs must be nonnegative");
30
+ }
31
+ const keeperFeeLamports = bigMath.max(300000n, maxExecutionLamports);
32
+ const refundableRentLamports = orderRentLamports + escrowRentLamports;
33
+ return {
34
+ keeperFeeLamports,
35
+ keeperFeeUsd: bigMath.mulDiv(keeperFeeLamports, solPrice, 1000000000n),
36
+ refundableRentLamports,
37
+ refundableRentUsd: bigMath.mulDiv(refundableRentLamports, solPrice, 1000000000n),
38
+ requiredLamports: keeperFeeLamports + refundableRentLamports,
39
+ };
40
+ }
41
+ export function getGmsolExecutionFeeRefund(p) {
42
+ const spent = p.ownerCancelledBeforeExecution
43
+ ? 0n
44
+ : bigMath.min(p.keeperFeeLamports, bigMath.max(0n, p.executionLamportsSpent));
45
+ return { keeperCostLamports: spent, refundLamports: p.refundableRentLamports + p.keeperFeeLamports - spent };
46
+ }
@@ -0,0 +1,193 @@
1
+ import { bigMath } from "../bigmath";
2
+ import { GMSOL_LONG, GMSOL_PRECISION, GMSOL_SHORT, GMSOL_SIDES } from "./constants";
3
+ import { gmsolMath } from "./numbers";
4
+ const MAX_PNL_FACTOR = {
5
+ maxAfterDeposit: ["maxPnlFactorForLongDeposit", "maxPnlFactorForShortDeposit"],
6
+ maxAfterWithdrawal: ["maxPnlFactorForLongWithdrawal", "maxPnlFactorForShortWithdrawal"],
7
+ maxForTrader: ["maxPnlFactorForLongTrader", "maxPnlFactorForShortTrader"],
8
+ };
9
+ function pickPrice(price, maximize) {
10
+ return maximize ? price.max : price.min;
11
+ }
12
+ function getSidePrice(prices, side) {
13
+ return side === GMSOL_LONG ? prices.long : prices.short;
14
+ }
15
+ function getOtherSide(side) {
16
+ return side === GMSOL_LONG ? GMSOL_SHORT : GMSOL_LONG;
17
+ }
18
+ export function getGmsolReservedValue({ market, prices, side, }) {
19
+ return side === GMSOL_LONG
20
+ ? gmsolMath.toUnsigned(market.openInterestInTokens[GMSOL_LONG] * prices.index.max, "reserved value")
21
+ : market.openInterest[GMSOL_SHORT];
22
+ }
23
+ export function getGmsolPoolValueWithoutPnl({ market, prices, side, maximize, }) {
24
+ return gmsolMath.toUnsigned(market.primary[side] * pickPrice(getSidePrice(prices, side), maximize), "pool value without pnl");
25
+ }
26
+ // maximizing values longs at the index ask and shorts at the bid
27
+ export function getGmsolPendingPnl({ market, indexPrice, side, maximize, }) {
28
+ const openInterest = market.openInterest[side];
29
+ const openInterestInTokens = market.openInterestInTokens[side];
30
+ if (openInterest === 0n && openInterestInTokens === 0n) {
31
+ return 0n;
32
+ }
33
+ const price = (side === GMSOL_LONG) !== maximize ? indexPrice.min : indexPrice.max;
34
+ const value = gmsolMath.toUnsigned(openInterestInTokens * price, "position value");
35
+ return gmsolMath.toSigned(side === GMSOL_LONG ? value - openInterest : openInterest - value, "pending pnl");
36
+ }
37
+ export function getGmsolBorrowingFactorPerSecond({ market, prices, side, }) {
38
+ const reserved = getGmsolReservedValue({ market, prices, side });
39
+ if (reserved === 0n) {
40
+ return 0n;
41
+ }
42
+ if (market.skipBorrowingFeeForSmallerSide && market.openInterest[side] < market.openInterest[getOtherSide(side)]) {
43
+ return 0n;
44
+ }
45
+ const poolValue = getGmsolPoolValueWithoutPnl({ market, prices, side, maximize: false });
46
+ if (poolValue === 0n) {
47
+ throw new Error("borrowing factor of an empty pool");
48
+ }
49
+ const optimal = market.borrowingFeeOptimalUsageFactor[side];
50
+ if (optimal === 0n) {
51
+ const reservedAfterExponent = gmsolMath.applyExponentFactor(reserved, market.borrowingFeeExponent[side], "borrowing");
52
+ const usage = gmsolMath.divToFactor(reservedAfterExponent, poolValue, "borrowing usage");
53
+ return gmsolMath.applyFactor(usage, market.borrowingFeeFactor[side], "borrowing factor");
54
+ }
55
+ let usage = gmsolMath.divToFactor(reserved, gmsolMath.applyFactor(poolValue, market.config.openInterestReserveFactor, "reservable pool value"), "reserve usage");
56
+ if (!market.ignoreOpenInterestForUsageFactor) {
57
+ const openInterestUsage = gmsolMath.divToFactor(market.openInterest[side], market.maxOpenInterest[side], "open interest usage");
58
+ usage = bigMath.max(usage, openInterestUsage);
59
+ }
60
+ const base = market.borrowingFeeBaseFactor[side];
61
+ let factor = gmsolMath.applyFactor(usage, base, "borrowing factor");
62
+ if (usage > optimal && GMSOL_PRECISION > optimal) {
63
+ const above = market.borrowingFeeAboveOptimalUsageFactor[side];
64
+ const additional = gmsolMath.mulDiv(above > base ? above - base : 0n, usage - optimal, GMSOL_PRECISION - optimal, "borrowing factor");
65
+ factor = gmsolMath.toUnsigned(factor + additional, "borrowing factor");
66
+ }
67
+ return factor;
68
+ }
69
+ export function getGmsolNextCumulativeBorrowingFactor({ market, prices, now, side, }) {
70
+ const duration = BigInt(Math.max(0, now - market.borrowingClock));
71
+ const increase = gmsolMath.toUnsigned(getGmsolBorrowingFactorPerSecond({ market, prices, side }) * duration, "borrowing increase");
72
+ return gmsolMath.toUnsigned(market.borrowingFactor[side] + increase, "cumulative borrowing factor");
73
+ }
74
+ export function getGmsolPendingBorrowingFees({ market, prices, now, side, }) {
75
+ const cumulative = getGmsolNextCumulativeBorrowingFactor({ market, prices, now, side });
76
+ const pending = gmsolMath.applyFactor(market.openInterest[side], cumulative, "borrowing fees") - market.totalBorrowing[side];
77
+ if (pending < 0n) {
78
+ throw new Error("negative pending borrowing fees");
79
+ }
80
+ return pending;
81
+ }
82
+ export function getGmsolNextPositionImpactPoolAmount(market, now) {
83
+ const current = market.positionImpactPoolAmount;
84
+ const factor = market.config.positionImpactDistributeFactor;
85
+ const floor = market.config.minPositionImpactPoolAmount;
86
+ if (factor === 0n || current <= floor) {
87
+ return current;
88
+ }
89
+ const duration = BigInt(Math.max(0, now - market.priceImpactDistributionClock));
90
+ const distributed = gmsolMath.applyFactor(duration, factor, "impact distribution");
91
+ return current - bigMath.min(distributed, current - floor);
92
+ }
93
+ // signed, since losses can exceed the pool
94
+ export function getGmsolPoolValue({ market, prices, now, pnlFactorKind, maximize, }) {
95
+ const sideValues = GMSOL_SIDES.map((side) => getGmsolPoolValueWithoutPnl({ market, prices, side, maximize }));
96
+ const fees = gmsolMath.toUnsigned(GMSOL_SIDES.reduce((sum, side) => sum + getGmsolPendingBorrowingFees({ market, prices, now, side }), 0n), "borrowing fees");
97
+ let value = sideValues[GMSOL_LONG] +
98
+ sideValues[GMSOL_SHORT] +
99
+ gmsolMath.applyFactor(fees, gmsolMath.toUnsigned(GMSOL_PRECISION - market.config.borrowingFeeReceiverFactor, "pool share"), "pool borrowing fees");
100
+ for (const side of GMSOL_SIDES) {
101
+ const pnl = getGmsolPendingPnl({ market, indexPrice: prices.index, side, maximize: !maximize });
102
+ const cap = gmsolMath.applyFactor(sideValues[side], market.config[MAX_PNL_FACTOR[pnlFactorKind][side]], "pnl cap");
103
+ value -= bigMath.min(pnl, cap);
104
+ }
105
+ value -= gmsolMath.toUnsigned(getGmsolNextPositionImpactPoolAmount(market, now) * pickPrice(prices.index, !maximize), "impact pool value");
106
+ return gmsolMath.toSigned(value, "pool value");
107
+ }
108
+ // a port of the funding and liquidity parts of gmsol's MarketCalculations::status, with its rounding and overflow checks
109
+ function toSignedFactor(value) {
110
+ return gmsolMath.toSigned(value, "signed conversion");
111
+ }
112
+ function boundMagnitude(value, min, max) {
113
+ if (min > max) {
114
+ throw new Error("funding factor min is above max");
115
+ }
116
+ const magnitude = bigMath.abs(value);
117
+ if (magnitude < min) {
118
+ return value < 0n ? -toSignedFactor(min) : toSignedFactor(min);
119
+ }
120
+ if (magnitude > max) {
121
+ return value < 0n ? -toSignedFactor(max) : toSignedFactor(max);
122
+ }
123
+ return value;
124
+ }
125
+ function getFundingChange({ params, saved, long, short, diffFactor, }) {
126
+ const sameDirection = (saved > 0n && long > short) || (saved < 0n && long < short);
127
+ if (!sameDirection || diffFactor > params.thresholdForStableFunding) {
128
+ return "increase";
129
+ }
130
+ return diffFactor < params.thresholdForDecreaseFunding ? "decrease" : "none";
131
+ }
132
+ // gmsol next_funding_factor_per_second: the rate moves from the saved one over the time since the funding clock
133
+ function getNextFundingFactorPerSecond({ params, saved, duration, long, short, }) {
134
+ const diff = bigMath.abs(long - short);
135
+ if (diff === 0n && params.increaseFactorPerSecond === 0n) {
136
+ return { factor: 0n, longsPayShorts: true };
137
+ }
138
+ const diffFactor = gmsolMath.mulDiv(gmsolMath.applyExponentFactor(diff, params.exponent, "funding"), GMSOL_PRECISION, gmsolMath.toUnsigned(long + short, "total"), "diff");
139
+ if (params.increaseFactorPerSecond === 0n) {
140
+ const factor = gmsolMath.applyFactor(diffFactor, params.factor, "funding factor");
141
+ return {
142
+ factor: bigMath.min(factor, params.maxFactorPerSecond),
143
+ longsPayShorts: long > short,
144
+ };
145
+ }
146
+ const change = getFundingChange({ params, saved, long, short, diffFactor });
147
+ let next = saved;
148
+ if (change === "increase") {
149
+ const increase = gmsolMath.toUnsigned(gmsolMath.applyFactor(diffFactor, params.increaseFactorPerSecond, "increase") * duration, "increase");
150
+ next = gmsolMath.toSigned(saved + (long < short ? -toSignedFactor(increase) : toSignedFactor(increase)), "funding increase");
151
+ }
152
+ else if (change === "decrease" && saved !== 0n) {
153
+ const magnitude = bigMath.abs(saved);
154
+ const decrease = gmsolMath.toUnsigned(params.decreaseFactorPerSecond * duration, "decrease");
155
+ if (magnitude <= decrease) {
156
+ next = saved > 0n ? 1n : -1n;
157
+ }
158
+ else {
159
+ next = saved > 0n ? toSignedFactor(magnitude - decrease) : -toSignedFactor(magnitude - decrease);
160
+ }
161
+ }
162
+ const bounded = boundMagnitude(boundMagnitude(next, 0n, params.maxFactorPerSecond), params.minFactorPerSecond, params.maxFactorPerSecond);
163
+ return { factor: bigMath.abs(bounded), longsPayShorts: bounded > 0n };
164
+ }
165
+ function getLiquidity({ market, prices, side, }) {
166
+ const reserved = getGmsolReservedValue({ market, prices, side });
167
+ const reserveFactor = bigMath.min(market.config.reserveFactor, market.config.openInterestReserveFactor);
168
+ const maxLiquidity = bigMath.min(gmsolMath.applyFactor(getGmsolPoolValueWithoutPnl({ market, prices, side, maximize: false }), reserveFactor, "max reserve"), market.maxOpenInterest[side]);
169
+ return maxLiquidity > reserved ? maxLiquidity - reserved : 0n;
170
+ }
171
+ export function getGmsolNextFunding(market, now) {
172
+ const [long, short] = market.openInterest;
173
+ if (long === 0n || short === 0n) {
174
+ return { factor: 0n, longsPayShorts: true };
175
+ }
176
+ const duration = BigInt(Math.max(0, now - market.fundingClock));
177
+ return getNextFundingFactorPerSecond({
178
+ params: market.funding,
179
+ saved: market.fundingFactorPerSecond,
180
+ duration,
181
+ long,
182
+ short,
183
+ });
184
+ }
185
+ export function getGmsolMarketStatus({ market, prices, now, }) {
186
+ const funding = getGmsolNextFunding(market, now);
187
+ return {
188
+ fundingFactorPerSecond: funding.factor,
189
+ longsPayShorts: funding.longsPayShorts,
190
+ liquidityForLong: getLiquidity({ market, prices, side: GMSOL_LONG }),
191
+ liquidityForShort: getLiquidity({ market, prices, side: GMSOL_SHORT }),
192
+ };
193
+ }