@velocity-exchange/sdk 0.4.0 → 0.6.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 (325) hide show
  1. package/README.md +3 -3
  2. package/lib/browser/adminClient.d.ts +52 -0
  3. package/lib/browser/adminClient.js +97 -0
  4. package/lib/browser/config.js +6 -7
  5. package/lib/browser/constants/numericConstants.d.ts +1 -1
  6. package/lib/browser/constants/numericConstants.js +1 -1
  7. package/lib/browser/decode/user.js +5 -1
  8. package/lib/browser/idl/velocity.d.ts +191 -15
  9. package/lib/browser/idl/velocity.json +192 -16
  10. package/lib/browser/orderSubscriber/OrderSubscriber.d.ts +1 -0
  11. package/lib/browser/orderSubscriber/OrderSubscriber.js +10 -4
  12. package/lib/browser/pyth/pythLazerSubscriber.js +37 -27
  13. package/lib/browser/types.d.ts +6 -0
  14. package/lib/browser/user.d.ts +20 -3
  15. package/lib/browser/user.js +52 -4
  16. package/lib/browser/velocityClient.d.ts +46 -10
  17. package/lib/browser/velocityClient.js +107 -35
  18. package/lib/node/adminClient.d.ts +52 -0
  19. package/lib/node/adminClient.d.ts.map +1 -1
  20. package/lib/node/adminClient.js +97 -0
  21. package/lib/node/config.d.ts.map +1 -1
  22. package/lib/node/config.js +6 -7
  23. package/lib/node/constants/numericConstants.d.ts +1 -1
  24. package/lib/node/constants/numericConstants.d.ts.map +1 -1
  25. package/lib/node/constants/numericConstants.js +1 -1
  26. package/lib/node/decode/user.d.ts.map +1 -1
  27. package/lib/node/decode/user.js +5 -1
  28. package/lib/node/idl/velocity.d.ts +191 -15
  29. package/lib/node/idl/velocity.d.ts.map +1 -1
  30. package/lib/node/idl/velocity.json +192 -16
  31. package/lib/node/orderSubscriber/OrderSubscriber.d.ts +1 -0
  32. package/lib/node/orderSubscriber/OrderSubscriber.d.ts.map +1 -1
  33. package/lib/node/orderSubscriber/OrderSubscriber.js +10 -4
  34. package/lib/node/pyth/pythLazerSubscriber.d.ts.map +1 -1
  35. package/lib/node/pyth/pythLazerSubscriber.js +37 -27
  36. package/lib/node/types.d.ts +6 -0
  37. package/lib/node/types.d.ts.map +1 -1
  38. package/lib/node/user.d.ts +20 -3
  39. package/lib/node/user.d.ts.map +1 -1
  40. package/lib/node/user.js +52 -4
  41. package/lib/node/velocityClient.d.ts +46 -10
  42. package/lib/node/velocityClient.d.ts.map +1 -1
  43. package/lib/node/velocityClient.js +107 -35
  44. package/package.json +7 -3
  45. package/.prettierignore +0 -1
  46. package/CHANGELOG.md +0 -132
  47. package/build-browser.js +0 -58
  48. package/bunfig.toml +0 -3
  49. package/esbuild-shims.js +0 -12
  50. package/scripts/deposit-isolated-positions.ts +0 -110
  51. package/scripts/find-flagged-users.ts +0 -213
  52. package/scripts/grpc-client-test-comparison.ts +0 -372
  53. package/scripts/grpc-multiuser-client-test-comparison.ts +0 -158
  54. package/scripts/postbuild.js +0 -95
  55. package/scripts/single-grpc-client-test.ts +0 -284
  56. package/scripts/withdraw-isolated-positions.ts +0 -174
  57. package/src/accounts/README_WebSocketAccountSubscriberV2.md +0 -95
  58. package/src/accounts/README_WebSocketProgramAccountSubscriberV2.md +0 -135
  59. package/src/accounts/basicUserAccountSubscriber.ts +0 -79
  60. package/src/accounts/basicUserStatsAccountSubscriber.ts +0 -87
  61. package/src/accounts/bulkAccountLoader.ts +0 -358
  62. package/src/accounts/bulkUserStatsSubscription.ts +0 -40
  63. package/src/accounts/bulkUserSubscription.ts +0 -39
  64. package/src/accounts/customizedCadenceBulkAccountLoader.ts +0 -250
  65. package/src/accounts/fetch.ts +0 -200
  66. package/src/accounts/grpcAccountSubscriber.ts +0 -225
  67. package/src/accounts/grpcInsuranceFundStakeAccountSubscriber.ts +0 -73
  68. package/src/accounts/grpcMultiAccountSubscriber.ts +0 -566
  69. package/src/accounts/grpcMultiUserAccountSubscriber.ts +0 -328
  70. package/src/accounts/grpcProgramAccountSubscriber.ts +0 -264
  71. package/src/accounts/grpcUserAccountSubscriber.ts +0 -63
  72. package/src/accounts/grpcUserStatsAccountSubscriber.ts +0 -65
  73. package/src/accounts/grpcVelocityClientAccountSubscriber.ts +0 -257
  74. package/src/accounts/grpcVelocityClientAccountSubscriberV2.ts +0 -941
  75. package/src/accounts/laserProgramAccountSubscriber.ts +0 -266
  76. package/src/accounts/oneShotUserAccountSubscriber.ts +0 -88
  77. package/src/accounts/oneShotUserStatsAccountSubscriber.ts +0 -94
  78. package/src/accounts/pollingInsuranceFundStakeAccountSubscriber.ts +0 -223
  79. package/src/accounts/pollingOracleAccountSubscriber.ts +0 -151
  80. package/src/accounts/pollingTokenAccountSubscriber.ts +0 -147
  81. package/src/accounts/pollingUserAccountSubscriber.ts +0 -198
  82. package/src/accounts/pollingUserStatsAccountSubscriber.ts +0 -180
  83. package/src/accounts/pollingVelocityClientAccountSubscriber.ts +0 -774
  84. package/src/accounts/testBulkAccountLoader.ts +0 -59
  85. package/src/accounts/types.ts +0 -428
  86. package/src/accounts/utils.ts +0 -90
  87. package/src/accounts/webSocketAccountSubscriber.ts +0 -304
  88. package/src/accounts/webSocketAccountSubscriberV2.ts +0 -536
  89. package/src/accounts/webSocketInsuranceFundStakeAccountSubscriber.ts +0 -171
  90. package/src/accounts/webSocketProgramAccountSubscriber.ts +0 -244
  91. package/src/accounts/webSocketProgramAccountSubscriberV2.ts +0 -1048
  92. package/src/accounts/webSocketProgramAccountsSubscriberV2.ts +0 -1042
  93. package/src/accounts/webSocketUserAccountSubscriber.ts +0 -139
  94. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +0 -131
  95. package/src/accounts/webSocketVelocityClientAccountSubscriber.ts +0 -865
  96. package/src/accounts/webSocketVelocityClientAccountSubscriberV2.ts +0 -897
  97. package/src/accounts/websocketProgramUserAccountSubscriber.ts +0 -127
  98. package/src/addresses/marketAddresses.ts +0 -28
  99. package/src/addresses/pda.ts +0 -620
  100. package/src/adminClient.ts +0 -8136
  101. package/src/assert/assert.ts +0 -5
  102. package/src/auctionSubscriber/auctionSubscriber.ts +0 -86
  103. package/src/auctionSubscriber/auctionSubscriberGrpc.ts +0 -99
  104. package/src/auctionSubscriber/index.ts +0 -9
  105. package/src/auctionSubscriber/types.ts +0 -30
  106. package/src/bankrun/bankrunConnection.ts +0 -630
  107. package/src/blockhashSubscriber/BlockhashSubscriber.ts +0 -160
  108. package/src/blockhashSubscriber/index.ts +0 -6
  109. package/src/blockhashSubscriber/types.ts +0 -13
  110. package/src/clock/clockSubscriber.ts +0 -146
  111. package/src/config.ts +0 -312
  112. package/src/constants/index.ts +0 -9
  113. package/src/constants/numericConstants.ts +0 -194
  114. package/src/constants/perpMarkets.ts +0 -127
  115. package/src/constants/spotMarkets.ts +0 -104
  116. package/src/constants/txConstants.ts +0 -2
  117. package/src/constituentMap/constituentMap.ts +0 -305
  118. package/src/constituentMap/pollingConstituentAccountSubscriber.ts +0 -99
  119. package/src/constituentMap/webSocketConstituentAccountSubscriber.ts +0 -121
  120. package/src/core/VelocityCore.ts +0 -606
  121. package/src/core/index.ts +0 -12
  122. package/src/core/instructions/deposit.ts +0 -64
  123. package/src/core/instructions/fill.ts +0 -51
  124. package/src/core/instructions/funding.ts +0 -33
  125. package/src/core/instructions/liquidation.ts +0 -55
  126. package/src/core/instructions/orders.ts +0 -84
  127. package/src/core/instructions/perpOrders.ts +0 -312
  128. package/src/core/instructions/settlement.ts +0 -40
  129. package/src/core/instructions/trigger.ts +0 -41
  130. package/src/core/instructions/withdraw.ts +0 -65
  131. package/src/core/remainingAccounts.ts +0 -320
  132. package/src/core/signedMsg.ts +0 -109
  133. package/src/decode/customCoder.ts +0 -148
  134. package/src/decode/user.ts +0 -401
  135. package/src/dlob/DLOB.ts +0 -2793
  136. package/src/dlob/DLOBNode.ts +0 -305
  137. package/src/dlob/DLOBSubscriber.ts +0 -269
  138. package/src/dlob/NodeList.ts +0 -244
  139. package/src/dlob/orderBookLevels.ts +0 -695
  140. package/src/dlob/types.ts +0 -37
  141. package/src/events/eventList.ts +0 -114
  142. package/src/events/eventSubscriber.ts +0 -521
  143. package/src/events/eventsServerLogProvider.ts +0 -189
  144. package/src/events/fetchLogs.ts +0 -219
  145. package/src/events/parse.ts +0 -271
  146. package/src/events/pollingLogProvider.ts +0 -113
  147. package/src/events/sort.ts +0 -51
  148. package/src/events/txEventCache.ts +0 -92
  149. package/src/events/types.ts +0 -337
  150. package/src/events/webSocketLogProvider.ts +0 -152
  151. package/src/factory/bigNum.ts +0 -709
  152. package/src/factory/oracleClient.ts +0 -73
  153. package/src/idl/pyth.json +0 -142
  154. package/src/idl/pyth.ts +0 -97
  155. package/src/idl/pyth_solana_receiver.json +0 -628
  156. package/src/idl/token_faucet.json +0 -229
  157. package/src/idl/token_faucet.ts +0 -197
  158. package/src/idl/velocity.json +0 -23974
  159. package/src/idl/velocity.ts +0 -23980
  160. package/src/index.ts +0 -150
  161. package/src/indicative-quotes/indicativeQuotesSender.ts +0 -233
  162. package/src/isomorphic/README.md +0 -19
  163. package/src/isomorphic/anchor.browser.ts +0 -44
  164. package/src/isomorphic/anchor.node.ts +0 -1
  165. package/src/isomorphic/anchor.ts +0 -1
  166. package/src/isomorphic/anchor29.browser.ts +0 -24
  167. package/src/isomorphic/anchor29.node.ts +0 -1
  168. package/src/isomorphic/anchor29.ts +0 -1
  169. package/src/isomorphic/grpc.browser.ts +0 -4
  170. package/src/isomorphic/grpc.node.ts +0 -130
  171. package/src/isomorphic/grpc.ts +0 -1
  172. package/src/jupiter/jupiterClient.ts +0 -502
  173. package/src/keypair.ts +0 -32
  174. package/src/margin/README.md +0 -138
  175. package/src/marginCalculation.ts +0 -407
  176. package/src/marinade/idl/idl.json +0 -1962
  177. package/src/marinade/index.ts +0 -73
  178. package/src/marinade/types.ts +0 -3925
  179. package/src/math/amm.ts +0 -1758
  180. package/src/math/auction.ts +0 -480
  181. package/src/math/bankruptcy.ts +0 -138
  182. package/src/math/builder.ts +0 -130
  183. package/src/math/conversion.ts +0 -45
  184. package/src/math/exchangeStatus.ts +0 -261
  185. package/src/math/funding.ts +0 -498
  186. package/src/math/insurance.ts +0 -171
  187. package/src/math/liquidation.ts +0 -433
  188. package/src/math/margin.ts +0 -327
  189. package/src/math/market.ts +0 -487
  190. package/src/math/oracles.ts +0 -477
  191. package/src/math/orders.ts +0 -500
  192. package/src/math/position.ts +0 -381
  193. package/src/math/repeg.ts +0 -223
  194. package/src/math/spotBalance.ts +0 -996
  195. package/src/math/spotMarket.ts +0 -115
  196. package/src/math/spotPosition.ts +0 -263
  197. package/src/math/state.ts +0 -71
  198. package/src/math/superStake.ts +0 -602
  199. package/src/math/tiers.ts +0 -73
  200. package/src/math/trade.ts +0 -879
  201. package/src/math/utils.ts +0 -183
  202. package/src/memcmp.ts +0 -279
  203. package/src/oracles/oracleClientCache.ts +0 -41
  204. package/src/oracles/oracleId.ts +0 -99
  205. package/src/oracles/prelaunchOracleClient.ts +0 -63
  206. package/src/oracles/pythClient.ts +0 -125
  207. package/src/oracles/pythLazerClient.ts +0 -141
  208. package/src/oracles/quoteAssetOracleClient.ts +0 -43
  209. package/src/oracles/strictOraclePrice.ts +0 -40
  210. package/src/oracles/types.ts +0 -82
  211. package/src/oracles/utils.ts +0 -45
  212. package/src/orderParams.ts +0 -117
  213. package/src/orderSubscriber/OrderSubscriber.ts +0 -378
  214. package/src/orderSubscriber/PollingSubscription.ts +0 -50
  215. package/src/orderSubscriber/WebsocketSubscription.ts +0 -137
  216. package/src/orderSubscriber/grpcSubscription.ts +0 -155
  217. package/src/orderSubscriber/index.ts +0 -7
  218. package/src/orderSubscriber/types.ts +0 -64
  219. package/src/priorityFee/averageOverSlotsStrategy.ts +0 -17
  220. package/src/priorityFee/averageStrategy.ts +0 -13
  221. package/src/priorityFee/ewmaStrategy.ts +0 -51
  222. package/src/priorityFee/heliusPriorityFeeMethod.ts +0 -68
  223. package/src/priorityFee/index.ts +0 -16
  224. package/src/priorityFee/maxOverSlotsStrategy.ts +0 -18
  225. package/src/priorityFee/maxStrategy.ts +0 -8
  226. package/src/priorityFee/priorityFeeSubscriber.ts +0 -328
  227. package/src/priorityFee/priorityFeeSubscriberMap.ts +0 -134
  228. package/src/priorityFee/solanaPriorityFeeMethod.ts +0 -46
  229. package/src/priorityFee/types.ts +0 -82
  230. package/src/priorityFee/velocityPriorityFeeMethod.ts +0 -53
  231. package/src/pyth/constants.ts +0 -9
  232. package/src/pyth/index.ts +0 -15
  233. package/src/pyth/pythLazerSubscriber.ts +0 -365
  234. package/src/pyth/types.ts +0 -4451
  235. package/src/pyth/utils.ts +0 -13
  236. package/src/slot/SlotSubscriber.ts +0 -126
  237. package/src/slot/SlothashSubscriber.ts +0 -163
  238. package/src/swap/UnifiedSwapClient.ts +0 -315
  239. package/src/swift/grpcSignedMsgUserAccountSubscriber.ts +0 -81
  240. package/src/swift/index.ts +0 -10
  241. package/src/swift/signedMsgUserAccountSubscriber.ts +0 -251
  242. package/src/swift/swiftOrderSubscriber.ts +0 -351
  243. package/src/testClient.ts +0 -42
  244. package/src/titan/titanClient.ts +0 -438
  245. package/src/token/index.ts +0 -13
  246. package/src/tokenFaucet.ts +0 -296
  247. package/src/tx/baseTxSender.ts +0 -651
  248. package/src/tx/blockhashFetcher/baseBlockhashFetcher.ts +0 -31
  249. package/src/tx/blockhashFetcher/cachedBlockhashFetcher.ts +0 -105
  250. package/src/tx/blockhashFetcher/types.ts +0 -9
  251. package/src/tx/fastSingleTxSender.ts +0 -200
  252. package/src/tx/forwardOnlyTxSender.ts +0 -193
  253. package/src/tx/priorityFeeCalculator.ts +0 -117
  254. package/src/tx/reportTransactionError.ts +0 -176
  255. package/src/tx/retryTxSender.ts +0 -177
  256. package/src/tx/txHandler.ts +0 -1009
  257. package/src/tx/txParamProcessor.ts +0 -225
  258. package/src/tx/types.ts +0 -117
  259. package/src/tx/utils.ts +0 -133
  260. package/src/tx/whileValidTxSender.ts +0 -377
  261. package/src/types.ts +0 -2575
  262. package/src/user.ts +0 -5316
  263. package/src/userConfig.ts +0 -38
  264. package/src/userMap/PollingSubscription.ts +0 -61
  265. package/src/userMap/WebsocketSubscription.ts +0 -93
  266. package/src/userMap/grpcSubscription.ts +0 -93
  267. package/src/userMap/referrerMap.ts +0 -360
  268. package/src/userMap/revenueShareEscrowMap.ts +0 -342
  269. package/src/userMap/userMap.ts +0 -784
  270. package/src/userMap/userMapConfig.ts +0 -82
  271. package/src/userMap/userStatsMap.ts +0 -393
  272. package/src/userName.ts +0 -37
  273. package/src/userStats.ts +0 -159
  274. package/src/userStatsConfig.ts +0 -35
  275. package/src/util/TransactionConfirmationManager.ts +0 -333
  276. package/src/util/chainClock.ts +0 -65
  277. package/src/util/computeUnits.ts +0 -101
  278. package/src/util/digest.ts +0 -33
  279. package/src/util/ed25519Utils.ts +0 -95
  280. package/src/util/promiseTimeout.ts +0 -23
  281. package/src/velocityClient.ts +0 -14802
  282. package/src/velocityClientConfig.ts +0 -119
  283. package/src/wallet.ts +0 -91
  284. package/tests/VelocityCore/builder_escrow.test.ts +0 -121
  285. package/tests/VelocityCore/decode.test.ts +0 -16
  286. package/tests/VelocityCore/fill_trigger.test.ts +0 -73
  287. package/tests/VelocityCore/instructions.test.ts +0 -46
  288. package/tests/VelocityCore/pdas.test.ts +0 -30
  289. package/tests/VelocityCore/perp_orders.test.ts +0 -205
  290. package/tests/VelocityCore/remainingAccounts.test.ts +0 -72
  291. package/tests/VelocityCore/settlement_liquidation.test.ts +0 -69
  292. package/tests/accounts/customizedCadenceBulkAccountLoader.test.ts +0 -211
  293. package/tests/amm/test.ts +0 -2402
  294. package/tests/auctions/test.ts +0 -81
  295. package/tests/bn/test.ts +0 -355
  296. package/tests/builder/builderFee.test.ts +0 -42
  297. package/tests/ci/verifyConstants.ts +0 -393
  298. package/tests/decode/test.ts +0 -262
  299. package/tests/decode/userAccountBufferStrings.ts +0 -102
  300. package/tests/dlob/helpers.ts +0 -748
  301. package/tests/dlob/test.ts +0 -6969
  302. package/tests/dlob/tickSizeStandardization.ts +0 -545
  303. package/tests/events/parseLogsForCuUsage.ts +0 -139
  304. package/tests/exchangeStatus/test.ts +0 -45
  305. package/tests/insurance/test.ts +0 -40
  306. package/tests/liquidation/test.ts +0 -125
  307. package/tests/oracles/mmOracleGate.test.ts +0 -379
  308. package/tests/oracles/pythPegSnap.test.ts +0 -76
  309. package/tests/sdkParity/enumParity.test.ts +0 -84
  310. package/tests/sdkParity/marginCategoryFill.test.ts +0 -143
  311. package/tests/sdkParity/memcmpOffsets.test.ts +0 -139
  312. package/tests/spot/test.ts +0 -281
  313. package/tests/tx/TransactionConfirmationManager.test.ts +0 -312
  314. package/tests/tx/cachedBlockhashFetcher.test.ts +0 -96
  315. package/tests/tx/priorityFeeCalculator.ts +0 -77
  316. package/tests/tx/priorityFeeStrategy.ts +0 -95
  317. package/tests/user/bankruptcy.ts +0 -165
  318. package/tests/user/feeAndWithdrawLimits.ts +0 -284
  319. package/tests/user/getMarginCalculation.ts +0 -586
  320. package/tests/user/helpers.ts +0 -184
  321. package/tests/user/liquidations.ts +0 -129
  322. package/tests/user/marginCalculations.test.ts +0 -321
  323. package/tests/user/test.ts +0 -833
  324. package/tsconfig.browser.json +0 -18
  325. package/tsconfig.json +0 -36
