@drift-labs/sdk 0.1.36-master.7 → 0.2.0-master.10

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 (254) hide show
  1. package/lib/accounts/bulkAccountLoader.d.ts +6 -6
  2. package/lib/accounts/bulkAccountLoader.js +81 -95
  3. package/lib/accounts/bulkUserSubscription.js +13 -57
  4. package/lib/accounts/fetch.d.ts +4 -0
  5. package/lib/accounts/fetch.js +18 -0
  6. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +34 -38
  7. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +224 -224
  8. package/lib/accounts/pollingOracleSubscriber.d.ts +3 -3
  9. package/lib/accounts/pollingOracleSubscriber.js +37 -49
  10. package/lib/accounts/pollingTokenAccountSubscriber.d.ts +3 -3
  11. package/lib/accounts/pollingTokenAccountSubscriber.js +35 -50
  12. package/lib/accounts/pollingUserAccountSubscriber.d.ts +7 -13
  13. package/lib/accounts/pollingUserAccountSubscriber.js +71 -134
  14. package/lib/accounts/types.d.ts +34 -41
  15. package/lib/accounts/webSocketAccountSubscriber.d.ts +6 -4
  16. package/lib/accounts/webSocketAccountSubscriber.js +39 -35
  17. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +33 -28
  18. package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +153 -185
  19. package/lib/accounts/webSocketUserAccountSubscriber.d.ts +5 -11
  20. package/lib/accounts/webSocketUserAccountSubscriber.js +22 -67
  21. package/lib/addresses/marketAddresses.d.ts +4 -0
  22. package/lib/addresses/marketAddresses.js +15 -0
  23. package/lib/addresses/pda.d.ts +12 -0
  24. package/lib/addresses/pda.js +83 -0
  25. package/lib/admin.d.ts +12 -18
  26. package/lib/admin.js +398 -558
  27. package/lib/clearingHouse.d.ts +83 -109
  28. package/lib/clearingHouse.js +832 -893
  29. package/lib/clearingHouseConfig.d.ts +34 -0
  30. package/lib/clearingHouseConfig.js +2 -0
  31. package/lib/clearingHouseUser.d.ts +19 -22
  32. package/lib/clearingHouseUser.js +155 -141
  33. package/lib/clearingHouseUserConfig.d.ts +14 -0
  34. package/lib/clearingHouseUserConfig.js +2 -0
  35. package/lib/config.d.ts +12 -0
  36. package/lib/config.js +35 -4
  37. package/lib/constants/banks.d.ts +16 -0
  38. package/lib/constants/banks.js +41 -0
  39. package/lib/constants/markets.d.ts +8 -3
  40. package/lib/constants/markets.js +13 -206
  41. package/lib/constants/numericConstants.d.ts +17 -0
  42. package/lib/constants/numericConstants.js +23 -6
  43. package/lib/events/eventList.d.ts +22 -0
  44. package/lib/events/eventList.js +77 -0
  45. package/lib/events/eventSubscriber.d.ts +34 -0
  46. package/lib/events/eventSubscriber.js +126 -0
  47. package/lib/events/fetchLogs.d.ts +13 -0
  48. package/lib/events/fetchLogs.js +39 -0
  49. package/lib/events/pollingLogProvider.d.ts +15 -0
  50. package/lib/events/pollingLogProvider.js +53 -0
  51. package/lib/events/sort.d.ts +2 -0
  52. package/lib/events/sort.js +44 -0
  53. package/lib/events/txEventCache.d.ts +24 -0
  54. package/lib/events/txEventCache.js +71 -0
  55. package/lib/events/types.d.ts +49 -0
  56. package/lib/events/types.js +20 -0
  57. package/lib/events/webSocketLogProvider.d.ts +12 -0
  58. package/lib/events/webSocketLogProvider.js +30 -0
  59. package/lib/examples/makeTradeExample.js +26 -27
  60. package/lib/factory/bigNum.d.ts +118 -0
  61. package/lib/factory/bigNum.js +364 -0
  62. package/lib/factory/oracleClient.d.ts +1 -2
  63. package/lib/factory/oracleClient.js +6 -2
  64. package/lib/idl/clearing_house.json +2258 -2774
  65. package/lib/index.d.ts +14 -5
  66. package/lib/index.js +18 -5
  67. package/lib/math/amm.d.ts +24 -29
  68. package/lib/math/amm.js +209 -176
  69. package/lib/math/auction.d.ts +5 -0
  70. package/lib/math/auction.js +42 -0
  71. package/lib/math/bankBalance.d.ts +9 -0
  72. package/lib/math/bankBalance.js +75 -0
  73. package/lib/math/conversion.d.ts +0 -1
  74. package/lib/math/conversion.js +1 -5
  75. package/lib/math/funding.d.ts +6 -6
  76. package/lib/math/funding.js +158 -175
  77. package/lib/math/market.d.ts +6 -6
  78. package/lib/math/market.js +10 -9
  79. package/lib/math/orders.d.ts +6 -1
  80. package/lib/math/orders.js +38 -1
  81. package/lib/math/position.d.ts +7 -5
  82. package/lib/math/position.js +29 -27
  83. package/lib/math/repeg.d.ts +22 -0
  84. package/lib/math/repeg.js +128 -0
  85. package/lib/math/trade.d.ts +5 -4
  86. package/lib/math/trade.js +29 -24
  87. package/lib/mockUSDCFaucet.js +87 -116
  88. package/lib/oracles/oracleClientCache.d.ts +8 -0
  89. package/lib/oracles/oracleClientCache.js +19 -0
  90. package/lib/oracles/pythClient.d.ts +3 -5
  91. package/lib/oracles/pythClient.js +12 -31
  92. package/lib/oracles/quoteAssetOracleClient.d.ts +9 -0
  93. package/lib/oracles/quoteAssetOracleClient.js +21 -0
  94. package/lib/oracles/switchboardClient.d.ts +3 -5
  95. package/lib/oracles/switchboardClient.js +29 -50
  96. package/lib/oracles/types.d.ts +6 -1
  97. package/lib/orderParams.d.ts +14 -5
  98. package/lib/orderParams.js +8 -96
  99. package/lib/orders.d.ts +6 -7
  100. package/lib/orders.js +11 -89
  101. package/lib/slot/SlotSubscriber.d.ts +19 -0
  102. package/lib/slot/SlotSubscriber.js +26 -0
  103. package/lib/tx/retryTxSender.d.ts +2 -2
  104. package/lib/tx/retryTxSender.js +108 -123
  105. package/lib/tx/types.d.ts +5 -1
  106. package/lib/tx/utils.d.ts +1 -1
  107. package/lib/tx/utils.js +11 -2
  108. package/lib/types.d.ts +180 -110
  109. package/lib/types.js +54 -1
  110. package/lib/userName.d.ts +4 -0
  111. package/lib/userName.js +20 -0
  112. package/lib/util/computeUnits.js +10 -21
  113. package/lib/util/tps.js +11 -22
  114. package/lib/wallet.js +7 -20
  115. package/package.json +11 -4
  116. package/src/accounts/bulkAccountLoader.js +197 -0
  117. package/src/accounts/bulkAccountLoader.ts +21 -15
  118. package/src/accounts/bulkUserSubscription.js +33 -0
  119. package/src/accounts/bulkUserSubscription.ts +1 -45
  120. package/src/accounts/fetch.js +29 -0
  121. package/src/accounts/fetch.ts +33 -0
  122. package/src/accounts/pollingClearingHouseAccountSubscriber.js +311 -0
  123. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +249 -214
  124. package/src/accounts/pollingOracleSubscriber.js +93 -0
  125. package/src/accounts/pollingOracleSubscriber.ts +16 -8
  126. package/src/accounts/pollingTokenAccountSubscriber.js +90 -0
  127. package/src/accounts/pollingTokenAccountSubscriber.ts +11 -8
  128. package/src/accounts/pollingUserAccountSubscriber.js +132 -0
  129. package/src/accounts/pollingUserAccountSubscriber.ts +21 -86
  130. package/src/accounts/types.js +10 -0
  131. package/src/accounts/types.ts +41 -70
  132. package/src/accounts/utils.js +7 -0
  133. package/src/accounts/webSocketAccountSubscriber.js +93 -0
  134. package/src/accounts/webSocketAccountSubscriber.ts +33 -16
  135. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +233 -0
  136. package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +190 -240
  137. package/src/accounts/webSocketUserAccountSubscriber.js +62 -0
  138. package/src/accounts/webSocketUserAccountSubscriber.ts +11 -71
  139. package/src/addresses/marketAddresses.js +26 -0
  140. package/src/addresses/marketAddresses.ts +18 -0
  141. package/{lib/addresses.js → src/addresses/pda.js} +45 -34
  142. package/src/addresses/pda.ts +118 -0
  143. package/src/admin.ts +247 -336
  144. package/src/assert/assert.js +9 -0
  145. package/src/clearingHouse.ts +1023 -1026
  146. package/src/clearingHouseConfig.ts +37 -0
  147. package/src/clearingHouseUser.ts +275 -185
  148. package/src/clearingHouseUserConfig.ts +18 -0
  149. package/src/config.ts +54 -1
  150. package/src/constants/banks.ts +50 -0
  151. package/src/constants/markets.ts +16 -207
  152. package/src/constants/numericConstants.ts +34 -5
  153. package/src/events/eventList.js +77 -0
  154. package/src/events/eventList.ts +94 -0
  155. package/src/events/eventSubscriber.js +139 -0
  156. package/src/events/eventSubscriber.ts +194 -0
  157. package/src/events/fetchLogs.js +50 -0
  158. package/src/events/fetchLogs.ts +80 -0
  159. package/src/events/pollingLogProvider.js +64 -0
  160. package/src/events/pollingLogProvider.ts +79 -0
  161. package/src/events/sort.js +44 -0
  162. package/src/events/sort.ts +65 -0
  163. package/src/events/txEventCache.js +71 -0
  164. package/src/events/txEventCache.ts +74 -0
  165. package/src/events/types.js +20 -0
  166. package/src/events/types.ts +98 -0
  167. package/src/events/webSocketLogProvider.js +41 -0
  168. package/src/events/webSocketLogProvider.ts +38 -0
  169. package/src/examples/makeTradeExample.js +80 -0
  170. package/src/examples/makeTradeExample.ts +20 -11
  171. package/src/factory/bigNum.js +364 -0
  172. package/src/factory/bigNum.ts +524 -0
  173. package/src/factory/oracleClient.js +20 -0
  174. package/src/factory/oracleClient.ts +7 -4
  175. package/src/idl/clearing_house.json +2258 -2774
  176. package/src/index.js +69 -0
  177. package/src/index.ts +14 -5
  178. package/src/math/amm.js +369 -0
  179. package/src/math/amm.ts +382 -243
  180. package/src/math/auction.js +42 -0
  181. package/src/math/auction.ts +43 -0
  182. package/src/math/bankBalance.js +75 -0
  183. package/src/math/bankBalance.ts +112 -0
  184. package/src/math/conversion.js +11 -0
  185. package/src/math/conversion.ts +1 -11
  186. package/src/math/funding.js +248 -0
  187. package/src/math/funding.ts +12 -9
  188. package/src/math/market.js +57 -0
  189. package/src/math/market.ts +37 -30
  190. package/src/math/oracles.js +26 -0
  191. package/src/math/orders.js +110 -0
  192. package/src/math/orders.ts +43 -1
  193. package/src/math/position.js +140 -0
  194. package/src/math/position.ts +52 -35
  195. package/src/math/repeg.js +128 -0
  196. package/src/math/repeg.ts +176 -0
  197. package/src/math/state.js +15 -0
  198. package/src/math/trade.js +253 -0
  199. package/src/math/trade.ts +55 -47
  200. package/src/math/utils.js +26 -0
  201. package/src/math/utils.js.map +1 -0
  202. package/src/mockUSDCFaucet.js +171 -0
  203. package/src/oracles/oracleClientCache.js +19 -0
  204. package/src/oracles/oracleClientCache.ts +20 -0
  205. package/src/oracles/pythClient.js +46 -0
  206. package/src/oracles/pythClient.ts +4 -11
  207. package/src/oracles/quoteAssetOracleClient.js +32 -0
  208. package/src/oracles/quoteAssetOracleClient.ts +25 -0
  209. package/src/oracles/switchboardClient.js +69 -0
  210. package/src/oracles/switchboardClient.ts +11 -24
  211. package/src/oracles/types.js +2 -0
  212. package/src/oracles/types.ts +7 -1
  213. package/src/orderParams.js +20 -0
  214. package/src/orderParams.ts +20 -141
  215. package/src/orders.js +134 -0
  216. package/src/orders.ts +25 -134
  217. package/src/slot/SlotSubscriber.js +39 -0
  218. package/src/slot/SlotSubscriber.ts +42 -0
  219. package/src/token/index.js +38 -0
  220. package/src/tx/retryTxSender.js +188 -0
  221. package/src/tx/retryTxSender.ts +6 -4
  222. package/src/tx/types.js +2 -0
  223. package/src/tx/types.ts +6 -1
  224. package/src/tx/utils.js +17 -0
  225. package/src/tx/utils.ts +22 -3
  226. package/src/types.js +114 -0
  227. package/src/types.ts +176 -124
  228. package/src/userName.js +20 -0
  229. package/src/userName.ts +20 -0
  230. package/src/util/promiseTimeout.js +14 -0
  231. package/src/util/tps.js +27 -0
  232. package/src/wallet.js +35 -0
  233. package/tests/bn/test.ts +255 -0
  234. package/tsconfig.json +12 -12
  235. package/lib/addresses.d.ts +0 -10
  236. package/lib/constants/accounts.d.ts +0 -15
  237. package/lib/constants/accounts.js +0 -18
  238. package/lib/factory/clearingHouse.d.ts +0 -35
  239. package/lib/factory/clearingHouse.js +0 -81
  240. package/lib/factory/clearingHouseUser.d.ts +0 -19
  241. package/lib/factory/clearingHouseUser.js +0 -34
  242. package/lib/math/insuranceFund.d.ts +0 -15
  243. package/lib/math/insuranceFund.js +0 -33
  244. package/lib/settlement.d.ts +0 -4
  245. package/lib/settlement.js +0 -10
  246. package/lib/tx/defaultTxSender.d.ts +0 -8
  247. package/lib/tx/defaultTxSender.js +0 -12
  248. package/src/addresses.ts +0 -82
  249. package/src/constants/accounts.ts +0 -26
  250. package/src/factory/clearingHouse.ts +0 -173
  251. package/src/factory/clearingHouseUser.ts +0 -73
  252. package/src/math/insuranceFund.ts +0 -29
  253. package/src/settlement.ts +0 -9
  254. package/src/tx/defaultTxSender.ts +0 -24
