@drift-labs/sdk 2.10.0-beta.0 → 2.10.0-beta.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.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.10.0-beta.0",
2
+ "version": "2.10.0-beta.2",
3
3
  "name": "drift",
4
4
  "instructions": [
5
5
  {
package/src/index.ts CHANGED
@@ -21,6 +21,7 @@ export * from './accounts/pollingUserStatsAccountSubscriber';
21
21
  export * from './accounts/types';
22
22
  export * from './addresses/pda';
23
23
  export * from './adminClient';
24
+ export * from './testClient';
24
25
  export * from './user';
25
26
  export * from './userConfig';
26
27
  export * from './userStats';
package/src/math/amm.ts CHANGED
@@ -67,6 +67,8 @@ export function calculateOptimalPegAndBudget(
67
67
 
68
68
  const totalFeeLB = amm.totalExchangeFee.div(new BN(2));
69
69
  const budget = BN.max(ZERO, amm.totalFeeMinusDistributions.sub(totalFeeLB));
70
+
71
+ let checkLowerBound = true;
70
72
  if (budget.lt(prePegCost)) {
71
73
  const halfMaxPriceSpread = new BN(amm.maxSpread)
72
74
  .div(new BN(2))
@@ -94,11 +96,17 @@ export function calculateOptimalPegAndBudget(
94
96
  );
95
97
 
96
98
  newBudget = calculateRepegCost(amm, newOptimalPeg);
99
+ checkLowerBound = false;
100
+
97
101
  return [newTargetPrice, newOptimalPeg, newBudget, false];
102
+ } else if (
103
+ amm.totalFeeMinusDistributions.lt(amm.totalExchangeFee.div(new BN(2)))
104
+ ) {
105
+ checkLowerBound = false;
98
106
  }
99
107
  }
100
108
 
101
- return [targetPrice, newPeg, budget, true];
109
+ return [targetPrice, newPeg, budget, checkLowerBound];
102
110
  }
103
111
 
104
112
  export function calculateNewAmm(
@@ -108,12 +116,12 @@ export function calculateNewAmm(
108
116
  let pKNumer = new BN(1);
109
117
  let pKDenom = new BN(1);
110
118
 
111
- const [targetPrice, _newPeg, budget, checkLowerBound] =
119
+ const [targetPrice, _newPeg, budget, _checkLowerBound] =
112
120
  calculateOptimalPegAndBudget(amm, oraclePriceData);
113
121
  let prePegCost = calculateRepegCost(amm, _newPeg);
114
122
  let newPeg = _newPeg;
115
123
 
116
- if (prePegCost.gt(budget) && checkLowerBound) {
124
+ if (prePegCost.gte(budget) && prePegCost.gt(ZERO)) {
117
125
  [pKNumer, pKDenom] = [new BN(999), new BN(1000)];
118
126
  const deficitMadeup = calculateAdjustKCost(amm, pKNumer, pKDenom);
119
127
  assert(deficitMadeup.lte(new BN(0)));
@@ -136,7 +144,6 @@ export function calculateNewAmm(
136
144
  );
137
145
 
138
146
  newAmm.terminalQuoteAssetReserve = newQuoteAssetReserve;
139
-
140
147
  newPeg = calculateBudgetedPeg(newAmm, prePegCost, targetPrice);
141
148
  prePegCost = calculateRepegCost(newAmm, newPeg);
142
149
  }
@@ -148,7 +155,7 @@ export function calculateUpdatedAMM(
148
155
  amm: AMM,
149
156
  oraclePriceData: OraclePriceData
150
157
  ): AMM {
151
- if (amm.curveUpdateIntensity == 0) {
158
+ if (amm.curveUpdateIntensity == 0 || oraclePriceData === undefined) {
152
159
  return amm;
153
160
  }
154
161
  const newAmm = Object.assign({}, amm);
@@ -181,7 +188,6 @@ export function calculateUpdatedAMM(
181
188
  newAmm.totalFeeMinusDistributions.sub(prepegCost);
182
189
  newAmm.netRevenueSinceLastFunding =
183
190
  newAmm.netRevenueSinceLastFunding.sub(prepegCost);
184
-
185
191
  return newAmm;
186
192
  }
187
193
 
@@ -605,13 +611,22 @@ export function calculateSpreadBN(
605
611
  DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT
606
612
  )
607
613
  ) {
608
- const revenueRetreatAmount = Math.min(
609
- maxTargetSpread / 10,
610
- Math.floor(
611
- (baseSpread * netRevenueSinceLastFunding.abs().toNumber()) /
612
- DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT.abs().toNumber()
614
+ const maxRetreat = maxTargetSpread / 10;
615
+ let revenueRetreatAmount = maxRetreat;
616
+ if (
617
+ netRevenueSinceLastFunding.gte(
618
+ DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT.mul(new BN(1000))
613
619
  )
614
- );
620
+ ) {
621
+ revenueRetreatAmount = Math.min(
622
+ maxRetreat,
623
+ Math.floor(
624
+ (baseSpread * netRevenueSinceLastFunding.abs().toNumber()) /
625
+ DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT.abs().toNumber()
626
+ )
627
+ );
628
+ }
629
+
615
630
  const halfRevenueRetreatAmount = Math.floor(revenueRetreatAmount / 2);
616
631
 
617
632
  spreadTerms.revenueRetreatAmount = revenueRetreatAmount;
@@ -94,8 +94,9 @@ export function calculateLiveOracleTwap(
94
94
  oraclePriceData: OraclePriceData,
95
95
  now: BN
96
96
  ): BN {
97
- const sinceLastUpdate = now.sub(
98
- amm.historicalOracleData.lastOraclePriceTwapTs
97
+ const sinceLastUpdate = BN.max(
98
+ ONE,
99
+ now.sub(amm.historicalOracleData.lastOraclePriceTwapTs)
99
100
  );
100
101
  const sinceStart = BN.max(ZERO, amm.fundingPeriod.sub(sinceLastUpdate));
101
102
 
@@ -124,8 +125,9 @@ export function calculateLiveOracleStd(
124
125
  oraclePriceData: OraclePriceData,
125
126
  now: BN
126
127
  ): BN {
127
- const sinceLastUpdate = now.sub(
128
- amm.historicalOracleData.lastOraclePriceTwapTs
128
+ const sinceLastUpdate = BN.max(
129
+ ONE,
130
+ now.sub(amm.historicalOracleData.lastOraclePriceTwapTs)
129
131
  );
130
132
  const sinceStart = BN.max(ZERO, amm.fundingPeriod.sub(sinceLastUpdate));
131
133
 
package/src/math/repeg.ts CHANGED
@@ -8,6 +8,8 @@ import {
8
8
  PRICE_DIV_PEG,
9
9
  QUOTE_PRECISION,
10
10
  ZERO,
11
+ ONE,
12
+ PERCENTAGE_PRECISION,
11
13
  } from '../constants/numericConstants';
12
14
  import { AMM } from '../types';
13
15
  /**
@@ -34,19 +36,51 @@ export function calculateAdjustKCost(
34
36
  const p = numerator.mul(PRICE_PRECISION).div(denomenator);
35
37
 
36
38
  const cost = quoteScale
39
+ .mul(PERCENTAGE_PRECISION)
40
+ .mul(PERCENTAGE_PRECISION)
37
41
  .div(x.add(d))
38
42
  .sub(
39
43
  quoteScale
40
44
  .mul(p)
45
+ .mul(PERCENTAGE_PRECISION)
46
+ .mul(PERCENTAGE_PRECISION)
41
47
  .div(PRICE_PRECISION)
42
48
  .div(x.mul(p).div(PRICE_PRECISION).add(d))
43
49
  )
50
+ .div(PERCENTAGE_PRECISION)
51
+ .div(PERCENTAGE_PRECISION)
44
52
  .div(AMM_TO_QUOTE_PRECISION_RATIO)
45
53
  .div(PEG_PRECISION);
46
54
 
47
55
  return cost.mul(new BN(-1));
48
56
  }
49
57
 
58
+ // /**
59
+ // * Helper function calculating adjust k cost
60
+ // * @param amm
61
+ // * @param numerator
62
+ // * @param denomenator
63
+ // * @returns cost : Precision QUOTE_ASSET_PRECISION
64
+ // */
65
+ // export function calculateAdjustKCost2(
66
+ // amm: AMM,
67
+ // numerator: BN,
68
+ // denomenator: BN
69
+ // ): BN {
70
+ // // const k = market.amm.sqrtK.mul(market.amm.sqrtK);
71
+ // const directionToClose = amm.baseAssetAmountWithAmm.gt(ZERO)
72
+ // ? PositionDirection.SHORT
73
+ // : PositionDirection.LONG;
74
+
75
+ // const [newQuoteAssetReserve, _newBaseAssetReserve] =
76
+ // calculateAmmReservesAfterSwap(
77
+ // amm,
78
+ // 'base',
79
+ // amm.baseAssetAmountWithAmm.abs(),
80
+ // getSwapDirection('base', directionToClose)
81
+ // );
82
+ // }
83
+
50
84
  /**
51
85
  * Helper function calculating adjust pegMultiplier (repeg) cost
52
86
  *
@@ -143,44 +177,38 @@ export function calculateBudgetedK(amm: AMM, cost: BN): [BN, BN] {
143
177
  return [numerator, denominator];
144
178
  }
145
179
 
146
- export function calculateBudgetedPeg(amm: AMM, cost: BN, targetPrice: BN): BN {
147
- // wolframalpha.com
148
- // (1/(x+d) - p/(x*p+d))*y*d*Q = C solve for p
149
- // p = (d(y*d*Q - C(x+d))) / (C*x(x+d) + y*y*d*Q)
180
+ export function calculateBudgetedPeg(
181
+ amm: AMM,
182
+ budget: BN,
183
+ targetPrice: BN
184
+ ): BN {
185
+ let perPegCost = amm.quoteAssetReserve
186
+ .sub(amm.terminalQuoteAssetReserve)
187
+ .div(AMM_RESERVE_PRECISION.div(PRICE_PRECISION));
188
+
189
+ if (perPegCost.gt(ZERO)) {
190
+ perPegCost = perPegCost.add(ONE);
191
+ } else if (perPegCost.lt(ZERO)) {
192
+ perPegCost = perPegCost.sub(ONE);
193
+ }
150
194
 
151
- // todo: assumes k = x * y
152
- // otherwise use: (y(1-p) + (kp^2/(x*p+d)) - k/(x+d)) * Q = C solve for p
153
195
  const targetPeg = targetPrice
154
196
  .mul(amm.baseAssetReserve)
155
197
  .div(amm.quoteAssetReserve)
156
198
  .div(PRICE_DIV_PEG);
157
199
 
158
- const k = amm.sqrtK.mul(amm.sqrtK);
159
- const x = amm.baseAssetReserve;
160
- const y = amm.quoteAssetReserve;
161
-
162
- const d = amm.baseAssetAmountWithAmm;
163
- const Q = amm.pegMultiplier;
164
-
165
- const C = cost.mul(new BN(-1));
166
-
167
- const deltaQuoteAssetReserves = y.sub(k.div(x.add(d)));
168
- const pegChangeDirection = targetPeg.sub(Q);
200
+ const pegChangeDirection = targetPeg.sub(amm.pegMultiplier);
169
201
 
170
202
  const useTargetPeg =
171
- (deltaQuoteAssetReserves.lt(ZERO) && pegChangeDirection.gt(ZERO)) ||
172
- (deltaQuoteAssetReserves.gt(ZERO) && pegChangeDirection.lt(ZERO));
203
+ (perPegCost.lt(ZERO) && pegChangeDirection.gt(ZERO)) ||
204
+ (perPegCost.gt(ZERO) && pegChangeDirection.lt(ZERO));
173
205
 
174
- if (deltaQuoteAssetReserves.eq(ZERO) || useTargetPeg) {
206
+ if (perPegCost.eq(ZERO) || useTargetPeg) {
175
207
  return targetPeg;
176
208
  }
177
209
 
178
- const deltaPegMultiplier = C.mul(PRICE_PRECISION).div(
179
- deltaQuoteAssetReserves.div(AMM_TO_QUOTE_PRECISION_RATIO)
180
- );
181
- const newPeg = Q.sub(
182
- deltaPegMultiplier.mul(PEG_PRECISION).div(PRICE_PRECISION)
183
- );
210
+ const budgetDeltaPeg = budget.mul(PEG_PRECISION).div(perPegCost);
211
+ const newPeg = BN.max(ONE, amm.pegMultiplier.add(budgetDeltaPeg));
184
212
 
185
213
  return newPeg;
186
214
  }
@@ -109,11 +109,7 @@ export function calculateAssetWeight(
109
109
  );
110
110
  break;
111
111
  case 'Maintenance':
112
- assetWeight = calculateSizeDiscountAssetWeight(
113
- sizeInAmmReservePrecision,
114
- new BN(spotMarket.imfFactor),
115
- new BN(spotMarket.maintenanceAssetWeight)
116
- );
112
+ assetWeight = new BN(spotMarket.maintenanceAssetWeight);
117
113
  break;
118
114
  default:
119
115
  assetWeight = new BN(spotMarket.initialAssetWeight);
@@ -0,0 +1,40 @@
1
+ import { AdminClient } from './adminClient';
2
+ import { ConfirmOptions, Signer, Transaction } from '@solana/web3.js';
3
+ import { TxSigAndSlot } from './tx/types';
4
+ import { PollingDriftClientAccountSubscriber } from './accounts/pollingDriftClientAccountSubscriber';
5
+ import { DriftClientConfig } from './driftClientConfig';
6
+
7
+ export class TestClient extends AdminClient {
8
+ public constructor(config: DriftClientConfig) {
9
+ if (config.accountSubscription.type !== 'polling') {
10
+ throw new Error('Test client must be polling');
11
+ }
12
+ super(config);
13
+ }
14
+
15
+ async sendTransaction(
16
+ tx: Transaction,
17
+ additionalSigners?: Array<Signer>,
18
+ opts?: ConfirmOptions,
19
+ preSigned?: boolean
20
+ ): Promise<TxSigAndSlot> {
21
+ const { txSig, slot } = await super.sendTransaction(
22
+ tx,
23
+ additionalSigners,
24
+ opts,
25
+ preSigned
26
+ );
27
+
28
+ let lastFetchedSlot = (
29
+ this.accountSubscriber as PollingDriftClientAccountSubscriber
30
+ ).accountLoader.mostRecentSlot;
31
+ while (lastFetchedSlot < slot) {
32
+ await this.fetchAccounts();
33
+ lastFetchedSlot = (
34
+ this.accountSubscriber as PollingDriftClientAccountSubscriber
35
+ ).accountLoader.mostRecentSlot;
36
+ }
37
+
38
+ return { txSig, slot };
39
+ }
40
+ }
package/src/user.ts CHANGED
@@ -124,6 +124,11 @@ export class User {
124
124
  return this.accountSubscriber.getUserAccountAndSlot().data;
125
125
  }
126
126
 
127
+ public async forceGetUserAccount(): Promise<UserAccount> {
128
+ await this.fetchAccounts();
129
+ return this.accountSubscriber.getUserAccountAndSlot().data;
130
+ }
131
+
127
132
  public getUserAccountAndSlot(): DataAndSlot<UserAccount> | undefined {
128
133
  return this.accountSubscriber.getUserAccountAndSlot();
129
134
  }