@drift-labs/sdk 0.2.0-master.21 → 0.2.0-master.24

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 (88) hide show
  1. package/lib/accounts/types.d.ts +1 -0
  2. package/lib/addresses/pda.d.ts +3 -0
  3. package/lib/addresses/pda.js +23 -1
  4. package/lib/admin.d.ts +3 -0
  5. package/lib/admin.js +31 -0
  6. package/lib/clearingHouse.d.ts +9 -2
  7. package/lib/clearingHouse.js +132 -4
  8. package/lib/clearingHouseUser.js +5 -5
  9. package/lib/config.js +1 -1
  10. package/lib/constants/banks.d.ts +2 -0
  11. package/lib/constants/banks.js +9 -0
  12. package/lib/constants/numericConstants.d.ts +2 -0
  13. package/lib/constants/numericConstants.js +4 -1
  14. package/lib/events/sort.js +7 -10
  15. package/lib/events/types.d.ts +2 -1
  16. package/lib/events/types.js +1 -0
  17. package/lib/idl/clearing_house.json +1008 -147
  18. package/lib/index.d.ts +1 -0
  19. package/lib/index.js +1 -0
  20. package/lib/math/amm.js +2 -2
  21. package/lib/math/insurance.d.ts +4 -0
  22. package/lib/math/insurance.js +27 -0
  23. package/lib/math/margin.d.ts +1 -1
  24. package/lib/math/margin.js +5 -7
  25. package/lib/math/position.js +1 -1
  26. package/lib/types.d.ts +56 -20
  27. package/lib/types.js +0 -3
  28. package/package.json +1 -1
  29. package/src/addresses/marketAddresses.js +26 -0
  30. package/src/addresses/pda.ts +47 -0
  31. package/src/admin.ts +65 -0
  32. package/src/assert/assert.js +9 -0
  33. package/src/clearingHouse.ts +217 -9
  34. package/src/clearingHouseUser.ts +10 -6
  35. package/src/config.ts +1 -1
  36. package/src/constants/banks.js +42 -0
  37. package/src/constants/banks.ts +16 -0
  38. package/src/constants/markets.js +42 -0
  39. package/src/constants/numericConstants.js +41 -0
  40. package/src/constants/numericConstants.ts +4 -0
  41. package/src/events/eventList.js +77 -0
  42. package/src/events/sort.ts +10 -14
  43. package/src/events/txEventCache.js +71 -0
  44. package/src/events/types.ts +3 -0
  45. package/src/examples/makeTradeExample.js +80 -0
  46. package/src/factory/bigNum.js +390 -0
  47. package/src/factory/oracleClient.js +20 -0
  48. package/src/idl/clearing_house.json +1008 -147
  49. package/src/index.ts +1 -0
  50. package/src/math/amm.ts +2 -2
  51. package/src/math/auction.js +42 -0
  52. package/src/math/conversion.js +11 -0
  53. package/src/math/funding.js +248 -0
  54. package/src/math/insurance.ts +35 -0
  55. package/src/math/margin.ts +3 -10
  56. package/src/math/oracles.js +26 -0
  57. package/src/math/position.ts +2 -2
  58. package/src/math/repeg.js +128 -0
  59. package/src/math/state.js +15 -0
  60. package/src/math/trade.js +253 -0
  61. package/src/math/utils.js +26 -0
  62. package/src/math/utils.js.map +1 -0
  63. package/src/oracles/oracleClientCache.js +19 -0
  64. package/src/oracles/pythClient.js +46 -0
  65. package/src/oracles/quoteAssetOracleClient.js +32 -0
  66. package/src/oracles/switchboardClient.js +69 -0
  67. package/src/oracles/types.js +2 -0
  68. package/src/orderParams.js +20 -0
  69. package/src/slot/SlotSubscriber.js +39 -0
  70. package/src/token/index.js +38 -0
  71. package/src/tokenFaucet.js +189 -0
  72. package/src/tx/types.js +2 -0
  73. package/src/tx/utils.js +17 -0
  74. package/src/types.ts +64 -20
  75. package/src/userName.js +20 -0
  76. package/src/util/computeUnits.js +27 -0
  77. package/src/util/getTokenAddress.js +9 -0
  78. package/src/util/promiseTimeout.js +14 -0
  79. package/src/util/tps.js +27 -0
  80. package/src/wallet.js +35 -0
  81. package/my-script/.env +0 -7
  82. package/my-script/getUserStats.ts +0 -124
  83. package/my-script/multiConnections.ts +0 -137
  84. package/my-script/test-regex.ts +0 -11
  85. package/my-script/utils.ts +0 -52
  86. package/my-script/ww18NdhuLSQPCrHSx7V68eZJpe2y311heWeXJfSmP3Q.json +0 -1
  87. package/my-script/ww2z7N9TG1PLLUQGQF2VKzCFaPtQ5FBhRfeEAuy6c5C.json +0 -1
  88. package/my-script/ww3StJtTubhwssqAhvSSAc5ifCgKjzmF8hz7Gt2DmSa.json +0 -1