@@ -0,0 +1,39 @@
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.SlotSubscriber = void 0;
13
+ const events_1 = require("events");
14
+ class SlotSubscriber {
15
+ constructor(connection, _config) {
16
+ this.connection = connection;
17
+ this.eventEmitter = new events_1.EventEmitter();
18
+ }
19
+ subscribe() {
20
+ return __awaiter(this, void 0, void 0, function* () {
21
+ this.currentSlot = yield this.connection.getSlot('confirmed');
22
+ this.subscriptionId = this.connection.onSlotChange((slotInfo) => {
23
+ this.currentSlot = slotInfo.slot;
24
+ this.eventEmitter.emit('newSlot', slotInfo.slot);
25
+ });
26
+ });
27
+ }
28
+ getSlot() {
29
+ return this.currentSlot;
30
+ }
31
+ unsubscribe() {
32
+ return __awaiter(this, void 0, void 0, function* () {
33
+ if (this.subscriptionId) {
34
+ yield this.connection.removeSlotChangeListener(this.subscriptionId);
35
+ }
36
+ });
37
+ }
38
+ }
39
+ exports.SlotSubscriber = SlotSubscriber;
@@ -0,0 +1,42 @@
1
+ import { Connection } from '@solana/web3.js';
2
+ import { EventEmitter } from 'events';
3
+ import StrictEventEmitter from 'strict-event-emitter-types/types/src';
4
+
5
+ // eslint-disable-next-line @typescript-eslint/ban-types
6
+ type SlotSubscriberConfig = {}; // for future customization
7
+
8
+ export interface SlotSubscriberEvents {
9
+ newSlot: (newSlot: number) => void;
10
+ }
11
+
12
+ export class SlotSubscriber {
13
+ currentSlot: number;
14
+ subscriptionId: number;
15
+ eventEmitter: StrictEventEmitter<EventEmitter, SlotSubscriberEvents>;
16
+
17
+ public constructor(
18
+ private connection: Connection,
19
+ _config?: SlotSubscriberConfig
20
+ ) {
21
+ this.eventEmitter = new EventEmitter();
22
+ }
23
+
24
+ public async subscribe(): Promise<void> {
25
+ this.currentSlot = await this.connection.getSlot('confirmed');
26
+
27
+ this.subscriptionId = this.connection.onSlotChange((slotInfo) => {
28
+ this.currentSlot = slotInfo.slot;
29
+ this.eventEmitter.emit('newSlot', slotInfo.slot);
30
+ });
31
+ }
32
+
33
+ public getSlot(): number {
34
+ return this.currentSlot;
35
+ }
36
+
37
+ public async unsubscribe(): Promise<void> {
38
+ if (this.subscriptionId) {
39
+ await this.connection.removeSlotChangeListener(this.subscriptionId);
40
+ }
41
+ }
42
+ }
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseTokenAccount = void 0;
4
+ const spl_token_1 = require("@solana/spl-token");
5
+ const web3_js_1 = require("@solana/web3.js");
6
+ function parseTokenAccount(data) {
7
+ const accountInfo = spl_token_1.AccountLayout.decode(data);
8
+ accountInfo.mint = new web3_js_1.PublicKey(accountInfo.mint);
9
+ accountInfo.owner = new web3_js_1.PublicKey(accountInfo.owner);
10
+ accountInfo.amount = spl_token_1.u64.fromBuffer(accountInfo.amount);
11
+ if (accountInfo.delegateOption === 0) {
12
+ accountInfo.delegate = null;
13
+ // eslint-disable-next-line new-cap
14
+ accountInfo.delegatedAmount = new spl_token_1.u64(0);
15
+ }
16
+ else {
17
+ accountInfo.delegate = new web3_js_1.PublicKey(accountInfo.delegate);
18
+ accountInfo.delegatedAmount = spl_token_1.u64.fromBuffer(accountInfo.delegatedAmount);
19
+ }
20
+ accountInfo.isInitialized = accountInfo.state !== 0;
21
+ accountInfo.isFrozen = accountInfo.state === 2;
22
+ if (accountInfo.isNativeOption === 1) {
23
+ accountInfo.rentExemptReserve = spl_token_1.u64.fromBuffer(accountInfo.isNative);
24
+ accountInfo.isNative = true;
25
+ }
26
+ else {
27
+ accountInfo.rentExemptReserve = null;
28
+ accountInfo.isNative = false;
29
+ }
30
+ if (accountInfo.closeAuthorityOption === 0) {
31
+ accountInfo.closeAuthority = null;
32
+ }
33
+ else {
34
+ accountInfo.closeAuthority = new web3_js_1.PublicKey(accountInfo.closeAuthority);
35
+ }
36
+ return accountInfo;
37
+ }
38
+ exports.parseTokenAccount = parseTokenAccount;
@@ -0,0 +1,188 @@
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
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.RetryTxSender = void 0;
16
+ const assert_1 = __importDefault(require("assert"));
17
+ const bs58_1 = __importDefault(require("bs58"));
18
+ const DEFAULT_TIMEOUT = 35000;
19
+ const DEFAULT_RETRY = 8000;
20
+ class RetryTxSender {
21
+ constructor(provider, timeout, retrySleep, additionalConnections = new Array()) {
22
+ this.provider = provider;
23
+ this.timeout = timeout !== null && timeout !== void 0 ? timeout : DEFAULT_TIMEOUT;
24
+ this.retrySleep = retrySleep !== null && retrySleep !== void 0 ? retrySleep : DEFAULT_RETRY;
25
+ this.additionalConnections = additionalConnections;
26
+ }
27
+ send(tx, additionalSigners, opts) {
28
+ return __awaiter(this, void 0, void 0, function* () {
29
+ if (additionalSigners === undefined) {
30
+ additionalSigners = [];
31
+ }
32
+ if (opts === undefined) {
33
+ opts = this.provider.opts;
34
+ }
35
+ yield this.prepareTx(tx, additionalSigners, opts);
36
+ const rawTransaction = tx.serialize();
37
+ const startTime = this.getTimestamp();
38
+ const txid = yield this.provider.connection.sendRawTransaction(rawTransaction, opts);
39
+ this.sendToAdditionalConnections(rawTransaction, opts);
40
+ let done = false;
41
+ const resolveReference = {
42
+ resolve: undefined,
43
+ };
44
+ const stopWaiting = () => {
45
+ done = true;
46
+ if (resolveReference.resolve) {
47
+ resolveReference.resolve();
48
+ }
49
+ };
50
+ (() => __awaiter(this, void 0, void 0, function* () {
51
+ while (!done && this.getTimestamp() - startTime < this.timeout) {
52
+ yield this.sleep(resolveReference);
53
+ if (!done) {
54
+ this.provider.connection
55
+ .sendRawTransaction(rawTransaction, opts)
56
+ .catch((e) => {
57
+ console.error(e);
58
+ stopWaiting();
59
+ });
60
+ this.sendToAdditionalConnections(rawTransaction, opts);
61
+ }
62
+ }
63
+ }))();
64
+ let slot;
65
+ try {
66
+ const result = yield this.confirmTransaction(txid, opts.commitment);
67
+ slot = result.context.slot;
68
+ }
69
+ catch (e) {
70
+ console.error(e);
71
+ throw e;
72
+ }
73
+ finally {
74
+ stopWaiting();
75
+ }
76
+ return { txSig: txid, slot };
77
+ });
78
+ }
79
+ prepareTx(tx, additionalSigners, opts) {
80
+ return __awaiter(this, void 0, void 0, function* () {
81
+ tx.feePayer = this.provider.wallet.publicKey;
82
+ tx.recentBlockhash = (yield this.provider.connection.getRecentBlockhash(opts.preflightCommitment)).blockhash;
83
+ yield this.provider.wallet.signTransaction(tx);
84
+ additionalSigners
85
+ .filter((s) => s !== undefined)
86
+ .forEach((kp) => {
87
+ tx.partialSign(kp);
88
+ });
89
+ return tx;
90
+ });
91
+ }
92
+ confirmTransaction(signature, commitment) {
93
+ return __awaiter(this, void 0, void 0, function* () {
94
+ let decodedSignature;
95
+ try {
96
+ decodedSignature = bs58_1.default.decode(signature);
97
+ }
98
+ catch (err) {
99
+ throw new Error('signature must be base58 encoded: ' + signature);
100
+ }
101
+ assert_1.default(decodedSignature.length === 64, 'signature has invalid length');
102
+ const start = Date.now();
103
+ const subscriptionCommitment = commitment || this.provider.opts.commitment;
104
+ const subscriptionIds = new Array();
105
+ const connections = [
106
+ this.provider.connection,
107
+ ...this.additionalConnections,
108
+ ];
109
+ let response = null;
110
+ const promises = connections.map((connection, i) => {
111
+ let subscriptionId;
112
+ const confirmPromise = new Promise((resolve, reject) => {
113
+ try {
114
+ subscriptionId = connection.onSignature(signature, (result, context) => {
115
+ subscriptionIds[i] = undefined;
116
+ response = {
117
+ context,
118
+ value: result,
119
+ };
120
+ resolve(null);
121
+ }, subscriptionCommitment);
122
+ }
123
+ catch (err) {
124
+ reject(err);
125
+ }
126
+ });
127
+ subscriptionIds.push(subscriptionId);
128
+ return confirmPromise;
129
+ });
130
+ try {
131
+ yield this.promiseTimeout(promises, this.timeout);
132
+ }
133
+ finally {
134
+ for (const [i, subscriptionId] of subscriptionIds.entries()) {
135
+ if (subscriptionId) {
136
+ connections[i].removeSignatureListener(subscriptionId);
137
+ }
138
+ }
139
+ }
140
+ if (response === null) {
141
+ const duration = (Date.now() - start) / 1000;
142
+ throw new Error(`Transaction was not confirmed in ${duration.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${signature} using the Solana Explorer or CLI tools.`);
143
+ }
144
+ return response;
145
+ });
146
+ }
147
+ getTimestamp() {
148
+ return new Date().getTime();
149
+ }
150
+ sleep(reference) {
151
+ return __awaiter(this, void 0, void 0, function* () {
152
+ return new Promise((resolve) => {
153
+ reference.resolve = resolve;
154
+ setTimeout(resolve, this.retrySleep);
155
+ });
156
+ });
157
+ }
158
+ promiseTimeout(promises, timeoutMs) {
159
+ let timeoutId;
160
+ const timeoutPromise = new Promise((resolve) => {
161
+ timeoutId = setTimeout(() => resolve(null), timeoutMs);
162
+ });
163
+ return Promise.race([...promises, timeoutPromise]).then((result) => {
164
+ clearTimeout(timeoutId);
165
+ return result;
166
+ });
167
+ }
168
+ sendToAdditionalConnections(rawTx, opts) {
169
+ this.additionalConnections.map((connection) => {
170
+ connection.sendRawTransaction(rawTx, opts).catch((e) => {
171
+ console.error(
172
+ // @ts-ignore
173
+ `error sending tx to additional connection ${connection._rpcEndpoint}`);
174
+ console.error(e);
175
+ });
176
+ });
177
+ }
178
+ addAdditionalConnection(newConnection) {
179
+ const alreadyUsingConnection = this.additionalConnections.filter((connection) => {
180
+ // @ts-ignore
181
+ return connection._rpcEndpoint === newConnection.rpcEndpoint;
182
+ }).length > 0;
183
+ if (!alreadyUsingConnection) {
184
+ this.additionalConnections.push(newConnection);
185
+ }
186
+ }
187
+ }
188
+ exports.RetryTxSender = RetryTxSender;
@@ -1,4 +1,4 @@
1
- import { TxSender } from './types';
1
+ import { TxSender, TxSigAndSlot } from './types';
2
2
  import {
3
3
  Commitment,
4
4
  ConfirmOptions,
@@ -43,7 +43,7 @@ export class RetryTxSender implements TxSender {
43
43
  tx: Transaction,
44
44
  additionalSigners?: Array<Signer>,
45
45
  opts?: ConfirmOptions
46
- ): Promise<TransactionSignature> {
46
+ ): Promise<TxSigAndSlot> {
47
47
  if (additionalSigners === undefined) {
48
48
  additionalSigners = [];
49
49
  }
@@ -86,8 +86,10 @@ export class RetryTxSender implements TxSender {
86
86
  }
87
87
  })();
