@velocity-exchange/sdk 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (323) hide show
  1. package/README.md +3 -3
  2. package/lib/browser/adminClient.d.ts +35 -0
  3. package/lib/browser/adminClient.js +65 -0
  4. package/lib/browser/config.js +6 -7
  5. package/lib/browser/constants/numericConstants.d.ts +1 -1
  6. package/lib/browser/constants/numericConstants.js +1 -1
  7. package/lib/browser/decode/user.js +5 -1
  8. package/lib/browser/idl/velocity.d.ts +146 -3
  9. package/lib/browser/idl/velocity.json +147 -4
  10. package/lib/browser/orderSubscriber/OrderSubscriber.js +3 -0
  11. package/lib/browser/pyth/pythLazerSubscriber.js +37 -27
  12. package/lib/browser/types.d.ts +4 -0
  13. package/lib/browser/user.d.ts +15 -0
  14. package/lib/browser/user.js +37 -1
  15. package/lib/browser/velocityClient.d.ts +46 -10
  16. package/lib/browser/velocityClient.js +107 -35
  17. package/lib/node/adminClient.d.ts +35 -0
  18. package/lib/node/adminClient.d.ts.map +1 -1
  19. package/lib/node/adminClient.js +65 -0
  20. package/lib/node/config.d.ts.map +1 -1
  21. package/lib/node/config.js +6 -7
  22. package/lib/node/constants/numericConstants.d.ts +1 -1
  23. package/lib/node/constants/numericConstants.d.ts.map +1 -1
  24. package/lib/node/constants/numericConstants.js +1 -1
  25. package/lib/node/decode/user.d.ts.map +1 -1
  26. package/lib/node/decode/user.js +5 -1
  27. package/lib/node/idl/velocity.d.ts +146 -3
  28. package/lib/node/idl/velocity.d.ts.map +1 -1
  29. package/lib/node/idl/velocity.json +147 -4
  30. package/lib/node/orderSubscriber/OrderSubscriber.d.ts.map +1 -1
  31. package/lib/node/orderSubscriber/OrderSubscriber.js +3 -0
  32. package/lib/node/pyth/pythLazerSubscriber.d.ts.map +1 -1
  33. package/lib/node/pyth/pythLazerSubscriber.js +37 -27
  34. package/lib/node/types.d.ts +4 -0
  35. package/lib/node/types.d.ts.map +1 -1
  36. package/lib/node/user.d.ts +15 -0
  37. package/lib/node/user.d.ts.map +1 -1
  38. package/lib/node/user.js +37 -1
  39. package/lib/node/velocityClient.d.ts +46 -10
  40. package/lib/node/velocityClient.d.ts.map +1 -1
  41. package/lib/node/velocityClient.js +107 -35
  42. package/package.json +7 -3
  43. package/.prettierignore +0 -1
  44. package/CHANGELOG.md +0 -132
  45. package/build-browser.js +0 -58
  46. package/bunfig.toml +0 -3
  47. package/esbuild-shims.js +0 -12
  48. package/scripts/deposit-isolated-positions.ts +0 -110
  49. package/scripts/find-flagged-users.ts +0 -213
  50. package/scripts/grpc-client-test-comparison.ts +0 -372
  51. package/scripts/grpc-multiuser-client-test-comparison.ts +0 -158
  52. package/scripts/postbuild.js +0 -95
  53. package/scripts/single-grpc-client-test.ts +0 -284
  54. package/scripts/withdraw-isolated-positions.ts +0 -174
  55. package/src/accounts/README_WebSocketAccountSubscriberV2.md +0 -95
  56. package/src/accounts/README_WebSocketProgramAccountSubscriberV2.md +0 -135
  57. package/src/accounts/basicUserAccountSubscriber.ts +0 -79
  58. package/src/accounts/basicUserStatsAccountSubscriber.ts +0 -87
  59. package/src/accounts/bulkAccountLoader.ts +0 -358
  60. package/src/accounts/bulkUserStatsSubscription.ts +0 -40
  61. package/src/accounts/bulkUserSubscription.ts +0 -39
  62. package/src/accounts/customizedCadenceBulkAccountLoader.ts +0 -250
  63. package/src/accounts/fetch.ts +0 -200
  64. package/src/accounts/grpcAccountSubscriber.ts +0 -225
  65. package/src/accounts/grpcInsuranceFundStakeAccountSubscriber.ts +0 -73
  66. package/src/accounts/grpcMultiAccountSubscriber.ts +0 -566
  67. package/src/accounts/grpcMultiUserAccountSubscriber.ts +0 -328
  68. package/src/accounts/grpcProgramAccountSubscriber.ts +0 -264
  69. package/src/accounts/grpcUserAccountSubscriber.ts +0 -63
  70. package/src/accounts/grpcUserStatsAccountSubscriber.ts +0 -65
  71. package/src/accounts/grpcVelocityClientAccountSubscriber.ts +0 -257
  72. package/src/accounts/grpcVelocityClientAccountSubscriberV2.ts +0 -941
  73. package/src/accounts/laserProgramAccountSubscriber.ts +0 -266
  74. package/src/accounts/oneShotUserAccountSubscriber.ts +0 -88
  75. package/src/accounts/oneShotUserStatsAccountSubscriber.ts +0 -94
  76. package/src/accounts/pollingInsuranceFundStakeAccountSubscriber.ts +0 -223
  77. package/src/accounts/pollingOracleAccountSubscriber.ts +0 -151
  78. package/src/accounts/pollingTokenAccountSubscriber.ts +0 -147
  79. package/src/accounts/pollingUserAccountSubscriber.ts +0 -198
  80. package/src/accounts/pollingUserStatsAccountSubscriber.ts +0 -180
  81. package/src/accounts/pollingVelocityClientAccountSubscriber.ts +0 -774
  82. package/src/accounts/testBulkAccountLoader.ts +0 -59
  83. package/src/accounts/types.ts +0 -428
  84. package/src/accounts/utils.ts +0 -90
  85. package/src/accounts/webSocketAccountSubscriber.ts +0 -304
  86. package/src/accounts/webSocketAccountSubscriberV2.ts +0 -536
  87. package/src/accounts/webSocketInsuranceFundStakeAccountSubscriber.ts +0 -171
  88. package/src/accounts/webSocketProgramAccountSubscriber.ts +0 -244
  89. package/src/accounts/webSocketProgramAccountSubscriberV2.ts +0 -1048
  90. package/src/accounts/webSocketProgramAccountsSubscriberV2.ts +0 -1042
  91. package/src/accounts/webSocketUserAccountSubscriber.ts +0 -139
  92. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +0 -131
  93. package/src/accounts/webSocketVelocityClientAccountSubscriber.ts +0 -865
  94. package/src/accounts/webSocketVelocityClientAccountSubscriberV2.ts +0 -897
  95. package/src/accounts/websocketProgramUserAccountSubscriber.ts +0 -127
  96. package/src/addresses/marketAddresses.ts +0 -28
  97. package/src/addresses/pda.ts +0 -620
  98. package/src/adminClient.ts +0 -8136
  99. package/src/assert/assert.ts +0 -5
  100. package/src/auctionSubscriber/auctionSubscriber.ts +0 -86
  101. package/src/auctionSubscriber/auctionSubscriberGrpc.ts +0 -99
  102. package/src/auctionSubscriber/index.ts +0 -9
  103. package/src/auctionSubscriber/types.ts +0 -30
  104. package/src/bankrun/bankrunConnection.ts +0 -630
  105. package/src/blockhashSubscriber/BlockhashSubscriber.ts +0 -160
  106. package/src/blockhashSubscriber/index.ts +0 -6
  107. package/src/blockhashSubscriber/types.ts +0 -13
  108. package/src/clock/clockSubscriber.ts +0 -146
  109. package/src/config.ts +0 -312
  110. package/src/constants/index.ts +0 -9
  111. package/src/constants/numericConstants.ts +0 -194
  112. package/src/constants/perpMarkets.ts +0 -127
  113. package/src/constants/spotMarkets.ts +0 -104
  114. package/src/constants/txConstants.ts +0 -2
  115. package/src/constituentMap/constituentMap.ts +0 -305
  116. package/src/constituentMap/pollingConstituentAccountSubscriber.ts +0 -99
  117. package/src/constituentMap/webSocketConstituentAccountSubscriber.ts +0 -121
  118. package/src/core/VelocityCore.ts +0 -606
  119. package/src/core/index.ts +0 -12
  120. package/src/core/instructions/deposit.ts +0 -64
  121. package/src/core/instructions/fill.ts +0 -51
  122. package/src/core/instructions/funding.ts +0 -33
  123. package/src/core/instructions/liquidation.ts +0 -55
  124. package/src/core/instructions/orders.ts +0 -84
  125. package/src/core/instructions/perpOrders.ts +0 -312
  126. package/src/core/instructions/settlement.ts +0 -40
  127. package/src/core/instructions/trigger.ts +0 -41
  128. package/src/core/instructions/withdraw.ts +0 -65
  129. package/src/core/remainingAccounts.ts +0 -320
  130. package/src/core/signedMsg.ts +0 -109
  131. package/src/decode/customCoder.ts +0 -148
  132. package/src/decode/user.ts +0 -401
  133. package/src/dlob/DLOB.ts +0 -2793
  134. package/src/dlob/DLOBNode.ts +0 -305
  135. package/src/dlob/DLOBSubscriber.ts +0 -269
  136. package/src/dlob/NodeList.ts +0 -244
  137. package/src/dlob/orderBookLevels.ts +0 -695
  138. package/src/dlob/types.ts +0 -37
  139. package/src/events/eventList.ts +0 -114
  140. package/src/events/eventSubscriber.ts +0 -521
  141. package/src/events/eventsServerLogProvider.ts +0 -189
  142. package/src/events/fetchLogs.ts +0 -219
  143. package/src/events/parse.ts +0 -271
  144. package/src/events/pollingLogProvider.ts +0 -113
  145. package/src/events/sort.ts +0 -51
  146. package/src/events/txEventCache.ts +0 -92
  147. package/src/events/types.ts +0 -337
  148. package/src/events/webSocketLogProvider.ts +0 -152
  149. package/src/factory/bigNum.ts +0 -709
  150. package/src/factory/oracleClient.ts +0 -73
  151. package/src/idl/pyth.json +0 -142
  152. package/src/idl/pyth.ts +0 -97
  153. package/src/idl/pyth_solana_receiver.json +0 -628
  154. package/src/idl/token_faucet.json +0 -229
  155. package/src/idl/token_faucet.ts +0 -197
  156. package/src/idl/velocity.json +0 -23974
  157. package/src/idl/velocity.ts +0 -23980
  158. package/src/index.ts +0 -150
  159. package/src/indicative-quotes/indicativeQuotesSender.ts +0 -233
  160. package/src/isomorphic/README.md +0 -19
  161. package/src/isomorphic/anchor.browser.ts +0 -44
  162. package/src/isomorphic/anchor.node.ts +0 -1
  163. package/src/isomorphic/anchor.ts +0 -1
  164. package/src/isomorphic/anchor29.browser.ts +0 -24
  165. package/src/isomorphic/anchor29.node.ts +0 -1
  166. package/src/isomorphic/anchor29.ts +0 -1
  167. package/src/isomorphic/grpc.browser.ts +0 -4
  168. package/src/isomorphic/grpc.node.ts +0 -130
  169. package/src/isomorphic/grpc.ts +0 -1
  170. package/src/jupiter/jupiterClient.ts +0 -502
  171. package/src/keypair.ts +0 -32
  172. package/src/margin/README.md +0 -138
  173. package/src/marginCalculation.ts +0 -407
  174. package/src/marinade/idl/idl.json +0 -1962
  175. package/src/marinade/index.ts +0 -73
  176. package/src/marinade/types.ts +0 -3925
  177. package/src/math/amm.ts +0 -1758
  178. package/src/math/auction.ts +0 -480
  179. package/src/math/bankruptcy.ts +0 -138
  180. package/src/math/builder.ts +0 -130
  181. package/src/math/conversion.ts +0 -45
  182. package/src/math/exchangeStatus.ts +0 -261
  183. package/src/math/funding.ts +0 -498
  184. package/src/math/insurance.ts +0 -171
  185. package/src/math/liquidation.ts +0 -433
  186. package/src/math/margin.ts +0 -327
  187. package/src/math/market.ts +0 -487
  188. package/src/math/oracles.ts +0 -477
  189. package/src/math/orders.ts +0 -500
  190. package/src/math/position.ts +0 -381
  191. package/src/math/repeg.ts +0 -223
  192. package/src/math/spotBalance.ts +0 -996
  193. package/src/math/spotMarket.ts +0 -115
  194. package/src/math/spotPosition.ts +0 -263
  195. package/src/math/state.ts +0 -71
  196. package/src/math/superStake.ts +0 -602
  197. package/src/math/tiers.ts +0 -73
  198. package/src/math/trade.ts +0 -879
  199. package/src/math/utils.ts +0 -183
  200. package/src/memcmp.ts +0 -279
  201. package/src/oracles/oracleClientCache.ts +0 -41
  202. package/src/oracles/oracleId.ts +0 -99
  203. package/src/oracles/prelaunchOracleClient.ts +0 -63
  204. package/src/oracles/pythClient.ts +0 -125
  205. package/src/oracles/pythLazerClient.ts +0 -141
  206. package/src/oracles/quoteAssetOracleClient.ts +0 -43
  207. package/src/oracles/strictOraclePrice.ts +0 -40
  208. package/src/oracles/types.ts +0 -82
  209. package/src/oracles/utils.ts +0 -45
  210. package/src/orderParams.ts +0 -117
  211. package/src/orderSubscriber/OrderSubscriber.ts +0 -378
  212. package/src/orderSubscriber/PollingSubscription.ts +0 -50
  213. package/src/orderSubscriber/WebsocketSubscription.ts +0 -137
  214. package/src/orderSubscriber/grpcSubscription.ts +0 -155
  215. package/src/orderSubscriber/index.ts +0 -7
  216. package/src/orderSubscriber/types.ts +0 -64
  217. package/src/priorityFee/averageOverSlotsStrategy.ts +0 -17
  218. package/src/priorityFee/averageStrategy.ts +0 -13
  219. package/src/priorityFee/ewmaStrategy.ts +0 -51
  220. package/src/priorityFee/heliusPriorityFeeMethod.ts +0 -68
  221. package/src/priorityFee/index.ts +0 -16
  222. package/src/priorityFee/maxOverSlotsStrategy.ts +0 -18
  223. package/src/priorityFee/maxStrategy.ts +0 -8
  224. package/src/priorityFee/priorityFeeSubscriber.ts +0 -328
  225. package/src/priorityFee/priorityFeeSubscriberMap.ts +0 -134
  226. package/src/priorityFee/solanaPriorityFeeMethod.ts +0 -46
  227. package/src/priorityFee/types.ts +0 -82
  228. package/src/priorityFee/velocityPriorityFeeMethod.ts +0 -53
  229. package/src/pyth/constants.ts +0 -9
  230. package/src/pyth/index.ts +0 -15
  231. package/src/pyth/pythLazerSubscriber.ts +0 -365
  232. package/src/pyth/types.ts +0 -4451
  233. package/src/pyth/utils.ts +0 -13
  234. package/src/slot/SlotSubscriber.ts +0 -126
  235. package/src/slot/SlothashSubscriber.ts +0 -163
  236. package/src/swap/UnifiedSwapClient.ts +0 -315
  237. package/src/swift/grpcSignedMsgUserAccountSubscriber.ts +0 -81
  238. package/src/swift/index.ts +0 -10
  239. package/src/swift/signedMsgUserAccountSubscriber.ts +0 -251
  240. package/src/swift/swiftOrderSubscriber.ts +0 -351
  241. package/src/testClient.ts +0 -42
  242. package/src/titan/titanClient.ts +0 -438
  243. package/src/token/index.ts +0 -13
  244. package/src/tokenFaucet.ts +0 -296
  245. package/src/tx/baseTxSender.ts +0 -651
  246. package/src/tx/blockhashFetcher/baseBlockhashFetcher.ts +0 -31
  247. package/src/tx/blockhashFetcher/cachedBlockhashFetcher.ts +0 -105
  248. package/src/tx/blockhashFetcher/types.ts +0 -9
  249. package/src/tx/fastSingleTxSender.ts +0 -200
  250. package/src/tx/forwardOnlyTxSender.ts +0 -193
  251. package/src/tx/priorityFeeCalculator.ts +0 -117
  252. package/src/tx/reportTransactionError.ts +0 -176
  253. package/src/tx/retryTxSender.ts +0 -177
  254. package/src/tx/txHandler.ts +0 -1009
  255. package/src/tx/txParamProcessor.ts +0 -225
  256. package/src/tx/types.ts +0 -117
  257. package/src/tx/utils.ts +0 -133
  258. package/src/tx/whileValidTxSender.ts +0 -377
  259. package/src/types.ts +0 -2575
  260. package/src/user.ts +0 -5316
  261. package/src/userConfig.ts +0 -38
  262. package/src/userMap/PollingSubscription.ts +0 -61
  263. package/src/userMap/WebsocketSubscription.ts +0 -93
  264. package/src/userMap/grpcSubscription.ts +0 -93
  265. package/src/userMap/referrerMap.ts +0 -360
  266. package/src/userMap/revenueShareEscrowMap.ts +0 -342
  267. package/src/userMap/userMap.ts +0 -784
  268. package/src/userMap/userMapConfig.ts +0 -82
  269. package/src/userMap/userStatsMap.ts +0 -393
  270. package/src/userName.ts +0 -37
  271. package/src/userStats.ts +0 -159
  272. package/src/userStatsConfig.ts +0 -35
  273. package/src/util/TransactionConfirmationManager.ts +0 -333
  274. package/src/util/chainClock.ts +0 -65
  275. package/src/util/computeUnits.ts +0 -101
  276. package/src/util/digest.ts +0 -33
  277. package/src/util/ed25519Utils.ts +0 -95
  278. package/src/util/promiseTimeout.ts +0 -23
  279. package/src/velocityClient.ts +0 -14802
  280. package/src/velocityClientConfig.ts +0 -119
  281. package/src/wallet.ts +0 -91
  282. package/tests/VelocityCore/builder_escrow.test.ts +0 -121
  283. package/tests/VelocityCore/decode.test.ts +0 -16
  284. package/tests/VelocityCore/fill_trigger.test.ts +0 -73
  285. package/tests/VelocityCore/instructions.test.ts +0 -46
  286. package/tests/VelocityCore/pdas.test.ts +0 -30
  287. package/tests/VelocityCore/perp_orders.test.ts +0 -205
  288. package/tests/VelocityCore/remainingAccounts.test.ts +0 -72
  289. package/tests/VelocityCore/settlement_liquidation.test.ts +0 -69
  290. package/tests/accounts/customizedCadenceBulkAccountLoader.test.ts +0 -211
  291. package/tests/amm/test.ts +0 -2402
  292. package/tests/auctions/test.ts +0 -81
  293. package/tests/bn/test.ts +0 -355
  294. package/tests/builder/builderFee.test.ts +0 -42
  295. package/tests/ci/verifyConstants.ts +0 -393
  296. package/tests/decode/test.ts +0 -262
  297. package/tests/decode/userAccountBufferStrings.ts +0 -102
  298. package/tests/dlob/helpers.ts +0 -748
  299. package/tests/dlob/test.ts +0 -6969
  300. package/tests/dlob/tickSizeStandardization.ts +0 -545
  301. package/tests/events/parseLogsForCuUsage.ts +0 -139
  302. package/tests/exchangeStatus/test.ts +0 -45
  303. package/tests/insurance/test.ts +0 -40
  304. package/tests/liquidation/test.ts +0 -125
  305. package/tests/oracles/mmOracleGate.test.ts +0 -379
  306. package/tests/oracles/pythPegSnap.test.ts +0 -76
  307. package/tests/sdkParity/enumParity.test.ts +0 -84
  308. package/tests/sdkParity/marginCategoryFill.test.ts +0 -143
  309. package/tests/sdkParity/memcmpOffsets.test.ts +0 -139
  310. package/tests/spot/test.ts +0 -281
  311. package/tests/tx/TransactionConfirmationManager.test.ts +0 -312
  312. package/tests/tx/cachedBlockhashFetcher.test.ts +0 -96
  313. package/tests/tx/priorityFeeCalculator.ts +0 -77
  314. package/tests/tx/priorityFeeStrategy.ts +0 -95
  315. package/tests/user/bankruptcy.ts +0 -165
  316. package/tests/user/feeAndWithdrawLimits.ts +0 -284
  317. package/tests/user/getMarginCalculation.ts +0 -586
  318. package/tests/user/helpers.ts +0 -184
  319. package/tests/user/liquidations.ts +0 -129
  320. package/tests/user/marginCalculations.test.ts +0 -321
  321. package/tests/user/test.ts +0 -833
  322. package/tsconfig.browser.json +0 -18
  323. package/tsconfig.json +0 -36
