@drift-labs/sdk 0.2.0-master.25 → 0.2.0-master.27

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 (124) hide show
  1. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +14 -13
  2. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +30 -27
  3. package/lib/accounts/types.d.ts +9 -9
  4. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +15 -14
  5. package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +38 -34
  6. package/lib/addresses/pda.d.ts +7 -6
  7. package/lib/addresses/pda.js +31 -27
  8. package/lib/admin.d.ts +13 -7
  9. package/lib/admin.js +111 -44
  10. package/lib/clearingHouse.d.ts +71 -42
  11. package/lib/clearingHouse.js +767 -278
  12. package/lib/clearingHouseConfig.d.ts +2 -2
  13. package/lib/clearingHouseUser.d.ts +24 -22
  14. package/lib/clearingHouseUser.js +273 -177
  15. package/lib/config.d.ts +7 -7
  16. package/lib/config.js +21 -21
  17. package/lib/constants/numericConstants.d.ts +12 -12
  18. package/lib/constants/numericConstants.js +13 -13
  19. package/lib/constants/{markets.d.ts → perpMarkets.d.ts} +5 -5
  20. package/lib/constants/{markets.js → perpMarkets.js} +4 -4
  21. package/lib/constants/{banks.d.ts → spotMarkets.d.ts} +6 -6
  22. package/lib/constants/{banks.js → spotMarkets.js} +16 -16
  23. package/lib/dlob/DLOB.d.ts +73 -0
  24. package/lib/dlob/DLOB.js +557 -0
  25. package/lib/dlob/DLOBNode.d.ts +52 -0
  26. package/lib/dlob/DLOBNode.js +82 -0
  27. package/lib/dlob/NodeList.d.ts +26 -0
  28. package/lib/dlob/NodeList.js +138 -0
  29. package/lib/events/types.d.ts +2 -1
  30. package/lib/events/types.js +1 -0
  31. package/lib/examples/makeTradeExample.js +7 -7
  32. package/lib/idl/clearing_house.json +1152 -503
  33. package/lib/index.d.ts +10 -3
  34. package/lib/index.js +10 -3
  35. package/lib/math/amm.d.ts +2 -2
  36. package/lib/math/amm.js +1 -1
  37. package/lib/math/funding.d.ts +6 -6
  38. package/lib/math/funding.js +2 -1
  39. package/lib/math/margin.d.ts +4 -4
  40. package/lib/math/margin.js +18 -11
  41. package/lib/math/market.d.ts +11 -10
  42. package/lib/math/market.js +30 -7
  43. package/lib/math/oracles.d.ts +2 -1
  44. package/lib/math/oracles.js +11 -1
  45. package/lib/math/orders.d.ts +6 -6
  46. package/lib/math/orders.js +31 -16
  47. package/lib/math/position.d.ts +13 -13
  48. package/lib/math/position.js +19 -19
  49. package/lib/math/spotBalance.d.ts +22 -0
  50. package/lib/math/spotBalance.js +193 -0
  51. package/lib/math/spotMarket.d.ts +4 -0
  52. package/lib/math/spotMarket.js +8 -0
  53. package/lib/math/spotPosition.d.ts +6 -0
  54. package/lib/math/spotPosition.js +23 -0
  55. package/lib/math/state.js +2 -2
  56. package/lib/math/trade.d.ts +4 -4
  57. package/lib/orderParams.d.ts +4 -4
  58. package/lib/orderParams.js +12 -4
  59. package/lib/serum/serumSubscriber.d.ts +23 -0
  60. package/lib/serum/serumSubscriber.js +41 -0
  61. package/lib/serum/types.d.ts +11 -0
  62. package/lib/serum/types.js +2 -0
  63. package/lib/tx/retryTxSender.d.ts +1 -1
  64. package/lib/tx/retryTxSender.js +4 -2
  65. package/lib/tx/types.d.ts +1 -1
  66. package/lib/types.d.ts +148 -57
  67. package/lib/types.js +39 -11
  68. package/lib/userMap/userMap.d.ts +25 -0
  69. package/lib/userMap/userMap.js +73 -0
  70. package/lib/userMap/userStatsMap.d.ts +19 -0
  71. package/lib/userMap/userStatsMap.js +68 -0
  72. package/package.json +6 -3
  73. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +42 -38
  74. package/src/accounts/types.ts +12 -9
  75. package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +65 -52
  76. package/src/addresses/pda.ts +49 -44
  77. package/src/admin.ts +190 -55
  78. package/src/clearingHouse.ts +1092 -365
  79. package/src/clearingHouseConfig.ts +2 -2
  80. package/src/clearingHouseUser.ts +518 -255
  81. package/src/config.ts +30 -30
  82. package/src/constants/numericConstants.ts +17 -15
  83. package/src/constants/{markets.ts → perpMarkets.ts} +5 -5
  84. package/src/constants/{banks.ts → spotMarkets.ts} +19 -19
  85. package/src/dlob/DLOB.ts +884 -0
  86. package/src/dlob/DLOBNode.ts +163 -0
  87. package/src/dlob/NodeList.ts +185 -0
  88. package/src/events/types.ts +3 -0
  89. package/src/examples/makeTradeExample.js +152 -75
  90. package/src/examples/makeTradeExample.ts +10 -8
  91. package/src/idl/clearing_house.json +1152 -503
  92. package/src/index.ts +10 -3
  93. package/src/math/amm.ts +6 -3
  94. package/src/math/funding.ts +7 -7
  95. package/src/math/margin.ts +34 -23
  96. package/src/math/market.ts +72 -20
  97. package/src/math/oracles.ts +18 -1
  98. package/src/math/orders.ts +33 -25
  99. package/src/math/position.ts +31 -31
  100. package/src/math/spotBalance.ts +316 -0
  101. package/src/math/spotMarket.ts +9 -0
  102. package/src/math/spotPosition.ts +47 -0
  103. package/src/math/state.ts +2 -2
  104. package/src/math/trade.ts +4 -4
  105. package/src/orderParams.ts +16 -8
  106. package/src/serum/serumSubscriber.ts +80 -0
  107. package/src/serum/types.ts +13 -0
  108. package/src/tx/retryTxSender.ts +5 -2
  109. package/src/tx/types.ts +2 -1
  110. package/src/types.ts +135 -56
  111. package/src/userMap/userMap.ts +100 -0
  112. package/src/userMap/userStatsMap.ts +110 -0
  113. package/tests/bn/test.ts +2 -3
  114. package/tests/dlob/helpers.ts +322 -0
  115. package/tests/dlob/test.ts +2865 -0
  116. package/lib/math/bankBalance.d.ts +0 -15
  117. package/lib/math/bankBalance.js +0 -150
  118. package/src/constants/numericConstants.js +0 -41
  119. package/src/math/bankBalance.ts +0 -258
  120. package/src/math/oracles.js +0 -26
  121. package/src/math/state.js +0 -15
  122. package/src/orderParams.js +0 -20
  123. package/src/slot/SlotSubscriber.js +0 -39
  124. package/src/tokenFaucet.js +0 -189
