@drift-labs/sdk 0.2.0-master.8 → 0.2.0-temp.1

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 (55) hide show
  1. package/lib/admin.d.ts +3 -3
  2. package/lib/admin.js +6 -6
  3. package/lib/clearingHouse.d.ts +15 -4
  4. package/lib/clearingHouse.js +200 -37
  5. package/lib/clearingHouseUser.d.ts +2 -2
  6. package/lib/clearingHouseUser.js +8 -17
  7. package/lib/config.js +1 -1
  8. package/lib/constants/banks.js +2 -3
  9. package/lib/constants/numericConstants.d.ts +1 -0
  10. package/lib/constants/numericConstants.js +2 -1
  11. package/lib/idl/clearing_house.json +484 -103
  12. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  13. package/lib/index.d.ts +1 -1
  14. package/lib/index.js +1 -1
  15. package/lib/orders.js +1 -1
  16. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +7 -5
  17. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +41 -40
  18. package/lib/types.d.ts +62 -13
  19. package/lib/types.js +12 -1
  20. package/lib/util/computeUnits.js +1 -1
  21. package/package.json +1 -1
  22. package/src/admin.js +517 -0
  23. package/src/admin.ts +7 -7
  24. package/src/clearingHouse.ts +335 -47
  25. package/src/clearingHouseConfig.js +2 -0
  26. package/src/clearingHouseUser.ts +12 -23
  27. package/src/clearingHouseUserConfig.js +2 -0
  28. package/src/config.js +67 -0
  29. package/src/config.ts +1 -1
  30. package/src/constants/banks.js +42 -0
  31. package/src/constants/banks.ts +2 -3
  32. package/src/constants/markets.js +42 -0
  33. package/src/constants/numericConstants.js +41 -0
  34. package/src/constants/numericConstants.ts +1 -0
  35. package/src/factory/bigNum.js +37 -11
  36. package/src/idl/clearing_house.json +484 -103
  37. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  38. package/src/index.js +1 -1
  39. package/src/index.ts +1 -1
  40. package/src/mockUSDCFaucet.js +276 -167
  41. package/src/orders.ts +2 -1
  42. package/src/tokenFaucet.js +189 -0
  43. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +48 -59
  44. package/src/types.js +12 -1
  45. package/src/types.ts +63 -13
  46. package/src/{accounts/fetch.js → util/computeUnits.js} +11 -13
  47. package/src/util/computeUnits.ts +1 -1
  48. package/src/util/getTokenAddress.js +9 -0
  49. package/src/addresses/pda.js +0 -104
  50. package/src/math/bankBalance.js +0 -75
  51. package/src/math/market.js +0 -57
  52. package/src/math/orders.js +0 -110
  53. package/src/math/position.js +0 -140
  54. package/src/orders.js +0 -134
  55. 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,78 +39,56 @@ 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
 
@@ -118,18 +96,29 @@ export class MockUSDCFaucet {
118
96
  userTokenAccount: PublicKey,
119
97
  amount: BN
120
98
  ): Promise<TransactionSignature> {
121
- const state: any = await this.fetchState();
122
99
  return await this.program.rpc.mintToUser(amount, {
123
100
  accounts: {
124
- mockUsdcFaucetState: await this.getMockUSDCFaucetStatePublicKey(),
125
- mintAccount: state.mint,
101
+ faucetConfig: await this.getFaucetConfigPublicKey(),
102
+ mintAccount: this.mint,
126
103
  userTokenAccount,
127
- mintAuthority: state.mintAuthority,
104
+ mintAuthority: await this.getMintAuthority(),
128
105
  tokenProgram: TOKEN_PROGRAM_ID,
129
106
  },
130
107
  });
131
108
  }
132
109
 
