envio 3.3.0-alpha.1 → 3.3.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/evm.schema.json +10 -0
  2. package/index.d.ts +45 -25
  3. package/package.json +7 -7
  4. package/src/Address.res +5 -2
  5. package/src/Address.res.mjs +3 -1
  6. package/src/Api.res +1 -1
  7. package/src/Api.res.mjs +1 -1
  8. package/src/Batch.res +0 -6
  9. package/src/Batch.res.mjs +1 -12
  10. package/src/BatchProcessing.res +7 -12
  11. package/src/BatchProcessing.res.mjs +8 -7
  12. package/src/Bin.res +3 -0
  13. package/src/Bin.res.mjs +4 -0
  14. package/src/ChainFetching.res +43 -9
  15. package/src/ChainFetching.res.mjs +34 -15
  16. package/src/ChainMetadata.res +1 -11
  17. package/src/ChainMetadata.res.mjs +1 -10
  18. package/src/ChainState.res +605 -151
  19. package/src/ChainState.res.mjs +427 -104
  20. package/src/ChainState.resi +72 -4
  21. package/src/Config.res +61 -33
  22. package/src/Config.res.mjs +50 -10
  23. package/src/ContractRegisterContext.res +2 -12
  24. package/src/ContractRegisterContext.res.mjs +3 -5
  25. package/src/Core.res +14 -3
  26. package/src/CrossChainState.res +113 -89
  27. package/src/CrossChainState.res.mjs +64 -60
  28. package/src/CrossChainState.resi +1 -1
  29. package/src/Ecosystem.res +5 -6
  30. package/src/Ecosystem.res.mjs +3 -3
  31. package/src/Envio.res +17 -11
  32. package/src/EnvioGlobal.res +53 -0
  33. package/src/EnvioGlobal.res.mjs +31 -0
  34. package/src/EventConfigBuilder.res +177 -88
  35. package/src/EventConfigBuilder.res.mjs +99 -42
  36. package/src/EventProcessing.res +74 -28
  37. package/src/EventProcessing.res.mjs +55 -29
  38. package/src/ExitOnCaughtUp.res +10 -2
  39. package/src/ExitOnCaughtUp.res.mjs +10 -1
  40. package/src/FetchState.res +544 -356
  41. package/src/FetchState.res.mjs +412 -471
  42. package/src/HandlerLoader.res +8 -104
  43. package/src/HandlerLoader.res.mjs +2 -81
  44. package/src/HandlerRegister.res +518 -144
  45. package/src/HandlerRegister.res.mjs +285 -133
  46. package/src/HandlerRegister.resi +24 -8
  47. package/src/IndexerState.res +10 -3
  48. package/src/IndexerState.res.mjs +11 -4
  49. package/src/IndexerState.resi +2 -1
  50. package/src/IndexingAddresses.res +108 -0
  51. package/src/IndexingAddresses.res.mjs +101 -0
  52. package/src/IndexingAddresses.resi +34 -0
  53. package/src/Internal.res +155 -46
  54. package/src/Internal.res.mjs +30 -2
  55. package/src/LoadLayer.res +5 -5
  56. package/src/LoadLayer.res.mjs +6 -6
  57. package/src/LogSelection.res +102 -165
  58. package/src/LogSelection.res.mjs +101 -116
  59. package/src/Main.res +71 -236
  60. package/src/Main.res.mjs +60 -145
  61. package/src/Metrics.res +74 -0
  62. package/src/Metrics.res.mjs +75 -0
  63. package/src/PgStorage.res +4 -4
  64. package/src/PgStorage.res.mjs +5 -5
  65. package/src/Prometheus.res +10 -63
  66. package/src/Prometheus.res.mjs +124 -171
  67. package/src/PruneStaleHistory.res +2 -2
  68. package/src/PruneStaleHistory.res.mjs +3 -3
  69. package/src/RawEvent.res +7 -2
  70. package/src/RawEvent.res.mjs +4 -4
  71. package/src/Rollback.res +3 -3
  72. package/src/Rollback.res.mjs +4 -4
  73. package/src/RollbackCommit.res +4 -1
  74. package/src/RollbackCommit.res.mjs +3 -2
  75. package/src/SimulateDeadInputTracker.res +85 -0
  76. package/src/SimulateDeadInputTracker.res.mjs +73 -0
  77. package/src/SimulateDeadInputTracker.resi +12 -0
  78. package/src/SimulateItems.res +91 -23
  79. package/src/SimulateItems.res.mjs +55 -32
  80. package/src/TestIndexer.res +54 -40
  81. package/src/TestIndexer.res.mjs +37 -30
  82. package/src/bindings/Performance.res +7 -0
  83. package/src/bindings/Performance.res.mjs +21 -0
  84. package/src/bindings/Performance.resi +7 -0
  85. package/src/bindings/Viem.res +0 -41
  86. package/src/bindings/Viem.res.mjs +1 -43
  87. package/src/sources/BlockStore.res +46 -0
  88. package/src/sources/BlockStore.res.mjs +24 -0
  89. package/src/sources/EventRouter.res +36 -33
  90. package/src/sources/EventRouter.res.mjs +13 -14
  91. package/src/sources/Evm.res +83 -72
  92. package/src/sources/Evm.res.mjs +53 -69
  93. package/src/sources/EvmChain.res +18 -20
  94. package/src/sources/EvmChain.res.mjs +15 -15
  95. package/src/sources/EvmRpcClient.res +74 -5
  96. package/src/sources/EvmRpcClient.res.mjs +13 -4
  97. package/src/sources/FieldMask.res +39 -0
  98. package/src/sources/FieldMask.res.mjs +42 -0
  99. package/src/sources/Fuel.res +9 -6
  100. package/src/sources/Fuel.res.mjs +5 -10
  101. package/src/sources/HyperFuelSource.res +46 -50
  102. package/src/sources/HyperFuelSource.res.mjs +64 -54
  103. package/src/sources/HyperSync.res +39 -7
  104. package/src/sources/HyperSync.res.mjs +57 -37
  105. package/src/sources/HyperSync.resi +12 -2
  106. package/src/sources/HyperSyncClient.res +22 -111
  107. package/src/sources/HyperSyncClient.res.mjs +2 -30
  108. package/src/sources/HyperSyncHeightStream.res +1 -8
  109. package/src/sources/HyperSyncHeightStream.res.mjs +0 -2
  110. package/src/sources/HyperSyncSource.res +94 -107
  111. package/src/sources/HyperSyncSource.res.mjs +82 -86
  112. package/src/sources/Rpc.res +15 -47
  113. package/src/sources/Rpc.res.mjs +25 -56
  114. package/src/sources/RpcSource.res +320 -467
  115. package/src/sources/RpcSource.res.mjs +268 -385
  116. package/src/sources/RpcWebSocketHeightStream.res +0 -5
  117. package/src/sources/RpcWebSocketHeightStream.res.mjs +0 -2
  118. package/src/sources/SimulateSource.res +10 -4
  119. package/src/sources/SimulateSource.res.mjs +16 -6
  120. package/src/sources/Source.res +34 -6
  121. package/src/sources/SourceManager.res +77 -19
  122. package/src/sources/SourceManager.res.mjs +63 -21
  123. package/src/sources/SourceManager.resi +10 -0
  124. package/src/sources/Svm.res +31 -16
  125. package/src/sources/Svm.res.mjs +36 -13
  126. package/src/sources/SvmHyperSyncClient.res +5 -32
  127. package/src/sources/SvmHyperSyncSource.res +159 -134
  128. package/src/sources/SvmHyperSyncSource.res.mjs +164 -129
  129. package/src/sources/TransactionStore.res +49 -0
  130. package/src/sources/TransactionStore.res.mjs +30 -0
  131. package/src/tui/Tui.res +13 -16
  132. package/src/tui/Tui.res.mjs +12 -14
  133. package/svm.schema.json +49 -37
  134. package/src/bindings/Hrtime.res +0 -58
  135. package/src/bindings/Hrtime.res.mjs +0 -90
  136. package/src/bindings/Hrtime.resi +0 -30
