@drift-labs/sdk 0.2.0-master.24 → 0.2.0-master.25
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/addresses/pda.d.ts +1 -0
- package/lib/addresses/pda.js +5 -1
- package/lib/admin.js +7 -12
- package/lib/clearingHouse.d.ts +2 -0
- package/lib/clearingHouse.js +12 -5
- package/lib/clearingHouseUser.d.ts +3 -1
- package/lib/clearingHouseUser.js +6 -4
- package/lib/config.js +1 -1
- package/lib/events/eventSubscriber.d.ts +4 -2
- package/lib/events/eventSubscriber.js +16 -9
- package/lib/events/fetchLogs.d.ts +10 -1
- package/lib/events/fetchLogs.js +27 -7
- package/lib/events/pollingLogProvider.d.ts +2 -1
- package/lib/events/pollingLogProvider.js +6 -2
- package/lib/events/types.d.ts +3 -2
- package/lib/events/types.js +1 -0
- package/lib/examples/makeTradeExample.js +13 -1
- package/lib/idl/clearing_house.json +97 -45
- package/lib/index.d.ts +1 -0
- package/lib/index.js +1 -0
- package/lib/math/amm.d.ts +3 -1
- package/lib/math/amm.js +41 -3
- package/lib/types.d.ts +25 -6
- package/lib/types.js +7 -1
- package/package.json +1 -1
- package/src/addresses/pda.ts +9 -0
- package/src/admin.ts +11 -30
- package/src/clearingHouse.ts +17 -5
- package/src/clearingHouseUser.ts +6 -5
- package/src/config.ts +1 -1
- package/src/events/eventSubscriber.ts +20 -12
- package/src/events/fetchLogs.ts +35 -8
- package/src/events/pollingLogProvider.ts +10 -2
- package/src/events/types.ts +4 -1
- package/src/examples/makeTradeExample.ts +20 -1
- package/src/idl/clearing_house.json +97 -45
- package/src/index.ts +1 -0
- package/src/math/amm.ts +67 -2
- package/src/types.ts +21 -6
package/lib/addresses/pda.d.ts
CHANGED
|
@@ -14,3 +14,4 @@ export declare function getBankVaultAuthorityPublicKey(programId: PublicKey, ban
|
|
|
14
14
|
export declare function getInsuranceFundVaultPublicKey(programId: PublicKey, bankIndex: BN): Promise<PublicKey>;
|
|
15
15
|
export declare function getInsuranceFundVaultAuthorityPublicKey(programId: PublicKey, bankIndex: BN): Promise<PublicKey>;
|
|
16
16
|
export declare function getInsuranceFundStakeAccountPublicKey(programId: PublicKey, authority: PublicKey, bankIndex: BN): PublicKey;
|
|
17
|
+
export declare function getClearingHouseSignerPublicKey(programId: PublicKey): PublicKey;
|
package/lib/addresses/pda.js
CHANGED
|
@@ -23,7 +23,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
|
|
|
23
23
|
return result;
|
|
24
24
|
};
|
|
25
25
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
-
exports.getInsuranceFundStakeAccountPublicKey = exports.getInsuranceFundVaultAuthorityPublicKey = exports.getInsuranceFundVaultPublicKey = exports.getBankVaultAuthorityPublicKey = exports.getBankVaultPublicKey = exports.getBankPublicKey = exports.getMarketPublicKey = exports.getUserStatsAccountPublicKey = exports.getUserAccountPublicKeySync = exports.getUserAccountPublicKey = exports.getUserAccountPublicKeyAndNonce = exports.getClearingHouseStateAccountPublicKey = exports.getClearingHouseStateAccountPublicKeyAndNonce = void 0;
|
|
26
|
+
exports.getClearingHouseSignerPublicKey = exports.getInsuranceFundStakeAccountPublicKey = exports.getInsuranceFundVaultAuthorityPublicKey = exports.getInsuranceFundVaultPublicKey = exports.getBankVaultAuthorityPublicKey = exports.getBankVaultPublicKey = exports.getBankPublicKey = exports.getMarketPublicKey = exports.getUserStatsAccountPublicKey = exports.getUserAccountPublicKeySync = exports.getUserAccountPublicKey = exports.getUserAccountPublicKeyAndNonce = exports.getClearingHouseStateAccountPublicKey = exports.getClearingHouseStateAccountPublicKeyAndNonce = void 0;
|
|
27
27
|
const anchor = __importStar(require("@project-serum/anchor"));
|
|
28
28
|
async function getClearingHouseStateAccountPublicKeyAndNonce(programId) {
|
|
29
29
|
return anchor.web3.PublicKey.findProgramAddress([Buffer.from(anchor.utils.bytes.utf8.encode('clearing_house'))], programId);
|
|
@@ -110,3 +110,7 @@ function getInsuranceFundStakeAccountPublicKey(programId, authority, bankIndex)
|
|
|
110
110
|
], programId)[0];
|
|
111
111
|
}
|
|
112
112
|
exports.getInsuranceFundStakeAccountPublicKey = getInsuranceFundStakeAccountPublicKey;
|
|
113
|
+
function getClearingHouseSignerPublicKey(programId) {
|
|
114
|
+
return anchor.web3.PublicKey.findProgramAddressSync([Buffer.from(anchor.utils.bytes.utf8.encode('clearing_house_signer'))], programId)[0];
|
|
115
|
+
}
|
|
116
|
+
exports.getClearingHouseSignerPublicKey = getClearingHouseSignerPublicKey;
|
package/lib/admin.js
CHANGED
|
@@ -40,17 +40,16 @@ class Admin extends clearingHouse_1.ClearingHouse {
|
|
|
40
40
|
if (stateAccountRPCResponse.value !== null) {
|
|
41
41
|
throw new Error('Clearing house already initialized');
|
|
42
42
|
}
|
|
43
|
-
const [insuranceVaultPublicKey] = await web3_js_1.PublicKey.findProgramAddress([Buffer.from(anchor.utils.bytes.utf8.encode('insurance_vault'))], this.program.programId);
|
|
44
|
-
const [insuranceVaultAuthority] = await web3_js_1.PublicKey.findProgramAddress([insuranceVaultPublicKey.toBuffer()], this.program.programId);
|
|
45
43
|
const [clearingHouseStatePublicKey] = await (0, pda_1.getClearingHouseStateAccountPublicKeyAndNonce)(this.program.programId);
|
|
44
|
+
const [insuranceVaultPublicKey] = await web3_js_1.PublicKey.findProgramAddress([Buffer.from(anchor.utils.bytes.utf8.encode('insurance_vault'))], this.program.programId);
|
|
46
45
|
const initializeTx = await this.program.transaction.initialize(adminControlsPrices, {
|
|
47
46
|
accounts: {
|
|
48
47
|
admin: this.wallet.publicKey,
|
|
49
48
|
state: clearingHouseStatePublicKey,
|
|
50
49
|
quoteAssetMint: usdcMint,
|
|
51
|
-
insuranceVault: insuranceVaultPublicKey,
|
|
52
|
-
insuranceVaultAuthority: insuranceVaultAuthority,
|
|
53
50
|
rent: web3_js_1.SYSVAR_RENT_PUBKEY,
|
|
51
|
+
insuranceVault: insuranceVaultPublicKey,
|
|
52
|
+
clearingHouseSigner: this.getSignerPublicKey(),
|
|
54
53
|
systemProgram: anchor.web3.SystemProgram.programId,
|
|
55
54
|
tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
|
|
56
55
|
},
|
|
@@ -62,18 +61,15 @@ class Admin extends clearingHouse_1.ClearingHouse {
|
|
|
62
61
|
const bankIndex = this.getStateAccount().numberOfBanks;
|
|
63
62
|
const bank = await (0, pda_1.getBankPublicKey)(this.program.programId, bankIndex);
|
|
64
63
|
const bankVault = await (0, pda_1.getBankVaultPublicKey)(this.program.programId, bankIndex);
|
|
65
|
-
const bankVaultAuthority = await (0, pda_1.getBankVaultAuthorityPublicKey)(this.program.programId, bankIndex);
|
|
66
64
|
const insuranceFundVault = await (0, pda_1.getInsuranceFundVaultPublicKey)(this.program.programId, bankIndex);
|
|
67
|
-
const insuranceFundVaultAuthority = await (0, pda_1.getInsuranceFundVaultAuthorityPublicKey)(this.program.programId, bankIndex);
|
|
68
65
|
const initializeTx = await this.program.transaction.initializeBank(optimalUtilization, optimalRate, maxRate, oracleSource, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight, imfFactor, liquidationFee, {
|
|
69
66
|
accounts: {
|
|
70
67
|
admin: this.wallet.publicKey,
|
|
71
68
|
state: await this.getStatePublicKey(),
|
|
72
69
|
bank,
|
|
73
70
|
bankVault,
|
|
74
|
-
bankVaultAuthority,
|
|
75
71
|
insuranceFundVault,
|
|
76
|
-
|
|
72
|
+
clearingHouseSigner: this.getSignerPublicKey(),
|
|
77
73
|
bankMint: mint,
|
|
78
74
|
oracle,
|
|
79
75
|
rent: web3_js_1.SYSVAR_RENT_PUBKEY,
|
|
@@ -188,7 +184,7 @@ class Admin extends clearingHouse_1.ClearingHouse {
|
|
|
188
184
|
state: await this.getStatePublicKey(),
|
|
189
185
|
bank: bank.pubkey,
|
|
190
186
|
insuranceVault: state.insuranceVault,
|
|
191
|
-
|
|
187
|
+
clearingHouseSigner: this.getSignerPublicKey(),
|
|
192
188
|
recipient: recipient,
|
|
193
189
|
tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
|
|
194
190
|
},
|
|
@@ -204,7 +200,7 @@ class Admin extends clearingHouse_1.ClearingHouse {
|
|
|
204
200
|
market: marketPublicKey,
|
|
205
201
|
bank: bank.pubkey,
|
|
206
202
|
bankVault: bank.vault,
|
|
207
|
-
|
|
203
|
+
clearingHouseSigner: this.getSignerPublicKey(),
|
|
208
204
|
recipient: recipient,
|
|
209
205
|
tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
|
|
210
206
|
},
|
|
@@ -219,10 +215,9 @@ class Admin extends clearingHouse_1.ClearingHouse {
|
|
|
219
215
|
state: await this.getStatePublicKey(),
|
|
220
216
|
market: await (0, pda_1.getMarketPublicKey)(this.program.programId, marketIndex),
|
|
221
217
|
insuranceVault: state.insuranceVault,
|
|
222
|
-
|
|
218
|
+
clearingHouseSigner: this.getSignerPublicKey(),
|
|
223
219
|
bank: bank.pubkey,
|
|
224
220
|
bankVault: bank.vault,
|
|
225
|
-
bankVaultAuthority: bank.vaultAuthority,
|
|
226
221
|
tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
|
|
227
222
|
},
|
|
228
223
|
});
|
package/lib/clearingHouse.d.ts
CHANGED
|
@@ -47,6 +47,8 @@ export declare class ClearingHouse {
|
|
|
47
47
|
unsubscribeUsers(): Promise<void>[];
|
|
48
48
|
statePublicKey?: PublicKey;
|
|
49
49
|
getStatePublicKey(): Promise<PublicKey>;
|
|
50
|
+
signerPublicKey?: PublicKey;
|
|
51
|
+
getSignerPublicKey(): PublicKey;
|
|
50
52
|
getStateAccount(): StateAccount;
|
|
51
53
|
getMarketAccount(marketIndex: BN | number): MarketAccount | undefined;
|
|
52
54
|
getMarketAccounts(): MarketAccount[];
|
package/lib/clearingHouse.js
CHANGED
|
@@ -159,6 +159,13 @@ class ClearingHouse {
|
|
|
159
159
|
this.statePublicKey = await (0, pda_1.getClearingHouseStateAccountPublicKey)(this.program.programId);
|
|
160
160
|
return this.statePublicKey;
|
|
161
161
|
}
|
|
162
|
+
getSignerPublicKey() {
|
|
163
|
+
if (this.signerPublicKey) {
|
|
164
|
+
return this.signerPublicKey;
|
|
165
|
+
}
|
|
166
|
+
this.signerPublicKey = (0, pda_1.getClearingHouseSignerPublicKey)(this.program.programId);
|
|
167
|
+
return this.signerPublicKey;
|
|
168
|
+
}
|
|
162
169
|
getStateAccount() {
|
|
163
170
|
return this.accountSubscriber.getStateAccountAndSlot().data;
|
|
164
171
|
}
|
|
@@ -631,7 +638,7 @@ class ClearingHouse {
|
|
|
631
638
|
state: await this.getStatePublicKey(),
|
|
632
639
|
bank: bank.pubkey,
|
|
633
640
|
bankVault: bank.vault,
|
|
634
|
-
|
|
641
|
+
clearingHouseSigner: this.getSignerPublicKey(),
|
|
635
642
|
user: userAccountPublicKey,
|
|
636
643
|
userStats: this.getUserStatsAccountPublicKey(),
|
|
637
644
|
userTokenAccount: userTokenAccount,
|
|
@@ -1320,7 +1327,7 @@ class ClearingHouse {
|
|
|
1320
1327
|
liquidator: liquidatorPublicKey,
|
|
1321
1328
|
bankVault: bank.vault,
|
|
1322
1329
|
insuranceFundVault: bank.insuranceFundVault,
|
|
1323
|
-
|
|
1330
|
+
clearingHouseSigner: this.getSignerPublicKey(),
|
|
1324
1331
|
tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
|
|
1325
1332
|
},
|
|
1326
1333
|
remainingAccounts: remainingAccounts,
|
|
@@ -1345,7 +1352,7 @@ class ClearingHouse {
|
|
|
1345
1352
|
liquidator: liquidatorPublicKey,
|
|
1346
1353
|
bankVault: bank.vault,
|
|
1347
1354
|
insuranceFundVault: bank.insuranceFundVault,
|
|
1348
|
-
|
|
1355
|
+
clearingHouseSigner: this.getSignerPublicKey(),
|
|
1349
1356
|
tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
|
|
1350
1357
|
},
|
|
1351
1358
|
remainingAccounts: remainingAccounts,
|
|
@@ -1621,7 +1628,7 @@ class ClearingHouse {
|
|
|
1621
1628
|
userStats: this.getUserStatsAccountPublicKey(),
|
|
1622
1629
|
authority: this.wallet.publicKey,
|
|
1623
1630
|
insuranceFundVault: bank.insuranceFundVault,
|
|
1624
|
-
|
|
1631
|
+
clearingHouseSigner: this.getSignerPublicKey(),
|
|
1625
1632
|
userTokenAccount: collateralAccountPublicKey,
|
|
1626
1633
|
tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
|
|
1627
1634
|
},
|
|
@@ -1638,7 +1645,7 @@ class ClearingHouse {
|
|
|
1638
1645
|
state: await this.getStatePublicKey(),
|
|
1639
1646
|
bank: bank.pubkey,
|
|
1640
1647
|
bankVault: bank.vault,
|
|
1641
|
-
|
|
1648
|
+
clearingHouseSigner: this.getSignerPublicKey(),
|
|
1642
1649
|
insuranceFundVault: bank.insuranceFundVault,
|
|
1643
1650
|
tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
|
|
1644
1651
|
},
|
|
@@ -52,7 +52,9 @@ export declare class ClearingHouseUser {
|
|
|
52
52
|
exists(): Promise<boolean>;
|
|
53
53
|
/**
|
|
54
54
|
* calculates the market position if the lp position was settled
|
|
55
|
-
* @returns : userPosition
|
|
55
|
+
* @returns : the settled userPosition
|
|
56
|
+
* @returns : the dust base asset amount (ie, < stepsize)
|
|
57
|
+
* @returns : pnl from settle
|
|
56
58
|
*/
|
|
57
59
|
getSettledLPPosition(marketIndex: BN): [UserPosition, BN, BN];
|
|
58
60
|
/**
|
package/lib/clearingHouseUser.js
CHANGED
|
@@ -105,7 +105,9 @@ class ClearingHouseUser {
|
|
|
105
105
|
}
|
|
106
106
|
/**
|
|
107
107
|
* calculates the market position if the lp position was settled
|
|
108
|
-
* @returns : userPosition
|
|
108
|
+
* @returns : the settled userPosition
|
|
109
|
+
* @returns : the dust base asset amount (ie, < stepsize)
|
|
110
|
+
* @returns : pnl from settle
|
|
109
111
|
*/
|
|
110
112
|
getSettledLPPosition(marketIndex) {
|
|
111
113
|
const _position = this.getUserPosition(marketIndex);
|
|
@@ -138,8 +140,6 @@ class ClearingHouseUser {
|
|
|
138
140
|
}
|
|
139
141
|
const standardizedBaa = deltaBaa.sub(remainderBaa);
|
|
140
142
|
const reaminderPerLP = remainderBaa.mul(numericConstants_1.AMM_RESERVE_PRECISION).div(nShares);
|
|
141
|
-
position.baseAssetAmount = position.baseAssetAmount.add(standardizedBaa);
|
|
142
|
-
position.quoteAssetAmount = position.quoteAssetAmount.add(deltaQaa);
|
|
143
143
|
position.lastNetBaseAssetAmountPerLp =
|
|
144
144
|
market.amm.marketPositionPerLp.baseAssetAmount.sub(reaminderPerLP);
|
|
145
145
|
let updateType;
|
|
@@ -168,13 +168,15 @@ class ClearingHouseUser {
|
|
|
168
168
|
newQuoteEntry = position.quoteEntryAmount.sub(position.quoteEntryAmount
|
|
169
169
|
.mul(deltaBaa.abs())
|
|
170
170
|
.div(position.baseAssetAmount.abs()));
|
|
171
|
-
pnl = position.quoteEntryAmount.sub(newQuoteEntry);
|
|
171
|
+
pnl = position.quoteEntryAmount.sub(newQuoteEntry).add(deltaQaa);
|
|
172
172
|
}
|
|
173
173
|
else {
|
|
174
174
|
newQuoteEntry = deltaQaa.sub(deltaQaa.mul(position.baseAssetAmount.abs()).div(deltaBaa.abs()));
|
|
175
175
|
pnl = position.quoteEntryAmount.add(deltaQaa.sub(newQuoteEntry));
|
|
176
176
|
}
|
|
177
177
|
position.quoteEntryAmount = newQuoteEntry;
|
|
178
|
+
position.baseAssetAmount = position.baseAssetAmount.add(standardizedBaa);
|
|
179
|
+
position.quoteAssetAmount = position.quoteAssetAmount.add(deltaQaa);
|
|
178
180
|
if (position.baseAssetAmount.gt(numericConstants_1.ZERO)) {
|
|
179
181
|
position.lastCumulativeFundingRate = market.amm.cumulativeFundingRateLong;
|
|
180
182
|
}
|
package/lib/config.js
CHANGED
|
@@ -7,7 +7,7 @@ exports.configs = {
|
|
|
7
7
|
devnet: {
|
|
8
8
|
ENV: 'devnet',
|
|
9
9
|
PYTH_ORACLE_MAPPING_ADDRESS: 'BmA9Z6FjioHJPpjT39QazZyhDRUdZy2ezwx4GiDdE2u2',
|
|
10
|
-
CLEARING_HOUSE_PROGRAM_ID: '
|
|
10
|
+
CLEARING_HOUSE_PROGRAM_ID: '3v1iEjbSSLSSYyt1pmx4UB5rqJGurmz71RibXF7X6UF3',
|
|
11
11
|
USDC_MINT_ADDRESS: '8zGuJQqwhZafTah7Uc7Z4tXRnguqkn5KLFAP8oV6PHe2',
|
|
12
12
|
MARKETS: markets_1.DevnetMarkets,
|
|
13
13
|
BANKS: banks_1.DevnetBanks,
|
|
@@ -15,10 +15,12 @@ export declare class EventSubscriber {
|
|
|
15
15
|
private awaitTxResolver;
|
|
16
16
|
private logProvider;
|
|
17
17
|
eventEmitter: StrictEventEmitter<EventEmitter, EventSubscriberEvents>;
|
|
18
|
+
private lastSeenSlot;
|
|
19
|
+
lastSeenTxSig: string;
|
|
18
20
|
constructor(connection: Connection, program: Program, options?: EventSubscriptionOptions);
|
|
19
|
-
subscribe(): boolean
|
|
21
|
+
subscribe(): Promise<boolean>;
|
|
20
22
|
private handleTxLogs;
|
|
21
|
-
|
|
23
|
+
fetchPreviousTx(fetchMax?: boolean): Promise<void>;
|
|
22
24
|
unsubscribe(): Promise<boolean>;
|
|
23
25
|
private parseEventsFromLogs;
|
|
24
26
|
awaitTx(txSig: TransactionSignature): Promise<void>;
|
|
@@ -30,17 +30,21 @@ 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) => {
|
|
39
|
+
this.handleTxLogs(txSig, slot, logs);
|
|
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
49
|
handleTxLogs(txSig, slot, logs) {
|
|
46
50
|
if (this.txEventCache.has(txSig)) {
|
|
@@ -56,10 +60,13 @@ class EventSubscriber {
|
|
|
56
60
|
this.awaitTxResolver.get(txSig)();
|
|
57
61
|
this.awaitTxResolver.delete(txSig);
|
|
58
62
|
}
|
|
63
|
+
if (slot > this.lastSeenSlot) {
|
|
64
|
+
this.lastSeenTxSig = txSig;
|
|
65
|
+
}
|
|
59
66
|
this.txEventCache.add(txSig, wrappedEvents);
|
|
60
67
|
}
|
|
61
|
-
async fetchPreviousTx() {
|
|
62
|
-
if (!this.options.untilTx) {
|
|
68
|
+
async fetchPreviousTx(fetchMax) {
|
|
69
|
+
if (!this.options.untilTx && !fetchMax) {
|
|
63
70
|
return;
|
|
64
71
|
}
|
|
65
72
|
let txFetched = 0;
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { Program } from '@project-serum/anchor';
|
|
1
2
|
import { Connection, Finality, PublicKey, 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,14 @@ 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[];
|
|
11
15
|
};
|
|
12
|
-
export declare function fetchLogs(connection: Connection, programId: PublicKey, finality: Finality, beforeTx?: TransactionSignature, untilTx?: TransactionSignature): Promise<FetchLogsResponse
|
|
16
|
+
export declare function fetchLogs(connection: Connection, programId: PublicKey, finality: Finality, beforeTx?: TransactionSignature, untilTx?: TransactionSignature, limit?: number): Promise<FetchLogsResponse>;
|
|
17
|
+
export declare class LogParser {
|
|
18
|
+
private program;
|
|
19
|
+
constructor(program: Program);
|
|
20
|
+
parseEventsFromLogs(event: Log): WrappedEvents;
|
|
21
|
+
}
|
|
13
22
|
export {};
|
package/lib/events/fetchLogs.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.fetchLogs = void 0;
|
|
4
|
-
async function fetchLogs(connection, programId, finality, beforeTx, untilTx) {
|
|
3
|
+
exports.LogParser = exports.fetchLogs = void 0;
|
|
4
|
+
async function fetchLogs(connection, programId, finality, beforeTx, untilTx, limit) {
|
|
5
5
|
const signatures = await connection.getSignaturesForAddress(programId, {
|
|
6
6
|
before: beforeTx,
|
|
7
7
|
until: untilTx,
|
|
8
|
+
limit,
|
|
8
9
|
}, finality);
|
|
9
|
-
const sortedSignatures = signatures.sort((a, b) => a.slot < b.slot ? -1 : 1);
|
|
10
|
+
const sortedSignatures = signatures.sort((a, b) => a.slot === b.slot ? 0 : a.slot < b.slot ? -1 : 1);
|
|
10
11
|
const filteredSignatures = sortedSignatures.filter((signature) => !signature.err);
|
|
11
12
|
if (filteredSignatures.length === 0) {
|
|
12
13
|
return undefined;
|
|
@@ -22,12 +23,14 @@ async function fetchLogs(connection, programId, finality, beforeTx, untilTx) {
|
|
|
22
23
|
};
|
|
23
24
|
});
|
|
24
25
|
}))).flat();
|
|
25
|
-
const
|
|
26
|
-
const
|
|
26
|
+
const earliest = filteredSignatures[0];
|
|
27
|
+
const mostRecent = filteredSignatures[filteredSignatures.length - 1];
|
|
27
28
|
return {
|
|
28
29
|
transactionLogs: transactionLogs,
|
|
29
|
-
earliestTx:
|
|
30
|
-
mostRecentTx:
|
|
30
|
+
earliestTx: earliest.signature,
|
|
31
|
+
mostRecentTx: mostRecent.signature,
|
|
32
|
+
earliestSlot: earliest.slot,
|
|
33
|
+
mostRecentSlot: mostRecent.slot,
|
|
31
34
|
};
|
|
32
35
|
}
|
|
33
36
|
exports.fetchLogs = fetchLogs;
|
|
@@ -37,3 +40,20 @@ function chunk(array, size) {
|
|
|
37
40
|
.map((_, index) => index * size)
|
|
38
41
|
.map((begin) => array.slice(begin, begin + size));
|
|
39
42
|
}
|
|
43
|
+
class LogParser {
|
|
44
|
+
constructor(program) {
|
|
45
|
+
this.program = program;
|
|
46
|
+
}
|
|
47
|
+
parseEventsFromLogs(event) {
|
|
48
|
+
const records = [];
|
|
49
|
+
// @ts-ignore
|
|
50
|
+
this.program._events._eventParser.parseLogs(event.logs, (eventLog) => {
|
|
51
|
+
eventLog.data.txSig = event.txSig;
|
|
52
|
+
eventLog.data.slot = event.slot;
|
|
53
|
+
eventLog.data.eventType = eventLog.name;
|
|
54
|
+
records.push(eventLog.data);
|
|
55
|
+
});
|
|
56
|
+
return records;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
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,7 +20,10 @@ 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
|
}
|
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, NewUserRecord, OrderActionRecord, OrderRecord, SettlePnlRecord } from '../index';
|
|
2
|
+
import { DepositRecord, FundingPaymentRecord, FundingRateRecord, LiquidationRecord, NewUserRecord, OrderActionRecord, OrderRecord, SettlePnlRecord, LPRecord } from '../index';
|
|
3
3
|
export declare type EventSubscriptionOptions = {
|
|
4
4
|
eventTypes?: EventType[];
|
|
5
5
|
maxEventsPerType?: number;
|
|
@@ -30,6 +30,7 @@ export declare type EventMap = {
|
|
|
30
30
|
OrderActionRecord: Event<OrderActionRecord>;
|
|
31
31
|
SettlePnlRecord: Event<SettlePnlRecord>;
|
|
32
32
|
NewUserRecord: Event<NewUserRecord>;
|
|
33
|
+
LPRecord: Event<LPRecord>;
|
|
33
34
|
};
|
|
34
35
|
export declare type EventType = keyof EventMap;
|
|
35
36
|
export interface EventSubscriberEvents {
|
|
@@ -39,7 +40,7 @@ export declare type SortFn = (currentRecord: EventMap[EventType], newRecord: Eve
|
|
|
39
40
|
export declare type logProviderCallback = (txSig: TransactionSignature, slot: number, logs: string[]) => void;
|
|
40
41
|
export interface LogProvider {
|
|
41
42
|
isSubscribed(): boolean;
|
|
42
|
-
subscribe(callback: logProviderCallback): boolean;
|
|
43
|
+
subscribe(callback: logProviderCallback, skipHistory?: boolean): boolean;
|
|
43
44
|
unsubscribe(): Promise<boolean>;
|
|
44
45
|
}
|
|
45
46
|
export declare type WebSocketLogProviderConfig = {
|
package/lib/events/types.js
CHANGED
|
@@ -11,9 +11,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)));
|
|
@@ -30,16 +31,27 @@ const main = async () => {
|
|
|
30
31
|
const usdcTokenAddress = await (0, exports.getTokenAddress)(sdkConfig.USDC_MINT_ADDRESS, wallet.publicKey.toString());
|
|
31
32
|
// Set up the Drift Clearing House
|
|
32
33
|
const clearingHousePublicKey = new web3_js_1.PublicKey(sdkConfig.CLEARING_HOUSE_PROGRAM_ID);
|
|
34
|
+
const bulkAccountLoader = new __2.BulkAccountLoader(connection, 'confirmed', 1000);
|
|
33
35
|
const clearingHouse = new __2.ClearingHouse({
|
|
34
36
|
connection,
|
|
35
37
|
wallet: provider.wallet,
|
|
36
38
|
programID: clearingHousePublicKey,
|
|
39
|
+
marketIndexes: __2.Markets[cluster].map((market) => market.marketIndex),
|
|
40
|
+
bankIndexes: banks_1.Banks[cluster].map((bank) => bank.bankIndex),
|
|
41
|
+
accountSubscription: {
|
|
42
|
+
type: 'polling',
|
|
43
|
+
accountLoader: bulkAccountLoader,
|
|
44
|
+
},
|
|
37
45
|
});
|
|
38
46
|
await clearingHouse.subscribe();
|
|
39
47
|
// Set up Clearing House user client
|
|
40
48
|
const user = new __2.ClearingHouseUser({
|
|
41
49
|
clearingHouse,
|
|
42
50
|
userAccountPublicKey: await clearingHouse.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();
|