@@ -0,0 +1,163 @@
1
+ import {
2
+ isOneOfVariant,
3
+ AMM_RESERVE_PRECISION,
4
+ BN,
5
+ convertToNumber,
6
+ getLimitPrice,
7
+ isVariant,
8
+ SpotMarketAccount,
9
+ PerpMarketAccount,
10
+ MARK_PRICE_PRECISION,
11
+ OraclePriceData,
12
+ Order,
13
+ ZERO,
14
+ } from '..';
15
+ import { PublicKey } from '@solana/web3.js';
16
+ import { getOrderSignature } from './NodeList';
17
+
18
+ export interface DLOBNode {
19
+ getPrice(oraclePriceData: OraclePriceData, slot: number): BN;
20
+ isVammNode(): boolean;
21
+ order: Order | undefined;
22
+ haveFilled: boolean;
23
+ userAccount: PublicKey | undefined;
24
+ market: SpotMarketAccount | PerpMarketAccount;
25
+ }
26
+
27
+ export abstract class OrderNode implements DLOBNode {
28
+ order: Order;
29
+ market: SpotMarketAccount | PerpMarketAccount;
30
+ userAccount: PublicKey;
31
+ sortValue: BN;
32
+ haveFilled = false;
33
+ haveTrigger = false;
34
+
35
+ constructor(
36
+ order: Order,
37
+ market: SpotMarketAccount | PerpMarketAccount,
38
+ userAccount: PublicKey
39
+ ) {
40
+ this.order = order;
41
+ this.market = market;
42
+ this.userAccount = userAccount;
43
+ this.sortValue = this.getSortValue(order);
44
+ }
45
+
46
+ abstract getSortValue(order: Order): BN;
47
+
48
+ public getLabel(): string {
49
+ let msg = `Order ${getOrderSignature(
50
+ this.order.orderId,
51
+ this.userAccount
52
+ )}`;
53
+ msg += ` ${isVariant(this.order.direction, 'long') ? 'LONG' : 'SHORT'} `;
54
+ msg += `${convertToNumber(
55
+ this.order.baseAssetAmount,
56
+ AMM_RESERVE_PRECISION
57
+ ).toFixed(3)}`;
58
+ if (this.order.price.gt(ZERO)) {
59
+ msg += ` @ ${convertToNumber(
60
+ this.order.price,
61
+ MARK_PRICE_PRECISION
62
+ ).toFixed(3)}`;
63
+ }
64
+ if (this.order.triggerPrice.gt(ZERO)) {
65
+ msg += ` ${
66
+ isVariant(this.order.triggerCondition, 'below') ? 'BELOW' : 'ABOVE'
67
+ }`;
68
+ msg += ` ${convertToNumber(
69
+ this.order.triggerPrice,
70
+ MARK_PRICE_PRECISION
71
+ ).toFixed(3)}`;
72
+ }
73
+ return msg;
74
+ }
75
+
76
+ getPrice(oraclePriceData: OraclePriceData, slot: number): BN {
77
+ if (isOneOfVariant(this.order.marketType, ['spot'])) {
78
+ return getLimitPrice(this.order, oraclePriceData, slot);
79
+ } else if (isOneOfVariant(this.order.marketType, ['perp'])) {
80
+ return getLimitPrice(
81
+ this.order,
82
+ oraclePriceData,
83
+ slot,
84
+ this.market as PerpMarketAccount
85
+ );
86
+ } else {
87
+ console.error(`Unknown market type: ${this.order.marketType}`);
88
+ }
89
+ }
90
+
91
+ isVammNode(): boolean {
92
+ return false;
93
+ }
94
+ }
95
+
96
+ export class LimitOrderNode extends OrderNode {
97
+ next?: LimitOrderNode;
98
+ previous?: LimitOrderNode;
99
+
100
+ getSortValue(order: Order): BN {
101
+ return order.price;
102
+ }
103
+ }
104
+
105
+ export class FloatingLimitOrderNode extends OrderNode {
106
+ next?: FloatingLimitOrderNode;
107
+ previous?: FloatingLimitOrderNode;
108
+
109
+ getSortValue(order: Order): BN {
110
+ return order.oraclePriceOffset;
111
+ }
112
+ }
113
+
114
+ export class MarketOrderNode extends OrderNode {
115
+ next?: MarketOrderNode;
116
+ previous?: MarketOrderNode;
117
+
118
+ getSortValue(order: Order): BN {
119
+ return order.slot;
120
+ }
121
+ }
122
+
123
+ export class TriggerOrderNode extends OrderNode {
124
+ next?: TriggerOrderNode;
125
+ previous?: TriggerOrderNode;
126
+
127
+ getSortValue(order: Order): BN {
128
+ return order.triggerPrice;
129
+ }
130
+ }
131
+
132
+ export type DLOBNodeMap = {
133
+ limit: LimitOrderNode;
134
+ floatingLimit: FloatingLimitOrderNode;
135
+ market: MarketOrderNode;
136
+ trigger: TriggerOrderNode;
137
+ };
138
+
139
+ export type DLOBNodeType =
140
+ | 'limit'
141
+ | 'floatingLimit'
142
+ | 'market'
143
+ | ('trigger' & keyof DLOBNodeMap);
144
+
145
+ export function createNode<T extends DLOBNodeType>(
146
+ nodeType: T,
147
+ order: Order,
148
+ market: SpotMarketAccount | PerpMarketAccount,
149
+ userAccount: PublicKey
150
+ ): DLOBNodeMap[T] {
151
+ switch (nodeType) {
152
+ case 'floatingLimit':
153
+ return new FloatingLimitOrderNode(order, market, userAccount);
154
+ case 'limit':
155
+ return new LimitOrderNode(order, market, userAccount);
156
+ case 'market':
157
+ return new MarketOrderNode(order, market, userAccount);
158
+ case 'trigger':
159
+ return new TriggerOrderNode(order, market, userAccount);
160
+ default:
161
+ throw Error(`Unknown DLOBNode type ${nodeType}`);
162
+ }
163
+ }
@@ -0,0 +1,185 @@
1
+ import {
2
+ BN,
3
+ isVariant,
4
+ MarketTypeStr,
5
+ Order,
6
+ PerpMarketAccount,
7
+ SpotMarketAccount,
8
+ } from '..';
9
+ import { PublicKey } from '@solana/web3.js';
10
+ import { createNode, DLOBNode, DLOBNodeMap } from './DLOBNode';
11
+
12
+ export type SortDirection = 'asc' | 'desc';
13
+
14
+ export function getOrderSignature(orderId: BN, userAccount: PublicKey): string {
15
+ return `${userAccount.toString()}-${orderId.toString()}`;
16
+ }
17
+
18
+ export interface DLOBNodeGenerator {
19
+ getGenerator(): Generator<DLOBNode>;
20
+ }
21
+
22
+ export class NodeList<NodeType extends keyof DLOBNodeMap>
23
+ implements DLOBNodeGenerator
24
+ {
25
+ head?: DLOBNodeMap[NodeType];
26
+ length = 0;
27
+ nodeMap = new Map<string, DLOBNodeMap[NodeType]>();
28
+
29
+ constructor(
30
+ private nodeType: NodeType,
31
+ private sortDirection: SortDirection
32
+ ) {}
33
+
34
+ public insert(
35
+ order: Order,
36
+ marketType: MarketTypeStr,
37
+ market: PerpMarketAccount | SpotMarketAccount,
38
+ userAccount: PublicKey
39
+ ): void {
40
+ if (isVariant(order.status, 'init')) {
41
+ return;
42
+ }
43
+
44
+ if (marketType === 'spot') {
45
+ market = market as SpotMarketAccount;
46
+ } else if (marketType === 'perp') {
47
+ market = market as PerpMarketAccount;
48
+ }
49
+
50
+ const newNode = createNode(this.nodeType, order, market, userAccount);
51
+
52
+ const orderId = getOrderSignature(order.orderId, userAccount);
53
+ if (this.nodeMap.has(orderId)) {
54
+ return;
55
+ }
56
+ this.nodeMap.set(orderId, newNode);
57
+
58
+ this.length += 1;
59
+
60
+ if (this.head === undefined) {
61
+ this.head = newNode;
62
+ return;
63
+ }
64
+
65
+ if (this.prependNode(this.head, newNode)) {
66
+ this.head.previous = newNode;
67
+ newNode.next = this.head;
68
+ this.head = newNode;
69
+ return;
70
+ }
71
+
72
+ let currentNode = this.head;
73
+ while (
74
+ currentNode.next !== undefined &&
75
+ !this.prependNode(currentNode.next, newNode)
76
+ ) {
77
+ currentNode = currentNode.next;
78
+ }
79
+
80
+ newNode.next = currentNode.next;
81
+ if (currentNode.next !== undefined) {
82
+ newNode.next.previous = newNode;
83
+ }
84
+ currentNode.next = newNode;
85
+ newNode.previous = currentNode;
86
+ }
87
+
88
+ prependNode(
89
+ currentNode: DLOBNodeMap[NodeType],
90
+ newNode: DLOBNodeMap[NodeType]
91
+ ): boolean {
92
+ const currentOrder = currentNode.order;
93
+ const newOrder = newNode.order;
94
+
95
+ const currentOrderSortPrice = currentNode.sortValue;
96
+ const newOrderSortPrice = newNode.sortValue;
97
+
98
+ if (newOrderSortPrice.eq(currentOrderSortPrice)) {
99
+ return newOrder.ts.lt(currentOrder.ts);
100
+ }
101
+
102
+ if (this.sortDirection === 'asc') {
103
+ return newOrderSortPrice.lt(currentOrderSortPrice);
104
+ } else {
105
+ return newOrderSortPrice.gt(currentOrderSortPrice);
106
+ }
107
+ }
108
+
109
+ public update(order: Order, userAccount: PublicKey): void {
110
+ const orderId = getOrderSignature(order.orderId, userAccount);
111
+ if (this.nodeMap.has(orderId)) {
112
+ const node = this.nodeMap.get(orderId);
113
+ Object.assign(node.order, order);
114
+ node.haveFilled = false;
115
+ }
116
+ }
117
+
118
+ public remove(order: Order, userAccount: PublicKey): void {
119
+ const orderId = getOrderSignature(order.orderId, userAccount);
120
+ if (this.nodeMap.has(orderId)) {
121
+ const node = this.nodeMap.get(orderId);
122
+ if (node.next) {
123
+ node.next.previous = node.previous;
124
+ }
125
+ if (node.previous) {
126
+ node.previous.next = node.next;
127
+ }
128
+
129
+ if (this.head && node.order.orderId.eq(this.head.order.orderId)) {
130
+ this.head = node.next;
131
+ }
132
+
133
+ node.previous = undefined;
134
+ node.next = undefined;
135
+
136
+ this.nodeMap.delete(orderId);
137
+
138
+ this.length--;
139
+ }
140
+ }
141
+
142
+ *getGenerator(): Generator<DLOBNode> {
143
+ let node = this.head;
144
+ while (node !== undefined) {
145
+ yield node;
146
+ node = node.next;
147
+ }
148
+ }
149
+
150
+ public has(order: Order, userAccount: PublicKey): boolean {
151
+ return this.nodeMap.has(getOrderSignature(order.orderId, userAccount));
152
+ }
153
+
154
+ public print(): void {
155
+ let currentNode = this.head;
156
+ while (currentNode !== undefined) {
157
+ console.log(currentNode.getLabel());
158
+ currentNode = currentNode.next;
159
+ }
160
+ }
161
+
162
+ public printTop(): void {
163
+ if (this.head) {
164
+ console.log(this.sortDirection.toUpperCase(), this.head.getLabel());
165
+ } else {
166
+ console.log('---');
167
+ }
168
+ }
169
+ }
170
+
171
+ export function* getVammNodeGenerator(
172
+ price: BN | undefined
173
+ ): Generator<DLOBNode> {
174
+ if (!price) {
175
+ return;
176
+ }
177
+ yield {
178
+ getPrice: () => price,
179
+ isVammNode: () => true,
180
+ order: undefined,
181
+ market: undefined,
182
+ userAccount: undefined,
183
+ haveFilled: false,
184
+ };
185
+ }
@@ -9,6 +9,7 @@ import {
9
9
  OrderRecord,
10
10
  SettlePnlRecord,
11
11
  LPRecord,
12
+ InsuranceFundRecord,
12
13
  } from '../index';
