Skip to content

Commit

Permalink
fix: resolves #2733
Browse files Browse the repository at this point in the history
  • Loading branch information
jxom committed Sep 17, 2024
1 parent b509c6e commit 312160a
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/pretty-brooms-pull.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"viem": patch
---

Fixed issue where \`watchBlock\` would not respect the \`emitOnBegin\` property for WebSocket Transports.
23 changes: 23 additions & 0 deletions src/actions/public/watchBlocks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -623,6 +623,8 @@ describe('poll', () => {
})
expect(error).toMatchInlineSnapshot('[Error: foo]')
unwatch()

vi.restoreAllMocks()
})
})
})
Expand Down Expand Up @@ -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[] = []
Expand Down
18 changes: 18 additions & 0 deletions src/actions/public/watchBlocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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) {
Expand Down

0 comments on commit 312160a

Please sign in to comment.