88
88
 
89
+ let slot: number;
89
90
  try {
90
- await this.confirmTransaction(txid, opts.commitment);
91
+ const result = await this.confirmTransaction(txid, opts.commitment);
92
+ slot = result.context.slot;
91
93
  } catch (e) {
92
94
  console.error(e);
93
95
  throw e;
@@ -95,7 +97,7 @@ export class RetryTxSender implements TxSender {
95
97
  stopWaiting();
96
98
  }
97
99
 
98
- return txid;
100
+ return { txSig: txid, slot };
99
101
  }
100
102
 
101
103
  async prepareTx(
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/src/tx/types.ts CHANGED
@@ -6,6 +6,11 @@ import {
6
6
  TransactionSignature,
7
7
  } from '@solana/web3.js';
8
8
 
9
+ export type TxSigAndSlot = {
10
+ txSig: TransactionSignature;
11
+ slot: number;
12
+ };
13
+
9
14
  export interface TxSender {
10
15
  provider: Provider;
11
16
 
@@ -13,5 +18,5 @@ export interface TxSender {
13
18
  tx: Transaction,
14
19
  additionalSigners?: Array<Signer>,
15
20
  opts?: ConfirmOptions
16
- ): Promise<TransactionSignature>;
21
+ ): Promise<TxSigAndSlot>;
17
22
  }
