@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,152 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getGmsolPendingPositionFees = void 0;
4
+ const constants_1 = require("./constants");
5
+ const markets_1 = require("./markets");
6
+ const numbers_1 = require("./numbers");
7
+ // a port of gmsol's pending_borrowing_fee_value and pending_funding_fees (crates/model/src/position.rs at 8af1e70c) on the
8
+ // market advanced to `now` the way the store program's update_fees_state advances it before every order: the borrowing
9
+ // factors, then the funding amounts per size (next_funding_amount_per_size), with the same rounding and checks
10
+ // gmsol-programs' FUNDING_AMOUNT_PER_SIZE_ADJUSTMENT, which the amounts per size carry on top of the factor unit
11
+ const PER_SIZE_UNIT = 10n ** 10n * constants_1.GMSOL_PRECISION;
12
+ function getPerSide(getValue) {
13
+ return [getValue(constants_1.GMSOL_LONG), getValue(constants_1.GMSOL_SHORT)];
14
+ }
15
+ // gmsol's Prices::validate, which both state updates run first
16
+ function validatePrices(prices) {
17
+ for (const { min, max } of [prices.index, prices.long, prices.short]) {
18
+ if (min <= 0n || max <= 0n) {
19
+ throw new Error("invalid prices");
20
+ }
21
+ numbers_1.gmsolMath.toUnsigned(min + max, "prices");
22
+ }
23
+ }
24
+ // MarketMeta::token_side, so a single-token market's collateral is its long token
25
+ function getCollateralSide(market, token) {
26
+ if (token === market.longTokenMint) {
27
+ return constants_1.GMSOL_LONG;
28
+ }
29
+ if (token === market.shortTokenMint) {
30
+ return constants_1.GMSOL_SHORT;
31
+ }
32
+ throw new Error(`${token} is not a collateral token of ${market.name}`);
33
+ }
34
+ function getAmountPerSize({ value, openInterest, price, roundUp, }) {
35
+ if (value === 0n || openInterest === 0n) {
36
+ return 0n;
37
+ }
38
+ if (roundUp) {
39
+ return numbers_1.gmsolMath.roundUpDiv(numbers_1.gmsolMath.mulDivCeil(value, PER_SIZE_UNIT, openInterest, "funding per size"), price, "funding per size");
40
+ }
41
+ return numbers_1.gmsolMath.mulDiv(value, PER_SIZE_UNIT, openInterest, "funding per size") / price;
42
+ }
43
+ // a market's pools are pure exactly when its long and short token are one mint (Market::init); a pure pool keeps one
44
+ // balance that a delta for either collateral moves and that reads back split in half, the long side taking the odd unit
45
+ function addPerSize({ pool, delta, pure }) {
46
+ const long = numbers_1.gmsolMath.toSigned(delta[constants_1.GMSOL_LONG], "funding delta");
47
+ const short = numbers_1.gmsolMath.toSigned(delta[constants_1.GMSOL_SHORT], "funding delta");
48
+ if (!pure) {
49
+ return [
50
+ numbers_1.gmsolMath.toUnsigned(pool[constants_1.GMSOL_LONG] + long, "funding per size"),
51
+ numbers_1.gmsolMath.toUnsigned(pool[constants_1.GMSOL_SHORT] + short, "funding per size"),
52
+ ];
53
+ }
54
+ const balance = numbers_1.gmsolMath.toUnsigned(pool[constants_1.GMSOL_LONG] + pool[constants_1.GMSOL_SHORT] + long + short, "funding per size");
55
+ return [(balance + 1n) / 2n, balance / 2n];
56
+ }
57
+ function replaceSidePool({ pools, side, pool, }) {
58
+ return side === constants_1.GMSOL_LONG ? [pool, pools[constants_1.GMSOL_SHORT]] : [pools[constants_1.GMSOL_LONG], pool];
59
+ }
60
+ function getNextFundingPerSize({ market, prices, now, }) {
61
+ const current = { fee: market.fundingFeeAmountPerSize, claimable: market.claimableFundingAmountPerSize };
62
+ if (market.openInterest[constants_1.GMSOL_LONG] === 0n || market.openInterest[constants_1.GMSOL_SHORT] === 0n) {
63
+ return current;
64
+ }
65
+ const { factor, longsPayShorts } = (0, markets_1.getGmsolNextFunding)(market, now);
66
+ const payer = longsPayShorts ? constants_1.GMSOL_LONG : constants_1.GMSOL_SHORT;
67
+ const receiver = longsPayShorts ? constants_1.GMSOL_SHORT : constants_1.GMSOL_LONG;
68
+ const paying = market.openInterestByCollateral[payer];
69
+ const payerOpenInterest = market.openInterest[payer];
70
+ const duration = BigInt(Math.max(0, now - market.fundingClock));
71
+ const fundingValue = numbers_1.gmsolMath.applyFactor(payerOpenInterest, numbers_1.gmsolMath.toUnsigned(duration * factor, "funding factor"), "funding value");
72
+ const values = getPerSide((collateral) => numbers_1.gmsolMath.mulDiv(fundingValue, paying[collateral], payerOpenInterest, "funding value"));
73
+ const getPrice = (collateral) => (collateral === constants_1.GMSOL_LONG ? prices.long : prices.short).max;
74
+ const fee = getPerSide((collateral) => getAmountPerSize({
75
+ value: values[collateral],
76
+ openInterest: paying[collateral],
77
+ price: getPrice(collateral),
78
+ roundUp: true,
79
+ }));
80
+ const claimable = getPerSide((collateral) => getAmountPerSize({
81
+ value: values[collateral],
82
+ openInterest: market.openInterest[receiver],
83
+ price: getPrice(collateral),
84
+ roundUp: false,
85
+ }));
86
+ const pure = market.longTokenMint === market.shortTokenMint;
87
+ return {
88
+ fee: replaceSidePool({
89
+ pools: current.fee,
90
+ side: payer,
91
+ pool: addPerSize({ pool: current.fee[payer], delta: fee, pure }),
92
+ }),
93
+ claimable: replaceSidePool({
94
+ pools: current.claimable,
95
+ side: receiver,
96
+ pool: addPerSize({ pool: current.claimable[receiver], delta: claimable, pure }),
97
+ }),
98
+ };
99
+ }
100
+ function getFundingAmount({ latest, ofPosition, sizeInUsd, roundUp, what, }) {
101
+ const diff = latest - ofPosition;
102
+ if (diff < 0n) {
103
+ throw new Error(`the position's ${what} per size is ahead of the market's`);
104
+ }
105
+ return roundUp
106
+ ? numbers_1.gmsolMath.mulDivCeil(sizeInUsd, diff, PER_SIZE_UNIT, what)
107
+ : numbers_1.gmsolMath.mulDiv(sizeInUsd, diff, PER_SIZE_UNIT, what);
108
+ }
109
+ function getGmsolPendingPositionFees({ market, prices, now, position, }) {
110
+ if (position.store !== market.store || position.marketToken !== market.marketTokenMint) {
111
+ throw new Error(`the position is not in ${market.name}`);
112
+ }
113
+ const side = position.isLong ? constants_1.GMSOL_LONG : constants_1.GMSOL_SHORT;
114
+ const collateral = getCollateralSide(market, position.collateralToken);
115
+ validatePrices(prices);
116
+ const borrowingFactors = getPerSide((each) => {
117
+ const next = (0, markets_1.getGmsolNextCumulativeBorrowingFactor)({ market, prices, now, side: each });
118
+ numbers_1.gmsolMath.toSigned(next - market.borrowingFactor[each], "borrowing delta");
119
+ return next;
120
+ });
121
+ const funding = getNextFundingPerSize({ market, prices, now });
122
+ const borrowingDiff = borrowingFactors[side] - position.borrowingFactor;
123
+ if (borrowingDiff < 0n) {
124
+ throw new Error("the position's borrowing factor is ahead of the market's");
125
+ }
126
+ const size = position.sizeInUsd;
127
+ return {
128
+ borrowingFeeValue: numbers_1.gmsolMath.applyFactor(size, borrowingDiff, "borrowing fee value"),
129
+ fundingFeeAmount: getFundingAmount({
130
+ latest: funding.fee[side][collateral],
131
+ ofPosition: position.fundingFeeAmountPerSize,
132
+ sizeInUsd: size,
133
+ roundUp: true,
134
+ what: "fee",
135
+ }),
136
+ claimableLongTokenAmount: getFundingAmount({
137
+ latest: funding.claimable[side][constants_1.GMSOL_LONG],
138
+ ofPosition: position.longTokenClaimableFundingAmountPerSize,
139
+ sizeInUsd: size,
140
+ roundUp: false,
141
+ what: "claimable long token",
142
+ }),
143
+ claimableShortTokenAmount: getFundingAmount({
144
+ latest: funding.claimable[side][constants_1.GMSOL_SHORT],
145
+ ofPosition: position.shortTokenClaimableFundingAmountPerSize,
146
+ sizeInUsd: size,
147
+ roundUp: false,
148
+ what: "claimable short token",
149
+ }),
150
+ };
151
+ }
152
+ exports.getGmsolPendingPositionFees = getGmsolPendingPositionFees;