@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,189 +0,0 @@
|
|
|
1
|
-
// import WebSocket from 'ws';
|
|
2
|
-
import { logProviderCallback, EventType, LogProvider } from './types';
|
|
3
|
-
import { EventEmitter } from 'events';
|
|
4
|
-
|
|
5
|
-
// browser support
|
|
6
|
-
let WebSocketImpl: typeof WebSocket;
|
|
7
|
-
if (typeof window !== 'undefined' && window.WebSocket) {
|
|
8
|
-
WebSocketImpl = window.WebSocket;
|
|
9
|
-
} else {
|
|
10
|
-
WebSocketImpl = require('ws');
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
const EVENT_SERVER_HEARTBEAT_INTERVAL_MS = 5000;
|
|
14
|
-
const ALLOWED_MISSED_HEARTBEATS = 3;
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* `LogProvider` backed by the Velocity-hosted events server: a websocket
|
|
18
|
-
* that pushes pre-parsed events per subscribed channel (event type),
|
|
19
|
-
* optionally filtered to one user account, instead of raw RPC logs. Expects
|
|
20
|
-
* a heartbeat message on channel `'heartbeat'` at least every
|
|
21
|
-
* `EVENT_SERVER_HEARTBEAT_INTERVAL_MS` (5s); if none arrives within 3 missed
|
|
22
|
-
* intervals it closes and resubscribes, emitting `'reconnect'` on
|
|
23
|
-
* `eventEmitter` with the attempt count. Each received event is repackaged
|
|
24
|
-
* as a synthetic 3-line log array (`invoke` / raw log / `success`) so it can
|
|
25
|
-
* be run back through the same `parseLogs` pipeline as RPC-sourced logs.
|
|
26
|
-
*/
|
|
27
|
-
export class EventsServerLogProvider implements LogProvider {
|
|
28
|
-
private ws?: WebSocket;
|
|
29
|
-
private callback?: logProviderCallback;
|
|
30
|
-
private isUnsubscribing = false;
|
|
31
|
-
private externalUnsubscribe = false;
|
|
32
|
-
private lastHeartbeat = 0;
|
|
33
|
-
private timeoutId?: ReturnType<typeof setTimeout>;
|
|
34
|
-
private reconnectAttempts = 0;
|
|
35
|
-
eventEmitter: EventEmitter = new EventEmitter();
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* @param url Websocket URL of the Velocity events server.
|
|
39
|
-
* @param eventTypes Event type channels to subscribe to (one `subscribe` message sent per type on connect).
|
|
40
|
-
* @param userAccount If provided, scopes the subscription server-side to events for this user account (base58 pubkey string).
|
|
41
|
-
*/
|
|
42
|
-
public constructor(
|
|
43
|
-
private readonly url: string,
|
|
44
|
-
private readonly eventTypes: EventType[],
|
|
45
|
-
private readonly userAccount?: string
|
|
46
|
-
) {}
|
|
47
|
-
|
|
48
|
-
public isSubscribed(): boolean {
|
|
49
|
-
return this.ws !== undefined;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/** Opens the websocket and sends a `subscribe` message per configured event type once connected. `skipHistory` is accepted for `LogProvider` interface compatibility but has no effect (the server only ever pushes new events). Always resolves `true`; malformed inbound messages are caught and logged, not thrown. */
|
|
53
|
-
public async subscribe(callback: logProviderCallback): Promise<boolean> {
|
|
54
|
-
if (this.ws !== undefined) {
|
|
55
|
-
return true;
|
|
56
|
-
}
|
|
57
|
-
const ws = new WebSocketImpl(this.url);
|
|
58
|
-
this.ws = ws;
|
|
59
|
-
|
|
60
|
-
// reset teardown flags for a fresh subscription cycle — the `ws !== undefined`
|
|
61
|
-
// unsubscribe path (e.g. a heartbeat-timeout resubscribe) leaves isUnsubscribing
|
|
62
|
-
// set, which would otherwise disable the watchdog and reconnect on this new socket
|
|
63
|
-
this.isUnsubscribing = false;
|
|
64
|
-
this.externalUnsubscribe = false;
|
|
65
|
-
|
|
66
|
-
this.callback = callback;
|
|
67
|
-
ws.addEventListener('open', () => {
|
|
68
|
-
for (const channel of this.eventTypes) {
|
|
69
|
-
const subscribeMessage: {
|
|
70
|
-
type: string;
|
|
71
|
-
channel: EventType;
|
|
72
|
-
user?: string;
|
|
73
|
-
} = {
|
|
74
|
-
type: 'subscribe',
|
|
75
|
-
channel: channel,
|
|
76
|
-
};
|
|
77
|
-
if (this.userAccount) {
|
|
78
|
-
subscribeMessage.user = this.userAccount;
|
|
79
|
-
}
|
|
80
|
-
ws.send(JSON.stringify(subscribeMessage));
|
|
81
|
-
}
|
|
82
|
-
this.reconnectAttempts = 0;
|
|
83
|
-
});
|
|
84
|
-
|
|
85
|
-
ws.addEventListener('message', (data) => {
|
|
86
|
-
try {
|
|
87
|
-
if (!this.isUnsubscribing) {
|
|
88
|
-
clearTimeout(this.timeoutId);
|
|
89
|
-
this.setTimeout();
|
|
90
|
-
if (this.reconnectAttempts > 0) {
|
|
91
|
-
console.log(
|
|
92
|
-
'eventsServerLogProvider: Resetting reconnect attempts to 0'
|
|
93
|
-
);
|
|
94
|
-
}
|
|
95
|
-
this.reconnectAttempts = 0;
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
const parsedData = JSON.parse(data.data.toString());
|
|
99
|
-
if (parsedData.channel === 'heartbeat') {
|
|
100
|
-
this.lastHeartbeat = Date.now();
|
|
101
|
-
return;
|
|
102
|
-
}
|
|
103
|
-
if (parsedData.message !== undefined) {
|
|
104
|
-
return;
|
|
105
|
-
}
|
|
106
|
-
const event = JSON.parse(parsedData.data);
|
|
107
|
-
if (this.callback === undefined) {
|
|
108
|
-
return;
|
|
109
|
-
}
|
|
110
|
-
this.callback(
|
|
111
|
-
event.txSig,
|
|
112
|
-
event.slot,
|
|
113
|
-
[
|
|
114
|
-
'Program vELoC1audYbSYVRXn1vPaV8Axoa9oU6BYmNGZZBDZ1P invoke [1]',
|
|
115
|
-
event.rawLog,
|
|
116
|
-
'Program vELoC1audYbSYVRXn1vPaV8Axoa9oU6BYmNGZZBDZ1P success',
|
|
117
|
-
],
|
|
118
|
-
undefined,
|
|
119
|
-
event.txSigIndex
|
|
120
|
-
);
|
|
121
|
-
} catch (error) {
|
|
122
|
-
console.error('Error parsing message:', error);
|
|
123
|
-
}
|
|
124
|
-
});
|
|
125
|
-
|
|
126
|
-
ws.addEventListener('close', () => {
|
|
127
|
-
console.log('eventsServerLogProvider: WebSocket closed');
|
|
128
|
-
});
|
|
129
|
-
|
|
130
|
-
ws.addEventListener('error', (error) => {
|
|
131
|
-
console.error('eventsServerLogProvider: WebSocket error:', error);
|
|
132
|
-
});
|
|
133
|
-
|
|
134
|
-
this.setTimeout();
|
|
135
|
-
|
|
136
|
-
return true;
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
/**
|
|
140
|
-
* Closes the websocket and clears the heartbeat timeout.
|
|
141
|
-
* @param external Whether this is a caller-initiated unsubscribe rather than an internal one during a reconnect cycle.
|
|
142
|
-
* @returns Always resolves `true`.
|
|
143
|
-
*/
|
|
144
|
-
public async unsubscribe(external = false): Promise<boolean> {
|
|
145
|
-
this.isUnsubscribing = true;
|
|
146
|
-
this.externalUnsubscribe = external;
|
|
147
|
-
if (this.timeoutId) {
|
|
148
|
-
clearInterval(this.timeoutId);
|
|
149
|
-
this.timeoutId = undefined;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
if (this.ws !== undefined) {
|
|
153
|
-
this.ws.close();
|
|
154
|
-
this.ws = undefined;
|
|
155
|
-
return true;
|
|
156
|
-
} else {
|
|
157
|
-
this.isUnsubscribing = false;
|
|
158
|
-
return true;
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
private setTimeout(): void {
|
|
163
|
-
this.timeoutId = setTimeout(async () => {
|
|
164
|
-
if (this.isUnsubscribing || this.externalUnsubscribe) {
|
|
165
|
-
// If we are in the process of unsubscribing, do not attempt to resubscribe
|
|
166
|
-
return;
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
const timeSinceLastHeartbeat = Date.now() - this.lastHeartbeat;
|
|
170
|
-
if (
|
|
171
|
-
timeSinceLastHeartbeat >
|
|
172
|
-
EVENT_SERVER_HEARTBEAT_INTERVAL_MS * ALLOWED_MISSED_HEARTBEATS
|
|
173
|
-
) {
|
|
174
|
-
console.log(
|
|
175
|
-
`eventServerLogProvider: No heartbeat in ${timeSinceLastHeartbeat}ms, resubscribing on attempt ${
|
|
176
|
-
this.reconnectAttempts + 1
|
|
177
|
-
}`
|
|
178
|
-
);
|
|
179
|
-
const callback = this.callback;
|
|
180
|
-
await this.unsubscribe();
|
|
181
|
-
this.reconnectAttempts++;
|
|
182
|
-
this.eventEmitter.emit('reconnect', this.reconnectAttempts);
|
|
183
|
-
if (callback !== undefined) {
|
|
184
|
-
this.subscribe(callback);
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
}, EVENT_SERVER_HEARTBEAT_INTERVAL_MS * 2);
|
|
188
|
-
}
|
|
189
|
-
}
|
package/src/events/fetchLogs.ts
DELETED
|
@@ -1,219 +0,0 @@
|
|
|
1
|
-
import { Program } from '../isomorphic/anchor';
|
|
2
|
-
import {
|
|
3
|
-
Connection,
|
|
4
|
-
Finality,
|
|
5
|
-
PublicKey,
|
|
6
|
-
TransactionResponse,
|
|
7
|
-
TransactionSignature,
|
|
8
|
-
VersionedTransactionResponse,
|
|
9
|
-
} from '@solana/web3.js';
|
|
10
|
-
import {
|
|
11
|
-
DefaultEventSubscriptionOptions,
|
|
12
|
-
EventType,
|
|
13
|
-
WrappedEvents,
|
|
14
|
-
} from './types';
|
|
15
|
-
import { promiseTimeout } from '../util/promiseTimeout';
|
|
16
|
-
import { parseLogs } from './parse';
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* Case-insensitive lookup from decoded (camelCase) IDL event names to
|
|
20
|
-
* PascalCase `EventType` keys, mirroring `EventSubscriber`'s
|
|
21
|
-
* `eventTypeByLowercaseName` — `@coral-xyz/anchor` 0.32+ decodes event names
|
|
22
|
-
* in camelCase, but the rest of the SDK keys off the PascalCase `EventType`.
|
|
23
|
-
*/
|
|
24
|
-
const eventTypeByLowercaseName = new Map<string, EventType>(
|
|
25
|
-
(DefaultEventSubscriptionOptions.eventTypes ?? []).map((eventType) => [
|
|
26
|
-
eventType.toLowerCase(),
|
|
27
|
-
eventType,
|
|
28
|
-
])
|
|
29
|
-
);
|
|
30
|
-
|
|
31
|
-
type Log = { txSig: TransactionSignature; slot: number; logs: string[] };
|
|
32
|
-
type FetchLogsResponse = {
|
|
33
|
-
earliestTx: string;
|
|
34
|
-
mostRecentTx: string;
|
|
35
|
-
earliestSlot: number;
|
|
36
|
-
mostRecentSlot: number;
|
|
37
|
-
transactionLogs: Log[];
|
|
38
|
-
mostRecentBlockTime: number | undefined;
|
|
39
|
-
};
|
|
40
|
-
|
|
41
|
-
function mapTransactionResponseToLog(
|
|
42
|
-
transaction: TransactionResponse | VersionedTransactionResponse
|
|
43
|
-
): Log {
|
|
44
|
-
return {
|
|
45
|
-
txSig: transaction.transaction.signatures[0],
|
|
46
|
-
slot: transaction.slot,
|
|
47
|
-
logs: transaction.meta?.logMessages ?? [],
|
|
48
|
-
};
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* Fetches raw transaction logs for `address`, newest-first from
|
|
53
|
-
* `getSignaturesForAddress` then batch-fetched via `getTransaction`. Used by
|
|
54
|
-
* both `PollingLogProvider` (incremental polling) and
|
|
55
|
-
* `EventSubscriber.fetchPreviousTx` (historical backfill). Failed
|
|
56
|
-
* transactions (with an `err`) are filtered out before fetching logs.
|
|
57
|
-
* @param connection RPC connection.
|
|
58
|
-
* @param address Account/program address to fetch signatures for.
|
|
59
|
-
* @param finality Commitment for both the signature list and the transaction fetches.
|
|
60
|
-
* @param beforeTx Only return signatures older than this one (pagination cursor).
|
|
61
|
-
* @param untilTx Stop at (exclusive of) this signature.
|
|
62
|
-
* @param limit Max signatures to request from `getSignaturesForAddress`; RPC default applies if omitted.
|
|
63
|
-
* @param batchSize Number of `getTransaction` calls batched per RPC round-trip; defaults to 25.
|
|
64
|
-
* @returns `undefined` if no non-failed signatures were found in range; otherwise the transaction logs plus the earliest/most-recent signature, slot, and block time observed, for use as the next `beforeTx`/`mostRecentSeenTx` cursor.
|
|
65
|
-
*/
|
|
66
|
-
export async function fetchLogs(
|
|
67
|
-
connection: Connection,
|
|
68
|
-
address: PublicKey,
|
|
69
|
-
finality: Finality,
|
|
70
|
-
beforeTx?: TransactionSignature,
|
|
71
|
-
untilTx?: TransactionSignature,
|
|
72
|
-
limit?: number,
|
|
73
|
-
batchSize = 25
|
|
74
|
-
): Promise<FetchLogsResponse | undefined> {
|
|
75
|
-
const signatures = await connection.getSignaturesForAddress(
|
|
76
|
-
address,
|
|
77
|
-
{
|
|
78
|
-
before: beforeTx,
|
|
79
|
-
until: untilTx,
|
|
80
|
-
limit,
|
|
81
|
-
},
|
|
82
|
-
finality
|
|
83
|
-
);
|
|
84
|
-
|
|
85
|
-
const sortedSignatures = signatures.sort((a, b) =>
|
|
86
|
-
a.slot === b.slot ? 0 : a.slot < b.slot ? -1 : 1
|
|
87
|
-
);
|
|
88
|
-
|
|
89
|
-
const filteredSignatures = sortedSignatures.filter(
|
|
90
|
-
(signature) => !signature.err
|
|
91
|
-
);
|
|
92
|
-
|
|
93
|
-
if (filteredSignatures.length === 0) {
|
|
94
|
-
return undefined;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
const chunkedSignatures = chunk(filteredSignatures, batchSize);
|
|
98
|
-
|
|
99
|
-
const transactionLogs = (
|
|
100
|
-
await Promise.all(
|
|
101
|
-
chunkedSignatures.map(async (chunk) => {
|
|
102
|
-
return await fetchTransactionLogs(
|
|
103
|
-
connection,
|
|
104
|
-
chunk.map((confirmedSignature) => confirmedSignature.signature),
|
|
105
|
-
finality
|
|
106
|
-
);
|
|
107
|
-
})
|
|
108
|
-
)
|
|
109
|
-
).flat();
|
|
110
|
-
|
|
111
|
-
const earliest = filteredSignatures[0];
|
|
112
|
-
const mostRecent = filteredSignatures[filteredSignatures.length - 1];
|
|
113
|
-
|
|
114
|
-
return {
|
|
115
|
-
transactionLogs: transactionLogs,
|
|
116
|
-
earliestTx: earliest.signature,
|
|
117
|
-
mostRecentTx: mostRecent.signature,
|
|
118
|
-
earliestSlot: earliest.slot,
|
|
119
|
-
mostRecentSlot: mostRecent.slot,
|
|
120
|
-
mostRecentBlockTime: mostRecent.blockTime ?? undefined,
|
|
121
|
-
};
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* Fetches `getTransaction` for a batch of signatures in a single RPC batch
|
|
126
|
-
* request, with a 10-second overall timeout.
|
|
127
|
-
* @param connection RPC connection.
|
|
128
|
-
* @param signatures Signatures to fetch (fetched as `maxSupportedTransactionVersion: 0`).
|
|
129
|
-
* @param finality Commitment to fetch each transaction at.
|
|
130
|
-
* @returns One `Log` per signature that returned a result (signatures the RPC couldn't resolve are silently dropped, not padded with placeholders).
|
|
131
|
-
* @throws (rejects) if the batch RPC call doesn't complete within 10 seconds.
|
|
132
|
-
*/
|
|
133
|
-
export async function fetchTransactionLogs(
|
|
134
|
-
connection: Connection,
|
|
135
|
-
signatures: TransactionSignature[],
|
|
136
|
-
finality: Finality
|
|
137
|
-
): Promise<Log[]> {
|
|
138
|
-
const requests = new Array<{ methodName: string; args: any }>();
|
|
139
|
-
for (const signature of signatures) {
|
|
140
|
-
const args = [
|
|
141
|
-
signature,
|
|
142
|
-
{ commitment: finality, maxSupportedTransactionVersion: 0 },
|
|
143
|
-
];
|
|
144
|
-
|
|
145
|
-
requests.push({
|
|
146
|
-
methodName: 'getTransaction',
|
|
147
|
-
args,
|
|
148
|
-
});
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
const rpcResponses: any | null = await promiseTimeout(
|
|
152
|
-
// @ts-ignore
|
|
153
|
-
connection._rpcBatchRequest(requests),
|
|
154
|
-
10 * 1000 // 10 second timeout
|
|
155
|
-
);
|
|
156
|
-
|
|
157
|
-
if (rpcResponses === null) {
|
|
158
|
-
return Promise.reject('RPC request timed out fetching transactions');
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
const logs = new Array<Log>();
|
|
162
|
-
for (const rpcResponse of rpcResponses) {
|
|
163
|
-
if (rpcResponse.result) {
|
|
164
|
-
logs.push(mapTransactionResponseToLog(rpcResponse.result));
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
return logs;
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
function chunk<T>(array: readonly T[], size: number): T[][] {
|
|
172
|
-
return new Array(Math.ceil(array.length / size))
|
|
173
|
-
.fill(null)
|
|
174
|
-
.map((_, index) => index * size)
|
|
175
|
-
.map((begin) => array.slice(begin, begin + size));
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
/**
|
|
179
|
-
* Standalone helper to decode events out of an already-fetched transaction or
|
|
180
|
-
* log object, without going through `EventSubscriber`. Useful for one-off
|
|
181
|
-
* decoding (e.g. re-parsing a transaction fetched elsewhere).
|
|
182
|
-
*/
|
|
183
|
-
export class LogParser {
|
|
184
|
-
private program: Program;
|
|
185
|
-
|
|
186
|
-
constructor(program: Program) {
|
|
187
|
-
this.program = program;
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
/** Decodes the events emitted in a fetched `TransactionResponse`. Assigns `txSigIndex` by decode order (0-based), not by any provider-supplied index. */
|
|
191
|
-
public parseEventsFromTransaction(
|
|
192
|
-
transaction: TransactionResponse
|
|
193
|
-
): WrappedEvents {
|
|
194
|
-
const transactionLogObject = mapTransactionResponseToLog(transaction);
|
|
195
|
-
|
|
196
|
-
return this.parseEventsFromLogs(transactionLogObject);
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
/** Decodes the events in a `{ txSig, slot, logs }` log object. Returns an empty array if `logs` is falsy. Assigns `txSigIndex` by decode order (0-based). */
|
|
200
|
-
public parseEventsFromLogs(event: Log): WrappedEvents {
|
|
201
|
-
const records: WrappedEvents = [];
|
|
202
|
-
|
|
203
|
-
if (!event.logs) return records;
|
|
204
|
-
|
|
205
|
-
let runningEventIndex = 0;
|
|
206
|
-
for (const eventLog of parseLogs(this.program, event.logs)) {
|
|
207
|
-
eventLog.data.txSig = event.txSig;
|
|
208
|
-
eventLog.data.slot = event.slot;
|
|
209
|
-
eventLog.data.eventType =
|
|
210
|
-
eventTypeByLowercaseName.get(eventLog.name.toLowerCase()) ??
|
|
211
|
-
eventLog.name;
|
|
212
|
-
eventLog.data.txSigIndex = runningEventIndex;
|
|
213
|
-
// @ts-ignore
|
|
214
|
-
records.push(eventLog.data);
|
|
215
|
-
runningEventIndex++;
|
|
216
|
-
}
|
|
217
|
-
return records;
|
|
218
|
-
}
|
|
219
|
-
}
|
package/src/events/parse.ts
DELETED
|
@@ -1,271 +0,0 @@
|
|
|
1
|
-
import { Program, Event } from '../isomorphic/anchor';
|
|
2
|
-
import { CuUsageEvent } from './types';
|
|
3
|
-
|
|
4
|
-
const velocityProgramId = 'vELoC1audYbSYVRXn1vPaV8Axoa9oU6BYmNGZZBDZ1P';
|
|
5
|
-
const PROGRAM_LOG = 'Program log: ';
|
|
6
|
-
const PROGRAM_INSTRUCTION = 'Program log: Instruction: ';
|
|
7
|
-
const PROGRAM_DATA = 'Program data: ';
|
|
8
|
-
const PROGRAM_LOG_START_INDEX = PROGRAM_LOG.length;
|
|
9
|
-
const PROGRAM_DATA_START_INDEX = PROGRAM_DATA.length;
|
|
10
|
-
const PROGRAM_INSTRUCTION_START_INDEX = PROGRAM_INSTRUCTION.length;
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* Decodes Anchor events from a transaction's raw log lines. Walks the log
|
|
14
|
-
* lines tracking the CPI call stack so only `msg!`/`sol_log_data` lines
|
|
15
|
-
* logged while the Velocity program is the currently-executing program are
|
|
16
|
-
* treated as candidate events; lines after `'Log truncated'` are ignored
|
|
17
|
-
* (the RPC node cut off the log before printing exceeded 10KB).
|
|
18
|
-
* @param program Anchor `Program` whose IDL coder decodes the event discriminator/payload.
|
|
19
|
-
* @param logs Raw `logMessages` for one transaction.
|
|
20
|
-
* @param programId Program ID whose logs are decoded; defaults to the Velocity program.
|
|
21
|
-
* @returns Decoded Anchor `Event`s in log order (does not include `slot`/`txSig`/`txSigIndex` — callers such as `EventSubscriber` attach those).
|
|
22
|
-
*/
|
|
23
|
-
export function parseLogs(
|
|
24
|
-
program: Program,
|
|
25
|
-
logs: string[],
|
|
26
|
-
programId = velocityProgramId
|
|
27
|
-
): Event[] {
|
|
28
|
-
const { events } = parseLogsWithRaw(program, logs, programId);
|
|
29
|
-
return events;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
/** Same as `parseLogs`, but also returns the raw log line each event was decoded from (parallel-indexed to `events`), for callers that need to keep the original log text. */
|
|
33
|
-
export function parseLogsWithRaw(
|
|
34
|
-
program: Program,
|
|
35
|
-
logs: string[],
|
|
36
|
-
programId = velocityProgramId
|
|
37
|
-
): { events: Event[]; rawLogs: string[] } {
|
|
38
|
-
const events = [];
|
|
39
|
-
const rawLogs = [];
|
|
40
|
-
const execution = new ExecutionContext();
|
|
41
|
-
for (const log of logs) {
|
|
42
|
-
if (log.startsWith('Log truncated')) {
|
|
43
|
-
break;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
const [event, newProgram, didPop] = handleLog(
|
|
47
|
-
execution,
|
|
48
|
-
log,
|
|
49
|
-
program,
|
|
50
|
-
programId
|
|
51
|
-
);
|
|
52
|
-
if (event) {
|
|
53
|
-
events.push(event);
|
|
54
|
-
rawLogs.push(log);
|
|
55
|
-
}
|
|
56
|
-
if (newProgram) {
|
|
57
|
-
execution.push(newProgram);
|
|
58
|
-
}
|
|
59
|
-
if (didPop) {
|
|
60
|
-
execution.pop();
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
return { events, rawLogs };
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
function handleLog(
|
|
67
|
-
execution: ExecutionContext,
|
|
68
|
-
log: string,
|
|
69
|
-
program: Program,
|
|
70
|
-
programId = velocityProgramId
|
|
71
|
-
): [Event | null, string | null, boolean] {
|
|
72
|
-
// Executing program is velocity program.
|
|
73
|
-
if (execution.stack.length > 0 && execution.program() === programId) {
|
|
74
|
-
return handleProgramLog(log, program, programId);
|
|
75
|
-
}
|
|
76
|
-
// Executing program is not velocity program.
|
|
77
|
-
else {
|
|
78
|
-
return [null, ...handleSystemLog(log, programId)];
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
// Handles logs from *velocity* program.
|
|
83
|
-
function handleProgramLog(
|
|
84
|
-
log: string,
|
|
85
|
-
program: Program,
|
|
86
|
-
programId = velocityProgramId
|
|
87
|
-
): [Event | null, string | null, boolean] {
|
|
88
|
-
// This is a `msg!` log or a `sol_log_data` log.
|
|
89
|
-
if (log.startsWith(PROGRAM_LOG)) {
|
|
90
|
-
const logStr = log.slice(PROGRAM_LOG_START_INDEX);
|
|
91
|
-
const event = program.coder.events.decode(logStr);
|
|
92
|
-
return [event, null, false];
|
|
93
|
-
} else if (log.startsWith(PROGRAM_DATA)) {
|
|
94
|
-
const logStr = log.slice(PROGRAM_DATA_START_INDEX);
|
|
95
|
-
const event = program.coder.events.decode(logStr);
|
|
96
|
-
return [event, null, false];
|
|
97
|
-
} else {
|
|
98
|
-
return [null, ...handleSystemLog(log, programId)];
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
// Handles logs when the current program being executing is *not* velocity.
|
|
103
|
-
function handleSystemLog(
|
|
104
|
-
log: string,
|
|
105
|
-
programId = velocityProgramId
|
|
106
|
-
): [string | null, boolean] {
|
|
107
|
-
// System component.
|
|
108
|
-
const logStart = log.split(':')[0];
|
|
109
|
-
const programStart = `Program ${programId} invoke`;
|
|
110
|
-
|
|
111
|
-
// Did the program finish executing?
|
|
112
|
-
if (logStart.match(/^Program (.*) success/g) !== null) {
|
|
113
|
-
return [null, true];
|
|
114
|
-
// Recursive call.
|
|
115
|
-
} else if (logStart.startsWith(programStart)) {
|
|
116
|
-
return [programId, false];
|
|
117
|
-
}
|
|
118
|
-
// CPI call.
|
|
119
|
-
else if (logStart.includes('invoke')) {
|
|
120
|
-
return ['cpi', false]; // Any string will do.
|
|
121
|
-
} else {
|
|
122
|
-
return [null, false];
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
// Stack frame execution context, allowing one to track what program is
|
|
127
|
-
// executing for a given log.
|
|
128
|
-
class ExecutionContext {
|
|
129
|
-
stack: string[] = [];
|
|
130
|
-
ixStack: string[] = [];
|
|
131
|
-
|
|
132
|
-
program(): string {
|
|
133
|
-
if (!this.stack.length) {
|
|
134
|
-
throw new Error('Expected the stack to have elements');
|
|
135
|
-
}
|
|
136
|
-
return this.stack[this.stack.length - 1];
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
push(newProgram: string) {
|
|
140
|
-
this.stack.push(newProgram);
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
pop() {
|
|
144
|
-
if (!this.stack.length) {
|
|
145
|
-
throw new Error('Expected the stack to have elements');
|
|
146
|
-
}
|
|
147
|
-
this.stack.pop();
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
ix(): string {
|
|
151
|
-
if (!this.ixStack.length) {
|
|
152
|
-
throw new Error('Expected the ix stack to have elements');
|
|
153
|
-
}
|
|
154
|
-
return this.ixStack[this.ixStack.length - 1];
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
pushIx(newIx: string) {
|
|
158
|
-
this.ixStack.push(newIx);
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
popIx() {
|
|
162
|
-
this.ixStack.pop();
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
/**
|
|
167
|
-
* Extracts per-instruction compute-unit usage from a transaction's raw logs
|
|
168
|
-
* by matching `Program log: Instruction: <name>` and
|
|
169
|
-
* `Program <id> consumed N of M compute units` lines while `programId` is
|
|
170
|
-
* the currently-executing program. Unlike `parseLogs`, this is not decoding
|
|
171
|
-
* a real on-chain `#[event]` — `CuUsage` is a synthetic event shape for
|
|
172
|
-
* client-side profiling.
|
|
173
|
-
* @param logs Raw `logMessages` for one transaction.
|
|
174
|
-
* @param programId Program ID whose CU consumption is measured; defaults to the Velocity program.
|
|
175
|
-
* @returns One `Event<CuUsage>` per top-level instruction invoking that program, in log order. `cuUsage` is in compute units.
|
|
176
|
-
*/
|
|
177
|
-
export function parseLogsForCuUsage(
|
|
178
|
-
logs: string[],
|
|
179
|
-
programId = velocityProgramId
|
|
180
|
-
): Event<any, CuUsageEvent>[] {
|
|
181
|
-
const cuUsageEvents: Event<any, CuUsageEvent>[] = [];
|
|
182
|
-
|
|
183
|
-
const execution = new ExecutionContext();
|
|
184
|
-
for (const log of logs) {
|
|
185
|
-
if (log.startsWith('Log truncated')) {
|
|
186
|
-
break;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
const [newProgram, newIx, didPopProgram, didPopIx] = handleLogForCuUsage(
|
|
190
|
-
execution,
|
|
191
|
-
log,
|
|
192
|
-
programId
|
|
193
|
-
);
|
|
194
|
-
if (newProgram) {
|
|
195
|
-
execution.push(newProgram);
|
|
196
|
-
}
|
|
197
|
-
if (newIx) {
|
|
198
|
-
execution.pushIx(newIx);
|
|
199
|
-
}
|
|
200
|
-
if (didPopProgram) {
|
|
201
|
-
execution.pop();
|
|
202
|
-
}
|
|
203
|
-
if (didPopIx !== null) {
|
|
204
|
-
cuUsageEvents.push({
|
|
205
|
-
name: 'CuUsage',
|
|
206
|
-
data: {
|
|
207
|
-
instruction: execution.ix(),
|
|
208
|
-
cuUsage: didPopIx!,
|
|
209
|
-
},
|
|
210
|
-
} as any);
|
|
211
|
-
execution.popIx();
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
return cuUsageEvents;
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
function handleLogForCuUsage(
|
|
218
|
-
execution: ExecutionContext,
|
|
219
|
-
log: string,
|
|
220
|
-
programId = velocityProgramId
|
|
221
|
-
): [string | null, string | null, boolean, number | null] {
|
|
222
|
-
if (execution.stack.length > 0 && execution.program() === programId) {
|
|
223
|
-
return handleProgramLogForCuUsage(log, programId);
|
|
224
|
-
} else {
|
|
225
|
-
return handleSystemLogForCuUsage(log, programId);
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
function handleProgramLogForCuUsage(
|
|
230
|
-
log: string,
|
|
231
|
-
programId = velocityProgramId
|
|
232
|
-
): [string | null, string | null, boolean, number | null] {
|
|
233
|
-
if (log.startsWith(PROGRAM_INSTRUCTION)) {
|
|
234
|
-
const ixStr = log.slice(PROGRAM_INSTRUCTION_START_INDEX);
|
|
235
|
-
return [null, ixStr, false, null];
|
|
236
|
-
} else {
|
|
237
|
-
return handleSystemLogForCuUsage(log, programId);
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
function handleSystemLogForCuUsage(
|
|
242
|
-
log: string,
|
|
243
|
-
programId = velocityProgramId
|
|
244
|
-
): [string | null, string | null, boolean, number | null] {
|
|
245
|
-
// System component.
|
|
246
|
-
const logStart = log.split(':')[0];
|
|
247
|
-
const programStart = `Program ${programId} invoke`;
|
|
248
|
-
|
|
249
|
-
// Did the program finish executing?
|
|
250
|
-
if (logStart.match(/^Program (.*) success/g) !== null) {
|
|
251
|
-
return [null, null, true, null];
|
|
252
|
-
// Recursive call.
|
|
253
|
-
} else if (logStart.startsWith(programStart)) {
|
|
254
|
-
return [programId, null, false, null];
|
|
255
|
-
// Consumed CU log.
|
|
256
|
-
} else if (log.startsWith(`Program ${programId} consumed `)) {
|
|
257
|
-
// Extract CU usage, e.g. 'Program ... consumed 29242 of 199700 compute units'
|
|
258
|
-
// We need to extract the consumed value (29242)
|
|
259
|
-
const matches = log.match(/consumed (\d+) of \d+ compute units/);
|
|
260
|
-
if (matches) {
|
|
261
|
-
return [null, null, false, Number(matches[1])];
|
|
262
|
-
}
|
|
263
|
-
return [null, null, false, null];
|
|
264
|
-
}
|
|
265
|
-
// CPI call.
|
|
266
|
-
else if (logStart.includes('invoke')) {
|
|
267
|
-
return ['cpi', null, false, null]; // Any string will do.
|
|
268
|
-
} else {
|
|
269
|
-
return [null, null, false, null];
|
|
270
|
-
}
|
|
271
|
-
}
|