@@ -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/tx/utils.ts CHANGED
@@ -1,5 +1,24 @@
1
- import { Transaction, TransactionInstruction } from '@solana/web3.js';
1
+ import {
2
+ Transaction,
3
+ TransactionInstruction,
4
+ ComputeBudgetProgram,
5
+ } from '@solana/web3.js';
2
6
 
3
- export function wrapInTx(instruction: TransactionInstruction): Transaction {
4
- return new Transaction().add(instruction);
7
+ const COMPUTE_UNITS_DEFAULT = 200_000;
8
+
9
+ export function wrapInTx(
10
+ instruction: TransactionInstruction,
11
+ computeUnits = 600_000 // TODO, requires less code change
12
+ ): Transaction {
13
+ const tx = new Transaction();
14
+ if (computeUnits != COMPUTE_UNITS_DEFAULT) {
15
+ tx.add(
16
+ ComputeBudgetProgram.requestUnits({
17
+ units: computeUnits,
18
+ additionalFee: 0,
19
+ })
20
+ );
21
+ }
22
+
23
+ return tx.add(instruction);
5
24
  }
package/src/types.js ADDED
@@ -0,0 +1,114 @@
1
+ "use strict";
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;
4
+ const _1 = require(".");
5
+ // # Utility Types / Enums / Constants
6
+ class SwapDirection {
7
+ }
8
+ exports.SwapDirection = SwapDirection;
9
+ SwapDirection.ADD = { add: {} };
10
+ SwapDirection.REMOVE = { remove: {} };
11
+ class BankBalanceType {
12
+ }
13
+ exports.BankBalanceType = BankBalanceType;
14
+ BankBalanceType.DEPOSIT = { deposit: {} };
15
+ BankBalanceType.BORROW = { borrow: {} };
16
+ class PositionDirection {
17
+ }
18
+ exports.PositionDirection = PositionDirection;
19
+ PositionDirection.LONG = { long: {} };
20
+ PositionDirection.SHORT = { short: {} };
21
+ class DepositDirection {
22
+ }
23
+ exports.DepositDirection = DepositDirection;
24
+ DepositDirection.DEPOSIT = { deposit: {} };
25
+ DepositDirection.WITHDRAW = { withdraw: {} };
26
+ class OracleSource {
27
+ }
28
+ exports.OracleSource = OracleSource;
29
+ OracleSource.PYTH = { pyth: {} };
30
+ OracleSource.SWITCHBOARD = { switchboard: {} };
31
+ OracleSource.QUOTE_ASSET = { quoteAsset: {} };
32
+ class OrderType {
33
+ }
34
+ exports.OrderType = OrderType;
35
+ OrderType.LIMIT = { limit: {} };
36
+ OrderType.TRIGGER_MARKET = { triggerMarket: {} };
37
+ OrderType.TRIGGER_LIMIT = { triggerLimit: {} };
38
+ OrderType.MARKET = { market: {} };
39
+ class OrderStatus {
40
+ }
41
+ exports.OrderStatus = OrderStatus;
42
+ OrderStatus.INIT = { init: {} };
43
+ OrderStatus.OPEN = { open: {} };
44
+ class OrderDiscountTier {
45
+ }
46
+ exports.OrderDiscountTier = OrderDiscountTier;
47
+ OrderDiscountTier.NONE = { none: {} };
48
+ OrderDiscountTier.FIRST = { first: {} };
49
+ OrderDiscountTier.SECOND = { second: {} };
50
+ OrderDiscountTier.THIRD = { third: {} };
51
+ OrderDiscountTier.FOURTH = { fourth: {} };
52
+ class OrderAction {
53
+ }
54
+ exports.OrderAction = OrderAction;
55
+ OrderAction.PLACE = { place: {} };
56
+ OrderAction.CANCEL = { cancel: {} };
57
+ OrderAction.EXPIRE = { expire: {} };
58
+ OrderAction.FILL = { fill: {} };
59
+ OrderAction.TRIGGER = { trigger: {} };
60
+ class OrderActionExplanation {
61
+ }
62
+ exports.OrderActionExplanation = OrderActionExplanation;
63
+ OrderActionExplanation.NONE = { none: {} };
64
+ OrderActionExplanation.BREACHED_MARGIN_REQUIREMENT = {
65
+ breachedMarginRequirement: {},
66
+ };
67
+ OrderActionExplanation.ORACLE_PRICE_BREACHED_LIMIT_PRICE = {
68
+ oraclePriceBreachedLimitPrice: {},
69
+ };
70
+ OrderActionExplanation.MARKET_ORDER_FILLED_TO_LIMIT_PRICE = {
71
+ marketOrderFilledToLimitPrice: {},
72
+ };
73
+ class OrderTriggerCondition {
74
+ }
75
+ exports.OrderTriggerCondition = OrderTriggerCondition;
76
+ OrderTriggerCondition.ABOVE = { above: {} };
77
+ OrderTriggerCondition.BELOW = { below: {} };
78
+ function isVariant(object, type) {
79
+ return object.hasOwnProperty(type);
80
+ }
81
+ exports.isVariant = isVariant;
82
+ function isOneOfVariant(object, types) {
83
+ return types.reduce((result, type) => {
84
+ return result || object.hasOwnProperty(type);
85
+ }, false);
86
+ }
87
+ exports.isOneOfVariant = isOneOfVariant;
88
+ var TradeSide;
89
+ (function (TradeSide) {
90
+ TradeSide[TradeSide["None"] = 0] = "None";
91
+ TradeSide[TradeSide["Buy"] = 1] = "Buy";
92
+ TradeSide[TradeSide["Sell"] = 2] = "Sell";
93
+ })(TradeSide = exports.TradeSide || (exports.TradeSide = {}));
94
+ exports.DefaultOrderParams = {
95
+ orderType: OrderType.MARKET,
96
+ userOrderId: 0,
97
+ direction: PositionDirection.LONG,
98
+ baseAssetAmount: _1.ZERO,
99
+ price: _1.ZERO,
100
+ marketIndex: _1.ZERO,
101
+ reduceOnly: false,
102
+ postOnly: false,
103
+ immediateOrCancel: false,
104
+ triggerPrice: _1.ZERO,
105
+ triggerCondition: OrderTriggerCondition.ABOVE,
106
+ positionLimit: _1.ZERO,
107
+ oraclePriceOffset: _1.ZERO,
108
+ padding0: _1.ZERO,
109
+ padding1: _1.ZERO,
110
+ optionalAccounts: {
111
+ discountToken: false,
112
+ referrer: false,
113
+ },
114
+ };