@gmx-io/sdk 2.9.2 → 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.
@@ -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
+ });
@@ -4,3 +4,6 @@ export const GMSOL_PRECISION_SCALE = PRECISION / GMSOL_PRECISION;
4
4
  export const GMSOL_MAX_UNSIGNED = (1n << 128n) - 1n;
5
5
  export const GMSOL_MAX_SIGNED = (1n << 127n) - 1n;
6
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
+ }
@@ -1,8 +1,11 @@
1
1
  import { bigMath } from "../bigmath";
2
2
  import { expandDecimals, roundUpMagnitudeDivision } from "../numbers";
3
3
  import { GMSOL_PRECISION_SCALE } from "./constants";
4
- export { GMSOL_PRECISION_SCALE } from "./constants";
5
- export { getGmsolFractionalPower } from "./numbers";
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";
6
9
  export function getGmsolUsdAmount(value) {
7
10
  return bigMath.mulDiv(value, 1n, GMSOL_PRECISION_SCALE) * GMSOL_PRECISION_SCALE;
8
11
  }
@@ -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
+ }
@@ -1,4 +1,4 @@
1
- import { GMSOL_PRECISION } from "./constants";
1
+ import { GMSOL_MAX_SIGNED, GMSOL_MAX_UNSIGNED, GMSOL_PRECISION } from "./constants";
2
2
  const MAX_COEFFICIENT = (1n << 96n) - 1n;
3
3
  const MAX_U64 = (1n << 64n) - 1n;
4
4
  const MAX_I64 = (1n << 63n) - 1n;
@@ -170,3 +170,57 @@ export function getGmsolFractionalPower(base20, exponent20) {
170
170
  }
171
171
  return result * INPUT_SCALE;
172
172
  }
