@velocity-exchange/sdk 0.4.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (325) hide show
  1. package/README.md +3 -3
  2. package/lib/browser/adminClient.d.ts +52 -0
  3. package/lib/browser/adminClient.js +97 -0
  4. package/lib/browser/config.js +6 -7
  5. package/lib/browser/constants/numericConstants.d.ts +1 -1
  6. package/lib/browser/constants/numericConstants.js +1 -1
  7. package/lib/browser/decode/user.js +5 -1
  8. package/lib/browser/idl/velocity.d.ts +191 -15
  9. package/lib/browser/idl/velocity.json +192 -16
  10. package/lib/browser/orderSubscriber/OrderSubscriber.d.ts +1 -0
  11. package/lib/browser/orderSubscriber/OrderSubscriber.js +10 -4
  12. package/lib/browser/pyth/pythLazerSubscriber.js +37 -27
  13. package/lib/browser/types.d.ts +6 -0
  14. package/lib/browser/user.d.ts +20 -3
  15. package/lib/browser/user.js +52 -4
  16. package/lib/browser/velocityClient.d.ts +46 -10
  17. package/lib/browser/velocityClient.js +107 -35
  18. package/lib/node/adminClient.d.ts +52 -0
  19. package/lib/node/adminClient.d.ts.map +1 -1
  20. package/lib/node/adminClient.js +97 -0
  21. package/lib/node/config.d.ts.map +1 -1
  22. package/lib/node/config.js +6 -7
  23. package/lib/node/constants/numericConstants.d.ts +1 -1
  24. package/lib/node/constants/numericConstants.d.ts.map +1 -1
  25. package/lib/node/constants/numericConstants.js +1 -1
  26. package/lib/node/decode/user.d.ts.map +1 -1
  27. package/lib/node/decode/user.js +5 -1
  28. package/lib/node/idl/velocity.d.ts +191 -15
  29. package/lib/node/idl/velocity.d.ts.map +1 -1
  30. package/lib/node/idl/velocity.json +192 -16
  31. package/lib/node/orderSubscriber/OrderSubscriber.d.ts +1 -0
  32. package/lib/node/orderSubscriber/OrderSubscriber.d.ts.map +1 -1
  33. package/lib/node/orderSubscriber/OrderSubscriber.js +10 -4
  34. package/lib/node/pyth/pythLazerSubscriber.d.ts.map +1 -1
  35. package/lib/node/pyth/pythLazerSubscriber.js +37 -27
  36. package/lib/node/types.d.ts +6 -0
  37. package/lib/node/types.d.ts.map +1 -1
  38. package/lib/node/user.d.ts +20 -3
  39. package/lib/node/user.d.ts.map +1 -1
  40. package/lib/node/user.js +52 -4
  41. package/lib/node/velocityClient.d.ts +46 -10
  42. package/lib/node/velocityClient.d.ts.map +1 -1
  43. package/lib/node/velocityClient.js +107 -35
  44. package/package.json +7 -3
  45. package/.prettierignore +0 -1
  46. package/CHANGELOG.md +0 -132
  47. package/build-browser.js +0 -58
  48. package/bunfig.toml +0 -3
  49. package/esbuild-shims.js +0 -12
  50. package/scripts/deposit-isolated-positions.ts +0 -110
  51. package/scripts/find-flagged-users.ts +0 -213
  52. package/scripts/grpc-client-test-comparison.ts +0 -372
  53. package/scripts/grpc-multiuser-client-test-comparison.ts +0 -158
  54. package/scripts/postbuild.js +0 -95
  55. package/scripts/single-grpc-client-test.ts +0 -284
  56. package/scripts/withdraw-isolated-positions.ts +0 -174
  57. package/src/accounts/README_WebSocketAccountSubscriberV2.md +0 -95
  58. package/src/accounts/README_WebSocketProgramAccountSubscriberV2.md +0 -135
  59. package/src/accounts/basicUserAccountSubscriber.ts +0 -79
  60. package/src/accounts/basicUserStatsAccountSubscriber.ts +0 -87
  61. package/src/accounts/bulkAccountLoader.ts +0 -358
  62. package/src/accounts/bulkUserStatsSubscription.ts +0 -40
  63. package/src/accounts/bulkUserSubscription.ts +0 -39
  64. package/src/accounts/customizedCadenceBulkAccountLoader.ts +0 -250
  65. package/src/accounts/fetch.ts +0 -200
  66. package/src/accounts/grpcAccountSubscriber.ts +0 -225
  67. package/src/accounts/grpcInsuranceFundStakeAccountSubscriber.ts +0 -73
  68. package/src/accounts/grpcMultiAccountSubscriber.ts +0 -566
  69. package/src/accounts/grpcMultiUserAccountSubscriber.ts +0 -328
  70. package/src/accounts/grpcProgramAccountSubscriber.ts +0 -264
  71. package/src/accounts/grpcUserAccountSubscriber.ts +0 -63
  72. package/src/accounts/grpcUserStatsAccountSubscriber.ts +0 -65
  73. package/src/accounts/grpcVelocityClientAccountSubscriber.ts +0 -257
  74. package/src/accounts/grpcVelocityClientAccountSubscriberV2.ts +0 -941
  75. package/src/accounts/laserProgramAccountSubscriber.ts +0 -266
  76. package/src/accounts/oneShotUserAccountSubscriber.ts +0 -88
  77. package/src/accounts/oneShotUserStatsAccountSubscriber.ts +0 -94
  78. package/src/accounts/pollingInsuranceFundStakeAccountSubscriber.ts +0 -223
  79. package/src/accounts/pollingOracleAccountSubscriber.ts +0 -151
  80. package/src/accounts/pollingTokenAccountSubscriber.ts +0 -147
  81. package/src/accounts/pollingUserAccountSubscriber.ts +0 -198
  82. package/src/accounts/pollingUserStatsAccountSubscriber.ts +0 -180
  83. package/src/accounts/pollingVelocityClientAccountSubscriber.ts +0 -774
  84. package/src/accounts/testBulkAccountLoader.ts +0 -59
  85. package/src/accounts/types.ts +0 -428
  86. package/src/accounts/utils.ts +0 -90
  87. package/src/accounts/webSocketAccountSubscriber.ts +0 -304
  88. package/src/accounts/webSocketAccountSubscriberV2.ts +0 -536
  89. package/src/accounts/webSocketInsuranceFundStakeAccountSubscriber.ts +0 -171
  90. package/src/accounts/webSocketProgramAccountSubscriber.ts +0 -244
  91. package/src/accounts/webSocketProgramAccountSubscriberV2.ts +0 -1048
  92. package/src/accounts/webSocketProgramAccountsSubscriberV2.ts +0 -1042
  93. package/src/accounts/webSocketUserAccountSubscriber.ts +0 -139
  94. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +0 -131
  95. package/src/accounts/webSocketVelocityClientAccountSubscriber.ts +0 -865
  96. package/src/accounts/webSocketVelocityClientAccountSubscriberV2.ts +0 -897
  97. package/src/accounts/websocketProgramUserAccountSubscriber.ts +0 -127
  98. package/src/addresses/marketAddresses.ts +0 -28
  99. package/src/addresses/pda.ts +0 -620
  100. package/src/adminClient.ts +0 -8136
  101. package/src/assert/assert.ts +0 -5
  102. package/src/auctionSubscriber/auctionSubscriber.ts +0 -86
  103. package/src/auctionSubscriber/auctionSubscriberGrpc.ts +0 -99
  104. package/src/auctionSubscriber/index.ts +0 -9
  105. package/src/auctionSubscriber/types.ts +0 -30
  106. package/src/bankrun/bankrunConnection.ts +0 -630
  107. package/src/blockhashSubscriber/BlockhashSubscriber.ts +0 -160
  108. package/src/blockhashSubscriber/index.ts +0 -6
  109. package/src/blockhashSubscriber/types.ts +0 -13
  110. package/src/clock/clockSubscriber.ts +0 -146
  111. package/src/config.ts +0 -312
  112. package/src/constants/index.ts +0 -9
  113. package/src/constants/numericConstants.ts +0 -194
  114. package/src/constants/perpMarkets.ts +0 -127
  115. package/src/constants/spotMarkets.ts +0 -104
  116. package/src/constants/txConstants.ts +0 -2
  117. package/src/constituentMap/constituentMap.ts +0 -305
  118. package/src/constituentMap/pollingConstituentAccountSubscriber.ts +0 -99
  119. package/src/constituentMap/webSocketConstituentAccountSubscriber.ts +0 -121
  120. package/src/core/VelocityCore.ts +0 -606
  121. package/src/core/index.ts +0 -12
  122. package/src/core/instructions/deposit.ts +0 -64
  123. package/src/core/instructions/fill.ts +0 -51
  124. package/src/core/instructions/funding.ts +0 -33
  125. package/src/core/instructions/liquidation.ts +0 -55
  126. package/src/core/instructions/orders.ts +0 -84
  127. package/src/core/instructions/perpOrders.ts +0 -312
  128. package/src/core/instructions/settlement.ts +0 -40
  129. package/src/core/instructions/trigger.ts +0 -41
  130. package/src/core/instructions/withdraw.ts +0 -65
  131. package/src/core/remainingAccounts.ts +0 -320
  132. package/src/core/signedMsg.ts +0 -109
  133. package/src/decode/customCoder.ts +0 -148
  134. package/src/decode/user.ts +0 -401
  135. package/src/dlob/DLOB.ts +0 -2793
  136. package/src/dlob/DLOBNode.ts +0 -305
  137. package/src/dlob/DLOBSubscriber.ts +0 -269
  138. package/src/dlob/NodeList.ts +0 -244
  139. package/src/dlob/orderBookLevels.ts +0 -695
  140. package/src/dlob/types.ts +0 -37
  141. package/src/events/eventList.ts +0 -114
  142. package/src/events/eventSubscriber.ts +0 -521
  143. package/src/events/eventsServerLogProvider.ts +0 -189
  144. package/src/events/fetchLogs.ts +0 -219
  145. package/src/events/parse.ts +0 -271
  146. package/src/events/pollingLogProvider.ts +0 -113
  147. package/src/events/sort.ts +0 -51
  148. package/src/events/txEventCache.ts +0 -92
  149. package/src/events/types.ts +0 -337
  150. package/src/events/webSocketLogProvider.ts +0 -152
  151. package/src/factory/bigNum.ts +0 -709
  152. package/src/factory/oracleClient.ts +0 -73
  153. package/src/idl/pyth.json +0 -142
  154. package/src/idl/pyth.ts +0 -97
  155. package/src/idl/pyth_solana_receiver.json +0 -628
  156. package/src/idl/token_faucet.json +0 -229
  157. package/src/idl/token_faucet.ts +0 -197
  158. package/src/idl/velocity.json +0 -23974
  159. package/src/idl/velocity.ts +0 -23980
  160. package/src/index.ts +0 -150
  161. package/src/indicative-quotes/indicativeQuotesSender.ts +0 -233
  162. package/src/isomorphic/README.md +0 -19
  163. package/src/isomorphic/anchor.browser.ts +0 -44
  164. package/src/isomorphic/anchor.node.ts +0 -1
  165. package/src/isomorphic/anchor.ts +0 -1
  166. package/src/isomorphic/anchor29.browser.ts +0 -24
  167. package/src/isomorphic/anchor29.node.ts +0 -1
  168. package/src/isomorphic/anchor29.ts +0 -1
  169. package/src/isomorphic/grpc.browser.ts +0 -4
  170. package/src/isomorphic/grpc.node.ts +0 -130
  171. package/src/isomorphic/grpc.ts +0 -1
  172. package/src/jupiter/jupiterClient.ts +0 -502
  173. package/src/keypair.ts +0 -32
  174. package/src/margin/README.md +0 -138
  175. package/src/marginCalculation.ts +0 -407
  176. package/src/marinade/idl/idl.json +0 -1962
  177. package/src/marinade/index.ts +0 -73
  178. package/src/marinade/types.ts +0 -3925
  179. package/src/math/amm.ts +0 -1758
  180. package/src/math/auction.ts +0 -480
  181. package/src/math/bankruptcy.ts +0 -138
  182. package/src/math/builder.ts +0 -130
  183. package/src/math/conversion.ts +0 -45
  184. package/src/math/exchangeStatus.ts +0 -261
  185. package/src/math/funding.ts +0 -498
  186. package/src/math/insurance.ts +0 -171
  187. package/src/math/liquidation.ts +0 -433
  188. package/src/math/margin.ts +0 -327
  189. package/src/math/market.ts +0 -487
  190. package/src/math/oracles.ts +0 -477
  191. package/src/math/orders.ts +0 -500
  192. package/src/math/position.ts +0 -381
  193. package/src/math/repeg.ts +0 -223
  194. package/src/math/spotBalance.ts +0 -996
  195. package/src/math/spotMarket.ts +0 -115
  196. package/src/math/spotPosition.ts +0 -263
  197. package/src/math/state.ts +0 -71
  198. package/src/math/superStake.ts +0 -602
  199. package/src/math/tiers.ts +0 -73
  200. package/src/math/trade.ts +0 -879
  201. package/src/math/utils.ts +0 -183
  202. package/src/memcmp.ts +0 -279
  203. package/src/oracles/oracleClientCache.ts +0 -41
  204. package/src/oracles/oracleId.ts +0 -99
  205. package/src/oracles/prelaunchOracleClient.ts +0 -63
  206. package/src/oracles/pythClient.ts +0 -125
  207. package/src/oracles/pythLazerClient.ts +0 -141
  208. package/src/oracles/quoteAssetOracleClient.ts +0 -43
  209. package/src/oracles/strictOraclePrice.ts +0 -40
  210. package/src/oracles/types.ts +0 -82
  211. package/src/oracles/utils.ts +0 -45
  212. package/src/orderParams.ts +0 -117
  213. package/src/orderSubscriber/OrderSubscriber.ts +0 -378
  214. package/src/orderSubscriber/PollingSubscription.ts +0 -50
  215. package/src/orderSubscriber/WebsocketSubscription.ts +0 -137
  216. package/src/orderSubscriber/grpcSubscription.ts +0 -155
  217. package/src/orderSubscriber/index.ts +0 -7
  218. package/src/orderSubscriber/types.ts +0 -64
  219. package/src/priorityFee/averageOverSlotsStrategy.ts +0 -17
  220. package/src/priorityFee/averageStrategy.ts +0 -13
  221. package/src/priorityFee/ewmaStrategy.ts +0 -51
  222. package/src/priorityFee/heliusPriorityFeeMethod.ts +0 -68
  223. package/src/priorityFee/index.ts +0 -16
  224. package/src/priorityFee/maxOverSlotsStrategy.ts +0 -18
  225. package/src/priorityFee/maxStrategy.ts +0 -8
  226. package/src/priorityFee/priorityFeeSubscriber.ts +0 -328
  227. package/src/priorityFee/priorityFeeSubscriberMap.ts +0 -134
  228. package/src/priorityFee/solanaPriorityFeeMethod.ts +0 -46
  229. package/src/priorityFee/types.ts +0 -82
  230. package/src/priorityFee/velocityPriorityFeeMethod.ts +0 -53
  231. package/src/pyth/constants.ts +0 -9
  232. package/src/pyth/index.ts +0 -15
  233. package/src/pyth/pythLazerSubscriber.ts +0 -365
  234. package/src/pyth/types.ts +0 -4451
  235. package/src/pyth/utils.ts +0 -13
  236. package/src/slot/SlotSubscriber.ts +0 -126
  237. package/src/slot/SlothashSubscriber.ts +0 -163
  238. package/src/swap/UnifiedSwapClient.ts +0 -315
  239. package/src/swift/grpcSignedMsgUserAccountSubscriber.ts +0 -81
  240. package/src/swift/index.ts +0 -10
  241. package/src/swift/signedMsgUserAccountSubscriber.ts +0 -251
  242. package/src/swift/swiftOrderSubscriber.ts +0 -351
  243. package/src/testClient.ts +0 -42
  244. package/src/titan/titanClient.ts +0 -438
  245. package/src/token/index.ts +0 -13
  246. package/src/tokenFaucet.ts +0 -296
  247. package/src/tx/baseTxSender.ts +0 -651
  248. package/src/tx/blockhashFetcher/baseBlockhashFetcher.ts +0 -31
  249. package/src/tx/blockhashFetcher/cachedBlockhashFetcher.ts +0 -105
  250. package/src/tx/blockhashFetcher/types.ts +0 -9
  251. package/src/tx/fastSingleTxSender.ts +0 -200
  252. package/src/tx/forwardOnlyTxSender.ts +0 -193
  253. package/src/tx/priorityFeeCalculator.ts +0 -117
  254. package/src/tx/reportTransactionError.ts +0 -176
  255. package/src/tx/retryTxSender.ts +0 -177
  256. package/src/tx/txHandler.ts +0 -1009
  257. package/src/tx/txParamProcessor.ts +0 -225
  258. package/src/tx/types.ts +0 -117
  259. package/src/tx/utils.ts +0 -133
  260. package/src/tx/whileValidTxSender.ts +0 -377
  261. package/src/types.ts +0 -2575
  262. package/src/user.ts +0 -5316
  263. package/src/userConfig.ts +0 -38
  264. package/src/userMap/PollingSubscription.ts +0 -61
  265. package/src/userMap/WebsocketSubscription.ts +0 -93
  266. package/src/userMap/grpcSubscription.ts +0 -93
  267. package/src/userMap/referrerMap.ts +0 -360
  268. package/src/userMap/revenueShareEscrowMap.ts +0 -342
  269. package/src/userMap/userMap.ts +0 -784
  270. package/src/userMap/userMapConfig.ts +0 -82
  271. package/src/userMap/userStatsMap.ts +0 -393
  272. package/src/userName.ts +0 -37
  273. package/src/userStats.ts +0 -159
  274. package/src/userStatsConfig.ts +0 -35
  275. package/src/util/TransactionConfirmationManager.ts +0 -333
  276. package/src/util/chainClock.ts +0 -65
  277. package/src/util/computeUnits.ts +0 -101
  278. package/src/util/digest.ts +0 -33
  279. package/src/util/ed25519Utils.ts +0 -95
  280. package/src/util/promiseTimeout.ts +0 -23
  281. package/src/velocityClient.ts +0 -14802
  282. package/src/velocityClientConfig.ts +0 -119
  283. package/src/wallet.ts +0 -91
  284. package/tests/VelocityCore/builder_escrow.test.ts +0 -121
  285. package/tests/VelocityCore/decode.test.ts +0 -16
  286. package/tests/VelocityCore/fill_trigger.test.ts +0 -73
  287. package/tests/VelocityCore/instructions.test.ts +0 -46
  288. package/tests/VelocityCore/pdas.test.ts +0 -30
  289. package/tests/VelocityCore/perp_orders.test.ts +0 -205
  290. package/tests/VelocityCore/remainingAccounts.test.ts +0 -72
  291. package/tests/VelocityCore/settlement_liquidation.test.ts +0 -69
  292. package/tests/accounts/customizedCadenceBulkAccountLoader.test.ts +0 -211
  293. package/tests/amm/test.ts +0 -2402
  294. package/tests/auctions/test.ts +0 -81
  295. package/tests/bn/test.ts +0 -355
  296. package/tests/builder/builderFee.test.ts +0 -42
  297. package/tests/ci/verifyConstants.ts +0 -393
  298. package/tests/decode/test.ts +0 -262
  299. package/tests/decode/userAccountBufferStrings.ts +0 -102
  300. package/tests/dlob/helpers.ts +0 -748
  301. package/tests/dlob/test.ts +0 -6969
  302. package/tests/dlob/tickSizeStandardization.ts +0 -545
  303. package/tests/events/parseLogsForCuUsage.ts +0 -139
  304. package/tests/exchangeStatus/test.ts +0 -45
  305. package/tests/insurance/test.ts +0 -40
  306. package/tests/liquidation/test.ts +0 -125
  307. package/tests/oracles/mmOracleGate.test.ts +0 -379
  308. package/tests/oracles/pythPegSnap.test.ts +0 -76
  309. package/tests/sdkParity/enumParity.test.ts +0 -84
  310. package/tests/sdkParity/marginCategoryFill.test.ts +0 -143
  311. package/tests/sdkParity/memcmpOffsets.test.ts +0 -139
  312. package/tests/spot/test.ts +0 -281
  313. package/tests/tx/TransactionConfirmationManager.test.ts +0 -312
  314. package/tests/tx/cachedBlockhashFetcher.test.ts +0 -96
  315. package/tests/tx/priorityFeeCalculator.ts +0 -77
  316. package/tests/tx/priorityFeeStrategy.ts +0 -95
  317. package/tests/user/bankruptcy.ts +0 -165
  318. package/tests/user/feeAndWithdrawLimits.ts +0 -284
  319. package/tests/user/getMarginCalculation.ts +0 -586
  320. package/tests/user/helpers.ts +0 -184
  321. package/tests/user/liquidations.ts +0 -129
  322. package/tests/user/marginCalculations.test.ts +0 -321
  323. package/tests/user/test.ts +0 -833
  324. package/tsconfig.browser.json +0 -18
  325. package/tsconfig.json +0 -36