package/src/LoadLayer.res CHANGED
@@ -85,7 +85,7 @@ let callEffect = (
85
85
  )
86
86
 
87
87
  if hadActiveCalls {
88
- let elapsed = Hrtime.secondsBetween(~from=effect.prevCallStartTimerRef, ~to=timerRef)
88
+ let elapsed = Performance.secondsBetween(~from=effect.prevCallStartTimerRef, ~to=timerRef)
89
89
  if elapsed > 0. {
90
90
  Prometheus.EffectCalls.timeCounter->Prometheus.SafeCounter.handleFloat(
91
91
  ~labels=effectName,
@@ -113,17 +113,17 @@ let callEffect = (
113
113
  ~labels=effectName,
114
114
  ~value=effect.activeCallsCount,
115
115
  )
116
- let newTimer = Hrtime.makeTimer()
116
+ let newTimer = Performance.now()
117
117
  Prometheus.EffectCalls.timeCounter->Prometheus.SafeCounter.handleFloat(
118
118
  ~labels=effectName,
119
- ~value=Hrtime.secondsBetween(~from=effect.prevCallStartTimerRef, ~to=newTimer),
119
+ ~value=Performance.secondsBetween(~from=effect.prevCallStartTimerRef, ~to=newTimer),
120
120
  )
121
121
  effect.prevCallStartTimerRef = newTimer
122
122
 
123
123
  Prometheus.EffectCalls.totalCallsCount->Prometheus.SafeCounter.increment(~labels=effectName)
124
124
  Prometheus.EffectCalls.sumTimeCounter->Prometheus.SafeCounter.handleFloat(
125
125
  ~labels=effectName,
126
- ~value=timerRef->Hrtime.timeSince->Hrtime.toSecondsFloat,
126
+ ~value=timerRef->Performance.secondsSince,
127
127
  )
128
128
  })
129
129
  }
