@drift-labs/sdk 0.2.0-master.4 → 0.2.0-master.41
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 +27 -27
- package/lib/accounts/bulkAccountLoader.d.ts +2 -0
- package/lib/accounts/bulkAccountLoader.js +36 -29
- package/lib/accounts/bulkUserStatsSubscription.d.ts +7 -0
- package/lib/accounts/bulkUserStatsSubscription.js +21 -0
- package/lib/accounts/bulkUserSubscription.d.ts +2 -2
- package/lib/accounts/bulkUserSubscription.js +0 -1
- package/lib/accounts/fetch.d.ts +2 -1
- package/lib/accounts/fetch.js +9 -1
- package/lib/accounts/{pollingClearingHouseAccountSubscriber.d.ts → pollingDriftClientAccountSubscriber.d.ts} +20 -25
- package/lib/accounts/{pollingClearingHouseAccountSubscriber.js → pollingDriftClientAccountSubscriber.js} +45 -49
- package/lib/accounts/{pollingOracleSubscriber.d.ts → pollingOracleAccountSubscriber.d.ts} +2 -2
- package/lib/accounts/{pollingOracleSubscriber.js → pollingOracleAccountSubscriber.js} +3 -3
- package/lib/accounts/pollingUserAccountSubscriber.d.ts +1 -1
- package/lib/accounts/pollingUserAccountSubscriber.js +5 -11
- package/lib/accounts/pollingUserStatsAccountSubscriber.d.ts +27 -0
- package/lib/accounts/pollingUserStatsAccountSubscriber.js +107 -0
- package/lib/accounts/types.d.ts +26 -15
- package/lib/accounts/webSocketDriftClientAccountSubscriber.d.ts +49 -0
- package/lib/accounts/{webSocketClearingHouseAccountSubscriber.js → webSocketDriftClientAccountSubscriber.js} +47 -45
- package/lib/accounts/webSocketUserStatsAccountSubsriber.d.ts +20 -0
- package/lib/accounts/webSocketUserStatsAccountSubsriber.js +47 -0
- package/lib/addresses/marketAddresses.d.ts +1 -3
- package/lib/addresses/marketAddresses.js +1 -1
- package/lib/addresses/pda.d.ts +15 -9
- package/lib/addresses/pda.js +73 -35
- package/lib/adminClient.d.ts +65 -0
- package/lib/adminClient.js +637 -0
- package/lib/config.d.ts +9 -9
- package/lib/config.js +25 -21
- package/lib/constants/numericConstants.d.ts +30 -12
- package/lib/constants/numericConstants.js +41 -21
- package/lib/constants/perpMarkets.d.ts +18 -0
- package/lib/constants/{markets.js → perpMarkets.js} +7 -7
- package/lib/constants/spotMarkets.d.ts +19 -0
- package/lib/constants/spotMarkets.js +53 -0
- package/lib/dlob/DLOB.d.ts +82 -0
- package/lib/dlob/DLOB.js +694 -0
- package/lib/dlob/DLOBNode.d.ts +54 -0
- package/lib/dlob/DLOBNode.js +77 -0
- package/lib/dlob/NodeList.d.ts +27 -0
- package/lib/dlob/NodeList.js +144 -0
- package/lib/driftClient.d.ts +234 -0
- package/lib/driftClient.js +2108 -0
- package/lib/{clearingHouseConfig.d.ts → driftClientConfig.d.ts} +9 -9
- package/lib/{clearingHouseConfig.js → driftClientConfig.js} +0 -0
- package/lib/events/eventList.js +3 -0
- package/lib/events/eventSubscriber.d.ts +5 -2
- package/lib/events/eventSubscriber.js +25 -11
- package/lib/events/fetchLogs.d.ts +13 -2
- package/lib/events/fetchLogs.js +40 -12
- package/lib/events/pollingLogProvider.d.ts +2 -1
- package/lib/events/pollingLogProvider.js +7 -3
- package/lib/events/sort.js +8 -11
- package/lib/events/types.d.ts +11 -3
- package/lib/events/types.js +8 -0
- package/lib/events/webSocketLogProvider.js +1 -1
- package/lib/examples/makeTradeExample.js +30 -18
- package/lib/factory/bigNum.d.ts +8 -4
- package/lib/factory/bigNum.js +109 -19
- package/lib/idl/drift.json +8386 -0
- package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
- package/lib/index.d.ts +30 -13
- package/lib/index.js +30 -13
- package/lib/math/amm.d.ts +9 -6
- package/lib/math/amm.js +91 -38
- package/lib/math/conversion.js +1 -1
- package/lib/math/exchangeStatus.d.ts +4 -0
- package/lib/math/exchangeStatus.js +18 -0
- package/lib/math/funding.d.ts +6 -6
- package/lib/math/funding.js +23 -21
- package/lib/math/insurance.d.ts +4 -0
- package/lib/math/insurance.js +27 -0
- package/lib/math/margin.d.ts +11 -0
- package/lib/math/margin.js +82 -0
- package/lib/math/market.d.ts +14 -9
- package/lib/math/market.js +70 -10
- package/lib/math/oracles.d.ts +4 -0
- package/lib/math/oracles.js +36 -8
- package/lib/math/orders.d.ts +16 -6
- package/lib/math/orders.js +97 -17
- package/lib/math/position.d.ts +27 -13
- package/lib/math/position.js +92 -36
- package/lib/math/repeg.js +17 -8
- package/lib/math/spotBalance.d.ts +22 -0
- package/lib/math/spotBalance.js +192 -0
- package/lib/math/spotMarket.d.ts +4 -0
- package/lib/math/spotMarket.js +8 -0
- package/lib/math/spotPosition.d.ts +6 -0
- package/lib/math/spotPosition.js +23 -0
- package/lib/math/trade.d.ts +10 -10
- package/lib/math/trade.js +27 -31
- package/lib/oracles/pythClient.js +1 -1
- package/lib/oracles/quoteAssetOracleClient.js +1 -1
- package/lib/oracles/switchboardClient.js +1 -1
- package/lib/orderParams.d.ts +4 -4
- package/lib/orderParams.js +12 -4
- package/lib/serum/serumFulfillmentConfigMap.d.ts +10 -0
- package/lib/serum/serumFulfillmentConfigMap.js +17 -0
- package/lib/serum/serumSubscriber.d.ts +27 -0
- package/lib/serum/serumSubscriber.js +56 -0
- package/lib/serum/types.d.ts +11 -0
- package/lib/{clearingHouseUserConfig.js → serum/types.js} +0 -0
- package/lib/slot/SlotSubscriber.d.ts +7 -0
- package/lib/slot/SlotSubscriber.js +3 -0
- package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +8 -5
- package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +63 -51
- package/lib/tx/retryTxSender.d.ts +1 -1
- package/lib/tx/retryTxSender.js +13 -4
- package/lib/tx/types.d.ts +1 -1
- package/lib/tx/utils.js +1 -1
- package/lib/types.d.ts +688 -216
- package/lib/types.js +153 -24
- package/lib/user.d.ts +228 -0
- package/lib/user.js +959 -0
- package/lib/userConfig.d.ts +14 -0
- package/lib/userConfig.js +2 -0
- package/lib/userMap/userMap.d.ts +41 -0
- package/lib/userMap/userMap.js +85 -0
- package/lib/userMap/userStatsMap.d.ts +19 -0
- package/lib/userMap/userStatsMap.js +68 -0
- package/lib/userName.d.ts +1 -0
- package/lib/userName.js +3 -2
- package/lib/userStats.d.ts +18 -0
- package/lib/userStats.js +49 -0
- package/lib/userStatsConfig.d.ts +14 -0
- package/lib/userStatsConfig.js +2 -0
- package/lib/util/computeUnits.js +1 -1
- package/lib/util/getTokenAddress.d.ts +2 -0
- package/lib/util/getTokenAddress.js +9 -0
- package/package.json +11 -4
- package/src/accounts/bulkAccountLoader.ts +44 -34
- package/src/accounts/bulkUserStatsSubscription.ts +33 -0
- package/src/accounts/bulkUserSubscription.ts +2 -3
- package/src/accounts/fetch.ts +27 -2
- package/src/accounts/{pollingClearingHouseAccountSubscriber.ts → pollingDriftClientAccountSubscriber.ts} +65 -75
- package/src/accounts/{pollingOracleSubscriber.ts → pollingOracleAccountSubscriber.ts} +2 -2
- package/src/accounts/pollingUserAccountSubscriber.ts +5 -12
- package/src/accounts/pollingUserStatsAccountSubscriber.ts +166 -0
- package/src/accounts/types.ts +35 -15
- package/src/accounts/{webSocketClearingHouseAccountSubscriber.ts → webSocketDriftClientAccountSubscriber.ts} +78 -73
- package/src/accounts/webSocketUserStatsAccountSubsriber.ts +80 -0
- package/src/addresses/marketAddresses.ts +3 -4
- package/src/addresses/pda.ts +105 -33
- package/src/adminClient.ts +1207 -0
- package/src/assert/assert.js +9 -0
- package/src/config.ts +37 -31
- package/src/constants/numericConstants.ts +58 -24
- package/src/constants/{markets.ts → perpMarkets.ts} +10 -10
- package/src/constants/spotMarkets.ts +73 -0
- package/src/dlob/DLOB.ts +1120 -0
- package/src/dlob/DLOBNode.ts +155 -0
- package/src/dlob/NodeList.ts +195 -0
- package/src/driftClient.ts +3594 -0
- package/src/{clearingHouseConfig.ts → driftClientConfig.ts} +9 -8
- package/src/events/eventList.js +77 -0
- package/src/events/eventList.ts +3 -0
- package/src/events/eventSubscriber.ts +36 -14
- package/src/events/fetchLogs.ts +55 -13
- package/src/events/pollingLogProvider.ts +11 -3
- package/src/events/sort.ts +11 -15
- package/src/events/types.ts +27 -2
- package/src/events/webSocketLogProvider.ts +1 -1
- package/src/examples/makeTradeExample.js +157 -0
- package/src/examples/makeTradeExample.ts +44 -28
- package/src/factory/bigNum.ts +150 -22
- package/src/idl/drift.json +8386 -0
- package/src/idl/pyth.json +98 -2
- package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
- package/src/index.ts +30 -13
- package/src/math/amm.ts +161 -48
- package/src/math/conversion.ts +2 -2
- package/src/math/exchangeStatus.ts +31 -0
- package/src/math/funding.ts +41 -31
- package/src/math/insurance.ts +35 -0
- package/src/math/margin.ts +133 -0
- package/src/math/market.ts +143 -14
- package/src/math/oracles.ts +63 -9
- package/src/math/orders.ts +168 -26
- package/src/math/position.ts +136 -58
- package/src/math/repeg.ts +19 -9
- package/src/math/spotBalance.ts +319 -0
- package/src/math/spotMarket.ts +9 -0
- package/src/math/spotPosition.ts +47 -0
- package/src/math/trade.ts +33 -37
- package/src/oracles/pythClient.ts +2 -2
- package/src/oracles/quoteAssetOracleClient.ts +2 -2
- package/src/oracles/switchboardClient.ts +2 -2
- package/src/orderParams.ts +16 -8
- package/src/serum/serumFulfillmentConfigMap.ts +26 -0
- package/src/serum/serumSubscriber.ts +99 -0
- package/src/serum/types.ts +13 -0
- package/src/slot/SlotSubscriber.ts +11 -1
- package/src/token/index.js +38 -0
- package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
- package/src/tx/retryTxSender.ts +16 -5
- package/src/tx/types.js +2 -0
- package/src/tx/types.ts +2 -1
- package/src/tx/utils.js +17 -0
- package/src/tx/utils.ts +1 -1
- package/src/types.ts +650 -189
- package/src/user.ts +1599 -0
- package/src/{clearingHouseUserConfig.ts → userConfig.ts} +5 -5
- package/src/userMap/userMap.ts +124 -0
- package/src/userMap/userStatsMap.ts +108 -0
- package/src/userName.ts +2 -1
- package/src/userStats.ts +75 -0
- package/src/userStatsConfig.ts +18 -0
- package/src/util/computeUnits.js +21 -11
- package/src/util/computeUnits.ts +1 -1
- package/src/util/getTokenAddress.js +9 -0
- package/src/util/getTokenAddress.ts +18 -0
- package/src/util/promiseTimeout.js +14 -0
- package/src/util/tps.js +27 -0
- package/tests/bn/test.ts +46 -11
- package/tests/dlob/helpers.ts +620 -0
- package/tests/dlob/test.ts +4586 -0
- package/yarn-error.log +3160 -0
- package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +0 -49
- package/lib/admin.d.ts +0 -44
- package/lib/admin.js +0 -433
- package/lib/clearingHouse.d.ts +0 -133
- package/lib/clearingHouse.js +0 -931
- package/lib/clearingHouseUser.d.ts +0 -187
- package/lib/clearingHouseUser.js +0 -643
- package/lib/clearingHouseUserConfig.d.ts +0 -14
- package/lib/constants/banks.d.ts +0 -16
- package/lib/constants/banks.js +0 -34
- package/lib/constants/markets.d.ts +0 -19
- package/lib/idl/clearing_house.json +0 -3998
- package/lib/math/bankBalance.d.ts +0 -9
- package/lib/math/bankBalance.js +0 -75
- package/lib/math/state.d.ts +0 -8
- package/lib/math/state.js +0 -15
- package/lib/orders.d.ts +0 -8
- package/lib/orders.js +0 -134
- package/src/admin.ts +0 -722
- package/src/clearingHouse.ts +0 -1451
- package/src/clearingHouseUser.ts +0 -989
- package/src/constants/banks.ts +0 -43
- package/src/idl/clearing_house.json +0 -3998
- package/src/math/bankBalance.ts +0 -112
- package/src/math/state.ts +0 -14
- package/src/math/utils.js +0 -27
- package/src/math/utils.js.map +0 -1
- package/src/orders.ts +0 -244
- package/src/util/computeUnits.js.map +0 -1
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
/// <reference types="bn.js" />
|
|
2
1
|
import { ConfirmOptions, Connection, PublicKey } from '@solana/web3.js';
|
|
3
2
|
import { IWallet } from './types';
|
|
4
|
-
import { BN } from '@project-serum/anchor';
|
|
5
3
|
import { OracleInfo } from './oracles/types';
|
|
6
4
|
import { BulkAccountLoader } from './accounts/bulkAccountLoader';
|
|
7
5
|
import { DriftEnv } from './config';
|
|
8
|
-
export declare type
|
|
6
|
+
export declare type DriftClientConfig = {
|
|
9
7
|
connection: Connection;
|
|
10
8
|
wallet: IWallet;
|
|
11
9
|
programID: PublicKey;
|
|
12
|
-
accountSubscription?:
|
|
10
|
+
accountSubscription?: DriftClientSubscriptionConfig;
|
|
13
11
|
opts?: ConfirmOptions;
|
|
14
12
|
txSenderConfig?: TxSenderConfig;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
13
|
+
subAccountIds?: number[];
|
|
14
|
+
activeSubAccountId?: number;
|
|
15
|
+
perpMarketIndexes?: number[];
|
|
16
|
+
spotMarketIndexes?: number[];
|
|
19
17
|
oracleInfos?: OracleInfo[];
|
|
20
18
|
env?: DriftEnv;
|
|
19
|
+
userStats?: boolean;
|
|
20
|
+
authority?: PublicKey;
|
|
21
21
|
};
|
|
22
|
-
declare type
|
|
22
|
+
declare type DriftClientSubscriptionConfig = {
|
|
23
23
|
type: 'websocket';
|
|
24
24
|
} | {
|
|
25
25
|
type: 'polling';
|
|
File without changes
|
package/lib/events/eventList.js
CHANGED
|
@@ -15,10 +15,13 @@ export declare class EventSubscriber {
|
|
|
15
15
|
private awaitTxResolver;
|
|
16
16
|
private logProvider;
|
|
17
17
|
eventEmitter: StrictEventEmitter<EventEmitter, EventSubscriberEvents>;
|
|
18
|
+
private lastSeenSlot;
|
|
19
|
+
private lastSeenBlockTime;
|
|
20
|
+
lastSeenTxSig: string;
|
|
18
21
|
constructor(connection: Connection, program: Program, options?: EventSubscriptionOptions);
|
|
19
|
-
subscribe(): boolean
|
|
22
|
+
subscribe(): Promise<boolean>;
|
|
20
23
|
private handleTxLogs;
|
|
21
|
-
|
|
24
|
+
fetchPreviousTx(fetchMax?: boolean): Promise<void>;
|
|
22
25
|
unsubscribe(): Promise<boolean>;
|
|
23
26
|
private parseEventsFromLogs;
|
|
24
27
|
awaitTx(txSig: TransactionSignature): Promise<void>;
|
|
@@ -30,25 +30,32 @@ class EventSubscriber {
|
|
|
30
30
|
this.logProvider = new pollingLogProvider_1.PollingLogProvider(this.connection, this.program.programId, options.commitment, this.options.logProviderConfig.frequency);
|
|
31
31
|
}
|
|
32
32
|
}
|
|
33
|
-
subscribe() {
|
|
34
|
-
|
|
33
|
+
async subscribe() {
|
|
34
|
+
try {
|
|
35
|
+
if (this.logProvider.isSubscribed()) {
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
this.logProvider.subscribe((txSig, slot, logs, mostRecentBlockTime) => {
|
|
39
|
+
this.handleTxLogs(txSig, slot, logs, mostRecentBlockTime);
|
|
40
|
+
}, true);
|
|
35
41
|
return true;
|
|
36
42
|
}
|
|
37
|
-
|
|
43
|
+
catch (e) {
|
|
38
44
|
console.error('Error fetching previous txs in event subscriber');
|
|
39
45
|
console.error(e);
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
this.handleTxLogs(txSig, slot, logs);
|
|
43
|
-
});
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
44
48
|
}
|
|
45
|
-
handleTxLogs(txSig, slot, logs) {
|
|
49
|
+
handleTxLogs(txSig, slot, logs, mostRecentBlockTime) {
|
|
46
50
|
if (this.txEventCache.has(txSig)) {
|
|
47
51
|
return;
|
|
48
52
|
}
|
|
49
53
|
const wrappedEvents = this.parseEventsFromLogs(txSig, slot, logs);
|
|
50
54
|
for (const wrappedEvent of wrappedEvents) {
|
|
51
55
|
this.eventListMap.get(wrappedEvent.eventType).insert(wrappedEvent);
|
|
56
|
+
}
|
|
57
|
+
// dont emit event till we've added all the events to the eventListMap
|
|
58
|
+
for (const wrappedEvent of wrappedEvents) {
|
|
52
59
|
this.eventEmitter.emit('newEvent', wrappedEvent);
|
|
53
60
|
}
|
|
54
61
|
if (this.awaitTxPromises.has(txSig)) {
|
|
@@ -56,10 +63,17 @@ class EventSubscriber {
|
|
|
56
63
|
this.awaitTxResolver.get(txSig)();
|
|
57
64
|
this.awaitTxResolver.delete(txSig);
|
|
58
65
|
}
|
|
66
|
+
if (slot > this.lastSeenSlot) {
|
|
67
|
+
this.lastSeenTxSig = txSig;
|
|
68
|
+
}
|
|
69
|
+
if (this.lastSeenBlockTime === undefined ||
|
|
70
|
+
mostRecentBlockTime > this.lastSeenBlockTime) {
|
|
71
|
+
this.lastSeenBlockTime = mostRecentBlockTime;
|
|
72
|
+
}
|
|
59
73
|
this.txEventCache.add(txSig, wrappedEvents);
|
|
60
74
|
}
|
|
61
|
-
async fetchPreviousTx() {
|
|
62
|
-
if (!this.options.untilTx) {
|
|
75
|
+
async fetchPreviousTx(fetchMax) {
|
|
76
|
+
if (!this.options.untilTx && !fetchMax) {
|
|
63
77
|
return;
|
|
64
78
|
}
|
|
65
79
|
let txFetched = 0;
|
|
@@ -73,7 +87,7 @@ class EventSubscriber {
|
|
|
73
87
|
txFetched += response.transactionLogs.length;
|
|
74
88
|
beforeTx = response.earliestTx;
|
|
75
89
|
for (const { txSig, slot, logs } of response.transactionLogs) {
|
|
76
|
-
this.handleTxLogs(txSig, slot, logs);
|
|
90
|
+
this.handleTxLogs(txSig, slot, logs, response.mostRecentBlockTime);
|
|
77
91
|
}
|
|
78
92
|
}
|
|
79
93
|
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Program } from '@project-serum/anchor';
|
|
2
|
+
import { Connection, Finality, PublicKey, TransactionResponse, TransactionSignature } from '@solana/web3.js';
|
|
3
|
+
import { WrappedEvents } from './types';
|
|
2
4
|
declare type Log = {
|
|
3
5
|
txSig: TransactionSignature;
|
|
4
6
|
slot: number;
|
|
@@ -7,7 +9,16 @@ declare type Log = {
|
|
|
7
9
|
declare type FetchLogsResponse = {
|
|
8
10
|
earliestTx: string;
|
|
9
11
|
mostRecentTx: string;
|
|
12
|
+
earliestSlot: number;
|
|
13
|
+
mostRecentSlot: number;
|
|
10
14
|
transactionLogs: Log[];
|
|
15
|
+
mostRecentBlockTime: number | undefined;
|
|
11
16
|
};
|
|
12
|
-
export declare function fetchLogs(connection: Connection, programId: PublicKey, finality: Finality, beforeTx?: TransactionSignature, untilTx?: TransactionSignature): Promise<FetchLogsResponse
|
|
17
|
+
export declare function fetchLogs(connection: Connection, programId: PublicKey, finality: Finality, beforeTx?: TransactionSignature, untilTx?: TransactionSignature, limit?: number): Promise<FetchLogsResponse>;
|
|
18
|
+
export declare class LogParser {
|
|
19
|
+
private program;
|
|
20
|
+
constructor(program: Program);
|
|
21
|
+
parseEventsFromTransaction(transaction: TransactionResponse): WrappedEvents;
|
|
22
|
+
parseEventsFromLogs(event: Log): WrappedEvents;
|
|
23
|
+
}
|
|
13
24
|
export {};
|
package/lib/events/fetchLogs.js
CHANGED
|
@@ -1,12 +1,20 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.fetchLogs = void 0;
|
|
4
|
-
|
|
3
|
+
exports.LogParser = exports.fetchLogs = void 0;
|
|
4
|
+
function mapTransactionResponseToLog(transaction) {
|
|
5
|
+
return {
|
|
6
|
+
txSig: transaction.transaction.signatures[0],
|
|
7
|
+
slot: transaction.slot,
|
|
8
|
+
logs: transaction.meta.logMessages,
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
async function fetchLogs(connection, programId, finality, beforeTx, untilTx, limit) {
|
|
5
12
|
const signatures = await connection.getSignaturesForAddress(programId, {
|
|
6
13
|
before: beforeTx,
|
|
7
14
|
until: untilTx,
|
|
15
|
+
limit,
|
|
8
16
|
}, finality);
|
|
9
|
-
const sortedSignatures = signatures.sort((a, b) => a.slot < b.slot ? -1 : 1);
|
|
17
|
+
const sortedSignatures = signatures.sort((a, b) => a.slot === b.slot ? 0 : a.slot < b.slot ? -1 : 1);
|
|
10
18
|
const filteredSignatures = sortedSignatures.filter((signature) => !signature.err);
|
|
11
19
|
if (filteredSignatures.length === 0) {
|
|
12
20
|
return undefined;
|
|
@@ -15,19 +23,18 @@ async function fetchLogs(connection, programId, finality, beforeTx, untilTx) {
|
|
|
15
23
|
const transactionLogs = (await Promise.all(chunkedSignatures.map(async (chunk) => {
|
|
16
24
|
const transactions = await connection.getTransactions(chunk.map((confirmedSignature) => confirmedSignature.signature), finality);
|
|
17
25
|
return transactions.map((transaction) => {
|
|
18
|
-
return
|
|
19
|
-
txSig: transaction.transaction.signatures[0],
|
|
20
|
-
slot: transaction.slot,
|
|
21
|
-
logs: transaction.meta.logMessages,
|
|
22
|
-
};
|
|
26
|
+
return mapTransactionResponseToLog(transaction);
|
|
23
27
|
});
|
|
24
28
|
}))).flat();
|
|
25
|
-
const
|
|
26
|
-
const
|
|
29
|
+
const earliest = filteredSignatures[0];
|
|
30
|
+
const mostRecent = filteredSignatures[filteredSignatures.length - 1];
|
|
27
31
|
return {
|
|
28
32
|
transactionLogs: transactionLogs,
|
|
29
|
-
earliestTx:
|
|
30
|
-
mostRecentTx:
|
|
33
|
+
earliestTx: earliest.signature,
|
|
34
|
+
mostRecentTx: mostRecent.signature,
|
|
35
|
+
earliestSlot: earliest.slot,
|
|
36
|
+
mostRecentSlot: mostRecent.slot,
|
|
37
|
+
mostRecentBlockTime: mostRecent.blockTime,
|
|
31
38
|
};
|
|
32
39
|
}
|
|
33
40
|
exports.fetchLogs = fetchLogs;
|
|
@@ -37,3 +44,24 @@ function chunk(array, size) {
|
|
|
37
44
|
.map((_, index) => index * size)
|
|
38
45
|
.map((begin) => array.slice(begin, begin + size));
|
|
39
46
|
}
|
|
47
|
+
class LogParser {
|
|
48
|
+
constructor(program) {
|
|
49
|
+
this.program = program;
|
|
50
|
+
}
|
|
51
|
+
parseEventsFromTransaction(transaction) {
|
|
52
|
+
const transactionLogObject = mapTransactionResponseToLog(transaction);
|
|
53
|
+
return this.parseEventsFromLogs(transactionLogObject);
|
|
54
|
+
}
|
|
55
|
+
parseEventsFromLogs(event) {
|
|
56
|
+
const records = [];
|
|
57
|
+
// @ts-ignore
|
|
58
|
+
this.program._events._eventParser.parseLogs(event.logs, (eventLog) => {
|
|
59
|
+
eventLog.data.txSig = event.txSig;
|
|
60
|
+
eventLog.data.slot = event.slot;
|
|
61
|
+
eventLog.data.eventType = eventLog.name;
|
|
62
|
+
records.push(eventLog.data);
|
|
63
|
+
});
|
|
64
|
+
return records;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
exports.LogParser = LogParser;
|
|
@@ -8,8 +8,9 @@ export declare class PollingLogProvider implements LogProvider {
|
|
|
8
8
|
private intervalId;
|
|
9
9
|
private mostRecentSeenTx?;
|
|
10
10
|
private mutex;
|
|
11
|
+
private firstFetch;
|
|
11
12
|
constructor(connection: Connection, programId: PublicKey, commitment: Commitment, frequency?: number);
|
|
12
|
-
subscribe(callback: logProviderCallback): boolean;
|
|
13
|
+
subscribe(callback: logProviderCallback, skipHistory?: boolean): boolean;
|
|
13
14
|
isSubscribed(): boolean;
|
|
14
15
|
unsubscribe(): Promise<boolean>;
|
|
15
16
|
}
|
|
@@ -7,9 +7,10 @@ class PollingLogProvider {
|
|
|
7
7
|
this.connection = connection;
|
|
8
8
|
this.programId = programId;
|
|
9
9
|
this.frequency = frequency;
|
|
10
|
+
this.firstFetch = true;
|
|
10
11
|
this.finality = commitment === 'finalized' ? 'finalized' : 'confirmed';
|
|
11
12
|
}
|
|
12
|
-
subscribe(callback) {
|
|
13
|
+
subscribe(callback, skipHistory) {
|
|
13
14
|
if (this.intervalId) {
|
|
14
15
|
return true;
|
|
15
16
|
}
|
|
@@ -19,13 +20,16 @@ class PollingLogProvider {
|
|
|
19
20
|
}
|
|
20
21
|
this.mutex = 1;
|
|
21
22
|
try {
|
|
22
|
-
const response = await (0, fetchLogs_1.fetchLogs)(this.connection, this.programId, this.finality, undefined, this.mostRecentSeenTx
|
|
23
|
+
const response = await (0, fetchLogs_1.fetchLogs)(this.connection, this.programId, this.finality, undefined, this.mostRecentSeenTx,
|
|
24
|
+
// If skipping history, only fetch one log back, not the maximum amount available
|
|
25
|
+
skipHistory && this.firstFetch ? 1 : undefined);
|
|
26
|
+
this.firstFetch = false;
|
|
23
27
|
if (response === undefined) {
|
|
24
28
|
return;
|
|
25
29
|
}
|
|
26
30
|
const { mostRecentTx, transactionLogs } = response;
|
|
27
31
|
for (const { txSig, slot, logs } of transactionLogs) {
|
|
28
|
-
callback(txSig, slot, logs);
|
|
32
|
+
callback(txSig, slot, logs, response.mostRecentBlockTime);
|
|
29
33
|
}
|
|
30
34
|
this.mostRecentSeenTx = mostRecentTx;
|
|
31
35
|
}
|
package/lib/events/sort.js
CHANGED
|
@@ -11,17 +11,14 @@ function clientSortDescFn() {
|
|
|
11
11
|
function defaultBlockchainSortFn(currentEvent, newEvent) {
|
|
12
12
|
return currentEvent.slot <= newEvent.slot ? 'less than' : 'greater than';
|
|
13
13
|
}
|
|
14
|
-
function
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
? newEvent.makerOrder.marketIndex
|
|
20
|
-
: newEvent.takerOrder.marketIndex;
|
|
21
|
-
if (!currentEventMarketIndex.eq(newEventMarketIndex)) {
|
|
14
|
+
function orderActionRecordSortFn(currentEvent, newEvent) {
|
|
15
|
+
var _a, _b;
|
|
16
|
+
const currentEventMarketIndex = currentEvent.marketIndex;
|
|
17
|
+
const newEventMarketIndex = newEvent.marketIndex;
|
|
18
|
+
if (currentEventMarketIndex !== newEventMarketIndex) {
|
|
22
19
|
return currentEvent.ts.lte(newEvent.ts) ? 'less than' : 'greater than';
|
|
23
20
|
}
|
|
24
|
-
if (currentEvent.fillRecordId.gt(index_1.ZERO) && newEvent.fillRecordId.gt(index_1.ZERO)) {
|
|
21
|
+
if (((_a = currentEvent.fillRecordId) === null || _a === void 0 ? void 0 : _a.gt(index_1.ZERO)) && ((_b = newEvent.fillRecordId) === null || _b === void 0 ? void 0 : _b.gt(index_1.ZERO))) {
|
|
25
22
|
return currentEvent.fillRecordId.lte(newEvent.fillRecordId)
|
|
26
23
|
? 'less than'
|
|
27
24
|
: 'greater than';
|
|
@@ -35,8 +32,8 @@ function getSortFn(orderBy, orderDir, eventType) {
|
|
|
35
32
|
return orderDir === 'asc' ? clientSortAscFn : clientSortDescFn;
|
|
36
33
|
}
|
|
37
34
|
switch (eventType) {
|
|
38
|
-
case '
|
|
39
|
-
return
|
|
35
|
+
case 'OrderActionRecord':
|
|
36
|
+
return orderActionRecordSortFn;
|
|
40
37
|
default:
|
|
41
38
|
return defaultBlockchainSortFn;
|
|
42
39
|
}
|
package/lib/events/types.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Commitment, TransactionSignature } from '@solana/web3.js';
|
|
2
|
-
import { DepositRecord, FundingPaymentRecord, FundingRateRecord, LiquidationRecord, OrderRecord } from '../index';
|
|
2
|
+
import { DepositRecord, FundingPaymentRecord, FundingRateRecord, LiquidationRecord, NewUserRecord, OrderActionRecord, OrderRecord, SettlePnlRecord, LPRecord, InsuranceFundRecord, SpotInterestRecord, InsuranceFundStakeRecord, CurveRecord } from '../index';
|
|
3
3
|
export declare type EventSubscriptionOptions = {
|
|
4
4
|
eventTypes?: EventType[];
|
|
5
5
|
maxEventsPerType?: number;
|
|
@@ -27,16 +27,24 @@ export declare type EventMap = {
|
|
|
27
27
|
LiquidationRecord: Event<LiquidationRecord>;
|
|
28
28
|
FundingRateRecord: Event<FundingRateRecord>;
|
|
29
29
|
OrderRecord: Event<OrderRecord>;
|
|
30
|
+
OrderActionRecord: Event<OrderActionRecord>;
|
|
31
|
+
SettlePnlRecord: Event<SettlePnlRecord>;
|
|
32
|
+
NewUserRecord: Event<NewUserRecord>;
|
|
33
|
+
LPRecord: Event<LPRecord>;
|
|
34
|
+
InsuranceFundRecord: Event<InsuranceFundRecord>;
|
|
35
|
+
SpotInterestRecord: Event<SpotInterestRecord>;
|
|
36
|
+
InsuranceFundStakeRecord: Event<InsuranceFundStakeRecord>;
|
|
37
|
+
CurveRecord: Event<CurveRecord>;
|
|
30
38
|
};
|
|
31
39
|
export declare type EventType = keyof EventMap;
|
|
32
40
|
export interface EventSubscriberEvents {
|
|
33
41
|
newEvent: (event: WrappedEvent<EventType>) => void;
|
|
34
42
|
}
|
|
35
43
|
export declare type SortFn = (currentRecord: EventMap[EventType], newRecord: EventMap[EventType]) => 'less than' | 'greater than';
|
|
36
|
-
export declare type logProviderCallback = (txSig: TransactionSignature, slot: number, logs: string[]) => void;
|
|
44
|
+
export declare type logProviderCallback = (txSig: TransactionSignature, slot: number, logs: string[], mostRecentBlockTime: number | undefined) => void;
|
|
37
45
|
export interface LogProvider {
|
|
38
46
|
isSubscribed(): boolean;
|
|
39
|
-
subscribe(callback: logProviderCallback): boolean;
|
|
47
|
+
subscribe(callback: logProviderCallback, skipHistory?: boolean): boolean;
|
|
40
48
|
unsubscribe(): Promise<boolean>;
|
|
41
49
|
}
|
|
42
50
|
export declare type WebSocketLogProviderConfig = {
|
package/lib/events/types.js
CHANGED
|
@@ -7,7 +7,15 @@ exports.DefaultEventSubscriptionOptions = {
|
|
|
7
7
|
'FundingPaymentRecord',
|
|
8
8
|
'LiquidationRecord',
|
|
9
9
|
'OrderRecord',
|
|
10
|
+
'OrderActionRecord',
|
|
10
11
|
'FundingRateRecord',
|
|
12
|
+
'NewUserRecord',
|
|
13
|
+
'SettlePnlRecord',
|
|
14
|
+
'LPRecord',
|
|
15
|
+
'InsuranceFundRecord',
|
|
16
|
+
'SpotInterestRecord',
|
|
17
|
+
'InsuranceFundStakeRecord',
|
|
18
|
+
'CurveRecord',
|
|
11
19
|
],
|
|
12
20
|
maxEventsPerType: 4096,
|
|
13
21
|
orderBy: 'blockchain',
|
|
@@ -12,7 +12,7 @@ class WebSocketLogProvider {
|
|
|
12
12
|
return true;
|
|
13
13
|
}
|
|
14
14
|
this.subscriptionId = this.connection.onLogs(this.programId, (logs, ctx) => {
|
|
15
|
-
callback(logs.signature, ctx.slot, logs.logs);
|
|
15
|
+
callback(logs.signature, ctx.slot, logs.logs, undefined);
|
|
16
16
|
}, this.commitment);
|
|
17
17
|
return true;
|
|
18
18
|
}
|
|
@@ -6,14 +6,15 @@ const __1 = require("..");
|
|
|
6
6
|
const spl_token_1 = require("@solana/spl-token");
|
|
7
7
|
const web3_js_1 = require("@solana/web3.js");
|
|
8
8
|
const __2 = require("..");
|
|
9
|
-
const
|
|
9
|
+
const spotMarkets_1 = require("../constants/spotMarkets");
|
|
10
10
|
const getTokenAddress = (mintAddress, userPubKey) => {
|
|
11
11
|
return spl_token_1.Token.getAssociatedTokenAddress(new web3_js_1.PublicKey(`ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL`), spl_token_1.TOKEN_PROGRAM_ID, new web3_js_1.PublicKey(mintAddress), new web3_js_1.PublicKey(userPubKey));
|
|
12
12
|
};
|
|
13
13
|
exports.getTokenAddress = getTokenAddress;
|
|
14
|
+
const cluster = 'devnet';
|
|
14
15
|
const main = async () => {
|
|
15
16
|
// Initialize Drift SDK
|
|
16
|
-
const sdkConfig = (0, __2.initialize)({ env:
|
|
17
|
+
const sdkConfig = (0, __2.initialize)({ env: cluster });
|
|
17
18
|
// Set up the Wallet and Provider
|
|
18
19
|
const privateKey = process.env.BOT_PRIVATE_KEY; // stored as an array string
|
|
19
20
|
const keypair = web3_js_1.Keypair.fromSecretKey(Uint8Array.from(JSON.parse(privateKey)));
|
|
@@ -29,43 +30,54 @@ const main = async () => {
|
|
|
29
30
|
// Misc. other things to set up
|
|
30
31
|
const usdcTokenAddress = await (0, exports.getTokenAddress)(sdkConfig.USDC_MINT_ADDRESS, wallet.publicKey.toString());
|
|
31
32
|
// Set up the Drift Clearing House
|
|
32
|
-
const
|
|
33
|
-
const
|
|
33
|
+
const driftPublicKey = new web3_js_1.PublicKey(sdkConfig.CLEARING_HOUSE_PROGRAM_ID);
|
|
34
|
+
const bulkAccountLoader = new __2.BulkAccountLoader(connection, 'confirmed', 1000);
|
|
35
|
+
const driftClient = new __2.DriftClient({
|
|
34
36
|
connection,
|
|
35
37
|
wallet: provider.wallet,
|
|
36
|
-
programID:
|
|
38
|
+
programID: driftPublicKey,
|
|
39
|
+
perpMarketIndexes: __2.PerpMarkets[cluster].map((market) => market.marketIndex),
|
|
40
|
+
spotMarketIndexes: spotMarkets_1.SpotMarkets[cluster].map((spotMarket) => spotMarket.marketIndex),
|
|
41
|
+
accountSubscription: {
|
|
42
|
+
type: 'polling',
|
|
43
|
+
accountLoader: bulkAccountLoader,
|
|
44
|
+
},
|
|
37
45
|
});
|
|
38
|
-
await
|
|
46
|
+
await driftClient.subscribe();
|
|
39
47
|
// Set up Clearing House user client
|
|
40
|
-
const user = new __2.
|
|
41
|
-
|
|
42
|
-
userAccountPublicKey: await
|
|
48
|
+
const user = new __2.User({
|
|
49
|
+
driftClient: driftClient,
|
|
50
|
+
userAccountPublicKey: await driftClient.getUserAccountPublicKey(),
|
|
51
|
+
accountSubscription: {
|
|
52
|
+
type: 'polling',
|
|
53
|
+
accountLoader: bulkAccountLoader,
|
|
54
|
+
},
|
|
43
55
|
});
|
|
44
56
|
//// Check if clearing house account exists for the current wallet
|
|
45
57
|
const userAccountExists = await user.exists();
|
|
46
58
|
if (!userAccountExists) {
|
|
47
59
|
//// Create a Clearing House account by Depositing some USDC ($10,000 in this case)
|
|
48
60
|
const depositAmount = new anchor_1.BN(10000).mul(__2.QUOTE_PRECISION);
|
|
49
|
-
await
|
|
61
|
+
await driftClient.initializeUserAccountAndDepositCollateral(depositAmount, await (0, exports.getTokenAddress)(usdcTokenAddress.toString(), wallet.publicKey.toString()), spotMarkets_1.SpotMarkets['devnet'][0].marketIndex);
|
|
50
62
|
}
|
|
51
63
|
await user.subscribe();
|
|
52
64
|
// Get current price
|
|
53
|
-
const solMarketInfo = sdkConfig.
|
|
54
|
-
const currentMarketPrice = (0, __2.
|
|
55
|
-
const formattedPrice = (0, __2.convertToNumber)(currentMarketPrice, __2.
|
|
65
|
+
const solMarketInfo = sdkConfig.PERP_MARKETS.find((market) => market.baseAssetSymbol === 'SOL');
|
|
66
|
+
const currentMarketPrice = (0, __2.calculateReservePrice)(driftClient.getPerpMarketAccount(solMarketInfo.marketIndex), undefined);
|
|
67
|
+
const formattedPrice = (0, __2.convertToNumber)(currentMarketPrice, __2.PRICE_PRECISION);
|
|
56
68
|
console.log(`Current Market Price is $${formattedPrice}`);
|
|
57
69
|
// Estimate the slippage for a $5000 LONG trade
|
|
58
|
-
const solMarketAccount =
|
|
70
|
+
const solMarketAccount = driftClient.getPerpMarketAccount(solMarketInfo.marketIndex);
|
|
59
71
|
const longAmount = new anchor_1.BN(5000).mul(__2.QUOTE_PRECISION);
|
|
60
|
-
const slippage = (0, __2.convertToNumber)((0, __2.calculateTradeSlippage)(__2.PositionDirection.LONG, longAmount, solMarketAccount, 'quote', undefined)[0], __2.
|
|
72
|
+
const slippage = (0, __2.convertToNumber)((0, __2.calculateTradeSlippage)(__2.PositionDirection.LONG, longAmount, solMarketAccount, 'quote', undefined)[0], __2.PRICE_PRECISION);
|
|
61
73
|
console.log(`Slippage for a $5000 LONG on the SOL market would be $${slippage}`);
|
|
62
74
|
// Make a $5000 LONG trade
|
|
63
|
-
await
|
|
75
|
+
await driftClient.openPosition(__2.PositionDirection.LONG, longAmount, solMarketInfo.marketIndex);
|
|
64
76
|
console.log(`LONGED $5000 SOL`);
|
|
65
77
|
// Reduce the position by $2000
|
|
66
78
|
const reduceAmount = new anchor_1.BN(2000).mul(__2.QUOTE_PRECISION);
|
|
67
|
-
await
|
|
79
|
+
await driftClient.openPosition(__2.PositionDirection.SHORT, reduceAmount, solMarketInfo.marketIndex);
|
|
68
80
|
// Close the rest of the position
|
|
69
|
-
await
|
|
81
|
+
await driftClient.closePosition(solMarketInfo.marketIndex);
|
|
70
82
|
};
|
|
71
83
|
main();
|
package/lib/factory/bigNum.d.ts
CHANGED
|
@@ -5,7 +5,9 @@ export declare class BigNum {
|
|
|
5
5
|
precision: BN;
|
|
6
6
|
static delim: string;
|
|
7
7
|
static spacer: string;
|
|
8
|
+
static setLocale(locale: string): void;
|
|
8
9
|
constructor(val: BN | number | string, precisionVal?: BN | number | string);
|
|
10
|
+
private bigNumFromParam;
|
|
9
11
|
add(bn: BigNum): BigNum;
|
|
10
12
|
sub(bn: BigNum): BigNum;
|
|
11
13
|
mul(bn: BigNum | BN): BigNum;
|
|
@@ -67,14 +69,16 @@ export declare class BigNum {
|
|
|
67
69
|
* @param fixedPrecision
|
|
68
70
|
* @returns
|
|
69
71
|
*/
|
|
70
|
-
toFixed(fixedPrecision: number): string;
|
|
72
|
+
toFixed(fixedPrecision: number, rounded?: boolean): string;
|
|
73
|
+
private getZeroes;
|
|
74
|
+
toRounded(roundingPrecision: number): BigNum;
|
|
71
75
|
/**
|
|
72
76
|
* Pretty print to the specified number of significant figures
|
|
73
77
|
* @param fixedPrecision
|
|
74
78
|
* @returns
|
|
75
79
|
*/
|
|
76
|
-
toPrecision(fixedPrecision: number, trailingZeroes?: boolean): string;
|
|
77
|
-
toTradePrecision(): string;
|
|
80
|
+
toPrecision(fixedPrecision: number, trailingZeroes?: boolean, rounded?: boolean): string;
|
|
81
|
+
toTradePrecision(rounded?: boolean): string;
|
|
78
82
|
/**
|
|
79
83
|
* Print dollar formatted value. Defaults to fixed decimals two unless a given precision is given.
|
|
80
84
|
* @param useTradePrecision
|
|
@@ -82,7 +86,7 @@ export declare class BigNum {
|
|
|
82
86
|
* @returns
|
|
83
87
|
*/
|
|
84
88
|
toNotional(useTradePrecision?: boolean, precisionOverride?: number): string;
|
|
85
|
-
toMillified(precision?: number): string;
|
|
89
|
+
toMillified(precision?: number, rounded?: boolean): string;
|
|
86
90
|
toJSON(): {
|
|
87
91
|
val: string;
|
|
88
92
|
precision: string;
|