package/src/types.ts DELETED
@@ -1,2575 +0,0 @@
1
- /**
2
- * Shared TypeScript types for the Velocity SDK.
3
- *
4
- * Contains TypeScript mirrors of all on-chain account structs (UserAccount, PerpMarketAccount,
5
- * SpotMarketAccount, StateAccount, OracleData, etc.), instruction parameter types (OrderParams,
6
- * ModifyOrderParams), enums (MarketType, OrderType, PositionDirection, OracleSource), and
7
- * precision constants used throughout the SDK.
8
- *
9
- * The authoritative layout source is `sdk/src/idl/velocity.json` (generated from the program).
10
- * Do not edit struct shapes here without a corresponding on-chain change.
11
- */
12
- import {
13
- Keypair,
14
- PublicKey,
15
- Transaction,
16
- TransactionVersion,
17
- VersionedTransaction,
18
- } from '@solana/web3.js';
19
- import { BN } from './isomorphic/anchor';
20
- import { ZERO } from './constants/numericConstants';
21
-
22
- /** Utility type that maps every key of `A` to the same-shaped record with all values replaced by type `B`. */
23
- export type MappedRecord<A extends Record<string, unknown>, B> = {
24
- [K in keyof A]: B;
25
- };
26
-
27
- // # Utility Types / Enums / Constants
28
-
29
- /**
30
- * Bitmask mirror of `State.exchangeStatus`. Each non-zero member pauses one class of
31
- * instructions protocol-wide; multiple bits may be set simultaneously (e.g. deposits and
32
- * withdrawals paused together). `PAUSED` (255) is the "pause everything" value, not a flag
33
- * combinable with the others. Only `coldAdmin`/`warmAdmin` may clear bits; `pauseAdmin` may
34
- * only set them (see `StateAccount.pauseAdmin`).
35
- */
36
- export enum ExchangeStatus {
37
- ACTIVE = 0,
38
- DEPOSIT_PAUSED = 1,
39
- WITHDRAW_PAUSED = 2,
40
- AMM_PAUSED = 4,
41
- FILL_PAUSED = 8,
42
- LIQ_PAUSED = 16,
43
- FUNDING_PAUSED = 32,
44
- SETTLE_PNL_PAUSED = 64,
45
- AMM_IMMEDIATE_FILL_PAUSED = 128,
46
- PAUSED = 255,
47
- }
48
-
49
- /**
50
- * Mirror of the Rust `SolvencyStatus` bitflag (`StateAccount.solvencyStatus`). Gates internal
51
- * solvency-repair flows (bankruptcy / pnl-deficit resolution) independently of
52
- * `ExchangeStatus.WITHDRAW_PAUSED`, so withdrawals can be halted while repair keeps running, or
53
- * repair can be frozen on its own (e.g. when an oracle is suspect) without touching withdrawals.
54
- * `ACTIVE` (0) means repair is allowed.
55
- */
56
- export enum SolvencyStatus {
57
- ACTIVE = 0,
58
- SOLVENCY_REPAIR_PAUSED = 1,
59
- }
60
-
61
- /** Bitmask mirror of `StateAccount.featureBitFlags`, gating protocol-wide optional features. */
62
- export enum FeatureBitFlags {
63
- MM_ORACLE_UPDATE = 1,
64
- MEDIAN_TRIGGER_PRICE = 2,
65
- BUILDER_CODES = 4,
66
- }
67
-
68
- /**
69
- * Mirrors the Rust `MarketStatus` enum on `PerpMarketAccount.status` / `SpotMarketAccount.status`.
70
- * Controls which operations a market allows: `INITIALIZED` (warm-up, fills paused), `ACTIVE` (all
71
- * operations allowed), `REDUCE_ONLY` (fills may only shrink a liability), `SETTLEMENT` (market has
72
- * a determined settlement price; positions must be settled), `DELISTED` (no participants remain).
73
- * Velocity's on-chain discriminants (`Initialized`=0, `Active`=1, `ReduceOnly`=2, `Settlement`=3,
74
- * `Delisted`=4) are **shifted down from upstream Drift's** (`ReduceOnly`=6, `Settlement`=7,
75
- * `Delisted`=8) after the deprecated `FundingPaused`/`AmmPaused`/`FillPaused`/`WithdrawPaused`
76
- * variants were removed — any decoder built against the old Drift discriminants will silently
77
- * misread these states.
78
- */
79
- export class MarketStatus {
80
- static readonly INITIALIZED = { initialized: {} };
81
- static readonly ACTIVE = { active: {} };
82
- static readonly REDUCE_ONLY = { reduceOnly: {} };
83
- static readonly SETTLEMENT = { settlement: {} };
84
- static readonly DELISTED = { delisted: {} };
85
- }
86
-
87
- /** Bitmask mirror of `PerpMarketAccount.pausedOperations`; each bit disables one perp-market operation. */
88
- export enum PerpOperation {
89
- UPDATE_FUNDING = 1,
90
- AMM_FILL = 2,
91
- FILL = 4,
92
- SETTLE_PNL = 8,
93
- SETTLE_PNL_WITH_POSITION = 16,
94
- LIQUIDATION = 32,
95
- AMM_IMMEDIATE_FILL = 64,
96
- SETTLE_REV_POOL = 128,
97
- }
98
-
99
- /** Bitmask mirror of `SpotMarketAccount.pausedOperations`; each bit disables one spot-market operation. */
100
- export enum SpotOperation {
101
- UPDATE_CUMULATIVE_INTEREST = 1,
102
- FILL = 2,
103
- DEPOSIT = 4,
104
- WITHDRAW = 8,
105
- LIQUIDATION = 16,
106
- }
107
-
108
- /** Bitmask mirror of `SpotMarketAccount.ifPausedOperations`; each bit disables one insurance-fund-stake operation. */
109
- export enum InsuranceFundOperation {
110
- INIT = 1,
111
- ADD = 2,
112
- REQUEST_REMOVE = 4,
113
- REMOVE = 8,
114
- }
115
-
116
- /**
117
- * Bitmask mirror of `UserAccount.status`. Multiple bits can be set at once (e.g. a bankrupt user
118
- * is also `BEING_LIQUIDATED`). `0` (unset) means active/normal. Bit `16` (was `PROTECTED_MAKER`)
119
- * is reserved and no longer assigned.
120
- */
121
- export enum UserStatus {
122
- BEING_LIQUIDATED = 1,
123
- BANKRUPT = 2,
124
- REDUCE_ONLY = 4,
125
- ADVANCED_LP = 8,
126
- // 16 reserved (was PROTECTED_MAKER)
127
- }
128
-
129
- /** Bitmask mirror of `UserAccount.specialUserStatus`. `VAMM_HEDGER` marks the account used by the protocol's own vAMM-hedging bot. */
130
- export enum SpecialUserStatus {
131
- VAMM_HEDGER = 1,
132
- }
133
-
134
- /** Bitmask mirror of `UserStatsAccount.pausedOperations`; each bit disables one per-user-stats update path. */
135
- export enum UserStatsPausedOperation {
136
- UPDATE_BID_ASK_TWAP = 1,
137
- AMM_ATOMIC_FILL = 2,
138
- AMM_ATOMIC_RISK_INCREASING_FILL = 4,
139
- }
140
-
141
- /** Bitmask mirror of `PerpMarketAccount.marketConfig`. `DISABLE_FORMULAIC_K_UPDATE` turns off the AMM's automatic `k` (liquidity depth) adjustments for that market. */
142
- export enum MarketConfigFlag {
143
- DISABLE_FORMULAIC_K_UPDATE = 1,
144
- }
145
-
146
- /** Margin-mode enum-class. Currently only `DEFAULT` (cross margin) exists; isolated margin is expressed per-position via `PositionFlag.IsolatedPosition`, not a distinct margin mode. */
147
- export class MarginMode {
148
- static readonly DEFAULT = { default: {} };
149
- }
150
-
151
- /**
152
- * Mirrors the on-chain `ContractType` on `PerpMarketAccount.contractType`. Only `PERPETUAL` is
153
- * live; `DEPRECATED_FUTURE` and `DEPRECATED_PREDICTION` are inert stubs kept for IDL/discriminant
154
- * compatibility and are never assigned to a market.
155
- */
156
- export class ContractType {
157
- static readonly PERPETUAL = { perpetual: {} };
158
- static readonly DEPRECATED_FUTURE = { deprecatedFuture: {} };
159
- static readonly DEPRECATED_PREDICTION = { deprecatedPrediction: {} };
160
- }
161
-
162
- /**
163
- * A perp market's speculativeness tier (`PerpMarketAccount.contractTier`). Determines how much of
164
- * the insurance fund the market may draw on during bankruptcy and the order markets are
165
- * liquidated in — `ISOLATED` markets receive no shared insurance coverage; `A` is safest.
166
- */
167
- export class ContractTier {
168
- static readonly A = { a: {} };
169
- static readonly B = { b: {} };
170
- static readonly C = { c: {} };
171
- static readonly SPECULATIVE = { speculative: {} };
172
- static readonly HIGHLY_SPECULATIVE = { highlySpeculative: {} };
173
- static readonly ISOLATED = { isolated: {} };
174
- }
175
-
176
- /**
177
- * A spot market's collateral-safety tier (`SpotMarketAccount.assetTier`). Determines whether a
178
- * deposit can be used as cross-margin collateral alongside other assets: `COLLATERAL` may back
179
- * any borrow, `PROTECTED`/`CROSS` have restrictions on being borrowed against, `ISOLATED` deposits
180
- * can't be combined with other borrows, and `UNLISTED` deposits count for nothing.
181
- */
182
- export class AssetTier {
183
- static readonly COLLATERAL = { collateral: {} };
184
- static readonly PROTECTED = { protected: {} };
185
- static readonly CROSS = { cross: {} };
186
- static readonly ISOLATED = { isolated: {} };
187
- static readonly UNLISTED = { unlisted: {} };
188
- }
189
-
190
- /** Bitmask mirror of `SpotMarketAccount.tokenProgramFlag`, recording which SPL token-program features the market's mint uses. */
191
- export enum TokenProgramFlag {
192
- Token2022 = 1,
193
- TransferHook = 2,
194
- }
195
-
196
- /** Direction of an LP-pool constituent swap (add liquidity vs remove liquidity). */
197
- export class SwapDirection {
198
- static readonly ADD = { add: {} };
199
- static readonly REMOVE = { remove: {} };
200
- }
201
-
202
- /** Whether a `SpotPosition`/`PoolBalance`'s scaled balance represents a deposit (positive token claim) or a borrow (liability). */
203
- export class SpotBalanceType {
204
- static readonly DEPOSIT = { deposit: {} };
205
- static readonly BORROW = { borrow: {} };
206
- }
207
-
208
- /** Long (bid) or short (ask) side of a perp/spot order or position. */
209
- export class PositionDirection {
210
- static readonly LONG = { long: {} };
211
- static readonly SHORT = { short: {} };
212
- }
213
-
214
- /** Direction of a `DepositRecord` / `LPBorrowLendDepositRecord` event: funds entering or leaving the protocol. */
215
- export class DepositDirection {
216
- static readonly DEPOSIT = { deposit: {} };
217
- static readonly WITHDRAW = { withdraw: {} };
218
- }
219
-
220
- /**
221
- * Mirrors the on-chain `OracleSource` enum, identifying which oracle provider/decoder to use for
222
- * a market's `oracle` account. The `1K`/`1M` suffixes scale the raw feed price by 1e3/1e6 (used
223
- * for low-priced assets like BONK). `DEPRECATED_SWITCHBOARD`/`DEPRECATED_SWITCHBOARD_ON_DEMAND`
224
- * are inert stubs — using them returns `InvalidOracle`. `Prelaunch` reads from a `PrelaunchOracle`
225
- * account instead of an external feed.
226
- */
227
- export class OracleSource {
228
- static readonly PYTH = { pyth: {} };
229
- static readonly PYTH_1K = { pyth1K: {} };
230
- static readonly PYTH_1M = { pyth1M: {} };
231
- static readonly PYTH_PULL = { pythPull: {} };
232
- static readonly PYTH_1K_PULL = { pyth1KPull: {} };
233
- static readonly PYTH_1M_PULL = { pyth1MPull: {} };
234
- static readonly DEPRECATED_SWITCHBOARD = { deprecatedSwitchboard: {} };
235
- static readonly QUOTE_ASSET = { quoteAsset: {} };
236
- static readonly PYTH_STABLE_COIN = { pythStableCoin: {} };
237
- static readonly PYTH_STABLE_COIN_PULL = { pythStableCoinPull: {} };
238
- static readonly Prelaunch = { prelaunch: {} };
239
- static readonly DEPRECATED_SWITCHBOARD_ON_DEMAND = {
240
- deprecatedSwitchboardOnDemand: {},
241
- };
242
- static readonly PYTH_LAZER = { pythLazer: {} };
243
- static readonly PYTH_LAZER_1K = { pythLazer1K: {} };
244
- static readonly PYTH_LAZER_1M = { pythLazer1M: {} };
245
- static readonly PYTH_LAZER_STABLE_COIN = { pythLazerStableCoin: {} };
246
- }
247
-
248
- /**
249
- * Stable SDK-internal numeric encoding of `OracleSource`, used only for oracle-id string
250
- * round-tripping (`getOracleSourceNum` ↔ `getOracleSourceFromNum` in `oracles/oracleId.ts`).
251
- * NOTE: these numbers are **not** the on-chain Borsh discriminants and are **not** in the
252
- * on-chain enum's declaration order — do not use them for raw memcmp filters against chain
253
- * data. They only need to be self-consistent within the SDK.
254
- */
255
- export class OracleSourceNum {
256
- static readonly PYTH = 0;
257
- static readonly PYTH_1K = 1;
258
- static readonly PYTH_1M = 2;
259
- static readonly PYTH_PULL = 3;
260
- static readonly PYTH_1K_PULL = 4;
261
- static readonly PYTH_1M_PULL = 5;
262
- static readonly DEPRECATED_SWITCHBOARD = 6;
263
- static readonly QUOTE_ASSET = 7;
264
- static readonly PYTH_STABLE_COIN = 8;
265
- static readonly PYTH_STABLE_COIN_PULL = 9;
266
- static readonly PRELAUNCH = 10;
267
- static readonly DEPRECATED_SWITCHBOARD_ON_DEMAND = 11;
268
- static readonly PYTH_LAZER = 12;
269
- static readonly PYTH_LAZER_1K = 13;
270
- static readonly PYTH_LAZER_1M = 14;
271
- static readonly PYTH_LAZER_STABLE_COIN = 15;
272
- }
273
-
274
- /** The order's price-determination mechanism: `LIMIT`/`TRIGGER_LIMIT` use `Order.price`, `MARKET`/`TRIGGER_MARKET` fill at the best available price (subject to any auction), and `ORACLE` prices relative to the oracle via `Order.oraclePriceOffset`. `TRIGGER_*` variants only become active once `Order.triggerPrice` is crossed. */
275
- export class OrderType {
276
- static readonly LIMIT = { limit: {} };
277
- static readonly TRIGGER_MARKET = { triggerMarket: {} };
278
- static readonly TRIGGER_LIMIT = { triggerLimit: {} };
279
- static readonly MARKET = { market: {} };
280
- static readonly ORACLE = { oracle: {} };
281
- }
282
-
283
- /** String-literal twin of `MarketType`, used where a plain `'perp' | 'spot'` string (not the `{variant: {}}` shape) is more convenient, e.g. UI/query params. */
284
- export declare type MarketTypeStr = 'perp' | 'spot';
285
- /** Whether an order/position/market is on the spot or perp side of the protocol. */
286
- export class MarketType {
287
- static readonly SPOT = { spot: {} };
288
- static readonly PERP = { perp: {} };
289
- }
290
-
291
- /** Lifecycle state of an `Order`: `INIT` (unused slot), `OPEN` (live, may still be filled), `FILLED` (fully filled), `CANCELED`. */
292
- export class OrderStatus {
293
- static readonly INIT = { init: {} };
294
- static readonly OPEN = { open: {} };
295
- static readonly FILLED = { filled: {} };
296
- static readonly CANCELED = { canceled: {} };
297
- }
298
-
299
- /**
300
- * Bitmask mirror of `Order.bitFlags` / `OrderParams.bitFlags`.
301
- * - `SignedMessage`: order originated from a signed off-chain message (swift/signed-msg flow).
302
- * - `OracleTriggerMarket`: a `TriggerMarket` order whose trigger condition is evaluated against
303
- * the oracle price rather than the last mark/fill price.
304
- * - `SafeTriggerOrder`: exempts the order from the AMM's low-risk-fill slot-delay gate — it may
305
- * be immediately filled by the AMM once triggered, or when the order itself is a liquidation.
306
- * - `NewTriggerReduceOnly`: for a reduce-only order that has triggered, suppresses updating the
307
- * user's `openBids`/`openAsks` counters (avoids double-counting margin already reserved).
308
- * - `HasBuilder`: the order carries a `builderIdx`/`builderFeeTenthBps` builder-code fee split.
309
- * - `IsIsolatedPosition`: the order trades against/opens an isolated-margin position rather than cross margin.
310
- */
311
- export class OrderBitFlag {
312
- static readonly SignedMessage = 1;
313
- static readonly OracleTriggerMarket = 2;
314
- static readonly SafeTriggerOrder = 4;
315
- static readonly NewTriggerReduceOnly = 8;
316
- static readonly HasBuilder = 16;
317
- static readonly IsIsolatedPosition = 32;
318
- }
319
-
320
- /** The kind of action an `OrderActionRecord` event describes. */
321
- export class OrderAction {
322
- static readonly PLACE = { place: {} };
323
- static readonly CANCEL = { cancel: {} };
324
- static readonly EXPIRE = { expire: {} };
325
- static readonly FILL = { fill: {} };
326
- static readonly TRIGGER = { trigger: {} };
327
- }
328
-
329
- /** Why an `OrderActionRecord` event happened — the specific reason a fill/cancel/expire/trigger occurred (e.g. which fulfillment method filled the order, or why it was rejected/canceled). */
330
- export class OrderActionExplanation {
331
- static readonly NONE = { none: {} };
332
- static readonly INSUFFICIENT_FREE_COLLATERAL = {
333
- insufficientFreeCollateral: {},
334
- };
335
- static readonly ORACLE_PRICE_BREACHED_LIMIT_PRICE = {
336
- oraclePriceBreachedLimitPrice: {},
337
- };
338
- static readonly MARKET_ORDER_FILLED_TO_LIMIT_PRICE = {
339
- marketOrderFilledToLimitPrice: {},
340
- };
341
- static readonly ORDER_EXPIRED = {
342
- orderExpired: {},
343
- };
344
- static readonly LIQUIDATION = {
345
- liquidation: {},
346
- };
347
- static readonly ORDER_FILLED_WITH_AMM = {
348
- orderFilledWithAmm: {},
349
- };
350
- static readonly ORDER_FILLED_WITH_AMM_JIT = {
351
- orderFilledWithAmmJit: {},
352
- };
353
- static readonly ORDER_FILLED_WITH_AMM_JIT_LP_SPLIT = {
354
- orderFilledWithAmmJitLpSplit: {},
355
- };
356
- static readonly ORDER_FILLED_WITH_LP_JIT = {
357
- orderFilledWithLpJit: {},
358
- };
359
- static readonly ORDER_FILLED_WITH_MATCH = {
360
- orderFilledWithMatch: {},
361
- };
362
- static readonly ORDER_FILLED_WITH_MATCH_JIT = {
363
- orderFilledWithMatchJit: {},
364
- };
365
- static readonly MARKET_EXPIRED = {
366
- marketExpired: {},
367
- };
368
- static readonly RISK_INCREASING_ORDER = {
369
- riskingIncreasingOrder: {},
370
- };
371
- static readonly REDUCE_ONLY_ORDER_INCREASED_POSITION = {
372
- reduceOnlyOrderIncreasedPosition: {},
373
- };
374
- static readonly DERISK_LP = {
375
- deriskLp: {},
376
- };
377
- static readonly TRANSFER_PERP_POSITION = {
378
- transferPerpPosition: {},
379
- };
380
- }
381
-
382
- /** Trigger-order condition on `Order.triggerCondition`. `ABOVE`/`BELOW` are the pending (not-yet-triggered) states; `TRIGGERED_ABOVE`/`TRIGGERED_BELOW` record that the condition has already fired, so the order is now live for filling. */
383
- export class OrderTriggerCondition {
384
- static readonly ABOVE = { above: {} };
385
- static readonly BELOW = { below: {} };
386
- static readonly TRIGGERED_ABOVE = { triggeredAbove: {} }; // above condition has been triggered
387
- static readonly TRIGGERED_BELOW = { triggeredBelow: {} }; // below condition has been triggered
388
- }
389
-
390
- /** Why a `DepositRecord` event happened: a direct transfer, a borrow being drawn, a borrow being repaid, or a protocol reward credit. */
391
- export class DepositExplanation {
392
- static readonly NONE = { none: {} };
393
- static readonly TRANSFER = { transfer: {} };
394
- static readonly BORROW = { borrow: {} };
395
- static readonly REPAY_BORROW = { repayBorrow: {} };
396
- static readonly REWARD = { reward: {} };
397
- }
398
-
399
- /** Why a `SettlePnlRecord` event happened: a normal settle, or settlement of an expired-market position at the market's `expiryPrice`. */
400
- export class SettlePnlExplanation {
401
- static readonly NONE = { none: {} };
402
- static readonly EXPIRED_POSITION = { expiredPosition: {} };
403
- }
404
-
405
- /** The insurance-fund-stake action an `InsuranceFundStakeRecord` event describes. */
406
- export class StakeAction {
407
- static readonly STAKE = { stake: {} };
408
- static readonly UNSTAKE_REQUEST = { unstakeRequest: {} };
409
- static readonly UNSTAKE_CANCEL_REQUEST = { unstakeCancelRequest: {} };
410
- static readonly UNSTAKE = { unstake: {} };
411
- static readonly UNSTAKE_TRANSFER = { unstakeTransfer: {} };
412
- static readonly STAKE_TRANSFER = { stakeTransfer: {} };
413
- }
414
-
415
- /** Fill/settle-PnL strictness passed to settle-PnL instructions: `TRY_SETTLE` settles as much as is safe and never fails outright, `MUST_SETTLE` requires the full requested settlement to succeed or the instruction reverts. */
416
- export class SettlePnlMode {
417
- static readonly TRY_SETTLE = { trySettle: {} };
418
- static readonly MUST_SETTLE = { mustSettle: {} };
419
- }
420
-
421
- /** Returns true if the Anchor enum-class instance `object` (shape `{ [variant]: {} }`) is the given variant key. */
422
- export function isVariant(object: unknown, type: string) {
423
- return Object.prototype.hasOwnProperty.call(object, type);
424
- }
425
-
426
- /** Returns true if the Anchor enum-class instance `object` matches any of the given variant keys. */
427
- export function isOneOfVariant(object: unknown, types: string[]) {
428
- return types.reduce((result, type) => {
429
- return result || Object.prototype.hasOwnProperty.call(object, type);
430
- }, false);
431
- }
432
-
433
- /** Returns the sole variant key of an Anchor enum-class instance (shape `{ [variant]: {} }`), e.g. `"long"` for `PositionDirection.LONG`. */
434
- export function getVariant(object: unknown): string {
435
- return Object.keys(object as object)[0];
436
- }
437
-
438
- /** Aggressor side of a trade for candle/trade-history purposes. `None` is used when a fill has no clear taker side (e.g. some liquidations). */
439
- export enum TradeSide {
440
- None = 0,
441
- Buy = 1,
442
- Sell = 2,
443
- }
444
-
445
- /** Candle bucket size in minutes (`'1'`…`'240'`), or `'D'`/`'W'`/`'M'` for day/week/month candles. */
446
- export type CandleResolution =
447
- | '1'
448
- | '5'
449
- | '15'
450
- | '60'
451
- | '240'
452
- | 'D'
453
- | 'W'
454
- | 'M';
455
-
456
- /** Emitted when a new `UserAccount` sub-account is created. */
457
- export type NewUserRecord = {
458
- ts: BN;
459
- userAuthority: PublicKey;
460
- user: PublicKey;
461
- subAccountId: number;
462
- name: number[];
463
- referrer: PublicKey;
464
- };
465
-
466
- /** Emitted on every deposit, withdraw, or internal transfer that moves tokens into/out of a spot market. */
467
- export type DepositRecord = {
468
- ts: BN;
469
- userAuthority: PublicKey;
470
- user: PublicKey;
471
- direction: {
472
- deposit?: any;
473
- withdraw?: any;
474
- };
475
- marketIndex: number;
476
- /** amount moved, in the spot market's token-mint precision (`SpotMarketConfig.precision`) */
477
- amount: BN;
478
- /** PRICE_PRECISION (1e6) */
479
- oraclePrice: BN;
480
- /** market's total deposit balance after this action, SPOT_BALANCE_PRECISION (1e9) scaled balance */
481
- marketDepositBalance: BN;
482
- /** market's total borrow balance after this action, SPOT_BALANCE_PRECISION (1e9) scaled balance */
483
- marketWithdrawBalance: BN;
484
- /** SPOT_CUMULATIVE_INTEREST_PRECISION (1e10) */
485
- marketCumulativeDepositInterest: BN;
486
- /** SPOT_CUMULATIVE_INTEREST_PRECISION (1e10) */
487
- marketCumulativeBorrowInterest: BN;
488
- /** user's lifetime deposits after this action, QUOTE_PRECISION (1e6) */
489
- totalDepositsAfter: BN;
490
- /** user's lifetime withdraws after this action, QUOTE_PRECISION (1e6) */
491
- totalWithdrawsAfter: BN;
492
- depositRecordId: BN;
493
- explanation: DepositExplanation;
494
- /** set when this was a `transferDeposit`: the counterparty user account */
495
- transferUser?: PublicKey;
496
- /** the signer that authorized the action, when different from the user's own authority (e.g. a delegate or keeper) */
497
- signer?: PublicKey;
498
- /** the user's token amount (deposit/borrow value) after this action, spot market token-mint precision */
499
- userTokenAmountAfter: BN;
500
- };
501
-
502
- /** Emitted whenever a spot market's cumulative deposit/borrow interest is updated. */
503
- export type SpotInterestRecord = {
504
- ts: BN;
505
- marketIndex: number;
506
- /** SPOT_BALANCE_PRECISION (1e9) */
507
- depositBalance: BN;
508
- /** SPOT_CUMULATIVE_INTEREST_PRECISION (1e10) */
509
- cumulativeDepositInterest: BN;
510
- /** SPOT_BALANCE_PRECISION (1e9) */
511
- borrowBalance: BN;
512
- /** SPOT_CUMULATIVE_INTEREST_PRECISION (1e10) */
513
- cumulativeBorrowInterest: BN;
514
- /** SPOT_UTILIZATION_PRECISION (1e6) */
515
- optimalUtilization: number;
516
- /** SPOT_RATE_PRECISION (1e6) */
517
- optimalBorrowRate: number;
518
- /** SPOT_RATE_PRECISION (1e6) */
519
- maxBorrowRate: number;
520
- };
521
-
522
- /** Emitted when a perp market's AMM curve is adjusted (repeg or `k` update). */
523
- export type AmmCurveChanged = {
524
- ts: BN;
525
- marketIndex: number;
526
- /** PEG_PRECISION (1e6) */
527
- pegMultiplierBefore: BN;
528
- /** AMM_RESERVE_PRECISION (1e9) */
529
- baseAssetReserveBefore: BN;
530
- /** AMM_RESERVE_PRECISION (1e9) */
531
- quoteAssetReserveBefore: BN;
532
- /** AMM_RESERVE_PRECISION (1e9) */
533
- sqrtKBefore: BN;
534
- /** PEG_PRECISION (1e6) */
535
- pegMultiplierAfter: BN;
536
- /** AMM_RESERVE_PRECISION (1e9) */
537
- baseAssetReserveAfter: BN;
538
- /** AMM_RESERVE_PRECISION (1e9) */
539
- quoteAssetReserveAfter: BN;
540
- /** AMM_RESERVE_PRECISION (1e9) */
541
- sqrtKAfter: BN;
542
- /** signed cost of the curve adjustment, QUOTE_PRECISION (1e6) */
543
- adjustmentCost: BN;
544
- /** QUOTE_PRECISION (1e6) */
545
- totalFeeMinusDistributionsAfter: BN;
546
- /** PRICE_PRECISION (1e6) */
547
- oraclePrice: BN;
548
- };
549
-
550
- /** Emitted on insurance-fund vault operations (init/add/request-remove/remove) for a spot market's IF, keyed by the perp market that triggered it when settling a deficit. */
551
- export declare type InsuranceFundRecord = {
552
- ts: BN;
553
- spotMarketIndex: number;
554
- perpMarketIndex: number;
555
- /** IF_FACTOR_PRECISION (1e6) share of this action attributed to the user */
556
- userIfFactor: number;
557
- /** IF_FACTOR_PRECISION (1e6) total IF factor at the time of the action */
558
- totalIfFactor: number;
559
- /** spot market vault token balance before the action, spot market token-mint precision */
560
- vaultAmountBefore: BN;
561
- /** insurance-fund vault token balance before the action, spot market token-mint precision */
562
- insuranceVaultAmountBefore: BN;
563
- totalIfSharesBefore: BN;
564
- totalIfSharesAfter: BN;
565
- /** amount moved, spot market token-mint precision */
566
- amount: BN;
567
- };
568
-
569
- /** Emitted on every `InsuranceFundStake` account mutation (stake, unstake request/cancel, unstake, transfer). */
570
- export declare type InsuranceFundStakeRecord = {
571
- ts: BN;
572
- userAuthority: PublicKey;
573
- action: StakeAction;
574
- /** amount staked/unstaked, spot market token-mint precision */
575
- amount: BN;
576
- marketIndex: number;
577
- /** insurance-fund vault token balance before the action, spot market token-mint precision */
578
- insuranceVaultAmountBefore: BN;
579
- ifSharesBefore: BN;
580
- userIfSharesBefore: BN;
581
- totalIfSharesBefore: BN;
582
- ifSharesAfter: BN;
583
- userIfSharesAfter: BN;
584
- totalIfSharesAfter: BN;
585
- };
586
-
587
- /** Emitted every time a perp market's funding rate is updated. */
588
- export type FundingRateRecord = {
589
- ts: BN;
590
- recordId: BN;
591
- marketIndex: number;
592
- /** unit is quote per base, FUNDING_RATE_PRECISION (1e9) */
593
- fundingRate: BN;
594
- /** FUNDING_RATE_PRECISION (1e9) */
595
- fundingRateLong: BN;
596
- /** FUNDING_RATE_PRECISION (1e9) */
597
- fundingRateShort: BN;
598
- /** FUNDING_RATE_PRECISION (1e9) */
599
- cumulativeFundingRateLong: BN;
600
- /** FUNDING_RATE_PRECISION (1e9) */
601
- cumulativeFundingRateShort: BN;
602
- /** PRICE_PRECISION (1e6) */
603
- oraclePriceTwap: BN;
604
- /** PRICE_PRECISION (1e6) */
605
- markPriceTwap: BN;
606
- /** BASE_PRECISION (1e9) */
607
- baseAssetAmountWithAmm: BN;
608
- };
609
-
610
- /** Emitted whenever a user's perp position settles a funding payment. */
611
- export type FundingPaymentRecord = {
612
- ts: BN;
613
- userAuthority: PublicKey;
614
- user: PublicKey;
615
- marketIndex: number;
616
- /** signed, positive = user received funding; QUOTE_PRECISION (1e6) */
617
- fundingPayment: BN;
618
- /** the position size the payment was calculated against, BASE_PRECISION (1e9) */
619
- baseAssetAmount: BN;
620
- /** the user's cumulative funding rate prior to this payment, FUNDING_RATE_PRECISION (1e9) */
621
- userLastCumulativeFunding: BN;
622
- /** FUNDING_RATE_PRECISION (1e9) */
623
- ammCumulativeFundingLong: BN;
624
- /** FUNDING_RATE_PRECISION (1e9) */
625
- ammCumulativeFundingShort: BN;
626
- };
627
-
628
- /** Emitted for every liquidation action. Exactly one of `liquidatePerp`/`liquidateSpot`/`liquidateBorrowForPerpPnl`/`liquidatePerpPnlForDeposit`/`perpBankruptcy`/`spotBankruptcy` is populated, selected by `liquidationType`; the others are left as zeroed defaults. */
629
- export type LiquidationRecord = {
630
- ts: BN;
631
- user: PublicKey;
632
- liquidator: PublicKey;
633
- liquidationType: LiquidationType;
634
- /** QUOTE_PRECISION (1e6) */
635
- marginRequirement: BN;
636
- /** signed, QUOTE_PRECISION (1e6) */
637
- totalCollateral: BN;
638
- /** cumulative margin freed by this liquidation so far, QUOTE_PRECISION (1e6) */
639
- marginFreed: BN;
640
- liquidationId: number;
641
- /** true if the user was bankrupt (their loss exceeded their collateral) as of this action */
642
- bankrupt: boolean;
643
- canceledOrderIds: number[];
644
- liquidatePerp: LiquidatePerpRecord;
645
- liquidateSpot: LiquidateSpotRecord;
646
- liquidateBorrowForPerpPnl: LiquidateBorrowForPerpPnlRecord;
647
- liquidatePerpPnlForDeposit: LiquidatePerpPnlForDepositRecord;
648
- perpBankruptcy: PerpBankruptcyRecord;
649
- spotBankruptcy: SpotBankruptcyRecord;
650
- /** bitmask, see `LiquidationBitFlag` */
651
- bitFlags: number;
652
- };
653
-
654
- /** Which liquidation path a `LiquidationRecord` describes; selects which of the record's sub-record fields is populated. */
655
- export class LiquidationType {
656
- static readonly LIQUIDATE_PERP = { liquidatePerp: {} };
657
- static readonly LIQUIDATE_BORROW_FOR_PERP_PNL = {
658
- liquidateBorrowForPerpPnl: {},
659
- };
660
- static readonly LIQUIDATE_PERP_PNL_FOR_DEPOSIT = {
661
- liquidatePerpPnlForDeposit: {},
662
- };
663
- static readonly PERP_BANKRUPTCY = {
664
- perpBankruptcy: {},
665
- };
666
- static readonly SPOT_BANKRUPTCY = {
667
- spotBankruptcy: {},
668
- };
669
- static readonly LIQUIDATE_SPOT = {
670
- liquidateSpot: {},
671
- };
672
- }
673
-
674
- /** Populated on `LiquidationRecord` when `liquidationType` is `LIQUIDATE_PERP`: a perp position was force-closed. */
675
- export type LiquidatePerpRecord = {
676
- marketIndex: number;
677
- /** PRICE_PRECISION (1e6) */
678
- oraclePrice: BN;
679
- /** signed size transferred to the liquidator, BASE_PRECISION (1e9) */
680
- baseAssetAmount: BN;
681
- /** QUOTE_PRECISION (1e6) */
682
- quoteAssetAmount: BN;
683
- userOrderId: number;
684
- liquidatorOrderId: number;
685
- fillRecordId: BN;
686
- /** paid to the liquidator, LIQUIDATOR_FEE_PRECISION (1e6)-denominated rate applied to `quoteAssetAmount`; QUOTE_PRECISION (1e6) amount */
687
- liquidatorFee: BN;
688
- /** cut routed to the insurance fund, QUOTE_PRECISION (1e6) */
689
- ifFee: BN;
690
- /** cut routed to the protocol fee pool, QUOTE_PRECISION (1e6) */
691
- protocolFee: BN;
692
- };
693
-
694
- /** Populated on `LiquidationRecord` when `liquidationType` is `LIQUIDATE_SPOT`: a spot borrow was liquidated against a spot asset deposit. */
695
- export type LiquidateSpotRecord = {
696
- assetMarketIndex: number;
697
- /** PRICE_PRECISION (1e6) */
698
- assetPrice: BN;
699
- /** asset market token-mint precision */
700
- assetTransfer: BN;
701
- liabilityMarketIndex: number;
702
- /** PRICE_PRECISION (1e6) */
703
- liabilityPrice: BN;
704
- /** liability market token-mint precision */
705
- liabilityTransfer: BN;
706
- /** liability market token-mint precision */
707
- ifFee: BN;
708
- /** liability market token-mint precision */
709
- protocolFee: BN;
710
- };
711
-
712
- /** Populated on `LiquidationRecord` when `liquidationType` is `LIQUIDATE_BORROW_FOR_PERP_PNL`: a user's negative perp PnL was covered by seizing one of their spot borrows/deposits. */
713
- export type LiquidateBorrowForPerpPnlRecord = {
714
- perpMarketIndex: number;
715
- /** PRICE_PRECISION (1e6) */
716
- marketOraclePrice: BN;
717
- /** QUOTE_PRECISION (1e6) */
718
- pnlTransfer: BN;
719
- liabilityMarketIndex: number;
720
- /** PRICE_PRECISION (1e6) */
721
- liabilityPrice: BN;
722
- /** liability market token-mint precision */
723
- liabilityTransfer: BN;
724
- };
725
-
726
- /** Populated on `LiquidationRecord` when `liquidationType` is `LIQUIDATE_PERP_PNL_FOR_DEPOSIT`: a user's positive perp PnL was seized to cover a deficit, paid out from one of their spot deposits. */
727
- export type LiquidatePerpPnlForDepositRecord = {
728
- perpMarketIndex: number;
729
- /** PRICE_PRECISION (1e6) */
730
- marketOraclePrice: BN;
731
- /** QUOTE_PRECISION (1e6) */
732
- pnlTransfer: BN;
733
- assetMarketIndex: number;
734
- /** PRICE_PRECISION (1e6) */
735
- assetPrice: BN;
736
- /** asset market token-mint precision */
737
- assetTransfer: BN;
738
- };
739
-
740
- /** Populated on `LiquidationRecord` when `liquidationType` is `PERP_BANKRUPTCY`: a user's unpaid perp loss was resolved via insurance-fund payout and/or socialized loss (`clawbackUser`/`clawbackUserPayment` set only when a clawback source exists). */
741
- export type PerpBankruptcyRecord = {
742
- marketIndex: number;
743
- /** the bankrupt (unresolved negative) pnl, signed, QUOTE_PRECISION (1e6) */
744
- pnl: BN;
745
- /** amount paid from the insurance fund, QUOTE_PRECISION (1e6) */
746
- ifPayment: BN;
747
- clawbackUser: PublicKey | null;
748
- /** QUOTE_PRECISION (1e6), set only when `clawbackUser` is set */
749
- clawbackUserPayment: BN | null;
750
- /** FUNDING_RATE_PRECISION (1e9) */
751
- cumulativeFundingRateDelta: BN;
752
- };
753
-
754
- /** Populated on `LiquidationRecord` when `liquidationType` is `SPOT_BANKRUPTCY`: a user's unpaid spot borrow was resolved via insurance-fund payout and socialized loss. */
755
- export type SpotBankruptcyRecord = {
756
- marketIndex: number;
757
- /** spot market token-mint precision */
758
- borrowAmount: BN;
759
- /** SPOT_CUMULATIVE_INTEREST_PRECISION (1e10) */
760
- cumulativeDepositInterestDelta: BN;
761
- /** amount paid from the insurance fund, spot market token-mint precision */
762
- ifPayment: BN;
763
- };
764
-
765
- /** Bitmask mirror of `LiquidationRecord.bitFlags`. `IsolatedPosition` marks that the liquidation acted on an isolated-margin position rather than the user's cross-margin account. */
766
- export class LiquidationBitFlag {
767
- static readonly IsolatedPosition = 1;
768
- }
769
-
770
- /** Emitted every time a user's perp PnL is settled against the market's pnl pool. */
771
- export type SettlePnlRecord = {
772
- ts: BN;
773
- user: PublicKey;
774
- marketIndex: number;
775
- /** signed amount settled, QUOTE_PRECISION (1e6) */
776
- pnl: BN;
777
- /** the position size at settlement time, BASE_PRECISION (1e9) */
778
- baseAssetAmount: BN;
779
- /** `PerpPosition.quoteAssetAmount` after settlement, QUOTE_PRECISION (1e6) */
780
- quoteAssetAmountAfter: BN;
781
- /** `PerpPosition.quoteEntryAmount` at settlement time, QUOTE_PRECISION (1e6) */
782
- quoteEntryAmount: BN;
783
- /** the price pnl was settled at, PRICE_PRECISION (1e6) */
784
- settlePrice: BN;
785
- explanation: SettlePnlExplanation;
786
- };
787
-
788
- /** Emitted when a signed off-chain (swift) order message is matched/recorded on-chain, so indexers can associate the signed message with its resulting order. */
789
- export type SignedMsgOrderRecord = {
790
- ts: BN;
791
- user: PublicKey;
792
- /** hash of the signed message, used to dedupe/look up the original signed order */
793
- hash: string;
794
- matchingOrderParams: OrderParams;
795
- /** slot after which the signed message is no longer eligible to be placed */
796
- signedMsgOrderMaxSlot: BN;
797
- signedMsgOrderUuid: Uint8Array;
798
- userOrderId: number;
799
- };
800
-
801
- /** Emitted whenever an `Order` slot is written (placed, updated on fill, canceled, expired, triggered) — a full snapshot of the order's post-action state. */
802
- export type OrderRecord = {
803
- ts: BN;
804
- user: PublicKey;
805
- order: Order;
806
- };
807
-
808
- /** Emitted for every order lifecycle action (place/fill/cancel/expire/trigger). Taker/maker fields are `null` when not applicable to the action (e.g. AMM fills have no `maker`). */
809
- export type OrderActionRecord = {
810
- ts: BN;
811
- action: OrderAction;
812
- actionExplanation: OrderActionExplanation;
813
- marketIndex: number;
814
- marketType: MarketType;
815
- filler: PublicKey | null;
816
- /** paid to the filler/keeper, QUOTE_PRECISION (1e6) */
817
- fillerReward: BN | null;
818
- fillRecordId: BN | null;
819
- /** perp: BASE_PRECISION (1e9); spot: market token-mint precision */
820
- baseAssetAmountFilled: BN | null;
821
- /** QUOTE_PRECISION (1e6) */
822
- quoteAssetAmountFilled: BN | null;
823
- /** QUOTE_PRECISION (1e6) */
824
- takerFee: BN | null;
825
- /** rebate paid to the maker (can be negative if the maker pays a fee), QUOTE_PRECISION (1e6) */
826
- makerFee: BN | null;
827
- /** BPS_PRECISION-style share of the taker fee credited to the referrer */
828
- referrerReward: number | null;
829
- /** taker's price improvement vs. their limit/oracle price, QUOTE_PRECISION (1e6) */
830
- quoteAssetAmountSurplus: BN | null;
831
- /** fee charged by the spot fulfillment method (e.g. an external DEX), spot market token-mint precision */
832
- spotFulfillmentMethodFee: BN | null;
833
- taker: PublicKey | null;
834
- takerOrderId: number | null;
835
- takerOrderDirection: PositionDirection | null;
836
- /** perp: BASE_PRECISION (1e9); spot: market token-mint precision */
837
- takerOrderBaseAssetAmount: BN | null;
838
- /** perp: BASE_PRECISION (1e9); spot: market token-mint precision */
839
- takerOrderCumulativeBaseAssetAmountFilled: BN | null;
840
- /** QUOTE_PRECISION (1e6) */
841
- takerOrderCumulativeQuoteAssetAmountFilled: BN | null;
842
- maker: PublicKey | null;
843
- makerOrderId: number | null;
844
- makerOrderDirection: PositionDirection | null;
845
- /** perp: BASE_PRECISION (1e9); spot: market token-mint precision */
846
- makerOrderBaseAssetAmount: BN | null;
847
- /** perp: BASE_PRECISION (1e9); spot: market token-mint precision */
848
- makerOrderCumulativeBaseAssetAmountFilled: BN | null;
849
- /** QUOTE_PRECISION (1e6) */
850
- makerOrderCumulativeQuoteAssetAmountFilled: BN | null;
851
- /** PRICE_PRECISION (1e6) */
852
- oraclePrice: BN;
853
- /** bitmask, currently records isolated-margin/builder-fee flags mirrored from `OrderBitFlag` */
854
- bitFlags: number;
855
- /** taker's `PerpPosition.quoteEntryAmount` immediately before this fill, QUOTE_PRECISION (1e6) */
856
- takerExistingQuoteEntryAmount: BN | null;
857
- /** taker's `PerpPosition.baseAssetAmount` immediately before this fill, BASE_PRECISION (1e9) */
858
- takerExistingBaseAssetAmount: BN | null;
859
- /** maker's `PerpPosition.quoteEntryAmount` immediately before this fill, QUOTE_PRECISION (1e6) */
860
- makerExistingQuoteEntryAmount: BN | null;
861
- /** maker's `PerpPosition.baseAssetAmount` immediately before this fill, BASE_PRECISION (1e9) */
862
- makerExistingBaseAssetAmount: BN | null;
863
- /** PRICE_PRECISION (1e6), set only for trigger-order fills */
864
- triggerPrice: BN | null;
865
- /** index into the taker's `RevenueShareEscrow.approvedBuilders`, set only when the taker order had `OrderBitFlag.HasBuilder` */
866
- builderIdx: number | null;
867
- /** builder fee charged on this fill, QUOTE_PRECISION (1e6) */
868
- builderFee: BN | null;
869
- };
870
-
871
- /** Emitted on every constant-product spot swap (`beginSwap`/`endSwap`) between two spot markets. */
872
- export type SwapRecord = {
873
- ts: BN;
874
- user: PublicKey;
875
- /** out market token-mint precision */
876
- amountOut: BN;
877
- /** in market token-mint precision */
878
- amountIn: BN;
879
- outMarketIndex: number;
880
- inMarketIndex: number;
881
- /** PRICE_PRECISION (1e6) */
882
- outOraclePrice: BN;
883
- /** PRICE_PRECISION (1e6) */
884
- inOraclePrice: BN;
885
- /** total fee charged on the swap, out market token-mint precision */
886
- fee: BN;
887
- };
888
-
889
- /** Emitted when a spot market's vault balance is reconciled against `SpotMarketAccount.depositBalance`/`borrowBalance` (drift/donation detection). */
890
- export type SpotMarketVaultDepositRecord = {
891
- ts: BN;
892
- marketIndex: number;
893
- /** SPOT_BALANCE_PRECISION (1e9) */
894
- depositBalance: BN;
895
- /** SPOT_CUMULATIVE_INTEREST_PRECISION (1e10) */
896
- cumulativeDepositInterestBefore: BN;
897
- /** SPOT_CUMULATIVE_INTEREST_PRECISION (1e10) */
898
- cumulativeDepositInterestAfter: BN;
899
- /** spot market token-mint precision */
900
- depositTokenAmountBefore: BN;
901
- /** spot market token-mint precision */
902
- amount: BN;
903
- };
904
-
905
- /** Emitted when a `UserAccount` sub-account is deleted. */
906
- export type DeleteUserRecord = {
907
- ts: BN;
908
- userAuthority: PublicKey;
909
- user: PublicKey;
910
- subAccountId: number;
911
- /** set when a keeper (not the user/delegate) deleted an idle account */
912
- keeper: PublicKey | null;
913
- };
914
-
915
- /** Emitted on every constituent-to-constituent swap inside an LP pool (`LPPoolAccount`). */
916
- export type LPSwapRecord = {
917
- ts: BN;
918
- slot: BN;
919
- authority: PublicKey;
920
- /** out constituent's spot market token-mint precision */
921
- outAmount: BN;
922
- /** in constituent's spot market token-mint precision */
923
- inAmount: BN;
924
- /** out constituent's spot market token-mint precision */
925
- outFee: BN;
926
- /** in constituent's spot market token-mint precision */
927
- inFee: BN;
928
- outSpotMarketIndex: number;
929
- inSpotMarketIndex: number;
930
- outConstituentIndex: number;
931
- inConstituentIndex: number;
932
- /** PRICE_PRECISION (1e6) */
933
- outOraclePrice: BN;
934
- /** PRICE_PRECISION (1e6) */
935
- inOraclePrice: BN;
936
- /** LP pool AUM at the time of the swap, QUOTE_PRECISION (1e6) */
937
- lastAum: BN;
938
- lastAumSlot: BN;
939
- /** PERCENTAGE_PRECISION (1e6) */
940
- inMarketCurrentWeight: BN;
941
- /** PERCENTAGE_PRECISION (1e6) */
942
- outMarketCurrentWeight: BN;
943
- /** PERCENTAGE_PRECISION (1e6) */
944
- inMarketTargetWeight: BN;
945
- /** PERCENTAGE_PRECISION (1e6) */
946
- outMarketTargetWeight: BN;
947
- inSwapId: BN;
948
- outSwapId: BN;
949
- lpPool: PublicKey;
950
- };
951
-
952
- /** Emitted when LP tokens are minted (deposit) or redeemed (withdraw) against an LP pool. */
953
- export type LPMintRedeemRecord = {
954
- ts: BN;
955
- slot: BN;
956
- authority: PublicKey;
957
- /** encodes mint vs. redeem (and any sub-variant); compare against the program's `MintRedeemDescription` discriminant */
958
- description: number;
959
- /** constituent spot market token-mint precision */
960
- amount: BN;
961
- /** constituent spot market token-mint precision */
962
- fee: BN;
963
- spotMarketIndex: number;
964
- constituentIndex: number;
965
- /** PRICE_PRECISION (1e6) */
966
- oraclePrice: BN;
967
- mint: PublicKey;
968
- /** LP token precision (quote-mint precision, QUOTE_PRECISION 1e6) */
969
- lpAmount: BN;
970
- /** LP token precision */
971
- lpFee: BN;
972
- /** LP token price, PRICE_PRECISION (1e6) */
973
- lpPrice: BN;
974
- mintRedeemId: BN;
975
- /** LP pool AUM at the time of the action, QUOTE_PRECISION (1e6) */
976
- lastAum: BN;
977
- lastAumSlot: BN;
978
- /** PERCENTAGE_PRECISION (1e6) */
979
- inMarketCurrentWeight: BN;
980
- /** PERCENTAGE_PRECISION (1e6) */
981
- inMarketTargetWeight: BN;
982
- lpPool: PublicKey;
983
- };
984
-
985
- /** Emitted when a perp market settles PnL/fees with its hedging LP pool. */
986
- export type LPSettleRecord = {
987
- recordId: BN;
988
- lastTs: BN;
989
- lastSlot: BN;
990
- ts: BN;
991
- slot: BN;
992
- perpMarketIndex: number;
993
- /** signed amount transferred to/from the LP pool, QUOTE_PRECISION (1e6) */
994
- settleToLpAmount: BN;
995
- /** signed, QUOTE_PRECISION (1e6) */
996
- perpAmmPnlDelta: BN;
997
- /** signed, QUOTE_PRECISION (1e6) */
998
- perpAmmExFeeDelta: BN;
999
- /** LP pool AUM after this settle, QUOTE_PRECISION (1e6) */
1000
- lpAum: BN;
1001
- /** LP token price after this settle, PRICE_PRECISION (1e6) */
1002
- lpPrice: BN;
1003
- lpPool: PublicKey;
1004
- };
1005
-
1006
- /** Emitted when an LP pool constituent's borrow/lend deposit into (or withdrawal from) the underlying spot market changes. */
1007
- export type LPBorrowLendDepositRecord = {
1008
- ts: BN;
1009
- slot: BN;
1010
- spotMarketIndex: number;
1011
- constituentIndex: number;
1012
- direction: DepositDirection;
1013
- /** constituent spot market token-mint precision */
1014
- tokenBalance: BN;
1015
- /** constituent spot market token-mint precision */
1016
- lastTokenBalance: BN;
1017
- /** interest accrued since the last update, constituent spot market token-mint precision */
1018
- interestAccruedTokenAmount: BN;
1019
- /** constituent spot market token-mint precision */
1020
- amountDepositWithdraw: BN;
1021
- lpPool: PublicKey;
1022
- };
1023
-
1024
- /**
1025
- * The protocol's single global config account (one per deployment). Decoded mirror of the Rust
1026
- * `State` zero-copy account.
1027
- *
1028
- * **Admin tiers** — three levels of authority, from slowest/most-trusted to fastest/least-trusted:
1029
- * - `coldAdmin`: root authority, set once at `initialize`. Only key that can rotate `warmAdmin`
1030
- * and `pauseAdmin`. Expected to sit behind a (small) timelocked multisig.
1031
- * - `warmAdmin`: operational authority that can rotate the eleven `hot*` bot keys below.
1032
- * `PublicKey.default()` means unset, in which case only `coldAdmin` can act.
1033
- * - `pauseAdmin`: emergency-pause authority with no on-chain timelock — may only *add* pause bits
1034
- * to `exchangeStatus` (never clear them); `coldAdmin`/`warmAdmin` retain full pause+unpause power.
1035
- * `PublicKey.default()` means unassigned (only cold/warm can pause).
1036
- *
1037
- * **Hot role keys** (`hot*`): purpose-specific bot keys for high-frequency keeper actions (AMM
1038
- * cranking, LP cache/swap/settle, feature-flag toggles, fuel, user-flag updates, vault deposits,
1039
- * mm-oracle cranking, AMM spread adjustment, protocol-fee withdrawal). `PublicKey.default()` means
1040
- * the role is unassigned and only `warmAdmin`/`coldAdmin` may call handlers gated on that role.
1041
- */
1042
- export type StateAccount = {
1043
- coldAdmin: PublicKey;
1044
- warmAdmin: PublicKey;
1045
- pauseAdmin: PublicKey;
1046
- hotAmmCrank: PublicKey;
1047
- hotLpCache: PublicKey;
1048
- hotLpSwap: PublicKey;
1049
- hotLpSettle: PublicKey;
1050
- hotFeatureFlag: PublicKey;
1051
- hotFuel: PublicKey;
1052
- hotUserFlag: PublicKey;
1053
- hotVaultDeposit: PublicKey;
1054
- hotMmOracleCrank: PublicKey;
1055
- hotAmmSpreadAdjust: PublicKey;
1056
- /** hot key authorized to trigger protocol-fee withdrawals to `protocolFeeRecipientPerp`/`protocolFeeRecipientSpot` */
1057
- hotFeeWithdraw: PublicKey;
1058
- /** treasury PERP protocol fees are withdrawn to (settable only by `coldAdmin`); `PublicKey.default()` makes perp fee withdrawals inert */
1059
- protocolFeeRecipientPerp: PublicKey;
1060
- /** treasury SPOT protocol fees are withdrawn to (settable only by `coldAdmin`); `PublicKey.default()` makes spot fee withdrawals inert */
1061
- protocolFeeRecipientSpot: PublicKey;
1062
- /** bitmask, see `ExchangeStatus` */
1063
- exchangeStatus: number;
1064
- whitelistMint: PublicKey;
1065
- discountMint: PublicKey;
1066
- oracleGuardRails: OracleGuardRails;
1067
- numberOfAuthorities: BN;
1068
- numberOfSubAccounts: BN;
1069
- numberOfMarkets: number;
1070
- numberOfSpotMarkets: number;
1071
- /** slots */
1072
- minPerpAuctionDuration: number;
1073
- /** seconds */
1074
- defaultMarketOrderTimeInForce: number;
1075
- /** slots */
1076
- defaultSpotAuctionDuration: number;
1077
- /** MARGIN_PRECISION (1e4); extra maintenance-margin buffer required before a liquidation may proceed */
1078
- liquidationMarginBufferRatio: number;
1079
- /** seconds a market stays in `SETTLEMENT` status before positions must be settled */
1080
- settlementDuration: number;
1081
- maxNumberOfSubAccounts: number;
1082
- signer: PublicKey;
1083
- signerNonce: number;
1084
- srmVault: PublicKey;
1085
- /** default `FeeStructure` applied to new perp markets */
1086
- perpFeeStructure: FeeStructure;
1087
- /** default `FeeStructure` applied to new spot markets */
1088
- spotFeeStructure: FeeStructure;
1089
- /** LIQUIDATION_PCT_PRECISION (1e4); fraction of a position liquidated per partial-liquidation pass */
1090
- initialPctToLiquidate: number;
1091
- /** seconds a liquidation is spread over */
1092
- liquidationDuration: number;
1093
- /** max SOL fee `getInitUserFee` may charge to create a new sub-account, in value/100 SOL (e.g. 100 = 1 SOL); ramps from 0 to this max as account-space utilization rises from 80% to 100% of `maxNumberOfSubAccounts` */
1094
- maxInitializeUserFee: number;
1095
- /** bitmask, see `FeatureBitFlags` */
1096
- featureBitFlags: number;
1097
- /** bitmask of LP-pool-specific feature flags */
1098
- lpPoolFeatureBitFlags: number;
1099
- /** bitmask, see `SolvencyStatus` */
1100
- solvencyStatus: number;
1101
- };
1102
-
1103
- /** Decoded mirror of the on-chain `PerpMarket` zero-copy account. */
1104
- export type PerpMarketAccount = {
1105
- status: MarketStatus;
1106
- contractType: ContractType;
1107
- contractTier: ContractTier;
1108
- /** unix timestamp the market will expire; only set if the market is reduce-only */
1109
- expiryTs: BN;
1110
- /** PRICE_PRECISION (1e6); the price positions settle at, only set once the market is expired */
1111
- expiryPrice: BN;
1112
- marketIndex: number;
1113
- pubkey: PublicKey;
1114
- name: number[];
1115
- /** the market's constant-product vAMM state */
1116
- amm: AMM;
1117
- /** market-wide stats shared across all makers (mark/oracle TWAPs, volume, mm-oracle snapshot) */
1118
- marketStats: MarketStats;
1119
- numberOfUsersWithBase: number;
1120
- numberOfUsers: number;
1121
- /** MARGIN_PRECISION (1e4); collateral fraction required to open a position, e.g. 1000 = 10% = 10x max leverage */
1122
- marginRatioInitial: number;
1123
- /** MARGIN_PRECISION (1e4); collateral fraction below which a position is liquidated */
1124
- marginRatioMaintenance: number;
1125
- nextFillRecordId: BN;
1126
- nextFundingRateRecordId: BN;
1127
- /** the market's pnl pool: increases when users settle negative pnl, decreases when users settle positive pnl; SPOT_BALANCE_PRECISION (1e9) scaled balance in the quote spot market */
1128
- pnlPool: PoolBalance;
1129
- /** protocol-owned quote-denominated fee claim, withdrawn to `StateAccount.protocolFeeRecipientPerp`; SPOT_BALANCE_PRECISION (1e9) scaled balance */
1130
- protocolFeePool: PoolBalance;
1131
- /** consolidated fee-split accounting: lifetime analytics counters plus pending protocol/IF/AMM carveouts */
1132
- feeLedger: FeeLedger;
1133
- /** LIQUIDATOR_FEE_PRECISION (1e6); fee paid to the liquidator for taking over the position */
1134
- liquidatorFee: number;
1135
- /** LIQUIDATOR_FEE_PRECISION (1e6); cut of a liquidation routed to the insurance fund */
1136
- ifLiquidationFee: number;
1137
- /** LIQUIDATOR_FEE_PRECISION (1e6); protocol's cut of a liquidation, taken from the liquidatee */
1138
- protocolLiquidationFee: number;
1139
- /** QUOTE_PRECISION (1e6); pnl-pool retention buffer the fee-sweep leaves untouched above `max(net_user_pnl, 0)` */
1140
- feePoolBufferTarget: BN;
1141
- /** MARGIN_PRECISION (1e4); scales margin ratio up for large positions */
1142
- imfFactor: number;
1143
- /** MARGIN_PRECISION (1e4); discounts positive-unrealized-pnl asset weight for large positions */
1144
- unrealizedPnlImfFactor: number;
1145
- /** QUOTE_PRECISION (1e6); pnl imbalance (long pnl − short pnl) above which positive-pnl asset weight starts being discounted */
1146
- unrealizedPnlMaxImbalance: BN;
1147
- /** SPOT_WEIGHT_PRECISION (1e4); initial-margin asset weight applied to a user's unrealized positive pnl */
1148
- unrealizedPnlInitialAssetWeight: number;
1149
- /** SPOT_WEIGHT_PRECISION (1e4); maintenance-margin asset weight applied to a user's unrealized positive pnl */
1150
- unrealizedPnlMaintenanceAssetWeight: number;
1151
- /** the market's claim on the insurance fund */
1152
- insuranceClaim: {
1153
- /** QUOTE_PRECISION (1e6), signed: positive if funds left the market, negative if pulled in */
1154
- revenueWithdrawSinceLastSettle: BN;
1155
- /** QUOTE_PRECISION (1e6); cap on revenue withdrawable per settle period */
1156
- maxRevenueWithdrawPerPeriod: BN;
1157
- lastRevenueWithdrawTs: BN;
1158
- /** QUOTE_PRECISION (1e6); insurance already used to resolve bankruptcy/pnl deficits */
1159
- quoteSettledInsurance: BN;
1160
- /** QUOTE_PRECISION (1e6); max insurance this market may draw to resolve bankruptcy/pnl deficits */
1161
- quoteMaxInsurance: BN;
1162
- };
1163
- quoteSpotMarketIndex: number;
1164
- /** -100 to 100; percentage adjustment applied to the base fee rate (e.g. -50 halves a 5bps fee to 2.5bps) */
1165
- feeAdjustment: number;
1166
- /** bitmask, see `PerpOperation` */
1167
- pausedOperations: number;
1168
-
1169
- /** PRICE_PRECISION (1e6); price of the most recent fill */
1170
- lastFillPrice: BN;
1171
- poolId: number;
1172
-
1173
- /** this market's relationship to its hedging LP pool; admin-set, never mutated per fill */
1174
- hedgeConfig: {
1175
- /** the `LPPoolAccount.lpPoolId` this market hedges into */
1176
- poolId: number;
1177
- /** hedging enabled for this market when non-zero */
1178
- status: number;
1179
- /** bitmask of paused `ConstituentLpOperation`s */
1180
- pausedOperations: number;
1181
- /** scalar excluding a share of exchange fees from hedge routing */
1182
- exchangeFeeExclusionScalar: number;
1183
- /** scalar for the share of fees transferred to the hedge pool */
1184
- feeTransferScalar: number;
1185
- };
1186
- /** bitmask, see `MarketConfigFlag` */
1187
- marketConfig: number;
1188
-
1189
- // Fields migrated off AMM to top-level PerpMarket
1190
- oracle: PublicKey;
1191
- oracleSource: OracleSource;
1192
- /** override for the per-fill slot delay required from the oracle; -1 = use the state default */
1193
- oracleSlotDelayOverride: number;
1194
- /** override for `StateAccount.minPerpAuctionDuration`; 0 = no override, -1 = disable speed bump, 1-100 = literal speed bump slots */
1195
- oracleLowRiskSlotDelayOverride: number;
1196
- /** always non-negative; total long open interest across all users, BASE_PRECISION (1e9) */
1197
- baseAssetAmountLong: BN;
1198
- /** always non-positive; total short open interest across all users, BASE_PRECISION (1e9) */
1199
- baseAssetAmountShort: BN;
1200
- /** sum of all users' `PerpPosition.quoteAssetAmount` in this market, QUOTE_PRECISION (1e6) */
1201
- quoteAssetAmount: BN;
1202
- /** QUOTE_PRECISION (1e6) */
1203
- quoteEntryAmountLong: BN;
1204
- /** QUOTE_PRECISION (1e6) */
1205
- quoteEntryAmountShort: BN;
1206
- /** QUOTE_PRECISION (1e6) */
1207
- quoteBreakEvenAmountLong: BN;
1208
- /** QUOTE_PRECISION (1e6) */
1209
- quoteBreakEvenAmountShort: BN;
1210
- /** QUOTE_PRECISION (1e6); accumulated socialized loss paid by users in this market since inception */
1211
- totalSocialLoss: BN;
1212
- /** BASE_PRECISION (1e9); max allowed open interest — trades that would breach this are blocked */
1213
- maxOpenInterest: BN;
1214
- /** FUNDING_RATE_PRECISION (1e9) */
1215
- cumulativeFundingRateLong: BN;
1216
- /** FUNDING_RATE_PRECISION (1e9) */
1217
- cumulativeFundingRateShort: BN;
1218
- /** unit is quote per base, FUNDING_RATE_PRECISION (1e9) */
1219
- lastFundingRate: BN;
1220
- /** FUNDING_RATE_PRECISION (1e9) */
1221
- lastFundingRateLong: BN;
1222
- /** FUNDING_RATE_PRECISION (1e9) */
1223
- lastFundingRateShort: BN;
1224
- lastFundingRateTs: BN;
1225
- /** unsettled funding pnl across the whole market */
1226
- netUnsettledFundingPnl: BN;
1227
- /** BPS_PRECISION (1e4); dead-zone threshold for the funding premium — mark/oracle spreads within this band add no funding premium */
1228
- fundingClampThreshold: number;
1229
- /** PERCENTAGE_PRECISION (1e6); slope of the funding premium ramp above the dead zone (1.0x = pass shrunk spread through unchanged) */
1230
- fundingRampSlope: number;
1231
- /** orders must be a multiple of this, BASE_PRECISION (1e9) */
1232
- orderStepSize: BN;
1233
- /** orders must be a multiple of this, PRICE_PRECISION (1e6) */
1234
- orderTickSize: BN;
1235
- };
1236
-
1237
- /** Oracle price/TWAP snapshot shared by `PerpMarketAccount.marketStats` and `SpotMarketAccount`. All price fields are PRICE_PRECISION (1e6). */
1238
- export type HistoricalOracleData = {
1239
- lastOraclePrice: BN;
1240
- /** number of slots since the last oracle update */
1241
- lastOracleDelay: BN;
1242
- lastOracleConf: BN;
1243
- lastOraclePriceTwap: BN;
1244
- lastOraclePriceTwap5Min: BN;
1245
- /** unix timestamp of the last TWAP snapshot */
1246
- lastOraclePriceTwapTs: BN;
1247
- };
1248
-
1249
- /** Rolling index-price stats for a spot market (bid/ask/TWAP of the underlying index, e.g. a basket or peg reference). All price fields are PRICE_PRECISION (1e6). */
1250
- export type HistoricalIndexData = {
1251
- lastIndexBidPrice: BN;
1252
- lastIndexAskPrice: BN;
1253
- lastIndexPriceTwap: BN;
1254
- lastIndexPriceTwap5Min: BN;
1255
- /** unix timestamp of the last TWAP snapshot */
1256
- lastIndexPriceTwapTs: BN;
1257
- };
1258
-
1259
- /** Decoded mirror of the on-chain `SpotMarket` zero-copy account. */
1260
- export type SpotMarketAccount = {
1261
- status: MarketStatus;
1262
- assetTier: AssetTier;
1263
- name: number[];
1264
-
1265
- marketIndex: number;
1266
- pubkey: PublicKey;
1267
- mint: PublicKey;
1268
- /** the market's token vault; balance should be >= `depositBalance` token amount − `borrowBalance` token amount */
1269
- vault: PublicKey;
1270
-
1271
- oracle: PublicKey;
1272
- oracleSource: OracleSource;
1273
- historicalOracleData: HistoricalOracleData;
1274
- historicalIndexData: HistoricalIndexData;
1275
-
1276
- /** covers bankruptcies for borrows of this market's token and perps settling in this market's token */
1277
- insuranceFund: {
1278
- vault: PublicKey;
1279
- totalShares: BN;
1280
- userShares: BN;
1281
- /** exponent used to rebase `totalShares`/`userShares` */
1282
- sharesBase: BN;
1283
- /** seconds a stake must wait after an unstake request before it can be withdrawn */
1284
- unstakingPeriod: BN;
1285
- lastRevenueSettleTs: BN;
1286
- /** seconds; how often `revenuePool` may settle into the IF vault */
1287
- revenueSettlePeriod: BN;
1288
- /** IF_FACTOR_PRECISION (1e6); fraction of spot deposit-interest gains carved out to the (100% staker-owned) insurance fund */
1289
- ifFeeFactor: number;
1290
- };
1291
-
1292
- /** revenue this market's token has collected (e.g. for SOL-PERP, settled funds flow into the USDC revenue pool); SPOT_BALANCE_PRECISION (1e9) scaled balance */
1293
- revenuePool: PoolBalance;
1294
- /** protocol-owned fee claim in this market's token, withdrawn to `StateAccount.protocolFeeRecipientSpot`; SPOT_BALANCE_PRECISION (1e9) scaled balance */
1295
- protocolFeePool: PoolBalance;
1296
-
1297
- /** LIQUIDATOR_FEE_PRECISION (1e6); cut of a liquidation routed to the insurance fund */
1298
- ifLiquidationFee: number;
1299
- /** LIQUIDATOR_FEE_PRECISION (1e6); protocol's cut of a spot liquidation, taken from the liquidatee */
1300
- protocolLiquidationFee: number;
1301
- /** IF_FACTOR_PRECISION (1e6); protocol's carveout of lending deposit-interest gains */
1302
- protocolFeeFactor: number;
1303
-
1304
- /** token mint decimals; token-mint precision throughout this account is 10^decimals */
1305
- decimals: number;
1306
- /** SPOT_UTILIZATION_PRECISION (1e6) */
1307
- optimalUtilization: number;
1308
- /** SPOT_RATE_PRECISION (1e6); borrow rate when the market is at `optimalUtilization` */
1309
- optimalBorrowRate: number;
1310
- /** SPOT_RATE_PRECISION (1e6); borrow rate at 100% utilization */
1311
- maxBorrowRate: number;
1312
- /** SPOT_CUMULATIVE_INTEREST_PRECISION (1e10) */
1313
- cumulativeDepositInterest: BN;
1314
- /** SPOT_CUMULATIVE_INTEREST_PRECISION (1e10) */
1315
- cumulativeBorrowInterest: BN;
1316
- /** token mint precision; accumulated socialized loss from borrows, in this market's own token */
1317
- totalSocialLoss: BN;
1318
- /** QUOTE_PRECISION (1e6); accumulated socialized loss from borrows, converted to quote */
1319
- totalQuoteSocialLoss: BN;
1320
- /** SPOT_BALANCE_PRECISION (1e9) scaled balance; multiply by `cumulativeDepositInterest` for the token amount */
1321
- depositBalance: BN;
1322
- /** SPOT_BALANCE_PRECISION (1e9) scaled balance; multiply by `cumulativeBorrowInterest` for the token amount */
1323
- borrowBalance: BN;
1324
- /** token mint precision; 0 = no limit */
1325
- maxTokenDeposits: BN;
1326
-
1327
- lastInterestTs: BN;
1328
- lastTwapTs: BN;
1329
- /** unix timestamp the market is set to expire; only set if reduce-only */
1330
- expiryTs: BN;
1331
- /** SPOT_WEIGHT_PRECISION (1e4); e.g. 8000 (.8) means $100 of deposits contributes $80 to initial collateral */
1332
- initialAssetWeight: number;
1333
- /** SPOT_WEIGHT_PRECISION (1e4); e.g. 9000 (.9) means $100 of deposits contributes $90 to maintenance collateral */
1334
- maintenanceAssetWeight: number;
1335
- /** SPOT_WEIGHT_PRECISION (1e4); e.g. 9000 (.9) means $100 of borrows contributes $90 to the initial margin requirement */
1336
- initialLiabilityWeight: number;
1337
- /** SPOT_WEIGHT_PRECISION (1e4); e.g. 8000 (.8) means $100 of borrows contributes $80 to the maintenance margin requirement */
1338
- maintenanceLiabilityWeight: number;
1339
- /** LIQUIDATOR_FEE_PRECISION (1e6); fee paid to the liquidator for taking over the borrow/deposit */
1340
- liquidatorFee: number;
1341
- /** MARGIN_PRECISION (1e4); scales liability weight up / asset weight down for large positions */
1342
- imfFactor: number;
1343
- /** QUOTE_PRECISION (1e6); deposit level at which `initialAssetWeight` begins scaling down; 0 = disabled */
1344
- scaleInitialAssetWeightStart: BN;
1345
-
1346
- /** token mint precision; below this vault balance, no withdraw limits/guards apply */
1347
- withdrawGuardThreshold: BN;
1348
- /** token mint precision; 24h rolling average of deposit token amount */
1349
- depositTokenTwap: BN;
1350
- /** token mint precision; 24h rolling average of borrow token amount */
1351
- borrowTokenTwap: BN;
1352
- /** SPOT_UTILIZATION_PRECISION (1e6); 24h rolling average utilization (borrow / total) */
1353
- utilizationTwap: BN;
1354
- nextDepositRecordId: BN;
1355
-
1356
- /** orders must be a multiple of this, token mint precision */
1357
- orderStepSize: BN;
1358
- /** orders must be a multiple of this, PRICE_PRECISION (1e6) */
1359
- orderTickSize: BN;
1360
- /** token mint precision */
1361
- minOrderSize: BN;
1362
- /** token mint precision; 0 = no limit */
1363
- maxPositionSize: BN;
1364
- nextFillRecordId: BN;
1365
- /** fees collected from swaps between this market and the quote market, settled to the quote market's revenue pool; SPOT_BALANCE_PRECISION (1e9) scaled balance */
1366
- spotFeePool: PoolBalance;
1367
- /** QUOTE_PRECISION (1e6) */
1368
- totalSpotFee: BN;
1369
- /** token mint precision; total fees received from swaps */
1370
- totalSwapFee: BN;
1371
-
1372
- /** token mint precision; amount loaned out in `beginSwap`, for the in-flight flash-loan invariant check */
1373
- flashLoanAmount: BN;
1374
- /** token mint precision; user's token balance snapshotted at `beginSwap`, used to compute how much left the system by `endSwap` */
1375
- flashLoanInitialTokenAmount: BN;
1376
-
1377
- ordersEnabled: boolean;
1378
-
1379
- /** bitmask, see `SpotOperation` */
1380
- pausedOperations: number;
1381
-
1382
- /** bitmask, see `InsuranceFundOperation` */
1383
- ifPausedOperations: number;
1384
-
1385
- /** X/10000; fraction of `maxTokenDeposits` that may be borrowed in total; 0 disables the cap */
1386
- maxTokenBorrowsFraction: number;
1387
- /** X/200; floor borrow rate regardless of utilization */
1388
- minBorrowRate: number;
1389
-
1390
- /** bitmask, see `TokenProgramFlag` */
1391
- tokenProgramFlag: number;
1392
-
1393
- poolId: number;
1394
-
1395
- /** -100 to 100; percentage adjustment applied to the base fee rate */
1396
- feeAdjustment: number;
1397
- };
1398
-
1399
- /** A scaled token balance inside a market's internal pools (pnl pool, protocol fee pool, revenue pool, spot fee pool, AMM fee pool). Multiply `scaledBalance` (SPOT_BALANCE_PRECISION, 1e9) by the referenced spot market's `cumulativeDepositInterest`/`cumulativeBorrowInterest` to get the token amount. */
1400
- export type PoolBalance = {
1401
- scaledBalance: BN;
1402
- /** the spot market this balance's token amount is denominated in */
1403
- marketIndex: number;
1404
- };
1405
-
1406
- /**
1407
- * Consolidated per-market fee ledger: lifetime analytics counters plus the pending
1408
- * (not-yet-materialized) protocol/IF/AMM carveouts and the AMM's backstop-of-last-resort
1409
- * clawback cap. All fields are QUOTE_PRECISION (1e6). Pure counters — the actual token claims
1410
- * live in `PerpMarketAccount.protocolFeePool` / `pnlPool` / `AMM.feePool`.
1411
- */
1412
- export type FeeLedger = {
1413
- /** lifetime gross taker fees collected (analytics only, post referee-discount, pre carve-outs) */
1414
- totalExchangeFee: BN;
1415
- /** lifetime liquidation fees charged to liquidatees (IF + protocol cuts; analytics only) */
1416
- totalLiquidationFee: BN;
1417
- /** protocol carveouts accrued but not yet materialized into `protocolFeePool` */
1418
- pendingProtocolFee: BN;
1419
- /** insurance-fund carveouts accrued but not yet materialized into the quote market's revenue pool; also the first bankruptcy tranche */
1420
- pendingIfFee: BN;
1421
- /** cumulative fee provision granted to the AMM as its backstop-of-last-resort tranche; drawable (and decremented) only in bankruptcy */
1422
- ammProtocolFeesReceived: BN;
1423
- /** AMM fee provision accrued at fill but not yet tokenized into `AMM.feePool` by the sweep; always `<= ammProtocolFeesReceived` */
1424
- pendingAmmProvision: BN;
1425
- };
1426
-
1427
- /** Decoded mirror of the on-chain constant-product `AMM` struct embedded in `PerpMarketAccount.amm`. */
1428
- export type AMM = {
1429
- /** partition of fees moved from pnl settlements; SPOT_BALANCE_PRECISION (1e9) scaled balance */
1430
- feePool: PoolBalance;
1431
- /** `x` reserve of the constant-product formula (x*y=k), AMM_RESERVE_PRECISION (1e9) */
1432
- baseAssetReserve: BN;
1433
- /** `y` reserve of the constant-product formula (x*y=k), AMM_RESERVE_PRECISION (1e9) */
1434
- quoteAssetReserve: BN;
1435
- /** PERCENTAGE_PRECISION (1e6); how tightly the min/max reserves bracket the current reserves (lowers slippage without adding liquidity) */
1436
- concentrationCoef: BN;
1437
- /** AMM_RESERVE_PRECISION (1e9); reserve floor below which the AMM is unavailable */
1438
- minBaseAssetReserve: BN;
1439
- /** AMM_RESERVE_PRECISION (1e9); reserve ceiling above which the AMM is unavailable */
1440
- maxBaseAssetReserve: BN;
1441
- /** `sqrt(k)`, AMM_RESERVE_PRECISION (1e9); cached to avoid precision loss recomputing it */
1442
- sqrtK: BN;
1443
- /** normalizes quote reserves for lowest slippage when the market is balanced; PEG_PRECISION (1e6) */
1444
- pegMultiplier: BN;
1445
- /** `y` reserve when the market is balanced, AMM_RESERVE_PRECISION (1e9) */
1446
- terminalQuoteAssetReserve: BN;
1447
- /** net position (longs − shorts) with the AMM as counterparty, BASE_PRECISION (1e9) */
1448
- baseAssetAmountWithAmm: BN;
1449
- /** the AMM's own fee-derived income (provision + spread surplus), QUOTE_PRECISION (1e6) — the market's gross fees are `feeLedger.totalExchangeFee` */
1450
- totalFee: BN;
1451
- /** spread-capture component of `totalFee` (trading profit, not a paid fee), QUOTE_PRECISION (1e6) */
1452
- totalMmFee: BN;
1453
- /** the AMM's equity ledger (retained earnings): fee income + funding/PnL + credits − curve costs − bankruptcy clawbacks; AMM money only, QUOTE_PRECISION (1e6) */
1454
- totalFeeMinusDistributions: BN;
1455
- /** @deprecated frozen pre-isolation analytics counter; nothing writes this anymore. QUOTE_PRECISION (1e6) */
1456
- totalFeeWithdrawn: BN;
1457
- /** cached spread-adjusted ask (long-take) reserve, AMM_RESERVE_PRECISION (1e9) */
1458
- askBaseAssetReserve: BN;
1459
- /** AMM_RESERVE_PRECISION (1e9) */
1460
- askQuoteAssetReserve: BN;
1461
- /** cached spread-adjusted bid (short-take) reserve, AMM_RESERVE_PRECISION (1e9) */
1462
- bidBaseAssetReserve: BN;
1463
- /** AMM_RESERVE_PRECISION (1e9) */
1464
- bidQuoteAssetReserve: BN;
1465
- lastUpdateSlot: BN;
1466
- /** change in `totalFeeMinusDistributions` since the last funding update, QUOTE_PRECISION (1e6) */
1467
- netRevenueSinceLastFunding: BN;
1468
- /** the AMM's last-seen cumulative long funding rate (mirrors `PerpPosition.lastCumulativeFundingRate`), FUNDING_RATE_PRECISION (1e9) */
1469
- lastCumulativeFundingRateLong: BN;
1470
- /** FUNDING_RATE_PRECISION (1e9) */
1471
- lastCumulativeFundingRateShort: BN;
1472
- /** signed, BID_ASK_SPREAD_PRECISION (1e6); cached oracle-vs-reserve price spread feeding `calculate_spread` */
1473
- lastOracleReservePriceSpreadPct: BN;
1474
- lastSpreadUpdateSlot: BN;
1475
- /** BID_ASK_SPREAD_PRECISION (1e6); minimum spread the AMM can quote */
1476
- baseSpread: number;
1477
- /** BID_ASK_SPREAD_PRECISION (1e6); maximum spread the AMM can quote */
1478
- maxSpread: number;
1479
- /** BID_ASK_SPREAD_PRECISION (1e6); cached spread applied to the ask (long-take) side */
1480
- longSpread: number;
1481
- /** BID_ASK_SPREAD_PRECISION (1e6); cached spread applied to the bid (short-take) side */
1482
- shortSpread: number;
1483
- /** signed, PRICE_PRECISION (1e6); cached reference-price offset applied to both sides' quotes */
1484
- referencePriceOffset: number;
1485
- /** fraction of total available liquidity a single AMM fill may consume */
1486
- maxFillReserveFraction: number;
1487
- /** maximum slippage ratio a single AMM fill may push */
1488
- maxSlippageRatio: number;
1489
- /** 0-100; intensity of the AMM's formulaic `k` updates */
1490
- curveUpdateIntensity: number;
1491
- /** 0 = no AMM JIT participation, (0,100] = intensity of protocol-owned-AMM JIT participation */
1492
- ammJitIntensity: number;
1493
- /** signed, -100 = 0x scale, 100 = 2x scale, applied to the computed spread */
1494
- ammSpreadAdjustment: number;
1495
- /** signed, -100 = 0x scale, 100 = 2x scale, applied to the inventory-skew component of the spread */
1496
- ammInventorySpreadAdjustment: number;
1497
- referencePriceOffsetDeadbandPct: number;
1498
- /** stored in hundredths (value/100); how much the paying side's spread widens while the AMM pays funding on its inventory — 50 => 1.5x, 100 => 2x, 0 disables the bias */
1499
- fundingBiasSensitivity: number;
1500
- };
1501
-
1502
- /** Market-wide stats shared across all makers (vAMM, DLOB resting orders, JIT participants), updated on every fill regardless of which maker filled. */
1503
- export type MarketStats = {
1504
- /** average (bid+ask)/2 price over `fundingPeriod`, PRICE_PRECISION (1e6) */
1505
- lastMarkPriceTwap: BN;
1506
- /** average (bid+ask)/2 price over 5 minutes, PRICE_PRECISION (1e6) */
1507
- lastMarkPriceTwap5Min: BN;
1508
- lastMarkPriceTwapTs: BN;
1509
- /** PRICE_PRECISION (1e6) */
1510
- lastBidPriceTwap: BN;
1511
- /** PRICE_PRECISION (1e6) */
1512
- lastAskPriceTwap: BN;
1513
- /** standard deviation of fill (mark) prices, PRICE_PRECISION (1e6) */
1514
- markStd: BN;
1515
- /** standard deviation of the oracle price at each update, PRICE_PRECISION (1e6) */
1516
- oracleStd: BN;
1517
- /** PERCENTAGE_PRECISION (1e6); size of the oracle confidence interval as a fraction of price */
1518
- lastOracleConfPct: BN;
1519
- /** QUOTE_PRECISION (1e6); estimated total volume traded in the market */
1520
- volume24H: BN;
1521
- longIntensityVolume: BN;
1522
- shortIntensityVolume: BN;
1523
- lastTradeTs: BN;
1524
- /** unit is quote per base, QUOTE_PRECISION (1e6); estimate of the last 24h average funding rate */
1525
- last24HAvgFundingRate: BN;
1526
- /** seconds; periodicity of funding rate updates */
1527
- fundingPeriod: BN;
1528
- /** BASE_PRECISION (1e9); minimum order size, mirrored here from `PerpMarketAccount` config so the AMM can read it without touching the market's other fields */
1529
- minOrderSize: BN;
1530
- /** market-maker oracle price snapshot set by the native `updateMmOracle` handler */
1531
- mmOraclePrice: BN;
1532
- mmOracleSlot: BN;
1533
- /** monotonically increasing; guards against out-of-order mm-oracle updates */
1534
- mmOracleSequenceId: BN;
1535
- /** canonical sanitised/clamped oracle price after normalisation */
1536
- lastOracleNormalisedPrice: BN;
1537
- /** PRICE_PRECISION (1e6); reference-price offset from the previous `_update_amm` call, used to smooth the sign-flip transition when the freshly computed offset changes direction */
1538
- lastReferencePriceOffset: number;
1539
- lastOracleValid: boolean;
1540
- /** unit is quote per base, QUOTE_PRECISION (1e6); oracle TWAP snapshot used by the funding-rate computation */
1541
- lastFundingOracleTwap: BN;
1542
- historicalOracleData: HistoricalOracleData;
1543
- };
1544
-
1545
- // # User Account Types
1546
- /** A user's position in one perp market. Decoded mirror of the on-chain `PerpPosition`. */
1547
- export type PerpPosition = {
1548
- /** signed size of the position, BASE_PRECISION (1e9) */
1549
- baseAssetAmount: BN;
1550
- /** the market's last cumulative funding rate this position has settled against, FUNDING_RATE_PRECISION (1e9) */
1551
- lastCumulativeFundingRate: BN;
1552
- marketIndex: number;
1553
- /** used to calculate pnl; updated on open/close/settle, includes fees/funding, QUOTE_PRECISION (1e6) */
1554
- quoteAssetAmount: BN;
1555
- /** quote the position was entered with (base * avg entry price), excludes fees/funding, QUOTE_PRECISION (1e6) */
1556
- quoteEntryAmount: BN;
1557
- /** quote needed to exit at breakeven, includes fees/funding, QUOTE_PRECISION (1e6) */
1558
- quoteBreakEvenAmount: BN;
1559
- openOrders: number;
1560
- /** size of non-reduce-only bids resting/triggering against this position, BASE_PRECISION (1e9) */
1561
- openBids: BN;
1562
- /** size of non-reduce-only asks resting/triggering against this position, BASE_PRECISION (1e9) */
1563
- openAsks: BN;
1564
- /** cumulative pnl settled in this market since the position was opened, QUOTE_PRECISION (1e6) */
1565
- settledPnl: BN;
1566
- /** TODO: remove this field - it doesn't exist on chain */
1567
- remainderBaseAssetAmount: number;
1568
- /** MARGIN_PRECISION (1e4); custom max margin ratio for this position, 0 = use the market default */
1569
- maxMarginRatio: number;
1570
- /** bitmask, see `PositionFlag` */
1571
- positionFlag: number;
1572
- /** SPOT_BALANCE_PRECISION (1e9) scaled balance backing this position when it is isolated-margin (`PositionFlag.IsolatedPosition` set) */
1573
- isolatedPositionScaledBalance: BN;
1574
- };
1575
-
1576
- /** Decoded mirror of the on-chain `UserStats` account: authority-level (cross-sub-account) rolling volume, fee, and referral stats. */
1577
- export type UserStatsAccount = {
1578
- numberOfSubAccounts: number;
1579
- /** can exceed `numberOfSubAccounts` if sub-accounts were deleted */
1580
- numberOfSubAccountsCreated: number;
1581
- /** rolling 30-day maker volume, QUOTE_PRECISION (1e6) */
1582
- makerVolume30D: BN;
1583
- /** rolling 30-day taker volume, QUOTE_PRECISION (1e6) */
1584
- takerVolume30D: BN;
1585
- /** rolling 30-day filler (keeper) volume, QUOTE_PRECISION (1e6) */
1586
- fillerVolume30D: BN;
1587
- lastMakerVolume30DTs: BN;
1588
- lastTakerVolume30DTs: BN;
1589
- lastFillerVolume30DTs: BN;
1590
- fees: {
1591
- /** total taker fees paid, QUOTE_PRECISION (1e6) */
1592
- totalFeePaid: BN;
1593
- /** total maker rebate received, QUOTE_PRECISION (1e6) */
1594
- totalFeeRebate: BN;
1595
- /** total discount from holding the discount token, QUOTE_PRECISION (1e6) */
1596
- totalTokenDiscount: BN;
1597
- /** total discount from being a referred user, QUOTE_PRECISION (1e6) */
1598
- totalRefereeDiscount: BN;
1599
- };
1600
- referrer: PublicKey;
1601
- /** bitmask, see `ReferrerStatus` */
1602
- referrerStatus: number;
1603
- disableUpdatePerpBidAskTwap: number;
1604
- /** bitmask, see `UserStatsPausedOperation` */
1605
- pausedOperations: number;
1606
- authority: PublicKey;
1607
- ifStakedQuoteAssetAmount: BN;
1608
- delegatePermissions: number;
1609
- };
1610
-
1611
- /** Decoded mirror of the on-chain `User` (sub-account) zero-copy account. */
1612
- export type UserAccount = {
1613
- authority: PublicKey;
1614
- /** address that can control the account on the authority's behalf; limited power, cannot withdraw */
1615
- delegate: PublicKey;
1616
- name: number[];
1617
- subAccountId: number;
1618
- spotPositions: SpotPosition[];
1619
- perpPositions: PerpPosition[];
1620
- orders: Order[];
1621
- /** bitmask, see `UserStatus` */
1622
- status: number;
1623
- nextLiquidationId: number;
1624
- nextOrderId: number;
1625
- /** MARGIN_PRECISION (1e4); custom max initial margin ratio for the whole account, 0 = use market defaults */
1626
- maxMarginRatio: number;
1627
- /** fees (taker fee, maker rebate, referrer reward, filler reward) and pnl for perps, QUOTE_PRECISION (1e6) */
1628
- settledPerpPnl: BN;
1629
- /** QUOTE_PRECISION (1e6) */
1630
- totalDeposits: BN;
1631
- /** QUOTE_PRECISION (1e6) */
1632
- totalWithdraws: BN;
1633
- /** QUOTE_PRECISION (1e6) */
1634
- totalSocialLoss: BN;
1635
- /** cumulative funding paid/received across perps, QUOTE_PRECISION (1e6) */
1636
- cumulativePerpFunding: BN;
1637
- /** fees (taker fee, maker rebate, filler reward) for spot, QUOTE_PRECISION (1e6) */
1638
- cumulativeSpotFees: BN;
1639
- /** QUOTE_PRECISION (1e6); margin freed so far during an in-progress liquidation (spreads the liquidation over time); 0 when not being liquidated */
1640
- liquidationMarginFreed: BN;
1641
- lastActiveSlot: BN;
1642
- isMarginTradingEnabled: boolean;
1643
- /** true if the account hasn't interacted with the protocol in ~1 week and has no orders/positions/borrows; off-chain keepers may ignore idle accounts */
1644
- idle: boolean;
1645
- openOrders: number;
1646
- hasOpenOrder: boolean;
1647
- openAuctions: number;
1648
- hasOpenAuction: boolean;
1649
- poolId: number;
1650
- /** bitmask, see `SpecialUserStatus` */
1651
- specialUserStatus: number;
1652
- };
1653
-
1654
- /** A user's balance in one spot market. Decoded mirror of the on-chain `SpotPosition`. */
1655
- export type SpotPosition = {
1656
- marketIndex: number;
1657
- balanceType: SpotBalanceType;
1658
- /** SPOT_BALANCE_PRECISION (1e9) scaled balance; multiply by the spot market's cumulative deposit/borrow interest for the token amount */
1659
- scaledBalance: BN;
1660
- openOrders: number;
1661
- /** size of non-reduce-only bids resting/triggering, token mint precision */
1662
- openBids: BN;
1663
- /** size of non-reduce-only asks resting/triggering, token mint precision */
1664
- openAsks: BN;
1665
- /** cumulative deposits/borrows into this market, token mint precision */
1666
- cumulativeDeposits: BN;
1667
- };
1668
-
1669
- /** Decoded mirror of an on-chain `Order` slot inside `UserAccount.orders`. */
1670
- export type Order = {
1671
- status: OrderStatus;
1672
- orderType: OrderType;
1673
- marketType: MarketType;
1674
- slot: BN;
1675
- orderId: number;
1676
- userOrderId: number;
1677
- marketIndex: number;
1678
- /** the limit price; can be 0 for market orders. For orders with an auction, unused until the auction completes. PRICE_PRECISION (1e6) */
1679
- price: BN;
1680
- /** perp: BASE_PRECISION (1e9); spot: token mint precision */
1681
- baseAssetAmount: BN;
1682
- /** perp: BASE_PRECISION (1e9); spot: token mint precision */
1683
- baseAssetAmountFilled: BN;
1684
- /** QUOTE_PRECISION (1e6) */
1685
- quoteAssetAmountFilled: BN;
1686
- direction: PositionDirection;
1687
- reduceOnly: boolean;
1688
- /** price at which the order becomes active; only relevant for trigger orders, PRICE_PRECISION (1e6) */
1689
- triggerPrice: BN;
1690
- triggerCondition: OrderTriggerCondition;
1691
- /** the user's position direction when this order was placed */
1692
- existingPositionDirection: PositionDirection;
1693
- postOnly: boolean;
1694
- /** must be canceled the same slot it's placed if not fully filled */
1695
- immediateOrCancel: boolean;
1696
- /** if set, the limit price is `oraclePrice + oraclePriceOffset`; PRICE_PRECISION (1e6), signed */
1697
- oraclePriceOffset: BN;
1698
- /** slots the auction lasts; only relevant for market/oracle orders */
1699
- auctionDuration: number;
1700
- /** PRICE_PRECISION (1e6), signed; only relevant for market/oracle orders */
1701
- auctionStartPrice: BN;
1702
- /** PRICE_PRECISION (1e6), signed; only relevant for market/oracle orders */
1703
- auctionEndPrice: BN;
1704
- /** unix timestamp after which the order expires */
1705
- maxTs: BN;
1706
- /** bitmask, see `OrderBitFlag` */
1707
- bitFlags: number;
1708
- /** low 8 bits of the slot the order was posted on-chain (not the order's `slot` field for signed-msg orders) */
1709
- postedSlotTail: number;
1710
- };
1711
-
1712
- /** Instruction-parameter shape for placing an order (perp or spot). Optional fields default to `null`/unset on-chain unless noted. */
1713
- export type OrderParams = {
1714
- orderType: OrderType;
1715
- marketType: MarketType;
1716
- userOrderId: number;
1717
- direction: PositionDirection;
1718
- /** perp: BASE_PRECISION (1e9); spot: token mint precision */
1719
- baseAssetAmount: BN;
1720
- /** limit price, PRICE_PRECISION (1e6); 0 for market orders */
1721
- price: BN;
1722
- marketIndex: number;
1723
- reduceOnly: boolean;
1724
- postOnly: PostOnlyParams;
1725
- /** bitmask, see `OrderParamsBitFlag` (distinct from the on-chain `Order.bitFlags` set of flags) */
1726
- bitFlags: number;
1727
- /** PRICE_PRECISION (1e6); only used for trigger orders */
1728
- triggerPrice: BN | null;
1729
- triggerCondition: OrderTriggerCondition;
1730
- /** signed offset from the oracle price, PRICE_PRECISION (1e6); when set, the order's effective limit price tracks the oracle */
1731
- oraclePriceOffset: BN | null;
1732
- /** slots; only used for market/oracle orders */
1733
- auctionDuration: number | null;
1734
- /** unix timestamp after which the order expires */
1735
- maxTs: BN | null;
1736
- /** PRICE_PRECISION (1e6) or oracle-offset units depending on the order, signed; only used for market/oracle orders */
1737
- auctionStartPrice: BN | null;
1738
- /** PRICE_PRECISION (1e6) or oracle-offset units depending on the order, signed; only used for market/oracle orders */
1739
- auctionEndPrice: BN | null;
1740
- /** index into the placing user's RevenueShareEscrow.approved_builders list (non-swift builder codes) */
1741
- builderIdx?: number | null;
1742
- /** builder fee on this order, in tenths of a bps, e.g. 100 = 0.01% */
1743
- builderFeeTenthBps?: number | null;
1744
- };
1745
-
1746
- /** Whether/how an order must avoid taking liquidity. `MUST_POST_ONLY` reverts the transaction if the order would cross; `TRY_POST_ONLY` silently drops the order instead of reverting; `SLIDE` adjusts the price to make it post-only. */
1747
- export class PostOnlyParams {
1748
- static readonly NONE = { none: {} };
1749
- static readonly MUST_POST_ONLY = { mustPostOnly: {} }; // Tx fails if order can't be post only
1750
- static readonly TRY_POST_ONLY = { tryPostOnly: {} }; // Tx succeeds and order not placed if can't be post only
1751
- static readonly SLIDE = { slide: {} }; // Modify price to be post only if can't be post only
1752
- }
1753
-
1754
- /**
1755
- * How to distribute order sizes across scale orders
1756
- */
1757
- export class SizeDistribution {
1758
- static readonly FLAT = { flat: {} }; // Equal size for all orders
1759
- static readonly ASCENDING = { ascending: {} }; // Smallest at start price, largest at end price
1760
- static readonly DESCENDING = { descending: {} }; // Largest at start price, smallest at end price
1761
- }
1762
-
1763
- /**
1764
- * Parameters for placing scale orders - multiple limit orders distributed across a price range
1765
- */
1766
- export type ScaleOrderParams = {
1767
- marketType: MarketType;
1768
- direction: PositionDirection;
1769
- marketIndex: number;
1770
- /** Total base asset amount to distribute across all orders */
1771
- totalBaseAssetAmount: BN;
1772
- /** Starting price for the scale (in PRICE_PRECISION) */
1773
- startPrice: BN;
1774
- /** Ending price for the scale (in PRICE_PRECISION) */
1775
- endPrice: BN;
1776
- /** Number of orders to place (min 2, max 32). User cannot exceed 32 total open orders. */
1777
- orderCount: number;
1778
- /** How to distribute sizes across orders */
1779
- sizeDistribution: SizeDistribution;
1780
- /** Whether orders should be reduce-only */
1781
- reduceOnly: boolean;
1782
- /** Post-only setting for all orders */
1783
- postOnly: PostOnlyParams;
1784
- /** Bit flags (e.g., for high leverage mode) */
1785
- bitFlags: number;
1786
- /** Maximum timestamp for orders to be valid */
1787
- maxTs: BN | null;
1788
- };
1789
-
1790
- /** Bitmask mirror of `OrderParams.bitFlags` (the instruction-parameter flag set; distinct from the on-chain `Order.bitFlags` set of `OrderBitFlag`). */
1791
- export class OrderParamsBitFlag {
1792
- static readonly ImmediateOrCancel = 1;
1793
- }
1794
-
1795
- /** Bitmask mirror of `PerpPosition.positionFlag`. Multiple bits can be set (e.g. an isolated position mid-liquidation has both `IsolatedPosition` and `BeingLiquidated`). */
1796
- export class PositionFlag {
1797
- static readonly IsolatedPosition = 1;
1798
- static readonly BeingLiquidated = 2;
1799
- static readonly Bankruptcy = 4;
1800
- }
1801
-
1802
- /** The subset of `OrderParams` an SDK caller must always supply; everything else can be defaulted. */
1803
- export type NecessaryOrderParams = {
1804
- orderType: OrderType;
1805
- marketIndex: number;
1806
- baseAssetAmount: BN;
1807
- direction: PositionDirection;
1808
- };
1809
-
1810
- /** `OrderParams` with every field optional except `NecessaryOrderParams`; SDK order-placement helpers fill in the rest from `DefaultOrderParams`. */
1811
- export type OptionalOrderParams = {
1812
- [Property in keyof OrderParams]?: OrderParams[Property];
1813
- } & NecessaryOrderParams;
1814
-
1815
- /** Fields to change on an existing order via `modifyOrder`. Only the fields present (non-`undefined`) are changed on-chain; the rest of the order is left as-is. `null` explicitly clears an optional on-chain field (e.g. `triggerPrice: null` removes the trigger). */
1816
- export type ModifyOrderParams = {
1817
- [Property in keyof OrderParams]?: OrderParams[Property] | null;
1818
- } & { policy?: ModifyOrderPolicy | null };
1819
-
1820
- /** Bitmask passed as `ModifyOrderParams.policy` (combine with `|`). `MustModify`: fail the instruction instead of silently no-op'ing if the target order id can't be found. `ExcludePreviousFill`: when a new `baseAssetAmount` is given, treat it as the new *remaining* size — the already-filled amount is subtracted off it (rather than replacing the order's total size outright). */
1821
- export enum ModifyOrderPolicy {
1822
- MustModify = 1,
1823
- ExcludePreviousFill = 2,
1824
- }
1825
-
1826
- /** Base `OrderParams` (a market perp long of size 0) that SDK order-building helpers spread their caller-supplied `OptionalOrderParams` over. */
1827
- export const DefaultOrderParams: OrderParams = {
1828
- orderType: OrderType.MARKET,
1829
- marketType: MarketType.PERP,
1830
- userOrderId: 0,
1831
- direction: PositionDirection.LONG,
1832
- baseAssetAmount: ZERO,
1833
- price: ZERO,
1834
- marketIndex: 0,
1835
- reduceOnly: false,
1836
- postOnly: PostOnlyParams.NONE,
1837
- bitFlags: 0,
1838
- triggerPrice: null,
1839
- triggerCondition: OrderTriggerCondition.ABOVE,
1840
- oraclePriceOffset: null,
1841
- auctionDuration: null,
1842
- maxTs: null,
1843
- auctionStartPrice: null,
1844
- auctionEndPrice: null,
1845
- builderIdx: null,
1846
- builderFeeTenthBps: null,
1847
- };
1848
-
1849
- /** The payload signed off-chain by a user (non-delegated) for a swift/signed-msg order, optionally bundling bracket TP/SL orders and an isolated-margin deposit. */
1850
- export type SignedMsgOrderParamsMessage = {
1851
- signedMsgOrderParams: OrderParams;
1852
- subAccountId: number;
1853
- /** slot the message was signed at; combined with `signedMsgOrderMaxSlot`-style checks to bound message validity */
1854
- slot: BN;
1855
- uuid: Uint8Array;
1856
- takeProfitOrderParams: SignedMsgTriggerOrderParams | null;
1857
- stopLossOrderParams: SignedMsgTriggerOrderParams | null;
1858
- /** MARGIN_PRECISION (1e4); custom max margin ratio applied to the resulting position, if any */
1859
- maxMarginRatio?: number | null;
1860
- builderIdx?: number | null;
1861
- /** builder fee on this order, in tenths of a bps, e.g. 100 = 0.01% */
1862
- builderFeeTenthBps?: number | null;
1863
- /** if set, deposits this amount (spot market token-mint precision) into a new isolated-margin position when placing the order */
1864
- isolatedPositionDeposit?: BN | null;
1865
- };
1866
-
1867
- /** Same as `SignedMsgOrderParamsMessage`, but signed by a delegate on the taker's behalf; carries `takerPubkey` explicitly since the signer isn't the taker's own authority. */
1868
- export type SignedMsgOrderParamsDelegateMessage = {
1869
- signedMsgOrderParams: OrderParams;
1870
- slot: BN;
1871
- uuid: Uint8Array;
1872
- takerPubkey: PublicKey;
1873
- takeProfitOrderParams: SignedMsgTriggerOrderParams | null;
1874
- stopLossOrderParams: SignedMsgTriggerOrderParams | null;
1875
- maxMarginRatio?: number | null;
1876
- builderIdx?: number | null;
1877
- builderFeeTenthBps?: number | null;
1878
- isolatedPositionDeposit?: BN | null;
1879
- };
1880
-
1881
- /** A bracket take-profit/stop-loss order attached to a signed-msg order message. */
1882
- export type SignedMsgTriggerOrderParams = {
1883
- /** PRICE_PRECISION (1e6) */
1884
- triggerPrice: BN;
1885
- /** perp: BASE_PRECISION (1e9); spot: token mint precision */
1886
- baseAssetAmount: BN;
1887
- };
1888
-
1889
- /** Identifies a resting maker order/account to pass into a fill instruction's remaining accounts. `order` may be omitted when the whole account (not one specific order) is being matched against, e.g. AMM-JIT. */
1890
- export type MakerInfo = {
1891
- maker: PublicKey;
1892
- makerStats: PublicKey;
1893
- makerUserAccount: UserAccount;
1894
- order?: Order;
1895
- };
1896
-
1897
- /** Identifies the taker order/account being filled, for fill instructions. */
1898
- export type TakerInfo = {
1899
- taker: PublicKey;
1900
- takerStats: PublicKey;
1901
- takerUserAccount: UserAccount;
1902
- order: Order;
1903
- };
1904
-
1905
- /** Referrer accounts to pass into an instruction so the referrer's reward can be credited. */
1906
- export type ReferrerInfo = {
1907
- referrer: PublicKey;
1908
- referrerStats: PublicKey;
1909
- };
1910
-
1911
- /** Bitmask mirror of `UserStatsAccount.referrerStatus`. */
1912
- export enum ReferrerStatus {
1913
- IsReferrer = 1,
1914
- IsReferred = 2,
1915
- /** set when the user's RevenueShareEscrow was initialized with a referrer */
1916
- BuilderReferral = 4,
1917
- }
1918
-
1919
- /** Which fill outcome counts as "success" for a `placeAndTake*` instruction's on-chain success check. */
1920
- export enum PlaceAndTakeOrderSuccessCondition {
1921
- PartialFill = 1,
1922
- FullFill = 2,
1923
- }
1924
-
1925
- type ExactType<T> = Pick<T, keyof T>;
1926
-
1927
- /** Compute-budget overrides accepted by SDK transaction-building helpers. Omit either field to let the SDK compute/skip it. */
1928
- export type BaseTxParams = ExactType<{
1929
- /** explicit compute-unit limit to request; if omitted, may be derived via simulation (see `ProcessingTxParams`) */
1930
- computeUnits?: number;
1931
- /** micro-lamports per compute unit for the priority fee */
1932
- computeUnitsPrice?: number;
1933
- }>;
1934
-
1935
- /** Controls how the SDK derives compute-unit limit/price when not explicitly given in `BaseTxParams`. */
1936
- export type ProcessingTxParams = {
1937
- /** simulate the transaction to determine the compute-unit limit instead of using a static estimate */
1938
- useSimulatedComputeUnits?: boolean;
1939
- /** multiplier applied to the simulated/estimated compute-unit count to leave headroom, e.g. 1.2 = +20% */
1940
- computeUnitsBufferMultiplier?: number;
1941
- /** also use the simulated compute-unit count (rather than the static estimate) as the basis for `getCUPriceFromComputeUnits` */
1942
- useSimulatedComputeUnitsForCUPriceCalculation?: boolean;
1943
- /** custom function mapping a compute-unit count to a compute-unit price (micro-lamports); overrides `computeUnitsPrice` */
1944
- getCUPriceFromComputeUnits?: (computeUnits: number) => number;
1945
- /** floor applied to the computed/simulated compute-unit count before requesting a limit */
1946
- lowerBoundCu?: number;
1947
- };
1948
-
1949
- /** Combined compute-budget + compute-unit-derivation options accepted by SDK transaction-building helpers. */
1950
- export type TxParams = BaseTxParams & ProcessingTxParams;
1951
-
1952
- /** For `beginSwap`/`endSwap`, whether the reduce-only constraint applies to the `In` (source) or `Out` (destination) side of the swap. */
1953
- export class SwapReduceOnly {
1954
- static readonly In = { in: {} };
1955
- static readonly Out = { out: {} };
1956
- }
1957
-
1958
- // # Misc Types
1959
- /** Minimal wallet adapter the SDK requires for legacy (non-versioned) transaction signing. */
1960
- export interface IWallet {
1961
- signTransaction(tx: Transaction): Promise<Transaction>;
1962
- signAllTransactions(txs: Transaction[]): Promise<Transaction[]>;
1963
- publicKey: PublicKey;
1964
- payer?: Keypair;
1965
- supportedTransactionVersions?:
1966
- | ReadonlySet<TransactionVersion>
1967
- | null
1968
- | undefined;
1969
- }
1970
- /** Wallet adapter capable of signing versioned transactions (v0 message format). */
1971
- export interface IVersionedWallet {
1972
- signVersionedTransaction(
1973
- tx: VersionedTransaction
1974
- ): Promise<VersionedTransaction>;
1975
- signAllVersionedTransactions(
1976
- txs: VersionedTransaction[]
1977
- ): Promise<VersionedTransaction[]>;
1978
- publicKey: PublicKey;
1979
- payer?: Keypair;
1980
- }
1981
-
1982
- /** `IWallet` extended with arbitrary-message signing (used for signed-msg/swift order flows). */
1983
- export interface IWalletV2 extends IWallet {
1984
- signMessage(message: Uint8Array): Promise<Uint8Array>;
1985
- }
1986
-
1987
- /** The fee schedule applied to fills in a market category (perp or spot); decoded from `StateAccount.perpFeeStructure`/`spotFeeStructure`. */
1988
- export type FeeStructure = {
1989
- /** volume-based fee tiers, evaluated by the taker's 30-day volume; tier 0 is the base/default tier */
1990
- feeTiers: FeeTier[];
1991
- fillerRewardStructure: OrderFillerRewardStructure;
1992
- /** flat portion of the filler (keeper) reward, QUOTE_PRECISION (1e6) */
1993
- flatFillerFee: BN;
1994
- /** FEE_PERCENTAGE_DENOMINATOR (100)-denominated share of the trade-fee remainder provisioned to the AMM as its backstop-of-last-resort tranche; `ammFeeNumerator + ifFeeNumerator` must be <= 100, the protocol keeps the residual */
1995
- ammFeeNumerator: number;
1996
- /** FEE_PERCENTAGE_DENOMINATOR (100)-denominated share of the trade-fee remainder routed to the insurance fund */
1997
- ifFeeNumerator: number;
1998
- };
1999
-
2000
- /** One volume tier of a `FeeStructure`. All `*Numerator`/`*Denominator` pairs form a fraction (e.g. `feeNumerator / feeDenominator`). */
2001
- export type FeeTier = {
2002
- /** taker fee rate */
2003
- feeNumerator: number;
2004
- feeDenominator: number;
2005
- /** rebate paid to the resting maker */
2006
- makerRebateNumerator: number;
2007
- makerRebateDenominator: number;
2008
- /** share of the taker fee credited to the taker's referrer */
2009
- referrerRewardNumerator: number;
2010
- referrerRewardDenominator: number;
2011
- /** discount applied to the taker's own fee when they were referred */
2012
- refereeFeeNumerator: number;
2013
- refereeFeeDenominator: number;
2014
- };
2015
-
2016
- /** The reward paid to the keeper (filler) that submits a fill transaction. */
2017
- export type OrderFillerRewardStructure = {
2018
- /** share of the fill's fee/size paid as a variable reward */
2019
- rewardNumerator: number;
2020
- rewardDenominator: number;
2021
- /** QUOTE_PRECISION (1e6); floor below which the time-based reward component doesn't apply */
2022
- timeBasedRewardLowerBound: BN;
2023
- };
2024
-
2025
- /** Protocol-wide oracle safety thresholds (`StateAccount.oracleGuardRails`), gating how far an oracle price may diverge from mark and how stale/uncertain it may be before it's rejected for a given action. */
2026
- export type OracleGuardRails = {
2027
- priceDivergence: {
2028
- /** PERCENTAGE_PRECISION (1e6); max allowed |mark − oracle| / oracle before divergence checks reject the price */
2029
- markOraclePercentDivergence: BN;
2030
- /** PERCENTAGE_PRECISION (1e6); max allowed divergence between the oracle's live price and its 5-minute TWAP */
2031
- oracleTwap5MinPercentDivergence: BN;
2032
- };
2033
- validity: {
2034
- /** slots; oracle updates older than this are stale for AMM-facing actions */
2035
- slotsBeforeStaleForAmm: BN;
2036
- /** slots; oracle updates older than this are stale for margin/liquidation actions */
2037
- slotsBeforeStaleForMargin: BN;
2038
- /** PERCENTAGE_PRECISION (1e6)-scaled fraction of price; oracle confidence intervals wider than this are rejected */
2039
- confidenceIntervalMaxSize: BN;
2040
- /** oracle price moves within one update exceeding this multiple of the recent range are rejected as "too volatile" */
2041
- tooVolatileRatio: BN;
2042
- };
2043
- };
2044
-
2045
- /** Result of the oracle validity check (`is_oracle_valid_for_action` and friends). Only `Valid` (7) permits using the price; every other variant identifies the specific failure so callers can gate accordingly (stale-for-margin still permits AMM-only actions, etc.). */
2046
- export enum OracleValidity {
2047
- NonPositive = 0,
2048
- TooVolatile = 1,
2049
- TooUncertain = 2,
2050
- StaleForMargin = 3,
2051
- InsufficientDataPoints = 4,
2052
- StaleForAMMLowRisk = 5,
2053
- isStaleForAmmImmediate = 6,
2054
- Valid = 7,
2055
- }
2056
-
2057
- /** Decoded mirror of a `PrelaunchOracle` account — an admin-fed synthetic price feed used before a market has a real external oracle (`OracleSource.Prelaunch`). */
2058
- export type PrelaunchOracle = {
2059
- /** PRICE_PRECISION (1e6) */
2060
- price: BN;
2061
- /** PRICE_PRECISION (1e6); ceiling the admin-set price is clamped to */
2062
- maxPrice: BN;
2063
- /** PRICE_PRECISION (1e6) */
2064
- confidence: BN;
2065
- ammLastUpdateSlot: BN;
2066
- lastUpdateSlot: BN;
2067
- perpMarketIndex: number;
2068
- };
2069
-
2070
- /** Admin instruction params for updating a `PrelaunchOracle`; `null` fields leave the current on-chain value unchanged. */
2071
- export type PrelaunchOracleParams = {
2072
- perpMarketIndex: number;
2073
- /** PRICE_PRECISION (1e6) */
2074
- price: BN | null;
2075
- /** PRICE_PRECISION (1e6) */
2076
- maxPrice: BN | null;
2077
- };
2078
-
2079
- /** Decoded mirror of a Pyth Lazer oracle account. `price`/`conf` are in the feed's native `exponent` (a power-of-ten scale factor, typically negative), not a fixed SDK precision — divide by `10^-exponent` to get the human-readable price. */
2080
- export type PythLazerOracle = {
2081
- price: BN;
2082
- publishTime: BN;
2083
- postedSlot: BN;
2084
- exponent: number;
2085
- conf: BN;
2086
- };
2087
-
2088
- /** Admin instruction params for correcting a perp market's cached AMM summary stats; `null` fields leave the current on-chain value unchanged. */
2089
- export type UpdatePerpMarketSummaryStatsParams = {
2090
- /** QUOTE_PRECISION (1e6) */
2091
- netUnsettledFundingPnl: BN | null;
2092
- updateAmmSummaryStats: boolean | null;
2093
- };
2094
-
2095
- /**
2096
- * Which margin requirement a calculation is being performed for, mirroring the program's
2097
- * `MarginRequirementType`: `'Initial'` (opening/maintaining leverage headroom), `'Maintenance'`
2098
- * (liquidation), or `'Fill'` (fill-time check — weights/ratios are the integer-averaged midpoint
2099
- * of initial and maintenance).
2100
- */
2101
- export type MarginCategory = 'Initial' | 'Maintenance' | 'Fill';
2102
-
2103
- /** Decoded mirror of the on-chain `InsuranceFundStake` account: one user's stake in one spot market's insurance fund. */
2104
- export type InsuranceFundStake = {
2105
- /** signed, spot market token-mint precision; tracks the staker's cost basis for pnl reporting */
2106
- costBasis: BN;
2107
-
2108
- marketIndex: number;
2109
- authority: PublicKey;
2110
-
2111
- /** the staker's share count; multiply by the IF's share price to get token value */
2112
- ifShares: BN;
2113
- /** exponent used to rebase `ifShares` in step with `InsuranceFund.sharesBase` */
2114
- ifBase: BN;
2115
- lastValidTs: BN;
2116
-
2117
- lastWithdrawRequestShares: BN;
2118
- /** spot market token-mint precision value of `lastWithdrawRequestShares` at request time */
2119
- lastWithdrawRequestValue: BN;
2120
- lastWithdrawRequestTs: BN;
2121
- };
2122
-
2123
- /** Decoded mirror of a `ReferrerName` account, mapping a human-readable referrer name to its user/authority. */
2124
- export type ReferrerNameAccount = {
2125
- name: number[];
2126
- user: PublicKey;
2127
- authority: PublicKey;
2128
- userStats: PublicKey;
2129
- };
2130
-
2131
- /** SDK-computed convenience summary of a perp market's order-size/margin/insurance limits, derived from `PerpMarketAccount` (not decoded directly from a single on-chain field). */
2132
- export type PerpMarketExtendedInfo = {
2133
- marketIndex: number;
2134
- /**
2135
- * Min order size measured in base asset, using base precision
2136
- */
2137
- minOrderSize: BN;
2138
- /**
2139
- * Margin maintenance percentage, using margin precision (1e4)
2140
- */
2141
- marginMaintenance: number;
2142
- /**
2143
- * Max insurance available, measured in quote asset, using quote preicision
2144
- */
2145
- availableInsurance: BN;
2146
- /**
2147
- * Pnl pool available, this is measured in quote asset, using quote precision.
2148
- * Should be generated by using getTokenAmount and passing in the scaled balance of the base asset + quote spot account
2149
- */
2150
- pnlPoolValue: BN;
2151
- contractTier: ContractTier;
2152
- };
2153
-
2154
- /** SDK-computed breakdown of a user's margin-health calculation, grouped by contribution type; each group is a list of the individual `HealthComponent`s that summed into the account's total collateral/margin requirement. */
2155
- export type HealthComponents = {
2156
- deposits: HealthComponent[];
2157
- borrows: HealthComponent[];
2158
- perpPositions: HealthComponent[];
2159
- perpPnl: HealthComponent[];
2160
- };
2161
-
2162
- /** One market's contribution to a `HealthComponents` group. */
2163
- export type HealthComponent = {
2164
- marketIndex: number;
2165
- /** perp: signed BASE_PRECISION (1e9) position size; spot: signed token-mint-precision balance */
2166
- size: BN;
2167
- /** unweighted USD value, QUOTE_PRECISION (1e6) */
2168
- value: BN;
2169
- /** the asset/liability weight applied, SPOT_WEIGHT_PRECISION or MARGIN_PRECISION (1e4) depending on component type */
2170
- weight: BN;
2171
- /** `value` after applying `weight`, QUOTE_PRECISION (1e6); this is what's actually summed into total collateral/margin requirement */
2172
- weightedValue: BN;
2173
- };
2174
-
2175
- /** Event map for `VelocityClient`'s internal metrics emitter. */
2176
- export interface VelocityClientMetricsEvents {
2177
- txSigned: SignedTxData[];
2178
- preTxSigned: void;
2179
- }
2180
-
2181
- /** A transaction the SDK has signed, returned by transaction-sending helpers before/instead of submission. */
2182
- export type SignedTxData = {
2183
- txSig: string;
2184
- signedTx: Transaction | VersionedTransaction;
2185
- lastValidBlockHeight?: number;
2186
- blockHash: string;
2187
- };
2188
-
2189
- /** Proof of a signed-msg (swift) taker order, submitted to the program to fill it. */
2190
- export interface SignedMsgOrderParams {
2191
- /**
2192
- * The encoded order params that were signed (borsh encoded then hexified).
2193
- */
2194
- orderParams: Buffer;
2195
- /**
2196
- * The signature generated for the orderParams
2197
- */
2198
- signature: Buffer;
2199
- }
2200
-
2201
- /** One slot of a `SignedMsgUserOrdersAccount`, recording a signed-msg order's validity window and dedupe key so a replayed/expired signed message can be rejected without an extra RPC round-trip. */
2202
- export type SignedMsgOrderId = {
2203
- /** slot after which this signed message is no longer eligible to be placed */
2204
- maxSlot: BN;
2205
- uuid: Uint8Array;
2206
- orderId: number;
2207
- };
2208
-
2209
- /** Per-authority account tracking recently-seen signed-msg order UUIDs, used to detect replay/duplicate submission of the same signed message. */
2210
- export type SignedMsgUserOrdersAccount = {
2211
- authorityPubkey: PublicKey;
2212
- signedMsgOrderData: SignedMsgOrderId[];
2213
- };
2214
-
2215
- /** Account listing the delegate keys authorized to submit signed-msg orders over the swift websocket on a user's behalf. */
2216
- export type SignedMsgWsDelegatesAccount = {
2217
- delegates: PublicKey[];
2218
- };
2219
-
2220
- /** Decoded mirror of the on-chain `RevenueShare` account: one per builder/referrer, accumulating their lifetime rewards. */
2221
- export type RevenueShareAccount = {
2222
- /** the builder or referrer that owns this account */
2223
- authority: PublicKey;
2224
- /** QUOTE_PRECISION (1e6) */
2225
- totalReferrerRewards: BN;
2226
- /** QUOTE_PRECISION (1e6) */
2227
- totalBuilderRewards: BN;
2228
- padding: number[];
2229
- };
2230
-
2231
- /** Decoded mirror of the on-chain `RevenueShareEscrow` account: one per trading user, holding their referrer link, approved builder codes, and in-flight per-order fee accruals awaiting settlement. Required in remaining accounts when filling an order with a builder code or a referred taker (see `TakerInfo`/fill-instruction docs). */
2232
- export type RevenueShareEscrowAccount = {
2233
- /** the user that owns this escrow */
2234
- authority: PublicKey;
2235
- referrer: PublicKey;
2236
- reservedFixed: number[];
2237
- /** ring-buffer of in-flight order fee accruals, settled into the builder's/referrer's `RevenueShareAccount` on settle-PnL */
2238
- orders: RevenueShareOrder[];
2239
- /** builders this user has approved to charge a fee, indexed by `builderIdx` on `OrderParams`/`RevenueShareOrder` */
2240
- approvedBuilders: BuilderInfo[];
2241
- };
2242
-
2243
- /** One in-flight order's accrued builder/referral fee inside a `RevenueShareEscrowAccount`. */
2244
- export type RevenueShareOrder = {
2245
- /** QUOTE_PRECISION (1e6); accrued so far for this slot — may include fees from other orders that reused the same slot, not exclusively `orderId` */
2246
- feesAccrued: BN;
2247
- /** the currently-active order's id in this slot; only meaningful while the slot is open */
2248
- orderId: number;
2249
- /** builder fee on this order, in tenths of a bps, e.g. 100 = 0.01% */
2250
- feeTenthBps: number;
2251
- marketIndex: number;
2252
- /** only meaningful while the slot is open */
2253
- subAccountId: number;
2254
- /** index into `RevenueShareEscrowAccount.approvedBuilders` this order's fee settles to; ignored for a referral-only slot */
2255
- builderIdx: number;
2256
- /** bitflags describing slot state (init/open/completed) and whether it holds referral rewards rather than a builder fee */
2257
- bitFlags: number;
2258
- userOrderIndex: number;
2259
- marketType: MarketType;
2260
- padding: number[];
2261
- };
2262
-
2263
- /** One builder a user has approved to charge a fee on their orders, inside `RevenueShareEscrowAccount.approvedBuilders`. */
2264
- export type BuilderInfo = {
2265
- /** the builder's authority */
2266
- authority: PublicKey;
2267
- /** ceiling on the fee (tenths of a bps) this builder may charge; `0` means the approval has been revoked */
2268
- maxFeeTenthBps: number;
2269
- padding: number[];
2270
- };
2271
-
2272
- /** Emitted when a perp market's fee-ledger pendings are swept into their durable homes (protocol fee pool, quote market revenue pool, AMM fee pool). */
2273
- export type PerpMarketFeeSweepRecord = {
2274
- ts: BN;
2275
- marketIndex: number;
2276
- /** pending insurance cut moved to the quote spot market's revenue pool, QUOTE_PRECISION (1e6) */
2277
- ifSwept: BN;
2278
- /** pending protocol cut moved to the market's protocol fee pool, QUOTE_PRECISION (1e6) */
2279
- protocolSwept: BN;
2280
- /** AMM fee provision (booked at fill) tokenized into `AMM.feePool`, QUOTE_PRECISION (1e6) */
2281
- ammProvisionTokenized: BN;
2282
- };
2283
-
2284
- /** Emitted when `coldAdmin` withdraws accumulated protocol fees to the configured recipient. */
2285
- export type ProtocolFeeWithdrawRecord = {
2286
- ts: BN;
2287
- /** perp market index for a perp-fee withdrawal, else the spot market index */
2288
- marketIndex: number;
2289
- /** true if this withdrawal drained a perp market's `protocolFeePool` (sourced from the quote spot vault); false for a spot market withdrawal */
2290
- isPerp: boolean;
2291
- /** the spot market the tokens were drawn from */
2292
- spotMarketIndex: number;
2293
- /** spot market token-mint precision */
2294
- amount: BN;
2295
- recipientTokenAccount: PublicKey;
2296
- };
2297
-
2298
- /** Emitted when a builder's/referrer's accrued `RevenueShareOrder` fees are settled into their `RevenueShareAccount`. */
2299
- export type RevenueShareSettleRecord = {
2300
- ts: BN;
2301
- /** set when this settle paid a builder fee */
2302
- builder: PublicKey | null;
2303
- /** set when this settle paid a referral reward */
2304
- referrer: PublicKey | null;
2305
- /** QUOTE_PRECISION (1e6) */
2306
- feeSettled: BN;
2307
- marketIndex: number;
2308
- marketType: MarketType;
2309
- /** the builder's `RevenueShareAccount.totalReferrerRewards` after this settle, QUOTE_PRECISION (1e6) */
2310
- builderTotalReferrerRewards: BN;
2311
- /** the builder's `RevenueShareAccount.totalBuilderRewards` after this settle, QUOTE_PRECISION (1e6) */
2312
- builderTotalBuilderRewards: BN;
2313
- builderSubAccountId: number;
2314
- };
2315
-
2316
- /** Admin instruction params to add one constituent's weight in a perp market's AMM constituent mapping (used to route hedge flow). */
2317
- export type AddAmmConstituentMappingDatum = {
2318
- constituentIndex: number;
2319
- perpMarketIndex: number;
2320
- /** PERCENTAGE_PRECISION (1e6) */
2321
- weight: BN;
2322
- };
2323
-
2324
- /** One entry of an `AmmConstituentMapping`, weighting how much of a perp market's hedge flow routes to a given LP-pool constituent. */
2325
- export type AmmConstituentDatum = AddAmmConstituentMappingDatum & {
2326
- lastSlot: BN;
2327
- };
2328
-
2329
- /** Decoded mirror of the `AmmConstituentMapping` account: which LP-pool constituents each perp market hedges into, and by how much. */
2330
- export type AmmConstituentMapping = {
2331
- lpPool: PublicKey;
2332
- bump: number;
2333
- weights: AmmConstituentDatum[];
2334
- };
2335
-
2336
- /** One perp market's target-hedge-position entry inside a `ConstituentTargetBaseAccount`. */
2337
- export type TargetDatum = {
2338
- /** bps; estimated cost to trade into/out of the target position */
2339
- costToTradeBps: number;
2340
- lastOracleSlot: BN;
2341
- lastPositionSlot: BN;
2342
- /** BASE_PRECISION (1e9); the target hedge position size */
2343
- targetBase: BN;
2344
- };
2345
-
2346
- /** Decoded mirror of the `ConstituentTargetBase` account: the LP pool's per-perp-market target hedge positions. */
2347
- export type ConstituentTargetBaseAccount = {
2348
- lpPool: PublicKey;
2349
- bump: number;
2350
- targets: TargetDatum[];
2351
- };
2352
-
2353
- /** Decoded mirror of the `ConstituentCorrelations` account: pairwise correlation coefficients between an LP pool's constituents, used in swap-fee pricing. */
2354
- export type ConstituentCorrelations = {
2355
- lpPool: PublicKey;
2356
- bump: number;
2357
- /** PERCENTAGE_PRECISION (1e6), signed; flattened row-major correlation matrix */
2358
- correlations: BN[];
2359
- };
2360
-
2361
- /** Decoded mirror of the on-chain `LPPool` account: a hedging vault that mints/redeems LP tokens against a basket of spot-market constituents and hedges perp-market exposure. */
2362
- export type LPPoolAccount = {
2363
- lpPoolId: number;
2364
- pubkey: PublicKey;
2365
- /** the LP token mint */
2366
- mint: PublicKey;
2367
- whitelistMint: PublicKey;
2368
- constituentTargetBase: PublicKey;
2369
- constituentCorrelations: PublicKey;
2370
- /** QUOTE_PRECISION (1e6); mint requests that would push AUM above this are rejected */
2371
- maxAum: BN;
2372
- /** QUOTE_PRECISION (1e6); AUM of the vault in USD, updated lazily */
2373
- lastAum: BN;
2374
- /** QUOTE_PRECISION (1e6) */
2375
- cumulativeQuoteSentToPerpMarkets: BN;
2376
- /** QUOTE_PRECISION (1e6) */
2377
- cumulativeQuoteReceivedFromPerpMarkets: BN;
2378
- /** signed, QUOTE_PRECISION (1e6); total fees paid for minting and redeeming LP tokens */
2379
- totalMintRedeemFeesPaid: BN;
2380
- lastAumSlot: BN;
2381
- /** token-mint precision cap on a single settle's quote transfer */
2382
- maxSettleQuoteAmount: BN;
2383
- mintRedeemId: BN;
2384
- settleId: BN;
2385
- /** PERCENTAGE_PRECISION (1e6); floor fee charged on mint/redeem */
2386
- minMintFee: BN;
2387
- /** LP token precision; the LP mint's total supply */
2388
- tokenSupply: BN;
2389
- /** PERCENTAGE_PRECISION (1e6); pool-wide volatility parameter feeding swap-fee/target pricing */
2390
- volatility: BN;
2391
- constituents: number;
2392
- quoteConsituentIndex: number;
2393
- bump: number;
2394
- /** no precision — a raw constant used in swap-fee execution-cost pricing */
2395
- gammaExecution: number;
2396
- /** no precision — a raw constant used in swap-fee pricing */
2397
- xi: number;
2398
- /** bps of fee per 10 slots of oracle-target delay */
2399
- targetOracleDelayFeeBpsPer10Slots: number;
2400
- /** bps of fee per 10 slots of position-target delay */
2401
- targetPositionDelayFeeBpsPer10Slots: number;
2402
- };
2403
-
2404
- /** A constituent's spot-market balance inside an LP pool (parallel to `PoolBalance` but tracking cumulative deposits too). */
2405
- export type ConstituentSpotBalance = {
2406
- /** SPOT_BALANCE_PRECISION (1e9) scaled balance */
2407
- scaledBalance: BN;
2408
- /** token mint precision */
2409
- cumulativeDeposits: BN;
2410
- marketIndex: number;
2411
- balanceType: SpotBalanceType;
2412
- };
2413
-
2414
- /** Admin instruction params for `initializeConstituent`, configuring a new LP-pool spot-market constituent. */
2415
- export type InitializeConstituentParams = {
2416
- spotMarketIndex: number;
2417
- decimals: number;
2418
- /** PERCENTAGE_PRECISION (1e6); max allowed deviation from target weight before rebalance pressure kicks in */
2419
- maxWeightDeviation: BN;
2420
- /** PERCENTAGE_PRECISION (1e6) */
2421
- swapFeeMin: BN;
2422
- /** PERCENTAGE_PRECISION (1e6) */
2423
- swapFeeMax: BN;
2424
- /** token mint precision; borrow cap for this constituent */
2425
- maxBorrowTokenAmount: BN;
2426
- /** slots; oracle updates older than this are treated as stale for this constituent */
2427
- oracleStalenessThreshold: BN;
2428
- /** bps; estimated cost to trade this constituent */
2429
- costToTrade: number;
2430
- /** PERCENTAGE_PRECISION (1e6); weight applied when this constituent derives its price from another constituent */
2431
- derivativeWeight: BN;
2432
- constituentDerivativeIndex?: number;
2433
- /** PERCENTAGE_PRECISION (1e6); max allowed depeg from the derivative reference before the constituent is treated as broken */
2434
- constituentDerivativeDepegThreshold?: BN;
2435
- /** PERCENTAGE_PRECISION (1e6), signed; this constituent's correlation with every other constituent */
2436
- constituentCorrelations: BN[];
2437
- /** PERCENTAGE_PRECISION (1e6) */
2438
- volatility: BN;
2439
- gammaExecution?: number;
2440
- gammaInventory?: number;
2441
- xi?: number;
2442
- };
2443
-
2444
- /** Lifecycle status of an LP-pool `ConstituentAccount`. */
2445
- export enum ConstituentStatus {
2446
- ACTIVE = 0,
2447
- /** may only shrink toward its target weight, not grow */
2448
- REDUCE_ONLY = 1,
2449
- DECOMMISSIONED = 2,
2450
- }
2451
- /** Bitmask mirror of `ConstituentAccount.pausedOperations`, gating which LP-pool operations a constituent allows. */
2452
- export enum ConstituentLpOperation {
2453
- Swap = 0b00000001,
2454
- Deposit = 0b00000010,
2455
- Withdraw = 0b00000100,
2456
- }
2457
-
2458
- /** Decoded mirror of the on-chain `Constituent` account: one spot-market asset inside an LP pool's basket. */
2459
- export type ConstituentAccount = {
2460
- pubkey: PublicKey;
2461
- mint: PublicKey;
2462
- lpPool: PublicKey;
2463
- vault: PublicKey;
2464
- /** signed, positive = fees received, negative = fees paid; PERCENTAGE_PRECISION-derived token units */
2465
- totalSwapFees: BN;
2466
- spotBalance: ConstituentSpotBalance;
2467
- /** token mint precision */
2468
- lastSpotBalanceTokenAmount: BN;
2469
- /** token mint precision */
2470
- cumulativeSpotInterestAccruedTokenAmount: BN;
2471
- /** PERCENTAGE_PRECISION (1e6); max allowed deviation from target weight */
2472
- maxWeightDeviation: BN;
2473
- /** PERCENTAGE_PRECISION (1e6); min fee charged on swaps to/from this constituent */
2474
- swapFeeMin: BN;
2475
- /** PERCENTAGE_PRECISION (1e6); max fee charged on swaps to/from this constituent */
2476
- swapFeeMax: BN;
2477
- /** token mint precision */
2478
- maxBorrowTokenAmount: BN;
2479
- /** token mint precision; the vault's actual token account balance */
2480
- vaultTokenBalance: BN;
2481
- lastOraclePrice: BN;
2482
- lastOracleSlot: BN;
2483
- /** slots; delay allowed for a valid AUM calculation before this constituent's price is considered stale */
2484
- oracleStalenessThreshold: BN;
2485
- /** token mint precision; user's token balance snapshotted at `beginSwap`-style flash accounting */
2486
- flashLoanInitialTokenAmount: BN;
2487
- nextSwapId: BN;
2488
- /** PERCENTAGE_PRECISION (1e6); share of derivative weight routed to this constituent specifically; 0 if this constituent has no derivative weight */
2489
- derivativeWeight: BN;
2490
- /** PERCENTAGE_PRECISION (1e6); 1 = 1% */
2491
- volatility: BN;
2492
- /** PERCENTAGE_PRECISION (1e6); max allowed depeg from the parent constituent before this derivative is treated as broken */
2493
- constituentDerivativeDepegThreshold: BN;
2494
- /** the parent constituent's index if this is a derivative (e.g. dSOL -> SOL); -1 if this constituent is itself a parent */
2495
- constituentDerivativeIndex: number;
2496
- spotMarketIndex: number;
2497
- constituentIndex: number;
2498
- decimals: number;
2499
- bump: number;
2500
- vaultBump: number;
2501
- /** no precision — raw constant used in swap-fee inventory-skew pricing */
2502
- gammaInventory: number;
2503
- /** no precision — raw constant used in swap-fee execution-cost pricing */
2504
- gammaExecution: number;
2505
- /** no precision — raw constant used in swap-fee pricing */
2506
- xi: number;
2507
- /** see `ConstituentStatus` */
2508
- status: number;
2509
- /** bitmask, see `ConstituentLpOperation` */
2510
- pausedOperations: number;
2511
- };
2512
-
2513
- /** One perp market's cached AMM/settlement snapshot inside an `AmmCache`, refreshed by the keeper crank so LP-pool settlement doesn't need to reload the full `PerpMarketAccount`. */
2514
- export type CacheInfo = {
2515
- oracle: PublicKey;
2516
- lastFeePoolTokenAmount: BN;
2517
- /** signed */
2518
- lastNetPnlPoolTokenAmount: BN;
2519
- lastExchangeFees: BN;
2520
- lastSettleAmmExFees: BN;
2521
- /** signed */
2522
- lastSettleAmmPnl: BN;
2523
- /** BASE_PRECISION (1e9), signed; the AMM's net position at last cache update */
2524
- position: BN;
2525
- slot: BN;
2526
- lastSettleAmount: BN;
2527
- lastSettleSlot: BN;
2528
- lastSettleTs: BN;
2529
- /** signed; quote owed from the LP pool to this market (or vice versa if negative) */
2530
- quoteOwedFromLpPool: BN;
2531
- /** signed; cap on the AMM's hedgeable inventory */
2532
- ammInventoryLimit: BN;
2533
- /** PRICE_PRECISION (1e6), signed */
2534
- oraclePrice: BN;
2535
- oracleSlot: BN;
2536
- /** numeric `OracleSourceNum` discriminant */
2537
- oracleSource: number;
2538
- /** `OracleValidity` discriminant at last cache update */
2539
- oracleValidity: number;
2540
- lpStatusForPerpMarket: number;
2541
- ammPositionScalar: number;
2542
- marketIndex: number;
2543
- };
2544
-
2545
- /** Decoded mirror of the on-chain `AmmCache` account: one `CacheInfo` per perp market, indexed by `marketIndex`. */
2546
- export type AmmCache = {
2547
- bump: number;
2548
- cache: CacheInfo[];
2549
- };
2550
-
2551
- /** SDK-computed result of checking whether a user account can currently be liquidated. */
2552
- export type AccountLiquidatableStatus = {
2553
- canBeLiquidated: boolean;
2554
- /** QUOTE_PRECISION (1e6); the maintenance margin requirement compared against */
2555
- marginRequirement: BN;
2556
- /** signed, QUOTE_PRECISION (1e6) */
2557
- totalCollateral: BN;
2558
- };
2559
-
2560
- /** Direction of an admin `transferFeeAndPnlPool` action, moving funds between a perp market's protocol fee pool and its pnl pool. */
2561
- export class TransferFeeAndPnlPoolDirection {
2562
- static readonly FEE_TO_PNL_POOL = { feeToPnlPool: {} };
2563
- static readonly PNL_TO_FEE_POOL = { pnlToFeePool: {} };
2564
- }
2565
-
2566
- /** Emitted when an admin transfers funds between a perp market's fee pool and pnl pool (`transferFeeAndPnlPool`). The two market indices may refer to the same or different perp markets. */
2567
- export type TransferFeeAndPnlPoolRecord = {
2568
- ts: BN;
2569
- slot: BN;
2570
- perpMarketIndexWithFeePool: number;
2571
- perpMarketIndexWithPnlPool: number;
2572
- direction: TransferFeeAndPnlPoolDirection;
2573
- /** QUOTE_PRECISION (1e6) */
2574
- amount: BN;
2575
- };