@drift-labs/sdk 2.10.0-beta.1 → 2.10.0-beta.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.
- package/lib/accounts/bulkAccountLoader.d.ts +2 -1
- package/lib/accounts/pollingDriftClientAccountSubscriber.js +12 -3
- package/lib/accounts/types.d.ts +5 -4
- package/lib/adminClient.js +96 -34
- package/lib/config.d.ts +2 -2
- package/lib/constants/perpMarkets.d.ts +1 -1
- package/lib/constants/spotMarkets.d.ts +1 -1
- package/lib/dlob/DLOB.d.ts +4 -4
- package/lib/dlob/DLOBNode.d.ts +2 -2
- package/lib/dlob/DLOBOrders.d.ts +2 -2
- package/lib/dlob/NodeList.d.ts +1 -1
- package/lib/driftClient.d.ts +4 -3
- package/lib/driftClient.js +105 -64
- package/lib/driftClientConfig.d.ts +3 -3
- package/lib/events/fetchLogs.d.ts +2 -2
- package/lib/events/types.d.ts +13 -13
- package/lib/factory/bigNum.js +4 -4
- package/lib/idl/drift.json +1 -1
- package/lib/index.d.ts +1 -0
- package/lib/index.js +1 -0
- package/lib/math/amm.d.ts +1 -1
- package/lib/math/amm.js +15 -6
- package/lib/math/oracles.js +2 -2
- package/lib/math/repeg.d.ts +1 -1
- package/lib/math/repeg.js +46 -19
- package/lib/math/trade.d.ts +1 -1
- package/lib/oracles/types.d.ts +2 -2
- package/lib/serum/types.d.ts +1 -1
- package/lib/slot/SlotSubscriber.d.ts +1 -1
- package/lib/testClient.d.ts +8 -0
- package/lib/testClient.js +22 -0
- package/lib/tx/retryTxSender.d.ts +1 -1
- package/lib/tx/types.d.ts +1 -1
- package/lib/types.d.ts +43 -43
- package/lib/user.d.ts +1 -0
- package/lib/user.js +10 -6
- package/lib/userConfig.d.ts +2 -2
- package/lib/userMap/userMap.js +3 -0
- package/lib/userMap/userStatsMap.js +3 -0
- package/lib/userStatsConfig.d.ts +2 -2
- package/package.json +1 -1
- package/src/accounts/pollingDriftClientAccountSubscriber.ts +26 -3
- package/src/adminClient.ts +301 -169
- package/src/driftClient.ts +199 -118
- package/src/driftClientConfig.ts +1 -1
- package/src/idl/drift.json +1 -1
- package/src/index.ts +1 -0
- package/src/math/amm.ts +27 -12
- package/src/math/oracles.ts +6 -4
- package/src/math/repeg.ts +54 -26
- package/src/testClient.ts +40 -0
- package/src/user.ts +5 -0
- package/src/userMap/userMap.ts +2 -0
- package/src/userMap/userStatsMap.ts +2 -0
- package/src/assert/assert.js +0 -9
- package/src/examples/makeTradeExample.js +0 -157
- package/src/token/index.js +0 -38
- package/src/tx/types.js +0 -2
- package/src/tx/utils.js +0 -17
- package/src/util/computeUnits.js +0 -27
- package/src/util/getTokenAddress.js +0 -9
- package/src/util/promiseTimeout.js +0 -14
- package/src/util/tps.js +0 -27
package/src/driftClientConfig.ts
CHANGED
package/src/idl/drift.json
CHANGED
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,
|
|
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,
|
|
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.
|
|
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
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
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;
|
package/src/math/oracles.ts
CHANGED
|
@@ -94,8 +94,9 @@ export function calculateLiveOracleTwap(
|
|
|
94
94
|
oraclePriceData: OraclePriceData,
|
|
95
95
|
now: BN
|
|
96
96
|
): BN {
|
|
97
|
-
const sinceLastUpdate =
|
|
98
|
-
|
|
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 =
|
|
128
|
-
|
|
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(
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
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
|
|
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
|
-
(
|
|
172
|
-
(
|
|
203
|
+
(perPegCost.lt(ZERO) && pegChangeDirection.gt(ZERO)) ||
|
|
204
|
+
(perPegCost.gt(ZERO) && pegChangeDirection.lt(ZERO));
|
|
173
205
|
|
|
174
|
-
if (
|
|
206
|
+
if (perPegCost.eq(ZERO) || useTargetPeg) {
|
|
175
207
|
return targetPeg;
|
|
176
208
|
}
|
|
177
209
|
|
|
178
|
-
const
|
|
179
|
-
|
|
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
|
}
|
|
@@ -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
|
}
|
package/src/userMap/userMap.ts
CHANGED
package/src/assert/assert.js
DELETED
|
@@ -1,157 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
var __awaiter =
|
|
3
|
-
(this && this.__awaiter) ||
|
|
4
|
-
function (thisArg, _arguments, P, generator) {
|
|
5
|
-
function adopt(value) {
|
|
6
|
-
return value instanceof P
|
|
7
|
-
? value
|
|
8
|
-
: new P(function (resolve) {
|
|
9
|
-
resolve(value);
|
|
10
|
-
});
|
|
11
|
-
}
|
|
12
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
13
|
-
function fulfilled(value) {
|
|
14
|
-
try {
|
|
15
|
-
step(generator.next(value));
|
|
16
|
-
} catch (e) {
|
|
17
|
-
reject(e);
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
function rejected(value) {
|
|
21
|
-
try {
|
|
22
|
-
step(generator['throw'](value));
|
|
23
|
-
} catch (e) {
|
|
24
|
-
reject(e);
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
function step(result) {
|
|
28
|
-
result.done
|
|
29
|
-
? resolve(result.value)
|
|
30
|
-
: adopt(result.value).then(fulfilled, rejected);
|
|
31
|
-
}
|
|
32
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
33
|
-
});
|
|
34
|
-
};
|
|
35
|
-
Object.defineProperty(exports, '__esModule', { value: true });
|
|
36
|
-
exports.getTokenAddress = void 0;
|
|
37
|
-
const anchor_1 = require('@project-serum/anchor');
|
|
38
|
-
const __1 = require('..');
|
|
39
|
-
const spl_token_1 = require('@solana/spl-token');
|
|
40
|
-
const web3_js_1 = require('@solana/web3.js');
|
|
41
|
-
const __2 = require('..');
|
|
42
|
-
const banks_1 = require('../constants/spotMarkets');
|
|
43
|
-
const getTokenAddress = (mintAddress, userPubKey) => {
|
|
44
|
-
return spl_token_1.Token.getAssociatedTokenAddress(
|
|
45
|
-
new web3_js_1.PublicKey(`ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL`),
|
|
46
|
-
spl_token_1.TOKEN_PROGRAM_ID,
|
|
47
|
-
new web3_js_1.PublicKey(mintAddress),
|
|
48
|
-
new web3_js_1.PublicKey(userPubKey)
|
|
49
|
-
);
|
|
50
|
-
};
|
|
51
|
-
exports.getTokenAddress = getTokenAddress;
|
|
52
|
-
const main = () =>
|
|
53
|
-
__awaiter(void 0, void 0, void 0, function* () {
|
|
54
|
-
// Initialize Drift SDK
|
|
55
|
-
const sdkConfig = __2.initialize({ env: 'devnet' });
|
|
56
|
-
// Set up the Wallet and Provider
|
|
57
|
-
const privateKey = process.env.BOT_PRIVATE_KEY; // stored as an array string
|
|
58
|
-
const keypair = web3_js_1.Keypair.fromSecretKey(
|
|
59
|
-
Uint8Array.from(JSON.parse(privateKey))
|
|
60
|
-
);
|
|
61
|
-
const wallet = new __1.Wallet(keypair);
|
|
62
|
-
// Set up the Connection
|
|
63
|
-
const rpcAddress = process.env.RPC_ADDRESS; // can use: https://api.devnet.solana.com for devnet; https://api.mainnet-beta.solana.com for mainnet;
|
|
64
|
-
const connection = new web3_js_1.Connection(rpcAddress);
|
|
65
|
-
// Set up the Provider
|
|
66
|
-
const provider = new anchor_1.AnchorProvider(
|
|
67
|
-
connection,
|
|
68
|
-
wallet,
|
|
69
|
-
anchor_1.AnchorProvider.defaultOptions()
|
|
70
|
-
);
|
|
71
|
-
// Check SOL Balance
|
|
72
|
-
const lamportsBalance = yield connection.getBalance(wallet.publicKey);
|
|
73
|
-
console.log('SOL balance:', lamportsBalance / Math.pow(10, 9));
|
|
74
|
-
// Misc. other things to set up
|
|
75
|
-
const usdcTokenAddress = yield exports.getTokenAddress(
|
|
76
|
-
sdkConfig.USDC_MINT_ADDRESS,
|
|
77
|
-
wallet.publicKey.toString()
|
|
78
|
-
);
|
|
79
|
-
// Set up the Drift Clearing House
|
|
80
|
-
const clearingHousePublicKey = new web3_js_1.PublicKey(
|
|
81
|
-
sdkConfig.DRIFT_PROGRAM_ID
|
|
82
|
-
);
|
|
83
|
-
const clearingHouse = new __2.ClearingHouse({
|
|
84
|
-
connection,
|
|
85
|
-
wallet: provider.wallet,
|
|
86
|
-
programID: clearingHousePublicKey,
|
|
87
|
-
});
|
|
88
|
-
yield clearingHouse.subscribe();
|
|
89
|
-
// Set up Clearing House user client
|
|
90
|
-
const user = new __2.ClearingHouseUser({
|
|
91
|
-
clearingHouse,
|
|
92
|
-
userAccountPublicKey: yield clearingHouse.getUserAccountPublicKey(),
|
|
93
|
-
});
|
|
94
|
-
//// Check if clearing house account exists for the current wallet
|
|
95
|
-
const userAccountExists = yield user.exists();
|
|
96
|
-
if (!userAccountExists) {
|
|
97
|
-
//// Create a Clearing House account by Depositing some USDC ($10,000 in this case)
|
|
98
|
-
const depositAmount = new anchor_1.BN(10000).mul(__2.QUOTE_PRECISION);
|
|
99
|
-
yield clearingHouse.initializeUserAccountAndDepositCollateral(
|
|
100
|
-
depositAmount,
|
|
101
|
-
yield exports.getTokenAddress(
|
|
102
|
-
usdcTokenAddress.toString(),
|
|
103
|
-
wallet.publicKey.toString()
|
|
104
|
-
),
|
|
105
|
-
banks_1.SpotMarkets['devnet'][0].marketIndex
|
|
106
|
-
);
|
|
107
|
-
}
|
|
108
|
-
yield user.subscribe();
|
|
109
|
-
// Get current price
|
|
110
|
-
const solMarketInfo = sdkConfig.PERP_MARKETS.find(
|
|
111
|
-
(market) => market.baseAssetSymbol === 'SOL'
|
|
112
|
-
);
|
|
113
|
-
const currentMarketPrice = __2.calculateMarkPrice(
|
|
114
|
-
clearingHouse.getMarketAccount(solMarketInfo.marketIndex),
|
|
115
|
-
undefined
|
|
116
|
-
);
|
|
117
|
-
const formattedPrice = __2.convertToNumber(
|
|
118
|
-
currentMarketPrice,
|
|
119
|
-
__2.PRICE_PRECISION
|
|
120
|
-
);
|
|
121
|
-
console.log(`Current Market Price is $${formattedPrice}`);
|
|
122
|
-
// Estimate the slippage for a $5000 LONG trade
|
|
123
|
-
const solMarketAccount = clearingHouse.getMarketAccount(
|
|
124
|
-
solMarketInfo.marketIndex
|
|
125
|
-
);
|
|
126
|
-
const longAmount = new anchor_1.BN(5000).mul(__2.QUOTE_PRECISION);
|
|
127
|
-
const slippage = __2.convertToNumber(
|
|
128
|
-
__2.calculateTradeSlippage(
|
|
129
|
-
__2.PositionDirection.LONG,
|
|
130
|
-
longAmount,
|
|
131
|
-
solMarketAccount,
|
|
132
|
-
'quote',
|
|
133
|
-
undefined
|
|
134
|
-
)[0],
|
|
135
|
-
__2.PRICE_PRECISION
|
|
136
|
-
);
|
|
137
|
-
console.log(
|
|
138
|
-
`Slippage for a $5000 LONG on the SOL market would be $${slippage}`
|
|
139
|
-
);
|
|
140
|
-
// Make a $5000 LONG trade
|
|
141
|
-
yield clearingHouse.openPosition(
|
|
142
|
-
__2.PositionDirection.LONG,
|
|
143
|
-
longAmount,
|
|
144
|
-
solMarketInfo.marketIndex
|
|
145
|
-
);
|
|
146
|
-
console.log(`LONGED $5000 SOL`);
|
|
147
|
-
// Reduce the position by $2000
|
|
148
|
-
const reduceAmount = new anchor_1.BN(2000).mul(__2.QUOTE_PRECISION);
|
|
149
|
-
yield clearingHouse.openPosition(
|
|
150
|
-
__2.PositionDirection.SHORT,
|
|
151
|
-
reduceAmount,
|
|
152
|
-
solMarketInfo.marketIndex
|
|
153
|
-
);
|
|
154
|
-
// Close the rest of the position
|
|
155
|
-
yield clearingHouse.closePosition(solMarketInfo.marketIndex);
|
|
156
|
-
});
|
|
157
|
-
main();
|
package/src/token/index.js
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.parseTokenAccount = void 0;
|
|
4
|
-
const spl_token_1 = require("@solana/spl-token");
|
|
5
|
-
const web3_js_1 = require("@solana/web3.js");
|
|
6
|
-
function parseTokenAccount(data) {
|
|
7
|
-
const accountInfo = spl_token_1.AccountLayout.decode(data);
|
|
8
|
-
accountInfo.mint = new web3_js_1.PublicKey(accountInfo.mint);
|
|
9
|
-
accountInfo.owner = new web3_js_1.PublicKey(accountInfo.owner);
|
|
10
|
-
accountInfo.amount = spl_token_1.u64.fromBuffer(accountInfo.amount);
|
|
11
|
-
if (accountInfo.delegateOption === 0) {
|
|
12
|
-
accountInfo.delegate = null;
|
|
13
|
-
// eslint-disable-next-line new-cap
|
|
14
|
-
accountInfo.delegatedAmount = new spl_token_1.u64(0);
|
|
15
|
-
}
|
|
16
|
-
else {
|
|
17
|
-
accountInfo.delegate = new web3_js_1.PublicKey(accountInfo.delegate);
|
|
18
|
-
accountInfo.delegatedAmount = spl_token_1.u64.fromBuffer(accountInfo.delegatedAmount);
|
|
19
|
-
}
|
|
20
|
-
accountInfo.isInitialized = accountInfo.state !== 0;
|
|
21
|
-
accountInfo.isFrozen = accountInfo.state === 2;
|
|
22
|
-
if (accountInfo.isNativeOption === 1) {
|
|
23
|
-
accountInfo.rentExemptReserve = spl_token_1.u64.fromBuffer(accountInfo.isNative);
|
|
24
|
-
accountInfo.isNative = true;
|
|
25
|
-
}
|
|
26
|
-
else {
|
|
27
|
-
accountInfo.rentExemptReserve = null;
|
|
28
|
-
accountInfo.isNative = false;
|
|
29
|
-
}
|
|
30
|
-
if (accountInfo.closeAuthorityOption === 0) {
|
|
31
|
-
accountInfo.closeAuthority = null;
|
|
32
|
-
}
|
|
33
|
-
else {
|
|
34
|
-
accountInfo.closeAuthority = new web3_js_1.PublicKey(accountInfo.closeAuthority);
|
|
35
|
-
}
|
|
36
|
-
return accountInfo;
|
|
37
|
-
}
|
|
38
|
-
exports.parseTokenAccount = parseTokenAccount;
|
package/src/tx/types.js
DELETED
package/src/tx/utils.js
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.wrapInTx = void 0;
|
|
4
|
-
const web3_js_1 = require("@solana/web3.js");
|
|
5
|
-
const COMPUTE_UNITS_DEFAULT = 200000;
|
|
6
|
-
function wrapInTx(instruction, computeUnits = 600000 // TODO, requires less code change
|
|
7
|
-
) {
|
|
8
|
-
const tx = new web3_js_1.Transaction();
|
|
9
|
-
if (computeUnits != COMPUTE_UNITS_DEFAULT) {
|
|
10
|
-
tx.add(web3_js_1.ComputeBudgetProgram.requestUnits({
|
|
11
|
-
units: computeUnits,
|
|
12
|
-
additionalFee: 0,
|
|
13
|
-
}));
|
|
14
|
-
}
|
|
15
|
-
return tx.add(instruction);
|
|
16
|
-
}
|
|
17
|
-
exports.wrapInTx = wrapInTx;
|
package/src/util/computeUnits.js
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
-
});
|
|
10
|
-
};
|
|
11
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.findComputeUnitConsumption = void 0;
|
|
13
|
-
function findComputeUnitConsumption(programId, connection, txSignature, commitment = 'confirmed') {
|
|
14
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
15
|
-
const tx = yield connection.getTransaction(txSignature, { commitment });
|
|
16
|
-
const computeUnits = [];
|
|
17
|
-
const regex = new RegExp(`Program ${programId.toString()} consumed ([0-9]{0,6}) of ([0-9]{0,7}) compute units`);
|
|
18
|
-
tx.meta.logMessages.forEach((logMessage) => {
|
|
19
|
-
const match = logMessage.match(regex);
|
|
20
|
-
if (match && match[1]) {
|
|
21
|
-
computeUnits.push(match[1]);
|
|
22
|
-
}
|
|
23
|
-
});
|
|
24
|
-
return computeUnits;
|
|
25
|
-
});
|
|
26
|
-
}
|
|
27
|
-
exports.findComputeUnitConsumption = findComputeUnitConsumption;
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.getTokenAddress = void 0;
|
|
4
|
-
const spl_token_1 = require("@solana/spl-token");
|
|
5
|
-
const web3_js_1 = require("@solana/web3.js");
|
|
6
|
-
const getTokenAddress = (mintAddress, userPubKey) => {
|
|
7
|
-
return spl_token_1.Token.getAssociatedTokenAddress(spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID, spl_token_1.TOKEN_PROGRAM_ID, new web3_js_1.PublicKey(mintAddress), new web3_js_1.PublicKey(userPubKey));
|
|
8
|
-
};
|
|
9
|
-
exports.getTokenAddress = getTokenAddress;
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.promiseTimeout = void 0;
|
|
4
|
-
function promiseTimeout(promise, timeoutMs) {
|
|
5
|
-
let timeoutId;
|
|
6
|
-
const timeoutPromise = new Promise((resolve) => {
|
|
7
|
-
timeoutId = setTimeout(() => resolve(null), timeoutMs);
|
|
8
|
-
});
|
|
9
|
-
return Promise.race([promise, timeoutPromise]).then((result) => {
|
|
10
|
-
clearTimeout(timeoutId);
|
|
11
|
-
return result;
|
|
12
|
-
});
|
|
13
|
-
}
|
|
14
|
-
exports.promiseTimeout = promiseTimeout;
|
package/src/util/tps.js
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
-
});
|
|
10
|
-
};
|
|
11
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.estimateTps = void 0;
|
|
13
|
-
function estimateTps(programId, connection, failed) {
|
|
14
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
15
|
-
let signatures = yield connection.getSignaturesForAddress(programId, undefined, 'finalized');
|
|
16
|
-
if (failed) {
|
|
17
|
-
signatures = signatures.filter((signature) => signature.err);
|
|
18
|
-
}
|
|
19
|
-
const numberOfSignatures = signatures.length;
|
|
20
|
-
if (numberOfSignatures === 0) {
|
|
21
|
-
return 0;
|
|
22
|
-
}
|
|
23
|
-
return (numberOfSignatures /
|
|
24
|
-
(signatures[0].blockTime - signatures[numberOfSignatures - 1].blockTime));
|
|
25
|
-
});
|
|
26
|
-
}
|
|
27
|
-
exports.estimateTps = estimateTps;
|