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
@@ -5,21 +5,26 @@ import * as Js_math from "@rescript/runtime/lib/es6/Js_math.js";
5
5
  import * as Logging from "./Logging.res.mjs";
6
6
  import * as Prometheus from "./Prometheus.res.mjs";
7
7
  import * as Stdlib_Int from "@rescript/runtime/lib/es6/Stdlib_Int.js";
8
+ import * as Stdlib_Array from "@rescript/runtime/lib/es6/Stdlib_Array.js";
8
9
  import * as Primitive_int from "@rescript/runtime/lib/es6/Primitive_int.js";
9
10
  import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.js";
10
11
  import * as Stdlib_JsError from "@rescript/runtime/lib/es6/Stdlib_JsError.js";
12
+ import * as Primitive_float from "@rescript/runtime/lib/es6/Primitive_float.js";
11
13
  import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.js";
14
+ import * as IndexingAddresses from "./IndexingAddresses.res.mjs";
12
15
 
13
- function deriveEffectiveStartBlock(registrationBlock, contractStartBlock) {
14
- return Primitive_int.max(Primitive_int.max(registrationBlock, 0), Stdlib_Option.getOr(contractStartBlock, 0));
15
- }
16
+ let deriveContractNameByAddress = Utils.$$WeakMap.memoize(addressesByContractName => {
17
+ let result = {};
18
+ Utils.Dict.forEachWithKey(addressesByContractName, (addresses, contractName) => {
19
+ for (let i = 0, i_finish = addresses.length; i < i_finish; ++i) {
20
+ result[addresses[i]] = contractName;
21
+ }
22
+ });
23
+ return result;
24
+ });
16
25
 
