diff --git a/.changeset/pretty-brooms-pull.md b/.changeset/pretty-brooms-pull.md new file mode 100644 index 0000000000..1f9a8b5763 --- /dev/null +++ b/.changeset/pretty-brooms-pull.md @@ -0,0 +1,5 @@ +--- +"viem": patch +--- + +Fixed issue where \`watchBlock\` would not respect the \`emitOnBegin\` property for WebSocket Transports. diff --git a/src/actions/public/watchBlocks.test.ts b/src/actions/public/watchBlocks.test.ts index 34f794fcac..00b02adb2a 100644 --- a/src/actions/public/watchBlocks.test.ts +++ b/src/actions/public/watchBlocks.test.ts @@ -623,6 +623,8 @@ describe('poll', () => { }) expect(error).toMatchInlineSnapshot('[Error: foo]') unwatch() + + vi.restoreAllMocks() }) }) }) @@ -654,6 +656,27 @@ describe('subscribe', () => { expect(typeof blocks[0].number).toBe('bigint') }) + describe('emitOnBegin', () => { + test('watches for new blocks', async () => { + const blocks: OnBlockParameter[] = [] + const unwatch = watchBlocks(webSocketClient, { + emitOnBegin: true, + onBlock: (block) => blocks.push(block), + }) + await wait(800) + await mine(client, { blocks: 1 }) + await wait(200) + await mine(client, { blocks: 1 }) + await wait(200) + await mine(client, { blocks: 1 }) + await wait(200) + await mine(client, { blocks: 1 }) + await wait(200) + unwatch() + expect(blocks.length).toBe(5) + }) + }) + describe('behavior', () => { test('does not emit when no new incoming blocks', async () => { const blocks: OnBlockParameter[] = [] diff --git a/src/actions/public/watchBlocks.ts b/src/actions/public/watchBlocks.ts index b68bd61017..0ecd26d8bb 100644 --- a/src/actions/public/watchBlocks.ts +++ b/src/actions/public/watchBlocks.ts @@ -202,9 +202,26 @@ export function watchBlocks< const subscribeBlocks = () => { let active = true + let emitFetched = true let unsubscribe = () => (active = false) ;(async () => { try { + if (emitOnBegin) { + getAction( + client, + getBlock, + 'getBlock', + )({ + blockTag, + includeTransactions, + }).then((block) => { + if (!active) return + if (!emitFetched) return + onBlock(block as any, undefined) + emitFetched = false + }) + } + const transport = (() => { if (client.transport.type === 'fallback') { const transport = client.transport.transports.find( @@ -225,6 +242,7 @@ export function watchBlocks< client.chain?.formatters?.block?.format || formatBlock const block = format(data.result) onBlock(block, prevBlock as any) + emitFetched = false prevBlock = block }, onError(error: Error) {