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.
- package/evm.schema.json +10 -0
- package/index.d.ts +45 -25
- package/package.json +7 -7
- package/src/Address.res +5 -2
- package/src/Address.res.mjs +3 -1
- package/src/Api.res +1 -1
- package/src/Api.res.mjs +1 -1
- package/src/Batch.res +0 -6
- package/src/Batch.res.mjs +1 -12
- package/src/BatchProcessing.res +7 -12
- package/src/BatchProcessing.res.mjs +8 -7
- package/src/Bin.res +3 -0
- package/src/Bin.res.mjs +4 -0
- package/src/ChainFetching.res +43 -9
- package/src/ChainFetching.res.mjs +34 -15
- package/src/ChainMetadata.res +1 -11
- package/src/ChainMetadata.res.mjs +1 -10
- package/src/ChainState.res +605 -151
- package/src/ChainState.res.mjs +427 -104
- package/src/ChainState.resi +72 -4
- package/src/Config.res +61 -33
- package/src/Config.res.mjs +50 -10
- package/src/ContractRegisterContext.res +2 -12
- package/src/ContractRegisterContext.res.mjs +3 -5
- package/src/Core.res +14 -3
- package/src/CrossChainState.res +113 -89
- package/src/CrossChainState.res.mjs +64 -60
- package/src/CrossChainState.resi +1 -1
- package/src/Ecosystem.res +5 -6
- package/src/Ecosystem.res.mjs +3 -3
- package/src/Envio.res +17 -11
- package/src/EnvioGlobal.res +53 -0
- package/src/EnvioGlobal.res.mjs +31 -0
- package/src/EventConfigBuilder.res +177 -88
- package/src/EventConfigBuilder.res.mjs +99 -42
- package/src/EventProcessing.res +74 -28
- package/src/EventProcessing.res.mjs +55 -29
- package/src/ExitOnCaughtUp.res +10 -2
- package/src/ExitOnCaughtUp.res.mjs +10 -1
- package/src/FetchState.res +544 -356
- package/src/FetchState.res.mjs +412 -471
- package/src/HandlerLoader.res +8 -104
- package/src/HandlerLoader.res.mjs +2 -81
- package/src/HandlerRegister.res +518 -144
- package/src/HandlerRegister.res.mjs +285 -133
- package/src/HandlerRegister.resi +24 -8
- package/src/IndexerState.res +10 -3
- package/src/IndexerState.res.mjs +11 -4
- package/src/IndexerState.resi +2 -1
- package/src/IndexingAddresses.res +108 -0
- package/src/IndexingAddresses.res.mjs +101 -0
- package/src/IndexingAddresses.resi +34 -0
- package/src/Internal.res +155 -46
- package/src/Internal.res.mjs +30 -2
- package/src/LoadLayer.res +5 -5
- package/src/LoadLayer.res.mjs +6 -6
- package/src/LogSelection.res +102 -165
- package/src/LogSelection.res.mjs +101 -116
- package/src/Main.res +71 -236
- package/src/Main.res.mjs +60 -145
- package/src/Metrics.res +74 -0
- package/src/Metrics.res.mjs +75 -0
- package/src/PgStorage.res +4 -4
- package/src/PgStorage.res.mjs +5 -5
- package/src/Prometheus.res +10 -63
- package/src/Prometheus.res.mjs +124 -171
- package/src/PruneStaleHistory.res +2 -2
- package/src/PruneStaleHistory.res.mjs +3 -3
- package/src/RawEvent.res +7 -2
- package/src/RawEvent.res.mjs +4 -4
- package/src/Rollback.res +3 -3
- package/src/Rollback.res.mjs +4 -4
- package/src/RollbackCommit.res +4 -1
- package/src/RollbackCommit.res.mjs +3 -2
- package/src/SimulateDeadInputTracker.res +85 -0
- package/src/SimulateDeadInputTracker.res.mjs +73 -0
- package/src/SimulateDeadInputTracker.resi +12 -0
- package/src/SimulateItems.res +91 -23
- package/src/SimulateItems.res.mjs +55 -32
- package/src/TestIndexer.res +54 -40
- package/src/TestIndexer.res.mjs +37 -30
- package/src/bindings/Performance.res +7 -0
- package/src/bindings/Performance.res.mjs +21 -0
- package/src/bindings/Performance.resi +7 -0
- package/src/bindings/Viem.res +0 -41
- package/src/bindings/Viem.res.mjs +1 -43
- package/src/sources/BlockStore.res +46 -0
- package/src/sources/BlockStore.res.mjs +24 -0
- package/src/sources/EventRouter.res +36 -33
- package/src/sources/EventRouter.res.mjs +13 -14
- package/src/sources/Evm.res +83 -72
- package/src/sources/Evm.res.mjs +53 -69
- package/src/sources/EvmChain.res +18 -20
- package/src/sources/EvmChain.res.mjs +15 -15
- package/src/sources/EvmRpcClient.res +74 -5
- package/src/sources/EvmRpcClient.res.mjs +13 -4
- package/src/sources/FieldMask.res +39 -0
- package/src/sources/FieldMask.res.mjs +42 -0
- package/src/sources/Fuel.res +9 -6
- package/src/sources/Fuel.res.mjs +5 -10
- package/src/sources/HyperFuelSource.res +46 -50
- package/src/sources/HyperFuelSource.res.mjs +64 -54
- package/src/sources/HyperSync.res +39 -7
- package/src/sources/HyperSync.res.mjs +57 -37
- package/src/sources/HyperSync.resi +12 -2
- package/src/sources/HyperSyncClient.res +22 -111
- package/src/sources/HyperSyncClient.res.mjs +2 -30
- package/src/sources/HyperSyncHeightStream.res +1 -8
- package/src/sources/HyperSyncHeightStream.res.mjs +0 -2
- package/src/sources/HyperSyncSource.res +94 -107
- package/src/sources/HyperSyncSource.res.mjs +82 -86
- package/src/sources/Rpc.res +15 -47
- package/src/sources/Rpc.res.mjs +25 -56
- package/src/sources/RpcSource.res +320 -467
- package/src/sources/RpcSource.res.mjs +268 -385
- package/src/sources/RpcWebSocketHeightStream.res +0 -5
- package/src/sources/RpcWebSocketHeightStream.res.mjs +0 -2
- package/src/sources/SimulateSource.res +10 -4
- package/src/sources/SimulateSource.res.mjs +16 -6
- package/src/sources/Source.res +34 -6
- package/src/sources/SourceManager.res +77 -19
- package/src/sources/SourceManager.res.mjs +63 -21
- package/src/sources/SourceManager.resi +10 -0
- package/src/sources/Svm.res +31 -16
- package/src/sources/Svm.res.mjs +36 -13
- package/src/sources/SvmHyperSyncClient.res +5 -32
- package/src/sources/SvmHyperSyncSource.res +159 -134
- package/src/sources/SvmHyperSyncSource.res.mjs +164 -129
- package/src/sources/TransactionStore.res +49 -0
- package/src/sources/TransactionStore.res.mjs +30 -0
- package/src/tui/Tui.res +13 -16
- package/src/tui/Tui.res.mjs +12 -14
- package/svm.schema.json +49 -37
- package/src/bindings/Hrtime.res +0 -58
- package/src/bindings/Hrtime.res.mjs +0 -90
- package/src/bindings/Hrtime.resi +0 -30
package/src/ChainState.res
CHANGED
|
@@ -5,18 +5,56 @@
|
|
|
5
5
|
type t = {
|
|
6
6
|
logger: Pino.t,
|
|
7
7
|
mutable fetchState: FetchState.t,
|
|
8
|
+
// The chain-wide address index. Not `mutable`: the dict is mutated in place by
|
|
9
|
+
// register/rollback, so the reference is stable across fetchState versions.
|
|
10
|
+
indexingAddresses: IndexingAddresses.t,
|
|
8
11
|
sourceManager: SourceManager.t,
|
|
9
12
|
chainConfig: Config.chain,
|
|
10
13
|
mutable isProgressAtHead: bool,
|
|
11
14
|
mutable timestampCaughtUpToHeadOrEndblock: option<Date.t>,
|
|
12
15
|
mutable committedProgressBlockNumber: int,
|
|
16
|
+
// Progress of the batch currently being processed. The buffer is consumed at
|
|
17
|
+
// batch creation (see advanceAfterBatch), so this runs ahead of
|
|
18
|
+
// committedProgressBlockNumber until the batch commits — it's the true lower
|
|
19
|
+
// boundary of the remaining buffer's block span.
|
|
20
|
+
mutable processingBlockNumber: int,
|
|
13
21
|
mutable numEventsProcessed: float,
|
|
14
|
-
// Running sum of in-flight queries'
|
|
22
|
+
// Running sum of in-flight queries' itemsEst, kept here so the
|
|
15
23
|
// scheduler doesn't re-sum pending queries on every tick. Incremented when
|
|
16
24
|
// queries are dispatched, decremented as their responses land.
|
|
17
25
|
mutable pendingBudget: float,
|
|
26
|
+
// Chain-wide events/block, used to turn a chain's item budget into a target
|
|
27
|
+
// block for query sizing. Seeded from cumulative progress on construction,
|
|
28
|
+
// then smoothed with an EMA on every batch (see applyBatchProgress). None
|
|
29
|
+
// until the chain has processed at least one event.
|
|
30
|
+
mutable chainDensity: option<float>,
|
|
18
31
|
mutable reorgDetection: ReorgDetection.t,
|
|
19
32
|
mutable safeCheckpointTracking: option<SafeCheckpointTracking.t>,
|
|
33
|
+
// Holds this chain's transactions (kept in Rust) keyed by (blockNumber,
|
|
34
|
+
// transactionIndex). Fetch responses merge their page in; entries are pruned
|
|
35
|
+
// as the chain progresses and dropped above the target on rollback.
|
|
36
|
+
transactionStore: TransactionStore.t,
|
|
37
|
+
// Holds this chain's blocks (kept in Rust) keyed by block number. Same merge /
|
|
38
|
+
// prune / rollback lifecycle as the transaction store.
|
|
39
|
+
blockStore: BlockStore.t,
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Per-chain shape returned by the status API.
|
|
43
|
+
type chainData = {
|
|
44
|
+
chainId: float,
|
|
45
|
+
poweredByHyperSync: bool,
|
|
46
|
+
firstEventBlockNumber: option<int>,
|
|
47
|
+
latestProcessedBlock: option<int>,
|
|
48
|
+
timestampCaughtUpToHeadOrEndblock: option<Date.t>,
|
|
49
|
+
numEventsProcessed: float,
|
|
50
|
+
latestFetchedBlockNumber: int,
|
|
51
|
+
// Need this for API backwards compatibility
|
|
52
|
+
@as("currentBlockHeight")
|
|
53
|
+
knownHeight: int,
|
|
54
|
+
numBatchesFetched: int,
|
|
55
|
+
startBlock: int,
|
|
56
|
+
endBlock: option<int>,
|
|
57
|
+
numAddresses: int,
|
|
20
58
|
}
|
|
21
59
|
|
|
22
60
|
let configAddresses = (chainConfig: Config.chain): array<Internal.indexingAddress> => {
|
|
@@ -36,6 +74,7 @@ let configAddresses = (chainConfig: Config.chain): array<Internal.indexingAddres
|
|
|
36
74
|
let make = (
|
|
37
75
|
~chainConfig: Config.chain,
|
|
38
76
|
~fetchState: FetchState.t,
|
|
77
|
+
~indexingAddresses: IndexingAddresses.t,
|
|
39
78
|
~sourceManager: SourceManager.t,
|
|
40
79
|
~reorgDetection: ReorgDetection.t,
|
|
41
80
|
~committedProgressBlockNumber: int,
|
|
@@ -43,19 +82,27 @@ let make = (
|
|
|
43
82
|
~numEventsProcessed=0.,
|
|
44
83
|
~timestampCaughtUpToHeadOrEndblock=None,
|
|
45
84
|
~isProgressAtHead=false,
|
|
85
|
+
~transactionStore=TransactionStore.make(~ecosystem=Ecosystem.Evm, ~shouldChecksum=false),
|
|
86
|
+
~chainDensity=None,
|
|
87
|
+
~blockStore=BlockStore.make(~ecosystem=Ecosystem.Evm, ~shouldChecksum=false),
|
|
46
88
|
~logger: Pino.t,
|
|
47
89
|
): t => {
|
|
48
90
|
logger,
|
|
49
91
|
fetchState,
|
|
92
|
+
indexingAddresses,
|
|
50
93
|
sourceManager,
|
|
51
94
|
chainConfig,
|
|
52
95
|
isProgressAtHead,
|
|
53
96
|
timestampCaughtUpToHeadOrEndblock,
|
|
54
97
|
committedProgressBlockNumber,
|
|
98
|
+
processingBlockNumber: committedProgressBlockNumber,
|
|
55
99
|
numEventsProcessed,
|
|
56
100
|
pendingBudget: 0.,
|
|
101
|
+
chainDensity,
|
|
57
102
|
reorgDetection,
|
|
58
103
|
safeCheckpointTracking,
|
|
104
|
+
transactionStore,
|
|
105
|
+
blockStore,
|
|
59
106
|
}
|
|
60
107
|
|
|
61
108
|
let makeInternal = (
|
|
@@ -66,7 +113,7 @@ let makeInternal = (
|
|
|
66
113
|
~firstEventBlock=None,
|
|
67
114
|
~progressBlockNumber,
|
|
68
115
|
~config: Config.t,
|
|
69
|
-
~
|
|
116
|
+
~registrationsByChainId: HandlerRegister.registrationsByChainId,
|
|
70
117
|
~logger,
|
|
71
118
|
~timestampCaughtUpToHeadOrEndblock,
|
|
72
119
|
~numEventsProcessed,
|
|
@@ -77,129 +124,35 @@ let makeInternal = (
|
|
|
77
124
|
~knownHeight=0,
|
|
78
125
|
~reducedPollingInterval=?,
|
|
79
126
|
): t => {
|
|
80
|
-
//
|
|
81
|
-
//
|
|
82
|
-
//
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
let eventConfigs: array<Internal.eventConfig> = []
|
|
88
|
-
|
|
89
|
-
let notRegisteredEvents = []
|
|
127
|
+
// Handler binding + `where`-derived fetch state, and onBlock registrations,
|
|
128
|
+
// are already collected by `HandlerRegister.finishRegistration`, keyed by
|
|
129
|
+
// chain - this just looks up this chain's slice.
|
|
130
|
+
let {onEventRegistrations, onBlockRegistrations} =
|
|
131
|
+
registrationsByChainId
|
|
132
|
+
->Utils.Dict.dangerouslyGetNonOption(chainConfig.id->Int.toString)
|
|
133
|
+
->Option.getOr({onEventRegistrations: [], onBlockRegistrations: []})
|
|
90
134
|
|
|
91
135
|
chainConfig.contracts->Array.forEach(contract => {
|
|
92
|
-
let contractName = contract.name
|
|
93
|
-
|
|
94
|
-
contract.events->Array.forEach(eventConfig => {
|
|
95
|
-
let {isWildcard} = eventConfig
|
|
96
|
-
let hasContractRegister = eventConfig.contractRegister->Option.isSome
|
|
97
|
-
|
|
98
|
-
// Should validate the events
|
|
99
|
-
eventRouter->EventRouter.addOrThrow(
|
|
100
|
-
eventConfig.id,
|
|
101
|
-
(),
|
|
102
|
-
~contractName,
|
|
103
|
-
~chain=ChainMap.Chain.makeUnsafe(~chainId=chainConfig.id),
|
|
104
|
-
~eventName=eventConfig.name,
|
|
105
|
-
~isWildcard,
|
|
106
|
-
)
|
|
107
|
-
|
|
108
|
-
// Filter out non-preRegistration events on preRegistration phase
|
|
109
|
-
// so we don't care about it in fetch state and workers anymore
|
|
110
|
-
let shouldBeIncluded = if config.enableRawEvents {
|
|
111
|
-
true
|
|
112
|
-
} else {
|
|
113
|
-
let isRegistered = hasContractRegister || eventConfig.handler->Option.isSome
|
|
114
|
-
if !isRegistered {
|
|
115
|
-
notRegisteredEvents->Array.push(eventConfig)
|
|
116
|
-
}
|
|
117
|
-
isRegistered
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
// Check if event has Static([]) filters (from a dynamic where
|
|
121
|
-
// callback returning `false` / SkipAll for this chain).
|
|
122
|
-
// If so, skip it entirely - it should never be fetched
|
|
123
|
-
let shouldSkip = try {
|
|
124
|
-
let getEventFiltersOrThrow = (
|
|
125
|
-
eventConfig->(Utils.magic: Internal.eventConfig => Internal.evmEventConfig)
|
|
126
|
-
).getEventFiltersOrThrow
|
|
127
|
-
|
|
128
|
-
// Check for non-evm chains
|
|
129
|
-
if (
|
|
130
|
-
getEventFiltersOrThrow->(Utils.magic: (ChainMap.Chain.t => Internal.eventFilters) => bool)
|
|
131
|
-
) {
|
|
132
|
-
switch getEventFiltersOrThrow(ChainMap.Chain.makeUnsafe(~chainId=chainConfig.id)) {
|
|
133
|
-
| Static([]) => true
|
|
134
|
-
| _ => false
|
|
135
|
-
}
|
|
136
|
-
} else {
|
|
137
|
-
false
|
|
138
|
-
}
|
|
139
|
-
} catch {
|
|
140
|
-
// Can throw when filter is invalid
|
|
141
|
-
// Don't skip an event in this case. Let it throw in a better place - source code
|
|
142
|
-
| _ => false
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
if shouldBeIncluded && !shouldSkip {
|
|
146
|
-
eventConfigs->Array.push(eventConfig)
|
|
147
|
-
}
|
|
148
|
-
})
|
|
149
|
-
|
|
150
136
|
switch contract.startBlock {
|
|
151
137
|
| Some(startBlock) if startBlock < chainConfig.startBlock =>
|
|
152
138
|
JsError.throwWithMessage(
|
|
153
|
-
`The start block for contract "${
|
|
139
|
+
`The start block for contract "${contract.name}" is less than the chain start block. This is not supported yet.`,
|
|
154
140
|
)
|
|
155
141
|
| _ => ()
|
|
156
142
|
}
|
|
157
143
|
})
|
|
158
144
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
`The event${if notRegisteredEvents->Array.length > 1 {
|
|
162
|
-
"s"
|
|
163
|
-
} else {
|
|
164
|
-
""
|
|
165
|
-
}} ${notRegisteredEvents
|
|
166
|
-
->Array.map(eventConfig => `${eventConfig.contractName}.${eventConfig.name}`)
|
|
167
|
-
->Array.joinUnsafe(", ")} don't have an event handler and skipped for indexing.`,
|
|
168
|
-
)
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
let onBlockConfigs =
|
|
172
|
-
registrations.onBlockByChainId->Utils.Dict.dangerouslyGetNonOption(chainConfig.id->Int.toString)
|
|
173
|
-
switch onBlockConfigs {
|
|
174
|
-
| Some(onBlockConfigs) =>
|
|
175
|
-
// TODO: Move it to the HandlerRegister module
|
|
176
|
-
// so the error is thrown with better stack trace
|
|
177
|
-
onBlockConfigs->Array.forEach(onBlockConfig => {
|
|
178
|
-
if onBlockConfig.startBlock->Option.getOr(startBlock) < startBlock {
|
|
179
|
-
JsError.throwWithMessage(
|
|
180
|
-
`The start block for onBlock handler "${onBlockConfig.name}" is less than the chain start block (${startBlock->Int.toString}). This is not supported yet.`,
|
|
181
|
-
)
|
|
182
|
-
}
|
|
183
|
-
switch endBlock {
|
|
184
|
-
| Some(chainEndBlock) =>
|
|
185
|
-
if onBlockConfig.endBlock->Option.getOr(chainEndBlock) > chainEndBlock {
|
|
186
|
-
JsError.throwWithMessage(
|
|
187
|
-
`The end block for onBlock handler "${onBlockConfig.name}" is greater than the chain end block (${chainEndBlock->Int.toString}). This is not supported yet.`,
|
|
188
|
-
)
|
|
189
|
-
}
|
|
190
|
-
| None => ()
|
|
191
|
-
}
|
|
192
|
-
})
|
|
193
|
-
| None => ()
|
|
194
|
-
}
|
|
145
|
+
let contractConfigs = IndexingAddresses.makeContractConfigs(~onEventRegistrations)
|
|
146
|
+
let indexingAddressIndex = IndexingAddresses.make(~contractConfigs, ~addresses=indexingAddresses)
|
|
195
147
|
|
|
196
148
|
let fetchState = FetchState.make(
|
|
197
149
|
~maxAddrInPartition=config.maxAddrInPartition,
|
|
150
|
+
~contractConfigs,
|
|
198
151
|
~addresses=indexingAddresses,
|
|
199
152
|
~progressBlockNumber,
|
|
200
153
|
~startBlock,
|
|
201
154
|
~endBlock,
|
|
202
|
-
~
|
|
155
|
+
~onEventRegistrations,
|
|
203
156
|
~maxOnBlockBufferSize=2 * config.batchSize,
|
|
204
157
|
~knownHeight,
|
|
205
158
|
~chainId=chainConfig.id,
|
|
@@ -208,7 +161,7 @@ let makeInternal = (
|
|
|
208
161
|
!config.shouldRollbackOnReorg || isInReorgThreshold ? 0 : chainConfig.maxReorgDepth,
|
|
209
162
|
chainConfig.blockLag,
|
|
210
163
|
),
|
|
211
|
-
~
|
|
164
|
+
~onBlockRegistrations,
|
|
212
165
|
~firstEventBlock,
|
|
213
166
|
)
|
|
214
167
|
|
|
@@ -225,29 +178,23 @@ let makeInternal = (
|
|
|
225
178
|
let lowercaseAddresses = config.lowercaseAddresses
|
|
226
179
|
let sources = switch chainConfig.sourceConfig {
|
|
227
180
|
| Config.EvmSourceConfig({hypersync, rpcs}) =>
|
|
228
|
-
// Build Internal.evmContractConfig from contracts for EvmChain.makeSources
|
|
229
|
-
let evmContracts: array<Internal.evmContractConfig> = chainConfig.contracts->Array.map((
|
|
230
|
-
contract
|
|
231
|
-
): Internal.evmContractConfig => {
|
|
232
|
-
name: contract.name,
|
|
233
|
-
abi: contract.abi,
|
|
234
|
-
events: contract.events->(
|
|
235
|
-
Utils.magic: array<Internal.eventConfig> => array<Internal.evmEventConfig>
|
|
236
|
-
),
|
|
237
|
-
})
|
|
238
181
|
let evmRpcs: array<EvmChain.rpc> = rpcs->Array.map((rpc): EvmChain.rpc => {
|
|
239
182
|
let syncConfig = rpc.syncConfig
|
|
240
183
|
let ws = rpc.ws
|
|
184
|
+
let headers = rpc.headers
|
|
241
185
|
{
|
|
242
186
|
url: rpc.url,
|
|
243
187
|
sourceFor: rpc.sourceFor,
|
|
244
188
|
?syncConfig,
|
|
245
189
|
?ws,
|
|
190
|
+
?headers,
|
|
246
191
|
}
|
|
247
192
|
})
|
|
248
193
|
EvmChain.makeSources(
|
|
249
194
|
~chain,
|
|
250
|
-
~
|
|
195
|
+
~onEventRegistrations=onEventRegistrations->(
|
|
196
|
+
Utils.magic: array<Internal.onEventRegistration> => array<Internal.evmOnEventRegistration>
|
|
197
|
+
),
|
|
251
198
|
~hyperSync=hypersync,
|
|
252
199
|
~rpcs=evmRpcs,
|
|
253
200
|
~lowercaseAddresses,
|
|
@@ -265,17 +212,13 @@ let makeInternal = (
|
|
|
265
212
|
| (Some(hypersyncUrl), _) =>
|
|
266
213
|
// HyperSync drives instruction sync. A configured RPC is ignored for now
|
|
267
214
|
// (RPC fallback isn't wired up yet).
|
|
268
|
-
let svmEventConfigs =
|
|
269
|
-
chainConfig.contracts
|
|
270
|
-
->Array.flatMap(contract => contract.events)
|
|
271
|
-
->(Utils.magic: array<Internal.eventConfig> => array<Internal.svmInstructionEventConfig>)
|
|
272
215
|
let apiToken = Env.envioApiToken
|
|
273
216
|
[
|
|
274
217
|
SvmHyperSyncSource.make({
|
|
275
218
|
chain,
|
|
276
219
|
endpointUrl: hypersyncUrl,
|
|
277
220
|
apiToken,
|
|
278
|
-
|
|
221
|
+
onEventRegistrations,
|
|
279
222
|
clientTimeoutMillis: Env.hyperSyncClientTimeoutMillis,
|
|
280
223
|
}),
|
|
281
224
|
]
|
|
@@ -284,9 +227,18 @@ let makeInternal = (
|
|
|
284
227
|
| Config.CustomSources(sources) => sources
|
|
285
228
|
}
|
|
286
229
|
|
|
230
|
+
// Seed chain density from whatever progress this chain already has (from a
|
|
231
|
+
// resumed DB state, or 0 on a fresh chain) — refined per-batch afterwards.
|
|
232
|
+
let chainDensity = switch fetchState.firstEventBlock {
|
|
233
|
+
| Some(firstEventBlock) if progressBlockNumber > firstEventBlock && numEventsProcessed > 0. =>
|
|
234
|
+
Some(numEventsProcessed /. (progressBlockNumber - firstEventBlock)->Int.toFloat)
|
|
235
|
+
| _ => None
|
|
236
|
+
}
|
|
237
|
+
|
|
287
238
|
make(
|
|
288
239
|
~chainConfig,
|
|
289
240
|
~fetchState,
|
|
241
|
+
~indexingAddresses=indexingAddressIndex,
|
|
290
242
|
~sourceManager=SourceManager.make(~sources, ~isRealtime, ~reducedPollingInterval?),
|
|
291
243
|
~reorgDetection=ReorgDetection.make(
|
|
292
244
|
~chainReorgCheckpoints,
|
|
@@ -301,17 +253,31 @@ let makeInternal = (
|
|
|
301
253
|
~committedProgressBlockNumber=progressBlockNumber,
|
|
302
254
|
~timestampCaughtUpToHeadOrEndblock,
|
|
303
255
|
~numEventsProcessed,
|
|
256
|
+
~transactionStore=TransactionStore.make(
|
|
257
|
+
~ecosystem=config.ecosystem.name,
|
|
258
|
+
~shouldChecksum=!lowercaseAddresses,
|
|
259
|
+
),
|
|
260
|
+
~chainDensity,
|
|
261
|
+
~blockStore=BlockStore.make(
|
|
262
|
+
~ecosystem=config.ecosystem.name,
|
|
263
|
+
~shouldChecksum=!lowercaseAddresses,
|
|
264
|
+
),
|
|
304
265
|
~logger,
|
|
305
266
|
)
|
|
306
267
|
}
|
|
307
268
|
|
|
308
|
-
let makeFromConfig = (
|
|
269
|
+
let makeFromConfig = (
|
|
270
|
+
chainConfig: Config.chain,
|
|
271
|
+
~config,
|
|
272
|
+
~registrationsByChainId,
|
|
273
|
+
~knownHeight,
|
|
274
|
+
) => {
|
|
309
275
|
let logger = Logging.createChild(~params={"chainId": chainConfig.id})
|
|
310
276
|
|
|
311
277
|
makeInternal(
|
|
312
278
|
~chainConfig,
|
|
313
279
|
~config,
|
|
314
|
-
~
|
|
280
|
+
~registrationsByChainId,
|
|
315
281
|
~startBlock=chainConfig.startBlock,
|
|
316
282
|
~endBlock=chainConfig.endBlock,
|
|
317
283
|
~reorgCheckpoints=[],
|
|
@@ -337,7 +303,7 @@ let makeFromDbState = (
|
|
|
337
303
|
~isInReorgThreshold,
|
|
338
304
|
~isRealtime,
|
|
339
305
|
~config,
|
|
340
|
-
~
|
|
306
|
+
~registrationsByChainId,
|
|
341
307
|
~reducedPollingInterval=?,
|
|
342
308
|
) => {
|
|
343
309
|
let chainId = chainConfig.id
|
|
@@ -357,7 +323,7 @@ let makeFromDbState = (
|
|
|
357
323
|
~startBlock=resumedChainState.startBlock,
|
|
358
324
|
~endBlock=resumedChainState.endBlock,
|
|
359
325
|
~config,
|
|
360
|
-
~
|
|
326
|
+
~registrationsByChainId,
|
|
361
327
|
~reorgCheckpoints,
|
|
362
328
|
~maxReorgDepth=resumedChainState.maxReorgDepth,
|
|
363
329
|
~firstEventBlock=resumedChainState.firstEventBlockNumber,
|
|
@@ -377,7 +343,6 @@ let makeFromDbState = (
|
|
|
377
343
|
// --- Read accessors. ---
|
|
378
344
|
|
|
379
345
|
let logger = (cs: t) => cs.logger
|
|
380
|
-
let fetchState = (cs: t) => cs.fetchState
|
|
381
346
|
let sourceManager = (cs: t) => cs.sourceManager
|
|
382
347
|
let chainConfig = (cs: t) => cs.chainConfig
|
|
383
348
|
let reorgDetection = (cs: t) => cs.reorgDetection
|
|
@@ -388,13 +353,26 @@ let numEventsProcessed = (cs: t) => cs.numEventsProcessed
|
|
|
388
353
|
let pendingBudget = (cs: t) => cs.pendingBudget
|
|
389
354
|
let timestampCaughtUpToHeadOrEndblock = (cs: t) => cs.timestampCaughtUpToHeadOrEndblock
|
|
390
355
|
|
|
356
|
+
// Fetch-frontier reads. The FetchState is owned here; callers go through these
|
|
357
|
+
// rather than reaching into it.
|
|
358
|
+
let knownHeight = (cs: t) => cs.fetchState.knownHeight
|
|
359
|
+
let contractAddresses = (cs: t, ~contractName) =>
|
|
360
|
+
cs.indexingAddresses->IndexingAddresses.getContractAddresses(~contractName)
|
|
361
|
+
let bufferSize = (cs: t) => cs.fetchState->FetchState.bufferSize
|
|
362
|
+
let bufferReadyCount = (cs: t) => cs.fetchState->FetchState.bufferReadyCount
|
|
363
|
+
let getProgressPercentage = (cs: t) => cs.fetchState->FetchState.getProgressPercentage
|
|
364
|
+
let chainDensity = (cs: t) => cs.chainDensity
|
|
365
|
+
let hasReadyItem = (cs: t) =>
|
|
366
|
+
cs.fetchState->FetchState.isActivelyIndexing && cs.fetchState->FetchState.hasReadyItem
|
|
367
|
+
let isReadyToEnterReorgThreshold = (cs: t) => cs.fetchState->FetchState.isReadyToEnterReorgThreshold
|
|
368
|
+
|
|
391
369
|
// Mark queries as in flight and reserve their estimated size against the shared
|
|
392
370
|
// buffer budget in one step, so the counter stays in sync with the pending
|
|
393
371
|
// queries it tracks.
|
|
394
372
|
let startFetchingQueries = (cs: t, ~queries: array<FetchState.query>) => {
|
|
395
373
|
cs.fetchState->FetchState.startFetchingQueries(~queries)
|
|
396
374
|
cs.pendingBudget =
|
|
397
|
-
cs.pendingBudget +. queries->Array.reduce(0., (acc, query) => acc +. query.
|
|
375
|
+
cs.pendingBudget +. queries->Array.reduce(0., (acc, query) => acc +. query.itemsEst->Int.toFloat)
|
|
398
376
|
}
|
|
399
377
|
|
|
400
378
|
// Drop every in-flight query and release their reservations together, keeping
|
|
@@ -404,6 +382,161 @@ let resetPendingQueries = (cs: t) => {
|
|
|
404
382
|
cs.pendingBudget = 0.
|
|
405
383
|
}
|
|
406
384
|
|
|
385
|
+
let isReady = (cs: t) => cs.timestampCaughtUpToHeadOrEndblock !== None
|
|
386
|
+
|
|
387
|
+
// Block span over which a batch fully replaces the chain density estimate;
|
|
388
|
+
// smaller batches blend in proportionally, so a few sparse/dense blocks only
|
|
389
|
+
// nudge it.
|
|
390
|
+
let densityBlendWindow = 100.
|
|
391
|
+
|
|
392
|
+
// The last block this chain can fetch right now: the head, or endBlock when
|
|
393
|
+
// it's below the head.
|
|
394
|
+
let fetchCeiling = (cs: t) => {
|
|
395
|
+
let fetchState = cs.fetchState
|
|
396
|
+
switch fetchState.endBlock {
|
|
397
|
+
| Some(endBlock) => Pervasives.min(endBlock, fetchState.knownHeight)
|
|
398
|
+
| None => fetchState.knownHeight
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// Events/block over the ready part of the buffer — a live signal that reacts
|
|
403
|
+
// to what fetching just found, unlike the processing EMA which only moves as
|
|
404
|
+
// batches commit.
|
|
405
|
+
let readyBufferDensity = (cs: t) => {
|
|
406
|
+
let readyCount = cs.fetchState->FetchState.bufferReadyCount
|
|
407
|
+
let span = cs.fetchState->FetchState.bufferBlockNumber - cs.processingBlockNumber
|
|
408
|
+
if readyCount > 0 && span > 0 {
|
|
409
|
+
Some(readyCount->Int.toFloat /. span->Int.toFloat)
|
|
410
|
+
} else {
|
|
411
|
+
None
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// Density used for query sizing: the higher of the processing EMA and the
|
|
416
|
+
// ready-buffer density, so a stale-low EMA can't undersize queries while the
|
|
417
|
+
// buffer proves the range is dense. None means the chain is cold — no density
|
|
418
|
+
// signal at all.
|
|
419
|
+
let effectiveDensity = (cs: t) =>
|
|
420
|
+
switch (cs.chainDensity, cs->readyBufferDensity) {
|
|
421
|
+
| (Some(ema), Some(buffer)) => Some(Pervasives.max(ema, buffer))
|
|
422
|
+
| (Some(_) as density, None) | (None, Some(_) as density) => density
|
|
423
|
+
| (None, None) => None
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// How far past the frontier a chain with no density signal targets while it
|
|
427
|
+
// takes its first measurements.
|
|
428
|
+
let coldTargetRange = 20_000
|
|
429
|
+
|
|
430
|
+
// This chain's share of the indexer-wide buffer budget turned into a soft
|
|
431
|
+
// target block: via density, or frontier + coldTargetRange when there's no
|
|
432
|
+
// density signal yet.
|
|
433
|
+
let targetBlock = (cs: t, ~chainTargetItems: float) => {
|
|
434
|
+
let fetchState = cs.fetchState
|
|
435
|
+
let fetchCeiling = cs->fetchCeiling
|
|
436
|
+
let bufferBlockNumber = fetchState->FetchState.bufferBlockNumber
|
|
437
|
+
switch cs->effectiveDensity {
|
|
438
|
+
| Some(density) if density > 0. =>
|
|
439
|
+
Pervasives.min(
|
|
440
|
+
fetchCeiling,
|
|
441
|
+
bufferBlockNumber + Math.ceil(chainTargetItems /. density)->Float.toInt,
|
|
442
|
+
)
|
|
443
|
+
| _ => Pervasives.min(bufferBlockNumber + coldTargetRange, fetchCeiling)
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// Block range that cross-chain progress alignment maps fractions over: from
|
|
448
|
+
// the first block that can hold this chain's events to the last block it will
|
|
449
|
+
// fetch.
|
|
450
|
+
let progressRange = (cs: t) => {
|
|
451
|
+
let fetchState = cs.fetchState
|
|
452
|
+
let lower = fetchState.firstEventBlock->Option.getOr(fetchState.startBlock)
|
|
453
|
+
let upper = switch fetchState.endBlock {
|
|
454
|
+
| Some(endBlock) => endBlock
|
|
455
|
+
| None => fetchState.knownHeight
|
|
456
|
+
}
|
|
457
|
+
(lower, upper)
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// A degenerate range (chain already at or past its last block) maps to 1 so it
|
|
461
|
+
// never constrains the other chains. Clamped at 0 for the initial -1 fetch
|
|
462
|
+
// frontier — the only possible blockNumber below the range's lower bound.
|
|
463
|
+
let progressAtBlock = (cs: t, ~blockNumber) => {
|
|
464
|
+
let (lower, upper) = cs->progressRange
|
|
465
|
+
upper <= lower
|
|
466
|
+
? 1.
|
|
467
|
+
: Pervasives.max(
|
|
468
|
+
0.,
|
|
469
|
+
Pervasives.min(1., (blockNumber - lower)->Int.toFloat /. (upper - lower)->Int.toFloat),
|
|
470
|
+
)
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
let blockAtProgress = (cs: t, ~progress) => {
|
|
474
|
+
let (lower, upper) = cs->progressRange
|
|
475
|
+
lower + Math.ceil(progress *. (upper - lower)->Int.toFloat)->Float.toInt
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
// Propose queries sized against this chain's target block. Called by
|
|
479
|
+
// CrossChainState's waterfall, furthest-behind chain first, with
|
|
480
|
+
// chainTargetItems set to whatever budget remains at that point and
|
|
481
|
+
// maxTargetBlock set to the most-behind chain's progress mapped onto this
|
|
482
|
+
// chain, so a chain with budget can't run further ahead than the chain the
|
|
483
|
+
// whole pool is prioritizing.
|
|
484
|
+
let getNextQuery = (
|
|
485
|
+
cs: t,
|
|
486
|
+
~chainTargetItems: float,
|
|
487
|
+
~chunkItemsMultiplier=1.,
|
|
488
|
+
~maxTargetBlock=?,
|
|
489
|
+
) => {
|
|
490
|
+
let chainTargetBlock = cs->targetBlock(~chainTargetItems)
|
|
491
|
+
let chainTargetBlock = switch maxTargetBlock {
|
|
492
|
+
| Some(maxTargetBlock) => Pervasives.min(chainTargetBlock, maxTargetBlock)
|
|
493
|
+
| None => chainTargetBlock
|
|
494
|
+
}
|
|
495
|
+
// When the target block is clamped (head/endBlock/cross-chain alignment) a
|
|
496
|
+
// known-density chain can't use the whole handed budget — cap the fresh part
|
|
497
|
+
// at what the clamped range actually costs (in-flight reservations stay on
|
|
498
|
+
// top: they're already accounted and shouldn't crowd out new partitions), so
|
|
499
|
+
// the waterfall's leftover flows to the next chain in the same tick instead
|
|
500
|
+
// of being held by an oversized probe.
|
|
501
|
+
let chainTargetItems = switch cs->effectiveDensity {
|
|
502
|
+
| Some(density) if density > 0. =>
|
|
503
|
+
// No extra headroom here: the budget is reserved in honest itemsEst units,
|
|
504
|
+
// and truncation safety lives in the itemsTarget server cap (sized with
|
|
505
|
+
// chunkItemsMultiplier at query creation) — multiplying the budget cap too
|
|
506
|
+
// would compound the two and hold budget away from other chains.
|
|
507
|
+
let rangeCost =
|
|
508
|
+
density *. (chainTargetBlock - cs.fetchState->FetchState.bufferBlockNumber)->Int.toFloat
|
|
509
|
+
Pervasives.min(chainTargetItems, Math.ceil(rangeCost) +. cs.pendingBudget)
|
|
510
|
+
// No density signal: the cross-chain waterfall already clamped the handed
|
|
511
|
+
// budget to the cold-chain cap, so it's used as-is.
|
|
512
|
+
| _ => chainTargetItems
|
|
513
|
+
}
|
|
514
|
+
cs.fetchState->FetchState.getNextQuery(
|
|
515
|
+
~chainTargetBlock,
|
|
516
|
+
~chainTargetItems,
|
|
517
|
+
~chunkItemsMultiplier,
|
|
518
|
+
)
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// Run a fetch tick for this chain against its sources, feeding the owned fetch
|
|
522
|
+
// frontier to the source manager.
|
|
523
|
+
let dispatch = (
|
|
524
|
+
cs: t,
|
|
525
|
+
~executeQuery,
|
|
526
|
+
~waitForNewBlock,
|
|
527
|
+
~onNewBlock,
|
|
528
|
+
~action: FetchState.nextQuery,
|
|
529
|
+
~stateId,
|
|
530
|
+
) =>
|
|
531
|
+
cs.sourceManager->SourceManager.dispatch(
|
|
532
|
+
~fetchState=cs.fetchState,
|
|
533
|
+
~executeQuery,
|
|
534
|
+
~waitForNewBlock,
|
|
535
|
+
~onNewBlock,
|
|
536
|
+
~action,
|
|
537
|
+
~stateId,
|
|
538
|
+
)
|
|
539
|
+
|
|
407
540
|
// --- Derived (pure). ---
|
|
408
541
|
|
|
409
542
|
let hasProcessedToEndblock = (cs: t) => {
|
|
@@ -421,16 +554,201 @@ let getHighestBlockBelowThreshold = (cs: t): int => {
|
|
|
421
554
|
|
|
422
555
|
let isActivelyIndexing = (cs: t) => cs.fetchState->FetchState.isActivelyIndexing
|
|
423
556
|
|
|
424
|
-
let isReady = (cs: t) => cs.timestampCaughtUpToHeadOrEndblock !== None
|
|
425
|
-
|
|
426
557
|
// True once the fetch frontier has reached the head/endBlock for this chain.
|
|
427
558
|
let isFetchingAtHead = (cs: t) => cs.fetchState->FetchState.isFetchingAtHead
|
|
428
559
|
|
|
560
|
+
// Reached head on a chain with no configured endBlock — used by auto-exit to
|
|
561
|
+
// detect that no events were found in the start..head range.
|
|
562
|
+
let isAtHeadWithoutEndBlock = (cs: t) =>
|
|
563
|
+
cs.isProgressAtHead && cs.fetchState.endBlock->Option.isNone
|
|
564
|
+
|
|
429
565
|
// --- State transitions. The chain state is mutated only through these; each
|
|
430
566
|
// owns a cohesive update so callers don't juggle individual fields. ---
|
|
431
567
|
|
|
432
|
-
//
|
|
433
|
-
//
|
|
568
|
+
// Per-store grouping data a single pass over `items` produces (see
|
|
569
|
+
// `groupBatchItems`), fed into `TransactionStore`/`BlockStore`'s `materialize`.
|
|
570
|
+
type transactionGroups = {
|
|
571
|
+
txBlockNumbers: array<int>,
|
|
572
|
+
transactionIndices: array<int>,
|
|
573
|
+
transactionMasks: array<float>,
|
|
574
|
+
payloadGroups: array<array<Internal.eventPayload>>,
|
|
575
|
+
anyTransactionFieldSelected: bool,
|
|
576
|
+
}
|
|
577
|
+
type blockGroups = {
|
|
578
|
+
blockBlockNumbers: array<int>,
|
|
579
|
+
blockMasks: array<float>,
|
|
580
|
+
blockItemGroups: array<array<Internal.eventItem>>,
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
// Walk `items` once to build both the transaction-store and block-store
|
|
584
|
+
// grouping data, instead of `TransactionStore`/`BlockStore` each re-walking the
|
|
585
|
+
// same batch independently. Items already arrive in (blockNumber, logIndex)
|
|
586
|
+
// order, so a (blockNumber, transactionIndex) run and a blockNumber-only run
|
|
587
|
+
// each stay adjacent; every item is checked against both, in the same pass.
|
|
588
|
+
// `includeBlocks` skips the block side entirely for Fuel, which carries the
|
|
589
|
+
// block inline and has no store.
|
|
590
|
+
let groupBatchItems = (items: array<Internal.item>, ~includeBlocks: bool): (
|
|
591
|
+
transactionGroups,
|
|
592
|
+
blockGroups,
|
|
593
|
+
) => {
|
|
594
|
+
let txBlockNumbers = []
|
|
595
|
+
let transactionIndices = []
|
|
596
|
+
let transactionMasks = []
|
|
597
|
+
let payloadGroups = []
|
|
598
|
+
let anyTransactionFieldSelected = ref(false)
|
|
599
|
+
|
|
600
|
+
let blockBlockNumbers = []
|
|
601
|
+
let blockMasks = []
|
|
602
|
+
let blockItemGroups = []
|
|
603
|
+
|
|
604
|
+
items->Array.forEach(item =>
|
|
605
|
+
switch item {
|
|
606
|
+
| Internal.Event(_) =>
|
|
607
|
+
let eventItem = item->Internal.castUnsafeEventItem
|
|
608
|
+
let {blockNumber} = eventItem
|
|
609
|
+
|
|
610
|
+
switch eventItem.payload->Internal.getPayloadTransaction->Nullable.toOption {
|
|
611
|
+
| Some(_) => () // RPC/simulate/Fuel carry the transaction inline.
|
|
612
|
+
| None =>
|
|
613
|
+
let {transactionIndex} = eventItem
|
|
614
|
+
let mask = eventItem.onEventRegistration.eventConfig.transactionFieldMask
|
|
615
|
+
if mask != 0. {
|
|
616
|
+
anyTransactionFieldSelected := true
|
|
617
|
+
}
|
|
618
|
+
let last = payloadGroups->Array.length - 1
|
|
619
|
+
if (
|
|
620
|
+
last >= 0 &&
|
|
621
|
+
txBlockNumbers->Array.getUnsafe(last) == blockNumber &&
|
|
622
|
+
transactionIndices->Array.getUnsafe(last) == transactionIndex
|
|
623
|
+
) {
|
|
624
|
+
payloadGroups->Array.getUnsafe(last)->Array.push(eventItem.payload)
|
|
625
|
+
transactionMasks->Array.setUnsafe(
|
|
626
|
+
last,
|
|
627
|
+
FieldMask.orMask(transactionMasks->Array.getUnsafe(last), mask),
|
|
628
|
+
)
|
|
629
|
+
} else {
|
|
630
|
+
txBlockNumbers->Array.push(blockNumber)
|
|
631
|
+
transactionIndices->Array.push(transactionIndex)
|
|
632
|
+
transactionMasks->Array.push(mask)
|
|
633
|
+
payloadGroups->Array.push([eventItem.payload])
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
if includeBlocks {
|
|
638
|
+
switch eventItem.payload->Internal.getPayloadBlock->Nullable.toOption {
|
|
639
|
+
| Some(_) => () // RPC/simulate/Fuel carry the block inline.
|
|
640
|
+
| None =>
|
|
641
|
+
let mask = eventItem.onEventRegistration.eventConfig.blockFieldMask
|
|
642
|
+
let last = blockItemGroups->Array.length - 1
|
|
643
|
+
if last >= 0 && blockBlockNumbers->Array.getUnsafe(last) == blockNumber {
|
|
644
|
+
blockItemGroups->Array.getUnsafe(last)->Array.push(eventItem)
|
|
645
|
+
blockMasks->Array.setUnsafe(
|
|
646
|
+
last,
|
|
647
|
+
FieldMask.orMask(blockMasks->Array.getUnsafe(last), mask),
|
|
648
|
+
)
|
|
649
|
+
} else {
|
|
650
|
+
blockBlockNumbers->Array.push(blockNumber)
|
|
651
|
+
blockMasks->Array.push(mask)
|
|
652
|
+
blockItemGroups->Array.push([eventItem])
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
| Internal.Block(_) => ()
|
|
657
|
+
}
|
|
658
|
+
)
|
|
659
|
+
|
|
660
|
+
(
|
|
661
|
+
{
|
|
662
|
+
txBlockNumbers,
|
|
663
|
+
transactionIndices,
|
|
664
|
+
transactionMasks,
|
|
665
|
+
payloadGroups,
|
|
666
|
+
anyTransactionFieldSelected: anyTransactionFieldSelected.contents,
|
|
667
|
+
},
|
|
668
|
+
{blockBlockNumbers, blockMasks, blockItemGroups},
|
|
669
|
+
)
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
// Materialise a `TransactionStore` against precomputed groups (see
|
|
673
|
+
// `groupBatchItems`). Store-backed items always get a transaction object — the
|
|
674
|
+
// selected fields, or `{}` when nothing was selected — so `event.transaction`
|
|
675
|
+
// is never `undefined` (matching the inline sources).
|
|
676
|
+
let applyTransactionGroups = async (store: TransactionStore.t, g: transactionGroups) => {
|
|
677
|
+
if g.payloadGroups->Utils.Array.notEmpty {
|
|
678
|
+
if g.anyTransactionFieldSelected {
|
|
679
|
+
let txs = await store->TransactionStore.materialize(
|
|
680
|
+
~blockNumbers=g.txBlockNumbers,
|
|
681
|
+
~transactionIndices=g.transactionIndices,
|
|
682
|
+
~masks=g.transactionMasks,
|
|
683
|
+
)
|
|
684
|
+
g.payloadGroups->Array.forEachWithIndex((payloads, i) => {
|
|
685
|
+
let tx = txs->Array.getUnsafe(i)
|
|
686
|
+
payloads->Array.forEach(payload => payload->Internal.setPayloadTransaction(tx))
|
|
687
|
+
})
|
|
688
|
+
} else {
|
|
689
|
+
g.payloadGroups->Array.forEach(payloads =>
|
|
690
|
+
payloads->Array.forEach(payload => payload->Internal.setPayloadTransaction(%raw(`{}`)))
|
|
691
|
+
)
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
// Materialise a `BlockStore` against precomputed groups (see `groupBatchItems`).
|
|
697
|
+
let applyBlockGroups = async (store: BlockStore.t, g: blockGroups) => {
|
|
698
|
+
if g.blockItemGroups->Utils.Array.notEmpty {
|
|
699
|
+
let blocks = await store->BlockStore.materialize(
|
|
700
|
+
~blockNumbers=g.blockBlockNumbers,
|
|
701
|
+
~masks=g.blockMasks,
|
|
702
|
+
)
|
|
703
|
+
g.blockItemGroups->Array.forEachWithIndex((group, i) => {
|
|
704
|
+
let block = blocks->Array.getUnsafe(i)
|
|
705
|
+
group->Array.forEach(ei => ei.payload->Internal.setPayloadBlock(block))
|
|
706
|
+
})
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
let includeBlocksForEcosystem = (ecosystem: Ecosystem.name) =>
|
|
711
|
+
switch ecosystem {
|
|
712
|
+
| Evm | Svm => true
|
|
713
|
+
| Fuel => false
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
// Materialise the chain stores' selected transaction and block fields onto a
|
|
717
|
+
// batch's items at batch prep (the persistent-store path). A single pass over
|
|
718
|
+
// `items` (`groupBatchItems`) builds both stores' selection masks before the
|
|
719
|
+
// two independent materialize calls run concurrently.
|
|
720
|
+
let materializeBatchItems = async (cs: t, ~items: array<Internal.item>, ~ecosystem) => {
|
|
721
|
+
let (txGroups, blockGroups) =
|
|
722
|
+
items->groupBatchItems(~includeBlocks=ecosystem->includeBlocksForEcosystem)
|
|
723
|
+
let _ = await Promise.all2((
|
|
724
|
+
cs.transactionStore->applyTransactionGroups(txGroups),
|
|
725
|
+
cs.blockStore->applyBlockGroups(blockGroups),
|
|
726
|
+
))
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
// Materialise a fetch-response page's transactions and blocks onto its items
|
|
730
|
+
// before contract-register handlers read them. `None` pages (RPC/Fuel/Simulate
|
|
731
|
+
// keep them inline) are a no-op.
|
|
732
|
+
let materializePageItems = async (
|
|
733
|
+
~items: array<Internal.item>,
|
|
734
|
+
~transactionStore: option<TransactionStore.t>,
|
|
735
|
+
~blockStore: option<BlockStore.t>,
|
|
736
|
+
~ecosystem,
|
|
737
|
+
) => {
|
|
738
|
+
let (txGroups, blockGroups) =
|
|
739
|
+
items->groupBatchItems(~includeBlocks=ecosystem->includeBlocksForEcosystem)
|
|
740
|
+
let _ = await Promise.all2((
|
|
741
|
+
switch transactionStore {
|
|
742
|
+
| Some(store) => store->applyTransactionGroups(txGroups)
|
|
743
|
+
| None => Promise.resolve()
|
|
744
|
+
},
|
|
745
|
+
switch blockStore {
|
|
746
|
+
| Some(store) => store->applyBlockGroups(blockGroups)
|
|
747
|
+
| None => Promise.resolve()
|
|
748
|
+
},
|
|
749
|
+
))
|
|
750
|
+
}
|
|
751
|
+
|
|
434
752
|
let handleQueryResult = (
|
|
435
753
|
cs: t,
|
|
436
754
|
~query: FetchState.query,
|
|
@@ -438,19 +756,41 @@ let handleQueryResult = (
|
|
|
438
756
|
~newItemsWithDcs,
|
|
439
757
|
~latestFetchedBlock,
|
|
440
758
|
~knownHeight,
|
|
759
|
+
~transactionStore as txPage: option<TransactionStore.t>,
|
|
760
|
+
~blockStore as blockPage: option<BlockStore.t>,
|
|
441
761
|
) => {
|
|
762
|
+
// Merge this response's pages into the chain stores in lockstep with appending
|
|
763
|
+
// its items to the buffer. Inline sources contribute no page.
|
|
764
|
+
switch txPage {
|
|
765
|
+
| Some(page) => cs.transactionStore->TransactionStore.merge(page)
|
|
766
|
+
| None => ()
|
|
767
|
+
}
|
|
768
|
+
switch blockPage {
|
|
769
|
+
| Some(page) => cs.blockStore->BlockStore.merge(page)
|
|
770
|
+
| None => ()
|
|
771
|
+
}
|
|
772
|
+
|
|
442
773
|
let fs = switch newItemsWithDcs {
|
|
443
774
|
| [] => cs.fetchState
|
|
444
|
-
| _ =>
|
|
775
|
+
| _ =>
|
|
776
|
+
cs.fetchState->FetchState.registerDynamicContracts(
|
|
777
|
+
~indexingAddresses=cs.indexingAddresses,
|
|
778
|
+
newItemsWithDcs,
|
|
779
|
+
)
|
|
445
780
|
}
|
|
446
781
|
|
|
447
782
|
cs.fetchState =
|
|
448
783
|
fs
|
|
449
|
-
->FetchState.handleQueryResult(
|
|
784
|
+
->FetchState.handleQueryResult(
|
|
785
|
+
~indexingAddresses=cs.indexingAddresses,
|
|
786
|
+
~query,
|
|
787
|
+
~latestFetchedBlock,
|
|
788
|
+
~newItems,
|
|
789
|
+
)
|
|
450
790
|
->FetchState.updateKnownHeight(~knownHeight)
|
|
451
791
|
|
|
452
792
|
// The query is no longer in flight, so release its reservation.
|
|
453
|
-
cs.pendingBudget = Pervasives.max(0., cs.pendingBudget -. query.
|
|
793
|
+
cs.pendingBudget = Pervasives.max(0., cs.pendingBudget -. query.itemsEst->Int.toFloat)
|
|
454
794
|
}
|
|
455
795
|
|
|
456
796
|
// Run reorg detection against a fetch response and commit the updated guard.
|
|
@@ -491,6 +831,56 @@ let setEndBlockToFirstEvent = (cs: t, ~blockNumber) =>
|
|
|
491
831
|
let enterReorgThreshold = (cs: t) =>
|
|
492
832
|
cs.fetchState = cs.fetchState->FetchState.updateInternal(~blockLag=cs.chainConfig.blockLag)
|
|
493
833
|
|
|
834
|
+
// Snapshot the chain's metadata fields for staging into the chains table.
|
|
835
|
+
let toChainMetadata = (cs: t): InternalTable.Chains.metaFields => {
|
|
836
|
+
firstEventBlockNumber: cs.fetchState.firstEventBlock->Null.fromOption,
|
|
837
|
+
isHyperSync: (cs.sourceManager->SourceManager.getActiveSource).poweredByHyperSync,
|
|
838
|
+
latestFetchedBlockNumber: cs.fetchState->FetchState.bufferBlockNumber,
|
|
839
|
+
timestampCaughtUpToHeadOrEndblock: cs.timestampCaughtUpToHeadOrEndblock->Null.fromOption,
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
// Snapshot the chain's view for the status API.
|
|
843
|
+
let toChainData = (cs: t): chainData => {
|
|
844
|
+
chainId: cs.chainConfig.id->Int.toFloat,
|
|
845
|
+
poweredByHyperSync: (cs.sourceManager->SourceManager.getActiveSource).poweredByHyperSync,
|
|
846
|
+
firstEventBlockNumber: cs.fetchState.firstEventBlock,
|
|
847
|
+
latestProcessedBlock: cs.committedProgressBlockNumber === -1
|
|
848
|
+
? None
|
|
849
|
+
: Some(cs.committedProgressBlockNumber),
|
|
850
|
+
timestampCaughtUpToHeadOrEndblock: cs.timestampCaughtUpToHeadOrEndblock,
|
|
851
|
+
numEventsProcessed: cs.numEventsProcessed,
|
|
852
|
+
latestFetchedBlockNumber: Pervasives.max(cs.fetchState->FetchState.bufferBlockNumber, 0),
|
|
853
|
+
knownHeight: cs->hasProcessedToEndblock
|
|
854
|
+
? cs.fetchState.endBlock->Option.getOr(cs.fetchState.knownHeight)
|
|
855
|
+
: cs.fetchState.knownHeight,
|
|
856
|
+
numBatchesFetched: 0,
|
|
857
|
+
startBlock: cs.fetchState.startBlock,
|
|
858
|
+
endBlock: cs.fetchState.endBlock,
|
|
859
|
+
numAddresses: cs.indexingAddresses->IndexingAddresses.size,
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
// Snapshot the inputs a batch build needs from this chain.
|
|
863
|
+
let toChainBeforeBatch = (cs: t): Batch.chainBeforeBatch => {
|
|
864
|
+
fetchState: cs.fetchState,
|
|
865
|
+
progressBlockNumber: cs.committedProgressBlockNumber,
|
|
866
|
+
totalEventsProcessed: cs.numEventsProcessed,
|
|
867
|
+
sourceBlockNumber: cs.fetchState.knownHeight,
|
|
868
|
+
reorgDetection: cs.reorgDetection,
|
|
869
|
+
chainConfig: cs.chainConfig,
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
// Whether the chain's post-batch fetch frontier is ready to cross into the reorg
|
|
873
|
+
// threshold, using the batch's progressed frontier when this chain advanced.
|
|
874
|
+
let isReadyToEnterReorgThresholdAfterBatch = (cs: t, ~batch: Batch.t) => {
|
|
875
|
+
let fetchState = switch batch.progressedChainsById->Utils.Dict.dangerouslyGetByIntNonOption(
|
|
876
|
+
cs.fetchState.chainId,
|
|
877
|
+
) {
|
|
878
|
+
| Some(chainAfterBatch) => chainAfterBatch.fetchState
|
|
879
|
+
| None => cs.fetchState
|
|
880
|
+
}
|
|
881
|
+
fetchState->FetchState.isReadyToEnterReorgThreshold
|
|
882
|
+
}
|
|
883
|
+
|
|
494
884
|
// Commit the post-batch fetch frontier for a chain that progressed in the batch,
|
|
495
885
|
// applying blockLag when this batch also crosses into the reorg threshold.
|
|
496
886
|
let advanceAfterBatch = (cs: t, ~batch: Batch.t, ~enteringReorgThreshold) =>
|
|
@@ -501,14 +891,19 @@ let advanceAfterBatch = (cs: t, ~batch: Batch.t, ~enteringReorgThreshold) =>
|
|
|
501
891
|
cs.fetchState = enteringReorgThreshold
|
|
502
892
|
? chainAfterBatch.fetchState->FetchState.updateInternal(~blockLag=cs.chainConfig.blockLag)
|
|
503
893
|
: chainAfterBatch.fetchState
|
|
894
|
+
|
|
895
|
+
// The batch's items just left the buffer, so the remaining buffer's span
|
|
896
|
+
// starts at the batch's progress.
|
|
897
|
+
cs.processingBlockNumber = chainAfterBatch.progressBlockNumber
|
|
504
898
|
| None => ()
|
|
505
899
|
}
|
|
506
900
|
|
|
507
901
|
// Commit a processed batch's progress for this chain (progress block, events
|
|
508
902
|
// processed, head/safe-checkpoint tracking, first event block). Emits the
|
|
509
903
|
// per-chain progress metrics. Readiness is decided by CrossChainState once every
|
|
510
|
-
// chain is caught up (see markReady).
|
|
511
|
-
|
|
904
|
+
// chain is caught up (see markReady). `blockTimestampName` is the ecosystem's
|
|
905
|
+
// block-timestamp field, read off the payload block for the latency metric.
|
|
906
|
+
let applyBatchProgress = (cs: t, ~batch: Batch.t, ~blockTimestampName: string) => {
|
|
512
907
|
let chainId = cs.chainConfig.id
|
|
513
908
|
|
|
514
909
|
switch batch.progressedChainsById->Utils.Dict.dangerouslyGetByIntNonOption(chainId) {
|
|
@@ -526,15 +921,27 @@ let applyBatchProgress = (cs: t, ~batch: Batch.t) => {
|
|
|
526
921
|
)
|
|
527
922
|
}
|
|
528
923
|
|
|
529
|
-
// Calculate and set latency metrics
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
924
|
+
// Calculate and set latency metrics. The payload block is materialised or
|
|
925
|
+
// inline by processing time; its timestamp may still be absent (e.g. an
|
|
926
|
+
// SVM slot with no block row) — the metric is skipped then.
|
|
927
|
+
switch batch
|
|
928
|
+
->Batch.findLastEventItem(~chainId)
|
|
929
|
+
->Option.flatMap(eventItem =>
|
|
930
|
+
eventItem.payload
|
|
931
|
+
->Internal.getPayloadBlock
|
|
932
|
+
->Nullable.toOption
|
|
933
|
+
)
|
|
934
|
+
->Option.flatMap(block =>
|
|
935
|
+
block
|
|
936
|
+
->(Utils.magic: Internal.eventBlock => dict<unknown>)
|
|
937
|
+
->Utils.Dict.dangerouslyGetNonOption(blockTimestampName)
|
|
938
|
+
) {
|
|
939
|
+
| Some(blockTimestamp) =>
|
|
940
|
+
let blockTimestampMs = blockTimestamp->(Utils.magic: unknown => int) * 1000
|
|
941
|
+
Prometheus.ProgressLatency.set(
|
|
942
|
+
~latencyMs=Date.now()->Float.toInt - blockTimestampMs,
|
|
943
|
+
~chainId,
|
|
944
|
+
)
|
|
538
945
|
| None => ()
|
|
539
946
|
}
|
|
540
947
|
|
|
@@ -549,8 +956,42 @@ let applyBatchProgress = (cs: t, ~batch: Batch.t) => {
|
|
|
549
956
|
}
|
|
550
957
|
}
|
|
551
958
|
|
|
959
|
+
// Chain-wide density update: seed with the batch's own events/block on
|
|
960
|
+
// the first update, then blend weighted by the batch's block span — a
|
|
961
|
+
// few sparse/dense blocks barely nudge the estimate, while a
|
|
962
|
+
// window-sized batch replaces it.
|
|
963
|
+
let deltaBlocks = chainAfterBatch.progressBlockNumber - cs.committedProgressBlockNumber
|
|
964
|
+
if deltaBlocks > 0 {
|
|
965
|
+
let deltaEvents = chainAfterBatch.totalEventsProcessed -. cs.numEventsProcessed
|
|
966
|
+
// Don't seed a density before the first event is seen — a progress-only
|
|
967
|
+
// batch would otherwise set it to 0, matching the resume-seed guard.
|
|
968
|
+
switch (cs.chainDensity, deltaEvents > 0.) {
|
|
969
|
+
| (None, false) => ()
|
|
970
|
+
| _ =>
|
|
971
|
+
let batchDensity = deltaEvents /. deltaBlocks->Int.toFloat
|
|
972
|
+
cs.chainDensity = Some(
|
|
973
|
+
switch cs.chainDensity {
|
|
974
|
+
| None => batchDensity
|
|
975
|
+
| Some(oldDensity) =>
|
|
976
|
+
let alpha = Pervasives.min(1., deltaBlocks->Int.toFloat /. densityBlendWindow)
|
|
977
|
+
oldDensity *. (1. -. alpha) +. batchDensity *. alpha
|
|
978
|
+
},
|
|
979
|
+
)
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
|
|
552
983
|
cs.committedProgressBlockNumber = chainAfterBatch.progressBlockNumber
|
|
984
|
+
|
|
985
|
+
// Normally already set by advanceAfterBatch at batch creation; catch up
|
|
986
|
+
// here for paths that commit progress without it.
|
|
987
|
+
cs.processingBlockNumber = Pervasives.max(
|
|
988
|
+
cs.processingBlockNumber,
|
|
989
|
+
chainAfterBatch.progressBlockNumber,
|
|
990
|
+
)
|
|
553
991
|
cs.numEventsProcessed = chainAfterBatch.totalEventsProcessed
|
|
992
|
+
// Processed blocks' transactions and blocks are no longer needed.
|
|
993
|
+
cs.transactionStore->TransactionStore.prune(chainAfterBatch.progressBlockNumber)
|
|
994
|
+
cs.blockStore->BlockStore.prune(chainAfterBatch.progressBlockNumber)
|
|
554
995
|
cs.isProgressAtHead = cs.isProgressAtHead || chainAfterBatch.isProgressAtHeadWhenBatchCreated
|
|
555
996
|
switch cs.safeCheckpointTracking {
|
|
556
997
|
| Some(safeCheckpointTracking) =>
|
|
@@ -623,8 +1064,15 @@ let rollback = (
|
|
|
623
1064
|
)
|
|
624
1065
|
| None => ()
|
|
625
1066
|
}
|
|
626
|
-
cs.fetchState =
|
|
1067
|
+
cs.fetchState =
|
|
1068
|
+
cs.fetchState->FetchState.rollback(
|
|
1069
|
+
~indexingAddresses=cs.indexingAddresses,
|
|
1070
|
+
~targetBlockNumber=newProgressBlockNumber,
|
|
1071
|
+
)
|
|
1072
|
+
cs.transactionStore->TransactionStore.rollback(newProgressBlockNumber)
|
|
1073
|
+
cs.blockStore->BlockStore.rollback(newProgressBlockNumber)
|
|
627
1074
|
cs.committedProgressBlockNumber = newProgressBlockNumber
|
|
1075
|
+
cs.processingBlockNumber = newProgressBlockNumber
|
|
628
1076
|
cs.numEventsProcessed = newTotalEventsProcessed
|
|
629
1077
|
| None =>
|
|
630
1078
|
if isReorgChain {
|
|
@@ -633,11 +1081,17 @@ let rollback = (
|
|
|
633
1081
|
~blockNumber=rollbackTargetBlockNumber,
|
|
634
1082
|
)
|
|
635
1083
|
cs.fetchState =
|
|
636
|
-
cs.fetchState->FetchState.rollback(
|
|
1084
|
+
cs.fetchState->FetchState.rollback(
|
|
1085
|
+
~indexingAddresses=cs.indexingAddresses,
|
|
1086
|
+
~targetBlockNumber=rollbackTargetBlockNumber,
|
|
1087
|
+
)
|
|
1088
|
+
cs.transactionStore->TransactionStore.rollback(rollbackTargetBlockNumber)
|
|
1089
|
+
cs.blockStore->BlockStore.rollback(rollbackTargetBlockNumber)
|
|
637
1090
|
cs.committedProgressBlockNumber = Pervasives.min(
|
|
638
1091
|
cs.committedProgressBlockNumber,
|
|
639
1092
|
rollbackTargetBlockNumber,
|
|
640
1093
|
)
|
|
1094
|
+
cs.processingBlockNumber = Pervasives.min(cs.processingBlockNumber, rollbackTargetBlockNumber)
|
|
641
1095
|
}
|
|
642
1096
|
}
|
|
643
1097
|
}
|