@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,113 +0,0 @@
1
- import { LogProvider, logProviderCallback } from './types';
2
- import {
3
- Commitment,
4
- Connection,
5
- Finality,
6
- PublicKey,
7
- TransactionSignature,
8
- } from '@solana/web3.js';
9
- import { fetchLogs } from './fetchLogs';
10
-
11
- /**
12
- * `LogProvider` that polls `fetchLogs` (`getSignaturesForAddress` +
13
- * `getTransaction`) on a fixed interval instead of holding a websocket open.
14
- * Used both as the default fallback provider after repeated websocket
15
- * reconnect failures and as an explicit choice for RPCs without reliable log
16
- * subscriptions. Only one poll runs at a time (a simple mutex flag skips an
17
- * overlapping tick if the previous fetch hasn't finished).
18
- */
19
- export class PollingLogProvider implements LogProvider {
20
- private finality: Finality;
21
- private intervalId?: ReturnType<typeof setTimeout>;
22
- private mostRecentSeenTx?: TransactionSignature;
23
- private mutex = 0;
24
- private firstFetch = true;
25
-
26
- /**
27
- * @param connection RPC connection to poll on.
28
- * @param address Account/program address to poll logs for.
29
- * @param commitment Commitment level; anything other than `'finalized'` is treated as `'confirmed'` for the underlying `fetchLogs` calls.
30
- * @param frequency Poll interval in milliseconds; defaults to 15000 (15s).
31
- * @param batchSize Max `getTransaction` calls batched per `fetchLogs` round-trip.
32
- */
33
- public constructor(
34
- private connection: Connection,
35
- private address: PublicKey,
36
- commitment: Commitment,
37
- private frequency = 15 * 1000,
38
- private batchSize?: number
39
- ) {
40
- this.finality = commitment === 'finalized' ? 'finalized' : 'confirmed';
41
- }
42
-
43
- /**
44
- * Starts the polling interval; the first tick fires immediately per
45
- * `setInterval` semantics only after `frequency` ms (there is no
46
- * immediate initial fetch). Idempotent — a second call while already
47
- * subscribed is a no-op.
48
- * @param skipHistory On the first poll only, fetches just the single most recent transaction instead of the full backlog since `mostRecentSeenTx`.
49
- * @returns Always resolves `true`.
50
- */
51
- public async subscribe(
52
- callback: logProviderCallback,
53
- skipHistory?: boolean
54
- ): Promise<boolean> {
55
- if (this.intervalId) {
56
- return true;
57
- }
58
-
59
- this.intervalId = setInterval(async () => {
60
- if (this.mutex === 1) {
61
- return;
62
- }
63
- this.mutex = 1;
64
-
65
- try {
66
- const response = await fetchLogs(
67
- this.connection,
68
- this.address,
69
- this.finality,
70
- undefined,
71
- this.mostRecentSeenTx,
72
- // If skipping history, only fetch one log back, not the maximum amount available
73
- skipHistory && this.firstFetch ? 1 : undefined,
74
- this.batchSize
75
- );
76
-
77
- if (response === undefined) {
78
- return;
79
- }
80
-
81
- this.firstFetch = false;
82
-
83
- const { mostRecentTx, transactionLogs } = response;
84
-
85
- for (const { txSig, slot, logs } of transactionLogs) {
86
- callback(txSig, slot, logs, response.mostRecentBlockTime, undefined);
87
- }
88
-
89
- this.mostRecentSeenTx = mostRecentTx;
90
- } catch (e) {
91
- console.error('PollingLogProvider threw an Error');
92
- console.error(e);
93
- } finally {
94
- this.mutex = 0;
95
- }
96
- }, this.frequency);
97
-
98
- return true;
99
- }
100
-
101
- public isSubscribed(): boolean {
102
- return this.intervalId !== undefined;
103
- }
104
-
105
- /** Stops the polling interval. Always resolves `true`. */
106
- public async unsubscribe(): Promise<boolean> {
107
- if (this.intervalId !== undefined) {
108
- clearInterval(this.intervalId);
109
- this.intervalId = undefined;
110
- }
111
- return true;
112
- }
113
- }
@@ -1,51 +0,0 @@
1
- import {
2
- EventMap,
3
- EventSubscriptionOrderBy,
4
- EventSubscriptionOrderDirection,
5
- EventType,
6
- SortFn,
7
- } from './types';
8
-
9
- function clientSortAscFn(): 'less than' {
10
- return 'less than';
11
- }
12
-
13
- function clientSortDescFn(): 'greater than' {
14
- return 'greater than';
15
- }
16
-
17
- /** Orders events by `slot`, breaking ties by `txSigIndex` (position within the same transaction). Reproducible regardless of delivery order. */
18
- function blockchainSortFn(
19
- currentEvent: EventMap[EventType],
20
- newEvent: EventMap[EventType]
21
- ): 'less than' | 'greater than' {
22
- if (currentEvent.slot == newEvent.slot) {
23
- return currentEvent.txSigIndex < newEvent.txSigIndex
24
- ? 'less than'
25
- : 'greater than';
26
- }
27
-
28
- return currentEvent.slot < newEvent.slot ? 'less than' : 'greater than';
29
- }
30
-
31
- /**
32
- * Selects the `SortFn` an `EventList` uses to place newly inserted events.
33
- * `orderBy: 'client'` always inserts at the position matching `orderDir`
34
- * (head for `'asc'`, tail for `'desc'`) regardless of the events' own
35
- * slot/index — i.e. pure arrival order. `orderBy: 'blockchain'` always uses
36
- * `blockchainSortFn` (slot, then `txSigIndex`); `orderDir` is ignored in that
37
- * case — blockchain order is always ascending by slot/`txSigIndex`.
38
- * @param orderBy Whether to sort by client arrival order or blockchain-produced order.
39
- * @param orderDir Sort direction; ignored when `orderBy` is `'blockchain'`.
40
- * @returns The `SortFn` to pass to `EventList`.
41
- */
42
- export function getSortFn(
43
- orderBy: EventSubscriptionOrderBy,
44
- orderDir: EventSubscriptionOrderDirection
45
- ): SortFn {
46
- if (orderBy === 'client') {
47
- return orderDir === 'asc' ? clientSortAscFn : clientSortDescFn;
48
- }
49
-
50
- return blockchainSortFn;
51
- }
@@ -1,92 +0,0 @@
1
- import { WrappedEvent, EventType } from './types';
2
-
3
- class Node {
4
- constructor(
5
- public key: string,
6
- public value: WrappedEvent<EventType>[],
7
- public next?: Node,
8
- public prev?: Node
9
- ) {}
10
- }
11
-
12
- // lru cache
13
- /**
14
- * LRU cache of decoded events keyed by transaction signature, used by
15
- * `EventSubscriber` both to serve `getEventsByTx`/`awaitTx` and to dedup
16
- * redeliveries of the same transaction from a log provider. Evicts the
17
- * least-recently-used entry once `maxTx` is exceeded (`add()` refreshes an
18
- * existing key's recency by moving it back to the head).
19
- */
20
- export class TxEventCache {
21
- size = 0;
22
- head?: Node;
23
- tail?: Node;
24
- cacheMap = new Map<string, Node>();
25
-
26
- /** @param maxTx Max number of transactions retained; defaults to 1024. */
27
- constructor(public maxTx = 1024) {}
28
-
29
- /** Inserts (or refreshes, if `key` already exists) the events for transaction `key` at the head, evicting the tail if this exceeds `maxTx`. */
30
- public add(key: string, events: WrappedEvent<EventType>[]): void {
31
- const existingNode = this.cacheMap.get(key);
32
- if (existingNode) {
33
- this.detach(existingNode);
34
- this.size--;
35
- } else if (this.size === this.maxTx) {
36
- const tail = this.tail;
37
- if (tail === undefined) {
38
- throw new Error(
39
- 'TxEventCache.add: cache at capacity but tail is unset'
40
- );
41
- }
42
- this.cacheMap.delete(tail.key);
43
- this.detach(tail);
44
- this.size--;
45
- }
46
-
47
- // Write to head of LinkedList
48
- if (!this.head) {
49
- this.head = this.tail = new Node(key, events);
50
- } else {
51
- const node = new Node(key, events, this.head);
52
- this.head.prev = node;
53
- this.head = node;
54
- }
55
-
56
- // update cacheMap with LinkedList key and Node reference
57
- this.cacheMap.set(key, this.head);
58
- this.size++;
59
- }
60
-
61
- /** Whether transaction `key` is currently cached. */
62
- public has(key: string): boolean {
63
- return this.cacheMap.has(key);
64
- }
65
-
66
- /** @returns The cached events for transaction `key`, or `undefined` if not cached (never seen, or evicted). */
67
- public get(key: string): WrappedEvent<EventType>[] | undefined {
68
- return this.cacheMap.get(key)?.value;
69
- }
70
-
71
- detach(node: Node): void {
72
- if (node.prev !== undefined) {
73
- node.prev.next = node.next;
74
- } else {
75
- this.head = node.next;
76
- }
77
-
78
- if (node.next !== undefined) {
79
- node.next.prev = node.prev;
80
- } else {
81
- this.tail = node.prev;
82
- }
83
- }
84
-
85
- /** Empties the cache. */
86
- public clear(): void {
87
- this.head = undefined;
88
- this.tail = undefined;
89
- this.size = 0;
90
- this.cacheMap.clear();
91
- }
92
- }
@@ -1,337 +0,0 @@
1
- import { Commitment, PublicKey, TransactionSignature } from '@solana/web3.js';
2
- import {
3
- DepositRecord,
4
- FundingPaymentRecord,
5
- FundingRateRecord,
6
- LiquidationRecord,
7
- NewUserRecord,
8
- OrderActionRecord,
9
- OrderRecord,
10
- SettlePnlRecord,
11
- InsuranceFundRecord,
12
- SpotInterestRecord,
13
- InsuranceFundStakeRecord,
14
- AmmCurveChanged,
15
- SwapRecord,
16
- SpotMarketVaultDepositRecord,
17
- SignedMsgOrderRecord,
18
- DeleteUserRecord,
19
- LPMintRedeemRecord,
20
- LPSettleRecord,
21
- LPSwapRecord,
22
- LPBorrowLendDepositRecord,
23
- PerpMarketFeeSweepRecord,
24
- ProtocolFeeWithdrawRecord,
25
- RevenueShareSettleRecord,
26
- TransferFeeAndPnlPoolRecord,
27
- } from '../types';
28
- import { EventEmitter } from 'events';
29
-
30
- /**
31
- * Configuration for `EventSubscriber`. Unset fields fall back to the matching
32
- * field in `DefaultEventSubscriptionOptions`.
33
- */
34
- export type EventSubscriptionOptions = {
35
- /** Program/account whose logs are parsed for events. Defaults to the Velocity program ID. */
36
- address?: PublicKey;
37
- /** Event names to decode and retain; events not in this list are dropped even if present in the logs. */
38
- eventTypes?: EventType[];
39
- /** Max events retained per event type in the in-memory `EventList` (oldest evicted first once exceeded). */
40
- maxEventsPerType?: number;
41
- /** Whether `EventList`s are sorted by the order the blockchain produced events (`'blockchain'`, by slot/txSigIndex) or the order the client received them (`'client'`). */
42
- orderBy?: EventSubscriptionOrderBy;
43
- /** Sort direction applied on top of `orderBy`. */
44
- orderDir?: EventSubscriptionOrderDirection;
45
- /** Commitment level used for both the live log subscription and any `fetchPreviousTx` backfill. */
46
- commitment?: Commitment;
47
- /** Max number of past transactions to backfill via `fetchPreviousTx`, and the `TxEventCache` LRU size. */
48
- maxTx?: number;
49
- /** Which `LogProvider` implementation streams new events: websocket, polling, or the Velocity events-server. */
50
- logProviderConfig?: LogProviderConfig;
51
- /** When the subscription starts, backtrack and fetch historical transactions until this signature (exclusive) is reached. Only consulted by `fetchPreviousTx`. */
52
- untilTx?: TransactionSignature;
53
- };
54
-
55
- /**
56
- * Default `EventSubscriptionOptions`: all known event types (including the
57
- * fee-sweep/revenue-share/LP-borrow-lend records), 4096 events retained per
58
- * type, blockchain-order ascending sort, `confirmed` commitment, and a
59
- * websocket log provider.
60
- */
61
- export const DefaultEventSubscriptionOptions: EventSubscriptionOptions = {
62
- eventTypes: [
63
- 'DepositRecord',
64
- 'FundingPaymentRecord',
65
- 'LiquidationRecord',
66
- 'OrderRecord',
67
- 'OrderActionRecord',
68
- 'FundingRateRecord',
69
- 'NewUserRecord',
70
- 'SettlePnlRecord',
71
- 'InsuranceFundRecord',
72
- 'SpotInterestRecord',
73
- 'InsuranceFundStakeRecord',
74
- 'AmmCurveChanged',
75
- 'SwapRecord',
76
- 'SpotMarketVaultDepositRecord',
77
- 'SignedMsgOrderRecord',
78
- 'DeleteUserRecord',
79
- 'LPMintRedeemRecord',
80
- 'LPSettleRecord',
81
- 'LPSwapRecord',
82
- 'LPBorrowLendDepositRecord',
83
- 'PerpMarketFeeSweepRecord',
84
- 'ProtocolFeeWithdrawRecord',
85
- 'RevenueShareSettleRecord',
86
- 'TransferFeeAndPnlPoolRecord',
87
- ],
88
- maxEventsPerType: 4096,
89
- orderBy: 'blockchain',
90
- orderDir: 'asc',
91
- commitment: 'confirmed',
92
- maxTx: 4096,
93
- logProviderConfig: {
94
- type: 'websocket',
95
- },
96
- };
97
-
98
- /**
99
- * `'blockchain'` sorts by the order the chain produced events (slot, then
100
- * `txSigIndex` within a tx) — stable across reconnects/replays. `'client'`
101
- * sorts purely by arrival order at this process, which is cheaper but not
102
- * reproducible if the client reconnects or replays history.
103
- */
104
- export type EventSubscriptionOrderBy = 'blockchain' | 'client';
105
-
106
- /** Direction applied on top of `EventSubscriptionOrderBy`: `'asc'` sorts oldest/lowest-order-key first, `'desc'` newest first. */
107
- export type EventSubscriptionOrderDirection = 'asc' | 'desc';
108
-
109
- /**
110
- * A decoded program event record `T` (e.g. `DepositRecord`, `OrderRecord`)
111
- * augmented with the transaction it was emitted in.
112
- */
113
- export type Event<T> = T & {
114
- /** Signature of the transaction that emitted this event. */
115
- txSig: TransactionSignature;
116
- /** Slot the transaction landed in. */
117
- slot: number;
118
- /** Index of this event among all decoded events in the same transaction; used to break slot ties when sorting and for dedup. */
119
- txSigIndex: number;
120
- };
121
-
122
- /** An `Event` tagged with its `EventMap` key, as emitted on `EventSubscriber.eventEmitter`'s `'newEvent'`. */
123
- export type WrappedEvent<Type extends EventType> = EventMap[Type] & {
124
- eventType: Type;
125
- };
126
-
127
- /** An array of `WrappedEvent`s of any `EventType`, e.g. as returned by `getEventsByTx`/`LogParser.parseEventsFromLogs`. */
128
- export type WrappedEvents = WrappedEvent<EventType>[];
129
-
130
- /**
131
- * Maps each on-chain event name (as declared in `state/events.rs` and emitted
132
- * via Anchor's `emit!`) to its decoded, transaction-augmented shape. See
133
- * `../types.ts` for each record's field-level precisions. Five entries were
134
- * newly wired in this parity pass: `LPBorrowLendDepositRecord` (LP pool
135
- * borrow/lend deposit or withdraw against a constituent, token-amount
136
- * precision per the constituent's spot market), `PerpMarketFeeSweepRecord`
137
- * (streaming fee-sweep drains from a perp market's pnl pool — insurance,
138
- * protocol, and AMM-provision cuts — quote-token amounts, `QUOTE_PRECISION`),
139
- * `ProtocolFeeWithdrawRecord` (admin withdrawal from a perp or spot market's
140
- * protocol fee pool, token-amount precision of the source spot market),
141
- * `RevenueShareSettleRecord` (builder/referrer revenue-share settlement, fee
142
- * amounts in `QUOTE_PRECISION`), and `TransferFeeAndPnlPoolRecord` (internal
143
- * transfer between a market's fee pool and pnl pool, `QUOTE_PRECISION`).
144
- */
145
- export type EventMap = {
146
- DepositRecord: Event<DepositRecord>;
147
- FundingPaymentRecord: Event<FundingPaymentRecord>;
148
- LiquidationRecord: Event<LiquidationRecord>;
149
- FundingRateRecord: Event<FundingRateRecord>;
150
- OrderRecord: Event<OrderRecord>;
151
- OrderActionRecord: Event<OrderActionRecord>;
152
- SettlePnlRecord: Event<SettlePnlRecord>;
153
- NewUserRecord: Event<NewUserRecord>;
154
- InsuranceFundRecord: Event<InsuranceFundRecord>;
155
- SpotInterestRecord: Event<SpotInterestRecord>;
156
- InsuranceFundStakeRecord: Event<InsuranceFundStakeRecord>;
157
- AmmCurveChanged: Event<AmmCurveChanged>;
158
- SwapRecord: Event<SwapRecord>;
159
- SpotMarketVaultDepositRecord: Event<SpotMarketVaultDepositRecord>;
160
- SignedMsgOrderRecord: Event<SignedMsgOrderRecord>;
161
- DeleteUserRecord: Event<DeleteUserRecord>;
162
- LPSettleRecord: Event<LPSettleRecord>;
163
- LPMintRedeemRecord: Event<LPMintRedeemRecord>;
164
- LPSwapRecord: Event<LPSwapRecord>;
165
- /** LP pool borrow/lend deposit or withdraw against a constituent's spot market. */
166
- LPBorrowLendDepositRecord: Event<LPBorrowLendDepositRecord>;
167
- /** Streaming sweep of a perp market's accrued fee ledger into the insurance, protocol, and AMM fee pools. Amounts are quote-token, `QUOTE_PRECISION` (1e6). */
168
- PerpMarketFeeSweepRecord: Event<PerpMarketFeeSweepRecord>;
169
- /** Admin withdrawal from a perp or spot market's protocol fee pool to a recipient token account. */
170
- ProtocolFeeWithdrawRecord: Event<ProtocolFeeWithdrawRecord>;
171
- /** Builder/referrer fee revenue-share settlement for a market. Fee amounts are quote-token, `QUOTE_PRECISION` (1e6). */
172
- RevenueShareSettleRecord: Event<RevenueShareSettleRecord>;
173
- /** Internal transfer of quote token between a perp market's fee pool and pnl pool. */
174
- TransferFeeAndPnlPoolRecord: Event<TransferFeeAndPnlPoolRecord>;
175
- };
176
-
177
- /** Union of all decodable event names — the keys of `EventMap`. */
178
- export type EventType = keyof EventMap;
179
-
180
- /**
181
- * Union of every possible decoded event shape (all `EventMap` value types
182
- * plus the synthetic `CuUsage` event, which is not a program event and is
183
- * only produced by `parseLogsForCuUsage`, not by `EventSubscriber`).
184
- */
185
- export type VelocityEvent =
186
- | Event<DepositRecord>
187
- | Event<FundingPaymentRecord>
188
- | Event<LiquidationRecord>
189
- | Event<FundingRateRecord>
190
- | Event<OrderRecord>
191
- | Event<OrderActionRecord>
192
- | Event<SettlePnlRecord>
193
- | Event<NewUserRecord>
194
- | Event<InsuranceFundRecord>
195
- | Event<SpotInterestRecord>
196
- | Event<InsuranceFundStakeRecord>
197
- | Event<AmmCurveChanged>
198
- | Event<SwapRecord>
199
- | Event<SpotMarketVaultDepositRecord>
200
- | Event<SignedMsgOrderRecord>
201
- | Event<DeleteUserRecord>
202
- | Event<LPSettleRecord>
203
- | Event<LPMintRedeemRecord>
204
- | Event<LPSwapRecord>
205
- | Event<LPBorrowLendDepositRecord>
206
- | Event<PerpMarketFeeSweepRecord>
207
- | Event<ProtocolFeeWithdrawRecord>
208
- | Event<RevenueShareSettleRecord>
209
- | Event<TransferFeeAndPnlPoolRecord>
210
- | Event<CuUsage>;
211
-
212
- /** Events emitted on `EventSubscriber.eventEmitter`. */
213
- export interface EventSubscriberEvents {
214
- /** Fired once per decoded event, after it has been inserted into the subscriber's `EventList` for its type. */
215
- newEvent: (event: WrappedEvent<EventType>) => void;
216
- }
217
-
218
- /**
219
- * Comparator used by `EventList` to keep events ordered. Returns whether
220
- * `newRecord` sorts before (`'less than'`) or after (`'greater than'`)
221
- * `currentRecord`; see `getSortFn` for the concrete `'blockchain'`/`'client'`
222
- * implementations.
223
- */
224
- export type SortFn = (
225
- currentRecord: EventMap[EventType],
226
- newRecord: EventMap[EventType]
227
- ) => 'less than' | 'greater than';
228
-
229
- /**
230
- * Callback a `LogProvider` invokes once per transaction containing raw
231
- * program logs, before they are decoded into typed events.
232
- * @param txSig Signature of the transaction the logs came from.
233
- * @param slot Slot the transaction landed in.
234
- * @param logs Raw log lines for the transaction.
235
- * @param mostRecentBlockTime Unix timestamp (seconds) of the most recent block seen by the provider, if known.
236
- * @param txSigIndex Explicit event index within the tx, if the provider can supply one (e.g. events-server); otherwise the consumer numbers events by decode order.
237
- */
238
- export type logProviderCallback = (
239
- txSig: TransactionSignature,
240
- slot: number,
241
- logs: string[],
242
- mostRecentBlockTime: number | undefined,
243
- txSigIndex: number | undefined
244
- ) => void;
245
-
246
- /**
247
- * Common interface implemented by each log transport (`WebSocketLogProvider`,
248
- * `PollingLogProvider`, `EventsServerLogProvider`) that `EventSubscriber`
249
- * drives to receive raw transaction logs.
250
- */
251
- export interface LogProvider {
252
- /** Whether the provider currently has an active subscription/connection. */
253
- isSubscribed(): boolean;
254
- /**
255
- * Starts streaming logs, invoking `callback` per transaction.
256
- * @param skipHistory If true, only the most recent log (not full backlog) is fetched on initial subscribe, where supported.
257
- * @returns `true` once the subscription is established.
258
- */
259
- subscribe(
260
- callback: logProviderCallback,
261
- skipHistory?: boolean
262
- ): Promise<boolean>;
263
- /**
264
- * Tears down the subscription.
265
- * @param external Whether this is a caller-initiated unsubscribe (as opposed to an internal one during a reconnect); suppresses auto-resubscribe when true.
266
- */
267
- unsubscribe(external?: boolean): Promise<boolean>;
268
- /** Emits `'reconnect'` with the current attempt count when a streaming provider detects a stall and is about to resubscribe. Only set on streaming (websocket/events-server) providers. */
269
- eventEmitter?: EventEmitter;
270
- }
271
-
272
- /** Which `LogProvider` implementation backs an `EventSubscriber`. */
273
- export type LogProviderType = 'websocket' | 'polling' | 'events-server';
274
-
275
- /** Shared reconnect/fallback options for streaming (websocket, events-server) log providers. */
276
- export type StreamingLogProviderConfig = {
277
- /** Max reconnect attempts before `EventSubscriber` fails over to the next provider in the chain (events-server → websocket → polling); default `Infinity` (never fails over). */
278
- maxReconnectAttempts?: number;
279
- /** Poll interval (ms) for the `PollingLogProviderConfig` used once failed over to polling. */
280
- fallbackFrequency?: number;
281
- /** `getTransaction` batch size for the `PollingLogProviderConfig` used once failed over to polling. */
282
- fallbackBatchSize?: number;
283
- };
284
-
285
- /** Configures `EventSubscriber` to stream events via `connection.onLogs`. */
286
- export type WebSocketLogProviderConfig = StreamingLogProviderConfig & {
287
- type: 'websocket';
288
- /** Resubscribe if no log data arrives within this many ms; left unset, the websocket never auto-resubscribes. */
289
- resubTimeoutMs?: number;
290
- };
291
-
292
- /** Configures `EventSubscriber` to poll for new transactions via `getSignaturesForAddress`/`getTransaction` on an interval. */
293
- export type PollingLogProviderConfig = {
294
- type: 'polling';
295
- /** Poll interval in milliseconds. */
296
- frequency: number;
297
- /** Max `getTransaction` calls batched per poll round-trip; defaults to 25 (see `fetchLogs`). */
298
- batchSize?: number;
299
- };
300
-
301
- /** Configures `EventSubscriber` to receive pre-decoded events pushed over a websocket from the Velocity-hosted events server, instead of raw RPC logs. */
302
- export type EventsServerLogProviderConfig = StreamingLogProviderConfig & {
303
- type: 'events-server';
304
- /** Websocket URL of the Velocity events server. */
305
- url: string;
306
- };
307
-
308
- /** Discriminated union of the three supported log-transport configs; the `type` field selects which `LogProvider` is constructed. */
309
- export type LogProviderConfig =
310
- | WebSocketLogProviderConfig
311
- | PollingLogProviderConfig
312
- | EventsServerLogProviderConfig;
313
-
314
- /** IDL-style event descriptor used to synthesize the `CuUsage` pseudo-event decoded by `parseLogsForCuUsage`; not a real on-chain `#[event]`. */
315
- export type CuUsageEvent = {
316
- name: 'CuUsage';
317
- fields: [
318
- {
319
- name: 'instruction';
320
- type: 'string';
321
- index: false;
322
- },
323
- {
324
- name: 'cuUsage';
325
- type: 'u32';
326
- index: false;
327
- },
328
- ];
329
- };
330
-
331
- /** Compute-unit usage for one instruction, derived from `Program ... consumed N of M compute units` log lines (see `parseLogsForCuUsage`). Not emitted by the program itself. */
332
- export type CuUsage = {
333
- /** Instruction name, as logged by `Program log: Instruction: <name>`. */
334
- instruction: string;
335
- /** Compute units consumed by that instruction. */
336
- cuUsage: number;
337
- };