@@ -127,6 +127,36 @@ class PythLazerSubscriber {
127
127
  });
128
128
  // Reset allSubscribedIds to rebuild with only stable feeds
129
129
  this.allSubscribedIds = [];
130
+ // addMessageListener is global to the client (fires for every message,
131
+ // not scoped to a subscription), and each message carries its own
132
+ // subscriptionId — so one listener serves all subscriptions. Registering
133
+ // it per chunk would run every message once per chunk.
134
+ this.pythLazerClient.addMessageListener((message) => {
135
+ var _a, _b;
136
+ this.receivingData = true;
137
+ clearTimeout(this.timeoutId);
138
+ switch (message.type) {
139
+ case 'json': {
140
+ if (message.value.type == 'streamUpdated') {
141
+ if ((_a = message.value.solana) === null || _a === void 0 ? void 0 : _a.data) {
142
+ this.feedIdChunkToPriceMessage.set(this.subscriptionIdsToFeedIdsHash.get(message.value.subscriptionId), message.value.solana.data);
143
+ }
144
+ if ((_b = message.value.parsed) === null || _b === void 0 ? void 0 : _b.priceFeeds) {
145
+ for (const priceFeed of message.value.parsed.priceFeeds) {
146
+ const price = Number(priceFeed.price) *
147
+ Math.pow(10, Number(priceFeed.exponent));
148
+ this.feedIdToPrice.set(priceFeed.priceFeedId, price);
149
+ }
150
+ }
151
+ }
152
+ break;
153
+ }
154
+ default: {
155
+ break;
156
+ }
157
+ }
158
+ this.setTimeout();
159
+ });
130
160
  let subscriptionId = 1;
