@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,160 +0,0 @@
1
- import {
2
- BlockhashWithExpiryBlockHeight,
3
- Commitment,
4
- Connection,
5
- Context,
6
- } from '@solana/web3.js';
7
- import { BlockhashSubscriberConfig } from './types';
8
-
9
- /**
10
- * BlockhashSubscriber — polls `getLatestBlockhashAndContext`/`getBlockHeight`
11
- * on a fixed interval and caches a short history of recent blockhashes, so
12
- * callers can grab a recent blockhash for transaction building without an
13
- * RPC round-trip per transaction. Nothing is populated until `subscribe()`
14
- * (or a manual `updateBlockhash()`) has completed at least once — all getters
15
- * return `undefined`/empty before then.
16
- */
17
- export class BlockhashSubscriber {
18
- private connection: Connection;
19
- private isSubscribed = false;
20
- private latestBlockHeight: number | undefined;
21
- private latestBlockHeightContext: Context | undefined;
22
- private blockhashes: Array<BlockhashWithExpiryBlockHeight> = [];
23
- private updateBlockhashIntervalId: ReturnType<typeof setTimeout> | undefined;
24
- private commitment: Commitment;
25
- private updateIntervalMs: number;
26
-
27
- /**
28
- * @param config Either `connection` or `rpcUrl` must be provided (a `Connection` is created from `rpcUrl` if `connection` is omitted). `commitment` defaults to `'confirmed'`; `updateIntervalMs` defaults to 1000ms.
29
- * @throws If neither `config.connection` nor `config.rpcUrl` is provided.
30
- */
31
- constructor(config: BlockhashSubscriberConfig) {
32
- if (!config.connection && !config.rpcUrl) {
33
- throw new Error(
34
- 'BlockhashSubscriber requires one of connection or rpcUrl must be provided'
35
- );
36
- }
37
- this.connection = config.connection || new Connection(config.rpcUrl!);
38
- this.commitment = config.commitment ?? 'confirmed';
39
- this.updateIntervalMs = config.updateIntervalMs ?? 1000;
40
- }
41
-
42
- /** @returns The number of blockhashes currently cached (not-yet-expired, per `pruneBlockhashes`). */
43
- getBlockhashCacheSize(): number {
44
- return this.blockhashes.length;
45
- }
46
-
47
- /**
48
- * @returns The block height as of the most recent successful poll, or
49
- * `undefined` if `subscribe()`/`updateBlockhash()` has not yet completed
50
- * successfully at least once (including if every poll so far has errored).
51
- * This value is a `getBlockHeight` snapshot taken alongside the latest
52
- * blockhash fetch — it is not guaranteed to be perfectly in sync with the
53
- * blockhash slot, only "recent as of the last poll".
54
- */
55
- getLatestBlockHeight(): number | undefined {
56
- return this.latestBlockHeight;
57
- }
58
-
59
- /** @returns The RPC `Context` (including `slot`) captured with the most recent successful blockhash poll, or `undefined` before the first successful poll. */
60
- getLatestBlockHeightContext(): Context | undefined {
61
- return this.latestBlockHeightContext;
62
- }
63
-
64
- /**
65
- * Returns the latest cached blockhash, based on an offset from the latest obtained
66
- * @param offset Offset to use, defaulting to 0
67
- * @param offsetType If 'seconds', it will use calculate the actual element offset based on the update interval; otherwise it will return a fixed index
68
- * @returns Cached blockhash at the given offset, or undefined
69
- */
70
- getLatestBlockhash(
71
- offset = 0,
72
- offsetType: 'index' | 'seconds' = 'index'
73
- ): BlockhashWithExpiryBlockHeight | undefined {
74
- if (this.blockhashes.length === 0) {
75
- return undefined;
76
- }
77
-
78
- const elementOffset =
79
- offsetType == 'seconds'
80
- ? Math.floor((offset * 1000) / this.updateIntervalMs)
81
- : offset;
82
-
83
- const clampedOffset = Math.max(
84
- 0,
85
- Math.min(this.blockhashes.length - 1, elementOffset)
86
- );
87
-
88
- return this.blockhashes[this.blockhashes.length - 1 - clampedOffset];
89
- }
90
-
91
- /** Drops cached blockhashes whose `lastValidBlockHeight` is at or below `latestBlockHeight` (i.e. already expired for transaction signing). Called automatically after every `updateBlockhash`. No-ops if `latestBlockHeight` hasn't been set yet. */
92
- pruneBlockhashes() {
93
- if (this.latestBlockHeight !== undefined) {
94
- const latestBlockHeight = this.latestBlockHeight;
95
- this.blockhashes = this.blockhashes.filter(
96
- (blockhash) => blockhash.lastValidBlockHeight > latestBlockHeight
97
- );
98
- }
99
- }
100
-
101
- /**
102
- * Fetches the latest blockhash and block height in parallel and appends
103
- * the blockhash to the cache (skipped if it's identical to the
104
- * most-recently-cached one), then prunes expired entries. Errors (e.g. RPC
105
- * failure) are caught and logged, not thrown — on error, `latestBlockHeight`
106
- * is left at its previous value, but `pruneBlockhashes()` still runs in a
107
- * `finally` block and may evict entries that expired in the meantime.
108
- */
109
- async updateBlockhash() {
110
- try {
111
- const [resp, lastConfirmedBlockHeight] = await Promise.all([
112
- this.connection.getLatestBlockhashAndContext({
113
- commitment: this.commitment,
114
- }),
115
- this.connection.getBlockHeight({ commitment: this.commitment }),
116
- ]);
117
- this.latestBlockHeight = lastConfirmedBlockHeight;
118
- this.latestBlockHeightContext = resp.context;
119
-
120
- // avoid caching duplicate blockhashes
121
- if (this.blockhashes.length > 0) {
122
- if (
123
- resp.value.blockhash ===
124
- this.blockhashes[this.blockhashes.length - 1].blockhash
125
- ) {
126
- return;
127
- }
128
- }
129
-
130
- this.blockhashes.push(resp.value);
131
- } catch (e) {
132
- console.error('Error updating blockhash:\n', e);
133
- } finally {
134
- this.pruneBlockhashes();
135
- }
136
- }
137
-
138
- /** Performs an immediate `updateBlockhash()` and then starts polling on `updateIntervalMs`. Idempotent — a second call while already subscribed is a no-op. */
139
- async subscribe() {
140
- if (this.isSubscribed) {
141
- return;
142
- }
143
- this.isSubscribed = true;
144
-
145
- await this.updateBlockhash();
146
- this.updateBlockhashIntervalId = setInterval(
147
- this.updateBlockhash.bind(this),
148
- this.updateIntervalMs
149
- );
150
- }
151
-
152
- /** Stops the polling interval. Cached blockhashes and `latestBlockHeight` are left in place (not cleared). */
153
- unsubscribe() {
154
- if (this.updateBlockhashIntervalId) {
155
- clearInterval(this.updateBlockhashIntervalId);
156
- this.updateBlockhashIntervalId = undefined;
157
- }
158
- this.isSubscribed = false;
159
- }
160
- }
@@ -1,6 +0,0 @@
1
- /**
2
- * `BlockhashSubscriber` — polls and caches recent blockhashes/block heights so
3
- * transaction builders can grab a recent blockhash without an RPC round-trip
4
- * per transaction.
5
- */
6
- export * from './BlockhashSubscriber';
@@ -1,13 +0,0 @@
1
- import { Commitment, Connection } from '@solana/web3.js';
2
-
3
- /** Configuration for `BlockhashSubscriber`. */
4
- export type BlockhashSubscriberConfig = {
5
- /** RPC URL to poll block hashes from; a `Connection` is constructed from it if `connection` is not provided. One of `rpcUrl`/`connection` must be supplied. */
6
- rpcUrl?: string;
7
- /** Existing `Connection` to poll block hashes on, taking precedence over `rpcUrl` if both are given. One of `rpcUrl`/`connection` must be supplied. */
8
- connection?: Connection;
9
- /** Commitment level for both the blockhash and block-height polls; defaults to `'confirmed'`. */
10
- commitment?: Commitment;
11
- /** Poll interval in milliseconds; defaults to `1000`. */
12
- updateIntervalMs?: number;
13
- };
@@ -1,146 +0,0 @@
1
- import { Commitment, Connection, SYSVAR_CLOCK_PUBKEY } from '@solana/web3.js';
2
- import { EventEmitter } from 'events';
3
- import StrictEventEmitter from 'strict-event-emitter-types/types/src';
4
- import { BN } from '../isomorphic/anchor';
5
-
6
- // eslint-disable-next-line @typescript-eslint/ban-types
7
- type ClockSubscriberConfig = {
8
- commitment: Commitment;
9
- resubTimeoutMs?: number;
10
- };
11
-
12
- /** Events emitted on `ClockSubscriber.eventEmitter`. */
13
- export interface ClockSubscriberEvent {
14
- /** Fired with the new on-chain unix timestamp (seconds) whenever a strictly-newer `Clock` sysvar update is observed. */
15
- clockUpdate: (ts: number) => void;
16
- }
17
-
18
- /**
19
- * ClockSubscriber — tracks the on-chain unix timestamp by subscribing to the
20
- * `Clock` sysvar via `connection.onAccountChange`, with an optional
21
- * stall-detection resubscribe. Useful for reading "on-chain now" without a
22
- * per-call RPC round-trip (e.g. for evaluating time-based order/auction
23
- * conditions the same way the program would). Nothing is populated until
24
- * `subscribe()` completes its first update — `currentTs`/`getUnixTs()` return
25
- * `undefined` until then.
26
- */
27
- export class ClockSubscriber {
28
- private _latestSlot?: number;
29
- private _currentTs?: number;
30
- private subscriptionId?: number;
31
- commitment: Commitment;
32
- eventEmitter: StrictEventEmitter<EventEmitter, ClockSubscriberEvent>;
33
-
34
- /** Slot of the most recently observed `Clock` sysvar update, or `undefined` before the first update. */
35
- public get latestSlot(): number | undefined {
36
- return this._latestSlot;
37
- }
38
-
39
- /** On-chain unix timestamp (seconds) as of the most recently observed `Clock` sysvar update, or `undefined` before the first update. */
40
- public get currentTs(): number | undefined {
41
- return this._currentTs;
42
- }
43
-
44
- // Reconnection
45
- private timeoutId?: ReturnType<typeof setTimeout>;
46
- private resubTimeoutMs?: number;
47
- private isUnsubscribing = false;
48
- private receivingData = false;
49
-
50
- /**
51
- * @param connection RPC connection to subscribe on.
52
- * @param config.commitment Commitment for the account-change subscription; defaults to `'confirmed'`.
53
- * @param config.resubTimeoutMs If set to a positive value, resubscribe when no update arrives for this many ms; `0` (or unset) disables the resubscribe watchdog. Positive values below 1000ms log a warning but are still honored.
54
- */
55
- public constructor(
56
- private connection: Connection,
57
- config?: ClockSubscriberConfig
58
- ) {
59
- this.eventEmitter = new EventEmitter();
60
- this.resubTimeoutMs = config?.resubTimeoutMs;
61
- this.commitment = config?.commitment || 'confirmed';
62
- if (this.resubTimeoutMs !== undefined && this.resubTimeoutMs < 1000) {
63
- console.log(
64
- 'resubTimeoutMs should be at least 1000ms to avoid spamming resub'
65
- );
66
- }
67
- }
68
-
69
- /** Subscribes to `Clock` sysvar account changes. Unlike `SlotSubscriber`/`SlothashSubscriber`, does not perform an initial RPC fetch — `currentTs`/`latestSlot` stay `undefined` until the first account-change notification arrives. Idempotent while already subscribed. */
70
- public async subscribe(): Promise<void> {
71
- if (this.subscriptionId != null) {
72
- return;
73
- }
74
-
75
- this.subscriptionId = this.connection.onAccountChange(
76
- SYSVAR_CLOCK_PUBKEY,
77
- (acctInfo, context) => {
78
- if (!this.latestSlot || this.latestSlot < context.slot) {
79
- if (this.resubTimeoutMs && !this.isUnsubscribing) {
80
- this.receivingData = true;
81
- clearTimeout(this.timeoutId);
82
- this.setTimeout();
83
- }
84
- this._latestSlot = context.slot;
85
- const currentTs = new BN(
86
- acctInfo.data.subarray(32, 39),
87
- undefined,
88
- 'le'
89
- ).toNumber();
90
- this._currentTs = currentTs;
91
- this.eventEmitter.emit('clockUpdate', currentTs);
92
- }
93
- },
94
- this.commitment
95
- );
96
-
97
- if (this.resubTimeoutMs) {
98
- this.receivingData = true;
99
- this.setTimeout();
100
- }
101
- }
102
-
103
- private setTimeout(): void {
104
- this.timeoutId = setTimeout(async () => {
105
- if (this.isUnsubscribing) {
106
- // If we are in the process of unsubscribing, do not attempt to resubscribe
107
- return;
108
- }
109
-
110
- if (this.receivingData) {
111
- console.log(
112
- `No new slot in ${this.resubTimeoutMs}ms, slot subscriber resubscribing`
113
- );
114
- await this.unsubscribe(true);
115
- this.receivingData = false;
116
- await this.subscribe();
117
- }
118
- }, this.resubTimeoutMs);
119
- }
120
-
121
- /** @returns The on-chain unix timestamp (seconds) as of the last update, or `undefined` if `subscribe()` hasn't received an update yet. Equivalent to the `currentTs` getter. */
122
- public getUnixTs(): number | undefined {
123
- return this.currentTs;
124
- }
125
-
126
- /**
127
- * Removes the `onAccountChange` listener and cancels the resub timeout.
128
- * @param onResub Internal flag used when unsubscribing as part of an automatic resubscribe cycle; when `false`, also permanently disables future auto-resubscribe by clearing `resubTimeoutMs`.
129
- */
130
- public async unsubscribe(onResub = false): Promise<void> {
131
- if (!onResub) {
132
- this.resubTimeoutMs = undefined;
133
- }
134
- this.isUnsubscribing = true;
135
- clearTimeout(this.timeoutId);
136
- this.timeoutId = undefined;
137
-
138
- if (this.subscriptionId != null) {
139
- await this.connection.removeAccountChangeListener(this.subscriptionId);
140
- this.subscriptionId = undefined;
141
- this.isUnsubscribing = false;
142
- } else {
143
- this.isUnsubscribing = false;
144
- }
145
- }
146
- }
package/src/config.ts DELETED
@@ -1,312 +0,0 @@
1
- import { ConfirmOptions, PublicKey } from '@solana/web3.js';
2
- import {
3
- isVariant,
4
- OracleSource,
5
- PerpMarketAccount,
6
- SpotMarketAccount,
7
- } from './types';
8
- import {
9
- DevnetPerpMarkets,
10
- MainnetPerpMarkets,
11
- PerpMarketConfig,
12
- PerpMarkets,
13
- } from './constants/perpMarkets';
14
- import {
15
- SpotMarketConfig,
16
- SpotMarkets,
17
- DevnetSpotMarkets,
18
- MainnetSpotMarkets,
19
- } from './constants/spotMarkets';
20
- import { OracleInfo } from './oracles/types';
21
- import { Program, ProgramAccount } from './isomorphic/anchor';
22
- import { getOracleId } from './oracles/oracleId';
23
- import { Velocity } from './idl/velocity';
24
-
25
- /** The Anchor `Program` client type for the velocity IDL, parameterized over the generated `Velocity` type. */
26
- export type VelocityProgram = Program<Velocity>;
27
-
28
- /** Supported deployment environments. */
29
- export type VelocityEnv = 'devnet' | 'mainnet-beta';
30
-
31
- /** Widened env type accepted by `initialize()`; `'master'` is a legacy alias for `'devnet'`. */
32
- export type LegacyVelocityEnv = VelocityEnv | 'master';
33
-
34
- /** Per-environment addresses, program ids, and default market lists returned by `getConfig()`/`initialize()`. */
35
- export interface VelocityConfig {
36
- ENV: VelocityEnv;
37
- /** Legacy Pyth oracle mapping account address for this environment (push-oracle discovery; not used by pull/Lazer sources). */
38
- PYTH_ORACLE_MAPPING_ADDRESS: string;
39
- /** Deployed velocity program id for this environment, base58. */
40
- VELOCITY_PROGRAM_ID: string;
41
- /** Deployed jit-proxy program id, base58, if jit-proxy is available in this environment. */
42
- JIT_PROXY_PROGRAM_ID?: string;
43
- /** Velocity's oracle-receiver program id (verifies/receives pushed oracle updates), base58. */
44
- VELOCITY_ORACLE_RECEIVER_ID: string;
45
- /** Mint address of the protocol's quote asset (e.g. USDC) for this environment, base58. */
46
- QUOTE_MINT_ADDRESS: string;
47
- /** Mint address of the legacy v2-alpha ticket token for this environment, base58. */
48
- V2_ALPHA_TICKET_MINT_ADDRESS: string;
49
- /** Default perp market configs to subscribe to when the caller doesn't supply an explicit list. */
50
- PERP_MARKETS: PerpMarketConfig[];
51
- /** Default spot market configs to subscribe to when the caller doesn't supply an explicit list. */
52
- SPOT_MARKETS: SpotMarketConfig[];
53
- /** @deprecated use MARKET_LOOKUP_TABLES */
54
- MARKET_LOOKUP_TABLE: string;
55
- /** Address lookup table accounts (base58) used to fit market/oracle accounts into versioned transactions. */
56
- MARKET_LOOKUP_TABLES: string[];
57
- /** Deployed Switchboard On-Demand program id for this environment. */
58
- SB_ON_DEMAND_PID: PublicKey;
59
- }
60
-
61
- /** Mainnet-beta velocity program id, base58. */
62
- export const VELOCITY_PROGRAM_ID =
63
- 'vELoC1audYbSYVRXn1vPaV8Axoa9oU6BYmNGZZBDZ1P';
64
-
65
- /** Devnet velocity program id, base58. */
66
- export const VELOCITY_DEVNET_PROGRAM_ID =
67
- 'vELoC1audYbSYVRXn1vPaV8Axoa9oU6BYmNGZZBDZ1P';
68
-
69
- /** Velocity's oracle-receiver program id, base58 (same across devnet and mainnet-beta). */
70
- export const VELOCITY_ORACLE_RECEIVER_ID =
71
- 'G6EoTTTgpkNBtVXo96EQp2m6uwwVh2Kt6YidjkmQqoha';
72
-
73
- /** Pyth Lazer program id, base58. */
74
- export const PYTH_LAZER_PROGRAM_ID =
75
- 'pytd2yyk641x7ak7mkaasSJVXh6YYZnC7wTmtgAyxPt';
76
-
77
- /** Switchboard On-Demand program id on devnet. */
78
- export const SB_ON_DEMAND_DEVNET_PID = new PublicKey(
79
- 'Aio4gaXjXzJNVLtzwtNVmSqGKpANtXhybbkhtAC94ji2'
80
- );
81
- /** Switchboard On-Demand program id on mainnet-beta. */
82
- export const SB_ON_DEMAND_MAINNET_PID = new PublicKey(
83
- 'SBondMDrcV3K4kxZR1HNVT7osZxAHVHgYXL5Ze1oMUv'
84
- );
85
- /** Pyth Lazer storage account holding feed metadata, shared across environments. */
86
- export const PYTH_LAZER_STORAGE_ACCOUNT_KEY = new PublicKey(
87
- '3rdJbqfnagQ4yx9HXJViD4zc4xpiSqmFsKpPuSCQVyQL'
88
- );
89
-
90
- /** Default `ConfirmOptions` (both preflight and confirmation at `'confirmed'` commitment) used across the SDK's tx senders unless overridden. */
91
- export const DEFAULT_CONFIRMATION_OPTS: ConfirmOptions = {
92
- preflightCommitment: 'confirmed',
93
- commitment: 'confirmed',
94
- };
95
-
96
- /** Built-in `VelocityConfig` presets for each supported environment. */
97
- export const configs: { [key in VelocityEnv]: VelocityConfig } = {
98
- devnet: {
99
- ENV: 'devnet',
100
- PYTH_ORACLE_MAPPING_ADDRESS: 'BmA9Z6FjioHJPpjT39QazZyhDRUdZy2ezwx4GiDdE2u2',
101
- VELOCITY_PROGRAM_ID: VELOCITY_DEVNET_PROGRAM_ID,
102
- JIT_PROXY_PROGRAM_ID: 'J1TnP8zvVxbtF5KFp5xRmWuvG9McnhzmBd9XGfCyuxFP',
103
- QUOTE_MINT_ADDRESS: 'GqmEqYsy8EyvofDpmtFxK8zhYrgWgNokAtYoduQdL7v6',
104
- V2_ALPHA_TICKET_MINT_ADDRESS:
105
- 'DeEiGWfCMP9psnLGkxGrBBMEAW5Jv8bBGMN8DCtFRCyB',
106
- PERP_MARKETS: DevnetPerpMarkets,
107
- SPOT_MARKETS: DevnetSpotMarkets,
108
- /** @deprecated use MARKET_LOOKUP_TABLES */
109
- MARKET_LOOKUP_TABLE: 'FaMS3U4uBojvGn5FSDEPimddcXsCfwkKsFgMVVnDdxGb',
110
- MARKET_LOOKUP_TABLES: ['FaMS3U4uBojvGn5FSDEPimddcXsCfwkKsFgMVVnDdxGb'],
111
- VELOCITY_ORACLE_RECEIVER_ID,
112
- SB_ON_DEMAND_PID: SB_ON_DEMAND_DEVNET_PID,
113
- },
114
- 'mainnet-beta': {
115
- ENV: 'mainnet-beta',
116
- PYTH_ORACLE_MAPPING_ADDRESS: 'AHtgzX45WTKfkPG53L6WYhGEXwQkN1BVknET3sVsLL8J',
117
- VELOCITY_PROGRAM_ID,
118
- JIT_PROXY_PROGRAM_ID: 'J1TnP8zvVxbtF5KFp5xRmWuvG9McnhzmBd9XGfCyuxFP',
119
- // Relaunch quote market (spot 0) is USDT — see
120
- // deploy-scripts/params/relaunch-spot-markets.json.
121
- QUOTE_MINT_ADDRESS: 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB',
122
- V2_ALPHA_TICKET_MINT_ADDRESS:
123
- 'Cmvhycb6LQvvzaShGw4iDHRLzeSSryioAsU98DSSkMNa',
124
- PERP_MARKETS: MainnetPerpMarkets,
125
- SPOT_MARKETS: MainnetSpotMarkets,
126
- /** @deprecated use MARKET_LOOKUP_TABLES */
127
- MARKET_LOOKUP_TABLE: 'Fpys8GRa5RBWfyeN7AaDUwFGD1zkDCA4z3t4CJLV8dfL',
128
- MARKET_LOOKUP_TABLES: [
129
- 'Fpys8GRa5RBWfyeN7AaDUwFGD1zkDCA4z3t4CJLV8dfL',
130
- 'EiWSskK5HXnBTptiS5DH6gpAJRVNQ3cAhTKBGaiaysAb',
131
- ],
132
- VELOCITY_ORACLE_RECEIVER_ID,
133
- SB_ON_DEMAND_PID: SB_ON_DEMAND_MAINNET_PID,
134
- },
135
- };
136
-
137
- /** Module-level active config; defaults to the `devnet` preset until `initialize()` is called. */
138
- let currentConfig: VelocityConfig = configs.devnet;
139
-
140
- /**
141
- * Returns the SDK's currently active `VelocityConfig` (the `devnet` preset by default, or
142
- * whatever was last set via `initialize()`).
143
- * @returns The active config.
144
- */
145
- export const getConfig = (): VelocityConfig => currentConfig;
146
-
147
- /**
148
- * Sets the SDK's active environment/config, read thereafter via `getConfig()`. This mutates
149
- * process-wide module state — call it once at startup before constructing clients, not
150
- * concurrently with multiple environments in the same process.
151
- *
152
- * Defaults to the `devnet` preset if you never call this function.
153
- * @param props.env - Environment to activate; `'master'` is accepted as a legacy alias for `'devnet'`.
154
- * @param props.overrideEnv - Partial fields to overlay on top of the selected preset (e.g. a custom `VELOCITY_PROGRAM_ID`).
155
- * @returns The resulting active `VelocityConfig` (preset merged with `overrideEnv`).
156
- */
157
- export const initialize = (props: {
158
- env: LegacyVelocityEnv;
159
- overrideEnv?: Partial<VelocityConfig>;
160
- }): VelocityConfig => {
161
- const override = props.overrideEnv ?? {};
162
- const normalizedEnv: VelocityEnv =
163
- props.env === 'master' ? 'devnet' : props.env;
164
-
165
- currentConfig = { ...configs[normalizedEnv], ...override };
166
- return currentConfig;
167
- };
168
-
169
- /**
170
- * Whether the SDK can construct an `OracleClient` for `source` — mirrors the throwing branches in
171
- * `getOracleClient`. Markets whose oracle source is unsupported (retired Switchboard feeds and
172
- * removed Pyth pull feeds) are still listed/indexed, but their oracles must not be added to
173
- * subscription lists, since building a client for them throws and would abort the whole subscribe.
174
- */
175
- function isOracleSourceSubscribable(source: OracleSource): boolean {
176
- return !(
177
- isVariant(source, 'deprecatedSwitchboard') ||
178
- isVariant(source, 'deprecatedSwitchboardOnDemand') ||
179
- isVariant(source, 'pythPull') ||
180
- isVariant(source, 'pyth1KPull') ||
181
- isVariant(source, 'pyth1MPull') ||
182
- isVariant(source, 'pythStableCoinPull')
183
- );
184
- }
185
-
186
- /**
187
- * Builds the market-index and oracle-subscription lists a `VelocityClient` needs to subscribe to,
188
- * from static market configs (no RPC calls) — the fast, offline alternative to
189
- * `findAllMarketAndOracles`. Oracles are de-duplicated by `getOracleId` (pubkey + source), so a
190
- * pubkey shared across multiple markets under the same source only appears once.
191
- * @param env - Environment whose built-in market lists (`PerpMarkets[env]`/`SpotMarkets[env]`) are
192
- * used as the fallback when `perpMarkets`/`spotMarkets` aren't supplied.
193
- * @param perpMarkets - Explicit perp market configs to use instead of the environment default; if
194
- * omitted or empty, falls back to `PerpMarkets[env]`.
195
- * @param spotMarkets - Explicit spot market configs to use instead of the environment default; if
196
- * omitted or empty, falls back to `SpotMarkets[env]`.
197
- * @returns `perpMarketIndexes`/`spotMarketIndexes` for every market considered, and the
198
- * de-duplicated `oracleInfos` needed to subscribe to their oracles.
199
- */
200
- export function getMarketsAndOraclesForSubscription(
201
- env: VelocityEnv,
202
- perpMarkets?: PerpMarketConfig[],
203
- spotMarkets?: SpotMarketConfig[]
204
- ): {
205
- perpMarketIndexes: number[];
206
- spotMarketIndexes: number[];
207
- oracleInfos: OracleInfo[];
208
- } {
209
- const perpMarketsToUse =
210
- perpMarkets !== undefined && perpMarkets.length > 0
211
- ? perpMarkets
212
- : PerpMarkets[env];
213
- const spotMarketsToUse =
214
- spotMarkets !== undefined && spotMarkets.length > 0
215
- ? spotMarkets
216
- : SpotMarkets[env];
217
-
218
- const perpMarketIndexes = [];
219
- const spotMarketIndexes = [];
220
- const oracleInfos = new Map<string, OracleInfo>();
221
-
222
- for (const market of perpMarketsToUse) {
223
- perpMarketIndexes.push(market.marketIndex);
224
- if (isOracleSourceSubscribable(market.oracleSource)) {
225
- oracleInfos.set(getOracleId(market.oracle, market.oracleSource), {
226
- publicKey: market.oracle,
227
- source: market.oracleSource,
228
- });
229
- }
230
- }
231
-
232
- for (const spotMarket of spotMarketsToUse) {
233
- spotMarketIndexes.push(spotMarket.marketIndex);
234
- if (isOracleSourceSubscribable(spotMarket.oracleSource)) {
235
- oracleInfos.set(getOracleId(spotMarket.oracle, spotMarket.oracleSource), {
236
- publicKey: spotMarket.oracle,
237
- source: spotMarket.oracleSource,
238
- });
239
- }
240
- }
241
-
242
- return {
243
- perpMarketIndexes: perpMarketIndexes,
244
- spotMarketIndexes: spotMarketIndexes,
245
- oracleInfos: Array.from(oracleInfos.values()),
246
- };
247
- }
248
-
249
- /**
250
- * Discovers every perp/spot market currently deployed under `program`'s program id via
251
- * `getProgramAccounts` (`perpMarket.all()`/`spotMarket.all()`), rather than relying on a static
252
- * config list — use this to pick up markets added after the SDK's bundled configs were published,
253
- * or when running against a custom/unlisted deployment. Oracles are de-duplicated by `getOracleId`
254
- * (pubkey + source).
255
- * @param program - Anchor program client used to fetch all `PerpMarket`/`SpotMarket` accounts.
256
- * @returns Market indexes and full decoded accounts for every discovered perp/spot market, plus
257
- * the de-duplicated `oracleInfos` needed to subscribe to their oracles.
258
- */
259
- export async function findAllMarketAndOracles(
260
- program: VelocityProgram
261
- ): Promise<{
262
- perpMarketIndexes: number[];
263
- perpMarketAccounts: PerpMarketAccount[];
264
- spotMarketIndexes: number[];
265
- oracleInfos: OracleInfo[];
266
- spotMarketAccounts: SpotMarketAccount[];
267
- }> {
268
- const perpMarketIndexes = [];
269
- const spotMarketIndexes = [];
270
- const oracleInfos = new Map<string, OracleInfo>();
271
-
272
- const perpMarketProgramAccounts = (await (
273
- program.account as any
274
- ).perpMarket.all()) as ProgramAccount<PerpMarketAccount>[];
275
- const spotMarketProgramAccounts = (await (
276
- program.account as any
277
- ).spotMarket.all()) as ProgramAccount<SpotMarketAccount>[];
278
-
279
- for (const perpMarketProgramAccount of perpMarketProgramAccounts) {
280
- const perpMarket = perpMarketProgramAccount.account as PerpMarketAccount;
281
- perpMarketIndexes.push(perpMarket.marketIndex);
282
- if (isOracleSourceSubscribable(perpMarket.oracleSource)) {
283
- oracleInfos.set(getOracleId(perpMarket.oracle, perpMarket.oracleSource), {
284
- publicKey: perpMarket.oracle,
285
- source: perpMarket.oracleSource,
286
- });
287
- }
288
- }
289
-
290
- for (const spotMarketProgramAccount of spotMarketProgramAccounts) {
291
- const spotMarket = spotMarketProgramAccount.account as SpotMarketAccount;
292
- spotMarketIndexes.push(spotMarket.marketIndex);
293
- if (isOracleSourceSubscribable(spotMarket.oracleSource)) {
294
- oracleInfos.set(getOracleId(spotMarket.oracle, spotMarket.oracleSource), {
295
- publicKey: spotMarket.oracle,
296
- source: spotMarket.oracleSource,
297
- });
298
- }
299
- }
300
-
301
- return {
302
- perpMarketIndexes,
303
- perpMarketAccounts: perpMarketProgramAccounts.map(
304
- (account) => account.account
305
- ),
306
- spotMarketIndexes,
307
- spotMarketAccounts: spotMarketProgramAccounts.map(
308
- (account) => account.account
309
- ),
310
- oracleInfos: Array.from(oracleInfos.values()),
311
- };
312
- }
@@ -1,9 +0,0 @@
1
- /**
2
- * Protocol constants: numeric precision bases, market indices, transaction size limits,
3
- * and perp/spot market config arrays.
4
- * Import specific submodules to avoid pulling in unused market lists.
5
- */
6
- export * from './numericConstants';
7
- export * from './perpMarkets';
8
- export * from './spotMarkets';
9
- export * from './txConstants';