-
Notifications
You must be signed in to change notification settings - Fork 38
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
refactor(sdk): Support multiple contracts in ChainEventPoller
#2928
Open
teogeb
wants to merge
9
commits into
main
Choose a base branch
from
sdk-chaineventpoller-supports-multiple-contracts
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
68d7583
support multiple contracts
teogeb 9cd6dd2
style
teogeb fc9604b
catch listener error
teogeb c381a14
style
teogeb 7c9f56f
test cleanup
teogeb b4a6eef
style
teogeb 3551b3d
rm try-catch
teogeb 1a0d0b7
Merge branch 'main' into sdk-chaineventpoller-supports-multiple-contr…
teogeb da22c00
style
teogeb File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,39 +1,51 @@ | ||
import { Logger, Multimap, randomString, scheduleAtInterval, wait } from '@streamr/utils' | ||
import { Contract, EventLog, Provider } from 'ethers' | ||
import { sample } from 'lodash' | ||
|
||
type EventName = string | ||
type Listener = (...args: any[]) => void | ||
import { EthereumAddress, Logger, randomString, scheduleAtInterval, toEthereumAddress, wait } from '@streamr/utils' | ||
import { AbstractProvider, EventFragment, Interface } from 'ethers' | ||
import { remove, sample, uniq } from 'lodash' | ||
import { inject, Lifecycle, scoped } from 'tsyringe' | ||
import { ConfigInjectionToken, StrictStreamrClientConfig } from '../Config' | ||
import { RpcProviderSource } from '../RpcProviderSource' | ||
|
||
export interface EventListenerDefinition { | ||
onEvent: (...args: any[]) => void | ||
contractInterfaceFragment: EventFragment | ||
contractAddress: EthereumAddress | ||
} | ||
|
||
const BLOCK_NUMBER_QUERY_RETRY_DELAY = 1000 | ||
export const POLLS_SINCE_LAST_FROM_BLOCK_UPDATE_THRESHOLD = 30 | ||
|
||
@scoped(Lifecycle.ContainerScoped) | ||
export class ChainEventPoller { | ||
|
||
private listeners: Multimap<EventName, Listener> = new Multimap() | ||
private abortController?: AbortController | ||
private contracts: Contract[] | ||
private listeners: EventListenerDefinition[] = [] | ||
private providers: AbstractProvider[] | ||
private pollInterval: number | ||
private abortController?: AbortController | ||
|
||
// all these contracts are actually the same chain contract (i.e. StreamRegistry), but have different providers | ||
// connected to them | ||
constructor(contracts: Contract[], pollInterval: number) { | ||
this.contracts = contracts | ||
this.pollInterval = pollInterval | ||
constructor( | ||
rpcProviderSource: RpcProviderSource, | ||
@inject(ConfigInjectionToken) config: Pick<StrictStreamrClientConfig, 'contracts'> | ||
) { | ||
this.providers = rpcProviderSource.getSubProviders() | ||
this.pollInterval = config.contracts.pollInterval | ||
} | ||
|
||
on(eventName: string, listener: Listener): void { | ||
const started = !this.listeners.isEmpty() | ||
this.listeners.add(eventName, listener) | ||
on(definition: EventListenerDefinition): void { | ||
const started = this.listeners.length > 0 | ||
this.listeners.push(definition) | ||
if (!started) { | ||
this.start() | ||
} | ||
} | ||
|
||
off(eventName: string, listener: Listener): void { | ||
const started = !this.listeners.isEmpty() | ||
this.listeners.remove(eventName, listener) | ||
if (started && this.listeners.isEmpty()) { | ||
off(definition: EventListenerDefinition): void { | ||
const started = this.listeners.length > 0 | ||
remove(this.listeners, (l) => { | ||
return (l.contractAddress === definition.contractAddress) | ||
&& (l.contractInterfaceFragment.topicHash === definition.contractInterfaceFragment.topicHash) | ||
&& (l.onEvent == definition.onEvent) | ||
}) | ||
if (started && this.listeners.length === 0) { | ||
this.abortController!.abort() | ||
} | ||
} | ||
|
@@ -48,7 +60,7 @@ export class ChainEventPoller { | |
let fromBlock: number | undefined = undefined | ||
do { | ||
try { | ||
fromBlock = await sample(this.getProviders())!.getBlockNumber() | ||
fromBlock = await sample(this.providers)!.getBlockNumber() | ||
} catch (err) { | ||
logger.debug('Failed to query block number', { err }) | ||
await wait(BLOCK_NUMBER_QUERY_RETRY_DELAY) // TODO: pass signal? | ||
|
@@ -57,25 +69,46 @@ export class ChainEventPoller { | |
|
||
let pollsSinceFromBlockUpdate = 0 | ||
await scheduleAtInterval(async () => { | ||
const contract = sample(this.contracts)! | ||
const eventNames = [...this.listeners.keys()] | ||
const provider = sample(this.providers)! | ||
const eventNames = this.listeners.map((l) => l.contractInterfaceFragment.name) | ||
let newFromBlock = 0 | ||
let events: EventLog[] | undefined = undefined | ||
let events: { contractAddress: EthereumAddress, name: string, args: any[], blockNumber: number }[] | undefined = undefined | ||
|
||
try { | ||
// If we haven't updated `fromBlock` for a while, fetch the latest block number explicitly. If | ||
// `fromBlock` falls too much behind the current block number, the RPCs may start rejecting our | ||
// eth_getLogs requests (presumably for performance reasons). | ||
if (pollsSinceFromBlockUpdate >= POLLS_SINCE_LAST_FROM_BLOCK_UPDATE_THRESHOLD) { | ||
newFromBlock = await contract.runner!.provider!.getBlockNumber() + 1 | ||
newFromBlock = await provider.getBlockNumber() + 1 | ||
logger.debug('Fetch next block number explicitly', { newFromBlock } ) | ||
if (abortController.signal.aborted) { | ||
return | ||
} | ||
} | ||
|
||
logger.debug('Polling', { fromBlock, eventNames }) | ||
events = await contract.queryFilter([eventNames], fromBlock) as EventLog[] | ||
const filter = { | ||
address: uniq(this.listeners.map((l) => l.contractAddress)), | ||
topics: [uniq(this.listeners.map((l) => l.contractInterfaceFragment.topicHash))], | ||
fromBlock | ||
Comment on lines
+90
to
+91
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We need to check that this definitely works as we think it does |
||
} | ||
const logItems = await provider.getLogs(filter) | ||
events = [] | ||
for (const logItem of logItems) { | ||
const definition = this.listeners.find((l) => { | ||
return (l.contractAddress === toEthereumAddress(logItem.address)) | ||
&& (l.contractInterfaceFragment.topicHash === logItem.topics[0]) | ||
}) | ||
if (definition !== undefined) { | ||
const contractInterface = new Interface([definition.contractInterfaceFragment.format('minimal')]) | ||
const args = contractInterface.decodeEventLog(definition.contractInterfaceFragment.name, logItem.data, logItem.topics) | ||
events.push({ | ||
contractAddress: definition.contractAddress, | ||
name: definition.contractInterfaceFragment.name, | ||
args, | ||
blockNumber: logItem.blockNumber | ||
}) | ||
} | ||
} | ||
logger.debug('Polled', { fromBlock, events: events.length }) | ||
} catch (err) { | ||
logger.debug('Failed to poll', { reason: err?.reason, eventNames, fromBlock }) | ||
|
@@ -87,9 +120,11 @@ export class ChainEventPoller { | |
|
||
if (events !== undefined && events.length > 0) { | ||
for (const event of events) { | ||
const listeners = this.listeners.get(event.fragment.name) | ||
const listeners = this.listeners.filter( | ||
(l) => (l.contractAddress === event.contractAddress) && (l.contractInterfaceFragment.name === event.name) | ||
) | ||
for (const listener of listeners) { | ||
listener(...event.args, event.blockNumber) | ||
listener.onEvent(...event.args, event.blockNumber) | ||
} | ||
} | ||
newFromBlock = Math.max(...events.map((e) => e.blockNumber)) + 1 | ||
|
@@ -108,8 +143,4 @@ export class ChainEventPoller { | |
}, this.pollInterval, true, abortController.signal) | ||
}) | ||
} | ||
|
||
private getProviders(): Provider[] { | ||
return this.contracts.map((c) => c.runner!.provider!) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe worth commenting how the filtering logic here works, e.g.