@@ -1,59 +0,0 @@
1
- import { AccountToLoad, BulkAccountLoader } from './bulkAccountLoader';
2
-
3
- /**
4
- * Test-only `BulkAccountLoader` that overrides `loadChunk` to fetch each account individually via
5
- * `connection.getAccountInfoAndContext` instead of batching through `getMultipleAccounts`. Used
6
- * against test validators/bankrun connections that don't implement the `_rpcBatchRequest` path
7
- * the base class relies on. Preserves the same per-account slot/buffer dedup semantics as the
8
- * base class (an update is only dispatched if the new slot is not older and the buffer changed).
9
- */
10
- export class TestBulkAccountLoader extends BulkAccountLoader {
11
- /** Sequentially fetches every account in every chunk via individual RPC calls, dispatching callbacks for any that changed at a non-decreasing slot. Slower than the base class's batched `getMultipleAccounts` approach by design — intended for test environments only. */
12
- async loadChunk(accountsToLoadChunks: AccountToLoad[][]): Promise<void> {
13
- if (accountsToLoadChunks.length === 0) {
14
- return;
15
- }
16
-
17
- for (const accountsToLoadChunk of accountsToLoadChunks) {
18
- for (const accountToLoad of accountsToLoadChunk) {
19
- const account = await this.connection.getAccountInfoAndContext(
20
- accountToLoad.publicKey,
21
- this.commitment
22
- );
23
- const newSlot = account.context.slot;
24
- if (newSlot > this.mostRecentSlot) {
25
- this.mostRecentSlot = newSlot;
26
- }
27
-
28
- if (accountToLoad.callbacks.size === 0) {
29
- continue;
30
- }
31
-
32
- const key = accountToLoad.publicKey.toBase58();
33
- const prev = this.bufferAndSlotMap.get(key);
34
-
35
- if (prev && newSlot < prev.slot) {
36
- continue;
37
- }
38
-
39
- let newBuffer: Buffer | undefined = undefined;
40
-
41
- if (account.value) {
42
- newBuffer = account.value.data;
43
- }
44
-
45
- if (!prev) {
46
- this.bufferAndSlotMap.set(key, { slot: newSlot, buffer: newBuffer });
47
- this.handleAccountCallbacks(accountToLoad, newBuffer, newSlot);
48
- continue;
49
- }
50
-
51
- const oldBuffer = prev.buffer;
52
- if (newBuffer && (!oldBuffer || !newBuffer.equals(oldBuffer))) {
53
- this.bufferAndSlotMap.set(key, { slot: newSlot, buffer: newBuffer });
54
- this.handleAccountCallbacks(accountToLoad, newBuffer, newSlot);
55
- }
56
- }
57
- }
58
- }
59
- }
@@ -1,428 +0,0 @@
1
- /**
2
- * Account subscription interfaces and types.
3
- *
4
- * VelocityClient uses a `VelocityClientAccountSubscriber` (WebSocket or polling) to keep
5
- * market, oracle, and state accounts cached in memory. `User` uses a `UserAccountSubscriber`
6
- * for the individual User account. All subscribers implement the interfaces defined here.
7
- *
8
- * Implementations: `webSocketVelocityClientAccountSubscriber.ts` (default),
9
- * `pollingVelocityClientAccountSubscriber.ts`, `bulkAccountLoader.ts` (batched RPC).
10
- */
11
- import {
12
- SpotMarketAccount,
13
- PerpMarketAccount,
14
- OracleSource,
15
- StateAccount,
16
- UserAccount,
17
- UserStatsAccount,
18
- InsuranceFundStake,
19
- ConstituentAccount,
20
- } from '../types';
21
- import StrictEventEmitter from 'strict-event-emitter-types';
22
- import { EventEmitter } from 'events';
23
- import { Context, PublicKey } from '@solana/web3.js';
24
- import { Account } from '@solana/spl-token';
25
- import { OracleInfo, OraclePriceData } from '../oracles/types';
26
- import { User } from '../user';
27
- import { Client, CommitmentLevel, LaserstreamConfig } from '../isomorphic/grpc';
28
-
29
- /**
30
- * Common contract for a subscriber that tracks a single on-chain account of type `T`.
31
- * Implemented by the `WebSocketAccountSubscriber`/`WebSocketAccountSubscriberV2`,
32
- * `grpcAccountSubscriber`, and polling-loader-backed subscribers. `dataAndSlot` is
33
- * undefined until the first fetch/notification lands; once set, `data` and `slot`
34
- * are always updated together (see `DataAndSlot`) so a caller never sees data from
35
- * one slot paired with another.
36
- */
37
- export interface AccountSubscriber<T> {
38
- /** Latest decoded account data and the slot it was observed at, or undefined before the first load. */
39
- dataAndSlot?: DataAndSlot<T>;
40
- /**
41
- * Begins tracking the account, seeding `dataAndSlot` with an initial `fetch()` if not already
42
- * set, then attaching a live update source (WebSocket/gRPC notification or accountLoader
43
- * callback). Idempotent: calling again while already subscribed is a no-op.
44
- * @param onChange Invoked with the newly decoded account data whenever a strictly newer slot's
45
- * update is observed.
46
- */
47
- subscribe(onChange: (data: T) => void): Promise<void>;
48
- /** Fetches the account once via RPC and updates `dataAndSlot` if the response's slot is newer than what's cached. */
49
- fetch(): Promise<void>;
50
- /** Tears down the live update source. Safe to call when not subscribed. */
51
- unsubscribe(): Promise<void>;
52
-
53
- /**
54
- * Seeds or overwrites `dataAndSlot` without an RPC round trip. Used to inject data the caller
55
- * already has (e.g. from a prior fetch elsewhere) before `subscribe()` runs its own fetch.
56
- * @param userAccount Decoded account data to store.
57
- * @param slot Slot the data was observed at; defaults to 0 (the oldest-possible sentinel) if omitted, so a later real update always wins.
58
- */
59
- setData(userAccount: T, slot?: number): void;
60
- }
61
-
62
- /**
63
- * Contract for a subscriber that tracks every account matching a program-account filter
64
- * (e.g. all `User` accounts owned by the program), rather than one specific pubkey.
65
- * Implemented by `WebSocketProgramAccountSubscriber`, `WebSocketProgramAccountsSubscriberV2`,
66
- * `grpcProgramAccountSubscriber`, and `LaserstreamProgramAccountSubscriber`.
67
- */
68
- export interface ProgramAccountSubscriber<T> {
69
- /**
70
- * Subscribes to program-account change notifications matching the filters supplied at
71
- * construction.
72
- * @param onChange Invoked once per changed account with its pubkey, decoded data, the
73
- * notification's `Context` (including `slot`), and the raw account buffer.
74
- */
75
- subscribe(
76
- onChange: (
77
- accountId: PublicKey,
78
- data: T,
79
- context: Context,
80
- buffer: Buffer
81
- ) => void
82
- ): Promise<void>;
83
- /** Tears down the underlying subscription. Safe to call when not subscribed. */
84
- unsubscribe(): Promise<void>;
85
- }
86
-
87
- /**
88
- * Thrown by every subscriber's `assertIsSubscribed()`-guarded getter (e.g.
89
- * `getUserAccountAndSlot`, `getStateAccountAndSlot`) when called before `subscribe()` has
90
- * completed. This is the uniform contract across all subscriber implementations in this
91
- * directory: never read cached account data without having subscribed first.
92
- */
93
- export class NotSubscribedError extends Error {
94
- name = 'NotSubscribedError';
95
- }
96
-
97
- /**
98
- * Events emitted by a `VelocityClientAccountSubscriber` on its `eventEmitter`. `update` fires
99
- * after every individual account-specific event (state/market/oracle) as a generic "something
100
- * changed" signal; `error` surfaces underlying transport errors (e.g. RPC batch failures)
101
- * without unsubscribing.
102
- */
103
- export interface VelocityClientAccountEvents {
104
- stateAccountUpdate: (payload: StateAccount) => void;
105
- perpMarketAccountUpdate: (payload: PerpMarketAccount) => void;
106
- spotMarketAccountUpdate: (payload: SpotMarketAccount) => void;
107
- oraclePriceUpdate: (
108
- publicKey: PublicKey,
109
- oracleSource: OracleSource,
110
- data: OraclePriceData
111
- ) => void;
112
- userAccountUpdate: (payload: UserAccount) => void;
113
- update: void;
114
- error: (e: Error) => void;
115
- }
116
-
117
- /**
118
- * Contract for the subscriber `VelocityClient` uses to keep `State`, `PerpMarket`,
119
- * `SpotMarket`, and oracle accounts cached in memory. See `webSocketVelocityClientAccountSubscriber.ts`
120
- * (default, one WebSocket subscription per account), `pollingVelocityClientAccountSubscriber.ts`
121
- * (single `BulkAccountLoader` batches all accounts via periodic `getMultipleAccounts`), and
122
- * `grpcVelocityClientAccountSubscriber.ts`/`grpcVelocityClientAccountSubscriberV2.ts` (gRPC
123
- * Geyser stream). Accessor contracts differ by shape: the guarded singleton getters
124
- * (`getStateAccountAndSlot`) throw `NotSubscribedError` until `subscribe()` has completed; the
125
- * per-market/oracle accessors return `undefined` when that entry isn't cached yet; and the
126
- * collection getters (`getMarketAccountsAndSlots`, etc.) are cache reads that return a
127
- * possibly-empty array.
128
- */
129
- export interface VelocityClientAccountSubscriber {
130
- eventEmitter: StrictEventEmitter<EventEmitter, VelocityClientAccountEvents>;
131
- isSubscribed: boolean;
132
-
133
- subscribe(): Promise<boolean>;
134
- fetch(): Promise<void>;
135
- unsubscribe(): Promise<void>;
136
-
137
- addPerpMarket(marketIndex: number): Promise<boolean>;
138
- addSpotMarket(marketIndex: number): Promise<boolean>;
139
- addOracle(oracleInfo: OracleInfo): Promise<boolean>;
140
- setPerpOracleMap(): Promise<void>;
141
- setSpotOracleMap(): Promise<void>;
142
-
143
- getStateAccountAndSlot(): DataAndSlot<StateAccount>;
144
- getMarketAccountAndSlot(
145
- marketIndex: number
146
- ): DataAndSlot<PerpMarketAccount> | undefined;
147
- getMarketAccountsAndSlots(): DataAndSlot<PerpMarketAccount>[];
148
- getSpotMarketAccountAndSlot(
149
- marketIndex: number
150
- ): DataAndSlot<SpotMarketAccount> | undefined;
151
- getSpotMarketAccountsAndSlots(): DataAndSlot<SpotMarketAccount>[];
152
- getOraclePriceDataAndSlot(
153
- oracleId: string
154
- ): DataAndSlot<OraclePriceData> | undefined;
155
- getOraclePriceDataAndSlotForPerpMarket(
156
- marketIndex: number
157
- ): DataAndSlot<OraclePriceData> | undefined;
158
- getOraclePriceDataAndSlotForSpotMarket(
159
- marketIndex: number
160
- ): DataAndSlot<OraclePriceData> | undefined;
161
-
162
- /** Present only on polling-backed implementations; retunes the shared `BulkAccountLoader`'s poll interval (ms) for all accounts it batches. */
163
- updateAccountLoaderPollingFrequency?: (pollingFrequency: number) => void;
164
- }
165
-
166
- /**
167
- * Controls what a `VelocityClientAccountSubscriber` does with a perp market (and its oracle, if
168
- * unused elsewhere) once the on-chain market status becomes `delisted`.
169
- */
170
- export enum DelistedMarketSetting {
171
- /** Drop the live subscription for the delisted market/oracle but keep the last-known data cached. */
172
- Unsubscribe,
173
- /** Keep subscribing to the delisted market/oracle as normal (no special handling). */
174
- Subscribe,
175
- /** Drop the subscription and remove the market/oracle from the subscriber's internal maps entirely. */
176
- Discard,
177
- }
178
-
179
- /** Events emitted by a `UserAccountSubscriber` on its `eventEmitter`. `update` fires alongside every `userAccountUpdate`. */
180
- export interface UserAccountEvents {
181
- userAccountUpdate: (payload: UserAccount) => void;
182
- update: void;
183
- error: (e: Error) => void;
184
- }
185
-
186
- /** Events emitted at the `User` (SDK wrapper) level, distinct from the lower-level `UserAccountEvents`. */
187
- export interface UserEvents {
188
- userUpdate: (payload: User) => void;
189
- update: void;
190
- error: (e: Error) => void;
191
- }
192
-
193
- /**
194
- * Contract for the subscriber `User` uses to track a single `UserAccount`. Implementations:
195
- * `WebSocketUserAccountSubscriber` (default), `PollingUserAccountSubscriber` (via
196
- * `BulkAccountLoader`), `grpcUserAccountSubscriber`, `OneShotUserAccountSubscriber` (fetch-only,
197
- * ~1 RPC call), `BasicUserAccountSubscriber` (no network I/O, data supplied by the caller), and
198
- * `WebSocketProgramUserAccountSubscriber` (filters a shared program-account stream).
199
- */
200
- export interface UserAccountSubscriber {
201
- eventEmitter: StrictEventEmitter<EventEmitter, UserAccountEvents>;
202
- isSubscribed: boolean;
203
-
204
- /**
205
- * @param userAccount Optional pre-fetched account data to seed the subscriber with, skipping
206
- * the initial RPC fetch.
207
- */
208
- subscribe(userAccount?: UserAccount): Promise<boolean>;
209
- fetch(): Promise<void>;
210
- /**
211
- * Applies an externally-obtained account update (e.g. relayed from a parent subscriber) if its
212
- * slot is not older than the currently cached one, emitting `userAccountUpdate`/`update` on
213
- * acceptance.
214
- * @param userAccount Decoded account data to apply.
215
- * @param slot Slot the data was observed at.
216
- */
217
- updateData(userAccount: UserAccount, slot: number): void;
218
- unsubscribe(): Promise<void>;
219
-
220
- /** Throws `NotSubscribedError` if not subscribed. Returns undefined only if subscribed but no data has loaded yet. */
221
- getUserAccountAndSlot(): DataAndSlot<UserAccount> | undefined;
222
- }
223
-
224
- /** Events emitted by a `TokenAccountSubscriber` on its `eventEmitter`. */
225
- export interface TokenAccountEvents {
226
- tokenAccountUpdate: (payload: Account) => void;
227
- update: void;
228
- error: (e: Error) => void;
229
- }
230
-
231
- /** Contract for tracking an SPL token account balance (e.g. a spot market vault or a user's token wallet). Implemented by `PollingTokenAccountSubscriber`. */
232
- export interface TokenAccountSubscriber {
233
- eventEmitter: StrictEventEmitter<EventEmitter, TokenAccountEvents>;
234
- isSubscribed: boolean;
235
-
236
- subscribe(): Promise<boolean>;
237
- fetch(): Promise<void>;
238
- unsubscribe(): Promise<void>;
239
-
240
- /** Throws `NotSubscribedError` if not subscribed. */
241
- getTokenAccountAndSlot(): DataAndSlot<Account>;
242
- }
243
-
244
- /**
245
- * Contract for tracking an `InsuranceFundStake` account. Implementations:
246
- * `WebSocketInsuranceFundStakeAccountSubscriber` (default), `PollingInsuranceFundStakeAccountSubscriber`,
247
- * and `grpcInsuranceFundStakeAccountSubscriber`.
248
- */
249
- export interface InsuranceFundStakeAccountSubscriber {
250
- eventEmitter: StrictEventEmitter<
251
- EventEmitter,
252
- InsuranceFundStakeAccountEvents
253
- >;
254
- isSubscribed: boolean;
255
-
256
- subscribe(): Promise<boolean>;
257
- fetch(): Promise<void>;
258
- unsubscribe(): Promise<void>;
259
-
260
- /** Throws `NotSubscribedError` if not subscribed. */
261
- getInsuranceFundStakeAccountAndSlot():
262
- | DataAndSlot<InsuranceFundStake>
263
- | undefined;
264
- }
265
-
266
- /** Events emitted by an `InsuranceFundStakeAccountSubscriber` on its `eventEmitter`. */
267
- export interface InsuranceFundStakeAccountEvents {
268
- insuranceFundStakeAccountUpdate: (payload: InsuranceFundStake) => void;
269
- update: void;
270
- error: (e: Error) => void;
271
- }
272
-
273
- /** Events emitted by an `OracleAccountSubscriber` on its `eventEmitter`. */
274
- export interface OracleEvents {
275
- oracleUpdate: (payload: OraclePriceData) => void;
276
- update: void;
277
- error: (e: Error) => void;
278
- }
279
-
280
- /** Contract for tracking a single oracle account's decoded price data. Implemented by `PollingOracleAccountSubscriber` (via `BulkAccountLoader`). */
281
- export interface OracleAccountSubscriber {
282
- eventEmitter: StrictEventEmitter<EventEmitter, OracleEvents>;
283
- isSubscribed: boolean;
284
-
285
- subscribe(): Promise<boolean>;
286
- fetch(): Promise<void>;
287
- unsubscribe(): Promise<void>;
288
-
289
- /** Throws `NotSubscribedError` if not subscribed. */
290
- getOraclePriceData(): DataAndSlot<OraclePriceData>;
291
- }
292
-
293
- /** A `state`/`perpMarket`/`spotMarket` account registered with a `PollingVelocityClientAccountSubscriber`'s `BulkAccountLoader`. */
294
- export type AccountToPoll = {
295
- /** Anchor account discriminator name, also used to route the decoded data and pick the emitted event. */
296
- key: 'state' | 'perpMarket' | 'spotMarket';
297
- publicKey: PublicKey;
298
- /** `VelocityClientAccountEvents` key emitted when this account changes. */
299
- eventType: string;
300
- /** `BulkAccountLoader` callback id, set once registered; used to remove the account later. */
301
- callbackId?: string;
302
- /** For `perpMarket`/`spotMarket`, the market index this account decodes to. */
303
- mapKey?: number;
304
- };
305
-
306
- /** An oracle account registered with a `PollingVelocityClientAccountSubscriber`'s `BulkAccountLoader`. */
307
- export type OraclesToPoll = {
308
- publicKey: PublicKey;
309
- source: OracleSource;
310
- /** `BulkAccountLoader` callback id, set once registered; used to remove the oracle later. */
311
- callbackId?: string;
312
- };
313
-
314
- /** Raw account buffer paired with the slot it was fetched/observed at; the buffer is undefined if the account does not exist on-chain. */
315
- export type BufferAndSlot = {
316
- slot: number;
317
- buffer: Buffer | undefined;
318
- };
319
-
320
- /**
321
- * A decoded account payload paired atomically with the slot it was observed at. Every
322
- * `AccountSubscriber`/getter in this directory updates `data` and `slot` together in a single
323
- * assignment, so a caller reading `dataAndSlot` never sees data from one slot mixed with a slot
324
- * number from another. `slot === 0` is the seeded sentinel used when data is injected via
325
- * `setData`/a constructor without a real fetch (e.g. `BasicUserAccountSubscriber`) — it is
326
- * always superseded once a real fetch or notification lands, since updates only apply when the
327
- * new slot is `>=` the cached one.
328
- */
329
- export type DataAndSlot<T> = {
330
- data: T;
331
- slot: number;
332
- };
333
-
334
- /** Resubscription/polling-fallback tuning for WebSocket- and gRPC-backed subscribers. */
335
- export type ResubOpts = {
336
- /**
337
- * Milliseconds of inactivity (no notification) before the subscriber treats the stream as
338
- * stalled and resubscribes (or starts polling, see `usePollingInsteadOfResub`). Should be at
339
- * least 1000ms; smaller values log a warning. Leave undefined to disable the inactivity
340
- * watchdog entirely.
341
- */
342
- resubTimeoutMs?: number;
343
- /** Emits verbose `console.log`/`console.debug` diagnostics for resub/polling transitions. Defaults to false. */
344
- logResubMessages?: boolean;
345
- // New options for polling-based resubscription
346
- /**
347
- * On inactivity timeout, poll via RPC to check for a missed update instead of immediately
348
- * tearing down and recreating the WebSocket subscription. Defaults to false on the v1
349
- * `WebSocketAccountSubscriber`; the V2 subscribers default this to `true`.
350
- */
351
- usePollingInsteadOfResub?: boolean;
352
- /** Polling cadence in ms when `usePollingInsteadOfResub` is active. Defaults to 30000 (30s). */
353
- pollingIntervalMs?: number;
354
- };
355
-
356
- /** Events emitted by a `UserStatsAccountSubscriber` on its `eventEmitter`. */
357
- export interface UserStatsAccountEvents {
358
- userStatsAccountUpdate: (payload: UserStatsAccount) => void;
359
- update: void;
360
- error: (e: Error) => void;
361
- }
362
-
363
- /**
364
- * Contract for the subscriber `UserStats` uses to track a single `UserStatsAccount`.
365
- * Implementations mirror `UserAccountSubscriber`: `WebSocketUserStatsAccountSubscriber` (default),
366
- * `PollingUserStatsAccountSubscriber`, `grpcUserStatsAccountSubscriber`,
367
- * `OneShotUserStatsAccountSubscriber`, and `BasicUserStatsAccountSubscriber`.
368
- */
369
- export interface UserStatsAccountSubscriber {
370
- eventEmitter: StrictEventEmitter<EventEmitter, UserStatsAccountEvents>;
371
- isSubscribed: boolean;
372
-
373
- /** @param userStatsAccount Optional pre-fetched account data to seed the subscriber with, skipping the initial RPC fetch. */
374
- subscribe(userStatsAccount?: UserStatsAccount): Promise<boolean>;
375
- fetch(): Promise<void>;
376
- unsubscribe(): Promise<void>;
377
-
378
- /** Throws `NotSubscribedError` if not subscribed. Returns undefined only if subscribed but no data has loaded yet. */
379
- getUserStatsAccountAndSlot(): DataAndSlot<UserStatsAccount> | undefined;
380
- }
381
-
382
- type BaseGrpcConfigs = {
383
- endpoint: string;
384
- token: string;
385
- commitmentLevel?: CommitmentLevel;
386
- /**
387
- * Whether to enable automatic reconnection on connection loss .
388
- * Defaults to false, will throw on connection loss.
389
- */
390
- enableReconnect?: boolean;
391
- };
392
-
393
- /** gRPC Geyser config for the default Yellowstone (Triton/Dragon's Mouth-compatible) client. */
394
- export type YellowstoneGrpcConfigs = BaseGrpcConfigs & {
395
- client?: 'yellowstone';
396
- channelOptions?: ConstructorParameters<typeof Client>[2];
397
- };
398
-
399
- /** gRPC Geyser config for the Helius LaserStream client (`LaserstreamProgramAccountSubscriber`). Requires the optional `helius-laserstream` peer dependency. */
400
- export type LaserGrpcConfigs = BaseGrpcConfigs & {
401
- client: 'laser';
402
- channelOptions?: LaserstreamConfig['channelOptions'];
403
- };
404
-
405
- /** Union of supported gRPC Geyser client configs; the `client` discriminant selects Yellowstone vs. LaserStream. */
406
- export type GrpcConfigs = YellowstoneGrpcConfigs | LaserGrpcConfigs;
407
-
408
- /** Contract for tracking an LP-pool `ConstituentAccount`. `sync()` is the fetch/reconcile entry point (analogous to `fetch()` on other subscribers). */
409
- export interface ConstituentAccountSubscriber {
410
- eventEmitter: StrictEventEmitter<EventEmitter, ConstituentAccountEvents>;
411
- isSubscribed: boolean;
412
-
413
- /** @param constituentAccount Optional pre-fetched account data to seed the subscriber with. */
414
- subscribe(constituentAccount?: ConstituentAccount): Promise<boolean>;
415
- sync(): Promise<void>;
416
- unsubscribe(): Promise<void>;
417
- }
418
-
419
- /** Events emitted by a `ConstituentAccountSubscriber` on its `eventEmitter`. */
420
- export interface ConstituentAccountEvents {
421
- onAccountUpdate: (
422
- account: ConstituentAccount,
423
- pubkey: PublicKey,
424
- slot: number
425
- ) => void;
426
- update: void;
427
- error: (e: Error) => void;
428
- }
@@ -1,90 +0,0 @@
1
- import { DataAndSlot } from './types';
2
- import { isVariant, PerpMarketAccount, SpotMarketAccount } from '../types';
3
- import { OracleInfo } from '../oracles/types';
4
- import { getOracleId } from '../oracles/oracleId';
5
-
6
- /** Capitalizes the first character of `value` (e.g. for building Anchor event/method names from account names). */
7
- export function capitalize(value: string): string {
8
- return value[0].toUpperCase() + value.slice(1);
9
- }
10
-
11
- /**
12
- * Unwraps a possibly-undefined `DataAndSlot<T>`, throwing if it hasn't loaded. Use this instead
13
- * of a bare non-null assertion when a subscriber's cached data must be present by this point.
14
- * @param dataAndSlot The cached data/slot pair to check, typically from `AccountSubscriber.dataAndSlot`.
15
- * @param message Error message to throw if `dataAndSlot` is undefined.
16
- * @returns The same `dataAndSlot`, narrowed to non-undefined.
17
- */
18
- export function assertDataAndSlot<T>(
19
- dataAndSlot: DataAndSlot<T> | undefined,
20
- message: string
21
- ): DataAndSlot<T> {
22
- if (!dataAndSlot) {
23
- throw new Error(message);
24
- }
25
- return dataAndSlot;
26
- }
27
-
28
- /**
29
- * Scans cached perp/spot market data for perp markets with `status: delisted` and identifies
30
- * both the delisted market indexes and their oracles, excluding any oracle still in use by a
31
- * spot market or a non-delisted perp market (so a shared oracle isn't dropped out from under a
32
- * still-live market). Used by `VelocityClientAccountSubscriber` implementations to drive
33
- * `DelistedMarketSetting` (unsubscribe/discard) handling.
34
- * @param perpMarkets Currently cached perp market data/slots (entries with missing `data` are skipped).
35
- * @param spotMarkets Currently cached spot market data/slots, checked to avoid dropping oracles they still reference.
36
- * @returns `perpMarketIndexes` of delisted perp markets and `oracles` safe to stop tracking.
37
- */
38
- export function findDelistedPerpMarketsAndOracles(
39
- perpMarkets: DataAndSlot<PerpMarketAccount>[],
40
- spotMarkets: DataAndSlot<SpotMarketAccount>[]
41
- ): { perpMarketIndexes: number[]; oracles: OracleInfo[] } {
42
- const delistedPerpMarketIndexes = [];
43
- const delistedOracles: OracleInfo[] = [];
44
- for (const perpMarket of perpMarkets) {
45
- if (!perpMarket || !perpMarket.data) {
46
- continue;
47
- }
48
-
49
- if (isVariant(perpMarket.data.status, 'delisted')) {
50
- delistedPerpMarketIndexes.push(perpMarket.data.marketIndex);
51
- delistedOracles.push({
52
- publicKey: perpMarket.data.oracle,
53
- source: perpMarket.data.oracleSource,
54
- });
55
- }
56
- }
57
-
58
- // make sure oracle isn't still used by a spot market or a live perp market
59
- const liveOracleIds = new Set<string>();
60
- for (const spotMarket of spotMarkets) {
61
- if (!spotMarket || !spotMarket.data) {
62
- continue;
63
- }
64
- liveOracleIds.add(
65
- getOracleId(spotMarket.data.oracle, spotMarket.data.oracleSource)
66
- );
67
- }
68
- for (const perpMarket of perpMarkets) {
69
- if (!perpMarket || !perpMarket.data) {
70
- continue;
71
- }
72
- if (!isVariant(perpMarket.data.status, 'delisted')) {
73
- liveOracleIds.add(
74
- getOracleId(perpMarket.data.oracle, perpMarket.data.oracleSource)
75
- );
76
- }
77
- }
78
-
79
- const filteredDelistedOracles = delistedOracles.filter(
80
- (delistedOracle) =>
81
- !liveOracleIds.has(
82
- getOracleId(delistedOracle.publicKey, delistedOracle.source)
83
- )
84
- );
85
-
86
- return {
87
- perpMarketIndexes: delistedPerpMarketIndexes,
88
- oracles: filteredDelistedOracles,
89
- };
90
- }