@@ -0,0 +1,189 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
22
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
23
+ return new (P || (P = Promise))(function (resolve, reject) {
24
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
25
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
26
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
27
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
28
+ });
29
+ };
30
+ var __importDefault = (this && this.__importDefault) || function (mod) {
31
+ return (mod && mod.__esModule) ? mod : { "default": mod };
32
+ };
33
+ Object.defineProperty(exports, "__esModule", { value: true });
34
+ exports.TokenFaucet = void 0;
35
+ const anchor = __importStar(require("@project-serum/anchor"));
36
+ const anchor_1 = require("@project-serum/anchor");
37
+ const spl_token_1 = require("@solana/spl-token");
38
+ const web3_js_1 = require("@solana/web3.js");
39
+ const token_faucet_json_1 = __importDefault(require("./idl/token_faucet.json"));
40
+ class TokenFaucet {
41
+ constructor(connection, wallet, programId, mint, opts) {
42
+ this.connection = connection;
43
+ this.wallet = wallet;
44
+ this.opts = opts || anchor_1.AnchorProvider.defaultOptions();
45
+ const provider = new anchor_1.AnchorProvider(connection, wallet, this.opts);
46
+ this.provider = provider;
47
+ this.program = new anchor_1.Program(token_faucet_json_1.default, programId, provider);
48
+ this.mint = mint;
49
+ }
50
+ getFaucetConfigPublicKeyAndNonce() {
51
+ return __awaiter(this, void 0, void 0, function* () {
52
+ return anchor.web3.PublicKey.findProgramAddress([
53
+ Buffer.from(anchor.utils.bytes.utf8.encode('faucet_config')),
54
+ this.mint.toBuffer(),
55
+ ], this.program.programId);
56
+ });
57
+ }
58
+ getMintAuthority() {
59
+ return __awaiter(this, void 0, void 0, function* () {
60
+ return (yield anchor.web3.PublicKey.findProgramAddress([
61
+ Buffer.from(anchor.utils.bytes.utf8.encode('mint_authority')),
62
+ this.mint.toBuffer(),
63
+ ], this.program.programId))[0];
64
+ });
65
+ }
66
+ getFaucetConfigPublicKey() {
67
+ return __awaiter(this, void 0, void 0, function* () {
68
+ return (yield this.getFaucetConfigPublicKeyAndNonce())[0];
69
+ });
70
+ }
71
+ initialize() {
72
+ return __awaiter(this, void 0, void 0, function* () {
73
+ const [faucetConfigPublicKey] = yield this.getFaucetConfigPublicKeyAndNonce();
74
+ return yield this.program.rpc.initialize({
75
+ accounts: {
76
+ faucetConfig: faucetConfigPublicKey,
77
+ admin: this.wallet.publicKey,
78
+ mintAccount: this.mint,
79
+ rent: web3_js_1.SYSVAR_RENT_PUBKEY,
80
+ systemProgram: anchor.web3.SystemProgram.programId,
81
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
82
+ },
83
+ });
84
+ });
85
+ }
86
+ fetchState() {
87
+ return __awaiter(this, void 0, void 0, function* () {
88
+ return yield this.program.account.faucetConfig.fetch(yield this.getFaucetConfigPublicKey());
89
+ });
90
+ }
91
+ mintToUserIx(userTokenAccount, amount) {
92
+ return __awaiter(this, void 0, void 0, function* () {
93
+ return this.program.instruction.mintToUser(amount, {
94
+ accounts: {
95
+ faucetConfig: yield this.getFaucetConfigPublicKey(),
96
+ mintAccount: this.mint,
97
+ userTokenAccount,
98
+ mintAuthority: yield this.getMintAuthority(),
99
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
100
+ },
101
+ });
102
+ });
103
+ }
104
+ mintToUser(userTokenAccount, amount) {
105
+ return __awaiter(this, void 0, void 0, function* () {
106
+ const mintIx = yield this.mintToUserIx(userTokenAccount, amount);
107
+ const tx = new web3_js_1.Transaction().add(mintIx);
108
+ const txSig = yield this.program.provider.sendAndConfirm(tx, [], this.opts);
109
+ return txSig;
110
+ });
111
+ }
112
+ transferMintAuthority() {
113
+ return __awaiter(this, void 0, void 0, function* () {
114
+ return yield this.program.rpc.transferMintAuthority({
115
+ accounts: {
116
+ faucetConfig: yield this.getFaucetConfigPublicKey(),
117
+ mintAccount: this.mint,
118
+ mintAuthority: yield this.getMintAuthority(),
119
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
120
+ admin: this.wallet.publicKey,
121
+ },
122
+ });
123
+ });
124
+ }
125
+ createAssociatedTokenAccountAndMintTo(userPublicKey, amount) {
126
+ return __awaiter(this, void 0, void 0, function* () {
127
+ const tx = new web3_js_1.Transaction();
128
+ const [associatedTokenPublicKey, createAssociatedAccountIx, mintToTx] = yield this.createAssociatedTokenAccountAndMintToInstructions(userPublicKey, amount);
129
+ let associatedTokenAccountExists = false;
130
+ try {
131
+ const assosciatedTokenAccount = yield this.connection.getAccountInfo(associatedTokenPublicKey);
132
+ associatedTokenAccountExists = !!assosciatedTokenAccount;
133
+ }
134
+ catch (e) {
135
+ // token account doesn't exist
136
+ associatedTokenAccountExists = false;
137
+ }
138
+ const skipAccountCreation = associatedTokenAccountExists;
139
+ if (!skipAccountCreation)
140
+ tx.add(createAssociatedAccountIx);
141
+ tx.add(mintToTx);
142
+ const txSig = yield this.program.provider.sendAndConfirm(tx, [], this.opts);
143
+ return [associatedTokenPublicKey, txSig];
144
+ });
145
+ }
146
+ createAssociatedTokenAccountAndMintToInstructions(userPublicKey, amount) {
147
+ return __awaiter(this, void 0, void 0, function* () {
148
+ const state = yield this.fetchState();
149
+ const associateTokenPublicKey = yield this.getAssosciatedMockUSDMintAddress({ userPubKey: userPublicKey });
150
+ const createAssociatedAccountIx = spl_token_1.Token.createAssociatedTokenAccountInstruction(spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID, spl_token_1.TOKEN_PROGRAM_ID, state.mint, associateTokenPublicKey, userPublicKey, this.wallet.publicKey);
151
+ const mintToIx = yield this.mintToUserIx(associateTokenPublicKey, amount);
152
+ return [associateTokenPublicKey, createAssociatedAccountIx, mintToIx];
153
+ });
154
+ }
155
+ getAssosciatedMockUSDMintAddress(props) {
156
+ return __awaiter(this, void 0, void 0, function* () {
157
+ const state = yield this.fetchState();
158
+ return spl_token_1.Token.getAssociatedTokenAddress(spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID, spl_token_1.TOKEN_PROGRAM_ID, state.mint, props.userPubKey);
159
+ });
160
+ }
161
+ getTokenAccountInfo(props) {
162
+ return __awaiter(this, void 0, void 0, function* () {
163
+ const assosciatedKey = yield this.getAssosciatedMockUSDMintAddress(props);
164
+ const state = yield this.fetchState();
165
+ const token = new spl_token_1.Token(this.connection, state.mint, spl_token_1.TOKEN_PROGRAM_ID,
166
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
167
+ // @ts-ignore
168
+ this.provider.payer);
169
+ return yield token.getAccountInfo(assosciatedKey);
170
+ });
171
+ }
172
+ subscribeToTokenAccount(props) {
173
+ return __awaiter(this, void 0, void 0, function* () {
174
+ try {
175
+ const tokenAccountKey = yield this.getAssosciatedMockUSDMintAddress(props);
176
+ props.callback(yield this.getTokenAccountInfo(props));
177
+ // Couldn't find a way to do it using anchor framework subscription, someone on serum discord recommended this way
178
+ this.connection.onAccountChange(tokenAccountKey, (_accountInfo /* accountInfo is a buffer which we don't know how to deserialize */) => __awaiter(this, void 0, void 0, function* () {
179
+ props.callback(yield this.getTokenAccountInfo(props));
180
+ }));
181
+ return true;
182
+ }
183
+ catch (e) {
184
+ return false;
185
+ }
186
+ });
187
+ }
188
+ }
189
+ exports.TokenFaucet = TokenFaucet;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,17 @@
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/types.ts CHANGED
@@ -58,9 +58,6 @@ export class OrderAction {
58
58
 
59
59
  export class OrderActionExplanation {
60
60
  static readonly NONE = { none: {} };
61
- static readonly BREACHED_MARGIN_REQUIREMENT = {
62
- breachedMarginRequirement: {},
63
- };
64
61
  static readonly ORACLE_PRICE_BREACHED_LIMIT_PRICE = {
65
62
  oraclePriceBreachedLimitPrice: {},
66
63
  };
@@ -156,10 +153,15 @@ export type FundingRateRecord = {
156
153
  recordId: BN;
157
154
  marketIndex: BN;
158
155
  fundingRate: BN;
156
+ fundingRateLong: BN;
157
+ fundingRateShort: BN;
159
158
  cumulativeFundingRateLong: BN;
160
159
  cumulativeFundingRateShort: BN;
161
160
  oraclePriceTwap: BN;
162
161
  markPriceTwap: BN;
162
+ periodRevenue: BN;
163
+ netBaseAssetAmount: BN;
164
+ netUnsettledLpBaseAssetAmount: BN;
163
165
  };
164
166
 
165
167
  export type FundingPaymentRecord = {
@@ -274,27 +276,41 @@ export type SettlePnlRecord = {
274
276
 
275
277
  export type OrderRecord = {
276
278
  ts: BN;
277
- taker: PublicKey;
278
- maker: PublicKey;
279
- takerOrder: Order;
280
- makerOrder: Order;
281
- takerPnl: BN;
282
- makerPnl: BN;
279
+ user: PublicKey;
280
+ order: Order;
281
+ };
282
+
283
+ export type OrderActionRecord = {
284
+ ts: BN;
283
285
  action: OrderAction;
284
286
  actionExplanation: OrderActionExplanation;
285
- filler: PublicKey;
286
- fillRecordId: BN;
287
287
  marketIndex: BN;
288
- baseAssetAmountFilled: BN;
289
- quoteAssetAmountFilled: BN;
290
- makerRebate: BN;
291
- takerFee: BN;
292
- fillerReward: BN;
293
- quoteAssetAmountSurplus: BN;
288
+ filler: PublicKey | null;
289
+ fillerReward: BN | null;
290
+ fillRecordId: BN | null;
291
+ referrer: PublicKey | null;
292
+ baseAssetAmountFilled: BN | null;
293
+ quoteAssetAmountFilled: BN | null;
294
+ takerPnl: BN | null;
295
+ makerPnl: BN | null;
296
+ takerFee: BN | null;
297
+ makerRebate: BN | null;
298
+ referrerReward: BN | null;
299
+ refereeDiscount: BN | null;
300
+ quoteAssetAmountSurplus: BN | null;
301
+ taker: PublicKey | null;
302
+ takerOrderId: BN | null;
303
+ takerOrderBaseAssetAmount: BN | null;
304
+ takerOrderBaseAssetAmountFilled: BN | null;
305
+ takerOrderQuoteAssetAmountFilled: BN | null;
306
+ takerOrderFee: BN | null;
307
+ maker: PublicKey | null;
308
+ makerOrderId: BN | null;
309
+ makerOrderBaseAssetAmount: BN | null;
310
+ makerOrderBaseAssetAmountFilled: BN | null;
311
+ makerOrderQuoteAssetAmountFilled: BN | null;
312
+ makerOrderFee: BN | null;
294
313
  oraclePrice: BN;
295
- referrer: PublicKey;
296
- referrerReward: BN;
297
- refereeDiscount: BN;
298
314
  };
299
315
 
300
316
  export type StateAccount = {
@@ -357,6 +373,20 @@ export type BankAccount = {
357
373
  vault: PublicKey;
358
374
  vaultAuthority: PublicKey;
359
375
  vaultAuthorityNonce: number;
376
+
377
+ insuranceFundVault: PublicKey;
378
+ insuranceFundVaultAuthority: PublicKey;
379
+ insuranceFundVaultAuthorityNonce: number;
380
+ insuranceWithdrawEscrowPeriod: BN;
381
+ revenuePool: PoolBalance;
382
+
383
+ totalIfShares: BN;
384
+ userIfShares: BN;
385
+
386
+ userIfFactor: BN;
387
+ totalIfFactor: BN;
388
+ liquidationIfFactor: BN;
389
+
360
390
  decimals: number;
361
391
  optimalUtilization: BN;
362
392
  optimalBorrowRate: BN;
@@ -439,6 +469,7 @@ export type AMM = {
439
469
  maxSpread: number;
440
470
  marketPosition: UserPosition;
441
471
  marketPositionPerLp: UserPosition;
472
+ ammJitIntensity: number;
442
473
  maxBaseAssetReserve: BN;
443
474
  minBaseAssetReserve: BN;
444
475
  };
@@ -478,6 +509,7 @@ export type UserStatsAccount = {
478
509
  isReferrer: boolean;
479
510
  totalReferrerReward: BN;
480
511
  authority: PublicKey;
512
+ quoteAssetInsuranceFundStake: BN;
481
513
  };
482
514
 
483
515
  export type UserAccount = {
@@ -664,3 +696,15 @@ export type OrderFillerRewardStructure = {
664
696
  };
665
697
 
666
698
  export type MarginCategory = 'Initial' | 'Maintenance';
699
+
700
+ export type InsuranceFundStake = {
701
+ bankIndex: BN;
702
+ authority: PublicKey;
703
+
704
+ ifShares: BN;
705
+ ifBase: BN;
706
+
707
+ lastWithdrawRequestShares: BN;
708
+ lastWithdrawRequestValue: BN;
709
+ lastWithdrawRequestTs: BN;
710
+ };
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.decodeName = exports.encodeName = exports.DEFAULT_USER_NAME = exports.MAX_NAME_LENGTH = void 0;
4
+ exports.MAX_NAME_LENGTH = 32;
5
+ exports.DEFAULT_USER_NAME = 'Main Account';
6
+ function encodeName(name) {
7
+ if (name.length > exports.MAX_NAME_LENGTH) {
8
+ throw Error(`User name (${name}) longer than 32 characters`);
9
+ }
10
+ const buffer = Buffer.alloc(32);
11
+ buffer.fill(name);
12
+ buffer.fill(' ', name.length);
13
+ return Array(...buffer);
14
+ }
15
+ exports.encodeName = encodeName;
16
+ function decodeName(bytes) {
17
+ const buffer = Buffer.from(bytes);
18
+ return buffer.toString('utf8').trim();
19
+ }
20
+ exports.decodeName = decodeName;
@@ -0,0 +1,27 @@
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;
@@ -0,0 +1,9 @@
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;
@@ -0,0 +1,14 @@
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;
@@ -0,0 +1,27 @@
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;
package/src/wallet.js ADDED
@@ -0,0 +1,35 @@
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.Wallet = void 0;
13
+ class Wallet {
14
+ constructor(payer) {
15
+ this.payer = payer;
16
+ }
17
+ signTransaction(tx) {
18
+ return __awaiter(this, void 0, void 0, function* () {
19
+ tx.partialSign(this.payer);
20
+ return tx;
21
+ });
22
+ }
23
+ signAllTransactions(txs) {
24
+ return __awaiter(this, void 0, void 0, function* () {
25
+ return txs.map((t) => {
26
+ t.partialSign(this.payer);
27
+ return t;
28
+ });
29
+ });
30
+ }
31
+ get publicKey() {
32
+ return this.payer.publicKey;
33
+ }
34
+ }
35
+ exports.Wallet = Wallet;
package/my-script/.env DELETED
@@ -1,7 +0,0 @@
1
- #ANCHOR_WALLET=/Users/ww/.config/solana/id.json
2
-
3
- #ANCHOR_WALLET=/Users/ww/.config/solana/bot2RzYy9oY5s3z71Yubo4MmRxyDBQP3qNNCqyqLcPp.json
4
-
5
- ANCHOR_WALLET=./ww18NdhuLSQPCrHSx7V68eZJpe2y311heWeXJfSmP3Q.json
6
- #ANCHOR_WALLET=./ww2z7N9TG1PLLUQGQF2VKzCFaPtQ5FBhRfeEAuy6c5C.json
7
- #ANCHOR_WALLET=./ww3StJtTubhwssqAhvSSAc5ifCgKjzmF8hz7Gt2DmSa.json
@@ -1,124 +0,0 @@
1
- import * as anchor from '@project-serum/anchor';
2
- // import { AnchorProvider } from '@project-serum/anchor';
3
- import { PublicKey, clusterApiUrl } from '@solana/web3.js';
4
-
5
- import {
6
- DriftEnv,
7
- initialize,
8
- BN,
9
- BulkAccountLoader,
10
- convertToNumber,
11
- calculateAdjustKCost,
12
- calculateBidAskPrice,
13
- EventSubscriber,
14
- UserAccount,
15
- DevnetBanks,
16
- DevnetMarkets,
17
- MARK_PRICE_PRECISION,
18
- BASE_PRECISION,
19
- QUOTE_PRECISION,
20
- ClearingHouse,
21
- getMarketOrderParams,
22
- PositionDirection,
23
- ZERO,
24
- } from '..';
25
- import { printUserStats } from './utils';
26
-
27
- require('dotenv').config();
28
- const driftEnv = process.env.ENV as DriftEnv;
29
-
30
- function sleep(ms) {
31
- return new Promise((resolve) => setTimeout(resolve, ms));
32
- }
33
-
34
- async function main(provider: anchor.AnchorProvider) {
35
- const connection = provider.connection;
36
- const config = initialize({ env: 'devnet' });
37
- const clearingHousePublicKey = new PublicKey(
38
- config.CLEARING_HOUSE_PROGRAM_ID
39
- );
40
-
41
- const bulkAccountLoader = new BulkAccountLoader(connection, 'confirmed', 1000);
42
- const clearingHouse = new ClearingHouse({
43
- connection,
44
- wallet: provider.wallet,
45
- programID: clearingHousePublicKey,
46
- env: 'devnet',
47
- // accountSubscription: {
48
- // type: 'websocket',
49
- // }
50
- accountSubscription: {
51
- type: 'polling',
52
- accountLoader: bulkAccountLoader,
53
- }
54
- });
55
-
56
- console.log(`clearingHouseProgramID: ${clearingHousePublicKey}`)
57
- console.log(`provider.wallet: ${provider.wallet.publicKey.toBase58()}`)
58
-
59
- const eventSubscriber = new EventSubscriber(connection, clearingHouse.program, {
60
- maxTx: 8192,
61
- maxEventsPerType: 4096,
62
- orderBy: 'blockchain',
63
- orderDir: 'desc',
64
- commitment: 'confirmed',
65
- logProviderConfig: {
66
- type: 'websocket',
67
- },
68
- });
69
-
70
- if (!(await clearingHouse.getUser().exists())) {
71
- console.error(`ClearingHouseUser for ${provider.wallet.publicKey} does not exist`);
72
- console.info(`Creating ClearingHouseUser for ${provider.wallet.publicKey}`);
73
- const [txSig] = await clearingHouse.initializeUserAccount();
74
- console.log(`Initialized user account in transaction: ${txSig}`);
75
- }
76
-
77
- if (!await clearingHouse.subscribe()) {
78
- throw new Error("fail clearingHouse.subscribe");
79
- }
80
- if (!await clearingHouse.accountSubscriber.subscribe()) {
81
- throw new Error("fail clearingHouse.accountSubscriber.subscribe");
82
- }
83
- if (!eventSubscriber.subscribe()) {
84
- throw new Error("fail eventSubscriber.subscribe");
85
- }
86
-
87
- const chUser = clearingHouse.getUser();
88
- const chUserAccount = clearingHouse.getUserAccount();
89
- console.log(`chUserAcc.authority: ${chUserAccount!.authority.toBase58()}`);
90
- console.log(` chUserAccount pubkey: ${chUser.userAccountPublicKey.toBase58()}`)
91
-
92
- const keyToSymbol = new Map<string, string>();
93
- const marketIndexToSymbol = new Map<number, string>();
94
- for (const market of DevnetMarkets) {
95
- keyToSymbol.set(market.oracle.toBase58(), market.baseAssetSymbol);
96
- marketIndexToSymbol.set(market.marketIndex.toNumber(), market.symbol);
97
- }
98
-
99
- const run = async () => {
100
- await clearingHouse.fetchAccounts();
101
- await chUser.fetchAccounts();
102
- printUserStats(chUserAccount!, marketIndexToSymbol);
103
- }
104
- await run();
105
- setInterval(run, 1000);
106
- }
107
-
108
-
109
- try {
110
- if (!process.env.ANCHOR_WALLET) {
111
- throw new Error('ANCHOR_WALLET must be set.');
112
- }
113
- main(
114
- anchor.AnchorProvider.local(clusterApiUrl("devnet"), {
115
- // anchor.AnchorProvider.local('https://devnet.genesysgo.net', {
116
- preflightCommitment: 'confirmed',
117
- skipPreflight: false,
118
- commitment: 'confirmed',
119
- })
120
- );
121
- // anchor.AnchorProvider.local('https://psytrbhymqlkfrhudd.dev.genesysgo.net:8899/');
122
- } catch (e) {
123
- console.error(e);
124
- }