@velocity-exchange/sdk 0.0.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.
- package/.prettierignore +1 -0
- package/.yarn/install-state.gz +0 -0
- package/README.md +275 -0
- package/VERSION +1 -0
- package/build-browser.js +58 -0
- package/bun.lock +1885 -0
- package/esbuild-shims.js +12 -0
- package/lib/browser/accounts/basicUserAccountSubscriber.d.ts +27 -0
- package/lib/browser/accounts/basicUserAccountSubscriber.js +38 -0
- package/lib/browser/accounts/basicUserStatsAccountSubscriber.d.ts +27 -0
- package/lib/browser/accounts/basicUserStatsAccountSubscriber.js +38 -0
- package/lib/browser/accounts/bulkAccountLoader.d.ts +37 -0
- package/lib/browser/accounts/bulkAccountLoader.js +222 -0
- package/lib/browser/accounts/bulkUserStatsSubscription.d.ts +7 -0
- package/lib/browser/accounts/bulkUserStatsSubscription.js +21 -0
- package/lib/browser/accounts/bulkUserSubscription.d.ts +7 -0
- package/lib/browser/accounts/bulkUserSubscription.js +21 -0
- package/lib/browser/accounts/customizedCadenceBulkAccountLoader.d.ts +44 -0
- package/lib/browser/accounts/customizedCadenceBulkAccountLoader.js +152 -0
- package/lib/browser/accounts/fetch.d.ts +17 -0
- package/lib/browser/accounts/fetch.js +60 -0
- package/lib/browser/accounts/grpcAccountSubscriber.d.ts +17 -0
- package/lib/browser/accounts/grpcAccountSubscriber.js +162 -0
- package/lib/browser/accounts/grpcInsuranceFundStakeAccountSubscriber.d.ts +10 -0
- package/lib/browser/accounts/grpcInsuranceFundStakeAccountSubscriber.js +31 -0
- package/lib/browser/accounts/grpcMultiAccountSubscriber.d.ts +37 -0
- package/lib/browser/accounts/grpcMultiAccountSubscriber.js +378 -0
- package/lib/browser/accounts/grpcMultiUserAccountSubscriber.d.ts +25 -0
- package/lib/browser/accounts/grpcMultiUserAccountSubscriber.js +203 -0
- package/lib/browser/accounts/grpcProgramAccountSubscriber.d.ts +18 -0
- package/lib/browser/accounts/grpcProgramAccountSubscriber.js +179 -0
- package/lib/browser/accounts/grpcUserAccountSubscriber.d.ts +10 -0
- package/lib/browser/accounts/grpcUserAccountSubscriber.js +28 -0
- package/lib/browser/accounts/grpcUserStatsAccountSubscriber.d.ts +10 -0
- package/lib/browser/accounts/grpcUserStatsAccountSubscriber.js +28 -0
- package/lib/browser/accounts/grpcVelocityClientAccountSubscriber.d.ts +16 -0
- package/lib/browser/accounts/grpcVelocityClientAccountSubscriber.js +101 -0
- package/lib/browser/accounts/grpcVelocityClientAccountSubscriberV2.d.ts +69 -0
- package/lib/browser/accounts/grpcVelocityClientAccountSubscriberV2.js +457 -0
- package/lib/browser/accounts/laserProgramAccountSubscriber.d.ts +23 -0
- package/lib/browser/accounts/laserProgramAccountSubscriber.js +162 -0
- package/lib/browser/accounts/oneShotUserAccountSubscriber.d.ts +18 -0
- package/lib/browser/accounts/oneShotUserAccountSubscriber.js +48 -0
- package/lib/browser/accounts/oneShotUserStatsAccountSubscriber.d.ts +18 -0
- package/lib/browser/accounts/oneShotUserStatsAccountSubscriber.js +48 -0
- package/lib/browser/accounts/pollingInsuranceFundStakeAccountSubscriber.d.ts +29 -0
- package/lib/browser/accounts/pollingInsuranceFundStakeAccountSubscriber.js +110 -0
- package/lib/browser/accounts/pollingOracleAccountSubscriber.d.ts +27 -0
- package/lib/browser/accounts/pollingOracleAccountSubscriber.js +78 -0
- package/lib/browser/accounts/pollingTokenAccountSubscriber.d.ts +26 -0
- package/lib/browser/accounts/pollingTokenAccountSubscriber.js +78 -0
- package/lib/browser/accounts/pollingUserAccountSubscriber.d.ts +29 -0
- package/lib/browser/accounts/pollingUserAccountSubscriber.js +102 -0
- package/lib/browser/accounts/pollingUserStatsAccountSubscriber.d.ts +27 -0
- package/lib/browser/accounts/pollingUserStatsAccountSubscriber.js +94 -0
- package/lib/browser/accounts/pollingVelocityClientAccountSubscriber.d.ts +73 -0
- package/lib/browser/accounts/pollingVelocityClientAccountSubscriber.js +420 -0
- package/lib/browser/accounts/testBulkAccountLoader.d.ts +4 -0
- package/lib/browser/accounts/testBulkAccountLoader.js +43 -0
- package/lib/browser/accounts/types.d.ts +205 -0
- package/lib/browser/accounts/types.js +16 -0
- package/lib/browser/accounts/utils.d.ts +8 -0
- package/lib/browser/accounts/utils.js +49 -0
- package/lib/browser/accounts/webSocketAccountSubscriber.d.ts +29 -0
- package/lib/browser/accounts/webSocketAccountSubscriber.js +170 -0
- package/lib/browser/accounts/webSocketAccountSubscriberV2.d.ts +109 -0
- package/lib/browser/accounts/webSocketAccountSubscriberV2.js +395 -0
- package/lib/browser/accounts/webSocketInsuranceFundStakeAccountSubscriber.d.ts +23 -0
- package/lib/browser/accounts/webSocketInsuranceFundStakeAccountSubscriber.js +67 -0
- package/lib/browser/accounts/webSocketProgramAccountSubscriber.d.ts +31 -0
- package/lib/browser/accounts/webSocketProgramAccountSubscriber.js +120 -0
- package/lib/browser/accounts/webSocketProgramAccountSubscriberV2.d.ts +145 -0
- package/lib/browser/accounts/webSocketProgramAccountSubscriberV2.js +744 -0
- package/lib/browser/accounts/webSocketProgramAccountsSubscriberV2.d.ts +145 -0
- package/lib/browser/accounts/webSocketProgramAccountsSubscriberV2.js +744 -0
- package/lib/browser/accounts/webSocketUserAccountSubscriber.d.ts +23 -0
- package/lib/browser/accounts/webSocketUserAccountSubscriber.js +61 -0
- package/lib/browser/accounts/webSocketUserStatsAccountSubsriber.d.ts +22 -0
- package/lib/browser/accounts/webSocketUserStatsAccountSubsriber.js +52 -0
- package/lib/browser/accounts/webSocketVelocityClientAccountSubscriber.d.ts +77 -0
- package/lib/browser/accounts/webSocketVelocityClientAccountSubscriber.js +400 -0
- package/lib/browser/accounts/webSocketVelocityClientAccountSubscriberV2.d.ts +91 -0
- package/lib/browser/accounts/webSocketVelocityClientAccountSubscriberV2.js +446 -0
- package/lib/browser/accounts/websocketProgramUserAccountSubscriber.d.ts +22 -0
- package/lib/browser/accounts/websocketProgramUserAccountSubscriber.js +54 -0
- package/lib/browser/addresses/marketAddresses.d.ts +2 -0
- package/lib/browser/addresses/marketAddresses.js +15 -0
- package/lib/browser/addresses/pda.d.ts +47 -0
- package/lib/browser/addresses/pda.js +263 -0
- package/lib/browser/adminClient.d.ts +402 -0
- package/lib/browser/adminClient.js +2798 -0
- package/lib/browser/assert/assert.d.ts +1 -0
- package/lib/browser/assert/assert.js +9 -0
- package/lib/browser/auctionSubscriber/auctionSubscriber.d.ts +14 -0
- package/lib/browser/auctionSubscriber/auctionSubscriber.js +32 -0
- package/lib/browser/auctionSubscriber/auctionSubscriberGrpc.d.ts +15 -0
- package/lib/browser/auctionSubscriber/auctionSubscriberGrpc.js +32 -0
- package/lib/browser/auctionSubscriber/index.d.ts +3 -0
- package/lib/browser/auctionSubscriber/index.js +19 -0
- package/lib/browser/auctionSubscriber/types.d.ts +14 -0
- package/lib/browser/auctionSubscriber/types.js +2 -0
- package/lib/browser/bankrun/bankrunConnection.d.ts +76 -0
- package/lib/browser/bankrun/bankrunConnection.js +348 -0
- package/lib/browser/blockhashSubscriber/BlockhashSubscriber.d.ts +27 -0
- package/lib/browser/blockhashSubscriber/BlockhashSubscriber.js +89 -0
- package/lib/browser/blockhashSubscriber/index.d.ts +1 -0
- package/lib/browser/blockhashSubscriber/index.js +17 -0
- package/lib/browser/blockhashSubscriber/types.d.ts +7 -0
- package/lib/browser/blockhashSubscriber/types.js +2 -0
- package/lib/browser/clock/clockSubscriber.d.ts +31 -0
- package/lib/browser/clock/clockSubscriber.js +80 -0
- package/lib/browser/config.d.ts +75 -0
- package/lib/browser/config.js +164 -0
- package/lib/browser/constants/index.d.ts +10 -0
- package/lib/browser/constants/index.js +26 -0
- package/lib/browser/constants/insuranceFund.d.ts +5 -0
- package/lib/browser/constants/insuranceFund.js +9 -0
- package/lib/browser/constants/numericConstants.d.ts +73 -0
- package/lib/browser/constants/numericConstants.js +79 -0
- package/lib/browser/constants/perpMarkets.d.ts +21 -0
- package/lib/browser/constants/perpMarkets.js +971 -0
- package/lib/browser/constants/spotMarkets.d.ts +24 -0
- package/lib/browser/constants/spotMarkets.js +797 -0
- package/lib/browser/constants/txConstants.d.ts +1 -0
- package/lib/browser/constants/txConstants.js +4 -0
- package/lib/browser/constituentMap/constituentMap.d.ts +66 -0
- package/lib/browser/constituentMap/constituentMap.js +177 -0
- package/lib/browser/constituentMap/pollingConstituentAccountSubscriber.d.ts +24 -0
- package/lib/browser/constituentMap/pollingConstituentAccountSubscriber.js +60 -0
- package/lib/browser/constituentMap/webSocketConstituentAccountSubscriber.d.ts +24 -0
- package/lib/browser/constituentMap/webSocketConstituentAccountSubscriber.js +58 -0
- package/lib/browser/core/VelocityCore.d.ts +226 -0
- package/lib/browser/core/VelocityCore.js +138 -0
- package/lib/browser/core/index.d.ts +12 -0
- package/lib/browser/core/index.js +28 -0
- package/lib/browser/core/instructions/deposit.d.ts +19 -0
- package/lib/browser/core/instructions/deposit.js +19 -0
- package/lib/browser/core/instructions/fill.d.ts +13 -0
- package/lib/browser/core/instructions/fill.js +17 -0
- package/lib/browser/core/instructions/funding.d.ts +9 -0
- package/lib/browser/core/instructions/funding.js +13 -0
- package/lib/browser/core/instructions/liquidation.d.ts +15 -0
- package/lib/browser/core/instructions/liquidation.js +17 -0
- package/lib/browser/core/instructions/orders.d.ts +22 -0
- package/lib/browser/core/instructions/orders.js +27 -0
- package/lib/browser/core/instructions/perpOrders.d.ts +78 -0
- package/lib/browser/core/instructions/perpOrders.js +99 -0
- package/lib/browser/core/instructions/settlement.d.ts +11 -0
- package/lib/browser/core/instructions/settlement.js +15 -0
- package/lib/browser/core/instructions/trigger.d.ts +11 -0
- package/lib/browser/core/instructions/trigger.js +15 -0
- package/lib/browser/core/instructions/withdraw.d.ts +20 -0
- package/lib/browser/core/instructions/withdraw.js +20 -0
- package/lib/browser/core/remainingAccounts.d.ts +27 -0
- package/lib/browser/core/remainingAccounts.js +122 -0
- package/lib/browser/core/signedMsg.d.ts +17 -0
- package/lib/browser/core/signedMsg.js +39 -0
- package/lib/browser/decode/customCoder.d.ts +44 -0
- package/lib/browser/decode/customCoder.js +64 -0
- package/lib/browser/decode/user.d.ts +4 -0
- package/lib/browser/decode/user.js +337 -0
- package/lib/browser/dlob/DLOB.d.ts +253 -0
- package/lib/browser/dlob/DLOB.js +1137 -0
- package/lib/browser/dlob/DLOBNode.d.ts +70 -0
- package/lib/browser/dlob/DLOBNode.js +103 -0
- package/lib/browser/dlob/DLOBSubscriber.d.ts +57 -0
- package/lib/browser/dlob/DLOBSubscriber.js +143 -0
- package/lib/browser/dlob/NodeList.d.ts +27 -0
- package/lib/browser/dlob/NodeList.js +126 -0
- package/lib/browser/dlob/orderBookLevels.d.ts +77 -0
- package/lib/browser/dlob/orderBookLevels.js +404 -0
- package/lib/browser/dlob/types.d.ts +18 -0
- package/lib/browser/dlob/types.js +2 -0
- package/lib/browser/events/eventList.d.ts +22 -0
- package/lib/browser/events/eventList.js +80 -0
- package/lib/browser/events/eventSubscriber.d.ts +55 -0
- package/lib/browser/events/eventSubscriber.js +229 -0
- package/lib/browser/events/eventsServerLogProvider.d.ts +21 -0
- package/lib/browser/events/eventsServerLogProvider.js +121 -0
- package/lib/browser/events/fetchLogs.d.ts +25 -0
- package/lib/browser/events/fetchLogs.js +99 -0
- package/lib/browser/events/parse.d.ts +8 -0
- package/lib/browser/events/parse.js +199 -0
- package/lib/browser/events/pollingLogProvider.d.ts +17 -0
- package/lib/browser/events/pollingLogProvider.js +58 -0
- package/lib/browser/events/sort.d.ts +2 -0
- package/lib/browser/events/sort.js +24 -0
- package/lib/browser/events/txEventCache.d.ts +24 -0
- package/lib/browser/events/txEventCache.js +71 -0
- package/lib/browser/events/types.d.ts +104 -0
- package/lib/browser/events/types.js +36 -0
- package/lib/browser/events/webSocketLogProvider.d.ts +24 -0
- package/lib/browser/events/webSocketLogProvider.js +96 -0
- package/lib/browser/factory/bigNum.d.ts +122 -0
- package/lib/browser/factory/bigNum.js +500 -0
- package/lib/browser/factory/oracleClient.d.ts +5 -0
- package/lib/browser/factory/oracleClient.js +53 -0
- package/lib/browser/idl/drift.d.ts +23894 -0
- package/lib/browser/idl/drift.js +2 -0
- package/lib/browser/idl/drift.json +18698 -0
- package/lib/browser/idl/pyth.d.ts +97 -0
- package/lib/browser/idl/pyth.js +2 -0
- package/lib/browser/idl/token_faucet.d.ts +197 -0
- package/lib/browser/idl/token_faucet.js +2 -0
- package/lib/browser/idl/token_faucet.json +229 -0
- package/lib/browser/index.d.ts +144 -0
- package/lib/browser/index.js +175 -0
- package/lib/browser/indicative-quotes/indicativeQuotesSender.d.ts +35 -0
- package/lib/browser/indicative-quotes/indicativeQuotesSender.js +192 -0
- package/lib/browser/isomorphic/anchor.browser.d.ts +24 -0
- package/lib/browser/isomorphic/anchor.browser.js +60 -0
- package/lib/browser/isomorphic/anchor.d.ts +24 -0
- package/lib/browser/isomorphic/anchor.js +60 -0
- package/lib/browser/isomorphic/anchor29.browser.d.ts +12 -0
- package/lib/browser/isomorphic/anchor29.browser.js +48 -0
- package/lib/browser/isomorphic/anchor29.d.ts +12 -0
- package/lib/browser/isomorphic/anchor29.js +48 -0
- package/lib/browser/isomorphic/grpc.browser.d.ts +1 -0
- package/lib/browser/isomorphic/grpc.browser.js +8 -0
- package/lib/browser/isomorphic/grpc.d.ts +1 -0
- package/lib/browser/isomorphic/grpc.js +8 -0
- package/lib/browser/jupiter/jupiterClient.d.ts +291 -0
- package/lib/browser/jupiter/jupiterClient.js +164 -0
- package/lib/browser/keypair.d.ts +2 -0
- package/lib/browser/keypair.js +28 -0
- package/lib/browser/marginCalculation.d.ts +67 -0
- package/lib/browser/marginCalculation.js +176 -0
- package/lib/browser/marinade/index.d.ts +12 -0
- package/lib/browser/marinade/index.js +36 -0
- package/lib/browser/marinade/types.d.ts +1963 -0
- package/lib/browser/marinade/types.js +1965 -0
- package/lib/browser/math/amm.d.ts +98 -0
- package/lib/browser/math/amm.js +671 -0
- package/lib/browser/math/auction.d.ts +65 -0
- package/lib/browser/math/auction.js +261 -0
- package/lib/browser/math/bankruptcy.d.ts +2 -0
- package/lib/browser/math/bankruptcy.js +32 -0
- package/lib/browser/math/builder.d.ts +5 -0
- package/lib/browser/math/builder.js +22 -0
- package/lib/browser/math/conversion.d.ts +4 -0
- package/lib/browser/math/conversion.js +21 -0
- package/lib/browser/math/exchangeStatus.d.ts +8 -0
- package/lib/browser/math/exchangeStatus.js +85 -0
- package/lib/browser/math/funding.d.ts +44 -0
- package/lib/browser/math/funding.js +260 -0
- package/lib/browser/math/insurance.d.ts +8 -0
- package/lib/browser/math/insurance.js +74 -0
- package/lib/browser/math/liquidation.d.ts +7 -0
- package/lib/browser/math/liquidation.js +134 -0
- package/lib/browser/math/margin.d.ts +45 -0
- package/lib/browser/math/margin.js +205 -0
- package/lib/browser/math/market.d.ts +50 -0
- package/lib/browser/math/market.js +234 -0
- package/lib/browser/math/oracles.d.ts +19 -0
- package/lib/browser/math/oracles.js +215 -0
- package/lib/browser/math/orders.d.ts +36 -0
- package/lib/browser/math/orders.js +294 -0
- package/lib/browser/math/position.d.ts +71 -0
- package/lib/browser/math/position.js +232 -0
- package/lib/browser/math/repeg.d.ts +22 -0
- package/lib/browser/math/repeg.js +164 -0
- package/lib/browser/math/spotBalance.d.ts +85 -0
- package/lib/browser/math/spotBalance.js +438 -0
- package/lib/browser/math/spotMarket.d.ts +11 -0
- package/lib/browser/math/spotMarket.js +49 -0
- package/lib/browser/math/spotPosition.d.ts +19 -0
- package/lib/browser/math/spotPosition.js +79 -0
- package/lib/browser/math/state.d.ts +8 -0
- package/lib/browser/math/state.js +44 -0
- package/lib/browser/math/superStake.d.ts +168 -0
- package/lib/browser/math/superStake.js +308 -0
- package/lib/browser/math/tiers.d.ts +4 -0
- package/lib/browser/math/tiers.js +52 -0
- package/lib/browser/math/trade.d.ts +93 -0
- package/lib/browser/math/trade.js +503 -0
- package/lib/browser/math/utils.d.ts +23 -0
- package/lib/browser/math/utils.js +113 -0
- package/lib/browser/memcmp.d.ts +18 -0
- package/lib/browser/memcmp.js +162 -0
- package/lib/browser/oracles/oracleClientCache.d.ts +9 -0
- package/lib/browser/oracles/oracleClientCache.js +19 -0
- package/lib/browser/oracles/oracleId.d.ts +9 -0
- package/lib/browser/oracles/oracleId.js +89 -0
- package/lib/browser/oracles/prelaunchOracleClient.d.ts +12 -0
- package/lib/browser/oracles/prelaunchOracleClient.js +24 -0
- package/lib/browser/oracles/pythClient.d.ts +14 -0
- package/lib/browser/oracles/pythClient.js +51 -0
- package/lib/browser/oracles/pythLazerClient.d.ts +16 -0
- package/lib/browser/oracles/pythLazerClient.js +61 -0
- package/lib/browser/oracles/quoteAssetOracleClient.d.ts +10 -0
- package/lib/browser/oracles/quoteAssetOracleClient.js +21 -0
- package/lib/browser/oracles/strictOraclePrice.d.ts +9 -0
- package/lib/browser/oracles/strictOraclePrice.js +17 -0
- package/lib/browser/oracles/types.d.ts +33 -0
- package/lib/browser/oracles/types.js +2 -0
- package/lib/browser/oracles/utils.d.ts +4 -0
- package/lib/browser/oracles/utils.js +8 -0
- package/lib/browser/orderParams.d.ts +29 -0
- package/lib/browser/orderParams.js +44 -0
- package/lib/browser/orderSubscriber/OrderSubscriber.d.ts +45 -0
- package/lib/browser/orderSubscriber/OrderSubscriber.js +193 -0
- package/lib/browser/orderSubscriber/PollingSubscription.d.ts +12 -0
- package/lib/browser/orderSubscriber/PollingSubscription.js +23 -0
- package/lib/browser/orderSubscriber/WebsocketSubscription.d.ts +23 -0
- package/lib/browser/orderSubscriber/WebsocketSubscription.js +67 -0
- package/lib/browser/orderSubscriber/grpcSubscription.d.ts +22 -0
- package/lib/browser/orderSubscriber/grpcSubscription.js +75 -0
- package/lib/browser/orderSubscriber/index.d.ts +7 -0
- package/lib/browser/orderSubscriber/index.js +23 -0
- package/lib/browser/orderSubscriber/types.d.ts +35 -0
- package/lib/browser/orderSubscriber/types.js +2 -0
- package/lib/browser/priorityFee/averageOverSlotsStrategy.d.ts +5 -0
- package/lib/browser/priorityFee/averageOverSlotsStrategy.js +16 -0
- package/lib/browser/priorityFee/averageStrategy.d.ts +5 -0
- package/lib/browser/priorityFee/averageStrategy.js +11 -0
- package/lib/browser/priorityFee/ewmaStrategy.d.ts +11 -0
- package/lib/browser/priorityFee/ewmaStrategy.js +33 -0
- package/lib/browser/priorityFee/heliusPriorityFeeMethod.d.ts +20 -0
- package/lib/browser/priorityFee/heliusPriorityFeeMethod.js +46 -0
- package/lib/browser/priorityFee/index.d.ts +16 -0
- package/lib/browser/priorityFee/index.js +32 -0
- package/lib/browser/priorityFee/maxOverSlotsStrategy.d.ts +5 -0
- package/lib/browser/priorityFee/maxOverSlotsStrategy.js +17 -0
- package/lib/browser/priorityFee/maxStrategy.d.ts +7 -0
- package/lib/browser/priorityFee/maxStrategy.js +9 -0
- package/lib/browser/priorityFee/priorityFeeSubscriber.d.ts +48 -0
- package/lib/browser/priorityFee/priorityFeeSubscriber.js +193 -0
- package/lib/browser/priorityFee/priorityFeeSubscriberMap.d.ts +50 -0
- package/lib/browser/priorityFee/priorityFeeSubscriberMap.js +96 -0
- package/lib/browser/priorityFee/solanaPriorityFeeMethod.d.ts +6 -0
- package/lib/browser/priorityFee/solanaPriorityFeeMethod.js +21 -0
- package/lib/browser/priorityFee/types.d.ts +35 -0
- package/lib/browser/priorityFee/types.js +10 -0
- package/lib/browser/priorityFee/velocityPriorityFeeMethod.d.ts +21 -0
- package/lib/browser/priorityFee/velocityPriorityFeeMethod.js +28 -0
- package/lib/browser/pyth/constants.d.ts +3 -0
- package/lib/browser/pyth/constants.js +6 -0
- package/lib/browser/pyth/index.d.ts +4 -0
- package/lib/browser/pyth/index.js +12 -0
- package/lib/browser/pyth/pythLazerSubscriber.d.ts +91 -0
- package/lib/browser/pyth/pythLazerSubscriber.js +276 -0
- package/lib/browser/pyth/types.d.ts +2226 -0
- package/lib/browser/pyth/types.js +2224 -0
- package/lib/browser/pyth/utils.d.ts +2 -0
- package/lib/browser/pyth/utils.js +10 -0
- package/lib/browser/slot/SlotSubscriber.d.ts +27 -0
- package/lib/browser/slot/SlotSubscriber.js +76 -0
- package/lib/browser/slot/SlothashSubscriber.d.ts +25 -0
- package/lib/browser/slot/SlothashSubscriber.js +88 -0
- package/lib/browser/swap/UnifiedSwapClient.d.ts +120 -0
- package/lib/browser/swap/UnifiedSwapClient.js +179 -0
- package/lib/browser/swift/grpcSignedMsgUserAccountSubscriber.d.ts +22 -0
- package/lib/browser/swift/grpcSignedMsgUserAccountSubscriber.js +57 -0
- package/lib/browser/swift/index.d.ts +10 -0
- package/lib/browser/swift/index.js +26 -0
- package/lib/browser/swift/signedMsgUserAccountSubscriber.d.ts +42 -0
- package/lib/browser/swift/signedMsgUserAccountSubscriber.js +118 -0
- package/lib/browser/swift/swiftOrderSubscriber.d.ts +63 -0
- package/lib/browser/swift/swiftOrderSubscriber.js +187 -0
- package/lib/browser/testClient.d.ts +8 -0
- package/lib/browser/testClient.js +24 -0
- package/lib/browser/titan/titanClient.d.ts +90 -0
- package/lib/browser/titan/titanClient.js +227 -0
- package/lib/browser/token/index.d.ts +5 -0
- package/lib/browser/token/index.js +15 -0
- package/lib/browser/tokenFaucet.d.ts +41 -0
- package/lib/browser/tokenFaucet.js +188 -0
- package/lib/browser/tx/baseTxSender.d.ts +59 -0
- package/lib/browser/tx/baseTxSender.js +292 -0
- package/lib/browser/tx/blockhashFetcher/baseBlockhashFetcher.d.ts +8 -0
- package/lib/browser/tx/blockhashFetcher/baseBlockhashFetcher.js +13 -0
- package/lib/browser/tx/blockhashFetcher/cachedBlockhashFetcher.d.ts +28 -0
- package/lib/browser/tx/blockhashFetcher/cachedBlockhashFetcher.js +73 -0
- package/lib/browser/tx/blockhashFetcher/types.d.ts +4 -0
- package/lib/browser/tx/blockhashFetcher/types.js +2 -0
- package/lib/browser/tx/fastSingleTxSender.d.ts +41 -0
- package/lib/browser/tx/fastSingleTxSender.js +86 -0
- package/lib/browser/tx/forwardOnlyTxSender.d.ts +37 -0
- package/lib/browser/tx/forwardOnlyTxSender.js +92 -0
- package/lib/browser/tx/priorityFeeCalculator.d.ts +44 -0
- package/lib/browser/tx/priorityFeeCalculator.js +85 -0
- package/lib/browser/tx/reportTransactionError.d.ts +20 -0
- package/lib/browser/tx/reportTransactionError.js +103 -0
- package/lib/browser/tx/retryTxSender.d.ts +37 -0
- package/lib/browser/tx/retryTxSender.js +86 -0
- package/lib/browser/tx/txHandler.d.ts +173 -0
- package/lib/browser/tx/txHandler.js +522 -0
- package/lib/browser/tx/txParamProcessor.d.ts +26 -0
- package/lib/browser/tx/txParamProcessor.js +92 -0
- package/lib/browser/tx/types.d.ts +29 -0
- package/lib/browser/tx/types.js +20 -0
- package/lib/browser/tx/utils.d.ts +6 -0
- package/lib/browser/tx/utils.js +78 -0
- package/lib/browser/tx/whileValidTxSender.d.ts +45 -0
- package/lib/browser/tx/whileValidTxSender.js +168 -0
- package/lib/browser/types.d.ts +1747 -0
- package/lib/browser/types.js +427 -0
- package/lib/browser/user.d.ts +446 -0
- package/lib/browser/user.js +2372 -0
- package/lib/browser/userConfig.d.ts +31 -0
- package/lib/browser/userConfig.js +2 -0
- package/lib/browser/userMap/PollingSubscription.d.ts +15 -0
- package/lib/browser/userMap/PollingSubscription.js +30 -0
- package/lib/browser/userMap/WebsocketSubscription.d.ts +27 -0
- package/lib/browser/userMap/WebsocketSubscription.js +45 -0
- package/lib/browser/userMap/grpcSubscription.d.ts +27 -0
- package/lib/browser/userMap/grpcSubscription.js +44 -0
- package/lib/browser/userMap/referrerMap.d.ts +45 -0
- package/lib/browser/userMap/referrerMap.js +184 -0
- package/lib/browser/userMap/revenueShareEscrowMap.d.ts +66 -0
- package/lib/browser/userMap/revenueShareEscrowMap.js +210 -0
- package/lib/browser/userMap/userMap.d.ts +114 -0
- package/lib/browser/userMap/userMap.js +486 -0
- package/lib/browser/userMap/userMapConfig.d.ts +40 -0
- package/lib/browser/userMap/userMapConfig.js +2 -0
- package/lib/browser/userMap/userStatsMap.d.ts +66 -0
- package/lib/browser/userMap/userStatsMap.js +266 -0
- package/lib/browser/userName.d.ts +5 -0
- package/lib/browser/userName.js +21 -0
- package/lib/browser/userStats.d.ts +24 -0
- package/lib/browser/userStats.js +70 -0
- package/lib/browser/userStatsConfig.d.ts +26 -0
- package/lib/browser/userStatsConfig.js +2 -0
- package/lib/browser/util/TransactionConfirmationManager.d.ts +16 -0
- package/lib/browser/util/TransactionConfirmationManager.js +174 -0
- package/lib/browser/util/chainClock.d.ts +17 -0
- package/lib/browser/util/chainClock.js +29 -0
- package/lib/browser/util/computeUnits.d.ts +8 -0
- package/lib/browser/util/computeUnits.js +48 -0
- package/lib/browser/util/digest.d.ts +5 -0
- package/lib/browser/util/digest.js +19 -0
- package/lib/browser/util/ed25519Utils.d.ts +10 -0
- package/lib/browser/util/ed25519Utils.js +80 -0
- package/lib/browser/util/promiseTimeout.d.ts +1 -0
- package/lib/browser/util/promiseTimeout.js +14 -0
- package/lib/browser/util/tps.d.ts +2 -0
- package/lib/browser/util/tps.js +16 -0
- package/lib/browser/velocityClient.d.ts +1230 -0
- package/lib/browser/velocityClient.js +5778 -0
- package/lib/browser/velocityClientConfig.d.ts +84 -0
- package/lib/browser/velocityClientConfig.js +2 -0
- package/lib/browser/wallet.d.ts +16 -0
- package/lib/browser/wallet.js +46 -0
- package/lib/node/accounts/basicUserAccountSubscriber.d.ts +28 -0
- package/lib/node/accounts/basicUserAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/basicUserAccountSubscriber.js +38 -0
- package/lib/node/accounts/basicUserStatsAccountSubscriber.d.ts +28 -0
- package/lib/node/accounts/basicUserStatsAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/basicUserStatsAccountSubscriber.js +38 -0
- package/lib/node/accounts/bulkAccountLoader.d.ts +38 -0
- package/lib/node/accounts/bulkAccountLoader.d.ts.map +1 -0
- package/lib/node/accounts/bulkAccountLoader.js +222 -0
- package/lib/node/accounts/bulkUserStatsSubscription.d.ts +8 -0
- package/lib/node/accounts/bulkUserStatsSubscription.d.ts.map +1 -0
- package/lib/node/accounts/bulkUserStatsSubscription.js +21 -0
- package/lib/node/accounts/bulkUserSubscription.d.ts +8 -0
- package/lib/node/accounts/bulkUserSubscription.d.ts.map +1 -0
- package/lib/node/accounts/bulkUserSubscription.js +21 -0
- package/lib/node/accounts/customizedCadenceBulkAccountLoader.d.ts +45 -0
- package/lib/node/accounts/customizedCadenceBulkAccountLoader.d.ts.map +1 -0
- package/lib/node/accounts/customizedCadenceBulkAccountLoader.js +152 -0
- package/lib/node/accounts/fetch.d.ts +18 -0
- package/lib/node/accounts/fetch.d.ts.map +1 -0
- package/lib/node/accounts/fetch.js +60 -0
- package/lib/node/accounts/grpcAccountSubscriber.d.ts +18 -0
- package/lib/node/accounts/grpcAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/grpcAccountSubscriber.js +162 -0
- package/lib/node/accounts/grpcInsuranceFundStakeAccountSubscriber.d.ts +11 -0
- package/lib/node/accounts/grpcInsuranceFundStakeAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/grpcInsuranceFundStakeAccountSubscriber.js +31 -0
- package/lib/node/accounts/grpcMultiAccountSubscriber.d.ts +38 -0
- package/lib/node/accounts/grpcMultiAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/grpcMultiAccountSubscriber.js +378 -0
- package/lib/node/accounts/grpcMultiUserAccountSubscriber.d.ts +26 -0
- package/lib/node/accounts/grpcMultiUserAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/grpcMultiUserAccountSubscriber.js +203 -0
- package/lib/node/accounts/grpcProgramAccountSubscriber.d.ts +19 -0
- package/lib/node/accounts/grpcProgramAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/grpcProgramAccountSubscriber.js +179 -0
- package/lib/node/accounts/grpcUserAccountSubscriber.d.ts +11 -0
- package/lib/node/accounts/grpcUserAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/grpcUserAccountSubscriber.js +28 -0
- package/lib/node/accounts/grpcUserStatsAccountSubscriber.d.ts +11 -0
- package/lib/node/accounts/grpcUserStatsAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/grpcUserStatsAccountSubscriber.js +28 -0
- package/lib/node/accounts/grpcVelocityClientAccountSubscriber.d.ts +17 -0
- package/lib/node/accounts/grpcVelocityClientAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/grpcVelocityClientAccountSubscriber.js +101 -0
- package/lib/node/accounts/grpcVelocityClientAccountSubscriberV2.d.ts +70 -0
- package/lib/node/accounts/grpcVelocityClientAccountSubscriberV2.d.ts.map +1 -0
- package/lib/node/accounts/grpcVelocityClientAccountSubscriberV2.js +457 -0
- package/lib/node/accounts/laserProgramAccountSubscriber.d.ts +24 -0
- package/lib/node/accounts/laserProgramAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/laserProgramAccountSubscriber.js +162 -0
- package/lib/node/accounts/oneShotUserAccountSubscriber.d.ts +19 -0
- package/lib/node/accounts/oneShotUserAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/oneShotUserAccountSubscriber.js +48 -0
- package/lib/node/accounts/oneShotUserStatsAccountSubscriber.d.ts +19 -0
- package/lib/node/accounts/oneShotUserStatsAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/oneShotUserStatsAccountSubscriber.js +48 -0
- package/lib/node/accounts/pollingInsuranceFundStakeAccountSubscriber.d.ts +30 -0
- package/lib/node/accounts/pollingInsuranceFundStakeAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/pollingInsuranceFundStakeAccountSubscriber.js +110 -0
- package/lib/node/accounts/pollingOracleAccountSubscriber.d.ts +28 -0
- package/lib/node/accounts/pollingOracleAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/pollingOracleAccountSubscriber.js +78 -0
- package/lib/node/accounts/pollingTokenAccountSubscriber.d.ts +27 -0
- package/lib/node/accounts/pollingTokenAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/pollingTokenAccountSubscriber.js +78 -0
- package/lib/node/accounts/pollingUserAccountSubscriber.d.ts +30 -0
- package/lib/node/accounts/pollingUserAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/pollingUserAccountSubscriber.js +102 -0
- package/lib/node/accounts/pollingUserStatsAccountSubscriber.d.ts +28 -0
- package/lib/node/accounts/pollingUserStatsAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/pollingUserStatsAccountSubscriber.js +94 -0
- package/lib/node/accounts/pollingVelocityClientAccountSubscriber.d.ts +74 -0
- package/lib/node/accounts/pollingVelocityClientAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/pollingVelocityClientAccountSubscriber.js +420 -0
- package/lib/node/accounts/testBulkAccountLoader.d.ts +5 -0
- package/lib/node/accounts/testBulkAccountLoader.d.ts.map +1 -0
- package/lib/node/accounts/testBulkAccountLoader.js +43 -0
- package/lib/node/accounts/types.d.ts +206 -0
- package/lib/node/accounts/types.d.ts.map +1 -0
- package/lib/node/accounts/types.js +16 -0
- package/lib/node/accounts/utils.d.ts +9 -0
- package/lib/node/accounts/utils.d.ts.map +1 -0
- package/lib/node/accounts/utils.js +49 -0
- package/lib/node/accounts/webSocketAccountSubscriber.d.ts +30 -0
- package/lib/node/accounts/webSocketAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/webSocketAccountSubscriber.js +170 -0
- package/lib/node/accounts/webSocketAccountSubscriberV2.d.ts +110 -0
- package/lib/node/accounts/webSocketAccountSubscriberV2.d.ts.map +1 -0
- package/lib/node/accounts/webSocketAccountSubscriberV2.js +395 -0
- package/lib/node/accounts/webSocketInsuranceFundStakeAccountSubscriber.d.ts +24 -0
- package/lib/node/accounts/webSocketInsuranceFundStakeAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/webSocketInsuranceFundStakeAccountSubscriber.js +67 -0
- package/lib/node/accounts/webSocketProgramAccountSubscriber.d.ts +32 -0
- package/lib/node/accounts/webSocketProgramAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/webSocketProgramAccountSubscriber.js +120 -0
- package/lib/node/accounts/webSocketProgramAccountSubscriberV2.d.ts +146 -0
- package/lib/node/accounts/webSocketProgramAccountSubscriberV2.d.ts.map +1 -0
- package/lib/node/accounts/webSocketProgramAccountSubscriberV2.js +744 -0
- package/lib/node/accounts/webSocketProgramAccountsSubscriberV2.d.ts +146 -0
- package/lib/node/accounts/webSocketProgramAccountsSubscriberV2.d.ts.map +1 -0
- package/lib/node/accounts/webSocketProgramAccountsSubscriberV2.js +744 -0
- package/lib/node/accounts/webSocketUserAccountSubscriber.d.ts +24 -0
- package/lib/node/accounts/webSocketUserAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/webSocketUserAccountSubscriber.js +61 -0
- package/lib/node/accounts/webSocketUserStatsAccountSubsriber.d.ts +23 -0
- package/lib/node/accounts/webSocketUserStatsAccountSubsriber.d.ts.map +1 -0
- package/lib/node/accounts/webSocketUserStatsAccountSubsriber.js +52 -0
- package/lib/node/accounts/webSocketVelocityClientAccountSubscriber.d.ts +78 -0
- package/lib/node/accounts/webSocketVelocityClientAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/webSocketVelocityClientAccountSubscriber.js +400 -0
- package/lib/node/accounts/webSocketVelocityClientAccountSubscriberV2.d.ts +92 -0
- package/lib/node/accounts/webSocketVelocityClientAccountSubscriberV2.d.ts.map +1 -0
- package/lib/node/accounts/webSocketVelocityClientAccountSubscriberV2.js +446 -0
- package/lib/node/accounts/websocketProgramUserAccountSubscriber.d.ts +23 -0
- package/lib/node/accounts/websocketProgramUserAccountSubscriber.d.ts.map +1 -0
- package/lib/node/accounts/websocketProgramUserAccountSubscriber.js +54 -0
- package/lib/node/addresses/marketAddresses.d.ts +3 -0
- package/lib/node/addresses/marketAddresses.d.ts.map +1 -0
- package/lib/node/addresses/marketAddresses.js +15 -0
- package/lib/node/addresses/pda.d.ts +48 -0
- package/lib/node/addresses/pda.d.ts.map +1 -0
- package/lib/node/addresses/pda.js +263 -0
- package/lib/node/adminClient.d.ts +403 -0
- package/lib/node/adminClient.d.ts.map +1 -0
- package/lib/node/adminClient.js +2798 -0
- package/lib/node/assert/assert.d.ts +2 -0
- package/lib/node/assert/assert.d.ts.map +1 -0
- package/lib/node/assert/assert.js +9 -0
- package/lib/node/auctionSubscriber/auctionSubscriber.d.ts +15 -0
- package/lib/node/auctionSubscriber/auctionSubscriber.d.ts.map +1 -0
- package/lib/node/auctionSubscriber/auctionSubscriber.js +32 -0
- package/lib/node/auctionSubscriber/auctionSubscriberGrpc.d.ts +16 -0
- package/lib/node/auctionSubscriber/auctionSubscriberGrpc.d.ts.map +1 -0
- package/lib/node/auctionSubscriber/auctionSubscriberGrpc.js +32 -0
- package/lib/node/auctionSubscriber/index.d.ts +4 -0
- package/lib/node/auctionSubscriber/index.d.ts.map +1 -0
- package/lib/node/auctionSubscriber/index.js +19 -0
- package/lib/node/auctionSubscriber/types.d.ts +15 -0
- package/lib/node/auctionSubscriber/types.d.ts.map +1 -0
- package/lib/node/auctionSubscriber/types.js +2 -0
- package/lib/node/bankrun/bankrunConnection.d.ts +77 -0
- package/lib/node/bankrun/bankrunConnection.d.ts.map +1 -0
- package/lib/node/bankrun/bankrunConnection.js +348 -0
- package/lib/node/blockhashSubscriber/BlockhashSubscriber.d.ts +28 -0
- package/lib/node/blockhashSubscriber/BlockhashSubscriber.d.ts.map +1 -0
- package/lib/node/blockhashSubscriber/BlockhashSubscriber.js +89 -0
- package/lib/node/blockhashSubscriber/index.d.ts +2 -0
- package/lib/node/blockhashSubscriber/index.d.ts.map +1 -0
- package/lib/node/blockhashSubscriber/index.js +17 -0
- package/lib/node/blockhashSubscriber/types.d.ts +8 -0
- package/lib/node/blockhashSubscriber/types.d.ts.map +1 -0
- package/lib/node/blockhashSubscriber/types.js +2 -0
- package/lib/node/clock/clockSubscriber.d.ts +32 -0
- package/lib/node/clock/clockSubscriber.d.ts.map +1 -0
- package/lib/node/clock/clockSubscriber.js +80 -0
- package/lib/node/config.d.ts +76 -0
- package/lib/node/config.d.ts.map +1 -0
- package/lib/node/config.js +164 -0
- package/lib/node/constants/index.d.ts +11 -0
- package/lib/node/constants/index.d.ts.map +1 -0
- package/lib/node/constants/index.js +26 -0
- package/lib/node/constants/insuranceFund.d.ts +6 -0
- package/lib/node/constants/insuranceFund.d.ts.map +1 -0
- package/lib/node/constants/insuranceFund.js +9 -0
- package/lib/node/constants/numericConstants.d.ts +74 -0
- package/lib/node/constants/numericConstants.d.ts.map +1 -0
- package/lib/node/constants/numericConstants.js +79 -0
- package/lib/node/constants/perpMarkets.d.ts +22 -0
- package/lib/node/constants/perpMarkets.d.ts.map +1 -0
- package/lib/node/constants/perpMarkets.js +971 -0
- package/lib/node/constants/spotMarkets.d.ts +25 -0
- package/lib/node/constants/spotMarkets.d.ts.map +1 -0
- package/lib/node/constants/spotMarkets.js +797 -0
- package/lib/node/constants/txConstants.d.ts +2 -0
- package/lib/node/constants/txConstants.d.ts.map +1 -0
- package/lib/node/constants/txConstants.js +4 -0
- package/lib/node/constituentMap/constituentMap.d.ts +67 -0
- package/lib/node/constituentMap/constituentMap.d.ts.map +1 -0
- package/lib/node/constituentMap/constituentMap.js +177 -0
- package/lib/node/constituentMap/pollingConstituentAccountSubscriber.d.ts +25 -0
- package/lib/node/constituentMap/pollingConstituentAccountSubscriber.d.ts.map +1 -0
- package/lib/node/constituentMap/pollingConstituentAccountSubscriber.js +60 -0
- package/lib/node/constituentMap/webSocketConstituentAccountSubscriber.d.ts +25 -0
- package/lib/node/constituentMap/webSocketConstituentAccountSubscriber.d.ts.map +1 -0
- package/lib/node/constituentMap/webSocketConstituentAccountSubscriber.js +58 -0
- package/lib/node/core/VelocityCore.d.ts +227 -0
- package/lib/node/core/VelocityCore.d.ts.map +1 -0
- package/lib/node/core/VelocityCore.js +138 -0
- package/lib/node/core/index.d.ts +13 -0
- package/lib/node/core/index.d.ts.map +1 -0
- package/lib/node/core/index.js +28 -0
- package/lib/node/core/instructions/deposit.d.ts +20 -0
- package/lib/node/core/instructions/deposit.d.ts.map +1 -0
- package/lib/node/core/instructions/deposit.js +19 -0
- package/lib/node/core/instructions/fill.d.ts +14 -0
- package/lib/node/core/instructions/fill.d.ts.map +1 -0
- package/lib/node/core/instructions/fill.js +17 -0
- package/lib/node/core/instructions/funding.d.ts +10 -0
- package/lib/node/core/instructions/funding.d.ts.map +1 -0
- package/lib/node/core/instructions/funding.js +13 -0
- package/lib/node/core/instructions/liquidation.d.ts +16 -0
- package/lib/node/core/instructions/liquidation.d.ts.map +1 -0
- package/lib/node/core/instructions/liquidation.js +17 -0
- package/lib/node/core/instructions/orders.d.ts +23 -0
- package/lib/node/core/instructions/orders.d.ts.map +1 -0
- package/lib/node/core/instructions/orders.js +27 -0
- package/lib/node/core/instructions/perpOrders.d.ts +79 -0
- package/lib/node/core/instructions/perpOrders.d.ts.map +1 -0
- package/lib/node/core/instructions/perpOrders.js +99 -0
- package/lib/node/core/instructions/settlement.d.ts +12 -0
- package/lib/node/core/instructions/settlement.d.ts.map +1 -0
- package/lib/node/core/instructions/settlement.js +15 -0
- package/lib/node/core/instructions/trigger.d.ts +12 -0
- package/lib/node/core/instructions/trigger.d.ts.map +1 -0
- package/lib/node/core/instructions/trigger.js +15 -0
- package/lib/node/core/instructions/withdraw.d.ts +21 -0
- package/lib/node/core/instructions/withdraw.d.ts.map +1 -0
- package/lib/node/core/instructions/withdraw.js +20 -0
- package/lib/node/core/remainingAccounts.d.ts +28 -0
- package/lib/node/core/remainingAccounts.d.ts.map +1 -0
- package/lib/node/core/remainingAccounts.js +122 -0
- package/lib/node/core/signedMsg.d.ts +18 -0
- package/lib/node/core/signedMsg.d.ts.map +1 -0
- package/lib/node/core/signedMsg.js +39 -0
- package/lib/node/decode/customCoder.d.ts +45 -0
- package/lib/node/decode/customCoder.d.ts.map +1 -0
- package/lib/node/decode/customCoder.js +64 -0
- package/lib/node/decode/user.d.ts +5 -0
- package/lib/node/decode/user.d.ts.map +1 -0
- package/lib/node/decode/user.js +337 -0
- package/lib/node/dlob/DLOB.d.ts +254 -0
- package/lib/node/dlob/DLOB.d.ts.map +1 -0
- package/lib/node/dlob/DLOB.js +1137 -0
- package/lib/node/dlob/DLOBNode.d.ts +71 -0
- package/lib/node/dlob/DLOBNode.d.ts.map +1 -0
- package/lib/node/dlob/DLOBNode.js +103 -0
- package/lib/node/dlob/DLOBSubscriber.d.ts +58 -0
- package/lib/node/dlob/DLOBSubscriber.d.ts.map +1 -0
- package/lib/node/dlob/DLOBSubscriber.js +143 -0
- package/lib/node/dlob/NodeList.d.ts +28 -0
- package/lib/node/dlob/NodeList.d.ts.map +1 -0
- package/lib/node/dlob/NodeList.js +126 -0
- package/lib/node/dlob/orderBookLevels.d.ts +78 -0
- package/lib/node/dlob/orderBookLevels.d.ts.map +1 -0
- package/lib/node/dlob/orderBookLevels.js +404 -0
- package/lib/node/dlob/types.d.ts +19 -0
- package/lib/node/dlob/types.d.ts.map +1 -0
- package/lib/node/dlob/types.js +2 -0
- package/lib/node/events/eventList.d.ts +23 -0
- package/lib/node/events/eventList.d.ts.map +1 -0
- package/lib/node/events/eventList.js +80 -0
- package/lib/node/events/eventSubscriber.d.ts +56 -0
- package/lib/node/events/eventSubscriber.d.ts.map +1 -0
- package/lib/node/events/eventSubscriber.js +229 -0
- package/lib/node/events/eventsServerLogProvider.d.ts +22 -0
- package/lib/node/events/eventsServerLogProvider.d.ts.map +1 -0
- package/lib/node/events/eventsServerLogProvider.js +121 -0
- package/lib/node/events/fetchLogs.d.ts +26 -0
- package/lib/node/events/fetchLogs.d.ts.map +1 -0
- package/lib/node/events/fetchLogs.js +99 -0
- package/lib/node/events/parse.d.ts +9 -0
- package/lib/node/events/parse.d.ts.map +1 -0
- package/lib/node/events/parse.js +199 -0
- package/lib/node/events/pollingLogProvider.d.ts +18 -0
- package/lib/node/events/pollingLogProvider.d.ts.map +1 -0
- package/lib/node/events/pollingLogProvider.js +58 -0
- package/lib/node/events/sort.d.ts +3 -0
- package/lib/node/events/sort.d.ts.map +1 -0
- package/lib/node/events/sort.js +24 -0
- package/lib/node/events/txEventCache.d.ts +25 -0
- package/lib/node/events/txEventCache.d.ts.map +1 -0
- package/lib/node/events/txEventCache.js +71 -0
- package/lib/node/events/types.d.ts +105 -0
- package/lib/node/events/types.d.ts.map +1 -0
- package/lib/node/events/types.js +36 -0
- package/lib/node/events/webSocketLogProvider.d.ts +25 -0
- package/lib/node/events/webSocketLogProvider.d.ts.map +1 -0
- package/lib/node/events/webSocketLogProvider.js +96 -0
- package/lib/node/factory/bigNum.d.ts +123 -0
- package/lib/node/factory/bigNum.d.ts.map +1 -0
- package/lib/node/factory/bigNum.js +500 -0
- package/lib/node/factory/oracleClient.d.ts +6 -0
- package/lib/node/factory/oracleClient.d.ts.map +1 -0
- package/lib/node/factory/oracleClient.js +53 -0
- package/lib/node/idl/drift.d.ts +23895 -0
- package/lib/node/idl/drift.d.ts.map +1 -0
- package/lib/node/idl/drift.js +2 -0
- package/lib/node/idl/drift.json +18698 -0
- package/lib/node/idl/pyth.d.ts +98 -0
- package/lib/node/idl/pyth.d.ts.map +1 -0
- package/lib/node/idl/pyth.js +2 -0
- package/lib/node/idl/token_faucet.d.ts +198 -0
- package/lib/node/idl/token_faucet.d.ts.map +1 -0
- package/lib/node/idl/token_faucet.js +2 -0
- package/lib/node/idl/token_faucet.json +229 -0
- package/lib/node/index.d.ts +145 -0
- package/lib/node/index.d.ts.map +1 -0
- package/lib/node/index.js +175 -0
- package/lib/node/indicative-quotes/indicativeQuotesSender.d.ts +36 -0
- package/lib/node/indicative-quotes/indicativeQuotesSender.d.ts.map +1 -0
- package/lib/node/indicative-quotes/indicativeQuotesSender.js +192 -0
- package/lib/node/isomorphic/anchor.browser.d.ts.map +1 -0
- package/lib/node/isomorphic/anchor.d.ts +2 -0
- package/lib/node/isomorphic/anchor.d.ts.map +1 -0
- package/lib/node/isomorphic/anchor.js +17 -0
- package/lib/node/isomorphic/anchor.node.d.ts +2 -0
- package/lib/node/isomorphic/anchor.node.d.ts.map +1 -0
- package/lib/node/isomorphic/anchor.node.js +17 -0
- package/lib/node/isomorphic/anchor29.browser.d.ts.map +1 -0
- package/lib/node/isomorphic/anchor29.d.ts +2 -0
- package/lib/node/isomorphic/anchor29.d.ts.map +1 -0
- package/lib/node/isomorphic/anchor29.js +17 -0
- package/lib/node/isomorphic/anchor29.node.d.ts +2 -0
- package/lib/node/isomorphic/anchor29.node.d.ts.map +1 -0
- package/lib/node/isomorphic/anchor29.node.js +17 -0
- package/lib/node/isomorphic/grpc.browser.d.ts.map +1 -0
- package/lib/node/isomorphic/grpc.d.ts +18 -0
- package/lib/node/isomorphic/grpc.d.ts.map +1 -0
- package/lib/node/isomorphic/grpc.js +109 -0
- package/lib/node/isomorphic/grpc.node.d.ts +18 -0
- package/lib/node/isomorphic/grpc.node.d.ts.map +1 -0
- package/lib/node/isomorphic/grpc.node.js +109 -0
- package/lib/node/jupiter/jupiterClient.d.ts +292 -0
- package/lib/node/jupiter/jupiterClient.d.ts.map +1 -0
- package/lib/node/jupiter/jupiterClient.js +164 -0
- package/lib/node/keypair.d.ts +3 -0
- package/lib/node/keypair.d.ts.map +1 -0
- package/lib/node/keypair.js +28 -0
- package/lib/node/marginCalculation.d.ts +68 -0
- package/lib/node/marginCalculation.d.ts.map +1 -0
- package/lib/node/marginCalculation.js +176 -0
- package/lib/node/marinade/index.d.ts +13 -0
- package/lib/node/marinade/index.d.ts.map +1 -0
- package/lib/node/marinade/index.js +36 -0
- package/lib/node/marinade/types.d.ts +1964 -0
- package/lib/node/marinade/types.d.ts.map +1 -0
- package/lib/node/marinade/types.js +1965 -0
- package/lib/node/math/amm.d.ts +99 -0
- package/lib/node/math/amm.d.ts.map +1 -0
- package/lib/node/math/amm.js +671 -0
- package/lib/node/math/auction.d.ts +66 -0
- package/lib/node/math/auction.d.ts.map +1 -0
- package/lib/node/math/auction.js +261 -0
- package/lib/node/math/bankruptcy.d.ts +3 -0
- package/lib/node/math/bankruptcy.d.ts.map +1 -0
- package/lib/node/math/bankruptcy.js +32 -0
- package/lib/node/math/builder.d.ts +6 -0
- package/lib/node/math/builder.d.ts.map +1 -0
- package/lib/node/math/builder.js +22 -0
- package/lib/node/math/conversion.d.ts +5 -0
- package/lib/node/math/conversion.d.ts.map +1 -0
- package/lib/node/math/conversion.js +21 -0
- package/lib/node/math/exchangeStatus.d.ts +9 -0
- package/lib/node/math/exchangeStatus.d.ts.map +1 -0
- package/lib/node/math/exchangeStatus.js +85 -0
- package/lib/node/math/funding.d.ts +45 -0
- package/lib/node/math/funding.d.ts.map +1 -0
- package/lib/node/math/funding.js +260 -0
- package/lib/node/math/insurance.d.ts +9 -0
- package/lib/node/math/insurance.d.ts.map +1 -0
- package/lib/node/math/insurance.js +74 -0
- package/lib/node/math/liquidation.d.ts +8 -0
- package/lib/node/math/liquidation.d.ts.map +1 -0
- package/lib/node/math/liquidation.js +134 -0
- package/lib/node/math/margin.d.ts +46 -0
- package/lib/node/math/margin.d.ts.map +1 -0
- package/lib/node/math/margin.js +205 -0
- package/lib/node/math/market.d.ts +51 -0
- package/lib/node/math/market.d.ts.map +1 -0
- package/lib/node/math/market.js +234 -0
- package/lib/node/math/oracles.d.ts +20 -0
- package/lib/node/math/oracles.d.ts.map +1 -0
- package/lib/node/math/oracles.js +215 -0
- package/lib/node/math/orders.d.ts +37 -0
- package/lib/node/math/orders.d.ts.map +1 -0
- package/lib/node/math/orders.js +294 -0
- package/lib/node/math/position.d.ts +72 -0
- package/lib/node/math/position.d.ts.map +1 -0
- package/lib/node/math/position.js +232 -0
- package/lib/node/math/repeg.d.ts +23 -0
- package/lib/node/math/repeg.d.ts.map +1 -0
- package/lib/node/math/repeg.js +164 -0
- package/lib/node/math/spotBalance.d.ts +86 -0
- package/lib/node/math/spotBalance.d.ts.map +1 -0
- package/lib/node/math/spotBalance.js +438 -0
- package/lib/node/math/spotMarket.d.ts +12 -0
- package/lib/node/math/spotMarket.d.ts.map +1 -0
- package/lib/node/math/spotMarket.js +49 -0
- package/lib/node/math/spotPosition.d.ts +20 -0
- package/lib/node/math/spotPosition.d.ts.map +1 -0
- package/lib/node/math/spotPosition.js +79 -0
- package/lib/node/math/state.d.ts +9 -0
- package/lib/node/math/state.d.ts.map +1 -0
- package/lib/node/math/state.js +44 -0
- package/lib/node/math/superStake.d.ts +169 -0
- package/lib/node/math/superStake.d.ts.map +1 -0
- package/lib/node/math/superStake.js +308 -0
- package/lib/node/math/tiers.d.ts +5 -0
- package/lib/node/math/tiers.d.ts.map +1 -0
- package/lib/node/math/tiers.js +52 -0
- package/lib/node/math/trade.d.ts +94 -0
- package/lib/node/math/trade.d.ts.map +1 -0
- package/lib/node/math/trade.js +503 -0
- package/lib/node/math/utils.d.ts +24 -0
- package/lib/node/math/utils.d.ts.map +1 -0
- package/lib/node/math/utils.js +113 -0
- package/lib/node/memcmp.d.ts +19 -0
- package/lib/node/memcmp.d.ts.map +1 -0
- package/lib/node/memcmp.js +162 -0
- package/lib/node/oracles/oracleClientCache.d.ts +10 -0
- package/lib/node/oracles/oracleClientCache.d.ts.map +1 -0
- package/lib/node/oracles/oracleClientCache.js +19 -0
- package/lib/node/oracles/oracleId.d.ts +10 -0
- package/lib/node/oracles/oracleId.d.ts.map +1 -0
- package/lib/node/oracles/oracleId.js +89 -0
- package/lib/node/oracles/prelaunchOracleClient.d.ts +13 -0
- package/lib/node/oracles/prelaunchOracleClient.d.ts.map +1 -0
- package/lib/node/oracles/prelaunchOracleClient.js +24 -0
- package/lib/node/oracles/pythClient.d.ts +15 -0
- package/lib/node/oracles/pythClient.d.ts.map +1 -0
- package/lib/node/oracles/pythClient.js +51 -0
- package/lib/node/oracles/pythLazerClient.d.ts +17 -0
- package/lib/node/oracles/pythLazerClient.d.ts.map +1 -0
- package/lib/node/oracles/pythLazerClient.js +61 -0
- package/lib/node/oracles/quoteAssetOracleClient.d.ts +11 -0
- package/lib/node/oracles/quoteAssetOracleClient.d.ts.map +1 -0
- package/lib/node/oracles/quoteAssetOracleClient.js +21 -0
- package/lib/node/oracles/strictOraclePrice.d.ts +10 -0
- package/lib/node/oracles/strictOraclePrice.d.ts.map +1 -0
- package/lib/node/oracles/strictOraclePrice.js +17 -0
- package/lib/node/oracles/types.d.ts +34 -0
- package/lib/node/oracles/types.d.ts.map +1 -0
- package/lib/node/oracles/types.js +2 -0
- package/lib/node/oracles/utils.d.ts +5 -0
- package/lib/node/oracles/utils.d.ts.map +1 -0
- package/lib/node/oracles/utils.js +8 -0
- package/lib/node/orderParams.d.ts +30 -0
- package/lib/node/orderParams.d.ts.map +1 -0
- package/lib/node/orderParams.js +44 -0
- package/lib/node/orderSubscriber/OrderSubscriber.d.ts +46 -0
- package/lib/node/orderSubscriber/OrderSubscriber.d.ts.map +1 -0
- package/lib/node/orderSubscriber/OrderSubscriber.js +193 -0
- package/lib/node/orderSubscriber/PollingSubscription.d.ts +13 -0
- package/lib/node/orderSubscriber/PollingSubscription.d.ts.map +1 -0
- package/lib/node/orderSubscriber/PollingSubscription.js +23 -0
- package/lib/node/orderSubscriber/WebsocketSubscription.d.ts +24 -0
- package/lib/node/orderSubscriber/WebsocketSubscription.d.ts.map +1 -0
- package/lib/node/orderSubscriber/WebsocketSubscription.js +67 -0
- package/lib/node/orderSubscriber/grpcSubscription.d.ts +23 -0
- package/lib/node/orderSubscriber/grpcSubscription.d.ts.map +1 -0
- package/lib/node/orderSubscriber/grpcSubscription.js +75 -0
- package/lib/node/orderSubscriber/index.d.ts +8 -0
- package/lib/node/orderSubscriber/index.d.ts.map +1 -0
- package/lib/node/orderSubscriber/index.js +23 -0
- package/lib/node/orderSubscriber/types.d.ts +36 -0
- package/lib/node/orderSubscriber/types.d.ts.map +1 -0
- package/lib/node/orderSubscriber/types.js +2 -0
- package/lib/node/priorityFee/averageOverSlotsStrategy.d.ts +6 -0
- package/lib/node/priorityFee/averageOverSlotsStrategy.d.ts.map +1 -0
- package/lib/node/priorityFee/averageOverSlotsStrategy.js +16 -0
- package/lib/node/priorityFee/averageStrategy.d.ts +6 -0
- package/lib/node/priorityFee/averageStrategy.d.ts.map +1 -0
- package/lib/node/priorityFee/averageStrategy.js +11 -0
- package/lib/node/priorityFee/ewmaStrategy.d.ts +12 -0
- package/lib/node/priorityFee/ewmaStrategy.d.ts.map +1 -0
- package/lib/node/priorityFee/ewmaStrategy.js +33 -0
- package/lib/node/priorityFee/heliusPriorityFeeMethod.d.ts +21 -0
- package/lib/node/priorityFee/heliusPriorityFeeMethod.d.ts.map +1 -0
- package/lib/node/priorityFee/heliusPriorityFeeMethod.js +46 -0
- package/lib/node/priorityFee/index.d.ts +17 -0
- package/lib/node/priorityFee/index.d.ts.map +1 -0
- package/lib/node/priorityFee/index.js +32 -0
- package/lib/node/priorityFee/maxOverSlotsStrategy.d.ts +6 -0
- package/lib/node/priorityFee/maxOverSlotsStrategy.d.ts.map +1 -0
- package/lib/node/priorityFee/maxOverSlotsStrategy.js +17 -0
- package/lib/node/priorityFee/maxStrategy.d.ts +8 -0
- package/lib/node/priorityFee/maxStrategy.d.ts.map +1 -0
- package/lib/node/priorityFee/maxStrategy.js +9 -0
- package/lib/node/priorityFee/priorityFeeSubscriber.d.ts +49 -0
- package/lib/node/priorityFee/priorityFeeSubscriber.d.ts.map +1 -0
- package/lib/node/priorityFee/priorityFeeSubscriber.js +193 -0
- package/lib/node/priorityFee/priorityFeeSubscriberMap.d.ts +51 -0
- package/lib/node/priorityFee/priorityFeeSubscriberMap.d.ts.map +1 -0
- package/lib/node/priorityFee/priorityFeeSubscriberMap.js +96 -0
- package/lib/node/priorityFee/solanaPriorityFeeMethod.d.ts +7 -0
- package/lib/node/priorityFee/solanaPriorityFeeMethod.d.ts.map +1 -0
- package/lib/node/priorityFee/solanaPriorityFeeMethod.js +21 -0
- package/lib/node/priorityFee/types.d.ts +36 -0
- package/lib/node/priorityFee/types.d.ts.map +1 -0
- package/lib/node/priorityFee/types.js +10 -0
- package/lib/node/priorityFee/velocityPriorityFeeMethod.d.ts +22 -0
- package/lib/node/priorityFee/velocityPriorityFeeMethod.d.ts.map +1 -0
- package/lib/node/priorityFee/velocityPriorityFeeMethod.js +28 -0
- package/lib/node/pyth/constants.d.ts +4 -0
- package/lib/node/pyth/constants.d.ts.map +1 -0
- package/lib/node/pyth/constants.js +6 -0
- package/lib/node/pyth/index.d.ts +5 -0
- package/lib/node/pyth/index.d.ts.map +1 -0
- package/lib/node/pyth/index.js +12 -0
- package/lib/node/pyth/pythLazerSubscriber.d.ts +92 -0
- package/lib/node/pyth/pythLazerSubscriber.d.ts.map +1 -0
- package/lib/node/pyth/pythLazerSubscriber.js +276 -0
- package/lib/node/pyth/types.d.ts +2227 -0
- package/lib/node/pyth/types.d.ts.map +1 -0
- package/lib/node/pyth/types.js +2224 -0
- package/lib/node/pyth/utils.d.ts +3 -0
- package/lib/node/pyth/utils.d.ts.map +1 -0
- package/lib/node/pyth/utils.js +10 -0
- package/lib/node/slot/SlotSubscriber.d.ts +28 -0
- package/lib/node/slot/SlotSubscriber.d.ts.map +1 -0
- package/lib/node/slot/SlotSubscriber.js +76 -0
- package/lib/node/slot/SlothashSubscriber.d.ts +26 -0
- package/lib/node/slot/SlothashSubscriber.d.ts.map +1 -0
- package/lib/node/slot/SlothashSubscriber.js +88 -0
- package/lib/node/swap/UnifiedSwapClient.d.ts +121 -0
- package/lib/node/swap/UnifiedSwapClient.d.ts.map +1 -0
- package/lib/node/swap/UnifiedSwapClient.js +179 -0
- package/lib/node/swift/grpcSignedMsgUserAccountSubscriber.d.ts +23 -0
- package/lib/node/swift/grpcSignedMsgUserAccountSubscriber.d.ts.map +1 -0
- package/lib/node/swift/grpcSignedMsgUserAccountSubscriber.js +57 -0
- package/lib/node/swift/index.d.ts +11 -0
- package/lib/node/swift/index.d.ts.map +1 -0
- package/lib/node/swift/index.js +26 -0
- package/lib/node/swift/signedMsgUserAccountSubscriber.d.ts +43 -0
- package/lib/node/swift/signedMsgUserAccountSubscriber.d.ts.map +1 -0
- package/lib/node/swift/signedMsgUserAccountSubscriber.js +118 -0
- package/lib/node/swift/swiftOrderSubscriber.d.ts +64 -0
- package/lib/node/swift/swiftOrderSubscriber.d.ts.map +1 -0
- package/lib/node/swift/swiftOrderSubscriber.js +187 -0
- package/lib/node/testClient.d.ts +9 -0
- package/lib/node/testClient.d.ts.map +1 -0
- package/lib/node/testClient.js +24 -0
- package/lib/node/titan/titanClient.d.ts +91 -0
- package/lib/node/titan/titanClient.d.ts.map +1 -0
- package/lib/node/titan/titanClient.js +227 -0
- package/lib/node/token/index.d.ts +6 -0
- package/lib/node/token/index.d.ts.map +1 -0
- package/lib/node/token/index.js +15 -0
- package/lib/node/tokenFaucet.d.ts +42 -0
- package/lib/node/tokenFaucet.d.ts.map +1 -0
- package/lib/node/tokenFaucet.js +188 -0
- package/lib/node/tx/baseTxSender.d.ts +60 -0
- package/lib/node/tx/baseTxSender.d.ts.map +1 -0
- package/lib/node/tx/baseTxSender.js +292 -0
- package/lib/node/tx/blockhashFetcher/baseBlockhashFetcher.d.ts +9 -0
- package/lib/node/tx/blockhashFetcher/baseBlockhashFetcher.d.ts.map +1 -0
- package/lib/node/tx/blockhashFetcher/baseBlockhashFetcher.js +13 -0
- package/lib/node/tx/blockhashFetcher/cachedBlockhashFetcher.d.ts +29 -0
- package/lib/node/tx/blockhashFetcher/cachedBlockhashFetcher.d.ts.map +1 -0
- package/lib/node/tx/blockhashFetcher/cachedBlockhashFetcher.js +73 -0
- package/lib/node/tx/blockhashFetcher/types.d.ts +5 -0
- package/lib/node/tx/blockhashFetcher/types.d.ts.map +1 -0
- package/lib/node/tx/blockhashFetcher/types.js +2 -0
- package/lib/node/tx/fastSingleTxSender.d.ts +42 -0
- package/lib/node/tx/fastSingleTxSender.d.ts.map +1 -0
- package/lib/node/tx/fastSingleTxSender.js +86 -0
- package/lib/node/tx/forwardOnlyTxSender.d.ts +38 -0
- package/lib/node/tx/forwardOnlyTxSender.d.ts.map +1 -0
- package/lib/node/tx/forwardOnlyTxSender.js +92 -0
- package/lib/node/tx/priorityFeeCalculator.d.ts +45 -0
- package/lib/node/tx/priorityFeeCalculator.d.ts.map +1 -0
- package/lib/node/tx/priorityFeeCalculator.js +85 -0
- package/lib/node/tx/reportTransactionError.d.ts +21 -0
- package/lib/node/tx/reportTransactionError.d.ts.map +1 -0
- package/lib/node/tx/reportTransactionError.js +103 -0
- package/lib/node/tx/retryTxSender.d.ts +38 -0
- package/lib/node/tx/retryTxSender.d.ts.map +1 -0
- package/lib/node/tx/retryTxSender.js +86 -0
- package/lib/node/tx/txHandler.d.ts +174 -0
- package/lib/node/tx/txHandler.d.ts.map +1 -0
- package/lib/node/tx/txHandler.js +522 -0
- package/lib/node/tx/txParamProcessor.d.ts +27 -0
- package/lib/node/tx/txParamProcessor.d.ts.map +1 -0
- package/lib/node/tx/txParamProcessor.js +92 -0
- package/lib/node/tx/types.d.ts +30 -0
- package/lib/node/tx/types.d.ts.map +1 -0
- package/lib/node/tx/types.js +20 -0
- package/lib/node/tx/utils.d.ts +7 -0
- package/lib/node/tx/utils.d.ts.map +1 -0
- package/lib/node/tx/utils.js +78 -0
- package/lib/node/tx/whileValidTxSender.d.ts +46 -0
- package/lib/node/tx/whileValidTxSender.d.ts.map +1 -0
- package/lib/node/tx/whileValidTxSender.js +168 -0
- package/lib/node/types.d.ts +1748 -0
- package/lib/node/types.d.ts.map +1 -0
- package/lib/node/types.js +427 -0
- package/lib/node/user.d.ts +447 -0
- package/lib/node/user.d.ts.map +1 -0
- package/lib/node/user.js +2372 -0
- package/lib/node/userConfig.d.ts +32 -0
- package/lib/node/userConfig.d.ts.map +1 -0
- package/lib/node/userConfig.js +2 -0
- package/lib/node/userMap/PollingSubscription.d.ts +16 -0
- package/lib/node/userMap/PollingSubscription.d.ts.map +1 -0
- package/lib/node/userMap/PollingSubscription.js +30 -0
- package/lib/node/userMap/WebsocketSubscription.d.ts +28 -0
- package/lib/node/userMap/WebsocketSubscription.d.ts.map +1 -0
- package/lib/node/userMap/WebsocketSubscription.js +45 -0
- package/lib/node/userMap/grpcSubscription.d.ts +28 -0
- package/lib/node/userMap/grpcSubscription.d.ts.map +1 -0
- package/lib/node/userMap/grpcSubscription.js +44 -0
- package/lib/node/userMap/referrerMap.d.ts +46 -0
- package/lib/node/userMap/referrerMap.d.ts.map +1 -0
- package/lib/node/userMap/referrerMap.js +184 -0
- package/lib/node/userMap/revenueShareEscrowMap.d.ts +67 -0
- package/lib/node/userMap/revenueShareEscrowMap.d.ts.map +1 -0
- package/lib/node/userMap/revenueShareEscrowMap.js +210 -0
- package/lib/node/userMap/userMap.d.ts +115 -0
- package/lib/node/userMap/userMap.d.ts.map +1 -0
- package/lib/node/userMap/userMap.js +486 -0
- package/lib/node/userMap/userMapConfig.d.ts +41 -0
- package/lib/node/userMap/userMapConfig.d.ts.map +1 -0
- package/lib/node/userMap/userMapConfig.js +2 -0
- package/lib/node/userMap/userStatsMap.d.ts +67 -0
- package/lib/node/userMap/userStatsMap.d.ts.map +1 -0
- package/lib/node/userMap/userStatsMap.js +266 -0
- package/lib/node/userName.d.ts +6 -0
- package/lib/node/userName.d.ts.map +1 -0
- package/lib/node/userName.js +21 -0
- package/lib/node/userStats.d.ts +25 -0
- package/lib/node/userStats.d.ts.map +1 -0
- package/lib/node/userStats.js +70 -0
- package/lib/node/userStatsConfig.d.ts +27 -0
- package/lib/node/userStatsConfig.d.ts.map +1 -0
- package/lib/node/userStatsConfig.js +2 -0
- package/lib/node/util/TransactionConfirmationManager.d.ts +17 -0
- package/lib/node/util/TransactionConfirmationManager.d.ts.map +1 -0
- package/lib/node/util/TransactionConfirmationManager.js +174 -0
- package/lib/node/util/chainClock.d.ts +18 -0
- package/lib/node/util/chainClock.d.ts.map +1 -0
- package/lib/node/util/chainClock.js +29 -0
- package/lib/node/util/computeUnits.d.ts +9 -0
- package/lib/node/util/computeUnits.d.ts.map +1 -0
- package/lib/node/util/computeUnits.js +48 -0
- package/lib/node/util/digest.d.ts +6 -0
- package/lib/node/util/digest.d.ts.map +1 -0
- package/lib/node/util/digest.js +19 -0
- package/lib/node/util/ed25519Utils.d.ts +11 -0
- package/lib/node/util/ed25519Utils.d.ts.map +1 -0
- package/lib/node/util/ed25519Utils.js +80 -0
- package/lib/node/util/promiseTimeout.d.ts +2 -0
- package/lib/node/util/promiseTimeout.d.ts.map +1 -0
- package/lib/node/util/promiseTimeout.js +14 -0
- package/lib/node/util/tps.d.ts +3 -0
- package/lib/node/util/tps.d.ts.map +1 -0
- package/lib/node/util/tps.js +16 -0
- package/lib/node/velocityClient.d.ts +1231 -0
- package/lib/node/velocityClient.d.ts.map +1 -0
- package/lib/node/velocityClient.js +5778 -0
- package/lib/node/velocityClientConfig.d.ts +85 -0
- package/lib/node/velocityClientConfig.d.ts.map +1 -0
- package/lib/node/velocityClientConfig.js +2 -0
- package/lib/node/wallet.d.ts +17 -0
- package/lib/node/wallet.d.ts.map +1 -0
- package/lib/node/wallet.js +46 -0
- package/package.json +157 -0
- package/scripts/deposit-isolated-positions.ts +110 -0
- package/scripts/find-flagged-users.ts +213 -0
- package/scripts/grpc-client-test-comparison.ts +372 -0
- package/scripts/grpc-multiuser-client-test-comparison.ts +158 -0
- package/scripts/postbuild.js +95 -0
- package/scripts/single-grpc-client-test.ts +284 -0
- package/scripts/updateVersion.js +28 -0
- package/scripts/withdraw-isolated-positions.ts +174 -0
- package/src/accounts/README_WebSocketAccountSubscriberV2.md +95 -0
- package/src/accounts/README_WebSocketProgramAccountSubscriberV2.md +135 -0
- package/src/accounts/basicUserAccountSubscriber.ts +59 -0
- package/src/accounts/basicUserStatsAccountSubscriber.ts +65 -0
- package/src/accounts/bulkAccountLoader.ts +293 -0
- package/src/accounts/bulkUserStatsSubscription.ts +33 -0
- package/src/accounts/bulkUserSubscription.ts +33 -0
- package/src/accounts/customizedCadenceBulkAccountLoader.ts +213 -0
- package/src/accounts/fetch.ts +143 -0
- package/src/accounts/grpcAccountSubscriber.ts +187 -0
- package/src/accounts/grpcInsuranceFundStakeAccountSubscriber.ts +57 -0
- package/src/accounts/grpcMultiAccountSubscriber.ts +476 -0
- package/src/accounts/grpcMultiUserAccountSubscriber.ts +281 -0
- package/src/accounts/grpcProgramAccountSubscriber.ts +223 -0
- package/src/accounts/grpcUserAccountSubscriber.ts +48 -0
- package/src/accounts/grpcUserStatsAccountSubscriber.ts +50 -0
- package/src/accounts/grpcVelocityClientAccountSubscriber.ts +213 -0
- package/src/accounts/grpcVelocityClientAccountSubscriberV2.ts +762 -0
- package/src/accounts/laserProgramAccountSubscriber.ts +229 -0
- package/src/accounts/oneShotUserAccountSubscriber.ts +67 -0
- package/src/accounts/oneShotUserStatsAccountSubscriber.ts +70 -0
- package/src/accounts/pollingInsuranceFundStakeAccountSubscriber.ts +186 -0
- package/src/accounts/pollingOracleAccountSubscriber.ts +125 -0
- package/src/accounts/pollingTokenAccountSubscriber.ts +118 -0
- package/src/accounts/pollingUserAccountSubscriber.ts +160 -0
- package/src/accounts/pollingUserStatsAccountSubscriber.ts +156 -0
- package/src/accounts/pollingVelocityClientAccountSubscriber.ts +652 -0
- package/src/accounts/testBulkAccountLoader.ts +51 -0
- package/src/accounts/types.ts +284 -0
- package/src/accounts/utils.ts +62 -0
- package/src/accounts/webSocketAccountSubscriber.ts +250 -0
- package/src/accounts/webSocketAccountSubscriberV2.ts +517 -0
- package/src/accounts/webSocketInsuranceFundStakeAccountSubscriber.ts +129 -0
- package/src/accounts/webSocketProgramAccountSubscriber.ts +183 -0
- package/src/accounts/webSocketProgramAccountSubscriberV2.ts +996 -0
- package/src/accounts/webSocketProgramAccountsSubscriberV2.ts +996 -0
- package/src/accounts/webSocketUserAccountSubscriber.ts +104 -0
- package/src/accounts/webSocketUserStatsAccountSubsriber.ts +98 -0
- package/src/accounts/webSocketVelocityClientAccountSubscriber.ts +719 -0
- package/src/accounts/webSocketVelocityClientAccountSubscriberV2.ts +755 -0
- package/src/accounts/websocketProgramUserAccountSubscriber.ts +94 -0
- package/src/addresses/marketAddresses.ts +17 -0
- package/src/addresses/pda.ts +439 -0
- package/src/adminClient.ts +5936 -0
- package/src/assert/assert.ts +5 -0
- package/src/auctionSubscriber/auctionSubscriber.ts +68 -0
- package/src/auctionSubscriber/auctionSubscriberGrpc.ts +72 -0
- package/src/auctionSubscriber/index.ts +3 -0
- package/src/auctionSubscriber/types.ts +20 -0
- package/src/bankrun/bankrunConnection.ts +560 -0
- package/src/blockhashSubscriber/BlockhashSubscriber.ts +126 -0
- package/src/blockhashSubscriber/index.ts +1 -0
- package/src/blockhashSubscriber/types.ts +12 -0
- package/src/clock/clockSubscriber.ts +121 -0
- package/src/config.ts +268 -0
- package/src/constants/index.ts +10 -0
- package/src/constants/insuranceFund.ts +8 -0
- package/src/constants/numericConstants.ts +119 -0
- package/src/constants/perpMarkets.ts +1042 -0
- package/src/constants/spotMarkets.ts +874 -0
- package/src/constants/txConstants.ts +1 -0
- package/src/constituentMap/constituentMap.ts +294 -0
- package/src/constituentMap/pollingConstituentAccountSubscriber.ts +97 -0
- package/src/constituentMap/webSocketConstituentAccountSubscriber.ts +112 -0
- package/src/core/VelocityCore.ts +331 -0
- package/src/core/index.ts +12 -0
- package/src/core/instructions/deposit.ts +42 -0
- package/src/core/instructions/fill.ts +34 -0
- package/src/core/instructions/funding.ts +21 -0
- package/src/core/instructions/liquidation.ts +37 -0
- package/src/core/instructions/orders.ts +56 -0
- package/src/core/instructions/perpOrders.ts +192 -0
- package/src/core/instructions/settlement.ts +26 -0
- package/src/core/instructions/trigger.ts +26 -0
- package/src/core/instructions/withdraw.ts +44 -0
- package/src/core/remainingAccounts.ts +276 -0
- package/src/core/signedMsg.ts +71 -0
- package/src/decode/customCoder.ts +105 -0
- package/src/decode/user.ts +372 -0
- package/src/dlob/DLOB.ts +2098 -0
- package/src/dlob/DLOBNode.ts +193 -0
- package/src/dlob/DLOBSubscriber.ts +211 -0
- package/src/dlob/NodeList.ts +174 -0
- package/src/dlob/orderBookLevels.ts +575 -0
- package/src/dlob/types.ts +22 -0
- package/src/events/eventList.ts +97 -0
- package/src/events/eventSubscriber.ts +382 -0
- package/src/events/eventsServerLogProvider.ts +152 -0
- package/src/events/fetchLogs.ts +169 -0
- package/src/events/parse.ts +248 -0
- package/src/events/pollingLogProvider.ts +89 -0
- package/src/events/sort.ts +39 -0
- package/src/events/txEventCache.ts +74 -0
- package/src/events/types.ts +228 -0
- package/src/events/webSocketLogProvider.ts +121 -0
- package/src/factory/bigNum.ts +709 -0
- package/src/factory/oracleClient.ts +73 -0
- package/src/idl/drift.json +18698 -0
- package/src/idl/drift.ts +23894 -0
- package/src/idl/pyth.json +142 -0
- package/src/idl/pyth.ts +97 -0
- package/src/idl/pyth_solana_receiver.json +628 -0
- package/src/idl/token_faucet.json +229 -0
- package/src/idl/token_faucet.ts +197 -0
- package/src/index.ts +150 -0
- package/src/indicative-quotes/indicativeQuotesSender.ts +233 -0
- package/src/isomorphic/README.md +19 -0
- package/src/isomorphic/anchor.browser.ts +44 -0
- package/src/isomorphic/anchor.node.ts +1 -0
- package/src/isomorphic/anchor.ts +1 -0
- package/src/isomorphic/anchor29.browser.ts +24 -0
- package/src/isomorphic/anchor29.node.ts +1 -0
- package/src/isomorphic/anchor29.ts +1 -0
- package/src/isomorphic/grpc.browser.ts +4 -0
- package/src/isomorphic/grpc.node.ts +130 -0
- package/src/isomorphic/grpc.ts +1 -0
- package/src/jupiter/jupiterClient.ts +482 -0
- package/src/keypair.ts +24 -0
- package/src/margin/README.md +138 -0
- package/src/marginCalculation.ts +255 -0
- package/src/marinade/idl/idl.json +1962 -0
- package/src/marinade/index.ts +64 -0
- package/src/marinade/types.ts +3925 -0
- package/src/math/amm.ts +1246 -0
- package/src/math/auction.ts +374 -0
- package/src/math/bankruptcy.ts +35 -0
- package/src/math/builder.ts +20 -0
- package/src/math/conversion.ts +24 -0
- package/src/math/exchangeStatus.ts +136 -0
- package/src/math/funding.ts +436 -0
- package/src/math/insurance.ts +111 -0
- package/src/math/liquidation.ts +209 -0
- package/src/math/margin.ts +368 -0
- package/src/math/market.ts +438 -0
- package/src/math/oracles.ts +367 -0
- package/src/math/orders.ts +473 -0
- package/src/math/position.ts +340 -0
- package/src/math/repeg.ts +214 -0
- package/src/math/spotBalance.ts +752 -0
- package/src/math/spotMarket.ts +82 -0
- package/src/math/spotPosition.ts +191 -0
- package/src/math/state.ts +48 -0
- package/src/math/superStake.ts +528 -0
- package/src/math/tiers.ts +44 -0
- package/src/math/trade.ts +805 -0
- package/src/math/utils.ts +121 -0
- package/src/memcmp.ts +164 -0
- package/src/oracles/oracleClientCache.ts +25 -0
- package/src/oracles/oracleId.ts +66 -0
- package/src/oracles/prelaunchOracleClient.ts +38 -0
- package/src/oracles/pythClient.ts +85 -0
- package/src/oracles/pythLazerClient.ts +102 -0
- package/src/oracles/quoteAssetOracleClient.ts +25 -0
- package/src/oracles/strictOraclePrice.ts +19 -0
- package/src/oracles/types.ts +37 -0
- package/src/oracles/utils.ts +10 -0
- package/src/orderParams.ts +79 -0
- package/src/orderSubscriber/OrderSubscriber.ts +296 -0
- package/src/orderSubscriber/PollingSubscription.ts +39 -0
- package/src/orderSubscriber/WebsocketSubscription.ts +119 -0
- package/src/orderSubscriber/grpcSubscription.ts +139 -0
- package/src/orderSubscriber/index.ts +7 -0
- package/src/orderSubscriber/types.ts +55 -0
- package/src/priorityFee/averageOverSlotsStrategy.ts +16 -0
- package/src/priorityFee/averageStrategy.ts +12 -0
- package/src/priorityFee/ewmaStrategy.ts +41 -0
- package/src/priorityFee/heliusPriorityFeeMethod.ts +57 -0
- package/src/priorityFee/index.ts +16 -0
- package/src/priorityFee/maxOverSlotsStrategy.ts +17 -0
- package/src/priorityFee/maxStrategy.ts +7 -0
- package/src/priorityFee/priorityFeeSubscriber.ts +256 -0
- package/src/priorityFee/priorityFeeSubscriberMap.ts +125 -0
- package/src/priorityFee/solanaPriorityFeeMethod.ts +34 -0
- package/src/priorityFee/types.ts +64 -0
- package/src/priorityFee/velocityPriorityFeeMethod.ts +54 -0
- package/src/pyth/constants.ts +9 -0
- package/src/pyth/index.ts +15 -0
- package/src/pyth/pythLazerSubscriber.ts +365 -0
- package/src/pyth/types.ts +4453 -0
- package/src/pyth/utils.ts +13 -0
- package/src/slot/SlotSubscriber.ts +108 -0
- package/src/slot/SlothashSubscriber.ts +126 -0
- package/src/swap/UnifiedSwapClient.ts +315 -0
- package/src/swift/grpcSignedMsgUserAccountSubscriber.ts +95 -0
- package/src/swift/index.ts +10 -0
- package/src/swift/signedMsgUserAccountSubscriber.ts +241 -0
- package/src/swift/swiftOrderSubscriber.ts +347 -0
- package/src/testClient.ts +42 -0
- package/src/titan/titanClient.ts +438 -0
- package/src/token/index.ts +13 -0
- package/src/tokenFaucet.ts +274 -0
- package/src/tx/baseTxSender.ts +471 -0
- package/src/tx/blockhashFetcher/baseBlockhashFetcher.ts +19 -0
- package/src/tx/blockhashFetcher/cachedBlockhashFetcher.ts +90 -0
- package/src/tx/blockhashFetcher/types.ts +5 -0
- package/src/tx/fastSingleTxSender.ts +142 -0
- package/src/tx/forwardOnlyTxSender.ts +145 -0
- package/src/tx/priorityFeeCalculator.ts +117 -0
- package/src/tx/reportTransactionError.ts +159 -0
- package/src/tx/retryTxSender.ts +135 -0
- package/src/tx/txHandler.ts +853 -0
- package/src/tx/txParamProcessor.ts +163 -0
- package/src/tx/types.ts +71 -0
- package/src/tx/utils.ts +107 -0
- package/src/tx/whileValidTxSender.ts +266 -0
- package/src/types.ts +1793 -0
- package/src/user.ts +4487 -0
- package/src/userConfig.ts +37 -0
- package/src/userMap/PollingSubscription.ts +47 -0
- package/src/userMap/WebsocketSubscription.ts +84 -0
- package/src/userMap/grpcSubscription.ts +85 -0
- package/src/userMap/referrerMap.ts +267 -0
- package/src/userMap/revenueShareEscrowMap.ts +310 -0
- package/src/userMap/userMap.ts +683 -0
- package/src/userMap/userMapConfig.ts +66 -0
- package/src/userMap/userStatsMap.ts +358 -0
- package/src/userName.ts +21 -0
- package/src/userStats.ts +117 -0
- package/src/userStatsConfig.ts +32 -0
- package/src/util/TransactionConfirmationManager.ts +292 -0
- package/src/util/chainClock.ts +41 -0
- package/src/util/computeUnits.ts +65 -0
- package/src/util/digest.ts +16 -0
- package/src/util/ed25519Utils.ts +85 -0
- package/src/util/promiseTimeout.ts +14 -0
- package/src/util/tps.ts +27 -0
- package/src/velocityClient.ts +11364 -0
- package/src/velocityClientConfig.ts +144 -0
- package/src/wallet.ts +54 -0
- package/tests/DriftCore/decode.test.ts +16 -0
- package/tests/DriftCore/fill_trigger.test.ts +73 -0
- package/tests/DriftCore/instructions.test.ts +46 -0
- package/tests/DriftCore/pdas.test.ts +28 -0
- package/tests/DriftCore/perp_orders.test.ts +205 -0
- package/tests/DriftCore/remainingAccounts.test.ts +73 -0
- package/tests/DriftCore/settlement_liquidation.test.ts +69 -0
- package/tests/accounts/customizedCadenceBulkAccountLoader.test.ts +203 -0
- package/tests/amm/test.ts +2095 -0
- package/tests/auctions/test.ts +81 -0
- package/tests/bn/test.ts +355 -0
- package/tests/ci/verifyConstants.ts +396 -0
- package/tests/decode/phoenix.ts +71 -0
- package/tests/decode/test.ts +262 -0
- package/tests/decode/userAccountBufferStrings.ts +102 -0
- package/tests/dlob/helpers.ts +740 -0
- package/tests/dlob/test.ts +6920 -0
- package/tests/events/parseLogsForCuUsage.ts +139 -0
- package/tests/insurance/test.ts +40 -0
- package/tests/spot/test.ts +226 -0
- package/tests/tx/TransactionConfirmationManager.test.ts +305 -0
- package/tests/tx/cachedBlockhashFetcher.test.ts +96 -0
- package/tests/tx/priorityFeeCalculator.ts +77 -0
- package/tests/tx/priorityFeeStrategy.ts +95 -0
- package/tests/user/getMarginCalculation.ts +361 -0
- package/tests/user/helpers.ts +185 -0
- package/tests/user/liquidations.ts +129 -0
- package/tests/user/marginCalculations.test.ts +321 -0
- package/tests/user/test.ts +826 -0
- package/tsconfig.browser.json +16 -0
- package/tsconfig.json +17 -0
|
@@ -0,0 +1,2372 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.User = void 0;
|
|
4
|
+
const types_1 = require("./types");
|
|
5
|
+
const position_1 = require("./math/position");
|
|
6
|
+
const numericConstants_1 = require("./constants/numericConstants");
|
|
7
|
+
const bigNum_1 = require("./factory/bigNum");
|
|
8
|
+
const anchor_1 = require("./isomorphic/anchor");
|
|
9
|
+
const position_2 = require("./math/position");
|
|
10
|
+
const market_1 = require("./math/market");
|
|
11
|
+
const margin_1 = require("./math/margin");
|
|
12
|
+
const spotMarket_1 = require("./math/spotMarket");
|
|
13
|
+
const utils_1 = require("./math/utils");
|
|
14
|
+
const spotBalance_1 = require("./math/spotBalance");
|
|
15
|
+
const trade_1 = require("./math/trade");
|
|
16
|
+
const types_2 = require("./types");
|
|
17
|
+
const orders_1 = require("./math/orders");
|
|
18
|
+
const websocketProgramUserAccountSubscriber_1 = require("./accounts/websocketProgramUserAccountSubscriber");
|
|
19
|
+
const spotBalance_2 = require("./math/spotBalance");
|
|
20
|
+
const margin_2 = require("./math/margin");
|
|
21
|
+
const pollingUserAccountSubscriber_1 = require("./accounts/pollingUserAccountSubscriber");
|
|
22
|
+
const webSocketUserAccountSubscriber_1 = require("./accounts/webSocketUserAccountSubscriber");
|
|
23
|
+
const spotPosition_1 = require("./math/spotPosition");
|
|
24
|
+
const oracles_1 = require("./math/oracles");
|
|
25
|
+
const tiers_1 = require("./math/tiers");
|
|
26
|
+
const strictOraclePrice_1 = require("./oracles/strictOraclePrice");
|
|
27
|
+
const grpcUserAccountSubscriber_1 = require("./accounts/grpcUserAccountSubscriber");
|
|
28
|
+
const marginCalculation_1 = require("./marginCalculation");
|
|
29
|
+
class User {
|
|
30
|
+
get isSubscribed() {
|
|
31
|
+
return this._isSubscribed && this.accountSubscriber.isSubscribed;
|
|
32
|
+
}
|
|
33
|
+
set isSubscribed(val) {
|
|
34
|
+
this._isSubscribed = val;
|
|
35
|
+
}
|
|
36
|
+
constructor(config) {
|
|
37
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
|
|
38
|
+
this._isSubscribed = false;
|
|
39
|
+
this.driftClient = config.driftClient;
|
|
40
|
+
this.userAccountPublicKey = config.userAccountPublicKey;
|
|
41
|
+
if (((_a = config.accountSubscription) === null || _a === void 0 ? void 0 : _a.type) === 'polling') {
|
|
42
|
+
this.accountSubscriber = new pollingUserAccountSubscriber_1.PollingUserAccountSubscriber(config.driftClient.connection, config.userAccountPublicKey, config.accountSubscription.accountLoader, this.driftClient.program.account.user.coder.accounts.decodeUnchecked.bind(this.driftClient.program.account.user.coder.accounts));
|
|
43
|
+
}
|
|
44
|
+
else if (((_b = config.accountSubscription) === null || _b === void 0 ? void 0 : _b.type) === 'custom') {
|
|
45
|
+
this.accountSubscriber = config.accountSubscription.userAccountSubscriber;
|
|
46
|
+
}
|
|
47
|
+
else if (((_c = config.accountSubscription) === null || _c === void 0 ? void 0 : _c.type) === 'grpc') {
|
|
48
|
+
if (config.accountSubscription.grpcMultiUserAccountSubscriber) {
|
|
49
|
+
this.accountSubscriber =
|
|
50
|
+
config.accountSubscription.grpcMultiUserAccountSubscriber.forUser(config.userAccountPublicKey);
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
this.accountSubscriber = new grpcUserAccountSubscriber_1.grpcUserAccountSubscriber(config.accountSubscription.grpcConfigs, config.driftClient.program, config.userAccountPublicKey, {
|
|
54
|
+
resubTimeoutMs: (_d = config.accountSubscription) === null || _d === void 0 ? void 0 : _d.resubTimeoutMs,
|
|
55
|
+
logResubMessages: (_e = config.accountSubscription) === null || _e === void 0 ? void 0 : _e.logResubMessages,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
if (((_f = config.accountSubscription) === null || _f === void 0 ? void 0 : _f.type) === 'websocket' &&
|
|
61
|
+
((_g = config.accountSubscription) === null || _g === void 0 ? void 0 : _g.programUserAccountSubscriber)) {
|
|
62
|
+
this.accountSubscriber = new websocketProgramUserAccountSubscriber_1.WebSocketProgramUserAccountSubscriber(config.driftClient.program, config.userAccountPublicKey, config.accountSubscription.programUserAccountSubscriber);
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
this.accountSubscriber = new webSocketUserAccountSubscriber_1.WebSocketUserAccountSubscriber(config.driftClient.program, config.userAccountPublicKey, {
|
|
66
|
+
resubTimeoutMs: (_h = config.accountSubscription) === null || _h === void 0 ? void 0 : _h.resubTimeoutMs,
|
|
67
|
+
logResubMessages: (_j = config.accountSubscription) === null || _j === void 0 ? void 0 : _j.logResubMessages,
|
|
68
|
+
}, (_k = config.accountSubscription) === null || _k === void 0 ? void 0 : _k.commitment);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
this.eventEmitter = this.accountSubscriber.eventEmitter;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Subscribe to User state accounts
|
|
75
|
+
* @returns SusbcriptionSuccess result
|
|
76
|
+
*/
|
|
77
|
+
async subscribe(userAccount) {
|
|
78
|
+
this.isSubscribed = await this.accountSubscriber.subscribe(userAccount);
|
|
79
|
+
return this.isSubscribed;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Forces the accountSubscriber to fetch account updates from rpc
|
|
83
|
+
*/
|
|
84
|
+
async fetchAccounts() {
|
|
85
|
+
await this.accountSubscriber.fetch();
|
|
86
|
+
}
|
|
87
|
+
async unsubscribe() {
|
|
88
|
+
this.eventEmitter.removeAllListeners();
|
|
89
|
+
await this.accountSubscriber.unsubscribe();
|
|
90
|
+
this.isSubscribed = false;
|
|
91
|
+
}
|
|
92
|
+
getUserAccount() {
|
|
93
|
+
return this.accountSubscriber.getUserAccountAndSlot().data;
|
|
94
|
+
}
|
|
95
|
+
async forceGetUserAccount() {
|
|
96
|
+
await this.fetchAccounts();
|
|
97
|
+
return this.accountSubscriber.getUserAccountAndSlot().data;
|
|
98
|
+
}
|
|
99
|
+
getUserAccountAndSlot() {
|
|
100
|
+
return this.accountSubscriber.getUserAccountAndSlot();
|
|
101
|
+
}
|
|
102
|
+
getPerpPositionForUserAccount(userAccount, marketIndex) {
|
|
103
|
+
return this.getActivePerpPositionsForUserAccount(userAccount).find((position) => position.marketIndex === marketIndex);
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Gets the user's current position for a given perp market. If the user has no position returns undefined
|
|
107
|
+
* @param marketIndex
|
|
108
|
+
* @returns userPerpPosition
|
|
109
|
+
*/
|
|
110
|
+
getPerpPosition(marketIndex) {
|
|
111
|
+
const userAccount = this.getUserAccount();
|
|
112
|
+
return this.getPerpPositionForUserAccount(userAccount, marketIndex);
|
|
113
|
+
}
|
|
114
|
+
getPerpPositionOrEmpty(marketIndex) {
|
|
115
|
+
var _a;
|
|
116
|
+
const userAccount = this.getUserAccount();
|
|
117
|
+
return ((_a = this.getPerpPositionForUserAccount(userAccount, marketIndex)) !== null && _a !== void 0 ? _a : this.getEmptyPosition(marketIndex));
|
|
118
|
+
}
|
|
119
|
+
getPerpPositionAndSlot(marketIndex) {
|
|
120
|
+
const userAccount = this.getUserAccountAndSlot();
|
|
121
|
+
const perpPosition = this.getPerpPositionForUserAccount(userAccount.data, marketIndex);
|
|
122
|
+
return {
|
|
123
|
+
data: perpPosition,
|
|
124
|
+
slot: userAccount.slot,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
getSpotPositionForUserAccount(userAccount, marketIndex) {
|
|
128
|
+
return userAccount.spotPositions.find((position) => position.marketIndex === marketIndex);
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Gets the user's current position for a given spot market. If the user has no position returns undefined
|
|
132
|
+
* @param marketIndex
|
|
133
|
+
* @returns userSpotPosition
|
|
134
|
+
*/
|
|
135
|
+
getSpotPosition(marketIndex) {
|
|
136
|
+
const userAccount = this.getUserAccount();
|
|
137
|
+
return this.getSpotPositionForUserAccount(userAccount, marketIndex);
|
|
138
|
+
}
|
|
139
|
+
getSpotPositionAndSlot(marketIndex) {
|
|
140
|
+
const userAccount = this.getUserAccountAndSlot();
|
|
141
|
+
const spotPosition = this.getSpotPositionForUserAccount(userAccount.data, marketIndex);
|
|
142
|
+
return {
|
|
143
|
+
data: spotPosition,
|
|
144
|
+
slot: userAccount.slot,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
getEmptySpotPosition(marketIndex) {
|
|
148
|
+
return {
|
|
149
|
+
marketIndex,
|
|
150
|
+
scaledBalance: numericConstants_1.ZERO,
|
|
151
|
+
balanceType: types_2.SpotBalanceType.DEPOSIT,
|
|
152
|
+
cumulativeDeposits: numericConstants_1.ZERO,
|
|
153
|
+
openAsks: numericConstants_1.ZERO,
|
|
154
|
+
openBids: numericConstants_1.ZERO,
|
|
155
|
+
openOrders: 0,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Returns the token amount for a given market. The spot market precision is based on the token mint decimals.
|
|
160
|
+
* Positive if it is a deposit, negative if it is a borrow.
|
|
161
|
+
*
|
|
162
|
+
* @param marketIndex
|
|
163
|
+
*/
|
|
164
|
+
getTokenAmount(marketIndex) {
|
|
165
|
+
const spotPosition = this.getSpotPosition(marketIndex);
|
|
166
|
+
if (spotPosition === undefined) {
|
|
167
|
+
return numericConstants_1.ZERO;
|
|
168
|
+
}
|
|
169
|
+
const spotMarket = this.driftClient.getSpotMarketAccount(marketIndex);
|
|
170
|
+
return (0, spotBalance_1.getSignedTokenAmount)((0, spotBalance_2.getTokenAmount)(spotPosition.scaledBalance, spotMarket, spotPosition.balanceType), spotPosition.balanceType);
|
|
171
|
+
}
|
|
172
|
+
getEmptyPosition(marketIndex) {
|
|
173
|
+
return {
|
|
174
|
+
baseAssetAmount: numericConstants_1.ZERO,
|
|
175
|
+
remainderBaseAssetAmount: 0,
|
|
176
|
+
lastCumulativeFundingRate: numericConstants_1.ZERO,
|
|
177
|
+
marketIndex,
|
|
178
|
+
quoteAssetAmount: numericConstants_1.ZERO,
|
|
179
|
+
quoteEntryAmount: numericConstants_1.ZERO,
|
|
180
|
+
quoteBreakEvenAmount: numericConstants_1.ZERO,
|
|
181
|
+
openOrders: 0,
|
|
182
|
+
openBids: numericConstants_1.ZERO,
|
|
183
|
+
openAsks: numericConstants_1.ZERO,
|
|
184
|
+
settledPnl: numericConstants_1.ZERO,
|
|
185
|
+
maxMarginRatio: 0,
|
|
186
|
+
isolatedPositionScaledBalance: numericConstants_1.ZERO,
|
|
187
|
+
positionFlag: 0,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
isPositionEmpty(position) {
|
|
191
|
+
return position.baseAssetAmount.eq(numericConstants_1.ZERO) && position.openOrders === 0;
|
|
192
|
+
}
|
|
193
|
+
getIsolatePerpPositionTokenAmount(perpMarketIndex) {
|
|
194
|
+
var _a;
|
|
195
|
+
const perpPosition = this.getPerpPosition(perpMarketIndex);
|
|
196
|
+
if (!perpPosition)
|
|
197
|
+
return numericConstants_1.ZERO;
|
|
198
|
+
const perpMarket = this.driftClient.getPerpMarketAccount(perpMarketIndex);
|
|
199
|
+
const spotMarket = this.driftClient.getSpotMarketAccount(perpMarket.quoteSpotMarketIndex);
|
|
200
|
+
if (perpPosition === undefined) {
|
|
201
|
+
return numericConstants_1.ZERO;
|
|
202
|
+
}
|
|
203
|
+
return (0, spotBalance_2.getTokenAmount)((_a = perpPosition.isolatedPositionScaledBalance) !== null && _a !== void 0 ? _a : numericConstants_1.ZERO, //TODO remove ? later
|
|
204
|
+
spotMarket, types_2.SpotBalanceType.DEPOSIT);
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Returns the total USD value of deposits across all isolated perp positions.
|
|
208
|
+
*/
|
|
209
|
+
getTotalIsolatedPositionDeposits() {
|
|
210
|
+
return this.getActivePerpPositions().reduce((total, perpPosition) => {
|
|
211
|
+
var _a;
|
|
212
|
+
if (!((_a = perpPosition.isolatedPositionScaledBalance) === null || _a === void 0 ? void 0 : _a.gt(numericConstants_1.ZERO))) {
|
|
213
|
+
return total;
|
|
214
|
+
}
|
|
215
|
+
const perpMarket = this.driftClient.getPerpMarketAccount(perpPosition.marketIndex);
|
|
216
|
+
const quoteSpotMarket = this.driftClient.getSpotMarketAccount(perpMarket.quoteSpotMarketIndex);
|
|
217
|
+
const quoteOraclePriceData = this.getOracleDataForSpotMarket(perpMarket.quoteSpotMarketIndex);
|
|
218
|
+
const strictOracle = new strictOraclePrice_1.StrictOraclePrice(quoteOraclePriceData.price, quoteOraclePriceData.twap);
|
|
219
|
+
const tokenAmount = (0, spotBalance_2.getTokenAmount)(perpPosition.isolatedPositionScaledBalance, quoteSpotMarket, types_2.SpotBalanceType.DEPOSIT);
|
|
220
|
+
return total.add((0, spotBalance_1.getStrictTokenValue)(tokenAmount, quoteSpotMarket.decimals, strictOracle));
|
|
221
|
+
}, numericConstants_1.ZERO);
|
|
222
|
+
}
|
|
223
|
+
getClonedPosition(position) {
|
|
224
|
+
const clonedPosition = Object.assign({}, position);
|
|
225
|
+
return clonedPosition;
|
|
226
|
+
}
|
|
227
|
+
getOrderForUserAccount(userAccount, orderId) {
|
|
228
|
+
return userAccount.orders.find((order) => order.orderId === orderId);
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* @param orderId
|
|
232
|
+
* @returns Order
|
|
233
|
+
*/
|
|
234
|
+
getOrder(orderId) {
|
|
235
|
+
const userAccount = this.getUserAccount();
|
|
236
|
+
return this.getOrderForUserAccount(userAccount, orderId);
|
|
237
|
+
}
|
|
238
|
+
getOrderAndSlot(orderId) {
|
|
239
|
+
const userAccount = this.getUserAccountAndSlot();
|
|
240
|
+
const order = this.getOrderForUserAccount(userAccount.data, orderId);
|
|
241
|
+
return {
|
|
242
|
+
data: order,
|
|
243
|
+
slot: userAccount.slot,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
getOrderByUserIdForUserAccount(userAccount, userOrderId) {
|
|
247
|
+
return userAccount.orders.find((order) => order.userOrderId === userOrderId);
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* @param userOrderId
|
|
251
|
+
* @returns Order
|
|
252
|
+
*/
|
|
253
|
+
getOrderByUserOrderId(userOrderId) {
|
|
254
|
+
const userAccount = this.getUserAccount();
|
|
255
|
+
return this.getOrderByUserIdForUserAccount(userAccount, userOrderId);
|
|
256
|
+
}
|
|
257
|
+
getOrderByUserOrderIdAndSlot(userOrderId) {
|
|
258
|
+
const userAccount = this.getUserAccountAndSlot();
|
|
259
|
+
const order = this.getOrderByUserIdForUserAccount(userAccount.data, userOrderId);
|
|
260
|
+
return {
|
|
261
|
+
data: order,
|
|
262
|
+
slot: userAccount.slot,
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
getOpenOrdersForUserAccount(userAccount) {
|
|
266
|
+
return userAccount === null || userAccount === void 0 ? void 0 : userAccount.orders.filter((order) => (0, types_1.isVariant)(order.status, 'open'));
|
|
267
|
+
}
|
|
268
|
+
getOpenOrders() {
|
|
269
|
+
const userAccount = this.getUserAccount();
|
|
270
|
+
return this.getOpenOrdersForUserAccount(userAccount);
|
|
271
|
+
}
|
|
272
|
+
getOpenOrdersAndSlot() {
|
|
273
|
+
const userAccount = this.getUserAccountAndSlot();
|
|
274
|
+
const openOrders = this.getOpenOrdersForUserAccount(userAccount.data);
|
|
275
|
+
return {
|
|
276
|
+
data: openOrders,
|
|
277
|
+
slot: userAccount.slot,
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
getUserAccountPublicKey() {
|
|
281
|
+
return this.userAccountPublicKey;
|
|
282
|
+
}
|
|
283
|
+
async exists() {
|
|
284
|
+
const userAccountRPCResponse = await this.driftClient.connection.getParsedAccountInfo(this.userAccountPublicKey);
|
|
285
|
+
return userAccountRPCResponse.value !== null;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* calculates the total open bids/asks in a perp market (including lps)
|
|
289
|
+
* @returns : open bids
|
|
290
|
+
* @returns : open asks
|
|
291
|
+
*/
|
|
292
|
+
getPerpBidAsks(marketIndex) {
|
|
293
|
+
const position = this.getPerpPosition(marketIndex);
|
|
294
|
+
const totalOpenBids = position.openBids;
|
|
295
|
+
const totalOpenAsks = position.openAsks;
|
|
296
|
+
return [totalOpenBids, totalOpenAsks];
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* calculates Buying Power = free collateral / initial margin ratio
|
|
300
|
+
* @returns : Precision QUOTE_PRECISION
|
|
301
|
+
*/
|
|
302
|
+
getPerpBuyingPower(marketIndex, collateralBuffer = numericConstants_1.ZERO, maxMarginRatio = undefined, positionType = 'cross') {
|
|
303
|
+
const perpPosition = this.getPerpPositionOrEmpty(marketIndex);
|
|
304
|
+
const perpMarket = this.driftClient.getPerpMarketAccount(marketIndex);
|
|
305
|
+
const oraclePriceData = this.getOracleDataForPerpMarket(marketIndex);
|
|
306
|
+
const worstCaseBaseAssetAmount = perpPosition
|
|
307
|
+
? (0, margin_2.calculateWorstCaseBaseAssetAmount)(perpPosition, perpMarket, oraclePriceData.price)
|
|
308
|
+
: numericConstants_1.ZERO;
|
|
309
|
+
// if position is isolated, we always add on available quote from the cross account
|
|
310
|
+
let freeCollateral = numericConstants_1.ZERO;
|
|
311
|
+
if (positionType === 'isolated') {
|
|
312
|
+
const { totalAssetValue: quoteSpotMarketAssetValue, totalLiabilityValue: quoteSpotMarketLiabilityValue, } = this.getSpotMarketAssetAndLiabilityValue(perpMarket.quoteSpotMarketIndex, 'Initial', undefined, undefined, true);
|
|
313
|
+
const usdcAvailableForIsolatedMargin = quoteSpotMarketAssetValue.sub(quoteSpotMarketLiabilityValue);
|
|
314
|
+
const generalFreeCollateral = this.getFreeCollateral('Initial', undefined);
|
|
315
|
+
freeCollateral = anchor_1.BN.min(usdcAvailableForIsolatedMargin, generalFreeCollateral).sub(collateralBuffer);
|
|
316
|
+
}
|
|
317
|
+
else {
|
|
318
|
+
// free collateral from the cross account only
|
|
319
|
+
freeCollateral = this.getFreeCollateral('Initial', undefined).sub(collateralBuffer);
|
|
320
|
+
}
|
|
321
|
+
return this.getPerpBuyingPowerFromFreeCollateralAndBaseAssetAmount(marketIndex, freeCollateral, worstCaseBaseAssetAmount, maxMarginRatio || perpPosition.maxMarginRatio);
|
|
322
|
+
}
|
|
323
|
+
getPerpBuyingPowerFromFreeCollateralAndBaseAssetAmount(marketIndex, freeCollateral, baseAssetAmount, perpMarketMaxMarginRatio = undefined) {
|
|
324
|
+
const maxMarginRatio = Math.max(perpMarketMaxMarginRatio, this.getUserAccount().maxMarginRatio);
|
|
325
|
+
const marginRatio = (0, market_1.calculateMarketMarginRatio)(this.driftClient.getPerpMarketAccount(marketIndex), baseAssetAmount, 'Initial', maxMarginRatio);
|
|
326
|
+
return freeCollateral.mul(numericConstants_1.MARGIN_PRECISION).div(new anchor_1.BN(marginRatio));
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* calculates Free Collateral = Total collateral - margin requirement
|
|
330
|
+
* @returns : Precision QUOTE_PRECISION
|
|
331
|
+
*/
|
|
332
|
+
getFreeCollateral(marginCategory = 'Initial', perpMarketIndex) {
|
|
333
|
+
const calc = this.getMarginCalculation(marginCategory, {
|
|
334
|
+
strict: marginCategory === 'Initial',
|
|
335
|
+
});
|
|
336
|
+
if (perpMarketIndex !== undefined) {
|
|
337
|
+
// getIsolatedFreeCollateral will throw if no existing isolated position but we are fetching for potential new position, so we wrap in a try/catch
|
|
338
|
+
try {
|
|
339
|
+
return calc.getIsolatedFreeCollateral(perpMarketIndex);
|
|
340
|
+
}
|
|
341
|
+
catch (error) {
|
|
342
|
+
return numericConstants_1.ZERO;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
else {
|
|
346
|
+
return calc.getCrossFreeCollateral();
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
getMarginRequirement(marginCategory, liquidationBuffer, strict, includeOpenOrders, perpMarketIndex) {
|
|
350
|
+
const liquidationBufferMap = new Map();
|
|
351
|
+
if (liquidationBuffer && perpMarketIndex !== undefined) {
|
|
352
|
+
liquidationBufferMap.set(perpMarketIndex, liquidationBuffer);
|
|
353
|
+
}
|
|
354
|
+
else if (liquidationBuffer) {
|
|
355
|
+
liquidationBufferMap.set('cross', liquidationBuffer);
|
|
356
|
+
}
|
|
357
|
+
const marginCalc = this.getMarginCalculation(marginCategory, {
|
|
358
|
+
strict,
|
|
359
|
+
includeOpenOrders,
|
|
360
|
+
liquidationBufferMap,
|
|
361
|
+
});
|
|
362
|
+
// If perpMarketIndex is provided, compute only for that market index
|
|
363
|
+
if (perpMarketIndex !== undefined) {
|
|
364
|
+
const isolatedMarginCalculation = marginCalc.isolatedMarginCalculations.get(perpMarketIndex);
|
|
365
|
+
if (!isolatedMarginCalculation)
|
|
366
|
+
return numericConstants_1.ZERO;
|
|
367
|
+
const { marginRequirement, marginRequirementPlusBuffer } = isolatedMarginCalculation;
|
|
368
|
+
if (liquidationBuffer === null || liquidationBuffer === void 0 ? void 0 : liquidationBuffer.gt(numericConstants_1.ZERO)) {
|
|
369
|
+
return marginRequirementPlusBuffer;
|
|
370
|
+
}
|
|
371
|
+
return marginRequirement;
|
|
372
|
+
}
|
|
373
|
+
// Default: Cross margin requirement
|
|
374
|
+
if (liquidationBuffer === null || liquidationBuffer === void 0 ? void 0 : liquidationBuffer.gt(numericConstants_1.ZERO)) {
|
|
375
|
+
return marginCalc.marginRequirementPlusBuffer;
|
|
376
|
+
}
|
|
377
|
+
return marginCalc.marginRequirement;
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* @returns The initial margin requirement in USDC. : QUOTE_PRECISION
|
|
381
|
+
*/
|
|
382
|
+
getInitialMarginRequirement(perpMarketIndex) {
|
|
383
|
+
return this.getMarginRequirement('Initial', undefined, true, undefined, perpMarketIndex);
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* @returns The maintenance margin requirement in USDC. : QUOTE_PRECISION
|
|
387
|
+
*/
|
|
388
|
+
getMaintenanceMarginRequirement(liquidationBuffer, perpMarketIndex) {
|
|
389
|
+
return this.getMarginRequirement('Maintenance', liquidationBuffer, false, // strict default
|
|
390
|
+
true, // includeOpenOrders default
|
|
391
|
+
perpMarketIndex);
|
|
392
|
+
}
|
|
393
|
+
getActivePerpPositionsForUserAccount(userAccount) {
|
|
394
|
+
return userAccount.perpPositions.filter((pos) => {
|
|
395
|
+
var _a;
|
|
396
|
+
return !pos.baseAssetAmount.eq(numericConstants_1.ZERO) ||
|
|
397
|
+
!pos.quoteAssetAmount.eq(numericConstants_1.ZERO) ||
|
|
398
|
+
!(pos.openOrders == 0) ||
|
|
399
|
+
((_a = pos.isolatedPositionScaledBalance) === null || _a === void 0 ? void 0 : _a.gt(numericConstants_1.ZERO));
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
getActivePerpPositions() {
|
|
403
|
+
const userAccount = this.getUserAccount();
|
|
404
|
+
return this.getActivePerpPositionsForUserAccount(userAccount);
|
|
405
|
+
}
|
|
406
|
+
getActivePerpPositionsAndSlot() {
|
|
407
|
+
const userAccount = this.getUserAccountAndSlot();
|
|
408
|
+
const positions = this.getActivePerpPositionsForUserAccount(userAccount.data);
|
|
409
|
+
return {
|
|
410
|
+
data: positions,
|
|
411
|
+
slot: userAccount.slot,
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
getActiveSpotPositionsForUserAccount(userAccount) {
|
|
415
|
+
return userAccount.spotPositions.filter((pos) => !(0, spotPosition_1.isSpotPositionAvailable)(pos));
|
|
416
|
+
}
|
|
417
|
+
getActiveSpotPositions() {
|
|
418
|
+
const userAccount = this.getUserAccount();
|
|
419
|
+
return this.getActiveSpotPositionsForUserAccount(userAccount);
|
|
420
|
+
}
|
|
421
|
+
getActiveSpotPositionsAndSlot() {
|
|
422
|
+
const userAccount = this.getUserAccountAndSlot();
|
|
423
|
+
const positions = this.getActiveSpotPositionsForUserAccount(userAccount.data);
|
|
424
|
+
return {
|
|
425
|
+
data: positions,
|
|
426
|
+
slot: userAccount.slot,
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* calculates unrealized position price pnl
|
|
431
|
+
* @returns : Precision QUOTE_PRECISION
|
|
432
|
+
*/
|
|
433
|
+
getUnrealizedPNL(withFunding, marketIndex, withWeightMarginCategory, strict = false, liquidationBuffer) {
|
|
434
|
+
return this.getActivePerpPositions()
|
|
435
|
+
.filter((pos) => marketIndex !== undefined ? pos.marketIndex === marketIndex : true)
|
|
436
|
+
.reduce((unrealizedPnl, perpPosition) => {
|
|
437
|
+
const market = this.driftClient.getPerpMarketAccount(perpPosition.marketIndex);
|
|
438
|
+
const oraclePriceData = this.getMMOracleDataForPerpMarket(market.marketIndex);
|
|
439
|
+
const quoteSpotMarket = this.driftClient.getSpotMarketAccount(market.quoteSpotMarketIndex);
|
|
440
|
+
const quoteOraclePriceData = this.getOracleDataForSpotMarket(market.quoteSpotMarketIndex);
|
|
441
|
+
let positionUnrealizedPnl = (0, position_2.calculatePositionPNL)(market, perpPosition, withFunding, oraclePriceData);
|
|
442
|
+
let quotePrice;
|
|
443
|
+
if (strict && positionUnrealizedPnl.gt(numericConstants_1.ZERO)) {
|
|
444
|
+
quotePrice = anchor_1.BN.min(quoteOraclePriceData.price, quoteSpotMarket.historicalOracleData.lastOraclePriceTwap5Min);
|
|
445
|
+
}
|
|
446
|
+
else if (strict && positionUnrealizedPnl.lt(numericConstants_1.ZERO)) {
|
|
447
|
+
quotePrice = anchor_1.BN.max(quoteOraclePriceData.price, quoteSpotMarket.historicalOracleData.lastOraclePriceTwap5Min);
|
|
448
|
+
}
|
|
449
|
+
else {
|
|
450
|
+
quotePrice = quoteOraclePriceData.price;
|
|
451
|
+
}
|
|
452
|
+
positionUnrealizedPnl = positionUnrealizedPnl
|
|
453
|
+
.mul(quotePrice)
|
|
454
|
+
.div(numericConstants_1.PRICE_PRECISION);
|
|
455
|
+
if (withWeightMarginCategory !== undefined) {
|
|
456
|
+
if (positionUnrealizedPnl.gt(numericConstants_1.ZERO)) {
|
|
457
|
+
positionUnrealizedPnl = positionUnrealizedPnl
|
|
458
|
+
.mul((0, market_1.calculateUnrealizedAssetWeight)(market, quoteSpotMarket, positionUnrealizedPnl, withWeightMarginCategory, oraclePriceData))
|
|
459
|
+
.div(new anchor_1.BN(numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION));
|
|
460
|
+
}
|
|
461
|
+
if (liquidationBuffer && positionUnrealizedPnl.lt(numericConstants_1.ZERO)) {
|
|
462
|
+
positionUnrealizedPnl = positionUnrealizedPnl.add(positionUnrealizedPnl.mul(liquidationBuffer).div(numericConstants_1.MARGIN_PRECISION));
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
return unrealizedPnl.add(positionUnrealizedPnl);
|
|
466
|
+
}, numericConstants_1.ZERO);
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* calculates unrealized funding payment pnl
|
|
470
|
+
* @returns : Precision QUOTE_PRECISION
|
|
471
|
+
*/
|
|
472
|
+
getUnrealizedFundingPNL(marketIndex) {
|
|
473
|
+
return this.getUserAccount()
|
|
474
|
+
.perpPositions.filter((pos) => marketIndex !== undefined ? pos.marketIndex === marketIndex : true)
|
|
475
|
+
.reduce((pnl, perpPosition) => {
|
|
476
|
+
const market = this.driftClient.getPerpMarketAccount(perpPosition.marketIndex);
|
|
477
|
+
return pnl.add((0, position_1.calculateUnsettledFundingPnl)(market, perpPosition));
|
|
478
|
+
}, numericConstants_1.ZERO);
|
|
479
|
+
}
|
|
480
|
+
getSpotMarketAssetAndLiabilityValue(marketIndex, marginCategory, liquidationBuffer, includeOpenOrders, strict = false, now) {
|
|
481
|
+
now = now || new anchor_1.BN(new Date().getTime() / 1000);
|
|
482
|
+
let netQuoteValue = numericConstants_1.ZERO;
|
|
483
|
+
let totalAssetValue = numericConstants_1.ZERO;
|
|
484
|
+
let totalLiabilityValue = numericConstants_1.ZERO;
|
|
485
|
+
for (const spotPosition of this.getUserAccount().spotPositions) {
|
|
486
|
+
const countForBase = marketIndex === undefined || spotPosition.marketIndex === marketIndex;
|
|
487
|
+
const countForQuote = marketIndex === undefined ||
|
|
488
|
+
marketIndex === numericConstants_1.QUOTE_SPOT_MARKET_INDEX ||
|
|
489
|
+
(includeOpenOrders && spotPosition.openOrders !== 0);
|
|
490
|
+
if ((0, spotPosition_1.isSpotPositionAvailable)(spotPosition) ||
|
|
491
|
+
(!countForBase && !countForQuote)) {
|
|
492
|
+
continue;
|
|
493
|
+
}
|
|
494
|
+
const spotMarketAccount = this.driftClient.getSpotMarketAccount(spotPosition.marketIndex);
|
|
495
|
+
const oraclePriceData = this.getOracleDataForSpotMarket(spotPosition.marketIndex);
|
|
496
|
+
let twap5min;
|
|
497
|
+
if (strict) {
|
|
498
|
+
twap5min = (0, oracles_1.calculateLiveOracleTwap)(spotMarketAccount.historicalOracleData, oraclePriceData, now, numericConstants_1.FIVE_MINUTE // 5MIN
|
|
499
|
+
);
|
|
500
|
+
}
|
|
501
|
+
const strictOraclePrice = new strictOraclePrice_1.StrictOraclePrice(oraclePriceData.price, twap5min);
|
|
502
|
+
if (spotPosition.marketIndex === numericConstants_1.QUOTE_SPOT_MARKET_INDEX &&
|
|
503
|
+
countForQuote) {
|
|
504
|
+
const tokenAmount = (0, spotBalance_1.getSignedTokenAmount)((0, spotBalance_2.getTokenAmount)(spotPosition.scaledBalance, spotMarketAccount, spotPosition.balanceType), spotPosition.balanceType);
|
|
505
|
+
if ((0, types_1.isVariant)(spotPosition.balanceType, 'borrow')) {
|
|
506
|
+
const weightedTokenValue = this.getSpotLiabilityValue(tokenAmount, strictOraclePrice, spotMarketAccount, marginCategory, liquidationBuffer).abs();
|
|
507
|
+
netQuoteValue = netQuoteValue.sub(weightedTokenValue);
|
|
508
|
+
}
|
|
509
|
+
else {
|
|
510
|
+
const weightedTokenValue = this.getSpotAssetValue(tokenAmount, strictOraclePrice, spotMarketAccount, marginCategory);
|
|
511
|
+
netQuoteValue = netQuoteValue.add(weightedTokenValue);
|
|
512
|
+
}
|
|
513
|
+
continue;
|
|
514
|
+
}
|
|
515
|
+
if (!includeOpenOrders && countForBase) {
|
|
516
|
+
if ((0, types_1.isVariant)(spotPosition.balanceType, 'borrow')) {
|
|
517
|
+
const tokenAmount = (0, spotBalance_1.getSignedTokenAmount)((0, spotBalance_2.getTokenAmount)(spotPosition.scaledBalance, spotMarketAccount, spotPosition.balanceType), types_2.SpotBalanceType.BORROW);
|
|
518
|
+
const liabilityValue = this.getSpotLiabilityValue(tokenAmount, strictOraclePrice, spotMarketAccount, marginCategory, liquidationBuffer).abs();
|
|
519
|
+
totalLiabilityValue = totalLiabilityValue.add(liabilityValue);
|
|
520
|
+
continue;
|
|
521
|
+
}
|
|
522
|
+
else {
|
|
523
|
+
const tokenAmount = (0, spotBalance_2.getTokenAmount)(spotPosition.scaledBalance, spotMarketAccount, spotPosition.balanceType);
|
|
524
|
+
const assetValue = this.getSpotAssetValue(tokenAmount, strictOraclePrice, spotMarketAccount, marginCategory);
|
|
525
|
+
totalAssetValue = totalAssetValue.add(assetValue);
|
|
526
|
+
continue;
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
const { tokenAmount: worstCaseTokenAmount, ordersValue: worstCaseQuoteTokenAmount, } = (0, spotPosition_1.getWorstCaseTokenAmounts)(spotPosition, spotMarketAccount, strictOraclePrice, marginCategory, this.getUserAccount().maxMarginRatio);
|
|
530
|
+
if (worstCaseTokenAmount.gt(numericConstants_1.ZERO) && countForBase) {
|
|
531
|
+
const baseAssetValue = this.getSpotAssetValue(worstCaseTokenAmount, strictOraclePrice, spotMarketAccount, marginCategory);
|
|
532
|
+
totalAssetValue = totalAssetValue.add(baseAssetValue);
|
|
533
|
+
}
|
|
534
|
+
if (worstCaseTokenAmount.lt(numericConstants_1.ZERO) && countForBase) {
|
|
535
|
+
const baseLiabilityValue = this.getSpotLiabilityValue(worstCaseTokenAmount, strictOraclePrice, spotMarketAccount, marginCategory, liquidationBuffer).abs();
|
|
536
|
+
totalLiabilityValue = totalLiabilityValue.add(baseLiabilityValue);
|
|
537
|
+
}
|
|
538
|
+
if (worstCaseQuoteTokenAmount.gt(numericConstants_1.ZERO) && countForQuote) {
|
|
539
|
+
netQuoteValue = netQuoteValue.add(worstCaseQuoteTokenAmount);
|
|
540
|
+
}
|
|
541
|
+
if (worstCaseQuoteTokenAmount.lt(numericConstants_1.ZERO) && countForQuote) {
|
|
542
|
+
let weight = numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION;
|
|
543
|
+
if (marginCategory === 'Initial') {
|
|
544
|
+
weight = anchor_1.BN.max(weight, new anchor_1.BN(this.getUserAccount().maxMarginRatio));
|
|
545
|
+
}
|
|
546
|
+
const weightedTokenValue = worstCaseQuoteTokenAmount
|
|
547
|
+
.abs()
|
|
548
|
+
.mul(weight)
|
|
549
|
+
.div(numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION);
|
|
550
|
+
netQuoteValue = netQuoteValue.sub(weightedTokenValue);
|
|
551
|
+
}
|
|
552
|
+
totalLiabilityValue = totalLiabilityValue.add(new anchor_1.BN(spotPosition.openOrders).mul(numericConstants_1.OPEN_ORDER_MARGIN_REQUIREMENT));
|
|
553
|
+
}
|
|
554
|
+
if (marketIndex === undefined || marketIndex === numericConstants_1.QUOTE_SPOT_MARKET_INDEX) {
|
|
555
|
+
if (netQuoteValue.gt(numericConstants_1.ZERO)) {
|
|
556
|
+
totalAssetValue = totalAssetValue.add(netQuoteValue);
|
|
557
|
+
}
|
|
558
|
+
else {
|
|
559
|
+
totalLiabilityValue = totalLiabilityValue.add(netQuoteValue.abs());
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
return { totalAssetValue, totalLiabilityValue };
|
|
563
|
+
}
|
|
564
|
+
getSpotMarketLiabilityValue(marketIndex, marginCategory, liquidationBuffer, includeOpenOrders, strict = false, now) {
|
|
565
|
+
const { totalLiabilityValue } = this.getSpotMarketAssetAndLiabilityValue(marketIndex, marginCategory, liquidationBuffer, includeOpenOrders, strict, now);
|
|
566
|
+
return totalLiabilityValue;
|
|
567
|
+
}
|
|
568
|
+
getSpotLiabilityValue(tokenAmount, strictOraclePrice, spotMarketAccount, marginCategory, liquidationBuffer) {
|
|
569
|
+
return (0, spotBalance_2.getSpotLiabilityValue)(tokenAmount, strictOraclePrice, spotMarketAccount, this.getUserAccount().maxMarginRatio, marginCategory, liquidationBuffer);
|
|
570
|
+
}
|
|
571
|
+
getSpotMarketAssetValue(marketIndex, marginCategory, includeOpenOrders, strict = false, now) {
|
|
572
|
+
const { totalAssetValue } = this.getSpotMarketAssetAndLiabilityValue(marketIndex, marginCategory, undefined, includeOpenOrders, strict, now);
|
|
573
|
+
return totalAssetValue;
|
|
574
|
+
}
|
|
575
|
+
getSpotAssetValue(tokenAmount, strictOraclePrice, spotMarketAccount, marginCategory) {
|
|
576
|
+
return (0, spotBalance_2.getSpotAssetValue)(tokenAmount, strictOraclePrice, spotMarketAccount, this.getUserAccount().maxMarginRatio, marginCategory);
|
|
577
|
+
}
|
|
578
|
+
getSpotPositionValue(marketIndex, marginCategory, includeOpenOrders, strict = false, now) {
|
|
579
|
+
const { totalAssetValue, totalLiabilityValue } = this.getSpotMarketAssetAndLiabilityValue(marketIndex, marginCategory, undefined, includeOpenOrders, strict, now);
|
|
580
|
+
return totalAssetValue.sub(totalLiabilityValue);
|
|
581
|
+
}
|
|
582
|
+
getNetSpotMarketValue(withWeightMarginCategory) {
|
|
583
|
+
const { totalAssetValue, totalLiabilityValue } = this.getSpotMarketAssetAndLiabilityValue(undefined, withWeightMarginCategory);
|
|
584
|
+
return totalAssetValue.sub(totalLiabilityValue);
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* calculates TotalCollateral: collateral + unrealized pnl
|
|
588
|
+
* @returns : Precision QUOTE_PRECISION
|
|
589
|
+
*/
|
|
590
|
+
getTotalCollateral(marginCategory = 'Initial', strict = false, includeOpenOrders = true, liquidationBuffer, perpMarketIndex) {
|
|
591
|
+
const liquidationBufferMap = (() => {
|
|
592
|
+
if (liquidationBuffer && perpMarketIndex !== undefined) {
|
|
593
|
+
return new Map([[perpMarketIndex, liquidationBuffer]]);
|
|
594
|
+
}
|
|
595
|
+
else if (liquidationBuffer) {
|
|
596
|
+
return new Map([['cross', liquidationBuffer]]);
|
|
597
|
+
}
|
|
598
|
+
return new Map();
|
|
599
|
+
})();
|
|
600
|
+
const marginCalc = this.getMarginCalculation(marginCategory, {
|
|
601
|
+
strict,
|
|
602
|
+
includeOpenOrders,
|
|
603
|
+
liquidationBufferMap,
|
|
604
|
+
});
|
|
605
|
+
if (perpMarketIndex !== undefined) {
|
|
606
|
+
const { totalCollateral, totalCollateralBuffer } = marginCalc.isolatedMarginCalculations.get(perpMarketIndex);
|
|
607
|
+
if (liquidationBuffer === null || liquidationBuffer === void 0 ? void 0 : liquidationBuffer.gt(numericConstants_1.ZERO)) {
|
|
608
|
+
return totalCollateralBuffer;
|
|
609
|
+
}
|
|
610
|
+
return totalCollateral;
|
|
611
|
+
}
|
|
612
|
+
if (liquidationBuffer === null || liquidationBuffer === void 0 ? void 0 : liquidationBuffer.gt(numericConstants_1.ZERO)) {
|
|
613
|
+
return marginCalc.totalCollateralBuffer;
|
|
614
|
+
}
|
|
615
|
+
return marginCalc.totalCollateral;
|
|
616
|
+
}
|
|
617
|
+
getLiquidationBuffer() {
|
|
618
|
+
const liquidationBufferMap = new Map();
|
|
619
|
+
if (this.isBeingLiquidated()) {
|
|
620
|
+
liquidationBufferMap.set('cross', new anchor_1.BN(this.driftClient.getStateAccount().liquidationMarginBufferRatio));
|
|
621
|
+
}
|
|
622
|
+
for (const position of this.getActivePerpPositions()) {
|
|
623
|
+
if (position.positionFlag &
|
|
624
|
+
(types_2.PositionFlag.BeingLiquidated | types_2.PositionFlag.Bankruptcy)) {
|
|
625
|
+
liquidationBufferMap.set(position.marketIndex, new anchor_1.BN(this.driftClient.getStateAccount().liquidationMarginBufferRatio));
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
return liquidationBufferMap;
|
|
629
|
+
}
|
|
630
|
+
/**
|
|
631
|
+
* calculates User Health by comparing total collateral and maint. margin requirement
|
|
632
|
+
* @returns : number (value from [0, 100])
|
|
633
|
+
*/
|
|
634
|
+
getHealth(perpMarketIndex) {
|
|
635
|
+
if (this.isCrossMarginBeingLiquidated() && !perpMarketIndex) {
|
|
636
|
+
return 0;
|
|
637
|
+
}
|
|
638
|
+
if (perpMarketIndex &&
|
|
639
|
+
this.isIsolatedPositionBeingLiquidated(perpMarketIndex)) {
|
|
640
|
+
return 0;
|
|
641
|
+
}
|
|
642
|
+
const marginCalc = this.getMarginCalculation('Maintenance');
|
|
643
|
+
let totalCollateral = numericConstants_1.ZERO;
|
|
644
|
+
let maintenanceMarginReq = numericConstants_1.ZERO;
|
|
645
|
+
if (perpMarketIndex != null) {
|
|
646
|
+
const isolatedMarginCalc = marginCalc.isolatedMarginCalculations.get(perpMarketIndex);
|
|
647
|
+
if (isolatedMarginCalc) {
|
|
648
|
+
totalCollateral = isolatedMarginCalc.totalCollateral;
|
|
649
|
+
maintenanceMarginReq = isolatedMarginCalc.marginRequirement;
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
else {
|
|
653
|
+
totalCollateral = marginCalc.totalCollateral;
|
|
654
|
+
maintenanceMarginReq = marginCalc.marginRequirement;
|
|
655
|
+
}
|
|
656
|
+
let health;
|
|
657
|
+
if (maintenanceMarginReq.eq(numericConstants_1.ZERO) && totalCollateral.gte(numericConstants_1.ZERO)) {
|
|
658
|
+
health = 100;
|
|
659
|
+
}
|
|
660
|
+
else if (totalCollateral.lte(numericConstants_1.ZERO)) {
|
|
661
|
+
health = 0;
|
|
662
|
+
}
|
|
663
|
+
else {
|
|
664
|
+
health = Math.round(Math.min(100, Math.max(0, (1 - maintenanceMarginReq.toNumber() / totalCollateral.toNumber()) *
|
|
665
|
+
100)));
|
|
666
|
+
}
|
|
667
|
+
return health;
|
|
668
|
+
}
|
|
669
|
+
calculateWeightedPerpPositionLiability(perpPosition, marginCategory, liquidationBuffer, includeOpenOrders, strict = false) {
|
|
670
|
+
const market = this.driftClient.getPerpMarketAccount(perpPosition.marketIndex);
|
|
671
|
+
let valuationPrice = this.getOracleDataForPerpMarket(market.marketIndex).price;
|
|
672
|
+
if ((0, types_1.isVariant)(market.status, 'settlement')) {
|
|
673
|
+
valuationPrice = market.expiryPrice;
|
|
674
|
+
}
|
|
675
|
+
let baseAssetAmount;
|
|
676
|
+
let liabilityValue;
|
|
677
|
+
if (includeOpenOrders) {
|
|
678
|
+
const { worstCaseBaseAssetAmount, worstCaseLiabilityValue } = (0, margin_1.calculateWorstCasePerpLiabilityValue)(perpPosition, market, valuationPrice);
|
|
679
|
+
baseAssetAmount = worstCaseBaseAssetAmount;
|
|
680
|
+
liabilityValue = worstCaseLiabilityValue;
|
|
681
|
+
}
|
|
682
|
+
else {
|
|
683
|
+
baseAssetAmount = perpPosition.baseAssetAmount;
|
|
684
|
+
liabilityValue = (0, margin_1.calculatePerpLiabilityValue)(baseAssetAmount, valuationPrice);
|
|
685
|
+
}
|
|
686
|
+
if (marginCategory) {
|
|
687
|
+
const userCustomMargin = Math.max(perpPosition.maxMarginRatio, this.getUserAccount().maxMarginRatio);
|
|
688
|
+
let marginRatio = new anchor_1.BN((0, market_1.calculateMarketMarginRatio)(market, baseAssetAmount.abs(), marginCategory, userCustomMargin));
|
|
689
|
+
if (liquidationBuffer !== undefined) {
|
|
690
|
+
marginRatio = marginRatio.add(liquidationBuffer);
|
|
691
|
+
}
|
|
692
|
+
if ((0, types_1.isVariant)(market.status, 'settlement')) {
|
|
693
|
+
marginRatio = numericConstants_1.ZERO;
|
|
694
|
+
}
|
|
695
|
+
const quoteSpotMarket = this.driftClient.getSpotMarketAccount(market.quoteSpotMarketIndex);
|
|
696
|
+
const quoteOraclePriceData = this.driftClient.getOracleDataForSpotMarket(numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
|
|
697
|
+
let quotePrice;
|
|
698
|
+
if (strict) {
|
|
699
|
+
quotePrice = anchor_1.BN.max(quoteOraclePriceData.price, quoteSpotMarket.historicalOracleData.lastOraclePriceTwap5Min);
|
|
700
|
+
}
|
|
701
|
+
else {
|
|
702
|
+
quotePrice = quoteOraclePriceData.price;
|
|
703
|
+
}
|
|
704
|
+
liabilityValue = liabilityValue
|
|
705
|
+
.mul(quotePrice)
|
|
706
|
+
.div(numericConstants_1.PRICE_PRECISION)
|
|
707
|
+
.mul(marginRatio)
|
|
708
|
+
.div(numericConstants_1.MARGIN_PRECISION);
|
|
709
|
+
if (includeOpenOrders) {
|
|
710
|
+
liabilityValue = liabilityValue.add(new anchor_1.BN(perpPosition.openOrders).mul(numericConstants_1.OPEN_ORDER_MARGIN_REQUIREMENT));
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
return liabilityValue;
|
|
714
|
+
}
|
|
715
|
+
/**
|
|
716
|
+
* calculates position value of a single perp market in margin system
|
|
717
|
+
* @returns : Precision QUOTE_PRECISION
|
|
718
|
+
*/
|
|
719
|
+
getPerpMarketLiabilityValue(marketIndex, marginCategory, liquidationBuffer, includeOpenOrders, strict = false) {
|
|
720
|
+
const perpPosition = this.getPerpPosition(marketIndex);
|
|
721
|
+
return this.calculateWeightedPerpPositionLiability(perpPosition, marginCategory, liquidationBuffer, includeOpenOrders, strict);
|
|
722
|
+
}
|
|
723
|
+
/**
|
|
724
|
+
* calculates sum of position value across all positions in margin system
|
|
725
|
+
* @returns : Precision QUOTE_PRECISION
|
|
726
|
+
*/
|
|
727
|
+
getTotalPerpPositionLiability(marginCategory, liquidationBuffer, includeOpenOrders, strict = false) {
|
|
728
|
+
return this.getActivePerpPositions().reduce((totalPerpValue, perpPosition) => {
|
|
729
|
+
const baseAssetValue = this.calculateWeightedPerpPositionLiability(perpPosition, marginCategory, liquidationBuffer, includeOpenOrders, strict);
|
|
730
|
+
return totalPerpValue.add(baseAssetValue);
|
|
731
|
+
}, numericConstants_1.ZERO);
|
|
732
|
+
}
|
|
733
|
+
/**
|
|
734
|
+
* calculates position value based on oracle
|
|
735
|
+
* @returns : Precision QUOTE_PRECISION
|
|
736
|
+
*/
|
|
737
|
+
getPerpPositionValue(marketIndex, oraclePriceData, includeOpenOrders = false) {
|
|
738
|
+
const userPosition = this.getPerpPositionOrEmpty(marketIndex);
|
|
739
|
+
const market = this.driftClient.getPerpMarketAccount(userPosition.marketIndex);
|
|
740
|
+
return (0, margin_2.calculateBaseAssetValueWithOracle)(market, userPosition, oraclePriceData, includeOpenOrders);
|
|
741
|
+
}
|
|
742
|
+
/**
|
|
743
|
+
* calculates position liabiltiy value in margin system
|
|
744
|
+
* @returns : Precision QUOTE_PRECISION
|
|
745
|
+
*/
|
|
746
|
+
getPerpLiabilityValue(marketIndex, oraclePriceData, includeOpenOrders = false) {
|
|
747
|
+
const userPosition = this.getPerpPositionOrEmpty(marketIndex);
|
|
748
|
+
const market = this.driftClient.getPerpMarketAccount(userPosition.marketIndex);
|
|
749
|
+
if (includeOpenOrders) {
|
|
750
|
+
return (0, margin_1.calculateWorstCasePerpLiabilityValue)(userPosition, market, oraclePriceData.price).worstCaseLiabilityValue;
|
|
751
|
+
}
|
|
752
|
+
else {
|
|
753
|
+
return (0, margin_1.calculatePerpLiabilityValue)(userPosition.baseAssetAmount, oraclePriceData.price);
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
getPositionSide(currentPosition) {
|
|
757
|
+
if (currentPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
|
|
758
|
+
return types_2.PositionDirection.LONG;
|
|
759
|
+
}
|
|
760
|
+
else if (currentPosition.baseAssetAmount.lt(numericConstants_1.ZERO)) {
|
|
761
|
+
return types_2.PositionDirection.SHORT;
|
|
762
|
+
}
|
|
763
|
+
else {
|
|
764
|
+
return undefined;
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* calculates average exit price (optionally for closing up to 100% of position)
|
|
769
|
+
* @returns : Precision PRICE_PRECISION
|
|
770
|
+
*/
|
|
771
|
+
getPositionEstimatedExitPriceAndPnl(position, amountToClose, useAMMClose = false) {
|
|
772
|
+
const market = this.driftClient.getPerpMarketAccount(position.marketIndex);
|
|
773
|
+
const entryPrice = (0, position_1.calculateEntryPrice)(position);
|
|
774
|
+
const oraclePriceData = this.getMMOracleDataForPerpMarket(position.marketIndex);
|
|
775
|
+
if (amountToClose) {
|
|
776
|
+
if (amountToClose.eq(numericConstants_1.ZERO)) {
|
|
777
|
+
return [(0, market_1.calculateReservePrice)(market, oraclePriceData), numericConstants_1.ZERO];
|
|
778
|
+
}
|
|
779
|
+
position = {
|
|
780
|
+
baseAssetAmount: amountToClose,
|
|
781
|
+
lastCumulativeFundingRate: position.lastCumulativeFundingRate,
|
|
782
|
+
marketIndex: position.marketIndex,
|
|
783
|
+
quoteAssetAmount: position.quoteAssetAmount,
|
|
784
|
+
};
|
|
785
|
+
}
|
|
786
|
+
let baseAssetValue;
|
|
787
|
+
if (useAMMClose) {
|
|
788
|
+
baseAssetValue = (0, position_2.calculateBaseAssetValue)(market, position, oraclePriceData);
|
|
789
|
+
}
|
|
790
|
+
else {
|
|
791
|
+
baseAssetValue = (0, margin_2.calculateBaseAssetValueWithOracle)(market, position, oraclePriceData);
|
|
792
|
+
}
|
|
793
|
+
if (position.baseAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
794
|
+
return [numericConstants_1.ZERO, numericConstants_1.ZERO];
|
|
795
|
+
}
|
|
796
|
+
const exitPrice = baseAssetValue
|
|
797
|
+
.mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
|
|
798
|
+
.mul(numericConstants_1.PRICE_PRECISION)
|
|
799
|
+
.div(position.baseAssetAmount.abs());
|
|
800
|
+
const pnlPerBase = exitPrice.sub(entryPrice);
|
|
801
|
+
const pnl = pnlPerBase
|
|
802
|
+
.mul(position.baseAssetAmount)
|
|
803
|
+
.div(numericConstants_1.PRICE_PRECISION)
|
|
804
|
+
.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO);
|
|
805
|
+
return [exitPrice, pnl];
|
|
806
|
+
}
|
|
807
|
+
/**
|
|
808
|
+
* calculates current user leverage which is (total liability size) / (net asset value)
|
|
809
|
+
* @returns : Precision TEN_THOUSAND
|
|
810
|
+
*/
|
|
811
|
+
getLeverage(includeOpenOrders = true, perpMarketIndex) {
|
|
812
|
+
return this.calculateLeverageFromComponents(this.getLeverageComponents(includeOpenOrders, undefined, perpMarketIndex));
|
|
813
|
+
}
|
|
814
|
+
calculateLeverageFromComponents({ perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue, }) {
|
|
815
|
+
const totalLiabilityValue = perpLiabilityValue.add(spotLiabilityValue);
|
|
816
|
+
const totalAssetValue = spotAssetValue.add(perpPnl);
|
|
817
|
+
const netAssetValue = totalAssetValue.sub(spotLiabilityValue);
|
|
818
|
+
if (netAssetValue.eq(numericConstants_1.ZERO)) {
|
|
819
|
+
return numericConstants_1.ZERO;
|
|
820
|
+
}
|
|
821
|
+
return totalLiabilityValue.mul(numericConstants_1.TEN_THOUSAND).div(netAssetValue);
|
|
822
|
+
}
|
|
823
|
+
getLeverageComponents(includeOpenOrders = true, marginCategory = undefined, perpMarketIndex) {
|
|
824
|
+
var _a;
|
|
825
|
+
if (perpMarketIndex) {
|
|
826
|
+
const perpPosition = this.getPerpPositionOrEmpty(perpMarketIndex);
|
|
827
|
+
const perpLiability = this.calculateWeightedPerpPositionLiability(perpPosition, marginCategory, undefined, includeOpenOrders);
|
|
828
|
+
const perpMarket = this.driftClient.getPerpMarketAccount(perpPosition.marketIndex);
|
|
829
|
+
const oraclePriceData = this.getOracleDataForPerpMarket(perpPosition.marketIndex);
|
|
830
|
+
const quoteSpotMarket = this.driftClient.getSpotMarketAccount(perpMarket.quoteSpotMarketIndex);
|
|
831
|
+
const quoteOraclePriceData = this.getOracleDataForSpotMarket(perpMarket.quoteSpotMarketIndex);
|
|
832
|
+
const strictOracle = new strictOraclePrice_1.StrictOraclePrice(quoteOraclePriceData.price, quoteOraclePriceData.twap);
|
|
833
|
+
const positionUnrealizedPnl = (0, position_2.calculatePositionPNL)(perpMarket, perpPosition, true, oraclePriceData);
|
|
834
|
+
const tokenAmount = (0, spotBalance_2.getTokenAmount)((_a = perpPosition.isolatedPositionScaledBalance) !== null && _a !== void 0 ? _a : numericConstants_1.ZERO, quoteSpotMarket, types_2.SpotBalanceType.DEPOSIT);
|
|
835
|
+
const spotAssetValue = (0, spotBalance_1.getStrictTokenValue)(tokenAmount, quoteSpotMarket.decimals, strictOracle);
|
|
836
|
+
return {
|
|
837
|
+
perpLiabilityValue: perpLiability,
|
|
838
|
+
perpPnl: positionUnrealizedPnl,
|
|
839
|
+
spotAssetValue,
|
|
840
|
+
spotLiabilityValue: numericConstants_1.ZERO,
|
|
841
|
+
};
|
|
842
|
+
}
|
|
843
|
+
const perpLiability = this.getTotalPerpPositionLiability(marginCategory, undefined, includeOpenOrders);
|
|
844
|
+
const perpPnl = this.getUnrealizedPNL(true, undefined, marginCategory);
|
|
845
|
+
const { totalAssetValue: spotAssetValue, totalLiabilityValue: spotLiabilityValue, } = this.getSpotMarketAssetAndLiabilityValue(undefined, marginCategory, undefined, includeOpenOrders);
|
|
846
|
+
const isolatedDeposits = marginCategory === undefined
|
|
847
|
+
? this.getTotalIsolatedPositionDeposits()
|
|
848
|
+
: numericConstants_1.ZERO;
|
|
849
|
+
return {
|
|
850
|
+
perpLiabilityValue: perpLiability,
|
|
851
|
+
perpPnl,
|
|
852
|
+
spotAssetValue: spotAssetValue.add(isolatedDeposits),
|
|
853
|
+
spotLiabilityValue,
|
|
854
|
+
};
|
|
855
|
+
}
|
|
856
|
+
isDustDepositPosition(spotMarketAccount) {
|
|
857
|
+
const marketIndex = spotMarketAccount.marketIndex;
|
|
858
|
+
const spotPosition = this.getSpotPosition(spotMarketAccount.marketIndex);
|
|
859
|
+
if ((0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
|
|
860
|
+
return false;
|
|
861
|
+
}
|
|
862
|
+
const depositAmount = this.getTokenAmount(spotMarketAccount.marketIndex);
|
|
863
|
+
if (depositAmount.lte(numericConstants_1.ZERO)) {
|
|
864
|
+
return false;
|
|
865
|
+
}
|
|
866
|
+
const oraclePriceData = this.getOracleDataForSpotMarket(marketIndex);
|
|
867
|
+
const strictOraclePrice = new strictOraclePrice_1.StrictOraclePrice(oraclePriceData.price, oraclePriceData.twap);
|
|
868
|
+
const balanceValue = this.getSpotAssetValue(depositAmount, strictOraclePrice, spotMarketAccount);
|
|
869
|
+
if (balanceValue.lt(numericConstants_1.DUST_POSITION_SIZE)) {
|
|
870
|
+
return true;
|
|
871
|
+
}
|
|
872
|
+
return false;
|
|
873
|
+
}
|
|
874
|
+
getSpotMarketAccountsWithDustPosition() {
|
|
875
|
+
const spotMarketAccounts = this.driftClient.getSpotMarketAccounts();
|
|
876
|
+
const dustPositionAccounts = [];
|
|
877
|
+
for (const spotMarketAccount of spotMarketAccounts) {
|
|
878
|
+
const isDust = this.isDustDepositPosition(spotMarketAccount);
|
|
879
|
+
if (isDust) {
|
|
880
|
+
dustPositionAccounts.push(spotMarketAccount);
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
return dustPositionAccounts;
|
|
884
|
+
}
|
|
885
|
+
getTotalLiabilityValue(marginCategory) {
|
|
886
|
+
return this.getTotalPerpPositionLiability(marginCategory, undefined, true).add(this.getSpotMarketLiabilityValue(undefined, marginCategory, undefined, true));
|
|
887
|
+
}
|
|
888
|
+
getTotalAssetValue(marginCategory) {
|
|
889
|
+
const value = this.getSpotMarketAssetValue(undefined, marginCategory, true).add(this.getUnrealizedPNL(true, undefined, marginCategory));
|
|
890
|
+
if (marginCategory === undefined) {
|
|
891
|
+
return value.add(this.getTotalIsolatedPositionDeposits());
|
|
892
|
+
}
|
|
893
|
+
return value;
|
|
894
|
+
}
|
|
895
|
+
getNetUsdValue() {
|
|
896
|
+
const netSpotValue = this.getNetSpotMarketValue();
|
|
897
|
+
const unrealizedPnl = this.getUnrealizedPNL(true, undefined, undefined);
|
|
898
|
+
const isolatedDeposits = this.getTotalIsolatedPositionDeposits();
|
|
899
|
+
return netSpotValue.add(unrealizedPnl).add(isolatedDeposits);
|
|
900
|
+
}
|
|
901
|
+
/**
|
|
902
|
+
* Calculates the all time P&L of the user.
|
|
903
|
+
*
|
|
904
|
+
* Net withdraws + Net spot market value + Net unrealized P&L -
|
|
905
|
+
*/
|
|
906
|
+
getTotalAllTimePnl() {
|
|
907
|
+
const netUsdValue = this.getNetUsdValue();
|
|
908
|
+
const totalDeposits = this.getUserAccount().totalDeposits;
|
|
909
|
+
const totalWithdraws = this.getUserAccount().totalWithdraws;
|
|
910
|
+
const totalPnl = netUsdValue.add(totalWithdraws).sub(totalDeposits);
|
|
911
|
+
return totalPnl;
|
|
912
|
+
}
|
|
913
|
+
/**
|
|
914
|
+
* calculates max allowable leverage exceeding hitting requirement category
|
|
915
|
+
* for large sizes where imf factor activates, result is a lower bound
|
|
916
|
+
* @param marginCategory {Initial, Maintenance}
|
|
917
|
+
* @returns : Precision TEN_THOUSAND
|
|
918
|
+
*/
|
|
919
|
+
getMaxLeverageForPerp(perpMarketIndex, _marginCategory = 'Initial') {
|
|
920
|
+
const { perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue } = this.getLeverageComponents();
|
|
921
|
+
const totalAssetValue = spotAssetValue.add(perpPnl);
|
|
922
|
+
const netAssetValue = totalAssetValue.sub(spotLiabilityValue);
|
|
923
|
+
if (netAssetValue.eq(numericConstants_1.ZERO)) {
|
|
924
|
+
return numericConstants_1.ZERO;
|
|
925
|
+
}
|
|
926
|
+
const totalLiabilityValue = perpLiabilityValue.add(spotLiabilityValue);
|
|
927
|
+
// absolute max fesible size (upper bound)
|
|
928
|
+
const maxSizeQuote = anchor_1.BN.max(anchor_1.BN.min(this.getMaxTradeSizeUSDCForPerp(perpMarketIndex, types_2.PositionDirection.LONG)
|
|
929
|
+
.tradeSize, this.getMaxTradeSizeUSDCForPerp(perpMarketIndex, types_2.PositionDirection.SHORT).tradeSize), numericConstants_1.ZERO);
|
|
930
|
+
return totalLiabilityValue
|
|
931
|
+
.add(maxSizeQuote)
|
|
932
|
+
.mul(numericConstants_1.TEN_THOUSAND)
|
|
933
|
+
.div(netAssetValue);
|
|
934
|
+
}
|
|
935
|
+
/**
|
|
936
|
+
* calculates max allowable leverage exceeding hitting requirement category
|
|
937
|
+
* @param spotMarketIndex
|
|
938
|
+
* @param direction
|
|
939
|
+
* @returns : Precision TEN_THOUSAND
|
|
940
|
+
*/
|
|
941
|
+
getMaxLeverageForSpot(spotMarketIndex, direction) {
|
|
942
|
+
const { perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue } = this.getLeverageComponents();
|
|
943
|
+
const totalLiabilityValue = perpLiabilityValue.add(spotLiabilityValue);
|
|
944
|
+
const totalAssetValue = spotAssetValue.add(perpPnl);
|
|
945
|
+
const netAssetValue = totalAssetValue.sub(spotLiabilityValue);
|
|
946
|
+
if (netAssetValue.eq(numericConstants_1.ZERO)) {
|
|
947
|
+
return numericConstants_1.ZERO;
|
|
948
|
+
}
|
|
949
|
+
const currentQuoteAssetValue = this.getSpotMarketAssetValue(numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
|
|
950
|
+
const currentQuoteLiabilityValue = this.getSpotMarketLiabilityValue(numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
|
|
951
|
+
const currentQuoteValue = currentQuoteAssetValue.sub(currentQuoteLiabilityValue);
|
|
952
|
+
const currentSpotMarketAssetValue = this.getSpotMarketAssetValue(spotMarketIndex);
|
|
953
|
+
const currentSpotMarketLiabilityValue = this.getSpotMarketLiabilityValue(spotMarketIndex);
|
|
954
|
+
const currentSpotMarketNetValue = currentSpotMarketAssetValue.sub(currentSpotMarketLiabilityValue);
|
|
955
|
+
const tradeQuoteAmount = this.getMaxTradeSizeUSDCForSpot(spotMarketIndex, direction, currentQuoteAssetValue, currentSpotMarketNetValue);
|
|
956
|
+
let assetValueToAdd = numericConstants_1.ZERO;
|
|
957
|
+
let liabilityValueToAdd = numericConstants_1.ZERO;
|
|
958
|
+
const newQuoteNetValue = (0, types_1.isVariant)(direction, 'short')
|
|
959
|
+
? currentQuoteValue.add(tradeQuoteAmount)
|
|
960
|
+
: currentQuoteValue.sub(tradeQuoteAmount);
|
|
961
|
+
const newQuoteAssetValue = anchor_1.BN.max(newQuoteNetValue, numericConstants_1.ZERO);
|
|
962
|
+
const newQuoteLiabilityValue = anchor_1.BN.min(newQuoteNetValue, numericConstants_1.ZERO).abs();
|
|
963
|
+
assetValueToAdd = assetValueToAdd.add(newQuoteAssetValue.sub(currentQuoteAssetValue));
|
|
964
|
+
liabilityValueToAdd = liabilityValueToAdd.add(newQuoteLiabilityValue.sub(currentQuoteLiabilityValue));
|
|
965
|
+
const newSpotMarketNetValue = (0, types_1.isVariant)(direction, 'long')
|
|
966
|
+
? currentSpotMarketNetValue.add(tradeQuoteAmount)
|
|
967
|
+
: currentSpotMarketNetValue.sub(tradeQuoteAmount);
|
|
968
|
+
const newSpotMarketAssetValue = anchor_1.BN.max(newSpotMarketNetValue, numericConstants_1.ZERO);
|
|
969
|
+
const newSpotMarketLiabilityValue = anchor_1.BN.min(newSpotMarketNetValue, numericConstants_1.ZERO).abs();
|
|
970
|
+
assetValueToAdd = assetValueToAdd.add(newSpotMarketAssetValue.sub(currentSpotMarketAssetValue));
|
|
971
|
+
liabilityValueToAdd = liabilityValueToAdd.add(newSpotMarketLiabilityValue.sub(currentSpotMarketLiabilityValue));
|
|
972
|
+
const finalTotalAssetValue = totalAssetValue.add(assetValueToAdd);
|
|
973
|
+
const finalTotalSpotLiability = spotLiabilityValue.add(liabilityValueToAdd);
|
|
974
|
+
const finalTotalLiabilityValue = totalLiabilityValue.add(liabilityValueToAdd);
|
|
975
|
+
const finalNetAssetValue = finalTotalAssetValue.sub(finalTotalSpotLiability);
|
|
976
|
+
return finalTotalLiabilityValue.mul(numericConstants_1.TEN_THOUSAND).div(finalNetAssetValue);
|
|
977
|
+
}
|
|
978
|
+
/**
|
|
979
|
+
* calculates margin ratio: 1 / leverage
|
|
980
|
+
* @returns : Precision TEN_THOUSAND
|
|
981
|
+
*/
|
|
982
|
+
getMarginRatio() {
|
|
983
|
+
const { perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue } = this.getLeverageComponents();
|
|
984
|
+
const totalLiabilityValue = perpLiabilityValue.add(spotLiabilityValue);
|
|
985
|
+
const totalAssetValue = spotAssetValue.add(perpPnl);
|
|
986
|
+
if (totalLiabilityValue.eq(numericConstants_1.ZERO)) {
|
|
987
|
+
return numericConstants_1.BN_MAX;
|
|
988
|
+
}
|
|
989
|
+
const netAssetValue = totalAssetValue.sub(spotLiabilityValue);
|
|
990
|
+
return netAssetValue.mul(numericConstants_1.TEN_THOUSAND).div(totalLiabilityValue);
|
|
991
|
+
}
|
|
992
|
+
canBeLiquidated() {
|
|
993
|
+
// Deprecated signature retained for backward compatibility in type only
|
|
994
|
+
// but implementation now delegates to the new Map-based API and returns cross margin status.
|
|
995
|
+
const map = this.getLiquidationStatuses();
|
|
996
|
+
const cross = map.get('cross');
|
|
997
|
+
const isolatedPositions = new Map(Array.from(map.entries())
|
|
998
|
+
.filter((e) => e[0] !== 'cross')
|
|
999
|
+
.map(([key, value]) => [key, value]));
|
|
1000
|
+
return cross
|
|
1001
|
+
? { ...cross, isolatedPositions }
|
|
1002
|
+
: {
|
|
1003
|
+
canBeLiquidated: false,
|
|
1004
|
+
marginRequirement: numericConstants_1.ZERO,
|
|
1005
|
+
totalCollateral: numericConstants_1.ZERO,
|
|
1006
|
+
isolatedPositions,
|
|
1007
|
+
};
|
|
1008
|
+
}
|
|
1009
|
+
/**
|
|
1010
|
+
* New API: Returns liquidation status for cross and each isolated perp position.
|
|
1011
|
+
* Map keys:
|
|
1012
|
+
* - 'cross' for cross margin
|
|
1013
|
+
* - marketIndex (number) for each isolated perp position
|
|
1014
|
+
*/
|
|
1015
|
+
getLiquidationStatuses(marginCalc) {
|
|
1016
|
+
// If not provided, use buffer-aware calc for canBeLiquidated checks
|
|
1017
|
+
if (!marginCalc) {
|
|
1018
|
+
const liquidationBufferMap = this.getLiquidationBuffer();
|
|
1019
|
+
marginCalc = this.getMarginCalculation('Maintenance', {
|
|
1020
|
+
liquidationBufferMap,
|
|
1021
|
+
});
|
|
1022
|
+
}
|
|
1023
|
+
const result = new Map();
|
|
1024
|
+
// Cross margin status
|
|
1025
|
+
const crossTotalCollateral = marginCalc.totalCollateral;
|
|
1026
|
+
const crossMarginRequirement = marginCalc.marginRequirement;
|
|
1027
|
+
result.set('cross', {
|
|
1028
|
+
canBeLiquidated: crossTotalCollateral.lt(crossMarginRequirement),
|
|
1029
|
+
marginRequirement: crossMarginRequirement,
|
|
1030
|
+
totalCollateral: crossTotalCollateral,
|
|
1031
|
+
});
|
|
1032
|
+
// Isolated positions status
|
|
1033
|
+
for (const [marketIndex, isoCalc,] of marginCalc.isolatedMarginCalculations) {
|
|
1034
|
+
const isoTotalCollateral = isoCalc.totalCollateral;
|
|
1035
|
+
const isoMarginRequirement = isoCalc.marginRequirement;
|
|
1036
|
+
result.set(marketIndex, {
|
|
1037
|
+
canBeLiquidated: isoTotalCollateral.lt(isoMarginRequirement),
|
|
1038
|
+
marginRequirement: isoMarginRequirement,
|
|
1039
|
+
totalCollateral: isoTotalCollateral,
|
|
1040
|
+
});
|
|
1041
|
+
}
|
|
1042
|
+
return result;
|
|
1043
|
+
}
|
|
1044
|
+
isBeingLiquidated() {
|
|
1045
|
+
return (this.isCrossMarginBeingLiquidated() ||
|
|
1046
|
+
this.hasIsolatedPositionBeingLiquidated());
|
|
1047
|
+
}
|
|
1048
|
+
isCrossMarginBeingLiquidated() {
|
|
1049
|
+
return ((this.getUserAccount().status &
|
|
1050
|
+
(types_1.UserStatus.BEING_LIQUIDATED | types_1.UserStatus.BANKRUPT)) >
|
|
1051
|
+
0);
|
|
1052
|
+
}
|
|
1053
|
+
/** Returns true if cross margin is currently below maintenance requirement (no buffer). */
|
|
1054
|
+
canCrossMarginBeLiquidated(marginCalc) {
|
|
1055
|
+
const calc = marginCalc !== null && marginCalc !== void 0 ? marginCalc : this.getMarginCalculation('Maintenance');
|
|
1056
|
+
return calc.totalCollateral.lt(calc.marginRequirement);
|
|
1057
|
+
}
|
|
1058
|
+
hasIsolatedPositionBeingLiquidated() {
|
|
1059
|
+
return this.getActivePerpPositions().some((position) => (position.positionFlag &
|
|
1060
|
+
(types_2.PositionFlag.BeingLiquidated | types_2.PositionFlag.Bankruptcy)) >
|
|
1061
|
+
0);
|
|
1062
|
+
}
|
|
1063
|
+
isIsolatedPositionBeingLiquidated(perpMarketIndex) {
|
|
1064
|
+
const position = this.getActivePerpPositions().find((position) => position.marketIndex === perpMarketIndex);
|
|
1065
|
+
return (((position === null || position === void 0 ? void 0 : position.positionFlag) &
|
|
1066
|
+
(types_2.PositionFlag.BeingLiquidated | types_2.PositionFlag.Bankruptcy)) >
|
|
1067
|
+
0);
|
|
1068
|
+
}
|
|
1069
|
+
/** Returns true if any isolated perp position is currently below its maintenance requirement (no buffer). */
|
|
1070
|
+
getLiquidatableIsolatedPositions(marginCalc) {
|
|
1071
|
+
const liquidatableIsolatedPositions = [];
|
|
1072
|
+
const calc = marginCalc !== null && marginCalc !== void 0 ? marginCalc : this.getMarginCalculation('Maintenance');
|
|
1073
|
+
for (const [marketIndex, isoCalc] of calc.isolatedMarginCalculations) {
|
|
1074
|
+
if (this.canIsolatedPositionMarginBeLiquidated(isoCalc)) {
|
|
1075
|
+
liquidatableIsolatedPositions.push(marketIndex);
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
return liquidatableIsolatedPositions;
|
|
1079
|
+
}
|
|
1080
|
+
canIsolatedPositionMarginBeLiquidated(isolatedMarginCalculation) {
|
|
1081
|
+
return isolatedMarginCalculation.totalCollateral.lt(isolatedMarginCalculation.marginRequirement);
|
|
1082
|
+
}
|
|
1083
|
+
hasStatus(status) {
|
|
1084
|
+
return (this.getUserAccount().status & status) > 0;
|
|
1085
|
+
}
|
|
1086
|
+
isBankrupt() {
|
|
1087
|
+
return (this.getUserAccount().status & types_1.UserStatus.BANKRUPT) > 0;
|
|
1088
|
+
}
|
|
1089
|
+
/**
|
|
1090
|
+
* Checks if any user position cumulative funding differs from respective market cumulative funding
|
|
1091
|
+
* @returns
|
|
1092
|
+
*/
|
|
1093
|
+
needsToSettleFundingPayment() {
|
|
1094
|
+
for (const userPosition of this.getUserAccount().perpPositions) {
|
|
1095
|
+
if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
1096
|
+
continue;
|
|
1097
|
+
}
|
|
1098
|
+
const market = this.driftClient.getPerpMarketAccount(userPosition.marketIndex);
|
|
1099
|
+
if (market.amm.cumulativeFundingRateLong.eq(userPosition.lastCumulativeFundingRate) ||
|
|
1100
|
+
market.amm.cumulativeFundingRateShort.eq(userPosition.lastCumulativeFundingRate)) {
|
|
1101
|
+
continue;
|
|
1102
|
+
}
|
|
1103
|
+
return true;
|
|
1104
|
+
}
|
|
1105
|
+
return false;
|
|
1106
|
+
}
|
|
1107
|
+
/**
|
|
1108
|
+
* Calculate the liquidation price of a spot position
|
|
1109
|
+
* @param marketIndex
|
|
1110
|
+
* @returns Precision : PRICE_PRECISION
|
|
1111
|
+
*/
|
|
1112
|
+
spotLiquidationPrice(marketIndex, positionBaseSizeChange = numericConstants_1.ZERO) {
|
|
1113
|
+
const currentSpotPosition = this.getSpotPosition(marketIndex);
|
|
1114
|
+
if (!currentSpotPosition) {
|
|
1115
|
+
return new anchor_1.BN(-1);
|
|
1116
|
+
}
|
|
1117
|
+
const totalCollateral = this.getTotalCollateral('Maintenance');
|
|
1118
|
+
const maintenanceMarginRequirement = this.getMaintenanceMarginRequirement();
|
|
1119
|
+
const freeCollateral = anchor_1.BN.max(numericConstants_1.ZERO, totalCollateral.sub(maintenanceMarginRequirement));
|
|
1120
|
+
const market = this.driftClient.getSpotMarketAccount(marketIndex);
|
|
1121
|
+
let signedTokenAmount = (0, spotBalance_1.getSignedTokenAmount)((0, spotBalance_2.getTokenAmount)(currentSpotPosition.scaledBalance, market, currentSpotPosition.balanceType), currentSpotPosition.balanceType);
|
|
1122
|
+
signedTokenAmount = signedTokenAmount.add(positionBaseSizeChange);
|
|
1123
|
+
if (signedTokenAmount.eq(numericConstants_1.ZERO)) {
|
|
1124
|
+
return new anchor_1.BN(-1);
|
|
1125
|
+
}
|
|
1126
|
+
let freeCollateralDelta = this.calculateFreeCollateralDeltaForSpot(market, signedTokenAmount);
|
|
1127
|
+
const oracle = market.oracle;
|
|
1128
|
+
const perpMarketWithSameOracle = this.driftClient
|
|
1129
|
+
.getPerpMarketAccounts()
|
|
1130
|
+
.find((market) => market.amm.oracle.equals(oracle));
|
|
1131
|
+
const oraclePrice = this.driftClient.getOracleDataForSpotMarket(marketIndex).price;
|
|
1132
|
+
if (perpMarketWithSameOracle) {
|
|
1133
|
+
const perpPosition = this.getPerpPositionOrEmpty(perpMarketWithSameOracle.marketIndex);
|
|
1134
|
+
if (perpPosition) {
|
|
1135
|
+
let freeCollateralDeltaForPerp = this.calculateFreeCollateralDeltaForPerp(perpMarketWithSameOracle, perpPosition, numericConstants_1.ZERO, oraclePrice);
|
|
1136
|
+
if (freeCollateralDeltaForPerp) {
|
|
1137
|
+
const { numerator, denominator } = (0, oracles_1.getMultipleBetweenOracleSources)(market.oracleSource, perpMarketWithSameOracle.amm.oracleSource);
|
|
1138
|
+
freeCollateralDeltaForPerp = freeCollateralDeltaForPerp
|
|
1139
|
+
.mul(numerator)
|
|
1140
|
+
.div(denominator);
|
|
1141
|
+
}
|
|
1142
|
+
freeCollateralDelta = freeCollateralDelta.add(freeCollateralDeltaForPerp || numericConstants_1.ZERO);
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
if (freeCollateralDelta.eq(numericConstants_1.ZERO)) {
|
|
1146
|
+
return new anchor_1.BN(-1);
|
|
1147
|
+
}
|
|
1148
|
+
const liqPriceDelta = freeCollateral
|
|
1149
|
+
.mul(numericConstants_1.QUOTE_PRECISION)
|
|
1150
|
+
.div(freeCollateralDelta);
|
|
1151
|
+
const liqPrice = oraclePrice.sub(liqPriceDelta);
|
|
1152
|
+
if (liqPrice.lt(numericConstants_1.ZERO)) {
|
|
1153
|
+
return new anchor_1.BN(-1);
|
|
1154
|
+
}
|
|
1155
|
+
return liqPrice;
|
|
1156
|
+
}
|
|
1157
|
+
/**
|
|
1158
|
+
* Calculate the liquidation price of a perp position, with optional parameter to calculate the liquidation price after a trade
|
|
1159
|
+
* @param marketIndex
|
|
1160
|
+
* @param positionBaseSizeChange // change in position size to calculate liquidation price for : Precision 10^9
|
|
1161
|
+
* @param estimatedEntryPrice
|
|
1162
|
+
* @param marginCategory // allow Initial to be passed in if we are trying to calculate price for DLP de-risking
|
|
1163
|
+
* @param includeOpenOrders
|
|
1164
|
+
* @param offsetCollateral // allows calculating the liquidation price after this offset collateral is added to the user's account (e.g. : what will the liquidation price be for this position AFTER I deposit $x worth of collateral)
|
|
1165
|
+
* @returns Precision : PRICE_PRECISION
|
|
1166
|
+
*/
|
|
1167
|
+
liquidationPrice(marketIndex, positionBaseSizeChange = numericConstants_1.ZERO, estimatedEntryPrice = numericConstants_1.ZERO, marginCategory = 'Maintenance', includeOpenOrders = false, offsetCollateral = numericConstants_1.ZERO, marginType) {
|
|
1168
|
+
const market = this.driftClient.getPerpMarketAccount(marketIndex);
|
|
1169
|
+
const oracle = this.driftClient.getPerpMarketAccount(marketIndex).amm.oracle;
|
|
1170
|
+
const oraclePrice = this.driftClient.getOracleDataForPerpMarket(marketIndex).price;
|
|
1171
|
+
const currentPerpPosition = this.getPerpPositionOrEmpty(marketIndex);
|
|
1172
|
+
if (marginType === 'Isolated') {
|
|
1173
|
+
const marginCalculation = this.getMarginCalculation(marginCategory, {
|
|
1174
|
+
strict: false,
|
|
1175
|
+
includeOpenOrders,
|
|
1176
|
+
});
|
|
1177
|
+
const isolatedMarginCalculation = marginCalculation.isolatedMarginCalculations.get(marketIndex);
|
|
1178
|
+
if (!isolatedMarginCalculation)
|
|
1179
|
+
return new anchor_1.BN(-1);
|
|
1180
|
+
const { totalCollateral, marginRequirement } = isolatedMarginCalculation;
|
|
1181
|
+
const freeCollateral = anchor_1.BN.max(numericConstants_1.ZERO, totalCollateral.sub(marginRequirement)).add(offsetCollateral);
|
|
1182
|
+
const freeCollateralDelta = this.calculateFreeCollateralDeltaForPerp(market, currentPerpPosition, positionBaseSizeChange, oraclePrice, marginCategory, includeOpenOrders);
|
|
1183
|
+
if (!freeCollateralDelta || freeCollateralDelta.eq(numericConstants_1.ZERO)) {
|
|
1184
|
+
return new anchor_1.BN(-1);
|
|
1185
|
+
}
|
|
1186
|
+
const liqPriceDelta = freeCollateral
|
|
1187
|
+
.mul(numericConstants_1.QUOTE_PRECISION)
|
|
1188
|
+
.div(freeCollateralDelta);
|
|
1189
|
+
const liqPrice = oraclePrice.sub(liqPriceDelta);
|
|
1190
|
+
if (liqPrice.lt(numericConstants_1.ZERO)) {
|
|
1191
|
+
return new anchor_1.BN(-1);
|
|
1192
|
+
}
|
|
1193
|
+
return liqPrice;
|
|
1194
|
+
}
|
|
1195
|
+
const totalCollateral = this.getTotalCollateral(marginCategory, false, includeOpenOrders);
|
|
1196
|
+
const marginRequirement = this.getMarginRequirement(marginCategory, undefined, false, includeOpenOrders);
|
|
1197
|
+
let freeCollateral = anchor_1.BN.max(numericConstants_1.ZERO, totalCollateral.sub(marginRequirement)).add(offsetCollateral);
|
|
1198
|
+
positionBaseSizeChange = (0, orders_1.standardizeBaseAssetAmount)(positionBaseSizeChange, market.amm.orderStepSize);
|
|
1199
|
+
const freeCollateralChangeFromNewPosition = this.calculateEntriesEffectOnFreeCollateral(market, oraclePrice, currentPerpPosition, positionBaseSizeChange, estimatedEntryPrice, includeOpenOrders);
|
|
1200
|
+
freeCollateral = freeCollateral.add(freeCollateralChangeFromNewPosition);
|
|
1201
|
+
let freeCollateralDelta = this.calculateFreeCollateralDeltaForPerp(market, currentPerpPosition, positionBaseSizeChange, oraclePrice, marginCategory, includeOpenOrders);
|
|
1202
|
+
if (!freeCollateralDelta) {
|
|
1203
|
+
return new anchor_1.BN(-1);
|
|
1204
|
+
}
|
|
1205
|
+
const spotMarketWithSameOracle = this.driftClient
|
|
1206
|
+
.getSpotMarketAccounts()
|
|
1207
|
+
.find((market) => market.oracle.equals(oracle));
|
|
1208
|
+
if (spotMarketWithSameOracle) {
|
|
1209
|
+
const spotPosition = this.getSpotPosition(spotMarketWithSameOracle.marketIndex);
|
|
1210
|
+
if (spotPosition) {
|
|
1211
|
+
const signedTokenAmount = (0, spotBalance_1.getSignedTokenAmount)((0, spotBalance_2.getTokenAmount)(spotPosition.scaledBalance, spotMarketWithSameOracle, spotPosition.balanceType), spotPosition.balanceType);
|
|
1212
|
+
let spotFreeCollateralDelta = this.calculateFreeCollateralDeltaForSpot(spotMarketWithSameOracle, signedTokenAmount, marginCategory);
|
|
1213
|
+
if (spotFreeCollateralDelta) {
|
|
1214
|
+
const { numerator, denominator } = (0, oracles_1.getMultipleBetweenOracleSources)(market.amm.oracleSource, spotMarketWithSameOracle.oracleSource);
|
|
1215
|
+
spotFreeCollateralDelta = spotFreeCollateralDelta
|
|
1216
|
+
.mul(numerator)
|
|
1217
|
+
.div(denominator);
|
|
1218
|
+
}
|
|
1219
|
+
freeCollateralDelta = freeCollateralDelta.add(spotFreeCollateralDelta || numericConstants_1.ZERO);
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
if (freeCollateralDelta.eq(numericConstants_1.ZERO)) {
|
|
1223
|
+
return new anchor_1.BN(-1);
|
|
1224
|
+
}
|
|
1225
|
+
const liqPriceDelta = freeCollateral
|
|
1226
|
+
.mul(numericConstants_1.QUOTE_PRECISION)
|
|
1227
|
+
.div(freeCollateralDelta);
|
|
1228
|
+
const liqPrice = oraclePrice.sub(liqPriceDelta);
|
|
1229
|
+
if (liqPrice.lt(numericConstants_1.ZERO)) {
|
|
1230
|
+
return new anchor_1.BN(-1);
|
|
1231
|
+
}
|
|
1232
|
+
return liqPrice;
|
|
1233
|
+
}
|
|
1234
|
+
calculateEntriesEffectOnFreeCollateral(market, oraclePrice, perpPosition, positionBaseSizeChange, estimatedEntryPrice, includeOpenOrders, marginCategory = 'Maintenance') {
|
|
1235
|
+
let freeCollateralChange = numericConstants_1.ZERO;
|
|
1236
|
+
// update free collateral to account for change in pnl from new position
|
|
1237
|
+
if (!estimatedEntryPrice.eq(numericConstants_1.ZERO) &&
|
|
1238
|
+
!positionBaseSizeChange.eq(numericConstants_1.ZERO) &&
|
|
1239
|
+
marginCategory === 'Maintenance') {
|
|
1240
|
+
const costBasis = oraclePrice
|
|
1241
|
+
.mul(positionBaseSizeChange.abs())
|
|
1242
|
+
.div(numericConstants_1.BASE_PRECISION);
|
|
1243
|
+
const newPositionValue = estimatedEntryPrice
|
|
1244
|
+
.mul(positionBaseSizeChange.abs())
|
|
1245
|
+
.div(numericConstants_1.BASE_PRECISION);
|
|
1246
|
+
if (positionBaseSizeChange.gt(numericConstants_1.ZERO)) {
|
|
1247
|
+
freeCollateralChange = costBasis.sub(newPositionValue);
|
|
1248
|
+
}
|
|
1249
|
+
else {
|
|
1250
|
+
freeCollateralChange = newPositionValue.sub(costBasis);
|
|
1251
|
+
}
|
|
1252
|
+
// assume worst fee tier
|
|
1253
|
+
const takerFeeTier = this.driftClient.getStateAccount().perpFeeStructure.feeTiers[0];
|
|
1254
|
+
const takerFee = newPositionValue
|
|
1255
|
+
.muln(takerFeeTier.feeNumerator)
|
|
1256
|
+
.divn(takerFeeTier.feeDenominator);
|
|
1257
|
+
freeCollateralChange = freeCollateralChange.sub(takerFee);
|
|
1258
|
+
}
|
|
1259
|
+
const calculateMarginRequirement = (perpPosition) => {
|
|
1260
|
+
let baseAssetAmount;
|
|
1261
|
+
let liabilityValue;
|
|
1262
|
+
if (includeOpenOrders) {
|
|
1263
|
+
const { worstCaseBaseAssetAmount, worstCaseLiabilityValue } = (0, margin_1.calculateWorstCasePerpLiabilityValue)(perpPosition, market, oraclePrice);
|
|
1264
|
+
baseAssetAmount = worstCaseBaseAssetAmount;
|
|
1265
|
+
liabilityValue = worstCaseLiabilityValue;
|
|
1266
|
+
}
|
|
1267
|
+
else {
|
|
1268
|
+
baseAssetAmount = perpPosition.baseAssetAmount;
|
|
1269
|
+
liabilityValue = (0, margin_1.calculatePerpLiabilityValue)(baseAssetAmount, oraclePrice);
|
|
1270
|
+
}
|
|
1271
|
+
const userCustomMargin = Math.max(perpPosition.maxMarginRatio, this.getUserAccount().maxMarginRatio);
|
|
1272
|
+
const marginRatio = (0, market_1.calculateMarketMarginRatio)(market, baseAssetAmount.abs(), marginCategory, userCustomMargin);
|
|
1273
|
+
return liabilityValue.mul(new anchor_1.BN(marginRatio)).div(numericConstants_1.MARGIN_PRECISION);
|
|
1274
|
+
};
|
|
1275
|
+
const freeCollateralConsumptionBefore = calculateMarginRequirement(perpPosition);
|
|
1276
|
+
const perpPositionAfter = Object.assign({}, perpPosition);
|
|
1277
|
+
perpPositionAfter.baseAssetAmount = perpPositionAfter.baseAssetAmount.add(positionBaseSizeChange);
|
|
1278
|
+
const freeCollateralConsumptionAfter = calculateMarginRequirement(perpPositionAfter);
|
|
1279
|
+
return freeCollateralChange.sub(freeCollateralConsumptionAfter.sub(freeCollateralConsumptionBefore));
|
|
1280
|
+
}
|
|
1281
|
+
calculateFreeCollateralDeltaForPerp(market, perpPosition, positionBaseSizeChange, oraclePrice, marginCategory = 'Maintenance', includeOpenOrders = false) {
|
|
1282
|
+
const baseAssetAmount = includeOpenOrders
|
|
1283
|
+
? (0, margin_2.calculateWorstCaseBaseAssetAmount)(perpPosition, market, oraclePrice)
|
|
1284
|
+
: perpPosition.baseAssetAmount;
|
|
1285
|
+
// zero if include orders == false
|
|
1286
|
+
const orderBaseAssetAmount = baseAssetAmount.sub(perpPosition.baseAssetAmount);
|
|
1287
|
+
const proposedBaseAssetAmount = baseAssetAmount.add(positionBaseSizeChange);
|
|
1288
|
+
const userCustomMargin = Math.max(perpPosition.maxMarginRatio, this.getUserAccount().maxMarginRatio);
|
|
1289
|
+
const marginRatio = (0, market_1.calculateMarketMarginRatio)(market, proposedBaseAssetAmount.abs(), marginCategory, userCustomMargin);
|
|
1290
|
+
const marginRatioQuotePrecision = new anchor_1.BN(marginRatio)
|
|
1291
|
+
.mul(numericConstants_1.QUOTE_PRECISION)
|
|
1292
|
+
.div(numericConstants_1.MARGIN_PRECISION);
|
|
1293
|
+
if (proposedBaseAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
1294
|
+
return undefined;
|
|
1295
|
+
}
|
|
1296
|
+
let freeCollateralDelta = numericConstants_1.ZERO;
|
|
1297
|
+
if (proposedBaseAssetAmount.gt(numericConstants_1.ZERO)) {
|
|
1298
|
+
freeCollateralDelta = numericConstants_1.QUOTE_PRECISION.sub(marginRatioQuotePrecision)
|
|
1299
|
+
.mul(proposedBaseAssetAmount)
|
|
1300
|
+
.div(numericConstants_1.BASE_PRECISION);
|
|
1301
|
+
}
|
|
1302
|
+
else {
|
|
1303
|
+
freeCollateralDelta = numericConstants_1.QUOTE_PRECISION.neg()
|
|
1304
|
+
.sub(marginRatioQuotePrecision)
|
|
1305
|
+
.mul(proposedBaseAssetAmount.abs())
|
|
1306
|
+
.div(numericConstants_1.BASE_PRECISION);
|
|
1307
|
+
}
|
|
1308
|
+
if (!orderBaseAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
1309
|
+
freeCollateralDelta = freeCollateralDelta.sub(marginRatioQuotePrecision
|
|
1310
|
+
.mul(orderBaseAssetAmount.abs())
|
|
1311
|
+
.div(numericConstants_1.BASE_PRECISION));
|
|
1312
|
+
}
|
|
1313
|
+
return freeCollateralDelta;
|
|
1314
|
+
}
|
|
1315
|
+
calculateFreeCollateralDeltaForSpot(market, signedTokenAmount, marginCategory = 'Maintenance') {
|
|
1316
|
+
const tokenPrecision = new anchor_1.BN(Math.pow(10, market.decimals));
|
|
1317
|
+
if (signedTokenAmount.gt(numericConstants_1.ZERO)) {
|
|
1318
|
+
const assetWeight = (0, spotBalance_2.calculateAssetWeight)(signedTokenAmount, this.driftClient.getOracleDataForSpotMarket(market.marketIndex).price, market, marginCategory);
|
|
1319
|
+
return numericConstants_1.QUOTE_PRECISION.mul(assetWeight)
|
|
1320
|
+
.div(numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION)
|
|
1321
|
+
.mul(signedTokenAmount)
|
|
1322
|
+
.div(tokenPrecision);
|
|
1323
|
+
}
|
|
1324
|
+
else {
|
|
1325
|
+
const liabilityWeight = (0, spotBalance_2.calculateLiabilityWeight)(signedTokenAmount.abs(), market, marginCategory);
|
|
1326
|
+
return numericConstants_1.QUOTE_PRECISION.neg()
|
|
1327
|
+
.mul(liabilityWeight)
|
|
1328
|
+
.div(numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION)
|
|
1329
|
+
.mul(signedTokenAmount.abs())
|
|
1330
|
+
.div(tokenPrecision);
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
/**
|
|
1334
|
+
* Calculates the estimated liquidation price for a position after closing a quote amount of the position.
|
|
1335
|
+
* @param positionMarketIndex
|
|
1336
|
+
* @param closeQuoteAmount
|
|
1337
|
+
* @returns : Precision PRICE_PRECISION
|
|
1338
|
+
*/
|
|
1339
|
+
liquidationPriceAfterClose(positionMarketIndex, closeQuoteAmount, estimatedEntryPrice = numericConstants_1.ZERO) {
|
|
1340
|
+
const currentPosition = this.getPerpPositionOrEmpty(positionMarketIndex);
|
|
1341
|
+
const closeBaseAmount = currentPosition.baseAssetAmount
|
|
1342
|
+
.mul(closeQuoteAmount)
|
|
1343
|
+
.div(currentPosition.quoteAssetAmount.abs())
|
|
1344
|
+
.add(currentPosition.baseAssetAmount
|
|
1345
|
+
.mul(closeQuoteAmount)
|
|
1346
|
+
.mod(currentPosition.quoteAssetAmount.abs()))
|
|
1347
|
+
.neg();
|
|
1348
|
+
return this.liquidationPrice(positionMarketIndex, closeBaseAmount, estimatedEntryPrice);
|
|
1349
|
+
}
|
|
1350
|
+
getMarginUSDCRequiredForTrade(targetMarketIndex, baseSize, estEntryPrice, perpMarketMaxMarginRatio) {
|
|
1351
|
+
const maxMarginRatio = Math.max(perpMarketMaxMarginRatio, this.getUserAccount().maxMarginRatio);
|
|
1352
|
+
return (0, margin_2.calculateMarginUSDCRequiredForTrade)(this.driftClient, targetMarketIndex, baseSize, maxMarginRatio, estEntryPrice);
|
|
1353
|
+
}
|
|
1354
|
+
getCollateralDepositRequiredForTrade(targetMarketIndex, baseSize, collateralIndex, perpMarketMaxMarginRatio) {
|
|
1355
|
+
const maxMarginRatio = Math.max(perpMarketMaxMarginRatio, this.getUserAccount().maxMarginRatio);
|
|
1356
|
+
return (0, margin_2.calculateCollateralDepositRequiredForTrade)(this.driftClient, targetMarketIndex, baseSize, collateralIndex, maxMarginRatio);
|
|
1357
|
+
}
|
|
1358
|
+
/**
|
|
1359
|
+
* Separates the max trade size into two parts:
|
|
1360
|
+
* - tradeSize: The maximum trade size for target direction
|
|
1361
|
+
* - oppositeSideTradeSize: the trade size for closing the opposite direction
|
|
1362
|
+
* @param targetMarketIndex
|
|
1363
|
+
* @param tradeSide
|
|
1364
|
+
* @returns { tradeSize: BN, oppositeSideTradeSize: BN} : Precision QUOTE_PRECISION
|
|
1365
|
+
*/
|
|
1366
|
+
getMaxTradeSizeUSDCForPerp(targetMarketIndex, tradeSide, maxMarginRatio = undefined, positionType = 'cross') {
|
|
1367
|
+
let tradeSize = numericConstants_1.ZERO;
|
|
1368
|
+
let oppositeSideTradeSize = numericConstants_1.ZERO;
|
|
1369
|
+
const currentPosition = this.getPerpPositionOrEmpty(targetMarketIndex);
|
|
1370
|
+
const targetSide = (0, types_1.isVariant)(tradeSide, 'short') ? 'short' : 'long';
|
|
1371
|
+
const currentPositionSide = (currentPosition === null || currentPosition === void 0 ? void 0 : currentPosition.baseAssetAmount.isNeg())
|
|
1372
|
+
? 'short'
|
|
1373
|
+
: 'long';
|
|
1374
|
+
const targetingSameSide = !currentPosition
|
|
1375
|
+
? true
|
|
1376
|
+
: targetSide === currentPositionSide;
|
|
1377
|
+
const oracleData = this.getMMOracleDataForPerpMarket(targetMarketIndex);
|
|
1378
|
+
const marketAccount = this.driftClient.getPerpMarketAccount(targetMarketIndex);
|
|
1379
|
+
// add any position we have on the opposite side of the current trade, because we can "flip" the size of this position without taking any extra leverage.
|
|
1380
|
+
const oppositeSizeLiabilityValue = targetingSameSide
|
|
1381
|
+
? numericConstants_1.ZERO
|
|
1382
|
+
: (0, margin_1.calculatePerpLiabilityValue)(currentPosition.baseAssetAmount, oracleData.price);
|
|
1383
|
+
const maxPositionSize = this.getPerpBuyingPower(targetMarketIndex, numericConstants_1.ZERO, maxMarginRatio, positionType);
|
|
1384
|
+
if (maxPositionSize.gte(numericConstants_1.ZERO)) {
|
|
1385
|
+
if (oppositeSizeLiabilityValue.eq(numericConstants_1.ZERO)) {
|
|
1386
|
+
// case 1 : Regular trade where current total position less than max, and no opposite position to account for
|
|
1387
|
+
// do nothing
|
|
1388
|
+
tradeSize = maxPositionSize;
|
|
1389
|
+
}
|
|
1390
|
+
else {
|
|
1391
|
+
// case 2 : trade where current total position less than max, but need to account for flipping the current position over to the other side
|
|
1392
|
+
tradeSize = maxPositionSize.add(oppositeSizeLiabilityValue);
|
|
1393
|
+
oppositeSideTradeSize = oppositeSizeLiabilityValue;
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
else {
|
|
1397
|
+
// current leverage is greater than max leverage - can only reduce position size
|
|
1398
|
+
if (!targetingSameSide) {
|
|
1399
|
+
const perpLiabilityValue = (0, margin_1.calculatePerpLiabilityValue)(currentPosition.baseAssetAmount, oracleData.price);
|
|
1400
|
+
const totalCollateral = this.getTotalCollateral();
|
|
1401
|
+
const marginRequirement = this.getInitialMarginRequirement();
|
|
1402
|
+
const marginRatio = Math.max(currentPosition.maxMarginRatio, this.getUserAccount().maxMarginRatio);
|
|
1403
|
+
const marginFreedByClosing = perpLiabilityValue
|
|
1404
|
+
.mul(new anchor_1.BN(marginRatio))
|
|
1405
|
+
.div(numericConstants_1.MARGIN_PRECISION);
|
|
1406
|
+
const marginRequirementAfterClosing = marginRequirement.sub(marginFreedByClosing);
|
|
1407
|
+
if (marginRequirementAfterClosing.gt(totalCollateral)) {
|
|
1408
|
+
oppositeSideTradeSize = perpLiabilityValue;
|
|
1409
|
+
}
|
|
1410
|
+
else {
|
|
1411
|
+
const freeCollateralAfterClose = totalCollateral.sub(marginRequirementAfterClosing);
|
|
1412
|
+
const buyingPowerAfterClose = this.getPerpBuyingPowerFromFreeCollateralAndBaseAssetAmount(targetMarketIndex, freeCollateralAfterClose, numericConstants_1.ZERO, currentPosition.maxMarginRatio);
|
|
1413
|
+
oppositeSideTradeSize = perpLiabilityValue;
|
|
1414
|
+
tradeSize = buyingPowerAfterClose;
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
else {
|
|
1418
|
+
// do nothing if targetting same side
|
|
1419
|
+
tradeSize = maxPositionSize;
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
const freeCollateral = this.getFreeCollateral('Initial');
|
|
1423
|
+
let baseTradeSize = targetSide === 'long'
|
|
1424
|
+
? tradeSize.mul(numericConstants_1.BASE_PRECISION).div(oracleData.price)
|
|
1425
|
+
: tradeSize.mul(numericConstants_1.BASE_PRECISION).div(oracleData.price).neg();
|
|
1426
|
+
let freeCollateralChangeFromNewPosition = this.calculateEntriesEffectOnFreeCollateral(marketAccount, oracleData.price, currentPosition, baseTradeSize, oracleData.price, false, 'Initial');
|
|
1427
|
+
while (freeCollateralChangeFromNewPosition.isNeg() &&
|
|
1428
|
+
freeCollateralChangeFromNewPosition.abs().gt(freeCollateral)) {
|
|
1429
|
+
tradeSize = tradeSize.mul(new anchor_1.BN(99)).div(new anchor_1.BN(100));
|
|
1430
|
+
baseTradeSize =
|
|
1431
|
+
targetSide === 'long'
|
|
1432
|
+
? tradeSize.mul(numericConstants_1.BASE_PRECISION).div(oracleData.price)
|
|
1433
|
+
: tradeSize.mul(numericConstants_1.BASE_PRECISION).div(oracleData.price).neg();
|
|
1434
|
+
freeCollateralChangeFromNewPosition =
|
|
1435
|
+
this.calculateEntriesEffectOnFreeCollateral(marketAccount, oracleData.price, currentPosition, baseTradeSize, oracleData.price, false, 'Initial');
|
|
1436
|
+
}
|
|
1437
|
+
return { tradeSize, oppositeSideTradeSize };
|
|
1438
|
+
}
|
|
1439
|
+
/**
|
|
1440
|
+
* Get the maximum trade size for a given market, taking into account the user's current leverage, positions, collateral, etc.
|
|
1441
|
+
*
|
|
1442
|
+
* @param targetMarketIndex
|
|
1443
|
+
* @param direction
|
|
1444
|
+
* @param currentQuoteAssetValue
|
|
1445
|
+
* @param currentSpotMarketNetValue
|
|
1446
|
+
* @returns tradeSizeAllowed : Precision QUOTE_PRECISION
|
|
1447
|
+
*/
|
|
1448
|
+
getMaxTradeSizeUSDCForSpot(targetMarketIndex, direction, currentQuoteAssetValue, currentSpotMarketNetValue) {
|
|
1449
|
+
const market = this.driftClient.getSpotMarketAccount(targetMarketIndex);
|
|
1450
|
+
const oraclePrice = this.driftClient.getOracleDataForSpotMarket(targetMarketIndex).price;
|
|
1451
|
+
currentQuoteAssetValue = this.getSpotMarketAssetValue(numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
|
|
1452
|
+
currentSpotMarketNetValue =
|
|
1453
|
+
currentSpotMarketNetValue !== null && currentSpotMarketNetValue !== void 0 ? currentSpotMarketNetValue : this.getSpotPositionValue(targetMarketIndex);
|
|
1454
|
+
let freeCollateral = this.getFreeCollateral();
|
|
1455
|
+
const marginRatio = (0, spotMarket_1.calculateSpotMarketMarginRatio)(market, oraclePrice, 'Initial', numericConstants_1.ZERO, (0, types_1.isVariant)(direction, 'long')
|
|
1456
|
+
? types_2.SpotBalanceType.DEPOSIT
|
|
1457
|
+
: types_2.SpotBalanceType.BORROW, this.getUserAccount().maxMarginRatio);
|
|
1458
|
+
let tradeAmount = numericConstants_1.ZERO;
|
|
1459
|
+
if (this.getUserAccount().isMarginTradingEnabled) {
|
|
1460
|
+
// if the user is buying/selling and already short/long, need to account for closing out short/long
|
|
1461
|
+
if ((0, types_1.isVariant)(direction, 'long') && currentSpotMarketNetValue.lt(numericConstants_1.ZERO)) {
|
|
1462
|
+
tradeAmount = currentSpotMarketNetValue.abs();
|
|
1463
|
+
const marginRatio = (0, spotMarket_1.calculateSpotMarketMarginRatio)(market, oraclePrice, 'Initial', this.getTokenAmount(targetMarketIndex).abs(), types_2.SpotBalanceType.BORROW, this.getUserAccount().maxMarginRatio);
|
|
1464
|
+
freeCollateral = freeCollateral.add(tradeAmount.mul(new anchor_1.BN(marginRatio)).div(numericConstants_1.MARGIN_PRECISION));
|
|
1465
|
+
}
|
|
1466
|
+
else if ((0, types_1.isVariant)(direction, 'short') &&
|
|
1467
|
+
currentSpotMarketNetValue.gt(numericConstants_1.ZERO)) {
|
|
1468
|
+
tradeAmount = currentSpotMarketNetValue;
|
|
1469
|
+
const marginRatio = (0, spotMarket_1.calculateSpotMarketMarginRatio)(market, oraclePrice, 'Initial', this.getTokenAmount(targetMarketIndex), types_2.SpotBalanceType.DEPOSIT, this.getUserAccount().maxMarginRatio);
|
|
1470
|
+
freeCollateral = freeCollateral.add(tradeAmount.mul(new anchor_1.BN(marginRatio)).div(numericConstants_1.MARGIN_PRECISION));
|
|
1471
|
+
}
|
|
1472
|
+
tradeAmount = tradeAmount.add(freeCollateral.mul(numericConstants_1.MARGIN_PRECISION).div(new anchor_1.BN(marginRatio)));
|
|
1473
|
+
}
|
|
1474
|
+
else if ((0, types_1.isVariant)(direction, 'long')) {
|
|
1475
|
+
tradeAmount = anchor_1.BN.min(currentQuoteAssetValue, freeCollateral.mul(numericConstants_1.MARGIN_PRECISION).div(new anchor_1.BN(marginRatio)));
|
|
1476
|
+
}
|
|
1477
|
+
else {
|
|
1478
|
+
tradeAmount = anchor_1.BN.max(numericConstants_1.ZERO, currentSpotMarketNetValue);
|
|
1479
|
+
}
|
|
1480
|
+
return tradeAmount;
|
|
1481
|
+
}
|
|
1482
|
+
/**
|
|
1483
|
+
* Calculates the max amount of token that can be swapped from inMarket to outMarket
|
|
1484
|
+
* Assumes swap happens at oracle price
|
|
1485
|
+
*
|
|
1486
|
+
* @param inMarketIndex
|
|
1487
|
+
* @param outMarketIndex
|
|
1488
|
+
* @param calculateSwap function to similate in to out swa
|
|
1489
|
+
* @param iterationLimit how long to run appromixation before erroring out
|
|
1490
|
+
*/
|
|
1491
|
+
getMaxSwapAmount({ inMarketIndex, outMarketIndex, calculateSwap, iterationLimit = 1000, }) {
|
|
1492
|
+
const inMarket = this.driftClient.getSpotMarketAccount(inMarketIndex);
|
|
1493
|
+
const outMarket = this.driftClient.getSpotMarketAccount(outMarketIndex);
|
|
1494
|
+
const inOraclePriceData = this.getOracleDataForSpotMarket(inMarketIndex);
|
|
1495
|
+
const inOraclePrice = inOraclePriceData.price;
|
|
1496
|
+
const outOraclePriceData = this.getOracleDataForSpotMarket(outMarketIndex);
|
|
1497
|
+
const outOraclePrice = outOraclePriceData.price;
|
|
1498
|
+
const inStrictOraclePrice = new strictOraclePrice_1.StrictOraclePrice(inOraclePrice);
|
|
1499
|
+
const outStrictOraclePrice = new strictOraclePrice_1.StrictOraclePrice(outOraclePrice);
|
|
1500
|
+
const inPrecision = new anchor_1.BN(10 ** inMarket.decimals);
|
|
1501
|
+
const outPrecision = new anchor_1.BN(10 ** outMarket.decimals);
|
|
1502
|
+
const inSpotPosition = this.getSpotPosition(inMarketIndex) ||
|
|
1503
|
+
this.getEmptySpotPosition(inMarketIndex);
|
|
1504
|
+
const outSpotPosition = this.getSpotPosition(outMarketIndex) ||
|
|
1505
|
+
this.getEmptySpotPosition(outMarketIndex);
|
|
1506
|
+
const freeCollateral = this.getFreeCollateral();
|
|
1507
|
+
const inContributionInitial = this.calculateSpotPositionFreeCollateralContribution(inSpotPosition, inStrictOraclePrice);
|
|
1508
|
+
const { totalAssetValue: inTotalAssetValueInitial, totalLiabilityValue: inTotalLiabilityValueInitial, } = this.calculateSpotPositionLeverageContribution(inSpotPosition, inStrictOraclePrice);
|
|
1509
|
+
const outContributionInitial = this.calculateSpotPositionFreeCollateralContribution(outSpotPosition, outStrictOraclePrice);
|
|
1510
|
+
const { totalAssetValue: outTotalAssetValueInitial, totalLiabilityValue: outTotalLiabilityValueInitial, } = this.calculateSpotPositionLeverageContribution(outSpotPosition, outStrictOraclePrice);
|
|
1511
|
+
const initialContribution = inContributionInitial.add(outContributionInitial);
|
|
1512
|
+
const { perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue } = this.getLeverageComponents();
|
|
1513
|
+
if (!calculateSwap) {
|
|
1514
|
+
calculateSwap = (inSwap) => {
|
|
1515
|
+
return inSwap
|
|
1516
|
+
.mul(outPrecision)
|
|
1517
|
+
.mul(inOraclePrice)
|
|
1518
|
+
.div(outOraclePrice)
|
|
1519
|
+
.div(inPrecision);
|
|
1520
|
+
};
|
|
1521
|
+
}
|
|
1522
|
+
let inSwap = numericConstants_1.ZERO;
|
|
1523
|
+
let outSwap = numericConstants_1.ZERO;
|
|
1524
|
+
const inTokenAmount = this.getTokenAmount(inMarketIndex);
|
|
1525
|
+
const outTokenAmount = this.getTokenAmount(outMarketIndex);
|
|
1526
|
+
const inAssetWeight = (0, spotBalance_2.calculateAssetWeight)(inTokenAmount, inOraclePriceData.price, inMarket, 'Initial');
|
|
1527
|
+
const outAssetWeight = (0, spotBalance_2.calculateAssetWeight)(outTokenAmount, outOraclePriceData.price, outMarket, 'Initial');
|
|
1528
|
+
const outSaferThanIn =
|
|
1529
|
+
// selling asset to close borrow
|
|
1530
|
+
(inTokenAmount.gt(numericConstants_1.ZERO) && outTokenAmount.lt(numericConstants_1.ZERO)) ||
|
|
1531
|
+
// buying asset with higher initial asset weight
|
|
1532
|
+
inAssetWeight.lte(outAssetWeight);
|
|
1533
|
+
if (freeCollateral.lt(numericConstants_1.PRICE_PRECISION.divn(100))) {
|
|
1534
|
+
if (outSaferThanIn && inTokenAmount.gt(numericConstants_1.ZERO)) {
|
|
1535
|
+
inSwap = inTokenAmount;
|
|
1536
|
+
outSwap = calculateSwap(inSwap);
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
else {
|
|
1540
|
+
let minSwap = numericConstants_1.ZERO;
|
|
1541
|
+
let maxSwap = anchor_1.BN.max(freeCollateral.mul(inPrecision).mul(new anchor_1.BN(100)).div(inOraclePrice), // 100x current free collateral
|
|
1542
|
+
inTokenAmount.abs().mul(new anchor_1.BN(10)) // 10x current position
|
|
1543
|
+
);
|
|
1544
|
+
inSwap = maxSwap.div(numericConstants_1.TWO);
|
|
1545
|
+
const error = freeCollateral.div(new anchor_1.BN(10000));
|
|
1546
|
+
let i = 0;
|
|
1547
|
+
let freeCollateralAfter = freeCollateral;
|
|
1548
|
+
while (freeCollateralAfter.gt(error) || freeCollateralAfter.isNeg()) {
|
|
1549
|
+
outSwap = calculateSwap(inSwap);
|
|
1550
|
+
const inPositionAfter = this.cloneAndUpdateSpotPosition(inSpotPosition, inSwap.neg(), inMarket);
|
|
1551
|
+
const outPositionAfter = this.cloneAndUpdateSpotPosition(outSpotPosition, outSwap, outMarket);
|
|
1552
|
+
const inContributionAfter = this.calculateSpotPositionFreeCollateralContribution(inPositionAfter, inStrictOraclePrice);
|
|
1553
|
+
const outContributionAfter = this.calculateSpotPositionFreeCollateralContribution(outPositionAfter, outStrictOraclePrice);
|
|
1554
|
+
const contributionAfter = inContributionAfter.add(outContributionAfter);
|
|
1555
|
+
const contributionDelta = contributionAfter.sub(initialContribution);
|
|
1556
|
+
freeCollateralAfter = freeCollateral.add(contributionDelta);
|
|
1557
|
+
if (freeCollateralAfter.gt(error)) {
|
|
1558
|
+
minSwap = inSwap;
|
|
1559
|
+
inSwap = minSwap.add(maxSwap).div(numericConstants_1.TWO);
|
|
1560
|
+
}
|
|
1561
|
+
else if (freeCollateralAfter.isNeg()) {
|
|
1562
|
+
maxSwap = inSwap;
|
|
1563
|
+
inSwap = minSwap.add(maxSwap).div(numericConstants_1.TWO);
|
|
1564
|
+
}
|
|
1565
|
+
if (i++ > iterationLimit) {
|
|
1566
|
+
console.log('getMaxSwapAmount iteration limit reached');
|
|
1567
|
+
break;
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
const inPositionAfter = this.cloneAndUpdateSpotPosition(inSpotPosition, inSwap.neg(), inMarket);
|
|
1572
|
+
const outPositionAfter = this.cloneAndUpdateSpotPosition(outSpotPosition, outSwap, outMarket);
|
|
1573
|
+
const { totalAssetValue: inTotalAssetValueAfter, totalLiabilityValue: inTotalLiabilityValueAfter, } = this.calculateSpotPositionLeverageContribution(inPositionAfter, inStrictOraclePrice);
|
|
1574
|
+
const { totalAssetValue: outTotalAssetValueAfter, totalLiabilityValue: outTotalLiabilityValueAfter, } = this.calculateSpotPositionLeverageContribution(outPositionAfter, outStrictOraclePrice);
|
|
1575
|
+
const spotAssetValueDelta = inTotalAssetValueAfter
|
|
1576
|
+
.add(outTotalAssetValueAfter)
|
|
1577
|
+
.sub(inTotalAssetValueInitial)
|
|
1578
|
+
.sub(outTotalAssetValueInitial);
|
|
1579
|
+
const spotLiabilityValueDelta = inTotalLiabilityValueAfter
|
|
1580
|
+
.add(outTotalLiabilityValueAfter)
|
|
1581
|
+
.sub(inTotalLiabilityValueInitial)
|
|
1582
|
+
.sub(outTotalLiabilityValueInitial);
|
|
1583
|
+
const spotAssetValueAfter = spotAssetValue.add(spotAssetValueDelta);
|
|
1584
|
+
const spotLiabilityValueAfter = spotLiabilityValue.add(spotLiabilityValueDelta);
|
|
1585
|
+
const leverage = this.calculateLeverageFromComponents({
|
|
1586
|
+
perpLiabilityValue,
|
|
1587
|
+
perpPnl,
|
|
1588
|
+
spotAssetValue: spotAssetValueAfter,
|
|
1589
|
+
spotLiabilityValue: spotLiabilityValueAfter,
|
|
1590
|
+
});
|
|
1591
|
+
return { inAmount: inSwap, outAmount: outSwap, leverage };
|
|
1592
|
+
}
|
|
1593
|
+
cloneAndUpdateSpotPosition(position, tokenAmount, market) {
|
|
1594
|
+
const clonedPosition = Object.assign({}, position);
|
|
1595
|
+
if (tokenAmount.eq(numericConstants_1.ZERO)) {
|
|
1596
|
+
return clonedPosition;
|
|
1597
|
+
}
|
|
1598
|
+
const preTokenAmount = (0, spotBalance_1.getSignedTokenAmount)((0, spotBalance_2.getTokenAmount)(position.scaledBalance, market, position.balanceType), position.balanceType);
|
|
1599
|
+
if ((0, utils_1.sigNum)(preTokenAmount).eq((0, utils_1.sigNum)(tokenAmount))) {
|
|
1600
|
+
const scaledBalanceDelta = (0, spotBalance_1.getBalance)(tokenAmount.abs(), market, position.balanceType);
|
|
1601
|
+
clonedPosition.scaledBalance =
|
|
1602
|
+
clonedPosition.scaledBalance.add(scaledBalanceDelta);
|
|
1603
|
+
return clonedPosition;
|
|
1604
|
+
}
|
|
1605
|
+
const updateDirection = tokenAmount.isNeg()
|
|
1606
|
+
? types_2.SpotBalanceType.BORROW
|
|
1607
|
+
: types_2.SpotBalanceType.DEPOSIT;
|
|
1608
|
+
if (tokenAmount.abs().gte(preTokenAmount.abs())) {
|
|
1609
|
+
clonedPosition.scaledBalance = (0, spotBalance_1.getBalance)(tokenAmount.abs().sub(preTokenAmount.abs()), market, updateDirection);
|
|
1610
|
+
clonedPosition.balanceType = updateDirection;
|
|
1611
|
+
}
|
|
1612
|
+
else {
|
|
1613
|
+
const scaledBalanceDelta = (0, spotBalance_1.getBalance)(tokenAmount.abs(), market, position.balanceType);
|
|
1614
|
+
clonedPosition.scaledBalance =
|
|
1615
|
+
clonedPosition.scaledBalance.sub(scaledBalanceDelta);
|
|
1616
|
+
}
|
|
1617
|
+
return clonedPosition;
|
|
1618
|
+
}
|
|
1619
|
+
calculateSpotPositionFreeCollateralContribution(spotPosition, strictOraclePrice) {
|
|
1620
|
+
const marginCategory = 'Initial';
|
|
1621
|
+
const spotMarketAccount = this.driftClient.getSpotMarketAccount(spotPosition.marketIndex);
|
|
1622
|
+
const { freeCollateralContribution } = (0, spotPosition_1.getWorstCaseTokenAmounts)(spotPosition, spotMarketAccount, strictOraclePrice, marginCategory, this.getUserAccount().maxMarginRatio);
|
|
1623
|
+
return freeCollateralContribution;
|
|
1624
|
+
}
|
|
1625
|
+
calculateSpotPositionLeverageContribution(spotPosition, strictOraclePrice) {
|
|
1626
|
+
let totalAssetValue = numericConstants_1.ZERO;
|
|
1627
|
+
let totalLiabilityValue = numericConstants_1.ZERO;
|
|
1628
|
+
const spotMarketAccount = this.driftClient.getSpotMarketAccount(spotPosition.marketIndex);
|
|
1629
|
+
const { tokenValue, ordersValue } = (0, spotPosition_1.getWorstCaseTokenAmounts)(spotPosition, spotMarketAccount, strictOraclePrice, 'Initial', this.getUserAccount().maxMarginRatio);
|
|
1630
|
+
if (tokenValue.gte(numericConstants_1.ZERO)) {
|
|
1631
|
+
totalAssetValue = tokenValue;
|
|
1632
|
+
}
|
|
1633
|
+
else {
|
|
1634
|
+
totalLiabilityValue = tokenValue.abs();
|
|
1635
|
+
}
|
|
1636
|
+
if (ordersValue.gt(numericConstants_1.ZERO)) {
|
|
1637
|
+
totalAssetValue = totalAssetValue.add(ordersValue);
|
|
1638
|
+
}
|
|
1639
|
+
else {
|
|
1640
|
+
totalLiabilityValue = totalLiabilityValue.add(ordersValue.abs());
|
|
1641
|
+
}
|
|
1642
|
+
return {
|
|
1643
|
+
totalAssetValue,
|
|
1644
|
+
totalLiabilityValue,
|
|
1645
|
+
};
|
|
1646
|
+
}
|
|
1647
|
+
/**
|
|
1648
|
+
* Estimates what the user leverage will be after swap
|
|
1649
|
+
* @param inMarketIndex
|
|
1650
|
+
* @param outMarketIndex
|
|
1651
|
+
* @param inAmount
|
|
1652
|
+
* @param outAmount
|
|
1653
|
+
*/
|
|
1654
|
+
accountLeverageAfterSwap({ inMarketIndex, outMarketIndex, inAmount, outAmount, }) {
|
|
1655
|
+
const inMarket = this.driftClient.getSpotMarketAccount(inMarketIndex);
|
|
1656
|
+
const outMarket = this.driftClient.getSpotMarketAccount(outMarketIndex);
|
|
1657
|
+
const inOraclePriceData = this.getOracleDataForSpotMarket(inMarketIndex);
|
|
1658
|
+
const inOraclePrice = inOraclePriceData.price;
|
|
1659
|
+
const outOraclePriceData = this.getOracleDataForSpotMarket(outMarketIndex);
|
|
1660
|
+
const outOraclePrice = outOraclePriceData.price;
|
|
1661
|
+
const inStrictOraclePrice = new strictOraclePrice_1.StrictOraclePrice(inOraclePrice);
|
|
1662
|
+
const outStrictOraclePrice = new strictOraclePrice_1.StrictOraclePrice(outOraclePrice);
|
|
1663
|
+
const inSpotPosition = this.getSpotPosition(inMarketIndex) ||
|
|
1664
|
+
this.getEmptySpotPosition(inMarketIndex);
|
|
1665
|
+
const outSpotPosition = this.getSpotPosition(outMarketIndex) ||
|
|
1666
|
+
this.getEmptySpotPosition(outMarketIndex);
|
|
1667
|
+
const { totalAssetValue: inTotalAssetValueInitial, totalLiabilityValue: inTotalLiabilityValueInitial, } = this.calculateSpotPositionLeverageContribution(inSpotPosition, inStrictOraclePrice);
|
|
1668
|
+
const { totalAssetValue: outTotalAssetValueInitial, totalLiabilityValue: outTotalLiabilityValueInitial, } = this.calculateSpotPositionLeverageContribution(outSpotPosition, outStrictOraclePrice);
|
|
1669
|
+
const { perpLiabilityValue, perpPnl, spotAssetValue, spotLiabilityValue } = this.getLeverageComponents();
|
|
1670
|
+
const inPositionAfter = this.cloneAndUpdateSpotPosition(inSpotPosition, inAmount.abs().neg(), inMarket);
|
|
1671
|
+
const outPositionAfter = this.cloneAndUpdateSpotPosition(outSpotPosition, outAmount.abs(), outMarket);
|
|
1672
|
+
const { totalAssetValue: inTotalAssetValueAfter, totalLiabilityValue: inTotalLiabilityValueAfter, } = this.calculateSpotPositionLeverageContribution(inPositionAfter, inStrictOraclePrice);
|
|
1673
|
+
const { totalAssetValue: outTotalAssetValueAfter, totalLiabilityValue: outTotalLiabilityValueAfter, } = this.calculateSpotPositionLeverageContribution(outPositionAfter, outStrictOraclePrice);
|
|
1674
|
+
const spotAssetValueDelta = inTotalAssetValueAfter
|
|
1675
|
+
.add(outTotalAssetValueAfter)
|
|
1676
|
+
.sub(inTotalAssetValueInitial)
|
|
1677
|
+
.sub(outTotalAssetValueInitial);
|
|
1678
|
+
const spotLiabilityValueDelta = inTotalLiabilityValueAfter
|
|
1679
|
+
.add(outTotalLiabilityValueAfter)
|
|
1680
|
+
.sub(inTotalLiabilityValueInitial)
|
|
1681
|
+
.sub(outTotalLiabilityValueInitial);
|
|
1682
|
+
const spotAssetValueAfter = spotAssetValue.add(spotAssetValueDelta);
|
|
1683
|
+
const spotLiabilityValueAfter = spotLiabilityValue.add(spotLiabilityValueDelta);
|
|
1684
|
+
return this.calculateLeverageFromComponents({
|
|
1685
|
+
perpLiabilityValue,
|
|
1686
|
+
perpPnl,
|
|
1687
|
+
spotAssetValue: spotAssetValueAfter,
|
|
1688
|
+
spotLiabilityValue: spotLiabilityValueAfter,
|
|
1689
|
+
});
|
|
1690
|
+
}
|
|
1691
|
+
// TODO - should this take the price impact of the trade into account for strict accuracy?
|
|
1692
|
+
/**
|
|
1693
|
+
* Returns the leverage ratio for the account after adding (or subtracting) the given quote size to the given position
|
|
1694
|
+
* @param targetMarketIndex
|
|
1695
|
+
* @param: targetMarketType
|
|
1696
|
+
* @param tradeQuoteAmount
|
|
1697
|
+
* @param tradeSide
|
|
1698
|
+
* @param includeOpenOrders
|
|
1699
|
+
* @returns leverageRatio : Precision TEN_THOUSAND
|
|
1700
|
+
*/
|
|
1701
|
+
accountLeverageRatioAfterTrade(targetMarketIndex, targetMarketType, tradeQuoteAmount, tradeSide, includeOpenOrders = true) {
|
|
1702
|
+
const tradeIsPerp = (0, types_1.isVariant)(targetMarketType, 'perp');
|
|
1703
|
+
if (!tradeIsPerp) {
|
|
1704
|
+
// calculate new asset/liability values for base and quote market to find new account leverage
|
|
1705
|
+
const totalLiabilityValue = this.getTotalLiabilityValue();
|
|
1706
|
+
const totalAssetValue = this.getTotalAssetValue();
|
|
1707
|
+
const spotLiabilityValue = this.getSpotMarketLiabilityValue(undefined, undefined, undefined, includeOpenOrders);
|
|
1708
|
+
const currentQuoteAssetValue = this.getSpotMarketAssetValue(numericConstants_1.QUOTE_SPOT_MARKET_INDEX, undefined, includeOpenOrders);
|
|
1709
|
+
const currentQuoteLiabilityValue = this.getSpotMarketLiabilityValue(numericConstants_1.QUOTE_SPOT_MARKET_INDEX, undefined, undefined, includeOpenOrders);
|
|
1710
|
+
const currentQuoteValue = currentQuoteAssetValue.sub(currentQuoteLiabilityValue);
|
|
1711
|
+
const currentSpotMarketAssetValue = this.getSpotMarketAssetValue(targetMarketIndex, undefined, includeOpenOrders);
|
|
1712
|
+
const currentSpotMarketLiabilityValue = this.getSpotMarketLiabilityValue(targetMarketIndex, undefined, undefined, includeOpenOrders);
|
|
1713
|
+
const currentSpotMarketNetValue = currentSpotMarketAssetValue.sub(currentSpotMarketLiabilityValue);
|
|
1714
|
+
let assetValueToAdd = numericConstants_1.ZERO;
|
|
1715
|
+
let liabilityValueToAdd = numericConstants_1.ZERO;
|
|
1716
|
+
const newQuoteNetValue = tradeSide == types_2.PositionDirection.SHORT
|
|
1717
|
+
? currentQuoteValue.add(tradeQuoteAmount)
|
|
1718
|
+
: currentQuoteValue.sub(tradeQuoteAmount);
|
|
1719
|
+
const newQuoteAssetValue = anchor_1.BN.max(newQuoteNetValue, numericConstants_1.ZERO);
|
|
1720
|
+
const newQuoteLiabilityValue = anchor_1.BN.min(newQuoteNetValue, numericConstants_1.ZERO).abs();
|
|
1721
|
+
assetValueToAdd = assetValueToAdd.add(newQuoteAssetValue.sub(currentQuoteAssetValue));
|
|
1722
|
+
liabilityValueToAdd = liabilityValueToAdd.add(newQuoteLiabilityValue.sub(currentQuoteLiabilityValue));
|
|
1723
|
+
const newSpotMarketNetValue = tradeSide == types_2.PositionDirection.LONG
|
|
1724
|
+
? currentSpotMarketNetValue.add(tradeQuoteAmount)
|
|
1725
|
+
: currentSpotMarketNetValue.sub(tradeQuoteAmount);
|
|
1726
|
+
const newSpotMarketAssetValue = anchor_1.BN.max(newSpotMarketNetValue, numericConstants_1.ZERO);
|
|
1727
|
+
const newSpotMarketLiabilityValue = anchor_1.BN.min(newSpotMarketNetValue, numericConstants_1.ZERO).abs();
|
|
1728
|
+
assetValueToAdd = assetValueToAdd.add(newSpotMarketAssetValue.sub(currentSpotMarketAssetValue));
|
|
1729
|
+
liabilityValueToAdd = liabilityValueToAdd.add(newSpotMarketLiabilityValue.sub(currentSpotMarketLiabilityValue));
|
|
1730
|
+
const totalAssetValueAfterTrade = totalAssetValue.add(assetValueToAdd);
|
|
1731
|
+
const totalSpotLiabilityValueAfterTrade = spotLiabilityValue.add(liabilityValueToAdd);
|
|
1732
|
+
const totalLiabilityValueAfterTrade = totalLiabilityValue.add(liabilityValueToAdd);
|
|
1733
|
+
const netAssetValueAfterTrade = totalAssetValueAfterTrade.sub(totalSpotLiabilityValueAfterTrade);
|
|
1734
|
+
if (netAssetValueAfterTrade.eq(numericConstants_1.ZERO)) {
|
|
1735
|
+
return numericConstants_1.ZERO;
|
|
1736
|
+
}
|
|
1737
|
+
const newLeverage = totalLiabilityValueAfterTrade
|
|
1738
|
+
.mul(numericConstants_1.TEN_THOUSAND)
|
|
1739
|
+
.div(netAssetValueAfterTrade);
|
|
1740
|
+
return newLeverage;
|
|
1741
|
+
}
|
|
1742
|
+
const currentPosition = this.getPerpPositionOrEmpty(targetMarketIndex);
|
|
1743
|
+
const perpMarket = this.driftClient.getPerpMarketAccount(targetMarketIndex);
|
|
1744
|
+
const oracleData = this.getOracleDataForPerpMarket(targetMarketIndex);
|
|
1745
|
+
let {
|
|
1746
|
+
// eslint-disable-next-line prefer-const
|
|
1747
|
+
worstCaseBaseAssetAmount: worstCaseBase, worstCaseLiabilityValue: currentPositionQuoteAmount, } = (0, margin_1.calculateWorstCasePerpLiabilityValue)(currentPosition, perpMarket, oracleData.price);
|
|
1748
|
+
// current side is short if position base asset amount is negative OR there is no position open but open orders are short
|
|
1749
|
+
const currentSide = currentPosition.baseAssetAmount.isNeg() ||
|
|
1750
|
+
(currentPosition.baseAssetAmount.eq(numericConstants_1.ZERO) && worstCaseBase.isNeg())
|
|
1751
|
+
? types_2.PositionDirection.SHORT
|
|
1752
|
+
: types_2.PositionDirection.LONG;
|
|
1753
|
+
if (currentSide === types_2.PositionDirection.SHORT)
|
|
1754
|
+
currentPositionQuoteAmount = currentPositionQuoteAmount.neg();
|
|
1755
|
+
if (tradeSide === types_2.PositionDirection.SHORT)
|
|
1756
|
+
tradeQuoteAmount = tradeQuoteAmount.neg();
|
|
1757
|
+
const currentPerpPositionAfterTrade = currentPositionQuoteAmount
|
|
1758
|
+
.add(tradeQuoteAmount)
|
|
1759
|
+
.abs();
|
|
1760
|
+
const totalPositionAfterTradeExcludingTargetMarket = this.getTotalPerpPositionValueExcludingMarket(targetMarketIndex, undefined, undefined, includeOpenOrders);
|
|
1761
|
+
const totalAssetValue = this.getTotalAssetValue();
|
|
1762
|
+
const totalPerpPositionLiability = currentPerpPositionAfterTrade
|
|
1763
|
+
.add(totalPositionAfterTradeExcludingTargetMarket)
|
|
1764
|
+
.abs();
|
|
1765
|
+
const totalSpotLiability = this.getSpotMarketLiabilityValue(undefined, undefined, undefined, includeOpenOrders);
|
|
1766
|
+
const totalLiabilitiesAfterTrade = totalPerpPositionLiability.add(totalSpotLiability);
|
|
1767
|
+
const netAssetValue = totalAssetValue.sub(totalSpotLiability);
|
|
1768
|
+
if (netAssetValue.eq(numericConstants_1.ZERO)) {
|
|
1769
|
+
return numericConstants_1.ZERO;
|
|
1770
|
+
}
|
|
1771
|
+
const newLeverage = totalLiabilitiesAfterTrade
|
|
1772
|
+
.mul(numericConstants_1.TEN_THOUSAND)
|
|
1773
|
+
.div(netAssetValue);
|
|
1774
|
+
return newLeverage;
|
|
1775
|
+
}
|
|
1776
|
+
getUserFeeTier(marketType, now) {
|
|
1777
|
+
const state = this.driftClient.getStateAccount();
|
|
1778
|
+
const feeTierIndex = 0;
|
|
1779
|
+
if ((0, types_1.isVariant)(marketType, 'perp')) {
|
|
1780
|
+
const userStatsAccount = this.driftClient
|
|
1781
|
+
.getUserStats()
|
|
1782
|
+
.getAccount();
|
|
1783
|
+
const total30dVolume = (0, trade_1.getUser30dRollingVolumeEstimate)(userStatsAccount, now);
|
|
1784
|
+
const stakedGovAssetAmount = userStatsAccount.ifStakedGovTokenAmount;
|
|
1785
|
+
const volumeThresholds = [
|
|
1786
|
+
new anchor_1.BN(2000000).mul(numericConstants_1.QUOTE_PRECISION),
|
|
1787
|
+
new anchor_1.BN(10000000).mul(numericConstants_1.QUOTE_PRECISION),
|
|
1788
|
+
new anchor_1.BN(20000000).mul(numericConstants_1.QUOTE_PRECISION),
|
|
1789
|
+
new anchor_1.BN(80000000).mul(numericConstants_1.QUOTE_PRECISION),
|
|
1790
|
+
new anchor_1.BN(200000000).mul(numericConstants_1.QUOTE_PRECISION),
|
|
1791
|
+
];
|
|
1792
|
+
const stakeThresholds = [
|
|
1793
|
+
new anchor_1.BN(1000 - 1).mul(numericConstants_1.QUOTE_PRECISION),
|
|
1794
|
+
new anchor_1.BN(10000 - 1).mul(numericConstants_1.QUOTE_PRECISION),
|
|
1795
|
+
new anchor_1.BN(50000 - 1).mul(numericConstants_1.QUOTE_PRECISION),
|
|
1796
|
+
new anchor_1.BN(100000 - 1).mul(numericConstants_1.QUOTE_PRECISION),
|
|
1797
|
+
new anchor_1.BN(250000 - 5).mul(numericConstants_1.QUOTE_PRECISION),
|
|
1798
|
+
];
|
|
1799
|
+
const stakeBenefitFrac = [0, 5, 10, 20, 30, 40];
|
|
1800
|
+
let feeTierIndex = 5;
|
|
1801
|
+
for (let i = 0; i < volumeThresholds.length; i++) {
|
|
1802
|
+
if (total30dVolume.lt(volumeThresholds[i])) {
|
|
1803
|
+
feeTierIndex = i;
|
|
1804
|
+
break;
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
let stakeBenefitIndex = 5;
|
|
1808
|
+
for (let i = 0; i < stakeThresholds.length; i++) {
|
|
1809
|
+
if (stakedGovAssetAmount.lt(stakeThresholds[i])) {
|
|
1810
|
+
stakeBenefitIndex = i;
|
|
1811
|
+
break;
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
const stakeBenefit = stakeBenefitFrac[stakeBenefitIndex];
|
|
1815
|
+
const tier = { ...state.perpFeeStructure.feeTiers[feeTierIndex] };
|
|
1816
|
+
if (stakeBenefit > 0) {
|
|
1817
|
+
tier.feeNumerator = (tier.feeNumerator * (100 - stakeBenefit)) / 100;
|
|
1818
|
+
tier.makerRebateNumerator =
|
|
1819
|
+
(tier.makerRebateNumerator * (100 + stakeBenefit)) / 100;
|
|
1820
|
+
}
|
|
1821
|
+
return tier;
|
|
1822
|
+
}
|
|
1823
|
+
return state.spotFeeStructure.feeTiers[feeTierIndex];
|
|
1824
|
+
}
|
|
1825
|
+
/**
|
|
1826
|
+
* Calculates how much perp fee will be taken for a given sized trade
|
|
1827
|
+
* @param quoteAmount
|
|
1828
|
+
* @returns feeForQuote : Precision QUOTE_PRECISION
|
|
1829
|
+
*/
|
|
1830
|
+
calculateFeeForQuoteAmount(quoteAmount, marketIndex) {
|
|
1831
|
+
if (marketIndex !== undefined) {
|
|
1832
|
+
const takerFeeMultiplier = this.driftClient.getMarketFees(types_2.MarketType.PERP, marketIndex, this).takerFee;
|
|
1833
|
+
const feeAmountNum = bigNum_1.BigNum.from(quoteAmount, numericConstants_1.QUOTE_PRECISION_EXP).toNum() *
|
|
1834
|
+
takerFeeMultiplier;
|
|
1835
|
+
return bigNum_1.BigNum.fromPrint(feeAmountNum.toString(), numericConstants_1.QUOTE_PRECISION_EXP).val;
|
|
1836
|
+
}
|
|
1837
|
+
else {
|
|
1838
|
+
const feeTier = this.getUserFeeTier(types_2.MarketType.PERP);
|
|
1839
|
+
return quoteAmount
|
|
1840
|
+
.mul(new anchor_1.BN(feeTier.feeNumerator))
|
|
1841
|
+
.div(new anchor_1.BN(feeTier.feeDenominator));
|
|
1842
|
+
}
|
|
1843
|
+
}
|
|
1844
|
+
/**
|
|
1845
|
+
* Calculates a user's max withdrawal amounts for a spot market. If reduceOnly is true,
|
|
1846
|
+
* it will return the max withdrawal amount without opening a liability for the user
|
|
1847
|
+
* @param marketIndex
|
|
1848
|
+
* @returns withdrawalLimit : Precision is the token precision for the chosen SpotMarket
|
|
1849
|
+
*/
|
|
1850
|
+
getWithdrawalLimit(marketIndex, reduceOnly) {
|
|
1851
|
+
const nowTs = new anchor_1.BN(Math.floor(Date.now() / 1000));
|
|
1852
|
+
const spotMarket = this.driftClient.getSpotMarketAccount(marketIndex);
|
|
1853
|
+
// eslint-disable-next-line prefer-const
|
|
1854
|
+
let { borrowLimit, withdrawLimit } = (0, spotBalance_2.calculateWithdrawLimit)(spotMarket, nowTs);
|
|
1855
|
+
const freeCollateral = this.getFreeCollateral();
|
|
1856
|
+
const initialMarginRequirement = this.getInitialMarginRequirement();
|
|
1857
|
+
const oracleData = this.getOracleDataForSpotMarket(marketIndex);
|
|
1858
|
+
const { numeratorScale, denominatorScale } = spotMarket.decimals > 6
|
|
1859
|
+
? {
|
|
1860
|
+
numeratorScale: new anchor_1.BN(10).pow(new anchor_1.BN(spotMarket.decimals - 6)),
|
|
1861
|
+
denominatorScale: new anchor_1.BN(1),
|
|
1862
|
+
}
|
|
1863
|
+
: {
|
|
1864
|
+
numeratorScale: new anchor_1.BN(1),
|
|
1865
|
+
denominatorScale: new anchor_1.BN(10).pow(new anchor_1.BN(6 - spotMarket.decimals)),
|
|
1866
|
+
};
|
|
1867
|
+
const { canBypass, depositAmount: userDepositAmount } = this.canBypassWithdrawLimits(marketIndex);
|
|
1868
|
+
if (canBypass) {
|
|
1869
|
+
withdrawLimit = anchor_1.BN.max(withdrawLimit, userDepositAmount);
|
|
1870
|
+
}
|
|
1871
|
+
const assetWeight = (0, spotBalance_2.calculateAssetWeight)(userDepositAmount, oracleData.price, spotMarket, 'Initial');
|
|
1872
|
+
let amountWithdrawable;
|
|
1873
|
+
if (assetWeight.eq(numericConstants_1.ZERO)) {
|
|
1874
|
+
amountWithdrawable = userDepositAmount;
|
|
1875
|
+
}
|
|
1876
|
+
else if (initialMarginRequirement.eq(numericConstants_1.ZERO)) {
|
|
1877
|
+
amountWithdrawable = userDepositAmount;
|
|
1878
|
+
}
|
|
1879
|
+
else {
|
|
1880
|
+
amountWithdrawable = (0, utils_1.divCeil)((0, utils_1.divCeil)(freeCollateral.mul(numericConstants_1.MARGIN_PRECISION), assetWeight).mul(numericConstants_1.PRICE_PRECISION), oracleData.price)
|
|
1881
|
+
.mul(numeratorScale)
|
|
1882
|
+
.div(denominatorScale);
|
|
1883
|
+
}
|
|
1884
|
+
const maxWithdrawValue = anchor_1.BN.min(anchor_1.BN.min(amountWithdrawable, userDepositAmount), withdrawLimit.abs());
|
|
1885
|
+
if (reduceOnly) {
|
|
1886
|
+
return anchor_1.BN.max(maxWithdrawValue, numericConstants_1.ZERO);
|
|
1887
|
+
}
|
|
1888
|
+
else {
|
|
1889
|
+
const weightedAssetValue = this.getSpotMarketAssetValue(marketIndex, 'Initial', false);
|
|
1890
|
+
const freeCollatAfterWithdraw = userDepositAmount.gt(numericConstants_1.ZERO)
|
|
1891
|
+
? freeCollateral.sub(weightedAssetValue)
|
|
1892
|
+
: freeCollateral;
|
|
1893
|
+
const maxLiabilityAllowed = freeCollatAfterWithdraw
|
|
1894
|
+
.mul(numericConstants_1.MARGIN_PRECISION)
|
|
1895
|
+
.div(new anchor_1.BN(spotMarket.initialLiabilityWeight))
|
|
1896
|
+
.mul(numericConstants_1.PRICE_PRECISION)
|
|
1897
|
+
.div(oracleData.price)
|
|
1898
|
+
.mul(numeratorScale)
|
|
1899
|
+
.div(denominatorScale);
|
|
1900
|
+
const maxBorrowValue = anchor_1.BN.min(maxWithdrawValue.add(maxLiabilityAllowed), borrowLimit.abs());
|
|
1901
|
+
return anchor_1.BN.max(maxBorrowValue, numericConstants_1.ZERO);
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1904
|
+
canBypassWithdrawLimits(marketIndex) {
|
|
1905
|
+
const spotMarket = this.driftClient.getSpotMarketAccount(marketIndex);
|
|
1906
|
+
const maxDepositAmount = spotMarket.withdrawGuardThreshold.div(new anchor_1.BN(10));
|
|
1907
|
+
const position = this.getSpotPosition(marketIndex);
|
|
1908
|
+
const netDeposits = this.getUserAccount().totalDeposits.sub(this.getUserAccount().totalWithdraws);
|
|
1909
|
+
if (!position) {
|
|
1910
|
+
return {
|
|
1911
|
+
canBypass: false,
|
|
1912
|
+
maxDepositAmount,
|
|
1913
|
+
depositAmount: numericConstants_1.ZERO,
|
|
1914
|
+
netDeposits,
|
|
1915
|
+
};
|
|
1916
|
+
}
|
|
1917
|
+
if ((0, types_1.isVariant)(position.balanceType, 'borrow')) {
|
|
1918
|
+
return {
|
|
1919
|
+
canBypass: false,
|
|
1920
|
+
maxDepositAmount,
|
|
1921
|
+
netDeposits,
|
|
1922
|
+
depositAmount: numericConstants_1.ZERO,
|
|
1923
|
+
};
|
|
1924
|
+
}
|
|
1925
|
+
const depositAmount = (0, spotBalance_2.getTokenAmount)(position.scaledBalance, spotMarket, types_2.SpotBalanceType.DEPOSIT);
|
|
1926
|
+
if (netDeposits.lt(numericConstants_1.ZERO)) {
|
|
1927
|
+
return {
|
|
1928
|
+
canBypass: false,
|
|
1929
|
+
maxDepositAmount,
|
|
1930
|
+
depositAmount,
|
|
1931
|
+
netDeposits,
|
|
1932
|
+
};
|
|
1933
|
+
}
|
|
1934
|
+
return {
|
|
1935
|
+
canBypass: depositAmount.lt(maxDepositAmount),
|
|
1936
|
+
maxDepositAmount,
|
|
1937
|
+
netDeposits,
|
|
1938
|
+
depositAmount,
|
|
1939
|
+
};
|
|
1940
|
+
}
|
|
1941
|
+
canMakeIdle(slot) {
|
|
1942
|
+
const userAccount = this.getUserAccount();
|
|
1943
|
+
if (userAccount.idle) {
|
|
1944
|
+
return false;
|
|
1945
|
+
}
|
|
1946
|
+
const { totalAssetValue, totalLiabilityValue } = this.getSpotMarketAssetAndLiabilityValue();
|
|
1947
|
+
const equity = totalAssetValue.sub(totalLiabilityValue);
|
|
1948
|
+
let slotsBeforeIdle;
|
|
1949
|
+
if (equity.lt(numericConstants_1.QUOTE_PRECISION.muln(1000))) {
|
|
1950
|
+
slotsBeforeIdle = new anchor_1.BN(9000); // 1 hour
|
|
1951
|
+
}
|
|
1952
|
+
else {
|
|
1953
|
+
slotsBeforeIdle = new anchor_1.BN(1512000); // 1 week
|
|
1954
|
+
}
|
|
1955
|
+
const userLastActiveSlot = userAccount.lastActiveSlot;
|
|
1956
|
+
const slotsSinceLastActive = slot.sub(userLastActiveSlot);
|
|
1957
|
+
if (slotsSinceLastActive.lt(slotsBeforeIdle)) {
|
|
1958
|
+
return false;
|
|
1959
|
+
}
|
|
1960
|
+
if (this.isBeingLiquidated()) {
|
|
1961
|
+
return false;
|
|
1962
|
+
}
|
|
1963
|
+
for (const perpPosition of userAccount.perpPositions) {
|
|
1964
|
+
if (!(0, position_1.positionIsAvailable)(perpPosition)) {
|
|
1965
|
+
return false;
|
|
1966
|
+
}
|
|
1967
|
+
}
|
|
1968
|
+
for (const spotPosition of userAccount.spotPositions) {
|
|
1969
|
+
if ((0, types_1.isVariant)(spotPosition.balanceType, 'borrow') &&
|
|
1970
|
+
spotPosition.scaledBalance.gt(numericConstants_1.ZERO)) {
|
|
1971
|
+
return false;
|
|
1972
|
+
}
|
|
1973
|
+
if (spotPosition.openOrders !== 0) {
|
|
1974
|
+
return false;
|
|
1975
|
+
}
|
|
1976
|
+
}
|
|
1977
|
+
for (const order of userAccount.orders) {
|
|
1978
|
+
if ((0, types_1.isVariant)(order.status, 'open')) {
|
|
1979
|
+
return false;
|
|
1980
|
+
}
|
|
1981
|
+
}
|
|
1982
|
+
return true;
|
|
1983
|
+
}
|
|
1984
|
+
canBeDeleted(userStatsAccount, now) {
|
|
1985
|
+
const userAccount = this.getUserAccount();
|
|
1986
|
+
const userStatsAccountToUse = userStatsAccount || this.driftClient.getUserStats().getAccount();
|
|
1987
|
+
const nowInSeconds = now || new anchor_1.BN(Math.floor(Date.now() / 1000));
|
|
1988
|
+
const stateAccount = this.driftClient.getStateAccount();
|
|
1989
|
+
// Referrer cannot delete sub_account_id 0
|
|
1990
|
+
const isReferrer = (userStatsAccountToUse.referrerStatus & types_1.ReferrerStatus.IsReferrer) > 0;
|
|
1991
|
+
if (isReferrer && userAccount.subAccountId === 0) {
|
|
1992
|
+
return { canDelete: false, reason: 'is-subaccount-0-referrer' };
|
|
1993
|
+
}
|
|
1994
|
+
if (this.isBankrupt()) {
|
|
1995
|
+
return { canDelete: false, reason: 'is-bankrupt' };
|
|
1996
|
+
}
|
|
1997
|
+
if (this.isBeingLiquidated()) {
|
|
1998
|
+
return { canDelete: false, reason: 'is-being-liquidated' };
|
|
1999
|
+
}
|
|
2000
|
+
// Any perp positions available
|
|
2001
|
+
for (const perpPosition of userAccount.perpPositions) {
|
|
2002
|
+
if (!(0, position_1.positionIsAvailable)(perpPosition)) {
|
|
2003
|
+
return { canDelete: false, reason: 'has-perp-position' };
|
|
2004
|
+
}
|
|
2005
|
+
}
|
|
2006
|
+
// Any spot positions available
|
|
2007
|
+
for (const spotPosition of userAccount.spotPositions) {
|
|
2008
|
+
if (!(0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
|
|
2009
|
+
return { canDelete: false, reason: 'has-spot-position' };
|
|
2010
|
+
}
|
|
2011
|
+
}
|
|
2012
|
+
// No open orders
|
|
2013
|
+
for (const order of userAccount.orders) {
|
|
2014
|
+
if ((0, types_1.isVariant)(order.status, 'open')) {
|
|
2015
|
+
return { canDelete: false, reason: 'has-open-order' };
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
2018
|
+
// Fresh account (< 13 days) with init fee must be idle
|
|
2019
|
+
if (stateAccount.maxInitializeUserFee > 0) {
|
|
2020
|
+
const minActionTs = anchor_1.BN.min(userStatsAccountToUse.lastFillerVolume30DTs, anchor_1.BN.min(userStatsAccountToUse.lastMakerVolume30DTs, userStatsAccountToUse.lastTakerVolume30DTs));
|
|
2021
|
+
const estimatedAge = anchor_1.BN.max(nowInSeconds.sub(minActionTs), numericConstants_1.ZERO);
|
|
2022
|
+
if (estimatedAge.lt(new anchor_1.BN(numericConstants_1.ACCOUNT_AGE_DELETION_CUTOFF_SECONDS))) {
|
|
2023
|
+
if (!userAccount.idle) {
|
|
2024
|
+
return {
|
|
2025
|
+
canDelete: false,
|
|
2026
|
+
reason: 'is-not-idle-fresh-account',
|
|
2027
|
+
};
|
|
2028
|
+
}
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
return { canDelete: true };
|
|
2032
|
+
}
|
|
2033
|
+
getSafestTiers() {
|
|
2034
|
+
let safestPerpTier = 4;
|
|
2035
|
+
let safestSpotTier = 4;
|
|
2036
|
+
for (const perpPosition of this.getActivePerpPositions()) {
|
|
2037
|
+
safestPerpTier = Math.min(safestPerpTier, (0, tiers_1.getPerpMarketTierNumber)(this.driftClient.getPerpMarketAccount(perpPosition.marketIndex)));
|
|
2038
|
+
}
|
|
2039
|
+
for (const spotPosition of this.getActiveSpotPositions()) {
|
|
2040
|
+
if ((0, types_1.isVariant)(spotPosition.balanceType, 'deposit')) {
|
|
2041
|
+
continue;
|
|
2042
|
+
}
|
|
2043
|
+
safestSpotTier = Math.min(safestSpotTier, (0, tiers_1.getSpotMarketTierNumber)(this.driftClient.getSpotMarketAccount(spotPosition.marketIndex)));
|
|
2044
|
+
}
|
|
2045
|
+
return {
|
|
2046
|
+
perpTier: safestPerpTier,
|
|
2047
|
+
spotTier: safestSpotTier,
|
|
2048
|
+
};
|
|
2049
|
+
}
|
|
2050
|
+
getPerpPositionHealth({ marginCategory, perpPosition, oraclePriceData, quoteOraclePriceData, includeOpenOrders = true, }) {
|
|
2051
|
+
const perpMarket = this.driftClient.getPerpMarketAccount(perpPosition.marketIndex);
|
|
2052
|
+
const _oraclePriceData = oraclePriceData ||
|
|
2053
|
+
this.driftClient.getOracleDataForPerpMarket(perpMarket.marketIndex);
|
|
2054
|
+
const oraclePrice = _oraclePriceData.price;
|
|
2055
|
+
let worstCaseBaseAmount;
|
|
2056
|
+
let worstCaseLiabilityValue;
|
|
2057
|
+
if (includeOpenOrders) {
|
|
2058
|
+
const worstCaseIncludeOrders = (0, margin_1.calculateWorstCasePerpLiabilityValue)(perpPosition, perpMarket, oraclePrice);
|
|
2059
|
+
worstCaseBaseAmount = worstCaseIncludeOrders.worstCaseBaseAssetAmount;
|
|
2060
|
+
worstCaseLiabilityValue = worstCaseIncludeOrders.worstCaseLiabilityValue;
|
|
2061
|
+
}
|
|
2062
|
+
else {
|
|
2063
|
+
worstCaseBaseAmount = perpPosition.baseAssetAmount;
|
|
2064
|
+
worstCaseLiabilityValue = (0, margin_1.calculatePerpLiabilityValue)(perpPosition.baseAssetAmount, oraclePrice);
|
|
2065
|
+
}
|
|
2066
|
+
const userCustomMargin = Math.max(perpPosition.maxMarginRatio, this.getUserAccount().maxMarginRatio);
|
|
2067
|
+
const marginRatio = new anchor_1.BN((0, market_1.calculateMarketMarginRatio)(perpMarket, worstCaseBaseAmount.abs(), marginCategory, userCustomMargin));
|
|
2068
|
+
const _quoteOraclePriceData = quoteOraclePriceData ||
|
|
2069
|
+
this.driftClient.getOracleDataForSpotMarket(numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
|
|
2070
|
+
let marginRequirement = worstCaseLiabilityValue
|
|
2071
|
+
.mul(_quoteOraclePriceData.price)
|
|
2072
|
+
.div(numericConstants_1.PRICE_PRECISION)
|
|
2073
|
+
.mul(marginRatio)
|
|
2074
|
+
.div(numericConstants_1.MARGIN_PRECISION);
|
|
2075
|
+
marginRequirement = marginRequirement.add(new anchor_1.BN(perpPosition.openOrders).mul(numericConstants_1.OPEN_ORDER_MARGIN_REQUIREMENT));
|
|
2076
|
+
return {
|
|
2077
|
+
marketIndex: perpMarket.marketIndex,
|
|
2078
|
+
size: worstCaseBaseAmount,
|
|
2079
|
+
value: worstCaseLiabilityValue,
|
|
2080
|
+
weight: marginRatio,
|
|
2081
|
+
weightedValue: marginRequirement,
|
|
2082
|
+
};
|
|
2083
|
+
}
|
|
2084
|
+
getHealthComponents({ marginCategory, }) {
|
|
2085
|
+
const healthComponents = {
|
|
2086
|
+
deposits: [],
|
|
2087
|
+
borrows: [],
|
|
2088
|
+
perpPositions: [],
|
|
2089
|
+
perpPnl: [],
|
|
2090
|
+
};
|
|
2091
|
+
for (const perpPosition of this.getActivePerpPositions()) {
|
|
2092
|
+
const perpMarket = this.driftClient.getPerpMarketAccount(perpPosition.marketIndex);
|
|
2093
|
+
const oraclePriceData = this.driftClient.getOracleDataForPerpMarket(perpMarket.marketIndex);
|
|
2094
|
+
const quoteOraclePriceData = this.driftClient.getOracleDataForSpotMarket(numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
|
|
2095
|
+
healthComponents.perpPositions.push(this.getPerpPositionHealth({
|
|
2096
|
+
marginCategory,
|
|
2097
|
+
perpPosition,
|
|
2098
|
+
oraclePriceData,
|
|
2099
|
+
quoteOraclePriceData,
|
|
2100
|
+
}));
|
|
2101
|
+
const quoteSpotMarket = this.driftClient.getSpotMarketAccount(perpMarket.quoteSpotMarketIndex);
|
|
2102
|
+
const positionUnrealizedPnl = (0, position_2.calculatePositionPNL)(perpMarket, perpPosition, true, oraclePriceData);
|
|
2103
|
+
let pnlWeight;
|
|
2104
|
+
if (positionUnrealizedPnl.gt(numericConstants_1.ZERO)) {
|
|
2105
|
+
pnlWeight = (0, market_1.calculateUnrealizedAssetWeight)(perpMarket, quoteSpotMarket, positionUnrealizedPnl, marginCategory, oraclePriceData);
|
|
2106
|
+
}
|
|
2107
|
+
else {
|
|
2108
|
+
pnlWeight = numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION;
|
|
2109
|
+
}
|
|
2110
|
+
const pnlValue = positionUnrealizedPnl
|
|
2111
|
+
.mul(quoteOraclePriceData.price)
|
|
2112
|
+
.div(numericConstants_1.PRICE_PRECISION);
|
|
2113
|
+
const wegithedPnlValue = pnlValue
|
|
2114
|
+
.mul(pnlWeight)
|
|
2115
|
+
.div(numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION);
|
|
2116
|
+
healthComponents.perpPnl.push({
|
|
2117
|
+
marketIndex: perpMarket.marketIndex,
|
|
2118
|
+
size: positionUnrealizedPnl,
|
|
2119
|
+
value: pnlValue,
|
|
2120
|
+
weight: pnlWeight,
|
|
2121
|
+
weightedValue: wegithedPnlValue,
|
|
2122
|
+
});
|
|
2123
|
+
}
|
|
2124
|
+
let netQuoteValue = numericConstants_1.ZERO;
|
|
2125
|
+
for (const spotPosition of this.getActiveSpotPositions()) {
|
|
2126
|
+
const spotMarketAccount = this.driftClient.getSpotMarketAccount(spotPosition.marketIndex);
|
|
2127
|
+
const oraclePriceData = this.getOracleDataForSpotMarket(spotPosition.marketIndex);
|
|
2128
|
+
const strictOraclePrice = new strictOraclePrice_1.StrictOraclePrice(oraclePriceData.price);
|
|
2129
|
+
if (spotPosition.marketIndex === numericConstants_1.QUOTE_SPOT_MARKET_INDEX) {
|
|
2130
|
+
const tokenAmount = (0, spotBalance_1.getSignedTokenAmount)((0, spotBalance_2.getTokenAmount)(spotPosition.scaledBalance, spotMarketAccount, spotPosition.balanceType), spotPosition.balanceType);
|
|
2131
|
+
netQuoteValue = netQuoteValue.add(tokenAmount);
|
|
2132
|
+
continue;
|
|
2133
|
+
}
|
|
2134
|
+
const { tokenAmount: worstCaseTokenAmount, tokenValue: tokenValue, weight, weightedTokenValue: weightedTokenValue, ordersValue: ordersValue, } = (0, spotPosition_1.getWorstCaseTokenAmounts)(spotPosition, spotMarketAccount, strictOraclePrice, marginCategory, this.getUserAccount().maxMarginRatio);
|
|
2135
|
+
netQuoteValue = netQuoteValue.add(ordersValue);
|
|
2136
|
+
const baseAssetValue = tokenValue.abs();
|
|
2137
|
+
const weightedValue = weightedTokenValue.abs();
|
|
2138
|
+
if (weightedTokenValue.lt(numericConstants_1.ZERO)) {
|
|
2139
|
+
healthComponents.borrows.push({
|
|
2140
|
+
marketIndex: spotMarketAccount.marketIndex,
|
|
2141
|
+
size: worstCaseTokenAmount,
|
|
2142
|
+
value: baseAssetValue,
|
|
2143
|
+
weight: weight,
|
|
2144
|
+
weightedValue: weightedValue,
|
|
2145
|
+
});
|
|
2146
|
+
}
|
|
2147
|
+
else {
|
|
2148
|
+
healthComponents.deposits.push({
|
|
2149
|
+
marketIndex: spotMarketAccount.marketIndex,
|
|
2150
|
+
size: worstCaseTokenAmount,
|
|
2151
|
+
value: baseAssetValue,
|
|
2152
|
+
weight: weight,
|
|
2153
|
+
weightedValue: weightedValue,
|
|
2154
|
+
});
|
|
2155
|
+
}
|
|
2156
|
+
}
|
|
2157
|
+
if (!netQuoteValue.eq(numericConstants_1.ZERO)) {
|
|
2158
|
+
const spotMarketAccount = this.driftClient.getQuoteSpotMarketAccount();
|
|
2159
|
+
const oraclePriceData = this.getOracleDataForSpotMarket(numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
|
|
2160
|
+
const baseAssetValue = (0, spotBalance_1.getTokenValue)(netQuoteValue, spotMarketAccount.decimals, oraclePriceData);
|
|
2161
|
+
const { weight, weightedTokenValue } = (0, spotPosition_1.calculateWeightedTokenValue)(netQuoteValue, baseAssetValue, oraclePriceData.price, spotMarketAccount, marginCategory, this.getUserAccount().maxMarginRatio);
|
|
2162
|
+
if (netQuoteValue.lt(numericConstants_1.ZERO)) {
|
|
2163
|
+
healthComponents.borrows.push({
|
|
2164
|
+
marketIndex: spotMarketAccount.marketIndex,
|
|
2165
|
+
size: netQuoteValue,
|
|
2166
|
+
value: baseAssetValue.abs(),
|
|
2167
|
+
weight: weight,
|
|
2168
|
+
weightedValue: weightedTokenValue.abs(),
|
|
2169
|
+
});
|
|
2170
|
+
}
|
|
2171
|
+
else {
|
|
2172
|
+
healthComponents.deposits.push({
|
|
2173
|
+
marketIndex: spotMarketAccount.marketIndex,
|
|
2174
|
+
size: netQuoteValue,
|
|
2175
|
+
value: baseAssetValue,
|
|
2176
|
+
weight: weight,
|
|
2177
|
+
weightedValue: weightedTokenValue,
|
|
2178
|
+
});
|
|
2179
|
+
}
|
|
2180
|
+
}
|
|
2181
|
+
return healthComponents;
|
|
2182
|
+
}
|
|
2183
|
+
/**
|
|
2184
|
+
* Get the total position value, excluding any position coming from the given target market
|
|
2185
|
+
* @param marketToIgnore
|
|
2186
|
+
* @returns positionValue : Precision QUOTE_PRECISION
|
|
2187
|
+
*/
|
|
2188
|
+
getTotalPerpPositionValueExcludingMarket(marketToIgnore, marginCategory, liquidationBuffer, includeOpenOrders) {
|
|
2189
|
+
const currentPerpPosition = this.getPerpPositionOrEmpty(marketToIgnore);
|
|
2190
|
+
const oracleData = this.getOracleDataForPerpMarket(marketToIgnore);
|
|
2191
|
+
let currentPerpPositionValueUSDC = numericConstants_1.ZERO;
|
|
2192
|
+
if (currentPerpPosition) {
|
|
2193
|
+
currentPerpPositionValueUSDC = this.getPerpLiabilityValue(marketToIgnore, oracleData, includeOpenOrders);
|
|
2194
|
+
}
|
|
2195
|
+
return this.getTotalPerpPositionLiability(marginCategory, liquidationBuffer, includeOpenOrders).sub(currentPerpPositionValueUSDC);
|
|
2196
|
+
}
|
|
2197
|
+
getMMOracleDataForPerpMarket(marketIndex) {
|
|
2198
|
+
return this.driftClient.getMMOracleDataForPerpMarket(marketIndex);
|
|
2199
|
+
}
|
|
2200
|
+
getOracleDataForPerpMarket(marketIndex) {
|
|
2201
|
+
return this.driftClient.getOracleDataForPerpMarket(marketIndex);
|
|
2202
|
+
}
|
|
2203
|
+
getOracleDataForSpotMarket(marketIndex) {
|
|
2204
|
+
return this.driftClient.getOracleDataForSpotMarket(marketIndex);
|
|
2205
|
+
}
|
|
2206
|
+
/**
|
|
2207
|
+
* Get the active perp and spot positions of the user.
|
|
2208
|
+
*/
|
|
2209
|
+
getActivePositions() {
|
|
2210
|
+
const activePerpMarkets = this.getActivePerpPositions().map((position) => position.marketIndex);
|
|
2211
|
+
const activeSpotMarkets = this.getActiveSpotPositions().map((position) => position.marketIndex);
|
|
2212
|
+
return {
|
|
2213
|
+
activePerpPositions: activePerpMarkets,
|
|
2214
|
+
activeSpotPositions: activeSpotMarkets,
|
|
2215
|
+
};
|
|
2216
|
+
}
|
|
2217
|
+
/**
|
|
2218
|
+
* Compute the full margin calculation for the user's account.
|
|
2219
|
+
* Prioritize using this function instead of calling getMarginRequirement or getTotalCollateral multiple times.
|
|
2220
|
+
* Consumers can use this to avoid duplicating work across separate calls.
|
|
2221
|
+
*/
|
|
2222
|
+
getMarginCalculation(marginCategory = 'Initial', opts) {
|
|
2223
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
|
|
2224
|
+
const strict = (_a = opts === null || opts === void 0 ? void 0 : opts.strict) !== null && _a !== void 0 ? _a : false;
|
|
2225
|
+
const liquidationBufferMap = (_b = opts === null || opts === void 0 ? void 0 : opts.liquidationBufferMap) !== null && _b !== void 0 ? _b : new Map();
|
|
2226
|
+
const includeOpenOrders = (_c = opts === null || opts === void 0 ? void 0 : opts.includeOpenOrders) !== null && _c !== void 0 ? _c : true;
|
|
2227
|
+
// Equivalent to on-chain user_custom_margin_ratio
|
|
2228
|
+
const userCustomMarginRatio = marginCategory === 'Initial' ? this.getUserAccount().maxMarginRatio : 0;
|
|
2229
|
+
// Initialize calc via JS mirror of Rust/on-chain MarginCalculation
|
|
2230
|
+
const isolatedMarginBuffers = new Map();
|
|
2231
|
+
for (const [marketIndex, isolatedMarginBuffer,] of (_d = opts === null || opts === void 0 ? void 0 : opts.liquidationBufferMap) !== null && _d !== void 0 ? _d : new Map()) {
|
|
2232
|
+
if (marketIndex !== 'cross') {
|
|
2233
|
+
isolatedMarginBuffers.set(marketIndex, isolatedMarginBuffer);
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
const ctx = marginCalculation_1.MarginContext.standard(marginCategory)
|
|
2237
|
+
.strictMode(strict)
|
|
2238
|
+
.setCrossMarginBuffer((_f = (_e = opts === null || opts === void 0 ? void 0 : opts.liquidationBufferMap) === null || _e === void 0 ? void 0 : _e.get('cross')) !== null && _f !== void 0 ? _f : numericConstants_1.ZERO)
|
|
2239
|
+
.setIsolatedMarginBuffers(isolatedMarginBuffers);
|
|
2240
|
+
const calc = new marginCalculation_1.MarginCalculation(ctx);
|
|
2241
|
+
// SPOT POSITIONS
|
|
2242
|
+
for (const spotPosition of this.getUserAccount().spotPositions) {
|
|
2243
|
+
if ((0, spotPosition_1.isSpotPositionAvailable)(spotPosition))
|
|
2244
|
+
continue;
|
|
2245
|
+
const isQuote = spotPosition.marketIndex === numericConstants_1.QUOTE_SPOT_MARKET_INDEX;
|
|
2246
|
+
const spotMarket = this.driftClient.getSpotMarketAccount(spotPosition.marketIndex);
|
|
2247
|
+
const oraclePriceData = this.getOracleDataForSpotMarket(spotPosition.marketIndex);
|
|
2248
|
+
const twap5 = strict
|
|
2249
|
+
? (0, oracles_1.calculateLiveOracleTwap)(spotMarket.historicalOracleData, oraclePriceData, new anchor_1.BN(Math.floor(Date.now() / 1000)), numericConstants_1.FIVE_MINUTE)
|
|
2250
|
+
: undefined;
|
|
2251
|
+
const strictOracle = new strictOraclePrice_1.StrictOraclePrice(oraclePriceData.price, twap5);
|
|
2252
|
+
if (isQuote) {
|
|
2253
|
+
const tokenAmount = (0, spotBalance_1.getSignedTokenAmount)((0, spotBalance_2.getTokenAmount)(spotPosition.scaledBalance, spotMarket, spotPosition.balanceType), spotPosition.balanceType);
|
|
2254
|
+
if ((0, types_1.isVariant)(spotPosition.balanceType, 'deposit')) {
|
|
2255
|
+
// add deposit value to total collateral
|
|
2256
|
+
const weightedTokenValue = this.getSpotAssetValue(tokenAmount, strictOracle, spotMarket, marginCategory);
|
|
2257
|
+
calc.addCrossMarginTotalCollateral(weightedTokenValue);
|
|
2258
|
+
}
|
|
2259
|
+
else {
|
|
2260
|
+
// borrow on quote contributes to margin requirement
|
|
2261
|
+
const tokenValueAbs = this.getSpotLiabilityValue(tokenAmount, strictOracle, spotMarket, marginCategory, (_g = liquidationBufferMap.get('cross')) !== null && _g !== void 0 ? _g : new anchor_1.BN(0)).abs();
|
|
2262
|
+
calc.addCrossMarginRequirement(tokenValueAbs, tokenValueAbs);
|
|
2263
|
+
}
|
|
2264
|
+
continue;
|
|
2265
|
+
}
|
|
2266
|
+
// Non-quote spot: worst-case simulation
|
|
2267
|
+
const { tokenAmount: worstCaseTokenAmount, ordersValue: worstCaseOrdersValue, } = (0, spotPosition_1.getWorstCaseTokenAmounts)(spotPosition, spotMarket, strictOracle, marginCategory, userCustomMarginRatio, includeOpenOrders
|
|
2268
|
+
// false
|
|
2269
|
+
);
|
|
2270
|
+
if (includeOpenOrders) {
|
|
2271
|
+
// open order IM
|
|
2272
|
+
calc.addCrossMarginRequirement(new anchor_1.BN(spotPosition.openOrders).mul(numericConstants_1.OPEN_ORDER_MARGIN_REQUIREMENT), numericConstants_1.ZERO);
|
|
2273
|
+
}
|
|
2274
|
+
if (worstCaseTokenAmount.gt(numericConstants_1.ZERO)) {
|
|
2275
|
+
const baseAssetValue = this.getSpotAssetValue(worstCaseTokenAmount, strictOracle, spotMarket, marginCategory);
|
|
2276
|
+
// asset side increases total collateral (weighted)
|
|
2277
|
+
calc.addCrossMarginTotalCollateral(baseAssetValue);
|
|
2278
|
+
}
|
|
2279
|
+
else if (worstCaseTokenAmount.lt(numericConstants_1.ZERO)) {
|
|
2280
|
+
// liability side increases margin requirement (weighted >= abs(token_value))
|
|
2281
|
+
const getSpotLiabilityValue = this.getSpotLiabilityValue(worstCaseTokenAmount, strictOracle, spotMarket, marginCategory, liquidationBufferMap.get('cross'));
|
|
2282
|
+
calc.addCrossMarginRequirement(getSpotLiabilityValue.abs(), getSpotLiabilityValue.abs());
|
|
2283
|
+
}
|
|
2284
|
+
// orders value contributes to collateral or requirement
|
|
2285
|
+
if (worstCaseOrdersValue.gt(numericConstants_1.ZERO)) {
|
|
2286
|
+
calc.addCrossMarginTotalCollateral(worstCaseOrdersValue);
|
|
2287
|
+
}
|
|
2288
|
+
else if (worstCaseOrdersValue.lt(numericConstants_1.ZERO)) {
|
|
2289
|
+
const absVal = worstCaseOrdersValue.abs();
|
|
2290
|
+
calc.addCrossMarginRequirement(absVal, absVal);
|
|
2291
|
+
}
|
|
2292
|
+
}
|
|
2293
|
+
// PERP POSITIONS
|
|
2294
|
+
for (const marketPosition of this.getActivePerpPositions()) {
|
|
2295
|
+
const market = this.driftClient.getPerpMarketAccount(marketPosition.marketIndex);
|
|
2296
|
+
const quoteSpotMarket = this.driftClient.getSpotMarketAccount(market.quoteSpotMarketIndex);
|
|
2297
|
+
const quoteOraclePriceData = this.getOracleDataForSpotMarket(market.quoteSpotMarketIndex);
|
|
2298
|
+
const oraclePriceData = this.getMMOracleDataForPerpMarket(market.marketIndex);
|
|
2299
|
+
const nonMmmOraclePriceData = this.getOracleDataForPerpMarket(market.marketIndex);
|
|
2300
|
+
// Worst-case perp liability and weighted pnl
|
|
2301
|
+
const { worstCaseBaseAssetAmount, worstCaseLiabilityValue } = (0, margin_1.calculateWorstCasePerpLiabilityValue)(marketPosition, market, nonMmmOraclePriceData.price, includeOpenOrders);
|
|
2302
|
+
// margin ratio for this perp
|
|
2303
|
+
const customMarginRatio = Math.max(userCustomMarginRatio, marketPosition.maxMarginRatio);
|
|
2304
|
+
let marginRatio = new anchor_1.BN((0, market_1.calculateMarketMarginRatio)(market, worstCaseBaseAssetAmount.abs(), marginCategory, customMarginRatio));
|
|
2305
|
+
if ((0, types_1.isVariant)(market.status, 'settlement')) {
|
|
2306
|
+
marginRatio = numericConstants_1.ZERO;
|
|
2307
|
+
}
|
|
2308
|
+
// convert liability to quote value and apply margin ratio
|
|
2309
|
+
const quotePrice = strict
|
|
2310
|
+
? anchor_1.BN.max(quoteOraclePriceData.price, quoteSpotMarket.historicalOracleData.lastOraclePriceTwap5Min)
|
|
2311
|
+
: quoteOraclePriceData.price;
|
|
2312
|
+
let perpMarginRequirement = worstCaseLiabilityValue
|
|
2313
|
+
.mul(quotePrice)
|
|
2314
|
+
.div(numericConstants_1.PRICE_PRECISION)
|
|
2315
|
+
.mul(marginRatio)
|
|
2316
|
+
.div(numericConstants_1.MARGIN_PRECISION);
|
|
2317
|
+
// add open orders IM
|
|
2318
|
+
if (includeOpenOrders) {
|
|
2319
|
+
perpMarginRequirement = perpMarginRequirement.add(new anchor_1.BN(marketPosition.openOrders).mul(numericConstants_1.OPEN_ORDER_MARGIN_REQUIREMENT));
|
|
2320
|
+
}
|
|
2321
|
+
// weighted unrealized pnl
|
|
2322
|
+
let positionUnrealizedPnl = (0, position_2.calculatePositionPNL)(market, marketPosition, true, oraclePriceData);
|
|
2323
|
+
let pnlQuotePrice;
|
|
2324
|
+
if (strict && positionUnrealizedPnl.gt(numericConstants_1.ZERO)) {
|
|
2325
|
+
pnlQuotePrice = anchor_1.BN.min(quoteOraclePriceData.price, quoteSpotMarket.historicalOracleData.lastOraclePriceTwap5Min);
|
|
2326
|
+
}
|
|
2327
|
+
else if (strict && positionUnrealizedPnl.lt(numericConstants_1.ZERO)) {
|
|
2328
|
+
pnlQuotePrice = anchor_1.BN.max(quoteOraclePriceData.price, quoteSpotMarket.historicalOracleData.lastOraclePriceTwap5Min);
|
|
2329
|
+
}
|
|
2330
|
+
else {
|
|
2331
|
+
pnlQuotePrice = quoteOraclePriceData.price;
|
|
2332
|
+
}
|
|
2333
|
+
positionUnrealizedPnl = positionUnrealizedPnl
|
|
2334
|
+
.mul(pnlQuotePrice)
|
|
2335
|
+
.div(numericConstants_1.PRICE_PRECISION);
|
|
2336
|
+
if (marginCategory !== undefined) {
|
|
2337
|
+
if (positionUnrealizedPnl.gt(numericConstants_1.ZERO)) {
|
|
2338
|
+
positionUnrealizedPnl = positionUnrealizedPnl
|
|
2339
|
+
.mul((0, market_1.calculateUnrealizedAssetWeight)(market, quoteSpotMarket, positionUnrealizedPnl, marginCategory, oraclePriceData))
|
|
2340
|
+
.div(new anchor_1.BN(numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION));
|
|
2341
|
+
}
|
|
2342
|
+
}
|
|
2343
|
+
// Add perp contribution: isolated vs cross
|
|
2344
|
+
const isIsolated = this.isPerpPositionIsolated(marketPosition);
|
|
2345
|
+
if (isIsolated) {
|
|
2346
|
+
// derive isolated quote deposit value, mirroring on-chain logic
|
|
2347
|
+
let depositValue = numericConstants_1.ZERO;
|
|
2348
|
+
if ((_h = marketPosition.isolatedPositionScaledBalance) === null || _h === void 0 ? void 0 : _h.gt(numericConstants_1.ZERO)) {
|
|
2349
|
+
const quoteSpotMarket = this.driftClient.getSpotMarketAccount(market.quoteSpotMarketIndex);
|
|
2350
|
+
const quoteOraclePriceData = this.getOracleDataForSpotMarket(market.quoteSpotMarketIndex);
|
|
2351
|
+
const strictQuote = new strictOraclePrice_1.StrictOraclePrice(quoteOraclePriceData.price, strict
|
|
2352
|
+
? quoteSpotMarket.historicalOracleData.lastOraclePriceTwap5Min
|
|
2353
|
+
: undefined);
|
|
2354
|
+
const quoteTokenAmount = (0, spotBalance_2.getTokenAmount)((_j = marketPosition.isolatedPositionScaledBalance) !== null && _j !== void 0 ? _j : numericConstants_1.ZERO, quoteSpotMarket, types_2.SpotBalanceType.DEPOSIT);
|
|
2355
|
+
depositValue = (0, spotBalance_1.getStrictTokenValue)(quoteTokenAmount, quoteSpotMarket.decimals, strictQuote);
|
|
2356
|
+
}
|
|
2357
|
+
calc.addIsolatedMarginCalculation(market.marketIndex, depositValue, positionUnrealizedPnl, worstCaseLiabilityValue, perpMarginRequirement);
|
|
2358
|
+
calc.addPerpLiabilityValue(worstCaseLiabilityValue);
|
|
2359
|
+
}
|
|
2360
|
+
else {
|
|
2361
|
+
// cross: add to global requirement and collateral
|
|
2362
|
+
calc.addCrossMarginRequirement(perpMarginRequirement, worstCaseLiabilityValue);
|
|
2363
|
+
calc.addCrossMarginTotalCollateral(positionUnrealizedPnl);
|
|
2364
|
+
}
|
|
2365
|
+
}
|
|
2366
|
+
return calc;
|
|
2367
|
+
}
|
|
2368
|
+
isPerpPositionIsolated(perpPosition) {
|
|
2369
|
+
return (perpPosition.positionFlag & types_2.PositionFlag.IsolatedPosition) !== 0;
|
|
2370
|
+
}
|
|
2371
|
+
}
|
|
2372
|
+
exports.User = User;
|