@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
package/src/math/utils.ts DELETED
@@ -1,183 +0,0 @@
1
- import { BN } from '../isomorphic/anchor';
2
- import { ONE, ZERO } from '../constants/numericConstants';
3
-
4
- /**
5
- * Clamps `x` to the inclusive range `[min, max]`.
6
- *
7
- * @param {BN} x - The value to clamp
8
- * @param {BN} min - The lower bound
9
- * @param {BN} max - The upper bound
10
- * @return {BN} `x` if within range, otherwise `min` or `max`
11
- */
12
- export function clampBN(x: BN, min: BN, max: BN): BN {
13
- return BN.max(min, BN.min(x, max));
14
- }
15
-
16
- /**
17
- * Integer square root via binary recursion, floored to the nearest integer (i.e.
18
- * `squareRootBN(n) === Math.floor(Math.sqrt(n))` for values representable as a double). Used
19
- * throughout the AMM math wherever the program takes an integer sqrt of the constant-product
20
- * invariant.
21
- *
22
- * @param {BN} n - A non-negative integer
23
- * @return {BN} `floor(sqrt(n))`
24
- * @throws {Error} If `n` is negative
25
- */
26
- export const squareRootBN = (n: BN): BN => {
27
- if (n.lt(new BN(0))) {
28
- throw new Error('Sqrt only works on non-negtiave inputs');
29
- }
30
- if (n.lt(new BN(2))) {
31
- return n;
32
- }
33
-
34
- const smallCand = squareRootBN(n.shrn(2)).shln(1);
35
- const largeCand = smallCand.add(new BN(1));
36
-
37
- if (largeCand.mul(largeCand).gt(n)) {
38
- return smallCand;
39
- } else {
40
- return largeCand;
41
- }
42
- };
43
-
44
- /**
45
- * Integer division rounded up (ceiling), mirroring the program's unsigned `safe_div_ceil` (e.g.
46
- * used for borrow token amounts, where rounding up favors the protocol/lenders over the
47
- * borrower). Only meaningful for non-negative operands — `bn.js`'s `.mod()` returns a remainder
48
- * with the sign of the dividend, so this is not a general-purpose ceiling division for signed
49
- * inputs.
50
- *
51
- * @param {BN} a - The dividend (expected non-negative)
52
- * @param {BN} b - The divisor (expected positive)
53
- * @return {BN} `ceil(a / b)`
54
- */
55
- export const divCeil = (a: BN, b: BN): BN => {
56
- const quotient = a.div(b);
57
-
58
- const remainder = a.mod(b);
59
-
60
- if (remainder.gt(ZERO)) {
61
- return quotient.add(ONE);
62
- } else {
63
- return quotient;
64
- }
65
- };
66
-
67
- /**
68
- * Sign function returning ±1 (never 0).
69
- *
70
- * @param {BN} x - The value to test
71
- * @return {BN} `-1` if `x` is negative, otherwise `1` (including for zero)
72
- */
73
- export const sigNum = (x: BN): BN => {
74
- return x.isNeg() ? new BN(-1) : new BN(1);
75
- };
76
-
77
- /**
78
- * Calculates the time remaining until the next update is eligible under a rounded, "on-the-hour"
79
- * update schedule. Used for perp funding rate updates and revenue-to-insurance-fund sweeps: if the
80
- * last update landed within 1/3 of `updatePeriod` of an hour boundary, the next update is allowed
81
- * on that boundary; otherwise it's pushed to the following boundary (two periods out) to avoid
82
- * drifting the schedule off-hour. Returns zero once the wait has already elapsed.
83
- *
84
- * @param {BN} now - Current unix timestamp, seconds
85
- * @param {BN} lastUpdateTs - Unix timestamp of the last update, seconds
86
- * @param {BN} updatePeriod - Desired interval between updates, seconds
87
- * @return {BN} Seconds remaining until the next update is eligible (zero if already due)
88
- */
89
- export function timeRemainingUntilUpdate(
90
- now: BN,
91
- lastUpdateTs: BN,
92
- updatePeriod: BN
93
- ): BN {
94
- const timeSinceLastUpdate = now.sub(lastUpdateTs);
95
-
96
- // round next update time to be available on the hour
97
- let nextUpdateWait = updatePeriod;
98
- if (updatePeriod.gt(new BN(1))) {
99
- const lastUpdateDelay = lastUpdateTs.umod(updatePeriod);
100
- if (!lastUpdateDelay.isZero()) {
101
- const maxDelayForNextPeriod = updatePeriod.div(new BN(3));
102
-
103
- const twoFundingPeriods = updatePeriod.mul(new BN(2));
104
-
105
- if (lastUpdateDelay.gt(maxDelayForNextPeriod)) {
106
- // too late for on the hour next period, delay to following period
107
- nextUpdateWait = twoFundingPeriods.sub(lastUpdateDelay);
108
- } else {
109
- // allow update on the hour
110
- nextUpdateWait = updatePeriod.sub(lastUpdateDelay);
111
- }
112
-
113
- if (nextUpdateWait.gt(twoFundingPeriods)) {
114
- nextUpdateWait = nextUpdateWait.sub(updatePeriod);
115
- }
116
- }
117
- }
118
- const timeRemainingUntilUpdate = nextUpdateWait
119
- .sub(timeSinceLastUpdate)
120
- .isNeg()
121
- ? ZERO
122
- : nextUpdateWait.sub(timeSinceLastUpdate);
123
-
124
- return timeRemainingUntilUpdate;
125
- }
126
-
127
- /**
128
- * Compares two date strings for equality by calendar day (year/month/date), ignoring
129
- * time-of-day. Uses the local `getDate()`/`getMonth()`/`getFullYear()` getters, so the
130
- * comparison is against the process's local-timezone calendar day (not UTC).
131
- *
132
- * @param {string} dateString1 - A date string parseable by `new Date()`
133
- * @param {string} dateString2 - A date string parseable by `new Date()`
134
- * @return {boolean} Whether both parse to the same calendar day
135
- */
136
- export const checkSameDate = (dateString1: string, dateString2: string) => {
137
- const date1 = new Date(dateString1);
138
- const date2 = new Date(dateString2);
139
-
140
- const isSameDate =
141
- date1.getDate() === date2.getDate() &&
142
- date1.getMonth() === date2.getMonth() &&
143
- date1.getFullYear() === date2.getFullYear();
144
-
145
- return isSameDate;
146
- };
147
-
148
- /**
149
- * True if `number` is within `Number.MAX_SAFE_INTEGER` (2^53 - 1), i.e. safe to convert to a
150
- * `BN` via a JS `number` without losing precision.
151
- *
152
- * @param {number} number - The value to check (typically already multiplied by a target precision)
153
- * @return {boolean} Whether `number` can be represented exactly as a JS number
154
- */
155
- export function isBNSafe(number: number): boolean {
156
- return number <= 0x1fffffffffffff;
157
- }
158
-
159
- /**
160
- * Converts a human-readable JS `number` into a `BN` scaled by `precision`, routing through a
161
- * string conversion (`number.toString()` for whole numbers) instead of `number * precision` when
162
- * the naive multiplication would exceed `Number.MAX_SAFE_INTEGER` (per `isBNSafe`), avoiding
163
- * silent floating-point precision loss for large inputs. Note a fractional input whose scaled
164
- * value exceeds `Number.MAX_SAFE_INTEGER` has its fractional part truncated (`bn.js` accepts only
165
- * integer numbers); this is intentional and pinned by `tests/bn/test.ts`.
166
- *
167
- * @param {number} number - The human-readable amount to convert
168
- * @param {BN} precision - The target fixed-point precision (e.g. `QUOTE_PRECISION`, `BASE_PRECISION`)
169
- * @return {BN} `number` scaled by `precision`
170
- */
171
- export function numberToSafeBN(number: number, precision: BN): BN {
172
- // check if number has decimals
173
- const candidate = number * precision.toNumber();
174
- if (isBNSafe(candidate)) {
175
- return new BN(candidate);
176
- } else {
177
- if (number % 1 === 0) {
178
- return new BN(number.toString()).mul(precision);
179
- } else {
180
- return new BN(number).mul(precision);
181
- }
182
- }
183
- }
package/src/memcmp.ts DELETED
@@ -1,279 +0,0 @@
1
- import { MemcmpFilter, PublicKey } from '@solana/web3.js';
2
- import bs58 from 'bs58';
3
- import { BorshAccountsCoder } from './isomorphic/anchor29';
4
- import { encodeName } from './userName';
5
-
6
- /**
7
- * Builds a `getProgramAccounts` memcmp filter matching the 8-byte Anchor discriminator of the
8
- * `User` account type at offset 0. Use to fetch all `User` (sub-account) accounts.
9
- * @returns A memcmp filter for `User` accounts.
10
- */
11
- export function getUserFilter(): MemcmpFilter {
12
- return {
13
- memcmp: {
14
- offset: 0,
15
- bytes: bs58.encode(BorshAccountsCoder.accountDiscriminator('User')),
16
- },
17
- };
18
- }
19
-
20
- /*
21
- * Byte offsets of the trailing scalar flags in the `User` account.
22
- *
23
- * These MUST match the on-chain `User` layout decoded in `decode/user.ts`. The
24
- * current Velocity layout is 4496 bytes, with the tail block laid out as
25
- * consecutive single bytes:
26
- * status(4468) isMarginTradingEnabled(4469) idle(4470) openOrders(4471)
27
- * hasOpenOrder(4472) openAuctions(4473) hasOpenAuction(4474) poolId(4475)
28
- * specialUserStatus(4476)
29
- *
30
- * NOTE: these were previously hardcoded to the older (4376-byte) layout
31
- * (idle@4350, hasOpenOrder@4352, ...). After Velocity added fields to
32
- * `PerpPosition`, the account grew by 120 bytes and these flags shifted, but
33
- * the filters were not updated — so `getUserWithOrderFilter()` matched zero
34
- * accounts and the DLOB order book never populated. Keep these in sync with
35
- * `decode/user.ts` if the `User` layout changes again.
36
- */
37
- const USER_IDLE_OFFSET = 4470;
38
- const USER_HAS_OPEN_ORDER_OFFSET = 4472;
39
- const USER_HAS_OPEN_AUCTION_OFFSET = 4474;
40
- const USER_POOL_ID_OFFSET = 4475;
41
-
42
- /**
43
- * Builds a memcmp filter matching `User` accounts whose `idle` flag (offset 4470) is `false`.
44
- * Idle sub-accounts have no open positions/orders and have been inactive past the idle threshold;
45
- * this filter excludes them, e.g. when scanning for accounts that need active monitoring.
46
- * @returns A memcmp filter for non-idle `User` accounts.
47
- */
48
- export function getNonIdleUserFilter(): MemcmpFilter {
49
- return {
50
- memcmp: {
51
- offset: USER_IDLE_OFFSET,
52
- bytes: bs58.encode(Uint8Array.from([0])),
53
- },
54
- };
55
- }
56
-
57
- /**
58
- * Builds a memcmp filter matching `User` accounts with `hasOpenOrder` (offset 4472) set to `true`
59
- * — i.e. at least one live order. Used by the DLOB to fetch only accounts that can populate the
60
- * order book.
61
- * @returns A memcmp filter for `User` accounts with at least one open order.
62
- */
63
- export function getUserWithOrderFilter(): MemcmpFilter {
64
- return {
65
- memcmp: {
66
- offset: USER_HAS_OPEN_ORDER_OFFSET,
67
- bytes: bs58.encode(Uint8Array.from([1])),
68
- },
69
- };
70
- }
71
-
72
- /**
73
- * Builds a memcmp filter matching `User` accounts with `hasOpenOrder` (offset 4472) set to `false`
74
- * — i.e. no live orders.
75
- * @returns A memcmp filter for `User` accounts with no open orders.
76
- */
77
- export function getUserWithoutOrderFilter(): MemcmpFilter {
78
- return {
79
- memcmp: {
80
- offset: USER_HAS_OPEN_ORDER_OFFSET,
81
- bytes: bs58.encode(Uint8Array.from([0])),
82
- },
83
- };
84
- }
85
-
86
- /**
87
- * Builds a memcmp filter matching `User` accounts with `hasOpenAuction` (offset 4474) set to
88
- * `true` — i.e. at least one order still in its Dutch-auction window.
89
- * @returns A memcmp filter for `User` accounts with an active order auction.
90
- */
91
- export function getUserWithAuctionFilter(): MemcmpFilter {
92
- return {
93
- memcmp: {
94
- offset: USER_HAS_OPEN_AUCTION_OFFSET,
95
- bytes: bs58.encode(Uint8Array.from([1])),
96
- },
97
- };
98
- }
99
-
100
- /**
101
- * Builds a memcmp filter matching `User` accounts whose `name` field (32 bytes, offset 72) equals
102
- * `name` once encoded/padded the same way as on-chain.
103
- * @param name - Human-readable sub-account name to match; encoded via `encodeName` (UTF-8,
104
- * space-padded/truncated to 32 bytes) before comparison.
105
- * @returns A memcmp filter for `User` accounts with the given name.
106
- */
107
- export function getUserWithName(name: string): MemcmpFilter {
108
- return {
109
- memcmp: {
110
- offset: 72,
111
- bytes: bs58.encode(Uint8Array.from(encodeName(name))),
112
- },
113
- };
114
- }
115
-
116
- /**
117
- * Builds a memcmp filter matching `User` accounts whose `poolId` (single byte, offset 4475) equals
118
- * `poolId`. Used to scope account scans to a specific isolated pool.
119
- * @param poolId - Pool id byte (0 = main/cross pool) to match.
120
- * @returns A memcmp filter for `User` accounts in the given pool.
121
- */
122
- export function getUsersWithPoolId(poolId: number): MemcmpFilter {
123
- return {
124
- memcmp: {
125
- offset: USER_POOL_ID_OFFSET,
126
- bytes: bs58.encode(Uint8Array.from([poolId])),
127
- },
128
- };
129
- }
130
-
131
- /**
132
- * Builds a `getProgramAccounts` memcmp filter matching the 8-byte Anchor discriminator of the
133
- * `UserStats` account type at offset 0. Use to fetch all `UserStats` accounts.
134
- * @returns A memcmp filter for `UserStats` accounts.
135
- */
136
- export function getUserStatsFilter(): MemcmpFilter {
137
- return {
138
- memcmp: {
139
- offset: 0,
140
- bytes: bs58.encode(BorshAccountsCoder.accountDiscriminator('UserStats')),
141
- },
142
- };
143
- }
144
-
145
- /*
146
- * Byte offset of `referrer_status` in the `UserStats` account: 8 (discriminator)
147
- * + authority(32) + referrer(32) + fees(32) + maker/taker/filler volume 30d(24)
148
- * + last maker/taker/filler volume 30d ts(24) + if_staked_quote_asset_amount(8)
149
- * + number_of_sub_accounts(2) + number_of_sub_accounts_created(2) = 164.
150
- */
151
- const USER_STATS_REFERRER_STATUS_OFFSET = 164;
152
-
153
- /**
154
- * Builds a memcmp filter matching `UserStats` accounts whose `referrerStatus` bitflag byte (offset
155
- * 164) is exactly `ReferrerStatus.IsReferred` (2) — i.e. the account was referred and is *not*
156
- * also flagged `IsReferrer`. Because memcmp does an exact byte match rather than a bitwise test,
157
- * this excludes accounts that are both `IsReferrer` and `IsReferred` (byte value 3); use
158
- * `getUserStatsIsReferredOrReferrerFilter` for that combined case.
159
- * @returns A memcmp filter for `UserStats` accounts referred by (but not also referring) another user.
160
- */
161
- export function getUserStatsIsReferredFilter(): MemcmpFilter {
162
- return {
163
- memcmp: {
164
- offset: USER_STATS_REFERRER_STATUS_OFFSET,
165
- bytes: bs58.encode(Buffer.from(Uint8Array.from([2]))),
166
- },
167
- };
168
- }
169
-
170
- /**
171
- * Builds a memcmp filter matching `UserStats` accounts whose `referrerStatus` bitflag byte (offset
172
- * 164) is exactly 3 — i.e. `ReferrerStatus.IsReferrer | ReferrerStatus.IsReferred` both set on the
173
- * same account. Despite the name, this is an exact-byte match (memcmp can't test bits in
174
- * isolation), so it does *not* match an account that is only `IsReferrer` (1) or only `IsReferred`
175
- * (2) — use `getUserStatsIsReferredFilter` for the referred-only case.
176
- * @returns A memcmp filter for `UserStats` accounts with both the referrer and referred flags set.
177
- */
178
- export function getUserStatsIsReferredOrReferrerFilter(): MemcmpFilter {
179
- return {
180
- memcmp: {
181
- offset: USER_STATS_REFERRER_STATUS_OFFSET,
182
- bytes: bs58.encode(Buffer.from(Uint8Array.from([3]))),
183
- },
184
- };
185
- }
186
-
187
- /**
188
- * Builds a `getProgramAccounts` memcmp filter matching the 8-byte Anchor discriminator of the
189
- * `SignedMsgUserOrders` account type at offset 0. Use to fetch all swift/signed-message order
190
- * accounts.
191
- * @returns A memcmp filter for `SignedMsgUserOrders` accounts.
192
- */
193
- export function getSignedMsgUserOrdersFilter(): MemcmpFilter {
194
- return {
195
- memcmp: {
196
- offset: 0,
197
- bytes: bs58.encode(
198
- BorshAccountsCoder.accountDiscriminator('SignedMsgUserOrders')
199
- ),
200
- },
201
- };
202
- }
203
-
204
- /**
205
- * Builds a `getProgramAccounts` memcmp filter matching the 8-byte Anchor discriminator of the
206
- * `PerpMarket` account type at offset 0. Use to fetch all perp market accounts.
207
- * @returns A memcmp filter for `PerpMarket` accounts.
208
- */
209
- export function getPerpMarketAccountsFilter(): MemcmpFilter {
210
- return {
211
- memcmp: {
212
- offset: 0,
213
- bytes: bs58.encode(BorshAccountsCoder.accountDiscriminator('PerpMarket')),
214
- },
215
- };
216
- }
217
- /**
218
- * Builds a `getProgramAccounts` memcmp filter matching the 8-byte Anchor discriminator of the
219
- * `SpotMarket` account type at offset 0. Use to fetch all spot market accounts.
220
- * @returns A memcmp filter for `SpotMarket` accounts.
221
- */
222
- export function getSpotMarketAccountsFilter(): MemcmpFilter {
223
- return {
224
- memcmp: {
225
- offset: 0,
226
- bytes: bs58.encode(BorshAccountsCoder.accountDiscriminator('SpotMarket')),
227
- },
228
- };
229
- }
230
-
231
- /**
232
- * Builds a `getProgramAccounts` memcmp filter matching the 8-byte Anchor discriminator of the
233
- * `RevenueShareEscrow` account type at offset 0. Use to fetch all revenue-share escrow accounts
234
- * (builder-fee approvals/referral state).
235
- * @returns A memcmp filter for `RevenueShareEscrow` accounts.
236
- */
237
- export function getRevenueShareEscrowFilter(): MemcmpFilter {
238
- return {
239
- memcmp: {
240
- offset: 0,
241
- bytes: bs58.encode(
242
- BorshAccountsCoder.accountDiscriminator('RevenueShareEscrow')
243
- ),
244
- },
245
- };
246
- }
247
-
248
- /**
249
- * Builds a `getProgramAccounts` memcmp filter matching the 8-byte Anchor discriminator of the
250
- * `Constituent` account type at offset 0. Use to fetch all LP-pool constituent accounts.
251
- * @returns A memcmp filter for `Constituent` accounts.
252
- */
253
- export function getConstituentFilter(): MemcmpFilter {
254
- return {
255
- memcmp: {
256
- offset: 0,
257
- bytes: bs58.encode(
258
- BorshAccountsCoder.accountDiscriminator('Constituent')
259
- ),
260
- },
261
- };
262
- }
263
-
264
- /**
265
- * Builds a memcmp filter matching `Constituent` accounts belonging to a specific LP pool, by
266
- * comparing the `lpPool` pubkey field (32 bytes, offset 72) against `lpPoolPublicKey`.
267
- * @param lpPoolPublicKey - The `LpPool` account's pubkey to match constituents against.
268
- * @returns A memcmp filter for `Constituent` accounts of the given LP pool.
269
- */
270
- export function getConstituentLpPoolFilter(
271
- lpPoolPublicKey: PublicKey
272
- ): MemcmpFilter {
273
- return {
274
- memcmp: {
275
- offset: 72,
276
- bytes: lpPoolPublicKey.toBase58(),
277
- },
278
- };
279
- }
@@ -1,41 +0,0 @@
1
- import { OracleClient } from './types';
2
- import { OracleSource } from '../types';
3
- import { getOracleClient } from '../factory/oracleClient';
4
- import { Connection } from '@solana/web3.js';
5
- import { VelocityProgram } from '../config';
6
-
7
- /**
8
- * Caches one `OracleClient` instance per oracle *source kind* (not per account), so repeated
9
- * lookups for the same `OracleSource` variant (e.g. every `pyth1KPull` market) reuse a single
10
- * adapter instead of constructing a new one each time.
11
- */
12
- export class OracleClientCache {
13
- cache = new Map<string, OracleClient>();
14
- public constructor() {}
15
-
16
- /**
17
- * Returns the cached `OracleClient` for `oracleSource`'s variant key, constructing and caching
18
- * one via `getOracleClient` on first use.
19
- * @param oracleSource - Oracle source variant (its top-level key, e.g. `"pyth"`, is the cache key —
20
- * note this means all sources sharing a variant name share one client instance regardless of any
21
- * other fields on the variant).
22
- * @param connection - RPC connection passed through to the client on construction.
23
- * @param program - Velocity Anchor program, used by clients that decode via the program's IDL coder.
24
- * @returns The `OracleClient` for this source variant.
25
- * @throws Error (via `getOracleClient`) if `oracleSource` is not a recognized variant.
26
- */
27
- public get(
28
- oracleSource: OracleSource,
29
- connection: Connection,
30
- program: VelocityProgram
31
- ) {
32
- const key = Object.keys(oracleSource)[0];
33
- if (this.cache.has(key)) {
34
- return this.cache.get(key);
35
- }
36
-
37
- const client = getOracleClient(oracleSource, connection, program);
38
- this.cache.set(key, client);
39
- return client;
40
- }
41
- }
@@ -1,99 +0,0 @@
1
- import { PublicKey } from '@solana/web3.js';
2
- import { OracleSource, OracleSourceNum } from '../types';
3
-
4
- /**
5
- * Maps an `OracleSource` enum-object (e.g. `{ pyth: {} }`) to its stable numeric encoding
6
- * (`OracleSourceNum`) used as part of an oracle id string. This encoding is SDK-internal — it
7
- * is not the on-chain Borsh discriminant (see `OracleSourceNum`).
8
- * @param source - The oracle source variant.
9
- * @returns The corresponding `OracleSourceNum` value.
10
- * @throws Error if `source` doesn't match any known variant.
11
- */
12
- export function getOracleSourceNum(source: OracleSource): number {
13
- if ('pyth' in source) return OracleSourceNum.PYTH;
14
- if ('pyth1K' in source) return OracleSourceNum.PYTH_1K;
15
- if ('pyth1M' in source) return OracleSourceNum.PYTH_1M;
16
- if ('pythPull' in source) return OracleSourceNum.PYTH_PULL;
17
- if ('pyth1KPull' in source) return OracleSourceNum.PYTH_1K_PULL;
18
- if ('pyth1MPull' in source) return OracleSourceNum.PYTH_1M_PULL;
19
- if ('deprecatedSwitchboard' in source)
20
- return OracleSourceNum.DEPRECATED_SWITCHBOARD;
21
- if ('quoteAsset' in source) return OracleSourceNum.QUOTE_ASSET;
22
- if ('pythStableCoin' in source) return OracleSourceNum.PYTH_STABLE_COIN;
23
- if ('pythStableCoinPull' in source)
24
- return OracleSourceNum.PYTH_STABLE_COIN_PULL;
25
- if ('prelaunch' in source) return OracleSourceNum.PRELAUNCH;
26
- if ('deprecatedSwitchboardOnDemand' in source)
27
- return OracleSourceNum.DEPRECATED_SWITCHBOARD_ON_DEMAND;
28
- if ('pythLazer' in source) return OracleSourceNum.PYTH_LAZER;
29
- if ('pythLazer1K' in source) return OracleSourceNum.PYTH_LAZER_1K;
30
- if ('pythLazer1M' in source) return OracleSourceNum.PYTH_LAZER_1M;
31
- if ('pythLazerStableCoin' in source)
32
- return OracleSourceNum.PYTH_LAZER_STABLE_COIN;
33
- throw new Error('Invalid oracle source');
34
- }
35
-
36
- /**
37
- * Inverse of `getOracleSourceNum`: maps a numeric `OracleSourceNum` back to its `OracleSource`
38
- * enum-object.
39
- * @param sourceNum - Numeric oracle source encoding.
40
- * @returns The corresponding `OracleSource` variant.
41
- * @throws Error if `sourceNum` doesn't match any known `OracleSourceNum` value.
42
- */
43
- export function getOracleSourceFromNum(sourceNum: number): OracleSource {
44
- if (sourceNum === OracleSourceNum.PYTH) return 'pyth';
45
- if (sourceNum === OracleSourceNum.PYTH_1K) return 'pyth1K';
46
- if (sourceNum === OracleSourceNum.PYTH_1M) return 'pyth1M';
47
- if (sourceNum === OracleSourceNum.PYTH_PULL) return 'pythPull';
48
- if (sourceNum === OracleSourceNum.PYTH_1K_PULL) return 'pyth1KPull';
49
- if (sourceNum === OracleSourceNum.PYTH_1M_PULL) return 'pyth1MPull';
50
- if (sourceNum === OracleSourceNum.DEPRECATED_SWITCHBOARD)
51
- return 'deprecatedSwitchboard';
52
- if (sourceNum === OracleSourceNum.QUOTE_ASSET) return 'quoteAsset';
53
- if (sourceNum === OracleSourceNum.PYTH_STABLE_COIN) return 'pythStableCoin';
54
- if (sourceNum === OracleSourceNum.PYTH_STABLE_COIN_PULL)
55
- return 'pythStableCoinPull';
56
- if (sourceNum === OracleSourceNum.PRELAUNCH) return 'prelaunch';
57
- if (sourceNum === OracleSourceNum.DEPRECATED_SWITCHBOARD_ON_DEMAND)
58
- return 'deprecatedSwitchboardOnDemand';
59
- if (sourceNum === OracleSourceNum.PYTH_LAZER) return 'pythLazer';
60
- if (sourceNum === OracleSourceNum.PYTH_LAZER_1K) return 'pythLazer1K';
61
- if (sourceNum === OracleSourceNum.PYTH_LAZER_1M) return 'pythLazer1M';
62
- if (sourceNum === OracleSourceNum.PYTH_LAZER_STABLE_COIN)
63
- return 'pythLazerStableCoin';
64
- throw new Error('Invalid oracle source');
65
- }
66
-
67
- /**
68
- * Builds a stable string id for an oracle account, uniquely identifying it by both its address
69
- * and the source/decoding scheme to use — the same pubkey can be interpreted under different
70
- * `OracleSource`s (e.g. `pyth` vs `pyth1K`) with different results, so the pubkey alone is not a
71
- * safe cache/map key.
72
- * @param publicKey - The oracle account's address.
73
- * @param source - The oracle source variant to decode it as.
74
- * @returns A string of the form `"<base58 pubkey>-<OracleSourceNum>"`.
75
- */
76
- export function getOracleId(
77
- publicKey: PublicKey,
78
- source: OracleSource
79
- ): string {
80
- return `${publicKey.toBase58()}-${getOracleSourceNum(source)}`;
81
- }
82
-
83
- /**
84
- * Inverse of `getOracleId`: parses an oracle id string back into its pubkey and `OracleSource`.
85
- * @param oracleId - An id string previously produced by `getOracleId`.
86
- * @returns The decoded `publicKey` and `source`.
87
- * @throws Error if the encoded source number doesn't match any known `OracleSourceNum` value, or
88
- * `PublicKey` construction fails on a malformed id.
89
- */
90
- export function getPublicKeyAndSourceFromOracleId(oracleId: string): {
91
- publicKey: PublicKey;
92
- source: OracleSource;
93
- } {
94
- const [publicKey, source] = oracleId.split('-');
95
- return {
96
- publicKey: new PublicKey(publicKey),
97
- source: getOracleSourceFromNum(parseInt(source)),
98
- };
99
- }
@@ -1,63 +0,0 @@
1
- import { Connection, PublicKey } from '@solana/web3.js';
2
- import { OracleClient, OraclePriceData } from './types';
3
- import { VelocityProgram } from '../config';
4
- import { PrelaunchOracle } from '../types';
5
- import { getOracleAccountDataOrThrow } from './utils';
6
-
7
- /**
8
- * `OracleClient` for the `PrelaunchOracle` account type — a synthetic, program-managed "oracle"
9
- * used for perp markets that have not yet listed on a real price feed. Its price is admin/keeper
10
- * set (via `updatePrelaunchOracleParams`) rather than fed by an external network.
11
- */
12
- export class PrelaunchOracleClient implements OracleClient {
13
- private connection: Connection;
14
- private program: VelocityProgram;
15
-
16
- public constructor(connection: Connection, program: VelocityProgram) {
17
- this.connection = connection;
18
- this.program = program;
19
- }
20
-
21
- /**
22
- * Fetches and decodes a `PrelaunchOracle` account's current price data.
23
- * @param pricePublicKey - The `PrelaunchOracle` account's address (see `getPrelaunchOraclePublicKey`).
24
- * @returns The decoded price data.
25
- * @throws Error if the account does not exist.
26
- */
27
- public async getOraclePriceData(
28
- pricePublicKey: PublicKey
29
- ): Promise<OraclePriceData> {
30
- const data = await getOracleAccountDataOrThrow(
31
- this.connection,
32
- pricePublicKey,
33
- 'Prelaunch oracle'
34
- );
35
- return this.getOraclePriceDataFromBuffer(data);
36
- }
37
-
38
- /**
39
- * Decodes raw `PrelaunchOracle` account bytes into normalized `OraclePriceData`. Note `slot` is
40
- * populated from `ammLastUpdateSlot` (the last time the paired AMM used this price), not a
41
- * slot recorded by the oracle account itself, and `hasSufficientNumberOfDataPoints` is always
42
- * `true` since there is no publisher-count concept for this source.
43
- * @param buffer - Raw `PrelaunchOracle` account data.
44
- * @returns Price (`price`), confidence (`confidence`, both PRICE_PRECISION 1e6), and the
45
- * prelaunch-only upper bound (`maxPrice`, PRICE_PRECISION 1e6).
46
- */
47
- public getOraclePriceDataFromBuffer(buffer: Buffer): OraclePriceData {
48
- const prelaunchOracle = (
49
- this.program.account as any
50
- ).prelaunchOracle.coder.accounts.decodeUnchecked(
51
- 'prelaunchOracle',
52
- buffer
53
- ) as PrelaunchOracle;
54
-
55
- return {
56
- price: prelaunchOracle.price,
57
- slot: prelaunchOracle.ammLastUpdateSlot,
58
- confidence: prelaunchOracle.confidence,
59
- hasSufficientNumberOfDataPoints: true,
60
- maxPrice: prelaunchOracle.maxPrice,
61
- };
62
- }
63
- }