17
- function calculateEstResponseSize(p, fromBlock, toBlock, maxQueryBlockNumber) {
18
- if (p.prevQueryRange <= 0) {
19
- return 10000;
20
- }
21
- let density = p.prevRangeSize / p.prevQueryRange;
22
- return ((Stdlib_Option.getOr(toBlock, maxQueryBlockNumber) - fromBlock | 0) + 1 | 0) * density;
26
+ function densityItemsTarget(density, fromBlock, toBlock, chainTargetBlock) {
27
+ return Primitive_int.max(1, Math.ceil(((Stdlib_Option.getOr(toBlock, chainTargetBlock) - fromBlock | 0) + 1 | 0) * density) | 0);
23
28
  }
24
29
 
25
30
  function getMinHistoryRange(p) {
@@ -30,6 +35,14 @@ function getMinHistoryRange(p) {
30
35
  }
31
36
  }
32
37
 
38
+ function getTrustedDensity(p) {
39
+ let match = p.prevQueryRange;
40
+ let match$1 = p.prevPrevQueryRange;
41
+ if (match !== 0 && match$1 !== 0) {
42
+ return p.prevRangeSize / match;
43
+ }
44
+ }
45
+
33
46
  function getMinQueryRange(partitions) {
34
47
  let min = 0;
35
48
  for (let i = 0, i_finish = partitions.length; i < i_finish; ++i) {
@@ -99,6 +112,7 @@ function mergePartitionsAtBlock(p1, p2, potentialMergeBlock, contractName, maxAd
99
112
  p1,
100
113
  p2
101
114
  ]);
115
+ let inheritedDensity = Stdlib_Option.getOr(getTrustedDensity(p1), 0) + Stdlib_Option.getOr(getTrustedDensity(p2), 0);
102
116
  continuingBase = {
103
117
  id: newId,
104
118
  latestFetchedBlock: {
@@ -112,7 +126,7 @@ function mergePartitionsAtBlock(p1, p2, potentialMergeBlock, contractName, maxAd
112
126
  mutPendingQueries: [],
113
127
  prevQueryRange: minRange,
114
128
  prevPrevQueryRange: minRange,
115
- prevRangeSize: 0,
129
+ prevRangeSize: Math.ceil(inheritedDensity * minRange) | 0,
116
130
  latestBlockRangeUpdateBlock: 0
117
131
  };
118
132
  } else {
@@ -349,11 +363,11 @@ function handleQueryResponse(optimizedPartitions, query, knownHeight, itemsCount
349
363
  let queryToBlock = query.toBlock;
350
364
  let tmp;
351
365
  if (queryToBlock !== undefined) {
352
- if (latestFetchedBlock.blockNumber >= queryToBlock) {
366
+ if (latestFetchedBlock.blockNumber < queryToBlock) {
367
+ tmp = itemsCount < query.itemsTarget;
368
+ } else {
353
369
  let minHistoryRange = getMinHistoryRange(p$1);
354
370
  tmp = minHistoryRange !== undefined ? ((queryToBlock - query.fromBlock | 0) + 1 | 0) >= minHistoryRange : false;
355
- } else {
356
- tmp = true;
357
371
  }
358
372
  } else {
359
373
  tmp = latestFetchedBlock.blockNumber < (knownHeight - 10 | 0);
@@ -454,6 +468,22 @@ function bufferBlock(param) {
454
468
  }
455
469
  }
456
470
 
471
+ function bufferReadyCount(fetchState) {
472
+ let frontier = bufferBlockNumber(fetchState);
473
+ let buffer = fetchState.buffer;
474
+ let lo = 0;
475
+ let hi = buffer.length;
476
+ while (lo < hi) {
477
+ let mid = (lo + hi | 0) / 2 | 0;
478
+ if (buffer[mid].blockNumber <= frontier) {
479
+ lo = mid + 1 | 0;
480
+ } else {
481
+ hi = mid;
482
+ }
483
+ };
484
+ return lo;
485
+ }
486
+
457
487
  function compareBufferItem(a, b) {
458
488
  let blockOrdering = Primitive_int.compare(a.blockNumber, b.blockNumber);
459
489
  if (blockOrdering === 0) {
@@ -463,31 +493,27 @@ function compareBufferItem(a, b) {
463
493
  }
464
494
  }
465
495
 
466
- function numAddresses(fetchState) {
467
- return Utils.Dict.size(fetchState.indexingAddresses);
468
- }
469
-
470
- function appendOnBlockItems(mutItems, onBlockConfigs, indexerStartBlock, fromBlock, maxBlockNumber, maxOnBlockBufferSize) {
496
+ function appendOnBlockItems(mutItems, onBlockRegistrations, indexerStartBlock, fromBlock, maxBlockNumber, maxOnBlockBufferSize) {
471
497
  let newItemsCounter = 0;
472
498
  let latestOnBlockBlockNumber = fromBlock;
473
499
  while (latestOnBlockBlockNumber < maxBlockNumber && newItemsCounter <= maxOnBlockBufferSize) {
474
500
  let blockNumber = latestOnBlockBlockNumber + 1 | 0;
475
501
  latestOnBlockBlockNumber = blockNumber;
476
- for (let configIdx = 0, configIdx_finish = onBlockConfigs.length; configIdx < configIdx_finish; ++configIdx) {
477
- let onBlockConfig = onBlockConfigs[configIdx];
478
- let startBlock = onBlockConfig.startBlock;
502
+ for (let configIdx = 0, configIdx_finish = onBlockRegistrations.length; configIdx < configIdx_finish; ++configIdx) {
503
+ let onBlockRegistration = onBlockRegistrations[configIdx];
504
+ let startBlock = onBlockRegistration.startBlock;
479
505
  let handlerStartBlock = startBlock !== undefined ? startBlock : indexerStartBlock;
480
506
  let tmp = false;
481
507
  if (blockNumber >= handlerStartBlock) {
482
- let endBlock = onBlockConfig.endBlock;
508
+ let endBlock = onBlockRegistration.endBlock;
483
509
  tmp = endBlock !== undefined ? blockNumber <= endBlock : true;
484
510
  }
485
- if (tmp && Primitive_int.mod_(blockNumber - handlerStartBlock | 0, onBlockConfig.interval) === 0) {
511
+ if (tmp && Primitive_int.mod_(blockNumber - handlerStartBlock | 0, onBlockRegistration.interval) === 0) {
486
512
  mutItems.push({
487
513
  kind: 1,
488
- onBlockConfig: onBlockConfig,
514
+ onBlockRegistration: onBlockRegistration,
489
515
  blockNumber: blockNumber,
490
- logIndex: 16777216 + onBlockConfig.index | 0
516
+ logIndex: 16777216 + onBlockRegistration.index | 0
491
517
  });
492
518
  newItemsCounter = newItemsCounter + 1 | 0;
493
519
  }
@@ -496,15 +522,14 @@ function appendOnBlockItems(mutItems, onBlockConfigs, indexerStartBlock, fromBlo
496
522
  return latestOnBlockBlockNumber;
497
523
  }
498
524
 
499
- function updateInternal(fetchState, optimizedPartitionsOpt, indexingAddressesOpt, mutItems, blockLagOpt, knownHeightOpt) {
525
+ function updateInternal(fetchState, optimizedPartitionsOpt, mutItems, blockLagOpt, knownHeightOpt) {
500
526
  let optimizedPartitions = optimizedPartitionsOpt !== undefined ? optimizedPartitionsOpt : fetchState.optimizedPartitions;
501
- let indexingAddresses = indexingAddressesOpt !== undefined ? indexingAddressesOpt : fetchState.indexingAddresses;
502
527
  let blockLag = blockLagOpt !== undefined ? blockLagOpt : fetchState.blockLag;
503
528
  let knownHeight = knownHeightOpt !== undefined ? knownHeightOpt : fetchState.knownHeight;
504
529
  let mutItemsRef = mutItems;
505
- let onBlockConfigs = fetchState.onBlockConfigs;
530
+ let onBlockRegistrations = fetchState.onBlockRegistrations;
506
531
  let latestOnBlockBlockNumber;
507
- if (onBlockConfigs.length !== 0) {
532
+ if (onBlockRegistrations.length !== 0) {
508
533
  let mutItems$1 = mutItemsRef;
509
534
  let item = (
510
535
  mutItems$1 !== undefined ? mutItems$1 : fetchState.buffer
@@ -520,7 +545,7 @@ function updateInternal(fetchState, optimizedPartitionsOpt, indexingAddressesOpt
520
545
  let mutItems$2 = mutItemsRef;
521
546
  let mutItems$3 = mutItems$2 !== undefined ? mutItems$2 : fetchState.buffer.slice();
522
547
  mutItemsRef = mutItems$3;
523
- latestOnBlockBlockNumber = appendOnBlockItems(mutItems$3, onBlockConfigs, fetchState.startBlock, fetchState.latestOnBlockBlockNumber, maxBlockNumber, fetchState.maxOnBlockBufferSize);
548
+ latestOnBlockBlockNumber = appendOnBlockItems(mutItems$3, onBlockRegistrations, fetchState.startBlock, fetchState.latestOnBlockBlockNumber, maxBlockNumber, fetchState.maxOnBlockBufferSize);
524
549
  } else {
525
550
  latestOnBlockBlockNumber = knownHeight;
526
551
  }
@@ -532,30 +557,26 @@ function updateInternal(fetchState, optimizedPartitionsOpt, indexingAddressesOpt
532
557
  let updatedFetchState_chainId = fetchState.chainId;
533
558
  let updatedFetchState_buffer = mutItems$4 !== undefined ? (mutItems$4.sort(compareBufferItem), mutItems$4) : fetchState.buffer;
534
559
  let updatedFetchState_maxOnBlockBufferSize = fetchState.maxOnBlockBufferSize;
535
- let updatedFetchState_onBlockConfigs = fetchState.onBlockConfigs;
560
+ let updatedFetchState_onBlockRegistrations = fetchState.onBlockRegistrations;
536
561
  let updatedFetchState_firstEventBlock = fetchState.firstEventBlock;
537
562
  let updatedFetchState = {
538
563
  optimizedPartitions: optimizedPartitions,
539
564
  startBlock: updatedFetchState_startBlock,
540
565
  endBlock: updatedFetchState_endBlock,
541
566
  normalSelection: updatedFetchState_normalSelection,
542
- indexingAddresses: indexingAddresses,
543
567
  contractConfigs: updatedFetchState_contractConfigs,
544
568
  chainId: updatedFetchState_chainId,
545
569
  latestOnBlockBlockNumber: latestOnBlockBlockNumber,
546
570
  blockLag: blockLag,
547
571
  buffer: updatedFetchState_buffer,
548
572
  maxOnBlockBufferSize: updatedFetchState_maxOnBlockBufferSize,
549
- onBlockConfigs: updatedFetchState_onBlockConfigs,
573
+ onBlockRegistrations: updatedFetchState_onBlockRegistrations,
550
574
  knownHeight: knownHeight,
551
575
  firstEventBlock: updatedFetchState_firstEventBlock
552
576
  };
553
577
  Prometheus.IndexingPartitions.set(optimizedPartitions.idsInAscOrder.length, fetchState.chainId);
554
578
  Prometheus.IndexingBufferSize.set(updatedFetchState_buffer.length, fetchState.chainId);
555
579
  Prometheus.IndexingBufferBlockNumber.set(bufferBlockNumber(updatedFetchState), fetchState.chainId);
556
- if (indexingAddresses !== fetchState.indexingAddresses) {
557
- Prometheus.IndexingAddresses.set(Utils.Dict.size(indexingAddresses), fetchState.chainId);
558
- }
559
580
  return updatedFetchState;
560
581
  }
561
582
 
@@ -737,11 +758,10 @@ function createPartitionsFromIndexingAddresses(registeringContractsByContract, d
737
758
  return make(existingPartitions.concat(mergedPartitions), maxAddrInPartition, nextPartitionIndexRef, dynamicContracts);
738
759
  }
739
760
 
740
- function registerDynamicContracts(fetchState, items) {
741
- if (Utils.$$Array.isEmpty(fetchState.normalSelection.eventConfigs)) {
761
+ function registerDynamicContracts(fetchState, indexingAddresses, items) {
762
+ if (Utils.$$Array.isEmpty(fetchState.normalSelection.onEventRegistrations)) {
742
763
  Stdlib_JsError.throwWithMessage("Invalid configuration. No events to fetch for the dynamic contract registration.");
743
764
  }
744
- let indexingAddresses = fetchState.indexingAddresses;
745
765
  let registeringContractsByContract = {};
746
766
  let earliestRegisteringEventBlockNumber = Infinity;
747
767
  let noEventsAddresses = {};
@@ -759,14 +779,14 @@ function registerDynamicContracts(fetchState, items) {
759
779
  let dcWithStartBlock_address = dc.address;
760
780
  let dcWithStartBlock_contractName = dc.contractName;
761
781
  let dcWithStartBlock_registrationBlock = dc.registrationBlock;
762
- let dcWithStartBlock_effectiveStartBlock = deriveEffectiveStartBlock(dc.registrationBlock, match.startBlock);
782
+ let dcWithStartBlock_effectiveStartBlock = IndexingAddresses.deriveEffectiveStartBlock(dc.registrationBlock, match.startBlock);
763
783
  let dcWithStartBlock = {
764
784
  address: dcWithStartBlock_address,
765
785
  contractName: dcWithStartBlock_contractName,
766
786
  registrationBlock: dcWithStartBlock_registrationBlock,
767
787
  effectiveStartBlock: dcWithStartBlock_effectiveStartBlock
768
788
  };
769
- let existingContract = indexingAddresses[dc.address];
789
+ let existingContract = IndexingAddresses.get(indexingAddresses, dc.address);
770
790
  if (existingContract !== undefined) {
771
791
  if (existingContract.contractName !== dc.contractName) {
772
792
  warnDifferentContractType(fetchState, existingContract, dcWithStartBlock);
@@ -797,14 +817,14 @@ function registerDynamicContracts(fetchState, items) {
797
817
  let dcAsIndexingAddress_address = dc.address;
798
818
  let dcAsIndexingAddress_contractName = dc.contractName;
799
819
  let dcAsIndexingAddress_registrationBlock = dc.registrationBlock;
800
- let dcAsIndexingAddress_effectiveStartBlock = deriveEffectiveStartBlock(dc.registrationBlock, undefined);
820
+ let dcAsIndexingAddress_effectiveStartBlock = IndexingAddresses.deriveEffectiveStartBlock(dc.registrationBlock, undefined);
801
821
  let dcAsIndexingAddress = {
802
822
  address: dcAsIndexingAddress_address,
803
823
  contractName: dcAsIndexingAddress_contractName,
804
824
  registrationBlock: dcAsIndexingAddress_registrationBlock,
805
825
  effectiveStartBlock: dcAsIndexingAddress_effectiveStartBlock
806
826
  };
807
- let existingContract$1 = indexingAddresses[dc.address];
827
+ let existingContract$1 = IndexingAddresses.get(indexingAddresses, dc.address);
808
828
  if (existingContract$1 !== undefined) {
809
829
  if (existingContract$1.contractName !== dc.contractName) {
810
830
  warnDifferentContractType(fetchState, existingContract$1, dcAsIndexingAddress);
@@ -839,101 +859,100 @@ function registerDynamicContracts(fetchState, items) {
839
859
  }
840
860
  let dcContractNamesToStore = Object.keys(registeringContractsByContract);
841
861
  let hasNoEventsUpdates = !Utils.Dict.isEmpty(noEventsAddresses);
842
- if (dcContractNamesToStore.length !== 0) {
843
- let newPartitions = [];
844
- let newIndexingAddresses = Utils.Dict.shallowCopy(indexingAddresses);
845
- let dynamicContractsRef = fetchState.optimizedPartitions.dynamicContracts;
846
- let mutExistingPartitions = Object.values(fetchState.optimizedPartitions.entities);
847
- for (let idx$1 = 0, idx_finish = dcContractNamesToStore.length; idx$1 < idx_finish; ++idx$1) {
848
- let contractName = dcContractNamesToStore[idx$1];
849
- if (!dynamicContractsRef.has(contractName)) {
850
- dynamicContractsRef = Utils.$$Set.immutableAdd(dynamicContractsRef, contractName);
851
- for (let idx$2 = 0, idx_finish$1 = mutExistingPartitions.length; idx$2 < idx_finish$1; ++idx$2) {
852
- let p = mutExistingPartitions[idx$2];
853
- let addresses = p.addressesByContractName[contractName];
854
- if (addresses !== undefined && p.selection.dependsOnAddresses && p.mergeBlock === undefined) {
855
- let allPartitionContractNames = Object.keys(p.addressesByContractName);
856
- if (allPartitionContractNames.length !== 1) {
857
- let isFetching = p.mutPendingQueries.length !== 0;
858
- if (!isFetching) {
859
- let newPartitionId = (fetchState.optimizedPartitions.nextPartitionIndex + newPartitions.length | 0).toString();
860
- let restAddressesByContractName = Utils.Dict.shallowCopy(p.addressesByContractName);
861
- Utils.Dict.deleteInPlace(restAddressesByContractName, contractName);
862
- mutExistingPartitions[idx$2] = {
863
- id: p.id,
864
- latestFetchedBlock: p.latestFetchedBlock,
865
- selection: p.selection,
866
- addressesByContractName: restAddressesByContractName,
867
- mergeBlock: p.mergeBlock,
868
- dynamicContract: p.dynamicContract,
869
- mutPendingQueries: p.mutPendingQueries,
870
- prevQueryRange: p.prevQueryRange,
871
- prevPrevQueryRange: p.prevPrevQueryRange,
872
- prevRangeSize: p.prevRangeSize,
873
- latestBlockRangeUpdateBlock: p.latestBlockRangeUpdateBlock
874
- };
875
- let addressesByContractName = {};
876
- addressesByContractName[contractName] = addresses;
877
- newPartitions.push({
878
- id: newPartitionId,
879
- latestFetchedBlock: p.latestFetchedBlock,
880
- selection: fetchState.normalSelection,
881
- addressesByContractName: addressesByContractName,
882
- mergeBlock: undefined,
883
- dynamicContract: contractName,
884
- mutPendingQueries: p.mutPendingQueries,
885
- prevQueryRange: p.prevQueryRange,
886
- prevPrevQueryRange: p.prevPrevQueryRange,
887
- prevRangeSize: p.prevRangeSize,
888
- latestBlockRangeUpdateBlock: p.latestBlockRangeUpdateBlock
889
- });
890
- }
891
- } else {
862
+ if (dcContractNamesToStore.length === 0) {
863
+ if (hasNoEventsUpdates) {
864
+ IndexingAddresses.register(indexingAddresses, noEventsAddresses);
865
+ return fetchState;
866
+ } else {
867
+ return fetchState;
868
+ }
869
+ }
870
+ let newPartitions = [];
871
+ let dynamicContractsRef = fetchState.optimizedPartitions.dynamicContracts;
872
+ let mutExistingPartitions = Object.values(fetchState.optimizedPartitions.entities);
873
+ for (let idx$1 = 0, idx_finish = dcContractNamesToStore.length; idx$1 < idx_finish; ++idx$1) {
874
+ let contractName = dcContractNamesToStore[idx$1];
875
+ if (!dynamicContractsRef.has(contractName)) {
876
+ dynamicContractsRef = Utils.$$Set.immutableAdd(dynamicContractsRef, contractName);
877
+ for (let idx$2 = 0, idx_finish$1 = mutExistingPartitions.length; idx$2 < idx_finish$1; ++idx$2) {
878
+ let p = mutExistingPartitions[idx$2];
879
+ let addresses = p.addressesByContractName[contractName];
880
+ if (addresses !== undefined && p.selection.dependsOnAddresses && p.mergeBlock === undefined) {
881
+ let allPartitionContractNames = Object.keys(p.addressesByContractName);
882
+ if (allPartitionContractNames.length !== 1) {
883
+ let isFetching = p.mutPendingQueries.length !== 0;
884
+ if (!isFetching) {
885
+ let newPartitionId = (fetchState.optimizedPartitions.nextPartitionIndex + newPartitions.length | 0).toString();
886
+ let restAddressesByContractName = Utils.Dict.shallowCopy(p.addressesByContractName);
887
+ Utils.Dict.deleteInPlace(restAddressesByContractName, contractName);
892
888
  mutExistingPartitions[idx$2] = {
893
889
  id: p.id,
894
890
  latestFetchedBlock: p.latestFetchedBlock,
895
891
  selection: p.selection,
896
- addressesByContractName: p.addressesByContractName,
892
+ addressesByContractName: restAddressesByContractName,
897
893
  mergeBlock: p.mergeBlock,
898
- dynamicContract: contractName,
894
+ dynamicContract: p.dynamicContract,
899
895
  mutPendingQueries: p.mutPendingQueries,
900
896
  prevQueryRange: p.prevQueryRange,
901
897
  prevPrevQueryRange: p.prevPrevQueryRange,
902
898
  prevRangeSize: p.prevRangeSize,
903
899
  latestBlockRangeUpdateBlock: p.latestBlockRangeUpdateBlock
904
900
  };
901
+ let addressesByContractName = {};
902
+ addressesByContractName[contractName] = addresses;
903
+ newPartitions.push({
904
+ id: newPartitionId,
905
+ latestFetchedBlock: p.latestFetchedBlock,
906
+ selection: fetchState.normalSelection,
907
+ addressesByContractName: addressesByContractName,
908
+ mergeBlock: undefined,
909
+ dynamicContract: contractName,
910
+ mutPendingQueries: p.mutPendingQueries,
911
+ prevQueryRange: p.prevQueryRange,
912
+ prevPrevQueryRange: p.prevPrevQueryRange,
913
+ prevRangeSize: p.prevRangeSize,
914
+ latestBlockRangeUpdateBlock: p.latestBlockRangeUpdateBlock
915
+ });
905
916
  }
917
+ } else {
918
+ mutExistingPartitions[idx$2] = {
919
+ id: p.id,
920
+ latestFetchedBlock: p.latestFetchedBlock,
921
+ selection: p.selection,
922
+ addressesByContractName: p.addressesByContractName,
923
+ mergeBlock: p.mergeBlock,
924
+ dynamicContract: contractName,
925
+ mutPendingQueries: p.mutPendingQueries,
926
+ prevQueryRange: p.prevQueryRange,
927
+ prevPrevQueryRange: p.prevPrevQueryRange,
928
+ prevRangeSize: p.prevRangeSize,
929
+ latestBlockRangeUpdateBlock: p.latestBlockRangeUpdateBlock
930
+ };
906
931
  }
907
932
  }
908
933
  }
909
- let registeringContracts = registeringContractsByContract[contractName];
910
- Object.assign(newIndexingAddresses, registeringContracts);
911
934
  }
912
- Object.assign(newIndexingAddresses, noEventsAddresses);
913
- let optimizedPartitions = createPartitionsFromIndexingAddresses(registeringContractsByContract, dynamicContractsRef, fetchState.normalSelection, fetchState.optimizedPartitions.maxAddrInPartition, fetchState.optimizedPartitions.nextPartitionIndex + newPartitions.length | 0, mutExistingPartitions.concat(newPartitions), 0);
914
- return updateInternal(fetchState, optimizedPartitions, newIndexingAddresses, undefined, undefined, undefined);
915
- }
916
- if (!hasNoEventsUpdates) {
917
- return fetchState;
935
+ let registeringContracts = registeringContractsByContract[contractName];
936
+ IndexingAddresses.register(indexingAddresses, registeringContracts);
918
937
  }
919
- let newIndexingContracts = Utils.Dict.shallowCopy(indexingAddresses);
920
- Object.assign(newIndexingContracts, noEventsAddresses);
921
- return updateInternal(fetchState, undefined, newIndexingContracts, undefined, undefined, undefined);
938
+ IndexingAddresses.register(indexingAddresses, noEventsAddresses);
939
+ let optimizedPartitions = createPartitionsFromIndexingAddresses(registeringContractsByContract, dynamicContractsRef, fetchState.normalSelection, fetchState.optimizedPartitions.maxAddrInPartition, fetchState.optimizedPartitions.nextPartitionIndex + newPartitions.length | 0, mutExistingPartitions.concat(newPartitions), 0);
940
+ return updateInternal(fetchState, optimizedPartitions, undefined, undefined, undefined);
922
941
  }
923
942
 
924
- function handleQueryResult(fetchState, query, latestFetchedBlock, newItems) {
943
+ function handleQueryResult(fetchState, indexingAddresses, query, latestFetchedBlock, newItems) {
925
944
  let newItems$1 = newItems.filter(item => {
926
945
  if (item.kind !== 0) {
927
946
  return true;
928
947
  }
929
- let filter = item.eventConfig.clientAddressFilter;
948
+ let filter = item.onEventRegistration.clientAddressFilter;
930
949
  if (filter !== undefined) {
931
- return filter(item.payload, item.blockNumber, fetchState.indexingAddresses);
950
+ return filter(item.payload, item.blockNumber, IndexingAddresses.rawForFilter(indexingAddresses));
932
951
  } else {
933
952
  return true;
934
953
  }
935
954
  });
936
- return updateInternal(fetchState, handleQueryResponse(fetchState.optimizedPartitions, query, fetchState.knownHeight, newItems$1.length, latestFetchedBlock), undefined, newItems$1.length !== 0 ? fetchState.buffer.concat(newItems$1) : undefined, undefined, undefined);
955
+ return updateInternal(fetchState, handleQueryResponse(fetchState.optimizedPartitions, query, fetchState.knownHeight, newItems$1.length, latestFetchedBlock), newItems$1.length !== 0 ? fetchState.buffer.concat(newItems$1) : undefined, undefined, undefined);
937
956
  }
938
957
 
939
958
  function startFetchingQueries(param, queries) {
@@ -947,7 +966,8 @@ function startFetchingQueries(param, queries) {
947
966
  fromBlock: q.fromBlock,
948
967
  toBlock: q.toBlock,
949
968
  isChunk: q.isChunk,
950
- estResponseSize: q.estResponseSize,
969
+ itemsTarget: q.itemsTarget,
970
+ itemsEst: q.itemsEst,
951
971
  fetchedBlock: undefined
952
972
  };
953
973
  let inserted = false;
@@ -965,199 +985,159 @@ function startFetchingQueries(param, queries) {
965
985
  }
966
986
  }
967
987
 
968
- function pushQueriesForRange(queries, partitionId, rangeFromBlock, rangeEndBlock, maxQueryBlockNumber, maybeChunkRange, partition, selection, addressesByContractName, indexingAddresses) {
969
- if (rangeFromBlock > maxQueryBlockNumber) {
970
- return;
971
- }
972
- if (rangeEndBlock !== undefined && rangeFromBlock > rangeEndBlock) {
973
- return;
974
- }
975
- if (maybeChunkRange !== undefined) {
976
- let maxBlock = rangeEndBlock !== undefined ? rangeEndBlock : maxQueryBlockNumber;
977
- let chunkSize = Js_math.ceil_int(maybeChunkRange * 1.8);
978
- let probeSize = Js_math.ceil_int(maybeChunkRange * 0.9);
979
- let getChunkSize = chunkIdx => {
980
- if (chunkIdx < 2) {
981
- return probeSize;
982
- } else {
983
- return chunkSize;
984
- }
985
- };
986
- if ((((rangeFromBlock + probeSize | 0) + probeSize | 0) - 1 | 0) <= maxBlock) {
987
- let chunkFromBlock = rangeFromBlock;
988
- let chunkIdx = 0;
989
- while (chunkIdx < 5 && ((chunkFromBlock + getChunkSize(chunkIdx) | 0) - 1 | 0) <= maxBlock) {
990
- let chunkToBlock = (chunkFromBlock + getChunkSize(chunkIdx) | 0) - 1 | 0;
988
+ function pushGapFillQueries(queries, partitionId, rangeFromBlock, rangeEndBlock, knownHeight, chainTargetBlock, maybeChunkRange, maxChunks, partition, partitionBudget, chunkItemsMultiplier, selection, addressesByContractName) {
989
+ let cost = {
990
+ contents: 0
991
+ };
992
+ if (rangeFromBlock <= Primitive_int.min(knownHeight, chainTargetBlock) && maxChunks > 0) {
993
+ let exit = 0;
994
+ if (!(rangeEndBlock !== undefined && rangeFromBlock > rangeEndBlock)) {
995
+ exit = 1;
996
+ }
997
+ if (exit === 1) {
998
+ let trustedDensity = getTrustedDensity(partition);
999
+ let maxBlock = rangeEndBlock !== undefined ? rangeEndBlock : chainTargetBlock;
1000
+ let pushSingleQuery = (density, isChunk) => {
1001
+ let itemsTarget = densityItemsTarget(density * chunkItemsMultiplier, rangeFromBlock, rangeEndBlock, chainTargetBlock);
1002
+ let itemsEst = densityItemsTarget(density, rangeFromBlock, rangeEndBlock, chainTargetBlock);
991
1003
  queries.push({
992
1004
  partitionId: partitionId,
993
- fromBlock: chunkFromBlock,
994
- toBlock: chunkToBlock,
995
- isChunk: true,
996
- estResponseSize: calculateEstResponseSize(partition, chunkFromBlock, chunkToBlock, maxQueryBlockNumber),
997
- chainId: 0,
998
- progress: 0,
1005
+ fromBlock: rangeFromBlock,
1006
+ toBlock: rangeEndBlock,
1007
+ isChunk: isChunk,
1008
+ itemsTarget: itemsTarget,
1009
+ itemsEst: itemsEst,
999
1010
  selection: selection,
1000
- addressesByContractName: addressesByContractName,
1001
- indexingAddresses: indexingAddresses
1011
+ addressesByContractName: addressesByContractName
1002
1012
  });
1003
- chunkFromBlock = chunkToBlock + 1 | 0;
1004
- chunkIdx = chunkIdx + 1 | 0;
1013
+ cost.contents = cost.contents + itemsEst;
1005
1014
  };
1006
- return;
1015
+ if (trustedDensity !== undefined) {
1016
+ if (maybeChunkRange !== undefined && trustedDensity > 0) {
1017
+ let chunkSize = Js_math.ceil_int(maybeChunkRange * 1.8);
1018
+ if (((rangeFromBlock + (chunkSize << 1) | 0) - 1 | 0) <= maxBlock) {
1019
+ let chunkFromBlock = rangeFromBlock;
1020
+ let chunkIdx = 0;
1021
+ while (chunkIdx < maxChunks && ((chunkFromBlock + chunkSize | 0) - 1 | 0) <= maxBlock) {
1022
+ let chunkToBlock = (chunkFromBlock + chunkSize | 0) - 1 | 0;
1023
+ let itemsTarget = densityItemsTarget(trustedDensity * chunkItemsMultiplier, chunkFromBlock, chunkToBlock, chainTargetBlock);
1024
+ let itemsEst = densityItemsTarget(trustedDensity, chunkFromBlock, chunkToBlock, chainTargetBlock);
1025
+ queries.push({
1026
+ partitionId: partitionId,
1027
+ fromBlock: chunkFromBlock,
1028
+ toBlock: chunkToBlock,
1029
+ isChunk: true,
1030
+ itemsTarget: itemsTarget,
1031
+ itemsEst: itemsEst,
1032
+ selection: selection,
1033
+ addressesByContractName: addressesByContractName
1034
+ });
1035
+ cost.contents = cost.contents + itemsEst;
1036
+ chunkFromBlock = chunkToBlock + 1 | 0;
1037
+ chunkIdx = chunkIdx + 1 | 0;
1038
+ };
1039
+ } else {
1040
+ pushSingleQuery(trustedDensity, rangeEndBlock !== undefined);
1041
+ }
1042
+ } else {
1043
+ pushSingleQuery(trustedDensity, false);
1044
+ }
1045
+ } else {
1046
+ let remainingRange = Primitive_int.max(1, (chainTargetBlock - rangeFromBlock | 0) + 1 | 0);
1047
+ pushSingleQuery(partitionBudget / remainingRange, false);
1048
+ }
1007
1049
  }
1008
- queries.push({
1009
- partitionId: partitionId,
1010
- fromBlock: rangeFromBlock,
1011
- toBlock: rangeEndBlock,
1012
- isChunk: rangeEndBlock !== undefined,
1013
- estResponseSize: calculateEstResponseSize(partition, rangeFromBlock, rangeEndBlock, maxQueryBlockNumber),
1014
- chainId: 0,
1015
- progress: 0,
1016
- selection: selection,
1017
- addressesByContractName: addressesByContractName,
1018
- indexingAddresses: indexingAddresses
1019
- });
1020
- return;
1021
1050
  }
1022
- queries.push({
1023
- partitionId: partitionId,
1024
- fromBlock: rangeFromBlock,
1025
- toBlock: rangeEndBlock,
1026
- isChunk: false,
1027
- estResponseSize: calculateEstResponseSize(partition, rangeFromBlock, rangeEndBlock, maxQueryBlockNumber),
1028
- chainId: 0,
1029
- progress: 0,
1030
- selection: selection,
1031
- addressesByContractName: addressesByContractName,
1032
- indexingAddresses: indexingAddresses
1033
- });
1051
+ return cost.contents;
1034
1052
  }
1035
1053
 
1036
- function getNextQuery(fetchState, budget, chainPendingBudget) {
1037
- let knownHeight = fetchState.knownHeight;
1038
- let blockLag = fetchState.blockLag;
1039
- let indexingAddresses = fetchState.indexingAddresses;
1040
- let optimizedPartitions = fetchState.optimizedPartitions;
1054
+ function waterLevel(budget, footprints) {
1055
+ let sorted = footprints.toSorted(Primitive_float.compare);
1056
+ let n = sorted.length;
1057
+ let prefix = 0;
1058
+ let level;
1059
+ let idx = 0;
1060
+ while (level === undefined && idx < n) {
1061
+ let i = idx;
1062
+ prefix = prefix + sorted[i];
1063
+ let candidate = (budget + prefix) / (i + 1 | 0);
1064
+ if (i === (n - 1 | 0) || candidate <= sorted[i + 1 | 0]) {
1065
+ level = candidate;
1066
+ }
1067
+ idx = idx + 1 | 0;
1068
+ };
1069
+ return Stdlib_Option.getOr(level, 0);
1070
+ }
1071
+
1072
+ function getNextQuery(param, chainTargetBlock, chainTargetItems, $staropt$star) {
1073
+ let knownHeight = param.knownHeight;
1074
+ let blockLag = param.blockLag;
1075
+ let endBlock = param.endBlock;
1076
+ let optimizedPartitions = param.optimizedPartitions;
1077
+ let chunkItemsMultiplier = $staropt$star !== undefined ? $staropt$star : 1;
1041
1078
  let headBlockNumber = knownHeight - blockLag | 0;
1042
1079
  if (headBlockNumber <= 0) {
1043
1080
  return "WaitingForNewBlock";
1044
1081
  }
1045
- if (budget <= 0) {
1046
- return "NothingToQuery";
1047
- }
1048
- let isOnBlockBehindTheHead = fetchState.latestOnBlockBlockNumber < headBlockNumber;
1049
- let endBlock = fetchState.endBlock;
1082
+ let isOnBlockBehindTheHead = param.latestOnBlockBlockNumber < headBlockNumber;
1050
1083
  let shouldWaitForNewBlock = (
1051
1084
  endBlock !== undefined ? headBlockNumber < endBlock : true
1052
1085
  ) && !isOnBlockBehindTheHead;
1053
- let item = fetchState.buffer[(budget + (chainPendingBudget | 0) | 0) - 1 | 0];
1054
- let maxQueryBlockNumber = item !== undefined ? Primitive_int.min(item.blockNumber, knownHeight) : knownHeight;
1055
- let queries = [];
1056
1086
  let partitionsCount = optimizedPartitions.idsInAscOrder.length;
1057
- let idxRef = 0;
1058
- while (idxRef < partitionsCount) {
1059
- let idx = idxRef;
1087
+ for (let idx = 0; idx < partitionsCount; ++idx) {
1060
1088
  let partitionId = optimizedPartitions.idsInAscOrder[idx];
1061
1089
  let p = optimizedPartitions.entities[partitionId];
1062
- let pendingCount = p.mutPendingQueries.length;
1063
- let isBehindTheHead = p.latestFetchedBlock.blockNumber < headBlockNumber;
1064
- let hasPendingQueries = pendingCount > 0;
1065
- if (hasPendingQueries || isBehindTheHead) {
1090
+ if (p.mutPendingQueries.length !== 0 || p.latestFetchedBlock.blockNumber < headBlockNumber) {
1066
1091
  shouldWaitForNewBlock = false;
1067
1092
  }
1068
- let partitionQueriesStart = queries.length;
1069
- let queryEndBlock = Utils.$$Math.minOptInt(fetchState.endBlock, p.mergeBlock);
1070
- let queryEndBlock$1 = blockLag !== 0 ? Utils.$$Math.minOptInt(headBlockNumber, queryEndBlock) : queryEndBlock;
1071
- let match = maxQueryBlockNumber < knownHeight;
1072
- let queryEndBlock$2 = queryEndBlock$1 !== undefined ? (
1073
- match ? Primitive_int.min(maxQueryBlockNumber, queryEndBlock$1) : queryEndBlock$1
1074
- ) : (
1075
- match ? maxQueryBlockNumber : queryEndBlock$1
1076
- );
1077
- let maybeChunkRange = getMinHistoryRange(p);
1078
- let cursor = p.latestFetchedBlock.blockNumber + 1 | 0;
1093
+ }
1094
+ let queriesByPartitionIndex = Stdlib_Array.fromInitializer(partitionsCount, param => []);
1095
+ let computeQueryEndBlock = p => {
1096
+ let queryEndBlock = Utils.$$Math.minOptInt(endBlock, p.mergeBlock);
1097
+ if (blockLag !== 0) {
1098
+ return Utils.$$Math.minOptInt(headBlockNumber, queryEndBlock);
1099
+ } else {
1100
+ return queryEndBlock;
1101
+ }
1102
+ };
1103
+ let existingReservedByPartition = {};
1104
+ let chainReserved = 0;
1105
+ for (let idx$1 = 0; idx$1 < partitionsCount; ++idx$1) {
1106
+ let partitionId$1 = optimizedPartitions.idsInAscOrder[idx$1];
1107
+ let p$1 = optimizedPartitions.entities[partitionId$1];
1108
+ let cost = 0;
1109
+ for (let pqIdx = 0, pqIdx_finish = p$1.mutPendingQueries.length; pqIdx < pqIdx_finish; ++pqIdx) {
1110
+ cost = cost + p$1.mutPendingQueries[pqIdx].itemsEst;
1111
+ }
1112
+ existingReservedByPartition[partitionId$1] = cost;
1113
+ chainReserved = chainReserved + cost;
1114
+ }
1115
+ let fillStates = [];
1116
+ let gapFillCost = 0;
1117
+ for (let idx$2 = 0; idx$2 < partitionsCount; ++idx$2) {
1118
+ let partitionId$2 = optimizedPartitions.idsInAscOrder[idx$2];
1119
+ let p$2 = optimizedPartitions.entities[partitionId$2];
1120
+ let bucket = queriesByPartitionIndex[idx$2];
1121
+ let pendingCount = p$2.mutPendingQueries.length;
1122
+ let queryEndBlock = computeQueryEndBlock(p$2);
1123
+ let maybeChunkRange = getMinHistoryRange(p$2);
1124
+ let cursor = p$2.latestFetchedBlock.blockNumber + 1 | 0;
1079
1125
  let canContinue = true;
1080
- let pqIdx = 0;
1081
- while (pqIdx < p.mutPendingQueries.length && canContinue) {
1082
- let pq = p.mutPendingQueries[pqIdx];
1126
+ let chunksUsedThisCall = 0;
1127
+ let pqIdx$1 = 0;
1128
+ while (pqIdx$1 < pendingCount && canContinue) {
1129
+ let pq = p$2.mutPendingQueries[pqIdx$1];
1083
1130
  if (pq.fromBlock > cursor) {
1084
- let addressesByContractName = p.addressesByContractName;
1085
- let selection = p.selection;
1086
- let rangeEndBlock = Utils.$$Math.minOptInt(pq.fromBlock - 1 | 0, queryEndBlock$2);
1087
- let rangeFromBlock = cursor;
1088
- if (rangeFromBlock <= maxQueryBlockNumber) {
1089
- let exit = 0;
1090
- if (!(rangeEndBlock !== undefined && rangeFromBlock > rangeEndBlock)) {
1091
- exit = 1;
1092
- }
1093
- if (exit === 1) {
1094
- if (maybeChunkRange !== undefined) {
1095
- let maxBlock = rangeEndBlock !== undefined ? rangeEndBlock : maxQueryBlockNumber;
1096
- let chunkSize = Js_math.ceil_int(maybeChunkRange * 1.8);
1097
- let probeSize = Js_math.ceil_int(maybeChunkRange * 0.9);
1098
- let getChunkSize = chunkIdx => {
1099
- if (chunkIdx < 2) {
1100
- return probeSize;
1101
- } else {
1102
- return chunkSize;
1103
- }
1104
- };
1105
- if ((((rangeFromBlock + getChunkSize(0) | 0) + getChunkSize(1) | 0) - 1 | 0) <= maxBlock) {
1106
- let chunkFromBlock = rangeFromBlock;
1107
- let chunkIdx = 0;
1108
- while (chunkIdx < 5 && ((chunkFromBlock + getChunkSize(chunkIdx) | 0) - 1 | 0) <= maxBlock) {
1109
- let chunkToBlock = (chunkFromBlock + getChunkSize(chunkIdx) | 0) - 1 | 0;
1110
- queries.push({
1111
- partitionId: partitionId,
1112
- fromBlock: chunkFromBlock,
1113
- toBlock: chunkToBlock,
1114
- isChunk: true,
1115
- estResponseSize: calculateEstResponseSize(p, chunkFromBlock, chunkToBlock, maxQueryBlockNumber),
1116
- chainId: 0,
1117
- progress: 0,
1118
- selection: selection,
1119
- addressesByContractName: addressesByContractName,
1120
- indexingAddresses: indexingAddresses
1121
- });
1122
- chunkFromBlock = chunkToBlock + 1 | 0;
1123
- chunkIdx = chunkIdx + 1 | 0;
1124
- };
1125
- } else {
1126
- queries.push({
1127
- partitionId: partitionId,
1128
- fromBlock: rangeFromBlock,
1129
- toBlock: rangeEndBlock,
1130
- isChunk: rangeEndBlock !== undefined,
1131
- estResponseSize: calculateEstResponseSize(p, rangeFromBlock, rangeEndBlock, maxQueryBlockNumber),
1132
- chainId: 0,
1133
- progress: 0,
1134
- selection: selection,
1135
- addressesByContractName: addressesByContractName,
1136
- indexingAddresses: indexingAddresses
1137
- });
1138
- }
1139
- } else {
1140
- queries.push({
1141
- partitionId: partitionId,
1142
- fromBlock: rangeFromBlock,
1143
- toBlock: rangeEndBlock,
1144
- isChunk: false,
1145
- estResponseSize: calculateEstResponseSize(p, rangeFromBlock, rangeEndBlock, maxQueryBlockNumber),
1146
- chainId: 0,
1147
- progress: 0,
1148
- selection: selection,
1149
- addressesByContractName: addressesByContractName,
1150
- indexingAddresses: indexingAddresses
1151
- });
1152
- }
1153
- }
1154
- }
1131
+ let beforeLen = bucket.length;
1132
+ let cost$1 = pushGapFillQueries(bucket, partitionId$2, cursor, Utils.$$Math.minOptInt(pq.fromBlock - 1 | 0, queryEndBlock), knownHeight, chainTargetBlock, maybeChunkRange, (12 - pendingCount | 0) - chunksUsedThisCall | 0, p$2, chainTargetItems / partitionsCount, chunkItemsMultiplier, p$2.selection, p$2.addressesByContractName);
1133
+ chunksUsedThisCall = chunksUsedThisCall + (bucket.length - beforeLen | 0) | 0;
1134
+ gapFillCost = gapFillCost + cost$1;
1155
1135
  }
1156
1136
  let toBlock = pq.toBlock;
1157
1137
  if (toBlock !== undefined && pq.isChunk) {
1158
- let match$1 = pq.fetchedBlock;
1159
- if (match$1 !== undefined) {
1160
- let blockNumber = match$1.blockNumber;
1138
+ let match = pq.fetchedBlock;
1139
+ if (match !== undefined) {
1140
+ let blockNumber = match.blockNumber;
1161
1141
  cursor = blockNumber < toBlock ? blockNumber + 1 | 0 : toBlock + 1 | 0;
1162
1142
  } else {
1163
1143
  cursor = toBlock + 1 | 0;
@@ -1165,87 +1145,122 @@ function getNextQuery(fetchState, budget, chainPendingBudget) {
1165
1145
  } else {
1166
1146
  canContinue = false;
1167
1147
  }
1168
- pqIdx = pqIdx + 1 | 0;
1148
+ pqIdx$1 = pqIdx$1 + 1 | 0;
1169
1149
  };
1170
1150
  if (canContinue) {
1171
- let addressesByContractName$1 = p.addressesByContractName;
1172
- let selection$1 = p.selection;
1173
- let rangeFromBlock$1 = cursor;
1174
- if (rangeFromBlock$1 <= maxQueryBlockNumber) {
1175
- let exit$1 = 0;
1176
- if (!(queryEndBlock$2 !== undefined && rangeFromBlock$1 > queryEndBlock$2)) {
1177
- exit$1 = 1;
1178
- }
1179
- if (exit$1 === 1) {
1180
- if (maybeChunkRange !== undefined) {
1181
- let maxBlock$1 = queryEndBlock$2 !== undefined ? queryEndBlock$2 : maxQueryBlockNumber;
1182
- let chunkSize$1 = Js_math.ceil_int(maybeChunkRange * 1.8);
1183
- let probeSize$1 = Js_math.ceil_int(maybeChunkRange * 0.9);
1184
- let getChunkSize$1 = chunkIdx => {
1185
- if (chunkIdx < 2) {
1186
- return probeSize$1;
1187
- } else {
1188
- return chunkSize$1;
1189
- }
1190
- };
1191
- if ((((rangeFromBlock$1 + getChunkSize$1(0) | 0) + getChunkSize$1(1) | 0) - 1 | 0) <= maxBlock$1) {
1192
- let chunkFromBlock$1 = rangeFromBlock$1;
1193
- let chunkIdx$1 = 0;
1194
- while (chunkIdx$1 < 5 && ((chunkFromBlock$1 + getChunkSize$1(chunkIdx$1) | 0) - 1 | 0) <= maxBlock$1) {
1195
- let chunkToBlock$1 = (chunkFromBlock$1 + getChunkSize$1(chunkIdx$1) | 0) - 1 | 0;
1196
- queries.push({
1197
- partitionId: partitionId,
1198
- fromBlock: chunkFromBlock$1,
1199
- toBlock: chunkToBlock$1,
1200
- isChunk: true,
1201
- estResponseSize: calculateEstResponseSize(p, chunkFromBlock$1, chunkToBlock$1, maxQueryBlockNumber),
1202
- chainId: 0,
1203
- progress: 0,
1204
- selection: selection$1,
1205
- addressesByContractName: addressesByContractName$1,
1206
- indexingAddresses: indexingAddresses
1207
- });
1208
- chunkFromBlock$1 = chunkToBlock$1 + 1 | 0;
1209
- chunkIdx$1 = chunkIdx$1 + 1 | 0;
1210
- };
1211
- } else {
1212
- queries.push({
1213
- partitionId: partitionId,
1214
- fromBlock: rangeFromBlock$1,
1215
- toBlock: queryEndBlock$2,
1216
- isChunk: queryEndBlock$2 !== undefined,
1217
- estResponseSize: calculateEstResponseSize(p, rangeFromBlock$1, queryEndBlock$2, maxQueryBlockNumber),
1218
- chainId: 0,
1219
- progress: 0,
1220
- selection: selection$1,
1221
- addressesByContractName: addressesByContractName$1,
1222
- indexingAddresses: indexingAddresses
1223
- });
1224
- }
1225
- } else {
1226
- queries.push({
1227
- partitionId: partitionId,
1228
- fromBlock: rangeFromBlock$1,
1229
- toBlock: queryEndBlock$2,
1230
- isChunk: false,
1231
- estResponseSize: calculateEstResponseSize(p, rangeFromBlock$1, queryEndBlock$2, maxQueryBlockNumber),
1232
- chainId: 0,
1233
- progress: 0,
1234
- selection: selection$1,
1235
- addressesByContractName: addressesByContractName$1,
1236
- indexingAddresses: indexingAddresses
1237
- });
1238
- }
1239
- }
1240
- }
1151
+ fillStates.push({
1152
+ partitionId: partitionId$2,
1153
+ p: p$2,
1154
+ cursor: cursor,
1155
+ chunksUsedThisCall: chunksUsedThisCall,
1156
+ pendingCount: pendingCount,
1157
+ queryEndBlock: queryEndBlock,
1158
+ maybeChunkRange: maybeChunkRange,
1159
+ bucket: bucket
1160
+ });
1241
1161
  }
1242
- let maxNewChunks = Primitive_int.max(0, 10 - pendingCount | 0);
1243
- let generatedCount = queries.length - partitionQueriesStart | 0;
1244
- if (generatedCount > maxNewChunks) {
1245
- queries.splice(partitionQueriesStart + maxNewChunks | 0, generatedCount - maxNewChunks | 0);
1162
+ }
1163
+ let rangeItemsTarget = Primitive_float.max(0, chainTargetItems - chainReserved - gapFillCost);
1164
+ let reservedByPartition = {};
1165
+ fillStates.forEach(fs => {
1166
+ let cost = existingReservedByPartition[fs.partitionId];
1167
+ for (let i = 0, i_finish = fs.bucket.length; i < i_finish; ++i) {
1168
+ cost = cost + fs.bucket[i].itemsEst;
1246
1169
  }
1247
- idxRef = idxRef + 1 | 0;
1170
+ reservedByPartition[fs.partitionId] = cost;
1171
+ });
1172
+ let isInRange = fs => {
1173
+ let tmp = false;
1174
+ if (fs.cursor <= chainTargetBlock) {
1175
+ let eb = fs.queryEndBlock;
1176
+ tmp = eb !== undefined ? fs.cursor <= eb : true;
1177
+ }
1178
+ if (tmp) {
1179
+ return (fs.pendingCount + fs.chunksUsedThisCall | 0) < 12;
1180
+ } else {
1181
+ return false;
1182
+ }
1183
+ };
1184
+ let inRangeStates = fillStates.filter(isInRange);
1185
+ let emitQueries = (fs, budget) => {
1186
+ let p = fs.p;
1187
+ let eb = fs.queryEndBlock;
1188
+ let maxBlock = eb !== undefined ? eb : chainTargetBlock;
1189
+ let match = fs.maybeChunkRange;
1190
+ let match$1 = getTrustedDensity(p);
1191
+ if (match !== undefined && match$1 !== undefined && match$1 > 0) {
1192
+ let chunkSize = Js_math.ceil_int(match * 1.8);
1193
+ let maxChunksRemaining = (12 - fs.pendingCount | 0) - fs.chunksUsedThisCall | 0;
1194
+ let consumed = 0;
1195
+ let created = 0;
1196
+ let chunkFromBlock = fs.cursor;
1197
+ let budgetLeft = true;
1198
+ while (budgetLeft && created < maxChunksRemaining && chunkFromBlock <= Primitive_int.min(maxBlock, chainTargetBlock)) {
1199
+ let chunkToBlock = Primitive_int.min((chunkFromBlock + chunkSize | 0) - 1 | 0, maxBlock);
1200
+ let rawEst = match$1 * ((chunkToBlock - chunkFromBlock | 0) + 1 | 0);
1201
+ let itemsEst = Primitive_int.max(1, Math.ceil(rawEst) | 0);
1202
+ let itemsTarget = Primitive_int.max(1, Math.ceil(rawEst * chunkItemsMultiplier) | 0);
1203
+ if (consumed === 0 || consumed + itemsEst <= budget) {
1204
+ fs.bucket.push({
1205
+ partitionId: fs.partitionId,
1206
+ fromBlock: chunkFromBlock,
1207
+ toBlock: chunkToBlock,
1208
+ isChunk: true,
1209
+ itemsTarget: itemsTarget,
1210
+ itemsEst: itemsEst,
1211
+ selection: p.selection,
1212
+ addressesByContractName: p.addressesByContractName
1213
+ });
1214
+ consumed = consumed + itemsEst;
1215
+ chunkFromBlock = chunkToBlock + 1 | 0;
1216
+ created = created + 1 | 0;
1217
+ } else {
1218
+ budgetLeft = false;
1219
+ }
1220
+ };
1221
+ fs.cursor = chunkFromBlock;
1222
+ fs.chunksUsedThisCall = fs.chunksUsedThisCall + created | 0;
1223
+ return consumed;
1224
+ }
1225
+ let itemsTarget$1 = Primitive_int.max(1, Math.round(budget) | 0);
1226
+ fs.bucket.push({
1227
+ partitionId: fs.partitionId,
1228
+ fromBlock: fs.cursor,
1229
+ toBlock: fs.queryEndBlock,
1230
+ isChunk: false,
1231
+ itemsTarget: itemsTarget$1,
1232
+ itemsEst: itemsTarget$1,
1233
+ selection: p.selection,
1234
+ addressesByContractName: p.addressesByContractName
1235
+ });
1236
+ fs.cursor = maxBlock + 1 | 0;
1237
+ fs.chunksUsedThisCall = fs.chunksUsedThisCall + 1 | 0;
1238
+ return itemsTarget$1;
1239
+ };
1240
+ let notFilledPartitions = inRangeStates;
1241
+ let remainingBudget = {
1242
+ contents: rangeItemsTarget
1248
1243
  };
1244
+ while (notFilledPartitions.length !== 0 && remainingBudget.contents > 0) {
1245
+ let level = waterLevel(remainingBudget.contents, notFilledPartitions.map(fs => reservedByPartition[fs.partitionId]));
1246
+ let next = [];
1247
+ notFilledPartitions.forEach(fs => {
1248
+ let reserved = reservedByPartition[fs.partitionId];
1249
+ let budget = level - reserved;
1250
+ if (budget <= 0) {
1251
+ return;
1252
+ }
1253
+ let consumed = emitQueries(fs, budget);
1254
+ reservedByPartition[fs.partitionId] = reserved + consumed;
1255
+ remainingBudget.contents = remainingBudget.contents - consumed;
1256
+ if (isInRange(fs)) {
1257
+ next.push(fs);
1258
+ return;
1259
+ }
1260
+ });
1261
+ notFilledPartitions = next;
1262
+ };
1263
+ let queries = queriesByPartitionIndex.flat();
1249
1264
  if (Utils.$$Array.isEmpty(queries)) {
1250
1265
  if (shouldWaitForNewBlock) {
1251
1266
  return "WaitingForNewBlock";
@@ -1292,9 +1307,9 @@ function getReadyItemsCount(fetchState, targetSize, fromItem) {
1292
1307
  return acc;
1293
1308
  }
1294
1309
 
1295
- function make$1(startBlock, endBlock, eventConfigs, addresses, maxAddrInPartition, chainId, maxOnBlockBufferSize, knownHeight, progressBlockNumberOpt, onBlockConfigsOpt, blockLagOpt, firstEventBlockOpt) {
1310
+ function make$1(startBlock, endBlock, onEventRegistrations, contractConfigs, addresses, maxAddrInPartition, chainId, maxOnBlockBufferSize, knownHeight, progressBlockNumberOpt, onBlockRegistrationsOpt, blockLagOpt, firstEventBlockOpt) {
1296
1311
  let progressBlockNumber = progressBlockNumberOpt !== undefined ? progressBlockNumberOpt : startBlock - 1 | 0;
1297
- let onBlockConfigs = onBlockConfigsOpt !== undefined ? onBlockConfigsOpt : [];
1312
+ let onBlockRegistrations = onBlockRegistrationsOpt !== undefined ? onBlockRegistrationsOpt : [];
1298
1313
  let blockLag = blockLagOpt !== undefined ? blockLagOpt : 0;
1299
1314
  let firstEventBlock = firstEventBlockOpt !== undefined ? Primitive_option.valFromOption(firstEventBlockOpt) : undefined;
1300
1315
  let latestFetchedBlock = {
@@ -1302,32 +1317,14 @@ function make$1(startBlock, endBlock, eventConfigs, addresses, maxAddrInPartitio
1302
1317
  blockTimestamp: 0
1303
1318
  };
1304
1319
  let notDependingOnAddresses = [];
1305
- let normalEventConfigs = [];
1320
+ let normalRegistrations = [];
1306
1321
  let contractNamesWithNormalEvents = new Set();
1307
- let indexingAddresses = {};
1308
- let contractConfigs = {};
1309
- eventConfigs.forEach(ec => {
1310
- let match = contractConfigs[ec.contractName];
1311
- if (match !== undefined) {
1312
- let startBlock = match.startBlock;
1313
- let match$1 = ec.startBlock;
1314
- contractConfigs[ec.contractName] = {
1315
- startBlock: startBlock !== undefined ? (
1316
- match$1 !== undefined ? Primitive_int.min(startBlock, match$1) : startBlock
1317
- ) : (
1318
- match$1 !== undefined ? match$1 : undefined
1319
- )
1320
- };
1321
- } else {
1322
- contractConfigs[ec.contractName] = {
1323
- startBlock: ec.startBlock
1324
- };
1325
- }
1326
- if (ec.dependsOnAddresses) {
1327
- normalEventConfigs.push(ec);
1328
- contractNamesWithNormalEvents.add(ec.contractName);
1322
+ onEventRegistrations.forEach(reg => {
1323
+ if (reg.dependsOnAddresses) {
1324
+ normalRegistrations.push(reg);
1325
+ contractNamesWithNormalEvents.add(reg.eventConfig.contractName);
1329
1326
  } else {
1330
- notDependingOnAddresses.push(ec);
1327
+ notDependingOnAddresses.push(reg);
1331
1328
  }
1332
1329
  });
1333
1330
  let partitions = [];
@@ -1336,7 +1333,7 @@ function make$1(startBlock, endBlock, eventConfigs, addresses, maxAddrInPartitio
1336
1333
  id: partitions.length.toString(),
1337
1334
  latestFetchedBlock: latestFetchedBlock,
1338
1335
  selection: {
1339
- eventConfigs: notDependingOnAddresses,
1336
+ onEventRegistrations: notDependingOnAddresses,
1340
1337
  dependsOnAddresses: false
1341
1338
  },
1342
1339
  addressesByContractName: {},
@@ -1350,47 +1347,34 @@ function make$1(startBlock, endBlock, eventConfigs, addresses, maxAddrInPartitio
1350
1347
  });
1351
1348
  }
1352
1349
  let normalSelection = {
1353
- eventConfigs: normalEventConfigs,
1350
+ onEventRegistrations: normalRegistrations,
1354
1351
  dependsOnAddresses: true
1355
1352
  };
1356
1353
  let registeringContractsByContract = {};
1357
1354
  let dynamicContracts = new Set();
1358
1355
  addresses.forEach(contract => {
1359
1356
  let contractName = contract.contractName;
1360
- let match = contractConfigs[contractName];
1361
- let contractStartBlock = match !== undefined ? match.startBlock : undefined;
1362
- let ia_address = contract.address;
1363
- let ia_contractName = contract.contractName;
1364
- let ia_registrationBlock = contract.registrationBlock;
1365
- let ia_effectiveStartBlock = deriveEffectiveStartBlock(contract.registrationBlock, contractStartBlock);
1366
- let ia = {
1367
- address: ia_address,
1368
- contractName: ia_contractName,
1369
- registrationBlock: ia_registrationBlock,
1370
- effectiveStartBlock: ia_effectiveStartBlock
1371
- };
1372
- indexingAddresses[contract.address] = ia;
1373
- if (!contractNamesWithNormalEvents.has(contractName)) {
1374
- return;
1375
- }
1376
- let registeringContracts = Utils.Dict.getOrInsertEmptyDict(registeringContractsByContract, contractName);
1377
- registeringContracts[contract.address] = ia;
1378
- if (contract.registrationBlock !== -1) {
1379
- dynamicContracts.add(contractName);
1380
- return;
1357
+ if (contractNamesWithNormalEvents.has(contractName)) {
1358
+ Utils.Dict.getOrInsertEmptyDict(registeringContractsByContract, contractName)[contract.address] = IndexingAddresses.makeIndexingAddress(contract, contractConfigs);
1359
+ if (contract.registrationBlock !== -1) {
1360
+ dynamicContracts.add(contractName);
1361
+ return;
1362
+ } else {
1363
+ return;
1364
+ }
1381
1365
  }
1382
1366
  });
1383
1367
  let optimizedPartitions = createPartitionsFromIndexingAddresses(registeringContractsByContract, dynamicContracts, normalSelection, maxAddrInPartition, partitions.length, partitions, progressBlockNumber);
1384
- if (optimizedPartitions.idsInAscOrder.length === 0 && Utils.$$Array.isEmpty(onBlockConfigs)) {
1385
- Stdlib_JsError.throwWithMessage(`Invalid configuration: Nothing to fetch on chain ` + chainId.toString() + `. ` + (`addresses=` + addresses.length.toString() + `, `) + (`eventConfigs=` + eventConfigs.length.toString() + `, `) + (`normalEventConfigs=` + normalEventConfigs.length.toString() + `. `) + `Make sure that you provided at least one contract address to index, or have events with Wildcard mode enabled, or have onBlock handlers.`);
1368
+ if (optimizedPartitions.idsInAscOrder.length === 0 && Utils.$$Array.isEmpty(onBlockRegistrations)) {
1369
+ Stdlib_JsError.throwWithMessage(`Invalid configuration: Nothing to fetch on chain ` + chainId.toString() + `. ` + (`addresses=` + addresses.length.toString() + `, `) + (`onEventRegistrations=` + onEventRegistrations.length.toString() + `, `) + (`normalRegistrations=` + normalRegistrations.length.toString() + `. `) + `Make sure that you provided at least one contract address to index, or have events with Wildcard mode enabled, or have onBlock handlers.`);
1386
1370
  }
1387
1371
  let buffer = [];
1388
1372
  let latestOnBlockBlockNumber;
1389
- if (knownHeight > 0 && Utils.$$Array.notEmpty(onBlockConfigs)) {
1373
+ if (knownHeight > 0 && Utils.$$Array.notEmpty(onBlockRegistrations)) {
1390
1374
  let id = optimizedPartitions.idsInAscOrder[0];
1391
1375
  let latestFullyFetchedBlock = id !== undefined ? optimizedPartitions.entities[id].latestFetchedBlock : undefined;
1392
1376
  let maxBlockNumber = latestFullyFetchedBlock !== undefined ? latestFullyFetchedBlock.blockNumber : knownHeight;
1393
- latestOnBlockBlockNumber = appendOnBlockItems(buffer, onBlockConfigs, startBlock, progressBlockNumber, maxBlockNumber, maxOnBlockBufferSize);
1377
+ latestOnBlockBlockNumber = appendOnBlockItems(buffer, onBlockRegistrations, startBlock, progressBlockNumber, maxBlockNumber, maxOnBlockBufferSize);
1394
1378
  } else {
1395
1379
  latestOnBlockBlockNumber = progressBlockNumber;
1396
1380
  }
@@ -1399,19 +1383,16 @@ function make$1(startBlock, endBlock, eventConfigs, addresses, maxAddrInPartitio
1399
1383
  startBlock: startBlock,
1400
1384
  endBlock: endBlock,
1401
1385
  normalSelection: normalSelection,
1402
- indexingAddresses: indexingAddresses,
1403
1386
  contractConfigs: contractConfigs,
1404
1387
  chainId: chainId,
1405
1388
  latestOnBlockBlockNumber: latestOnBlockBlockNumber,
1406
1389
  blockLag: blockLag,
1407
1390
  buffer: buffer,
1408
1391
  maxOnBlockBufferSize: maxOnBlockBufferSize,
1409
- onBlockConfigs: onBlockConfigs,
1392
+ onBlockRegistrations: onBlockRegistrations,
1410
1393
  knownHeight: knownHeight,
1411
1394
  firstEventBlock: firstEventBlock
1412
1395
  };
1413
- let numAddresses = Utils.Dict.size(indexingAddresses);
1414
- Prometheus.IndexingAddresses.set(numAddresses, chainId);
1415
1396
  Prometheus.IndexingPartitions.set(optimizedPartitions.idsInAscOrder.length, chainId);
1416
1397
  Prometheus.IndexingBufferSize.set(buffer.length, chainId);
1417
1398
  Prometheus.IndexingBufferBlockNumber.set(bufferBlockNumber(fetchState), chainId);
@@ -1425,22 +1406,6 @@ function bufferSize(param) {
1425
1406
  return param.buffer.length;
1426
1407
  }
1427
1408
 
1428
- function bufferReadyCount(fetchState) {
1429
- let frontier = bufferBlockNumber(fetchState);
1430
- let buffer = fetchState.buffer;
1431
- let lo = 0;
1432
- let hi = buffer.length;
1433
- while (lo < hi) {
1434
- let mid = (lo + hi | 0) / 2 | 0;
1435
- if (buffer[mid].blockNumber <= frontier) {
1436
- lo = mid + 1 | 0;
1437
- } else {
1438
- hi = mid;
1439
- }
1440
- };
1441
- return lo;
1442
- }
1443
-
1444
1409
  function rollbackPendingQueries(mutPendingQueries, targetBlockNumber) {
1445
1410
  let adjusted = [];
1446
1411
  for (let qIdx = 0, qIdx_finish = mutPendingQueries.length; qIdx < qIdx_finish; ++qIdx) {
@@ -1453,7 +1418,8 @@ function rollbackPendingQueries(mutPendingQueries, targetBlockNumber) {
1453
1418
  fromBlock: pq.fromBlock,
1454
1419
  toBlock: pq.toBlock,
1455
1420
  isChunk: pq.isChunk,
1456
- estResponseSize: pq.estResponseSize,
1421
+ itemsTarget: pq.itemsTarget,
1422
+ itemsEst: pq.itemsEst,
1457
1423
  fetchedBlock: {
1458
1424
  blockNumber: targetBlockNumber,
1459
1425
  blockTimestamp: 0
@@ -1470,16 +1436,8 @@ function rollbackPendingQueries(mutPendingQueries, targetBlockNumber) {
1470
1436
  return adjusted;
1471
1437
  }
1472
1438
 
1473
- function rollback(fetchState, targetBlockNumber) {
1474
- let addressesToRemove = new Set();
1475
- let indexingAddresses = {};
1476
- Utils.Dict.forEachWithKey(fetchState.indexingAddresses, (indexingContract, address) => {
1477
- if (indexingContract.registrationBlock > targetBlockNumber) {
1478
- addressesToRemove.add(address);
1479
- } else {
1480
- indexingAddresses[address] = indexingContract;
1481
- }
1482
- });
1439
+ function rollback(fetchState, indexingAddresses, targetBlockNumber) {
1440
+ IndexingAddresses.rollbackInPlace(indexingAddresses, targetBlockNumber);
1483
1441
  let keptPartitions = [];
1484
1442
  let nextKeptIdRef = 0;
1485
1443
  let registeringContractsByContract = {};
@@ -1490,11 +1448,12 @@ function rollback(fetchState, targetBlockNumber) {
1490
1448
  if (p.latestFetchedBlock.blockNumber > targetBlockNumber) {
1491
1449
  Utils.Dict.forEachWithKey(p.addressesByContractName, (addresses, contractName) => {
1492
1450
  addresses.forEach(address => {
1493
- if (!(!addressesToRemove.has(address) && Stdlib_Option.isSome(indexingAddresses[address]))) {
1451
+ let indexingContract = IndexingAddresses.get(indexingAddresses, address);
1452
+ if (indexingContract === undefined) {
1494
1453
  return;
1495
1454
  }
1496
1455
  let registeringContracts = Utils.Dict.getOrInsertEmptyDict(registeringContractsByContract, contractName);
1497
- registeringContracts[address] = indexingAddresses[address];
1456
+ registeringContracts[address] = indexingContract;
1498
1457
  });
1499
1458
  });
1500
1459
  } else {
@@ -1502,7 +1461,7 @@ function rollback(fetchState, targetBlockNumber) {
1502
1461
  let mergeBlock$1 = mergeBlock !== undefined && mergeBlock > targetBlockNumber ? targetBlockNumber : mergeBlock;
1503
1462
  let rollbackedAddressesByContractName = {};
1504
1463
  Utils.Dict.forEachWithKey(p.addressesByContractName, (addresses, contractName) => {
1505
- let keptAddresses = addresses.filter(address => !addressesToRemove.has(address));
1464
+ let keptAddresses = addresses.filter(address => Stdlib_Option.isSome(IndexingAddresses.get(indexingAddresses, address)));
1506
1465
  if (keptAddresses.length !== 0) {
1507
1466
  rollbackedAddressesByContractName[contractName] = keptAddresses;
1508
1467
  return;
@@ -1553,17 +1512,16 @@ function rollback(fetchState, targetBlockNumber) {
1553
1512
  startBlock: fetchState.startBlock,
1554
1513
  endBlock: fetchState.endBlock,
1555
1514
  normalSelection: fetchState.normalSelection,
1556
- indexingAddresses: fetchState.indexingAddresses,
1557
1515
  contractConfigs: fetchState.contractConfigs,
1558
1516
  chainId: fetchState.chainId,
1559
1517
  latestOnBlockBlockNumber: Primitive_int.min(fetchState.latestOnBlockBlockNumber, targetBlockNumber),
1560
1518
  blockLag: fetchState.blockLag,
1561
1519
  buffer: fetchState.buffer,
1562
1520
  maxOnBlockBufferSize: fetchState.maxOnBlockBufferSize,
1563
- onBlockConfigs: fetchState.onBlockConfigs,
1521
+ onBlockRegistrations: fetchState.onBlockRegistrations,
1564
1522
  knownHeight: fetchState.knownHeight,
1565
1523
  firstEventBlock: fetchState.firstEventBlock
1566
- }, optimizedPartitions, indexingAddresses, fetchState.buffer.filter(item => {
1524
+ }, optimizedPartitions, fetchState.buffer.filter(item => {
1567
1525
  let tmp;
1568
1526
  tmp = item.kind === 0 ? item.blockNumber : item.blockNumber;
1569
1527
  return tmp <= targetBlockNumber;
@@ -1604,14 +1562,13 @@ function resetPendingQueries(fetchState) {
1604
1562
  startBlock: fetchState.startBlock,
1605
1563
  endBlock: fetchState.endBlock,
1606
1564
  normalSelection: fetchState.normalSelection,
1607
- indexingAddresses: fetchState.indexingAddresses,
1608
1565
  contractConfigs: fetchState.contractConfigs,
1609
1566
  chainId: fetchState.chainId,
1610
1567
  latestOnBlockBlockNumber: fetchState.latestOnBlockBlockNumber,
1611
1568
  blockLag: fetchState.blockLag,
1612
1569
  buffer: fetchState.buffer,
1613
1570
  maxOnBlockBufferSize: fetchState.maxOnBlockBufferSize,
1614
- onBlockConfigs: fetchState.onBlockConfigs,
1571
+ onBlockRegistrations: fetchState.onBlockRegistrations,
1615
1572
  knownHeight: fetchState.knownHeight,
1616
1573
  firstEventBlock: fetchState.firstEventBlock
1617
1574
  };
@@ -1674,19 +1631,6 @@ function getProgressPercentage(fetchState) {
1674
1631
  return progress / totalRange;
1675
1632
  }
1676
1633
 
1677
- function getProgressPercentageAt(fetchState, blockNumber) {
1678
- let firstEventBlock = fetchState.firstEventBlock;
1679
- if (firstEventBlock === undefined) {
1680
- return 0;
1681
- }
1682
- let totalRange = fetchState.knownHeight - firstEventBlock | 0;
1683
- if (totalRange <= 0) {
1684
- return 0;
1685
- } else {
1686
- return (blockNumber - firstEventBlock | 0) / totalRange;
1687
- }
1688
- }
1689
-
1690
1634
  function hasFullBatch(fetchState, batchSizeTarget) {
1691
1635
  let item = fetchState.buffer[batchSizeTarget - 1 | 0];
1692
1636
  if (item !== undefined) {
@@ -1734,30 +1678,28 @@ function getProgressBlockNumberAt(fetchState, index) {
1734
1678
  function updateKnownHeight(fetchState, knownHeight) {
1735
1679
  if (knownHeight > fetchState.knownHeight) {
1736
1680
  Prometheus.IndexingKnownHeight.set(knownHeight, fetchState.chainId);
1737
- return updateInternal(fetchState, undefined, undefined, undefined, undefined, knownHeight);
1681
+ return updateInternal(fetchState, undefined, undefined, undefined, knownHeight);
1738
1682
  } else {
1739
1683
  return fetchState;
1740
1684
  }
1741
1685
  }
1742
1686
 
1743
- let defaultEstResponseSize = 10000;
1744
-
1745
1687
  let blockItemLogIndex = 16777216;
1746
1688
 
1747
- let maxPendingChunksPerPartition = 10;
1689
+ let maxPendingChunksPerPartition = 12;
1748
1690
 
1749
1691
  export {
1750
- deriveEffectiveStartBlock,
1751
- defaultEstResponseSize,
1752
- calculateEstResponseSize,
1692
+ deriveContractNameByAddress,
1693
+ densityItemsTarget,
1753
1694
  getMinHistoryRange,
1695
+ getTrustedDensity,
1754
1696
  getMinQueryRange,
1755
1697
  OptimizedPartitions,
1756
1698
  bufferBlockNumber,
1757
1699
  bufferBlock,
1700
+ bufferReadyCount,
1758
1701
  compareBufferItem,
1759
1702
  blockItemLogIndex,
1760
- numAddresses,
1761
1703
  appendOnBlockItems,
1762
1704
  updateInternal,
1763
1705
  warnDifferentContractType,
@@ -1767,14 +1709,14 @@ export {
1767
1709
  registerDynamicContracts,
1768
1710
  handleQueryResult,
1769
1711
  startFetchingQueries,
1770
- pushQueriesForRange,
1771
1712
  maxPendingChunksPerPartition,
1713
+ pushGapFillQueries,
1714
+ waterLevel,
1772
1715
  getNextQuery,
1773
1716
  hasReadyItem,
1774
1717
  getReadyItemsCount,
1775
1718
  make$1 as make,
1776
1719
  bufferSize,
1777
- bufferReadyCount,
1778
1720
  rollbackPendingQueries,
1779
1721
  rollback,
1780
1722
  resetPendingQueries,
@@ -1782,9 +1724,8 @@ export {
1782
1724
  isFetchingAtHead,
1783
1725
  isReadyToEnterReorgThreshold,
1784
1726
  getProgressPercentage,
1785
- getProgressPercentageAt,
1786
1727
  sortForBatch,
1787
1728
  getProgressBlockNumberAt,
1788
1729
  updateKnownHeight,
1789
1730
  }
1790
- /* Utils Not a pure module */
1731
+ /* deriveContractNameByAddress Not a pure module */