要开始重播的槽号,作为 u64。必须在重播窗口内(当前槽的最后约216,000个槽)。示例: currentSlot - 1000重要: 槽必须足够最近,以便在24小时重播窗口内。如果您传递的槽号早于窗口,LaserStream将拒绝请求并发出Operation was attempted past the valid range。
async function getCurrentSlot(): Promise<number> { const r = await fetch(`https://mainnet.helius-rpc.com/?api-key=${process.env.HELIUS_API_KEY}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getSlot', params: [{ commitment: 'confirmed' }] }), }); const { result } = await r.json(); return result as number;}// Load the last slot you processed from wherever you store it.let lastProcessedSlot = Number(process.env.LAST_PROCESSED_SLOT ?? 0);// Check if it's still within the replay windowconst currentSlot = await getCurrentSlot();const maxReplaySlot = currentSlot - 216_000;if (lastProcessedSlot < maxReplaySlot) { console.warn('Disconnection too long, some data may be lost'); lastProcessedSlot = maxReplaySlot;}const subscriptionRequest: SubscribeRequest = { // ... your subscription config fromSlot: lastProcessedSlot, // pass as number, not string};await subscribe(config, subscriptionRequest, async (data) => { // your handler here if (data.transaction?.slot) { lastProcessedSlot = Number(data.transaction.slot); // persist `lastProcessedSlot` here so the next reconnect picks up } });
使用最新上下文启动
从最近几分钟的上下文启动您的应用程序:
// Get a slot from 10 minutes ago (within the 24-hour window)const currentSlot = await getCurrentSlot();const startSlot = currentSlot - 1500; // ~10 minutes agoconst subscriptionRequest: SubscribeRequest = { // ... your subscription config fromSlot: startSlot, // u64 number};
使用近期数据进行测试
使用最近的历史数据进行测试(限最近24小时):
// Test with data from the last 5 minutesconst currentSlot = await getCurrentSlot();const testStartSlot = currentSlot - 750; // ~5 minutes agoconst testEndSlot = currentSlot - 150; // ~1 minute agoconst subscriptionRequest: SubscribeRequest = { // ... your subscription config fromSlot: testStartSlot, // u64 number};// Stop processing when reaching the test end slotconst stream = await subscribe(config, subscriptionRequest, async (data) => { const slot = Number(data.transaction?.slot ?? data.account?.slot ?? 0); if (slot >= testEndSlot) { stream.cancel(); return; } // your test handler here });