|
| 1 | +import { Bot } from '../types'; |
| 2 | +import { logger } from '../logger'; |
| 3 | +import { GlobalConfig, PythLazerCrankerBotConfig } from '../config'; |
| 4 | +import { PriceUpdateAccount } from '@pythnetwork/pyth-solana-receiver/lib/PythSolanaReceiver'; |
| 5 | +import { |
| 6 | + BlockhashSubscriber, |
| 7 | + DriftClient, |
| 8 | + getOracleClient, |
| 9 | + getPythLazerOraclePublicKey, |
| 10 | + OracleClient, |
| 11 | + OracleSource, |
| 12 | + PriorityFeeSubscriber, |
| 13 | + TxSigAndSlot, |
| 14 | +} from '@drift-labs/sdk'; |
| 15 | +import { BundleSender } from '../bundleSender'; |
| 16 | +import { |
| 17 | + AddressLookupTableAccount, |
| 18 | + ComputeBudgetProgram, |
| 19 | +} from '@solana/web3.js'; |
| 20 | +import { chunks, simulateAndGetTxWithCUs, sleepMs } from '../utils'; |
| 21 | +import { Agent, setGlobalDispatcher } from 'undici'; |
| 22 | +import { PythLazerClient } from '@pythnetwork/pyth-lazer-sdk'; |
| 23 | + |
| 24 | +setGlobalDispatcher( |
| 25 | + new Agent({ |
| 26 | + connections: 200, |
| 27 | + }) |
| 28 | +); |
| 29 | + |
| 30 | +const SIM_CU_ESTIMATE_MULTIPLIER = 1.5; |
| 31 | + |
| 32 | +export class PythLazerCrankerBot implements Bot { |
| 33 | + private wsClient: PythLazerClient; |
| 34 | + private pythOracleClient: OracleClient; |
| 35 | + readonly decodeFunc: (name: string, data: Buffer) => PriceUpdateAccount; |
| 36 | + |
| 37 | + public name: string; |
| 38 | + public dryRun: boolean; |
| 39 | + private intervalMs: number; |
| 40 | + private feedIdChunkToPriceMessage: Map<number[], string> = new Map(); |
| 41 | + public defaultIntervalMs = 30_000; |
| 42 | + |
| 43 | + private blockhashSubscriber: BlockhashSubscriber; |
| 44 | + private health: boolean = true; |
| 45 | + private slotStalenessThresholdRestart: number = 300; |
| 46 | + private txSuccessRateThreshold: number = 0.5; |
| 47 | + |
| 48 | + constructor( |
| 49 | + private globalConfig: GlobalConfig, |
| 50 | + private crankConfigs: PythLazerCrankerBotConfig, |
| 51 | + private driftClient: DriftClient, |
| 52 | + private priorityFeeSubscriber?: PriorityFeeSubscriber, |
| 53 | + private bundleSender?: BundleSender, |
| 54 | + private lookupTableAccounts: AddressLookupTableAccount[] = [] |
| 55 | + ) { |
| 56 | + this.name = crankConfigs.botId; |
| 57 | + this.dryRun = crankConfigs.dryRun; |
| 58 | + this.intervalMs = crankConfigs.intervalMs; |
| 59 | + if (!globalConfig.hermesEndpoint) { |
| 60 | + throw new Error('Missing hermesEndpoint in global config'); |
| 61 | + } |
| 62 | + |
| 63 | + if (globalConfig.driftEnv != 'devnet') { |
| 64 | + throw new Error('Only devnet drift env is supported'); |
| 65 | + } |
| 66 | + |
| 67 | + const hermesEndpointParts = globalConfig.hermesEndpoint.split('?token='); |
| 68 | + this.wsClient = new PythLazerClient( |
| 69 | + hermesEndpointParts[0], |
| 70 | + hermesEndpointParts[1] |
| 71 | + ); |
| 72 | + |
| 73 | + this.pythOracleClient = getOracleClient( |
| 74 | + OracleSource.PYTH_LAZER, |
| 75 | + driftClient.connection, |
| 76 | + driftClient.program |
| 77 | + ); |
| 78 | + this.decodeFunc = |
| 79 | + this.driftClient.program.account.pythLazerOracle.coder.accounts.decodeUnchecked.bind( |
| 80 | + this.driftClient.program.account.pythLazerOracle.coder.accounts |
| 81 | + ); |
| 82 | + |
| 83 | + this.blockhashSubscriber = new BlockhashSubscriber({ |
| 84 | + connection: driftClient.connection, |
| 85 | + }); |
| 86 | + this.txSuccessRateThreshold = crankConfigs.txSuccessRateThreshold; |
| 87 | + this.slotStalenessThresholdRestart = |
| 88 | + crankConfigs.slotStalenessThresholdRestart; |
| 89 | + } |
| 90 | + |
| 91 | + async init(): Promise<void> { |
| 92 | + logger.info(`Initializing ${this.name} bot`); |
| 93 | + await this.blockhashSubscriber.subscribe(); |
| 94 | + this.lookupTableAccounts.push( |
| 95 | + await this.driftClient.fetchMarketLookupTableAccount() |
| 96 | + ); |
| 97 | + |
| 98 | + const updateConfigs = this.crankConfigs.updateConfigs; |
| 99 | + |
| 100 | + let subscriptionId = 1; |
| 101 | + for (const configChunk of chunks(Object.keys(updateConfigs), 11)) { |
| 102 | + const priceFeedIds: number[] = configChunk.map((alias) => { |
| 103 | + return updateConfigs[alias].feedId; |
| 104 | + }); |
| 105 | + |
| 106 | + const sendMessage = () => |
| 107 | + this.wsClient.send({ |
| 108 | + type: 'subscribe', |
| 109 | + subscriptionId, |
| 110 | + priceFeedIds, |
| 111 | + properties: ['price'], |
| 112 | + chains: ['solana'], |
| 113 | + deliveryFormat: 'json', |
| 114 | + channel: 'fixed_rate@200ms', |
| 115 | + jsonBinaryEncoding: 'hex', |
| 116 | + }); |
| 117 | + if (this.wsClient.ws.readyState != 1) { |
| 118 | + this.wsClient.ws.addEventListener('open', () => { |
| 119 | + sendMessage(); |
| 120 | + }); |
| 121 | + } else { |
| 122 | + sendMessage(); |
| 123 | + } |
| 124 | + |
| 125 | + this.wsClient.addMessageListener((message) => { |
| 126 | + switch (message.type) { |
| 127 | + case 'json': { |
| 128 | + if (message.value.type == 'streamUpdated') { |
| 129 | + if (message.value.solana?.data) |
| 130 | + this.feedIdChunkToPriceMessage.set( |
| 131 | + priceFeedIds, |
| 132 | + message.value.solana.data |
| 133 | + ); |
| 134 | + } |
| 135 | + break; |
| 136 | + } |
| 137 | + default: { |
| 138 | + break; |
| 139 | + } |
| 140 | + } |
| 141 | + }); |
| 142 | + subscriptionId++; |
| 143 | + } |
| 144 | + |
| 145 | + this.priorityFeeSubscriber?.updateAddresses( |
| 146 | + Object.keys(this.feedIdChunkToPriceMessage) |
| 147 | + .flat() |
| 148 | + .map((feedId) => |
| 149 | + getPythLazerOraclePublicKey( |
| 150 | + this.driftClient.program.programId, |
| 151 | + Number(feedId) |
| 152 | + ) |
| 153 | + ) |
| 154 | + ); |
| 155 | + } |
| 156 | + |
| 157 | + async reset(): Promise<void> { |
| 158 | + logger.info(`Resetting ${this.name} bot`); |
| 159 | + this.blockhashSubscriber.unsubscribe(); |
| 160 | + await this.driftClient.unsubscribe(); |
| 161 | + this.wsClient.ws.close(); |
| 162 | + } |
| 163 | + |
| 164 | + async startIntervalLoop(intervalMs = this.intervalMs): Promise<void> { |
| 165 | + logger.info(`Starting ${this.name} bot with interval ${intervalMs} ms`); |
| 166 | + await sleepMs(5000); |
| 167 | + await this.runCrankLoop(); |
| 168 | + |
| 169 | + setInterval(async () => { |
| 170 | + await this.runCrankLoop(); |
| 171 | + }, intervalMs); |
| 172 | + } |
| 173 | + |
| 174 | + private async getBlockhashForTx(): Promise<string> { |
| 175 | + const cachedBlockhash = this.blockhashSubscriber.getLatestBlockhash(10); |
| 176 | + if (cachedBlockhash) { |
| 177 | + return cachedBlockhash.blockhash as string; |
| 178 | + } |
| 179 | + |
| 180 | + const recentBlockhash = |
| 181 | + await this.driftClient.connection.getLatestBlockhash({ |
| 182 | + commitment: 'confirmed', |
| 183 | + }); |
| 184 | + |
| 185 | + return recentBlockhash.blockhash; |
| 186 | + } |
| 187 | + |
| 188 | + async runCrankLoop() { |
| 189 | + for (const [ |
| 190 | + feedIds, |
| 191 | + priceMessage, |
| 192 | + ] of this.feedIdChunkToPriceMessage.entries()) { |
| 193 | + const ixs = [ |
| 194 | + ComputeBudgetProgram.setComputeUnitLimit({ |
| 195 | + units: 1_400_000, |
| 196 | + }), |
| 197 | + ]; |
| 198 | + if (this.globalConfig.useJito) { |
| 199 | + ixs.push(this.bundleSender!.getTipIx()); |
| 200 | + const simResult = await simulateAndGetTxWithCUs({ |
| 201 | + ixs, |
| 202 | + connection: this.driftClient.connection, |
| 203 | + payerPublicKey: this.driftClient.wallet.publicKey, |
| 204 | + lookupTableAccounts: this.lookupTableAccounts, |
| 205 | + cuLimitMultiplier: SIM_CU_ESTIMATE_MULTIPLIER, |
| 206 | + doSimulation: true, |
| 207 | + recentBlockhash: await this.getBlockhashForTx(), |
| 208 | + }); |
| 209 | + simResult.tx.sign([ |
| 210 | + // @ts-ignore |
| 211 | + this.driftClient.wallet.payer, |
| 212 | + ]); |
| 213 | + this.bundleSender?.sendTransactions( |
| 214 | + [simResult.tx], |
| 215 | + undefined, |
| 216 | + undefined, |
| 217 | + false |
| 218 | + ); |
| 219 | + } else { |
| 220 | + const priorityFees = Math.floor( |
| 221 | + (this.priorityFeeSubscriber?.getCustomStrategyResult() || 0) * |
| 222 | + this.driftClient.txSender.getSuggestedPriorityFeeMultiplier() |
| 223 | + ); |
| 224 | + logger.info( |
| 225 | + `Priority fees to use: ${priorityFees} with multiplier: ${this.driftClient.txSender.getSuggestedPriorityFeeMultiplier()}` |
| 226 | + ); |
| 227 | + ixs.push( |
| 228 | + ComputeBudgetProgram.setComputeUnitPrice({ |
| 229 | + microLamports: priorityFees, |
| 230 | + }) |
| 231 | + ); |
| 232 | + } |
| 233 | + const pythLazerIxs = |
| 234 | + await this.driftClient.getPostPythLazerOracleUpdateIxs( |
| 235 | + feedIds, |
| 236 | + priceMessage, |
| 237 | + ixs |
| 238 | + ); |
| 239 | + ixs.push(...pythLazerIxs); |
| 240 | + const simResult = await simulateAndGetTxWithCUs({ |
| 241 | + ixs, |
| 242 | + connection: this.driftClient.connection, |
| 243 | + payerPublicKey: this.driftClient.wallet.publicKey, |
| 244 | + lookupTableAccounts: this.lookupTableAccounts, |
| 245 | + cuLimitMultiplier: SIM_CU_ESTIMATE_MULTIPLIER, |
| 246 | + doSimulation: true, |
| 247 | + recentBlockhash: await this.getBlockhashForTx(), |
| 248 | + }); |
| 249 | + const startTime = Date.now(); |
| 250 | + this.driftClient |
| 251 | + .sendTransaction(simResult.tx) |
| 252 | + .then((txSigAndSlot: TxSigAndSlot) => { |
| 253 | + logger.info( |
| 254 | + `Posted pyth lazer oracles for ${feedIds} update atomic tx: ${ |
| 255 | + txSigAndSlot.txSig |
| 256 | + }, took ${Date.now() - startTime}ms` |
| 257 | + ); |
| 258 | + }) |
| 259 | + .catch((e) => { |
| 260 | + console.log(e); |
| 261 | + }); |
| 262 | + } |
| 263 | + } |
| 264 | + |
| 265 | + async healthCheck(): Promise<boolean> { |
| 266 | + return this.health; |
| 267 | + } |
| 268 | +} |
0 commit comments