@drift-labs/sdk 0.2.0-master.10 → 0.2.0-master.13

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 (82) hide show
  1. package/lib/admin.d.ts +3 -3
  2. package/lib/admin.js +6 -6
  3. package/lib/clearingHouse.d.ts +22 -6
  4. package/lib/clearingHouse.js +357 -74
  5. package/lib/clearingHouseUser.d.ts +12 -17
  6. package/lib/clearingHouseUser.js +97 -88
  7. package/lib/config.js +1 -1
  8. package/lib/constants/banks.d.ts +2 -2
  9. package/lib/constants/banks.js +5 -4
  10. package/lib/constants/numericConstants.d.ts +3 -0
  11. package/lib/constants/numericConstants.js +4 -1
  12. package/lib/events/eventList.js +3 -0
  13. package/lib/events/types.d.ts +2 -1
  14. package/lib/factory/bigNum.d.ts +1 -0
  15. package/lib/factory/bigNum.js +37 -11
  16. package/lib/idl/clearing_house.json +611 -146
  17. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  18. package/lib/index.d.ts +2 -1
  19. package/lib/index.js +2 -1
  20. package/lib/math/amm.js +2 -2
  21. package/lib/math/bankBalance.d.ts +3 -1
  22. package/lib/math/bankBalance.js +54 -1
  23. package/lib/math/margin.d.ts +11 -0
  24. package/lib/math/margin.js +72 -0
  25. package/lib/math/market.d.ts +4 -1
  26. package/lib/math/market.js +35 -1
  27. package/lib/math/position.d.ts +8 -0
  28. package/lib/math/position.js +42 -12
  29. package/lib/orders.d.ts +1 -2
  30. package/lib/orders.js +2 -77
  31. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +8 -5
  32. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +63 -51
  33. package/lib/tx/retryTxSender.js +9 -2
  34. package/lib/types.d.ts +86 -16
  35. package/lib/types.js +18 -1
  36. package/lib/util/computeUnits.js +1 -1
  37. package/lib/util/getTokenAddress.d.ts +2 -0
  38. package/lib/util/getTokenAddress.js +9 -0
  39. package/package.json +1 -1
  40. package/src/admin.ts +7 -7
  41. package/src/clearingHouse.ts +636 -94
  42. package/src/clearingHouseConfig.js +2 -0
  43. package/src/clearingHouseUser.ts +219 -121
  44. package/src/clearingHouseUserConfig.js +2 -0
  45. package/src/config.ts +1 -1
  46. package/src/constants/banks.js +42 -0
  47. package/src/constants/banks.ts +7 -4
  48. package/src/constants/markets.js +42 -0
  49. package/src/constants/numericConstants.js +41 -0
  50. package/src/constants/numericConstants.ts +4 -0
  51. package/src/events/eventList.ts +3 -0
  52. package/src/events/types.ts +2 -0
  53. package/src/factory/bigNum.js +37 -11
  54. package/src/factory/bigNum.ts +43 -13
  55. package/src/idl/clearing_house.json +611 -146
  56. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  57. package/src/index.js +1 -1
  58. package/src/index.ts +2 -1
  59. package/src/math/amm.ts +8 -5
  60. package/src/math/bankBalance.ts +98 -1
  61. package/src/math/margin.ts +124 -0
  62. package/src/math/market.ts +66 -1
  63. package/src/math/position.ts +59 -9
  64. package/src/mockUSDCFaucet.js +276 -167
  65. package/src/orders.ts +4 -157
  66. package/src/tokenFaucet.js +189 -0
  67. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
  68. package/src/tx/retryTxSender.ts +11 -3
  69. package/src/types.js +12 -1
  70. package/src/types.ts +88 -16
  71. package/src/{accounts/fetch.js → util/computeUnits.js} +11 -13
  72. package/src/util/computeUnits.ts +1 -1
  73. package/src/util/getTokenAddress.js +9 -0
  74. package/src/util/getTokenAddress.ts +18 -0
  75. package/tests/bn/test.ts +2 -0
  76. package/src/addresses/pda.js +0 -104
  77. package/src/math/bankBalance.js +0 -75
  78. package/src/math/market.js +0 -57
  79. package/src/math/orders.js +0 -110
  80. package/src/math/position.js +0 -140
  81. package/src/orders.js +0 -134
  82. package/src/tx/retryTxSender.js +0 -188