13
14
 
14
15
  export type EventSubscriptionOptions = {
@@ -35,6 +36,7 @@ export const DefaultEventSubscriptionOptions: EventSubscriptionOptions = {
35
36
  'NewUserRecord',
36
37
  'SettlePnlRecord',
37
38
  'LPRecord',
39
+ 'InsuranceFundRecord',
38
40
  ],
39
41
  maxEventsPerType: 4096,
40
42
  orderBy: 'blockchain',
@@ -71,6 +73,7 @@ export type EventMap = {
71
73
  SettlePnlRecord: Event<SettlePnlRecord>;
72
74
  NewUserRecord: Event<NewUserRecord>;
73
75
  LPRecord: Event<LPRecord>;
76
+ InsuranceFundRecord: Event<InsuranceFundRecord>;
74
77
  };
75
78
 
76
79
  export type EventType = keyof EventMap;
@@ -1,80 +1,157 @@
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 });
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 });
12
36
  exports.getTokenAddress = void 0;
13
- const anchor_1 = require("@project-serum/anchor");
14
- const __1 = require("..");
15
- const spl_token_1 = require("@solana/spl-token");
16
- const web3_js_1 = require("@solana/web3.js");
17
- const __2 = require("..");
18
- const banks_1 = require("../constants/banks");
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');
19
43
  const getTokenAddress = (mintAddress, userPubKey) => {
20
- return spl_token_1.Token.getAssociatedTokenAddress(new web3_js_1.PublicKey(`ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL`), spl_token_1.TOKEN_PROGRAM_ID, new web3_js_1.PublicKey(mintAddress), new web3_js_1.PublicKey(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
+ );
21
50
  };
22
51
  exports.getTokenAddress = getTokenAddress;
23
- const main = () => __awaiter(void 0, void 0, void 0, function* () {
24
- // Initialize Drift SDK
25
- const sdkConfig = __2.initialize({ env: 'devnet' });
26
- // Set up the Wallet and Provider
27
- const privateKey = process.env.BOT_PRIVATE_KEY; // stored as an array string
28
- const keypair = web3_js_1.Keypair.fromSecretKey(Uint8Array.from(JSON.parse(privateKey)));
29
- const wallet = new __1.Wallet(keypair);
30
- // Set up the Connection
31
- const rpcAddress = process.env.RPC_ADDRESS; // can use: https://api.devnet.solana.com for devnet; https://api.mainnet-beta.solana.com for mainnet;
32
- const connection = new web3_js_1.Connection(rpcAddress);
33
- // Set up the Provider
34
- const provider = new anchor_1.AnchorProvider(connection, wallet, anchor_1.AnchorProvider.defaultOptions());
35
- // Check SOL Balance
36
- const lamportsBalance = yield connection.getBalance(wallet.publicKey);
37
- console.log('SOL balance:', lamportsBalance / Math.pow(10, 9));
38
- // Misc. other things to set up
39
- const usdcTokenAddress = yield exports.getTokenAddress(sdkConfig.USDC_MINT_ADDRESS, wallet.publicKey.toString());
40
- // Set up the Drift Clearing House
41
- const clearingHousePublicKey = new web3_js_1.PublicKey(sdkConfig.CLEARING_HOUSE_PROGRAM_ID);
42
- const clearingHouse = new __2.ClearingHouse({
43
- connection,
44
- wallet: provider.wallet,
45
- programID: clearingHousePublicKey,
46
- });
47
- yield clearingHouse.subscribe();
48
- // Set up Clearing House user client
49
- const user = new __2.ClearingHouseUser({
50
- clearingHouse,
51
- userAccountPublicKey: yield clearingHouse.getUserAccountPublicKey(),
52
- });
53
- //// Check if clearing house account exists for the current wallet
54
- const userAccountExists = yield user.exists();
55
- if (!userAccountExists) {
56
- //// Create a Clearing House account by Depositing some USDC ($10,000 in this case)
57
- const depositAmount = new anchor_1.BN(10000).mul(__2.QUOTE_PRECISION);
58
- yield clearingHouse.initializeUserAccountAndDepositCollateral(depositAmount, yield exports.getTokenAddress(usdcTokenAddress.toString(), wallet.publicKey.toString()), banks_1.Banks['devnet'][0].bankIndex);
59
- }
60
- yield user.subscribe();
61
- // Get current price
62
- const solMarketInfo = sdkConfig.MARKETS.find((market) => market.baseAssetSymbol === 'SOL');
63
- const currentMarketPrice = __2.calculateMarkPrice(clearingHouse.getMarketAccount(solMarketInfo.marketIndex), undefined);
64
- const formattedPrice = __2.convertToNumber(currentMarketPrice, __2.MARK_PRICE_PRECISION);
65
- console.log(`Current Market Price is $${formattedPrice}`);
66
- // Estimate the slippage for a $5000 LONG trade
67
- const solMarketAccount = clearingHouse.getMarketAccount(solMarketInfo.marketIndex);
68
- const longAmount = new anchor_1.BN(5000).mul(__2.QUOTE_PRECISION);
69
- const slippage = __2.convertToNumber(__2.calculateTradeSlippage(__2.PositionDirection.LONG, longAmount, solMarketAccount, 'quote', undefined)[0], __2.MARK_PRICE_PRECISION);
70
- console.log(`Slippage for a $5000 LONG on the SOL market would be $${slippage}`);
71
- // Make a $5000 LONG trade
72
- yield clearingHouse.openPosition(__2.PositionDirection.LONG, longAmount, solMarketInfo.marketIndex);
73
- console.log(`LONGED $5000 SOL`);
74
- // Reduce the position by $2000
75
- const reduceAmount = new anchor_1.BN(2000).mul(__2.QUOTE_PRECISION);
76
- yield clearingHouse.openPosition(__2.PositionDirection.SHORT, reduceAmount, solMarketInfo.marketIndex);
77
- // Close the rest of the position
78
- yield clearingHouse.closePosition(solMarketInfo.marketIndex);
79
- });
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.CLEARING_HOUSE_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.MARK_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.MARK_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
+ });
80
157
  main();
