@velocity-exchange/sdk 0.4.0 → 0.6.0

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 (323) hide show
  1. package/README.md +3 -3
  2. package/lib/browser/adminClient.d.ts +35 -0
  3. package/lib/browser/adminClient.js +65 -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 +146 -3
  9. package/lib/browser/idl/velocity.json +147 -4
  10. package/lib/browser/orderSubscriber/OrderSubscriber.js +3 -0
  11. package/lib/browser/pyth/pythLazerSubscriber.js +37 -27
  12. package/lib/browser/types.d.ts +4 -0
  13. package/lib/browser/user.d.ts +15 -0
  14. package/lib/browser/user.js +37 -1
  15. package/lib/browser/velocityClient.d.ts +46 -10
  16. package/lib/browser/velocityClient.js +107 -35
  17. package/lib/node/adminClient.d.ts +35 -0
  18. package/lib/node/adminClient.d.ts.map +1 -1
  19. package/lib/node/adminClient.js +65 -0
  20. package/lib/node/config.d.ts.map +1 -1
  21. package/lib/node/config.js +6 -7
  22. package/lib/node/constants/numericConstants.d.ts +1 -1
  23. package/lib/node/constants/numericConstants.d.ts.map +1 -1
  24. package/lib/node/constants/numericConstants.js +1 -1
  25. package/lib/node/decode/user.d.ts.map +1 -1
  26. package/lib/node/decode/user.js +5 -1
  27. package/lib/node/idl/velocity.d.ts +146 -3
  28. package/lib/node/idl/velocity.d.ts.map +1 -1
  29. package/lib/node/idl/velocity.json +147 -4
  30. package/lib/node/orderSubscriber/OrderSubscriber.d.ts.map +1 -1
  31. package/lib/node/orderSubscriber/OrderSubscriber.js +3 -0
  32. package/lib/node/pyth/pythLazerSubscriber.d.ts.map +1 -1
  33. package/lib/node/pyth/pythLazerSubscriber.js +37 -27
  34. package/lib/node/types.d.ts +4 -0
  35. package/lib/node/types.d.ts.map +1 -1
  36. package/lib/node/user.d.ts +15 -0
  37. package/lib/node/user.d.ts.map +1 -1
  38. package/lib/node/user.js +37 -1
  39. package/lib/node/velocityClient.d.ts +46 -10
  40. package/lib/node/velocityClient.d.ts.map +1 -1
  41. package/lib/node/velocityClient.js +107 -35
  42. package/package.json +7 -3
  43. package/.prettierignore +0 -1
  44. package/CHANGELOG.md +0 -132
  45. package/build-browser.js +0 -58
  46. package/bunfig.toml +0 -3
  47. package/esbuild-shims.js +0 -12
  48. package/scripts/deposit-isolated-positions.ts +0 -110
  49. package/scripts/find-flagged-users.ts +0 -213
  50. package/scripts/grpc-client-test-comparison.ts +0 -372
  51. package/scripts/grpc-multiuser-client-test-comparison.ts +0 -158
  52. package/scripts/postbuild.js +0 -95
  53. package/scripts/single-grpc-client-test.ts +0 -284
  54. package/scripts/withdraw-isolated-positions.ts +0 -174
  55. package/src/accounts/README_WebSocketAccountSubscriberV2.md +0 -95
  56. package/src/accounts/README_WebSocketProgramAccountSubscriberV2.md +0 -135
  57. package/src/accounts/basicUserAccountSubscriber.ts +0 -79
  58. package/src/accounts/basicUserStatsAccountSubscriber.ts +0 -87
  59. package/src/accounts/bulkAccountLoader.ts +0 -358
  60. package/src/accounts/bulkUserStatsSubscription.ts +0 -40
  61. package/src/accounts/bulkUserSubscription.ts +0 -39
  62. package/src/accounts/customizedCadenceBulkAccountLoader.ts +0 -250
  63. package/src/accounts/fetch.ts +0 -200
  64. package/src/accounts/grpcAccountSubscriber.ts +0 -225
  65. package/src/accounts/grpcInsuranceFundStakeAccountSubscriber.ts +0 -73
  66. package/src/accounts/grpcMultiAccountSubscriber.ts +0 -566
  67. package/src/accounts/grpcMultiUserAccountSubscriber.ts +0 -328
  68. package/src/accounts/grpcProgramAccountSubscriber.ts +0 -264
  69. package/src/accounts/grpcUserAccountSubscriber.ts +0 -63
  70. package/src/accounts/grpcUserStatsAccountSubscriber.ts +0 -65
  71. package/src/accounts/grpcVelocityClientAccountSubscriber.ts +0 -257
  72. package/src/accounts/grpcVelocityClientAccountSubscriberV2.ts +0 -941
  73. package/src/accounts/laserProgramAccountSubscriber.ts +0 -266
  74. package/src/accounts/oneShotUserAccountSubscriber.ts +0 -88
  75. package/src/accounts/oneShotUserStatsAccountSubscriber.ts +0 -94
  76. package/src/accounts/pollingInsuranceFundStakeAccountSubscriber.ts +0 -223
  77. package/src/accounts/pollingOracleAccountSubscriber.ts +0 -151
  78. package/src/accounts/pollingTokenAccountSubscriber.ts +0 -147
  79. package/src/accounts/pollingUserAccountSubscriber.ts +0 -198
  80. package/src/accounts/pollingUserStatsAccountSubscriber.ts +0 -180
  81. package/src/accounts/pollingVelocityClientAccountSubscriber.ts +0 -774
  82. package/src/accounts/testBulkAccountLoader.ts +0 -59
  83. package/src/accounts/types.ts +0 -428
  84. package/src/accounts/utils.ts +0 -90
  85. package/src/accounts/webSocketAccountSubscriber.ts +0 -304
  86. package/src/accounts/webSocketAccountSubscriberV2.ts +0 -536
  87. package/src/accounts/webSocketInsuranceFundStakeAccountSubscriber.ts +0 -171
  88. package/src/accounts/webSocketProgramAccountSubscriber.ts +0 -244
  89. package/src/accounts/webSocketProgramAccountSubscriberV2.ts +0 -1048
  90. package/src/accounts/webSocketProgramAccountsSubscriberV2.ts +0 -1042
  91. package/src/accounts/webSocketUserAccountSubscriber.ts +0 -139
  92. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +0 -131
  93. package/src/accounts/webSocketVelocityClientAccountSubscriber.ts +0 -865
  94. package/src/accounts/webSocketVelocityClientAccountSubscriberV2.ts +0 -897
  95. package/src/accounts/websocketProgramUserAccountSubscriber.ts +0 -127
  96. package/src/addresses/marketAddresses.ts +0 -28
  97. package/src/addresses/pda.ts +0 -620
  98. package/src/adminClient.ts +0 -8136
  99. package/src/assert/assert.ts +0 -5
  100. package/src/auctionSubscriber/auctionSubscriber.ts +0 -86
  101. package/src/auctionSubscriber/auctionSubscriberGrpc.ts +0 -99
  102. package/src/auctionSubscriber/index.ts +0 -9
  103. package/src/auctionSubscriber/types.ts +0 -30
  104. package/src/bankrun/bankrunConnection.ts +0 -630
  105. package/src/blockhashSubscriber/BlockhashSubscriber.ts +0 -160
  106. package/src/blockhashSubscriber/index.ts +0 -6
  107. package/src/blockhashSubscriber/types.ts +0 -13
  108. package/src/clock/clockSubscriber.ts +0 -146
  109. package/src/config.ts +0 -312
  110. package/src/constants/index.ts +0 -9
  111. package/src/constants/numericConstants.ts +0 -194
  112. package/src/constants/perpMarkets.ts +0 -127
  113. package/src/constants/spotMarkets.ts +0 -104
  114. package/src/constants/txConstants.ts +0 -2
  115. package/src/constituentMap/constituentMap.ts +0 -305
  116. package/src/constituentMap/pollingConstituentAccountSubscriber.ts +0 -99
  117. package/src/constituentMap/webSocketConstituentAccountSubscriber.ts +0 -121
  118. package/src/core/VelocityCore.ts +0 -606
  119. package/src/core/index.ts +0 -12
  120. package/src/core/instructions/deposit.ts +0 -64
  121. package/src/core/instructions/fill.ts +0 -51
  122. package/src/core/instructions/funding.ts +0 -33
  123. package/src/core/instructions/liquidation.ts +0 -55
  124. package/src/core/instructions/orders.ts +0 -84
  125. package/src/core/instructions/perpOrders.ts +0 -312
  126. package/src/core/instructions/settlement.ts +0 -40
  127. package/src/core/instructions/trigger.ts +0 -41
  128. package/src/core/instructions/withdraw.ts +0 -65
  129. package/src/core/remainingAccounts.ts +0 -320
  130. package/src/core/signedMsg.ts +0 -109
  131. package/src/decode/customCoder.ts +0 -148
  132. package/src/decode/user.ts +0 -401
  133. package/src/dlob/DLOB.ts +0 -2793
  134. package/src/dlob/DLOBNode.ts +0 -305
  135. package/src/dlob/DLOBSubscriber.ts +0 -269
  136. package/src/dlob/NodeList.ts +0 -244
  137. package/src/dlob/orderBookLevels.ts +0 -695
  138. package/src/dlob/types.ts +0 -37
  139. package/src/events/eventList.ts +0 -114
  140. package/src/events/eventSubscriber.ts +0 -521
  141. package/src/events/eventsServerLogProvider.ts +0 -189
  142. package/src/events/fetchLogs.ts +0 -219
  143. package/src/events/parse.ts +0 -271
  144. package/src/events/pollingLogProvider.ts +0 -113
  145. package/src/events/sort.ts +0 -51
  146. package/src/events/txEventCache.ts +0 -92
  147. package/src/events/types.ts +0 -337
  148. package/src/events/webSocketLogProvider.ts +0 -152
  149. package/src/factory/bigNum.ts +0 -709
  150. package/src/factory/oracleClient.ts +0 -73
  151. package/src/idl/pyth.json +0 -142
  152. package/src/idl/pyth.ts +0 -97
  153. package/src/idl/pyth_solana_receiver.json +0 -628
  154. package/src/idl/token_faucet.json +0 -229
  155. package/src/idl/token_faucet.ts +0 -197
  156. package/src/idl/velocity.json +0 -23974
  157. package/src/idl/velocity.ts +0 -23980
  158. package/src/index.ts +0 -150
  159. package/src/indicative-quotes/indicativeQuotesSender.ts +0 -233
  160. package/src/isomorphic/README.md +0 -19
  161. package/src/isomorphic/anchor.browser.ts +0 -44
  162. package/src/isomorphic/anchor.node.ts +0 -1
  163. package/src/isomorphic/anchor.ts +0 -1
  164. package/src/isomorphic/anchor29.browser.ts +0 -24
  165. package/src/isomorphic/anchor29.node.ts +0 -1
  166. package/src/isomorphic/anchor29.ts +0 -1
  167. package/src/isomorphic/grpc.browser.ts +0 -4
  168. package/src/isomorphic/grpc.node.ts +0 -130
  169. package/src/isomorphic/grpc.ts +0 -1
  170. package/src/jupiter/jupiterClient.ts +0 -502
  171. package/src/keypair.ts +0 -32
  172. package/src/margin/README.md +0 -138
  173. package/src/marginCalculation.ts +0 -407
  174. package/src/marinade/idl/idl.json +0 -1962
  175. package/src/marinade/index.ts +0 -73
  176. package/src/marinade/types.ts +0 -3925
  177. package/src/math/amm.ts +0 -1758
  178. package/src/math/auction.ts +0 -480
  179. package/src/math/bankruptcy.ts +0 -138
  180. package/src/math/builder.ts +0 -130
  181. package/src/math/conversion.ts +0 -45
  182. package/src/math/exchangeStatus.ts +0 -261
  183. package/src/math/funding.ts +0 -498
  184. package/src/math/insurance.ts +0 -171
  185. package/src/math/liquidation.ts +0 -433
  186. package/src/math/margin.ts +0 -327
  187. package/src/math/market.ts +0 -487
  188. package/src/math/oracles.ts +0 -477
  189. package/src/math/orders.ts +0 -500
  190. package/src/math/position.ts +0 -381
  191. package/src/math/repeg.ts +0 -223
  192. package/src/math/spotBalance.ts +0 -996
  193. package/src/math/spotMarket.ts +0 -115
  194. package/src/math/spotPosition.ts +0 -263
  195. package/src/math/state.ts +0 -71
  196. package/src/math/superStake.ts +0 -602
  197. package/src/math/tiers.ts +0 -73
  198. package/src/math/trade.ts +0 -879
  199. package/src/math/utils.ts +0 -183
  200. package/src/memcmp.ts +0 -279
  201. package/src/oracles/oracleClientCache.ts +0 -41
  202. package/src/oracles/oracleId.ts +0 -99
  203. package/src/oracles/prelaunchOracleClient.ts +0 -63
  204. package/src/oracles/pythClient.ts +0 -125
  205. package/src/oracles/pythLazerClient.ts +0 -141
  206. package/src/oracles/quoteAssetOracleClient.ts +0 -43
  207. package/src/oracles/strictOraclePrice.ts +0 -40
  208. package/src/oracles/types.ts +0 -82
  209. package/src/oracles/utils.ts +0 -45
  210. package/src/orderParams.ts +0 -117
  211. package/src/orderSubscriber/OrderSubscriber.ts +0 -378
  212. package/src/orderSubscriber/PollingSubscription.ts +0 -50
  213. package/src/orderSubscriber/WebsocketSubscription.ts +0 -137
  214. package/src/orderSubscriber/grpcSubscription.ts +0 -155
  215. package/src/orderSubscriber/index.ts +0 -7
  216. package/src/orderSubscriber/types.ts +0 -64
  217. package/src/priorityFee/averageOverSlotsStrategy.ts +0 -17
  218. package/src/priorityFee/averageStrategy.ts +0 -13
  219. package/src/priorityFee/ewmaStrategy.ts +0 -51
  220. package/src/priorityFee/heliusPriorityFeeMethod.ts +0 -68
  221. package/src/priorityFee/index.ts +0 -16
  222. package/src/priorityFee/maxOverSlotsStrategy.ts +0 -18
  223. package/src/priorityFee/maxStrategy.ts +0 -8
  224. package/src/priorityFee/priorityFeeSubscriber.ts +0 -328
  225. package/src/priorityFee/priorityFeeSubscriberMap.ts +0 -134
  226. package/src/priorityFee/solanaPriorityFeeMethod.ts +0 -46
  227. package/src/priorityFee/types.ts +0 -82
  228. package/src/priorityFee/velocityPriorityFeeMethod.ts +0 -53
  229. package/src/pyth/constants.ts +0 -9
  230. package/src/pyth/index.ts +0 -15
  231. package/src/pyth/pythLazerSubscriber.ts +0 -365
  232. package/src/pyth/types.ts +0 -4451
  233. package/src/pyth/utils.ts +0 -13
  234. package/src/slot/SlotSubscriber.ts +0 -126
  235. package/src/slot/SlothashSubscriber.ts +0 -163
  236. package/src/swap/UnifiedSwapClient.ts +0 -315
  237. package/src/swift/grpcSignedMsgUserAccountSubscriber.ts +0 -81
  238. package/src/swift/index.ts +0 -10
  239. package/src/swift/signedMsgUserAccountSubscriber.ts +0 -251
  240. package/src/swift/swiftOrderSubscriber.ts +0 -351
  241. package/src/testClient.ts +0 -42
  242. package/src/titan/titanClient.ts +0 -438
  243. package/src/token/index.ts +0 -13
  244. package/src/tokenFaucet.ts +0 -296
  245. package/src/tx/baseTxSender.ts +0 -651
  246. package/src/tx/blockhashFetcher/baseBlockhashFetcher.ts +0 -31
  247. package/src/tx/blockhashFetcher/cachedBlockhashFetcher.ts +0 -105
  248. package/src/tx/blockhashFetcher/types.ts +0 -9
  249. package/src/tx/fastSingleTxSender.ts +0 -200
  250. package/src/tx/forwardOnlyTxSender.ts +0 -193
  251. package/src/tx/priorityFeeCalculator.ts +0 -117
  252. package/src/tx/reportTransactionError.ts +0 -176
  253. package/src/tx/retryTxSender.ts +0 -177
  254. package/src/tx/txHandler.ts +0 -1009
  255. package/src/tx/txParamProcessor.ts +0 -225
  256. package/src/tx/types.ts +0 -117
  257. package/src/tx/utils.ts +0 -133
  258. package/src/tx/whileValidTxSender.ts +0 -377
  259. package/src/types.ts +0 -2575
  260. package/src/user.ts +0 -5316
  261. package/src/userConfig.ts +0 -38
  262. package/src/userMap/PollingSubscription.ts +0 -61
  263. package/src/userMap/WebsocketSubscription.ts +0 -93
  264. package/src/userMap/grpcSubscription.ts +0 -93
  265. package/src/userMap/referrerMap.ts +0 -360
  266. package/src/userMap/revenueShareEscrowMap.ts +0 -342
  267. package/src/userMap/userMap.ts +0 -784
  268. package/src/userMap/userMapConfig.ts +0 -82
  269. package/src/userMap/userStatsMap.ts +0 -393
  270. package/src/userName.ts +0 -37
  271. package/src/userStats.ts +0 -159
  272. package/src/userStatsConfig.ts +0 -35
  273. package/src/util/TransactionConfirmationManager.ts +0 -333
  274. package/src/util/chainClock.ts +0 -65
  275. package/src/util/computeUnits.ts +0 -101
  276. package/src/util/digest.ts +0 -33
  277. package/src/util/ed25519Utils.ts +0 -95
  278. package/src/util/promiseTimeout.ts +0 -23
  279. package/src/velocityClient.ts +0 -14802
  280. package/src/velocityClientConfig.ts +0 -119
  281. package/src/wallet.ts +0 -91
  282. package/tests/VelocityCore/builder_escrow.test.ts +0 -121
  283. package/tests/VelocityCore/decode.test.ts +0 -16
  284. package/tests/VelocityCore/fill_trigger.test.ts +0 -73
  285. package/tests/VelocityCore/instructions.test.ts +0 -46
  286. package/tests/VelocityCore/pdas.test.ts +0 -30
  287. package/tests/VelocityCore/perp_orders.test.ts +0 -205
  288. package/tests/VelocityCore/remainingAccounts.test.ts +0 -72
  289. package/tests/VelocityCore/settlement_liquidation.test.ts +0 -69
  290. package/tests/accounts/customizedCadenceBulkAccountLoader.test.ts +0 -211
  291. package/tests/amm/test.ts +0 -2402
  292. package/tests/auctions/test.ts +0 -81
  293. package/tests/bn/test.ts +0 -355
  294. package/tests/builder/builderFee.test.ts +0 -42
  295. package/tests/ci/verifyConstants.ts +0 -393
  296. package/tests/decode/test.ts +0 -262
  297. package/tests/decode/userAccountBufferStrings.ts +0 -102
  298. package/tests/dlob/helpers.ts +0 -748
  299. package/tests/dlob/test.ts +0 -6969
  300. package/tests/dlob/tickSizeStandardization.ts +0 -545
  301. package/tests/events/parseLogsForCuUsage.ts +0 -139
  302. package/tests/exchangeStatus/test.ts +0 -45
  303. package/tests/insurance/test.ts +0 -40
  304. package/tests/liquidation/test.ts +0 -125
  305. package/tests/oracles/mmOracleGate.test.ts +0 -379
  306. package/tests/oracles/pythPegSnap.test.ts +0 -76
  307. package/tests/sdkParity/enumParity.test.ts +0 -84
  308. package/tests/sdkParity/marginCategoryFill.test.ts +0 -143
  309. package/tests/sdkParity/memcmpOffsets.test.ts +0 -139
  310. package/tests/spot/test.ts +0 -281
  311. package/tests/tx/TransactionConfirmationManager.test.ts +0 -312
  312. package/tests/tx/cachedBlockhashFetcher.test.ts +0 -96
  313. package/tests/tx/priorityFeeCalculator.ts +0 -77
  314. package/tests/tx/priorityFeeStrategy.ts +0 -95
  315. package/tests/user/bankruptcy.ts +0 -165
  316. package/tests/user/feeAndWithdrawLimits.ts +0 -284
  317. package/tests/user/getMarginCalculation.ts +0 -586
  318. package/tests/user/helpers.ts +0 -184
  319. package/tests/user/liquidations.ts +0 -129
  320. package/tests/user/marginCalculations.test.ts +0 -321
  321. package/tests/user/test.ts +0 -833
  322. package/tsconfig.browser.json +0 -18
  323. package/tsconfig.json +0 -36
