@drift-labs/sdk-browser 2.104.0-beta.21
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/README.md +276 -0
- package/VERSION +1 -0
- package/bun.lockb +0 -0
- package/get_events.ts +47 -0
- package/lib/browser/accounts/basicUserAccountSubscriber.d.ts +27 -0
- package/lib/browser/accounts/basicUserAccountSubscriber.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/fetch.d.ts +6 -0
- package/lib/browser/accounts/fetch.js +30 -0
- package/lib/browser/accounts/grpcAccountSubscriber.d.ts +16 -0
- package/lib/browser/accounts/grpcAccountSubscriber.js +154 -0
- package/lib/browser/accounts/grpcDriftClientAccountSubscriber.d.ts +12 -0
- package/lib/browser/accounts/grpcDriftClientAccountSubscriber.js +98 -0
- package/lib/browser/accounts/grpcInsuranceFundStakeAccountSubscriber.d.ts +10 -0
- package/lib/browser/accounts/grpcInsuranceFundStakeAccountSubscriber.js +30 -0
- package/lib/browser/accounts/grpcProgramAccountSubscriber.d.ts +18 -0
- package/lib/browser/accounts/grpcProgramAccountSubscriber.js +171 -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/oneShotUserAccountSubscriber.d.ts +18 -0
- package/lib/browser/accounts/oneShotUserAccountSubscriber.js +48 -0
- package/lib/browser/accounts/pollingDriftClientAccountSubscriber.d.ts +69 -0
- package/lib/browser/accounts/pollingDriftClientAccountSubscriber.js +418 -0
- package/lib/browser/accounts/pollingHighLeverageModeConfigAccountSubscriber.d.ts +29 -0
- package/lib/browser/accounts/pollingHighLeverageModeConfigAccountSubscriber.js +111 -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/testBulkAccountLoader.d.ts +4 -0
- package/lib/browser/accounts/testBulkAccountLoader.js +45 -0
- package/lib/browser/accounts/types.d.ts +168 -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 +149 -0
- package/lib/browser/accounts/webSocketDriftClientAccountSubscriber.d.ts +66 -0
- package/lib/browser/accounts/webSocketDriftClientAccountSubscriber.js +358 -0
- package/lib/browser/accounts/webSocketHighLeverageModeConfigAccountSubscriber.d.ts +23 -0
- package/lib/browser/accounts/webSocketHighLeverageModeConfigAccountSubscriber.js +69 -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 +32 -0
- package/lib/browser/accounts/webSocketProgramAccountSubscriber.js +120 -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/addresses/marketAddresses.d.ts +2 -0
- package/lib/browser/addresses/marketAddresses.js +15 -0
- package/lib/browser/addresses/pda.d.ts +32 -0
- package/lib/browser/addresses/pda.js +211 -0
- package/lib/browser/adminClient.d.ts +206 -0
- package/lib/browser/adminClient.js +1858 -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 +75 -0
- package/lib/browser/bankrun/bankrunConnection.js +332 -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 +60 -0
- package/lib/browser/config.js +130 -0
- package/lib/browser/constants/numericConstants.d.ts +71 -0
- package/lib/browser/constants/numericConstants.js +75 -0
- package/lib/browser/constants/perpMarkets.d.ts +19 -0
- package/lib/browser/constants/perpMarkets.js +997 -0
- package/lib/browser/constants/spotMarkets.d.ts +24 -0
- package/lib/browser/constants/spotMarkets.js +470 -0
- package/lib/browser/constants/txConstants.d.ts +1 -0
- package/lib/browser/constants/txConstants.js +4 -0
- package/lib/browser/decode/phoenix.d.ts +7 -0
- package/lib/browser/decode/phoenix.js +159 -0
- package/lib/browser/decode/user.d.ts +4 -0
- package/lib/browser/decode/user.js +339 -0
- package/lib/browser/dlob/DLOB.d.ts +186 -0
- package/lib/browser/dlob/DLOB.js +1039 -0
- package/lib/browser/dlob/DLOBNode.d.ts +68 -0
- package/lib/browser/dlob/DLOBNode.js +100 -0
- package/lib/browser/dlob/DLOBSubscriber.d.ts +54 -0
- package/lib/browser/dlob/DLOBSubscriber.js +139 -0
- package/lib/browser/dlob/NodeList.d.ts +25 -0
- package/lib/browser/dlob/NodeList.js +126 -0
- package/lib/browser/dlob/orderBookLevels.d.ts +72 -0
- package/lib/browser/dlob/orderBookLevels.js +438 -0
- package/lib/browser/dlob/types.d.ts +18 -0
- package/lib/browser/dlob/types.js +2 -0
- package/lib/browser/driftClient.d.ts +861 -0
- package/lib/browser/driftClient.js +4768 -0
- package/lib/browser/driftClientConfig.d.ts +49 -0
- package/lib/browser/driftClientConfig.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 +46 -0
- package/lib/browser/events/eventSubscriber.js +223 -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 +6 -0
- package/lib/browser/events/parse.js +106 -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 +79 -0
- package/lib/browser/events/types.js +32 -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 +457 -0
- package/lib/browser/factory/oracleClient.d.ts +5 -0
- package/lib/browser/factory/oracleClient.js +56 -0
- package/lib/browser/idl/drift.json +14440 -0
- package/lib/browser/idl/openbook.json +3854 -0
- package/lib/browser/idl/pyth_solana_receiver.json +628 -0
- package/lib/browser/idl/switchboard.json +8354 -0
- package/lib/browser/idl/switchboard_on_demand_30.json +4546 -0
- package/lib/browser/idl/token_faucet.json +142 -0
- package/lib/browser/index.d.ts +125 -0
- package/lib/browser/index.js +147 -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 +302 -0
- package/lib/browser/jupiter/jupiterClient.js +178 -0
- package/lib/browser/keypair.d.ts +2 -0
- package/lib/browser/keypair.js +28 -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 +626 -0
- package/lib/browser/math/auction.d.ts +23 -0
- package/lib/browser/math/auction.js +130 -0
- package/lib/browser/math/bankruptcy.d.ts +2 -0
- package/lib/browser/math/bankruptcy.js +31 -0
- package/lib/browser/math/conversion.d.ts +2 -0
- package/lib/browser/math/conversion.js +11 -0
- package/lib/browser/math/exchangeStatus.d.ts +6 -0
- package/lib/browser/math/exchangeStatus.js +77 -0
- package/lib/browser/math/fuel.d.ts +6 -0
- package/lib/browser/math/fuel.js +55 -0
- package/lib/browser/math/funding.d.ts +34 -0
- package/lib/browser/math/funding.js +209 -0
- package/lib/browser/math/insurance.d.ts +7 -0
- package/lib/browser/math/insurance.js +73 -0
- package/lib/browser/math/margin.d.ts +39 -0
- package/lib/browser/math/margin.js +184 -0
- package/lib/browser/math/market.d.ts +39 -0
- package/lib/browser/math/market.js +163 -0
- package/lib/browser/math/oracles.d.ts +14 -0
- package/lib/browser/math/oracles.js +134 -0
- package/lib/browser/math/orders.d.ts +23 -0
- package/lib/browser/math/orders.js +216 -0
- package/lib/browser/math/position.d.ts +70 -0
- package/lib/browser/math/position.js +225 -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 +83 -0
- package/lib/browser/math/spotBalance.js +373 -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 +78 -0
- package/lib/browser/math/state.d.ts +5 -0
- package/lib/browser/math/state.js +30 -0
- package/lib/browser/math/superStake.d.ts +167 -0
- package/lib/browser/math/superStake.js +306 -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 +117 -0
- package/lib/browser/math/trade.js +637 -0
- package/lib/browser/math/userStatus.d.ts +2 -0
- package/lib/browser/math/userStatus.js +8 -0
- package/lib/browser/math/utils.d.ts +23 -0
- package/lib/browser/math/utils.js +112 -0
- package/lib/browser/memcmp.d.ts +11 -0
- package/lib/browser/memcmp.js +99 -0
- package/lib/browser/openbook/openbookV2FulfillmentConfigMap.d.ts +10 -0
- package/lib/browser/openbook/openbookV2FulfillmentConfigMap.js +17 -0
- package/lib/browser/openbook/openbookV2Subscriber.d.ts +36 -0
- package/lib/browser/openbook/openbookV2Subscriber.js +104 -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 +4 -0
- package/lib/browser/oracles/oracleId.js +38 -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/pythPullClient.d.ts +19 -0
- package/lib/browser/oracles/pythPullClient.js +60 -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/switchboardClient.d.ts +12 -0
- package/lib/browser/oracles/switchboardClient.js +40 -0
- package/lib/browser/oracles/switchboardOnDemandClient.d.ts +12 -0
- package/lib/browser/oracles/switchboardOnDemandClient.js +32 -0
- package/lib/browser/oracles/types.d.ts +23 -0
- package/lib/browser/oracles/types.js +2 -0
- package/lib/browser/orderParams.d.ts +29 -0
- package/lib/browser/orderParams.js +44 -0
- package/lib/browser/orderSubscriber/OrderSubscriber.d.ts +42 -0
- package/lib/browser/orderSubscriber/OrderSubscriber.js +172 -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 +66 -0
- package/lib/browser/orderSubscriber/index.d.ts +2 -0
- package/lib/browser/orderSubscriber/index.js +18 -0
- package/lib/browser/orderSubscriber/types.d.ts +34 -0
- package/lib/browser/orderSubscriber/types.js +2 -0
- package/lib/browser/phoenix/phoenixFulfillmentConfigMap.d.ts +10 -0
- package/lib/browser/phoenix/phoenixFulfillmentConfigMap.js +17 -0
- package/lib/browser/phoenix/phoenixSubscriber.d.ts +41 -0
- package/lib/browser/phoenix/phoenixSubscriber.js +152 -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/driftPriorityFeeMethod.d.ts +13 -0
- package/lib/browser/priorityFee/driftPriorityFeeMethod.js +26 -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 +11 -0
- package/lib/browser/priorityFee/index.js +27 -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 +46 -0
- package/lib/browser/priorityFee/priorityFeeSubscriber.js +188 -0
- package/lib/browser/priorityFee/priorityFeeSubscriberMap.d.ts +48 -0
- package/lib/browser/priorityFee/priorityFeeSubscriberMap.js +88 -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 +31 -0
- package/lib/browser/priorityFee/types.js +10 -0
- package/lib/browser/serum/serumFulfillmentConfigMap.d.ts +10 -0
- package/lib/browser/serum/serumFulfillmentConfigMap.js +17 -0
- package/lib/browser/serum/serumSubscriber.d.ts +32 -0
- package/lib/browser/serum/serumSubscriber.js +107 -0
- package/lib/browser/serum/types.d.ts +13 -0
- package/lib/browser/serum/types.js +2 -0
- package/lib/browser/slot/SlotSubscriber.d.ts +27 -0
- package/lib/browser/slot/SlotSubscriber.js +71 -0
- package/lib/browser/slot/SlothashSubscriber.d.ts +26 -0
- package/lib/browser/slot/SlothashSubscriber.js +85 -0
- package/lib/browser/testClient.d.ts +8 -0
- package/lib/browser/testClient.js +23 -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 +294 -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 +154 -0
- package/lib/browser/tx/txHandler.js +453 -0
- package/lib/browser/tx/txParamProcessor.d.ts +25 -0
- package/lib/browser/tx/txParamProcessor.js +88 -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 +2 -0
- package/lib/browser/tx/utils.js +10 -0
- package/lib/browser/tx/whileValidTxSender.d.ts +45 -0
- package/lib/browser/tx/whileValidTxSender.js +167 -0
- package/lib/browser/types.d.ts +1385 -0
- package/lib/browser/types.js +366 -0
- package/lib/browser/user.d.ts +411 -0
- package/lib/browser/user.js +2151 -0
- package/lib/browser/userConfig.d.ts +26 -0
- package/lib/browser/userConfig.js +2 -0
- package/lib/browser/userMap/PollingSubscription.d.ts +16 -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 +181 -0
- package/lib/browser/userMap/userMap.d.ts +90 -0
- package/lib/browser/userMap/userMap.js +467 -0
- package/lib/browser/userMap/userMapConfig.d.ts +39 -0
- package/lib/browser/userMap/userMapConfig.js +2 -0
- package/lib/browser/userMap/userStatsMap.d.ts +46 -0
- package/lib/browser/userMap/userStatsMap.js +165 -0
- package/lib/browser/userName.d.ts +5 -0
- package/lib/browser/userName.js +21 -0
- package/lib/browser/userStats.d.ts +22 -0
- package/lib/browser/userStats.js +91 -0
- package/lib/browser/userStatsConfig.d.ts +25 -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 +4 -0
- package/lib/browser/util/digest.js +14 -0
- package/lib/browser/util/promiseTimeout.d.ts +1 -0
- package/lib/browser/util/promiseTimeout.js +14 -0
- package/lib/browser/util/pythOracleUtils.d.ts +17 -0
- package/lib/browser/util/pythOracleUtils.js +107 -0
- package/lib/browser/util/tps.d.ts +2 -0
- package/lib/browser/util/tps.js +16 -0
- package/lib/browser/wallet.d.ts +11 -0
- package/lib/browser/wallet.js +32 -0
- package/lib/node/accounts/basicUserAccountSubscriber.d.ts +27 -0
- package/lib/node/accounts/basicUserAccountSubscriber.js +38 -0
- package/lib/node/accounts/bulkAccountLoader.d.ts +37 -0
- package/lib/node/accounts/bulkAccountLoader.js +222 -0
- package/lib/node/accounts/bulkUserStatsSubscription.d.ts +7 -0
- package/lib/node/accounts/bulkUserStatsSubscription.js +21 -0
- package/lib/node/accounts/bulkUserSubscription.d.ts +7 -0
- package/lib/node/accounts/bulkUserSubscription.js +21 -0
- package/lib/node/accounts/fetch.d.ts +6 -0
- package/lib/node/accounts/fetch.js +30 -0
- package/lib/node/accounts/grpcAccountSubscriber.d.ts +16 -0
- package/lib/node/accounts/grpcAccountSubscriber.js +154 -0
- package/lib/node/accounts/grpcDriftClientAccountSubscriber.d.ts +12 -0
- package/lib/node/accounts/grpcDriftClientAccountSubscriber.js +98 -0
- package/lib/node/accounts/grpcInsuranceFundStakeAccountSubscriber.d.ts +10 -0
- package/lib/node/accounts/grpcInsuranceFundStakeAccountSubscriber.js +30 -0
- package/lib/node/accounts/grpcProgramAccountSubscriber.d.ts +18 -0
- package/lib/node/accounts/grpcProgramAccountSubscriber.js +171 -0
- package/lib/node/accounts/grpcUserAccountSubscriber.d.ts +10 -0
- package/lib/node/accounts/grpcUserAccountSubscriber.js +28 -0
- package/lib/node/accounts/grpcUserStatsAccountSubscriber.d.ts +10 -0
- package/lib/node/accounts/grpcUserStatsAccountSubscriber.js +28 -0
- package/lib/node/accounts/oneShotUserAccountSubscriber.d.ts +18 -0
- package/lib/node/accounts/oneShotUserAccountSubscriber.js +48 -0
- package/lib/node/accounts/pollingDriftClientAccountSubscriber.d.ts +69 -0
- package/lib/node/accounts/pollingDriftClientAccountSubscriber.js +418 -0
- package/lib/node/accounts/pollingHighLeverageModeConfigAccountSubscriber.d.ts +29 -0
- package/lib/node/accounts/pollingHighLeverageModeConfigAccountSubscriber.js +111 -0
- package/lib/node/accounts/pollingInsuranceFundStakeAccountSubscriber.d.ts +29 -0
- package/lib/node/accounts/pollingInsuranceFundStakeAccountSubscriber.js +110 -0
- package/lib/node/accounts/pollingOracleAccountSubscriber.d.ts +27 -0
- package/lib/node/accounts/pollingOracleAccountSubscriber.js +78 -0
- package/lib/node/accounts/pollingTokenAccountSubscriber.d.ts +26 -0
- package/lib/node/accounts/pollingTokenAccountSubscriber.js +78 -0
- package/lib/node/accounts/pollingUserAccountSubscriber.d.ts +29 -0
- package/lib/node/accounts/pollingUserAccountSubscriber.js +102 -0
- package/lib/node/accounts/pollingUserStatsAccountSubscriber.d.ts +27 -0
- package/lib/node/accounts/pollingUserStatsAccountSubscriber.js +94 -0
- package/lib/node/accounts/testBulkAccountLoader.d.ts +4 -0
- package/lib/node/accounts/testBulkAccountLoader.js +45 -0
- package/lib/node/accounts/types.d.ts +168 -0
- package/lib/node/accounts/types.js +16 -0
- package/lib/node/accounts/utils.d.ts +8 -0
- package/lib/node/accounts/utils.js +49 -0
- package/lib/node/accounts/webSocketAccountSubscriber.d.ts +29 -0
- package/lib/node/accounts/webSocketAccountSubscriber.js +149 -0
- package/lib/node/accounts/webSocketDriftClientAccountSubscriber.d.ts +66 -0
- package/lib/node/accounts/webSocketDriftClientAccountSubscriber.js +358 -0
- package/lib/node/accounts/webSocketHighLeverageModeConfigAccountSubscriber.d.ts +23 -0
- package/lib/node/accounts/webSocketHighLeverageModeConfigAccountSubscriber.js +69 -0
- package/lib/node/accounts/webSocketInsuranceFundStakeAccountSubscriber.d.ts +23 -0
- package/lib/node/accounts/webSocketInsuranceFundStakeAccountSubscriber.js +67 -0
- package/lib/node/accounts/webSocketProgramAccountSubscriber.d.ts +32 -0
- package/lib/node/accounts/webSocketProgramAccountSubscriber.js +120 -0
- package/lib/node/accounts/webSocketUserAccountSubscriber.d.ts +23 -0
- package/lib/node/accounts/webSocketUserAccountSubscriber.js +61 -0
- package/lib/node/accounts/webSocketUserStatsAccountSubsriber.d.ts +22 -0
- package/lib/node/accounts/webSocketUserStatsAccountSubsriber.js +52 -0
- package/lib/node/addresses/marketAddresses.d.ts +2 -0
- package/lib/node/addresses/marketAddresses.js +15 -0
- package/lib/node/addresses/pda.d.ts +32 -0
- package/lib/node/addresses/pda.js +211 -0
- package/lib/node/adminClient.d.ts +206 -0
- package/lib/node/adminClient.js +1858 -0
- package/lib/node/assert/assert.d.ts +1 -0
- package/lib/node/assert/assert.js +9 -0
- package/lib/node/auctionSubscriber/auctionSubscriber.d.ts +14 -0
- package/lib/node/auctionSubscriber/auctionSubscriber.js +32 -0
- package/lib/node/auctionSubscriber/auctionSubscriberGrpc.d.ts +15 -0
- package/lib/node/auctionSubscriber/auctionSubscriberGrpc.js +32 -0
- package/lib/node/auctionSubscriber/index.d.ts +3 -0
- package/lib/node/auctionSubscriber/index.js +19 -0
- package/lib/node/auctionSubscriber/types.d.ts +14 -0
- package/lib/node/auctionSubscriber/types.js +2 -0
- package/lib/node/bankrun/bankrunConnection.d.ts +75 -0
- package/lib/node/bankrun/bankrunConnection.js +332 -0
- package/lib/node/blockhashSubscriber/BlockhashSubscriber.d.ts +27 -0
- package/lib/node/blockhashSubscriber/BlockhashSubscriber.js +89 -0
- package/lib/node/blockhashSubscriber/index.d.ts +1 -0
- package/lib/node/blockhashSubscriber/index.js +17 -0
- package/lib/node/blockhashSubscriber/types.d.ts +7 -0
- package/lib/node/blockhashSubscriber/types.js +2 -0
- package/lib/node/clock/clockSubscriber.d.ts +31 -0
- package/lib/node/clock/clockSubscriber.js +80 -0
- package/lib/node/config.d.ts +60 -0
- package/lib/node/config.js +130 -0
- package/lib/node/constants/numericConstants.d.ts +71 -0
- package/lib/node/constants/numericConstants.js +75 -0
- package/lib/node/constants/perpMarkets.d.ts +19 -0
- package/lib/node/constants/perpMarkets.js +997 -0
- package/lib/node/constants/spotMarkets.d.ts +24 -0
- package/lib/node/constants/spotMarkets.js +470 -0
- package/lib/node/constants/txConstants.d.ts +1 -0
- package/lib/node/constants/txConstants.js +4 -0
- package/lib/node/decode/phoenix.d.ts +7 -0
- package/lib/node/decode/phoenix.js +159 -0
- package/lib/node/decode/user.d.ts +4 -0
- package/lib/node/decode/user.js +339 -0
- package/lib/node/dlob/DLOB.d.ts +186 -0
- package/lib/node/dlob/DLOB.js +1039 -0
- package/lib/node/dlob/DLOBNode.d.ts +68 -0
- package/lib/node/dlob/DLOBNode.js +100 -0
- package/lib/node/dlob/DLOBSubscriber.d.ts +54 -0
- package/lib/node/dlob/DLOBSubscriber.js +139 -0
- package/lib/node/dlob/NodeList.d.ts +25 -0
- package/lib/node/dlob/NodeList.js +126 -0
- package/lib/node/dlob/orderBookLevels.d.ts +72 -0
- package/lib/node/dlob/orderBookLevels.js +438 -0
- package/lib/node/dlob/types.d.ts +18 -0
- package/lib/node/dlob/types.js +2 -0
- package/lib/node/driftClient.d.ts +861 -0
- package/lib/node/driftClient.js +4768 -0
- package/lib/node/driftClientConfig.d.ts +49 -0
- package/lib/node/driftClientConfig.js +2 -0
- package/lib/node/events/eventList.d.ts +22 -0
- package/lib/node/events/eventList.js +80 -0
- package/lib/node/events/eventSubscriber.d.ts +46 -0
- package/lib/node/events/eventSubscriber.js +223 -0
- package/lib/node/events/eventsServerLogProvider.d.ts +21 -0
- package/lib/node/events/eventsServerLogProvider.js +121 -0
- package/lib/node/events/fetchLogs.d.ts +25 -0
- package/lib/node/events/fetchLogs.js +99 -0
- package/lib/node/events/parse.d.ts +6 -0
- package/lib/node/events/parse.js +106 -0
- package/lib/node/events/pollingLogProvider.d.ts +17 -0
- package/lib/node/events/pollingLogProvider.js +58 -0
- package/lib/node/events/sort.d.ts +2 -0
- package/lib/node/events/sort.js +24 -0
- package/lib/node/events/txEventCache.d.ts +24 -0
- package/lib/node/events/txEventCache.js +71 -0
- package/lib/node/events/types.d.ts +79 -0
- package/lib/node/events/types.js +32 -0
- package/lib/node/events/webSocketLogProvider.d.ts +24 -0
- package/lib/node/events/webSocketLogProvider.js +96 -0
- package/lib/node/factory/bigNum.d.ts +122 -0
- package/lib/node/factory/bigNum.js +457 -0
- package/lib/node/factory/oracleClient.d.ts +5 -0
- package/lib/node/factory/oracleClient.js +56 -0
- package/lib/node/idl/drift.json +14440 -0
- package/lib/node/idl/openbook.json +3854 -0
- package/lib/node/idl/pyth_solana_receiver.json +628 -0
- package/lib/node/idl/switchboard.json +8354 -0
- package/lib/node/idl/switchboard_on_demand_30.json +4546 -0
- package/lib/node/idl/token_faucet.json +142 -0
- package/lib/node/index.d.ts +125 -0
- package/lib/node/index.js +147 -0
- package/lib/node/isomorphic/grpc.browser.d.ts +1 -0
- package/lib/node/isomorphic/grpc.browser.js +8 -0
- package/lib/node/isomorphic/grpc.d.ts +1 -0
- package/lib/node/isomorphic/grpc.js +8 -0
- package/lib/node/jupiter/jupiterClient.d.ts +302 -0
- package/lib/node/jupiter/jupiterClient.js +178 -0
- package/lib/node/keypair.d.ts +2 -0
- package/lib/node/keypair.js +28 -0
- package/lib/node/marinade/index.d.ts +12 -0
- package/lib/node/marinade/index.js +36 -0
- package/lib/node/marinade/types.d.ts +1963 -0
- package/lib/node/marinade/types.js +1965 -0
- package/lib/node/math/amm.d.ts +98 -0
- package/lib/node/math/amm.js +626 -0
- package/lib/node/math/auction.d.ts +23 -0
- package/lib/node/math/auction.js +130 -0
- package/lib/node/math/bankruptcy.d.ts +2 -0
- package/lib/node/math/bankruptcy.js +31 -0
- package/lib/node/math/conversion.d.ts +2 -0
- package/lib/node/math/conversion.js +11 -0
- package/lib/node/math/exchangeStatus.d.ts +6 -0
- package/lib/node/math/exchangeStatus.js +77 -0
- package/lib/node/math/fuel.d.ts +6 -0
- package/lib/node/math/fuel.js +55 -0
- package/lib/node/math/funding.d.ts +34 -0
- package/lib/node/math/funding.js +209 -0
- package/lib/node/math/insurance.d.ts +7 -0
- package/lib/node/math/insurance.js +73 -0
- package/lib/node/math/margin.d.ts +39 -0
- package/lib/node/math/margin.js +184 -0
- package/lib/node/math/market.d.ts +39 -0
- package/lib/node/math/market.js +163 -0
- package/lib/node/math/oracles.d.ts +14 -0
- package/lib/node/math/oracles.js +134 -0
- package/lib/node/math/orders.d.ts +23 -0
- package/lib/node/math/orders.js +216 -0
- package/lib/node/math/position.d.ts +70 -0
- package/lib/node/math/position.js +225 -0
- package/lib/node/math/repeg.d.ts +22 -0
- package/lib/node/math/repeg.js +164 -0
- package/lib/node/math/spotBalance.d.ts +83 -0
- package/lib/node/math/spotBalance.js +373 -0
- package/lib/node/math/spotMarket.d.ts +11 -0
- package/lib/node/math/spotMarket.js +49 -0
- package/lib/node/math/spotPosition.d.ts +19 -0
- package/lib/node/math/spotPosition.js +78 -0
- package/lib/node/math/state.d.ts +5 -0
- package/lib/node/math/state.js +30 -0
- package/lib/node/math/superStake.d.ts +167 -0
- package/lib/node/math/superStake.js +306 -0
- package/lib/node/math/tiers.d.ts +4 -0
- package/lib/node/math/tiers.js +52 -0
- package/lib/node/math/trade.d.ts +117 -0
- package/lib/node/math/trade.js +637 -0
- package/lib/node/math/userStatus.d.ts +2 -0
- package/lib/node/math/userStatus.js +8 -0
- package/lib/node/math/utils.d.ts +23 -0
- package/lib/node/math/utils.js +112 -0
- package/lib/node/memcmp.d.ts +11 -0
- package/lib/node/memcmp.js +99 -0
- package/lib/node/openbook/openbookV2FulfillmentConfigMap.d.ts +10 -0
- package/lib/node/openbook/openbookV2FulfillmentConfigMap.js +17 -0
- package/lib/node/openbook/openbookV2Subscriber.d.ts +36 -0
- package/lib/node/openbook/openbookV2Subscriber.js +104 -0
- package/lib/node/oracles/oracleClientCache.d.ts +9 -0
- package/lib/node/oracles/oracleClientCache.js +19 -0
- package/lib/node/oracles/oracleId.d.ts +4 -0
- package/lib/node/oracles/oracleId.js +38 -0
- package/lib/node/oracles/prelaunchOracleClient.d.ts +12 -0
- package/lib/node/oracles/prelaunchOracleClient.js +24 -0
- package/lib/node/oracles/pythClient.d.ts +14 -0
- package/lib/node/oracles/pythClient.js +51 -0
- package/lib/node/oracles/pythLazerClient.d.ts +16 -0
- package/lib/node/oracles/pythLazerClient.js +61 -0
- package/lib/node/oracles/pythPullClient.d.ts +19 -0
- package/lib/node/oracles/pythPullClient.js +60 -0
- package/lib/node/oracles/quoteAssetOracleClient.d.ts +10 -0
- package/lib/node/oracles/quoteAssetOracleClient.js +21 -0
- package/lib/node/oracles/strictOraclePrice.d.ts +9 -0
- package/lib/node/oracles/strictOraclePrice.js +17 -0
- package/lib/node/oracles/switchboardClient.d.ts +12 -0
- package/lib/node/oracles/switchboardClient.js +40 -0
- package/lib/node/oracles/switchboardOnDemandClient.d.ts +12 -0
- package/lib/node/oracles/switchboardOnDemandClient.js +32 -0
- package/lib/node/oracles/types.d.ts +23 -0
- package/lib/node/oracles/types.js +2 -0
- package/lib/node/orderParams.d.ts +29 -0
- package/lib/node/orderParams.js +44 -0
- package/lib/node/orderSubscriber/OrderSubscriber.d.ts +42 -0
- package/lib/node/orderSubscriber/OrderSubscriber.js +172 -0
- package/lib/node/orderSubscriber/PollingSubscription.d.ts +12 -0
- package/lib/node/orderSubscriber/PollingSubscription.js +23 -0
- package/lib/node/orderSubscriber/WebsocketSubscription.d.ts +23 -0
- package/lib/node/orderSubscriber/WebsocketSubscription.js +67 -0
- package/lib/node/orderSubscriber/grpcSubscription.d.ts +22 -0
- package/lib/node/orderSubscriber/grpcSubscription.js +66 -0
- package/lib/node/orderSubscriber/index.d.ts +2 -0
- package/lib/node/orderSubscriber/index.js +18 -0
- package/lib/node/orderSubscriber/types.d.ts +34 -0
- package/lib/node/orderSubscriber/types.js +2 -0
- package/lib/node/phoenix/phoenixFulfillmentConfigMap.d.ts +10 -0
- package/lib/node/phoenix/phoenixFulfillmentConfigMap.js +17 -0
- package/lib/node/phoenix/phoenixSubscriber.d.ts +41 -0
- package/lib/node/phoenix/phoenixSubscriber.js +152 -0
- package/lib/node/priorityFee/averageOverSlotsStrategy.d.ts +5 -0
- package/lib/node/priorityFee/averageOverSlotsStrategy.js +16 -0
- package/lib/node/priorityFee/averageStrategy.d.ts +5 -0
- package/lib/node/priorityFee/averageStrategy.js +11 -0
- package/lib/node/priorityFee/driftPriorityFeeMethod.d.ts +13 -0
- package/lib/node/priorityFee/driftPriorityFeeMethod.js +26 -0
- package/lib/node/priorityFee/ewmaStrategy.d.ts +11 -0
- package/lib/node/priorityFee/ewmaStrategy.js +33 -0
- package/lib/node/priorityFee/heliusPriorityFeeMethod.d.ts +20 -0
- package/lib/node/priorityFee/heliusPriorityFeeMethod.js +46 -0
- package/lib/node/priorityFee/index.d.ts +11 -0
- package/lib/node/priorityFee/index.js +27 -0
- package/lib/node/priorityFee/maxOverSlotsStrategy.d.ts +5 -0
- package/lib/node/priorityFee/maxOverSlotsStrategy.js +17 -0
- package/lib/node/priorityFee/maxStrategy.d.ts +7 -0
- package/lib/node/priorityFee/maxStrategy.js +9 -0
- package/lib/node/priorityFee/priorityFeeSubscriber.d.ts +46 -0
- package/lib/node/priorityFee/priorityFeeSubscriber.js +188 -0
- package/lib/node/priorityFee/priorityFeeSubscriberMap.d.ts +48 -0
- package/lib/node/priorityFee/priorityFeeSubscriberMap.js +88 -0
- package/lib/node/priorityFee/solanaPriorityFeeMethod.d.ts +6 -0
- package/lib/node/priorityFee/solanaPriorityFeeMethod.js +21 -0
- package/lib/node/priorityFee/types.d.ts +31 -0
- package/lib/node/priorityFee/types.js +10 -0
- package/lib/node/serum/serumFulfillmentConfigMap.d.ts +10 -0
- package/lib/node/serum/serumFulfillmentConfigMap.js +17 -0
- package/lib/node/serum/serumSubscriber.d.ts +32 -0
- package/lib/node/serum/serumSubscriber.js +107 -0
- package/lib/node/serum/types.d.ts +13 -0
- package/lib/node/serum/types.js +2 -0
- package/lib/node/slot/SlotSubscriber.d.ts +27 -0
- package/lib/node/slot/SlotSubscriber.js +71 -0
- package/lib/node/slot/SlothashSubscriber.d.ts +26 -0
- package/lib/node/slot/SlothashSubscriber.js +85 -0
- package/lib/node/testClient.d.ts +8 -0
- package/lib/node/testClient.js +23 -0
- package/lib/node/token/index.d.ts +5 -0
- package/lib/node/token/index.js +15 -0
- package/lib/node/tokenFaucet.d.ts +41 -0
- package/lib/node/tokenFaucet.js +188 -0
- package/lib/node/tx/baseTxSender.d.ts +59 -0
- package/lib/node/tx/baseTxSender.js +294 -0
- package/lib/node/tx/blockhashFetcher/baseBlockhashFetcher.d.ts +8 -0
- package/lib/node/tx/blockhashFetcher/baseBlockhashFetcher.js +13 -0
- package/lib/node/tx/blockhashFetcher/cachedBlockhashFetcher.d.ts +28 -0
- package/lib/node/tx/blockhashFetcher/cachedBlockhashFetcher.js +73 -0
- package/lib/node/tx/blockhashFetcher/types.d.ts +4 -0
- package/lib/node/tx/blockhashFetcher/types.js +2 -0
- package/lib/node/tx/fastSingleTxSender.d.ts +41 -0
- package/lib/node/tx/fastSingleTxSender.js +86 -0
- package/lib/node/tx/forwardOnlyTxSender.d.ts +37 -0
- package/lib/node/tx/forwardOnlyTxSender.js +92 -0
- package/lib/node/tx/priorityFeeCalculator.d.ts +44 -0
- package/lib/node/tx/priorityFeeCalculator.js +85 -0
- package/lib/node/tx/reportTransactionError.d.ts +20 -0
- package/lib/node/tx/reportTransactionError.js +103 -0
- package/lib/node/tx/retryTxSender.d.ts +37 -0
- package/lib/node/tx/retryTxSender.js +86 -0
- package/lib/node/tx/txHandler.d.ts +154 -0
- package/lib/node/tx/txHandler.js +453 -0
- package/lib/node/tx/txParamProcessor.d.ts +25 -0
- package/lib/node/tx/txParamProcessor.js +88 -0
- package/lib/node/tx/types.d.ts +29 -0
- package/lib/node/tx/types.js +20 -0
- package/lib/node/tx/utils.d.ts +2 -0
- package/lib/node/tx/utils.js +10 -0
- package/lib/node/tx/whileValidTxSender.d.ts +45 -0
- package/lib/node/tx/whileValidTxSender.js +167 -0
- package/lib/node/types.d.ts +1385 -0
- package/lib/node/types.js +366 -0
- package/lib/node/user.d.ts +411 -0
- package/lib/node/user.js +2151 -0
- package/lib/node/userConfig.d.ts +26 -0
- package/lib/node/userConfig.js +2 -0
- package/lib/node/userMap/PollingSubscription.d.ts +16 -0
- package/lib/node/userMap/PollingSubscription.js +30 -0
- package/lib/node/userMap/WebsocketSubscription.d.ts +27 -0
- package/lib/node/userMap/WebsocketSubscription.js +45 -0
- package/lib/node/userMap/grpcSubscription.d.ts +27 -0
- package/lib/node/userMap/grpcSubscription.js +44 -0
- package/lib/node/userMap/referrerMap.d.ts +45 -0
- package/lib/node/userMap/referrerMap.js +181 -0
- package/lib/node/userMap/userMap.d.ts +90 -0
- package/lib/node/userMap/userMap.js +467 -0
- package/lib/node/userMap/userMapConfig.d.ts +39 -0
- package/lib/node/userMap/userMapConfig.js +2 -0
- package/lib/node/userMap/userStatsMap.d.ts +46 -0
- package/lib/node/userMap/userStatsMap.js +165 -0
- package/lib/node/userName.d.ts +5 -0
- package/lib/node/userName.js +21 -0
- package/lib/node/userStats.d.ts +22 -0
- package/lib/node/userStats.js +91 -0
- package/lib/node/userStatsConfig.d.ts +25 -0
- package/lib/node/userStatsConfig.js +2 -0
- package/lib/node/util/TransactionConfirmationManager.d.ts +16 -0
- package/lib/node/util/TransactionConfirmationManager.js +174 -0
- package/lib/node/util/chainClock.d.ts +17 -0
- package/lib/node/util/chainClock.js +29 -0
- package/lib/node/util/computeUnits.d.ts +8 -0
- package/lib/node/util/computeUnits.js +48 -0
- package/lib/node/util/digest.d.ts +4 -0
- package/lib/node/util/digest.js +14 -0
- package/lib/node/util/promiseTimeout.d.ts +1 -0
- package/lib/node/util/promiseTimeout.js +14 -0
- package/lib/node/util/pythOracleUtils.d.ts +17 -0
- package/lib/node/util/pythOracleUtils.js +107 -0
- package/lib/node/util/tps.d.ts +2 -0
- package/lib/node/util/tps.js +16 -0
- package/lib/node/wallet.d.ts +11 -0
- package/lib/node/wallet.js +32 -0
- package/package.json +92 -0
- package/scripts/postbuild.js +95 -0
- package/scripts/updateVersion.js +28 -0
- package/src/accounts/basicUserAccountSubscriber.ts +59 -0
- package/src/accounts/bulkAccountLoader.ts +294 -0
- package/src/accounts/bulkUserStatsSubscription.ts +33 -0
- package/src/accounts/bulkUserSubscription.ts +33 -0
- package/src/accounts/fetch.ts +66 -0
- package/src/accounts/grpcAccountSubscriber.ts +160 -0
- package/src/accounts/grpcDriftClientAccountSubscriber.ts +203 -0
- package/src/accounts/grpcInsuranceFundStakeAccountSubscriber.ts +56 -0
- package/src/accounts/grpcProgramAccountSubscriber.ts +190 -0
- package/src/accounts/grpcUserAccountSubscriber.ts +48 -0
- package/src/accounts/grpcUserStatsAccountSubscriber.ts +50 -0
- package/src/accounts/oneShotUserAccountSubscriber.ts +68 -0
- package/src/accounts/pollingDriftClientAccountSubscriber.ts +644 -0
- package/src/accounts/pollingHighLeverageModeConfigAccountSubscriber.ts +189 -0
- package/src/accounts/pollingInsuranceFundStakeAccountSubscriber.ts +185 -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/testBulkAccountLoader.ts +53 -0
- package/src/accounts/types.ts +245 -0
- package/src/accounts/utils.ts +62 -0
- package/src/accounts/webSocketAccountSubscriber.ts +205 -0
- package/src/accounts/webSocketDriftClientAccountSubscriber.ts +621 -0
- package/src/accounts/webSocketHighLeverageModeConfigAccountSubscriber.ts +131 -0
- package/src/accounts/webSocketInsuranceFundStakeAccountSubscriber.ts +129 -0
- package/src/accounts/webSocketProgramAccountSubscriber.ts +182 -0
- package/src/accounts/webSocketUserAccountSubscriber.ts +104 -0
- package/src/accounts/webSocketUserStatsAccountSubsriber.ts +98 -0
- package/src/addresses/marketAddresses.ts +17 -0
- package/src/addresses/pda.ts +355 -0
- package/src/adminClient.ts +4030 -0
- package/src/assert/assert.ts +5 -0
- package/src/auctionSubscriber/auctionSubscriber.ts +66 -0
- package/src/auctionSubscriber/auctionSubscriberGrpc.ts +70 -0
- package/src/auctionSubscriber/index.ts +3 -0
- package/src/auctionSubscriber/types.ts +20 -0
- package/src/bankrun/bankrunConnection.ts +534 -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 +212 -0
- package/src/constants/numericConstants.ts +113 -0
- package/src/constants/perpMarkets.ts +1084 -0
- package/src/constants/spotMarkets.ts +565 -0
- package/src/constants/txConstants.ts +1 -0
- package/src/decode/phoenix.ts +207 -0
- package/src/decode/user.ts +368 -0
- package/src/dlob/DLOB.ts +1897 -0
- package/src/dlob/DLOBNode.ts +197 -0
- package/src/dlob/DLOBSubscriber.ts +201 -0
- package/src/dlob/NodeList.ts +173 -0
- package/src/dlob/orderBookLevels.ts +643 -0
- package/src/dlob/types.ts +22 -0
- package/src/driftClient.ts +9032 -0
- package/src/driftClientConfig.ts +60 -0
- package/src/events/eventList.ts +97 -0
- package/src/events/eventSubscriber.ts +364 -0
- package/src/events/eventsServerLogProvider.ts +152 -0
- package/src/events/fetchLogs.ts +169 -0
- package/src/events/parse.ts +133 -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 +185 -0
- package/src/events/webSocketLogProvider.ts +121 -0
- package/src/factory/bigNum.ts +660 -0
- package/src/factory/oracleClient.ts +72 -0
- package/src/idl/drift.json +14440 -0
- package/src/idl/openbook.json +3854 -0
- package/src/idl/pyth.json +142 -0
- package/src/idl/pyth_solana_receiver.json +628 -0
- package/src/idl/switchboard.json +8354 -0
- package/src/idl/switchboard_on_demand_30.json +4546 -0
- package/src/idl/token_faucet.json +142 -0
- package/src/index.ts +127 -0
- package/src/isomorphic/README.md +19 -0
- package/src/isomorphic/grpc.browser.ts +4 -0
- package/src/isomorphic/grpc.node.ts +23 -0
- package/src/isomorphic/grpc.ts +1 -0
- package/src/jupiter/jupiterClient.ts +510 -0
- package/src/keypair.ts +24 -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 +1162 -0
- package/src/math/auction.ts +173 -0
- package/src/math/bankruptcy.ts +34 -0
- package/src/math/conversion.ts +13 -0
- package/src/math/exchangeStatus.ts +121 -0
- package/src/math/fuel.ts +70 -0
- package/src/math/funding.ts +342 -0
- package/src/math/insurance.ts +110 -0
- package/src/math/margin.ts +340 -0
- package/src/math/market.ts +336 -0
- package/src/math/oracles.ts +228 -0
- package/src/math/orders.ts +343 -0
- package/src/math/position.ts +324 -0
- package/src/math/repeg.ts +214 -0
- package/src/math/spotBalance.ts +630 -0
- package/src/math/spotMarket.ts +82 -0
- package/src/math/spotPosition.ts +184 -0
- package/src/math/state.ts +29 -0
- package/src/math/superStake.ts +525 -0
- package/src/math/tiers.ts +44 -0
- package/src/math/trade.ts +993 -0
- package/src/math/userStatus.ts +5 -0
- package/src/math/utils.ts +120 -0
- package/src/memcmp.ts +94 -0
- package/src/openbook/openbookV2FulfillmentConfigMap.ts +29 -0
- package/src/openbook/openbookV2Subscriber.ts +165 -0
- package/src/oracles/oracleClientCache.ts +25 -0
- package/src/oracles/oracleId.ts +28 -0
- package/src/oracles/prelaunchOracleClient.ts +37 -0
- package/src/oracles/pythClient.ts +85 -0
- package/src/oracles/pythLazerClient.ts +102 -0
- package/src/oracles/pythPullClient.ts +111 -0
- package/src/oracles/quoteAssetOracleClient.ts +25 -0
- package/src/oracles/strictOraclePrice.ts +19 -0
- package/src/oracles/switchboardClient.ts +77 -0
- package/src/oracles/switchboardOnDemandClient.ts +56 -0
- package/src/oracles/types.ts +23 -0
- package/src/orderParams.ts +79 -0
- package/src/orderSubscriber/OrderSubscriber.ts +249 -0
- package/src/orderSubscriber/PollingSubscription.ts +39 -0
- package/src/orderSubscriber/WebsocketSubscription.ts +119 -0
- package/src/orderSubscriber/grpcSubscription.ts +121 -0
- package/src/orderSubscriber/index.ts +2 -0
- package/src/orderSubscriber/types.ts +54 -0
- package/src/phoenix/phoenixFulfillmentConfigMap.ts +26 -0
- package/src/phoenix/phoenixSubscriber.ts +235 -0
- package/src/priorityFee/averageOverSlotsStrategy.ts +16 -0
- package/src/priorityFee/averageStrategy.ts +12 -0
- package/src/priorityFee/driftPriorityFeeMethod.ts +42 -0
- package/src/priorityFee/ewmaStrategy.ts +41 -0
- package/src/priorityFee/heliusPriorityFeeMethod.ts +57 -0
- package/src/priorityFee/index.ts +11 -0
- package/src/priorityFee/maxOverSlotsStrategy.ts +17 -0
- package/src/priorityFee/maxStrategy.ts +7 -0
- package/src/priorityFee/priorityFeeSubscriber.ts +251 -0
- package/src/priorityFee/priorityFeeSubscriberMap.ts +112 -0
- package/src/priorityFee/solanaPriorityFeeMethod.ts +34 -0
- package/src/priorityFee/types.ts +60 -0
- package/src/serum/serumFulfillmentConfigMap.ts +26 -0
- package/src/serum/serumSubscriber.ts +169 -0
- package/src/serum/types.ts +17 -0
- package/src/slot/SlotSubscriber.ts +101 -0
- package/src/slot/SlothashSubscriber.ts +126 -0
- package/src/testClient.ts +41 -0
- package/src/token/index.ts +13 -0
- package/src/tokenFaucet.ts +269 -0
- package/src/tx/baseTxSender.ts +477 -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 +737 -0
- package/src/tx/txParamProcessor.ts +155 -0
- package/src/tx/types.ts +71 -0
- package/src/tx/utils.ts +11 -0
- package/src/tx/whileValidTxSender.ts +265 -0
- package/src/types.ts +1386 -0
- package/src/user.ts +4054 -0
- package/src/userConfig.ts +32 -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/userMap.ts +654 -0
- package/src/userMap/userMapConfig.ts +63 -0
- package/src/userMap/userStatsMap.ts +218 -0
- package/src/userName.ts +21 -0
- package/src/userStats.ts +174 -0
- package/src/userStatsConfig.ts +31 -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 +11 -0
- package/src/util/promiseTimeout.ts +14 -0
- package/src/util/pythOracleUtils.ts +136 -0
- package/src/util/tps.ts +27 -0
- package/src/wallet.ts +43 -0
- package/tests/amm/test.ts +2092 -0
- package/tests/auctions/test.ts +81 -0
- package/tests/bn/test.ts +341 -0
- package/tests/ci/idl.ts +101 -0
- package/tests/ci/verifyConstants.ts +278 -0
- package/tests/decode/phoenix.ts +71 -0
- package/tests/decode/test.ts +266 -0
- package/tests/decode/userAccountBufferStrings.ts +102 -0
- package/tests/dlob/helpers.ts +749 -0
- package/tests/dlob/test.ts +6623 -0
- package/tests/insurance/test.ts +40 -0
- package/tests/spot/test.ts +226 -0
- package/tests/subscriber/openbook.ts +62 -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/helpers.ts +92 -0
- package/tests/user/test.ts +517 -0
- package/tsconfig.browser.json +13 -0
- package/tsconfig.json +13 -0
|
@@ -0,0 +1,4768 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod;
|
|
20
|
+
var result = {};
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
+
__setModuleDefault(result, mod);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
26
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
27
|
+
};
|
|
28
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
29
|
+
exports.DriftClient = void 0;
|
|
30
|
+
const anchor = __importStar(require("@coral-xyz/anchor"));
|
|
31
|
+
const anchor_1 = require("@coral-xyz/anchor");
|
|
32
|
+
const anchor_30_1 = require("@coral-xyz/anchor-30");
|
|
33
|
+
const bs58_1 = __importDefault(require("bs58"));
|
|
34
|
+
const spl_token_1 = require("@solana/spl-token");
|
|
35
|
+
const types_1 = require("./types");
|
|
36
|
+
const drift_json_1 = __importDefault(require("./idl/drift.json"));
|
|
37
|
+
const web3_js_1 = require("@solana/web3.js");
|
|
38
|
+
const events_1 = require("events");
|
|
39
|
+
const pda_1 = require("./addresses/pda");
|
|
40
|
+
const types_2 = require("./accounts/types");
|
|
41
|
+
const numericConstants_1 = require("./constants/numericConstants");
|
|
42
|
+
const position_1 = require("./math/position");
|
|
43
|
+
const spotBalance_1 = require("./math/spotBalance");
|
|
44
|
+
const userName_1 = require("./userName");
|
|
45
|
+
const pollingDriftClientAccountSubscriber_1 = require("./accounts/pollingDriftClientAccountSubscriber");
|
|
46
|
+
const webSocketDriftClientAccountSubscriber_1 = require("./accounts/webSocketDriftClientAccountSubscriber");
|
|
47
|
+
const retryTxSender_1 = require("./tx/retryTxSender");
|
|
48
|
+
const user_1 = require("./user");
|
|
49
|
+
const config_1 = require("./config");
|
|
50
|
+
const spotMarkets_1 = require("./constants/spotMarkets");
|
|
51
|
+
const userStats_1 = require("./userStats");
|
|
52
|
+
const spotPosition_1 = require("./math/spotPosition");
|
|
53
|
+
const market_1 = require("./math/market");
|
|
54
|
+
const fetch_1 = require("./accounts/fetch");
|
|
55
|
+
const spotMarket_1 = require("./math/spotMarket");
|
|
56
|
+
const memcmp_1 = require("./memcmp");
|
|
57
|
+
const marinade_1 = require("./marinade");
|
|
58
|
+
const orderParams_1 = require("./orderParams");
|
|
59
|
+
const utils_1 = require("./math/utils");
|
|
60
|
+
const txParamProcessor_1 = require("./tx/txParamProcessor");
|
|
61
|
+
const oracles_1 = require("./math/oracles");
|
|
62
|
+
const txHandler_1 = require("./tx/txHandler");
|
|
63
|
+
const pyth_solana_receiver_1 = require("@pythnetwork/pyth-solana-receiver");
|
|
64
|
+
const price_service_sdk_1 = require("@pythnetwork/price-service-sdk");
|
|
65
|
+
const address_1 = require("@pythnetwork/pyth-solana-receiver/lib/address");
|
|
66
|
+
const pythOracleUtils_1 = require("./util/pythOracleUtils");
|
|
67
|
+
const utils_2 = require("./tx/utils");
|
|
68
|
+
const pyth_solana_receiver_json_1 = __importDefault(require("./idl/pyth_solana_receiver.json"));
|
|
69
|
+
const on_demand_1 = require("@switchboard-xyz/on-demand");
|
|
70
|
+
const grpcDriftClientAccountSubscriber_1 = require("./accounts/grpcDriftClientAccountSubscriber");
|
|
71
|
+
const tweetnacl_1 = __importDefault(require("tweetnacl"));
|
|
72
|
+
const digest_1 = require("./util/digest");
|
|
73
|
+
const oracleId_1 = require("./oracles/oracleId");
|
|
74
|
+
/**
|
|
75
|
+
* # DriftClient
|
|
76
|
+
* This class is the main way to interact with Drift Protocol. It allows you to subscribe to the various accounts where the Market's state is stored, as well as: opening positions, liquidating, settling funding, depositing & withdrawing, and more.
|
|
77
|
+
*/
|
|
78
|
+
class DriftClient {
|
|
79
|
+
get isSubscribed() {
|
|
80
|
+
return this._isSubscribed && this.accountSubscriber.isSubscribed;
|
|
81
|
+
}
|
|
82
|
+
set isSubscribed(val) {
|
|
83
|
+
this._isSubscribed = val;
|
|
84
|
+
}
|
|
85
|
+
constructor(config) {
|
|
86
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20;
|
|
87
|
+
this.users = new Map();
|
|
88
|
+
this._isSubscribed = false;
|
|
89
|
+
this.perpMarketLastSlotCache = new Map();
|
|
90
|
+
this.spotMarketLastSlotCache = new Map();
|
|
91
|
+
this.mustIncludePerpMarketIndexes = new Set();
|
|
92
|
+
this.mustIncludeSpotMarketIndexes = new Set();
|
|
93
|
+
this.connection = config.connection;
|
|
94
|
+
this.wallet = config.wallet;
|
|
95
|
+
this.opts = config.opts || {
|
|
96
|
+
...config_1.DEFAULT_CONFIRMATION_OPTS,
|
|
97
|
+
};
|
|
98
|
+
if ((_a = config === null || config === void 0 ? void 0 : config.connection) === null || _a === void 0 ? void 0 : _a.commitment) {
|
|
99
|
+
// At the moment this ensures that our transaction simulations (which use Connection object) will use the same commitment level as our Transaction blockhashes (which use these opts)
|
|
100
|
+
this.opts.commitment = config.connection.commitment;
|
|
101
|
+
this.opts.preflightCommitment = config.connection.commitment;
|
|
102
|
+
}
|
|
103
|
+
this.provider = new anchor_1.AnchorProvider(config.connection,
|
|
104
|
+
// @ts-ignore
|
|
105
|
+
config.wallet, this.opts);
|
|
106
|
+
this.program = new anchor_1.Program(drift_json_1.default, (_b = config.programID) !== null && _b !== void 0 ? _b : new web3_js_1.PublicKey(config_1.DRIFT_PROGRAM_ID), this.provider);
|
|
107
|
+
this.swiftID = (_c = config.swiftID) !== null && _c !== void 0 ? _c : new web3_js_1.PublicKey(config_1.SWIFT_ID);
|
|
108
|
+
this.authority = (_d = config.authority) !== null && _d !== void 0 ? _d : this.wallet.publicKey;
|
|
109
|
+
this.activeSubAccountId = (_e = config.activeSubAccountId) !== null && _e !== void 0 ? _e : 0;
|
|
110
|
+
this.skipLoadUsers = (_f = config.skipLoadUsers) !== null && _f !== void 0 ? _f : false;
|
|
111
|
+
this.txVersion = (_g = config.txVersion) !== null && _g !== void 0 ? _g : 'legacy';
|
|
112
|
+
this.txParams = {
|
|
113
|
+
computeUnits: (_j = (_h = config.txParams) === null || _h === void 0 ? void 0 : _h.computeUnits) !== null && _j !== void 0 ? _j : 600000,
|
|
114
|
+
computeUnitsPrice: (_l = (_k = config.txParams) === null || _k === void 0 ? void 0 : _k.computeUnitsPrice) !== null && _l !== void 0 ? _l : 0,
|
|
115
|
+
};
|
|
116
|
+
this.txHandler =
|
|
117
|
+
(_m = config === null || config === void 0 ? void 0 : config.txHandler) !== null && _m !== void 0 ? _m : new txHandler_1.TxHandler({
|
|
118
|
+
connection: this.connection,
|
|
119
|
+
// @ts-ignore
|
|
120
|
+
wallet: this.provider.wallet,
|
|
121
|
+
confirmationOptions: this.opts,
|
|
122
|
+
opts: {
|
|
123
|
+
returnBlockHeightsWithSignedTxCallbackData: config.enableMetricsEvents,
|
|
124
|
+
onSignedCb: this.handleSignedTransaction.bind(this),
|
|
125
|
+
preSignedCb: this.handlePreSignedTransaction.bind(this),
|
|
126
|
+
},
|
|
127
|
+
config: config.txHandlerConfig,
|
|
128
|
+
});
|
|
129
|
+
if (config.includeDelegates && config.subAccountIds) {
|
|
130
|
+
throw new Error('Can only pass one of includeDelegates or subAccountIds. If you want to specify subaccount ids for multiple authorities, pass authoritySubaccountMap instead');
|
|
131
|
+
}
|
|
132
|
+
if (config.authoritySubAccountMap && config.subAccountIds) {
|
|
133
|
+
throw new Error('Can only pass one of authoritySubaccountMap or subAccountIds');
|
|
134
|
+
}
|
|
135
|
+
if (config.authoritySubAccountMap && config.includeDelegates) {
|
|
136
|
+
throw new Error('Can only pass one of authoritySubaccountMap or includeDelegates');
|
|
137
|
+
}
|
|
138
|
+
this.authoritySubAccountMap = config.authoritySubAccountMap
|
|
139
|
+
? config.authoritySubAccountMap
|
|
140
|
+
: config.subAccountIds
|
|
141
|
+
? new Map([[this.authority.toString(), config.subAccountIds]])
|
|
142
|
+
: new Map();
|
|
143
|
+
this.includeDelegates = (_o = config.includeDelegates) !== null && _o !== void 0 ? _o : false;
|
|
144
|
+
if (((_p = config.accountSubscription) === null || _p === void 0 ? void 0 : _p.type) === 'polling') {
|
|
145
|
+
this.userAccountSubscriptionConfig = {
|
|
146
|
+
type: 'polling',
|
|
147
|
+
accountLoader: config.accountSubscription.accountLoader,
|
|
148
|
+
};
|
|
149
|
+
this.userStatsAccountSubscriptionConfig = {
|
|
150
|
+
type: 'polling',
|
|
151
|
+
accountLoader: config.accountSubscription.accountLoader,
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
else if (((_q = config.accountSubscription) === null || _q === void 0 ? void 0 : _q.type) === 'grpc') {
|
|
155
|
+
this.userAccountSubscriptionConfig = {
|
|
156
|
+
type: 'grpc',
|
|
157
|
+
resubTimeoutMs: (_r = config.accountSubscription) === null || _r === void 0 ? void 0 : _r.resubTimeoutMs,
|
|
158
|
+
logResubMessages: (_s = config.accountSubscription) === null || _s === void 0 ? void 0 : _s.logResubMessages,
|
|
159
|
+
grpcConfigs: (_t = config.accountSubscription) === null || _t === void 0 ? void 0 : _t.grpcConfigs,
|
|
160
|
+
};
|
|
161
|
+
this.userStatsAccountSubscriptionConfig = {
|
|
162
|
+
type: 'grpc',
|
|
163
|
+
grpcConfigs: (_u = config.accountSubscription) === null || _u === void 0 ? void 0 : _u.grpcConfigs,
|
|
164
|
+
resubTimeoutMs: (_v = config.accountSubscription) === null || _v === void 0 ? void 0 : _v.resubTimeoutMs,
|
|
165
|
+
logResubMessages: (_w = config.accountSubscription) === null || _w === void 0 ? void 0 : _w.logResubMessages,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
this.userAccountSubscriptionConfig = {
|
|
170
|
+
type: 'websocket',
|
|
171
|
+
resubTimeoutMs: (_x = config.accountSubscription) === null || _x === void 0 ? void 0 : _x.resubTimeoutMs,
|
|
172
|
+
logResubMessages: (_y = config.accountSubscription) === null || _y === void 0 ? void 0 : _y.logResubMessages,
|
|
173
|
+
commitment: (_z = config.accountSubscription) === null || _z === void 0 ? void 0 : _z.commitment,
|
|
174
|
+
};
|
|
175
|
+
this.userStatsAccountSubscriptionConfig = {
|
|
176
|
+
type: 'websocket',
|
|
177
|
+
resubTimeoutMs: (_0 = config.accountSubscription) === null || _0 === void 0 ? void 0 : _0.resubTimeoutMs,
|
|
178
|
+
logResubMessages: (_1 = config.accountSubscription) === null || _1 === void 0 ? void 0 : _1.logResubMessages,
|
|
179
|
+
commitment: (_2 = config.accountSubscription) === null || _2 === void 0 ? void 0 : _2.commitment,
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
if (config.userStats) {
|
|
183
|
+
this.userStats = new userStats_1.UserStats({
|
|
184
|
+
driftClient: this,
|
|
185
|
+
userStatsAccountPublicKey: (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, this.authority),
|
|
186
|
+
accountSubscription: this.userAccountSubscriptionConfig,
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
this.marketLookupTable = config.marketLookupTable;
|
|
190
|
+
if (config.env && !this.marketLookupTable) {
|
|
191
|
+
this.marketLookupTable = new web3_js_1.PublicKey(config_1.configs[config.env].MARKET_LOOKUP_TABLE);
|
|
192
|
+
}
|
|
193
|
+
const delistedMarketSetting = config.delistedMarketSetting || types_2.DelistedMarketSetting.Unsubscribe;
|
|
194
|
+
const noMarketsAndOraclesSpecified = config.perpMarketIndexes === undefined &&
|
|
195
|
+
config.spotMarketIndexes === undefined &&
|
|
196
|
+
config.oracleInfos === undefined;
|
|
197
|
+
if (((_3 = config.accountSubscription) === null || _3 === void 0 ? void 0 : _3.type) === 'polling') {
|
|
198
|
+
this.accountSubscriber = new pollingDriftClientAccountSubscriber_1.PollingDriftClientAccountSubscriber(this.program, config.accountSubscription.accountLoader, (_4 = config.perpMarketIndexes) !== null && _4 !== void 0 ? _4 : [], (_5 = config.spotMarketIndexes) !== null && _5 !== void 0 ? _5 : [], (_6 = config.oracleInfos) !== null && _6 !== void 0 ? _6 : [], noMarketsAndOraclesSpecified, delistedMarketSetting);
|
|
199
|
+
}
|
|
200
|
+
else if (((_7 = config.accountSubscription) === null || _7 === void 0 ? void 0 : _7.type) === 'grpc') {
|
|
201
|
+
this.accountSubscriber = new grpcDriftClientAccountSubscriber_1.gprcDriftClientAccountSubscriber(config.accountSubscription.grpcConfigs, this.program, (_8 = config.perpMarketIndexes) !== null && _8 !== void 0 ? _8 : [], (_9 = config.spotMarketIndexes) !== null && _9 !== void 0 ? _9 : [], (_10 = config.oracleInfos) !== null && _10 !== void 0 ? _10 : [], noMarketsAndOraclesSpecified, delistedMarketSetting, {
|
|
202
|
+
resubTimeoutMs: (_11 = config.accountSubscription) === null || _11 === void 0 ? void 0 : _11.resubTimeoutMs,
|
|
203
|
+
logResubMessages: (_12 = config.accountSubscription) === null || _12 === void 0 ? void 0 : _12.logResubMessages,
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
else {
|
|
207
|
+
this.accountSubscriber = new webSocketDriftClientAccountSubscriber_1.WebSocketDriftClientAccountSubscriber(this.program, (_13 = config.perpMarketIndexes) !== null && _13 !== void 0 ? _13 : [], (_14 = config.spotMarketIndexes) !== null && _14 !== void 0 ? _14 : [], (_15 = config.oracleInfos) !== null && _15 !== void 0 ? _15 : [], noMarketsAndOraclesSpecified, delistedMarketSetting, {
|
|
208
|
+
resubTimeoutMs: (_16 = config.accountSubscription) === null || _16 === void 0 ? void 0 : _16.resubTimeoutMs,
|
|
209
|
+
logResubMessages: (_17 = config.accountSubscription) === null || _17 === void 0 ? void 0 : _17.logResubMessages,
|
|
210
|
+
}, (_18 = config.accountSubscription) === null || _18 === void 0 ? void 0 : _18.commitment);
|
|
211
|
+
}
|
|
212
|
+
this.eventEmitter = this.accountSubscriber.eventEmitter;
|
|
213
|
+
this.metricsEventEmitter = new events_1.EventEmitter();
|
|
214
|
+
if (config.enableMetricsEvents) {
|
|
215
|
+
this.enableMetricsEvents = true;
|
|
216
|
+
}
|
|
217
|
+
this.txSender =
|
|
218
|
+
(_19 = config.txSender) !== null && _19 !== void 0 ? _19 : new retryTxSender_1.RetryTxSender({
|
|
219
|
+
connection: this.connection,
|
|
220
|
+
wallet: this.wallet,
|
|
221
|
+
opts: this.opts,
|
|
222
|
+
txHandler: this.txHandler,
|
|
223
|
+
});
|
|
224
|
+
this.sbOnDemandProgramdId =
|
|
225
|
+
config_1.configs[(_20 = config.env) !== null && _20 !== void 0 ? _20 : 'mainnet-beta'].SB_ON_DEMAND_PID;
|
|
226
|
+
}
|
|
227
|
+
getUserMapKey(subAccountId, authority) {
|
|
228
|
+
return `${subAccountId}_${authority.toString()}`;
|
|
229
|
+
}
|
|
230
|
+
createUser(subAccountId, accountSubscriptionConfig, authority) {
|
|
231
|
+
const userAccountPublicKey = (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, authority !== null && authority !== void 0 ? authority : this.authority, subAccountId);
|
|
232
|
+
return new user_1.User({
|
|
233
|
+
driftClient: this,
|
|
234
|
+
userAccountPublicKey,
|
|
235
|
+
accountSubscription: accountSubscriptionConfig,
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
async subscribe() {
|
|
239
|
+
let subscribePromises = [this.addAndSubscribeToUsers()].concat(this.accountSubscriber.subscribe());
|
|
240
|
+
if (this.userStats !== undefined) {
|
|
241
|
+
subscribePromises = subscribePromises.concat(this.userStats.subscribe());
|
|
242
|
+
}
|
|
243
|
+
this.isSubscribed = (await Promise.all(subscribePromises)).reduce((success, prevSuccess) => success && prevSuccess);
|
|
244
|
+
return this.isSubscribed;
|
|
245
|
+
}
|
|
246
|
+
subscribeUsers() {
|
|
247
|
+
return [...this.users.values()].map((user) => user.subscribe());
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Forces the accountSubscriber to fetch account updates from rpc
|
|
251
|
+
*/
|
|
252
|
+
async fetchAccounts() {
|
|
253
|
+
let promises = [...this.users.values()]
|
|
254
|
+
.map((user) => user.fetchAccounts())
|
|
255
|
+
.concat(this.accountSubscriber.fetch());
|
|
256
|
+
if (this.userStats) {
|
|
257
|
+
promises = promises.concat(this.userStats.fetchAccounts());
|
|
258
|
+
}
|
|
259
|
+
await Promise.all(promises);
|
|
260
|
+
}
|
|
261
|
+
async unsubscribe() {
|
|
262
|
+
let unsubscribePromises = this.unsubscribeUsers().concat(this.accountSubscriber.unsubscribe());
|
|
263
|
+
if (this.userStats !== undefined) {
|
|
264
|
+
unsubscribePromises = unsubscribePromises.concat(this.userStats.unsubscribe());
|
|
265
|
+
}
|
|
266
|
+
await Promise.all(unsubscribePromises);
|
|
267
|
+
this.isSubscribed = false;
|
|
268
|
+
}
|
|
269
|
+
unsubscribeUsers() {
|
|
270
|
+
return [...this.users.values()].map((user) => user.unsubscribe());
|
|
271
|
+
}
|
|
272
|
+
async getStatePublicKey() {
|
|
273
|
+
if (this.statePublicKey) {
|
|
274
|
+
return this.statePublicKey;
|
|
275
|
+
}
|
|
276
|
+
this.statePublicKey = await (0, pda_1.getDriftStateAccountPublicKey)(this.program.programId);
|
|
277
|
+
return this.statePublicKey;
|
|
278
|
+
}
|
|
279
|
+
getSignerPublicKey() {
|
|
280
|
+
if (this.signerPublicKey) {
|
|
281
|
+
return this.signerPublicKey;
|
|
282
|
+
}
|
|
283
|
+
this.signerPublicKey = (0, pda_1.getDriftSignerPublicKey)(this.program.programId);
|
|
284
|
+
return this.signerPublicKey;
|
|
285
|
+
}
|
|
286
|
+
getStateAccount() {
|
|
287
|
+
return this.accountSubscriber.getStateAccountAndSlot().data;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Forces a fetch to rpc before returning accounts. Useful for anchor tests.
|
|
291
|
+
*/
|
|
292
|
+
async forceGetStateAccount() {
|
|
293
|
+
await this.accountSubscriber.fetch();
|
|
294
|
+
return this.accountSubscriber.getStateAccountAndSlot().data;
|
|
295
|
+
}
|
|
296
|
+
getPerpMarketAccount(marketIndex) {
|
|
297
|
+
var _a;
|
|
298
|
+
return (_a = this.accountSubscriber.getMarketAccountAndSlot(marketIndex)) === null || _a === void 0 ? void 0 : _a.data;
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Forces a fetch to rpc before returning accounts. Useful for anchor tests.
|
|
302
|
+
* @param marketIndex
|
|
303
|
+
*/
|
|
304
|
+
async forceGetPerpMarketAccount(marketIndex) {
|
|
305
|
+
var _a, _b;
|
|
306
|
+
await this.accountSubscriber.fetch();
|
|
307
|
+
let data = (_a = this.accountSubscriber.getMarketAccountAndSlot(marketIndex)) === null || _a === void 0 ? void 0 : _a.data;
|
|
308
|
+
let i = 0;
|
|
309
|
+
while (data === undefined && i < 10) {
|
|
310
|
+
await this.accountSubscriber.fetch();
|
|
311
|
+
data = (_b = this.accountSubscriber.getMarketAccountAndSlot(marketIndex)) === null || _b === void 0 ? void 0 : _b.data;
|
|
312
|
+
i++;
|
|
313
|
+
}
|
|
314
|
+
return data;
|
|
315
|
+
}
|
|
316
|
+
getPerpMarketAccounts() {
|
|
317
|
+
return this.accountSubscriber
|
|
318
|
+
.getMarketAccountsAndSlots()
|
|
319
|
+
.filter((value) => value !== undefined)
|
|
320
|
+
.map((value) => value.data);
|
|
321
|
+
}
|
|
322
|
+
getSpotMarketAccount(marketIndex) {
|
|
323
|
+
return this.accountSubscriber.getSpotMarketAccountAndSlot(marketIndex).data;
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Forces a fetch to rpc before returning accounts. Useful for anchor tests.
|
|
327
|
+
* @param marketIndex
|
|
328
|
+
*/
|
|
329
|
+
async forceGetSpotMarketAccount(marketIndex) {
|
|
330
|
+
await this.accountSubscriber.fetch();
|
|
331
|
+
return this.accountSubscriber.getSpotMarketAccountAndSlot(marketIndex).data;
|
|
332
|
+
}
|
|
333
|
+
getSpotMarketAccounts() {
|
|
334
|
+
return this.accountSubscriber
|
|
335
|
+
.getSpotMarketAccountsAndSlots()
|
|
336
|
+
.filter((value) => value !== undefined)
|
|
337
|
+
.map((value) => value.data);
|
|
338
|
+
}
|
|
339
|
+
getQuoteSpotMarketAccount() {
|
|
340
|
+
return this.accountSubscriber.getSpotMarketAccountAndSlot(numericConstants_1.QUOTE_SPOT_MARKET_INDEX).data;
|
|
341
|
+
}
|
|
342
|
+
getOraclePriceDataAndSlot(oraclePublicKey, oracleSource) {
|
|
343
|
+
return this.accountSubscriber.getOraclePriceDataAndSlot((0, oracleId_1.getOracleId)(oraclePublicKey, oracleSource));
|
|
344
|
+
}
|
|
345
|
+
async getSerumV3FulfillmentConfig(serumMarket) {
|
|
346
|
+
const address = await (0, pda_1.getSerumFulfillmentConfigPublicKey)(this.program.programId, serumMarket);
|
|
347
|
+
return (await this.program.account.serumV3FulfillmentConfig.fetch(address));
|
|
348
|
+
}
|
|
349
|
+
async getSerumV3FulfillmentConfigs() {
|
|
350
|
+
const accounts = await this.program.account.serumV3FulfillmentConfig.all();
|
|
351
|
+
return accounts.map((account) => account.account);
|
|
352
|
+
}
|
|
353
|
+
async getPhoenixV1FulfillmentConfig(phoenixMarket) {
|
|
354
|
+
const address = await (0, pda_1.getPhoenixFulfillmentConfigPublicKey)(this.program.programId, phoenixMarket);
|
|
355
|
+
return (await this.program.account.phoenixV1FulfillmentConfig.fetch(address));
|
|
356
|
+
}
|
|
357
|
+
async getPhoenixV1FulfillmentConfigs() {
|
|
358
|
+
const accounts = await this.program.account.phoenixV1FulfillmentConfig.all();
|
|
359
|
+
return accounts.map((account) => account.account);
|
|
360
|
+
}
|
|
361
|
+
async getOpenbookV2FulfillmentConfig(openbookMarket) {
|
|
362
|
+
const address = (0, pda_1.getOpenbookV2FulfillmentConfigPublicKey)(this.program.programId, openbookMarket);
|
|
363
|
+
return (await this.program.account.openbookV2FulfillmentConfig.fetch(address));
|
|
364
|
+
}
|
|
365
|
+
async getOpenbookV2FulfillmentConfigs() {
|
|
366
|
+
const accounts = await this.program.account.openbookV2FulfillmentConfig.all();
|
|
367
|
+
return accounts.map((account) => account.account);
|
|
368
|
+
}
|
|
369
|
+
async fetchMarketLookupTableAccount() {
|
|
370
|
+
if (this.lookupTableAccount)
|
|
371
|
+
return this.lookupTableAccount;
|
|
372
|
+
if (!this.marketLookupTable) {
|
|
373
|
+
console.log('Market lookup table address not set');
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
const lookupTableAccount = (await this.connection.getAddressLookupTable(this.marketLookupTable)).value;
|
|
377
|
+
this.lookupTableAccount = lookupTableAccount;
|
|
378
|
+
return lookupTableAccount;
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Update the wallet to use for drift transactions and linked user account
|
|
382
|
+
* @param newWallet
|
|
383
|
+
* @param subAccountIds
|
|
384
|
+
* @param activeSubAccountId
|
|
385
|
+
* @param includeDelegates
|
|
386
|
+
*/
|
|
387
|
+
async updateWallet(newWallet, subAccountIds, activeSubAccountId, includeDelegates, authoritySubaccountMap) {
|
|
388
|
+
var _a, _b, _c;
|
|
389
|
+
const newProvider = new anchor_1.AnchorProvider(this.connection,
|
|
390
|
+
// @ts-ignore
|
|
391
|
+
newWallet, this.opts);
|
|
392
|
+
const newProgram = new anchor_1.Program(drift_json_1.default, this.program.programId, newProvider);
|
|
393
|
+
this.skipLoadUsers = false;
|
|
394
|
+
// Update provider for txSender with new wallet details
|
|
395
|
+
this.txSender.wallet = newWallet;
|
|
396
|
+
this.wallet = newWallet;
|
|
397
|
+
this.txHandler.updateWallet(newWallet);
|
|
398
|
+
this.provider = newProvider;
|
|
399
|
+
this.program = newProgram;
|
|
400
|
+
this.authority = newWallet.publicKey;
|
|
401
|
+
this.activeSubAccountId = activeSubAccountId;
|
|
402
|
+
this.userStatsAccountPublicKey = undefined;
|
|
403
|
+
this.includeDelegates = includeDelegates !== null && includeDelegates !== void 0 ? includeDelegates : false;
|
|
404
|
+
const walletSupportsVersionedTxns =
|
|
405
|
+
//@ts-ignore
|
|
406
|
+
(_b = (_a = this.wallet.supportedTransactionVersions) === null || _a === void 0 ? void 0 : _a.size) !== null && _b !== void 0 ? _b : 0 > 1;
|
|
407
|
+
this.txVersion = walletSupportsVersionedTxns ? 0 : 'legacy';
|
|
408
|
+
if (includeDelegates && subAccountIds) {
|
|
409
|
+
throw new Error('Can only pass one of includeDelegates or subAccountIds. If you want to specify subaccount ids for multiple authorities, pass authoritySubaccountMap instead');
|
|
410
|
+
}
|
|
411
|
+
if (authoritySubaccountMap && subAccountIds) {
|
|
412
|
+
throw new Error('Can only pass one of authoritySubaccountMap or subAccountIds');
|
|
413
|
+
}
|
|
414
|
+
if (authoritySubaccountMap && includeDelegates) {
|
|
415
|
+
throw new Error('Can only pass one of authoritySubaccountMap or includeDelegates');
|
|
416
|
+
}
|
|
417
|
+
this.authoritySubAccountMap = authoritySubaccountMap
|
|
418
|
+
? authoritySubaccountMap
|
|
419
|
+
: subAccountIds
|
|
420
|
+
? new Map([[this.authority.toString(), subAccountIds]])
|
|
421
|
+
: new Map();
|
|
422
|
+
/* Reset user stats account */
|
|
423
|
+
if ((_c = this.userStats) === null || _c === void 0 ? void 0 : _c.isSubscribed) {
|
|
424
|
+
await this.userStats.unsubscribe();
|
|
425
|
+
}
|
|
426
|
+
this.userStats = undefined;
|
|
427
|
+
this.userStats = new userStats_1.UserStats({
|
|
428
|
+
driftClient: this,
|
|
429
|
+
userStatsAccountPublicKey: this.getUserStatsAccountPublicKey(),
|
|
430
|
+
accountSubscription: this.userStatsAccountSubscriptionConfig,
|
|
431
|
+
});
|
|
432
|
+
await this.userStats.subscribe();
|
|
433
|
+
let success = true;
|
|
434
|
+
if (this.isSubscribed) {
|
|
435
|
+
await Promise.all(this.unsubscribeUsers());
|
|
436
|
+
this.users.clear();
|
|
437
|
+
success = await this.addAndSubscribeToUsers();
|
|
438
|
+
}
|
|
439
|
+
return success;
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Update the subscribed accounts to a given authority, while leaving the
|
|
443
|
+
* connected wallet intact. This allows a user to emulate another user's
|
|
444
|
+
* account on the UI and sign permissionless transactions with their own wallet.
|
|
445
|
+
* @param emulateAuthority
|
|
446
|
+
*/
|
|
447
|
+
async emulateAccount(emulateAuthority) {
|
|
448
|
+
var _a, _b, _c;
|
|
449
|
+
this.skipLoadUsers = false;
|
|
450
|
+
// Update provider for txSender with new wallet details
|
|
451
|
+
this.authority = emulateAuthority;
|
|
452
|
+
this.userStatsAccountPublicKey = undefined;
|
|
453
|
+
this.includeDelegates = true;
|
|
454
|
+
const walletSupportsVersionedTxns =
|
|
455
|
+
//@ts-ignore
|
|
456
|
+
(_b = (_a = this.wallet.supportedTransactionVersions) === null || _a === void 0 ? void 0 : _a.size) !== null && _b !== void 0 ? _b : 0 > 1;
|
|
457
|
+
this.txVersion = walletSupportsVersionedTxns ? 0 : 'legacy';
|
|
458
|
+
this.authoritySubAccountMap = new Map();
|
|
459
|
+
/* Reset user stats account */
|
|
460
|
+
if ((_c = this.userStats) === null || _c === void 0 ? void 0 : _c.isSubscribed) {
|
|
461
|
+
await this.userStats.unsubscribe();
|
|
462
|
+
}
|
|
463
|
+
this.userStats = undefined;
|
|
464
|
+
this.userStats = new userStats_1.UserStats({
|
|
465
|
+
driftClient: this,
|
|
466
|
+
userStatsAccountPublicKey: this.getUserStatsAccountPublicKey(),
|
|
467
|
+
accountSubscription: this.userStatsAccountSubscriptionConfig,
|
|
468
|
+
});
|
|
469
|
+
await this.userStats.subscribe();
|
|
470
|
+
let success = true;
|
|
471
|
+
if (this.isSubscribed) {
|
|
472
|
+
await Promise.all(this.unsubscribeUsers());
|
|
473
|
+
this.users.clear();
|
|
474
|
+
success = await this.addAndSubscribeToUsers(emulateAuthority);
|
|
475
|
+
}
|
|
476
|
+
return success;
|
|
477
|
+
}
|
|
478
|
+
async switchActiveUser(subAccountId, authority) {
|
|
479
|
+
var _a;
|
|
480
|
+
const authorityChanged = authority && !((_a = this.authority) === null || _a === void 0 ? void 0 : _a.equals(authority));
|
|
481
|
+
this.activeSubAccountId = subAccountId;
|
|
482
|
+
this.authority = authority !== null && authority !== void 0 ? authority : this.authority;
|
|
483
|
+
this.userStatsAccountPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, this.authority);
|
|
484
|
+
/* If changing the user authority ie switching from delegate to non-delegate account, need to re-subscribe to the user stats account */
|
|
485
|
+
if (authorityChanged && this.userStats) {
|
|
486
|
+
if (this.userStats.isSubscribed) {
|
|
487
|
+
await this.userStats.unsubscribe();
|
|
488
|
+
}
|
|
489
|
+
this.userStats = new userStats_1.UserStats({
|
|
490
|
+
driftClient: this,
|
|
491
|
+
userStatsAccountPublicKey: this.userStatsAccountPublicKey,
|
|
492
|
+
accountSubscription: this.userAccountSubscriptionConfig,
|
|
493
|
+
});
|
|
494
|
+
this.userStats.subscribe();
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
async addUser(subAccountId, authority, userAccount) {
|
|
498
|
+
authority = authority !== null && authority !== void 0 ? authority : this.authority;
|
|
499
|
+
const userKey = this.getUserMapKey(subAccountId, authority);
|
|
500
|
+
if (this.users.has(userKey) && this.users.get(userKey).isSubscribed) {
|
|
501
|
+
return true;
|
|
502
|
+
}
|
|
503
|
+
const user = this.createUser(subAccountId, this.userAccountSubscriptionConfig, authority);
|
|
504
|
+
const result = await user.subscribe(userAccount);
|
|
505
|
+
if (result) {
|
|
506
|
+
this.users.set(userKey, user);
|
|
507
|
+
return true;
|
|
508
|
+
}
|
|
509
|
+
else {
|
|
510
|
+
return false;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Adds and subscribes to users based on params set by the constructor or by updateWallet.
|
|
515
|
+
*/
|
|
516
|
+
async addAndSubscribeToUsers(authority) {
|
|
517
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
518
|
+
// save the rpc calls if driftclient is initialized without a real wallet
|
|
519
|
+
if (this.skipLoadUsers)
|
|
520
|
+
return true;
|
|
521
|
+
let result = true;
|
|
522
|
+
if (this.authoritySubAccountMap && this.authoritySubAccountMap.size > 0) {
|
|
523
|
+
this.authoritySubAccountMap.forEach(async (value, key) => {
|
|
524
|
+
for (const subAccountId of value) {
|
|
525
|
+
result =
|
|
526
|
+
result && (await this.addUser(subAccountId, new web3_js_1.PublicKey(key)));
|
|
527
|
+
}
|
|
528
|
+
});
|
|
529
|
+
if (this.activeSubAccountId == undefined) {
|
|
530
|
+
this.switchActiveUser((_a = [...this.authoritySubAccountMap.values()][0][0]) !== null && _a !== void 0 ? _a : 0, new web3_js_1.PublicKey((_b = [...this.authoritySubAccountMap.keys()][0]) !== null && _b !== void 0 ? _b : this.authority.toString()));
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
else {
|
|
534
|
+
let userAccounts = [];
|
|
535
|
+
let delegatedAccounts = [];
|
|
536
|
+
const userAccountsPromise = this.getUserAccountsForAuthority(authority !== null && authority !== void 0 ? authority : this.wallet.publicKey);
|
|
537
|
+
if (this.includeDelegates) {
|
|
538
|
+
const delegatedAccountsPromise = this.getUserAccountsForDelegate(authority !== null && authority !== void 0 ? authority : this.wallet.publicKey);
|
|
539
|
+
[userAccounts, delegatedAccounts] = await Promise.all([
|
|
540
|
+
userAccountsPromise,
|
|
541
|
+
delegatedAccountsPromise,
|
|
542
|
+
]);
|
|
543
|
+
!userAccounts && (userAccounts = []);
|
|
544
|
+
!delegatedAccounts && (delegatedAccounts = []);
|
|
545
|
+
}
|
|
546
|
+
else {
|
|
547
|
+
userAccounts = (_c = (await userAccountsPromise)) !== null && _c !== void 0 ? _c : [];
|
|
548
|
+
}
|
|
549
|
+
const allAccounts = userAccounts.concat(delegatedAccounts);
|
|
550
|
+
const addAllAccountsPromise = allAccounts.map((acc) => this.addUser(acc.subAccountId, acc.authority, acc));
|
|
551
|
+
const addAllAccountsResults = await Promise.all(addAllAccountsPromise);
|
|
552
|
+
result = addAllAccountsResults.every((res) => !!res);
|
|
553
|
+
if (this.activeSubAccountId == undefined) {
|
|
554
|
+
this.switchActiveUser((_e = (_d = userAccounts.concat(delegatedAccounts)[0]) === null || _d === void 0 ? void 0 : _d.subAccountId) !== null && _e !== void 0 ? _e : 0, (_g = (_f = userAccounts.concat(delegatedAccounts)[0]) === null || _f === void 0 ? void 0 : _f.authority) !== null && _g !== void 0 ? _g : this.authority);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
return result;
|
|
558
|
+
}
|
|
559
|
+
async initializeUserAccount(subAccountId = 0, name, referrerInfo, txParams) {
|
|
560
|
+
const initializeIxs = [];
|
|
561
|
+
const [userAccountPublicKey, initializeUserAccountIx] = await this.getInitializeUserInstructions(subAccountId, name, referrerInfo);
|
|
562
|
+
if (subAccountId === 0) {
|
|
563
|
+
if (!(await this.checkIfAccountExists(this.getUserStatsAccountPublicKey()))) {
|
|
564
|
+
initializeIxs.push(await this.getInitializeUserStatsIx());
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
initializeIxs.push(initializeUserAccountIx);
|
|
568
|
+
const tx = await this.buildTransaction(initializeIxs, txParams);
|
|
569
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
570
|
+
await this.addUser(subAccountId);
|
|
571
|
+
return [txSig, userAccountPublicKey];
|
|
572
|
+
}
|
|
573
|
+
async getInitializeUserStatsIx() {
|
|
574
|
+
return await this.program.instruction.initializeUserStats({
|
|
575
|
+
accounts: {
|
|
576
|
+
userStats: this.getUserStatsAccountPublicKey(),
|
|
577
|
+
authority: this.wallet.publicKey,
|
|
578
|
+
payer: this.wallet.publicKey,
|
|
579
|
+
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
|
|
580
|
+
systemProgram: anchor.web3.SystemProgram.programId,
|
|
581
|
+
state: await this.getStatePublicKey(),
|
|
582
|
+
},
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
async initializeRFQUser(userAccountPublicKey, txParams) {
|
|
586
|
+
const initializeIxs = [];
|
|
587
|
+
const [rfqUserAccountPublicKey, initializeUserAccountIx] = await this.getInitializeRFQUserInstruction(userAccountPublicKey);
|
|
588
|
+
initializeIxs.push(initializeUserAccountIx);
|
|
589
|
+
const tx = await this.buildTransaction(initializeIxs, txParams);
|
|
590
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
591
|
+
return [txSig, rfqUserAccountPublicKey];
|
|
592
|
+
}
|
|
593
|
+
async getInitializeRFQUserInstruction(userAccountPublicKey) {
|
|
594
|
+
const rfqUserAccountPublicKey = (0, pda_1.getRFQUserAccountPublicKey)(this.program.programId, userAccountPublicKey);
|
|
595
|
+
const initializeUserAccountIx = await this.program.instruction.initializeRfqUser({
|
|
596
|
+
accounts: {
|
|
597
|
+
rfqUser: rfqUserAccountPublicKey,
|
|
598
|
+
authority: this.wallet.publicKey,
|
|
599
|
+
user: userAccountPublicKey,
|
|
600
|
+
payer: this.wallet.publicKey,
|
|
601
|
+
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
|
|
602
|
+
systemProgram: anchor.web3.SystemProgram.programId,
|
|
603
|
+
},
|
|
604
|
+
});
|
|
605
|
+
return [rfqUserAccountPublicKey, initializeUserAccountIx];
|
|
606
|
+
}
|
|
607
|
+
async initializeSwiftUserOrders(userAccountPublicKey, numOrders, txParams) {
|
|
608
|
+
const initializeIxs = [];
|
|
609
|
+
const [swiftUserAccountPublicKey, initializeUserAccountIx] = await this.getInitializeSwiftUserOrdersAccountIx(userAccountPublicKey, numOrders);
|
|
610
|
+
initializeIxs.push(initializeUserAccountIx);
|
|
611
|
+
const tx = await this.buildTransaction(initializeIxs, txParams);
|
|
612
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
613
|
+
return [txSig, swiftUserAccountPublicKey];
|
|
614
|
+
}
|
|
615
|
+
async getInitializeSwiftUserOrdersAccountIx(userAccountPublicKey, numOrders) {
|
|
616
|
+
const swiftUserAccountPublicKey = (0, pda_1.getSwiftUserAccountPublicKey)(this.program.programId, userAccountPublicKey);
|
|
617
|
+
const initializeUserAccountIx = await this.program.instruction.initializeSwiftUserOrders(numOrders, {
|
|
618
|
+
accounts: {
|
|
619
|
+
swiftUserOrders: swiftUserAccountPublicKey,
|
|
620
|
+
authority: this.wallet.publicKey,
|
|
621
|
+
user: userAccountPublicKey,
|
|
622
|
+
payer: this.wallet.publicKey,
|
|
623
|
+
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
|
|
624
|
+
systemProgram: anchor.web3.SystemProgram.programId,
|
|
625
|
+
},
|
|
626
|
+
});
|
|
627
|
+
return [swiftUserAccountPublicKey, initializeUserAccountIx];
|
|
628
|
+
}
|
|
629
|
+
async resizeSwiftUserOrders(userAccountPublicKey, numOrders, txParams) {
|
|
630
|
+
const resizeUserAccountIx = await this.getResizeSwiftUserOrdersInstruction(userAccountPublicKey, numOrders);
|
|
631
|
+
const tx = await this.buildTransaction([resizeUserAccountIx], txParams);
|
|
632
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
633
|
+
return txSig;
|
|
634
|
+
}
|
|
635
|
+
async getResizeSwiftUserOrdersInstruction(userAccountPublicKey, numOrders) {
|
|
636
|
+
const swiftUserAccountPublicKey = (0, pda_1.getSwiftUserAccountPublicKey)(this.program.programId, userAccountPublicKey);
|
|
637
|
+
const resizeUserAccountIx = await this.program.instruction.resizeSwiftUserOrders(numOrders, {
|
|
638
|
+
accounts: {
|
|
639
|
+
swiftUserOrders: swiftUserAccountPublicKey,
|
|
640
|
+
authority: this.wallet.publicKey,
|
|
641
|
+
user: userAccountPublicKey,
|
|
642
|
+
systemProgram: anchor.web3.SystemProgram.programId,
|
|
643
|
+
},
|
|
644
|
+
});
|
|
645
|
+
return resizeUserAccountIx;
|
|
646
|
+
}
|
|
647
|
+
async getInitializeUserInstructions(subAccountId = 0, name, referrerInfo) {
|
|
648
|
+
const userAccountPublicKey = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, subAccountId);
|
|
649
|
+
const remainingAccounts = new Array();
|
|
650
|
+
if (referrerInfo !== undefined) {
|
|
651
|
+
remainingAccounts.push({
|
|
652
|
+
pubkey: referrerInfo.referrer,
|
|
653
|
+
isWritable: true,
|
|
654
|
+
isSigner: false,
|
|
655
|
+
});
|
|
656
|
+
remainingAccounts.push({
|
|
657
|
+
pubkey: referrerInfo.referrerStats,
|
|
658
|
+
isWritable: true,
|
|
659
|
+
isSigner: false,
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
const state = this.getStateAccount();
|
|
663
|
+
if (!state.whitelistMint.equals(web3_js_1.PublicKey.default)) {
|
|
664
|
+
const associatedTokenPublicKey = await (0, spl_token_1.getAssociatedTokenAddress)(state.whitelistMint, this.wallet.publicKey);
|
|
665
|
+
remainingAccounts.push({
|
|
666
|
+
pubkey: associatedTokenPublicKey,
|
|
667
|
+
isWritable: false,
|
|
668
|
+
isSigner: false,
|
|
669
|
+
});
|
|
670
|
+
}
|
|
671
|
+
if (name === undefined) {
|
|
672
|
+
if (subAccountId === 0) {
|
|
673
|
+
name = userName_1.DEFAULT_USER_NAME;
|
|
674
|
+
}
|
|
675
|
+
else {
|
|
676
|
+
name = `Subaccount ${subAccountId + 1}`;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
const nameBuffer = (0, userName_1.encodeName)(name);
|
|
680
|
+
const initializeUserAccountIx = await this.program.instruction.initializeUser(subAccountId, nameBuffer, {
|
|
681
|
+
accounts: {
|
|
682
|
+
user: userAccountPublicKey,
|
|
683
|
+
userStats: this.getUserStatsAccountPublicKey(),
|
|
684
|
+
authority: this.wallet.publicKey,
|
|
685
|
+
payer: this.wallet.publicKey,
|
|
686
|
+
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
|
|
687
|
+
systemProgram: anchor.web3.SystemProgram.programId,
|
|
688
|
+
state: await this.getStatePublicKey(),
|
|
689
|
+
},
|
|
690
|
+
remainingAccounts,
|
|
691
|
+
});
|
|
692
|
+
return [userAccountPublicKey, initializeUserAccountIx];
|
|
693
|
+
}
|
|
694
|
+
async getNextSubAccountId() {
|
|
695
|
+
const userStats = this.getUserStats();
|
|
696
|
+
let userStatsAccount;
|
|
697
|
+
if (!userStats) {
|
|
698
|
+
userStatsAccount = await (0, fetch_1.fetchUserStatsAccount)(this.connection, this.program, this.wallet.publicKey);
|
|
699
|
+
}
|
|
700
|
+
else {
|
|
701
|
+
userStatsAccount = userStats.getAccount();
|
|
702
|
+
}
|
|
703
|
+
return userStatsAccount.numberOfSubAccountsCreated;
|
|
704
|
+
}
|
|
705
|
+
async initializeReferrerName(name) {
|
|
706
|
+
const userAccountPublicKey = (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, 0);
|
|
707
|
+
const nameBuffer = (0, userName_1.encodeName)(name);
|
|
708
|
+
const referrerNameAccountPublicKey = (0, pda_1.getReferrerNamePublicKeySync)(this.program.programId, nameBuffer);
|
|
709
|
+
const tx = await this.program.transaction.initializeReferrerName(nameBuffer, {
|
|
710
|
+
accounts: {
|
|
711
|
+
referrerName: referrerNameAccountPublicKey,
|
|
712
|
+
user: userAccountPublicKey,
|
|
713
|
+
authority: this.wallet.publicKey,
|
|
714
|
+
userStats: this.getUserStatsAccountPublicKey(),
|
|
715
|
+
payer: this.wallet.publicKey,
|
|
716
|
+
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
|
|
717
|
+
systemProgram: anchor.web3.SystemProgram.programId,
|
|
718
|
+
},
|
|
719
|
+
});
|
|
720
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
721
|
+
return txSig;
|
|
722
|
+
}
|
|
723
|
+
async updateUserName(name, subAccountId = 0) {
|
|
724
|
+
const userAccountPublicKey = (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, subAccountId);
|
|
725
|
+
const nameBuffer = (0, userName_1.encodeName)(name);
|
|
726
|
+
const tx = await this.program.transaction.updateUserName(subAccountId, nameBuffer, {
|
|
727
|
+
accounts: {
|
|
728
|
+
user: userAccountPublicKey,
|
|
729
|
+
authority: this.wallet.publicKey,
|
|
730
|
+
},
|
|
731
|
+
});
|
|
732
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
733
|
+
return txSig;
|
|
734
|
+
}
|
|
735
|
+
async updateUserCustomMarginRatio(updates, txParams) {
|
|
736
|
+
const ixs = await Promise.all(updates.map(async ({ marginRatio, subAccountId }) => {
|
|
737
|
+
const ix = await this.getUpdateUserCustomMarginRatioIx(marginRatio, subAccountId);
|
|
738
|
+
return ix;
|
|
739
|
+
}));
|
|
740
|
+
const tx = await this.buildTransaction(ixs, txParams !== null && txParams !== void 0 ? txParams : this.txParams);
|
|
741
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
742
|
+
return txSig;
|
|
743
|
+
}
|
|
744
|
+
async getUpdateUserCustomMarginRatioIx(marginRatio, subAccountId = 0) {
|
|
745
|
+
const userAccountPublicKey = (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, subAccountId);
|
|
746
|
+
await this.addUser(subAccountId, this.wallet.publicKey);
|
|
747
|
+
const ix = this.program.instruction.updateUserCustomMarginRatio(subAccountId, marginRatio, {
|
|
748
|
+
accounts: {
|
|
749
|
+
user: userAccountPublicKey,
|
|
750
|
+
authority: this.wallet.publicKey,
|
|
751
|
+
},
|
|
752
|
+
});
|
|
753
|
+
return ix;
|
|
754
|
+
}
|
|
755
|
+
async getUpdateUserMarginTradingEnabledIx(marginTradingEnabled, subAccountId = 0, userAccountPublicKey) {
|
|
756
|
+
const userAccountPublicKeyToUse = userAccountPublicKey ||
|
|
757
|
+
(0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, subAccountId);
|
|
758
|
+
await this.addUser(subAccountId, this.wallet.publicKey);
|
|
759
|
+
let remainingAccounts;
|
|
760
|
+
try {
|
|
761
|
+
remainingAccounts = this.getRemainingAccounts({
|
|
762
|
+
userAccounts: [this.getUserAccount(subAccountId)],
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
catch (err) {
|
|
766
|
+
remainingAccounts = [];
|
|
767
|
+
}
|
|
768
|
+
return await this.program.instruction.updateUserMarginTradingEnabled(subAccountId, marginTradingEnabled, {
|
|
769
|
+
accounts: {
|
|
770
|
+
user: userAccountPublicKeyToUse,
|
|
771
|
+
authority: this.wallet.publicKey,
|
|
772
|
+
},
|
|
773
|
+
remainingAccounts,
|
|
774
|
+
});
|
|
775
|
+
}
|
|
776
|
+
async updateUserMarginTradingEnabled(updates) {
|
|
777
|
+
const ixs = await Promise.all(updates.map(async ({ marginTradingEnabled, subAccountId }) => {
|
|
778
|
+
return await this.getUpdateUserMarginTradingEnabledIx(marginTradingEnabled, subAccountId);
|
|
779
|
+
}));
|
|
780
|
+
const tx = await this.buildTransaction(ixs, this.txParams);
|
|
781
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
782
|
+
return txSig;
|
|
783
|
+
}
|
|
784
|
+
async updateUserDelegate(delegate, subAccountId = 0) {
|
|
785
|
+
const tx = await this.program.transaction.updateUserDelegate(subAccountId, delegate, {
|
|
786
|
+
accounts: {
|
|
787
|
+
user: await this.getUserAccountPublicKey(),
|
|
788
|
+
authority: this.wallet.publicKey,
|
|
789
|
+
},
|
|
790
|
+
});
|
|
791
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
792
|
+
return txSig;
|
|
793
|
+
}
|
|
794
|
+
async updateUserAdvancedLp(updates) {
|
|
795
|
+
const ixs = await Promise.all(updates.map(async ({ advancedLp, subAccountId }) => {
|
|
796
|
+
return await this.getUpdateAdvancedDlpIx(advancedLp, subAccountId);
|
|
797
|
+
}));
|
|
798
|
+
const tx = await this.buildTransaction(ixs, this.txParams);
|
|
799
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
800
|
+
return txSig;
|
|
801
|
+
}
|
|
802
|
+
async getUpdateAdvancedDlpIx(advancedLp, subAccountId) {
|
|
803
|
+
const ix = await this.program.instruction.updateUserAdvancedLp(subAccountId, advancedLp, {
|
|
804
|
+
accounts: {
|
|
805
|
+
user: (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, subAccountId),
|
|
806
|
+
authority: this.wallet.publicKey,
|
|
807
|
+
},
|
|
808
|
+
});
|
|
809
|
+
return ix;
|
|
810
|
+
}
|
|
811
|
+
async updateUserReduceOnly(updates) {
|
|
812
|
+
const ixs = await Promise.all(updates.map(async ({ reduceOnly, subAccountId }) => {
|
|
813
|
+
return await this.getUpdateUserReduceOnlyIx(reduceOnly, subAccountId);
|
|
814
|
+
}));
|
|
815
|
+
const tx = await this.buildTransaction(ixs, this.txParams);
|
|
816
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
817
|
+
return txSig;
|
|
818
|
+
}
|
|
819
|
+
async getUpdateUserReduceOnlyIx(reduceOnly, subAccountId) {
|
|
820
|
+
const ix = await this.program.instruction.updateUserReduceOnly(subAccountId, reduceOnly, {
|
|
821
|
+
accounts: {
|
|
822
|
+
user: (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, subAccountId),
|
|
823
|
+
authority: this.wallet.publicKey,
|
|
824
|
+
},
|
|
825
|
+
});
|
|
826
|
+
return ix;
|
|
827
|
+
}
|
|
828
|
+
async updateUserPoolId(updates) {
|
|
829
|
+
const ixs = await Promise.all(updates.map(async ({ poolId, subAccountId }) => {
|
|
830
|
+
return await this.getUpdateUserPoolIdIx(poolId, subAccountId);
|
|
831
|
+
}));
|
|
832
|
+
const tx = await this.buildTransaction(ixs, this.txParams);
|
|
833
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
834
|
+
return txSig;
|
|
835
|
+
}
|
|
836
|
+
async getUpdateUserPoolIdIx(poolId, subAccountId) {
|
|
837
|
+
const ix = await this.program.instruction.updateUserPoolId(subAccountId, poolId, {
|
|
838
|
+
accounts: {
|
|
839
|
+
user: (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, subAccountId),
|
|
840
|
+
authority: this.wallet.publicKey,
|
|
841
|
+
},
|
|
842
|
+
});
|
|
843
|
+
return ix;
|
|
844
|
+
}
|
|
845
|
+
async fetchAllUserAccounts(includeIdle = true) {
|
|
846
|
+
let filters = undefined;
|
|
847
|
+
if (!includeIdle) {
|
|
848
|
+
filters = [(0, memcmp_1.getNonIdleUserFilter)()];
|
|
849
|
+
}
|
|
850
|
+
return (await this.program.account.user.all(filters));
|
|
851
|
+
}
|
|
852
|
+
async getUserAccountsForDelegate(delegate) {
|
|
853
|
+
const programAccounts = await this.program.account.user.all([
|
|
854
|
+
{
|
|
855
|
+
memcmp: {
|
|
856
|
+
offset: 40,
|
|
857
|
+
/** data to match, as base-58 encoded string and limited to less than 129 bytes */
|
|
858
|
+
bytes: bs58_1.default.encode(delegate.toBuffer()),
|
|
859
|
+
},
|
|
860
|
+
},
|
|
861
|
+
]);
|
|
862
|
+
return programAccounts
|
|
863
|
+
.map((programAccount) => programAccount.account)
|
|
864
|
+
.sort((a, b) => a.subAccountId - b.subAccountId);
|
|
865
|
+
}
|
|
866
|
+
async getUserAccountsAndAddressesForAuthority(authority) {
|
|
867
|
+
const programAccounts = await this.program.account.user.all([
|
|
868
|
+
{
|
|
869
|
+
memcmp: {
|
|
870
|
+
offset: 8,
|
|
871
|
+
/** data to match, as base-58 encoded string and limited to less than 129 bytes */
|
|
872
|
+
bytes: bs58_1.default.encode(authority.toBuffer()),
|
|
873
|
+
},
|
|
874
|
+
},
|
|
875
|
+
]);
|
|
876
|
+
return programAccounts.map((programAccount) => programAccount);
|
|
877
|
+
}
|
|
878
|
+
async getUserAccountsForAuthority(authority) {
|
|
879
|
+
const programAccounts = await this.program.account.user.all([
|
|
880
|
+
{
|
|
881
|
+
memcmp: {
|
|
882
|
+
offset: 8,
|
|
883
|
+
/** data to match, as base-58 encoded string and limited to less than 129 bytes */
|
|
884
|
+
bytes: bs58_1.default.encode(authority.toBuffer()),
|
|
885
|
+
},
|
|
886
|
+
},
|
|
887
|
+
]);
|
|
888
|
+
return programAccounts
|
|
889
|
+
.map((programAccount) => programAccount.account)
|
|
890
|
+
.sort((a, b) => a.subAccountId - b.subAccountId);
|
|
891
|
+
}
|
|
892
|
+
async getReferredUserStatsAccountsByReferrer(referrer) {
|
|
893
|
+
const programAccounts = await this.program.account.userStats.all([
|
|
894
|
+
{
|
|
895
|
+
memcmp: {
|
|
896
|
+
offset: 40,
|
|
897
|
+
/** data to match, as base-58 encoded string and limited to less than 129 bytes */
|
|
898
|
+
bytes: bs58_1.default.encode(referrer.toBuffer()),
|
|
899
|
+
},
|
|
900
|
+
},
|
|
901
|
+
]);
|
|
902
|
+
return programAccounts.map((programAccount) => programAccount.account);
|
|
903
|
+
}
|
|
904
|
+
async getReferrerNameAccountsForAuthority(authority) {
|
|
905
|
+
const programAccounts = await this.program.account.referrerName.all([
|
|
906
|
+
{
|
|
907
|
+
memcmp: {
|
|
908
|
+
offset: 8,
|
|
909
|
+
/** data to match, as base-58 encoded string and limited to less than 129 bytes */
|
|
910
|
+
bytes: bs58_1.default.encode(authority.toBuffer()),
|
|
911
|
+
},
|
|
912
|
+
},
|
|
913
|
+
]);
|
|
914
|
+
return programAccounts.map((programAccount) => programAccount.account);
|
|
915
|
+
}
|
|
916
|
+
async deleteUser(subAccountId = 0, txParams) {
|
|
917
|
+
var _a;
|
|
918
|
+
const userAccountPublicKey = (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, subAccountId);
|
|
919
|
+
const ix = await this.getUserDeletionIx(userAccountPublicKey);
|
|
920
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(ix, txParams), [], this.opts);
|
|
921
|
+
const userMapKey = this.getUserMapKey(subAccountId, this.wallet.publicKey);
|
|
922
|
+
await ((_a = this.users.get(userMapKey)) === null || _a === void 0 ? void 0 : _a.unsubscribe());
|
|
923
|
+
this.users.delete(userMapKey);
|
|
924
|
+
return txSig;
|
|
925
|
+
}
|
|
926
|
+
async getUserDeletionIx(userAccountPublicKey) {
|
|
927
|
+
const ix = await this.program.instruction.deleteUser({
|
|
928
|
+
accounts: {
|
|
929
|
+
user: userAccountPublicKey,
|
|
930
|
+
userStats: this.getUserStatsAccountPublicKey(),
|
|
931
|
+
authority: this.wallet.publicKey,
|
|
932
|
+
state: await this.getStatePublicKey(),
|
|
933
|
+
},
|
|
934
|
+
});
|
|
935
|
+
return ix;
|
|
936
|
+
}
|
|
937
|
+
async forceDeleteUser(userAccountPublicKey, userAccount, txParams) {
|
|
938
|
+
const tx = await this.buildTransaction(await this.getForceDeleteUserIx(userAccountPublicKey, userAccount), txParams);
|
|
939
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
940
|
+
return txSig;
|
|
941
|
+
}
|
|
942
|
+
async getForceDeleteUserIx(userAccountPublicKey, userAccount) {
|
|
943
|
+
const writableSpotMarketIndexes = [];
|
|
944
|
+
for (const spotPosition of userAccount.spotPositions) {
|
|
945
|
+
if ((0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
|
|
946
|
+
continue;
|
|
947
|
+
}
|
|
948
|
+
writableSpotMarketIndexes.push(spotPosition.marketIndex);
|
|
949
|
+
}
|
|
950
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
951
|
+
userAccounts: [userAccount],
|
|
952
|
+
writableSpotMarketIndexes,
|
|
953
|
+
});
|
|
954
|
+
const tokenPrograms = new Set();
|
|
955
|
+
for (const spotPosition of userAccount.spotPositions) {
|
|
956
|
+
if ((0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
|
|
957
|
+
continue;
|
|
958
|
+
}
|
|
959
|
+
const spotMarket = this.getSpotMarketAccount(spotPosition.marketIndex);
|
|
960
|
+
remainingAccounts.push({
|
|
961
|
+
isSigner: false,
|
|
962
|
+
isWritable: true,
|
|
963
|
+
pubkey: spotMarket.vault,
|
|
964
|
+
});
|
|
965
|
+
const tokenProgram = this.getTokenProgramForSpotMarket(spotMarket);
|
|
966
|
+
const keeperVault = await this.getAssociatedTokenAccount(spotPosition.marketIndex, false, tokenProgram);
|
|
967
|
+
remainingAccounts.push({
|
|
968
|
+
isSigner: false,
|
|
969
|
+
isWritable: true,
|
|
970
|
+
pubkey: keeperVault,
|
|
971
|
+
});
|
|
972
|
+
tokenPrograms.add(tokenProgram.toBase58());
|
|
973
|
+
}
|
|
974
|
+
for (const tokenProgram of tokenPrograms) {
|
|
975
|
+
remainingAccounts.push({
|
|
976
|
+
isSigner: false,
|
|
977
|
+
isWritable: false,
|
|
978
|
+
pubkey: new web3_js_1.PublicKey(tokenProgram),
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
const authority = userAccount.authority;
|
|
982
|
+
const userStats = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, authority);
|
|
983
|
+
const ix = await this.program.instruction.forceDeleteUser({
|
|
984
|
+
accounts: {
|
|
985
|
+
user: userAccountPublicKey,
|
|
986
|
+
userStats,
|
|
987
|
+
authority,
|
|
988
|
+
state: await this.getStatePublicKey(),
|
|
989
|
+
driftSigner: this.getSignerPublicKey(),
|
|
990
|
+
keeper: this.wallet.publicKey,
|
|
991
|
+
},
|
|
992
|
+
remainingAccounts,
|
|
993
|
+
});
|
|
994
|
+
return ix;
|
|
995
|
+
}
|
|
996
|
+
async deleteSwiftUserOrders(subAccountId = 0, txParams) {
|
|
997
|
+
var _a;
|
|
998
|
+
const userAccountPublicKey = (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, subAccountId);
|
|
999
|
+
const ix = await this.getSwiftUserOrdersDeletionIx(userAccountPublicKey);
|
|
1000
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(ix, txParams), [], this.opts);
|
|
1001
|
+
const userMapKey = this.getUserMapKey(subAccountId, this.wallet.publicKey);
|
|
1002
|
+
await ((_a = this.users.get(userMapKey)) === null || _a === void 0 ? void 0 : _a.unsubscribe());
|
|
1003
|
+
this.users.delete(userMapKey);
|
|
1004
|
+
return txSig;
|
|
1005
|
+
}
|
|
1006
|
+
async getSwiftUserOrdersDeletionIx(userAccountPublicKey) {
|
|
1007
|
+
const ix = await this.program.instruction.deleteSwiftUserOrders({
|
|
1008
|
+
accounts: {
|
|
1009
|
+
user: userAccountPublicKey,
|
|
1010
|
+
swiftUserOrders: (0, pda_1.getSwiftUserAccountPublicKey)(this.program.programId, userAccountPublicKey),
|
|
1011
|
+
authority: this.wallet.publicKey,
|
|
1012
|
+
state: await this.getStatePublicKey(),
|
|
1013
|
+
},
|
|
1014
|
+
});
|
|
1015
|
+
return ix;
|
|
1016
|
+
}
|
|
1017
|
+
async reclaimRent(subAccountId = 0, txParams) {
|
|
1018
|
+
const userAccountPublicKey = (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, subAccountId);
|
|
1019
|
+
const ix = await this.getReclaimRentIx(userAccountPublicKey);
|
|
1020
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(ix, txParams), [], this.opts);
|
|
1021
|
+
return txSig;
|
|
1022
|
+
}
|
|
1023
|
+
async getReclaimRentIx(userAccountPublicKey) {
|
|
1024
|
+
return await this.program.instruction.reclaimRent({
|
|
1025
|
+
accounts: {
|
|
1026
|
+
user: userAccountPublicKey,
|
|
1027
|
+
userStats: this.getUserStatsAccountPublicKey(),
|
|
1028
|
+
authority: this.wallet.publicKey,
|
|
1029
|
+
state: await this.getStatePublicKey(),
|
|
1030
|
+
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
|
|
1031
|
+
},
|
|
1032
|
+
});
|
|
1033
|
+
}
|
|
1034
|
+
getUser(subAccountId, authority) {
|
|
1035
|
+
subAccountId = subAccountId !== null && subAccountId !== void 0 ? subAccountId : this.activeSubAccountId;
|
|
1036
|
+
authority = authority !== null && authority !== void 0 ? authority : this.authority;
|
|
1037
|
+
const userMapKey = this.getUserMapKey(subAccountId, authority);
|
|
1038
|
+
if (!this.users.has(userMapKey)) {
|
|
1039
|
+
throw new Error(`DriftClient has no user for user id ${userMapKey}`);
|
|
1040
|
+
}
|
|
1041
|
+
return this.users.get(userMapKey);
|
|
1042
|
+
}
|
|
1043
|
+
hasUser(subAccountId, authority) {
|
|
1044
|
+
subAccountId = subAccountId !== null && subAccountId !== void 0 ? subAccountId : this.activeSubAccountId;
|
|
1045
|
+
authority = authority !== null && authority !== void 0 ? authority : this.authority;
|
|
1046
|
+
const userMapKey = this.getUserMapKey(subAccountId, authority);
|
|
1047
|
+
return this.users.has(userMapKey);
|
|
1048
|
+
}
|
|
1049
|
+
getUsers() {
|
|
1050
|
+
// delegate users get added to the end
|
|
1051
|
+
return [...this.users.values()]
|
|
1052
|
+
.filter((acct) => acct.getUserAccount().authority.equals(this.wallet.publicKey))
|
|
1053
|
+
.concat([...this.users.values()].filter((acct) => !acct.getUserAccount().authority.equals(this.wallet.publicKey)));
|
|
1054
|
+
}
|
|
1055
|
+
getUserStats() {
|
|
1056
|
+
return this.userStats;
|
|
1057
|
+
}
|
|
1058
|
+
async fetchReferrerNameAccount(name) {
|
|
1059
|
+
const nameBuffer = (0, userName_1.encodeName)(name);
|
|
1060
|
+
const referrerNameAccountPublicKey = (0, pda_1.getReferrerNamePublicKeySync)(this.program.programId, nameBuffer);
|
|
1061
|
+
return (await this.program.account.referrerName.fetch(referrerNameAccountPublicKey));
|
|
1062
|
+
}
|
|
1063
|
+
getUserStatsAccountPublicKey() {
|
|
1064
|
+
if (this.userStatsAccountPublicKey) {
|
|
1065
|
+
return this.userStatsAccountPublicKey;
|
|
1066
|
+
}
|
|
1067
|
+
this.userStatsAccountPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, this.authority);
|
|
1068
|
+
return this.userStatsAccountPublicKey;
|
|
1069
|
+
}
|
|
1070
|
+
async getUserAccountPublicKey(subAccountId, authority) {
|
|
1071
|
+
return this.getUser(subAccountId, authority).userAccountPublicKey;
|
|
1072
|
+
}
|
|
1073
|
+
getUserAccount(subAccountId, authority) {
|
|
1074
|
+
return this.getUser(subAccountId, authority).getUserAccount();
|
|
1075
|
+
}
|
|
1076
|
+
/**
|
|
1077
|
+
* Forces a fetch to rpc before returning accounts. Useful for anchor tests.
|
|
1078
|
+
* @param subAccountId
|
|
1079
|
+
*/
|
|
1080
|
+
async forceGetUserAccount(subAccountId) {
|
|
1081
|
+
await this.getUser(subAccountId).fetchAccounts();
|
|
1082
|
+
return this.getUser(subAccountId).getUserAccount();
|
|
1083
|
+
}
|
|
1084
|
+
getUserAccountAndSlot(subAccountId) {
|
|
1085
|
+
return this.getUser(subAccountId).getUserAccountAndSlot();
|
|
1086
|
+
}
|
|
1087
|
+
getSpotPosition(marketIndex, subAccountId) {
|
|
1088
|
+
return this.getUserAccount(subAccountId).spotPositions.find((spotPosition) => spotPosition.marketIndex === marketIndex);
|
|
1089
|
+
}
|
|
1090
|
+
getQuoteAssetTokenAmount() {
|
|
1091
|
+
return this.getTokenAmount(numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
|
|
1092
|
+
}
|
|
1093
|
+
/**
|
|
1094
|
+
* Returns the token amount for a given market. The spot market precision is based on the token mint decimals.
|
|
1095
|
+
* Positive if it is a deposit, negative if it is a borrow.
|
|
1096
|
+
* @param marketIndex
|
|
1097
|
+
*/
|
|
1098
|
+
getTokenAmount(marketIndex) {
|
|
1099
|
+
const spotPosition = this.getSpotPosition(marketIndex);
|
|
1100
|
+
if (spotPosition === undefined) {
|
|
1101
|
+
return numericConstants_1.ZERO;
|
|
1102
|
+
}
|
|
1103
|
+
const spotMarket = this.getSpotMarketAccount(marketIndex);
|
|
1104
|
+
return (0, spotBalance_1.getSignedTokenAmount)((0, spotBalance_1.getTokenAmount)(spotPosition.scaledBalance, spotMarket, spotPosition.balanceType), spotPosition.balanceType);
|
|
1105
|
+
}
|
|
1106
|
+
/**
|
|
1107
|
+
* Converts an amount to the spot precision for a given market. The spot market precision is based on the token mint decimals.
|
|
1108
|
+
* @param marketIndex
|
|
1109
|
+
* @param amount
|
|
1110
|
+
*/
|
|
1111
|
+
convertToSpotPrecision(marketIndex, amount) {
|
|
1112
|
+
const spotMarket = this.getSpotMarketAccount(marketIndex);
|
|
1113
|
+
return (0, spotMarket_1.castNumberToSpotPrecision)(amount, spotMarket);
|
|
1114
|
+
}
|
|
1115
|
+
/**
|
|
1116
|
+
* Converts an amount to the perp precision. The perp market precision is {@link BASE_PRECISION} (1e9).
|
|
1117
|
+
* @param amount
|
|
1118
|
+
*/
|
|
1119
|
+
convertToPerpPrecision(amount) {
|
|
1120
|
+
if (typeof amount === 'number') {
|
|
1121
|
+
return (0, utils_1.numberToSafeBN)(amount, numericConstants_1.BASE_PRECISION);
|
|
1122
|
+
}
|
|
1123
|
+
else {
|
|
1124
|
+
return amount.mul(numericConstants_1.BASE_PRECISION);
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
/**
|
|
1128
|
+
* Converts an amount to the price precision. The perp market precision is {@link PRICE_PRECISION} (1e6).
|
|
1129
|
+
* @param amount
|
|
1130
|
+
*/
|
|
1131
|
+
convertToPricePrecision(amount) {
|
|
1132
|
+
if (typeof amount === 'number') {
|
|
1133
|
+
return (0, utils_1.numberToSafeBN)(amount, numericConstants_1.PRICE_PRECISION);
|
|
1134
|
+
}
|
|
1135
|
+
else {
|
|
1136
|
+
return amount.mul(numericConstants_1.BASE_PRECISION);
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
/**
|
|
1140
|
+
* Each drift instruction must include perp and sport market accounts in the ix remaining accounts.
|
|
1141
|
+
* Use this function to force a subset of markets to be included in the remaining accounts for every ix
|
|
1142
|
+
*
|
|
1143
|
+
* @param perpMarketIndexes
|
|
1144
|
+
* @param spotMarketIndexes
|
|
1145
|
+
*/
|
|
1146
|
+
mustIncludeMarketsInIx({ perpMarketIndexes, spotMarketIndexes, }) {
|
|
1147
|
+
perpMarketIndexes.forEach((perpMarketIndex) => {
|
|
1148
|
+
this.mustIncludePerpMarketIndexes.add(perpMarketIndex);
|
|
1149
|
+
});
|
|
1150
|
+
spotMarketIndexes.forEach((spotMarketIndex) => {
|
|
1151
|
+
this.mustIncludeSpotMarketIndexes.add(spotMarketIndex);
|
|
1152
|
+
});
|
|
1153
|
+
}
|
|
1154
|
+
getRemainingAccounts(params) {
|
|
1155
|
+
var _a;
|
|
1156
|
+
const { oracleAccountMap, spotMarketAccountMap, perpMarketAccountMap } = this.getRemainingAccountMapsForUsers(params.userAccounts);
|
|
1157
|
+
if (params.useMarketLastSlotCache) {
|
|
1158
|
+
const lastUserSlot = (_a = this.getUserAccountAndSlot()) === null || _a === void 0 ? void 0 : _a.slot;
|
|
1159
|
+
for (const [marketIndex, slot,] of this.perpMarketLastSlotCache.entries()) {
|
|
1160
|
+
// if cache has more recent slot than user positions account slot, add market to remaining accounts
|
|
1161
|
+
// otherwise remove from slot
|
|
1162
|
+
if (slot > lastUserSlot) {
|
|
1163
|
+
this.addPerpMarketToRemainingAccountMaps(marketIndex, false, oracleAccountMap, spotMarketAccountMap, perpMarketAccountMap);
|
|
1164
|
+
}
|
|
1165
|
+
else {
|
|
1166
|
+
this.perpMarketLastSlotCache.delete(marketIndex);
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
for (const [marketIndex, slot,] of this.spotMarketLastSlotCache.entries()) {
|
|
1170
|
+
// if cache has more recent slot than user positions account slot, add market to remaining accounts
|
|
1171
|
+
// otherwise remove from slot
|
|
1172
|
+
if (slot > lastUserSlot) {
|
|
1173
|
+
this.addSpotMarketToRemainingAccountMaps(marketIndex, false, oracleAccountMap, spotMarketAccountMap);
|
|
1174
|
+
}
|
|
1175
|
+
else {
|
|
1176
|
+
this.spotMarketLastSlotCache.delete(marketIndex);
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
if (params.readablePerpMarketIndex !== undefined) {
|
|
1181
|
+
const readablePerpMarketIndexes = Array.isArray(params.readablePerpMarketIndex)
|
|
1182
|
+
? params.readablePerpMarketIndex
|
|
1183
|
+
: [params.readablePerpMarketIndex];
|
|
1184
|
+
for (const marketIndex of readablePerpMarketIndexes) {
|
|
1185
|
+
this.addPerpMarketToRemainingAccountMaps(marketIndex, false, oracleAccountMap, spotMarketAccountMap, perpMarketAccountMap);
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
for (const perpMarketIndex of this.mustIncludePerpMarketIndexes.values()) {
|
|
1189
|
+
this.addPerpMarketToRemainingAccountMaps(perpMarketIndex, false, oracleAccountMap, spotMarketAccountMap, perpMarketAccountMap);
|
|
1190
|
+
}
|
|
1191
|
+
if (params.readableSpotMarketIndexes !== undefined) {
|
|
1192
|
+
for (const readableSpotMarketIndex of params.readableSpotMarketIndexes) {
|
|
1193
|
+
this.addSpotMarketToRemainingAccountMaps(readableSpotMarketIndex, false, oracleAccountMap, spotMarketAccountMap);
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
for (const spotMarketIndex of this.mustIncludeSpotMarketIndexes.values()) {
|
|
1197
|
+
this.addSpotMarketToRemainingAccountMaps(spotMarketIndex, false, oracleAccountMap, spotMarketAccountMap);
|
|
1198
|
+
}
|
|
1199
|
+
if (params.writablePerpMarketIndexes !== undefined) {
|
|
1200
|
+
for (const writablePerpMarketIndex of params.writablePerpMarketIndexes) {
|
|
1201
|
+
this.addPerpMarketToRemainingAccountMaps(writablePerpMarketIndex, true, oracleAccountMap, spotMarketAccountMap, perpMarketAccountMap);
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
if (params.writableSpotMarketIndexes !== undefined) {
|
|
1205
|
+
for (const writableSpotMarketIndex of params.writableSpotMarketIndexes) {
|
|
1206
|
+
this.addSpotMarketToRemainingAccountMaps(writableSpotMarketIndex, true, oracleAccountMap, spotMarketAccountMap);
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
return [
|
|
1210
|
+
...oracleAccountMap.values(),
|
|
1211
|
+
...spotMarketAccountMap.values(),
|
|
1212
|
+
...perpMarketAccountMap.values(),
|
|
1213
|
+
];
|
|
1214
|
+
}
|
|
1215
|
+
addPerpMarketToRemainingAccountMaps(marketIndex, writable, oracleAccountMap, spotMarketAccountMap, perpMarketAccountMap) {
|
|
1216
|
+
const perpMarketAccount = this.getPerpMarketAccount(marketIndex);
|
|
1217
|
+
perpMarketAccountMap.set(marketIndex, {
|
|
1218
|
+
pubkey: perpMarketAccount.pubkey,
|
|
1219
|
+
isSigner: false,
|
|
1220
|
+
isWritable: writable,
|
|
1221
|
+
});
|
|
1222
|
+
const oracleWritable = writable && (0, types_1.isVariant)(perpMarketAccount.amm.oracleSource, 'prelaunch');
|
|
1223
|
+
oracleAccountMap.set(perpMarketAccount.amm.oracle.toString(), {
|
|
1224
|
+
pubkey: perpMarketAccount.amm.oracle,
|
|
1225
|
+
isSigner: false,
|
|
1226
|
+
isWritable: oracleWritable,
|
|
1227
|
+
});
|
|
1228
|
+
this.addSpotMarketToRemainingAccountMaps(perpMarketAccount.quoteSpotMarketIndex, false, oracleAccountMap, spotMarketAccountMap);
|
|
1229
|
+
}
|
|
1230
|
+
addSpotMarketToRemainingAccountMaps(marketIndex, writable, oracleAccountMap, spotMarketAccountMap) {
|
|
1231
|
+
const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
|
|
1232
|
+
spotMarketAccountMap.set(spotMarketAccount.marketIndex, {
|
|
1233
|
+
pubkey: spotMarketAccount.pubkey,
|
|
1234
|
+
isSigner: false,
|
|
1235
|
+
isWritable: writable,
|
|
1236
|
+
});
|
|
1237
|
+
if (!spotMarketAccount.oracle.equals(web3_js_1.PublicKey.default)) {
|
|
1238
|
+
oracleAccountMap.set(spotMarketAccount.oracle.toString(), {
|
|
1239
|
+
pubkey: spotMarketAccount.oracle,
|
|
1240
|
+
isSigner: false,
|
|
1241
|
+
isWritable: false,
|
|
1242
|
+
});
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
getRemainingAccountMapsForUsers(userAccounts) {
|
|
1246
|
+
const oracleAccountMap = new Map();
|
|
1247
|
+
const spotMarketAccountMap = new Map();
|
|
1248
|
+
const perpMarketAccountMap = new Map();
|
|
1249
|
+
for (const userAccount of userAccounts) {
|
|
1250
|
+
for (const spotPosition of userAccount.spotPositions) {
|
|
1251
|
+
if (!(0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
|
|
1252
|
+
this.addSpotMarketToRemainingAccountMaps(spotPosition.marketIndex, false, oracleAccountMap, spotMarketAccountMap);
|
|
1253
|
+
if (!spotPosition.openAsks.eq(numericConstants_1.ZERO) ||
|
|
1254
|
+
!spotPosition.openBids.eq(numericConstants_1.ZERO)) {
|
|
1255
|
+
this.addSpotMarketToRemainingAccountMaps(numericConstants_1.QUOTE_SPOT_MARKET_INDEX, false, oracleAccountMap, spotMarketAccountMap);
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
for (const position of userAccount.perpPositions) {
|
|
1260
|
+
if (!(0, position_1.positionIsAvailable)(position)) {
|
|
1261
|
+
this.addPerpMarketToRemainingAccountMaps(position.marketIndex, false, oracleAccountMap, spotMarketAccountMap, perpMarketAccountMap);
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
return {
|
|
1266
|
+
oracleAccountMap,
|
|
1267
|
+
spotMarketAccountMap,
|
|
1268
|
+
perpMarketAccountMap,
|
|
1269
|
+
};
|
|
1270
|
+
}
|
|
1271
|
+
getOrder(orderId, subAccountId) {
|
|
1272
|
+
var _a;
|
|
1273
|
+
return (_a = this.getUserAccount(subAccountId)) === null || _a === void 0 ? void 0 : _a.orders.find((order) => order.orderId === orderId);
|
|
1274
|
+
}
|
|
1275
|
+
getOrderByUserId(userOrderId, subAccountId) {
|
|
1276
|
+
var _a;
|
|
1277
|
+
return (_a = this.getUserAccount(subAccountId)) === null || _a === void 0 ? void 0 : _a.orders.find((order) => order.userOrderId === userOrderId);
|
|
1278
|
+
}
|
|
1279
|
+
/**
|
|
1280
|
+
* Get the associated token address for the given spot market
|
|
1281
|
+
* @param marketIndex
|
|
1282
|
+
* @param useNative
|
|
1283
|
+
* @param tokenProgram
|
|
1284
|
+
*/
|
|
1285
|
+
async getAssociatedTokenAccount(marketIndex, useNative = true, tokenProgram = spl_token_1.TOKEN_PROGRAM_ID) {
|
|
1286
|
+
const spotMarket = this.getSpotMarketAccount(marketIndex);
|
|
1287
|
+
if (useNative && spotMarket.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT)) {
|
|
1288
|
+
return this.wallet.publicKey;
|
|
1289
|
+
}
|
|
1290
|
+
const mint = spotMarket.mint;
|
|
1291
|
+
return await (0, spl_token_1.getAssociatedTokenAddress)(mint, this.wallet.publicKey, undefined, tokenProgram);
|
|
1292
|
+
}
|
|
1293
|
+
createAssociatedTokenAccountIdempotentInstruction(account, payer, owner, mint, tokenProgram = spl_token_1.TOKEN_PROGRAM_ID) {
|
|
1294
|
+
return new web3_js_1.TransactionInstruction({
|
|
1295
|
+
keys: [
|
|
1296
|
+
{ pubkey: payer, isSigner: true, isWritable: true },
|
|
1297
|
+
{ pubkey: account, isSigner: false, isWritable: true },
|
|
1298
|
+
{ pubkey: owner, isSigner: false, isWritable: false },
|
|
1299
|
+
{ pubkey: mint, isSigner: false, isWritable: false },
|
|
1300
|
+
{
|
|
1301
|
+
pubkey: anchor.web3.SystemProgram.programId,
|
|
1302
|
+
isSigner: false,
|
|
1303
|
+
isWritable: false,
|
|
1304
|
+
},
|
|
1305
|
+
{ pubkey: tokenProgram, isSigner: false, isWritable: false },
|
|
1306
|
+
],
|
|
1307
|
+
programId: spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID,
|
|
1308
|
+
data: Buffer.from([0x1]),
|
|
1309
|
+
});
|
|
1310
|
+
}
|
|
1311
|
+
async getDepositTxnIx(amount, marketIndex, associatedTokenAccount, subAccountId, reduceOnly = false) {
|
|
1312
|
+
const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
|
|
1313
|
+
const isSolMarket = spotMarketAccount.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
|
|
1314
|
+
const signerAuthority = this.wallet.publicKey;
|
|
1315
|
+
const createWSOLTokenAccount = isSolMarket && associatedTokenAccount.equals(signerAuthority);
|
|
1316
|
+
const instructions = [];
|
|
1317
|
+
if (createWSOLTokenAccount) {
|
|
1318
|
+
const { ixs, pubkey } = await this.getWrappedSolAccountCreationIxs(amount, true);
|
|
1319
|
+
associatedTokenAccount = pubkey;
|
|
1320
|
+
instructions.push(...ixs);
|
|
1321
|
+
}
|
|
1322
|
+
const depositCollateralIx = await this.getDepositInstruction(amount, marketIndex, associatedTokenAccount, subAccountId, reduceOnly, true);
|
|
1323
|
+
instructions.push(depositCollateralIx);
|
|
1324
|
+
// Close the wrapped sol account at the end of the transaction
|
|
1325
|
+
if (createWSOLTokenAccount) {
|
|
1326
|
+
instructions.push((0, spl_token_1.createCloseAccountInstruction)(associatedTokenAccount, signerAuthority, signerAuthority, []));
|
|
1327
|
+
}
|
|
1328
|
+
return instructions;
|
|
1329
|
+
}
|
|
1330
|
+
async createDepositTxn(amount, marketIndex, associatedTokenAccount, subAccountId, reduceOnly = false, txParams) {
|
|
1331
|
+
const instructions = await this.getDepositTxnIx(amount, marketIndex, associatedTokenAccount, subAccountId, reduceOnly);
|
|
1332
|
+
txParams = { ...(txParams !== null && txParams !== void 0 ? txParams : this.txParams), computeUnits: 600000 };
|
|
1333
|
+
const tx = await this.buildTransaction(instructions, txParams);
|
|
1334
|
+
return tx;
|
|
1335
|
+
}
|
|
1336
|
+
/**
|
|
1337
|
+
* Deposit funds into the given spot market
|
|
1338
|
+
*
|
|
1339
|
+
* @param amount to deposit
|
|
1340
|
+
* @param marketIndex spot market index to deposit into
|
|
1341
|
+
* @param associatedTokenAccount can be the wallet public key if using native sol
|
|
1342
|
+
* @param subAccountId subaccountId to deposit
|
|
1343
|
+
* @param reduceOnly if true, deposit must not increase account risk
|
|
1344
|
+
*/
|
|
1345
|
+
async deposit(amount, marketIndex, associatedTokenAccount, subAccountId, reduceOnly = false, txParams) {
|
|
1346
|
+
const tx = await this.createDepositTxn(amount, marketIndex, associatedTokenAccount, subAccountId, reduceOnly, txParams);
|
|
1347
|
+
const { txSig, slot } = await this.sendTransaction(tx, [], this.opts);
|
|
1348
|
+
this.spotMarketLastSlotCache.set(marketIndex, slot);
|
|
1349
|
+
return txSig;
|
|
1350
|
+
}
|
|
1351
|
+
async getDepositInstruction(amount, marketIndex, userTokenAccount, subAccountId, reduceOnly = false, userInitialized = true) {
|
|
1352
|
+
const userAccountPublicKey = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.authority, subAccountId !== null && subAccountId !== void 0 ? subAccountId : this.activeSubAccountId);
|
|
1353
|
+
let remainingAccounts = [];
|
|
1354
|
+
if (userInitialized) {
|
|
1355
|
+
remainingAccounts = this.getRemainingAccounts({
|
|
1356
|
+
userAccounts: [await this.forceGetUserAccount()],
|
|
1357
|
+
useMarketLastSlotCache: true,
|
|
1358
|
+
writableSpotMarketIndexes: [marketIndex],
|
|
1359
|
+
});
|
|
1360
|
+
}
|
|
1361
|
+
else {
|
|
1362
|
+
remainingAccounts = this.getRemainingAccounts({
|
|
1363
|
+
userAccounts: [],
|
|
1364
|
+
writableSpotMarketIndexes: [marketIndex],
|
|
1365
|
+
});
|
|
1366
|
+
}
|
|
1367
|
+
const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
|
|
1368
|
+
this.addTokenMintToRemainingAccounts(spotMarketAccount, remainingAccounts);
|
|
1369
|
+
const tokenProgram = this.getTokenProgramForSpotMarket(spotMarketAccount);
|
|
1370
|
+
return await this.program.instruction.deposit(marketIndex, amount, reduceOnly, {
|
|
1371
|
+
accounts: {
|
|
1372
|
+
state: await this.getStatePublicKey(),
|
|
1373
|
+
spotMarket: spotMarketAccount.pubkey,
|
|
1374
|
+
spotMarketVault: spotMarketAccount.vault,
|
|
1375
|
+
user: userAccountPublicKey,
|
|
1376
|
+
userStats: this.getUserStatsAccountPublicKey(),
|
|
1377
|
+
userTokenAccount: userTokenAccount,
|
|
1378
|
+
authority: this.wallet.publicKey,
|
|
1379
|
+
tokenProgram,
|
|
1380
|
+
},
|
|
1381
|
+
remainingAccounts,
|
|
1382
|
+
});
|
|
1383
|
+
}
|
|
1384
|
+
async checkIfAccountExists(account) {
|
|
1385
|
+
try {
|
|
1386
|
+
const accountInfo = await this.connection.getAccountInfo(account);
|
|
1387
|
+
return accountInfo != null;
|
|
1388
|
+
}
|
|
1389
|
+
catch (e) {
|
|
1390
|
+
// Doesn't already exist
|
|
1391
|
+
return false;
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
async getWrappedSolAccountCreationIxs(amount, includeRent) {
|
|
1395
|
+
const authority = this.wallet.publicKey;
|
|
1396
|
+
// Generate a random seed for wrappedSolAccount.
|
|
1397
|
+
const seed = web3_js_1.Keypair.generate().publicKey.toBase58().slice(0, 32);
|
|
1398
|
+
// Calculate a publicKey that will be controlled by the authority.
|
|
1399
|
+
const wrappedSolAccount = await web3_js_1.PublicKey.createWithSeed(authority, seed, spl_token_1.TOKEN_PROGRAM_ID);
|
|
1400
|
+
const result = {
|
|
1401
|
+
ixs: [],
|
|
1402
|
+
signers: [],
|
|
1403
|
+
pubkey: wrappedSolAccount,
|
|
1404
|
+
};
|
|
1405
|
+
const rentSpaceLamports = new anchor_1.BN(web3_js_1.LAMPORTS_PER_SOL / 100);
|
|
1406
|
+
const lamports = includeRent
|
|
1407
|
+
? amount.add(rentSpaceLamports)
|
|
1408
|
+
: rentSpaceLamports;
|
|
1409
|
+
result.ixs.push(web3_js_1.SystemProgram.createAccountWithSeed({
|
|
1410
|
+
fromPubkey: authority,
|
|
1411
|
+
basePubkey: authority,
|
|
1412
|
+
seed,
|
|
1413
|
+
newAccountPubkey: wrappedSolAccount,
|
|
1414
|
+
lamports: lamports.toNumber(),
|
|
1415
|
+
space: 165,
|
|
1416
|
+
programId: spl_token_1.TOKEN_PROGRAM_ID,
|
|
1417
|
+
}));
|
|
1418
|
+
result.ixs.push((0, spl_token_1.createInitializeAccountInstruction)(wrappedSolAccount, spotMarkets_1.WRAPPED_SOL_MINT, authority));
|
|
1419
|
+
return result;
|
|
1420
|
+
}
|
|
1421
|
+
getTokenProgramForSpotMarket(spotMarketAccount) {
|
|
1422
|
+
if (spotMarketAccount.tokenProgram === 1) {
|
|
1423
|
+
return spl_token_1.TOKEN_2022_PROGRAM_ID;
|
|
1424
|
+
}
|
|
1425
|
+
return spl_token_1.TOKEN_PROGRAM_ID;
|
|
1426
|
+
}
|
|
1427
|
+
addTokenMintToRemainingAccounts(spotMarketAccount, remainingAccounts) {
|
|
1428
|
+
if (spotMarketAccount.tokenProgram === 1) {
|
|
1429
|
+
remainingAccounts.push({
|
|
1430
|
+
pubkey: spotMarketAccount.mint,
|
|
1431
|
+
isSigner: false,
|
|
1432
|
+
isWritable: false,
|
|
1433
|
+
});
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
getAssociatedTokenAccountCreationIx(tokenMintAddress, associatedTokenAddress, tokenProgram) {
|
|
1437
|
+
return (0, spl_token_1.createAssociatedTokenAccountInstruction)(this.wallet.publicKey, associatedTokenAddress, this.wallet.publicKey, tokenMintAddress, tokenProgram);
|
|
1438
|
+
}
|
|
1439
|
+
async createInitializeUserAccountAndDepositCollateralIxs(amount, userTokenAccount, marketIndex = 0, subAccountId = 0, name, fromSubAccountId, referrerInfo, donateAmount, customMaxMarginRatio) {
|
|
1440
|
+
const ixs = [];
|
|
1441
|
+
const [userAccountPublicKey, initializeUserAccountIx] = await this.getInitializeUserInstructions(subAccountId, name, referrerInfo);
|
|
1442
|
+
const spotMarket = this.getSpotMarketAccount(marketIndex);
|
|
1443
|
+
const isSolMarket = spotMarket.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
|
|
1444
|
+
const authority = this.wallet.publicKey;
|
|
1445
|
+
const isFromSubaccount = fromSubAccountId !== null &&
|
|
1446
|
+
fromSubAccountId !== undefined &&
|
|
1447
|
+
!isNaN(fromSubAccountId);
|
|
1448
|
+
donateAmount = donateAmount ? donateAmount : numericConstants_1.ZERO;
|
|
1449
|
+
const createWSOLTokenAccount = (isSolMarket &&
|
|
1450
|
+
userTokenAccount.equals(authority) &&
|
|
1451
|
+
!isFromSubaccount) ||
|
|
1452
|
+
!donateAmount.eq(numericConstants_1.ZERO);
|
|
1453
|
+
const wSolAmount = isSolMarket ? amount.add(donateAmount) : donateAmount;
|
|
1454
|
+
let wsolTokenAccount;
|
|
1455
|
+
if (createWSOLTokenAccount) {
|
|
1456
|
+
const { ixs: startIxs, pubkey } = await this.getWrappedSolAccountCreationIxs(wSolAmount, true);
|
|
1457
|
+
wsolTokenAccount = pubkey;
|
|
1458
|
+
if (isSolMarket) {
|
|
1459
|
+
userTokenAccount = pubkey;
|
|
1460
|
+
}
|
|
1461
|
+
ixs.push(...startIxs);
|
|
1462
|
+
}
|
|
1463
|
+
const depositCollateralIx = isFromSubaccount
|
|
1464
|
+
? await this.getTransferDepositIx(amount, marketIndex, fromSubAccountId, subAccountId)
|
|
1465
|
+
: await this.getDepositInstruction(amount, marketIndex, userTokenAccount, subAccountId, false, false);
|
|
1466
|
+
if (subAccountId === 0) {
|
|
1467
|
+
if (!(await this.checkIfAccountExists(this.getUserStatsAccountPublicKey()))) {
|
|
1468
|
+
ixs.push(await this.getInitializeUserStatsIx());
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
ixs.push(initializeUserAccountIx, depositCollateralIx);
|
|
1472
|
+
if (!donateAmount.eq(numericConstants_1.ZERO)) {
|
|
1473
|
+
const donateIx = await this.getDepositIntoSpotMarketRevenuePoolIx(1, donateAmount, wsolTokenAccount);
|
|
1474
|
+
ixs.push(donateIx);
|
|
1475
|
+
}
|
|
1476
|
+
// Set the max margin ratio to initialize account with if passed
|
|
1477
|
+
if (customMaxMarginRatio) {
|
|
1478
|
+
const customMarginRatioIx = await this.getUpdateUserCustomMarginRatioIx(customMaxMarginRatio, subAccountId);
|
|
1479
|
+
ixs.push(customMarginRatioIx);
|
|
1480
|
+
}
|
|
1481
|
+
// Close the wrapped sol account at the end of the transaction
|
|
1482
|
+
if (createWSOLTokenAccount) {
|
|
1483
|
+
ixs.push((0, spl_token_1.createCloseAccountInstruction)(wsolTokenAccount, authority, authority, []));
|
|
1484
|
+
}
|
|
1485
|
+
return {
|
|
1486
|
+
ixs,
|
|
1487
|
+
userAccountPublicKey,
|
|
1488
|
+
};
|
|
1489
|
+
}
|
|
1490
|
+
async createInitializeUserAccountAndDepositCollateral(amount, userTokenAccount, marketIndex = 0, subAccountId = 0, name, fromSubAccountId, referrerInfo, donateAmount, txParams, customMaxMarginRatio) {
|
|
1491
|
+
const { ixs, userAccountPublicKey } = await this.createInitializeUserAccountAndDepositCollateralIxs(amount, userTokenAccount, marketIndex, subAccountId, name, fromSubAccountId, referrerInfo, donateAmount, customMaxMarginRatio);
|
|
1492
|
+
const tx = await this.buildTransaction(ixs, txParams);
|
|
1493
|
+
return [tx, userAccountPublicKey];
|
|
1494
|
+
}
|
|
1495
|
+
/**
|
|
1496
|
+
* Creates the User account for a user, and deposits some initial collateral
|
|
1497
|
+
* @param amount
|
|
1498
|
+
* @param userTokenAccount
|
|
1499
|
+
* @param marketIndex
|
|
1500
|
+
* @param subAccountId
|
|
1501
|
+
* @param name
|
|
1502
|
+
* @param fromSubAccountId
|
|
1503
|
+
* @param referrerInfo
|
|
1504
|
+
* @param donateAmount
|
|
1505
|
+
* @param txParams
|
|
1506
|
+
* @returns
|
|
1507
|
+
*/
|
|
1508
|
+
async initializeUserAccountAndDepositCollateral(amount, userTokenAccount, marketIndex = 0, subAccountId = 0, name, fromSubAccountId, referrerInfo, donateAmount, txParams, customMaxMarginRatio) {
|
|
1509
|
+
const [tx, userAccountPublicKey] = await this.createInitializeUserAccountAndDepositCollateral(amount, userTokenAccount, marketIndex, subAccountId, name, fromSubAccountId, referrerInfo, donateAmount, txParams, customMaxMarginRatio);
|
|
1510
|
+
const additionalSigners = [];
|
|
1511
|
+
const { txSig, slot } = await this.sendTransaction(tx, additionalSigners, this.opts);
|
|
1512
|
+
this.spotMarketLastSlotCache.set(marketIndex, slot);
|
|
1513
|
+
await this.addUser(subAccountId);
|
|
1514
|
+
return [txSig, userAccountPublicKey];
|
|
1515
|
+
}
|
|
1516
|
+
async initializeUserAccountForDevnet(subAccountId = 0, name = userName_1.DEFAULT_USER_NAME, marketIndex, tokenFaucet, amount, referrerInfo, txParams) {
|
|
1517
|
+
const ixs = [];
|
|
1518
|
+
const [associateTokenPublicKey, createAssociatedAccountIx, mintToIx] = await tokenFaucet.createAssociatedTokenAccountAndMintToInstructions(this.wallet.publicKey, amount);
|
|
1519
|
+
const [userAccountPublicKey, initializeUserAccountIx] = await this.getInitializeUserInstructions(subAccountId, name, referrerInfo);
|
|
1520
|
+
const depositCollateralIx = await this.getDepositInstruction(amount, marketIndex, associateTokenPublicKey, subAccountId, false, false);
|
|
1521
|
+
ixs.push(createAssociatedAccountIx, mintToIx);
|
|
1522
|
+
if (subAccountId === 0) {
|
|
1523
|
+
if (!(await this.checkIfAccountExists(this.getUserStatsAccountPublicKey()))) {
|
|
1524
|
+
ixs.push(await this.getInitializeUserStatsIx());
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
ixs.push(initializeUserAccountIx, depositCollateralIx);
|
|
1528
|
+
const tx = await this.buildTransaction(ixs, txParams);
|
|
1529
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
1530
|
+
await this.addUser(subAccountId);
|
|
1531
|
+
return [txSig, userAccountPublicKey];
|
|
1532
|
+
}
|
|
1533
|
+
async getWithdrawalIxs(amount, marketIndex, associatedTokenAddress, reduceOnly = false, subAccountId, updateFuel = false) {
|
|
1534
|
+
const withdrawIxs = [];
|
|
1535
|
+
const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
|
|
1536
|
+
const isSolMarket = spotMarketAccount.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
|
|
1537
|
+
const authority = this.wallet.publicKey;
|
|
1538
|
+
if (updateFuel) {
|
|
1539
|
+
const updateFuelIx = await this.getUpdateUserFuelBonusIx(await this.getUserAccountPublicKey(subAccountId), this.getUserAccount(subAccountId), this.authority);
|
|
1540
|
+
withdrawIxs.push(updateFuelIx);
|
|
1541
|
+
}
|
|
1542
|
+
const createWSOLTokenAccount = isSolMarket && associatedTokenAddress.equals(authority);
|
|
1543
|
+
if (createWSOLTokenAccount) {
|
|
1544
|
+
const { ixs, pubkey } = await this.getWrappedSolAccountCreationIxs(amount, false);
|
|
1545
|
+
associatedTokenAddress = pubkey;
|
|
1546
|
+
withdrawIxs.push(...ixs);
|
|
1547
|
+
}
|
|
1548
|
+
else {
|
|
1549
|
+
const accountExists = await this.checkIfAccountExists(associatedTokenAddress);
|
|
1550
|
+
if (!accountExists) {
|
|
1551
|
+
const createAssociatedTokenAccountIx = this.getAssociatedTokenAccountCreationIx(spotMarketAccount.mint, associatedTokenAddress, this.getTokenProgramForSpotMarket(spotMarketAccount));
|
|
1552
|
+
withdrawIxs.push(createAssociatedTokenAccountIx);
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
const withdrawCollateralIx = await this.getWithdrawIx(amount, spotMarketAccount.marketIndex, associatedTokenAddress, reduceOnly, subAccountId);
|
|
1556
|
+
withdrawIxs.push(withdrawCollateralIx);
|
|
1557
|
+
// Close the wrapped sol account at the end of the transaction
|
|
1558
|
+
if (createWSOLTokenAccount) {
|
|
1559
|
+
withdrawIxs.push((0, spl_token_1.createCloseAccountInstruction)(associatedTokenAddress, authority, authority, []));
|
|
1560
|
+
}
|
|
1561
|
+
return withdrawIxs;
|
|
1562
|
+
}
|
|
1563
|
+
/**
|
|
1564
|
+
* Withdraws from a user account. If deposit doesn't already exist, creates a borrow
|
|
1565
|
+
* @param amount
|
|
1566
|
+
* @param marketIndex
|
|
1567
|
+
* @param associatedTokenAddress - the token account to withdraw to. can be the wallet public key if using native sol
|
|
1568
|
+
* @param reduceOnly
|
|
1569
|
+
*/
|
|
1570
|
+
async withdraw(amount, marketIndex, associatedTokenAddress, reduceOnly = false, subAccountId, txParams, updateFuel = false) {
|
|
1571
|
+
const additionalSigners = [];
|
|
1572
|
+
const withdrawIxs = await this.getWithdrawalIxs(amount, marketIndex, associatedTokenAddress, reduceOnly, subAccountId, updateFuel);
|
|
1573
|
+
const tx = await this.buildTransaction(withdrawIxs, txParams !== null && txParams !== void 0 ? txParams : this.txParams);
|
|
1574
|
+
const { txSig, slot } = await this.sendTransaction(tx, additionalSigners, this.opts);
|
|
1575
|
+
this.spotMarketLastSlotCache.set(marketIndex, slot);
|
|
1576
|
+
return txSig;
|
|
1577
|
+
}
|
|
1578
|
+
async withdrawAllDustPositions(subAccountId, txParams, opts) {
|
|
1579
|
+
var _a, _b;
|
|
1580
|
+
const user = this.getUser(subAccountId);
|
|
1581
|
+
const dustPositionSpotMarketAccounts = user.getSpotMarketAccountsWithDustPosition();
|
|
1582
|
+
if (!dustPositionSpotMarketAccounts ||
|
|
1583
|
+
dustPositionSpotMarketAccounts.length === 0) {
|
|
1584
|
+
(_a = opts === null || opts === void 0 ? void 0 : opts.dustPositionCountCallback) === null || _a === void 0 ? void 0 : _a.call(opts, 0);
|
|
1585
|
+
return undefined;
|
|
1586
|
+
}
|
|
1587
|
+
(_b = opts === null || opts === void 0 ? void 0 : opts.dustPositionCountCallback) === null || _b === void 0 ? void 0 : _b.call(opts, dustPositionSpotMarketAccounts.length);
|
|
1588
|
+
let allWithdrawIxs = [];
|
|
1589
|
+
for (const position of dustPositionSpotMarketAccounts) {
|
|
1590
|
+
const tokenAccount = await (0, spl_token_1.getAssociatedTokenAddress)(position.mint, this.wallet.publicKey);
|
|
1591
|
+
const tokenAmount = await user.getTokenAmount(position.marketIndex);
|
|
1592
|
+
const withdrawIxs = await this.getWithdrawalIxs(tokenAmount.muln(2), // 2x to ensure all dust is withdrawn
|
|
1593
|
+
position.marketIndex, tokenAccount, true, // reduce-only true to ensure all dust is withdrawn
|
|
1594
|
+
subAccountId);
|
|
1595
|
+
allWithdrawIxs = allWithdrawIxs.concat(withdrawIxs);
|
|
1596
|
+
}
|
|
1597
|
+
const tx = await this.buildTransaction(allWithdrawIxs, txParams !== null && txParams !== void 0 ? txParams : this.txParams);
|
|
1598
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
1599
|
+
return txSig;
|
|
1600
|
+
}
|
|
1601
|
+
async getWithdrawIx(amount, marketIndex, userTokenAccount, reduceOnly = false, subAccountId) {
|
|
1602
|
+
const user = await this.getUserAccountPublicKey(subAccountId);
|
|
1603
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
1604
|
+
userAccounts: [this.getUserAccount(subAccountId)],
|
|
1605
|
+
useMarketLastSlotCache: true,
|
|
1606
|
+
writableSpotMarketIndexes: [marketIndex],
|
|
1607
|
+
readableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
|
|
1608
|
+
});
|
|
1609
|
+
const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
|
|
1610
|
+
this.addTokenMintToRemainingAccounts(spotMarketAccount, remainingAccounts);
|
|
1611
|
+
const tokenProgram = this.getTokenProgramForSpotMarket(spotMarketAccount);
|
|
1612
|
+
return await this.program.instruction.withdraw(marketIndex, amount, reduceOnly, {
|
|
1613
|
+
accounts: {
|
|
1614
|
+
state: await this.getStatePublicKey(),
|
|
1615
|
+
spotMarket: spotMarketAccount.pubkey,
|
|
1616
|
+
spotMarketVault: spotMarketAccount.vault,
|
|
1617
|
+
driftSigner: this.getSignerPublicKey(),
|
|
1618
|
+
user,
|
|
1619
|
+
userStats: this.getUserStatsAccountPublicKey(),
|
|
1620
|
+
userTokenAccount: userTokenAccount,
|
|
1621
|
+
authority: this.wallet.publicKey,
|
|
1622
|
+
tokenProgram,
|
|
1623
|
+
},
|
|
1624
|
+
remainingAccounts,
|
|
1625
|
+
});
|
|
1626
|
+
}
|
|
1627
|
+
/**
|
|
1628
|
+
* Withdraws from the fromSubAccount and deposits into the toSubAccount
|
|
1629
|
+
* @param amount
|
|
1630
|
+
* @param marketIndex
|
|
1631
|
+
* @param fromSubAccountId
|
|
1632
|
+
* @param toSubAccountId
|
|
1633
|
+
* @param txParams
|
|
1634
|
+
*/
|
|
1635
|
+
async transferDeposit(amount, marketIndex, fromSubAccountId, toSubAccountId, txParams) {
|
|
1636
|
+
const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getTransferDepositIx(amount, marketIndex, fromSubAccountId, toSubAccountId), txParams), [], this.opts);
|
|
1637
|
+
if (fromSubAccountId === this.activeSubAccountId ||
|
|
1638
|
+
toSubAccountId === this.activeSubAccountId) {
|
|
1639
|
+
this.spotMarketLastSlotCache.set(marketIndex, slot);
|
|
1640
|
+
}
|
|
1641
|
+
return txSig;
|
|
1642
|
+
}
|
|
1643
|
+
async getTransferDepositIx(amount, marketIndex, fromSubAccountId, toSubAccountId) {
|
|
1644
|
+
const fromUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, fromSubAccountId);
|
|
1645
|
+
const toUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, toSubAccountId);
|
|
1646
|
+
let remainingAccounts;
|
|
1647
|
+
const userMapKey = this.getUserMapKey(fromSubAccountId, this.wallet.publicKey);
|
|
1648
|
+
if (this.users.has(userMapKey)) {
|
|
1649
|
+
remainingAccounts = this.getRemainingAccounts({
|
|
1650
|
+
userAccounts: [this.users.get(userMapKey).getUserAccount()],
|
|
1651
|
+
useMarketLastSlotCache: true,
|
|
1652
|
+
writableSpotMarketIndexes: [marketIndex],
|
|
1653
|
+
});
|
|
1654
|
+
}
|
|
1655
|
+
else {
|
|
1656
|
+
const userAccountPublicKey = (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.authority, fromSubAccountId);
|
|
1657
|
+
const fromUserAccount = (await this.program.account.user.fetch(userAccountPublicKey));
|
|
1658
|
+
remainingAccounts = this.getRemainingAccounts({
|
|
1659
|
+
userAccounts: [fromUserAccount],
|
|
1660
|
+
useMarketLastSlotCache: true,
|
|
1661
|
+
writableSpotMarketIndexes: [marketIndex],
|
|
1662
|
+
});
|
|
1663
|
+
}
|
|
1664
|
+
return await this.program.instruction.transferDeposit(marketIndex, amount, {
|
|
1665
|
+
accounts: {
|
|
1666
|
+
authority: this.wallet.publicKey,
|
|
1667
|
+
fromUser,
|
|
1668
|
+
toUser,
|
|
1669
|
+
userStats: this.getUserStatsAccountPublicKey(),
|
|
1670
|
+
state: await this.getStatePublicKey(),
|
|
1671
|
+
spotMarketVault: this.getSpotMarketAccount(marketIndex).vault,
|
|
1672
|
+
},
|
|
1673
|
+
remainingAccounts,
|
|
1674
|
+
});
|
|
1675
|
+
}
|
|
1676
|
+
async updateSpotMarketCumulativeInterest(marketIndex, txParams) {
|
|
1677
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.updateSpotMarketCumulativeInterestIx(marketIndex), txParams), [], this.opts);
|
|
1678
|
+
return txSig;
|
|
1679
|
+
}
|
|
1680
|
+
async updateSpotMarketCumulativeInterestIx(marketIndex) {
|
|
1681
|
+
const spotMarket = this.getSpotMarketAccount(marketIndex);
|
|
1682
|
+
return await this.program.instruction.updateSpotMarketCumulativeInterest({
|
|
1683
|
+
accounts: {
|
|
1684
|
+
state: await this.getStatePublicKey(),
|
|
1685
|
+
spotMarket: spotMarket.pubkey,
|
|
1686
|
+
spotMarketVault: spotMarket.vault,
|
|
1687
|
+
oracle: spotMarket.oracle,
|
|
1688
|
+
},
|
|
1689
|
+
});
|
|
1690
|
+
}
|
|
1691
|
+
async settleLP(settleeUserAccountPublicKey, marketIndex, txParams) {
|
|
1692
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.settleLPIx(settleeUserAccountPublicKey, marketIndex), txParams), [], this.opts);
|
|
1693
|
+
return txSig;
|
|
1694
|
+
}
|
|
1695
|
+
async settleLPIx(settleeUserAccountPublicKey, marketIndex) {
|
|
1696
|
+
const settleeUserAccount = (await this.program.account.user.fetch(settleeUserAccountPublicKey));
|
|
1697
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
1698
|
+
userAccounts: [settleeUserAccount],
|
|
1699
|
+
writablePerpMarketIndexes: [marketIndex],
|
|
1700
|
+
});
|
|
1701
|
+
return this.program.instruction.settleLp(marketIndex, {
|
|
1702
|
+
accounts: {
|
|
1703
|
+
state: await this.getStatePublicKey(),
|
|
1704
|
+
user: settleeUserAccountPublicKey,
|
|
1705
|
+
},
|
|
1706
|
+
remainingAccounts: remainingAccounts,
|
|
1707
|
+
});
|
|
1708
|
+
}
|
|
1709
|
+
async removePerpLpShares(marketIndex, sharesToBurn, txParams, subAccountId) {
|
|
1710
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getRemovePerpLpSharesIx(marketIndex, sharesToBurn, subAccountId), txParams), [], this.opts);
|
|
1711
|
+
return txSig;
|
|
1712
|
+
}
|
|
1713
|
+
async removePerpLpSharesInExpiringMarket(marketIndex, userAccountPublicKey, sharesToBurn, txParams) {
|
|
1714
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getRemovePerpLpSharesInExpiringMarket(marketIndex, userAccountPublicKey, sharesToBurn), txParams), [], this.opts);
|
|
1715
|
+
return txSig;
|
|
1716
|
+
}
|
|
1717
|
+
async getRemovePerpLpSharesInExpiringMarket(marketIndex, userAccountPublicKey, sharesToBurn) {
|
|
1718
|
+
const userAccount = (await this.program.account.user.fetch(userAccountPublicKey));
|
|
1719
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
1720
|
+
userAccounts: [userAccount],
|
|
1721
|
+
useMarketLastSlotCache: true,
|
|
1722
|
+
writablePerpMarketIndexes: [marketIndex],
|
|
1723
|
+
});
|
|
1724
|
+
if (sharesToBurn == undefined) {
|
|
1725
|
+
const perpPosition = userAccount.perpPositions.filter((position) => position.marketIndex === marketIndex)[0];
|
|
1726
|
+
sharesToBurn = perpPosition.lpShares;
|
|
1727
|
+
console.log('burning lp shares:', sharesToBurn.toString());
|
|
1728
|
+
}
|
|
1729
|
+
return this.program.instruction.removePerpLpSharesInExpiringMarket(sharesToBurn, marketIndex, {
|
|
1730
|
+
accounts: {
|
|
1731
|
+
state: await this.getStatePublicKey(),
|
|
1732
|
+
user: userAccountPublicKey,
|
|
1733
|
+
},
|
|
1734
|
+
remainingAccounts: remainingAccounts,
|
|
1735
|
+
});
|
|
1736
|
+
}
|
|
1737
|
+
async getRemovePerpLpSharesIx(marketIndex, sharesToBurn, subAccountId) {
|
|
1738
|
+
const user = await this.getUserAccountPublicKey(subAccountId);
|
|
1739
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
1740
|
+
userAccounts: [this.getUserAccount(subAccountId)],
|
|
1741
|
+
useMarketLastSlotCache: true,
|
|
1742
|
+
writablePerpMarketIndexes: [marketIndex],
|
|
1743
|
+
});
|
|
1744
|
+
if (sharesToBurn == undefined) {
|
|
1745
|
+
const userAccount = this.getUserAccount(subAccountId);
|
|
1746
|
+
const perpPosition = userAccount.perpPositions.filter((position) => position.marketIndex === marketIndex)[0];
|
|
1747
|
+
sharesToBurn = perpPosition.lpShares;
|
|
1748
|
+
console.log('burning lp shares:', sharesToBurn.toString());
|
|
1749
|
+
}
|
|
1750
|
+
return this.program.instruction.removePerpLpShares(sharesToBurn, marketIndex, {
|
|
1751
|
+
accounts: {
|
|
1752
|
+
state: await this.getStatePublicKey(),
|
|
1753
|
+
user,
|
|
1754
|
+
authority: this.wallet.publicKey,
|
|
1755
|
+
},
|
|
1756
|
+
remainingAccounts: remainingAccounts,
|
|
1757
|
+
});
|
|
1758
|
+
}
|
|
1759
|
+
async addPerpLpShares(amount, marketIndex, txParams, subAccountId) {
|
|
1760
|
+
const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getAddPerpLpSharesIx(amount, marketIndex, subAccountId), txParams), [], this.opts);
|
|
1761
|
+
this.perpMarketLastSlotCache.set(marketIndex, slot);
|
|
1762
|
+
return txSig;
|
|
1763
|
+
}
|
|
1764
|
+
async getAddPerpLpSharesIx(amount, marketIndex, subAccountId) {
|
|
1765
|
+
const user = await this.getUserAccountPublicKey(subAccountId);
|
|
1766
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
1767
|
+
userAccounts: [this.getUserAccount(subAccountId)],
|
|
1768
|
+
useMarketLastSlotCache: true,
|
|
1769
|
+
writablePerpMarketIndexes: [marketIndex],
|
|
1770
|
+
});
|
|
1771
|
+
return this.program.instruction.addPerpLpShares(amount, marketIndex, {
|
|
1772
|
+
accounts: {
|
|
1773
|
+
state: await this.getStatePublicKey(),
|
|
1774
|
+
user,
|
|
1775
|
+
authority: this.wallet.publicKey,
|
|
1776
|
+
},
|
|
1777
|
+
remainingAccounts: remainingAccounts,
|
|
1778
|
+
});
|
|
1779
|
+
}
|
|
1780
|
+
getQuoteValuePerLpShare(marketIndex) {
|
|
1781
|
+
const perpMarketAccount = this.getPerpMarketAccount(marketIndex);
|
|
1782
|
+
const openBids = anchor_1.BN.max(perpMarketAccount.amm.baseAssetReserve.sub(perpMarketAccount.amm.minBaseAssetReserve), numericConstants_1.ZERO);
|
|
1783
|
+
const openAsks = anchor_1.BN.max(perpMarketAccount.amm.maxBaseAssetReserve.sub(perpMarketAccount.amm.baseAssetReserve), numericConstants_1.ZERO);
|
|
1784
|
+
const oraclePriceData = this.getOracleDataForPerpMarket(marketIndex);
|
|
1785
|
+
const maxOpenBidsAsks = anchor_1.BN.max(openBids, openAsks);
|
|
1786
|
+
const quoteValuePerLpShare = maxOpenBidsAsks
|
|
1787
|
+
.mul(oraclePriceData.price)
|
|
1788
|
+
.mul(numericConstants_1.QUOTE_PRECISION)
|
|
1789
|
+
.div(numericConstants_1.PRICE_PRECISION)
|
|
1790
|
+
.div(perpMarketAccount.amm.sqrtK);
|
|
1791
|
+
return quoteValuePerLpShare;
|
|
1792
|
+
}
|
|
1793
|
+
/**
|
|
1794
|
+
* @deprecated use {@link placePerpOrder} or {@link placeAndTakePerpOrder} instead
|
|
1795
|
+
*/
|
|
1796
|
+
async openPosition(direction, amount, marketIndex, limitPrice, subAccountId) {
|
|
1797
|
+
return await this.placeAndTakePerpOrder({
|
|
1798
|
+
orderType: types_1.OrderType.MARKET,
|
|
1799
|
+
marketIndex,
|
|
1800
|
+
direction,
|
|
1801
|
+
baseAssetAmount: amount,
|
|
1802
|
+
price: limitPrice,
|
|
1803
|
+
}, undefined, undefined, undefined, undefined, undefined, subAccountId);
|
|
1804
|
+
}
|
|
1805
|
+
async sendSignedTx(tx, opts) {
|
|
1806
|
+
const { txSig } = await this.sendTransaction(tx, undefined, opts !== null && opts !== void 0 ? opts : this.opts, true);
|
|
1807
|
+
return txSig;
|
|
1808
|
+
}
|
|
1809
|
+
async prepareMarketOrderTxs(orderParams, userAccountPublicKey, userAccount, makerInfo, txParams, bracketOrdersParams = new Array(), referrerInfo, cancelExistingOrders, settlePnl) {
|
|
1810
|
+
const marketIndex = orderParams.marketIndex;
|
|
1811
|
+
const orderId = userAccount.nextOrderId;
|
|
1812
|
+
const ixPromisesForTxs = {
|
|
1813
|
+
cancelExistingOrdersTx: undefined,
|
|
1814
|
+
settlePnlTx: undefined,
|
|
1815
|
+
fillTx: undefined,
|
|
1816
|
+
marketOrderTx: undefined,
|
|
1817
|
+
};
|
|
1818
|
+
const txKeys = Object.keys(ixPromisesForTxs);
|
|
1819
|
+
ixPromisesForTxs.marketOrderTx = this.getPlaceOrdersIx([orderParams, ...bracketOrdersParams], userAccount.subAccountId);
|
|
1820
|
+
/* Cancel open orders in market if requested */
|
|
1821
|
+
if (cancelExistingOrders && (0, types_1.isVariant)(orderParams.marketType, 'perp')) {
|
|
1822
|
+
ixPromisesForTxs.cancelExistingOrdersTx = this.getCancelOrdersIx(orderParams.marketType, orderParams.marketIndex, null, userAccount.subAccountId);
|
|
1823
|
+
}
|
|
1824
|
+
/* Settle PnL after fill if requested */
|
|
1825
|
+
if (settlePnl && (0, types_1.isVariant)(orderParams.marketType, 'perp')) {
|
|
1826
|
+
ixPromisesForTxs.settlePnlTx = this.settlePNLIx(userAccountPublicKey, userAccount, marketIndex);
|
|
1827
|
+
}
|
|
1828
|
+
// use versioned transactions if there is a lookup table account and wallet is compatible
|
|
1829
|
+
if (this.txVersion === 0) {
|
|
1830
|
+
ixPromisesForTxs.fillTx = this.getFillPerpOrderIx(userAccountPublicKey, userAccount, {
|
|
1831
|
+
orderId,
|
|
1832
|
+
marketIndex,
|
|
1833
|
+
}, makerInfo, referrerInfo, userAccount.subAccountId);
|
|
1834
|
+
}
|
|
1835
|
+
const ixs = await Promise.all(Object.values(ixPromisesForTxs));
|
|
1836
|
+
const ixsMap = ixs.reduce((acc, ix, i) => {
|
|
1837
|
+
acc[txKeys[i]] = ix;
|
|
1838
|
+
return acc;
|
|
1839
|
+
}, {});
|
|
1840
|
+
const txsMap = (await this.buildTransactionsMap(ixsMap, txParams));
|
|
1841
|
+
return txsMap;
|
|
1842
|
+
}
|
|
1843
|
+
/**
|
|
1844
|
+
* Sends a market order and returns a signed tx which can fill the order against the vamm, which the caller can use to fill their own order if required.
|
|
1845
|
+
* @param orderParams
|
|
1846
|
+
* @param userAccountPublicKey
|
|
1847
|
+
* @param userAccount
|
|
1848
|
+
* @param makerInfo
|
|
1849
|
+
* @param txParams
|
|
1850
|
+
* @param bracketOrdersParams
|
|
1851
|
+
* @param cancelExistingOrders - Builds and returns an extra transaciton to cancel the existing orders in the same perp market. Intended use is to auto-cancel TP/SL orders when closing a position. Ignored if orderParams.marketType is not MarketType.PERP
|
|
1852
|
+
* @returns
|
|
1853
|
+
*/
|
|
1854
|
+
async sendMarketOrderAndGetSignedFillTx(orderParams, userAccountPublicKey, userAccount, makerInfo, txParams, bracketOrdersParams = new Array(), referrerInfo, cancelExistingOrders, settlePnl) {
|
|
1855
|
+
const preppedTxs = await this.prepareMarketOrderTxs(orderParams, userAccountPublicKey, userAccount, makerInfo, txParams, bracketOrdersParams, referrerInfo, cancelExistingOrders, settlePnl);
|
|
1856
|
+
const signedTxs = (await this.txHandler.getSignedTransactionMap(preppedTxs, this.wallet)).signedTxMap;
|
|
1857
|
+
const { txSig, slot } = await this.sendTransaction(signedTxs.marketOrderTx, [], this.opts, true);
|
|
1858
|
+
this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
|
|
1859
|
+
return {
|
|
1860
|
+
txSig,
|
|
1861
|
+
signedFillTx: signedTxs.fillTx,
|
|
1862
|
+
signedCancelExistingOrdersTx: signedTxs.cancelExistingOrdersTx,
|
|
1863
|
+
signedSettlePnlTx: signedTxs.settlePnlTx,
|
|
1864
|
+
};
|
|
1865
|
+
}
|
|
1866
|
+
async placePerpOrder(orderParams, txParams, subAccountId) {
|
|
1867
|
+
const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getPlacePerpOrderIx(orderParams, subAccountId), txParams), [], this.opts);
|
|
1868
|
+
this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
|
|
1869
|
+
return txSig;
|
|
1870
|
+
}
|
|
1871
|
+
async getPlacePerpOrderIx(orderParams, subAccountId, depositToTradeArgs) {
|
|
1872
|
+
orderParams = (0, orderParams_1.getOrderParams)(orderParams, { marketType: types_1.MarketType.PERP });
|
|
1873
|
+
const isDepositToTradeTx = depositToTradeArgs !== undefined;
|
|
1874
|
+
const user = isDepositToTradeTx
|
|
1875
|
+
? (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.authority, subAccountId)
|
|
1876
|
+
: await this.getUserAccountPublicKey(subAccountId);
|
|
1877
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
1878
|
+
userAccounts: (depositToTradeArgs === null || depositToTradeArgs === void 0 ? void 0 : depositToTradeArgs.isMakingNewAccount)
|
|
1879
|
+
? []
|
|
1880
|
+
: [this.getUserAccount(subAccountId)],
|
|
1881
|
+
useMarketLastSlotCache: false,
|
|
1882
|
+
readablePerpMarketIndex: orderParams.marketIndex,
|
|
1883
|
+
readableSpotMarketIndexes: isDepositToTradeTx
|
|
1884
|
+
? [depositToTradeArgs === null || depositToTradeArgs === void 0 ? void 0 : depositToTradeArgs.depositMarketIndex]
|
|
1885
|
+
: undefined,
|
|
1886
|
+
});
|
|
1887
|
+
return await this.program.instruction.placePerpOrder(orderParams, {
|
|
1888
|
+
accounts: {
|
|
1889
|
+
state: await this.getStatePublicKey(),
|
|
1890
|
+
user,
|
|
1891
|
+
userStats: this.getUserStatsAccountPublicKey(),
|
|
1892
|
+
authority: this.wallet.publicKey,
|
|
1893
|
+
},
|
|
1894
|
+
remainingAccounts,
|
|
1895
|
+
});
|
|
1896
|
+
}
|
|
1897
|
+
async updateAMMs(marketIndexes, txParams) {
|
|
1898
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getUpdateAMMsIx(marketIndexes), txParams), [], this.opts);
|
|
1899
|
+
return txSig;
|
|
1900
|
+
}
|
|
1901
|
+
async getUpdateAMMsIx(marketIndexes) {
|
|
1902
|
+
for (let i = marketIndexes.length; i < 5; i++) {
|
|
1903
|
+
marketIndexes.push(100);
|
|
1904
|
+
}
|
|
1905
|
+
const marketAccountInfos = [];
|
|
1906
|
+
const oracleAccountInfos = [];
|
|
1907
|
+
for (const marketIndex of marketIndexes) {
|
|
1908
|
+
if (marketIndex !== 100) {
|
|
1909
|
+
const market = this.getPerpMarketAccount(marketIndex);
|
|
1910
|
+
marketAccountInfos.push({
|
|
1911
|
+
pubkey: market.pubkey,
|
|
1912
|
+
isWritable: true,
|
|
1913
|
+
isSigner: false,
|
|
1914
|
+
});
|
|
1915
|
+
oracleAccountInfos.push({
|
|
1916
|
+
pubkey: market.amm.oracle,
|
|
1917
|
+
isWritable: false,
|
|
1918
|
+
isSigner: false,
|
|
1919
|
+
});
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
const remainingAccounts = oracleAccountInfos.concat(marketAccountInfos);
|
|
1923
|
+
return await this.program.instruction.updateAmms(marketIndexes, {
|
|
1924
|
+
accounts: {
|
|
1925
|
+
state: await this.getStatePublicKey(),
|
|
1926
|
+
authority: this.wallet.publicKey,
|
|
1927
|
+
},
|
|
1928
|
+
remainingAccounts,
|
|
1929
|
+
});
|
|
1930
|
+
}
|
|
1931
|
+
async settleExpiredMarket(marketIndex, txParams) {
|
|
1932
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getSettleExpiredMarketIx(marketIndex), txParams), [], this.opts);
|
|
1933
|
+
return txSig;
|
|
1934
|
+
}
|
|
1935
|
+
async getSettleExpiredMarketIx(marketIndex) {
|
|
1936
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
1937
|
+
userAccounts: [],
|
|
1938
|
+
writablePerpMarketIndexes: [marketIndex],
|
|
1939
|
+
writableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
|
|
1940
|
+
});
|
|
1941
|
+
const perpMarketPublicKey = await (0, pda_1.getPerpMarketPublicKey)(this.program.programId, marketIndex);
|
|
1942
|
+
return await this.program.instruction.settleExpiredMarket(marketIndex, {
|
|
1943
|
+
accounts: {
|
|
1944
|
+
state: await this.getStatePublicKey(),
|
|
1945
|
+
admin: this.isSubscribed
|
|
1946
|
+
? this.getStateAccount().admin
|
|
1947
|
+
: this.wallet.publicKey,
|
|
1948
|
+
perpMarket: perpMarketPublicKey,
|
|
1949
|
+
},
|
|
1950
|
+
remainingAccounts,
|
|
1951
|
+
});
|
|
1952
|
+
}
|
|
1953
|
+
async settleExpiredMarketPoolsToRevenuePool(marketIndex, txParams) {
|
|
1954
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getSettleExpiredMarketPoolsToRevenuePoolIx(marketIndex), txParams), [], this.opts);
|
|
1955
|
+
return txSig;
|
|
1956
|
+
}
|
|
1957
|
+
async getSettleExpiredMarketPoolsToRevenuePoolIx(perpMarketIndex) {
|
|
1958
|
+
const perpMarketPublicKey = await (0, pda_1.getPerpMarketPublicKey)(this.program.programId, perpMarketIndex);
|
|
1959
|
+
const spotMarketPublicKey = await (0, pda_1.getSpotMarketPublicKey)(this.program.programId, numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
|
|
1960
|
+
return await this.program.instruction.settleExpiredMarketPoolsToRevenuePool({
|
|
1961
|
+
accounts: {
|
|
1962
|
+
state: await this.getStatePublicKey(),
|
|
1963
|
+
admin: this.isSubscribed
|
|
1964
|
+
? this.getStateAccount().admin
|
|
1965
|
+
: this.wallet.publicKey,
|
|
1966
|
+
spotMarket: spotMarketPublicKey,
|
|
1967
|
+
perpMarket: perpMarketPublicKey,
|
|
1968
|
+
},
|
|
1969
|
+
});
|
|
1970
|
+
}
|
|
1971
|
+
async cancelOrder(orderId, txParams, subAccountId) {
|
|
1972
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getCancelOrderIx(orderId, subAccountId), txParams), [], this.opts);
|
|
1973
|
+
return txSig;
|
|
1974
|
+
}
|
|
1975
|
+
async getCancelOrderIx(orderId, subAccountId) {
|
|
1976
|
+
const user = await this.getUserAccountPublicKey(subAccountId);
|
|
1977
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
1978
|
+
userAccounts: [this.getUserAccount(subAccountId)],
|
|
1979
|
+
useMarketLastSlotCache: true,
|
|
1980
|
+
});
|
|
1981
|
+
return await this.program.instruction.cancelOrder(orderId !== null && orderId !== void 0 ? orderId : null, {
|
|
1982
|
+
accounts: {
|
|
1983
|
+
state: await this.getStatePublicKey(),
|
|
1984
|
+
user,
|
|
1985
|
+
authority: this.wallet.publicKey,
|
|
1986
|
+
},
|
|
1987
|
+
remainingAccounts,
|
|
1988
|
+
});
|
|
1989
|
+
}
|
|
1990
|
+
async cancelOrderByUserId(userOrderId, txParams, subAccountId) {
|
|
1991
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getCancelOrderByUserIdIx(userOrderId, subAccountId), txParams), [], this.opts);
|
|
1992
|
+
return txSig;
|
|
1993
|
+
}
|
|
1994
|
+
async getCancelOrderByUserIdIx(userOrderId, subAccountId) {
|
|
1995
|
+
const user = await this.getUserAccountPublicKey(subAccountId);
|
|
1996
|
+
const order = this.getOrderByUserId(userOrderId);
|
|
1997
|
+
const oracle = this.getPerpMarketAccount(order.marketIndex).amm.oracle;
|
|
1998
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
1999
|
+
userAccounts: [this.getUserAccount(subAccountId)],
|
|
2000
|
+
useMarketLastSlotCache: true,
|
|
2001
|
+
});
|
|
2002
|
+
return await this.program.instruction.cancelOrderByUserId(userOrderId, {
|
|
2003
|
+
accounts: {
|
|
2004
|
+
state: await this.getStatePublicKey(),
|
|
2005
|
+
user,
|
|
2006
|
+
authority: this.wallet.publicKey,
|
|
2007
|
+
oracle,
|
|
2008
|
+
},
|
|
2009
|
+
remainingAccounts,
|
|
2010
|
+
});
|
|
2011
|
+
}
|
|
2012
|
+
async cancelOrdersByIds(orderIds, txParams, subAccountId) {
|
|
2013
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getCancelOrdersByIdsIx(orderIds, subAccountId), txParams), [], this.opts);
|
|
2014
|
+
return txSig;
|
|
2015
|
+
}
|
|
2016
|
+
async getCancelOrdersByIdsIx(orderIds, subAccountId) {
|
|
2017
|
+
const user = await this.getUserAccountPublicKey(subAccountId);
|
|
2018
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
2019
|
+
userAccounts: [this.getUserAccount(subAccountId)],
|
|
2020
|
+
useMarketLastSlotCache: true,
|
|
2021
|
+
});
|
|
2022
|
+
return await this.program.instruction.cancelOrdersByIds(orderIds, {
|
|
2023
|
+
accounts: {
|
|
2024
|
+
state: await this.getStatePublicKey(),
|
|
2025
|
+
user,
|
|
2026
|
+
authority: this.wallet.publicKey,
|
|
2027
|
+
},
|
|
2028
|
+
remainingAccounts,
|
|
2029
|
+
});
|
|
2030
|
+
}
|
|
2031
|
+
async cancelOrders(marketType, marketIndex, direction, txParams, subAccountId) {
|
|
2032
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getCancelOrdersIx(marketType, marketIndex, direction, subAccountId), txParams), [], this.opts);
|
|
2033
|
+
return txSig;
|
|
2034
|
+
}
|
|
2035
|
+
async getCancelOrdersIx(marketType, marketIndex, direction, subAccountId) {
|
|
2036
|
+
const user = await this.getUserAccountPublicKey(subAccountId);
|
|
2037
|
+
let readablePerpMarketIndex = undefined;
|
|
2038
|
+
let readableSpotMarketIndexes = undefined;
|
|
2039
|
+
if (typeof marketIndex === 'number') {
|
|
2040
|
+
if (marketType && (0, types_1.isVariant)(marketType, 'perp')) {
|
|
2041
|
+
readablePerpMarketIndex = marketIndex;
|
|
2042
|
+
}
|
|
2043
|
+
else if (marketType && (0, types_1.isVariant)(marketType, 'spot')) {
|
|
2044
|
+
readableSpotMarketIndexes = [marketIndex];
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
2048
|
+
userAccounts: [this.getUserAccount(subAccountId)],
|
|
2049
|
+
readablePerpMarketIndex,
|
|
2050
|
+
readableSpotMarketIndexes,
|
|
2051
|
+
useMarketLastSlotCache: true,
|
|
2052
|
+
});
|
|
2053
|
+
return await this.program.instruction.cancelOrders(marketType !== null && marketType !== void 0 ? marketType : null, marketIndex !== null && marketIndex !== void 0 ? marketIndex : null, direction !== null && direction !== void 0 ? direction : null, {
|
|
2054
|
+
accounts: {
|
|
2055
|
+
state: await this.getStatePublicKey(),
|
|
2056
|
+
user,
|
|
2057
|
+
authority: this.wallet.publicKey,
|
|
2058
|
+
},
|
|
2059
|
+
remainingAccounts,
|
|
2060
|
+
});
|
|
2061
|
+
}
|
|
2062
|
+
async cancelAndPlaceOrders(cancelOrderParams, placeOrderParams, txParams, subAccountId) {
|
|
2063
|
+
const ixs = [
|
|
2064
|
+
await this.getCancelOrdersIx(cancelOrderParams.marketType, cancelOrderParams.marketIndex, cancelOrderParams.direction, subAccountId),
|
|
2065
|
+
await this.getPlaceOrdersIx(placeOrderParams, subAccountId),
|
|
2066
|
+
];
|
|
2067
|
+
const tx = await this.buildTransaction(ixs, txParams);
|
|
2068
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
2069
|
+
return txSig;
|
|
2070
|
+
}
|
|
2071
|
+
async placeOrders(params, txParams, subAccountId) {
|
|
2072
|
+
const { txSig } = await this.sendTransaction((await this.preparePlaceOrdersTx(params, txParams, subAccountId))
|
|
2073
|
+
.placeOrdersTx, [], this.opts, false);
|
|
2074
|
+
return txSig;
|
|
2075
|
+
}
|
|
2076
|
+
async preparePlaceOrdersTx(params, txParams, subAccountId) {
|
|
2077
|
+
const tx = await this.buildTransaction(await this.getPlaceOrdersIx(params, subAccountId), txParams);
|
|
2078
|
+
return {
|
|
2079
|
+
placeOrdersTx: tx,
|
|
2080
|
+
};
|
|
2081
|
+
}
|
|
2082
|
+
async getPlaceOrdersIx(params, subAccountId) {
|
|
2083
|
+
const user = await this.getUserAccountPublicKey(subAccountId);
|
|
2084
|
+
const readablePerpMarketIndex = [];
|
|
2085
|
+
const readableSpotMarketIndexes = [];
|
|
2086
|
+
for (const param of params) {
|
|
2087
|
+
if (!param.marketType) {
|
|
2088
|
+
throw new Error('must set param.marketType');
|
|
2089
|
+
}
|
|
2090
|
+
if ((0, types_1.isVariant)(param.marketType, 'perp')) {
|
|
2091
|
+
readablePerpMarketIndex.push(param.marketIndex);
|
|
2092
|
+
}
|
|
2093
|
+
else {
|
|
2094
|
+
readableSpotMarketIndexes.push(param.marketIndex);
|
|
2095
|
+
}
|
|
2096
|
+
}
|
|
2097
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
2098
|
+
userAccounts: [this.getUserAccount(subAccountId)],
|
|
2099
|
+
readablePerpMarketIndex,
|
|
2100
|
+
readableSpotMarketIndexes,
|
|
2101
|
+
useMarketLastSlotCache: true,
|
|
2102
|
+
});
|
|
2103
|
+
const formattedParams = params.map((item) => (0, orderParams_1.getOrderParams)(item));
|
|
2104
|
+
return await this.program.instruction.placeOrders(formattedParams, {
|
|
2105
|
+
accounts: {
|
|
2106
|
+
state: await this.getStatePublicKey(),
|
|
2107
|
+
user,
|
|
2108
|
+
userStats: this.getUserStatsAccountPublicKey(),
|
|
2109
|
+
authority: this.wallet.publicKey,
|
|
2110
|
+
},
|
|
2111
|
+
remainingAccounts,
|
|
2112
|
+
});
|
|
2113
|
+
}
|
|
2114
|
+
async fillPerpOrder(userAccountPublicKey, user, order, makerInfo, referrerInfo, txParams, fillerPublicKey) {
|
|
2115
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getFillPerpOrderIx(userAccountPublicKey, user, order, makerInfo, referrerInfo, fillerPublicKey), txParams), [], this.opts);
|
|
2116
|
+
return txSig;
|
|
2117
|
+
}
|
|
2118
|
+
async getFillPerpOrderIx(userAccountPublicKey, userAccount, order, makerInfo, referrerInfo, fillerSubAccountId, isSwift) {
|
|
2119
|
+
const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
|
|
2120
|
+
const filler = await this.getUserAccountPublicKey(fillerSubAccountId);
|
|
2121
|
+
const fillerStatsPublicKey = this.getUserStatsAccountPublicKey();
|
|
2122
|
+
const marketIndex = order
|
|
2123
|
+
? order.marketIndex
|
|
2124
|
+
: userAccount.orders.find((order) => order.orderId === userAccount.nextOrderId - 1).marketIndex;
|
|
2125
|
+
makerInfo = Array.isArray(makerInfo)
|
|
2126
|
+
? makerInfo
|
|
2127
|
+
: makerInfo
|
|
2128
|
+
? [makerInfo]
|
|
2129
|
+
: [];
|
|
2130
|
+
const userAccounts = [userAccount];
|
|
2131
|
+
for (const maker of makerInfo) {
|
|
2132
|
+
userAccounts.push(maker.makerUserAccount);
|
|
2133
|
+
}
|
|
2134
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
2135
|
+
userAccounts,
|
|
2136
|
+
writablePerpMarketIndexes: [marketIndex],
|
|
2137
|
+
});
|
|
2138
|
+
for (const maker of makerInfo) {
|
|
2139
|
+
remainingAccounts.push({
|
|
2140
|
+
pubkey: maker.maker,
|
|
2141
|
+
isWritable: true,
|
|
2142
|
+
isSigner: false,
|
|
2143
|
+
});
|
|
2144
|
+
remainingAccounts.push({
|
|
2145
|
+
pubkey: maker.makerStats,
|
|
2146
|
+
isWritable: true,
|
|
2147
|
+
isSigner: false,
|
|
2148
|
+
});
|
|
2149
|
+
}
|
|
2150
|
+
if (referrerInfo) {
|
|
2151
|
+
const referrerIsMaker = makerInfo.find((maker) => maker.maker.equals(referrerInfo.referrer)) !==
|
|
2152
|
+
undefined;
|
|
2153
|
+
if (!referrerIsMaker) {
|
|
2154
|
+
remainingAccounts.push({
|
|
2155
|
+
pubkey: referrerInfo.referrer,
|
|
2156
|
+
isWritable: true,
|
|
2157
|
+
isSigner: false,
|
|
2158
|
+
});
|
|
2159
|
+
remainingAccounts.push({
|
|
2160
|
+
pubkey: referrerInfo.referrerStats,
|
|
2161
|
+
isWritable: true,
|
|
2162
|
+
isSigner: false,
|
|
2163
|
+
});
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
const orderId = isSwift ? null : order.orderId;
|
|
2167
|
+
return await this.program.instruction.fillPerpOrder(orderId, null, {
|
|
2168
|
+
accounts: {
|
|
2169
|
+
state: await this.getStatePublicKey(),
|
|
2170
|
+
filler,
|
|
2171
|
+
fillerStats: fillerStatsPublicKey,
|
|
2172
|
+
user: userAccountPublicKey,
|
|
2173
|
+
userStats: userStatsPublicKey,
|
|
2174
|
+
authority: this.wallet.publicKey,
|
|
2175
|
+
},
|
|
2176
|
+
remainingAccounts,
|
|
2177
|
+
});
|
|
2178
|
+
}
|
|
2179
|
+
async getRevertFillIx(fillerPublicKey) {
|
|
2180
|
+
const filler = fillerPublicKey !== null && fillerPublicKey !== void 0 ? fillerPublicKey : (await this.getUserAccountPublicKey());
|
|
2181
|
+
const fillerStatsPublicKey = this.getUserStatsAccountPublicKey();
|
|
2182
|
+
return this.program.instruction.revertFill({
|
|
2183
|
+
accounts: {
|
|
2184
|
+
state: await this.getStatePublicKey(),
|
|
2185
|
+
filler,
|
|
2186
|
+
fillerStats: fillerStatsPublicKey,
|
|
2187
|
+
authority: this.wallet.publicKey,
|
|
2188
|
+
},
|
|
2189
|
+
});
|
|
2190
|
+
}
|
|
2191
|
+
async placeSpotOrder(orderParams, txParams, subAccountId) {
|
|
2192
|
+
const { txSig, slot } = await this.sendTransaction((await this.preparePlaceSpotOrderTx(orderParams, txParams, subAccountId))
|
|
2193
|
+
.placeSpotOrderTx, [], this.opts, false);
|
|
2194
|
+
this.spotMarketLastSlotCache.set(orderParams.marketIndex, slot);
|
|
2195
|
+
this.spotMarketLastSlotCache.set(numericConstants_1.QUOTE_SPOT_MARKET_INDEX, slot);
|
|
2196
|
+
return txSig;
|
|
2197
|
+
}
|
|
2198
|
+
async preparePlaceSpotOrderTx(orderParams, txParams, subAccountId) {
|
|
2199
|
+
const tx = await this.buildTransaction(await this.getPlaceSpotOrderIx(orderParams, subAccountId), txParams);
|
|
2200
|
+
return {
|
|
2201
|
+
placeSpotOrderTx: tx,
|
|
2202
|
+
};
|
|
2203
|
+
}
|
|
2204
|
+
async getPlaceSpotOrderIx(orderParams, subAccountId) {
|
|
2205
|
+
orderParams = (0, orderParams_1.getOrderParams)(orderParams, { marketType: types_1.MarketType.SPOT });
|
|
2206
|
+
const userAccountPublicKey = await this.getUserAccountPublicKey(subAccountId);
|
|
2207
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
2208
|
+
userAccounts: [this.getUserAccount(subAccountId)],
|
|
2209
|
+
useMarketLastSlotCache: true,
|
|
2210
|
+
readableSpotMarketIndexes: [
|
|
2211
|
+
orderParams.marketIndex,
|
|
2212
|
+
numericConstants_1.QUOTE_SPOT_MARKET_INDEX,
|
|
2213
|
+
],
|
|
2214
|
+
});
|
|
2215
|
+
return await this.program.instruction.placeSpotOrder(orderParams, {
|
|
2216
|
+
accounts: {
|
|
2217
|
+
state: await this.getStatePublicKey(),
|
|
2218
|
+
user: userAccountPublicKey,
|
|
2219
|
+
userStats: this.getUserStatsAccountPublicKey(),
|
|
2220
|
+
authority: this.wallet.publicKey,
|
|
2221
|
+
},
|
|
2222
|
+
remainingAccounts,
|
|
2223
|
+
});
|
|
2224
|
+
}
|
|
2225
|
+
async fillSpotOrder(userAccountPublicKey, user, order, fulfillmentConfig, makerInfo, referrerInfo, txParams) {
|
|
2226
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getFillSpotOrderIx(userAccountPublicKey, user, order, fulfillmentConfig, makerInfo, referrerInfo), txParams), [], this.opts);
|
|
2227
|
+
return txSig;
|
|
2228
|
+
}
|
|
2229
|
+
async getFillSpotOrderIx(userAccountPublicKey, userAccount, order, fulfillmentConfig, makerInfo, referrerInfo, fillerPublicKey) {
|
|
2230
|
+
const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
|
|
2231
|
+
const filler = fillerPublicKey !== null && fillerPublicKey !== void 0 ? fillerPublicKey : (await this.getUserAccountPublicKey());
|
|
2232
|
+
const fillerStatsPublicKey = this.getUserStatsAccountPublicKey();
|
|
2233
|
+
const marketIndex = order
|
|
2234
|
+
? order.marketIndex
|
|
2235
|
+
: userAccount.orders.find((order) => order.orderId === userAccount.nextOrderId - 1).marketIndex;
|
|
2236
|
+
makerInfo = Array.isArray(makerInfo)
|
|
2237
|
+
? makerInfo
|
|
2238
|
+
: makerInfo
|
|
2239
|
+
? [makerInfo]
|
|
2240
|
+
: [];
|
|
2241
|
+
const userAccounts = [userAccount];
|
|
2242
|
+
for (const maker of makerInfo) {
|
|
2243
|
+
userAccounts.push(maker.makerUserAccount);
|
|
2244
|
+
}
|
|
2245
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
2246
|
+
userAccounts,
|
|
2247
|
+
writableSpotMarketIndexes: [marketIndex, numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
|
|
2248
|
+
});
|
|
2249
|
+
for (const maker of makerInfo) {
|
|
2250
|
+
remainingAccounts.push({
|
|
2251
|
+
pubkey: maker.maker,
|
|
2252
|
+
isWritable: true,
|
|
2253
|
+
isSigner: false,
|
|
2254
|
+
});
|
|
2255
|
+
remainingAccounts.push({
|
|
2256
|
+
pubkey: maker.makerStats,
|
|
2257
|
+
isWritable: true,
|
|
2258
|
+
isSigner: false,
|
|
2259
|
+
});
|
|
2260
|
+
}
|
|
2261
|
+
const orderId = order.orderId;
|
|
2262
|
+
this.addSpotFulfillmentAccounts(marketIndex, remainingAccounts, fulfillmentConfig);
|
|
2263
|
+
return await this.program.instruction.fillSpotOrder(orderId, fulfillmentConfig ? fulfillmentConfig.fulfillmentType : null, null, {
|
|
2264
|
+
accounts: {
|
|
2265
|
+
state: await this.getStatePublicKey(),
|
|
2266
|
+
filler,
|
|
2267
|
+
fillerStats: fillerStatsPublicKey,
|
|
2268
|
+
user: userAccountPublicKey,
|
|
2269
|
+
userStats: userStatsPublicKey,
|
|
2270
|
+
authority: this.wallet.publicKey,
|
|
2271
|
+
},
|
|
2272
|
+
remainingAccounts,
|
|
2273
|
+
});
|
|
2274
|
+
}
|
|
2275
|
+
addSpotFulfillmentAccounts(marketIndex, remainingAccounts, fulfillmentConfig) {
|
|
2276
|
+
if (fulfillmentConfig) {
|
|
2277
|
+
if ('serumProgramId' in fulfillmentConfig) {
|
|
2278
|
+
this.addSerumRemainingAccounts(marketIndex, remainingAccounts, fulfillmentConfig);
|
|
2279
|
+
}
|
|
2280
|
+
else if ('phoenixProgramId' in fulfillmentConfig) {
|
|
2281
|
+
this.addPhoenixRemainingAccounts(marketIndex, remainingAccounts, fulfillmentConfig);
|
|
2282
|
+
}
|
|
2283
|
+
else if ('openbookV2ProgramId' in fulfillmentConfig) {
|
|
2284
|
+
this.addOpenbookRemainingAccounts(marketIndex, remainingAccounts, fulfillmentConfig);
|
|
2285
|
+
}
|
|
2286
|
+
else {
|
|
2287
|
+
throw Error('Invalid fulfillment config type');
|
|
2288
|
+
}
|
|
2289
|
+
}
|
|
2290
|
+
else {
|
|
2291
|
+
remainingAccounts.push({
|
|
2292
|
+
pubkey: this.getSpotMarketAccount(marketIndex).vault,
|
|
2293
|
+
isWritable: false,
|
|
2294
|
+
isSigner: false,
|
|
2295
|
+
});
|
|
2296
|
+
remainingAccounts.push({
|
|
2297
|
+
pubkey: this.getQuoteSpotMarketAccount().vault,
|
|
2298
|
+
isWritable: false,
|
|
2299
|
+
isSigner: false,
|
|
2300
|
+
});
|
|
2301
|
+
}
|
|
2302
|
+
}
|
|
2303
|
+
addSerumRemainingAccounts(marketIndex, remainingAccounts, fulfillmentConfig) {
|
|
2304
|
+
remainingAccounts.push({
|
|
2305
|
+
pubkey: fulfillmentConfig.pubkey,
|
|
2306
|
+
isWritable: false,
|
|
2307
|
+
isSigner: false,
|
|
2308
|
+
});
|
|
2309
|
+
remainingAccounts.push({
|
|
2310
|
+
pubkey: fulfillmentConfig.serumProgramId,
|
|
2311
|
+
isWritable: false,
|
|
2312
|
+
isSigner: false,
|
|
2313
|
+
});
|
|
2314
|
+
remainingAccounts.push({
|
|
2315
|
+
pubkey: fulfillmentConfig.serumMarket,
|
|
2316
|
+
isWritable: true,
|
|
2317
|
+
isSigner: false,
|
|
2318
|
+
});
|
|
2319
|
+
remainingAccounts.push({
|
|
2320
|
+
pubkey: fulfillmentConfig.serumRequestQueue,
|
|
2321
|
+
isWritable: true,
|
|
2322
|
+
isSigner: false,
|
|
2323
|
+
});
|
|
2324
|
+
remainingAccounts.push({
|
|
2325
|
+
pubkey: fulfillmentConfig.serumEventQueue,
|
|
2326
|
+
isWritable: true,
|
|
2327
|
+
isSigner: false,
|
|
2328
|
+
});
|
|
2329
|
+
remainingAccounts.push({
|
|
2330
|
+
pubkey: fulfillmentConfig.serumBids,
|
|
2331
|
+
isWritable: true,
|
|
2332
|
+
isSigner: false,
|
|
2333
|
+
});
|
|
2334
|
+
remainingAccounts.push({
|
|
2335
|
+
pubkey: fulfillmentConfig.serumAsks,
|
|
2336
|
+
isWritable: true,
|
|
2337
|
+
isSigner: false,
|
|
2338
|
+
});
|
|
2339
|
+
remainingAccounts.push({
|
|
2340
|
+
pubkey: fulfillmentConfig.serumBaseVault,
|
|
2341
|
+
isWritable: true,
|
|
2342
|
+
isSigner: false,
|
|
2343
|
+
});
|
|
2344
|
+
remainingAccounts.push({
|
|
2345
|
+
pubkey: fulfillmentConfig.serumQuoteVault,
|
|
2346
|
+
isWritable: true,
|
|
2347
|
+
isSigner: false,
|
|
2348
|
+
});
|
|
2349
|
+
remainingAccounts.push({
|
|
2350
|
+
pubkey: fulfillmentConfig.serumOpenOrders,
|
|
2351
|
+
isWritable: true,
|
|
2352
|
+
isSigner: false,
|
|
2353
|
+
});
|
|
2354
|
+
remainingAccounts.push({
|
|
2355
|
+
pubkey: (0, pda_1.getSerumSignerPublicKey)(fulfillmentConfig.serumProgramId, fulfillmentConfig.serumMarket, fulfillmentConfig.serumSignerNonce),
|
|
2356
|
+
isWritable: false,
|
|
2357
|
+
isSigner: false,
|
|
2358
|
+
});
|
|
2359
|
+
remainingAccounts.push({
|
|
2360
|
+
pubkey: this.getSignerPublicKey(),
|
|
2361
|
+
isWritable: false,
|
|
2362
|
+
isSigner: false,
|
|
2363
|
+
});
|
|
2364
|
+
remainingAccounts.push({
|
|
2365
|
+
pubkey: spl_token_1.TOKEN_PROGRAM_ID,
|
|
2366
|
+
isWritable: false,
|
|
2367
|
+
isSigner: false,
|
|
2368
|
+
});
|
|
2369
|
+
remainingAccounts.push({
|
|
2370
|
+
pubkey: this.getSpotMarketAccount(marketIndex).vault,
|
|
2371
|
+
isWritable: true,
|
|
2372
|
+
isSigner: false,
|
|
2373
|
+
});
|
|
2374
|
+
remainingAccounts.push({
|
|
2375
|
+
pubkey: this.getQuoteSpotMarketAccount().vault,
|
|
2376
|
+
isWritable: true,
|
|
2377
|
+
isSigner: false,
|
|
2378
|
+
});
|
|
2379
|
+
remainingAccounts.push({
|
|
2380
|
+
pubkey: this.getStateAccount().srmVault,
|
|
2381
|
+
isWritable: false,
|
|
2382
|
+
isSigner: false,
|
|
2383
|
+
});
|
|
2384
|
+
}
|
|
2385
|
+
addPhoenixRemainingAccounts(marketIndex, remainingAccounts, fulfillmentConfig) {
|
|
2386
|
+
remainingAccounts.push({
|
|
2387
|
+
pubkey: fulfillmentConfig.pubkey,
|
|
2388
|
+
isWritable: false,
|
|
2389
|
+
isSigner: false,
|
|
2390
|
+
});
|
|
2391
|
+
remainingAccounts.push({
|
|
2392
|
+
pubkey: fulfillmentConfig.phoenixProgramId,
|
|
2393
|
+
isWritable: false,
|
|
2394
|
+
isSigner: false,
|
|
2395
|
+
});
|
|
2396
|
+
remainingAccounts.push({
|
|
2397
|
+
pubkey: fulfillmentConfig.phoenixLogAuthority,
|
|
2398
|
+
isWritable: false,
|
|
2399
|
+
isSigner: false,
|
|
2400
|
+
});
|
|
2401
|
+
remainingAccounts.push({
|
|
2402
|
+
pubkey: fulfillmentConfig.phoenixMarket,
|
|
2403
|
+
isWritable: true,
|
|
2404
|
+
isSigner: false,
|
|
2405
|
+
});
|
|
2406
|
+
remainingAccounts.push({
|
|
2407
|
+
pubkey: this.getSignerPublicKey(),
|
|
2408
|
+
isWritable: false,
|
|
2409
|
+
isSigner: false,
|
|
2410
|
+
});
|
|
2411
|
+
remainingAccounts.push({
|
|
2412
|
+
pubkey: fulfillmentConfig.phoenixBaseVault,
|
|
2413
|
+
isWritable: true,
|
|
2414
|
+
isSigner: false,
|
|
2415
|
+
});
|
|
2416
|
+
remainingAccounts.push({
|
|
2417
|
+
pubkey: fulfillmentConfig.phoenixQuoteVault,
|
|
2418
|
+
isWritable: true,
|
|
2419
|
+
isSigner: false,
|
|
2420
|
+
});
|
|
2421
|
+
remainingAccounts.push({
|
|
2422
|
+
pubkey: this.getSpotMarketAccount(marketIndex).vault,
|
|
2423
|
+
isWritable: true,
|
|
2424
|
+
isSigner: false,
|
|
2425
|
+
});
|
|
2426
|
+
remainingAccounts.push({
|
|
2427
|
+
pubkey: this.getQuoteSpotMarketAccount().vault,
|
|
2428
|
+
isWritable: true,
|
|
2429
|
+
isSigner: false,
|
|
2430
|
+
});
|
|
2431
|
+
remainingAccounts.push({
|
|
2432
|
+
pubkey: spl_token_1.TOKEN_PROGRAM_ID,
|
|
2433
|
+
isWritable: false,
|
|
2434
|
+
isSigner: false,
|
|
2435
|
+
});
|
|
2436
|
+
}
|
|
2437
|
+
addOpenbookRemainingAccounts(marketIndex, remainingAccounts, fulfillmentConfig) {
|
|
2438
|
+
remainingAccounts.push({
|
|
2439
|
+
pubkey: fulfillmentConfig.pubkey,
|
|
2440
|
+
isWritable: false,
|
|
2441
|
+
isSigner: false,
|
|
2442
|
+
});
|
|
2443
|
+
remainingAccounts.push({
|
|
2444
|
+
pubkey: this.getSignerPublicKey(),
|
|
2445
|
+
isWritable: true,
|
|
2446
|
+
isSigner: false,
|
|
2447
|
+
});
|
|
2448
|
+
remainingAccounts.push({
|
|
2449
|
+
pubkey: fulfillmentConfig.openbookV2ProgramId,
|
|
2450
|
+
isWritable: false,
|
|
2451
|
+
isSigner: false,
|
|
2452
|
+
});
|
|
2453
|
+
remainingAccounts.push({
|
|
2454
|
+
pubkey: fulfillmentConfig.openbookV2Market,
|
|
2455
|
+
isWritable: true,
|
|
2456
|
+
isSigner: false,
|
|
2457
|
+
});
|
|
2458
|
+
remainingAccounts.push({
|
|
2459
|
+
pubkey: fulfillmentConfig.openbookV2MarketAuthority,
|
|
2460
|
+
isWritable: false,
|
|
2461
|
+
isSigner: false,
|
|
2462
|
+
});
|
|
2463
|
+
remainingAccounts.push({
|
|
2464
|
+
pubkey: fulfillmentConfig.openbookV2EventHeap,
|
|
2465
|
+
isWritable: true,
|
|
2466
|
+
isSigner: false,
|
|
2467
|
+
});
|
|
2468
|
+
remainingAccounts.push({
|
|
2469
|
+
pubkey: fulfillmentConfig.openbookV2Bids,
|
|
2470
|
+
isWritable: true,
|
|
2471
|
+
isSigner: false,
|
|
2472
|
+
});
|
|
2473
|
+
remainingAccounts.push({
|
|
2474
|
+
pubkey: fulfillmentConfig.openbookV2Asks,
|
|
2475
|
+
isWritable: true,
|
|
2476
|
+
isSigner: false,
|
|
2477
|
+
});
|
|
2478
|
+
remainingAccounts.push({
|
|
2479
|
+
pubkey: fulfillmentConfig.openbookV2BaseVault,
|
|
2480
|
+
isWritable: true,
|
|
2481
|
+
isSigner: false,
|
|
2482
|
+
});
|
|
2483
|
+
remainingAccounts.push({
|
|
2484
|
+
pubkey: fulfillmentConfig.openbookV2QuoteVault,
|
|
2485
|
+
isWritable: true,
|
|
2486
|
+
isSigner: false,
|
|
2487
|
+
});
|
|
2488
|
+
remainingAccounts.push({
|
|
2489
|
+
pubkey: this.getSpotMarketAccount(marketIndex).vault,
|
|
2490
|
+
isWritable: true,
|
|
2491
|
+
isSigner: false,
|
|
2492
|
+
});
|
|
2493
|
+
remainingAccounts.push({
|
|
2494
|
+
pubkey: this.getQuoteSpotMarketAccount().vault,
|
|
2495
|
+
isWritable: true,
|
|
2496
|
+
isSigner: false,
|
|
2497
|
+
});
|
|
2498
|
+
remainingAccounts.push({
|
|
2499
|
+
pubkey: spl_token_1.TOKEN_PROGRAM_ID,
|
|
2500
|
+
isWritable: false,
|
|
2501
|
+
isSigner: false,
|
|
2502
|
+
});
|
|
2503
|
+
remainingAccounts.push({
|
|
2504
|
+
pubkey: web3_js_1.SystemProgram.programId,
|
|
2505
|
+
isWritable: false,
|
|
2506
|
+
isSigner: false,
|
|
2507
|
+
});
|
|
2508
|
+
remainingAccounts.push({
|
|
2509
|
+
pubkey: this.getSpotMarketAccount(marketIndex).pubkey,
|
|
2510
|
+
isWritable: true,
|
|
2511
|
+
isSigner: false,
|
|
2512
|
+
});
|
|
2513
|
+
remainingAccounts.push({
|
|
2514
|
+
pubkey: this.getQuoteSpotMarketAccount().pubkey,
|
|
2515
|
+
isWritable: true,
|
|
2516
|
+
isSigner: false,
|
|
2517
|
+
});
|
|
2518
|
+
if (fulfillmentConfig.remainingAccounts) {
|
|
2519
|
+
for (const remainingAccount of fulfillmentConfig.remainingAccounts) {
|
|
2520
|
+
remainingAccounts.push({
|
|
2521
|
+
pubkey: remainingAccount,
|
|
2522
|
+
isWritable: true,
|
|
2523
|
+
isSigner: false,
|
|
2524
|
+
});
|
|
2525
|
+
}
|
|
2526
|
+
}
|
|
2527
|
+
}
|
|
2528
|
+
/**
|
|
2529
|
+
* Swap tokens in drift account using jupiter
|
|
2530
|
+
* @param jupiterClient jupiter client to find routes and jupiter instructions
|
|
2531
|
+
* @param outMarketIndex the market index of the token you're buying
|
|
2532
|
+
* @param inMarketIndex the market index of the token you're selling
|
|
2533
|
+
* @param outAssociatedTokenAccount the token account to receive the token being sold on jupiter
|
|
2534
|
+
* @param inAssociatedTokenAccount the token account to
|
|
2535
|
+
* @param amount the amount of TokenIn, regardless of swapMode
|
|
2536
|
+
* @param slippageBps the max slippage passed to jupiter api
|
|
2537
|
+
* @param swapMode jupiter swapMode (ExactIn or ExactOut), default is ExactIn
|
|
2538
|
+
* @param route the jupiter route to use for the swap
|
|
2539
|
+
* @param reduceOnly specify if In or Out token on the drift account must reduceOnly, checked at end of swap
|
|
2540
|
+
* @param txParams
|
|
2541
|
+
*/
|
|
2542
|
+
async swap({ jupiterClient, outMarketIndex, inMarketIndex, outAssociatedTokenAccount, inAssociatedTokenAccount, amount, slippageBps, swapMode, route, reduceOnly, txParams, v6, onlyDirectRoutes = false, }) {
|
|
2543
|
+
let ixs;
|
|
2544
|
+
let lookupTables;
|
|
2545
|
+
if (v6) {
|
|
2546
|
+
const res = await this.getJupiterSwapIxV6({
|
|
2547
|
+
jupiterClient,
|
|
2548
|
+
outMarketIndex,
|
|
2549
|
+
inMarketIndex,
|
|
2550
|
+
outAssociatedTokenAccount,
|
|
2551
|
+
inAssociatedTokenAccount,
|
|
2552
|
+
amount,
|
|
2553
|
+
slippageBps,
|
|
2554
|
+
swapMode,
|
|
2555
|
+
quote: v6.quote,
|
|
2556
|
+
reduceOnly,
|
|
2557
|
+
onlyDirectRoutes,
|
|
2558
|
+
});
|
|
2559
|
+
ixs = res.ixs;
|
|
2560
|
+
lookupTables = res.lookupTables;
|
|
2561
|
+
}
|
|
2562
|
+
else {
|
|
2563
|
+
const res = await this.getJupiterSwapIx({
|
|
2564
|
+
jupiterClient,
|
|
2565
|
+
outMarketIndex,
|
|
2566
|
+
inMarketIndex,
|
|
2567
|
+
outAssociatedTokenAccount,
|
|
2568
|
+
inAssociatedTokenAccount,
|
|
2569
|
+
amount,
|
|
2570
|
+
slippageBps,
|
|
2571
|
+
swapMode,
|
|
2572
|
+
route,
|
|
2573
|
+
reduceOnly,
|
|
2574
|
+
});
|
|
2575
|
+
ixs = res.ixs;
|
|
2576
|
+
lookupTables = res.lookupTables;
|
|
2577
|
+
}
|
|
2578
|
+
const tx = (await this.buildTransaction(ixs, txParams, 0, lookupTables));
|
|
2579
|
+
const { txSig, slot } = await this.sendTransaction(tx);
|
|
2580
|
+
this.spotMarketLastSlotCache.set(outMarketIndex, slot);
|
|
2581
|
+
this.spotMarketLastSlotCache.set(inMarketIndex, slot);
|
|
2582
|
+
return txSig;
|
|
2583
|
+
}
|
|
2584
|
+
async getJupiterSwapIx({ jupiterClient, outMarketIndex, inMarketIndex, outAssociatedTokenAccount, inAssociatedTokenAccount, amount, slippageBps, swapMode, onlyDirectRoutes, route, reduceOnly, userAccountPublicKey, }) {
|
|
2585
|
+
const outMarket = this.getSpotMarketAccount(outMarketIndex);
|
|
2586
|
+
const inMarket = this.getSpotMarketAccount(inMarketIndex);
|
|
2587
|
+
if (!route) {
|
|
2588
|
+
const routes = await jupiterClient.getRoutes({
|
|
2589
|
+
inputMint: inMarket.mint,
|
|
2590
|
+
outputMint: outMarket.mint,
|
|
2591
|
+
amount,
|
|
2592
|
+
slippageBps,
|
|
2593
|
+
swapMode,
|
|
2594
|
+
onlyDirectRoutes,
|
|
2595
|
+
});
|
|
2596
|
+
if (!routes || routes.length === 0) {
|
|
2597
|
+
throw new Error('No jupiter routes found');
|
|
2598
|
+
}
|
|
2599
|
+
route = routes[0];
|
|
2600
|
+
}
|
|
2601
|
+
const transaction = await jupiterClient.getSwapTransaction({
|
|
2602
|
+
route,
|
|
2603
|
+
userPublicKey: this.provider.wallet.publicKey,
|
|
2604
|
+
slippageBps,
|
|
2605
|
+
});
|
|
2606
|
+
const { transactionMessage, lookupTables } = await jupiterClient.getTransactionMessageAndLookupTables({
|
|
2607
|
+
transaction,
|
|
2608
|
+
});
|
|
2609
|
+
const jupiterInstructions = jupiterClient.getJupiterInstructions({
|
|
2610
|
+
transactionMessage,
|
|
2611
|
+
inputMint: inMarket.mint,
|
|
2612
|
+
outputMint: outMarket.mint,
|
|
2613
|
+
});
|
|
2614
|
+
const preInstructions = [];
|
|
2615
|
+
if (!outAssociatedTokenAccount) {
|
|
2616
|
+
const tokenProgram = this.getTokenProgramForSpotMarket(outMarket);
|
|
2617
|
+
outAssociatedTokenAccount = await this.getAssociatedTokenAccount(outMarket.marketIndex, false, tokenProgram);
|
|
2618
|
+
const accountInfo = await this.connection.getAccountInfo(outAssociatedTokenAccount);
|
|
2619
|
+
if (!accountInfo) {
|
|
2620
|
+
preInstructions.push(this.createAssociatedTokenAccountIdempotentInstruction(outAssociatedTokenAccount, this.provider.wallet.publicKey, this.provider.wallet.publicKey, outMarket.mint, tokenProgram));
|
|
2621
|
+
}
|
|
2622
|
+
}
|
|
2623
|
+
if (!inAssociatedTokenAccount) {
|
|
2624
|
+
const tokenProgram = this.getTokenProgramForSpotMarket(outMarket);
|
|
2625
|
+
inAssociatedTokenAccount = await this.getAssociatedTokenAccount(inMarket.marketIndex, false, tokenProgram);
|
|
2626
|
+
const accountInfo = await this.connection.getAccountInfo(inAssociatedTokenAccount);
|
|
2627
|
+
if (!accountInfo) {
|
|
2628
|
+
preInstructions.push(this.createAssociatedTokenAccountIdempotentInstruction(inAssociatedTokenAccount, this.provider.wallet.publicKey, this.provider.wallet.publicKey, inMarket.mint, tokenProgram));
|
|
2629
|
+
}
|
|
2630
|
+
}
|
|
2631
|
+
const { beginSwapIx, endSwapIx } = await this.getSwapIx({
|
|
2632
|
+
outMarketIndex,
|
|
2633
|
+
inMarketIndex,
|
|
2634
|
+
amountIn: new anchor_1.BN(route.inAmount),
|
|
2635
|
+
inTokenAccount: inAssociatedTokenAccount,
|
|
2636
|
+
outTokenAccount: outAssociatedTokenAccount,
|
|
2637
|
+
reduceOnly,
|
|
2638
|
+
userAccountPublicKey,
|
|
2639
|
+
});
|
|
2640
|
+
const ixs = [
|
|
2641
|
+
...preInstructions,
|
|
2642
|
+
beginSwapIx,
|
|
2643
|
+
...jupiterInstructions,
|
|
2644
|
+
endSwapIx,
|
|
2645
|
+
];
|
|
2646
|
+
return { ixs, lookupTables };
|
|
2647
|
+
}
|
|
2648
|
+
async getJupiterSwapIxV6({ jupiterClient, outMarketIndex, inMarketIndex, outAssociatedTokenAccount, inAssociatedTokenAccount, amount, slippageBps, swapMode, onlyDirectRoutes, quote, reduceOnly, userAccountPublicKey, }) {
|
|
2649
|
+
const outMarket = this.getSpotMarketAccount(outMarketIndex);
|
|
2650
|
+
const inMarket = this.getSpotMarketAccount(inMarketIndex);
|
|
2651
|
+
if (!quote) {
|
|
2652
|
+
const fetchedQuote = await jupiterClient.getQuote({
|
|
2653
|
+
inputMint: inMarket.mint,
|
|
2654
|
+
outputMint: outMarket.mint,
|
|
2655
|
+
amount,
|
|
2656
|
+
slippageBps,
|
|
2657
|
+
swapMode,
|
|
2658
|
+
onlyDirectRoutes,
|
|
2659
|
+
});
|
|
2660
|
+
quote = fetchedQuote;
|
|
2661
|
+
}
|
|
2662
|
+
if (!quote) {
|
|
2663
|
+
throw new Error("Could not fetch Jupiter's quote. Please try again.");
|
|
2664
|
+
}
|
|
2665
|
+
const isExactOut = swapMode === 'ExactOut' || quote.swapMode === 'ExactOut';
|
|
2666
|
+
const amountIn = new anchor_1.BN(quote.inAmount);
|
|
2667
|
+
const exactOutBufferedAmountIn = amountIn.muln(1001).divn(1000); // Add 10bp buffer
|
|
2668
|
+
const transaction = await jupiterClient.getSwap({
|
|
2669
|
+
quote,
|
|
2670
|
+
userPublicKey: this.provider.wallet.publicKey,
|
|
2671
|
+
slippageBps,
|
|
2672
|
+
});
|
|
2673
|
+
const { transactionMessage, lookupTables } = await jupiterClient.getTransactionMessageAndLookupTables({
|
|
2674
|
+
transaction,
|
|
2675
|
+
});
|
|
2676
|
+
const jupiterInstructions = jupiterClient.getJupiterInstructions({
|
|
2677
|
+
transactionMessage,
|
|
2678
|
+
inputMint: inMarket.mint,
|
|
2679
|
+
outputMint: outMarket.mint,
|
|
2680
|
+
});
|
|
2681
|
+
const preInstructions = [];
|
|
2682
|
+
if (!outAssociatedTokenAccount) {
|
|
2683
|
+
const tokenProgram = this.getTokenProgramForSpotMarket(outMarket);
|
|
2684
|
+
outAssociatedTokenAccount = await this.getAssociatedTokenAccount(outMarket.marketIndex, false, tokenProgram);
|
|
2685
|
+
const accountInfo = await this.connection.getAccountInfo(outAssociatedTokenAccount);
|
|
2686
|
+
if (!accountInfo) {
|
|
2687
|
+
preInstructions.push(this.createAssociatedTokenAccountIdempotentInstruction(outAssociatedTokenAccount, this.provider.wallet.publicKey, this.provider.wallet.publicKey, outMarket.mint, tokenProgram));
|
|
2688
|
+
}
|
|
2689
|
+
}
|
|
2690
|
+
if (!inAssociatedTokenAccount) {
|
|
2691
|
+
const tokenProgram = this.getTokenProgramForSpotMarket(inMarket);
|
|
2692
|
+
inAssociatedTokenAccount = await this.getAssociatedTokenAccount(inMarket.marketIndex, false, tokenProgram);
|
|
2693
|
+
const accountInfo = await this.connection.getAccountInfo(inAssociatedTokenAccount);
|
|
2694
|
+
if (!accountInfo) {
|
|
2695
|
+
preInstructions.push(this.createAssociatedTokenAccountIdempotentInstruction(inAssociatedTokenAccount, this.provider.wallet.publicKey, this.provider.wallet.publicKey, inMarket.mint, tokenProgram));
|
|
2696
|
+
}
|
|
2697
|
+
}
|
|
2698
|
+
const { beginSwapIx, endSwapIx } = await this.getSwapIx({
|
|
2699
|
+
outMarketIndex,
|
|
2700
|
+
inMarketIndex,
|
|
2701
|
+
amountIn: isExactOut ? exactOutBufferedAmountIn : amountIn,
|
|
2702
|
+
inTokenAccount: inAssociatedTokenAccount,
|
|
2703
|
+
outTokenAccount: outAssociatedTokenAccount,
|
|
2704
|
+
reduceOnly,
|
|
2705
|
+
userAccountPublicKey,
|
|
2706
|
+
});
|
|
2707
|
+
const ixs = [
|
|
2708
|
+
...preInstructions,
|
|
2709
|
+
beginSwapIx,
|
|
2710
|
+
...jupiterInstructions,
|
|
2711
|
+
endSwapIx,
|
|
2712
|
+
];
|
|
2713
|
+
return { ixs, lookupTables };
|
|
2714
|
+
}
|
|
2715
|
+
/**
|
|
2716
|
+
* Get the drift begin_swap and end_swap instructions
|
|
2717
|
+
*
|
|
2718
|
+
* @param outMarketIndex the market index of the token you're buying
|
|
2719
|
+
* @param inMarketIndex the market index of the token you're selling
|
|
2720
|
+
* @param amountIn the amount of the token to sell
|
|
2721
|
+
* @param inTokenAccount the token account to move the tokens being sold
|
|
2722
|
+
* @param outTokenAccount the token account to receive the tokens being bought
|
|
2723
|
+
* @param limitPrice the limit price of the swap
|
|
2724
|
+
* @param reduceOnly
|
|
2725
|
+
* @param userAccountPublicKey optional, specify a custom userAccountPublicKey to use instead of getting the current user account; can be helpful if the account is being created within the current tx
|
|
2726
|
+
*/
|
|
2727
|
+
async getSwapIx({ outMarketIndex, inMarketIndex, amountIn, inTokenAccount, outTokenAccount, limitPrice, reduceOnly, userAccountPublicKey, }) {
|
|
2728
|
+
const userAccountPublicKeyToUse = userAccountPublicKey || (await this.getUserAccountPublicKey());
|
|
2729
|
+
const userAccounts = [];
|
|
2730
|
+
try {
|
|
2731
|
+
if (this.hasUser() && this.getUser().getUserAccountAndSlot()) {
|
|
2732
|
+
userAccounts.push(this.getUser().getUserAccountAndSlot().data);
|
|
2733
|
+
}
|
|
2734
|
+
}
|
|
2735
|
+
catch (err) {
|
|
2736
|
+
// ignore
|
|
2737
|
+
}
|
|
2738
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
2739
|
+
userAccounts,
|
|
2740
|
+
writableSpotMarketIndexes: [outMarketIndex, inMarketIndex],
|
|
2741
|
+
readableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
|
|
2742
|
+
});
|
|
2743
|
+
const outSpotMarket = this.getSpotMarketAccount(outMarketIndex);
|
|
2744
|
+
const inSpotMarket = this.getSpotMarketAccount(inMarketIndex);
|
|
2745
|
+
const outTokenProgram = this.getTokenProgramForSpotMarket(outSpotMarket);
|
|
2746
|
+
const inTokenProgram = this.getTokenProgramForSpotMarket(inSpotMarket);
|
|
2747
|
+
if (!outTokenProgram.equals(inTokenProgram)) {
|
|
2748
|
+
remainingAccounts.push({
|
|
2749
|
+
pubkey: outTokenProgram,
|
|
2750
|
+
isWritable: false,
|
|
2751
|
+
isSigner: false,
|
|
2752
|
+
});
|
|
2753
|
+
}
|
|
2754
|
+
if (outSpotMarket.tokenProgram === 1 || inSpotMarket.tokenProgram === 1) {
|
|
2755
|
+
remainingAccounts.push({
|
|
2756
|
+
pubkey: inSpotMarket.mint,
|
|
2757
|
+
isWritable: false,
|
|
2758
|
+
isSigner: false,
|
|
2759
|
+
});
|
|
2760
|
+
remainingAccounts.push({
|
|
2761
|
+
pubkey: outSpotMarket.mint,
|
|
2762
|
+
isWritable: false,
|
|
2763
|
+
isSigner: false,
|
|
2764
|
+
});
|
|
2765
|
+
}
|
|
2766
|
+
const beginSwapIx = await this.program.instruction.beginSwap(inMarketIndex, outMarketIndex, amountIn, {
|
|
2767
|
+
accounts: {
|
|
2768
|
+
state: await this.getStatePublicKey(),
|
|
2769
|
+
user: userAccountPublicKeyToUse,
|
|
2770
|
+
userStats: this.getUserStatsAccountPublicKey(),
|
|
2771
|
+
authority: this.wallet.publicKey,
|
|
2772
|
+
outSpotMarketVault: outSpotMarket.vault,
|
|
2773
|
+
inSpotMarketVault: inSpotMarket.vault,
|
|
2774
|
+
inTokenAccount,
|
|
2775
|
+
outTokenAccount,
|
|
2776
|
+
tokenProgram: inTokenProgram,
|
|
2777
|
+
driftSigner: this.getStateAccount().signer,
|
|
2778
|
+
instructions: anchor.web3.SYSVAR_INSTRUCTIONS_PUBKEY,
|
|
2779
|
+
},
|
|
2780
|
+
remainingAccounts,
|
|
2781
|
+
});
|
|
2782
|
+
const endSwapIx = await this.program.instruction.endSwap(inMarketIndex, outMarketIndex, limitPrice !== null && limitPrice !== void 0 ? limitPrice : null, reduceOnly !== null && reduceOnly !== void 0 ? reduceOnly : null, {
|
|
2783
|
+
accounts: {
|
|
2784
|
+
state: await this.getStatePublicKey(),
|
|
2785
|
+
user: userAccountPublicKeyToUse,
|
|
2786
|
+
userStats: this.getUserStatsAccountPublicKey(),
|
|
2787
|
+
authority: this.wallet.publicKey,
|
|
2788
|
+
outSpotMarketVault: outSpotMarket.vault,
|
|
2789
|
+
inSpotMarketVault: inSpotMarket.vault,
|
|
2790
|
+
inTokenAccount,
|
|
2791
|
+
outTokenAccount,
|
|
2792
|
+
tokenProgram: inTokenProgram,
|
|
2793
|
+
driftSigner: this.getStateAccount().signer,
|
|
2794
|
+
instructions: anchor.web3.SYSVAR_INSTRUCTIONS_PUBKEY,
|
|
2795
|
+
},
|
|
2796
|
+
remainingAccounts,
|
|
2797
|
+
});
|
|
2798
|
+
return { beginSwapIx, endSwapIx };
|
|
2799
|
+
}
|
|
2800
|
+
async stakeForMSOL({ amount }) {
|
|
2801
|
+
const ixs = await this.getStakeForMSOLIx({ amount });
|
|
2802
|
+
const tx = await this.buildTransaction(ixs);
|
|
2803
|
+
return this.sendTransaction(tx);
|
|
2804
|
+
}
|
|
2805
|
+
async getStakeForMSOLIx({ amount, userAccountPublicKey, }) {
|
|
2806
|
+
const wSOLMint = this.getSpotMarketAccount(1).mint;
|
|
2807
|
+
const mSOLAccount = await this.getAssociatedTokenAccount(2);
|
|
2808
|
+
const wSOLAccount = await this.getAssociatedTokenAccount(1, false);
|
|
2809
|
+
const wSOLAccountExists = await this.checkIfAccountExists(wSOLAccount);
|
|
2810
|
+
const closeWSOLIx = (0, spl_token_1.createCloseAccountInstruction)(wSOLAccount, this.wallet.publicKey, this.wallet.publicKey);
|
|
2811
|
+
const createWSOLIx = await this.createAssociatedTokenAccountIdempotentInstruction(wSOLAccount, this.wallet.publicKey, this.wallet.publicKey, wSOLMint);
|
|
2812
|
+
const { beginSwapIx, endSwapIx } = await this.getSwapIx({
|
|
2813
|
+
inMarketIndex: 1,
|
|
2814
|
+
outMarketIndex: 2,
|
|
2815
|
+
amountIn: amount,
|
|
2816
|
+
inTokenAccount: wSOLAccount,
|
|
2817
|
+
outTokenAccount: mSOLAccount,
|
|
2818
|
+
userAccountPublicKey,
|
|
2819
|
+
});
|
|
2820
|
+
const program = (0, marinade_1.getMarinadeFinanceProgram)(this.provider);
|
|
2821
|
+
const depositIx = await (0, marinade_1.getMarinadeDepositIx)({
|
|
2822
|
+
program,
|
|
2823
|
+
mSOLAccount: mSOLAccount,
|
|
2824
|
+
transferFrom: this.wallet.publicKey,
|
|
2825
|
+
amount,
|
|
2826
|
+
});
|
|
2827
|
+
const ixs = [];
|
|
2828
|
+
if (!wSOLAccountExists) {
|
|
2829
|
+
ixs.push(createWSOLIx);
|
|
2830
|
+
}
|
|
2831
|
+
ixs.push(beginSwapIx, closeWSOLIx, depositIx, createWSOLIx, endSwapIx);
|
|
2832
|
+
return ixs;
|
|
2833
|
+
}
|
|
2834
|
+
async triggerOrder(userAccountPublicKey, user, order, txParams, fillerPublicKey) {
|
|
2835
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getTriggerOrderIx(userAccountPublicKey, user, order, fillerPublicKey), txParams), [], this.opts);
|
|
2836
|
+
return txSig;
|
|
2837
|
+
}
|
|
2838
|
+
async getTriggerOrderIx(userAccountPublicKey, userAccount, order, fillerPublicKey) {
|
|
2839
|
+
const filler = fillerPublicKey !== null && fillerPublicKey !== void 0 ? fillerPublicKey : (await this.getUserAccountPublicKey());
|
|
2840
|
+
let remainingAccountsParams;
|
|
2841
|
+
if ((0, types_1.isVariant)(order.marketType, 'perp')) {
|
|
2842
|
+
remainingAccountsParams = {
|
|
2843
|
+
userAccounts: [userAccount],
|
|
2844
|
+
writablePerpMarketIndexes: [order.marketIndex],
|
|
2845
|
+
};
|
|
2846
|
+
}
|
|
2847
|
+
else {
|
|
2848
|
+
remainingAccountsParams = {
|
|
2849
|
+
userAccounts: [userAccount],
|
|
2850
|
+
writableSpotMarketIndexes: [order.marketIndex, numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
|
|
2851
|
+
};
|
|
2852
|
+
}
|
|
2853
|
+
const remainingAccounts = this.getRemainingAccounts(remainingAccountsParams);
|
|
2854
|
+
const orderId = order.orderId;
|
|
2855
|
+
return await this.program.instruction.triggerOrder(orderId, {
|
|
2856
|
+
accounts: {
|
|
2857
|
+
state: await this.getStatePublicKey(),
|
|
2858
|
+
filler,
|
|
2859
|
+
user: userAccountPublicKey,
|
|
2860
|
+
authority: this.wallet.publicKey,
|
|
2861
|
+
},
|
|
2862
|
+
remainingAccounts,
|
|
2863
|
+
});
|
|
2864
|
+
}
|
|
2865
|
+
async forceCancelOrders(userAccountPublicKey, user, txParams, fillerPublicKey) {
|
|
2866
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getForceCancelOrdersIx(userAccountPublicKey, user, fillerPublicKey), txParams), [], this.opts);
|
|
2867
|
+
return txSig;
|
|
2868
|
+
}
|
|
2869
|
+
async getForceCancelOrdersIx(userAccountPublicKey, userAccount, fillerPublicKey) {
|
|
2870
|
+
const filler = fillerPublicKey !== null && fillerPublicKey !== void 0 ? fillerPublicKey : (await this.getUserAccountPublicKey());
|
|
2871
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
2872
|
+
userAccounts: [userAccount],
|
|
2873
|
+
writableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
|
|
2874
|
+
});
|
|
2875
|
+
return await this.program.instruction.forceCancelOrders({
|
|
2876
|
+
accounts: {
|
|
2877
|
+
state: await this.getStatePublicKey(),
|
|
2878
|
+
filler,
|
|
2879
|
+
user: userAccountPublicKey,
|
|
2880
|
+
authority: this.wallet.publicKey,
|
|
2881
|
+
},
|
|
2882
|
+
remainingAccounts,
|
|
2883
|
+
});
|
|
2884
|
+
}
|
|
2885
|
+
async updateUserIdle(userAccountPublicKey, user, txParams, fillerPublicKey) {
|
|
2886
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getUpdateUserIdleIx(userAccountPublicKey, user, fillerPublicKey), txParams), [], this.opts);
|
|
2887
|
+
return txSig;
|
|
2888
|
+
}
|
|
2889
|
+
async getUpdateUserIdleIx(userAccountPublicKey, userAccount, fillerPublicKey) {
|
|
2890
|
+
const filler = fillerPublicKey !== null && fillerPublicKey !== void 0 ? fillerPublicKey : (await this.getUserAccountPublicKey());
|
|
2891
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
2892
|
+
userAccounts: [userAccount],
|
|
2893
|
+
});
|
|
2894
|
+
return await this.program.instruction.updateUserIdle({
|
|
2895
|
+
accounts: {
|
|
2896
|
+
state: await this.getStatePublicKey(),
|
|
2897
|
+
filler,
|
|
2898
|
+
user: userAccountPublicKey,
|
|
2899
|
+
authority: this.wallet.publicKey,
|
|
2900
|
+
},
|
|
2901
|
+
remainingAccounts,
|
|
2902
|
+
});
|
|
2903
|
+
}
|
|
2904
|
+
async logUserBalances(userAccountPublicKey, txParams) {
|
|
2905
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getLogUserBalancesIx(userAccountPublicKey), txParams), [], this.opts);
|
|
2906
|
+
return txSig;
|
|
2907
|
+
}
|
|
2908
|
+
async getLogUserBalancesIx(userAccountPublicKey) {
|
|
2909
|
+
const userAccount = (await this.program.account.user.fetch(userAccountPublicKey));
|
|
2910
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
2911
|
+
userAccounts: [userAccount],
|
|
2912
|
+
});
|
|
2913
|
+
return await this.program.instruction.logUserBalances({
|
|
2914
|
+
accounts: {
|
|
2915
|
+
state: await this.getStatePublicKey(),
|
|
2916
|
+
user: userAccountPublicKey,
|
|
2917
|
+
authority: this.wallet.publicKey,
|
|
2918
|
+
},
|
|
2919
|
+
remainingAccounts,
|
|
2920
|
+
});
|
|
2921
|
+
}
|
|
2922
|
+
async updateUserFuelBonus(userAccountPublicKey, user, userAuthority, txParams) {
|
|
2923
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getUpdateUserFuelBonusIx(userAccountPublicKey, user, userAuthority), txParams), [], this.opts);
|
|
2924
|
+
return txSig;
|
|
2925
|
+
}
|
|
2926
|
+
async getUpdateUserFuelBonusIx(userAccountPublicKey, userAccount, userAuthority) {
|
|
2927
|
+
const userStatsAccountPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAuthority);
|
|
2928
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
2929
|
+
userAccounts: [userAccount],
|
|
2930
|
+
});
|
|
2931
|
+
return await this.program.instruction.updateUserFuelBonus({
|
|
2932
|
+
accounts: {
|
|
2933
|
+
state: await this.getStatePublicKey(),
|
|
2934
|
+
user: userAccountPublicKey,
|
|
2935
|
+
userStats: userStatsAccountPublicKey,
|
|
2936
|
+
authority: this.wallet.publicKey,
|
|
2937
|
+
},
|
|
2938
|
+
remainingAccounts,
|
|
2939
|
+
});
|
|
2940
|
+
}
|
|
2941
|
+
async updateUserStatsReferrerStatus(userAuthority, txParams) {
|
|
2942
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getUpdateUserStatsReferrerStatusIx(userAuthority), txParams), [], this.opts);
|
|
2943
|
+
return txSig;
|
|
2944
|
+
}
|
|
2945
|
+
async getUpdateUserStatsReferrerStatusIx(userAuthority) {
|
|
2946
|
+
const userStatsAccountPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAuthority);
|
|
2947
|
+
return await this.program.instruction.updateUserStatsReferrerStatus({
|
|
2948
|
+
accounts: {
|
|
2949
|
+
state: await this.getStatePublicKey(),
|
|
2950
|
+
userStats: userStatsAccountPublicKey,
|
|
2951
|
+
authority: this.wallet.publicKey,
|
|
2952
|
+
},
|
|
2953
|
+
});
|
|
2954
|
+
}
|
|
2955
|
+
async updateUserOpenOrdersCount(userAccountPublicKey, user, txParams, fillerPublicKey) {
|
|
2956
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getUpdateUserOpenOrdersCountIx(userAccountPublicKey, user, fillerPublicKey), txParams), [], this.opts);
|
|
2957
|
+
return txSig;
|
|
2958
|
+
}
|
|
2959
|
+
async getUpdateUserOpenOrdersCountIx(userAccountPublicKey, userAccount, fillerPublicKey) {
|
|
2960
|
+
const filler = fillerPublicKey !== null && fillerPublicKey !== void 0 ? fillerPublicKey : (await this.getUserAccountPublicKey());
|
|
2961
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
2962
|
+
userAccounts: [userAccount],
|
|
2963
|
+
});
|
|
2964
|
+
return await this.program.instruction.updateUserOpenOrdersCount({
|
|
2965
|
+
accounts: {
|
|
2966
|
+
state: await this.getStatePublicKey(),
|
|
2967
|
+
filler,
|
|
2968
|
+
user: userAccountPublicKey,
|
|
2969
|
+
authority: this.wallet.publicKey,
|
|
2970
|
+
},
|
|
2971
|
+
remainingAccounts,
|
|
2972
|
+
});
|
|
2973
|
+
}
|
|
2974
|
+
async placeAndTakePerpOrder(orderParams, makerInfo, referrerInfo, successCondition, auctionDurationPercentage, txParams, subAccountId) {
|
|
2975
|
+
const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getPlaceAndTakePerpOrderIx(orderParams, makerInfo, referrerInfo, successCondition, auctionDurationPercentage, subAccountId), txParams), [], this.opts);
|
|
2976
|
+
this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
|
|
2977
|
+
return txSig;
|
|
2978
|
+
}
|
|
2979
|
+
async preparePlaceAndTakePerpOrderWithAdditionalOrders(orderParams, makerInfo, referrerInfo, bracketOrdersParams = new Array(), txParams, subAccountId, cancelExistingOrders, settlePnl, exitEarlyIfSimFails, auctionDurationPercentage) {
|
|
2980
|
+
const placeAndTakeIxs = [];
|
|
2981
|
+
const txsToSign = {
|
|
2982
|
+
placeAndTakeTx: undefined,
|
|
2983
|
+
cancelExistingOrdersTx: undefined,
|
|
2984
|
+
settlePnlTx: undefined,
|
|
2985
|
+
};
|
|
2986
|
+
// Get recent block hash so that we can re-use it for all transactions. Makes this logic run faster with fewer RPC requests
|
|
2987
|
+
const recentBlockHash = await this.txHandler.getLatestBlockhashForTransaction();
|
|
2988
|
+
let earlyExitFailedPlaceAndTakeSim = false;
|
|
2989
|
+
const prepPlaceAndTakeTx = async () => {
|
|
2990
|
+
var _a;
|
|
2991
|
+
const placeAndTakeIx = await this.getPlaceAndTakePerpOrderIx(orderParams, makerInfo, referrerInfo, undefined, auctionDurationPercentage, subAccountId);
|
|
2992
|
+
placeAndTakeIxs.push(placeAndTakeIx);
|
|
2993
|
+
if (bracketOrdersParams.length > 0) {
|
|
2994
|
+
const bracketOrdersIx = await this.getPlaceOrdersIx(bracketOrdersParams, subAccountId);
|
|
2995
|
+
placeAndTakeIxs.push(bracketOrdersIx);
|
|
2996
|
+
}
|
|
2997
|
+
const shouldUseSimulationComputeUnits = txParams === null || txParams === void 0 ? void 0 : txParams.useSimulatedComputeUnits;
|
|
2998
|
+
const shouldExitIfSimulationFails = exitEarlyIfSimFails;
|
|
2999
|
+
const txParamsWithoutImplicitSimulation = {
|
|
3000
|
+
...txParams,
|
|
3001
|
+
useSimulatedComputeUnits: false,
|
|
3002
|
+
};
|
|
3003
|
+
if (shouldUseSimulationComputeUnits || shouldExitIfSimulationFails) {
|
|
3004
|
+
const placeAndTakeTxToSim = (await this.buildTransaction(placeAndTakeIxs, txParams, undefined, undefined, true, recentBlockHash));
|
|
3005
|
+
const simulationResult = await txParamProcessor_1.TransactionParamProcessor.getTxSimComputeUnits(placeAndTakeTxToSim, this.connection, (_a = txParams.computeUnitsBufferMultiplier) !== null && _a !== void 0 ? _a : 1.2, txParams.lowerBoundCu);
|
|
3006
|
+
if (shouldExitIfSimulationFails && !simulationResult.success) {
|
|
3007
|
+
earlyExitFailedPlaceAndTakeSim = true;
|
|
3008
|
+
return;
|
|
3009
|
+
}
|
|
3010
|
+
txsToSign.placeAndTakeTx = await this.buildTransaction(placeAndTakeIxs, {
|
|
3011
|
+
...txParamsWithoutImplicitSimulation,
|
|
3012
|
+
computeUnits: simulationResult.computeUnits,
|
|
3013
|
+
}, undefined, undefined, undefined, recentBlockHash);
|
|
3014
|
+
}
|
|
3015
|
+
else {
|
|
3016
|
+
txsToSign.placeAndTakeTx = await this.buildTransaction(placeAndTakeIxs, txParams, undefined, undefined, undefined, recentBlockHash);
|
|
3017
|
+
}
|
|
3018
|
+
return;
|
|
3019
|
+
};
|
|
3020
|
+
const prepCancelOrderTx = async () => {
|
|
3021
|
+
if (cancelExistingOrders && (0, types_1.isVariant)(orderParams.marketType, 'perp')) {
|
|
3022
|
+
const cancelOrdersIx = await this.getCancelOrdersIx(orderParams.marketType, orderParams.marketIndex, null, subAccountId);
|
|
3023
|
+
txsToSign.cancelExistingOrdersTx = await this.buildTransaction([cancelOrdersIx], txParams, this.txVersion, undefined, undefined, recentBlockHash);
|
|
3024
|
+
}
|
|
3025
|
+
return;
|
|
3026
|
+
};
|
|
3027
|
+
const prepSettlePnlTx = async () => {
|
|
3028
|
+
if (settlePnl && (0, types_1.isVariant)(orderParams.marketType, 'perp')) {
|
|
3029
|
+
const userAccountPublicKey = await this.getUserAccountPublicKey(subAccountId);
|
|
3030
|
+
const settlePnlIx = await this.settlePNLIx(userAccountPublicKey, this.getUserAccount(subAccountId), orderParams.marketIndex);
|
|
3031
|
+
txsToSign.settlePnlTx = await this.buildTransaction([settlePnlIx], txParams, this.txVersion, undefined, undefined, recentBlockHash);
|
|
3032
|
+
}
|
|
3033
|
+
return;
|
|
3034
|
+
};
|
|
3035
|
+
await Promise.all([
|
|
3036
|
+
prepPlaceAndTakeTx(),
|
|
3037
|
+
prepCancelOrderTx(),
|
|
3038
|
+
prepSettlePnlTx(),
|
|
3039
|
+
]);
|
|
3040
|
+
if (earlyExitFailedPlaceAndTakeSim) {
|
|
3041
|
+
return null;
|
|
3042
|
+
}
|
|
3043
|
+
return txsToSign;
|
|
3044
|
+
}
|
|
3045
|
+
async placeAndTakePerpWithAdditionalOrders(orderParams, makerInfo, referrerInfo, bracketOrdersParams = new Array(), txParams, subAccountId, cancelExistingOrders, settlePnl, exitEarlyIfSimFails) {
|
|
3046
|
+
const txsToSign = await this.preparePlaceAndTakePerpOrderWithAdditionalOrders(orderParams, makerInfo, referrerInfo, bracketOrdersParams, txParams, subAccountId, cancelExistingOrders, settlePnl, exitEarlyIfSimFails);
|
|
3047
|
+
if (!txsToSign) {
|
|
3048
|
+
return null;
|
|
3049
|
+
}
|
|
3050
|
+
const signedTxs = (await this.txHandler.getSignedTransactionMap(txsToSign,
|
|
3051
|
+
// @ts-ignore
|
|
3052
|
+
this.provider.wallet)).signedTxMap;
|
|
3053
|
+
const { txSig, slot } = await this.sendTransaction(signedTxs.placeAndTakeTx, [], this.opts, true);
|
|
3054
|
+
this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
|
|
3055
|
+
return {
|
|
3056
|
+
txSig,
|
|
3057
|
+
signedCancelExistingOrdersTx: signedTxs.cancelExistingOrdersTx,
|
|
3058
|
+
signedSettlePnlTx: signedTxs.settlePnlTx,
|
|
3059
|
+
};
|
|
3060
|
+
}
|
|
3061
|
+
async getPlaceAndTakePerpOrderIx(orderParams, makerInfo, referrerInfo, successCondition, auctionDurationPercentage, subAccountId) {
|
|
3062
|
+
orderParams = (0, orderParams_1.getOrderParams)(orderParams, { marketType: types_1.MarketType.PERP });
|
|
3063
|
+
const userStatsPublicKey = await this.getUserStatsAccountPublicKey();
|
|
3064
|
+
const user = await this.getUserAccountPublicKey(subAccountId);
|
|
3065
|
+
makerInfo = Array.isArray(makerInfo)
|
|
3066
|
+
? makerInfo
|
|
3067
|
+
: makerInfo
|
|
3068
|
+
? [makerInfo]
|
|
3069
|
+
: [];
|
|
3070
|
+
const userAccounts = [this.getUserAccount(subAccountId)];
|
|
3071
|
+
for (const maker of makerInfo) {
|
|
3072
|
+
userAccounts.push(maker.makerUserAccount);
|
|
3073
|
+
}
|
|
3074
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
3075
|
+
userAccounts,
|
|
3076
|
+
useMarketLastSlotCache: true,
|
|
3077
|
+
writablePerpMarketIndexes: [orderParams.marketIndex],
|
|
3078
|
+
});
|
|
3079
|
+
for (const maker of makerInfo) {
|
|
3080
|
+
remainingAccounts.push({
|
|
3081
|
+
pubkey: maker.maker,
|
|
3082
|
+
isWritable: true,
|
|
3083
|
+
isSigner: false,
|
|
3084
|
+
});
|
|
3085
|
+
remainingAccounts.push({
|
|
3086
|
+
pubkey: maker.makerStats,
|
|
3087
|
+
isWritable: true,
|
|
3088
|
+
isSigner: false,
|
|
3089
|
+
});
|
|
3090
|
+
}
|
|
3091
|
+
if (referrerInfo) {
|
|
3092
|
+
const referrerIsMaker = makerInfo.find((maker) => maker.maker.equals(referrerInfo.referrer)) !==
|
|
3093
|
+
undefined;
|
|
3094
|
+
if (!referrerIsMaker) {
|
|
3095
|
+
remainingAccounts.push({
|
|
3096
|
+
pubkey: referrerInfo.referrer,
|
|
3097
|
+
isWritable: true,
|
|
3098
|
+
isSigner: false,
|
|
3099
|
+
});
|
|
3100
|
+
remainingAccounts.push({
|
|
3101
|
+
pubkey: referrerInfo.referrerStats,
|
|
3102
|
+
isWritable: true,
|
|
3103
|
+
isSigner: false,
|
|
3104
|
+
});
|
|
3105
|
+
}
|
|
3106
|
+
}
|
|
3107
|
+
let optionalParams = null;
|
|
3108
|
+
if (auctionDurationPercentage || successCondition) {
|
|
3109
|
+
optionalParams =
|
|
3110
|
+
((auctionDurationPercentage !== null && auctionDurationPercentage !== void 0 ? auctionDurationPercentage : 100) << 8) | (successCondition !== null && successCondition !== void 0 ? successCondition : 0);
|
|
3111
|
+
}
|
|
3112
|
+
return await this.program.instruction.placeAndTakePerpOrder(orderParams, optionalParams, {
|
|
3113
|
+
accounts: {
|
|
3114
|
+
state: await this.getStatePublicKey(),
|
|
3115
|
+
user,
|
|
3116
|
+
userStats: userStatsPublicKey,
|
|
3117
|
+
authority: this.wallet.publicKey,
|
|
3118
|
+
},
|
|
3119
|
+
remainingAccounts,
|
|
3120
|
+
});
|
|
3121
|
+
}
|
|
3122
|
+
async placeAndMakePerpOrder(orderParams, takerInfo, referrerInfo, txParams, subAccountId) {
|
|
3123
|
+
const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getPlaceAndMakePerpOrderIx(orderParams, takerInfo, referrerInfo, subAccountId), txParams), [], this.opts);
|
|
3124
|
+
this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
|
|
3125
|
+
return txSig;
|
|
3126
|
+
}
|
|
3127
|
+
async getPlaceAndMakePerpOrderIx(orderParams, takerInfo, referrerInfo, subAccountId) {
|
|
3128
|
+
orderParams = (0, orderParams_1.getOrderParams)(orderParams, { marketType: types_1.MarketType.PERP });
|
|
3129
|
+
const userStatsPublicKey = this.getUserStatsAccountPublicKey();
|
|
3130
|
+
const user = await this.getUserAccountPublicKey(subAccountId);
|
|
3131
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
3132
|
+
userAccounts: [
|
|
3133
|
+
this.getUserAccount(subAccountId),
|
|
3134
|
+
takerInfo.takerUserAccount,
|
|
3135
|
+
],
|
|
3136
|
+
useMarketLastSlotCache: true,
|
|
3137
|
+
writablePerpMarketIndexes: [orderParams.marketIndex],
|
|
3138
|
+
});
|
|
3139
|
+
if (referrerInfo) {
|
|
3140
|
+
remainingAccounts.push({
|
|
3141
|
+
pubkey: referrerInfo.referrer,
|
|
3142
|
+
isWritable: true,
|
|
3143
|
+
isSigner: false,
|
|
3144
|
+
});
|
|
3145
|
+
remainingAccounts.push({
|
|
3146
|
+
pubkey: referrerInfo.referrerStats,
|
|
3147
|
+
isWritable: true,
|
|
3148
|
+
isSigner: false,
|
|
3149
|
+
});
|
|
3150
|
+
}
|
|
3151
|
+
const takerOrderId = takerInfo.order.orderId;
|
|
3152
|
+
return await this.program.instruction.placeAndMakePerpOrder(orderParams, takerOrderId, {
|
|
3153
|
+
accounts: {
|
|
3154
|
+
state: await this.getStatePublicKey(),
|
|
3155
|
+
user,
|
|
3156
|
+
userStats: userStatsPublicKey,
|
|
3157
|
+
taker: takerInfo.taker,
|
|
3158
|
+
takerStats: takerInfo.takerStats,
|
|
3159
|
+
authority: this.wallet.publicKey,
|
|
3160
|
+
},
|
|
3161
|
+
remainingAccounts,
|
|
3162
|
+
});
|
|
3163
|
+
}
|
|
3164
|
+
encodeSwiftServerMessage(message) {
|
|
3165
|
+
return this.program.coder.types.encode('SwiftServerMessage', message);
|
|
3166
|
+
}
|
|
3167
|
+
decodeSwiftServerMessage(encodedMessage) {
|
|
3168
|
+
const decodedSwiftMessage = this.program.coder.types.decode('SwiftServerMessage', encodedMessage);
|
|
3169
|
+
return {
|
|
3170
|
+
uuid: decodedSwiftMessage.uuid,
|
|
3171
|
+
slot: decodedSwiftMessage.slot,
|
|
3172
|
+
swiftOrderSignature: decodedSwiftMessage.swiftSignature,
|
|
3173
|
+
};
|
|
3174
|
+
}
|
|
3175
|
+
signSwiftServerMessage(message) {
|
|
3176
|
+
const swiftServerMessage = Uint8Array.from((0, digest_1.digest)(this.encodeSwiftServerMessage(message)));
|
|
3177
|
+
return this.signMessage(swiftServerMessage);
|
|
3178
|
+
}
|
|
3179
|
+
signSwiftOrderParamsMessage(orderParamsMessage) {
|
|
3180
|
+
const takerOrderParamsMessage = this.encodeSwiftOrderParamsMessage(orderParamsMessage);
|
|
3181
|
+
return this.signMessage(new TextEncoder().encode((0, digest_1.digest)(takerOrderParamsMessage).toString('hex')));
|
|
3182
|
+
}
|
|
3183
|
+
encodeSwiftOrderParamsMessage(orderParamsMessage) {
|
|
3184
|
+
return this.program.coder.types.encode('SwiftOrderParamsMessage', orderParamsMessage);
|
|
3185
|
+
}
|
|
3186
|
+
decodeSwiftOrderParamsMessage(encodedMessage) {
|
|
3187
|
+
return this.program.coder.types.decode('SwiftOrderParamsMessage', encodedMessage);
|
|
3188
|
+
}
|
|
3189
|
+
signMessage(message, keypair = this.wallet.payer) {
|
|
3190
|
+
return Buffer.from(tweetnacl_1.default.sign.detached(message, keypair.secretKey));
|
|
3191
|
+
}
|
|
3192
|
+
async placeSwiftTakerOrder(swiftServerMessage, swiftSignature, swiftOrderParamsMessage, swiftOrderParamsSignature, marketIndex, takerInfo, txParams) {
|
|
3193
|
+
const ixs = await this.getPlaceSwiftTakerPerpOrderIxs(swiftServerMessage, swiftSignature, swiftOrderParamsMessage, swiftOrderParamsSignature, marketIndex, takerInfo);
|
|
3194
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(ixs, txParams), [], this.opts);
|
|
3195
|
+
return txSig;
|
|
3196
|
+
}
|
|
3197
|
+
async getPlaceSwiftTakerPerpOrderIxs(encodedSwiftServerMessage, swiftSignature, encodedSwiftOrderParamsMessage, swiftOrderParamsSignature, marketIndex, takerInfo, authority) {
|
|
3198
|
+
if (!authority && !takerInfo.takerUserAccount) {
|
|
3199
|
+
throw new Error('authority or takerUserAccount must be provided');
|
|
3200
|
+
}
|
|
3201
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
3202
|
+
userAccounts: [takerInfo.takerUserAccount],
|
|
3203
|
+
useMarketLastSlotCache: true,
|
|
3204
|
+
readablePerpMarketIndex: marketIndex,
|
|
3205
|
+
});
|
|
3206
|
+
const swiftServerSignatureIx = web3_js_1.Ed25519Program.createInstructionWithPublicKey({
|
|
3207
|
+
publicKey: new web3_js_1.PublicKey(this.swiftID).toBytes(),
|
|
3208
|
+
signature: Uint8Array.from(swiftSignature),
|
|
3209
|
+
message: Uint8Array.from((0, digest_1.digest)(encodedSwiftServerMessage)),
|
|
3210
|
+
});
|
|
3211
|
+
const authorityToUse = authority || takerInfo.takerUserAccount.authority;
|
|
3212
|
+
const swiftOrderParamsSignatureIx = web3_js_1.Ed25519Program.createInstructionWithPublicKey({
|
|
3213
|
+
publicKey: authorityToUse.toBytes(),
|
|
3214
|
+
signature: Uint8Array.from(swiftOrderParamsSignature),
|
|
3215
|
+
message: new TextEncoder().encode((0, digest_1.digest)(encodedSwiftOrderParamsMessage).toString('hex')),
|
|
3216
|
+
});
|
|
3217
|
+
const placeTakerSwiftPerpOrderIx = await this.program.instruction.placeSwiftTakerOrder(encodedSwiftServerMessage, encodedSwiftOrderParamsMessage, {
|
|
3218
|
+
accounts: {
|
|
3219
|
+
state: await this.getStatePublicKey(),
|
|
3220
|
+
user: takerInfo.taker,
|
|
3221
|
+
userStats: takerInfo.takerStats,
|
|
3222
|
+
swiftUserOrders: (0, pda_1.getSwiftUserAccountPublicKey)(this.program.programId, takerInfo.taker),
|
|
3223
|
+
authority: this.wallet.publicKey,
|
|
3224
|
+
ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
|
|
3225
|
+
},
|
|
3226
|
+
remainingAccounts,
|
|
3227
|
+
});
|
|
3228
|
+
return [
|
|
3229
|
+
swiftServerSignatureIx,
|
|
3230
|
+
swiftOrderParamsSignatureIx,
|
|
3231
|
+
placeTakerSwiftPerpOrderIx,
|
|
3232
|
+
];
|
|
3233
|
+
}
|
|
3234
|
+
async placeAndMakeSwiftPerpOrder(encodedSwiftMessage, swiftSignature, encodedSwiftOrderParamsMessage, swiftOrderParamsSignature, swiftOrderUuid, takerInfo, orderParams, referrerInfo, txParams, subAccountId) {
|
|
3235
|
+
const ixs = await this.getPlaceAndMakeSwiftPerpOrderIxs(encodedSwiftMessage, swiftSignature, encodedSwiftOrderParamsMessage, swiftOrderParamsSignature, swiftOrderUuid, takerInfo, orderParams, referrerInfo, subAccountId);
|
|
3236
|
+
const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(ixs, txParams), [], this.opts);
|
|
3237
|
+
this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);
|
|
3238
|
+
return txSig;
|
|
3239
|
+
}
|
|
3240
|
+
async getPlaceAndMakeSwiftPerpOrderIxs(encodedSwiftMessage, swiftSignature, encodedSwiftOrderParamsMessage, swiftOrderParamsSignature, swiftOrderUuid, takerInfo, orderParams, referrerInfo, subAccountId) {
|
|
3241
|
+
const [swiftServerSignatureIx, swiftOrderSignatureIx, placeTakerSwiftPerpOrderIx,] = await this.getPlaceSwiftTakerPerpOrderIxs(encodedSwiftMessage, swiftSignature, encodedSwiftOrderParamsMessage, swiftOrderParamsSignature, orderParams.marketIndex, takerInfo);
|
|
3242
|
+
orderParams = (0, orderParams_1.getOrderParams)(orderParams, { marketType: types_1.MarketType.PERP });
|
|
3243
|
+
const userStatsPublicKey = this.getUserStatsAccountPublicKey();
|
|
3244
|
+
const user = await this.getUserAccountPublicKey(subAccountId);
|
|
3245
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
3246
|
+
userAccounts: [
|
|
3247
|
+
this.getUserAccount(subAccountId),
|
|
3248
|
+
takerInfo.takerUserAccount,
|
|
3249
|
+
],
|
|
3250
|
+
useMarketLastSlotCache: true,
|
|
3251
|
+
writablePerpMarketIndexes: [orderParams.marketIndex],
|
|
3252
|
+
});
|
|
3253
|
+
if (referrerInfo) {
|
|
3254
|
+
remainingAccounts.push({
|
|
3255
|
+
pubkey: referrerInfo.referrer,
|
|
3256
|
+
isWritable: true,
|
|
3257
|
+
isSigner: false,
|
|
3258
|
+
});
|
|
3259
|
+
remainingAccounts.push({
|
|
3260
|
+
pubkey: referrerInfo.referrerStats,
|
|
3261
|
+
isWritable: true,
|
|
3262
|
+
isSigner: false,
|
|
3263
|
+
});
|
|
3264
|
+
}
|
|
3265
|
+
const placeAndMakeIx = await this.program.instruction.placeAndMakeSwiftPerpOrder(orderParams, swiftOrderUuid, {
|
|
3266
|
+
accounts: {
|
|
3267
|
+
state: await this.getStatePublicKey(),
|
|
3268
|
+
user,
|
|
3269
|
+
userStats: userStatsPublicKey,
|
|
3270
|
+
taker: takerInfo.taker,
|
|
3271
|
+
takerStats: takerInfo.takerStats,
|
|
3272
|
+
authority: this.wallet.publicKey,
|
|
3273
|
+
takerSwiftUserOrders: (0, pda_1.getSwiftUserAccountPublicKey)(this.program.programId, takerInfo.taker),
|
|
3274
|
+
},
|
|
3275
|
+
remainingAccounts,
|
|
3276
|
+
});
|
|
3277
|
+
return [
|
|
3278
|
+
swiftServerSignatureIx,
|
|
3279
|
+
swiftOrderSignatureIx,
|
|
3280
|
+
placeTakerSwiftPerpOrderIx,
|
|
3281
|
+
placeAndMakeIx,
|
|
3282
|
+
];
|
|
3283
|
+
}
|
|
3284
|
+
encodeRFQMakerOrderParams(message) {
|
|
3285
|
+
return this.program.coder.types.encode('RFQMakerOrderParams', message);
|
|
3286
|
+
}
|
|
3287
|
+
async placeAndMatchRFQOrders(rfqMatches, txParams) {
|
|
3288
|
+
const ixs = await this.getPlaceAndMatchRFQOrdersIxs(rfqMatches);
|
|
3289
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(ixs, txParams), [], this.opts);
|
|
3290
|
+
return txSig;
|
|
3291
|
+
}
|
|
3292
|
+
async getPlaceAndMatchRFQOrdersIxs(rfqMatches) {
|
|
3293
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
3294
|
+
userAccounts: [this.getUserAccount()],
|
|
3295
|
+
useMarketLastSlotCache: true,
|
|
3296
|
+
writablePerpMarketIndexes: [rfqMatches[0].makerOrderParams.marketIndex],
|
|
3297
|
+
});
|
|
3298
|
+
const makerAccountMetas = [];
|
|
3299
|
+
const verifyIxs = [];
|
|
3300
|
+
for (const match of rfqMatches) {
|
|
3301
|
+
const verifyIx = web3_js_1.Ed25519Program.createInstructionWithPublicKey({
|
|
3302
|
+
publicKey: match.makerOrderParams.authority.toBytes(),
|
|
3303
|
+
signature: match.makerSignature,
|
|
3304
|
+
message: Uint8Array.from(this.encodeRFQMakerOrderParams(match.makerOrderParams)),
|
|
3305
|
+
});
|
|
3306
|
+
verifyIxs.push(verifyIx);
|
|
3307
|
+
const userAccountPubkey = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, match.makerOrderParams.authority, match.makerOrderParams.subAccountId);
|
|
3308
|
+
makerAccountMetas.push({
|
|
3309
|
+
pubkey: userAccountPubkey,
|
|
3310
|
+
isWritable: true,
|
|
3311
|
+
isSigner: false,
|
|
3312
|
+
});
|
|
3313
|
+
makerAccountMetas.push({
|
|
3314
|
+
pubkey: (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, match.makerOrderParams.authority),
|
|
3315
|
+
isWritable: true,
|
|
3316
|
+
isSigner: false,
|
|
3317
|
+
});
|
|
3318
|
+
makerAccountMetas.push({
|
|
3319
|
+
pubkey: (0, pda_1.getRFQUserAccountPublicKey)(this.program.programId, userAccountPubkey),
|
|
3320
|
+
isWritable: true,
|
|
3321
|
+
isSigner: false,
|
|
3322
|
+
});
|
|
3323
|
+
}
|
|
3324
|
+
remainingAccounts.push(...makerAccountMetas);
|
|
3325
|
+
const userStatsPublicKey = this.getUserStatsAccountPublicKey();
|
|
3326
|
+
const user = await this.getUserAccountPublicKey();
|
|
3327
|
+
const placeAndMatchRFQOrdersIx = await this.program.instruction.placeAndMatchRfqOrders(rfqMatches, {
|
|
3328
|
+
accounts: {
|
|
3329
|
+
state: await this.getStatePublicKey(),
|
|
3330
|
+
user,
|
|
3331
|
+
userStats: userStatsPublicKey,
|
|
3332
|
+
authority: this.wallet.publicKey,
|
|
3333
|
+
ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
|
|
3334
|
+
},
|
|
3335
|
+
remainingAccounts,
|
|
3336
|
+
});
|
|
3337
|
+
return [...verifyIxs, placeAndMatchRFQOrdersIx];
|
|
3338
|
+
}
|
|
3339
|
+
async preparePlaceAndTakeSpotOrder(orderParams, fulfillmentConfig, makerInfo, referrerInfo, txParams, subAccountId) {
|
|
3340
|
+
const tx = await this.buildTransaction(await this.getPlaceAndTakeSpotOrderIx(orderParams, fulfillmentConfig, makerInfo, referrerInfo, subAccountId), txParams);
|
|
3341
|
+
return {
|
|
3342
|
+
placeAndTakeSpotOrderTx: tx,
|
|
3343
|
+
};
|
|
3344
|
+
}
|
|
3345
|
+
async placeAndTakeSpotOrder(orderParams, fulfillmentConfig, makerInfo, referrerInfo, txParams, subAccountId) {
|
|
3346
|
+
const { txSig, slot } = await this.sendTransaction((await this.preparePlaceAndTakeSpotOrder(orderParams, fulfillmentConfig, makerInfo, referrerInfo, txParams, subAccountId)).placeAndTakeSpotOrderTx, [], this.opts, false);
|
|
3347
|
+
this.spotMarketLastSlotCache.set(orderParams.marketIndex, slot);
|
|
3348
|
+
this.spotMarketLastSlotCache.set(numericConstants_1.QUOTE_SPOT_MARKET_INDEX, slot);
|
|
3349
|
+
return txSig;
|
|
3350
|
+
}
|
|
3351
|
+
async getPlaceAndTakeSpotOrderIx(orderParams, fulfillmentConfig, makerInfo, referrerInfo, subAccountId) {
|
|
3352
|
+
orderParams = (0, orderParams_1.getOrderParams)(orderParams, { marketType: types_1.MarketType.SPOT });
|
|
3353
|
+
const userStatsPublicKey = this.getUserStatsAccountPublicKey();
|
|
3354
|
+
const user = await this.getUserAccountPublicKey(subAccountId);
|
|
3355
|
+
const userAccounts = [this.getUserAccount(subAccountId)];
|
|
3356
|
+
if (makerInfo !== undefined) {
|
|
3357
|
+
userAccounts.push(makerInfo.makerUserAccount);
|
|
3358
|
+
}
|
|
3359
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
3360
|
+
userAccounts,
|
|
3361
|
+
useMarketLastSlotCache: true,
|
|
3362
|
+
writableSpotMarketIndexes: [
|
|
3363
|
+
orderParams.marketIndex,
|
|
3364
|
+
numericConstants_1.QUOTE_SPOT_MARKET_INDEX,
|
|
3365
|
+
],
|
|
3366
|
+
});
|
|
3367
|
+
let makerOrderId = null;
|
|
3368
|
+
if (makerInfo) {
|
|
3369
|
+
makerOrderId = makerInfo.order.orderId;
|
|
3370
|
+
remainingAccounts.push({
|
|
3371
|
+
pubkey: makerInfo.maker,
|
|
3372
|
+
isSigner: false,
|
|
3373
|
+
isWritable: true,
|
|
3374
|
+
});
|
|
3375
|
+
remainingAccounts.push({
|
|
3376
|
+
pubkey: makerInfo.makerStats,
|
|
3377
|
+
isSigner: false,
|
|
3378
|
+
isWritable: true,
|
|
3379
|
+
});
|
|
3380
|
+
}
|
|
3381
|
+
if (referrerInfo) {
|
|
3382
|
+
remainingAccounts.push({
|
|
3383
|
+
pubkey: referrerInfo.referrer,
|
|
3384
|
+
isWritable: true,
|
|
3385
|
+
isSigner: false,
|
|
3386
|
+
});
|
|
3387
|
+
remainingAccounts.push({
|
|
3388
|
+
pubkey: referrerInfo.referrerStats,
|
|
3389
|
+
isWritable: true,
|
|
3390
|
+
isSigner: false,
|
|
3391
|
+
});
|
|
3392
|
+
}
|
|
3393
|
+
this.addSpotFulfillmentAccounts(orderParams.marketIndex, remainingAccounts, fulfillmentConfig);
|
|
3394
|
+
return await this.program.instruction.placeAndTakeSpotOrder(orderParams, fulfillmentConfig ? fulfillmentConfig.fulfillmentType : null, makerOrderId, {
|
|
3395
|
+
accounts: {
|
|
3396
|
+
state: await this.getStatePublicKey(),
|
|
3397
|
+
user,
|
|
3398
|
+
userStats: userStatsPublicKey,
|
|
3399
|
+
authority: this.wallet.publicKey,
|
|
3400
|
+
},
|
|
3401
|
+
remainingAccounts,
|
|
3402
|
+
});
|
|
3403
|
+
}
|
|
3404
|
+
async placeAndMakeSpotOrder(orderParams, takerInfo, fulfillmentConfig, referrerInfo, txParams, subAccountId) {
|
|
3405
|
+
const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getPlaceAndMakeSpotOrderIx(orderParams, takerInfo, fulfillmentConfig, referrerInfo, subAccountId), txParams), [], this.opts);
|
|
3406
|
+
this.spotMarketLastSlotCache.set(orderParams.marketIndex, slot);
|
|
3407
|
+
this.spotMarketLastSlotCache.set(numericConstants_1.QUOTE_SPOT_MARKET_INDEX, slot);
|
|
3408
|
+
return txSig;
|
|
3409
|
+
}
|
|
3410
|
+
async getPlaceAndMakeSpotOrderIx(orderParams, takerInfo, fulfillmentConfig, referrerInfo, subAccountId) {
|
|
3411
|
+
orderParams = (0, orderParams_1.getOrderParams)(orderParams, { marketType: types_1.MarketType.SPOT });
|
|
3412
|
+
const userStatsPublicKey = this.getUserStatsAccountPublicKey();
|
|
3413
|
+
const user = await this.getUserAccountPublicKey(subAccountId);
|
|
3414
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
3415
|
+
userAccounts: [
|
|
3416
|
+
this.getUserAccount(subAccountId),
|
|
3417
|
+
takerInfo.takerUserAccount,
|
|
3418
|
+
],
|
|
3419
|
+
useMarketLastSlotCache: true,
|
|
3420
|
+
writableSpotMarketIndexes: [
|
|
3421
|
+
orderParams.marketIndex,
|
|
3422
|
+
numericConstants_1.QUOTE_SPOT_MARKET_INDEX,
|
|
3423
|
+
],
|
|
3424
|
+
});
|
|
3425
|
+
if (referrerInfo) {
|
|
3426
|
+
remainingAccounts.push({
|
|
3427
|
+
pubkey: referrerInfo.referrer,
|
|
3428
|
+
isWritable: true,
|
|
3429
|
+
isSigner: false,
|
|
3430
|
+
});
|
|
3431
|
+
remainingAccounts.push({
|
|
3432
|
+
pubkey: referrerInfo.referrerStats,
|
|
3433
|
+
isWritable: true,
|
|
3434
|
+
isSigner: false,
|
|
3435
|
+
});
|
|
3436
|
+
}
|
|
3437
|
+
this.addSpotFulfillmentAccounts(orderParams.marketIndex, remainingAccounts, fulfillmentConfig);
|
|
3438
|
+
const takerOrderId = takerInfo.order.orderId;
|
|
3439
|
+
return await this.program.instruction.placeAndMakeSpotOrder(orderParams, takerOrderId, fulfillmentConfig ? fulfillmentConfig.fulfillmentType : null, {
|
|
3440
|
+
accounts: {
|
|
3441
|
+
state: await this.getStatePublicKey(),
|
|
3442
|
+
user,
|
|
3443
|
+
userStats: userStatsPublicKey,
|
|
3444
|
+
taker: takerInfo.taker,
|
|
3445
|
+
takerStats: takerInfo.takerStats,
|
|
3446
|
+
authority: this.wallet.publicKey,
|
|
3447
|
+
},
|
|
3448
|
+
remainingAccounts,
|
|
3449
|
+
});
|
|
3450
|
+
}
|
|
3451
|
+
/**
|
|
3452
|
+
* @deprecated use {@link placePerpOrder} or {@link placeAndTakePerpOrder} instead
|
|
3453
|
+
*/
|
|
3454
|
+
async closePosition(marketIndex, limitPrice, subAccountId) {
|
|
3455
|
+
const userPosition = this.getUser(subAccountId).getPerpPosition(marketIndex);
|
|
3456
|
+
if (!userPosition) {
|
|
3457
|
+
throw Error(`No position in market ${marketIndex.toString()}`);
|
|
3458
|
+
}
|
|
3459
|
+
return await this.placeAndTakePerpOrder({
|
|
3460
|
+
orderType: types_1.OrderType.MARKET,
|
|
3461
|
+
marketIndex,
|
|
3462
|
+
direction: (0, position_1.findDirectionToClose)(userPosition),
|
|
3463
|
+
baseAssetAmount: userPosition.baseAssetAmount.abs(),
|
|
3464
|
+
reduceOnly: true,
|
|
3465
|
+
price: limitPrice,
|
|
3466
|
+
}, undefined, undefined, undefined, undefined, undefined, subAccountId);
|
|
3467
|
+
}
|
|
3468
|
+
/**
|
|
3469
|
+
* Modifies an open order by closing it and replacing it with a new order.
|
|
3470
|
+
* @deprecated use modifyOrder instead
|
|
3471
|
+
* @param orderId: The open order to modify
|
|
3472
|
+
* @param newBaseAmount: The new base amount for the order. One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
|
|
3473
|
+
* @param newLimitPice: The new limit price for the order. One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
|
|
3474
|
+
* @param newOraclePriceOffset: The new oracle price offset for the order. One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
|
|
3475
|
+
* @returns
|
|
3476
|
+
*/
|
|
3477
|
+
async modifyPerpOrder(orderId, newBaseAmount, newLimitPrice, newOraclePriceOffset) {
|
|
3478
|
+
return this.modifyOrder({
|
|
3479
|
+
orderId,
|
|
3480
|
+
newBaseAmount,
|
|
3481
|
+
newLimitPrice,
|
|
3482
|
+
newOraclePriceOffset,
|
|
3483
|
+
});
|
|
3484
|
+
}
|
|
3485
|
+
/**
|
|
3486
|
+
* Modifies an open order by closing it and replacing it with a new order.
|
|
3487
|
+
* @deprecated use modifyOrderByUserOrderId instead
|
|
3488
|
+
* @param userOrderId: The open order to modify
|
|
3489
|
+
* @param newBaseAmount: The new base amount for the order. One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
|
|
3490
|
+
* @param newLimitPice: The new limit price for the order. One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
|
|
3491
|
+
* @param newOraclePriceOffset: The new oracle price offset for the order. One of [newBaseAmount|newLimitPrice|newOraclePriceOffset] must be provided.
|
|
3492
|
+
* @returns
|
|
3493
|
+
*/
|
|
3494
|
+
async modifyPerpOrderByUserOrderId(userOrderId, newBaseAmount, newLimitPrice, newOraclePriceOffset) {
|
|
3495
|
+
return this.modifyOrderByUserOrderId({
|
|
3496
|
+
userOrderId,
|
|
3497
|
+
newBaseAmount,
|
|
3498
|
+
newLimitPrice,
|
|
3499
|
+
newOraclePriceOffset,
|
|
3500
|
+
});
|
|
3501
|
+
}
|
|
3502
|
+
/**
|
|
3503
|
+
* Modifies an open order (spot or perp) by closing it and replacing it with a new order.
|
|
3504
|
+
* @param orderParams.orderId: The open order to modify
|
|
3505
|
+
* @param orderParams.newDirection: The new direction for the order
|
|
3506
|
+
* @param orderParams.newBaseAmount: The new base amount for the order
|
|
3507
|
+
* @param orderParams.newLimitPice: The new limit price for the order
|
|
3508
|
+
* @param orderParams.newOraclePriceOffset: The new oracle price offset for the order
|
|
3509
|
+
* @param orderParams.newTriggerPrice: Optional - Thew new trigger price for the order.
|
|
3510
|
+
* @param orderParams.auctionDuration:
|
|
3511
|
+
* @param orderParams.auctionStartPrice:
|
|
3512
|
+
* @param orderParams.auctionEndPrice:
|
|
3513
|
+
* @param orderParams.reduceOnly:
|
|
3514
|
+
* @param orderParams.postOnly:
|
|
3515
|
+
* @param orderParams.immediateOrCancel:
|
|
3516
|
+
* @param orderParams.policy:
|
|
3517
|
+
* @param orderParams.maxTs:
|
|
3518
|
+
* @returns
|
|
3519
|
+
*/
|
|
3520
|
+
async modifyOrder(orderParams, txParams, subAccountId) {
|
|
3521
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getModifyOrderIx(orderParams, subAccountId), txParams), [], this.opts);
|
|
3522
|
+
return txSig;
|
|
3523
|
+
}
|
|
3524
|
+
async getModifyOrderIx({ orderId, newDirection, newBaseAmount, newLimitPrice, newOraclePriceOffset, newTriggerPrice, newTriggerCondition, auctionDuration, auctionStartPrice, auctionEndPrice, reduceOnly, postOnly, immediateOrCancel, maxTs, policy, }, subAccountId) {
|
|
3525
|
+
const user = await this.getUserAccountPublicKey(subAccountId);
|
|
3526
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
3527
|
+
userAccounts: [this.getUserAccount(subAccountId)],
|
|
3528
|
+
useMarketLastSlotCache: true,
|
|
3529
|
+
});
|
|
3530
|
+
const orderParams = {
|
|
3531
|
+
baseAssetAmount: newBaseAmount || null,
|
|
3532
|
+
direction: newDirection || null,
|
|
3533
|
+
price: newLimitPrice || null,
|
|
3534
|
+
oraclePriceOffset: newOraclePriceOffset || null,
|
|
3535
|
+
triggerPrice: newTriggerPrice || null,
|
|
3536
|
+
triggerCondition: newTriggerCondition || null,
|
|
3537
|
+
auctionDuration: auctionDuration || null,
|
|
3538
|
+
auctionStartPrice: auctionStartPrice || null,
|
|
3539
|
+
auctionEndPrice: auctionEndPrice || null,
|
|
3540
|
+
reduceOnly: reduceOnly != undefined ? reduceOnly : null,
|
|
3541
|
+
postOnly: postOnly != undefined ? postOnly : null,
|
|
3542
|
+
immediateOrCancel: immediateOrCancel != undefined ? immediateOrCancel : null,
|
|
3543
|
+
policy: policy || null,
|
|
3544
|
+
maxTs: maxTs || null,
|
|
3545
|
+
};
|
|
3546
|
+
return await this.program.instruction.modifyOrder(orderId, orderParams, {
|
|
3547
|
+
accounts: {
|
|
3548
|
+
state: await this.getStatePublicKey(),
|
|
3549
|
+
user,
|
|
3550
|
+
userStats: this.getUserStatsAccountPublicKey(),
|
|
3551
|
+
authority: this.wallet.publicKey,
|
|
3552
|
+
},
|
|
3553
|
+
remainingAccounts,
|
|
3554
|
+
});
|
|
3555
|
+
}
|
|
3556
|
+
/**
|
|
3557
|
+
* Modifies an open order by closing it and replacing it with a new order.
|
|
3558
|
+
* @param orderParams.userOrderId: The open order to modify
|
|
3559
|
+
* @param orderParams.newDirection: The new direction for the order
|
|
3560
|
+
* @param orderParams.newBaseAmount: The new base amount for the order
|
|
3561
|
+
* @param orderParams.newLimitPice: The new limit price for the order
|
|
3562
|
+
* @param orderParams.newOraclePriceOffset: The new oracle price offset for the order
|
|
3563
|
+
* @param orderParams.newTriggerPrice: Optional - Thew new trigger price for the order.
|
|
3564
|
+
* @param orderParams.auctionDuration: Only required if order type changed to market from something else
|
|
3565
|
+
* @param orderParams.auctionStartPrice: Only required if order type changed to market from something else
|
|
3566
|
+
* @param orderParams.auctionEndPrice: Only required if order type changed to market from something else
|
|
3567
|
+
* @param orderParams.reduceOnly:
|
|
3568
|
+
* @param orderParams.postOnly:
|
|
3569
|
+
* @param orderParams.immediateOrCancel:
|
|
3570
|
+
* @param orderParams.policy:
|
|
3571
|
+
* @param orderParams.maxTs:
|
|
3572
|
+
* @returns
|
|
3573
|
+
*/
|
|
3574
|
+
async modifyOrderByUserOrderId(orderParams, txParams, subAccountId) {
|
|
3575
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getModifyOrderByUserIdIx(orderParams, subAccountId), txParams), [], this.opts);
|
|
3576
|
+
return txSig;
|
|
3577
|
+
}
|
|
3578
|
+
async getModifyOrderByUserIdIx({ userOrderId, newDirection, newBaseAmount, newLimitPrice, newOraclePriceOffset, newTriggerPrice, newTriggerCondition, auctionDuration, auctionStartPrice, auctionEndPrice, reduceOnly, postOnly, immediateOrCancel, maxTs, policy, }, subAccountId) {
|
|
3579
|
+
const user = await this.getUserAccountPublicKey(subAccountId);
|
|
3580
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
3581
|
+
userAccounts: [this.getUserAccount(subAccountId)],
|
|
3582
|
+
useMarketLastSlotCache: true,
|
|
3583
|
+
});
|
|
3584
|
+
const orderParams = {
|
|
3585
|
+
baseAssetAmount: newBaseAmount || null,
|
|
3586
|
+
direction: newDirection || null,
|
|
3587
|
+
price: newLimitPrice || null,
|
|
3588
|
+
oraclePriceOffset: newOraclePriceOffset || null,
|
|
3589
|
+
triggerPrice: newTriggerPrice || null,
|
|
3590
|
+
triggerCondition: newTriggerCondition || null,
|
|
3591
|
+
auctionDuration: auctionDuration || null,
|
|
3592
|
+
auctionStartPrice: auctionStartPrice || null,
|
|
3593
|
+
auctionEndPrice: auctionEndPrice || null,
|
|
3594
|
+
reduceOnly: reduceOnly || false,
|
|
3595
|
+
postOnly: postOnly || null,
|
|
3596
|
+
immediateOrCancel: immediateOrCancel || false,
|
|
3597
|
+
policy: policy || null,
|
|
3598
|
+
maxTs: maxTs || null,
|
|
3599
|
+
};
|
|
3600
|
+
return await this.program.instruction.modifyOrderByUserId(userOrderId, orderParams, {
|
|
3601
|
+
accounts: {
|
|
3602
|
+
state: await this.getStatePublicKey(),
|
|
3603
|
+
user,
|
|
3604
|
+
userStats: this.getUserStatsAccountPublicKey(),
|
|
3605
|
+
authority: this.wallet.publicKey,
|
|
3606
|
+
},
|
|
3607
|
+
remainingAccounts,
|
|
3608
|
+
});
|
|
3609
|
+
}
|
|
3610
|
+
async settlePNLs(users, marketIndexes, opts, txParams) {
|
|
3611
|
+
const filterInvalidMarkets = opts === null || opts === void 0 ? void 0 : opts.filterInvalidMarkets;
|
|
3612
|
+
// # Filter market indexes by markets with valid oracle
|
|
3613
|
+
const marketIndexToSettle = filterInvalidMarkets
|
|
3614
|
+
? []
|
|
3615
|
+
: marketIndexes;
|
|
3616
|
+
if (filterInvalidMarkets) {
|
|
3617
|
+
for (const marketIndex of marketIndexes) {
|
|
3618
|
+
const perpMarketAccount = this.getPerpMarketAccount(marketIndex);
|
|
3619
|
+
const oraclePriceData = this.getOracleDataForPerpMarket(marketIndex);
|
|
3620
|
+
const stateAccountAndSlot = this.accountSubscriber.getStateAccountAndSlot();
|
|
3621
|
+
const oracleGuardRails = stateAccountAndSlot.data.oracleGuardRails;
|
|
3622
|
+
const isValid = (0, oracles_1.isOracleValid)(perpMarketAccount, oraclePriceData, oracleGuardRails, stateAccountAndSlot.slot);
|
|
3623
|
+
if (isValid) {
|
|
3624
|
+
marketIndexToSettle.push(marketIndex);
|
|
3625
|
+
}
|
|
3626
|
+
}
|
|
3627
|
+
}
|
|
3628
|
+
// # Settle filtered market indexes
|
|
3629
|
+
const ixs = await this.getSettlePNLsIxs(users, marketIndexToSettle);
|
|
3630
|
+
const tx = await this.buildTransaction(ixs, txParams !== null && txParams !== void 0 ? txParams : {
|
|
3631
|
+
computeUnits: 1400000,
|
|
3632
|
+
});
|
|
3633
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
3634
|
+
return txSig;
|
|
3635
|
+
}
|
|
3636
|
+
async getSettlePNLsIxs(users, marketIndexes) {
|
|
3637
|
+
const ixs = [];
|
|
3638
|
+
for (const { settleeUserAccountPublicKey, settleeUserAccount } of users) {
|
|
3639
|
+
for (const marketIndex of marketIndexes) {
|
|
3640
|
+
ixs.push(await this.settlePNLIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex));
|
|
3641
|
+
}
|
|
3642
|
+
}
|
|
3643
|
+
return ixs;
|
|
3644
|
+
}
|
|
3645
|
+
async settlePNL(settleeUserAccountPublicKey, settleeUserAccount, marketIndex, txParams) {
|
|
3646
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.settlePNLIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex), txParams), [], this.opts);
|
|
3647
|
+
return txSig;
|
|
3648
|
+
}
|
|
3649
|
+
async settlePNLIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex) {
|
|
3650
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
3651
|
+
userAccounts: [settleeUserAccount],
|
|
3652
|
+
writablePerpMarketIndexes: [marketIndex],
|
|
3653
|
+
writableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
|
|
3654
|
+
});
|
|
3655
|
+
return await this.program.instruction.settlePnl(marketIndex, {
|
|
3656
|
+
accounts: {
|
|
3657
|
+
state: await this.getStatePublicKey(),
|
|
3658
|
+
authority: this.wallet.publicKey,
|
|
3659
|
+
user: settleeUserAccountPublicKey,
|
|
3660
|
+
spotMarketVault: this.getQuoteSpotMarketAccount().vault,
|
|
3661
|
+
},
|
|
3662
|
+
remainingAccounts: remainingAccounts,
|
|
3663
|
+
});
|
|
3664
|
+
}
|
|
3665
|
+
async settleMultiplePNLs(settleeUserAccountPublicKey, settleeUserAccount, marketIndexes, mode, txParams) {
|
|
3666
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.settleMultiplePNLsIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndexes, mode), txParams), [], this.opts);
|
|
3667
|
+
return txSig;
|
|
3668
|
+
}
|
|
3669
|
+
async settleMultiplePNLsMultipleTxs(settleeUserAccountPublicKey, settleeUserAccount, marketIndexes, mode, txParams) {
|
|
3670
|
+
// need multiple TXs because settling more than 4 markets won't fit in a single TX
|
|
3671
|
+
const txsToSign = [];
|
|
3672
|
+
const marketIndexesInFourGroups = [];
|
|
3673
|
+
for (let i = 0; i < marketIndexes.length; i += 4) {
|
|
3674
|
+
marketIndexesInFourGroups.push(marketIndexes.slice(i, i + 4));
|
|
3675
|
+
}
|
|
3676
|
+
for (const marketIndexes of marketIndexesInFourGroups) {
|
|
3677
|
+
const ix = await this.settleMultiplePNLsIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndexes, mode);
|
|
3678
|
+
const computeUnits = Math.min(300000 * marketIndexes.length, 1400000);
|
|
3679
|
+
const tx = await this.buildTransaction(ix, {
|
|
3680
|
+
...txParams,
|
|
3681
|
+
computeUnits,
|
|
3682
|
+
});
|
|
3683
|
+
txsToSign.push(tx);
|
|
3684
|
+
}
|
|
3685
|
+
const txsMap = {};
|
|
3686
|
+
let i = 1;
|
|
3687
|
+
for (const tx of txsToSign) {
|
|
3688
|
+
txsMap[`tx-${i}`] = tx;
|
|
3689
|
+
i++;
|
|
3690
|
+
}
|
|
3691
|
+
const signedTxs = (await this.txHandler.getSignedTransactionMap(txsMap, this.provider.wallet)).signedTxMap;
|
|
3692
|
+
const txSigs = [];
|
|
3693
|
+
for (const key in signedTxs) {
|
|
3694
|
+
const tx = signedTxs[key];
|
|
3695
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts, true);
|
|
3696
|
+
txSigs.push(txSig);
|
|
3697
|
+
}
|
|
3698
|
+
return txSigs;
|
|
3699
|
+
}
|
|
3700
|
+
async settleMultiplePNLsIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndexes, mode) {
|
|
3701
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
3702
|
+
userAccounts: [settleeUserAccount],
|
|
3703
|
+
writablePerpMarketIndexes: marketIndexes,
|
|
3704
|
+
writableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
|
|
3705
|
+
});
|
|
3706
|
+
return await this.program.instruction.settleMultiplePnls(marketIndexes, mode, {
|
|
3707
|
+
accounts: {
|
|
3708
|
+
state: await this.getStatePublicKey(),
|
|
3709
|
+
authority: this.wallet.publicKey,
|
|
3710
|
+
user: settleeUserAccountPublicKey,
|
|
3711
|
+
spotMarketVault: this.getQuoteSpotMarketAccount().vault,
|
|
3712
|
+
},
|
|
3713
|
+
remainingAccounts: remainingAccounts,
|
|
3714
|
+
});
|
|
3715
|
+
}
|
|
3716
|
+
async getSetUserStatusToBeingLiquidatedIx(userAccountPublicKey, userAccount) {
|
|
3717
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
3718
|
+
userAccounts: [userAccount],
|
|
3719
|
+
});
|
|
3720
|
+
return await this.program.instruction.setUserStatusToBeingLiquidated({
|
|
3721
|
+
accounts: {
|
|
3722
|
+
state: await this.getStatePublicKey(),
|
|
3723
|
+
user: userAccountPublicKey,
|
|
3724
|
+
authority: this.wallet.publicKey,
|
|
3725
|
+
},
|
|
3726
|
+
remainingAccounts,
|
|
3727
|
+
});
|
|
3728
|
+
}
|
|
3729
|
+
async setUserStatusToBeingLiquidated(userAccountPublicKey, userAccount) {
|
|
3730
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getSetUserStatusToBeingLiquidatedIx(userAccountPublicKey, userAccount)), [], this.opts);
|
|
3731
|
+
return txSig;
|
|
3732
|
+
}
|
|
3733
|
+
async liquidatePerp(userAccountPublicKey, userAccount, marketIndex, maxBaseAssetAmount, limitPrice, txParams, liquidatorSubAccountId) {
|
|
3734
|
+
const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getLiquidatePerpIx(userAccountPublicKey, userAccount, marketIndex, maxBaseAssetAmount, limitPrice, liquidatorSubAccountId), txParams), [], this.opts);
|
|
3735
|
+
this.perpMarketLastSlotCache.set(marketIndex, slot);
|
|
3736
|
+
return txSig;
|
|
3737
|
+
}
|
|
3738
|
+
async getLiquidatePerpIx(userAccountPublicKey, userAccount, marketIndex, maxBaseAssetAmount, limitPrice, liquidatorSubAccountId) {
|
|
3739
|
+
const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
|
|
3740
|
+
const liquidator = await this.getUserAccountPublicKey(liquidatorSubAccountId);
|
|
3741
|
+
const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
|
|
3742
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
3743
|
+
userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
|
|
3744
|
+
useMarketLastSlotCache: true,
|
|
3745
|
+
writablePerpMarketIndexes: [marketIndex],
|
|
3746
|
+
});
|
|
3747
|
+
return await this.program.instruction.liquidatePerp(marketIndex, maxBaseAssetAmount, limitPrice !== null && limitPrice !== void 0 ? limitPrice : null, {
|
|
3748
|
+
accounts: {
|
|
3749
|
+
state: await this.getStatePublicKey(),
|
|
3750
|
+
authority: this.wallet.publicKey,
|
|
3751
|
+
user: userAccountPublicKey,
|
|
3752
|
+
userStats: userStatsPublicKey,
|
|
3753
|
+
liquidator,
|
|
3754
|
+
liquidatorStats: liquidatorStatsPublicKey,
|
|
3755
|
+
},
|
|
3756
|
+
remainingAccounts: remainingAccounts,
|
|
3757
|
+
});
|
|
3758
|
+
}
|
|
3759
|
+
async liquidatePerpWithFill(userAccountPublicKey, userAccount, marketIndex, makerInfos, txParams, liquidatorSubAccountId) {
|
|
3760
|
+
const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getLiquidatePerpWithFillIx(userAccountPublicKey, userAccount, marketIndex, makerInfos, liquidatorSubAccountId), txParams), [], this.opts);
|
|
3761
|
+
this.perpMarketLastSlotCache.set(marketIndex, slot);
|
|
3762
|
+
return txSig;
|
|
3763
|
+
}
|
|
3764
|
+
async getLiquidatePerpWithFillIx(userAccountPublicKey, userAccount, marketIndex, makerInfos, liquidatorSubAccountId) {
|
|
3765
|
+
const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
|
|
3766
|
+
const liquidator = await this.getUserAccountPublicKey(liquidatorSubAccountId);
|
|
3767
|
+
const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
|
|
3768
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
3769
|
+
userAccounts: [
|
|
3770
|
+
userAccount,
|
|
3771
|
+
...makerInfos.map((makerInfo) => makerInfo.makerUserAccount),
|
|
3772
|
+
],
|
|
3773
|
+
useMarketLastSlotCache: true,
|
|
3774
|
+
writablePerpMarketIndexes: [marketIndex],
|
|
3775
|
+
});
|
|
3776
|
+
for (const makerInfo of makerInfos) {
|
|
3777
|
+
remainingAccounts.push({
|
|
3778
|
+
pubkey: makerInfo.maker,
|
|
3779
|
+
isSigner: false,
|
|
3780
|
+
isWritable: true,
|
|
3781
|
+
});
|
|
3782
|
+
remainingAccounts.push({
|
|
3783
|
+
pubkey: makerInfo.makerStats,
|
|
3784
|
+
isSigner: false,
|
|
3785
|
+
isWritable: true,
|
|
3786
|
+
});
|
|
3787
|
+
}
|
|
3788
|
+
return await this.program.instruction.liquidatePerpWithFill(marketIndex, {
|
|
3789
|
+
accounts: {
|
|
3790
|
+
state: await this.getStatePublicKey(),
|
|
3791
|
+
authority: this.wallet.publicKey,
|
|
3792
|
+
user: userAccountPublicKey,
|
|
3793
|
+
userStats: userStatsPublicKey,
|
|
3794
|
+
liquidator,
|
|
3795
|
+
liquidatorStats: liquidatorStatsPublicKey,
|
|
3796
|
+
},
|
|
3797
|
+
remainingAccounts: remainingAccounts,
|
|
3798
|
+
});
|
|
3799
|
+
}
|
|
3800
|
+
async liquidateSpot(userAccountPublicKey, userAccount, assetMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice, txParams, liquidatorSubAccountId) {
|
|
3801
|
+
const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getLiquidateSpotIx(userAccountPublicKey, userAccount, assetMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice, liquidatorSubAccountId), txParams), [], this.opts);
|
|
3802
|
+
this.spotMarketLastSlotCache.set(assetMarketIndex, slot);
|
|
3803
|
+
this.spotMarketLastSlotCache.set(liabilityMarketIndex, slot);
|
|
3804
|
+
return txSig;
|
|
3805
|
+
}
|
|
3806
|
+
async getLiquidateSpotIx(userAccountPublicKey, userAccount, assetMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice, liquidatorSubAccountId) {
|
|
3807
|
+
const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
|
|
3808
|
+
const liquidator = await this.getUserAccountPublicKey(liquidatorSubAccountId);
|
|
3809
|
+
const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
|
|
3810
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
3811
|
+
userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
|
|
3812
|
+
useMarketLastSlotCache: true,
|
|
3813
|
+
writableSpotMarketIndexes: [liabilityMarketIndex, assetMarketIndex],
|
|
3814
|
+
});
|
|
3815
|
+
return await this.program.instruction.liquidateSpot(assetMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice || null, {
|
|
3816
|
+
accounts: {
|
|
3817
|
+
state: await this.getStatePublicKey(),
|
|
3818
|
+
authority: this.wallet.publicKey,
|
|
3819
|
+
user: userAccountPublicKey,
|
|
3820
|
+
userStats: userStatsPublicKey,
|
|
3821
|
+
liquidator,
|
|
3822
|
+
liquidatorStats: liquidatorStatsPublicKey,
|
|
3823
|
+
},
|
|
3824
|
+
remainingAccounts: remainingAccounts,
|
|
3825
|
+
});
|
|
3826
|
+
}
|
|
3827
|
+
async liquidateBorrowForPerpPnl(userAccountPublicKey, userAccount, perpMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice, txParams, liquidatorSubAccountId) {
|
|
3828
|
+
const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getLiquidateBorrowForPerpPnlIx(userAccountPublicKey, userAccount, perpMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice, liquidatorSubAccountId), txParams), [], this.opts);
|
|
3829
|
+
this.perpMarketLastSlotCache.set(perpMarketIndex, slot);
|
|
3830
|
+
this.spotMarketLastSlotCache.set(liabilityMarketIndex, slot);
|
|
3831
|
+
return txSig;
|
|
3832
|
+
}
|
|
3833
|
+
async getLiquidateBorrowForPerpPnlIx(userAccountPublicKey, userAccount, perpMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice, liquidatorSubAccountId) {
|
|
3834
|
+
const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
|
|
3835
|
+
const liquidator = await this.getUserAccountPublicKey(liquidatorSubAccountId);
|
|
3836
|
+
const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
|
|
3837
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
3838
|
+
userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
|
|
3839
|
+
writablePerpMarketIndexes: [perpMarketIndex],
|
|
3840
|
+
writableSpotMarketIndexes: [liabilityMarketIndex],
|
|
3841
|
+
});
|
|
3842
|
+
return await this.program.instruction.liquidateBorrowForPerpPnl(perpMarketIndex, liabilityMarketIndex, maxLiabilityTransfer, limitPrice || null, {
|
|
3843
|
+
accounts: {
|
|
3844
|
+
state: await this.getStatePublicKey(),
|
|
3845
|
+
authority: this.wallet.publicKey,
|
|
3846
|
+
user: userAccountPublicKey,
|
|
3847
|
+
userStats: userStatsPublicKey,
|
|
3848
|
+
liquidator,
|
|
3849
|
+
liquidatorStats: liquidatorStatsPublicKey,
|
|
3850
|
+
},
|
|
3851
|
+
remainingAccounts: remainingAccounts,
|
|
3852
|
+
});
|
|
3853
|
+
}
|
|
3854
|
+
async liquidatePerpPnlForDeposit(userAccountPublicKey, userAccount, perpMarketIndex, assetMarketIndex, maxPnlTransfer, limitPrice, txParams, liquidatorSubAccountId) {
|
|
3855
|
+
const { txSig, slot } = await this.sendTransaction(await this.buildTransaction(await this.getLiquidatePerpPnlForDepositIx(userAccountPublicKey, userAccount, perpMarketIndex, assetMarketIndex, maxPnlTransfer, limitPrice, liquidatorSubAccountId), txParams), [], this.opts);
|
|
3856
|
+
this.perpMarketLastSlotCache.set(perpMarketIndex, slot);
|
|
3857
|
+
this.spotMarketLastSlotCache.set(assetMarketIndex, slot);
|
|
3858
|
+
return txSig;
|
|
3859
|
+
}
|
|
3860
|
+
async getLiquidatePerpPnlForDepositIx(userAccountPublicKey, userAccount, perpMarketIndex, assetMarketIndex, maxPnlTransfer, limitPrice, liquidatorSubAccountId) {
|
|
3861
|
+
const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
|
|
3862
|
+
const liquidator = await this.getUserAccountPublicKey(liquidatorSubAccountId);
|
|
3863
|
+
const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
|
|
3864
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
3865
|
+
userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
|
|
3866
|
+
writablePerpMarketIndexes: [perpMarketIndex],
|
|
3867
|
+
writableSpotMarketIndexes: [assetMarketIndex],
|
|
3868
|
+
});
|
|
3869
|
+
return await this.program.instruction.liquidatePerpPnlForDeposit(perpMarketIndex, assetMarketIndex, maxPnlTransfer, limitPrice || null, {
|
|
3870
|
+
accounts: {
|
|
3871
|
+
state: await this.getStatePublicKey(),
|
|
3872
|
+
authority: this.wallet.publicKey,
|
|
3873
|
+
user: userAccountPublicKey,
|
|
3874
|
+
userStats: userStatsPublicKey,
|
|
3875
|
+
liquidator,
|
|
3876
|
+
liquidatorStats: liquidatorStatsPublicKey,
|
|
3877
|
+
},
|
|
3878
|
+
remainingAccounts: remainingAccounts,
|
|
3879
|
+
});
|
|
3880
|
+
}
|
|
3881
|
+
async resolvePerpBankruptcy(userAccountPublicKey, userAccount, marketIndex, txParams, liquidatorSubAccountId) {
|
|
3882
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getResolvePerpBankruptcyIx(userAccountPublicKey, userAccount, marketIndex, liquidatorSubAccountId), txParams), [], this.opts);
|
|
3883
|
+
return txSig;
|
|
3884
|
+
}
|
|
3885
|
+
async getResolvePerpBankruptcyIx(userAccountPublicKey, userAccount, marketIndex, liquidatorSubAccountId) {
|
|
3886
|
+
const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
|
|
3887
|
+
const liquidator = await this.getUserAccountPublicKey(liquidatorSubAccountId);
|
|
3888
|
+
const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
|
|
3889
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
3890
|
+
userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
|
|
3891
|
+
writablePerpMarketIndexes: [marketIndex],
|
|
3892
|
+
writableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
|
|
3893
|
+
});
|
|
3894
|
+
const spotMarket = this.getQuoteSpotMarketAccount();
|
|
3895
|
+
return await this.program.instruction.resolvePerpBankruptcy(numericConstants_1.QUOTE_SPOT_MARKET_INDEX, marketIndex, {
|
|
3896
|
+
accounts: {
|
|
3897
|
+
state: await this.getStatePublicKey(),
|
|
3898
|
+
authority: this.wallet.publicKey,
|
|
3899
|
+
user: userAccountPublicKey,
|
|
3900
|
+
userStats: userStatsPublicKey,
|
|
3901
|
+
liquidator,
|
|
3902
|
+
liquidatorStats: liquidatorStatsPublicKey,
|
|
3903
|
+
spotMarketVault: spotMarket.vault,
|
|
3904
|
+
insuranceFundVault: spotMarket.insuranceFund.vault,
|
|
3905
|
+
driftSigner: this.getSignerPublicKey(),
|
|
3906
|
+
tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
|
|
3907
|
+
},
|
|
3908
|
+
remainingAccounts: remainingAccounts,
|
|
3909
|
+
});
|
|
3910
|
+
}
|
|
3911
|
+
async resolveSpotBankruptcy(userAccountPublicKey, userAccount, marketIndex, txParams, liquidatorSubAccountId) {
|
|
3912
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getResolveSpotBankruptcyIx(userAccountPublicKey, userAccount, marketIndex, liquidatorSubAccountId), txParams), [], this.opts);
|
|
3913
|
+
return txSig;
|
|
3914
|
+
}
|
|
3915
|
+
async getResolveSpotBankruptcyIx(userAccountPublicKey, userAccount, marketIndex, liquidatorSubAccountId) {
|
|
3916
|
+
const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
|
|
3917
|
+
const liquidator = await this.getUserAccountPublicKey(liquidatorSubAccountId);
|
|
3918
|
+
const liquidatorStatsPublicKey = this.getUserStatsAccountPublicKey();
|
|
3919
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
3920
|
+
userAccounts: [this.getUserAccount(liquidatorSubAccountId), userAccount],
|
|
3921
|
+
writableSpotMarketIndexes: [marketIndex],
|
|
3922
|
+
});
|
|
3923
|
+
const spotMarket = this.getSpotMarketAccount(marketIndex);
|
|
3924
|
+
const tokenProgramId = this.getTokenProgramForSpotMarket(spotMarket);
|
|
3925
|
+
this.addTokenMintToRemainingAccounts(spotMarket, remainingAccounts);
|
|
3926
|
+
return await this.program.instruction.resolveSpotBankruptcy(marketIndex, {
|
|
3927
|
+
accounts: {
|
|
3928
|
+
state: await this.getStatePublicKey(),
|
|
3929
|
+
authority: this.wallet.publicKey,
|
|
3930
|
+
user: userAccountPublicKey,
|
|
3931
|
+
userStats: userStatsPublicKey,
|
|
3932
|
+
liquidatorStats: liquidatorStatsPublicKey,
|
|
3933
|
+
liquidator,
|
|
3934
|
+
spotMarketVault: spotMarket.vault,
|
|
3935
|
+
insuranceFundVault: spotMarket.insuranceFund.vault,
|
|
3936
|
+
driftSigner: this.getSignerPublicKey(),
|
|
3937
|
+
tokenProgram: tokenProgramId,
|
|
3938
|
+
},
|
|
3939
|
+
remainingAccounts: remainingAccounts,
|
|
3940
|
+
});
|
|
3941
|
+
}
|
|
3942
|
+
async updateFundingRate(perpMarketIndex, oracle, txParams) {
|
|
3943
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getUpdateFundingRateIx(perpMarketIndex, oracle), txParams), [], this.opts);
|
|
3944
|
+
return txSig;
|
|
3945
|
+
}
|
|
3946
|
+
async getUpdateFundingRateIx(perpMarketIndex, oracle) {
|
|
3947
|
+
const perpMarketPublicKey = await (0, pda_1.getPerpMarketPublicKey)(this.program.programId, perpMarketIndex);
|
|
3948
|
+
return await this.program.instruction.updateFundingRate(perpMarketIndex, {
|
|
3949
|
+
accounts: {
|
|
3950
|
+
state: await this.getStatePublicKey(),
|
|
3951
|
+
perpMarket: perpMarketPublicKey,
|
|
3952
|
+
oracle: oracle,
|
|
3953
|
+
},
|
|
3954
|
+
});
|
|
3955
|
+
}
|
|
3956
|
+
async updatePrelaunchOracle(perpMarketIndex, txParams) {
|
|
3957
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getUpdatePrelaunchOracleIx(perpMarketIndex), txParams), [], this.opts);
|
|
3958
|
+
return txSig;
|
|
3959
|
+
}
|
|
3960
|
+
async getUpdatePrelaunchOracleIx(perpMarketIndex) {
|
|
3961
|
+
const perpMarket = this.getPerpMarketAccount(perpMarketIndex);
|
|
3962
|
+
if (!(0, types_1.isVariant)(perpMarket.amm.oracleSource, 'prelaunch')) {
|
|
3963
|
+
throw new Error(`Wrong oracle source ${perpMarket.amm.oracleSource}`);
|
|
3964
|
+
}
|
|
3965
|
+
return await this.program.instruction.updatePrelaunchOracle({
|
|
3966
|
+
accounts: {
|
|
3967
|
+
state: await this.getStatePublicKey(),
|
|
3968
|
+
perpMarket: perpMarket.pubkey,
|
|
3969
|
+
oracle: perpMarket.amm.oracle,
|
|
3970
|
+
},
|
|
3971
|
+
});
|
|
3972
|
+
}
|
|
3973
|
+
async updatePerpBidAskTwap(perpMarketIndex, makers, txParams) {
|
|
3974
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getUpdatePerpBidAskTwapIx(perpMarketIndex, makers), txParams), [], this.opts);
|
|
3975
|
+
return txSig;
|
|
3976
|
+
}
|
|
3977
|
+
async getUpdatePerpBidAskTwapIx(perpMarketIndex, makers) {
|
|
3978
|
+
const perpMarket = this.getPerpMarketAccount(perpMarketIndex);
|
|
3979
|
+
const remainingAccounts = [];
|
|
3980
|
+
for (const [maker, makerStats] of makers) {
|
|
3981
|
+
remainingAccounts.push({
|
|
3982
|
+
pubkey: maker,
|
|
3983
|
+
isWritable: false,
|
|
3984
|
+
isSigner: false,
|
|
3985
|
+
});
|
|
3986
|
+
remainingAccounts.push({
|
|
3987
|
+
pubkey: makerStats,
|
|
3988
|
+
isWritable: false,
|
|
3989
|
+
isSigner: false,
|
|
3990
|
+
});
|
|
3991
|
+
}
|
|
3992
|
+
return await this.program.instruction.updatePerpBidAskTwap({
|
|
3993
|
+
accounts: {
|
|
3994
|
+
state: await this.getStatePublicKey(),
|
|
3995
|
+
perpMarket: perpMarket.pubkey,
|
|
3996
|
+
oracle: perpMarket.amm.oracle,
|
|
3997
|
+
authority: this.wallet.publicKey,
|
|
3998
|
+
keeperStats: this.getUserStatsAccountPublicKey(),
|
|
3999
|
+
},
|
|
4000
|
+
remainingAccounts,
|
|
4001
|
+
});
|
|
4002
|
+
}
|
|
4003
|
+
async settleFundingPayment(userAccountPublicKey, txParams) {
|
|
4004
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getSettleFundingPaymentIx(userAccountPublicKey), txParams), [], this.opts);
|
|
4005
|
+
return txSig;
|
|
4006
|
+
}
|
|
4007
|
+
async getSettleFundingPaymentIx(userAccountPublicKey) {
|
|
4008
|
+
const userAccount = (await this.program.account.user.fetch(userAccountPublicKey));
|
|
4009
|
+
const writablePerpMarketIndexes = [];
|
|
4010
|
+
for (const position of userAccount.perpPositions) {
|
|
4011
|
+
if (!(0, position_1.positionIsAvailable)(position)) {
|
|
4012
|
+
writablePerpMarketIndexes.push(position.marketIndex);
|
|
4013
|
+
}
|
|
4014
|
+
}
|
|
4015
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
4016
|
+
userAccounts: [userAccount],
|
|
4017
|
+
writablePerpMarketIndexes,
|
|
4018
|
+
});
|
|
4019
|
+
return await this.program.instruction.settleFundingPayment({
|
|
4020
|
+
accounts: {
|
|
4021
|
+
state: await this.getStatePublicKey(),
|
|
4022
|
+
user: userAccountPublicKey,
|
|
4023
|
+
},
|
|
4024
|
+
remainingAccounts,
|
|
4025
|
+
});
|
|
4026
|
+
}
|
|
4027
|
+
triggerEvent(eventName, data) {
|
|
4028
|
+
this.eventEmitter.emit(eventName, data);
|
|
4029
|
+
}
|
|
4030
|
+
getOracleDataForPerpMarket(marketIndex) {
|
|
4031
|
+
return this.accountSubscriber.getOraclePriceDataAndSlotForPerpMarket(marketIndex).data;
|
|
4032
|
+
}
|
|
4033
|
+
getOracleDataForSpotMarket(marketIndex) {
|
|
4034
|
+
return this.accountSubscriber.getOraclePriceDataAndSlotForSpotMarket(marketIndex).data;
|
|
4035
|
+
}
|
|
4036
|
+
async initializeInsuranceFundStake(marketIndex, txParams) {
|
|
4037
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getInitializeInsuranceFundStakeIx(marketIndex), txParams), [], this.opts);
|
|
4038
|
+
return txSig;
|
|
4039
|
+
}
|
|
4040
|
+
async getInitializeInsuranceFundStakeIx(marketIndex) {
|
|
4041
|
+
const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
|
|
4042
|
+
return await this.program.instruction.initializeInsuranceFundStake(marketIndex, {
|
|
4043
|
+
accounts: {
|
|
4044
|
+
insuranceFundStake: ifStakeAccountPublicKey,
|
|
4045
|
+
spotMarket: this.getSpotMarketAccount(marketIndex).pubkey,
|
|
4046
|
+
userStats: this.getUserStatsAccountPublicKey(),
|
|
4047
|
+
authority: this.wallet.publicKey,
|
|
4048
|
+
payer: this.wallet.publicKey,
|
|
4049
|
+
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
|
|
4050
|
+
systemProgram: anchor.web3.SystemProgram.programId,
|
|
4051
|
+
state: await this.getStatePublicKey(),
|
|
4052
|
+
},
|
|
4053
|
+
});
|
|
4054
|
+
}
|
|
4055
|
+
async getAddInsuranceFundStakeIx(marketIndex, amount, collateralAccountPublicKey) {
|
|
4056
|
+
const spotMarket = this.getSpotMarketAccount(marketIndex);
|
|
4057
|
+
const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
|
|
4058
|
+
const remainingAccounts = [];
|
|
4059
|
+
this.addTokenMintToRemainingAccounts(spotMarket, remainingAccounts);
|
|
4060
|
+
const tokenProgram = this.getTokenProgramForSpotMarket(spotMarket);
|
|
4061
|
+
const ix = this.program.instruction.addInsuranceFundStake(marketIndex, amount, {
|
|
4062
|
+
accounts: {
|
|
4063
|
+
state: await this.getStatePublicKey(),
|
|
4064
|
+
spotMarket: spotMarket.pubkey,
|
|
4065
|
+
insuranceFundStake: ifStakeAccountPublicKey,
|
|
4066
|
+
userStats: this.getUserStatsAccountPublicKey(),
|
|
4067
|
+
authority: this.wallet.publicKey,
|
|
4068
|
+
spotMarketVault: spotMarket.vault,
|
|
4069
|
+
insuranceFundVault: spotMarket.insuranceFund.vault,
|
|
4070
|
+
driftSigner: this.getSignerPublicKey(),
|
|
4071
|
+
userTokenAccount: collateralAccountPublicKey,
|
|
4072
|
+
tokenProgram,
|
|
4073
|
+
},
|
|
4074
|
+
remainingAccounts,
|
|
4075
|
+
});
|
|
4076
|
+
return ix;
|
|
4077
|
+
}
|
|
4078
|
+
/**
|
|
4079
|
+
* Add to an insurance fund stake and optionally initialize the account
|
|
4080
|
+
*/
|
|
4081
|
+
async addInsuranceFundStake({ marketIndex, amount, collateralAccountPublicKey, initializeStakeAccount, fromSubaccount, txParams, }) {
|
|
4082
|
+
const addIfStakeIxs = [];
|
|
4083
|
+
const additionalSigners = [];
|
|
4084
|
+
const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
|
|
4085
|
+
const isSolMarket = spotMarketAccount.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
|
|
4086
|
+
const createWSOLTokenAccount = isSolMarket && collateralAccountPublicKey.equals(this.wallet.publicKey);
|
|
4087
|
+
const tokenProgramId = this.getTokenProgramForSpotMarket(spotMarketAccount);
|
|
4088
|
+
// create associated token account because it may not exist
|
|
4089
|
+
const associatedTokenAccountPublicKey = (0, spl_token_1.getAssociatedTokenAddressSync)(spotMarketAccount.mint, this.wallet.publicKey, true, tokenProgramId);
|
|
4090
|
+
addIfStakeIxs.push(await (0, spl_token_1.createAssociatedTokenAccountIdempotentInstruction)(this.wallet.publicKey, associatedTokenAccountPublicKey, this.wallet.publicKey, spotMarketAccount.mint, tokenProgramId));
|
|
4091
|
+
let tokenAccount;
|
|
4092
|
+
if (!(await this.checkIfAccountExists(this.getUserStatsAccountPublicKey()))) {
|
|
4093
|
+
addIfStakeIxs.push(await this.getInitializeUserStatsIx());
|
|
4094
|
+
}
|
|
4095
|
+
if (createWSOLTokenAccount) {
|
|
4096
|
+
const { ixs, pubkey } = await this.getWrappedSolAccountCreationIxs(amount, true);
|
|
4097
|
+
tokenAccount = pubkey;
|
|
4098
|
+
ixs.forEach((ix) => {
|
|
4099
|
+
addIfStakeIxs.push(ix);
|
|
4100
|
+
});
|
|
4101
|
+
}
|
|
4102
|
+
else {
|
|
4103
|
+
tokenAccount = collateralAccountPublicKey;
|
|
4104
|
+
}
|
|
4105
|
+
if (fromSubaccount) {
|
|
4106
|
+
const withdrawIx = await this.getWithdrawIx(amount, marketIndex, tokenAccount);
|
|
4107
|
+
addIfStakeIxs.push(withdrawIx);
|
|
4108
|
+
}
|
|
4109
|
+
if (initializeStakeAccount) {
|
|
4110
|
+
const initializeIx = await this.getInitializeInsuranceFundStakeIx(marketIndex);
|
|
4111
|
+
addIfStakeIxs.push(initializeIx);
|
|
4112
|
+
}
|
|
4113
|
+
const addFundsIx = await this.getAddInsuranceFundStakeIx(marketIndex, amount, tokenAccount);
|
|
4114
|
+
addIfStakeIxs.push(addFundsIx);
|
|
4115
|
+
if (createWSOLTokenAccount) {
|
|
4116
|
+
addIfStakeIxs.push((0, spl_token_1.createCloseAccountInstruction)(tokenAccount, this.wallet.publicKey, this.wallet.publicKey, []));
|
|
4117
|
+
}
|
|
4118
|
+
const tx = await this.buildTransaction(addIfStakeIxs, txParams);
|
|
4119
|
+
const { txSig } = await this.sendTransaction(tx, additionalSigners, this.opts);
|
|
4120
|
+
return txSig;
|
|
4121
|
+
}
|
|
4122
|
+
async requestRemoveInsuranceFundStake(marketIndex, amount, txParams) {
|
|
4123
|
+
const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
|
|
4124
|
+
const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
|
|
4125
|
+
const ix = await this.program.instruction.requestRemoveInsuranceFundStake(marketIndex, amount, {
|
|
4126
|
+
accounts: {
|
|
4127
|
+
state: await this.getStatePublicKey(),
|
|
4128
|
+
spotMarket: spotMarketAccount.pubkey,
|
|
4129
|
+
insuranceFundStake: ifStakeAccountPublicKey,
|
|
4130
|
+
userStats: this.getUserStatsAccountPublicKey(),
|
|
4131
|
+
authority: this.wallet.publicKey,
|
|
4132
|
+
insuranceFundVault: spotMarketAccount.insuranceFund.vault,
|
|
4133
|
+
},
|
|
4134
|
+
});
|
|
4135
|
+
const tx = await this.buildTransaction(ix, txParams);
|
|
4136
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
4137
|
+
return txSig;
|
|
4138
|
+
}
|
|
4139
|
+
async cancelRequestRemoveInsuranceFundStake(marketIndex, txParams) {
|
|
4140
|
+
const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
|
|
4141
|
+
const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
|
|
4142
|
+
const ix = await this.program.instruction.cancelRequestRemoveInsuranceFundStake(marketIndex, {
|
|
4143
|
+
accounts: {
|
|
4144
|
+
state: await this.getStatePublicKey(),
|
|
4145
|
+
spotMarket: spotMarketAccount.pubkey,
|
|
4146
|
+
insuranceFundStake: ifStakeAccountPublicKey,
|
|
4147
|
+
userStats: this.getUserStatsAccountPublicKey(),
|
|
4148
|
+
authority: this.wallet.publicKey,
|
|
4149
|
+
insuranceFundVault: spotMarketAccount.insuranceFund.vault,
|
|
4150
|
+
},
|
|
4151
|
+
});
|
|
4152
|
+
const tx = await this.buildTransaction(ix, txParams);
|
|
4153
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
4154
|
+
return txSig;
|
|
4155
|
+
}
|
|
4156
|
+
async removeInsuranceFundStake(marketIndex, collateralAccountPublicKey, txParams) {
|
|
4157
|
+
const removeIfStakeIxs = [];
|
|
4158
|
+
const spotMarketAccount = this.getSpotMarketAccount(marketIndex);
|
|
4159
|
+
const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, this.wallet.publicKey, marketIndex);
|
|
4160
|
+
const additionalSigners = [];
|
|
4161
|
+
const isSolMarket = spotMarketAccount.mint.equals(spotMarkets_1.WRAPPED_SOL_MINT);
|
|
4162
|
+
const createWSOLTokenAccount = isSolMarket && collateralAccountPublicKey.equals(this.wallet.publicKey);
|
|
4163
|
+
const tokenProgramId = this.getTokenProgramForSpotMarket(spotMarketAccount);
|
|
4164
|
+
let tokenAccount;
|
|
4165
|
+
if (createWSOLTokenAccount) {
|
|
4166
|
+
const { ixs, pubkey } = await this.getWrappedSolAccountCreationIxs(numericConstants_1.ZERO, true);
|
|
4167
|
+
tokenAccount = pubkey;
|
|
4168
|
+
ixs.forEach((ix) => {
|
|
4169
|
+
removeIfStakeIxs.push(ix);
|
|
4170
|
+
});
|
|
4171
|
+
}
|
|
4172
|
+
else {
|
|
4173
|
+
tokenAccount = collateralAccountPublicKey;
|
|
4174
|
+
const tokenAccountExists = await this.checkIfAccountExists(tokenAccount);
|
|
4175
|
+
if (!tokenAccountExists) {
|
|
4176
|
+
const createTokenAccountIx = await this.createAssociatedTokenAccountIdempotentInstruction(tokenAccount, this.wallet.publicKey, this.wallet.publicKey, spotMarketAccount.mint, tokenProgramId);
|
|
4177
|
+
removeIfStakeIxs.push(createTokenAccountIx);
|
|
4178
|
+
}
|
|
4179
|
+
}
|
|
4180
|
+
const remainingAccounts = [];
|
|
4181
|
+
this.addTokenMintToRemainingAccounts(spotMarketAccount, remainingAccounts);
|
|
4182
|
+
const tokenProgram = this.getTokenProgramForSpotMarket(spotMarketAccount);
|
|
4183
|
+
const removeStakeIx = await this.program.instruction.removeInsuranceFundStake(marketIndex, {
|
|
4184
|
+
accounts: {
|
|
4185
|
+
state: await this.getStatePublicKey(),
|
|
4186
|
+
spotMarket: spotMarketAccount.pubkey,
|
|
4187
|
+
insuranceFundStake: ifStakeAccountPublicKey,
|
|
4188
|
+
userStats: this.getUserStatsAccountPublicKey(),
|
|
4189
|
+
authority: this.wallet.publicKey,
|
|
4190
|
+
insuranceFundVault: spotMarketAccount.insuranceFund.vault,
|
|
4191
|
+
driftSigner: this.getSignerPublicKey(),
|
|
4192
|
+
userTokenAccount: tokenAccount,
|
|
4193
|
+
tokenProgram,
|
|
4194
|
+
},
|
|
4195
|
+
remainingAccounts,
|
|
4196
|
+
});
|
|
4197
|
+
removeIfStakeIxs.push(removeStakeIx);
|
|
4198
|
+
// Close the wrapped sol account at the end of the transaction
|
|
4199
|
+
if (createWSOLTokenAccount) {
|
|
4200
|
+
removeIfStakeIxs.push((0, spl_token_1.createCloseAccountInstruction)(tokenAccount, this.wallet.publicKey, this.wallet.publicKey, []));
|
|
4201
|
+
}
|
|
4202
|
+
const tx = await this.buildTransaction(removeIfStakeIxs, txParams);
|
|
4203
|
+
const { txSig } = await this.sendTransaction(tx, additionalSigners, this.opts);
|
|
4204
|
+
return txSig;
|
|
4205
|
+
}
|
|
4206
|
+
async updateUserQuoteAssetInsuranceStake(authority, txParams) {
|
|
4207
|
+
const tx = await this.buildTransaction(await this.getUpdateUserQuoteAssetInsuranceStakeIx(authority), txParams);
|
|
4208
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
4209
|
+
return txSig;
|
|
4210
|
+
}
|
|
4211
|
+
async getUpdateUserQuoteAssetInsuranceStakeIx(authority) {
|
|
4212
|
+
const marketIndex = numericConstants_1.QUOTE_SPOT_MARKET_INDEX;
|
|
4213
|
+
const spotMarket = this.getSpotMarketAccount(marketIndex);
|
|
4214
|
+
const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, authority, marketIndex);
|
|
4215
|
+
const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, authority);
|
|
4216
|
+
const ix = this.program.instruction.updateUserQuoteAssetInsuranceStake({
|
|
4217
|
+
accounts: {
|
|
4218
|
+
state: await this.getStatePublicKey(),
|
|
4219
|
+
spotMarket: spotMarket.pubkey,
|
|
4220
|
+
insuranceFundStake: ifStakeAccountPublicKey,
|
|
4221
|
+
userStats: userStatsPublicKey,
|
|
4222
|
+
signer: this.wallet.publicKey,
|
|
4223
|
+
insuranceFundVault: spotMarket.insuranceFund.vault,
|
|
4224
|
+
},
|
|
4225
|
+
});
|
|
4226
|
+
return ix;
|
|
4227
|
+
}
|
|
4228
|
+
async updateUserGovTokenInsuranceStake(authority, txParams, env = 'mainnet-beta') {
|
|
4229
|
+
const ix = env == 'mainnet-beta'
|
|
4230
|
+
? await this.getUpdateUserGovTokenInsuranceStakeIx(authority)
|
|
4231
|
+
: await this.getUpdateUserGovTokenInsuranceStakeDevnetIx(authority);
|
|
4232
|
+
const tx = await this.buildTransaction(ix, txParams);
|
|
4233
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
4234
|
+
return txSig;
|
|
4235
|
+
}
|
|
4236
|
+
async getUpdateUserGovTokenInsuranceStakeIx(authority) {
|
|
4237
|
+
const marketIndex = numericConstants_1.GOV_SPOT_MARKET_INDEX;
|
|
4238
|
+
const spotMarket = this.getSpotMarketAccount(marketIndex);
|
|
4239
|
+
const ifStakeAccountPublicKey = (0, pda_1.getInsuranceFundStakeAccountPublicKey)(this.program.programId, authority, marketIndex);
|
|
4240
|
+
const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, authority);
|
|
4241
|
+
const ix = this.program.instruction.updateUserGovTokenInsuranceStake({
|
|
4242
|
+
accounts: {
|
|
4243
|
+
state: await this.getStatePublicKey(),
|
|
4244
|
+
spotMarket: spotMarket.pubkey,
|
|
4245
|
+
insuranceFundStake: ifStakeAccountPublicKey,
|
|
4246
|
+
userStats: userStatsPublicKey,
|
|
4247
|
+
signer: this.wallet.publicKey,
|
|
4248
|
+
insuranceFundVault: spotMarket.insuranceFund.vault,
|
|
4249
|
+
},
|
|
4250
|
+
});
|
|
4251
|
+
return ix;
|
|
4252
|
+
}
|
|
4253
|
+
async getUpdateUserGovTokenInsuranceStakeDevnetIx(authority, amount = new anchor_1.BN(1)) {
|
|
4254
|
+
const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, authority);
|
|
4255
|
+
const ix = this.program.instruction.updateUserGovTokenInsuranceStakeDevnet(amount, {
|
|
4256
|
+
accounts: {
|
|
4257
|
+
userStats: userStatsPublicKey,
|
|
4258
|
+
signer: this.wallet.publicKey,
|
|
4259
|
+
},
|
|
4260
|
+
});
|
|
4261
|
+
return ix;
|
|
4262
|
+
}
|
|
4263
|
+
async settleRevenueToInsuranceFund(spotMarketIndex, txParams) {
|
|
4264
|
+
const tx = await this.buildTransaction(await this.getSettleRevenueToInsuranceFundIx(spotMarketIndex), txParams);
|
|
4265
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
4266
|
+
return txSig;
|
|
4267
|
+
}
|
|
4268
|
+
async getSettleRevenueToInsuranceFundIx(spotMarketIndex) {
|
|
4269
|
+
const spotMarketAccount = this.getSpotMarketAccount(spotMarketIndex);
|
|
4270
|
+
const tokenProgramId = this.getTokenProgramForSpotMarket(spotMarketAccount);
|
|
4271
|
+
const remainingAccounts = [];
|
|
4272
|
+
this.addTokenMintToRemainingAccounts(spotMarketAccount, remainingAccounts);
|
|
4273
|
+
const ix = await this.program.instruction.settleRevenueToInsuranceFund(spotMarketIndex, {
|
|
4274
|
+
accounts: {
|
|
4275
|
+
state: await this.getStatePublicKey(),
|
|
4276
|
+
spotMarket: spotMarketAccount.pubkey,
|
|
4277
|
+
spotMarketVault: spotMarketAccount.vault,
|
|
4278
|
+
driftSigner: this.getSignerPublicKey(),
|
|
4279
|
+
insuranceFundVault: spotMarketAccount.insuranceFund.vault,
|
|
4280
|
+
tokenProgram: tokenProgramId,
|
|
4281
|
+
},
|
|
4282
|
+
remainingAccounts,
|
|
4283
|
+
});
|
|
4284
|
+
return ix;
|
|
4285
|
+
}
|
|
4286
|
+
async resolvePerpPnlDeficit(spotMarketIndex, perpMarketIndex, txParams) {
|
|
4287
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getResolvePerpPnlDeficitIx(spotMarketIndex, perpMarketIndex), txParams), [], this.opts);
|
|
4288
|
+
return txSig;
|
|
4289
|
+
}
|
|
4290
|
+
async getResolvePerpPnlDeficitIx(spotMarketIndex, perpMarketIndex) {
|
|
4291
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
4292
|
+
userAccounts: [this.getUserAccount()],
|
|
4293
|
+
useMarketLastSlotCache: true,
|
|
4294
|
+
writablePerpMarketIndexes: [perpMarketIndex],
|
|
4295
|
+
writableSpotMarketIndexes: [spotMarketIndex],
|
|
4296
|
+
});
|
|
4297
|
+
const spotMarket = this.getSpotMarketAccount(spotMarketIndex);
|
|
4298
|
+
const tokenProgramId = this.getTokenProgramForSpotMarket(spotMarket);
|
|
4299
|
+
return await this.program.instruction.resolvePerpPnlDeficit(spotMarketIndex, perpMarketIndex, {
|
|
4300
|
+
accounts: {
|
|
4301
|
+
state: await this.getStatePublicKey(),
|
|
4302
|
+
authority: this.wallet.publicKey,
|
|
4303
|
+
spotMarketVault: spotMarket.vault,
|
|
4304
|
+
insuranceFundVault: spotMarket.insuranceFund.vault,
|
|
4305
|
+
driftSigner: this.getSignerPublicKey(),
|
|
4306
|
+
tokenProgram: tokenProgramId,
|
|
4307
|
+
},
|
|
4308
|
+
remainingAccounts: remainingAccounts,
|
|
4309
|
+
});
|
|
4310
|
+
}
|
|
4311
|
+
async getDepositIntoSpotMarketRevenuePoolIx(marketIndex, amount, userTokenAccountPublicKey) {
|
|
4312
|
+
const spotMarket = await this.getSpotMarketAccount(marketIndex);
|
|
4313
|
+
const remainingAccounts = [];
|
|
4314
|
+
this.addTokenMintToRemainingAccounts(spotMarket, remainingAccounts);
|
|
4315
|
+
const tokenProgram = this.getTokenProgramForSpotMarket(spotMarket);
|
|
4316
|
+
const ix = await this.program.instruction.depositIntoSpotMarketRevenuePool(amount, {
|
|
4317
|
+
accounts: {
|
|
4318
|
+
state: await this.getStatePublicKey(),
|
|
4319
|
+
spotMarket: spotMarket.pubkey,
|
|
4320
|
+
authority: this.wallet.publicKey,
|
|
4321
|
+
spotMarketVault: spotMarket.vault,
|
|
4322
|
+
userTokenAccount: userTokenAccountPublicKey,
|
|
4323
|
+
tokenProgram,
|
|
4324
|
+
},
|
|
4325
|
+
});
|
|
4326
|
+
return ix;
|
|
4327
|
+
}
|
|
4328
|
+
/**
|
|
4329
|
+
* This ix will donate your funds to drift revenue pool. It does not deposit into your user account
|
|
4330
|
+
* @param marketIndex
|
|
4331
|
+
* @param amount
|
|
4332
|
+
* @param userTokenAccountPublicKey
|
|
4333
|
+
* @returns
|
|
4334
|
+
*/
|
|
4335
|
+
async depositIntoSpotMarketRevenuePool(marketIndex, amount, userTokenAccountPublicKey) {
|
|
4336
|
+
const ix = await this.getDepositIntoSpotMarketRevenuePoolIx(marketIndex, amount, userTokenAccountPublicKey);
|
|
4337
|
+
const tx = await this.buildTransaction([ix]);
|
|
4338
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
4339
|
+
return txSig;
|
|
4340
|
+
}
|
|
4341
|
+
getPerpMarketExtendedInfo(marketIndex) {
|
|
4342
|
+
var _a, _b;
|
|
4343
|
+
const marketAccount = this.getPerpMarketAccount(marketIndex);
|
|
4344
|
+
const quoteAccount = this.getSpotMarketAccount(numericConstants_1.QUOTE_SPOT_MARKET_INDEX);
|
|
4345
|
+
const extendedInfo = {
|
|
4346
|
+
marketIndex,
|
|
4347
|
+
minOrderSize: (_a = marketAccount.amm) === null || _a === void 0 ? void 0 : _a.minOrderSize,
|
|
4348
|
+
marginMaintenance: marketAccount.marginRatioMaintenance,
|
|
4349
|
+
pnlPoolValue: (0, spotBalance_1.getTokenAmount)((_b = marketAccount.pnlPool) === null || _b === void 0 ? void 0 : _b.scaledBalance, quoteAccount, types_1.SpotBalanceType.DEPOSIT),
|
|
4350
|
+
contractTier: marketAccount.contractTier,
|
|
4351
|
+
availableInsurance: (0, market_1.calculateMarketMaxAvailableInsurance)(marketAccount, quoteAccount),
|
|
4352
|
+
};
|
|
4353
|
+
return extendedInfo;
|
|
4354
|
+
}
|
|
4355
|
+
/**
|
|
4356
|
+
* Calculates taker / maker fee (as a percentage, e.g. .001 = 10 basis points) for particular marketType
|
|
4357
|
+
* @param marketType
|
|
4358
|
+
* @param positionMarketIndex
|
|
4359
|
+
* @returns : {takerFee: number, makerFee: number} Precision None
|
|
4360
|
+
*/
|
|
4361
|
+
getMarketFees(marketType, marketIndex, user) {
|
|
4362
|
+
let feeTier;
|
|
4363
|
+
if (user) {
|
|
4364
|
+
feeTier = user.getUserFeeTier(marketType);
|
|
4365
|
+
}
|
|
4366
|
+
else {
|
|
4367
|
+
const state = this.getStateAccount();
|
|
4368
|
+
feeTier = (0, types_1.isVariant)(marketType, 'perp')
|
|
4369
|
+
? state.perpFeeStructure.feeTiers[0]
|
|
4370
|
+
: state.spotFeeStructure.feeTiers[0];
|
|
4371
|
+
}
|
|
4372
|
+
let takerFee = feeTier.feeNumerator / feeTier.feeDenominator;
|
|
4373
|
+
let makerFee = feeTier.makerRebateNumerator / feeTier.makerRebateDenominator;
|
|
4374
|
+
if (marketIndex !== undefined) {
|
|
4375
|
+
let marketAccount = null;
|
|
4376
|
+
if ((0, types_1.isVariant)(marketType, 'perp')) {
|
|
4377
|
+
marketAccount = this.getPerpMarketAccount(marketIndex);
|
|
4378
|
+
}
|
|
4379
|
+
else {
|
|
4380
|
+
marketAccount = this.getSpotMarketAccount(marketIndex);
|
|
4381
|
+
}
|
|
4382
|
+
takerFee += (takerFee * marketAccount.feeAdjustment) / 100;
|
|
4383
|
+
if (user && user.isHighLeverageMode()) {
|
|
4384
|
+
takerFee *= 2;
|
|
4385
|
+
}
|
|
4386
|
+
makerFee += (makerFee * marketAccount.feeAdjustment) / 100;
|
|
4387
|
+
}
|
|
4388
|
+
return {
|
|
4389
|
+
takerFee,
|
|
4390
|
+
makerFee,
|
|
4391
|
+
};
|
|
4392
|
+
}
|
|
4393
|
+
/**
|
|
4394
|
+
* Returns the market index and type for a given market name
|
|
4395
|
+
* E.g. "SOL-PERP" -> { marketIndex: 0, marketType: MarketType.PERP }
|
|
4396
|
+
*
|
|
4397
|
+
* @param name
|
|
4398
|
+
*/
|
|
4399
|
+
getMarketIndexAndType(name) {
|
|
4400
|
+
name = name.toUpperCase();
|
|
4401
|
+
for (const perpMarketAccount of this.getPerpMarketAccounts()) {
|
|
4402
|
+
if ((0, userName_1.decodeName)(perpMarketAccount.name).toUpperCase() === name) {
|
|
4403
|
+
return {
|
|
4404
|
+
marketIndex: perpMarketAccount.marketIndex,
|
|
4405
|
+
marketType: types_1.MarketType.PERP,
|
|
4406
|
+
};
|
|
4407
|
+
}
|
|
4408
|
+
}
|
|
4409
|
+
for (const spotMarketAccount of this.getSpotMarketAccounts()) {
|
|
4410
|
+
if ((0, userName_1.decodeName)(spotMarketAccount.name).toUpperCase() === name) {
|
|
4411
|
+
return {
|
|
4412
|
+
marketIndex: spotMarketAccount.marketIndex,
|
|
4413
|
+
marketType: types_1.MarketType.SPOT,
|
|
4414
|
+
};
|
|
4415
|
+
}
|
|
4416
|
+
}
|
|
4417
|
+
return undefined;
|
|
4418
|
+
}
|
|
4419
|
+
getReceiverProgram() {
|
|
4420
|
+
if (this.receiverProgram === undefined) {
|
|
4421
|
+
this.receiverProgram = new anchor_1.Program(pyth_solana_receiver_json_1.default, pyth_solana_receiver_1.DEFAULT_RECEIVER_PROGRAM_ID, this.provider);
|
|
4422
|
+
}
|
|
4423
|
+
return this.receiverProgram;
|
|
4424
|
+
}
|
|
4425
|
+
async getSwitchboardOnDemandProgram() {
|
|
4426
|
+
const idl = (await anchor_30_1.Program.fetchIdl(this.sbOnDemandProgramdId, this.provider));
|
|
4427
|
+
if (this.sbOnDemandProgram === undefined) {
|
|
4428
|
+
this.sbOnDemandProgram = new anchor_30_1.Program(idl, this.provider);
|
|
4429
|
+
}
|
|
4430
|
+
return this.sbOnDemandProgram;
|
|
4431
|
+
}
|
|
4432
|
+
async postPythPullOracleUpdateAtomic(vaaString, feedId) {
|
|
4433
|
+
const postIxs = await this.getPostPythPullOracleUpdateAtomicIxs(vaaString, feedId);
|
|
4434
|
+
const tx = await this.buildTransaction(postIxs);
|
|
4435
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
4436
|
+
return txSig;
|
|
4437
|
+
}
|
|
4438
|
+
async postMultiPythPullOracleUpdatesAtomic(vaaString, feedIds) {
|
|
4439
|
+
const postIxs = await this.getPostPythPullOracleUpdateAtomicIxs(vaaString, feedIds);
|
|
4440
|
+
const tx = await this.buildTransaction(postIxs);
|
|
4441
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
4442
|
+
return txSig;
|
|
4443
|
+
}
|
|
4444
|
+
async getPostPythPullOracleUpdateAtomicIxs(vaaString, feedIds, numSignatures = 2) {
|
|
4445
|
+
const accumulatorUpdateData = (0, price_service_sdk_1.parseAccumulatorUpdateData)(Buffer.from(vaaString, 'base64'));
|
|
4446
|
+
const guardianSetIndex = accumulatorUpdateData.vaa.readUInt32BE(1);
|
|
4447
|
+
const guardianSet = (0, address_1.getGuardianSetPda)(guardianSetIndex, address_1.DEFAULT_WORMHOLE_PROGRAM_ID);
|
|
4448
|
+
const trimmedVaa = (0, oracles_1.trimVaaSignatures)(accumulatorUpdateData.vaa, numSignatures);
|
|
4449
|
+
const postIxs = [];
|
|
4450
|
+
if (accumulatorUpdateData.updates.length > 1) {
|
|
4451
|
+
const encodedParams = this.getReceiverProgram().coder.types.encode('PostMultiUpdatesAtomicParams', {
|
|
4452
|
+
vaa: trimmedVaa,
|
|
4453
|
+
merklePriceUpdates: accumulatorUpdateData.updates,
|
|
4454
|
+
});
|
|
4455
|
+
const feedIdsToUse = typeof feedIds === 'string' ? [feedIds] : feedIds;
|
|
4456
|
+
const pubkeys = feedIdsToUse.map((feedId) => {
|
|
4457
|
+
return (0, pda_1.getPythPullOraclePublicKey)(this.program.programId, (0, pythOracleUtils_1.getFeedIdUint8Array)(feedId));
|
|
4458
|
+
});
|
|
4459
|
+
const remainingAccounts = pubkeys.map((pubkey) => {
|
|
4460
|
+
return {
|
|
4461
|
+
pubkey,
|
|
4462
|
+
isSigner: false,
|
|
4463
|
+
isWritable: true,
|
|
4464
|
+
};
|
|
4465
|
+
});
|
|
4466
|
+
postIxs.push(this.program.instruction.postMultiPythPullOracleUpdatesAtomic(encodedParams, {
|
|
4467
|
+
accounts: {
|
|
4468
|
+
keeper: this.wallet.publicKey,
|
|
4469
|
+
pythSolanaReceiver: config_1.DRIFT_ORACLE_RECEIVER_ID,
|
|
4470
|
+
guardianSet,
|
|
4471
|
+
},
|
|
4472
|
+
remainingAccounts,
|
|
4473
|
+
}));
|
|
4474
|
+
}
|
|
4475
|
+
else {
|
|
4476
|
+
let feedIdToUse = typeof feedIds === 'string' ? feedIds : feedIds[0];
|
|
4477
|
+
feedIdToUse = (0, pythOracleUtils_1.trimFeedId)(feedIdToUse);
|
|
4478
|
+
postIxs.push(await this.getSinglePostPythPullOracleAtomicIx({
|
|
4479
|
+
vaa: trimmedVaa,
|
|
4480
|
+
merklePriceUpdate: accumulatorUpdateData.updates[0],
|
|
4481
|
+
}, feedIdToUse, guardianSet));
|
|
4482
|
+
}
|
|
4483
|
+
return postIxs;
|
|
4484
|
+
}
|
|
4485
|
+
async getSinglePostPythPullOracleAtomicIx(params, feedId, guardianSet) {
|
|
4486
|
+
const feedIdBuffer = (0, pythOracleUtils_1.getFeedIdUint8Array)(feedId);
|
|
4487
|
+
const receiverProgram = this.getReceiverProgram();
|
|
4488
|
+
const encodedParams = receiverProgram.coder.types.encode('PostUpdateAtomicParams', params);
|
|
4489
|
+
return this.program.instruction.postPythPullOracleUpdateAtomic(feedIdBuffer, encodedParams, {
|
|
4490
|
+
accounts: {
|
|
4491
|
+
keeper: this.wallet.publicKey,
|
|
4492
|
+
pythSolanaReceiver: config_1.DRIFT_ORACLE_RECEIVER_ID,
|
|
4493
|
+
guardianSet,
|
|
4494
|
+
priceFeed: (0, pda_1.getPythPullOraclePublicKey)(this.program.programId, feedIdBuffer),
|
|
4495
|
+
},
|
|
4496
|
+
});
|
|
4497
|
+
}
|
|
4498
|
+
async updatePythPullOracle(vaaString, feedId) {
|
|
4499
|
+
feedId = (0, pythOracleUtils_1.trimFeedId)(feedId);
|
|
4500
|
+
const accumulatorUpdateData = (0, price_service_sdk_1.parseAccumulatorUpdateData)(Buffer.from(vaaString, 'base64'));
|
|
4501
|
+
const guardianSetIndex = accumulatorUpdateData.vaa.readUInt32BE(1);
|
|
4502
|
+
const guardianSet = (0, address_1.getGuardianSetPda)(guardianSetIndex, address_1.DEFAULT_WORMHOLE_PROGRAM_ID);
|
|
4503
|
+
const [postIxs, encodedVaaAddress] = await this.getBuildEncodedVaaIxs(accumulatorUpdateData.vaa, guardianSet);
|
|
4504
|
+
for (const update of accumulatorUpdateData.updates) {
|
|
4505
|
+
postIxs.push(await this.getUpdatePythPullOracleIxs({
|
|
4506
|
+
merklePriceUpdate: update,
|
|
4507
|
+
}, feedId, encodedVaaAddress.publicKey));
|
|
4508
|
+
}
|
|
4509
|
+
const tx = await this.buildTransaction(postIxs);
|
|
4510
|
+
const { txSig } = await this.sendTransaction(tx, [encodedVaaAddress], this.opts);
|
|
4511
|
+
return txSig;
|
|
4512
|
+
}
|
|
4513
|
+
async getUpdatePythPullOracleIxs(params, feedId, encodedVaaAddress) {
|
|
4514
|
+
const feedIdBuffer = (0, pythOracleUtils_1.getFeedIdUint8Array)(feedId);
|
|
4515
|
+
const receiverProgram = this.getReceiverProgram();
|
|
4516
|
+
const encodedParams = receiverProgram.coder.types.encode('PostUpdateParams', params);
|
|
4517
|
+
return this.program.instruction.updatePythPullOracle(feedIdBuffer, encodedParams, {
|
|
4518
|
+
accounts: {
|
|
4519
|
+
keeper: this.wallet.publicKey,
|
|
4520
|
+
pythSolanaReceiver: config_1.DRIFT_ORACLE_RECEIVER_ID,
|
|
4521
|
+
encodedVaa: encodedVaaAddress,
|
|
4522
|
+
priceFeed: (0, pda_1.getPythPullOraclePublicKey)(this.program.programId, feedIdBuffer),
|
|
4523
|
+
},
|
|
4524
|
+
});
|
|
4525
|
+
}
|
|
4526
|
+
async postPythLazerOracleUpdate(feedIds, pythMessageHex) {
|
|
4527
|
+
const postIxs = this.getPostPythLazerOracleUpdateIxs(feedIds, pythMessageHex, undefined, 2);
|
|
4528
|
+
const tx = await this.buildTransaction(postIxs);
|
|
4529
|
+
const { txSig } = await this.sendTransaction(tx, [], this.opts);
|
|
4530
|
+
return txSig;
|
|
4531
|
+
}
|
|
4532
|
+
getPostPythLazerOracleUpdateIxs(feedIds, pythMessageHex, precedingIxs = [], overrideIxCount) {
|
|
4533
|
+
const pythMessageBytes = Buffer.from(pythMessageHex, 'hex');
|
|
4534
|
+
const updateData = new Uint8Array(pythMessageBytes);
|
|
4535
|
+
const verifyIx = (0, pythOracleUtils_1.createMinimalEd25519VerifyIx)(overrideIxCount || precedingIxs.length + 1, 0, updateData);
|
|
4536
|
+
const remainingAccountsMeta = feedIds.map((feedId) => {
|
|
4537
|
+
return {
|
|
4538
|
+
pubkey: (0, pda_1.getPythLazerOraclePublicKey)(this.program.programId, feedId),
|
|
4539
|
+
isSigner: false,
|
|
4540
|
+
isWritable: true,
|
|
4541
|
+
};
|
|
4542
|
+
});
|
|
4543
|
+
const ix = this.program.instruction.postPythLazerOracleUpdate(pythMessageBytes, {
|
|
4544
|
+
accounts: {
|
|
4545
|
+
keeper: this.wallet.publicKey,
|
|
4546
|
+
pythLazerStorage: config_1.PYTH_LAZER_STORAGE_ACCOUNT_KEY,
|
|
4547
|
+
ixSysvar: web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY,
|
|
4548
|
+
},
|
|
4549
|
+
remainingAccounts: remainingAccountsMeta,
|
|
4550
|
+
});
|
|
4551
|
+
return [verifyIx, ix];
|
|
4552
|
+
}
|
|
4553
|
+
async getPostSwitchboardOnDemandUpdateAtomicIx(feed, recentSlothash, numSignatures = 3) {
|
|
4554
|
+
const program = await this.getSwitchboardOnDemandProgram();
|
|
4555
|
+
const feedAccount = new on_demand_1.PullFeed(program, feed);
|
|
4556
|
+
if (!this.sbProgramFeedConfigs) {
|
|
4557
|
+
this.sbProgramFeedConfigs = new Map();
|
|
4558
|
+
}
|
|
4559
|
+
if (!this.sbProgramFeedConfigs.has(feedAccount.pubkey.toString())) {
|
|
4560
|
+
const feedConfig = await feedAccount.loadConfigs();
|
|
4561
|
+
this.sbProgramFeedConfigs.set(feed.toString(), feedConfig);
|
|
4562
|
+
}
|
|
4563
|
+
const [pullIx, _responses, success] = await feedAccount.fetchUpdateIx({
|
|
4564
|
+
numSignatures,
|
|
4565
|
+
}, recentSlothash
|
|
4566
|
+
? [[new anchor_1.BN(recentSlothash.slot), recentSlothash.hash]]
|
|
4567
|
+
: undefined);
|
|
4568
|
+
if (!success) {
|
|
4569
|
+
return undefined;
|
|
4570
|
+
}
|
|
4571
|
+
return pullIx;
|
|
4572
|
+
}
|
|
4573
|
+
async postSwitchboardOnDemandUpdate(feed, recentSlothash, numSignatures = 3) {
|
|
4574
|
+
const pullIx = await this.getPostSwitchboardOnDemandUpdateAtomicIx(feed, recentSlothash, numSignatures);
|
|
4575
|
+
if (!pullIx) {
|
|
4576
|
+
return undefined;
|
|
4577
|
+
}
|
|
4578
|
+
const tx = await (0, on_demand_1.asV0Tx)({
|
|
4579
|
+
connection: this.connection,
|
|
4580
|
+
ixs: [pullIx],
|
|
4581
|
+
payer: this.wallet.publicKey,
|
|
4582
|
+
computeUnitLimitMultiple: 1.3,
|
|
4583
|
+
lookupTables: [await this.fetchMarketLookupTableAccount()],
|
|
4584
|
+
});
|
|
4585
|
+
const { txSig } = await this.sendTransaction(tx, [], {
|
|
4586
|
+
commitment: 'processed',
|
|
4587
|
+
skipPreflight: true,
|
|
4588
|
+
maxRetries: 0,
|
|
4589
|
+
});
|
|
4590
|
+
return txSig;
|
|
4591
|
+
}
|
|
4592
|
+
async getBuildEncodedVaaIxs(vaa, guardianSet) {
|
|
4593
|
+
const postIxs = [];
|
|
4594
|
+
if (this.wormholeProgram === undefined) {
|
|
4595
|
+
this.wormholeProgram = new anchor_1.Program(pyth_solana_receiver_1.wormholeCoreBridgeIdl, address_1.DEFAULT_WORMHOLE_PROGRAM_ID, this.provider);
|
|
4596
|
+
}
|
|
4597
|
+
const encodedVaaKeypair = new web3_js_1.Keypair();
|
|
4598
|
+
postIxs.push(await this.wormholeProgram.account.encodedVaa.createInstruction(encodedVaaKeypair, vaa.length + 46));
|
|
4599
|
+
// Why do we need this too?
|
|
4600
|
+
postIxs.push(await this.wormholeProgram.methods
|
|
4601
|
+
.initEncodedVaa()
|
|
4602
|
+
.accounts({
|
|
4603
|
+
encodedVaa: encodedVaaKeypair.publicKey,
|
|
4604
|
+
})
|
|
4605
|
+
.instruction());
|
|
4606
|
+
// Split the write into two ixs
|
|
4607
|
+
postIxs.push(await this.wormholeProgram.methods
|
|
4608
|
+
.writeEncodedVaa({
|
|
4609
|
+
index: 0,
|
|
4610
|
+
data: vaa.subarray(0, 755),
|
|
4611
|
+
})
|
|
4612
|
+
.accounts({
|
|
4613
|
+
draftVaa: encodedVaaKeypair.publicKey,
|
|
4614
|
+
})
|
|
4615
|
+
.instruction());
|
|
4616
|
+
postIxs.push(await this.wormholeProgram.methods
|
|
4617
|
+
.writeEncodedVaa({
|
|
4618
|
+
index: 755,
|
|
4619
|
+
data: vaa.subarray(755),
|
|
4620
|
+
})
|
|
4621
|
+
.accounts({
|
|
4622
|
+
draftVaa: encodedVaaKeypair.publicKey,
|
|
4623
|
+
})
|
|
4624
|
+
.instruction());
|
|
4625
|
+
// Verify
|
|
4626
|
+
postIxs.push(await this.wormholeProgram.methods
|
|
4627
|
+
.verifyEncodedVaaV1()
|
|
4628
|
+
.accounts({
|
|
4629
|
+
guardianSet,
|
|
4630
|
+
draftVaa: encodedVaaKeypair.publicKey,
|
|
4631
|
+
})
|
|
4632
|
+
.instruction());
|
|
4633
|
+
return [postIxs, encodedVaaKeypair];
|
|
4634
|
+
}
|
|
4635
|
+
async enableUserHighLeverageMode(subAccountId, txParams) {
|
|
4636
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getEnableHighLeverageModeIx(subAccountId), txParams), [], this.opts);
|
|
4637
|
+
return txSig;
|
|
4638
|
+
}
|
|
4639
|
+
async getEnableHighLeverageModeIx(subAccountId, depositToTradeArgs) {
|
|
4640
|
+
const isDepositToTradeTx = depositToTradeArgs !== undefined;
|
|
4641
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
4642
|
+
userAccounts: (depositToTradeArgs === null || depositToTradeArgs === void 0 ? void 0 : depositToTradeArgs.isMakingNewAccount)
|
|
4643
|
+
? []
|
|
4644
|
+
: [this.getUserAccount(subAccountId)],
|
|
4645
|
+
useMarketLastSlotCache: false,
|
|
4646
|
+
readablePerpMarketIndex: depositToTradeArgs === null || depositToTradeArgs === void 0 ? void 0 : depositToTradeArgs.orderMarketIndex,
|
|
4647
|
+
readableSpotMarketIndexes: isDepositToTradeTx
|
|
4648
|
+
? [depositToTradeArgs === null || depositToTradeArgs === void 0 ? void 0 : depositToTradeArgs.depositMarketIndex]
|
|
4649
|
+
: undefined,
|
|
4650
|
+
});
|
|
4651
|
+
const ix = await this.program.instruction.enableUserHighLeverageMode(subAccountId, {
|
|
4652
|
+
accounts: {
|
|
4653
|
+
state: await this.getStatePublicKey(),
|
|
4654
|
+
user: (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, subAccountId),
|
|
4655
|
+
authority: this.wallet.publicKey,
|
|
4656
|
+
highLeverageModeConfig: (0, pda_1.getHighLeverageModeConfigPublicKey)(this.program.programId),
|
|
4657
|
+
},
|
|
4658
|
+
remainingAccounts,
|
|
4659
|
+
});
|
|
4660
|
+
return ix;
|
|
4661
|
+
}
|
|
4662
|
+
async disableUserHighLeverageMode(user, userAccount, txParams) {
|
|
4663
|
+
const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getDisableHighLeverageModeIx(user, userAccount), txParams), [], this.opts);
|
|
4664
|
+
return txSig;
|
|
4665
|
+
}
|
|
4666
|
+
async getDisableHighLeverageModeIx(user, userAccount) {
|
|
4667
|
+
const remainingAccounts = userAccount
|
|
4668
|
+
? this.getRemainingAccounts({
|
|
4669
|
+
userAccounts: [userAccount],
|
|
4670
|
+
})
|
|
4671
|
+
: undefined;
|
|
4672
|
+
const ix = await this.program.instruction.disableUserHighLeverageMode({
|
|
4673
|
+
accounts: {
|
|
4674
|
+
state: await this.getStatePublicKey(),
|
|
4675
|
+
user,
|
|
4676
|
+
authority: this.wallet.publicKey,
|
|
4677
|
+
highLeverageModeConfig: (0, pda_1.getHighLeverageModeConfigPublicKey)(this.program.programId),
|
|
4678
|
+
},
|
|
4679
|
+
remainingAccounts,
|
|
4680
|
+
});
|
|
4681
|
+
return ix;
|
|
4682
|
+
}
|
|
4683
|
+
async fetchHighLeverageModeConfig() {
|
|
4684
|
+
const config = await this.program.account.highLeverageModeConfig.fetch((0, pda_1.getHighLeverageModeConfigPublicKey)(this.program.programId));
|
|
4685
|
+
return config;
|
|
4686
|
+
}
|
|
4687
|
+
handleSignedTransaction(signedTxs) {
|
|
4688
|
+
if (this.enableMetricsEvents && this.metricsEventEmitter) {
|
|
4689
|
+
this.metricsEventEmitter.emit('txSigned', signedTxs);
|
|
4690
|
+
}
|
|
4691
|
+
}
|
|
4692
|
+
handlePreSignedTransaction() {
|
|
4693
|
+
if (this.enableMetricsEvents && this.metricsEventEmitter) {
|
|
4694
|
+
this.metricsEventEmitter.emit('preTxSigned');
|
|
4695
|
+
}
|
|
4696
|
+
}
|
|
4697
|
+
isVersionedTransaction(tx) {
|
|
4698
|
+
return (0, utils_2.isVersionedTransaction)(tx);
|
|
4699
|
+
}
|
|
4700
|
+
/**
|
|
4701
|
+
* Send a transaction.
|
|
4702
|
+
*
|
|
4703
|
+
* @param tx
|
|
4704
|
+
* @param additionalSigners
|
|
4705
|
+
* @param opts :: Will fallback to DriftClient's opts if not provided
|
|
4706
|
+
* @param preSigned
|
|
4707
|
+
* @returns
|
|
4708
|
+
*/
|
|
4709
|
+
sendTransaction(tx, additionalSigners, opts, preSigned) {
|
|
4710
|
+
const isVersionedTx = this.isVersionedTransaction(tx);
|
|
4711
|
+
if (isVersionedTx) {
|
|
4712
|
+
return this.txSender.sendVersionedTransaction(tx, additionalSigners, opts !== null && opts !== void 0 ? opts : this.opts, preSigned);
|
|
4713
|
+
}
|
|
4714
|
+
else {
|
|
4715
|
+
return this.txSender.send(tx, additionalSigners, opts !== null && opts !== void 0 ? opts : this.opts, preSigned);
|
|
4716
|
+
}
|
|
4717
|
+
}
|
|
4718
|
+
async buildTransaction(instructions, txParams, txVersion, lookupTables, forceVersionedTransaction, recentBlockhash) {
|
|
4719
|
+
return this.txHandler.buildTransaction({
|
|
4720
|
+
instructions,
|
|
4721
|
+
txVersion: txVersion !== null && txVersion !== void 0 ? txVersion : this.txVersion,
|
|
4722
|
+
txParams: txParams !== null && txParams !== void 0 ? txParams : this.txParams,
|
|
4723
|
+
connection: this.connection,
|
|
4724
|
+
preFlightCommitment: this.opts.preflightCommitment,
|
|
4725
|
+
fetchMarketLookupTableAccount: this.fetchMarketLookupTableAccount.bind(this),
|
|
4726
|
+
lookupTables,
|
|
4727
|
+
forceVersionedTransaction,
|
|
4728
|
+
recentBlockhash,
|
|
4729
|
+
});
|
|
4730
|
+
}
|
|
4731
|
+
async buildBulkTransactions(instructions, txParams, txVersion, lookupTables, forceVersionedTransaction) {
|
|
4732
|
+
return this.txHandler.buildBulkTransactions({
|
|
4733
|
+
instructions,
|
|
4734
|
+
txVersion: txVersion !== null && txVersion !== void 0 ? txVersion : this.txVersion,
|
|
4735
|
+
txParams: txParams !== null && txParams !== void 0 ? txParams : this.txParams,
|
|
4736
|
+
connection: this.connection,
|
|
4737
|
+
preFlightCommitment: this.opts.preflightCommitment,
|
|
4738
|
+
fetchMarketLookupTableAccount: this.fetchMarketLookupTableAccount.bind(this),
|
|
4739
|
+
lookupTables,
|
|
4740
|
+
forceVersionedTransaction,
|
|
4741
|
+
});
|
|
4742
|
+
}
|
|
4743
|
+
async buildTransactionsMap(instructionsMap, txParams, txVersion, lookupTables, forceVersionedTransaction) {
|
|
4744
|
+
return this.txHandler.buildTransactionsMap({
|
|
4745
|
+
instructionsMap,
|
|
4746
|
+
txVersion: txVersion !== null && txVersion !== void 0 ? txVersion : this.txVersion,
|
|
4747
|
+
txParams: txParams !== null && txParams !== void 0 ? txParams : this.txParams,
|
|
4748
|
+
connection: this.connection,
|
|
4749
|
+
preFlightCommitment: this.opts.preflightCommitment,
|
|
4750
|
+
fetchMarketLookupTableAccount: this.fetchMarketLookupTableAccount.bind(this),
|
|
4751
|
+
lookupTables,
|
|
4752
|
+
forceVersionedTransaction,
|
|
4753
|
+
});
|
|
4754
|
+
}
|
|
4755
|
+
async buildAndSignTransactionsMap(instructionsMap, txParams, txVersion, lookupTables, forceVersionedTransaction) {
|
|
4756
|
+
return this.txHandler.buildAndSignTransactionMap({
|
|
4757
|
+
instructionsMap,
|
|
4758
|
+
txVersion: txVersion !== null && txVersion !== void 0 ? txVersion : this.txVersion,
|
|
4759
|
+
txParams: txParams !== null && txParams !== void 0 ? txParams : this.txParams,
|
|
4760
|
+
connection: this.connection,
|
|
4761
|
+
preFlightCommitment: this.opts.preflightCommitment,
|
|
4762
|
+
fetchMarketLookupTableAccount: this.fetchMarketLookupTableAccount.bind(this),
|
|
4763
|
+
lookupTables,
|
|
4764
|
+
forceVersionedTransaction,
|
|
4765
|
+
});
|
|
4766
|
+
}
|
|
4767
|
+
}
|
|
4768
|
+
exports.DriftClient = DriftClient;
|