@@ -137,7 +137,7 @@ let rec executeWithRateLimit = (
137
137
  ) => {
138
138
  let effectName = effect.name
139
139
 
140
- let timerRef = Hrtime.makeTimer()
140
+ let timerRef = Performance.now()
141
141
  let promises = []
142
142
 
143
143
  switch effect.rateLimit {
@@ -2,11 +2,11 @@
2
2
 
3
3
  import * as Table from "./db/Table.res.mjs";
4
4
  import * as Utils from "./Utils.res.mjs";
5
- import * as Hrtime from "./bindings/Hrtime.res.mjs";
6
5
  import * as Logging from "./Logging.res.mjs";
7
6
  import * as Ecosystem from "./Ecosystem.res.mjs";
8
7
  import * as Prometheus from "./Prometheus.res.mjs";
9
8
  import * as LoadManager from "./LoadManager.res.mjs";
9
+ import * as Performance from "./bindings/Performance.res.mjs";
10
10
  import * as Persistence from "./Persistence.res.mjs";
11
11
  import * as EntityFilter from "./db/EntityFilter.res.mjs";
12
12
  import * as IndexerState from "./IndexerState.res.mjs";
@@ -55,7 +55,7 @@ function callEffect(effect, arg, inMemTable, timerRef, onError) {
55
55
  effect.activeCallsCount = effect.activeCallsCount + 1 | 0;
56
56
  Prometheus.SafeGauge.handleInt(Prometheus.EffectCalls.activeCallsCount, effectName, effect.activeCallsCount);
57
57
  if (hadActiveCalls) {
58
- let elapsed = Hrtime.secondsBetween(effect.prevCallStartTimerRef, timerRef);
58
+ let elapsed = Performance.secondsBetween(effect.prevCallStartTimerRef, timerRef);
59
59
  if (elapsed > 0) {
60
60
  Prometheus.SafeCounter.handleFloat(Prometheus.EffectCalls.timeCounter, effectName, elapsed);
61
61
  }
@@ -64,17 +64,17 @@ function callEffect(effect, arg, inMemTable, timerRef, onError) {
64
64
  return effect.handler(arg).then(output => InMemoryStore.setEffectOutput(inMemTable, arg.checkpointId, arg.cacheKey, output, arg.context.cache)).catch(exn => onError(arg.cacheKey, exn)).finally(() => {
65
65
  effect.activeCallsCount = effect.activeCallsCount - 1 | 0;
66
66
  Prometheus.SafeGauge.handleInt(Prometheus.EffectCalls.activeCallsCount, effectName, effect.activeCallsCount);
67
- let newTimer = Hrtime.makeTimer();
68
- Prometheus.SafeCounter.handleFloat(Prometheus.EffectCalls.timeCounter, effectName, Hrtime.secondsBetween(effect.prevCallStartTimerRef, newTimer));
67
+ let newTimer = Performance.now();
68
+ Prometheus.SafeCounter.handleFloat(Prometheus.EffectCalls.timeCounter, effectName, Performance.secondsBetween(effect.prevCallStartTimerRef, newTimer));
69
69
  effect.prevCallStartTimerRef = newTimer;
70
70
  Prometheus.SafeCounter.increment(Prometheus.EffectCalls.totalCallsCount, effectName);
71
- Prometheus.SafeCounter.handleFloat(Prometheus.EffectCalls.sumTimeCounter, effectName, Hrtime.toSecondsFloat(Hrtime.timeSince(timerRef)));
71
+ Prometheus.SafeCounter.handleFloat(Prometheus.EffectCalls.sumTimeCounter, effectName, Performance.secondsSince(timerRef));
72
72
  });
73
73
  }
74
74
 
75
75
  function executeWithRateLimit(effect, effectArgs, inMemTable, onError, isFromQueue) {
76
76
  let effectName = effect.name;
77
- let timerRef = Hrtime.makeTimer();
77
+ let timerRef = Performance.now();
78
78
  let promises = [];
79
79
  let state = effect.rateLimit;
80
80
  if (state !== undefined) {
@@ -1,5 +1,8 @@
1
1
  exception MissingRequiredTopic0
2
- let makeTopicSelection = (~topic0, ~topic1=[], ~topic2=[], ~topic3=[]) =>
2
+ let makeTopicSelection = (~topic0, ~topic1=[], ~topic2=[], ~topic3=[]): result<
3
+ Internal.topicSelection,
4
+ exn,
5
+ > =>
3
6
  if topic0->Utils.Array.isEmpty {
4
7
  Error(MissingRequiredTopic0)
5
8
  } else {
@@ -37,8 +40,8 @@ let compressTopicSelections = (topicSelections: array<Internal.topicSelection>)
37
40
  switch topic0sOfSelectionsWithoutFilters {
38
41
  | [] => selectionsWithFilters
39
42
  | topic0 =>
40
- let selectionWithoutFilters = {
41
- Internal.topic0,
43
+ let selectionWithoutFilters: Internal.topicSelection = {
44
+ topic0,
42
45
  topic1: [],
43
46
  topic2: [],
44
47
  topic3: [],
@@ -57,20 +60,33 @@ let make = (~addresses, ~topicSelections) => {
57
60
  {addresses, topicSelections}
58
61
  }
59
62
 
60
- type parsedEventFilters = {
61
- getEventFiltersOrThrow: ChainMap.Chain.t => Internal.eventFilters,
63
+ // Expand a resolved topic selection into concrete topic values for a query:
64
+ // `ContractAddresses` markers become the given partition addresses encoded as
65
+ // topics; `Values` pass through.
66
+ let materializeTopicFilter = (filter: Internal.topicFilter, ~addresses: array<Address.t>) =>
67
+ switch filter {
68
+ | Values(values) => values
69
+ | ContractAddresses(_) => addresses->Array.map(TopicFilter.fromAddress)
70
+ }
71
+
72
+ let materializeTopicSelections = (
73
+ topicSelections: array<Internal.resolvedTopicSelection>,
74
+ ~addresses: array<Address.t>,
75
+ ): array<Internal.topicSelection> =>
76
+ topicSelections->Array.map(({topic0, topic1, topic2, topic3}): Internal.topicSelection => {
77
+ topic0,
78
+ topic1: topic1->materializeTopicFilter(~addresses),
79
+ topic2: topic2->materializeTopicFilter(~addresses),
80
+ topic3: topic3->materializeTopicFilter(~addresses),
81
+ })
82
+
83
+ type parsedWhere = {
84
+ resolvedWhere: Internal.resolvedWhere,
62
85
  filterByAddresses: bool,
63
86
  // Indexed params filtered by `chain.<Contract>.addresses`, in disjunctive
64
87
  // normal form (outer array OR of AND-groups). Empty unless `filterByAddresses`.
65
88
  // Consumed by the codegen of the event's `clientAddressFilter`.
66
89
  addressFilterParamGroups: array<array<string>>,
67
- // `_gte` from the top-level `block` filter of the user's `where`,
68
- // resolved at build time (per-chain via the `probeChainId`). The
69
- // caller uses this to override the per-event `startBlock` — a
70
- // `where`-derived startBlock always wins over contract-level
71
- // config, so users can widen or narrow individual event ranges
72
- // without touching `config.yaml`.
73
- startBlock: option<int>,
74
90
  }
75
91
 
76
92
  // Inner schema for the event `block` filter chunk: `{_gte?}`.
@@ -123,24 +139,12 @@ let extractStartBlock = (
123
139
  }
124
140
  }
125
141
 
126
- // Build the runtime `chain` argument passed into a `where` callback.
127
- // Exposes `chain.id` and `chain.<ContractName>.addresses` as plain values
128
- // on a normal (Object.prototype) JS object. `Dict` is used so the
129
- // contract name can be a dynamic property key without defineProperty
130
- // ceremony.
131
- let makeChainArg = (~contractName: string, ~chainId: int, ~addresses: array<Address.t>) => {
132
- let chainObj = Dict.make()
133
- chainObj->Dict.set("id", chainId->Obj.magic)
134
- chainObj->Dict.set(contractName, {"addresses": addresses}->Obj.magic)
135
- chainObj
136
- }
137
-
138
- // Build the detection-time `chain` argument. `chain.<ContractName>.addresses`
139
- // is a getter so the runtime can tell whether the callback actually reads
140
- // it; the contract sub-object itself is built via `defineProperty` only
141
- // because its `addresses` field needs the getter — the enclosing chainObj
142
- // is a plain JS object.
143
- let makeDetectionChainArg = (
142
+ // Build the `chain` argument passed into a `where` callback.
143
+ // `chain.<ContractName>.addresses` is a getter so the runtime can tell
144
+ // whether the callback actually reads it; the contract sub-object itself is
145
+ // built via `defineProperty` only because its `addresses` field needs the
146
+ // getter — the enclosing chainObj is a plain JS object.
147
+ let makeChainArg = (
144
148
  ~contractName: string,
145
149
  ~chainId: int,
146
150
  ~getAddresses: unit => array<Address.t>,
@@ -155,7 +159,7 @@ let makeDetectionChainArg = (
155
159
  chainObj
156
160
  }
157
161
 
158
- // Sentinel returned by `chain.<Contract>.addresses` during detection. A Proxy
162
+ // Sentinel returned by `chain.<Contract>.addresses`. A Proxy
159
163
  // whose traps throw on any access, so the only non-throwing use is passing it
160
164
  // straight through as a param filter value — which `extractAddressFilterGroups`
161
165
  // then finds by identity. Misuse (spread/map/index/...) fails loud at the site.
@@ -173,78 +177,46 @@ let makeAddressesProbe: (
173
177
  return new Proxy([], {get: trap});
174
178
  }`)
175
179
 
176
- // Find which indexed params the probed `where` result assigned the Proxy to
177
- // (DNF: object => one AND-group, array => OR of groups), neutralizing each match
178
- // to `[]` so later passes can't touch the throwing Proxy. Throws when the
179
- // callback read the addresses but didn't use them as a param filter value, since
180
- // the caller only invokes this once it knows the addresses were read.
181
- let extractAddressFilterGroupsOrThrow = (
182
- result: JSON.t,
183
- ~probe: array<Address.t>,
184
- ~contractName: string,
185
- ): array<array<string>> => {
186
- let groups = []
187
- let scanGroup = (paramsObj: dict<JSON.t>) => {
188
- let names = []
189
- paramsObj->Utils.Dict.forEachWithKey((value, key) => {
190
- if value === probe->(Utils.magic: array<Address.t> => JSON.t) {
191
- names->Array.push(key)->ignore
192
- paramsObj->Dict.set(key, []->(Utils.magic: array<unknown> => JSON.t))
193
- }
194
- })
195
- if names->Utils.Array.isEmpty->not {
196
- groups->Array.push(names)->ignore
197
- }
198
- }
199
- switch result {
200
- | Object(obj) =>
201
- switch obj->Dict.get("params") {
202
- | Some(Object(p)) => scanGroup(p)
203
- | Some(Array(arr)) =>
204
- arr->Array.forEach(item =>
205
- switch item {
206
- | Object(p) => scanGroup(p)
207
- | _ => ()
208
- }
209
- )
210
- | _ => ()
211
- }
212
- | _ => ()
213
- }
214
- if groups->Utils.Array.isEmpty {
215
- JsError.throwWithMessage(
216
- `Invalid where configuration for ${contractName}. The callback reads \`chain.${contractName}.addresses\` but doesn't use it as an indexed-param filter value. Use it directly, e.g. { params: { to: chain.${contractName}.addresses } }.`,
217
- )
218
- }
219
- groups
220
- }
221
-
222
- let parseEventFiltersOrThrow = {
180
+ let parseWhereOrThrow = {
223
181
  let emptyTopics = []
224
182
  let noopGetter = _ => emptyTopics
225
183
 
226
184
  (
227
- ~eventFilters: option<JSON.t>,
185
+ ~where: option<JSON.t>,
228
186
  ~sighash,
229
- ~params,
187
+ ~params: array<string>,
230
188
  ~contractName: string,
231
- ~probeChainId: int,
189
+ ~chainId: int,
232
190
  ~onEventBlockFilterSchema: S.t<option<unknown>>,
233
191
  ~topic1=noopGetter,
234
192
  ~topic2=noopGetter,
235
193
  ~topic3=noopGetter,
236
- ): parsedEventFilters => {
237
- let filterByAddresses = ref(false)
238
- let addressFilterParamGroups = ref([])
239
- let startBlock = ref(None)
194
+ ): parsedWhere => {
195
+ let addressFilterParamGroups = []
196
+ let readAddresses = ref(false)
197
+ let addressesSentinel = makeAddressesProbe(~contractName)
198
+ let sentinelJson = addressesSentinel->(Utils.magic: array<Address.t> => JSON.t)
240
199
  let topic0 = [sighash->EvmTypes.Hex.fromStringUnsafe]
241
200
  let default = {
242
201
  Internal.topic0,
243
- topic1: emptyTopics,
244
- topic2: emptyTopics,
245
- topic3: emptyTopics,
202
+ topic1: Values(emptyTopics),
203
+ topic2: Values(emptyTopics),
204
+ topic3: Values(emptyTopics),
246
205
  }
247
206
 
207
+ // Topic positions map 1:1 onto the event's indexed params in declared
208
+ // order, so the sentinel check keys off `params[index]`. The sentinel must
209
+ // be detected before the topic getter runs — the getter would otherwise
210
+ // touch the throwing Proxy while encoding.
211
+ let topicFilterAt = (paramsFilter: dict<JSON.t>, ~index, ~getter) =>
212
+ switch params
213
+ ->Array.get(index)
214
+ ->Option.flatMap(name => paramsFilter->Utils.Dict.dangerouslyGetNonOption(name)) {
215
+ | Some(value) if value === sentinelJson =>
216
+ Internal.ContractAddresses({contractName: contractName})
217
+ | _ => Values(getter(paramsFilter))
218
+ }
219
+
248
220
  // Build a single topic selection from one indexed-param record (the
249
221
  // inside of `params`). Validates that the keys are actual indexed
250
222
  // parameters of the event — TS type checking doesn't catch this when
@@ -253,18 +225,25 @@ let parseEventFiltersOrThrow = {
253
225
  if paramsFilter->Utils.Dict.isEmpty {
254
226
  default
255
227
  } else {
256
- paramsFilter->Utils.Dict.forEachWithKey((_, key) => {
228
+ let sentinelParamNames = []
229
+ paramsFilter->Utils.Dict.forEachWithKey((value, key) => {
257
230
  if params->Array.includes(key)->not {
258
231
  JsError.throwWithMessage(
259
232
  `Invalid where configuration. The event doesn't have an indexed parameter "${key}" and can't use it for filtering`,
260
233
  )
261
234
  }
235
+ if value === sentinelJson {
236
+ sentinelParamNames->Array.push(key)->ignore
237
+ }
262
238
  })
239
+ if sentinelParamNames->Utils.Array.isEmpty->not {
240
+ addressFilterParamGroups->Array.push(sentinelParamNames)->ignore
241
+ }
263
242
  {
264
243
  Internal.topic0,
265
- topic1: topic1(paramsFilter),
266
- topic2: topic2(paramsFilter),
267
- topic3: topic3(paramsFilter),
244
+ topic1: paramsFilter->topicFilterAt(~index=0, ~getter=topic1),
245
+ topic2: paramsFilter->topicFilterAt(~index=1, ~getter=topic2),
246
+ topic3: paramsFilter->topicFilterAt(~index=2, ~getter=topic3),
268
247
  }
269
248
  }
270
249
  }
@@ -289,7 +268,7 @@ let parseEventFiltersOrThrow = {
289
268
  //
290
269
  // The runtime accepts both the function form (the only form ReScript
291
270
  // exposes) and a top-level static object form (TypeScript convenience).
292
- let parse = (where: JSON.t): array<Internal.topicSelection> => {
271
+ let parse = (where: JSON.t): array<Internal.resolvedTopicSelection> => {
293
272
  if where === Obj.magic(true) {
294
273
  [default]
295
274
  } else if where === Obj.magic(false) {
@@ -335,84 +314,42 @@ let parseEventFiltersOrThrow = {
335
314
  }
336
315
  }
337
316
 
338
- let getEventFiltersOrThrow = switch eventFilters {
339
- | None => {
340
- let static: Internal.eventFilters = Static([default])
341
- _ => static
317
+ // The callback is invoked exactly once per chain, at registration time,
318
+ // with the chain's real configured id. `chain.<Contract>.addresses` yields
319
+ // the throwing-Proxy sentinel, which the param parser turns into a
320
+ // `ContractAddresses` marker; addresses are expanded from the marker only
321
+ // when a source query is built.
322
+ // A misused Proxy (or any throw from the callback) propagates as-is —
323
+ // the Proxy's guidance message surfaces without wrapping.
324
+ let (topicSelections, startBlock) = switch where {
325
+ | None => ([default], None)
326
+ | Some(where) =>
327
+ let whereValue = if typeof(where) === #function {
328
+ let fn = where->(Utils.magic: JSON.t => Internal.onEventWhereArgs<_> => JSON.t)
329
+ let chain = makeChainArg(~contractName, ~chainId, ~getAddresses=() => {
330
+ readAddresses := true
331
+ addressesSentinel
332
+ })
333
+ fn({chain: chain->Obj.magic})
334
+ } else {
335
+ where
342
336
  }
343
- | Some(eventFilters) =>
344
- if typeof(eventFilters) === #function {
345
- let fn = eventFilters->(Utils.magic: JSON.t => Internal.onEventWhereArgs<_> => JSON.t)
346
- // Determine whether the callback uses addresses by probing it with
347
- // a detection chain arg whose `chain.<ContractName>.addresses` getter
348
- // flips a flag. The probe uses this chain's real configured id, so
349
- // handlers that branch on `chain.id` are exercised along the path
350
- // they take for this chain. Event configs are built per-chain, so
351
- // each chain gets a `filterByAddresses` verdict that matches its
352
- // own callback behaviour.
353
- //
354
- // The probe result is also reused to extract the per-event
355
- // `startBlock` (from `where.block`) for this chain — a second
356
- // invocation would risk observing different state for callbacks
357
- // that close over mutable references.
358
- // A misused Proxy (or any throw from the callback) propagates as-is —
359
- // the Proxy's guidance message surfaces without wrapping.
360
- let addressesProbe = makeAddressesProbe(~contractName)
361
- let chain = makeDetectionChainArg(
362
- ~contractName,
363
- ~chainId=probeChainId,
364
- ~getAddresses=() => {
365
- filterByAddresses := true
366
- addressesProbe
367
- },
337
+ let topicSelections = whereValue->parse
338
+ if readAddresses.contents && addressFilterParamGroups->Utils.Array.isEmpty {
339
+ JsError.throwWithMessage(
340
+ `Invalid where configuration for ${contractName}. The callback reads \`chain.${contractName}.addresses\` but doesn't use it as an indexed-param filter value. Use it directly, e.g. { params: { to: chain.${contractName}.addresses } }.`,
368
341
  )
369
- let probedResult = fn({chain: chain->Obj.magic})
370
- if filterByAddresses.contents {
371
- addressFilterParamGroups :=
372
- extractAddressFilterGroupsOrThrow(probedResult, ~probe=addressesProbe, ~contractName)
373
- }
374
- startBlock := extractStartBlock(~onEventBlockFilterSchema, ~contractName, probedResult)
375
- if filterByAddresses.contents {
376
- chain => Internal.Dynamic(
377
- addresses => {
378
- let chainArg = makeChainArg(
379
- ~contractName,
380
- ~chainId=chain->ChainMap.Chain.toChainId,
381
- ~addresses,
382
- )
383
- fn({chain: chainArg->Obj.magic})->parse
384
- },
385
- )
386
- } else {
387
- // No probed chain referenced the contract — cache as Static
388
- // per chain to avoid recomputing topic selections each batch.
389
- // The addresses getter throws: if a code path the probe didn't
390
- // exercise reads `chain.<Contract>.addresses` at runtime, silent
391
- // [] would produce wrong topics — throw a user-friendly error
392
- // instead so the user rewrites the callback to surface the
393
- // dependency up-front.
394
- chain => {
395
- let chainId = chain->ChainMap.Chain.toChainId
396
- let chainArg = makeDetectionChainArg(~contractName, ~chainId, ~getAddresses=() =>
397
- JsError.throwWithMessage(
398
- `Invalid where configuration. Event callback for contract "${contractName}" read \`chain.${contractName}.addresses\` at runtime but the probe didn't detect the access on chainId ${chainId->Int.toString}. Move the \`chain.${contractName}.addresses\` read above any \`chain.id\` branching so the probe picks up the dependency and switches to the dynamic fetch path.`,
399
- )
400
- )
401
- Internal.Static(fn({chain: chainArg->Obj.magic})->parse)
402
- }
403
- }
404
- } else {
405
- startBlock := extractStartBlock(~onEventBlockFilterSchema, ~contractName, eventFilters)
406
- let static: Internal.eventFilters = Static(eventFilters->parse)
407
- _ => static
408
342
  }
343
+ (topicSelections, extractStartBlock(~onEventBlockFilterSchema, ~contractName, whereValue))
409
344
  }
410
345
 
411
346
  {
412
- getEventFiltersOrThrow,
413
- filterByAddresses: filterByAddresses.contents,
414
- addressFilterParamGroups: addressFilterParamGroups.contents,
415
- startBlock: startBlock.contents,
347
+ resolvedWhere: {
348
+ topicSelections,
349
+ startBlock,
350
+ },
351
+ filterByAddresses: addressFilterParamGroups->Utils.Array.isEmpty->not,
352
+ addressFilterParamGroups,
416
353
  }
417
354
  }
418
355
  }