@@ -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;
@@ -3,7 +3,6 @@ import { AnchorProvider, Idl, Program } from '@project-serum/anchor';
3
3
  import {
4
4
  AccountInfo,
5
5
  ASSOCIATED_TOKEN_PROGRAM_ID,
6
- MintLayout,
7
6
  Token,
8
7
  TOKEN_PROGRAM_ID,
9
8
  } from '@solana/spl-token';
@@ -11,27 +10,28 @@ import {
11
10
  ConfirmOptions,
12
11
  Connection,
13
12
  PublicKey,
14
- SystemProgram,
15
13
  SYSVAR_RENT_PUBKEY,
16
14
  Transaction,
17
15
  TransactionInstruction,
18
16
  TransactionSignature,
19
17
  } from '@solana/web3.js';
20
18
  import { BN } from '.';
21
- import mockUSDCFaucetIDL from './idl/mock_usdc_faucet.json';
19
+ import tokenFaucet from './idl/token_faucet.json';
22
20
  import { IWallet } from './types';
23
21
 
24
- export class MockUSDCFaucet {
22
+ export class TokenFaucet {
25
23
  connection: Connection;
26
24
  wallet: IWallet;
27
25
  public program: Program;
28
26
  provider: AnchorProvider;
27
+ mint: PublicKey;
29
28
  opts?: ConfirmOptions;
30
29
 
31
30
  public constructor(
32
31
  connection: Connection,
33
32
  wallet: IWallet,
34
33
  programId: PublicKey,
34
+ mint: PublicKey,
35
35
  opts?: ConfirmOptions
36
36
  ) {
37
37
  this.connection = connection;
@@ -39,93 +39,92 @@ export class MockUSDCFaucet {
39
39
  this.opts = opts || AnchorProvider.defaultOptions();
40
40
  const provider = new AnchorProvider(connection, wallet, this.opts);
41
41
  this.provider = provider;
42
- this.program = new Program(mockUSDCFaucetIDL as Idl, programId, provider);
42
+ this.program = new Program(tokenFaucet as Idl, programId, provider);
43
+ this.mint = mint;
43
44
  }
44
45
 
45
- public async getMockUSDCFaucetStatePublicKeyAndNonce(): Promise<
46
+ public async getFaucetConfigPublicKeyAndNonce(): Promise<
46
47
  [PublicKey, number]
47
48
  > {
48
49
  return anchor.web3.PublicKey.findProgramAddress(
49
- [Buffer.from(anchor.utils.bytes.utf8.encode('mock_usdc_faucet'))],
50
+ [
51
+ Buffer.from(anchor.utils.bytes.utf8.encode('faucet_config')),
52
+ this.mint.toBuffer(),
53
+ ],
50
54
  this.program.programId
51
55
  );
52
56
  }
53
57
 
54
- mockUSDCFaucetStatePublicKey?: PublicKey;
55
- public async getMockUSDCFaucetStatePublicKey(): Promise<PublicKey> {
56
- if (this.mockUSDCFaucetStatePublicKey) {
57
- return this.mockUSDCFaucetStatePublicKey;
58
- }
59
- this.mockUSDCFaucetStatePublicKey = (
60
- await this.getMockUSDCFaucetStatePublicKeyAndNonce()
58
+ public async getMintAuthority(): Promise<PublicKey> {
59
+ return (
60
+ await anchor.web3.PublicKey.findProgramAddress(
61
+ [
62
+ Buffer.from(anchor.utils.bytes.utf8.encode('mint_authority')),
63
+ this.mint.toBuffer(),
64
+ ],
65
+ this.program.programId
66
+ )
61
67
  )[0];
62
- return this.mockUSDCFaucetStatePublicKey;
63
68
  }
64
69
 
65
- public async initialize(): Promise<TransactionSignature> {
66
- const stateAccountRPCResponse = await this.connection.getParsedAccountInfo(
67
- await this.getMockUSDCFaucetStatePublicKey()
68
- );
69
- if (stateAccountRPCResponse.value !== null) {
70
- throw new Error('Faucet already initialized');
71
- }
72
-
73
- const fakeUSDCMint = anchor.web3.Keypair.generate();
74
- const createUSDCMintAccountIx = SystemProgram.createAccount({
75
- fromPubkey: this.wallet.publicKey,
76
- newAccountPubkey: fakeUSDCMint.publicKey,
77
- lamports: await Token.getMinBalanceRentForExemptMint(this.connection),
78
- space: MintLayout.span,
79
- programId: TOKEN_PROGRAM_ID,
80
- });
81
-
82
- const [mintAuthority, _mintAuthorityNonce] =
83
- await PublicKey.findProgramAddress(
84
- [fakeUSDCMint.publicKey.toBuffer()],
85
- this.program.programId
86
- );
87
-
88
- const initUSDCMintIx = Token.createInitMintInstruction(
89
- TOKEN_PROGRAM_ID,
90
- fakeUSDCMint.publicKey,
91
- 6,
92
- mintAuthority,
93
- null
94
- );
70
+ public async getFaucetConfigPublicKey(): Promise<PublicKey> {
71
+ return (await this.getFaucetConfigPublicKeyAndNonce())[0];
72
+ }
95
73
 
96
- const [mockUSDCFaucetStatePublicKey, mockUSDCFaucetStateNonce] =
97
- await this.getMockUSDCFaucetStatePublicKeyAndNonce();
98
- return await this.program.rpc.initialize(mockUSDCFaucetStateNonce, {
74
+ public async initialize(): Promise<TransactionSignature> {
75
+ const [faucetConfigPublicKey] =
76
+ await this.getFaucetConfigPublicKeyAndNonce();
77
+ return await this.program.rpc.initialize({
99
78
  accounts: {
100
- mockUsdcFaucetState: mockUSDCFaucetStatePublicKey,
79
+ faucetConfig: faucetConfigPublicKey,
101
80
  admin: this.wallet.publicKey,
102
- mintAccount: fakeUSDCMint.publicKey,
81
+ mintAccount: this.mint,
103
82
  rent: SYSVAR_RENT_PUBKEY,
104
83
  systemProgram: anchor.web3.SystemProgram.programId,
84
+ tokenProgram: TOKEN_PROGRAM_ID,
105
85
  },
106
- instructions: [createUSDCMintAccountIx, initUSDCMintIx],
107
- signers: [fakeUSDCMint],
108
86
  });
109
87
  }
110
88
 
111
89
  public async fetchState(): Promise<any> {
112
- return await this.program.account.mockUsdcFaucetState.fetch(
113
- await this.getMockUSDCFaucetStatePublicKey()
90
+ return await this.program.account.faucetConfig.fetch(
91
+ await this.getFaucetConfigPublicKey()
114
92
  );
115
93
  }
116
94
 
95
+ private async mintToUserIx(userTokenAccount: PublicKey, amount: BN) {
96
+ return this.program.instruction.mintToUser(amount, {
97
+ accounts: {
98
+ faucetConfig: await this.getFaucetConfigPublicKey(),
99
+ mintAccount: this.mint,
100
+ userTokenAccount,
101
+ mintAuthority: await this.getMintAuthority(),
102
+ tokenProgram: TOKEN_PROGRAM_ID,
103
+ },
104
+ });
105
+ }
106
+
117
107
  public async mintToUser(
118
108
  userTokenAccount: PublicKey,
119
109
  amount: BN
120
110
  ): Promise<TransactionSignature> {
121
- const state: any = await this.fetchState();
122
- return await this.program.rpc.mintToUser(amount, {
111
+ const mintIx = await this.mintToUserIx(userTokenAccount, amount);
112
+
113
+ const tx = new Transaction().add(mintIx);
114
+
115
+ const txSig = await this.program.provider.sendAndConfirm(tx, [], this.opts);
116
+
117
+ return txSig;
118
+ }
119
+
120
+ public async transferMintAuthority(): Promise<TransactionSignature> {
121
+ return await this.program.rpc.transferMintAuthority({
123
122
  accounts: {
124
- mockUsdcFaucetState: await this.getMockUSDCFaucetStatePublicKey(),
125
- mintAccount: state.mint,
126
- userTokenAccount,
127
- mintAuthority: state.mintAuthority,
123
+ faucetConfig: await this.getFaucetConfigPublicKey(),
124
+ mintAccount: this.mint,
125
+ mintAuthority: await this.getMintAuthority(),
128
126
  tokenProgram: TOKEN_PROGRAM_ID,
127
+ admin: this.wallet.publicKey,
129
128
  },
130
129
  });
131
130
  }
@@ -134,12 +133,33 @@ export class MockUSDCFaucet {
134
133
  userPublicKey: PublicKey,
135
134
  amount: BN
136
135
  ): Promise<[PublicKey, TransactionSignature]> {
136
+ const tx = new Transaction();
137
+
137
138
  const [associatedTokenPublicKey, createAssociatedAccountIx, mintToTx] =
138
139
  await this.createAssociatedTokenAccountAndMintToInstructions(
139
140
  userPublicKey,
140
141
  amount
141
142
  );
142
- const tx = new Transaction().add(createAssociatedAccountIx).add(mintToTx);
143
+
144
+ let associatedTokenAccountExists = false;
145
+
146
+ try {
147
+ const assosciatedTokenAccount = await this.connection.getAccountInfo(
148
+ associatedTokenPublicKey
149
+ );
150
+
151
+ associatedTokenAccountExists = !!assosciatedTokenAccount;
152
+ } catch (e) {
153
+ // token account doesn't exist
154
+ associatedTokenAccountExists = false;
155
+ }
156
+
157
+ const skipAccountCreation = associatedTokenAccountExists;
158
+
159
+ if (!skipAccountCreation) tx.add(createAssociatedAccountIx);
160
+
161
+ tx.add(mintToTx);
162
+
143
163
  const txSig = await this.program.provider.sendAndConfirm(tx, [], this.opts);
144
164
  return [associatedTokenPublicKey, txSig];
145
165
  }
@@ -164,15 +184,7 @@ export class MockUSDCFaucet {
164
184
  this.wallet.publicKey
165
185
  );
166
186
 
167
- const mintToIx = await this.program.instruction.mintToUser(amount, {
168
- accounts: {
169
- mockUsdcFaucetState: await this.getMockUSDCFaucetStatePublicKey(),
170
- mintAccount: state.mint,
171
- userTokenAccount: associateTokenPublicKey,
172
- mintAuthority: state.mintAuthority,
173
- tokenProgram: TOKEN_PROGRAM_ID,
174
- },
175
- });
187
+ const mintToIx = await this.mintToUserIx(associateTokenPublicKey, amount);
176
188
 
177
189
  return [associateTokenPublicKey, createAssociatedAccountIx, mintToIx];
178
190
  }
@@ -56,9 +56,17 @@ export class RetryTxSender implements TxSender {
56
56
  const rawTransaction = tx.serialize();
57
57
  const startTime = this.getTimestamp();
58
58
 
59
- const txid: TransactionSignature =
60
- await this.provider.connection.sendRawTransaction(rawTransaction, opts);
61
- this.sendToAdditionalConnections(rawTransaction, opts);
59
+ let txid: TransactionSignature;
60
+ try {
61
+ txid = await this.provider.connection.sendRawTransaction(
62
+ rawTransaction,
63
+ opts
64
+ );
65
+ this.sendToAdditionalConnections(rawTransaction, opts);
66
+ } catch (e) {
67
+ console.error(e);
68
+ throw e;
69
+ }
62
70
 
63
71
  let done = false;
64
72
  const resolveReference: ResolveReference = {
package/src/types.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DefaultOrderParams = exports.TradeSide = exports.isOneOfVariant = exports.isVariant = exports.OrderTriggerCondition = exports.OrderActionExplanation = exports.OrderAction = exports.OrderDiscountTier = exports.OrderStatus = exports.OrderType = exports.OracleSource = exports.DepositDirection = exports.PositionDirection = exports.BankBalanceType = exports.SwapDirection = void 0;
3
+ exports.DefaultOrderParams = exports.LiquidationType = exports.TradeSide = exports.isOneOfVariant = exports.isVariant = exports.OrderTriggerCondition = exports.OrderActionExplanation = exports.OrderAction = exports.OrderDiscountTier = exports.OrderStatus = exports.OrderType = exports.OracleSource = exports.DepositDirection = exports.PositionDirection = exports.BankBalanceType = exports.SwapDirection = void 0;
4
4
  const _1 = require(".");
5
5
  // # Utility Types / Enums / Constants
6
6
  class SwapDirection {
@@ -91,6 +91,17 @@ var TradeSide;
91
91
  TradeSide[TradeSide["Buy"] = 1] = "Buy";
92
92
  TradeSide[TradeSide["Sell"] = 2] = "Sell";
93
93
  })(TradeSide = exports.TradeSide || (exports.TradeSide = {}));
94
+ class LiquidationType {
95
+ }
96
+ exports.LiquidationType = LiquidationType;
97
+ LiquidationType.LIQUIDATE_PERP = { liquidatePerp: {} };
98
+ LiquidationType.LIQUIDATE_BORROW = { liquidateBorrow: {} };
99
+ LiquidationType.LIQUIDATE_BORROW_FOR_PERP_PNL = {
100
+ liquidateBorrowForPerpPnl: {},
101
+ };
102
+ LiquidationType.LIQUIDATE_PERP_PNL_FOR_DEPOSIT = {
103
+ liquidatePerpPnlForDeposit: {},
104
+ };
94
105
  exports.DefaultOrderParams = {
95
106
  orderType: OrderType.MARKET,
96
107
  userOrderId: 0,
package/src/types.ts CHANGED
@@ -67,6 +67,12 @@ export class OrderActionExplanation {
67
67
  static readonly MARKET_ORDER_FILLED_TO_LIMIT_PRICE = {
68
68
  marketOrderFilledToLimitPrice: {},
69
69
  };
70
+ static readonly CANCELED_FOR_LIQUIDATION = {
71
+ canceledForLiquidation: {},
72
+ };
73
+ static readonly MARKET_ORDER_AUCTION_EXPIRED = {
74
+ marketOrderAuctionExpired: {},
75
+ };
70
76
  }
71
77
 
72
78
  export class OrderTriggerCondition {
@@ -161,20 +167,78 @@ export type FundingPaymentRecord = {
161
167
 
162
168
  export type LiquidationRecord = {
163
169
  ts: BN;
164
- recordId: BN;
165
- userAuthority: PublicKey;
166
170
  user: PublicKey;
167
- partial: boolean;
168
- baseAssetValue: BN;
169
- baseAssetValueClosed: BN;
170
- liquidationFee: BN;
171
- feeToLiquidator: BN;
172
- feeToInsuranceFund: BN;
173
171
  liquidator: PublicKey;
172
+ liquidationType: LiquidationType;
173
+ marginRequirement: BN;
174
174
  totalCollateral: BN;
175
- collateral: BN;
176
- unrealizedPnl: BN;
177
- marginRatio: BN;
175
+ liquidationId: number;
176
+ liquidatePerp: LiquidatePerpRecord;
177
+ liquidateBorrow: LiquidateBorrowRecord;
178
+ liquidateBorrowForPerpPnl: LiquidateBorrowForPerpPnlRecord;
179
+ liquidatePerpPnlForDeposit: LiquidatePerpPnlForDepositRecord;
180
+ };
181
+
182
+ export class LiquidationType {
183
+ static readonly LIQUIDATE_PERP = { liquidatePerp: {} };
184
+ static readonly LIQUIDATE_BORROW = { liquidateBorrow: {} };
185
+ static readonly LIQUIDATE_BORROW_FOR_PERP_PNL = {
186
+ liquidateBorrowForPerpPnl: {},
187
+ };
188
+ static readonly LIQUIDATE_PERP_PNL_FOR_DEPOSIT = {
189
+ liquidatePerpPnlForDeposit: {},
190
+ };
191
+ }
192
+
193
+ export type LiquidatePerpRecord = {
194
+ marketIndex: BN;
195
+ orderIds: BN[];
196
+ oraclePrice: BN;
197
+ baseAssetAmount: BN;
198
+ quoteAssetAmount: BN;
199
+ userPnl: BN;
200
+ liquidatorPnl: BN;
201
+ canceledOrdersFee: BN;
202
+ userOrderId: BN;
203
+ liquidatorOrderId: BN;
204
+ fillRecordId: BN;
205
+ };
206
+
207
+ export type LiquidateBorrowRecord = {
208
+ assetBankIndex: BN;
209
+ assetPrice: BN;
210
+ assetTransfer: BN;
211
+ liabilityBankIndex: BN;
212
+ liabilityPrice: BN;
213
+ liabilityTransfer: BN;
214
+ };
215
+
216
+ export type LiquidateBorrowForPerpPnlRecord = {
217
+ marketIndex: BN;
218
+ marketOraclePrice: BN;
219
+ pnlTransfer: BN;
220
+ liabilityBankIndex: BN;
221
+ liabilityPrice: BN;
222
+ liabilityTransfer: BN;
223
+ };
224
+
225
+ export type LiquidatePerpPnlForDepositRecord = {
226
+ marketIndex: BN;
227
+ marketOraclePrice: BN;
228
+ pnlTransfer: BN;
229
+ assetBankIndex: BN;
230
+ assetPrice: BN;
231
+ assetTransfer: BN;
232
+ };
233
+
234
+ export type SettlePnlRecord = {
235
+ ts: BN;
236
+ marketIndex: BN;
237
+ pnl: BN;
238
+ baseAssetAmount: BN;
239
+ quoteAssetAmountAfter: BN;
240
+ quoteEntryamount: BN;
241
+ oraclePrice: BN;
178
242
  };
179
243
 
180
244
  export type OrderRecord = {
@@ -183,8 +247,8 @@ export type OrderRecord = {
183
247
  maker: PublicKey;
184
248
  takerOrder: Order;
185
249
  makerOrder: Order;
186
- takerUnsettledPnl: BN;
187
- makerUnsettledPnl: BN;
250
+ takerPnl: BN;
251
+ makerPnl: BN;
188
252
  action: OrderAction;
189
253
  actionExplanation: OrderActionExplanation;
190
254
  filler: PublicKey;
@@ -241,9 +305,13 @@ export type MarketAccount = {
241
305
  openInterest: BN;
242
306
  marginRatioInitial: number;
243
307
  marginRatioMaintenance: number;
244
- marginRatioPartial: number;
245
308
  nextFillRecordId: BN;
246
309
  pnlPool: PoolBalance;
310
+ liquidationFee: BN;
311
+ imfFactor: BN;
312
+ unsettledImfFactor: BN;
313
+ unsettledInitialAssetWeight: number;
314
+ unsettledMaintenanceAssetWeight: number;
247
315
  };
248
316
 
249
317
  export type BankAccount = {
@@ -267,6 +335,8 @@ export type BankAccount = {
267
335
  maintenanceAssetWeight: BN;
268
336
  initialLiabilityWeight: BN;
269
337
  maintenanceLiabilityWeight: BN;
338
+ liquidationFee: BN;
339
+ imfFactor: BN;
270
340
  };
271
341
 
272
342
  export type PoolBalance = {
@@ -328,7 +398,6 @@ export type UserPosition = {
328
398
  quoteAssetAmount: BN;
329
399
  quoteEntryAmount: BN;
330
400
  openOrders: BN;
331
- unsettledPnl: BN;
332
401
  openBids: BN;
333
402
  openAsks: BN;
334
403
  };
@@ -349,6 +418,8 @@ export type UserAccount = {
349
418
  };
350
419
  positions: UserPosition[];
351
420
  orders: Order[];
421
+ beingLiquidated: boolean;
422
+ nextLiquidationId: number;
352
423
  };
353
424
 
354
425
  export type UserBankBalance = {
@@ -493,6 +564,7 @@ export type FeeStructure = {
493
564
  makerRebateNumerator: BN;
494
565
  makerRebateDenominator: BN;
495
566
  fillerRewardStructure: OrderFillerRewardStructure;
567
+ cancelOrderFee: BN;
496
568
  };
497
569
 
498
570
  export type OracleGuardRails = {
@@ -514,4 +586,4 @@ export type OrderFillerRewardStructure = {
514
586
  timeBasedRewardLowerBound: BN;
515
587
  };
516
588
 
517
- export type MarginCategory = 'Initial' | 'Partial' | 'Maintenance';
589
+ export type MarginCategory = 'Initial' | 'Maintenance';
@@ -9,21 +9,19 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.fetchUserAccounts = void 0;
13
- const pda_1 = require("../addresses/pda");
14
- function fetchUserAccounts(connection, program, authority, limit = 8) {
12
+ exports.findComputeUnitConsumption = void 0;
13
+ function findComputeUnitConsumption(programId, connection, txSignature, commitment = 'confirmed') {
15
14
  return __awaiter(this, void 0, void 0, function* () {
16
- const userAccountPublicKeys = new Array();
17
- for (let i = 0; i < limit; i++) {
18
- userAccountPublicKeys.push(yield pda_1.getUserAccountPublicKey(program.programId, authority, i));
19
- }
20
- const accountInfos = yield connection.getMultipleAccountsInfo(userAccountPublicKeys, 'confirmed');
21
- return accountInfos.map((accountInfo) => {
22
- if (!accountInfo) {
23
- return undefined;
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]);
24
22
  }
25
- return program.account.user.coder.accounts.decode('User', accountInfo.data);
26
23
  });
24
+ return computeUnits;
27
25
  });
28
26
  }
29
- exports.fetchUserAccounts = fetchUserAccounts;
27
+ exports.findComputeUnitConsumption = findComputeUnitConsumption;
@@ -9,7 +9,7 @@ export async function findComputeUnitConsumption(
9
9
  const tx = await connection.getTransaction(txSignature, { commitment });
10
10
  const computeUnits = [];
11
11
  const regex = new RegExp(
12
- `Program ${programId.toString()} consumed ([0-9]{0,6}) of 200000 compute units`
12
+ `Program ${programId.toString()} consumed ([0-9]{0,6}) of ([0-9]{0,7}) compute units`
13
13
  );
14
14
  tx.meta.logMessages.forEach((logMessage) => {
15
15
  const match = logMessage.match(regex);