@drift-labs/sdk 0.1.36-master.7 → 0.2.0-master.2
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/lib/accounts/bulkAccountLoader.d.ts +6 -6
- package/lib/accounts/bulkAccountLoader.js +81 -95
- package/lib/accounts/bulkUserSubscription.js +13 -57
- package/lib/accounts/fetch.d.ts +4 -0
- package/lib/accounts/fetch.js +18 -0
- package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +34 -38
- package/lib/accounts/pollingClearingHouseAccountSubscriber.js +224 -224
- package/lib/accounts/pollingOracleSubscriber.d.ts +3 -3
- package/lib/accounts/pollingOracleSubscriber.js +37 -49
- package/lib/accounts/pollingTokenAccountSubscriber.d.ts +3 -3
- package/lib/accounts/pollingTokenAccountSubscriber.js +35 -50
- package/lib/accounts/pollingUserAccountSubscriber.d.ts +7 -13
- package/lib/accounts/pollingUserAccountSubscriber.js +71 -134
- package/lib/accounts/types.d.ts +34 -41
- package/lib/accounts/webSocketAccountSubscriber.d.ts +6 -4
- package/lib/accounts/webSocketAccountSubscriber.js +39 -35
- package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +33 -28
- package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +153 -185
- package/lib/accounts/webSocketUserAccountSubscriber.d.ts +5 -11
- package/lib/accounts/webSocketUserAccountSubscriber.js +22 -67
- package/lib/addresses/marketAddresses.d.ts +4 -0
- package/lib/addresses/marketAddresses.js +15 -0
- package/lib/addresses/pda.d.ts +12 -0
- package/lib/addresses/pda.js +83 -0
- package/lib/admin.d.ts +9 -17
- package/lib/admin.js +375 -558
- package/lib/clearingHouse.d.ts +86 -109
- package/lib/clearingHouse.js +828 -895
- package/lib/clearingHouseConfig.d.ts +34 -0
- package/lib/clearingHouseConfig.js +2 -0
- package/lib/clearingHouseUser.d.ts +19 -22
- package/lib/clearingHouseUser.js +155 -141
- package/lib/clearingHouseUserConfig.d.ts +14 -0
- package/lib/clearingHouseUserConfig.js +2 -0
- package/lib/config.d.ts +12 -0
- package/lib/config.js +35 -4
- package/lib/constants/banks.d.ts +16 -0
- package/lib/constants/banks.js +34 -0
- package/lib/constants/markets.d.ts +8 -3
- package/lib/constants/markets.js +13 -206
- package/lib/constants/numericConstants.d.ts +17 -0
- package/lib/constants/numericConstants.js +23 -6
- package/lib/events/eventList.d.ts +22 -0
- package/lib/events/eventList.js +77 -0
- package/lib/events/eventSubscriber.d.ts +34 -0
- package/lib/events/eventSubscriber.js +126 -0
- package/lib/events/fetchLogs.d.ts +13 -0
- package/lib/events/fetchLogs.js +39 -0
- package/lib/events/pollingLogProvider.d.ts +15 -0
- package/lib/events/pollingLogProvider.js +53 -0
- package/lib/events/sort.d.ts +2 -0
- package/lib/events/sort.js +44 -0
- package/lib/events/txEventCache.d.ts +24 -0
- package/lib/events/txEventCache.js +71 -0
- package/lib/events/types.d.ts +49 -0
- package/lib/events/types.js +20 -0
- package/lib/events/webSocketLogProvider.d.ts +12 -0
- package/lib/events/webSocketLogProvider.js +30 -0
- package/lib/examples/makeTradeExample.js +26 -27
- package/lib/factory/bigNum.d.ts +118 -0
- package/lib/factory/bigNum.js +364 -0
- package/lib/factory/oracleClient.d.ts +1 -2
- package/lib/factory/oracleClient.js +6 -2
- package/lib/idl/clearing_house.json +2287 -2938
- package/lib/index.d.ts +12 -4
- package/lib/index.js +12 -4
- package/lib/math/amm.d.ts +24 -29
- package/lib/math/amm.js +239 -178
- package/lib/math/auction.d.ts +5 -0
- package/lib/math/auction.js +39 -0
- package/lib/math/bankBalance.d.ts +9 -0
- package/lib/math/bankBalance.js +75 -0
- package/lib/math/conversion.d.ts +0 -1
- package/lib/math/conversion.js +1 -5
- package/lib/math/funding.d.ts +6 -6
- package/lib/math/funding.js +158 -175
- package/lib/math/market.d.ts +6 -6
- package/lib/math/market.js +10 -9
- package/lib/math/orders.d.ts +5 -0
- package/lib/math/orders.js +31 -1
- package/lib/math/position.d.ts +7 -5
- package/lib/math/position.js +27 -27
- package/lib/math/repeg.d.ts +22 -0
- package/lib/math/repeg.js +128 -0
- package/lib/math/trade.d.ts +5 -4
- package/lib/math/trade.js +29 -21
- package/lib/mockUSDCFaucet.js +87 -116
- package/lib/oracles/oracleClientCache.d.ts +8 -0
- package/lib/oracles/oracleClientCache.js +19 -0
- package/lib/oracles/pythClient.d.ts +3 -5
- package/lib/oracles/pythClient.js +12 -31
- package/lib/oracles/quoteAssetOracleClient.d.ts +9 -0
- package/lib/oracles/quoteAssetOracleClient.js +21 -0
- package/lib/oracles/switchboardClient.d.ts +3 -5
- package/lib/oracles/switchboardClient.js +29 -50
- package/lib/oracles/types.d.ts +6 -1
- package/lib/orders.d.ts +6 -7
- package/lib/orders.js +10 -80
- package/lib/slot/SlotSubscriber.d.ts +12 -0
- package/lib/slot/SlotSubscriber.js +23 -0
- package/lib/tx/retryTxSender.d.ts +2 -2
- package/lib/tx/retryTxSender.js +108 -123
- package/lib/tx/types.d.ts +5 -1
- package/lib/tx/utils.d.ts +1 -1
- package/lib/tx/utils.js +11 -2
- package/lib/types.d.ts +110 -109
- package/lib/types.js +14 -1
- package/lib/userName.d.ts +4 -0
- package/lib/userName.js +20 -0
- package/lib/util/computeUnits.js +10 -21
- package/lib/util/tps.js +11 -22
- package/lib/wallet.js +7 -20
- package/package.json +11 -4
- package/src/accounts/bulkAccountLoader.ts +21 -15
- package/src/accounts/bulkUserSubscription.ts +1 -45
- package/src/accounts/fetch.ts +33 -0
- package/src/accounts/pollingClearingHouseAccountSubscriber.ts +249 -214
- package/src/accounts/pollingOracleSubscriber.ts +16 -8
- package/src/accounts/pollingTokenAccountSubscriber.ts +11 -8
- package/src/accounts/pollingUserAccountSubscriber.ts +21 -86
- package/src/accounts/types.ts +41 -70
- package/src/accounts/webSocketAccountSubscriber.ts +33 -16
- package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +190 -240
- package/src/accounts/webSocketUserAccountSubscriber.ts +11 -71
- package/src/addresses/marketAddresses.ts +18 -0
- package/src/addresses/pda.ts +118 -0
- package/src/admin.ts +218 -346
- package/src/clearingHouse.ts +983 -952
- package/src/clearingHouseConfig.ts +37 -0
- package/src/clearingHouseUser.ts +275 -185
- package/src/clearingHouseUserConfig.ts +18 -0
- package/src/config.ts +54 -1
- package/src/constants/banks.ts +43 -0
- package/src/constants/markets.ts +16 -207
- package/src/constants/numericConstants.ts +34 -5
- package/src/events/eventList.ts +94 -0
- package/src/events/eventSubscriber.ts +194 -0
- package/src/events/fetchLogs.ts +80 -0
- package/src/events/pollingLogProvider.ts +79 -0
- package/src/events/sort.ts +65 -0
- package/src/events/txEventCache.ts +74 -0
- package/src/events/types.ts +98 -0
- package/src/events/webSocketLogProvider.ts +38 -0
- package/src/examples/makeTradeExample.ts +20 -11
- package/src/factory/bigNum.ts +524 -0
- package/src/factory/oracleClient.ts +7 -4
- package/src/idl/clearing_house.json +2287 -2938
- package/src/index.ts +12 -4
- package/src/math/amm.ts +414 -245
- package/src/math/auction.ts +39 -0
- package/src/math/bankBalance.ts +112 -0
- package/src/math/conversion.ts +1 -11
- package/src/math/funding.ts +12 -9
- package/src/math/market.ts +37 -30
- package/src/math/orders.ts +38 -0
- package/src/math/position.ts +48 -35
- package/src/math/repeg.ts +176 -0
- package/src/math/trade.ts +45 -35
- package/src/math/utils.js +27 -0
- package/src/math/utils.js.map +1 -0
- package/src/oracles/oracleClientCache.ts +20 -0
- package/src/oracles/pythClient.ts +4 -11
- package/src/oracles/quoteAssetOracleClient.ts +25 -0
- package/src/oracles/switchboardClient.ts +11 -24
- package/src/oracles/types.ts +7 -1
- package/src/orders.ts +24 -126
- package/src/slot/SlotSubscriber.ts +32 -0
- package/src/tx/retryTxSender.ts +6 -4
- package/src/tx/types.ts +6 -1
- package/src/tx/utils.ts +22 -3
- package/src/types.ts +111 -122
- package/src/userName.ts +20 -0
- package/src/util/computeUnits.js +17 -0
- package/src/util/computeUnits.js.map +1 -0
- package/tests/bn/test.ts +255 -0
- package/tsconfig.json +12 -12
- package/lib/addresses.d.ts +0 -10
- package/lib/addresses.js +0 -93
- package/lib/constants/accounts.d.ts +0 -15
- package/lib/constants/accounts.js +0 -18
- package/lib/factory/clearingHouse.d.ts +0 -35
- package/lib/factory/clearingHouse.js +0 -81
- package/lib/factory/clearingHouseUser.d.ts +0 -19
- package/lib/factory/clearingHouseUser.js +0 -34
- package/lib/math/insuranceFund.d.ts +0 -15
- package/lib/math/insuranceFund.js +0 -33
- package/lib/settlement.d.ts +0 -4
- package/lib/settlement.js +0 -10
- package/lib/tx/defaultTxSender.d.ts +0 -8
- package/lib/tx/defaultTxSender.js +0 -12
- package/src/addresses.ts +0 -82
- package/src/constants/accounts.ts +0 -26
- package/src/factory/clearingHouse.ts +0 -173
- package/src/factory/clearingHouseUser.ts +0 -73
- package/src/math/insuranceFund.ts +0 -29
- package/src/settlement.ts +0 -9
- package/src/tx/defaultTxSender.ts +0 -24
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.EventSubscriber = void 0;
|
|
4
|
+
const types_1 = require("./types");
|
|
5
|
+
const txEventCache_1 = require("./txEventCache");
|
|
6
|
+
const eventList_1 = require("./eventList");
|
|
7
|
+
const pollingLogProvider_1 = require("./pollingLogProvider");
|
|
8
|
+
const fetchLogs_1 = require("./fetchLogs");
|
|
9
|
+
const webSocketLogProvider_1 = require("./webSocketLogProvider");
|
|
10
|
+
const events_1 = require("events");
|
|
11
|
+
const sort_1 = require("./sort");
|
|
12
|
+
class EventSubscriber {
|
|
13
|
+
constructor(connection, program, options = types_1.DefaultEventSubscriptionOptions) {
|
|
14
|
+
this.connection = connection;
|
|
15
|
+
this.program = program;
|
|
16
|
+
this.options = options;
|
|
17
|
+
this.awaitTxPromises = new Map();
|
|
18
|
+
this.awaitTxResolver = new Map();
|
|
19
|
+
this.options = Object.assign({}, types_1.DefaultEventSubscriptionOptions, options);
|
|
20
|
+
this.txEventCache = new txEventCache_1.TxEventCache(this.options.maxTx);
|
|
21
|
+
this.eventListMap = new Map();
|
|
22
|
+
for (const eventType of this.options.eventTypes) {
|
|
23
|
+
this.eventListMap.set(eventType, new eventList_1.EventList(eventType, this.options.maxEventsPerType, (0, sort_1.getSortFn)(this.options.orderBy, this.options.orderDir, eventType), this.options.orderDir));
|
|
24
|
+
}
|
|
25
|
+
this.eventEmitter = new events_1.EventEmitter();
|
|
26
|
+
if (this.options.logProviderConfig.type === 'websocket') {
|
|
27
|
+
this.logProvider = new webSocketLogProvider_1.WebSocketLogProvider(this.connection, this.program.programId, this.options.commitment);
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
this.logProvider = new pollingLogProvider_1.PollingLogProvider(this.connection, this.program.programId, options.commitment, this.options.logProviderConfig.frequency);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
subscribe() {
|
|
34
|
+
if (this.logProvider.isSubscribed()) {
|
|
35
|
+
return true;
|
|
36
|
+
}
|
|
37
|
+
this.fetchPreviousTx().catch((e) => {
|
|
38
|
+
console.error('Error fetching previous txs in event subscriber');
|
|
39
|
+
console.error(e);
|
|
40
|
+
});
|
|
41
|
+
return this.logProvider.subscribe((txSig, slot, logs) => {
|
|
42
|
+
this.handleTxLogs(txSig, slot, logs);
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
handleTxLogs(txSig, slot, logs) {
|
|
46
|
+
if (this.txEventCache.has(txSig)) {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const wrappedEvents = this.parseEventsFromLogs(txSig, slot, logs);
|
|
50
|
+
for (const wrappedEvent of wrappedEvents) {
|
|
51
|
+
this.eventListMap.get(wrappedEvent.eventType).insert(wrappedEvent);
|
|
52
|
+
this.eventEmitter.emit('newEvent', wrappedEvent);
|
|
53
|
+
}
|
|
54
|
+
if (this.awaitTxPromises.has(txSig)) {
|
|
55
|
+
this.awaitTxPromises.delete(txSig);
|
|
56
|
+
this.awaitTxResolver.get(txSig)();
|
|
57
|
+
this.awaitTxResolver.delete(txSig);
|
|
58
|
+
}
|
|
59
|
+
this.txEventCache.add(txSig, wrappedEvents);
|
|
60
|
+
}
|
|
61
|
+
async fetchPreviousTx() {
|
|
62
|
+
if (!this.options.untilTx) {
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
let txFetched = 0;
|
|
66
|
+
let beforeTx = undefined;
|
|
67
|
+
const untilTx = this.options.untilTx;
|
|
68
|
+
while (txFetched < this.options.maxTx) {
|
|
69
|
+
const response = await (0, fetchLogs_1.fetchLogs)(this.connection, this.program.programId, this.options.commitment === 'finalized' ? 'finalized' : 'confirmed', beforeTx, untilTx);
|
|
70
|
+
if (response === undefined) {
|
|
71
|
+
break;
|
|
72
|
+
}
|
|
73
|
+
txFetched += response.transactionLogs.length;
|
|
74
|
+
beforeTx = response.earliestTx;
|
|
75
|
+
for (const { txSig, slot, logs } of response.transactionLogs) {
|
|
76
|
+
this.handleTxLogs(txSig, slot, logs);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
async unsubscribe() {
|
|
81
|
+
return await this.logProvider.unsubscribe();
|
|
82
|
+
}
|
|
83
|
+
parseEventsFromLogs(txSig, slot, logs) {
|
|
84
|
+
const records = [];
|
|
85
|
+
// @ts-ignore
|
|
86
|
+
this.program._events._eventParser.parseLogs(logs, (event) => {
|
|
87
|
+
const expectRecordType = this.eventListMap.has(event.name);
|
|
88
|
+
if (expectRecordType) {
|
|
89
|
+
event.data.txSig = txSig;
|
|
90
|
+
event.data.slot = slot;
|
|
91
|
+
event.data.eventType = event.name;
|
|
92
|
+
records.push(event.data);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
return records;
|
|
96
|
+
}
|
|
97
|
+
awaitTx(txSig) {
|
|
98
|
+
if (this.awaitTxPromises.has(txSig)) {
|
|
99
|
+
return this.awaitTxPromises.get(txSig);
|
|
100
|
+
}
|
|
101
|
+
if (this.txEventCache.has(txSig)) {
|
|
102
|
+
return Promise.resolve();
|
|
103
|
+
}
|
|
104
|
+
const promise = new Promise((resolve) => {
|
|
105
|
+
this.awaitTxResolver.set(txSig, resolve);
|
|
106
|
+
});
|
|
107
|
+
this.awaitTxPromises.set(txSig, promise);
|
|
108
|
+
return promise;
|
|
109
|
+
}
|
|
110
|
+
getEventList(eventType) {
|
|
111
|
+
return this.eventListMap.get(eventType);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* This requires the EventList be cast to an array, which requires reallocation of memory.
|
|
115
|
+
* Would bias to using getEventList over getEvents
|
|
116
|
+
*
|
|
117
|
+
* @param eventType
|
|
118
|
+
*/
|
|
119
|
+
getEventsArray(eventType) {
|
|
120
|
+
return this.eventListMap.get(eventType).toArray();
|
|
121
|
+
}
|
|
122
|
+
getEventsByTx(txSig) {
|
|
123
|
+
return this.txEventCache.get(txSig);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
exports.EventSubscriber = EventSubscriber;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Connection, Finality, PublicKey, TransactionSignature } from '@solana/web3.js';
|
|
2
|
+
declare type Log = {
|
|
3
|
+
txSig: TransactionSignature;
|
|
4
|
+
slot: number;
|
|
5
|
+
logs: string[];
|
|
6
|
+
};
|
|
7
|
+
declare type FetchLogsResponse = {
|
|
8
|
+
earliestTx: string;
|
|
9
|
+
mostRecentTx: string;
|
|
10
|
+
transactionLogs: Log[];
|
|
11
|
+
};
|
|
12
|
+
export declare function fetchLogs(connection: Connection, programId: PublicKey, finality: Finality, beforeTx?: TransactionSignature, untilTx?: TransactionSignature): Promise<FetchLogsResponse | undefined>;
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.fetchLogs = void 0;
|
|
4
|
+
async function fetchLogs(connection, programId, finality, beforeTx, untilTx) {
|
|
5
|
+
const signatures = await connection.getSignaturesForAddress(programId, {
|
|
6
|
+
before: beforeTx,
|
|
7
|
+
until: untilTx,
|
|
8
|
+
}, finality);
|
|
9
|
+
const sortedSignatures = signatures.sort((a, b) => a.slot < b.slot ? -1 : 1);
|
|
10
|
+
const filteredSignatures = sortedSignatures.filter((signature) => !signature.err);
|
|
11
|
+
if (filteredSignatures.length === 0) {
|
|
12
|
+
return undefined;
|
|
13
|
+
}
|
|
14
|
+
const chunkedSignatures = chunk(filteredSignatures, 100);
|
|
15
|
+
const transactionLogs = (await Promise.all(chunkedSignatures.map(async (chunk) => {
|
|
16
|
+
const transactions = await connection.getTransactions(chunk.map((confirmedSignature) => confirmedSignature.signature), finality);
|
|
17
|
+
return transactions.map((transaction) => {
|
|
18
|
+
return {
|
|
19
|
+
txSig: transaction.transaction.signatures[0],
|
|
20
|
+
slot: transaction.slot,
|
|
21
|
+
logs: transaction.meta.logMessages,
|
|
22
|
+
};
|
|
23
|
+
});
|
|
24
|
+
}))).flat();
|
|
25
|
+
const earliestTx = filteredSignatures[0].signature;
|
|
26
|
+
const mostRecentTx = filteredSignatures[filteredSignatures.length - 1].signature;
|
|
27
|
+
return {
|
|
28
|
+
transactionLogs: transactionLogs,
|
|
29
|
+
earliestTx: earliestTx,
|
|
30
|
+
mostRecentTx: mostRecentTx,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
exports.fetchLogs = fetchLogs;
|
|
34
|
+
function chunk(array, size) {
|
|
35
|
+
return new Array(Math.ceil(array.length / size))
|
|
36
|
+
.fill(null)
|
|
37
|
+
.map((_, index) => index * size)
|
|
38
|
+
.map((begin) => array.slice(begin, begin + size));
|
|
39
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { LogProvider, logProviderCallback } from './types';
|
|
2
|
+
import { Commitment, Connection, PublicKey } from '@solana/web3.js';
|
|
3
|
+
export declare class PollingLogProvider implements LogProvider {
|
|
4
|
+
private connection;
|
|
5
|
+
private programId;
|
|
6
|
+
private frequency;
|
|
7
|
+
private finality;
|
|
8
|
+
private intervalId;
|
|
9
|
+
private mostRecentSeenTx?;
|
|
10
|
+
private mutex;
|
|
11
|
+
constructor(connection: Connection, programId: PublicKey, commitment: Commitment, frequency?: number);
|
|
12
|
+
subscribe(callback: logProviderCallback): boolean;
|
|
13
|
+
isSubscribed(): boolean;
|
|
14
|
+
unsubscribe(): Promise<boolean>;
|
|
15
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PollingLogProvider = void 0;
|
|
4
|
+
const fetchLogs_1 = require("./fetchLogs");
|
|
5
|
+
class PollingLogProvider {
|
|
6
|
+
constructor(connection, programId, commitment, frequency = 15 * 1000) {
|
|
7
|
+
this.connection = connection;
|
|
8
|
+
this.programId = programId;
|
|
9
|
+
this.frequency = frequency;
|
|
10
|
+
this.finality = commitment === 'finalized' ? 'finalized' : 'confirmed';
|
|
11
|
+
}
|
|
12
|
+
subscribe(callback) {
|
|
13
|
+
if (this.intervalId) {
|
|
14
|
+
return true;
|
|
15
|
+
}
|
|
16
|
+
this.intervalId = setInterval(async () => {
|
|
17
|
+
if (this.mutex === 1) {
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
this.mutex = 1;
|
|
21
|
+
try {
|
|
22
|
+
const response = await (0, fetchLogs_1.fetchLogs)(this.connection, this.programId, this.finality, undefined, this.mostRecentSeenTx);
|
|
23
|
+
if (response === undefined) {
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
const { mostRecentTx, transactionLogs } = response;
|
|
27
|
+
for (const { txSig, slot, logs } of transactionLogs) {
|
|
28
|
+
callback(txSig, slot, logs);
|
|
29
|
+
}
|
|
30
|
+
this.mostRecentSeenTx = mostRecentTx;
|
|
31
|
+
}
|
|
32
|
+
catch (e) {
|
|
33
|
+
console.error('PollingLogProvider threw an Error');
|
|
34
|
+
console.error(e);
|
|
35
|
+
}
|
|
36
|
+
finally {
|
|
37
|
+
this.mutex = 0;
|
|
38
|
+
}
|
|
39
|
+
}, this.frequency);
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
isSubscribed() {
|
|
43
|
+
return this.intervalId !== undefined;
|
|
44
|
+
}
|
|
45
|
+
async unsubscribe() {
|
|
46
|
+
if (this.intervalId !== undefined) {
|
|
47
|
+
clearInterval(this.intervalId);
|
|
48
|
+
this.intervalId = undefined;
|
|
49
|
+
}
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
exports.PollingLogProvider = PollingLogProvider;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getSortFn = void 0;
|
|
4
|
+
const index_1 = require("../index");
|
|
5
|
+
function clientSortAscFn() {
|
|
6
|
+
return 'less than';
|
|
7
|
+
}
|
|
8
|
+
function clientSortDescFn() {
|
|
9
|
+
return 'greater than';
|
|
10
|
+
}
|
|
11
|
+
function defaultBlockchainSortFn(currentEvent, newEvent) {
|
|
12
|
+
return currentEvent.slot <= newEvent.slot ? 'less than' : 'greater than';
|
|
13
|
+
}
|
|
14
|
+
function orderRecordSortFn(currentEvent, newEvent) {
|
|
15
|
+
const currentEventMarketIndex = !currentEvent.maker.equals(index_1.PublicKey.default)
|
|
16
|
+
? currentEvent.makerOrder.marketIndex
|
|
17
|
+
: currentEvent.takerOrder.marketIndex;
|
|
18
|
+
const newEventMarketIndex = !newEvent.maker.equals(index_1.PublicKey.default)
|
|
19
|
+
? newEvent.makerOrder.marketIndex
|
|
20
|
+
: newEvent.takerOrder.marketIndex;
|
|
21
|
+
if (!currentEventMarketIndex.eq(newEventMarketIndex)) {
|
|
22
|
+
return currentEvent.ts.lte(newEvent.ts) ? 'less than' : 'greater than';
|
|
23
|
+
}
|
|
24
|
+
if (currentEvent.fillRecordId.gt(index_1.ZERO) && newEvent.fillRecordId.gt(index_1.ZERO)) {
|
|
25
|
+
return currentEvent.fillRecordId.lte(newEvent.fillRecordId)
|
|
26
|
+
? 'less than'
|
|
27
|
+
: 'greater than';
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
return currentEvent.ts.lte(newEvent.ts) ? 'less than' : 'greater than';
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function getSortFn(orderBy, orderDir, eventType) {
|
|
34
|
+
if (orderBy === 'client') {
|
|
35
|
+
return orderDir === 'asc' ? clientSortAscFn : clientSortDescFn;
|
|
36
|
+
}
|
|
37
|
+
switch (eventType) {
|
|
38
|
+
case 'OrderRecord':
|
|
39
|
+
return orderRecordSortFn;
|
|
40
|
+
default:
|
|
41
|
+
return defaultBlockchainSortFn;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
exports.getSortFn = getSortFn;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { WrappedEvent, EventType } from './types';
|
|
2
|
+
declare class Node {
|
|
3
|
+
key: string;
|
|
4
|
+
value: WrappedEvent<EventType>[];
|
|
5
|
+
next?: Node;
|
|
6
|
+
prev?: Node;
|
|
7
|
+
constructor(key: string, value: WrappedEvent<EventType>[], next?: Node, prev?: Node);
|
|
8
|
+
}
|
|
9
|
+
export declare class TxEventCache {
|
|
10
|
+
maxTx: number;
|
|
11
|
+
size: number;
|
|
12
|
+
head?: Node;
|
|
13
|
+
tail?: Node;
|
|
14
|
+
cacheMap: {
|
|
15
|
+
[key: string]: Node;
|
|
16
|
+
};
|
|
17
|
+
constructor(maxTx?: number);
|
|
18
|
+
add(key: string, events: WrappedEvent<EventType>[]): void;
|
|
19
|
+
has(key: string): boolean;
|
|
20
|
+
get(key: string): WrappedEvent<EventType>[] | undefined;
|
|
21
|
+
detach(node: Node): void;
|
|
22
|
+
clear(): void;
|
|
23
|
+
}
|
|
24
|
+
export {};
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TxEventCache = void 0;
|
|
4
|
+
class Node {
|
|
5
|
+
constructor(key, value, next, prev) {
|
|
6
|
+
this.key = key;
|
|
7
|
+
this.value = value;
|
|
8
|
+
this.next = next;
|
|
9
|
+
this.prev = prev;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
// lru cache
|
|
13
|
+
class TxEventCache {
|
|
14
|
+
constructor(maxTx = 1024) {
|
|
15
|
+
this.maxTx = maxTx;
|
|
16
|
+
this.size = 0;
|
|
17
|
+
this.cacheMap = {};
|
|
18
|
+
}
|
|
19
|
+
add(key, events) {
|
|
20
|
+
const existingNode = this.cacheMap[key];
|
|
21
|
+
if (existingNode) {
|
|
22
|
+
this.detach(existingNode);
|
|
23
|
+
this.size--;
|
|
24
|
+
}
|
|
25
|
+
else if (this.size === this.maxTx) {
|
|
26
|
+
delete this.cacheMap[this.tail.key];
|
|
27
|
+
this.detach(this.tail);
|
|
28
|
+
this.size--;
|
|
29
|
+
}
|
|
30
|
+
// Write to head of LinkedList
|
|
31
|
+
if (!this.head) {
|
|
32
|
+
this.head = this.tail = new Node(key, events);
|
|
33
|
+
}
|
|
34
|
+
else {
|
|
35
|
+
const node = new Node(key, events, this.head);
|
|
36
|
+
this.head.prev = node;
|
|
37
|
+
this.head = node;
|
|
38
|
+
}
|
|
39
|
+
// update cacheMap with LinkedList key and Node reference
|
|
40
|
+
this.cacheMap[key] = this.head;
|
|
41
|
+
this.size++;
|
|
42
|
+
}
|
|
43
|
+
has(key) {
|
|
44
|
+
return this.cacheMap.hasOwnProperty(key);
|
|
45
|
+
}
|
|
46
|
+
get(key) {
|
|
47
|
+
var _a;
|
|
48
|
+
return (_a = this.cacheMap[key]) === null || _a === void 0 ? void 0 : _a.value;
|
|
49
|
+
}
|
|
50
|
+
detach(node) {
|
|
51
|
+
if (node.prev !== undefined) {
|
|
52
|
+
node.prev.next = node.next;
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
this.head = node.next;
|
|
56
|
+
}
|
|
57
|
+
if (node.next !== undefined) {
|
|
58
|
+
node.next.prev = node.prev;
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
this.tail = node.prev;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
clear() {
|
|
65
|
+
this.head = undefined;
|
|
66
|
+
this.tail = undefined;
|
|
67
|
+
this.size = 0;
|
|
68
|
+
this.cacheMap = {};
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
exports.TxEventCache = TxEventCache;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { Commitment, TransactionSignature } from '@solana/web3.js';
|
|
2
|
+
import { DepositRecord, FundingPaymentRecord, FundingRateRecord, LiquidationRecord, OrderRecord } from '../index';
|
|
3
|
+
export declare type EventSubscriptionOptions = {
|
|
4
|
+
eventTypes?: EventType[];
|
|
5
|
+
maxEventsPerType?: number;
|
|
6
|
+
orderBy?: EventSubscriptionOrderBy;
|
|
7
|
+
orderDir?: EventSubscriptionOrderDirection;
|
|
8
|
+
commitment?: Commitment;
|
|
9
|
+
maxTx?: number;
|
|
10
|
+
logProviderConfig?: LogProviderConfig;
|
|
11
|
+
untilTx?: TransactionSignature;
|
|
12
|
+
};
|
|
13
|
+
export declare const DefaultEventSubscriptionOptions: EventSubscriptionOptions;
|
|
14
|
+
export declare type EventSubscriptionOrderBy = 'blockchain' | 'client';
|
|
15
|
+
export declare type EventSubscriptionOrderDirection = 'asc' | 'desc';
|
|
16
|
+
export declare type Event<T> = T & {
|
|
17
|
+
txSig: TransactionSignature;
|
|
18
|
+
slot: number;
|
|
19
|
+
};
|
|
20
|
+
export declare type WrappedEvent<Type extends EventType> = EventMap[Type] & {
|
|
21
|
+
eventType: Type;
|
|
22
|
+
};
|
|
23
|
+
export declare type WrappedEvents = WrappedEvent<EventType>[];
|
|
24
|
+
export declare type EventMap = {
|
|
25
|
+
DepositRecord: Event<DepositRecord>;
|
|
26
|
+
FundingPaymentRecord: Event<FundingPaymentRecord>;
|
|
27
|
+
LiquidationRecord: Event<LiquidationRecord>;
|
|
28
|
+
FundingRateRecord: Event<FundingRateRecord>;
|
|
29
|
+
OrderRecord: Event<OrderRecord>;
|
|
30
|
+
};
|
|
31
|
+
export declare type EventType = keyof EventMap;
|
|
32
|
+
export interface EventSubscriberEvents {
|
|
33
|
+
newEvent: (event: WrappedEvent<EventType>) => void;
|
|
34
|
+
}
|
|
35
|
+
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;
|
|
37
|
+
export interface LogProvider {
|
|
38
|
+
isSubscribed(): boolean;
|
|
39
|
+
subscribe(callback: logProviderCallback): boolean;
|
|
40
|
+
unsubscribe(): Promise<boolean>;
|
|
41
|
+
}
|
|
42
|
+
export declare type WebSocketLogProviderConfig = {
|
|
43
|
+
type: 'websocket';
|
|
44
|
+
};
|
|
45
|
+
export declare type PollingLogProviderConfig = {
|
|
46
|
+
type: 'polling';
|
|
47
|
+
frequency: number;
|
|
48
|
+
};
|
|
49
|
+
export declare type LogProviderConfig = WebSocketLogProviderConfig | PollingLogProviderConfig;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DefaultEventSubscriptionOptions = void 0;
|
|
4
|
+
exports.DefaultEventSubscriptionOptions = {
|
|
5
|
+
eventTypes: [
|
|
6
|
+
'DepositRecord',
|
|
7
|
+
'FundingPaymentRecord',
|
|
8
|
+
'LiquidationRecord',
|
|
9
|
+
'OrderRecord',
|
|
10
|
+
'FundingRateRecord',
|
|
11
|
+
],
|
|
12
|
+
maxEventsPerType: 4096,
|
|
13
|
+
orderBy: 'blockchain',
|
|
14
|
+
orderDir: 'asc',
|
|
15
|
+
commitment: 'confirmed',
|
|
16
|
+
maxTx: 4096,
|
|
17
|
+
logProviderConfig: {
|
|
18
|
+
type: 'websocket',
|
|
19
|
+
},
|
|
20
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { LogProvider, logProviderCallback } from './types';
|
|
2
|
+
import { Commitment, Connection, PublicKey } from '@solana/web3.js';
|
|
3
|
+
export declare class WebSocketLogProvider implements LogProvider {
|
|
4
|
+
private connection;
|
|
5
|
+
private programId;
|
|
6
|
+
private commitment;
|
|
7
|
+
private subscriptionId;
|
|
8
|
+
constructor(connection: Connection, programId: PublicKey, commitment: Commitment);
|
|
9
|
+
subscribe(callback: logProviderCallback): boolean;
|
|
10
|
+
isSubscribed(): boolean;
|
|
11
|
+
unsubscribe(): Promise<boolean>;
|
|
12
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.WebSocketLogProvider = void 0;
|
|
4
|
+
class WebSocketLogProvider {
|
|
5
|
+
constructor(connection, programId, commitment) {
|
|
6
|
+
this.connection = connection;
|
|
7
|
+
this.programId = programId;
|
|
8
|
+
this.commitment = commitment;
|
|
9
|
+
}
|
|
10
|
+
subscribe(callback) {
|
|
11
|
+
if (this.subscriptionId) {
|
|
12
|
+
return true;
|
|
13
|
+
}
|
|
14
|
+
this.subscriptionId = this.connection.onLogs(this.programId, (logs, ctx) => {
|
|
15
|
+
callback(logs.signature, ctx.slot, logs.logs);
|
|
16
|
+
}, this.commitment);
|
|
17
|
+
return true;
|
|
18
|
+
}
|
|
19
|
+
isSubscribed() {
|
|
20
|
+
return this.subscriptionId !== undefined;
|
|
21
|
+
}
|
|
22
|
+
async unsubscribe() {
|
|
23
|
+
if (this.subscriptionId !== undefined) {
|
|
24
|
+
await this.connection.removeOnLogsListener(this.subscriptionId);
|
|
25
|
+
this.subscriptionId = undefined;
|
|
26
|
+
}
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
exports.WebSocketLogProvider = WebSocketLogProvider;
|
|
@@ -1,13 +1,4 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
-
});
|
|
10
|
-
};
|
|
11
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
3
|
exports.getTokenAddress = void 0;
|
|
13
4
|
const anchor_1 = require("@project-serum/anchor");
|
|
@@ -15,11 +6,12 @@ const __1 = require("..");
|
|
|
15
6
|
const spl_token_1 = require("@solana/spl-token");
|
|
16
7
|
const web3_js_1 = require("@solana/web3.js");
|
|
17
8
|
const __2 = require("..");
|
|
9
|
+
const banks_1 = require("../constants/banks");
|
|
18
10
|
const getTokenAddress = (mintAddress, userPubKey) => {
|
|
19
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));
|
|
20
12
|
};
|
|
21
13
|
exports.getTokenAddress = getTokenAddress;
|
|
22
|
-
const main = () =>
|
|
14
|
+
const main = async () => {
|
|
23
15
|
// Initialize Drift SDK
|
|
24
16
|
const sdkConfig = (0, __2.initialize)({ env: 'devnet' });
|
|
25
17
|
// Set up the Wallet and Provider
|
|
@@ -32,41 +24,48 @@ const main = () => __awaiter(void 0, void 0, void 0, function* () {
|
|
|
32
24
|
// Set up the Provider
|
|
33
25
|
const provider = new anchor_1.AnchorProvider(connection, wallet, anchor_1.AnchorProvider.defaultOptions());
|
|
34
26
|
// Check SOL Balance
|
|
35
|
-
const lamportsBalance =
|
|
36
|
-
console.log('SOL balance:', lamportsBalance /
|
|
27
|
+
const lamportsBalance = await connection.getBalance(wallet.publicKey);
|
|
28
|
+
console.log('SOL balance:', lamportsBalance / 10 ** 9);
|
|
37
29
|
// Misc. other things to set up
|
|
38
|
-
const usdcTokenAddress =
|
|
30
|
+
const usdcTokenAddress = await (0, exports.getTokenAddress)(sdkConfig.USDC_MINT_ADDRESS, wallet.publicKey.toString());
|
|
39
31
|
// Set up the Drift Clearing House
|
|
40
32
|
const clearingHousePublicKey = new web3_js_1.PublicKey(sdkConfig.CLEARING_HOUSE_PROGRAM_ID);
|
|
41
|
-
const clearingHouse = __2.ClearingHouse
|
|
42
|
-
|
|
33
|
+
const clearingHouse = new __2.ClearingHouse({
|
|
34
|
+
connection,
|
|
35
|
+
wallet: provider.wallet,
|
|
36
|
+
programID: clearingHousePublicKey,
|
|
37
|
+
});
|
|
38
|
+
await clearingHouse.subscribe();
|
|
43
39
|
// Set up Clearing House user client
|
|
44
|
-
const user = __2.ClearingHouseUser
|
|
40
|
+
const user = new __2.ClearingHouseUser({
|
|
41
|
+
clearingHouse,
|
|
42
|
+
userAccountPublicKey: await clearingHouse.getUserAccountPublicKey(),
|
|
43
|
+
});
|
|
45
44
|
//// Check if clearing house account exists for the current wallet
|
|
46
|
-
const userAccountExists =
|
|
45
|
+
const userAccountExists = await user.exists();
|
|
47
46
|
if (!userAccountExists) {
|
|
48
47
|
//// Create a Clearing House account by Depositing some USDC ($10,000 in this case)
|
|
49
48
|
const depositAmount = new anchor_1.BN(10000).mul(__2.QUOTE_PRECISION);
|
|
50
|
-
|
|
49
|
+
await clearingHouse.initializeUserAccountAndDepositCollateral(depositAmount, await (0, exports.getTokenAddress)(usdcTokenAddress.toString(), wallet.publicKey.toString()), banks_1.Banks['devnet'][0].bankIndex);
|
|
51
50
|
}
|
|
52
|
-
|
|
51
|
+
await user.subscribe();
|
|
53
52
|
// Get current price
|
|
54
|
-
const solMarketInfo =
|
|
55
|
-
const currentMarketPrice = (0, __2.calculateMarkPrice)(clearingHouse.
|
|
53
|
+
const solMarketInfo = sdkConfig.MARKETS.find((market) => market.baseAssetSymbol === 'SOL');
|
|
54
|
+
const currentMarketPrice = (0, __2.calculateMarkPrice)(clearingHouse.getMarketAccount(solMarketInfo.marketIndex), undefined);
|
|
56
55
|
const formattedPrice = (0, __2.convertToNumber)(currentMarketPrice, __2.MARK_PRICE_PRECISION);
|
|
57
56
|
console.log(`Current Market Price is $${formattedPrice}`);
|
|
58
57
|
// Estimate the slippage for a $5000 LONG trade
|
|
59
|
-
const solMarketAccount = clearingHouse.
|
|
58
|
+
const solMarketAccount = clearingHouse.getMarketAccount(solMarketInfo.marketIndex);
|
|
60
59
|
const longAmount = new anchor_1.BN(5000).mul(__2.QUOTE_PRECISION);
|
|
61
|
-
const slippage = (0, __2.convertToNumber)((0, __2.calculateTradeSlippage)(__2.PositionDirection.LONG, longAmount, solMarketAccount)[0], __2.MARK_PRICE_PRECISION);
|
|
60
|
+
const slippage = (0, __2.convertToNumber)((0, __2.calculateTradeSlippage)(__2.PositionDirection.LONG, longAmount, solMarketAccount, 'quote', undefined)[0], __2.MARK_PRICE_PRECISION);
|
|
62
61
|
console.log(`Slippage for a $5000 LONG on the SOL market would be $${slippage}`);
|
|
63
62
|
// Make a $5000 LONG trade
|
|
64
|
-
|
|
63
|
+
await clearingHouse.openPosition(__2.PositionDirection.LONG, longAmount, solMarketInfo.marketIndex);
|
|
65
64
|
console.log(`LONGED $5000 SOL`);
|
|
66
65
|
// Reduce the position by $2000
|
|
67
66
|
const reduceAmount = new anchor_1.BN(2000).mul(__2.QUOTE_PRECISION);
|
|
68
|
-
|
|
67
|
+
await clearingHouse.openPosition(__2.PositionDirection.SHORT, reduceAmount, solMarketInfo.marketIndex);
|
|
69
68
|
// Close the rest of the position
|
|
70
|
-
|
|
71
|
-
}
|
|
69
|
+
await clearingHouse.closePosition(solMarketInfo.marketIndex);
|
|
70
|
+
};
|
|
72
71
|
main();
|