@velocity-exchange/sdk 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/lib/browser/adminClient.d.ts +35 -0
- package/lib/browser/adminClient.js +65 -0
- package/lib/browser/config.js +6 -7
- package/lib/browser/constants/numericConstants.d.ts +1 -1
- package/lib/browser/constants/numericConstants.js +1 -1
- package/lib/browser/decode/user.js +5 -1
- package/lib/browser/idl/velocity.d.ts +146 -3
- package/lib/browser/idl/velocity.json +147 -4
- package/lib/browser/orderSubscriber/OrderSubscriber.js +3 -0
- package/lib/browser/pyth/pythLazerSubscriber.js +37 -27
- package/lib/browser/types.d.ts +4 -0
- package/lib/browser/user.d.ts +15 -0
- package/lib/browser/user.js +37 -1
- package/lib/browser/velocityClient.d.ts +46 -10
- package/lib/browser/velocityClient.js +107 -35
- package/lib/node/adminClient.d.ts +35 -0
- package/lib/node/adminClient.d.ts.map +1 -1
- package/lib/node/adminClient.js +65 -0
- package/lib/node/config.d.ts.map +1 -1
- package/lib/node/config.js +6 -7
- package/lib/node/constants/numericConstants.d.ts +1 -1
- package/lib/node/constants/numericConstants.d.ts.map +1 -1
- package/lib/node/constants/numericConstants.js +1 -1
- package/lib/node/decode/user.d.ts.map +1 -1
- package/lib/node/decode/user.js +5 -1
- package/lib/node/idl/velocity.d.ts +146 -3
- package/lib/node/idl/velocity.d.ts.map +1 -1
- package/lib/node/idl/velocity.json +147 -4
- package/lib/node/orderSubscriber/OrderSubscriber.d.ts.map +1 -1
- package/lib/node/orderSubscriber/OrderSubscriber.js +3 -0
- package/lib/node/pyth/pythLazerSubscriber.d.ts.map +1 -1
- package/lib/node/pyth/pythLazerSubscriber.js +37 -27
- package/lib/node/types.d.ts +4 -0
- package/lib/node/types.d.ts.map +1 -1
- package/lib/node/user.d.ts +15 -0
- package/lib/node/user.d.ts.map +1 -1
- package/lib/node/user.js +37 -1
- package/lib/node/velocityClient.d.ts +46 -10
- package/lib/node/velocityClient.d.ts.map +1 -1
- package/lib/node/velocityClient.js +107 -35
- package/package.json +7 -3
- package/.prettierignore +0 -1
- package/CHANGELOG.md +0 -132
- package/build-browser.js +0 -58
- package/bunfig.toml +0 -3
- package/esbuild-shims.js +0 -12
- package/scripts/deposit-isolated-positions.ts +0 -110
- package/scripts/find-flagged-users.ts +0 -213
- package/scripts/grpc-client-test-comparison.ts +0 -372
- package/scripts/grpc-multiuser-client-test-comparison.ts +0 -158
- package/scripts/postbuild.js +0 -95
- package/scripts/single-grpc-client-test.ts +0 -284
- package/scripts/withdraw-isolated-positions.ts +0 -174
- package/src/accounts/README_WebSocketAccountSubscriberV2.md +0 -95
- package/src/accounts/README_WebSocketProgramAccountSubscriberV2.md +0 -135
- package/src/accounts/basicUserAccountSubscriber.ts +0 -79
- package/src/accounts/basicUserStatsAccountSubscriber.ts +0 -87
- package/src/accounts/bulkAccountLoader.ts +0 -358
- package/src/accounts/bulkUserStatsSubscription.ts +0 -40
- package/src/accounts/bulkUserSubscription.ts +0 -39
- package/src/accounts/customizedCadenceBulkAccountLoader.ts +0 -250
- package/src/accounts/fetch.ts +0 -200
- package/src/accounts/grpcAccountSubscriber.ts +0 -225
- package/src/accounts/grpcInsuranceFundStakeAccountSubscriber.ts +0 -73
- package/src/accounts/grpcMultiAccountSubscriber.ts +0 -566
- package/src/accounts/grpcMultiUserAccountSubscriber.ts +0 -328
- package/src/accounts/grpcProgramAccountSubscriber.ts +0 -264
- package/src/accounts/grpcUserAccountSubscriber.ts +0 -63
- package/src/accounts/grpcUserStatsAccountSubscriber.ts +0 -65
- package/src/accounts/grpcVelocityClientAccountSubscriber.ts +0 -257
- package/src/accounts/grpcVelocityClientAccountSubscriberV2.ts +0 -941
- package/src/accounts/laserProgramAccountSubscriber.ts +0 -266
- package/src/accounts/oneShotUserAccountSubscriber.ts +0 -88
- package/src/accounts/oneShotUserStatsAccountSubscriber.ts +0 -94
- package/src/accounts/pollingInsuranceFundStakeAccountSubscriber.ts +0 -223
- package/src/accounts/pollingOracleAccountSubscriber.ts +0 -151
- package/src/accounts/pollingTokenAccountSubscriber.ts +0 -147
- package/src/accounts/pollingUserAccountSubscriber.ts +0 -198
- package/src/accounts/pollingUserStatsAccountSubscriber.ts +0 -180
- package/src/accounts/pollingVelocityClientAccountSubscriber.ts +0 -774
- package/src/accounts/testBulkAccountLoader.ts +0 -59
- package/src/accounts/types.ts +0 -428
- package/src/accounts/utils.ts +0 -90
- package/src/accounts/webSocketAccountSubscriber.ts +0 -304
- package/src/accounts/webSocketAccountSubscriberV2.ts +0 -536
- package/src/accounts/webSocketInsuranceFundStakeAccountSubscriber.ts +0 -171
- package/src/accounts/webSocketProgramAccountSubscriber.ts +0 -244
- package/src/accounts/webSocketProgramAccountSubscriberV2.ts +0 -1048
- package/src/accounts/webSocketProgramAccountsSubscriberV2.ts +0 -1042
- package/src/accounts/webSocketUserAccountSubscriber.ts +0 -139
- package/src/accounts/webSocketUserStatsAccountSubsriber.ts +0 -131
- package/src/accounts/webSocketVelocityClientAccountSubscriber.ts +0 -865
- package/src/accounts/webSocketVelocityClientAccountSubscriberV2.ts +0 -897
- package/src/accounts/websocketProgramUserAccountSubscriber.ts +0 -127
- package/src/addresses/marketAddresses.ts +0 -28
- package/src/addresses/pda.ts +0 -620
- package/src/adminClient.ts +0 -8136
- package/src/assert/assert.ts +0 -5
- package/src/auctionSubscriber/auctionSubscriber.ts +0 -86
- package/src/auctionSubscriber/auctionSubscriberGrpc.ts +0 -99
- package/src/auctionSubscriber/index.ts +0 -9
- package/src/auctionSubscriber/types.ts +0 -30
- package/src/bankrun/bankrunConnection.ts +0 -630
- package/src/blockhashSubscriber/BlockhashSubscriber.ts +0 -160
- package/src/blockhashSubscriber/index.ts +0 -6
- package/src/blockhashSubscriber/types.ts +0 -13
- package/src/clock/clockSubscriber.ts +0 -146
- package/src/config.ts +0 -312
- package/src/constants/index.ts +0 -9
- package/src/constants/numericConstants.ts +0 -194
- package/src/constants/perpMarkets.ts +0 -127
- package/src/constants/spotMarkets.ts +0 -104
- package/src/constants/txConstants.ts +0 -2
- package/src/constituentMap/constituentMap.ts +0 -305
- package/src/constituentMap/pollingConstituentAccountSubscriber.ts +0 -99
- package/src/constituentMap/webSocketConstituentAccountSubscriber.ts +0 -121
- package/src/core/VelocityCore.ts +0 -606
- package/src/core/index.ts +0 -12
- package/src/core/instructions/deposit.ts +0 -64
- package/src/core/instructions/fill.ts +0 -51
- package/src/core/instructions/funding.ts +0 -33
- package/src/core/instructions/liquidation.ts +0 -55
- package/src/core/instructions/orders.ts +0 -84
- package/src/core/instructions/perpOrders.ts +0 -312
- package/src/core/instructions/settlement.ts +0 -40
- package/src/core/instructions/trigger.ts +0 -41
- package/src/core/instructions/withdraw.ts +0 -65
- package/src/core/remainingAccounts.ts +0 -320
- package/src/core/signedMsg.ts +0 -109
- package/src/decode/customCoder.ts +0 -148
- package/src/decode/user.ts +0 -401
- package/src/dlob/DLOB.ts +0 -2793
- package/src/dlob/DLOBNode.ts +0 -305
- package/src/dlob/DLOBSubscriber.ts +0 -269
- package/src/dlob/NodeList.ts +0 -244
- package/src/dlob/orderBookLevels.ts +0 -695
- package/src/dlob/types.ts +0 -37
- package/src/events/eventList.ts +0 -114
- package/src/events/eventSubscriber.ts +0 -521
- package/src/events/eventsServerLogProvider.ts +0 -189
- package/src/events/fetchLogs.ts +0 -219
- package/src/events/parse.ts +0 -271
- package/src/events/pollingLogProvider.ts +0 -113
- package/src/events/sort.ts +0 -51
- package/src/events/txEventCache.ts +0 -92
- package/src/events/types.ts +0 -337
- package/src/events/webSocketLogProvider.ts +0 -152
- package/src/factory/bigNum.ts +0 -709
- package/src/factory/oracleClient.ts +0 -73
- package/src/idl/pyth.json +0 -142
- package/src/idl/pyth.ts +0 -97
- package/src/idl/pyth_solana_receiver.json +0 -628
- package/src/idl/token_faucet.json +0 -229
- package/src/idl/token_faucet.ts +0 -197
- package/src/idl/velocity.json +0 -23974
- package/src/idl/velocity.ts +0 -23980
- package/src/index.ts +0 -150
- package/src/indicative-quotes/indicativeQuotesSender.ts +0 -233
- package/src/isomorphic/README.md +0 -19
- package/src/isomorphic/anchor.browser.ts +0 -44
- package/src/isomorphic/anchor.node.ts +0 -1
- package/src/isomorphic/anchor.ts +0 -1
- package/src/isomorphic/anchor29.browser.ts +0 -24
- package/src/isomorphic/anchor29.node.ts +0 -1
- package/src/isomorphic/anchor29.ts +0 -1
- package/src/isomorphic/grpc.browser.ts +0 -4
- package/src/isomorphic/grpc.node.ts +0 -130
- package/src/isomorphic/grpc.ts +0 -1
- package/src/jupiter/jupiterClient.ts +0 -502
- package/src/keypair.ts +0 -32
- package/src/margin/README.md +0 -138
- package/src/marginCalculation.ts +0 -407
- package/src/marinade/idl/idl.json +0 -1962
- package/src/marinade/index.ts +0 -73
- package/src/marinade/types.ts +0 -3925
- package/src/math/amm.ts +0 -1758
- package/src/math/auction.ts +0 -480
- package/src/math/bankruptcy.ts +0 -138
- package/src/math/builder.ts +0 -130
- package/src/math/conversion.ts +0 -45
- package/src/math/exchangeStatus.ts +0 -261
- package/src/math/funding.ts +0 -498
- package/src/math/insurance.ts +0 -171
- package/src/math/liquidation.ts +0 -433
- package/src/math/margin.ts +0 -327
- package/src/math/market.ts +0 -487
- package/src/math/oracles.ts +0 -477
- package/src/math/orders.ts +0 -500
- package/src/math/position.ts +0 -381
- package/src/math/repeg.ts +0 -223
- package/src/math/spotBalance.ts +0 -996
- package/src/math/spotMarket.ts +0 -115
- package/src/math/spotPosition.ts +0 -263
- package/src/math/state.ts +0 -71
- package/src/math/superStake.ts +0 -602
- package/src/math/tiers.ts +0 -73
- package/src/math/trade.ts +0 -879
- package/src/math/utils.ts +0 -183
- package/src/memcmp.ts +0 -279
- package/src/oracles/oracleClientCache.ts +0 -41
- package/src/oracles/oracleId.ts +0 -99
- package/src/oracles/prelaunchOracleClient.ts +0 -63
- package/src/oracles/pythClient.ts +0 -125
- package/src/oracles/pythLazerClient.ts +0 -141
- package/src/oracles/quoteAssetOracleClient.ts +0 -43
- package/src/oracles/strictOraclePrice.ts +0 -40
- package/src/oracles/types.ts +0 -82
- package/src/oracles/utils.ts +0 -45
- package/src/orderParams.ts +0 -117
- package/src/orderSubscriber/OrderSubscriber.ts +0 -378
- package/src/orderSubscriber/PollingSubscription.ts +0 -50
- package/src/orderSubscriber/WebsocketSubscription.ts +0 -137
- package/src/orderSubscriber/grpcSubscription.ts +0 -155
- package/src/orderSubscriber/index.ts +0 -7
- package/src/orderSubscriber/types.ts +0 -64
- package/src/priorityFee/averageOverSlotsStrategy.ts +0 -17
- package/src/priorityFee/averageStrategy.ts +0 -13
- package/src/priorityFee/ewmaStrategy.ts +0 -51
- package/src/priorityFee/heliusPriorityFeeMethod.ts +0 -68
- package/src/priorityFee/index.ts +0 -16
- package/src/priorityFee/maxOverSlotsStrategy.ts +0 -18
- package/src/priorityFee/maxStrategy.ts +0 -8
- package/src/priorityFee/priorityFeeSubscriber.ts +0 -328
- package/src/priorityFee/priorityFeeSubscriberMap.ts +0 -134
- package/src/priorityFee/solanaPriorityFeeMethod.ts +0 -46
- package/src/priorityFee/types.ts +0 -82
- package/src/priorityFee/velocityPriorityFeeMethod.ts +0 -53
- package/src/pyth/constants.ts +0 -9
- package/src/pyth/index.ts +0 -15
- package/src/pyth/pythLazerSubscriber.ts +0 -365
- package/src/pyth/types.ts +0 -4451
- package/src/pyth/utils.ts +0 -13
- package/src/slot/SlotSubscriber.ts +0 -126
- package/src/slot/SlothashSubscriber.ts +0 -163
- package/src/swap/UnifiedSwapClient.ts +0 -315
- package/src/swift/grpcSignedMsgUserAccountSubscriber.ts +0 -81
- package/src/swift/index.ts +0 -10
- package/src/swift/signedMsgUserAccountSubscriber.ts +0 -251
- package/src/swift/swiftOrderSubscriber.ts +0 -351
- package/src/testClient.ts +0 -42
- package/src/titan/titanClient.ts +0 -438
- package/src/token/index.ts +0 -13
- package/src/tokenFaucet.ts +0 -296
- package/src/tx/baseTxSender.ts +0 -651
- package/src/tx/blockhashFetcher/baseBlockhashFetcher.ts +0 -31
- package/src/tx/blockhashFetcher/cachedBlockhashFetcher.ts +0 -105
- package/src/tx/blockhashFetcher/types.ts +0 -9
- package/src/tx/fastSingleTxSender.ts +0 -200
- package/src/tx/forwardOnlyTxSender.ts +0 -193
- package/src/tx/priorityFeeCalculator.ts +0 -117
- package/src/tx/reportTransactionError.ts +0 -176
- package/src/tx/retryTxSender.ts +0 -177
- package/src/tx/txHandler.ts +0 -1009
- package/src/tx/txParamProcessor.ts +0 -225
- package/src/tx/types.ts +0 -117
- package/src/tx/utils.ts +0 -133
- package/src/tx/whileValidTxSender.ts +0 -377
- package/src/types.ts +0 -2575
- package/src/user.ts +0 -5316
- package/src/userConfig.ts +0 -38
- package/src/userMap/PollingSubscription.ts +0 -61
- package/src/userMap/WebsocketSubscription.ts +0 -93
- package/src/userMap/grpcSubscription.ts +0 -93
- package/src/userMap/referrerMap.ts +0 -360
- package/src/userMap/revenueShareEscrowMap.ts +0 -342
- package/src/userMap/userMap.ts +0 -784
- package/src/userMap/userMapConfig.ts +0 -82
- package/src/userMap/userStatsMap.ts +0 -393
- package/src/userName.ts +0 -37
- package/src/userStats.ts +0 -159
- package/src/userStatsConfig.ts +0 -35
- package/src/util/TransactionConfirmationManager.ts +0 -333
- package/src/util/chainClock.ts +0 -65
- package/src/util/computeUnits.ts +0 -101
- package/src/util/digest.ts +0 -33
- package/src/util/ed25519Utils.ts +0 -95
- package/src/util/promiseTimeout.ts +0 -23
- package/src/velocityClient.ts +0 -14802
- package/src/velocityClientConfig.ts +0 -119
- package/src/wallet.ts +0 -91
- package/tests/VelocityCore/builder_escrow.test.ts +0 -121
- package/tests/VelocityCore/decode.test.ts +0 -16
- package/tests/VelocityCore/fill_trigger.test.ts +0 -73
- package/tests/VelocityCore/instructions.test.ts +0 -46
- package/tests/VelocityCore/pdas.test.ts +0 -30
- package/tests/VelocityCore/perp_orders.test.ts +0 -205
- package/tests/VelocityCore/remainingAccounts.test.ts +0 -72
- package/tests/VelocityCore/settlement_liquidation.test.ts +0 -69
- package/tests/accounts/customizedCadenceBulkAccountLoader.test.ts +0 -211
- package/tests/amm/test.ts +0 -2402
- package/tests/auctions/test.ts +0 -81
- package/tests/bn/test.ts +0 -355
- package/tests/builder/builderFee.test.ts +0 -42
- package/tests/ci/verifyConstants.ts +0 -393
- package/tests/decode/test.ts +0 -262
- package/tests/decode/userAccountBufferStrings.ts +0 -102
- package/tests/dlob/helpers.ts +0 -748
- package/tests/dlob/test.ts +0 -6969
- package/tests/dlob/tickSizeStandardization.ts +0 -545
- package/tests/events/parseLogsForCuUsage.ts +0 -139
- package/tests/exchangeStatus/test.ts +0 -45
- package/tests/insurance/test.ts +0 -40
- package/tests/liquidation/test.ts +0 -125
- package/tests/oracles/mmOracleGate.test.ts +0 -379
- package/tests/oracles/pythPegSnap.test.ts +0 -76
- package/tests/sdkParity/enumParity.test.ts +0 -84
- package/tests/sdkParity/marginCategoryFill.test.ts +0 -143
- package/tests/sdkParity/memcmpOffsets.test.ts +0 -139
- package/tests/spot/test.ts +0 -281
- package/tests/tx/TransactionConfirmationManager.test.ts +0 -312
- package/tests/tx/cachedBlockhashFetcher.test.ts +0 -96
- package/tests/tx/priorityFeeCalculator.ts +0 -77
- package/tests/tx/priorityFeeStrategy.ts +0 -95
- package/tests/user/bankruptcy.ts +0 -165
- package/tests/user/feeAndWithdrawLimits.ts +0 -284
- package/tests/user/getMarginCalculation.ts +0 -586
- package/tests/user/helpers.ts +0 -184
- package/tests/user/liquidations.ts +0 -129
- package/tests/user/marginCalculations.test.ts +0 -321
- package/tests/user/test.ts +0 -833
- package/tsconfig.browser.json +0 -18
- package/tsconfig.json +0 -36
|
@@ -1,897 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
AccountSubscriber,
|
|
3
|
-
DataAndSlot,
|
|
4
|
-
DelistedMarketSetting,
|
|
5
|
-
VelocityClientAccountEvents,
|
|
6
|
-
VelocityClientAccountSubscriber,
|
|
7
|
-
NotSubscribedError,
|
|
8
|
-
ResubOpts,
|
|
9
|
-
} from './types';
|
|
10
|
-
import { assertDataAndSlot } from './utils';
|
|
11
|
-
import {
|
|
12
|
-
isVariant,
|
|
13
|
-
PerpMarketAccount,
|
|
14
|
-
SpotMarketAccount,
|
|
15
|
-
StateAccount,
|
|
16
|
-
} from '../types';
|
|
17
|
-
import StrictEventEmitter from 'strict-event-emitter-types';
|
|
18
|
-
import { EventEmitter } from 'events';
|
|
19
|
-
import {
|
|
20
|
-
getVelocityStateAccountPublicKey,
|
|
21
|
-
getPerpMarketPublicKey,
|
|
22
|
-
getSpotMarketPublicKey,
|
|
23
|
-
} from '../addresses/pda';
|
|
24
|
-
import { Context, PublicKey } from '@solana/web3.js';
|
|
25
|
-
import {
|
|
26
|
-
Commitment,
|
|
27
|
-
SolanaRpcSubscriptionsApi,
|
|
28
|
-
Rpc,
|
|
29
|
-
RpcSubscriptions,
|
|
30
|
-
createSolanaClient,
|
|
31
|
-
} from 'gill';
|
|
32
|
-
import { OracleInfo, OraclePriceData } from '../oracles/types';
|
|
33
|
-
import { OracleClientCache } from '../oracles/oracleClientCache';
|
|
34
|
-
import { QUOTE_ORACLE_PRICE_DATA } from '../oracles/quoteAssetOracleClient';
|
|
35
|
-
import { VelocityProgram, findAllMarketAndOracles } from '../config';
|
|
36
|
-
import { findDelistedPerpMarketsAndOracles } from './utils';
|
|
37
|
-
import {
|
|
38
|
-
getOracleId,
|
|
39
|
-
getPublicKeyAndSourceFromOracleId,
|
|
40
|
-
} from '../oracles/oracleId';
|
|
41
|
-
import { OracleSource } from '../types';
|
|
42
|
-
import {
|
|
43
|
-
getPerpMarketAccountsFilter,
|
|
44
|
-
getSpotMarketAccountsFilter,
|
|
45
|
-
} from '../memcmp';
|
|
46
|
-
import { WebSocketProgramAccountsSubscriberV2 } from './webSocketProgramAccountsSubscriberV2';
|
|
47
|
-
import { WebSocketAccountSubscriberV2 } from './webSocketAccountSubscriberV2';
|
|
48
|
-
const ORACLE_DEFAULT_ID = getOracleId(
|
|
49
|
-
PublicKey.default,
|
|
50
|
-
OracleSource.QUOTE_ASSET
|
|
51
|
-
);
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* `VelocityClientAccountSubscriber` variant that, unlike `WebSocketVelocityClientAccountSubscriber`
|
|
55
|
-
* (one `WebSocketAccountSubscriber` per market), multiplexes all perp markets onto a single
|
|
56
|
-
* `WebSocketProgramAccountsSubscriberV2` program-account stream and all spot markets onto a
|
|
57
|
-
* second — two WebSocket subscriptions total instead of one per market. `State` and each oracle
|
|
58
|
-
* still get their own `WebSocketAccountSubscriberV2`. Lower connection overhead at scale;
|
|
59
|
-
* `addPerpMarket`/`addSpotMarket` are no-ops here since new markets simply arrive automatically
|
|
60
|
-
* over the existing program-account stream rather than needing an explicit new subscription.
|
|
61
|
-
*/
|
|
62
|
-
export class WebSocketVelocityClientAccountSubscriberV2
|
|
63
|
-
implements VelocityClientAccountSubscriber
|
|
64
|
-
{
|
|
65
|
-
isSubscribed: boolean;
|
|
66
|
-
program: VelocityProgram;
|
|
67
|
-
commitment?: Commitment;
|
|
68
|
-
perpMarketIndexes: number[];
|
|
69
|
-
spotMarketIndexes: number[];
|
|
70
|
-
oracleInfos: OracleInfo[];
|
|
71
|
-
oracleClientCache = new OracleClientCache();
|
|
72
|
-
|
|
73
|
-
resubOpts?: ResubOpts;
|
|
74
|
-
shouldFindAllMarketsAndOracles: boolean;
|
|
75
|
-
skipInitialData: boolean = true;
|
|
76
|
-
|
|
77
|
-
eventEmitter: StrictEventEmitter<EventEmitter, VelocityClientAccountEvents>;
|
|
78
|
-
stateAccountSubscriber?: WebSocketAccountSubscriberV2<StateAccount>;
|
|
79
|
-
private _perpMarketAllAccountsSubscriber?: WebSocketProgramAccountsSubscriberV2<PerpMarketAccount>;
|
|
80
|
-
get perpMarketAllAccountsSubscriber(): WebSocketProgramAccountsSubscriberV2<PerpMarketAccount> {
|
|
81
|
-
if (!this._perpMarketAllAccountsSubscriber) {
|
|
82
|
-
throw new Error(
|
|
83
|
-
'perpMarketAllAccountsSubscriber accessed before subscribe()'
|
|
84
|
-
);
|
|
85
|
-
}
|
|
86
|
-
return this._perpMarketAllAccountsSubscriber;
|
|
87
|
-
}
|
|
88
|
-
set perpMarketAllAccountsSubscriber(
|
|
89
|
-
subscriber: WebSocketProgramAccountsSubscriberV2<PerpMarketAccount>
|
|
90
|
-
) {
|
|
91
|
-
this._perpMarketAllAccountsSubscriber = subscriber;
|
|
92
|
-
}
|
|
93
|
-
perpMarketAccountLatestData = new Map<
|
|
94
|
-
number,
|
|
95
|
-
DataAndSlot<PerpMarketAccount>
|
|
96
|
-
>();
|
|
97
|
-
private _spotMarketAllAccountsSubscriber?: WebSocketProgramAccountsSubscriberV2<SpotMarketAccount>;
|
|
98
|
-
get spotMarketAllAccountsSubscriber(): WebSocketProgramAccountsSubscriberV2<SpotMarketAccount> {
|
|
99
|
-
if (!this._spotMarketAllAccountsSubscriber) {
|
|
100
|
-
throw new Error(
|
|
101
|
-
'spotMarketAllAccountsSubscriber accessed before subscribe()'
|
|
102
|
-
);
|
|
103
|
-
}
|
|
104
|
-
return this._spotMarketAllAccountsSubscriber;
|
|
105
|
-
}
|
|
106
|
-
set spotMarketAllAccountsSubscriber(
|
|
107
|
-
subscriber: WebSocketProgramAccountsSubscriberV2<SpotMarketAccount>
|
|
108
|
-
) {
|
|
109
|
-
this._spotMarketAllAccountsSubscriber = subscriber;
|
|
110
|
-
}
|
|
111
|
-
spotMarketAccountLatestData = new Map<
|
|
112
|
-
number,
|
|
113
|
-
DataAndSlot<SpotMarketAccount>
|
|
114
|
-
>();
|
|
115
|
-
perpOracleMap = new Map<number, PublicKey>();
|
|
116
|
-
perpOracleStringMap = new Map<number, string>();
|
|
117
|
-
spotOracleMap = new Map<number, PublicKey>();
|
|
118
|
-
spotOracleStringMap = new Map<number, string>();
|
|
119
|
-
oracleSubscribers = new Map<string, AccountSubscriber<OraclePriceData>>();
|
|
120
|
-
delistedMarketSetting: DelistedMarketSetting;
|
|
121
|
-
|
|
122
|
-
initialPerpMarketAccountData: Map<number, PerpMarketAccount> = new Map();
|
|
123
|
-
initialSpotMarketAccountData: Map<number, SpotMarketAccount> = new Map();
|
|
124
|
-
initialOraclePriceData: Map<string, OraclePriceData> = new Map();
|
|
125
|
-
|
|
126
|
-
protected isSubscribing = false;
|
|
127
|
-
private subscriptionPromiseResolver: (val: boolean) => void = () => {};
|
|
128
|
-
protected subscriptionPromise: Promise<boolean> = Promise.resolve(false);
|
|
129
|
-
|
|
130
|
-
private rpc: Rpc<any>;
|
|
131
|
-
private rpcSubscriptions: RpcSubscriptions<SolanaRpcSubscriptionsApi> &
|
|
132
|
-
string;
|
|
133
|
-
|
|
134
|
-
/**
|
|
135
|
-
* @param program Anchor program used to derive PDAs, decode accounts, and resolve oracle clients.
|
|
136
|
-
* @param perpMarketIndexes Perp market indexes to track, if `shouldFindAllMarketsAndOracles` is false. Only used to derive the initial pubkeys handed to the perp program-account subscriber; new markets arrive automatically thereafter.
|
|
137
|
-
* @param spotMarketIndexes Spot market indexes to track, if `shouldFindAllMarketsAndOracles` is false. Same caveat as `perpMarketIndexes`.
|
|
138
|
-
* @param oracleInfos Oracles to track up front, if `shouldFindAllMarketsAndOracles` is false.
|
|
139
|
-
* @param shouldFindAllMarketsAndOracles If true, `subscribe()` first discovers every market/oracle from on-chain state, ignoring the index/info args above.
|
|
140
|
-
* @param delistedMarketSetting Behavior applied to delisted perp markets/oracles after subscribing; see `DelistedMarketSetting`.
|
|
141
|
-
* @param resubOpts Resubscription watchdog options passed to the underlying program-account and per-oracle subscribers.
|
|
142
|
-
* @param commitment Commitment for every subscription; defaults to the provider's configured commitment.
|
|
143
|
-
* @param skipInitialData Currently unused by `subscribe()`/`setInitialData()` (the field is set but never read); defaults to `false`.
|
|
144
|
-
*/
|
|
145
|
-
public constructor(
|
|
146
|
-
program: VelocityProgram,
|
|
147
|
-
perpMarketIndexes: number[],
|
|
148
|
-
spotMarketIndexes: number[],
|
|
149
|
-
oracleInfos: OracleInfo[],
|
|
150
|
-
shouldFindAllMarketsAndOracles: boolean,
|
|
151
|
-
delistedMarketSetting: DelistedMarketSetting,
|
|
152
|
-
resubOpts?: ResubOpts,
|
|
153
|
-
commitment?: Commitment,
|
|
154
|
-
skipInitialData?: boolean
|
|
155
|
-
) {
|
|
156
|
-
this.isSubscribed = false;
|
|
157
|
-
this.program = program;
|
|
158
|
-
this.eventEmitter = new EventEmitter();
|
|
159
|
-
this.perpMarketIndexes = perpMarketIndexes;
|
|
160
|
-
this.spotMarketIndexes = spotMarketIndexes;
|
|
161
|
-
this.oracleInfos = oracleInfos;
|
|
162
|
-
this.shouldFindAllMarketsAndOracles = shouldFindAllMarketsAndOracles;
|
|
163
|
-
this.delistedMarketSetting = delistedMarketSetting;
|
|
164
|
-
this.resubOpts = resubOpts;
|
|
165
|
-
this.commitment = commitment;
|
|
166
|
-
this.skipInitialData = skipInitialData ?? false;
|
|
167
|
-
|
|
168
|
-
const { rpc, rpcSubscriptions } = createSolanaClient({
|
|
169
|
-
urlOrMoniker: this.program.provider.connection.rpcEndpoint,
|
|
170
|
-
});
|
|
171
|
-
this.rpc = rpc;
|
|
172
|
-
this.rpcSubscriptions = rpcSubscriptions;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
/**
|
|
176
|
-
* Derives all tracked perp/spot market pubkeys (or discovers them via `findAllMarketAndOracles`
|
|
177
|
-
* if `shouldFindAllMarketsAndOracles` is set), then in parallel: opens the perp and spot
|
|
178
|
-
* `WebSocketProgramAccountsSubscriberV2` streams, subscribes the `State` account, and seeds +
|
|
179
|
-
* subscribes every oracle. Applies `delistedMarketSetting` afterward. Idempotent: a no-op if
|
|
180
|
-
* already subscribed, and concurrent calls while a subscribe is in flight share the same
|
|
181
|
-
* result via `subscriptionPromise` rather than issuing duplicate subscriptions.
|
|
182
|
-
* @returns `true` on success; `false` if any step throws (subscription state is left partially applied in that case, and `isSubscribed` remains `false`).
|
|
183
|
-
*/
|
|
184
|
-
public async subscribe(): Promise<boolean> {
|
|
185
|
-
try {
|
|
186
|
-
const startTime = performance.now();
|
|
187
|
-
if (this.isSubscribed) {
|
|
188
|
-
console.log(
|
|
189
|
-
`[PROFILING] WebSocketVelocityClientAccountSubscriberV2.subscribe() skipped - already subscribed`
|
|
190
|
-
);
|
|
191
|
-
return true;
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
if (this.isSubscribing) {
|
|
195
|
-
console.log(
|
|
196
|
-
`[PROFILING] WebSocketVelocityClientAccountSubscriberV2.subscribe() waiting for existing subscription`
|
|
197
|
-
);
|
|
198
|
-
return await this.subscriptionPromise;
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
this.isSubscribing = true;
|
|
202
|
-
|
|
203
|
-
// Initialize subscriptionPromiseResolver to a no-op function
|
|
204
|
-
this.subscriptionPromiseResolver = () => {};
|
|
205
|
-
|
|
206
|
-
this.subscriptionPromise = new Promise((res) => {
|
|
207
|
-
this.subscriptionPromiseResolver = res;
|
|
208
|
-
});
|
|
209
|
-
|
|
210
|
-
const [perpMarketAccountPubkeys, spotMarketAccountPubkeys] =
|
|
211
|
-
await Promise.all([
|
|
212
|
-
Promise.all(
|
|
213
|
-
this.perpMarketIndexes.map((marketIndex) =>
|
|
214
|
-
getPerpMarketPublicKey(this.program.programId, marketIndex)
|
|
215
|
-
)
|
|
216
|
-
),
|
|
217
|
-
Promise.all(
|
|
218
|
-
this.spotMarketIndexes.map((marketIndex) =>
|
|
219
|
-
getSpotMarketPublicKey(this.program.programId, marketIndex)
|
|
220
|
-
)
|
|
221
|
-
),
|
|
222
|
-
]);
|
|
223
|
-
|
|
224
|
-
// Profile findAllMarketsAndOracles if needed
|
|
225
|
-
let findAllMarketsDuration = 0;
|
|
226
|
-
if (this.shouldFindAllMarketsAndOracles) {
|
|
227
|
-
const findAllMarketsStartTime = performance.now();
|
|
228
|
-
const {
|
|
229
|
-
perpMarketIndexes,
|
|
230
|
-
perpMarketAccounts,
|
|
231
|
-
spotMarketIndexes,
|
|
232
|
-
spotMarketAccounts,
|
|
233
|
-
oracleInfos,
|
|
234
|
-
} = await findAllMarketAndOracles(this.program);
|
|
235
|
-
this.perpMarketIndexes = perpMarketIndexes;
|
|
236
|
-
this.spotMarketIndexes = spotMarketIndexes;
|
|
237
|
-
this.oracleInfos = oracleInfos;
|
|
238
|
-
// front run and set the initial data here to save extra gma call in set initial data
|
|
239
|
-
this.initialPerpMarketAccountData = new Map(
|
|
240
|
-
perpMarketAccounts.map((market) => [market.marketIndex, market])
|
|
241
|
-
);
|
|
242
|
-
this.initialSpotMarketAccountData = new Map(
|
|
243
|
-
spotMarketAccounts.map((market) => [market.marketIndex, market])
|
|
244
|
-
);
|
|
245
|
-
const findAllMarketsEndTime = performance.now();
|
|
246
|
-
findAllMarketsDuration =
|
|
247
|
-
findAllMarketsEndTime - findAllMarketsStartTime;
|
|
248
|
-
console.log(
|
|
249
|
-
`[PROFILING] findAllMarketAndOracles completed in ${findAllMarketsDuration.toFixed(
|
|
250
|
-
2
|
|
251
|
-
)}ms (${perpMarketAccounts.length} perp markets, ${
|
|
252
|
-
spotMarketAccounts.length
|
|
253
|
-
} spot markets)`
|
|
254
|
-
);
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
// Create subscribers
|
|
258
|
-
this.perpMarketAllAccountsSubscriber =
|
|
259
|
-
new WebSocketProgramAccountsSubscriberV2<PerpMarketAccount>(
|
|
260
|
-
'PerpMarketAccountsSubscriber',
|
|
261
|
-
'perpMarket',
|
|
262
|
-
this.program,
|
|
263
|
-
(
|
|
264
|
-
this.program.account as any
|
|
265
|
-
).perpMarket.coder.accounts.decodeUnchecked.bind(
|
|
266
|
-
(this.program.account as any).perpMarket.coder.accounts
|
|
267
|
-
),
|
|
268
|
-
{
|
|
269
|
-
filters: [getPerpMarketAccountsFilter()],
|
|
270
|
-
commitment: this.commitment,
|
|
271
|
-
},
|
|
272
|
-
this.resubOpts,
|
|
273
|
-
perpMarketAccountPubkeys // because we pass these in, it will monitor these accounts and fetch them right away
|
|
274
|
-
);
|
|
275
|
-
|
|
276
|
-
this.spotMarketAllAccountsSubscriber =
|
|
277
|
-
new WebSocketProgramAccountsSubscriberV2<SpotMarketAccount>(
|
|
278
|
-
'SpotMarketAccountsSubscriber',
|
|
279
|
-
'spotMarket',
|
|
280
|
-
this.program,
|
|
281
|
-
(
|
|
282
|
-
this.program.account as any
|
|
283
|
-
).spotMarket.coder.accounts.decodeUnchecked.bind(
|
|
284
|
-
(this.program.account as any).spotMarket.coder.accounts
|
|
285
|
-
),
|
|
286
|
-
{
|
|
287
|
-
filters: [getSpotMarketAccountsFilter()],
|
|
288
|
-
commitment: this.commitment,
|
|
289
|
-
},
|
|
290
|
-
this.resubOpts,
|
|
291
|
-
spotMarketAccountPubkeys // because we pass these in, it will monitor these accounts and fetch them right away
|
|
292
|
-
);
|
|
293
|
-
|
|
294
|
-
// Run all subscriptions in parallel
|
|
295
|
-
await Promise.all([
|
|
296
|
-
// Perp market subscription
|
|
297
|
-
this.perpMarketAllAccountsSubscriber.subscribe(
|
|
298
|
-
(
|
|
299
|
-
_accountId: PublicKey,
|
|
300
|
-
data: PerpMarketAccount,
|
|
301
|
-
context: Context,
|
|
302
|
-
_buffer: Buffer
|
|
303
|
-
) => {
|
|
304
|
-
if (
|
|
305
|
-
this.delistedMarketSetting !== DelistedMarketSetting.Subscribe &&
|
|
306
|
-
isVariant(data.status, 'delisted')
|
|
307
|
-
) {
|
|
308
|
-
return;
|
|
309
|
-
}
|
|
310
|
-
this.perpMarketAccountLatestData.set(data.marketIndex, {
|
|
311
|
-
data,
|
|
312
|
-
slot: context.slot,
|
|
313
|
-
});
|
|
314
|
-
this.eventEmitter.emit('perpMarketAccountUpdate', data);
|
|
315
|
-
this.eventEmitter.emit('update');
|
|
316
|
-
}
|
|
317
|
-
),
|
|
318
|
-
// Spot market subscription
|
|
319
|
-
this.spotMarketAllAccountsSubscriber.subscribe(
|
|
320
|
-
(
|
|
321
|
-
_accountId: PublicKey,
|
|
322
|
-
data: SpotMarketAccount,
|
|
323
|
-
context: Context,
|
|
324
|
-
_buffer: Buffer
|
|
325
|
-
) => {
|
|
326
|
-
if (
|
|
327
|
-
this.delistedMarketSetting !== DelistedMarketSetting.Subscribe &&
|
|
328
|
-
isVariant(data.status, 'delisted')
|
|
329
|
-
) {
|
|
330
|
-
return;
|
|
331
|
-
}
|
|
332
|
-
this.spotMarketAccountLatestData.set(data.marketIndex, {
|
|
333
|
-
data,
|
|
334
|
-
slot: context.slot,
|
|
335
|
-
});
|
|
336
|
-
this.eventEmitter.emit('spotMarketAccountUpdate', data);
|
|
337
|
-
this.eventEmitter.emit('update');
|
|
338
|
-
}
|
|
339
|
-
),
|
|
340
|
-
// State account subscription
|
|
341
|
-
(async () => {
|
|
342
|
-
const statePublicKey = await getVelocityStateAccountPublicKey(
|
|
343
|
-
this.program.programId
|
|
344
|
-
);
|
|
345
|
-
this.stateAccountSubscriber = new WebSocketAccountSubscriberV2(
|
|
346
|
-
'state',
|
|
347
|
-
this.program,
|
|
348
|
-
statePublicKey,
|
|
349
|
-
undefined,
|
|
350
|
-
undefined,
|
|
351
|
-
this.commitment as Commitment,
|
|
352
|
-
this.rpcSubscriptions,
|
|
353
|
-
this.rpc
|
|
354
|
-
);
|
|
355
|
-
await Promise.all([
|
|
356
|
-
this.stateAccountSubscriber.fetch(),
|
|
357
|
-
this.stateAccountSubscriber.subscribe((data: StateAccount) => {
|
|
358
|
-
this.eventEmitter.emit('stateAccountUpdate', data);
|
|
359
|
-
this.eventEmitter.emit('update');
|
|
360
|
-
}),
|
|
361
|
-
]);
|
|
362
|
-
})(),
|
|
363
|
-
(async () => {
|
|
364
|
-
await this.setInitialData();
|
|
365
|
-
const subscribeToOraclesStartTime = performance.now();
|
|
366
|
-
await this.subscribeToOracles();
|
|
367
|
-
const subscribeToOraclesEndTime = performance.now();
|
|
368
|
-
const duration =
|
|
369
|
-
subscribeToOraclesEndTime - subscribeToOraclesStartTime;
|
|
370
|
-
return duration;
|
|
371
|
-
})(),
|
|
372
|
-
]);
|
|
373
|
-
|
|
374
|
-
// const initialPerpMarketDataFromLatestData = new Map(
|
|
375
|
-
// Array.from(this.perpMarketAccountLatestData.values()).map((data) => [
|
|
376
|
-
// data.data.marketIndex,
|
|
377
|
-
// data.data,
|
|
378
|
-
// ])
|
|
379
|
-
// );
|
|
380
|
-
// const initialSpotMarketDataFromLatestData = new Map(
|
|
381
|
-
// Array.from(this.spotMarketAccountLatestData.values()).map((data) => [
|
|
382
|
-
// data.data.marketIndex,
|
|
383
|
-
// data.data,
|
|
384
|
-
// ])
|
|
385
|
-
// );
|
|
386
|
-
// this.initialPerpMarketAccountData = initialPerpMarketDataFromLatestData;
|
|
387
|
-
// this.initialSpotMarketAccountData = initialSpotMarketDataFromLatestData;
|
|
388
|
-
|
|
389
|
-
await this.handleDelistedMarketOracles();
|
|
390
|
-
|
|
391
|
-
await Promise.all([this.setPerpOracleMap(), this.setSpotOracleMap()]);
|
|
392
|
-
|
|
393
|
-
this.eventEmitter.emit('update');
|
|
394
|
-
// delete initial data
|
|
395
|
-
this.removeInitialData();
|
|
396
|
-
|
|
397
|
-
const totalDuration = performance.now() - startTime;
|
|
398
|
-
console.log(
|
|
399
|
-
`[PROFILING] WebSocketVelocityClientAccountSubscriberV2.subscribe() completed in ${totalDuration.toFixed(
|
|
400
|
-
2
|
|
401
|
-
)}ms`
|
|
402
|
-
);
|
|
403
|
-
|
|
404
|
-
// Resolve the subscription promise
|
|
405
|
-
this.isSubscribed = true;
|
|
406
|
-
this.isSubscribing = false;
|
|
407
|
-
// Before calling subscriptionPromiseResolver, check if it's defined
|
|
408
|
-
this.subscriptionPromiseResolver(true);
|
|
409
|
-
|
|
410
|
-
return true;
|
|
411
|
-
} catch (error) {
|
|
412
|
-
console.error('Subscription failed:', error);
|
|
413
|
-
// Tear down any child subscribers that were created before the failure so a
|
|
414
|
-
// subsequent subscribe() attempt doesn't leak live connections; isSubscribed is
|
|
415
|
-
// still false at this point, so unsubscribe() alone would otherwise skip this.
|
|
416
|
-
await Promise.all([
|
|
417
|
-
this.stateAccountSubscriber?.unsubscribe(),
|
|
418
|
-
this.unsubscribeFromMarketAccounts(),
|
|
419
|
-
this.unsubscribeFromSpotMarketAccounts(),
|
|
420
|
-
this.unsubscribeFromOracles(),
|
|
421
|
-
]).catch((teardownError) => {
|
|
422
|
-
console.error(
|
|
423
|
-
'Error tearing down partial subscription:',
|
|
424
|
-
teardownError
|
|
425
|
-
);
|
|
426
|
-
});
|
|
427
|
-
this.isSubscribing = false;
|
|
428
|
-
this.subscriptionPromiseResolver(false);
|
|
429
|
-
return false;
|
|
430
|
-
}
|
|
431
|
-
}
|
|
432
|
-
|
|
433
|
-
chunks = <T>(array: readonly T[], size: number): T[][] => {
|
|
434
|
-
const result: T[][] = [];
|
|
435
|
-
for (let i = 0; i < array.length; i += size) {
|
|
436
|
-
result.push(array.slice(i, i + size));
|
|
437
|
-
}
|
|
438
|
-
return result;
|
|
439
|
-
};
|
|
440
|
-
|
|
441
|
-
/** Re-runs `setInitialData()`, re-fetching and re-emitting oracle price data. Does not re-fetch perp/spot market or `State` accounts — those are kept current via their live WebSocket streams. */
|
|
442
|
-
public async fetch(): Promise<void> {
|
|
443
|
-
await this.setInitialData();
|
|
444
|
-
}
|
|
445
|
-
|
|
446
|
-
/**
|
|
447
|
-
* This is a no-op method that always returns true.
|
|
448
|
-
* Unlike the previous implementation, we don't need to manually subscribe to individual perp markets
|
|
449
|
-
* because we automatically receive updates for all program account changes via a single websocket subscription.
|
|
450
|
-
* This means any new perp markets will automatically be included without explicit subscription.
|
|
451
|
-
* @param marketIndex The perp market index to add (unused)
|
|
452
|
-
* @returns Promise that resolves to true
|
|
453
|
-
*/
|
|
454
|
-
public addPerpMarket(_marketIndex: number): Promise<boolean> {
|
|
455
|
-
return Promise.resolve(true);
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
/**
|
|
459
|
-
* This is a no-op method that always returns true.
|
|
460
|
-
* Unlike the previous implementation, we don't need to manually subscribe to individual spot markets
|
|
461
|
-
* because we automatically receive updates for all program account changes via a single websocket subscription.
|
|
462
|
-
* This means any new spot markets will automatically be included without explicit subscription.
|
|
463
|
-
* @param marketIndex The spot market index to add (unused)
|
|
464
|
-
* @returns Promise that resolves to true
|
|
465
|
-
*/
|
|
466
|
-
public addSpotMarket(_marketIndex: number): Promise<boolean> {
|
|
467
|
-
return Promise.resolve(true);
|
|
468
|
-
}
|
|
469
|
-
|
|
470
|
-
// TODO: need more options to skip loading perp market and spot market data. Because of how we fetch within the program account subscribers, I am commenting this all out
|
|
471
|
-
/**
|
|
472
|
-
* Batch-fetches every tracked oracle account via chunked `getMultipleAccountsInfo` calls (100
|
|
473
|
-
* pubkeys per chunk), decodes each with the source-appropriate `OracleClient`, stashes the
|
|
474
|
-
* results in `initialOraclePriceData`, and immediately emits `oraclePriceUpdate`/`update` for
|
|
475
|
-
* each. Unlike the v1 subscriber's `setInitialData`, does not seed perp/spot market data —
|
|
476
|
-
* those markets are seeded directly by the program-account subscribers' own initial-account
|
|
477
|
-
* list instead.
|
|
478
|
-
*/
|
|
479
|
-
async setInitialData(): Promise<void> {
|
|
480
|
-
const connection = this.program.provider.connection;
|
|
481
|
-
// Profile oracle initial data setup
|
|
482
|
-
const oracleSetupStartTime = performance.now();
|
|
483
|
-
const oracleAccountPubkeyChunks = this.chunks(
|
|
484
|
-
this.oracleInfos.map((oracleInfo) => oracleInfo.publicKey),
|
|
485
|
-
100
|
|
486
|
-
);
|
|
487
|
-
const oracleAccountInfos = (
|
|
488
|
-
await Promise.all(
|
|
489
|
-
oracleAccountPubkeyChunks.map((oracleAccountPublicKeysChunk) =>
|
|
490
|
-
connection.getMultipleAccountsInfo(oracleAccountPublicKeysChunk)
|
|
491
|
-
)
|
|
492
|
-
)
|
|
493
|
-
).flat();
|
|
494
|
-
this.initialOraclePriceData = new Map(
|
|
495
|
-
this.oracleInfos.reduce(
|
|
496
|
-
(result, oracleInfo, i) => {
|
|
497
|
-
const oracleAccountInfo = oracleAccountInfos[i];
|
|
498
|
-
if (!oracleAccountInfo) {
|
|
499
|
-
return result;
|
|
500
|
-
}
|
|
501
|
-
|
|
502
|
-
const oracleClient = this.oracleClientCache.get(
|
|
503
|
-
oracleInfo.source,
|
|
504
|
-
connection,
|
|
505
|
-
this.program
|
|
506
|
-
);
|
|
507
|
-
if (!oracleClient) {
|
|
508
|
-
return result;
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
const oraclePriceData = oracleClient.getOraclePriceDataFromBuffer(
|
|
512
|
-
oracleAccountInfo.data
|
|
513
|
-
);
|
|
514
|
-
|
|
515
|
-
result.push([
|
|
516
|
-
getOracleId(oracleInfo.publicKey, oracleInfo.source),
|
|
517
|
-
oraclePriceData,
|
|
518
|
-
]);
|
|
519
|
-
return result;
|
|
520
|
-
},
|
|
521
|
-
[] as [string, OraclePriceData][]
|
|
522
|
-
)
|
|
523
|
-
);
|
|
524
|
-
const oracleSetupEndTime = performance.now();
|
|
525
|
-
const oracleSetupDuration = oracleSetupEndTime - oracleSetupStartTime;
|
|
526
|
-
if (this.resubOpts?.logResubMessages) {
|
|
527
|
-
console.log(
|
|
528
|
-
`[PROFILING] Oracle initial data setup completed in ${oracleSetupDuration.toFixed(
|
|
529
|
-
2
|
|
530
|
-
)}ms (${this.initialOraclePriceData.size} oracles)`
|
|
531
|
-
);
|
|
532
|
-
}
|
|
533
|
-
|
|
534
|
-
// emit initial oracle price data
|
|
535
|
-
Array.from(this.initialOraclePriceData.entries()).forEach(
|
|
536
|
-
([oracleId, oraclePriceData]) => {
|
|
537
|
-
const { publicKey, source } =
|
|
538
|
-
getPublicKeyAndSourceFromOracleId(oracleId);
|
|
539
|
-
this.eventEmitter.emit(
|
|
540
|
-
'oraclePriceUpdate',
|
|
541
|
-
publicKey,
|
|
542
|
-
source,
|
|
543
|
-
oraclePriceData
|
|
544
|
-
);
|
|
545
|
-
}
|
|
546
|
-
);
|
|
547
|
-
this.eventEmitter.emit('update');
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
/** Clears the seed data stashed by `setInitialData()`/`findAllMarketAndOracles` once consumed, freeing the memory. */
|
|
551
|
-
removeInitialData() {
|
|
552
|
-
this.initialPerpMarketAccountData = new Map();
|
|
553
|
-
this.initialSpotMarketAccountData = new Map();
|
|
554
|
-
this.initialOraclePriceData = new Map();
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
/** Subscribes a `WebSocketAccountSubscriberV2` for every tracked oracle not already subscribed, in parallel, skipping duplicates already present in `oracleSubscribers`. */
|
|
558
|
-
async subscribeToOracles(): Promise<boolean> {
|
|
559
|
-
const startTime = performance.now();
|
|
560
|
-
|
|
561
|
-
// Filter out default oracles and duplicates to avoid unnecessary subscriptions
|
|
562
|
-
const validOracleInfos = this.oracleInfos.filter(
|
|
563
|
-
(oracleInfo) =>
|
|
564
|
-
!this.oracleSubscribers.has(
|
|
565
|
-
getOracleId(oracleInfo.publicKey, oracleInfo.source)
|
|
566
|
-
)
|
|
567
|
-
);
|
|
568
|
-
|
|
569
|
-
await Promise.all(
|
|
570
|
-
validOracleInfos.map((oracleInfo) => this.subscribeToOracle(oracleInfo))
|
|
571
|
-
);
|
|
572
|
-
|
|
573
|
-
const totalDuration = performance.now() - startTime;
|
|
574
|
-
console.log(
|
|
575
|
-
`[PROFILING] subscribeToOracles() completed in ${totalDuration.toFixed(
|
|
576
|
-
2
|
|
577
|
-
)}ms`
|
|
578
|
-
);
|
|
579
|
-
|
|
580
|
-
return true;
|
|
581
|
-
}
|
|
582
|
-
|
|
583
|
-
/**
|
|
584
|
-
* Creates and subscribes a `WebSocketAccountSubscriberV2` for one oracle, decoding buffers
|
|
585
|
-
* with the source-appropriate `OracleClient`. Seeds from `initialOraclePriceData` if available
|
|
586
|
-
* before subscribing.
|
|
587
|
-
* @param oracleInfo Oracle pubkey and source to subscribe.
|
|
588
|
-
* @returns `false` if no `OracleClient` is registered for `oracleInfo.source` or the subscribe call throws; otherwise `true`.
|
|
589
|
-
*/
|
|
590
|
-
async subscribeToOracle(oracleInfo: OracleInfo): Promise<boolean> {
|
|
591
|
-
try {
|
|
592
|
-
const oracleId = getOracleId(oracleInfo.publicKey, oracleInfo.source);
|
|
593
|
-
|
|
594
|
-
const client = this.oracleClientCache.get(
|
|
595
|
-
oracleInfo.source,
|
|
596
|
-
this.program.provider.connection,
|
|
597
|
-
this.program
|
|
598
|
-
);
|
|
599
|
-
if (!client) {
|
|
600
|
-
return false;
|
|
601
|
-
}
|
|
602
|
-
const accountSubscriber =
|
|
603
|
-
new WebSocketAccountSubscriberV2<OraclePriceData>(
|
|
604
|
-
'oracle',
|
|
605
|
-
this.program,
|
|
606
|
-
oracleInfo.publicKey,
|
|
607
|
-
(buffer: Buffer) => {
|
|
608
|
-
return client.getOraclePriceDataFromBuffer(buffer);
|
|
609
|
-
},
|
|
610
|
-
this.resubOpts,
|
|
611
|
-
this.commitment,
|
|
612
|
-
this.rpcSubscriptions,
|
|
613
|
-
this.rpc
|
|
614
|
-
);
|
|
615
|
-
const initialOraclePriceData = this.initialOraclePriceData?.get(oracleId);
|
|
616
|
-
if (initialOraclePriceData) {
|
|
617
|
-
accountSubscriber.setData(initialOraclePriceData);
|
|
618
|
-
}
|
|
619
|
-
await accountSubscriber.subscribe((data: OraclePriceData) => {
|
|
620
|
-
this.eventEmitter.emit(
|
|
621
|
-
'oraclePriceUpdate',
|
|
622
|
-
oracleInfo.publicKey,
|
|
623
|
-
oracleInfo.source,
|
|
624
|
-
data
|
|
625
|
-
);
|
|
626
|
-
this.eventEmitter.emit('update');
|
|
627
|
-
});
|
|
628
|
-
|
|
629
|
-
this.oracleSubscribers.set(oracleId, accountSubscriber);
|
|
630
|
-
|
|
631
|
-
return true;
|
|
632
|
-
} catch (error) {
|
|
633
|
-
console.error(
|
|
634
|
-
`Failed to subscribe to oracle ${oracleInfo.publicKey.toString()}:`,
|
|
635
|
-
error
|
|
636
|
-
);
|
|
637
|
-
return false;
|
|
638
|
-
}
|
|
639
|
-
}
|
|
640
|
-
|
|
641
|
-
/** Unsubscribes the single multiplexed perp-market program-account stream. */
|
|
642
|
-
async unsubscribeFromMarketAccounts(): Promise<void> {
|
|
643
|
-
await this.perpMarketAllAccountsSubscriber.unsubscribe();
|
|
644
|
-
}
|
|
645
|
-
|
|
646
|
-
/** Unsubscribes the single multiplexed spot-market program-account stream. */
|
|
647
|
-
async unsubscribeFromSpotMarketAccounts(): Promise<void> {
|
|
648
|
-
await this.spotMarketAllAccountsSubscriber.unsubscribe();
|
|
649
|
-
}
|
|
650
|
-
|
|
651
|
-
/** Unsubscribes every per-oracle `WebSocketAccountSubscriberV2`, in parallel. */
|
|
652
|
-
async unsubscribeFromOracles(): Promise<void> {
|
|
653
|
-
await Promise.all(
|
|
654
|
-
Array.from(this.oracleSubscribers.values()).map((accountSubscriber) =>
|
|
655
|
-
accountSubscriber.unsubscribe()
|
|
656
|
-
)
|
|
657
|
-
);
|
|
658
|
-
}
|
|
659
|
-
|
|
660
|
-
/** Tears down the `State` subscriber, both market program-account streams, and every oracle subscriber. A no-op if not subscribed. */
|
|
661
|
-
public async unsubscribe(): Promise<void> {
|
|
662
|
-
if (!this.isSubscribed) {
|
|
663
|
-
return;
|
|
664
|
-
}
|
|
665
|
-
|
|
666
|
-
if (this.subscriptionPromise) {
|
|
667
|
-
await this.subscriptionPromise;
|
|
668
|
-
}
|
|
669
|
-
await Promise.all([
|
|
670
|
-
this.stateAccountSubscriber?.unsubscribe(),
|
|
671
|
-
this.unsubscribeFromMarketAccounts(),
|
|
672
|
-
this.unsubscribeFromSpotMarketAccounts(),
|
|
673
|
-
this.unsubscribeFromOracles(),
|
|
674
|
-
]);
|
|
675
|
-
|
|
676
|
-
this.isSubscribed = false;
|
|
677
|
-
this.isSubscribing = false;
|
|
678
|
-
this.subscriptionPromiseResolver = () => {};
|
|
679
|
-
}
|
|
680
|
-
|
|
681
|
-
/**
|
|
682
|
-
* Adds an oracle to be tracked, subscribing a new `WebSocketAccountSubscriberV2` for it. A
|
|
683
|
-
* no-op that resolves `true` immediately for the `PublicKey.default` sentinel (quote-asset "no
|
|
684
|
-
* oracle") or an oracle already tracked.
|
|
685
|
-
* @param oracleInfo Oracle pubkey and source to start tracking.
|
|
686
|
-
*/
|
|
687
|
-
async addOracle(oracleInfo: OracleInfo): Promise<boolean> {
|
|
688
|
-
const oracleId = getOracleId(oracleInfo.publicKey, oracleInfo.source);
|
|
689
|
-
if (this.oracleSubscribers.has(oracleId)) {
|
|
690
|
-
return true;
|
|
691
|
-
}
|
|
692
|
-
|
|
693
|
-
if (oracleInfo.publicKey.equals(PublicKey.default)) {
|
|
694
|
-
return true;
|
|
695
|
-
}
|
|
696
|
-
|
|
697
|
-
return this.subscribeToOracle(oracleInfo);
|
|
698
|
-
}
|
|
699
|
-
|
|
700
|
-
/** Rebuilds `perpOracleMap`/`perpOracleStringMap` from currently cached perp markets, calling `addOracle` for any oracle not yet tracked. */
|
|
701
|
-
async setPerpOracleMap() {
|
|
702
|
-
const perpMarkets = this.getMarketAccountsAndSlots();
|
|
703
|
-
const addOraclePromises = [];
|
|
704
|
-
for (const perpMarket of perpMarkets) {
|
|
705
|
-
if (!perpMarket || !perpMarket.data) {
|
|
706
|
-
continue;
|
|
707
|
-
}
|
|
708
|
-
const perpMarketAccount = perpMarket.data;
|
|
709
|
-
const perpMarketIndex = perpMarketAccount.marketIndex;
|
|
710
|
-
const oracle = perpMarketAccount.oracle;
|
|
711
|
-
const oracleId = getOracleId(oracle, perpMarket.data.oracleSource);
|
|
712
|
-
if (!this.oracleSubscribers.has(oracleId)) {
|
|
713
|
-
addOraclePromises.push(
|
|
714
|
-
this.addOracle({
|
|
715
|
-
publicKey: oracle,
|
|
716
|
-
source: perpMarket.data.oracleSource,
|
|
717
|
-
})
|
|
718
|
-
);
|
|
719
|
-
}
|
|
720
|
-
this.perpOracleMap.set(perpMarketIndex, oracle);
|
|
721
|
-
this.perpOracleStringMap.set(perpMarketIndex, oracleId);
|
|
722
|
-
}
|
|
723
|
-
await Promise.all(addOraclePromises);
|
|
724
|
-
}
|
|
725
|
-
|
|
726
|
-
/** Rebuilds `spotOracleMap`/`spotOracleStringMap` from currently cached spot markets, calling `addOracle` for any oracle not yet tracked. */
|
|
727
|
-
async setSpotOracleMap() {
|
|
728
|
-
const spotMarkets = this.getSpotMarketAccountsAndSlots();
|
|
729
|
-
const addOraclePromises = [];
|
|
730
|
-
for (const spotMarket of spotMarkets) {
|
|
731
|
-
if (!spotMarket || !spotMarket.data) {
|
|
732
|
-
continue;
|
|
733
|
-
}
|
|
734
|
-
const spotMarketAccount = spotMarket.data;
|
|
735
|
-
const spotMarketIndex = spotMarketAccount.marketIndex;
|
|
736
|
-
const oracle = spotMarketAccount.oracle;
|
|
737
|
-
const oracleId = getOracleId(oracle, spotMarketAccount.oracleSource);
|
|
738
|
-
if (!this.oracleSubscribers.has(oracleId)) {
|
|
739
|
-
addOraclePromises.push(
|
|
740
|
-
this.addOracle({
|
|
741
|
-
publicKey: oracle,
|
|
742
|
-
source: spotMarketAccount.oracleSource,
|
|
743
|
-
})
|
|
744
|
-
);
|
|
745
|
-
}
|
|
746
|
-
this.spotOracleMap.set(spotMarketIndex, oracle);
|
|
747
|
-
this.spotOracleStringMap.set(spotMarketIndex, oracleId);
|
|
748
|
-
}
|
|
749
|
-
await Promise.all(addOraclePromises);
|
|
750
|
-
}
|
|
751
|
-
|
|
752
|
-
/**
|
|
753
|
-
* Applies `delistedMarketSetting` to any oracle backing a currently `status: delisted` perp
|
|
754
|
-
* market (and not still used by a live spot market, per `findDelistedPerpMarketsAndOracles`):
|
|
755
|
-
* unsubscribes the oracle's subscriber, and additionally drops it from `oracleSubscribers` if
|
|
756
|
-
* the setting is `Discard`. A no-op if the setting is `Subscribe`. Note this only manages
|
|
757
|
-
* oracle subscriptions — delisted market accounts themselves cannot be selectively unsubscribed
|
|
758
|
-
* from the shared perp/spot program-account stream; instead the `subscribe()` update callback
|
|
759
|
-
* drops any incoming update for a `status: delisted` market unless `delistedMarketSetting` is
|
|
760
|
-
* `Subscribe`, freezing that market's cached data at its last pre-delisting state.
|
|
761
|
-
*/
|
|
762
|
-
async handleDelistedMarketOracles(): Promise<void> {
|
|
763
|
-
if (this.delistedMarketSetting === DelistedMarketSetting.Subscribe) {
|
|
764
|
-
return;
|
|
765
|
-
}
|
|
766
|
-
|
|
767
|
-
const { oracles } = findDelistedPerpMarketsAndOracles(
|
|
768
|
-
this.getMarketAccountsAndSlots(),
|
|
769
|
-
this.getSpotMarketAccountsAndSlots()
|
|
770
|
-
);
|
|
771
|
-
|
|
772
|
-
for (const oracle of oracles) {
|
|
773
|
-
const oracleId = getOracleId(oracle.publicKey, oracle.source);
|
|
774
|
-
const subscriber = this.oracleSubscribers.get(oracleId);
|
|
775
|
-
if (subscriber) {
|
|
776
|
-
await subscriber.unsubscribe();
|
|
777
|
-
if (this.delistedMarketSetting === DelistedMarketSetting.Discard) {
|
|
778
|
-
this.oracleSubscribers.delete(oracleId);
|
|
779
|
-
}
|
|
780
|
-
}
|
|
781
|
-
}
|
|
782
|
-
}
|
|
783
|
-
|
|
784
|
-
/** Throws `NotSubscribedError` if `subscribe()` has not been called. */
|
|
785
|
-
assertIsSubscribed(): void {
|
|
786
|
-
if (!this.isSubscribed) {
|
|
787
|
-
throw new NotSubscribedError(
|
|
788
|
-
'You must call `subscribe` before using this function'
|
|
789
|
-
);
|
|
790
|
-
}
|
|
791
|
-
}
|
|
792
|
-
|
|
793
|
-
/** Throws `NotSubscribedError` if not subscribed, or a generic `Error` (via `assertDataAndSlot`) if subscribed but the `State` account hasn't loaded yet. */
|
|
794
|
-
public getStateAccountAndSlot(): DataAndSlot<StateAccount> {
|
|
795
|
-
this.assertIsSubscribed();
|
|
796
|
-
return assertDataAndSlot(
|
|
797
|
-
this.stateAccountSubscriber?.dataAndSlot,
|
|
798
|
-
'State account data not available'
|
|
799
|
-
);
|
|
800
|
-
}
|
|
801
|
-
|
|
802
|
-
/** Throws `NotSubscribedError` if not subscribed. Returns undefined if `marketIndex` hasn't been observed yet on the perp program-account stream. */
|
|
803
|
-
public getMarketAccountAndSlot(
|
|
804
|
-
marketIndex: number
|
|
805
|
-
): DataAndSlot<PerpMarketAccount> | undefined {
|
|
806
|
-
this.assertIsSubscribed();
|
|
807
|
-
return this.perpMarketAccountLatestData.get(marketIndex);
|
|
808
|
-
}
|
|
809
|
-
|
|
810
|
-
/** Returns every currently cached (loaded) perp market. Does not throw `NotSubscribedError`. */
|
|
811
|
-
public getMarketAccountsAndSlots(): DataAndSlot<PerpMarketAccount>[] {
|
|
812
|
-
return Array.from(this.perpMarketAccountLatestData.values());
|
|
813
|
-
}
|
|
814
|
-
|
|
815
|
-
/** Throws `NotSubscribedError` if not subscribed. Returns undefined if `marketIndex` hasn't been observed yet on the spot program-account stream. */
|
|
816
|
-
public getSpotMarketAccountAndSlot(
|
|
817
|
-
marketIndex: number
|
|
818
|
-
): DataAndSlot<SpotMarketAccount> | undefined {
|
|
819
|
-
this.assertIsSubscribed();
|
|
820
|
-
return this.spotMarketAccountLatestData.get(marketIndex);
|
|
821
|
-
}
|
|
822
|
-
|
|
823
|
-
/** Returns every currently cached (loaded) spot market. Does not throw `NotSubscribedError`. */
|
|
824
|
-
public getSpotMarketAccountsAndSlots(): DataAndSlot<SpotMarketAccount>[] {
|
|
825
|
-
return Array.from(this.spotMarketAccountLatestData.values());
|
|
826
|
-
}
|
|
827
|
-
|
|
828
|
-
/**
|
|
829
|
-
* Looks up cached oracle price data by oracle id (see `getOracleId`). Special-cases the
|
|
830
|
-
* quote-asset default oracle id, returning the constant `QUOTE_ORACLE_PRICE_DATA` at slot 0
|
|
831
|
-
* rather than a subscriber lookup, since that oracle is never actually subscribed to.
|
|
832
|
-
* @param oracleId Oracle id string from `getOracleId(publicKey, source)`.
|
|
833
|
-
* @returns Cached price data/slot, or undefined if not tracked. Throws `NotSubscribedError` if not subscribed.
|
|
834
|
-
*/
|
|
835
|
-
public getOraclePriceDataAndSlot(
|
|
836
|
-
oracleId: string
|
|
837
|
-
): DataAndSlot<OraclePriceData> | undefined {
|
|
838
|
-
this.assertIsSubscribed();
|
|
839
|
-
if (oracleId === ORACLE_DEFAULT_ID) {
|
|
840
|
-
return {
|
|
841
|
-
data: QUOTE_ORACLE_PRICE_DATA,
|
|
842
|
-
slot: 0,
|
|
843
|
-
};
|
|
844
|
-
}
|
|
845
|
-
return this.oracleSubscribers.get(oracleId)?.dataAndSlot;
|
|
846
|
-
}
|
|
847
|
-
|
|
848
|
-
/**
|
|
849
|
-
* Convenience lookup: resolves the oracle price data currently mapped to a perp market's
|
|
850
|
-
* oracle. If the cached market's oracle pubkey has drifted from (or isn't yet in)
|
|
851
|
-
* `perpOracleMap`, triggers a background `setPerpOracleMap()` refresh and still returns the
|
|
852
|
-
* (possibly stale) mapping for this call.
|
|
853
|
-
* @param marketIndex Perp market index whose oracle price to look up.
|
|
854
|
-
*/
|
|
855
|
-
public getOraclePriceDataAndSlotForPerpMarket(
|
|
856
|
-
marketIndex: number
|
|
857
|
-
): DataAndSlot<OraclePriceData> | undefined {
|
|
858
|
-
const perpMarketAccount = this.getMarketAccountAndSlot(marketIndex);
|
|
859
|
-
const oracle = this.perpOracleMap.get(marketIndex);
|
|
860
|
-
const oracleId = this.perpOracleStringMap.get(marketIndex);
|
|
861
|
-
if (!perpMarketAccount || !oracleId) {
|
|
862
|
-
return undefined;
|
|
863
|
-
}
|
|
864
|
-
|
|
865
|
-
if (!oracle || !perpMarketAccount.data.oracle.equals(oracle)) {
|
|
866
|
-
// If the oracle has changed (or not yet cached), update the oracle map in background
|
|
867
|
-
this.setPerpOracleMap();
|
|
868
|
-
}
|
|
869
|
-
|
|
870
|
-
return this.getOraclePriceDataAndSlot(oracleId);
|
|
871
|
-
}
|
|
872
|
-
|
|
873
|
-
/**
|
|
874
|
-
* Convenience lookup: resolves the oracle price data currently mapped to a spot market's
|
|
875
|
-
* oracle. If the cached market's oracle pubkey has drifted from (or isn't yet in)
|
|
876
|
-
* `spotOracleMap`, triggers a background `setSpotOracleMap()` refresh and still returns the
|
|
877
|
-
* (possibly stale) mapping for this call.
|
|
878
|
-
* @param marketIndex Spot market index whose oracle price to look up.
|
|
879
|
-
*/
|
|
880
|
-
public getOraclePriceDataAndSlotForSpotMarket(
|
|
881
|
-
marketIndex: number
|
|
882
|
-
): DataAndSlot<OraclePriceData> | undefined {
|
|
883
|
-
const spotMarketAccount = this.getSpotMarketAccountAndSlot(marketIndex);
|
|
884
|
-
const oracle = this.spotOracleMap.get(marketIndex);
|
|
885
|
-
const oracleId = this.spotOracleStringMap.get(marketIndex);
|
|
886
|
-
if (!spotMarketAccount || !oracleId) {
|
|
887
|
-
return undefined;
|
|
888
|
-
}
|
|
889
|
-
|
|
890
|
-
if (!oracle || !spotMarketAccount.data.oracle.equals(oracle)) {
|
|
891
|
-
// If the oracle has changed (or not yet cached), update the oracle map in background
|
|
892
|
-
this.setSpotOracleMap();
|
|
893
|
-
}
|
|
894
|
-
|
|
895
|
-
return this.getOraclePriceDataAndSlot(oracleId);
|
|
896
|
-
}
|
|
897
|
-
}
|