131
161
  for (const priceFeedArray of this.priceFeedArrays) {
132
162
  const filteredFeedIds = this.filterStableFeeds(priceFeedArray.priceFeedIds);
@@ -153,33 +183,13 @@ class PythLazerSubscriber {
153
183
  this.marketIndextoPriceFeedIdChunk.delete(marketIndex);
154
184
  }
155
185
  }
156
- this.pythLazerClient.addMessageListener((message) => {
157
- var _a, _b;
158
- this.receivingData = true;
159
- clearTimeout(this.timeoutId);
160
- switch (message.type) {
161
- case 'json': {
162
- if (message.value.type == 'streamUpdated') {
163
- if ((_a = message.value.solana) === null || _a === void 0 ? void 0 : _a.data) {
164
- this.feedIdChunkToPriceMessage.set(this.subscriptionIdsToFeedIdsHash.get(message.value.subscriptionId), message.value.solana.data);
165
- }
166
- if ((_b = message.value.parsed) === null || _b === void 0 ? void 0 : _b.priceFeeds) {
167
- for (const priceFeed of message.value.parsed.priceFeeds) {
168
- const price = Number(priceFeed.price) *
169
- Math.pow(10, Number(priceFeed.exponent));
170
- this.feedIdToPrice.set(priceFeed.priceFeedId, price);
171
- }
172
- }
173
- }
174
- break;
175
- }
176
- default: {
177
- break;
178
- }
179
- }
180
- this.setTimeout();
181
- });
182
- this.pythLazerClient.send({
186
+ // Use subscribe() (not send()): subscribe() registers the request in
187
+ // the pool's subscriptions map so ResilientWebSocket replays it on
188
+ // every socket reconnect. send() fires once and is never replayed, so
189
+ // after the first heartbeat-timeout reconnect the socket streams
190
+ // nothing — forcing the watchdog to tear down the whole client and
191
+ // reopen numConnections fresh sockets. subscribe() recovers in place.
192
+ this.pythLazerClient.subscribe({
183
193
  type: 'subscribe',
184
194
  subscriptionId,
185
195
  priceFeedIds: filteredFeedIds,
@@ -1642,6 +1642,8 @@ export type UserStatsAccount = {
1642
1642
  authority: PublicKey;
1643
1643
  ifStakedQuoteAssetAmount: BN;
1644
1644
  delegatePermissions: number;
1645
+ /** non-zero when the permissionless `tripEquityFloorBreaker` fired: every subaccount of the authority rejects risk-increasing fills, withdrawals and transfers out until the warm admin resets */
1646
+ equityBreakerTripped: number;
1645
1647
  };
1646
1648
  /** Decoded mirror of the on-chain `User` (sub-account) zero-copy account. */
1647
1649
  export type UserAccount = {
@@ -1684,6 +1686,8 @@ export type UserAccount = {
1684
1686
  poolId: number;
1685
1687
  /** bitmask, see `SpecialUserStatus` */
1686
1688
  specialUserStatus: number;
1689
+ /** QUOTE_PRECISION (1e6); admin-set minimum cross-margin total collateral for risk-increasing orders, fills, withdrawals and transfers; 0 = disabled */
1690
+ equityFloor: BN;
1687
1691
  };
1688
1692
  /** A user's balance in one spot market. Decoded mirror of the on-chain `SpotPosition`. */
1689
1693
  export type SpotPosition = {
@@ -410,6 +410,21 @@ export declare class User {
410
410
  * @returns Precision QUOTE_PRECISION (1e6).
411
411
  */
412
412
  getTotalCollateral(marginCategory?: MarginCategory, strict?: boolean, includeOpenOrders?: boolean, liquidationBuffer?: BN, perpMarketIndex?: number): BN;
413
+ /**
414
+ * True when the account has an admin-set `equityFloor` and its cross-margin
415
+ * total collateral is below it. While below the floor, the program rejects
416
+ * risk-increasing order placement and fills, withdrawals, and transfers out
417
+ * of the account (`EquityBelowFloor`); reduce-only activity stays allowed.
418
+ * Mirrors `User::is_below_equity_floor` on-chain.
419
+ * @param strict Use TWAP-bounded oracle pricing, matching the withdraw path. Defaults to false.
420
+ */
421
+ isBelowEquityFloor(strict?: boolean): boolean;
422
+ /**
423
+ * Cross-margin total collateral in excess of the admin-set `equityFloor`,
424
+ * floored at zero (QUOTE_PRECISION). Unbounded (`null`) when no floor is set.
425
+ * @param strict Use TWAP-bounded oracle pricing. Defaults to false.
426
+ */
427
+ getEquityAboveFloor(strict?: boolean): BN | null;
413
428
  /**
414
429
  * Builds the liquidation-buffer map to pass into margin calculations while
415
430
  * a liquidation is in progress: `'cross'` is set to the state account's
@@ -898,6 +898,33 @@ class User {
898
898
  }
899
899
  return marginCalc.totalCollateral;
900
900
  }
901
+ /**
902
+ * True when the account has an admin-set `equityFloor` and its cross-margin
903
+ * total collateral is below it. While below the floor, the program rejects
904
+ * risk-increasing order placement and fills, withdrawals, and transfers out
905
+ * of the account (`EquityBelowFloor`); reduce-only activity stays allowed.
906
+ * Mirrors `User::is_below_equity_floor` on-chain.
907
+ * @param strict Use TWAP-bounded oracle pricing, matching the withdraw path. Defaults to false.
908
+ */
909
+ isBelowEquityFloor(strict = false) {
910
+ const equityFloor = this.getUserAccountOrThrow().equityFloor;
911
+ if (equityFloor.lte(numericConstants_1.ZERO)) {
912
+ return false;
913
+ }
914
+ return this.getTotalCollateral('Initial', strict).lt(equityFloor);
915
+ }
916
+ /**
917
+ * Cross-margin total collateral in excess of the admin-set `equityFloor`,
918
+ * floored at zero (QUOTE_PRECISION). Unbounded (`null`) when no floor is set.
919
+ * @param strict Use TWAP-bounded oracle pricing. Defaults to false.
920
+ */
921
+ getEquityAboveFloor(strict = false) {
922
+ const equityFloor = this.getUserAccountOrThrow().equityFloor;
923
+ if (equityFloor.lte(numericConstants_1.ZERO)) {
924
+ return null;
925
+ }
926
+ return anchor_1.BN.max(this.getTotalCollateral('Initial', strict).sub(equityFloor), numericConstants_1.ZERO);
927
+ }
901
928
  /**
902
929
  * Builds the liquidation-buffer map to pass into margin calculations while
903
930
  * a liquidation is in progress: `'cross'` is set to the state account's
@@ -2353,7 +2380,16 @@ class User {
2353
2380
  const spotMarket = this.velocityClient.getSpotMarketAccountOrThrow(marketIndex);
2354
2381
  // eslint-disable-next-line prefer-const
2355
2382
  let { borrowLimit, withdrawLimit } = (0, spotBalance_2.calculateWithdrawLimit)(spotMarket, nowTs);
2356
- const freeCollateral = this.getFreeCollateral();
2383
+ // the withdraw path enforces the equity floor on post-withdraw total
2384
+ // collateral, so equity above the floor caps free collateral here
2385
+ const equityAboveFloor = this.getEquityAboveFloor(true);
2386
+ if (equityAboveFloor !== null && equityAboveFloor.eq(numericConstants_1.ZERO)) {
2387
+ return numericConstants_1.ZERO;
2388
+ }
2389
+ let freeCollateral = this.getFreeCollateral();
2390
+ if (equityAboveFloor !== null) {
2391
+ freeCollateral = anchor_1.BN.min(freeCollateral, equityAboveFloor);
2392
+ }
2357
2393
  const initialMarginRequirement = this.getInitialMarginRequirement();
2358
2394
  const oracleData = this.getOracleDataForSpotMarket(marketIndex);
2359
2395
  const { numeratorScale, denominatorScale } = spotMarket.decimals > 6
@@ -1529,7 +1529,9 @@ export declare class VelocityClient {
1529
1529
  * @param subAccountId - Sub-account id to withdraw from; defaults to `this.activeSubAccountId`.
1530
1530
  * @returns The `withdraw` instruction.
1531
1531
  */
1532
- getWithdrawIx(amount: BN, marketIndex: number, userTokenAccount: PublicKey, reduceOnly?: boolean, subAccountId?: number): Promise<TransactionInstruction>;
1532
+ getWithdrawIx(amount: BN, marketIndex: number, userTokenAccount: PublicKey, reduceOnly?: boolean, subAccountId?: number, overrides?: {
1533
+ authority?: PublicKey;
1534
+ }): Promise<TransactionInstruction>;
1533
1535
  /**
1534
1536
  * Transfers a spot balance directly between two sub-accounts owned by `this.wallet.publicKey`
1535
1537
  * (withdraws from `fromSubAccountId`, deposits into `toSubAccountId`) without leaving the program —
@@ -1571,13 +1573,22 @@ export declare class VelocityClient {
1571
1573
  * @param marketIndex - Spot market index of the balance to transfer.
1572
1574
  * @param fromSubAccountId - Sub-account id to debit.
1573
1575
  * @param toSubAccountId - Sub-account id to credit.
1576
+ * @param equityFloorDelta - Equity floor (QUOTE_PRECISION) to move from the debited to the credited
1577
+ * sub-account along with the funds, keeping the sum of floors constant. The debited side must stay
1578
+ * at/above its reduced floor and the credited side's collateral (after the transfer lands) must back
1579
+ * its increased floor, else the transfer reverts with `InvalidEquityFloorTransfer`. Pass `'auto'`
1580
+ * (quote market only) to move the minimal floor needed for the debited side to stay at/above its
1581
+ * floor: `max(0, amount - (collateral - floor))`, capped at the debited side's floor. The auto delta
1582
+ * never exceeds `amount`, so the credited side stays backed whenever it was before. Client-side
1583
+ * pricing can differ slightly from the on-chain strict check at the exact boundary; retry with an
1584
+ * explicit padded delta if an `'auto'` transfer reverts. Defaults to zero.
1574
1585
  * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
1575
1586
  * @returns The transaction signature.
1576
1587
  * @throws (on-chain) if `allowDelegateTransfer` is not enabled, if the signer is not the delegate on
1577
1588
  * both sub-accounts, if the sub-accounts have different owners, if either is bankrupt, or if
1578
1589
  * `fromSubAccountId === toSubAccountId`.
1579
1590
  */
1580
- transferDepositByDelegate(amount: BN, marketIndex: number, fromSubAccountId: number, toSubAccountId: number, txParams?: TxParams): Promise<TransactionSignature>;
1591
+ transferDepositByDelegate(amount: BN, marketIndex: number, fromSubAccountId: number, toSubAccountId: number, equityFloorDelta?: BN | 'auto', txParams?: TxParams): Promise<TransactionSignature>;
1581
1592
  /**
1582
1593
  * Builds the `transferDepositByDelegate` instruction. See `transferDepositByDelegate` for the full
1583
1594
  * set of on-chain preconditions. Uses an already-loaded `from` sub-account's cached data if
@@ -1589,7 +1600,7 @@ export declare class VelocityClient {
1589
1600
  * @param toSubAccountId - Sub-account id to credit.
1590
1601
  * @returns The instruction.
1591
1602
  */
1592
- getTransferDepositByDelegateIx(amount: BN, marketIndex: number, fromSubAccountId: number, toSubAccountId: number): Promise<TransactionInstruction>;
1603
+ getTransferDepositByDelegateIx(amount: BN, marketIndex: number, fromSubAccountId: number, toSubAccountId: number, equityFloorDelta?: BN | 'auto'): Promise<TransactionInstruction>;
1593
1604
  /**
1594
1605
  * Moves a deposit balance and/or a borrow balance for the same underlying mint between two
1595
1606
  * sub-accounts owned by `this.wallet.publicKey` that sit in *different* isolated pools, in one
@@ -2519,6 +2530,26 @@ export declare class VelocityClient {
2519
2530
  * @returns The instruction.
2520
2531
  */
2521
2532
  getForceCancelOrdersIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, fillerPublicKey?: PublicKey): Promise<TransactionInstruction>;
2533
+ /**
2534
+ * Keeper instruction: trips the authority-wide equity floor breaker. Proves on-chain that the
2535
+ * given subaccount's cross-margin total collateral is below its `equityFloor` (reverts with
2536
+ * `SufficientCollateral` otherwise, or if no floor is set) and sets `equityBreakerTripped` on the
2537
+ * authority's `UserStats` — every subaccount of the authority then rejects risk-increasing fills,
2538
+ * withdrawals and transfers out until the warm admin calls `resetEquityFloorBreaker`.
2539
+ * Permissionless — any signer may trip it; the margin calculation is the proof.
2540
+ * @param userAccountPublicKey - Public key of the breached subaccount's user account.
2541
+ * @param user - Decoded user account of the breached subaccount.
2542
+ * @param txParams - Optional compute-unit/priority-fee overrides.
2543
+ * @returns The transaction signature.
2544
+ */
2545
+ tripEquityFloorBreaker(userAccountPublicKey: PublicKey, user: UserAccount, txParams?: TxParams): Promise<TransactionSignature>;
2546
+ /**
2547
+ * Builds the `tripEquityFloorBreaker` instruction. See `tripEquityFloorBreaker` for semantics.
2548
+ * @param userAccountPublicKey - Public key of the breached subaccount's user account.
2549
+ * @param userAccount - Decoded user account of the breached subaccount.
2550
+ * @returns The instruction.
2551
+ */
2552
+ getTripEquityFloorBreakerIx(userAccountPublicKey: PublicKey, userAccount: UserAccount): Promise<TransactionInstruction>;
2522
2553
  /**
2523
2554
  * Keeper instruction: marks a user account idle after confirming (via `validate_user_is_idle`)
2524
2555
  * it has been inactive long enough — the inactivity window is shorter (accelerated) when the
@@ -3495,11 +3526,12 @@ export declare class VelocityClient {
3495
3526
  getUpdatePrelaunchOracleIx(perpMarketIndex: number): Promise<TransactionInstruction>;
3496
3527
  /**
3497
3528
  * Keeper instruction: estimates the market's bid/ask price from the given makers' resting DLOB
3498
- * orders (filtered to those within `BID_ASK_TWAP_MAX_ORACLE_DIVERGENCE_PERCENT` of the oracle
3499
- * price) and folds the estimate into `lastBidPriceTwap`/`lastAskPriceTwap`. Restricted: the
3500
- * calling wallet's `UserStats` must have `canUpdateBidAskTwap` set and at least 1000 USDC
3501
- * (`QUOTE_PRECISION`, 1e6) staked in the insurance fund (`ifStakedQuoteAssetAmount`), or the
3502
- * instruction reverts.
3529
+ * orders (kept only within BID_ASK_TWAP_MAX_ORACLE_DIVERGENCE_PERCENT` of the oracle price on
3530
+ * both sides) and folds the estimate into `lastBidPriceTwap`/`lastAskPriceTwap`. This does NOT
3531
+ * update the funding rate, crank funding separately via `getUpdateFundingRateIx`. Restricted:
3532
+ * the calling wallet's `UserStats` (which must be the signer's own) must have
3533
+ * `canUpdateBidAskTwap` set and at least 1000 USDC (`QUOTE_PRECISION`, 1e6) staked in the
3534
+ * insurance fund (`ifStakedQuoteAssetAmount`), or the instruction reverts.
3503
3535
  * @param perpMarketIndex - Perp market index to update.
3504
3536
  * @param makers - `(maker, makerStats)` pairs whose resting orders are sampled for the estimate.
3505
3537
  * @param txParams - Optional compute-unit/priority-fee overrides.
@@ -3596,7 +3628,9 @@ export declare class VelocityClient {
3596
3628
  * @param marketIndex - Spot market index whose insurance fund to stake into.
3597
3629
  * @returns The instruction.
3598
3630
  */
3599
- getInitializeInsuranceFundStakeIx(marketIndex: number): Promise<TransactionInstruction>;
3631
+ getInitializeInsuranceFundStakeIx(marketIndex: number, overrides?: {
3632
+ authority?: PublicKey;
3633
+ }): Promise<TransactionInstruction>;
3600
3634
  /**
3601
3635
  * Builds the `addInsuranceFundStake` instruction, transferring `amount` of the market's token
3602
3636
  * from `collateralAccountPublicKey` into its insurance fund vault and minting the caller's
@@ -3609,7 +3643,9 @@ export declare class VelocityClient {
3609
3643
  * @param collateralAccountPublicKey - Token account to debit for the stake.
3610
3644
  * @returns The instruction.
3611
3645
  */
3612
- getAddInsuranceFundStakeIx(marketIndex: number, amount: BN, collateralAccountPublicKey: PublicKey): Promise<TransactionInstruction>;
3646
+ getAddInsuranceFundStakeIx(marketIndex: number, amount: BN, collateralAccountPublicKey: PublicKey, overrides?: {
3647
+ authority?: PublicKey;
3648
+ }): Promise<TransactionInstruction>;
3613
3649
  /**
3614
3650
  * Add to an insurance fund stake and optionally initialize the account
3615
3651
  */
@@ -3042,7 +3042,8 @@ class VelocityClient {
3042
3042
  * @param subAccountId - Sub-account id to withdraw from; defaults to `this.activeSubAccountId`.
3043
3043
  * @returns The `withdraw` instruction.
3044
3044
  */
3045
- async getWithdrawIx(amount, marketIndex, userTokenAccount, reduceOnly = false, subAccountId) {
3045
+ async getWithdrawIx(amount, marketIndex, userTokenAccount, reduceOnly = false, subAccountId, overrides) {
3046
+ var _a;
3046
3047
  const user = await this.getUserAccountPublicKey(subAccountId);
3047
3048
  const remainingAccounts = this.getRemainingAccounts({
3048
3049
  userAccounts: [this.getUserAccountOrThrow(subAccountId)],
@@ -3068,7 +3069,7 @@ class VelocityClient {
3068
3069
  user,
3069
3070
  userStats: this.getUserStatsAccountPublicKey(),
3070
3071
  userTokenAccount,
3071
- authority: this.wallet.publicKey,
3072
+ authority: (_a = overrides === null || overrides === void 0 ? void 0 : overrides.authority) !== null && _a !== void 0 ? _a : this.wallet.publicKey,
3072
3073
  tokenProgram,
3073
3074
  remainingAccounts,
3074
3075
  });
@@ -3154,14 +3155,23 @@ class VelocityClient {
3154
3155
  * @param marketIndex - Spot market index of the balance to transfer.
3155
3156
  * @param fromSubAccountId - Sub-account id to debit.
3156
3157
  * @param toSubAccountId - Sub-account id to credit.
3158
+ * @param equityFloorDelta - Equity floor (QUOTE_PRECISION) to move from the debited to the credited
3159
+ * sub-account along with the funds, keeping the sum of floors constant. The debited side must stay
3160
+ * at/above its reduced floor and the credited side's collateral (after the transfer lands) must back
3161
+ * its increased floor, else the transfer reverts with `InvalidEquityFloorTransfer`. Pass `'auto'`
3162
+ * (quote market only) to move the minimal floor needed for the debited side to stay at/above its
3163
+ * floor: `max(0, amount - (collateral - floor))`, capped at the debited side's floor. The auto delta
3164
+ * never exceeds `amount`, so the credited side stays backed whenever it was before. Client-side
3165
+ * pricing can differ slightly from the on-chain strict check at the exact boundary; retry with an
3166
+ * explicit padded delta if an `'auto'` transfer reverts. Defaults to zero.
3157
3167
  * @param txParams - Optional compute-unit/priority-fee overrides for the transaction.
3158
3168
  * @returns The transaction signature.
3159
3169
  * @throws (on-chain) if `allowDelegateTransfer` is not enabled, if the signer is not the delegate on
3160
3170
  * both sub-accounts, if the sub-accounts have different owners, if either is bankrupt, or if
3161
3171
  * `fromSubAccountId === toSubAccountId`.
3162
3172
  */
3163
- async transferDepositByDelegate(amount, marketIndex, fromSubAccountId, toSubAccountId, txParams) {
3164
- const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getTransferDepositByDelegateIx(amount, marketIndex, fromSubAccountId, toSubAccountId), txParams), [], this.opts);
3173
+ async transferDepositByDelegate(amount, marketIndex, fromSubAccountId, toSubAccountId, equityFloorDelta = numericConstants_1.ZERO, txParams) {
3174
+ const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getTransferDepositByDelegateIx(amount, marketIndex, fromSubAccountId, toSubAccountId, equityFloorDelta), txParams), [], this.opts);
3165
3175
  if (fromSubAccountId === this.activeSubAccountId ||
3166
3176
  toSubAccountId === this.activeSubAccountId) {
3167
3177
  this.cacheSpotMarketSlot(slot, marketIndex);
@@ -3179,28 +3189,49 @@ class VelocityClient {
3179
3189
  * @param toSubAccountId - Sub-account id to credit.
3180
3190
  * @returns The instruction.
3181
3191
  */
3182
- async getTransferDepositByDelegateIx(amount, marketIndex, fromSubAccountId, toSubAccountId) {
3192
+ async getTransferDepositByDelegateIx(amount, marketIndex, fromSubAccountId, toSubAccountId, equityFloorDelta = numericConstants_1.ZERO) {
3183
3193
  const fromUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.authority, fromSubAccountId);
3184
3194
  const toUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.authority, toSubAccountId);
3185
- let remainingAccounts;
3186
- const userMapKey = this.getUserMapKey(fromSubAccountId, this.authority);
3187
- const mapUser = this.users.get(userMapKey);
3188
- if (mapUser) {
3189
- remainingAccounts = this.getRemainingAccounts({
3190
- userAccounts: [mapUser.getUserAccountOrThrow()],
3191
- useMarketLastSlotCache: true,
3192
- writableSpotMarketIndexes: [marketIndex],
3193
- });
3195
+ let resolvedFloorDelta;
3196
+ if (equityFloorDelta === 'auto') {
3197
+ // auto assumes amount and equity share QUOTE_PRECISION; for
3198
+ // non-quote markets the caller must value the tokens themselves
3199
+ if (marketIndex !== numericConstants_1.QUOTE_SPOT_MARKET_INDEX) {
3200
+ throw new Error("equityFloorDelta 'auto' is only supported for the quote spot market; pass an explicit delta");
3201
+ }
3202
+ const fromUserClass = this.getUser(fromSubAccountId, this.authority);
3203
+ const floor = fromUserClass.getUserAccountOrThrow().equityFloor;
3204
+ if (floor.lte(numericConstants_1.ZERO)) {
3205
+ resolvedFloorDelta = numericConstants_1.ZERO;
3206
+ }
3207
+ else {
3208
+ const excess = anchor_1.BN.max(fromUserClass.getTotalCollateral('Initial', true).sub(floor), numericConstants_1.ZERO);
3209
+ resolvedFloorDelta = anchor_1.BN.min(anchor_1.BN.max(amount.sub(excess), numericConstants_1.ZERO), floor);
3210
+ }
3194
3211
  }
3195
3212
  else {
3196
- const fromUserAccount = (await this.program.account.user.fetch(fromUser));
3197
- remainingAccounts = this.getRemainingAccounts({
3198
- userAccounts: [fromUserAccount],
3199
- useMarketLastSlotCache: true,
3200
- writableSpotMarketIndexes: [marketIndex],
3201
- });
3213
+ resolvedFloorDelta = equityFloorDelta;
3202
3214
  }
3203
- return await this.program.instruction.transferDepositByDelegate(marketIndex, amount, {
3215
+ const loadUserAccount = async (subAccountId, userPublicKey) => {
3216
+ const userMapKey = this.getUserMapKey(subAccountId, this.authority);
3217
+ const mapUser = this.users.get(userMapKey);
3218
+ if (mapUser) {
3219
+ return mapUser.getUserAccountOrThrow();
3220
+ }
3221
+ return (await this.program.account.user.fetch(userPublicKey));
3222
+ };
3223
+ // moving equity floor triggers an on-chain margin check of the credited
3224
+ // side, so its markets/oracles must be in the remaining accounts too
3225
+ const userAccounts = [await loadUserAccount(fromSubAccountId, fromUser)];
3226
+ if (resolvedFloorDelta.gt(numericConstants_1.ZERO)) {
3227
+ userAccounts.push(await loadUserAccount(toSubAccountId, toUser));
3228
+ }
3229
+ const remainingAccounts = this.getRemainingAccounts({
3230
+ userAccounts,
3231
+ useMarketLastSlotCache: true,
3232
+ writableSpotMarketIndexes: [marketIndex],
3233
+ });
3234
+ return await this.program.instruction.transferDepositByDelegate(marketIndex, amount, resolvedFloorDelta, {
3204
3235
  accounts: {
3205
3236
  delegate: this.wallet.publicKey,
3206
3237
  fromUser,
@@ -5241,6 +5272,42 @@ class VelocityClient {
5241
5272
  remainingAccounts,
5242
5273
  });
5243
5274
  }
5275
+ /**
5276
+ * Keeper instruction: trips the authority-wide equity floor breaker. Proves on-chain that the
5277
+ * given subaccount's cross-margin total collateral is below its `equityFloor` (reverts with
5278
+ * `SufficientCollateral` otherwise, or if no floor is set) and sets `equityBreakerTripped` on the
5279
+ * authority's `UserStats` — every subaccount of the authority then rejects risk-increasing fills,
5280
+ * withdrawals and transfers out until the warm admin calls `resetEquityFloorBreaker`.
5281
+ * Permissionless — any signer may trip it; the margin calculation is the proof.
5282
+ * @param userAccountPublicKey - Public key of the breached subaccount's user account.
5283
+ * @param user - Decoded user account of the breached subaccount.
5284
+ * @param txParams - Optional compute-unit/priority-fee overrides.
5285
+ * @returns The transaction signature.
5286
+ */
5287
+ async tripEquityFloorBreaker(userAccountPublicKey, user, txParams) {
5288
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getTripEquityFloorBreakerIx(userAccountPublicKey, user), txParams), [], this.opts);
5289
+ return txSig;
5290
+ }
5291
+ /**
5292
+ * Builds the `tripEquityFloorBreaker` instruction. See `tripEquityFloorBreaker` for semantics.
5293
+ * @param userAccountPublicKey - Public key of the breached subaccount's user account.
5294
+ * @param userAccount - Decoded user account of the breached subaccount.
5295
+ * @returns The instruction.
5296
+ */
5297
+ async getTripEquityFloorBreakerIx(userAccountPublicKey, userAccount) {
5298
+ const remainingAccounts = this.getRemainingAccounts({
5299
+ userAccounts: [userAccount],
5300
+ });
5301
+ return await this.program.instruction.tripEquityFloorBreaker({
5302
+ accounts: {
5303
+ state: await this.getStatePublicKey(),
5304
+ keeper: this.wallet.publicKey,
5305
+ user: userAccountPublicKey,
5306
+ userStats: (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority),
5307
+ },
5308
+ remainingAccounts,
5309
+ });
5310
+ }
5244
5311
  /**
5245
5312
  * Keeper instruction: marks a user account idle after confirming (via `validate_user_is_idle`)
5246
5313
  * it has been inactive long enough — the inactivity window is shorter (accelerated) when the
@@ -7183,11 +7250,12 @@ class VelocityClient {
7183
7250
  }
7184
7251
  /**
7185
7252
  * Keeper instruction: estimates the market's bid/ask price from the given makers' resting DLOB
7186
- * orders (filtered to those within `BID_ASK_TWAP_MAX_ORACLE_DIVERGENCE_PERCENT` of the oracle
7187
- * price) and folds the estimate into `lastBidPriceTwap`/`lastAskPriceTwap`. Restricted: the
7188
- * calling wallet's `UserStats` must have `canUpdateBidAskTwap` set and at least 1000 USDC
7189
- * (`QUOTE_PRECISION`, 1e6) staked in the insurance fund (`ifStakedQuoteAssetAmount`), or the
7190
- * instruction reverts.
7253
+ * orders (kept only within BID_ASK_TWAP_MAX_ORACLE_DIVERGENCE_PERCENT` of the oracle price on
7254
+ * both sides) and folds the estimate into `lastBidPriceTwap`/`lastAskPriceTwap`. This does NOT
7255
+ * update the funding rate, crank funding separately via `getUpdateFundingRateIx`. Restricted:
7256
+ * the calling wallet's `UserStats` (which must be the signer's own) must have
7257
+ * `canUpdateBidAskTwap` set and at least 1000 USDC (`QUOTE_PRECISION`, 1e6) staked in the
7258
+ * insurance fund (`ifStakedQuoteAssetAmount`), or the instruction reverts.
7191
7259
  * @param perpMarketIndex - Perp market index to update.
7192
7260
  * @param makers - `(maker, makerStats)` pairs whose resting orders are sampled for the estimate.
7193
7261
  * @param txParams - Optional compute-unit/priority-fee overrides.
@@ -7433,15 +7501,17 @@ class VelocityClient {
7433
7501
  * @param marketIndex - Spot market index whose insurance fund to stake into.
7434
7502
  * @returns The instruction.
7435
7503
  */
7436
- async getInitializeInsuranceFundStakeIx(marketIndex) {
7437
- const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
7504
+ async getInitializeInsuranceFundStakeIx(marketIndex, overrides) {
7505
+ var _a;
7506
+ const authority = (_a = overrides === null || overrides === void 0 ? void 0 : overrides.authority) !== null && _a !== void 0 ? _a : this.wallet.publicKey;
7507
+ const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, authority, marketIndex);
7438
7508
  const accounts = {
7439
7509
  insuranceFundStake: ifStakeAccountPublicKey,
7440
7510
  spotMarket: this.getSpotMarketAccountOrThrow(marketIndex).pubkey,
7441
- userStats: (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, this.wallet.publicKey // only allow payer to initialize own insurance fund stake account
7511
+ userStats: (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, authority // only allow payer to initialize own insurance fund stake account
7442
7512
  ),
7443
- authority: this.wallet.publicKey,
7444
- payer: this.wallet.publicKey,
7513
+ authority,
7514
+ payer: authority,
7445
7515
  rent: web3_js_1.SYSVAR_RENT_PUBKEY,
7446
7516
  systemProgram: web3_js_1.SystemProgram.programId,
7447
7517
  state: await this.getStatePublicKey(),
@@ -7462,9 +7532,11 @@ class VelocityClient {
7462
7532
  * @param collateralAccountPublicKey - Token account to debit for the stake.
7463
7533
  * @returns The instruction.
7464
7534
  */
7465
- async getAddInsuranceFundStakeIx(marketIndex, amount, collateralAccountPublicKey) {
7535
+ async getAddInsuranceFundStakeIx(marketIndex, amount, collateralAccountPublicKey, overrides) {
7536
+ var _a;
7537
+ const authority = (_a = overrides === null || overrides === void 0 ? void 0 : overrides.authority) !== null && _a !== void 0 ? _a : this.wallet.publicKey;
7466
7538
  const spotMarket = this.getSpotMarketAccountOrThrow(marketIndex);
7467
- const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
7539
+ const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, authority, marketIndex);
7468
7540
  const remainingAccounts = [];
7469
7541
  this.addTokenMintToRemainingAccounts(spotMarket, remainingAccounts);
7470
7542
  if (this.isTransferHook(spotMarket)) {
@@ -7476,9 +7548,9 @@ class VelocityClient {
7476
7548
  state: await this.getStatePublicKey(),
7477
7549
  spotMarket: spotMarket.pubkey,
7478
7550
  insuranceFundStake: ifStakeAccountPublicKey,
7479
- userStats: (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, this.wallet.publicKey // only allow payer to add to own insurance fund stake account
7551
+ userStats: (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, authority // only allow payer to add to own insurance fund stake account
7480
7552
  ),
7481
- authority: this.wallet.publicKey,
7553
+ authority,
7482
7554
  spotMarketVault: spotMarket.vault,
7483
7555
  insuranceFundVault: spotMarket.insuranceFund.vault,
7484
7556
  velocitySigner: this.getSignerPublicKey(),
@@ -2462,6 +2462,41 @@ export declare class AdminClient extends VelocityClient {
2462
2462
  * @returns The unsigned `updateSpecialUserStatus` instruction.
2463
2463
  */
2464
2464
  getUpdateSpecialUserStatusIx(userAccountPublicKey: PublicKey, status: number): Promise<TransactionInstruction>;
2465
+ /**
2466
+ * Sets a `User` account's `equityFloor`: the minimum cross-margin total
2467
+ * collateral (QUOTE_PRECISION) the account must keep. Below the floor the
2468
+ * program rejects risk-increasing order placement and fills, withdrawals,
2469
+ * and deposit/position transfers out of the account; reduce-only activity
2470
+ * stays allowed. Requires warm admin (`check_warm`); the account's
2471
+ * authority and delegate cannot change it. Pass `0` to disable.
2472
+ * @param userAccountPublicKey - `User` PDA to update.
2473
+ * @param equityFloor - New floor, QUOTE_PRECISION; `0` disables.
2474
+ * @param txParams - Optional transaction-building overrides.
2475
+ * @returns Transaction signature.
2476
+ */
2477
+ updateUserEquityFloor(userAccountPublicKey: PublicKey, equityFloor: BN, txParams?: TxParams): Promise<TransactionSignature>;
2478
+ /**
2479
+ * Builds the `updateUserEquityFloor` instruction without sending it. See
2480
+ * `updateUserEquityFloor`.
2481
+ * @returns The unsigned `updateUserEquityFloor` instruction.
2482
+ */
2483
+ getUpdateUserEquityFloorIx(userAccountPublicKey: PublicKey, equityFloor: BN): Promise<TransactionInstruction>;
2484
+ /**
2485
+ * Clears the authority-wide equity floor breaker set by the permissionless
2486
+ * `tripEquityFloorBreaker` keeper instruction, unfreezing all of the
2487
+ * authority's subaccounts. Requires warm admin (`check_warm`); intended to
2488
+ * be called after a human has reviewed why the breaker fired.
2489
+ * @param userStatsPublicKey - `UserStats` PDA of the authority to unfreeze.
2490
+ * @param txParams - Optional transaction-building overrides.
2491
+ * @returns Transaction signature.
2492
+ */
2493
+ resetEquityFloorBreaker(userStatsPublicKey: PublicKey, txParams?: TxParams): Promise<TransactionSignature>;
2494
+ /**
2495
+ * Builds the `resetEquityFloorBreaker` instruction without sending it. See
2496
+ * `resetEquityFloorBreaker`.
2497
+ * @returns The unsigned `resetEquityFloorBreaker` instruction.
2498
+ */
2499
+ getResetEquityFloorBreakerIx(userStatsPublicKey: PublicKey): Promise<TransactionInstruction>;
2465
2500
  /**
2466
2501
  * Rotates `state.warmAdmin`, the operational (multisig+timelock) tier that can
2467
2502
  * rotate every hot-role key (`updateHotAdmin`). Cold-only: the `UpdateWarmAdmin`