110
+ public async transferMintAuthority(): Promise<TransactionSignature> {
111
+ return await this.program.rpc.transferMintAuthority({
112
+ accounts: {
113
+ faucetConfig: await this.getFaucetConfigPublicKey(),
114
+ mintAccount: this.mint,
115
+ mintAuthority: await this.getMintAuthority(),
116
+ tokenProgram: TOKEN_PROGRAM_ID,
117
+ admin: this.wallet.publicKey,
118
+ },
119
+ });
120
+ }
121
+
133
122
  public async createAssociatedTokenAccountAndMintTo(
134
123
  userPublicKey: PublicKey,
135
124
  amount: BN
@@ -166,7 +155,7 @@ export class MockUSDCFaucet {
166
155
 
167
156
  const mintToIx = await this.program.instruction.mintToUser(amount, {
168
157
  accounts: {
169
- mockUsdcFaucetState: await this.getMockUSDCFaucetStatePublicKey(),
158
+ faucetConfig: await this.getFaucetConfigPublicKey(),
170
159
  mintAccount: state.mint,
171
160
  userTokenAccount: associateTokenPublicKey,
172
161
  mintAuthority: state.mintAuthority,
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
@@ -161,20 +161,67 @@ export type FundingPaymentRecord = {
161
161
 
162
162
  export type LiquidationRecord = {
163
163
  ts: BN;
164
- recordId: BN;
165
- userAuthority: PublicKey;
166
164
  user: PublicKey;
167
- partial: boolean;
168
- baseAssetValue: BN;
169
- baseAssetValueClosed: BN;
170
- liquidationFee: BN;
171
- feeToLiquidator: BN;
172
- feeToInsuranceFund: BN;
173
165
  liquidator: PublicKey;
166
+ liquidationType: LiquidationType;
167
+ marginRequirement: BN;
174
168
  totalCollateral: BN;
175
- collateral: BN;
176
- unrealizedPnl: BN;
177
- marginRatio: BN;
169
+ liquidatePerp: LiquidatePerpRecord;
170
+ liquidateBorrow: LiquidateBorrowRecord;
171
+ liquidateBorrowForPerpPnl: LiquidateBorrowForPerpPnlRecord;
172
+ liquidatePerpPnlForDeposit: LiquidatePerpPnlForDepositRecord;
173
+ };
174
+
175
+ export class LiquidationType {
176
+ static readonly LIQUIDATE_PERP = { liquidatePerp: {} };
177
+ static readonly LIQUIDATE_BORROW = { liquidateBorrow: {} };
178
+ static readonly LIQUIDATE_BORROW_FOR_PERP_PNL = {
179
+ liquidateBorrowForPerpPnl: {},
180
+ };
181
+ static readonly LIQUIDATE_PERP_PNL_FOR_DEPOSIT = {
182
+ liquidatePerpPnlForDeposit: {},
183
+ };
184
+ }
185
+
186
+ export type LiquidatePerpRecord = {
187
+ marketIndex: BN;
188
+ orderIds: BN[];
189
+ oraclePrice: BN;
190
+ baseAssetAmount: BN;
191
+ quoteAssetAmount: BN;
192
+ userPnl: BN;
193
+ liquidatorPnl: BN;
194
+ canceledOrdersFee: BN;
195
+ userOrderId: BN;
196
+ liquidatorOrderId: BN;
197
+ fillRecordId: BN;
198
+ };
199
+
200
+ export type LiquidateBorrowRecord = {
201
+ assetBankIndex: BN;
202
+ assetPrice: BN;
203
+ assetTransfer: BN;
204
+ liabilityBankIndex: BN;
205
+ liabilityPrice: BN;
206
+ liabilityTransfer: BN;
207
+ };
208
+
209
+ export type LiquidateBorrowForPerpPnlRecord = {
210
+ marketIndex: BN;
211
+ marketOraclePrice: BN;
212
+ pnlTransfer: BN;
213
+ liabilityBankIndex: BN;
214
+ liabilityPrice: BN;
215
+ liabilityTransfer: BN;
216
+ };
217
+
218
+ export type LiquidatePerpPnlForDepositRecord = {
219
+ marketIndex: BN;
220
+ marketOraclePrice: BN;
221
+ pnlTransfer: BN;
222
+ assetBankIndex: BN;
223
+ assetPrice: BN;
224
+ assetTransfer: BN;
178
225
  };
179
226
 
180
227
  export type OrderRecord = {
@@ -241,9 +288,9 @@ export type MarketAccount = {
241
288
  openInterest: BN;
242
289
  marginRatioInitial: number;
243
290
  marginRatioMaintenance: number;
244
- marginRatioPartial: number;
245
291
  nextFillRecordId: BN;
246
292
  pnlPool: PoolBalance;
293
+ liquidationFee: BN;
247
294
  };
248
295
 
249
296
  export type BankAccount = {
@@ -267,6 +314,7 @@ export type BankAccount = {
267
314
  maintenanceAssetWeight: BN;
268
315
  initialLiabilityWeight: BN;
269
316
  maintenanceLiabilityWeight: BN;
317
+ liquidationFee: BN;
270
318
  };
271
319
 
272
320
  export type PoolBalance = {
@@ -349,6 +397,7 @@ export type UserAccount = {
349
397
  };
350
398
  positions: UserPosition[];
351
399
  orders: Order[];
400
+ beingLiquidated: boolean;
352
401
  };
353
402
 
354
403
  export type UserBankBalance = {
@@ -493,6 +542,7 @@ export type FeeStructure = {
493
542
  makerRebateNumerator: BN;
494
543
  makerRebateDenominator: BN;
495
544
  fillerRewardStructure: OrderFillerRewardStructure;
545
+ cancelOrderFee: BN;
496
546
  };
497
547
 
498
548
  export type OracleGuardRails = {
@@ -514,4 +564,4 @@ export type OrderFillerRewardStructure = {
514
564
  timeBasedRewardLowerBound: BN;
515
565
  };
516
566
 
517
- export type MarginCategory = 'Initial' | 'Partial' | 'Maintenance';
567
+ 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);
@@ -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;
@@ -1,104 +0,0 @@
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
- Object.defineProperty(exports, "__esModule", { value: true });
31
- exports.getBankVaultAuthorityPublicKey = exports.getBankVaultPublicKey = exports.getBankPublicKey = exports.getMarketPublicKey = exports.getUserAccountPublicKeySync = exports.getUserAccountPublicKey = exports.getUserAccountPublicKeyAndNonce = exports.getClearingHouseStateAccountPublicKey = exports.getClearingHouseStateAccountPublicKeyAndNonce = void 0;
32
- const anchor = __importStar(require("@project-serum/anchor"));
33
- function getClearingHouseStateAccountPublicKeyAndNonce(programId) {
34
- return __awaiter(this, void 0, void 0, function* () {
35
- return anchor.web3.PublicKey.findProgramAddress([Buffer.from(anchor.utils.bytes.utf8.encode('clearing_house'))], programId);
36
- });
37
- }
38
- exports.getClearingHouseStateAccountPublicKeyAndNonce = getClearingHouseStateAccountPublicKeyAndNonce;
39
- function getClearingHouseStateAccountPublicKey(programId) {
40
- return __awaiter(this, void 0, void 0, function* () {
41
- return (yield getClearingHouseStateAccountPublicKeyAndNonce(programId))[0];
42
- });
43
- }
44
- exports.getClearingHouseStateAccountPublicKey = getClearingHouseStateAccountPublicKey;
45
- function getUserAccountPublicKeyAndNonce(programId, authority, userId = 0) {
46
- return __awaiter(this, void 0, void 0, function* () {
47
- return anchor.web3.PublicKey.findProgramAddress([
48
- Buffer.from(anchor.utils.bytes.utf8.encode('user')),
49
- authority.toBuffer(),
50
- Uint8Array.from([userId]),
51
- ], programId);
52
- });
53
- }
54
- exports.getUserAccountPublicKeyAndNonce = getUserAccountPublicKeyAndNonce;
55
- function getUserAccountPublicKey(programId, authority, userId = 0) {
56
- return __awaiter(this, void 0, void 0, function* () {
57
- return (yield getUserAccountPublicKeyAndNonce(programId, authority, userId))[0];
58
- });
59
- }
60
- exports.getUserAccountPublicKey = getUserAccountPublicKey;
61
- function getUserAccountPublicKeySync(programId, authority, userId = 0) {
62
- return anchor.web3.PublicKey.findProgramAddressSync([
63
- Buffer.from(anchor.utils.bytes.utf8.encode('user')),
64
- authority.toBuffer(),
65
- Uint8Array.from([userId]),
66
- ], programId)[0];
67
- }
68
- exports.getUserAccountPublicKeySync = getUserAccountPublicKeySync;
69
- function getMarketPublicKey(programId, marketIndex) {
70
- return __awaiter(this, void 0, void 0, function* () {
71
- return (yield anchor.web3.PublicKey.findProgramAddress([
72
- Buffer.from(anchor.utils.bytes.utf8.encode('market')),
73
- marketIndex.toArrayLike(Buffer, 'le', 8),
74
- ], programId))[0];
75
- });
76
- }
77
- exports.getMarketPublicKey = getMarketPublicKey;
78
- function getBankPublicKey(programId, bankIndex) {
79
- return __awaiter(this, void 0, void 0, function* () {
80
- return (yield anchor.web3.PublicKey.findProgramAddress([
81
- Buffer.from(anchor.utils.bytes.utf8.encode('bank')),
82
- bankIndex.toArrayLike(Buffer, 'le', 8),
83
- ], programId))[0];
84
- });
85
- }
86
- exports.getBankPublicKey = getBankPublicKey;
87
- function getBankVaultPublicKey(programId, bankIndex) {
88
- return __awaiter(this, void 0, void 0, function* () {
89
- return (yield anchor.web3.PublicKey.findProgramAddress([
90
- Buffer.from(anchor.utils.bytes.utf8.encode('bank_vault')),
91
- bankIndex.toArrayLike(Buffer, 'le', 8),
92
- ], programId))[0];
93
- });
94
- }
95
- exports.getBankVaultPublicKey = getBankVaultPublicKey;
96
- function getBankVaultAuthorityPublicKey(programId, bankIndex) {
97
- return __awaiter(this, void 0, void 0, function* () {
98
- return (yield anchor.web3.PublicKey.findProgramAddress([
99
- Buffer.from(anchor.utils.bytes.utf8.encode('bank_vault_authority')),
100
- bankIndex.toArrayLike(Buffer, 'le', 8),
101
- ], programId))[0];
102
- });
103
- }
104
- exports.getBankVaultAuthorityPublicKey = getBankVaultAuthorityPublicKey;