@@ -1,266 +0,0 @@
1
- import { LaserGrpcConfigs, ResubOpts } from './types';
2
- import { Context, MemcmpFilter, PublicKey } from '@solana/web3.js';
3
- import { VelocityProgram } from '../config';
4
- import * as Buffer from 'buffer';
5
- import { WebSocketProgramAccountSubscriber } from './webSocketProgramAccountSubscriber';
6
-
7
- import {
8
- LaserCommitmentLevel,
9
- LaserstreamConfig,
10
- LaserSubscribeRequest,
11
- LaserSubscribeUpdate,
12
- CommitmentLevel,
13
- getLaserSubscribe,
14
- getLaserCompressionAlgorithms,
15
- getLaserCommitmentLevel,
16
- } from '../isomorphic/grpc';
17
-
18
- type LaserCommitment =
19
- (typeof LaserCommitmentLevel)[keyof typeof LaserCommitmentLevel];
20
-
21
- /**
22
- * `ProgramAccountSubscriber` that streams every account owned by the program (optionally filtered
23
- * by `memcmp`) via Helius LaserStream instead of `connection.onProgramAccountChange`. Extends
24
- * `WebSocketProgramAccountSubscriber` to reuse its per-account buffering/decode/resub-timer logic
25
- * (`handleRpcResponse`, `bufferAndSlotMap`) — only the transport (`subscribe`/`unsubscribe`) is
26
- * replaced. Construct via the static `create` factory, not the constructor directly, since it
27
- * dynamically loads the optional `helius-laserstream` peer dependency and its enums.
28
- */
29
- export class LaserstreamProgramAccountSubscriber<
30
- T,
31
- > extends WebSocketProgramAccountSubscriber<T> {
32
- private stream:
33
- | {
34
- id: string;
35
- cancel: () => void;
36
- write?: (req: LaserSubscribeRequest) => Promise<void>;
37
- }
38
- | undefined;
39
-
40
- private commitmentLevel: CommitmentLevel;
41
- public listenerId?: number;
42
-
43
- private readonly laserConfig: LaserstreamConfig;
44
- private readonly laserCommitmentLevel: typeof LaserCommitmentLevel;
45
-
46
- private constructor(
47
- laserConfig: LaserstreamConfig,
48
- commitmentLevel: CommitmentLevel,
49
- laserCommitmentLevel: typeof LaserCommitmentLevel,
50
- subscriptionName: string,
51
- accountDiscriminator: string,
52
- program: VelocityProgram,
53
- decodeBufferFn: (accountName: string, ix: Buffer) => T,
54
- options: { filters: MemcmpFilter[] } = { filters: [] },
55
- resubOpts?: ResubOpts
56
- ) {
57
- super(
58
- subscriptionName,
59
- accountDiscriminator,
60
- program,
61
- decodeBufferFn,
62
- options,
63
- resubOpts
64
- );
65
- this.laserConfig = laserConfig;
66
- this.laserCommitmentLevel = laserCommitmentLevel;
67
- this.commitmentLevel = this.toLaserCommitment(commitmentLevel);
68
- }
69
-
70
- /**
71
- * Loads the optional `helius-laserstream` module, builds its `LaserstreamConfig` (forcing zstd
72
- * compression and a 1GB max receive message size), and constructs a
73
- * `LaserstreamProgramAccountSubscriber`. Does not itself start streaming — call
74
- * `subscribe(onChange)` on the result.
75
- * @param grpcConfigs LaserStream endpoint/token/commitment config; `enableReconnect` maps to up to 10 reconnect attempts (0 if unset).
76
- * @param subscriptionName Human-readable name for logging.
77
- * @param accountDiscriminator Anchor account type name passed to `decodeBufferFn` for each update.
78
- * @param program Anchor program whose accounts to stream (filtered to `program.programId` as owner).
79
- * @param decodeBufferFn Decode function for each account's raw buffer.
80
- * @param options `filters` (memcmp) narrowing which program accounts are streamed; empty streams every account owned by the program.
81
- * @param resubOpts Resubscription watchdog options; omit to disable the inactivity timer.
82
- */
83
- public static async create<U>(
84
- grpcConfigs: LaserGrpcConfigs,
85
- subscriptionName: string,
86
- accountDiscriminator: string,
87
- program: VelocityProgram,
88
- decodeBufferFn: (accountName: string, ix: Buffer) => U,
89
- options: { filters: MemcmpFilter[] } = {
90
- filters: [],
91
- },
92
- resubOpts?: ResubOpts
93
- ): Promise<LaserstreamProgramAccountSubscriber<U>> {
94
- // Load enums from the optional helius-laserstream module
95
- const [compressionAlgorithms, laserCommitmentLevel] = await Promise.all([
96
- getLaserCompressionAlgorithms(),
97
- getLaserCommitmentLevel(),
98
- ]);
99
-
100
- const laserConfig: LaserstreamConfig = {
101
- apiKey: grpcConfigs.token,
102
- endpoint: grpcConfigs.endpoint,
103
- maxReconnectAttempts: grpcConfigs.enableReconnect ? 10 : 0,
104
- channelOptions: {
105
- 'grpc.default_compression_algorithm': compressionAlgorithms.zstd,
106
- 'grpc.max_receive_message_length': 1_000_000_000,
107
- },
108
- };
109
-
110
- const commitmentLevel =
111
- grpcConfigs.commitmentLevel ?? CommitmentLevel.CONFIRMED;
112
-
113
- return new LaserstreamProgramAccountSubscriber<U>(
114
- laserConfig,
115
- commitmentLevel,
116
- laserCommitmentLevel,
117
- subscriptionName,
118
- accountDiscriminator,
119
- program,
120
- decodeBufferFn,
121
- options,
122
- resubOpts
123
- );
124
- }
125
-
126
- /**
127
- * Opens a LaserStream `accounts` subscription filtered to `program.programId` as owner
128
- * (further narrowed by the `filters` passed to `create`). Idempotent: a no-op if already
129
- * subscribed or mid-unsubscribe. Does not perform an initial fetch — the caller must fetch any
130
- * pre-existing matching accounts separately if needed. Throws if the LaserStream client fails
131
- * to start.
132
- * @param onChange Invoked once per changed account with its pubkey, decoded data, the notification's `Context` (slot only), and the raw buffer.
133
- */
134
- async subscribe(
135
- onChange: (
136
- accountId: PublicKey,
137
- data: T,
138
- context: Context,
139
- buffer: Buffer
140
- ) => void
141
- ): Promise<void> {
142
- if (this.listenerId != null || this.isUnsubscribing) return;
143
-
144
- this.onChange = onChange;
145
-
146
- const filters = this.options.filters.map((filter) => {
147
- return {
148
- memcmp: {
149
- offset: filter.memcmp.offset,
150
- base58: filter.memcmp.bytes,
151
- },
152
- };
153
- });
154
-
155
- const request: LaserSubscribeRequest = {
156
- slots: {},
157
- accounts: {
158
- velocity: {
159
- account: [],
160
- owner: [this.program.programId.toBase58()],
161
- filters,
162
- },
163
- },
164
- transactions: {},
165
- blocks: {},
166
- blocksMeta: {},
167
- accountsDataSlice: [],
168
- commitment: this.commitmentLevel,
169
- entry: {},
170
- transactionsStatus: {},
171
- };
172
-
173
- try {
174
- // Dynamically load LaserSubscribe from the optional helius-laserstream module
175
- const laserSubscribe = await getLaserSubscribe();
176
-
177
- const stream = await laserSubscribe(
178
- this.laserConfig,
179
- request,
180
- async (update: LaserSubscribeUpdate) => {
181
- if (update.account) {
182
- const slot = Number(update.account.slot);
183
- const acc = update.account.account;
184
- if (!acc) {
185
- return;
186
- }
187
-
188
- const accountInfo = {
189
- owner: new PublicKey(acc.owner),
190
- lamports: Number(acc.lamports),
191
- data: Buffer.Buffer.from(acc.data),
192
- executable: acc.executable,
193
- rentEpoch: Number(acc.rentEpoch),
194
- };
195
-
196
- const payload = {
197
- accountId: new PublicKey(acc.pubkey),
198
- accountInfo,
199
- };
200
-
201
- if (this.resubOpts?.resubTimeoutMs) {
202
- this.receivingData = true;
203
- clearTimeout(this.timeoutId);
204
- this.handleRpcResponse({ slot }, payload);
205
- this.setTimeout();
206
- } else {
207
- this.handleRpcResponse({ slot }, payload);
208
- }
209
- }
210
- },
211
- async (error) => {
212
- console.error('LaserStream client error:', error);
213
- throw error;
214
- }
215
- );
216
-
217
- this.stream = stream;
218
- this.listenerId = 1;
219
-
220
- if (this.resubOpts?.resubTimeoutMs) {
221
- this.receivingData = true;
222
- this.setTimeout();
223
- }
224
- } catch (err) {
225
- console.error('Failed to start LaserStream client:', err);
226
- throw err;
227
- }
228
- }
229
-
230
- /**
231
- * Cancels the LaserStream and clears any pending resub timeout.
232
- * @param onResub Internal flag set to `true` when called as part of an automatic resubscribe cycle, which preserves `resubOpts.resubTimeoutMs` instead of clearing it. Callers should omit this.
233
- */
234
- public async unsubscribe(onResub = false): Promise<void> {
235
- if (!onResub && this.resubOpts) {
236
- this.resubOpts.resubTimeoutMs = undefined;
237
- }
238
- this.isUnsubscribing = true;
239
- clearTimeout(this.timeoutId);
240
- this.timeoutId = undefined;
241
-
242
- if (this.listenerId != null && this.stream) {
243
- try {
244
- this.stream.cancel();
245
- } finally {
246
- this.listenerId = undefined;
247
- this.isUnsubscribing = false;
248
- }
249
- } else {
250
- this.isUnsubscribing = false;
251
- }
252
- }
253
-
254
- /** Coerces a commitment level (string name, numeric enum value, or undefined) into a LaserStream `LaserCommitmentLevel`, defaulting to `CONFIRMED`. */
255
- public toLaserCommitment(
256
- level: string | number | undefined
257
- ): LaserCommitment {
258
- if (typeof level === 'string') {
259
- return (
260
- (this.laserCommitmentLevel as any)[level.toUpperCase()] ??
261
- this.laserCommitmentLevel.CONFIRMED
262
- );
263
- }
264
- return (level as LaserCommitment) ?? this.laserCommitmentLevel.CONFIRMED;
265
- }
266
- }
@@ -1,88 +0,0 @@
1
- import { Commitment, PublicKey } from '@solana/web3.js';
2
- import { UserAccount } from '../types';
3
- import { BasicUserAccountSubscriber } from './basicUserAccountSubscriber';
4
- import { UserAccountSubscriber } from './types';
5
- import { VelocityProgram } from '../config';
6
-
7
- /**
8
- * Simple implementation of UserAccountSubscriber. It will fetch the UserAccount
9
- * date on subscribe (or call to fetch) if no account data is provided on init.
10
- * Expect to use only 1 RPC call unless you call fetch repeatedly.
11
- */
12
- export class OneShotUserAccountSubscriber
13
- extends BasicUserAccountSubscriber
14
- implements UserAccountSubscriber
15
- {
16
- program: VelocityProgram;
17
- commitment: Commitment;
18
-
19
- /**
20
- * @param program Anchor program used for the one-off `fetchAndContext` call.
21
- * @param userAccountPublicKey Address of the `UserAccount` to fetch.
22
- * @param data Optional pre-fetched account data to seed with, skipping the RPC call entirely.
23
- * @param slot Slot `data` was observed at, if provided.
24
- * @param commitment Commitment for the fetch; defaults to `'confirmed'`.
25
- */
26
- public constructor(
27
- program: VelocityProgram,
28
- userAccountPublicKey: PublicKey,
29
- data?: UserAccount,
30
- slot?: number,
31
- commitment?: Commitment
32
- ) {
33
- super(userAccountPublicKey, data, slot);
34
- this.program = program;
35
- this.commitment = commitment ?? 'confirmed';
36
- }
37
-
38
- /**
39
- * If `userAccount` is supplied, seeds directly with no RPC call. Otherwise fetches once via
40
- * `fetchIfUnloaded()` if no data is cached yet. Always resolves `true` — there is no
41
- * persistent subscription to fail.
42
- * @param userAccount Optional pre-fetched account data to seed with instead of fetching.
43
- */
44
- async subscribe(userAccount?: UserAccount): Promise<boolean> {
45
- if (userAccount) {
46
- this.user = { data: userAccount, slot: this.user?.slot ?? 0 };
47
- return true;
48
- }
49
-
50
- await this.fetchIfUnloaded();
51
- if (this.doesAccountExist()) {
52
- this.eventEmitter.emit('update');
53
- }
54
- return true;
55
- }
56
-
57
- /** Fetches via `fetch()` only if no data is cached yet; otherwise a no-op. */
58
- async fetchIfUnloaded(): Promise<void> {
59
- if (!this.user) {
60
- await this.fetch();
61
- }
62
- }
63
-
64
- /**
65
- * Fetches the account once via `program.account.user.fetchAndContext`, applying it only if
66
- * the response's slot is newer than what's cached. Logs and swallows errors (e.g. account not
67
- * yet initialized) rather than throwing.
68
- */
69
- async fetch(): Promise<void> {
70
- try {
71
- const dataAndContext = await (
72
- this.program.account as any
73
- ).user.fetchAndContext(this.userAccountPublicKey, this.commitment);
74
- if (dataAndContext.context.slot > (this.user?.slot ?? 0)) {
75
- this.user = {
76
- data: dataAndContext.data as UserAccount,
77
- slot: dataAndContext.context.slot,
78
- };
79
- }
80
- } catch (e) {
81
- console.error(
82
- `OneShotUserAccountSubscriber.fetch() UserAccount does not exist: ${
83
- e instanceof Error ? e.message : String(e)
84
- }`
85
- );
86
- }
87
- }
88
- }
@@ -1,94 +0,0 @@
1
- import { Commitment, PublicKey } from '@solana/web3.js';
2
- import { UserStatsAccount } from '../types';
3
- import { BasicUserStatsAccountSubscriber } from './basicUserStatsAccountSubscriber';
4
- import { UserStatsAccountSubscriber } from './types';
5
- import { VelocityProgram } from '../config';
6
-
7
- /**
8
- * Simple implementation of UserStatsAccountSubscriber. It will fetch the UserStatsAccount
9
- * data on subscribe (or call to fetch) if no account data is provided on init.
10
- * Expect to use only 1 RPC call unless you call fetch repeatedly.
11
- */
12
- export class OneShotUserStatsAccountSubscriber
13
- extends BasicUserStatsAccountSubscriber
14
- implements UserStatsAccountSubscriber
15
- {
16
- program: VelocityProgram;
17
- commitment: Commitment;
18
-
19
- /**
20
- * @param program Anchor program used for the one-off `fetchAndContext` call.
21
- * @param userStatsAccountPublicKey Address of the `UserStatsAccount` to fetch.
22
- * @param data Optional pre-fetched account data to seed with, skipping the RPC call entirely.
23
- * @param slot Slot `data` was observed at, if provided.
24
- * @param commitment Commitment for the fetch; defaults to `'confirmed'`.
25
- */
26
- public constructor(
27
- program: VelocityProgram,
28
- userStatsAccountPublicKey: PublicKey,
29
- data?: UserStatsAccount,
30
- slot?: number,
31
- commitment?: Commitment
32
- ) {
33
- super(userStatsAccountPublicKey, data, slot);
34
- this.program = program;
35
- this.commitment = commitment ?? 'confirmed';
36
- }
37
-
38
- /**
39
- * If `userStatsAccount` is supplied, seeds directly with no RPC call. Otherwise fetches once
40
- * via `fetchIfUnloaded()` if no data is cached yet. Always resolves `true` — there is no
41
- * persistent subscription to fail.
42
- * @param userStatsAccount Optional pre-fetched account data to seed with instead of fetching.
43
- */
44
- async subscribe(userStatsAccount?: UserStatsAccount): Promise<boolean> {
45
- if (userStatsAccount) {
46
- this.userStats = {
47
- data: userStatsAccount,
48
- slot: this.userStats?.slot ?? 0,
49
- };
50
- return true;
51
- }
52
-
53
- await this.fetchIfUnloaded();
54
- if (this.doesAccountExist()) {
55
- this.eventEmitter.emit('update');
56
- }
57
- return true;
58
- }
59
-
60
- /** Fetches via `fetch()` only if no data is cached yet; otherwise a no-op. */
61
- async fetchIfUnloaded(): Promise<void> {
62
- if (!this.userStats) {
63
- await this.fetch();
64
- }
65
- }
66
-
67
- /**
68
- * Fetches the account once via `program.account.userStats.fetchAndContext`, applying it only
69
- * if the response's slot is newer than what's cached. Logs and swallows errors (e.g. account
70
- * not yet initialized) rather than throwing.
71
- */
72
- async fetch(): Promise<void> {
73
- try {
74
- const dataAndContext = await (
75
- this.program.account as any
76
- ).userStats.fetchAndContext(
77
- this.userStatsAccountPublicKey,
78
- this.commitment
79
- );
80
- if (dataAndContext.context.slot > (this.userStats?.slot ?? 0)) {
81
- this.userStats = {
82
- data: dataAndContext.data as unknown as UserStatsAccount,
83
- slot: dataAndContext.context.slot,
84
- };
85
- }
86
- } catch (e) {
87
- console.error(
88
- `OneShotUserStatsAccountSubscriber.fetch() UserStatsAccount does not exist: ${
89
- e instanceof Error ? e.message : String(e)
90
- }`
91
- );
92
- }
93
- }
94
- }
@@ -1,223 +0,0 @@
1
- import {
2
- DataAndSlot,
3
- NotSubscribedError,
4
- InsuranceFundStakeAccountEvents,
5
- InsuranceFundStakeAccountSubscriber,
6
- } from './types';
7
- import { VelocityProgram } from '../config';
8
- import StrictEventEmitter from 'strict-event-emitter-types';
9
- import { EventEmitter } from 'events';
10
- import { PublicKey } from '@solana/web3.js';
11
- import { BulkAccountLoader } from './bulkAccountLoader';
12
- import { InsuranceFundStake } from '../types';
13
-
14
- /**
15
- * `InsuranceFundStakeAccountSubscriber` backed by a shared `BulkAccountLoader` instead of a
16
- * dedicated WebSocket subscription, mirroring `PollingUserAccountSubscriber` for
17
- * `InsuranceFundStake` accounts.
18
- */
19
- export class PollingInsuranceFundStakeAccountSubscriber
20
- implements InsuranceFundStakeAccountSubscriber
21
- {
22
- isSubscribed: boolean;
23
- program: VelocityProgram;
24
- eventEmitter: StrictEventEmitter<
25
- EventEmitter,
26
- InsuranceFundStakeAccountEvents
27
- >;
28
- insuranceFundStakeAccountPublicKey: PublicKey;
29
-
30
- accountLoader: BulkAccountLoader;
31
- callbackId?: string;
32
- errorCallbackId?: string;
33
-
34
- insuranceFundStakeAccountAndSlot?: DataAndSlot<InsuranceFundStake>;
35
-
36
- /**
37
- * @param program Anchor program used for the one-off `fetch()` fallback and account decoding.
38
- * @param publicKey Address of the `InsuranceFundStake` account to track.
39
- * @param accountLoader Shared `BulkAccountLoader` this subscriber registers its callback with.
40
- */
41
- public constructor(
42
- program: VelocityProgram,
43
- publicKey: PublicKey,
44
- accountLoader: BulkAccountLoader
45
- ) {
46
- this.isSubscribed = false;
47
- this.program = program;
48
- this.insuranceFundStakeAccountPublicKey = publicKey;
49
- this.accountLoader = accountLoader;
50
- this.eventEmitter = new EventEmitter();
51
- }
52
-
53
- /**
54
- * Registers this account with the shared `BulkAccountLoader`. Note this does not wait for an
55
- * initial fetch to land before returning `isSubscribed = true`, unlike the analogous
56
- * `PollingUserAccountSubscriber.subscribe`; call `fetchIfUnloaded()` explicitly if data is
57
- * needed immediately. Idempotent: a no-op if already subscribed.
58
- * @param insuranceFundStake Optional pre-fetched account data to seed with (at slot 0) instead of an immediate fetch.
59
- */
60
- async subscribe(insuranceFundStake?: InsuranceFundStake): Promise<boolean> {
61
- if (this.isSubscribed) {
62
- return true;
63
- }
64
-
65
- if (insuranceFundStake) {
66
- this.insuranceFundStakeAccountAndSlot = {
67
- data: insuranceFundStake,
68
- slot: 0,
69
- };
70
- }
71
-
72
- await this.addToAccountLoader();
73
-
74
- if (this.doesAccountExist()) {
75
- this.eventEmitter.emit('update');
76
- }
77
-
78
- this.isSubscribed = true;
79
- return true;
80
- }
81
-
82
- /** Registers this account and an error callback with the `BulkAccountLoader`. A no-op if already registered. */
83
- async addToAccountLoader(): Promise<void> {
84
- if (this.callbackId) {
85
- return;
86
- }
87
-
88
- this.callbackId = await this.accountLoader.addAccount(
89
- this.insuranceFundStakeAccountPublicKey,
90
- (buffer, slot: number) => {
91
- if (!buffer) {
92
- return;
93
- }
94
-
95
- if (
96
- this.insuranceFundStakeAccountAndSlot &&
97
- this.insuranceFundStakeAccountAndSlot.slot > slot
98
- ) {
99
- return;
100
- }
101
-
102
- const account = this.program.coder.accounts.decode(
103
- 'insuranceFundStake',
104
- buffer
105
- );
106
- this.insuranceFundStakeAccountAndSlot = { data: account, slot };
107
- this.eventEmitter.emit('insuranceFundStakeAccountUpdate', account);
108
- this.eventEmitter.emit('update');
109
- }
110
- );
111
-
112
- this.errorCallbackId = this.accountLoader.addErrorCallbacks((error) => {
113
- this.eventEmitter.emit('error', error);
114
- });
115
- }
116
-
117
- /** Fetches via `fetch()` only if no data is cached yet; otherwise a no-op. */
118
- async fetchIfUnloaded(): Promise<void> {
119
- if (!this.doesAccountExist()) {
120
- await this.fetch();
121
- }
122
- }
123
-
124
- /** Fetches the account once directly via `program.account.insuranceFundStake.fetchAndContext` (independent of the account loader's poll cycle), applying it only if the response's slot is newer than what's cached. Logs and swallows errors rather than throwing. */
125
- async fetch(): Promise<void> {
126
- try {
127
- const dataAndContext = await (
128
- this.program.account as any
129
- ).insuranceFundStake.fetchAndContext(
130
- this.insuranceFundStakeAccountPublicKey,
131
- this.accountLoader.commitment
132
- );
133
- if (
134
- dataAndContext.context.slot >
135
- (this.insuranceFundStakeAccountAndSlot?.slot ?? 0)
136
- ) {
137
- this.insuranceFundStakeAccountAndSlot = {
138
- data: dataAndContext.data as InsuranceFundStake,
139
- slot: dataAndContext.context.slot,
140
- };
141
- }
142
- } catch (e) {
143
- console.log(
144
- `PollingInsuranceFundStakeAccountSubscriber.fetch() InsuranceFundStake does not exist: ${
145
- e instanceof Error ? e.message : String(e)
146
- }`
147
- );
148
- }
149
- }
150
-
151
- /** Type predicate: true once `insuranceFundStakeAccountAndSlot` has loaded, narrowing it to non-undefined. */
152
- doesAccountExist(): this is {
153
- insuranceFundStakeAccountAndSlot: DataAndSlot<InsuranceFundStake>;
154
- } {
155
- return this.insuranceFundStakeAccountAndSlot !== undefined;
156
- }
157
-
158
- /** Unregisters this account (and its error callback) from the `BulkAccountLoader`. A no-op if not subscribed. */
159
- async unsubscribe(): Promise<void> {
160
- if (!this.isSubscribed) {
161
- return;
162
- }
163
-
164
- this.accountLoader.removeAccount(
165
- this.insuranceFundStakeAccountPublicKey,
166
- this.callbackId
167
- );
168
- this.callbackId = undefined;
169
-
170
- this.accountLoader.removeErrorCallbacks(this.errorCallbackId);
171
- this.errorCallbackId = undefined;
172
-
173
- this.isSubscribed = false;
174
- }
175
-
176
- /** Throws `NotSubscribedError` if `subscribe()` has not been called. */
177
- assertIsSubscribed(): void {
178
- if (!this.isSubscribed) {
179
- throw new NotSubscribedError(
180
- 'You must call `subscribe` before using this function'
181
- );
182
- }
183
- }
184
-
185
- /** Throws `NotSubscribedError` if not subscribed. Returns undefined only if subscribed but no data has loaded yet. */
186
- public getInsuranceFundStakeAccountAndSlot():
187
- | DataAndSlot<InsuranceFundStake>
188
- | undefined {
189
- this.assertIsSubscribed();
190
- return this.insuranceFundStakeAccountAndSlot;
191
- }
192
-
193
- /** True once account data has been loaded, independent of `isSubscribed`. */
194
- didSubscriptionSucceed(): boolean {
195
- return !!this.insuranceFundStakeAccountAndSlot;
196
- }
197
-
198
- /**
199
- * Applies an externally-obtained account update if `slot` is newer than the currently cached
200
- * slot (strictly newer — unlike most other subscribers here, an equal slot is not accepted).
201
- * @param insuranceFundStake Decoded account data to apply.
202
- * @param slot Slot the data was observed at.
203
- */
204
- public updateData(
205
- insuranceFundStake: InsuranceFundStake,
206
- slot: number
207
- ): void {
208
- if (
209
- !this.insuranceFundStakeAccountAndSlot ||
210
- this.insuranceFundStakeAccountAndSlot.slot < slot
211
- ) {
212
- this.insuranceFundStakeAccountAndSlot = {
213
- data: insuranceFundStake,
214
- slot,
215
- };
216
- this.eventEmitter.emit(
217
- 'insuranceFundStakeAccountUpdate',
218
- insuranceFundStake
219
- );
220
- this.eventEmitter.emit('update');
221
- }
222
- }
223
- }