173
+ // gmsol's checked u128 and i128 arithmetic on 20-decimal fixed point: a result outside the type is an error, never a wrapped value
174
+ export const gmsolMath = {
175
+ toUnsigned(value, what) {
176
+ if (value < 0n || value > GMSOL_MAX_UNSIGNED) {
177
+ throw new Error(`u128 overflow in ${what}`);
178
+ }
179
+ return value;
180
+ },
181
+ toSigned(value, what) {
182
+ if (value < -GMSOL_MAX_SIGNED - 1n || value > GMSOL_MAX_SIGNED) {
183
+ throw new Error(`i128 overflow in ${what}`);
184
+ }
185
+ return value;
186
+ },
187
+ mulDiv(a, b, divisor, what) {
188
+ if (divisor === 0n) {
189
+ throw new Error(`division by zero in ${what}`);
190
+ }
191
+ return gmsolMath.toUnsigned((a * b) / divisor, what);
192
+ },
193
+ mulDivCeil(a, b, divisor, what) {
194
+ if (divisor === 0n) {
195
+ throw new Error(`division by zero in ${what}`);
196
+ }
197
+ return gmsolMath.toUnsigned((a * b + divisor - 1n) / divisor, what);
198
+ },
199
+ // gmsol's checked_round_up_div, whose intermediate sum must fit in u128
200
+ roundUpDiv(value, divisor, what) {
201
+ return (gmsolMath.toUnsigned(value + divisor, what) - 1n) / divisor;
202
+ },
203
+ applyFactor(value, factor, what) {
204
+ return gmsolMath.mulDiv(value, factor, GMSOL_PRECISION, what);
205
+ },
206
+ divToFactor(value, divisor, what) {
207
+ return divisor === 0n ? 0n : gmsolMath.mulDiv(value, GMSOL_PRECISION, divisor, what);
208
+ },
209
+ // a value below one unit counts as none, as in GMX's applyExponentFactor
210
+ applyExponentFactor(value, exponent, what) {
211
+ if (value < GMSOL_PRECISION) {
212
+ return 0n;
213
+ }
214
+ if (value === GMSOL_PRECISION || exponent === 0n) {
215
+ return GMSOL_PRECISION;
216
+ }
217
+ if (exponent % GMSOL_PRECISION !== 0n) {
218
+ return gmsolMath.toUnsigned(getGmsolFractionalPower(value, exponent), what);
219
+ }
220
+ let result = GMSOL_PRECISION;
221
+ for (let i = 0n; i < exponent / GMSOL_PRECISION; i++) {
222
+ result = gmsolMath.mulDiv(result, value, GMSOL_PRECISION, what);
223
+ }
224
+ return result;
225
+ },
226
+ };
@@ -0,0 +1,148 @@
1
+ import { GMSOL_LONG, GMSOL_PRECISION, GMSOL_SHORT } from "./constants";
2
+ import { getGmsolNextCumulativeBorrowingFactor, getGmsolNextFunding } from "./markets";
3
+ import { gmsolMath } from "./numbers";
4
+ // a port of gmsol's pending_borrowing_fee_value and pending_funding_fees (crates/model/src/position.rs at 8af1e70c) on the
5
+ // market advanced to `now` the way the store program's update_fees_state advances it before every order: the borrowing
6
+ // factors, then the funding amounts per size (next_funding_amount_per_size), with the same rounding and checks
7
+ // gmsol-programs' FUNDING_AMOUNT_PER_SIZE_ADJUSTMENT, which the amounts per size carry on top of the factor unit
8
+ const PER_SIZE_UNIT = 10n ** 10n * GMSOL_PRECISION;
9
+ function getPerSide(getValue) {
10
+ return [getValue(GMSOL_LONG), getValue(GMSOL_SHORT)];
11
+ }
12
+ // gmsol's Prices::validate, which both state updates run first
13
+ function validatePrices(prices) {
14
+ for (const { min, max } of [prices.index, prices.long, prices.short]) {
15
+ if (min <= 0n || max <= 0n) {
16
+ throw new Error("invalid prices");
17
+ }
18
+ gmsolMath.toUnsigned(min + max, "prices");
19
+ }
20
+ }
21
+ // MarketMeta::token_side, so a single-token market's collateral is its long token
22
+ function getCollateralSide(market, token) {
23
+ if (token === market.longTokenMint) {
24
+ return GMSOL_LONG;
25
+ }
26
+ if (token === market.shortTokenMint) {
27
+ return GMSOL_SHORT;
28
+ }
29
+ throw new Error(`${token} is not a collateral token of ${market.name}`);
30
+ }
31
+ function getAmountPerSize({ value, openInterest, price, roundUp, }) {
32
+ if (value === 0n || openInterest === 0n) {
33
+ return 0n;
34
+ }
35
+ if (roundUp) {
36
+ return gmsolMath.roundUpDiv(gmsolMath.mulDivCeil(value, PER_SIZE_UNIT, openInterest, "funding per size"), price, "funding per size");
37
+ }
38
+ return gmsolMath.mulDiv(value, PER_SIZE_UNIT, openInterest, "funding per size") / price;
39
+ }
40
+ // a market's pools are pure exactly when its long and short token are one mint (Market::init); a pure pool keeps one
41
+ // balance that a delta for either collateral moves and that reads back split in half, the long side taking the odd unit
42
+ function addPerSize({ pool, delta, pure }) {
43
+ const long = gmsolMath.toSigned(delta[GMSOL_LONG], "funding delta");
44
+ const short = gmsolMath.toSigned(delta[GMSOL_SHORT], "funding delta");
45
+ if (!pure) {
46
+ return [
47
+ gmsolMath.toUnsigned(pool[GMSOL_LONG] + long, "funding per size"),
48
+ gmsolMath.toUnsigned(pool[GMSOL_SHORT] + short, "funding per size"),
49
+ ];
50
+ }
51
+ const balance = gmsolMath.toUnsigned(pool[GMSOL_LONG] + pool[GMSOL_SHORT] + long + short, "funding per size");
52
+ return [(balance + 1n) / 2n, balance / 2n];
53
+ }
54
+ function replaceSidePool({ pools, side, pool, }) {
55
+ return side === GMSOL_LONG ? [pool, pools[GMSOL_SHORT]] : [pools[GMSOL_LONG], pool];
56
+ }
57
+ function getNextFundingPerSize({ market, prices, now, }) {
58
+ const current = { fee: market.fundingFeeAmountPerSize, claimable: market.claimableFundingAmountPerSize };
59
+ if (market.openInterest[GMSOL_LONG] === 0n || market.openInterest[GMSOL_SHORT] === 0n) {
60
+ return current;
61
+ }
62
+ const { factor, longsPayShorts } = getGmsolNextFunding(market, now);
63
+ const payer = longsPayShorts ? GMSOL_LONG : GMSOL_SHORT;
64
+ const receiver = longsPayShorts ? GMSOL_SHORT : GMSOL_LONG;
65
+ const paying = market.openInterestByCollateral[payer];
66
+ const payerOpenInterest = market.openInterest[payer];
67
+ const duration = BigInt(Math.max(0, now - market.fundingClock));
68
+ const fundingValue = gmsolMath.applyFactor(payerOpenInterest, gmsolMath.toUnsigned(duration * factor, "funding factor"), "funding value");
69
+ const values = getPerSide((collateral) => gmsolMath.mulDiv(fundingValue, paying[collateral], payerOpenInterest, "funding value"));
70
+ const getPrice = (collateral) => (collateral === GMSOL_LONG ? prices.long : prices.short).max;
71
+ const fee = getPerSide((collateral) => getAmountPerSize({
72
+ value: values[collateral],
73
+ openInterest: paying[collateral],
74
+ price: getPrice(collateral),
75
+ roundUp: true,
76
+ }));
77
+ const claimable = getPerSide((collateral) => getAmountPerSize({
78
+ value: values[collateral],
79
+ openInterest: market.openInterest[receiver],
80
+ price: getPrice(collateral),
81
+ roundUp: false,
82
+ }));
83
+ const pure = market.longTokenMint === market.shortTokenMint;
84
+ return {
85
+ fee: replaceSidePool({
86
+ pools: current.fee,
87
+ side: payer,
88
+ pool: addPerSize({ pool: current.fee[payer], delta: fee, pure }),
89
+ }),
90
+ claimable: replaceSidePool({
91
+ pools: current.claimable,
92
+ side: receiver,
93
+ pool: addPerSize({ pool: current.claimable[receiver], delta: claimable, pure }),
94
+ }),
95
+ };
96
+ }
97
+ function getFundingAmount({ latest, ofPosition, sizeInUsd, roundUp, what, }) {
98
+ const diff = latest - ofPosition;
99
+ if (diff < 0n) {
100
+ throw new Error(`the position's ${what} per size is ahead of the market's`);
101
+ }
102
+ return roundUp
103
+ ? gmsolMath.mulDivCeil(sizeInUsd, diff, PER_SIZE_UNIT, what)
104
+ : gmsolMath.mulDiv(sizeInUsd, diff, PER_SIZE_UNIT, what);
105
+ }
106
+ export function getGmsolPendingPositionFees({ market, prices, now, position, }) {
107
+ if (position.store !== market.store || position.marketToken !== market.marketTokenMint) {
108
+ throw new Error(`the position is not in ${market.name}`);
109
+ }
110
+ const side = position.isLong ? GMSOL_LONG : GMSOL_SHORT;
111
+ const collateral = getCollateralSide(market, position.collateralToken);
112
+ validatePrices(prices);
113
+ const borrowingFactors = getPerSide((each) => {
114
+ const next = getGmsolNextCumulativeBorrowingFactor({ market, prices, now, side: each });
115
+ gmsolMath.toSigned(next - market.borrowingFactor[each], "borrowing delta");
116
+ return next;
117
+ });
118
+ const funding = getNextFundingPerSize({ market, prices, now });
119
+ const borrowingDiff = borrowingFactors[side] - position.borrowingFactor;
120
+ if (borrowingDiff < 0n) {
121
+ throw new Error("the position's borrowing factor is ahead of the market's");
122
+ }
123
+ const size = position.sizeInUsd;
124
+ return {
125
+ borrowingFeeValue: gmsolMath.applyFactor(size, borrowingDiff, "borrowing fee value"),
126
+ fundingFeeAmount: getFundingAmount({
127
+ latest: funding.fee[side][collateral],
128
+ ofPosition: position.fundingFeeAmountPerSize,
129
+ sizeInUsd: size,
130
+ roundUp: true,
131
+ what: "fee",
132
+ }),
133
+ claimableLongTokenAmount: getFundingAmount({
134
+ latest: funding.claimable[side][GMSOL_LONG],
135
+ ofPosition: position.longTokenClaimableFundingAmountPerSize,
136
+ sizeInUsd: size,
137
+ roundUp: false,
138
+ what: "claimable long token",
139
+ }),
140
+ claimableShortTokenAmount: getFundingAmount({
141
+ latest: funding.claimable[side][GMSOL_SHORT],
142
+ ofPosition: position.shortTokenClaimableFundingAmountPerSize,
143
+ sizeInUsd: size,
144
+ roundUp: false,
145
+ what: "claimable short token",
146
+ }),
147
+ };
148
+ }