@@ -11,11 +11,11 @@ import {
11
11
  convertToNumber,
12
12
  calculateTradeSlippage,
13
13
  BulkAccountLoader,
14
- Markets,
14
+ PerpMarkets,
15
15
  MARK_PRICE_PRECISION,
16
16
  QUOTE_PRECISION,
17
17
  } from '..';
18
- import { Banks } from '../constants/banks';
18
+ import { SpotMarkets } from '../constants/spotMarkets';
19
19
 
20
20
  export const getTokenAddress = (
21
21
  mintAddress: string,
@@ -76,8 +76,10 @@ const main = async () => {
76
76
  connection,
77
77
  wallet: provider.wallet,
78
78
  programID: clearingHousePublicKey,
79
- marketIndexes: Markets[cluster].map((market) => market.marketIndex),
80
- bankIndexes: Banks[cluster].map((bank) => bank.bankIndex),
79
+ perpMarketIndexes: PerpMarkets[cluster].map((market) => market.marketIndex),
80
+ spotMarketIndexes: SpotMarkets[cluster].map(
81
+ (spotMarket) => spotMarket.marketIndex
82
+ ),
81
83
  accountSubscription: {
82
84
  type: 'polling',
83
85
  accountLoader: bulkAccountLoader,
@@ -107,19 +109,19 @@ const main = async () => {
107
109
  usdcTokenAddress.toString(),
108
110
  wallet.publicKey.toString()
109
111
  ),
110
- Banks['devnet'][0].bankIndex
112
+ SpotMarkets['devnet'][0].marketIndex
111
113
  );
112
114
  }
113
115
 
114
116
  await user.subscribe();
115
117
 
116
118
  // Get current price
117
- const solMarketInfo = sdkConfig.MARKETS.find(
119
+ const solMarketInfo = sdkConfig.PERP_MARKETS.find(
118
120
  (market) => market.baseAssetSymbol === 'SOL'
119
121
  );
120
122
 
121
123
  const currentMarketPrice = calculateMarkPrice(
122
- clearingHouse.getMarketAccount(solMarketInfo.marketIndex),
124
+ clearingHouse.getPerpMarketAccount(solMarketInfo.marketIndex),
123
125
  undefined
124
126
  );
125
127
 
@@ -131,7 +133,7 @@ const main = async () => {
131
133
  console.log(`Current Market Price is $${formattedPrice}`);
132
134
 
133
135
  // Estimate the slippage for a $5000 LONG trade
134
- const solMarketAccount = clearingHouse.getMarketAccount(
136
+ const solMarketAccount = clearingHouse.getPerpMarketAccount(
135
137
  solMarketInfo.marketIndex
136
138
  );
137
139