add back websocket support as env var toggle

This commit is contained in:
wphan
2023-11-26 23:19:10 -08:00
parent 4380a3d07e
commit 666488e49e

View File

@@ -24,6 +24,9 @@ import {
UserStatsMap, UserStatsMap,
DLOBSubscriber, DLOBSubscriber,
BulkAccountLoader, BulkAccountLoader,
DriftClientSubscriptionConfig,
SlotSubscriber,
SlotSource,
} from '@drift-labs/sdk'; } from '@drift-labs/sdk';
import { logger, setLogLevel } from './utils/logger'; import { logger, setLogLevel } from './utils/logger';
@@ -53,6 +56,7 @@ const sdkConfig = initialize({ env: process.env.ENV });
const stateCommitment: Commitment = 'processed'; const stateCommitment: Commitment = 'processed';
const serverPort = process.env.PORT || 6969; const serverPort = process.env.PORT || 6969;
export const ORDERBOOK_UPDATE_INTERVAL = 1000; export const ORDERBOOK_UPDATE_INTERVAL = 1000;
const useWebsocket = process.env.USE_WEBSOCKET?.toLowerCase() === 'true';
const rateLimitCallsPerSecond = process.env.RATE_LIMIT_CALLS_PER_SECOND const rateLimitCallsPerSecond = process.env.RATE_LIMIT_CALLS_PER_SECOND
? parseInt(process.env.RATE_LIMIT_CALLS_PER_SECOND) ? parseInt(process.env.RATE_LIMIT_CALLS_PER_SECOND)
@@ -117,6 +121,7 @@ const endpoint = process.env.ENDPOINT;
const wsEndpoint = process.env.WS_ENDPOINT; const wsEndpoint = process.env.WS_ENDPOINT;
logger.info(`RPC endpoint: ${endpoint}`); logger.info(`RPC endpoint: ${endpoint}`);
logger.info(`WS endpoint: ${wsEndpoint}`); logger.info(`WS endpoint: ${wsEndpoint}`);
logger.info(`useWebsocket: ${useWebsocket}`);
logger.info(`DriftEnv: ${driftEnv}`); logger.info(`DriftEnv: ${driftEnv}`);
logger.info(`Commit: ${commitHash}`); logger.info(`Commit: ${commitHash}`);
@@ -171,33 +176,52 @@ const main = async () => {
commitment: stateCommitment, commitment: stateCommitment,
}); });
const bulkAccountLoader = new BulkAccountLoader( // only set when polling
let bulkAccountLoader: BulkAccountLoader | undefined;
// only set when using websockets
let slotSubscriber: SlotSubscriber | undefined;
let accountSubscription: DriftClientSubscriptionConfig;
let slotSource: SlotSource;
if (!useWebsocket) {
bulkAccountLoader = new BulkAccountLoader(
connection, connection,
stateCommitment, stateCommitment,
ORDERBOOK_UPDATE_INTERVAL ORDERBOOK_UPDATE_INTERVAL
); );
accountSubscription = {
type: 'polling',
accountLoader: bulkAccountLoader,
};
slotSource = {
getSlot: () => bulkAccountLoader!.getSlot(),
};
} else {
accountSubscription = {
type: 'websocket',
commitment: stateCommitment,
};
slotSubscriber = new SlotSubscriber(connection);
await slotSubscriber.subscribe();
slotSource = {
getSlot: () => slotSubscriber!.getSlot(),
};
}
driftClient = new DriftClient({ driftClient = new DriftClient({
connection, connection,
wallet, wallet,
programID: clearingHousePublicKey, programID: clearingHousePublicKey,
accountSubscription: { accountSubscription,
type: 'polling',
accountLoader: bulkAccountLoader,
},
env: driftEnv, env: driftEnv,
userStats: true, userStats: true,
}); });
const dlobCoder = DLOBOrdersCoder.create(); const dlobCoder = DLOBOrdersCoder.create();
const lamportsBalance = await connection.getBalance(wallet.publicKey);
logger.info(
`DriftClient ProgramId: ${driftClient.program.programId.toBase58()}`
);
logger.info(`Wallet pubkey: ${wallet.publicKey.toBase58()}`);
logger.info(` . SOL balance: ${lamportsBalance / 10 ** 9}`);
await driftClient.subscribe(); await driftClient.subscribe();
driftClient.eventEmitter.on('error', (e) => { driftClient.eventEmitter.on('error', (e) => {
logger.info('clearing house error'); logger.info('clearing house error');
@@ -205,28 +229,39 @@ const main = async () => {
}); });
setInterval(async () => { setInterval(async () => {
lastSlotReceived = bulkAccountLoader.getSlot(); lastSlotReceived = slotSource.getSlot();
}, ORDERBOOK_UPDATE_INTERVAL); }, ORDERBOOK_UPDATE_INTERVAL);
logger.info(`Initializing userMap...`);
const initUserMapStart = Date.now();
const userMap = new UserMap( const userMap = new UserMap(
driftClient, driftClient,
driftClient.userAccountSubscriptionConfig, driftClient.userAccountSubscriptionConfig,
false false
); );
await userMap.subscribe(); await userMap.subscribe();
const userStatsMap = new UserStatsMap(driftClient, { logger.info(`userMap initialized in ${Date.now() - initUserMapStart} ms`);
type: 'polling',
accountLoader: new BulkAccountLoader(connection, stateCommitment, 0),
});
await userStatsMap.subscribe();
logger.info(`Initializing userStatsMap...`);
const initUserStatsMapStart = Date.now();
const userStatsMap = new UserStatsMap(driftClient, accountSubscription);
await userStatsMap.subscribe();
logger.info(
`userStatsMap initialized in ${Date.now() - initUserStatsMapStart} ms`
);
logger.info(`Initializing DLOBSubscriber...`);
const initDlobSubscriberStart = Date.now();
const dlobSubscriber = new DLOBSubscriber({ const dlobSubscriber = new DLOBSubscriber({
driftClient, driftClient,
dlobSource: userMap, dlobSource: userMap,
slotSource: bulkAccountLoader, slotSource,
updateFrequency: ORDERBOOK_UPDATE_INTERVAL, updateFrequency: ORDERBOOK_UPDATE_INTERVAL,
}); });
await dlobSubscriber.subscribe(); await dlobSubscriber.subscribe();
logger.info(
`DLOBSubscriber initialized in ${Date.now() - initDlobSubscriberStart} ms`
);
MARKET_SUBSCRIBERS = await initializeAllMarketSubscribers(driftClient); MARKET_SUBSCRIBERS = await initializeAllMarketSubscribers(driftClient);
@@ -253,7 +288,7 @@ const main = async () => {
// object with userAccount key and orders object serialized // object with userAccount key and orders object serialized
const orders: Array<any> = []; const orders: Array<any> = [];
const oracles: Array<any> = []; const oracles: Array<any> = [];
const slot = bulkAccountLoader.getSlot(); const slot = slotSource.getSlot();
for (const market of driftClient.getPerpMarketAccounts()) { for (const market of driftClient.getPerpMarketAccounts()) {
const oracle = driftClient.getOracleDataForPerpMarket( const oracle = driftClient.getOracleDataForPerpMarket(
@@ -297,7 +332,7 @@ const main = async () => {
app.get('/orders/json', async (_req, res, next) => { app.get('/orders/json', async (_req, res, next) => {
try { try {
// object with userAccount key and orders object serialized // object with userAccount key and orders object serialized
const slot = bulkAccountLoader.getSlot(); const slot = slotSource.getSlot();
const orders: Array<any> = []; const orders: Array<any> = [];
const oracles: Array<any> = []; const oracles: Array<any> = [];
for (const market of driftClient.getPerpMarketAccounts()) { for (const market of driftClient.getPerpMarketAccounts()) {
@@ -460,7 +495,7 @@ const main = async () => {
res.end( res.end(
JSON.stringify({ JSON.stringify({
slot: bulkAccountLoader.getSlot(), slot: slotSource.getSlot(),
data: dlobCoder.encode(dlobOrders).toString('base64'), data: dlobCoder.encode(dlobOrders).toString('base64'),
}) })
); );
@@ -549,7 +584,7 @@ const main = async () => {
.getDLOB() .getDLOB()
.getRestingLimitBids( .getRestingLimitBids(
normedMarketIndex, normedMarketIndex,
bulkAccountLoader.getSlot(), slotSource.getSlot(),
normedMarketType, normedMarketType,
oracle oracle
) )
@@ -560,7 +595,7 @@ const main = async () => {
.getDLOB() .getDLOB()
.getRestingLimitAsks( .getRestingLimitAsks(
normedMarketIndex, normedMarketIndex,
bulkAccountLoader.getSlot(), slotSource.getSlot(),
normedMarketType, normedMarketType,
oracle oracle
) )