@xyo-network/chain-sdk 4.0.6 → 4.2.1

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 (140) hide show
  1. package/dist/browser/modules/ethereum/block/findContractDeploymentBlock.d.ts +25 -0
  2. package/dist/browser/modules/ethereum/block/findContractDeploymentBlock.d.ts.map +1 -0
  3. package/dist/browser/modules/ethereum/block/index.d.ts +1 -0
  4. package/dist/browser/modules/ethereum/block/index.d.ts.map +1 -1
  5. package/dist/browser/modules/ethereum/drivers/EvmStakeEventZod.d.ts +12 -12
  6. package/dist/browser/modules/ethereum/drivers/EvmStakeEventsViewer.d.ts +44 -14
  7. package/dist/browser/modules/ethereum/drivers/EvmStakeEventsViewer.d.ts.map +1 -1
  8. package/dist/browser/modules/ethereum/drivers/EvmStakeViewer.d.ts +1 -1
  9. package/dist/browser/modules/ethereum/drivers/EvmStakeViewer.d.ts.map +1 -1
  10. package/dist/browser/modules/ethereum/index.d.ts +2 -0
  11. package/dist/browser/modules/ethereum/index.d.ts.map +1 -1
  12. package/dist/browser/modules/ethereum/indexing/EvmEventIndexModel.d.ts +107 -0
  13. package/dist/browser/modules/ethereum/indexing/EvmEventIndexModel.d.ts.map +1 -0
  14. package/dist/browser/modules/ethereum/indexing/EvmEventIndexPaths.d.ts +6 -0
  15. package/dist/browser/modules/ethereum/indexing/EvmEventIndexPaths.d.ts.map +1 -0
  16. package/dist/browser/modules/ethereum/indexing/EvmEventIndexPublishRunner.d.ts +9 -0
  17. package/dist/browser/modules/ethereum/indexing/EvmEventIndexPublishRunner.d.ts.map +1 -0
  18. package/dist/browser/modules/ethereum/indexing/RestStakeEventsViewer.d.ts +54 -0
  19. package/dist/browser/modules/ethereum/indexing/RestStakeEventsViewer.d.ts.map +1 -0
  20. package/dist/browser/modules/ethereum/indexing/index.d.ts +5 -0
  21. package/dist/browser/modules/ethereum/indexing/index.d.ts.map +1 -0
  22. package/dist/browser/modules/ethereum/providers/AbstractEvmProvider.d.ts +4 -1
  23. package/dist/browser/modules/ethereum/providers/AbstractEvmProvider.d.ts.map +1 -1
  24. package/dist/browser/modules/ethereum/providers/AbstractEvmViewer.d.ts +5 -1
  25. package/dist/browser/modules/ethereum/providers/AbstractEvmViewer.d.ts.map +1 -1
  26. package/dist/browser/modules/ethereum/providers/EvmChainContractViewer.d.ts +1 -2
  27. package/dist/browser/modules/ethereum/providers/EvmChainContractViewer.d.ts.map +1 -1
  28. package/dist/browser/modules/ethereum/providers/EvmStakeTotalsViewer.d.ts +1 -1
  29. package/dist/browser/modules/ethereum/providers/EvmStakeTotalsViewer.d.ts.map +1 -1
  30. package/dist/browser/modules/ethereum/rpc/index.d.ts +4 -0
  31. package/dist/browser/modules/ethereum/rpc/index.d.ts.map +1 -0
  32. package/dist/browser/modules/ethereum/rpc/isRpcRangeLimitError.d.ts +15 -0
  33. package/dist/browser/modules/ethereum/rpc/isRpcRangeLimitError.d.ts.map +1 -0
  34. package/dist/browser/modules/ethereum/rpc/isRpcRateLimitError.d.ts +1 -1
  35. package/dist/browser/modules/services/ChainValidator/XyoValidator.d.ts +7 -1
  36. package/dist/browser/modules/services/ChainValidator/XyoValidator.d.ts.map +1 -1
  37. package/dist/browser/modules/services/Election/BaseElectionService.d.ts +1 -0
  38. package/dist/browser/modules/services/Election/BaseElectionService.d.ts.map +1 -1
  39. package/dist/browser/modules/services/NetworkStakeStepReward/BaseNetworkStakeStepRewardService.d.ts +1 -2
  40. package/dist/browser/modules/services/NetworkStakeStepReward/BaseNetworkStakeStepRewardService.d.ts.map +1 -1
  41. package/dist/browser/modules/services/implementation/processPendingBlocks.d.ts +4 -4
  42. package/dist/browser/modules/services/simple/block/runner/SimpleBlockRunner.d.ts +5 -2
  43. package/dist/browser/modules/services/simple/block/runner/SimpleBlockRunner.d.ts.map +1 -1
  44. package/dist/browser/modules/services/simple/block/runner/producerTuning.d.ts +13 -0
  45. package/dist/browser/modules/services/simple/block/runner/producerTuning.d.ts.map +1 -0
  46. package/dist/neutral/ethereum.mjs +469 -95
  47. package/dist/neutral/ethereum.mjs.map +4 -4
  48. package/dist/neutral/modules/ethereum/block/findContractDeploymentBlock.d.ts +25 -0
  49. package/dist/neutral/modules/ethereum/block/findContractDeploymentBlock.d.ts.map +1 -0
  50. package/dist/neutral/modules/ethereum/block/index.d.ts +1 -0
  51. package/dist/neutral/modules/ethereum/block/index.d.ts.map +1 -1
  52. package/dist/neutral/modules/ethereum/drivers/EvmStakeEventZod.d.ts +12 -12
  53. package/dist/neutral/modules/ethereum/drivers/EvmStakeEventsViewer.d.ts +44 -14
  54. package/dist/neutral/modules/ethereum/drivers/EvmStakeEventsViewer.d.ts.map +1 -1
  55. package/dist/neutral/modules/ethereum/drivers/EvmStakeViewer.d.ts +1 -1
  56. package/dist/neutral/modules/ethereum/drivers/EvmStakeViewer.d.ts.map +1 -1
  57. package/dist/neutral/modules/ethereum/index.d.ts +2 -0
  58. package/dist/neutral/modules/ethereum/index.d.ts.map +1 -1
  59. package/dist/neutral/modules/ethereum/indexing/EvmEventIndexModel.d.ts +107 -0
  60. package/dist/neutral/modules/ethereum/indexing/EvmEventIndexModel.d.ts.map +1 -0
  61. package/dist/neutral/modules/ethereum/indexing/EvmEventIndexPaths.d.ts +6 -0
  62. package/dist/neutral/modules/ethereum/indexing/EvmEventIndexPaths.d.ts.map +1 -0
  63. package/dist/neutral/modules/ethereum/indexing/EvmEventIndexPublishRunner.d.ts +9 -0
  64. package/dist/neutral/modules/ethereum/indexing/EvmEventIndexPublishRunner.d.ts.map +1 -0
  65. package/dist/neutral/modules/ethereum/indexing/RestStakeEventsViewer.d.ts +54 -0
  66. package/dist/neutral/modules/ethereum/indexing/RestStakeEventsViewer.d.ts.map +1 -0
  67. package/dist/neutral/modules/ethereum/indexing/index.d.ts +5 -0
  68. package/dist/neutral/modules/ethereum/indexing/index.d.ts.map +1 -0
  69. package/dist/neutral/modules/ethereum/providers/AbstractEvmProvider.d.ts +4 -1
  70. package/dist/neutral/modules/ethereum/providers/AbstractEvmProvider.d.ts.map +1 -1
  71. package/dist/neutral/modules/ethereum/providers/AbstractEvmViewer.d.ts +5 -1
  72. package/dist/neutral/modules/ethereum/providers/AbstractEvmViewer.d.ts.map +1 -1
  73. package/dist/neutral/modules/ethereum/providers/EvmChainContractViewer.d.ts +1 -2
  74. package/dist/neutral/modules/ethereum/providers/EvmChainContractViewer.d.ts.map +1 -1
  75. package/dist/neutral/modules/ethereum/providers/EvmStakeTotalsViewer.d.ts +1 -1
  76. package/dist/neutral/modules/ethereum/providers/EvmStakeTotalsViewer.d.ts.map +1 -1
  77. package/dist/neutral/modules/ethereum/rpc/index.d.ts +4 -0
  78. package/dist/neutral/modules/ethereum/rpc/index.d.ts.map +1 -0
  79. package/dist/neutral/modules/ethereum/rpc/isRpcRangeLimitError.d.ts +15 -0
  80. package/dist/neutral/modules/ethereum/rpc/isRpcRangeLimitError.d.ts.map +1 -0
  81. package/dist/neutral/modules/ethereum/rpc/isRpcRateLimitError.d.ts +1 -1
  82. package/dist/neutral/modules/services/ChainValidator/XyoValidator.d.ts +7 -1
  83. package/dist/neutral/modules/services/ChainValidator/XyoValidator.d.ts.map +1 -1
  84. package/dist/neutral/modules/services/Election/BaseElectionService.d.ts +1 -0
  85. package/dist/neutral/modules/services/Election/BaseElectionService.d.ts.map +1 -1
  86. package/dist/neutral/modules/services/NetworkStakeStepReward/BaseNetworkStakeStepRewardService.d.ts +1 -2
  87. package/dist/neutral/modules/services/NetworkStakeStepReward/BaseNetworkStakeStepRewardService.d.ts.map +1 -1
  88. package/dist/neutral/modules/services/implementation/processPendingBlocks.d.ts +4 -4
  89. package/dist/neutral/modules/services/simple/block/runner/SimpleBlockRunner.d.ts +5 -2
  90. package/dist/neutral/modules/services/simple/block/runner/SimpleBlockRunner.d.ts.map +1 -1
  91. package/dist/neutral/modules/services/simple/block/runner/producerTuning.d.ts +13 -0
  92. package/dist/neutral/modules/services/simple/block/runner/producerTuning.d.ts.map +1 -0
  93. package/dist/neutral/services.mjs +46 -13
  94. package/dist/neutral/services.mjs.map +4 -4
  95. package/dist/node/modules/ethereum/block/findContractDeploymentBlock.d.ts +25 -0
  96. package/dist/node/modules/ethereum/block/findContractDeploymentBlock.d.ts.map +1 -0
  97. package/dist/node/modules/ethereum/block/index.d.ts +1 -0
  98. package/dist/node/modules/ethereum/block/index.d.ts.map +1 -1
  99. package/dist/node/modules/ethereum/drivers/EvmStakeEventZod.d.ts +12 -12
  100. package/dist/node/modules/ethereum/drivers/EvmStakeEventsViewer.d.ts +44 -14
  101. package/dist/node/modules/ethereum/drivers/EvmStakeEventsViewer.d.ts.map +1 -1
  102. package/dist/node/modules/ethereum/drivers/EvmStakeViewer.d.ts +1 -1
  103. package/dist/node/modules/ethereum/drivers/EvmStakeViewer.d.ts.map +1 -1
  104. package/dist/node/modules/ethereum/index.d.ts +2 -0
  105. package/dist/node/modules/ethereum/index.d.ts.map +1 -1
  106. package/dist/node/modules/ethereum/indexing/EvmEventIndexModel.d.ts +107 -0
  107. package/dist/node/modules/ethereum/indexing/EvmEventIndexModel.d.ts.map +1 -0
  108. package/dist/node/modules/ethereum/indexing/EvmEventIndexPaths.d.ts +6 -0
  109. package/dist/node/modules/ethereum/indexing/EvmEventIndexPaths.d.ts.map +1 -0
  110. package/dist/node/modules/ethereum/indexing/EvmEventIndexPublishRunner.d.ts +9 -0
  111. package/dist/node/modules/ethereum/indexing/EvmEventIndexPublishRunner.d.ts.map +1 -0
  112. package/dist/node/modules/ethereum/indexing/RestStakeEventsViewer.d.ts +54 -0
  113. package/dist/node/modules/ethereum/indexing/RestStakeEventsViewer.d.ts.map +1 -0
  114. package/dist/node/modules/ethereum/indexing/index.d.ts +5 -0
  115. package/dist/node/modules/ethereum/indexing/index.d.ts.map +1 -0
  116. package/dist/node/modules/ethereum/providers/AbstractEvmProvider.d.ts +4 -1
  117. package/dist/node/modules/ethereum/providers/AbstractEvmProvider.d.ts.map +1 -1
  118. package/dist/node/modules/ethereum/providers/AbstractEvmViewer.d.ts +5 -1
  119. package/dist/node/modules/ethereum/providers/AbstractEvmViewer.d.ts.map +1 -1
  120. package/dist/node/modules/ethereum/providers/EvmChainContractViewer.d.ts +1 -2
  121. package/dist/node/modules/ethereum/providers/EvmChainContractViewer.d.ts.map +1 -1
  122. package/dist/node/modules/ethereum/providers/EvmStakeTotalsViewer.d.ts +1 -1
  123. package/dist/node/modules/ethereum/providers/EvmStakeTotalsViewer.d.ts.map +1 -1
  124. package/dist/node/modules/ethereum/rpc/index.d.ts +4 -0
  125. package/dist/node/modules/ethereum/rpc/index.d.ts.map +1 -0
  126. package/dist/node/modules/ethereum/rpc/isRpcRangeLimitError.d.ts +15 -0
  127. package/dist/node/modules/ethereum/rpc/isRpcRangeLimitError.d.ts.map +1 -0
  128. package/dist/node/modules/ethereum/rpc/isRpcRateLimitError.d.ts +1 -1
  129. package/dist/node/modules/services/ChainValidator/XyoValidator.d.ts +7 -1
  130. package/dist/node/modules/services/ChainValidator/XyoValidator.d.ts.map +1 -1
  131. package/dist/node/modules/services/Election/BaseElectionService.d.ts +1 -0
  132. package/dist/node/modules/services/Election/BaseElectionService.d.ts.map +1 -1
  133. package/dist/node/modules/services/NetworkStakeStepReward/BaseNetworkStakeStepRewardService.d.ts +1 -2
  134. package/dist/node/modules/services/NetworkStakeStepReward/BaseNetworkStakeStepRewardService.d.ts.map +1 -1
  135. package/dist/node/modules/services/implementation/processPendingBlocks.d.ts +4 -4
  136. package/dist/node/modules/services/simple/block/runner/SimpleBlockRunner.d.ts +5 -2
  137. package/dist/node/modules/services/simple/block/runner/SimpleBlockRunner.d.ts.map +1 -1
  138. package/dist/node/modules/services/simple/block/runner/producerTuning.d.ts +13 -0
  139. package/dist/node/modules/services/simple/block/runner/producerTuning.d.ts.map +1 -0
  140. package/package.json +21 -45
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../src/modules/services/BlockReward/EvmBlockRewardViewer.ts", "../../src/modules/services/ChainValidator/XyoValidator.ts", "../../src/modules/services/Election/BaseElectionService.ts", "../../src/modules/services/implementation/head/createBootstrapHead.ts", "../../src/modules/services/implementation/processPendingBlocks.ts", "../../src/modules/services/NetworkStakeStepReward/BaseNetworkStakeStepRewardService.ts", "../../src/modules/services/simple/block/runner/SimpleBlockRunner.ts", "../../src/modules/services/simple/block/runner/generateTransactionFeeTransfers.ts", "../../src/modules/services/simple/block/runner/identifyOffendingTransactions.ts", "../../src/modules/services/StepStake/BaseStepStakeService.ts"],
4
- "sourcesContent": ["import type { CreatableParams } from '@ariestools/sdk'\nimport {\n AbstractCreatable,\n assertEx, creatable, toEthAddress,\n} from '@ariestools/sdk'\nimport { IXyoChainRewards__factory } from '@xyo-network/typechain'\nimport type {\n AttoXL1, BlockRewardViewer,\n ChainContractViewer,\n XL1BlockNumber,\n} from '@xyo-network/xl1-sdk'\nimport {\n asAttoXL1,\n BlockRewardViewerMoniker,\n} from '@xyo-network/xl1-sdk'\nimport type { Provider } from 'ethers/providers'\n\nexport interface EvmBlockRewardViewerParams extends CreatableParams {\n chainContractViewer: ChainContractViewer\n provider: Provider\n}\n\n@creatable()\nexport class EvmBlockRewardViewer extends AbstractCreatable<EvmBlockRewardViewerParams> implements BlockRewardViewer {\n static readonly connectionTypes = ['evm-rpc'] as const\n static readonly defaultMoniker = BlockRewardViewerMoniker\n static readonly monikers = [BlockRewardViewerMoniker]\n static readonly surface = 'node' as const\n moniker = EvmBlockRewardViewer.defaultMoniker\n\n protected _contractAddress: string | undefined\n\n protected get chainContractViewer() {\n return assertEx(this.params.chainContractViewer, () => 'chainContractViewer is required')\n }\n\n protected get contractAddress() {\n return assertEx(this._contractAddress, () => 'contractAddress is required')\n }\n\n protected get provider() {\n return assertEx(this.params.provider, () => 'provider is required')\n }\n\n async allowedRewardForBlock(blockNumber: XL1BlockNumber): Promise<AttoXL1> {\n const contract = IXyoChainRewards__factory.connect(toEthAddress(this.contractAddress), this.provider)\n return asAttoXL1(await contract.calcBlockReward(blockNumber))\n }\n\n override async createHandler() {\n await super.createHandler()\n try {\n this._contractAddress = await this.chainContractViewer.rewardsContract()\n } catch (ex) {\n const error = ex as Error\n throw new Error(`Failed to get rewards contract address: ${error.message}`, { cause: ex })\n }\n }\n}\n", "import type { Promisable } from '@ariestools/sdk'\nimport type {\n BlockBoundWitness,\n BlockViewer, HydratedBlockStateValidationFunction,\n SignedHydratedTransactionWithStorageMeta,\n} from '@xyo-network/xl1-sdk'\nimport { AbstractCreatableProvider, BlockViewerMoniker } from '@xyo-network/xl1-sdk'\n\nimport type { BaseServiceParams } from '../model/index.ts'\nimport type { Validator } from './model/index.ts'\n\nexport interface XyoValidatorParams extends BaseServiceParams {\n // account: AccountInstance\n // blockRewardService: BlockRewardService\n blockViewer: BlockViewer\n // chainId: ChainId\n // electionService: ElectionService\n // pendingBundledTransactionsArchivist: ArchivistInstance\n // stakeIntentService: StakeIntentService\n validateHydratedBlockState: HydratedBlockStateValidationFunction\n}\n\nexport class XyoValidator<TParams extends XyoValidatorParams = XyoValidatorParams> extends AbstractCreatableProvider<TParams> implements Validator {\n moniker = 'Validator'\n private _blockViewer?: BlockViewer\n // get address() {\n // return this.account.address\n // }\n\n // protected get account() {\n // return assertEx(this.params.account, () => 'account is required')\n // }\n\n protected get blockViewer() {\n return this._blockViewer!\n }\n\n // protected get chainInfo() {\n // return assertEx(this.params.chainId, () => 'chainInfo is required')\n // }\n\n // protected get electionService() {\n // return assertEx(this.params.electionService, () => 'electionService is required')\n // }\n\n // protected get pendingBundledTransactionsArchivist() {\n // return assertEx(this.params.pendingBundledTransactionsArchivist, () => 'pendingBundledTransactions is required')\n // }\n\n // protected get blockRewardService() {\n // return assertEx(this.params.blockRewardService, () => 'blockRewardService is required')\n // }\n\n override async createHandler() {\n this._blockViewer = await this.locator.getInstance(BlockViewerMoniker)\n }\n\n validatePendingBlock(_block: BlockBoundWitness): Promisable<Error[]> {\n return [] // await validateBlockProtocol(block, this.chainInfo)\n }\n\n // TODO: Move to validator and inherit this class from validator\n async validatePendingTransaction(hydratedTransaction: SignedHydratedTransactionWithStorageMeta): Promise<boolean> {\n const [tx] = hydratedTransaction\n // Ensure not confirmed already (replay attack)\n if ((await this.blockViewer.blockByHash(tx._hash)) !== undefined) return false\n // TODO: Ensure transaction is valid (double spend, has voucher, has required stake, etc.)\n // TODO: Ensure validator stake is valid\n return await Promise.resolve(true)\n }\n}\n", "import type { Hash } from '@ariestools/sdk'\nimport { assertEx } from '@ariestools/sdk'\nimport type { WithHashMeta, XyoAddress } from '@xyo-network/sdk'\nimport {\n AbstractCreatableProvider,\n type BlockBoundWitness,\n type BlockViewer,\n type ChainStakeViewer, creatableProvider,\n type ElectionService, type StakeIntentService,\n} from '@xyo-network/xl1-sdk'\n\nimport { hexToLast4BytesInt, shuffleWithSeed } from '#utils'\n\nimport type { BaseServiceParams } from '../model/index.ts'\n\nexport interface BaseElectionServicesParams extends BaseServiceParams {\n blockViewer?: BlockViewer\n chainStakeViewer?: ChainStakeViewer\n stakeIntentService?: StakeIntentService\n}\n\n@creatableProvider()\nexport class BaseElectionService extends AbstractCreatableProvider<BaseElectionServicesParams> implements ElectionService {\n static readonly defaultMoniker = 'Election'\n static readonly dependencies = []\n static readonly monikers = ['Election']\n moniker = BaseElectionService.defaultMoniker\n get blockViewer() {\n return assertEx(this.params.blockViewer, () => 'No block viewer')\n }\n\n get chainStakeViewer() {\n return assertEx(this.params.chainStakeViewer, () => 'No chain stake viewer')\n }\n\n get stakeIntentService() {\n return assertEx(this.params.stakeIntentService, () => 'No staked intent service')\n }\n\n async getCreatorCommitteeForNextBlock(current: WithHashMeta<BlockBoundWitness>): Promise<XyoAddress[]> {\n return await this.spanAsync('getCreatorCommitteeForNextBlock', async () => {\n const nextBlock = current.block + 1\n const candidates = await this.stakeIntentService.getDeclaredCandidatesForBlock(nextBlock, 'producer')\n const previousBlockHash = current._hash\n return this.generateCreatorCommittee(candidates, previousBlockHash)\n }, this.context)\n }\n\n protected generateCreatorCommittee(candidates: XyoAddress[], previousBlockHash: Hash, maxSize = 3): XyoAddress[] {\n const creators = new Set<XyoAddress>(candidates)\n const seed = hexToLast4BytesInt(previousBlockHash)\n const creatorArray = shuffleWithSeed(creators, seed)\n return creatorArray.slice(0, maxSize)\n }\n}\n", "import { toAddress } from '@ariestools/sdk'\nimport type { AccountInstance, XyoAddress } from '@xyo-network/sdk'\nimport type {\n AttoXL1, ChainId, SignedHydratedBlockWithHashMeta,\n} from '@xyo-network/xl1-sdk'\nimport { createDeclarationIntent } from '@xyo-network/xl1-sdk'\n\nimport { buildNextBlock, createGenesisBlock } from '#protocol'\n\nexport const createBootstrapHead = async (\n account: AccountInstance,\n chainId: ChainId,\n genesisBlockRewardAmount: AttoXL1,\n genesisBlockRewardAddress: XyoAddress,\n): Promise<SignedHydratedBlockWithHashMeta[]> => {\n const chain: SignedHydratedBlockWithHashMeta[] = []\n\n // Create genesis block\n const genesisBlock = await createGenesisBlock(account, chainId, genesisBlockRewardAmount, genesisBlockRewardAddress)\n chain.push(genesisBlock)\n\n // Create producer declaration block\n const producerDeclarationPayload = createDeclarationIntent(\n toAddress(account.address),\n 'producer',\n genesisBlock[0].block,\n genesisBlock[0].block + 10_000,\n )\n const producerDeclarationBlock = await buildNextBlock(\n genesisBlock[0],\n [],\n [producerDeclarationPayload],\n [account],\n )\n chain.push(producerDeclarationBlock)\n return chain\n}\n", "import type { Address, Logger } from '@ariestools/sdk'\nimport { assertEx, isDefined } from '@ariestools/sdk'\nimport type {\n BaseContext, BlockValidationViewer, BlockViewer, DeadLetterQueueRunner, FinalizationRunner, MempoolViewer,\n} from '@xyo-network/xl1-sdk'\nimport { BlockRejectionSchema, isSignedHydratedBlockWithHashMeta } from '@xyo-network/xl1-sdk'\n\nimport { ChainHeadSelector } from '#analyze'\n\n// type FinalizedBlockAttributes = { producer: Address }\n\ninterface ProcessPendingBlocksParams {\n allowedProducers?: Address[]\n blockValidationViewer: BlockValidationViewer\n blockViewer: BlockViewer\n context: BaseContext\n deadLetterQueueRunner?: DeadLetterQueueRunner\n finalizationRunner: FinalizationRunner\n logger?: Logger\n mempoolViewer: MempoolViewer\n minCandidates?: number\n}\n\n// eslint-disable-next-line complexity\nexport async function processPendingBlocks({\n blockValidationViewer, blockViewer, context, logger, mempoolViewer, finalizationRunner, allowedProducers, minCandidates, deadLetterQueueRunner,\n}: ProcessPendingBlocksParams) {\n const start = Date.now()\n\n const currentBlock = await blockViewer.currentBlock()\n\n const headSelector = new ChainHeadSelector({\n context, logger, mempoolViewer, blockViewer, windowedFinalizedChain: [currentBlock], allowedProducers, minCandidates,\n })\n\n // Use the head selector to find the best head or fallback to the starting head\n const bestHeadChain = await headSelector.findBestHead()\n\n // If we found a head\n if (isDefined(bestHeadChain) && bestHeadChain.length > 0) {\n const oldHeadBlock = currentBlock[0]\n const newHydratedHeadBlock = assertEx(bestHeadChain.at(-1), () => 'Missing best head block [processPendingBlocks]')\n const newHeadBlock = newHydratedHeadBlock[0]\n // let finalizedBlocksAttributes: FinalizedBlockAttributes[] = []\n\n // Synchronize the best head with the outArchivist all the way\n // back to the last finalized block\n\n logger?.debug('Validating new HeadBlock head from (block) ', oldHeadBlock?.block, 'to', newHeadBlock.block)\n logger?.debug('Validating new HeadBlock head from (hash) ', oldHeadBlock?._hash, 'to', newHeadBlock._hash)\n\n if (newHeadBlock._hash === oldHeadBlock?._hash) {\n logger?.debug('No new blocks found', oldHeadBlock?.block, 'to', newHeadBlock.block)\n return\n }\n\n // Store the items to be committed in the correct order\n const candidateBlocks = bestHeadChain.filter((b) => {\n return isDefined(oldHeadBlock) ? b[0].block > oldHeadBlock.block : true\n })\n\n // Validate candidate blocks before finalizing\n const validationResults = await Promise.all(candidateBlocks.map(candidateBlock => Promise.resolve(blockValidationViewer.validateBlocks([candidateBlock], { value: true, state: true }))))\n const blocksToFinalize: typeof candidateBlocks = []\n for (const [i, block] of candidateBlocks.entries()) {\n const result = validationResults[i][0]\n if (isSignedHydratedBlockWithHashMeta(result)) {\n blocksToFinalize.push(block)\n } else {\n logger?.error('Block validation failed', block[0].block, block[0]._hash, JSON.stringify(result, null, 2))\n if (deadLetterQueueRunner) {\n const errors = Array.isArray(result)\n ? result.map(e => ({\n hash: block[0]._hash, name: 'BlockValidationError', message: String(e.message ?? e),\n }))\n : [{ hash: block[0]._hash, name: 'BlockValidationError' }]\n await deadLetterQueueRunner.rejectBlock({\n schema: BlockRejectionSchema, block, errors, rejector: 'validator',\n })\n }\n }\n }\n\n logger?.info('Validated new HeadBlock head from (block) in', `${Date.now() - start}ms`, newHeadBlock.block, 'to', oldHeadBlock?.block)\n logger?.info('Validated new HeadBlock head from (hash) in', `${Date.now() - start}ms`, newHeadBlock._hash, 'to', oldHeadBlock?._hash)\n\n if (blocksToFinalize.length > 0) {\n await finalizationRunner.finalizeBlocks(blocksToFinalize)\n }\n\n // Prevent us from rechecking the same head\n await headSelector.finalizeChainFragment(blocksToFinalize)\n\n // this._startingHead = newHydratedHeadBlock\n\n // Return the finalized payloads\n return blocksToFinalize\n }\n // If no head was found, return an empty array\n logger?.info('No head found to validate', currentBlock?.[0]._hash)\n}\n", "import type { Address, Promisable } from '@ariestools/sdk'\nimport type { ReadArchivist } from '@xyo-network/sdk'\nimport type {\n AttoXL1,\n NetworkStakeStepRewardService,\n StepIdentity,\n StepIdentityString,\n} from '@xyo-network/xl1-sdk'\nimport {\n AbstractCreatableProvider,\n creatableProvider, NetworkStakeStepRewardViewerMoniker,\n} from '@xyo-network/xl1-sdk'\nimport type { Provider } from 'ethers'\n\nimport type { BaseServiceParams } from '../model/index.ts'\n\nexport interface BaseNetworkStakeStepRewardServiceParams extends BaseServiceParams {\n chainArchivist: ReadArchivist\n ethProvider?: Provider\n}\n\n@creatableProvider()\nexport class BaseNetworkStakeStepRewardService extends\n AbstractCreatableProvider<BaseNetworkStakeStepRewardServiceParams> implements NetworkStakeStepRewardService {\n static readonly defaultMoniker = NetworkStakeStepRewardViewerMoniker\n static readonly dependencies = []\n static readonly monikers = [NetworkStakeStepRewardViewerMoniker]\n override moniker = BaseNetworkStakeStepRewardService.defaultMoniker\n\n networkStakeStepRewardAddressHistory(_address: Address): Promisable<Record<Address, AttoXL1>> {\n throw new Error('Method [networkStakeStepRewardAddressHistory] not implemented.')\n }\n\n networkStakeStepRewardAddressReward(_context: StepIdentity, _address: Address): Promisable<Record<Address, AttoXL1>> {\n throw new Error('Method [networkStakeStepRewardAddressReward] not implemented.')\n }\n\n networkStakeStepRewardAddressShare(_context: StepIdentity, _address: Address): Promisable<[bigint, bigint]> {\n throw new Error('Method [networkStakeStepRewardAddressShare] not implemented.')\n }\n\n networkStakeStepRewardClaimedByAddress(_address: Address): Promisable<AttoXL1> {\n throw new Error('Method [networkStakeStepRewardClaimedByAddress] not implemented.')\n }\n\n networkStakeStepRewardForPosition(_position: number, _range: [number, number]): Promisable<[AttoXL1, AttoXL1]> {\n throw new Error('Method [networkStakeStepRewardForPosition] not implemented.')\n }\n\n networkStakeStepRewardForStep(_context: StepIdentity): Promisable<AttoXL1> {\n throw new Error('Method [networkStakeStepRewardForStep] not implemented.')\n }\n\n networkStakeStepRewardForStepForPosition(_context: StepIdentity, _position: number): Promisable<[AttoXL1, AttoXL1]> {\n throw new Error('Method [networkStakeStepRewardForStepForPosition] not implemented.')\n }\n\n networkStakeStepRewardPoolRewards(_context: StepIdentity): Promisable<Record<Address, AttoXL1>> {\n throw new Error('Method [networkStakeStepRewardPoolRewards] not implemented.')\n }\n\n networkStakeStepRewardPoolShares(_context: StepIdentity): Promisable<Record<Address, bigint>> {\n throw new Error('Method [networkStakeStepRewardPoolShares] not implemented.')\n }\n\n networkStakeStepRewardPositionWeight(_context: StepIdentity, _position: number): Promisable<bigint> {\n throw new Error('Method [networkStakeStepRewardPositionWeight] not implemented.')\n }\n\n networkStakeStepRewardPotentialPositionLoss(_context: StepIdentity, _position: number): Promisable<AttoXL1> {\n throw new Error('Method [networkStakeStepRewardPotentialPositionLoss] not implemented.')\n }\n\n networkStakeStepRewardRandomizer(_context: StepIdentity): Promisable<AttoXL1> {\n throw new Error('Method [networkStakeStepRewardRandomizer] not implemented.')\n }\n\n networkStakeStepRewardStakerCount(_context: StepIdentity): Promisable<number> {\n throw new Error('Method [networkStakeStepRewardStakerCount] not implemented.')\n }\n\n networkStakeStepRewardUnclaimedByAddress(_address: Address): Promisable<AttoXL1> {\n throw new Error('Method [networkStakeStepRewardUnclaimedByAddress] not implemented.')\n }\n\n networkStakeStepRewardWeightForAddress(_context: StepIdentity, _address: Address): Promisable<bigint> {\n throw new Error('Method [networkStakeStepRewardWeightForAddress] not implemented.')\n }\n\n networkStakeStepRewardsForPosition(_position: number, _range: [number, number]): Promisable<Record<StepIdentityString, [AttoXL1, AttoXL1]>> {\n throw new Error('Method [networkStakeStepRewardsForPosition] not implemented.')\n }\n\n networkStakeStepRewardsForRange(_range: [number, number]): Promisable<AttoXL1> {\n throw new Error('Method [networkStakeStepRewardsForRange] not implemented.')\n }\n\n networkStakeStepRewardsForStepLevel(_stepLevel: number, _range: [number, number]): Promisable<AttoXL1> {\n throw new Error('Method [networkStakeStepRewardsForStepLevel] not implemented.')\n }\n}\n", "import type {\n Address, Hash, Promisable,\n} from '@ariestools/sdk'\nimport {\n assertEx, hexToBigInt, isDefined, toAddress,\n} from '@ariestools/sdk'\nimport type {\n AccountInstance,\n ArchivistInstance, WithHashMeta, XyoAddress,\n} from '@xyo-network/sdk'\nimport {\n MemoryArchivist,\n PayloadBuilder,\n} from '@xyo-network/sdk'\nimport type {\n AccountBalanceViewer, AllowedBlockPayload, BlockBoundWitness,\n BlockNumberPayload, BlockRewardViewer, BlockRunner, BlockValidationViewer, ChainId, ChainStakeIntent, CreatableProviderParams,\n DeadLetterQueueRunner,\n FinalizationViewer,\n HydratedBlockStateValidationFunction, HydratedBlockValidationError, MempoolViewer,\n SignedBlockBoundWitnessWithHashMeta,\n SignedHydratedBlockWithHashMeta, SignedHydratedTransactionWithHashMeta,\n TimePayload, TimeSyncViewer, Transfer,\n} from '@xyo-network/xl1-sdk'\nimport {\n AbstractCreatableProvider, AccountBalanceViewerMoniker, asBlockBoundWitness, AttoXL1,\n BlockNumberSchema, BlockRejectionSchema, BlockRewardViewerMoniker, BlockRunnerMoniker,\n BlockValidationViewerMoniker, creatableProvider, createDeclarationIntent, DeadLetterQueueRunnerMoniker, defaultRewardRatio,\n FinalizationViewerMoniker, isSignedHydratedBlockWithHashMeta, isTransfer, MempoolViewerMoniker, TimeSyncViewerMoniker,\n TransactionRejectionSchema, XYO_STEP_REWARD_ADDRESS,\n} from '@xyo-network/xl1-sdk'\n\nimport type { BlockRewardDiviner } from '#modules'\nimport { FixedPercentageBlockRewardDiviner, FixedPercentageBlockRewardDivinerConfigSchema } from '#modules'\nimport { buildNextBlock } from '#protocol'\n\nimport { generateTransactionFeeTransfers } from './generateTransactionFeeTransfers.ts'\nimport { identifyOffendingTransactions } from './identifyOffendingTransactions.ts'\n\n/**\n * The default block size for a block\n */\nexport const DEFAULT_BLOCK_SIZE = 10\n\n/**\n * The amount of time for which a producer will restake their intent\n */\nexport const XYO_PRODUCER_REDECLARATION_DURATION = 100\n\n/**\n * The number of blocks within which a producer will redeclare\n * their intent to produce blocks\n */\nexport const XYO_PRODUCER_REDECLARATION_WINDOW = 100\n\nexport interface SimpleBlockRunnerParams extends CreatableProviderParams {\n account: AccountInstance\n disableIntentRedeclaration?: boolean\n heartbeatInterval?: number\n rejectedTransactionsArchivist?: ArchivistInstance\n rewardAddress: Address\n /**\n * When `true` (default), `filterByFunded` enforces the same cumulative-outflow\n * vs balance rule the post-submit block validator uses\n * (`base + priority + gasLimit + transfer amounts`). Setting this to `false`\n * is only appropriate for unit-style tests that exercise block-production\n * mechanics with synthetic unfunded senders and don't model balances.\n */\n validateBalances?: boolean\n validateHydratedBlockState?: HydratedBlockStateValidationFunction\n}\n\n@creatableProvider()\nexport class SimpleBlockRunner extends AbstractCreatableProvider<SimpleBlockRunnerParams> implements BlockRunner {\n static readonly connectionTypes = ['lmdb', 'mongo', 'memory'] as const\n static readonly defaultMoniker = BlockRunnerMoniker\n static readonly dependencies = [\n AccountBalanceViewerMoniker,\n BlockRewardViewerMoniker,\n BlockValidationViewerMoniker,\n FinalizationViewerMoniker,\n MempoolViewerMoniker,\n TimeSyncViewerMoniker,\n ]\n\n static readonly monikers = [BlockRunnerMoniker]\n static readonly surface = 'node' as const\n moniker = SimpleBlockRunner.defaultMoniker\n\n protected _blockRewardDiviner?: BlockRewardDiviner\n protected _deadLetterQueueRunner?: DeadLetterQueueRunner\n // TODO(producer-exclusion-set): uncapped for v1. If memory grows in long-running producers,\n // add FIFO eviction or a TTL keyed off block number.\n protected _excludedTransactionHashes = new Set<Hash>()\n protected _lastRedeclarationBlock?: number\n protected _rejectedTransactionsArchivist?: ArchivistInstance\n\n private _account?: AccountInstance\n private _accountBalanceViewer?: AccountBalanceViewer\n private _address?: Address\n private _blockRewardViewer?: BlockRewardViewer\n private _blockValidationViewer?: BlockValidationViewer\n private _finalizationViewer?: FinalizationViewer\n private _mempoolViewer?: MempoolViewer\n private _rewardAddress?: Address\n private _timeSyncViewer?: TimeSyncViewer\n\n /**\n * The default block size for a block\n */\n static get DefaultBlockSize(): number {\n return DEFAULT_BLOCK_SIZE\n }\n\n /**\n * The amount of time for which the producer will redeclare\n * their intent to continue producing blocks\n */\n static get RedeclarationDuration(): number {\n return XYO_PRODUCER_REDECLARATION_DURATION\n }\n\n /**\n * The number of blocks within which the producer will redeclare\n * their intent to continue producing blocks\n */\n static get RedeclarationWindow(): number {\n return XYO_PRODUCER_REDECLARATION_WINDOW\n }\n\n protected get account() {\n return this._account!\n }\n\n protected get accountBalanceViewer() {\n return this._accountBalanceViewer!\n }\n\n protected get address() {\n return this._address!\n }\n\n protected get blockRewardViewer() {\n return this._blockRewardViewer!\n }\n\n protected get blockValidationViewer() {\n return this._blockValidationViewer!\n }\n\n protected get finalizationViewer() {\n return this._finalizationViewer!\n }\n\n protected get heartbeatInterval() {\n return this.params.heartbeatInterval ?? 3_600_000\n }\n\n protected get mempoolViewer() {\n return this._mempoolViewer!\n }\n\n // protected get pendingTransactionsService() {\n // return assertEx(this.params.pendingTransactionsService, () => 'Missing pendingTransactionsService')\n // }\n\n protected get rejectedTransactionsArchivist() {\n return this._rejectedTransactionsArchivist!\n }\n\n protected get rewardAddress(): Address {\n return this._rewardAddress!\n }\n\n // protected get stakeIntentService(): StakeIntentService {\n // return assertEx(this.params.stakeIntentService, () => 'No StakeIntentService provided')\n // }\n\n protected get timeSyncViewer(): TimeSyncViewer {\n return this._timeSyncViewer!\n }\n\n // protected get validateHydratedBlockState() {\n // return assertEx(this.params.validateHydratedBlockState, () => 'validateHydratedBlockState is required')\n // }\n\n override async createHandler() {\n this._rejectedTransactionsArchivist = this.params.rejectedTransactionsArchivist ?? (await MemoryArchivist.create())\n this._account = assertEx(this.params.account, () => 'Account is required')\n this._address = toAddress(this.account.address)\n this._accountBalanceViewer = await this.locateAndCreate<AccountBalanceViewer>(AccountBalanceViewerMoniker)\n this._blockRewardViewer = await this.locateAndCreate<BlockRewardViewer>(BlockRewardViewerMoniker)\n this._blockValidationViewer = await this.locator.getInstance<BlockValidationViewer>(BlockValidationViewerMoniker)\n this._finalizationViewer = await this.locateAndCreate<FinalizationViewer>(FinalizationViewerMoniker)\n this._mempoolViewer = await this.locateAndCreate<MempoolViewer>(MempoolViewerMoniker)\n this._rewardAddress = this.params.rewardAddress\n this._timeSyncViewer = await this.locateAndCreate<TimeSyncViewer>(TimeSyncViewerMoniker)\n this._deadLetterQueueRunner = await this.locator.tryGetInstance<DeadLetterQueueRunner>(DeadLetterQueueRunnerMoniker)\n }\n\n async next(head: WithHashMeta<BlockBoundWitness>): Promise<SignedHydratedBlockWithHashMeta | undefined> {\n // If the block is for another chain, ignore\n // if (head.chain !== this.chainId) return\n // const leadersStart = Date.now()\n // const leaders = await this.electionService.getCreatorCommitteeForNextBlock(head)\n // const leadersDuration = Date.now() - leadersStart\n // if (leadersDuration > 100) {\n // this.logger?.warn(`[Slow] Fetched leaders in ${leadersDuration}ms: ${leaders.map(l => l.slice(0, 6)).join(', ')}`)\n // }\n // TODO: Should we propose block if creator committee is empty?\n // TODO: Handle the case where we're not the 1st leader but they're not responding\n // at a higher level than here as that's a network issue\n // if (!leaders.includes(this.address)) return\n return await this.proposeNextValidBlock(head)\n }\n\n async produceNextBlock(head: SignedBlockBoundWitnessWithHashMeta, force: true): Promise<SignedHydratedBlockWithHashMeta>\n async produceNextBlock(head: SignedBlockBoundWitnessWithHashMeta, force?: false): Promise<SignedHydratedBlockWithHashMeta | undefined>\n async produceNextBlock(head: SignedBlockBoundWitnessWithHashMeta, force?: boolean): Promise<SignedHydratedBlockWithHashMeta | undefined> {\n // assertEx(head.chain === this.chainId, () => 'Block chain ID does not match')\n const result = await this.proposeNextValidBlock(head)\n return force === true ? assertEx(result, () => 'Failed to produce next block') : result\n }\n\n protected async getBlockRewardTransfers(block: number): Promise<Transfer[]> {\n this._blockRewardDiviner ??= await FixedPercentageBlockRewardDiviner.create({\n account: 'random',\n blockRewardViewer: this.blockRewardViewer,\n config: {\n rewardAddress: this.rewardAddress,\n rewardPercentageRatio: defaultRewardRatio,\n schema: FixedPercentageBlockRewardDivinerConfigSchema,\n },\n })\n\n const blockIdBuilder = new PayloadBuilder<BlockNumberPayload>({ schema: BlockNumberSchema })\n const blockId = blockIdBuilder.fields({ block }).build()\n const rewards = await this._blockRewardDiviner.divine([blockId])\n return rewards as Transfer[]\n }\n\n /**\n * Handles the producer redeclaration logic\n * @param head The current head block\n * @returns chain stake intent for the producer redeclaration, or undefined if no redeclaration is needed\n */\n protected getProducerRedeclaration(head: WithHashMeta<BlockBoundWitness>): Promisable<ChainStakeIntent | undefined> {\n if (this.params.disableIntentRedeclaration === true) return\n const currentBlock = head.block\n // Only redeclare when the previous declaration has expired\n if (isDefined(this._lastRedeclarationBlock)) {\n const lastDeclarationExpiry = this._lastRedeclarationBlock + SimpleBlockRunner.RedeclarationDuration\n if (currentBlock < lastDeclarationExpiry) return\n }\n this._lastRedeclarationBlock = currentBlock\n return createDeclarationIntent(this.address, 'producer', currentBlock, currentBlock + SimpleBlockRunner.RedeclarationDuration)\n }\n\n // `validateBalances` resolves from (a) the explicit method argument when\n // passed, (b) the constructor `params.validateBalances`, or (c) `true`.\n // True is the safe default: `filterByFunded` then enforces the same\n // cumulative-outflow rule the post-submit block validator uses\n // (`base + priority + gasLimit + transfer amounts`). With the old default\n // of `false`, a tx whose declared gasLimit exceeded the sender's balance\n // would pass the producer's filter, get submitted, and then land in\n // `rejected_blocks` \u2014 silently wedging the chain because the producer's\n // `_lastProducedBlock` cache muted retries. Reproduced in the\n // api-local-mongodb-beta test rig.\n protected async proposeNextValidBlock(head: WithHashMeta<BlockBoundWitness>, validateBalances?: boolean, force = false) {\n const shouldValidateBalances = validateBalances ?? this.params.validateBalances ?? true\n return await this.spanAsync('proposeNextValidBlock', async () => {\n try {\n // Calculate the next block components\n const { block: previousBlock } = assertEx(asBlockBoundWitness(head), () => 'Invalid head block')\n const nextBlock = previousBlock + 1\n const chainId = await this.finalizationViewer.chainId()\n const pendingTransactionsRaw = await this.mempoolViewer.pendingTransactions({ limit: SimpleBlockRunner.DefaultBlockSize })\n const pendingTransactions = pendingTransactionsRaw.filter(tx => !this._excludedTransactionHashes.has(tx[0]._hash))\n const nextBlockTransactions = await this.rejectWrongChainTransactions(pendingTransactions, chainId)\n\n this.logger?.log(`Pending Tx Count ${nextBlockTransactions.length}`)\n\n const nonTxPayloads: AllowedBlockPayload[] = []\n\n // Calculate the optional producer redeclaration and add it if necessary\n const producerRedeclarationPayload = await this.getProducerRedeclaration(head)\n if (producerRedeclarationPayload) nonTxPayloads.push(producerRedeclarationPayload)\n\n // If there are no transactions, no payloads and no heartbeat required, we don't need to create a block\n if (nextBlockTransactions.length === 0 && !this.heartbeatRequired(head) && !force) return\n\n // Calculate the optional block reward transfer and add if necessary\n const rewardTransferPayloads = await this.getBlockRewardTransfers(nextBlock)\n nonTxPayloads.push(...rewardTransferPayloads)\n\n const transactionTransfers = await generateTransactionFeeTransfers(this.address, nextBlockTransactions)\n const timeStart = Date.now()\n const timePayload = await this.generateTimePayload()\n const timeDuration = Date.now() - timeStart\n if (timeDuration > 100) {\n this.logger?.warn(`[Slow] Generated time payload in ${timeDuration}ms`)\n }\n\n const [initialFundedTransactions, initialFundedTransfers]\n = await this.filterByFunded(head, nextBlockTransactions, transactionTransfers, shouldValidateBalances)\n\n const stepRewardBalances = await this.accountBalanceViewer.accountBalances([XYO_STEP_REWARD_ADDRESS])\n const stepRewardPoolBalance = (stepRewardBalances as Record<string, AttoXL1>)[String(XYO_STEP_REWARD_ADDRESS)]\n\n const result = await this.runBuildValidateRetryLoop({\n head,\n chainId,\n stepRewardPoolBalance,\n nonTxPayloads,\n timePayload,\n initialFundedTransactions,\n initialFundedTransfers,\n })\n const { block: proposedBlock, errors: proposedErrors } = result\n if (isSignedHydratedBlockWithHashMeta(proposedBlock)) {\n // Submission is the producer's responsibility (`ProducerActor.produceBlock`)\n // \u2014 SimpleBlockRunner just builds and validates. Previously this site\n // also called `mempoolRunner.submitBlocks`, double-submitting the\n // same block. The second submit at the producer always failed with\n // \"archivist accepted 0 of 1\" because the inner one had already\n // landed. Removing the inner submit eliminates that false positive\n // and means SimpleBlockRunner no longer needs a MempoolRunner\n // dependency at all.\n return proposedBlock\n }\n if (proposedBlock !== undefined) await this.rejectExhaustedBlock(proposedBlock, proposedErrors)\n } catch (error) {\n this.logger?.error(`Error proposing next valid block: ${(error as Error).message}`)\n throw error\n }\n }, this.context)\n }\n\n /**\n * Compute the cumulative outflow a single tx would charge to its `from`\n * address, using the same rule as `BlockCumulativeBalanceValidator`:\n * `outflow = base + priority + gasLimit + sum(transfer amounts to addresses\n * other than from)`. Mirroring the validator exactly here ensures the\n * producer doesn't include a tx that the post-submit block validator will\n * reject, which would otherwise wedge the chain because the producer's\n * `_lastProducedBlock` cache mutes retries.\n */\n private addTransferOutflow(outflow: bigint, payload: Transfer): bigint {\n let result = outflow\n for (const [to, amount] of Object.entries(payload.transfers)) {\n if (to === payload.from) continue\n result += hexToBigInt((amount ?? '00'))\n }\n return result\n }\n\n private computeTransactionOutflow(tx: SignedHydratedTransactionWithHashMeta): bigint {\n const [bw, payloads] = tx\n const {\n base, gasLimit, priority,\n } = bw.fees\n let outflow = hexToBigInt(base) + hexToBigInt(priority) + hexToBigInt(gasLimit)\n const txPayloadHashes = new Set(bw.payload_hashes)\n for (const payload of payloads) {\n if (!txPayloadHashes.has(payload._hash)) continue\n if (!isTransfer(payload)) continue\n if (payload.from !== bw.from) continue\n outflow = this.addTransferOutflow(outflow, payload)\n }\n return outflow\n }\n\n // remove unfunded transactions and block transfers\n private async filterByFunded(\n head: WithHashMeta<BlockBoundWitness>,\n txs: SignedHydratedTransactionWithHashMeta[],\n transfers: Transfer[],\n validateBalances = false,\n ): Promise<[SignedHydratedTransactionWithHashMeta[], Transfer[]]> {\n const fundedTransfers: Transfer[] = []\n const fundedTransactions: SignedHydratedTransactionWithHashMeta[] = []\n // Outflow already committed to this block per sender, plus a per-sender\n // balance cache (balances are read at the fixed parent `head`). Each tx is\n // gated against the sender's REMAINING balance, not the full balance in\n // isolation. Checking each tx independently (the previous behavior) lets two\n // individually-valid transfers from the same sender \u2014 a double-spend across\n // transactions, each \u2264 balance but jointly > balance \u2014 both pass. The block\n // then carries a cumulative outflow the post-submit validator rejects, and\n // the producer wedges (its `_lastProducedBlock` cache mutes retries).\n // Sequential, cumulative gating includes only the first transfer that fits\n // and drops the rest; the dropped tx stays pending and is pruned once the\n // included one lands and the sender can no longer cover it.\n const committedOutflow = new Map<XyoAddress, bigint>()\n const balanceCache = new Map<XyoAddress, bigint>()\n for (const tx of txs) {\n const transfer: Transfer | undefined = transfers.find(candidate => candidate.from === tx[0].from)\n if (!transfer) continue\n if (!validateBalances) {\n fundedTransfers.push(transfer)\n fundedTransactions.push(tx)\n continue\n }\n const { from } = transfer\n let balance = balanceCache.get(from)\n if (balance === undefined) {\n const accountBalances = await this.accountBalanceViewer.accountBalances([from])\n balance = (accountBalances as Record<string, bigint>)[String(from)] ?? AttoXL1(0n)\n balanceCache.set(from, balance)\n }\n // Mirror the post-submit block validator's cumulative-outflow rule\n // (base + priority + gasLimit + transfer amounts) against the running\n // total for this sender, so the producer never includes a tx the\n // validator will reject.\n const projectedOutflow = (committedOutflow.get(from) ?? 0n) + this.computeTransactionOutflow(tx)\n if (balance >= projectedOutflow) {\n committedOutflow.set(from, projectedOutflow)\n fundedTransfers.push(transfer)\n fundedTransactions.push(tx)\n } else {\n this.logger?.debug(\n `filterByFunded: dropping tx ${tx[0]._hash} from ${from} \u2014 cumulative outflow ${projectedOutflow} > balance ${balance}`,\n )\n }\n }\n return [fundedTransactions, fundedTransfers]\n }\n\n private async generateTimePayload() {\n return await this.timeSyncViewer.currentTimePayload()\n }\n\n /**\n * Check if a heartbeat block is required based on network activity.\n * @param head The current head block\n * @returns True if a heartbeat is required, false otherwise\n */\n private heartbeatRequired(head: WithHashMeta<BlockBoundWitness>): boolean {\n const epoch = head.$epoch\n if (isDefined(epoch) && Date.now() - epoch > this.heartbeatInterval) {\n return true\n }\n return false\n }\n\n private async rejectExhaustedBlock(\n block: SignedHydratedBlockWithHashMeta,\n errors: HydratedBlockValidationError[],\n ): Promise<void> {\n this.logger?.warn(`Validation of produced block failed: ${errors.at(0)?.message}`)\n if (this._deadLetterQueueRunner) {\n const rejectionErrors = errors.map(e => ({\n hash: block[0]._hash, name: 'BlockValidationError', message: String(e.message ?? e),\n }))\n await this._deadLetterQueueRunner.rejectBlock({\n schema: BlockRejectionSchema, block, errors: rejectionErrors, rejector: 'producer',\n })\n } else {\n await this.rejectedTransactionsArchivist.insert(block[1])\n }\n }\n\n // Partition pending transactions by chain-ID match; route mismatches to the transaction DLQ.\n private async rejectWrongChainTransactions(\n transactions: SignedHydratedTransactionWithHashMeta[],\n chainId: ChainId,\n ): Promise<SignedHydratedTransactionWithHashMeta[]> {\n const localChain = chainId.toLowerCase()\n const matched: SignedHydratedTransactionWithHashMeta[] = []\n const mismatched: SignedHydratedTransactionWithHashMeta[] = []\n for (const tx of transactions) {\n if (tx[0].chain.toLowerCase() === localChain) {\n matched.push(tx)\n } else {\n mismatched.push(tx)\n }\n }\n if (mismatched.length > 0) {\n this.logger?.warn(`Rejecting ${mismatched.length} transaction(s) targeting non-local chain`)\n const dlq = this._deadLetterQueueRunner\n await (dlq\n ? Promise.all(mismatched.map(tx => dlq.rejectTransaction({\n schema: TransactionRejectionSchema,\n transaction: tx,\n errors: [{\n hash: tx[0]._hash,\n name: 'TransactionChainMismatch',\n message: `Transaction chain ${tx[0].chain} does not match local chain ${localChain}`,\n }],\n rejector: 'producer',\n })))\n : this.rejectedTransactionsArchivist.insert(mismatched.map(tx => tx[0])))\n }\n return matched\n }\n\n private async runBuildValidateRetryLoop(args: {\n chainId: ChainId\n head: WithHashMeta<BlockBoundWitness>\n initialFundedTransactions: SignedHydratedTransactionWithHashMeta[]\n initialFundedTransfers: Transfer[]\n nonTxPayloads: AllowedBlockPayload[]\n stepRewardPoolBalance: AttoXL1\n timePayload: TimePayload\n }): Promise<{\n block: SignedHydratedBlockWithHashMeta | undefined\n errors: HydratedBlockValidationError[]\n }> {\n const {\n chainId, head, initialFundedTransactions, initialFundedTransfers,\n nonTxPayloads, stepRewardPoolBalance, timePayload,\n } = args\n const maxAttempts = Math.max(1, initialFundedTransactions.length)\n let candidateTransactions = initialFundedTransactions\n let candidateTransfers = initialFundedTransfers\n let lastBlock: SignedHydratedBlockWithHashMeta | undefined\n let lastErrors: HydratedBlockValidationError[] = []\n\n for (let attempt = 0; attempt <= maxAttempts; attempt++) {\n const blockPayloads = [...nonTxPayloads, ...candidateTransfers, timePayload]\n this.logger?.info(`Building block ${head.block + 1}${attempt > 0 ? ` (retry ${attempt})` : ''}`)\n lastBlock = await buildNextBlock(\n head,\n candidateTransactions,\n blockPayloads,\n [this.account],\n XYO_STEP_REWARD_ADDRESS,\n stepRewardPoolBalance,\n undefined,\n chainId,\n )\n const validated = await this.blockValidationViewer.validateBlock(lastBlock, { head: head._hash })\n if (isSignedHydratedBlockWithHashMeta(validated)) {\n return { block: validated, errors: [] }\n }\n lastErrors = validated\n if (attempt === maxAttempts) break\n const { offendingHashes, reason } = await identifyOffendingTransactions({ candidateTransactions, errors: validated })\n if (offendingHashes.length === 0 || reason === 'unknown') break\n for (const offendingHash of offendingHashes) this._excludedTransactionHashes.add(offendingHash)\n const offendingSet = new Set<Hash>(offendingHashes)\n candidateTransactions = candidateTransactions.filter(tx => !offendingSet.has(tx[0]._hash))\n const remainingFromAddresses = new Set<XyoAddress>(candidateTransactions.map(tx => tx[0].from))\n const feeTransfers = await generateTransactionFeeTransfers(this.address, candidateTransactions)\n candidateTransfers = feeTransfers.filter(t => remainingFromAddresses.has(t.from))\n this.logger?.warn(`Block validation failed (attempt ${attempt + 1}); excluded ${offendingHashes.length} tx(s), retrying`)\n }\n return { block: lastBlock, errors: lastErrors }\n }\n}\n", "import { assertEx, hexFromBigInt } from '@ariestools/sdk'\nimport type { XyoAddress } from '@xyo-network/sdk'\nimport { PayloadBuilder } from '@xyo-network/sdk'\nimport type {\n SignedHydratedTransaction,\n Transfer,\n XL1,\n} from '@xyo-network/xl1-sdk'\nimport {\n HydratedTransactionWrapper,\n transactionRequiredGas, TransferSchema, XYO_ZERO_ADDRESS,\n} from '@xyo-network/xl1-sdk'\n\nexport async function generateTransactionFeeTransfers(address: XyoAddress, transactions: SignedHydratedTransaction[]): Promise<Transfer[]> {\n const txs = await Promise.all(transactions.map(async (tx) => {\n return HydratedTransactionWrapper.parse([await PayloadBuilder.addStorageMeta(tx[0]), await PayloadBuilder.addStorageMeta(tx[1])])\n }))\n\n // merge transactions with the same from address\n const txBaseFeeCosts: Record<XyoAddress, bigint> = {}\n for (const tx of txs) {\n txBaseFeeCosts[tx.boundWitness.from] = (txBaseFeeCosts[tx.boundWitness.from] ?? 0n)\n + tx.fees.base\n }\n\n const txGasCosts: Record<XyoAddress, bigint> = {}\n for (const tx of txs) {\n const requiredGas = transactionRequiredGas(tx.data)\n const totalGasCost = requiredGas * tx.fees.gasPrice\n txGasCosts[tx.boundWitness.from] = (txBaseFeeCosts[tx.boundWitness.from] ?? 0n)\n + totalGasCost\n }\n\n // generate actual Transfer Payloads & burn the base fee\n const payloads = (Object.entries(txBaseFeeCosts) as [XyoAddress, XL1][]).map(([from, amount]) => {\n const payload: Transfer = {\n schema: TransferSchema,\n epoch: Date.now(),\n from,\n transfers: Object.fromEntries([[String(XYO_ZERO_ADDRESS), hexFromBigInt(amount)]]),\n }\n return payload\n })\n\n // transfer gas cost to producer\n for (const [from, amount] of Object.entries(txGasCosts)) {\n // every gas from should also be a base fee from\n const fromPayload = assertEx(payloads.find(p => p.from === from), () => 'from payload not found')\n fromPayload.transfers[address] = hexFromBigInt(amount)\n }\n\n return payloads\n}\n", "import type { Hash } from '@ariestools/sdk'\nimport type { HydratedBlockValidationError, SignedHydratedTransactionWithHashMeta } from '@xyo-network/xl1-sdk'\nimport {\n HydratedTransactionWrapper,\n netBalancesForPayloads,\n transactionRequiredGas,\n} from '@xyo-network/xl1-sdk'\n\nexport type OffendingTxReason = 'block-balance' | 'tx-invalid' | 'unknown'\n\nexport interface OffendingTxResult {\n offendingHashes: Hash[]\n reason: OffendingTxReason\n}\n\ninterface TxScore {\n cost: bigint\n gasPrice: bigint\n}\n\nasync function scoreTransaction(tx: SignedHydratedTransactionWithHashMeta): Promise<TxScore> {\n const wrapper = await HydratedTransactionWrapper.parse(tx)\n const from = wrapper.boundWitness.from\n const gasPrice = wrapper.fees.gasPrice\n const gasCost = transactionRequiredGas(tx) * gasPrice\n const baseCost = wrapper.fees.base\n const netBalances = netBalancesForPayloads({ singletons: {} }, tx[1])\n const fromNet = netBalances[from] ?? 0n\n const transferOut = fromNet < 0n ? -fromNet : 0n\n return { cost: gasCost + baseCost + transferOut, gasPrice }\n}\n\nexport async function identifyOffendingTransactions(args: {\n candidateTransactions: SignedHydratedTransactionWithHashMeta[]\n errors: HydratedBlockValidationError[]\n}): Promise<OffendingTxResult> {\n const { errors, candidateTransactions } = args\n const candidateHashes = new Set<Hash>(candidateTransactions.map(tx => tx[0]._hash))\n\n const txInvalidHashes = new Set<Hash>()\n for (const error of errors) {\n if (candidateHashes.has(error.hash)) txInvalidHashes.add(error.hash)\n const cause = error.cause as undefined | { hash?: Hash }\n if (cause?.hash && candidateHashes.has(cause.hash)) txInvalidHashes.add(cause.hash)\n }\n if (txInvalidHashes.size > 0) {\n return { offendingHashes: [...txInvalidHashes], reason: 'tx-invalid' }\n }\n\n const balanceOffenderHashes = new Set<Hash>()\n for (const error of errors) {\n const offendingHashes = (error as { offendingTransactionHashes?: Hash[] }).offendingTransactionHashes ?? []\n for (const hash of offendingHashes) {\n if (candidateHashes.has(hash)) balanceOffenderHashes.add(hash)\n }\n }\n if (balanceOffenderHashes.size === 0) {\n return { offendingHashes: [], reason: 'unknown' }\n }\n\n const offenders = candidateTransactions.filter(tx => balanceOffenderHashes.has(tx[0]._hash))\n const scored = await Promise.all(offenders.map(async tx => ({ tx, ...(await scoreTransaction(tx)) })))\n scored.sort((a, b) => {\n if (a.cost !== b.cost) return a.cost < b.cost ? 1 : -1\n if (a.gasPrice !== b.gasPrice) return a.gasPrice < b.gasPrice ? -1 : 1\n return a.tx[0]._hash < b.tx[0]._hash ? -1 : 1\n })\n return { offendingHashes: [scored[0].tx[0]._hash], reason: 'block-balance' }\n}\n", "import type { Promisable } from '@ariestools/sdk'\nimport type { ReadArchivist, XyoAddress } from '@xyo-network/sdk'\nimport type { StepIdentity, StepStakeViewer } from '@xyo-network/xl1-sdk'\nimport { AbstractCreatableProvider, StepStakeViewerMoniker } from '@xyo-network/xl1-sdk'\n\nimport type { BaseServiceParams } from '../model/index.ts'\n\nexport interface BaseStepStakeServiceParams extends BaseServiceParams {\n chainArchivist: ReadArchivist\n}\n\nexport abstract class AbstractStepStakeService extends AbstractCreatableProvider<BaseStepStakeServiceParams> implements StepStakeViewer {\n static readonly defaultMoniker = StepStakeViewerMoniker\n static readonly monikers = [StepStakeViewerMoniker]\n override moniker = AbstractStepStakeService.defaultMoniker\n\n stepStake(_step: StepIdentity): Promisable<Record<XyoAddress, bigint>> {\n throw new Error('Method [stepStake] not implemented.')\n }\n\n stepStakeForAddress(_address: XyoAddress, _step: StepIdentity): Promisable<bigint> {\n throw new Error('Method [stepStakeForAddress] not implemented.')\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;AACA;AAAA,EACE;AAAA,EACA;AAAA,EAAU;AAAA,EAAW;AAAA,OAChB;AACP,SAAS,iCAAiC;AAM1C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AASA,IAAM,uBAAN,cAAmC,kBAA2E;AAAA,EAKnH,UAAU,qBAAqB;AAAA,EAErB;AAAA,EAEV,IAAc,sBAAsB;AAClC,WAAO,SAAS,KAAK,OAAO,qBAAqB,MAAM,iCAAiC;AAAA,EAC1F;AAAA,EAEA,IAAc,kBAAkB;AAC9B,WAAO,SAAS,KAAK,kBAAkB,MAAM,6BAA6B;AAAA,EAC5E;AAAA,EAEA,IAAc,WAAW;AACvB,WAAO,SAAS,KAAK,OAAO,UAAU,MAAM,sBAAsB;AAAA,EACpE;AAAA,EAEA,MAAM,sBAAsB,aAA+C;AACzE,UAAM,WAAW,0BAA0B,QAAQ,aAAa,KAAK,eAAe,GAAG,KAAK,QAAQ;AACpG,WAAO,UAAU,MAAM,SAAS,gBAAgB,WAAW,CAAC;AAAA,EAC9D;AAAA,EAEA,MAAe,gBAAgB;AAC7B,UAAM,MAAM,cAAc;AAC1B,QAAI;AACF,WAAK,mBAAmB,MAAM,KAAK,oBAAoB,gBAAgB;AAAA,IACzE,SAAS,IAAI;AACX,YAAM,QAAQ;AACd,YAAM,IAAI,MAAM,2CAA2C,MAAM,OAAO,IAAI,EAAE,OAAO,GAAG,CAAC;AAAA,IAC3F;AAAA,EACF;AACF;AAlCE,cADW,sBACK,mBAAkB,CAAC,SAAS;AAC5C,cAFW,sBAEK,kBAAiB;AACjC,cAHW,sBAGK,YAAW,CAAC,wBAAwB;AACpD,cAJW,sBAI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AYK,YAAW,CAAC,kBAAkB;AAC9C,cAbW,mBAaK,WAAU;AAbf,oBAAN;AAAA,EADNO,mBAAkB;AAAA,GACN;;;AGtEb,SAAS,6BAAAC,4BAA2B,8BAA8B;AAQ3D,IAAe,2BAAf,MAAe,kCAAiCA,2BAAiF;AAAA,EACtI,OAAgB,iBAAiB;AAAA,EACjC,OAAgB,WAAW,CAAC,sBAAsB;AAAA,EACzC,UAAU,0BAAyB;AAAA,EAE5C,UAAU,OAA6D;AACrE,UAAM,IAAI,MAAM,qCAAqC;AAAA,EACvD;AAAA,EAEA,oBAAoB,UAAsB,OAAyC;AACjF,UAAM,IAAI,MAAM,+CAA+C;AAAA,EACjE;AACF;",
6
- "names": ["assertEx", "AbstractCreatableProvider", "AbstractCreatableProvider", "assertEx", "assertEx", "AbstractCreatableProvider", "creatableProvider", "AbstractCreatableProvider", "creatableProvider", "assertEx", "isDefined", "toAddress", "PayloadBuilder", "AbstractCreatableProvider", "BlockRejectionSchema", "BlockRewardViewerMoniker", "creatableProvider", "createDeclarationIntent", "isSignedHydratedBlockWithHashMeta", "buildNextBlock", "assertEx", "HydratedTransactionWrapper", "transactionRequiredGas", "AbstractCreatableProvider", "assertEx", "toAddress", "BlockRewardViewerMoniker", "PayloadBuilder", "isDefined", "createDeclarationIntent", "isSignedHydratedBlockWithHashMeta", "BlockRejectionSchema", "buildNextBlock", "creatableProvider", "AbstractCreatableProvider"]
3
+ "sources": ["../../src/modules/services/BlockReward/EvmBlockRewardViewer.ts", "../../src/modules/services/ChainValidator/XyoValidator.ts", "../../src/modules/services/Election/BaseElectionService.ts", "../../src/modules/services/implementation/head/createBootstrapHead.ts", "../../src/modules/services/implementation/processPendingBlocks.ts", "../../src/modules/services/NetworkStakeStepReward/BaseNetworkStakeStepRewardService.ts", "../../src/modules/services/simple/block/runner/SimpleBlockRunner.ts", "../../src/modules/services/simple/block/runner/generateTransactionFeeTransfers.ts", "../../src/modules/services/simple/block/runner/identifyOffendingTransactions.ts", "../../src/modules/services/simple/block/runner/producerTuning.ts", "../../src/modules/services/StepStake/BaseStepStakeService.ts"],
4
+ "sourcesContent": ["import type { CreatableParams } from '@ariestools/sdk'\nimport {\n AbstractCreatable,\n assertEx, creatable, toEthAddress,\n} from '@ariestools/sdk'\nimport { IXyoChainRewards__factory } from '@xyo-network/typechain'\nimport type {\n AttoXL1, BlockRewardViewer,\n ChainContractViewer,\n XL1BlockNumber,\n} from '@xyo-network/xl1-sdk'\nimport {\n asAttoXL1,\n BlockRewardViewerMoniker,\n} from '@xyo-network/xl1-sdk'\nimport type { Provider } from 'ethers/providers'\n\nexport interface EvmBlockRewardViewerParams extends CreatableParams {\n chainContractViewer: ChainContractViewer\n provider: Provider\n}\n\n@creatable()\nexport class EvmBlockRewardViewer extends AbstractCreatable<EvmBlockRewardViewerParams> implements BlockRewardViewer {\n static readonly connectionTypes = ['evm-rpc'] as const\n static readonly defaultMoniker = BlockRewardViewerMoniker\n static readonly monikers = [BlockRewardViewerMoniker]\n static readonly surface = 'node' as const\n moniker = EvmBlockRewardViewer.defaultMoniker\n\n protected _contractAddress: string | undefined\n\n protected get chainContractViewer() {\n return assertEx(this.params.chainContractViewer, () => 'chainContractViewer is required')\n }\n\n protected get contractAddress() {\n return assertEx(this._contractAddress, () => 'contractAddress is required')\n }\n\n protected get provider() {\n return assertEx(this.params.provider, () => 'provider is required')\n }\n\n async allowedRewardForBlock(blockNumber: XL1BlockNumber): Promise<AttoXL1> {\n const contract = IXyoChainRewards__factory.connect(toEthAddress(this.contractAddress), this.provider)\n return asAttoXL1(await contract.calcBlockReward(blockNumber))\n }\n\n override async createHandler() {\n await super.createHandler()\n try {\n this._contractAddress = await this.chainContractViewer.rewardsContract()\n } catch (ex) {\n const error = ex as Error\n throw new Error(`Failed to get rewards contract address: ${error.message}`, { cause: ex })\n }\n }\n}\n", "import type { Promisable } from '@ariestools/sdk'\nimport type {\n BlockBoundWitness,\n BlockViewer, HydratedBlockStateValidationFunction,\n SignedHydratedTransactionWithStorageMeta,\n} from '@xyo-network/xl1-sdk'\nimport {\n AbstractCreatableProvider, BlockViewerMoniker, creatableProvider,\n} from '@xyo-network/xl1-sdk'\n\nimport type { BaseServiceParams } from '../model/index.ts'\nimport type { Validator } from './model/index.ts'\n\nexport interface XyoValidatorParams extends BaseServiceParams {\n // account: AccountInstance\n // blockRewardService: BlockRewardService\n blockViewer?: BlockViewer\n // chainId: ChainId\n // electionService: ElectionService\n // pendingBundledTransactionsArchivist: ArchivistInstance\n // stakeIntentService: StakeIntentService\n validateHydratedBlockState: HydratedBlockStateValidationFunction\n}\n\nexport const ValidatorMoniker = 'Validator'\n\n@creatableProvider()\nexport class XyoValidator<TParams extends XyoValidatorParams = XyoValidatorParams> extends AbstractCreatableProvider<TParams> implements Validator {\n static readonly connectionTypes = [] as const\n static readonly defaultMoniker = ValidatorMoniker\n static readonly dependencies = [BlockViewerMoniker]\n static readonly monikers = [ValidatorMoniker]\n static readonly surface = 'node' as const\n moniker = XyoValidator.defaultMoniker\n private _blockViewer?: BlockViewer\n // get address() {\n // return this.account.address\n // }\n\n // protected get account() {\n // return assertEx(this.params.account, () => 'account is required')\n // }\n\n protected get blockViewer() {\n return this._blockViewer!\n }\n\n // protected get chainInfo() {\n // return assertEx(this.params.chainId, () => 'chainInfo is required')\n // }\n\n // protected get electionService() {\n // return assertEx(this.params.electionService, () => 'electionService is required')\n // }\n\n // protected get pendingBundledTransactionsArchivist() {\n // return assertEx(this.params.pendingBundledTransactionsArchivist, () => 'pendingBundledTransactions is required')\n // }\n\n // protected get blockRewardService() {\n // return assertEx(this.params.blockRewardService, () => 'blockRewardService is required')\n // }\n\n override async createHandler() {\n await super.createHandler()\n this._blockViewer = await this.locator.getInstance(BlockViewerMoniker)\n }\n\n validatePendingBlock(_block: BlockBoundWitness): Promisable<Error[]> {\n return [] // await validateBlockProtocol(block, this.chainInfo)\n }\n\n // TODO: Move to validator and inherit this class from validator\n async validatePendingTransaction(hydratedTransaction: SignedHydratedTransactionWithStorageMeta): Promise<boolean> {\n const [tx] = hydratedTransaction\n // Ensure not confirmed already (replay attack)\n if ((await this.blockViewer.blockByHash(tx._hash)) !== undefined) return false\n // TODO: Ensure transaction is valid (double spend, has voucher, has required stake, etc.)\n // TODO: Ensure validator stake is valid\n return await Promise.resolve(true)\n }\n}\n", "import type { Hash } from '@ariestools/sdk'\nimport { assertEx } from '@ariestools/sdk'\nimport type { WithHashMeta, XyoAddress } from '@xyo-network/sdk'\nimport {\n AbstractCreatableProvider,\n type BlockBoundWitness,\n type BlockViewer,\n type ChainStakeViewer, creatableProvider,\n type ElectionService, type StakeIntentService,\n} from '@xyo-network/xl1-sdk'\n\nimport { hexToLast4BytesInt, shuffleWithSeed } from '#utils'\n\nimport type { BaseServiceParams } from '../model/index.ts'\n\nexport interface BaseElectionServicesParams extends BaseServiceParams {\n blockViewer?: BlockViewer\n chainStakeViewer?: ChainStakeViewer\n stakeIntentService?: StakeIntentService\n}\n\n@creatableProvider()\nexport class BaseElectionService extends AbstractCreatableProvider<BaseElectionServicesParams> implements ElectionService {\n static readonly connectionTypes = [] as const\n static readonly defaultMoniker = 'Election'\n static readonly dependencies = []\n static readonly monikers = ['Election']\n moniker = BaseElectionService.defaultMoniker\n get blockViewer() {\n return assertEx(this.params.blockViewer, () => 'No block viewer')\n }\n\n get chainStakeViewer() {\n return assertEx(this.params.chainStakeViewer, () => 'No chain stake viewer')\n }\n\n get stakeIntentService() {\n return assertEx(this.params.stakeIntentService, () => 'No staked intent service')\n }\n\n async getCreatorCommitteeForNextBlock(current: WithHashMeta<BlockBoundWitness>): Promise<XyoAddress[]> {\n return await this.spanAsync('getCreatorCommitteeForNextBlock', async () => {\n const nextBlock = current.block + 1\n const candidates = await this.stakeIntentService.getDeclaredCandidatesForBlock(nextBlock, 'producer')\n const previousBlockHash = current._hash\n return this.generateCreatorCommittee(candidates, previousBlockHash)\n }, this.context)\n }\n\n protected generateCreatorCommittee(candidates: XyoAddress[], previousBlockHash: Hash, maxSize = 3): XyoAddress[] {\n const creators = new Set<XyoAddress>(candidates)\n const seed = hexToLast4BytesInt(previousBlockHash)\n const creatorArray = shuffleWithSeed(creators, seed)\n return creatorArray.slice(0, maxSize)\n }\n}\n", "import { toAddress } from '@ariestools/sdk'\nimport type { AccountInstance, XyoAddress } from '@xyo-network/sdk'\nimport type {\n AttoXL1, ChainId, SignedHydratedBlockWithHashMeta,\n} from '@xyo-network/xl1-sdk'\nimport { createDeclarationIntent } from '@xyo-network/xl1-sdk'\n\nimport { buildNextBlock, createGenesisBlock } from '#protocol'\n\nexport const createBootstrapHead = async (\n account: AccountInstance,\n chainId: ChainId,\n genesisBlockRewardAmount: AttoXL1,\n genesisBlockRewardAddress: XyoAddress,\n): Promise<SignedHydratedBlockWithHashMeta[]> => {\n const chain: SignedHydratedBlockWithHashMeta[] = []\n\n // Create genesis block\n const genesisBlock = await createGenesisBlock(account, chainId, genesisBlockRewardAmount, genesisBlockRewardAddress)\n chain.push(genesisBlock)\n\n // Create producer declaration block\n const producerDeclarationPayload = createDeclarationIntent(\n toAddress(account.address),\n 'producer',\n genesisBlock[0].block,\n genesisBlock[0].block + 10_000,\n )\n const producerDeclarationBlock = await buildNextBlock(\n genesisBlock[0],\n [],\n [producerDeclarationPayload],\n [account],\n )\n chain.push(producerDeclarationBlock)\n return chain\n}\n", "import type { Address, Logger } from '@ariestools/sdk'\nimport { assertEx, isDefined } from '@ariestools/sdk'\nimport type {\n BaseContext, BlockValidationViewer, BlockViewer, DeadLetterQueueRunner, FinalizationRunner, MempoolViewer,\n} from '@xyo-network/xl1-sdk'\nimport { BlockRejectionSchema, isSignedHydratedBlockWithHashMeta } from '@xyo-network/xl1-sdk'\n\nimport { ChainHeadSelector } from '#analyze'\n\n// type FinalizedBlockAttributes = { producer: Address }\n\ninterface ProcessPendingBlocksParams {\n allowedProducers?: Address[]\n blockValidationViewer: BlockValidationViewer\n blockViewer: BlockViewer\n context: BaseContext\n deadLetterQueueRunner?: DeadLetterQueueRunner\n finalizationRunner: FinalizationRunner\n logger?: Logger\n mempoolViewer: MempoolViewer\n minCandidates?: number\n}\n\n// eslint-disable-next-line complexity\nexport async function processPendingBlocks({\n blockValidationViewer, blockViewer, context, logger, mempoolViewer, finalizationRunner, allowedProducers, minCandidates, deadLetterQueueRunner,\n}: ProcessPendingBlocksParams) {\n const start = Date.now()\n\n const currentBlock = await blockViewer.currentBlock()\n\n const headSelector = new ChainHeadSelector({\n context, logger, mempoolViewer, blockViewer, windowedFinalizedChain: [currentBlock], allowedProducers, minCandidates,\n })\n\n // Use the head selector to find the best head or fallback to the starting head\n const bestHeadChain = await headSelector.findBestHead()\n\n // If we found a head\n if (isDefined(bestHeadChain) && bestHeadChain.length > 0) {\n const oldHeadBlock = currentBlock[0]\n const newHydratedHeadBlock = assertEx(bestHeadChain.at(-1), () => 'Missing best head block [processPendingBlocks]')\n const newHeadBlock = newHydratedHeadBlock[0]\n // let finalizedBlocksAttributes: FinalizedBlockAttributes[] = []\n\n // Synchronize the best head with the outArchivist all the way\n // back to the last finalized block\n\n logger?.debug('Validating new HeadBlock head from (block) ', oldHeadBlock?.block, 'to', newHeadBlock.block)\n logger?.debug('Validating new HeadBlock head from (hash) ', oldHeadBlock?._hash, 'to', newHeadBlock._hash)\n\n if (newHeadBlock._hash === oldHeadBlock?._hash) {\n logger?.debug('No new blocks found', oldHeadBlock?.block, 'to', newHeadBlock.block)\n return\n }\n\n // Store the items to be committed in the correct order\n const candidateBlocks = bestHeadChain.filter((b) => {\n return isDefined(oldHeadBlock) ? b[0].block > oldHeadBlock.block : true\n })\n\n // Validate candidate blocks before finalizing\n const validationResults = await Promise.all(candidateBlocks.map(candidateBlock => Promise.resolve(blockValidationViewer.validateBlocks([candidateBlock], { value: true, state: true }))))\n const blocksToFinalize: typeof candidateBlocks = []\n for (const [i, block] of candidateBlocks.entries()) {\n const result = validationResults[i][0]\n if (isSignedHydratedBlockWithHashMeta(result)) {\n blocksToFinalize.push(block)\n } else {\n logger?.error('Block validation failed', block[0].block, block[0]._hash, JSON.stringify(result, null, 2))\n if (deadLetterQueueRunner) {\n const errors = Array.isArray(result)\n ? result.map(e => ({\n hash: block[0]._hash, name: 'BlockValidationError', message: String(e.message ?? e),\n }))\n : [{ hash: block[0]._hash, name: 'BlockValidationError' }]\n await deadLetterQueueRunner.rejectBlock({\n schema: BlockRejectionSchema, block, errors, rejector: 'validator',\n })\n }\n }\n }\n\n logger?.info('Validated new HeadBlock head from (block) in', `${Date.now() - start}ms`, newHeadBlock.block, 'to', oldHeadBlock?.block)\n logger?.info('Validated new HeadBlock head from (hash) in', `${Date.now() - start}ms`, newHeadBlock._hash, 'to', oldHeadBlock?._hash)\n\n if (blocksToFinalize.length > 0) {\n await finalizationRunner.finalizeBlocks(blocksToFinalize)\n }\n\n // Prevent us from rechecking the same head\n await headSelector.finalizeChainFragment(blocksToFinalize)\n\n // this._startingHead = newHydratedHeadBlock\n\n // Return the finalized payloads\n return blocksToFinalize\n }\n // If no head was found, return an empty array\n logger?.info('No head found to validate', currentBlock?.[0]._hash)\n}\n", "import type { Address, Promisable } from '@ariestools/sdk'\nimport type { ReadArchivist } from '@xyo-network/sdk'\nimport type {\n AttoXL1,\n NetworkStakeStepRewardService,\n StepIdentity,\n StepIdentityString,\n} from '@xyo-network/xl1-sdk'\nimport {\n AbstractCreatableProvider,\n creatableProvider, NetworkStakeStepRewardViewerMoniker,\n} from '@xyo-network/xl1-sdk'\n\nimport type { BaseServiceParams } from '../model/index.ts'\n\nexport interface BaseNetworkStakeStepRewardServiceParams extends BaseServiceParams {\n chainArchivist: ReadArchivist\n}\n\n@creatableProvider()\nexport class BaseNetworkStakeStepRewardService extends\n AbstractCreatableProvider<BaseNetworkStakeStepRewardServiceParams> implements NetworkStakeStepRewardService {\n static readonly connectionTypes = [] as const\n static readonly defaultMoniker = NetworkStakeStepRewardViewerMoniker\n static readonly dependencies = []\n static readonly monikers = [NetworkStakeStepRewardViewerMoniker]\n override moniker = BaseNetworkStakeStepRewardService.defaultMoniker\n\n networkStakeStepRewardAddressHistory(_address: Address): Promisable<Record<Address, AttoXL1>> {\n throw new Error('Method [networkStakeStepRewardAddressHistory] not implemented.')\n }\n\n networkStakeStepRewardAddressReward(_context: StepIdentity, _address: Address): Promisable<Record<Address, AttoXL1>> {\n throw new Error('Method [networkStakeStepRewardAddressReward] not implemented.')\n }\n\n networkStakeStepRewardAddressShare(_context: StepIdentity, _address: Address): Promisable<[bigint, bigint]> {\n throw new Error('Method [networkStakeStepRewardAddressShare] not implemented.')\n }\n\n networkStakeStepRewardClaimedByAddress(_address: Address): Promisable<AttoXL1> {\n throw new Error('Method [networkStakeStepRewardClaimedByAddress] not implemented.')\n }\n\n networkStakeStepRewardForPosition(_position: number, _range: [number, number]): Promisable<[AttoXL1, AttoXL1]> {\n throw new Error('Method [networkStakeStepRewardForPosition] not implemented.')\n }\n\n networkStakeStepRewardForStep(_context: StepIdentity): Promisable<AttoXL1> {\n throw new Error('Method [networkStakeStepRewardForStep] not implemented.')\n }\n\n networkStakeStepRewardForStepForPosition(_context: StepIdentity, _position: number): Promisable<[AttoXL1, AttoXL1]> {\n throw new Error('Method [networkStakeStepRewardForStepForPosition] not implemented.')\n }\n\n networkStakeStepRewardPoolRewards(_context: StepIdentity): Promisable<Record<Address, AttoXL1>> {\n throw new Error('Method [networkStakeStepRewardPoolRewards] not implemented.')\n }\n\n networkStakeStepRewardPoolShares(_context: StepIdentity): Promisable<Record<Address, bigint>> {\n throw new Error('Method [networkStakeStepRewardPoolShares] not implemented.')\n }\n\n networkStakeStepRewardPositionWeight(_context: StepIdentity, _position: number): Promisable<bigint> {\n throw new Error('Method [networkStakeStepRewardPositionWeight] not implemented.')\n }\n\n networkStakeStepRewardPotentialPositionLoss(_context: StepIdentity, _position: number): Promisable<AttoXL1> {\n throw new Error('Method [networkStakeStepRewardPotentialPositionLoss] not implemented.')\n }\n\n networkStakeStepRewardRandomizer(_context: StepIdentity): Promisable<AttoXL1> {\n throw new Error('Method [networkStakeStepRewardRandomizer] not implemented.')\n }\n\n networkStakeStepRewardStakerCount(_context: StepIdentity): Promisable<number> {\n throw new Error('Method [networkStakeStepRewardStakerCount] not implemented.')\n }\n\n networkStakeStepRewardUnclaimedByAddress(_address: Address): Promisable<AttoXL1> {\n throw new Error('Method [networkStakeStepRewardUnclaimedByAddress] not implemented.')\n }\n\n networkStakeStepRewardWeightForAddress(_context: StepIdentity, _address: Address): Promisable<bigint> {\n throw new Error('Method [networkStakeStepRewardWeightForAddress] not implemented.')\n }\n\n networkStakeStepRewardsForPosition(_position: number, _range: [number, number]): Promisable<Record<StepIdentityString, [AttoXL1, AttoXL1]>> {\n throw new Error('Method [networkStakeStepRewardsForPosition] not implemented.')\n }\n\n networkStakeStepRewardsForRange(_range: [number, number]): Promisable<AttoXL1> {\n throw new Error('Method [networkStakeStepRewardsForRange] not implemented.')\n }\n\n networkStakeStepRewardsForStepLevel(_stepLevel: number, _range: [number, number]): Promisable<AttoXL1> {\n throw new Error('Method [networkStakeStepRewardsForStepLevel] not implemented.')\n }\n}\n", "import type {\n Address, Hash, Promisable,\n} from '@ariestools/sdk'\nimport {\n asAddress,\n assertEx, hexToBigInt, isDefined, toAddress,\n} from '@ariestools/sdk'\nimport type {\n AccountInstance,\n ArchivistInstance, WithHashMeta, XyoAddress,\n} from '@xyo-network/sdk'\nimport {\n MemoryArchivist,\n PayloadBuilder,\n} from '@xyo-network/sdk'\nimport type {\n AccountBalanceViewer, AllowedBlockPayload, BlockBoundWitness,\n BlockNumberPayload, BlockRewardViewer, BlockRunner, BlockValidationViewer, ChainId, ChainStakeIntent, CreatableProviderParams,\n DeadLetterQueueRunner,\n FinalizationViewer,\n HydratedBlockStateValidationFunction, HydratedBlockValidationError, MempoolViewer,\n SignedBlockBoundWitnessWithHashMeta,\n SignedHydratedBlockWithHashMeta, SignedHydratedTransactionWithHashMeta,\n TimePayload, TimeSyncViewer, Transfer,\n} from '@xyo-network/xl1-sdk'\nimport {\n AbstractCreatableProvider, AccountBalanceViewerMoniker, asBlockBoundWitness, AttoXL1,\n BlockNumberSchema, BlockRejectionSchema, BlockRewardViewerMoniker, BlockRunnerMoniker,\n BlockValidationViewerMoniker, connectArchivist, creatableProvider, createDeclarationIntent, DeadLetterQueueRunnerMoniker, defaultRewardRatio,\n FinalizationViewerMoniker, isSignedHydratedBlockWithHashMeta, isTransfer, MempoolViewerMoniker, REJECTED_TRANSACTIONS_ARCHIVIST_ROLE,\n TimeSyncViewerMoniker,\n TransactionRejectionSchema, XYO_STEP_REWARD_ADDRESS,\n} from '@xyo-network/xl1-sdk'\n\nimport type { BlockRewardDiviner } from '#modules'\nimport { FixedPercentageBlockRewardDiviner, FixedPercentageBlockRewardDivinerConfigSchema } from '#modules'\nimport { buildNextBlock } from '#protocol'\n\nimport { generateTransactionFeeTransfers } from './generateTransactionFeeTransfers.ts'\nimport { identifyOffendingTransactions } from './identifyOffendingTransactions.ts'\nimport { producerTuningFromConfig } from './producerTuning.ts'\n\n/**\n * The default block size for a block\n */\nexport const DEFAULT_BLOCK_SIZE = 10\n\n/**\n * The amount of time for which a producer will restake their intent\n */\nexport const XYO_PRODUCER_REDECLARATION_DURATION = 100\n\n/**\n * The number of blocks within which a producer will redeclare\n * their intent to produce blocks\n */\nexport const XYO_PRODUCER_REDECLARATION_WINDOW = 100\n\nexport interface SimpleBlockRunnerParams extends CreatableProviderParams {\n /** Explicit signing account (deprecated path) \u2014 defaults to the context signer registry. */\n account?: AccountInstance\n disableIntentRedeclaration?: boolean\n heartbeatInterval?: number\n rejectedTransactionsArchivist?: ArchivistInstance\n /** Defaults to `config.rewardAddress` (producer config), then the signing account's address. */\n rewardAddress?: Address\n /**\n * When `true` (default), `filterByFunded` enforces the same cumulative-outflow\n * vs balance rule the post-submit block validator uses\n * (`base + priority + gasLimit + transfer amounts`). Setting this to `false`\n * is only appropriate for unit-style tests that exercise block-production\n * mechanics with synthetic unfunded senders and don't model balances.\n */\n validateBalances?: boolean\n validateHydratedBlockState?: HydratedBlockStateValidationFunction\n}\n\n@creatableProvider()\nexport class SimpleBlockRunner extends AbstractCreatableProvider<SimpleBlockRunnerParams> implements BlockRunner {\n static readonly connectionTypes = ['lmdb', 'mongo', 'memory'] as const\n static readonly defaultMoniker = BlockRunnerMoniker\n static readonly dependencies = [\n AccountBalanceViewerMoniker,\n BlockRewardViewerMoniker,\n BlockValidationViewerMoniker,\n FinalizationViewerMoniker,\n MempoolViewerMoniker,\n TimeSyncViewerMoniker,\n ]\n\n static readonly monikers = [BlockRunnerMoniker]\n static readonly surface = 'node' as const\n moniker = SimpleBlockRunner.defaultMoniker\n\n protected _blockRewardDiviner?: BlockRewardDiviner\n protected _deadLetterQueueRunner?: DeadLetterQueueRunner\n // TODO(producer-exclusion-set): uncapped for v1. If memory grows in long-running producers,\n // add FIFO eviction or a TTL keyed off block number.\n protected _excludedTransactionHashes = new Set<Hash>()\n protected _lastRedeclarationBlock?: number\n protected _rejectedTransactionsArchivist?: ArchivistInstance\n\n private _account?: AccountInstance\n private _accountBalanceViewer?: AccountBalanceViewer\n private _address?: Address\n private _blockRewardViewer?: BlockRewardViewer\n private _blockValidationViewer?: BlockValidationViewer\n private _finalizationViewer?: FinalizationViewer\n private _mempoolViewer?: MempoolViewer\n private _rewardAddress?: Address\n private _timeSyncViewer?: TimeSyncViewer\n\n /**\n * The default block size for a block\n */\n static get DefaultBlockSize(): number {\n return DEFAULT_BLOCK_SIZE\n }\n\n /**\n * The amount of time for which the producer will redeclare\n * their intent to continue producing blocks\n */\n static get RedeclarationDuration(): number {\n return XYO_PRODUCER_REDECLARATION_DURATION\n }\n\n /**\n * The number of blocks within which the producer will redeclare\n * their intent to continue producing blocks\n */\n static get RedeclarationWindow(): number {\n return XYO_PRODUCER_REDECLARATION_WINDOW\n }\n\n protected get account() {\n return this._account!\n }\n\n protected get accountBalanceViewer() {\n return this._accountBalanceViewer!\n }\n\n protected get address() {\n return this._address!\n }\n\n protected get blockRewardViewer() {\n return this._blockRewardViewer!\n }\n\n protected get blockValidationViewer() {\n return this._blockValidationViewer!\n }\n\n protected get finalizationViewer() {\n return this._finalizationViewer!\n }\n\n protected get heartbeatInterval() {\n return this.params.heartbeatInterval ?? this.producerTuning.heartbeatInterval ?? 3_600_000\n }\n\n protected get mempoolViewer() {\n return this._mempoolViewer!\n }\n\n protected get producerTuning() {\n return producerTuningFromConfig(this.config)\n }\n\n // protected get pendingTransactionsService() {\n // return assertEx(this.params.pendingTransactionsService, () => 'Missing pendingTransactionsService')\n // }\n\n protected get rejectedTransactionsArchivist() {\n return this._rejectedTransactionsArchivist!\n }\n\n protected get rewardAddress(): Address {\n return this._rewardAddress!\n }\n\n // protected get stakeIntentService(): StakeIntentService {\n // return assertEx(this.params.stakeIntentService, () => 'No StakeIntentService provided')\n // }\n\n protected get timeSyncViewer(): TimeSyncViewer {\n return this._timeSyncViewer!\n }\n\n // protected get validateHydratedBlockState() {\n // return assertEx(this.params.validateHydratedBlockState, () => 'validateHydratedBlockState is required')\n // }\n\n override async createHandler() {\n const boundConnection = this.boundConnection\n this._rejectedTransactionsArchivist = this.params.rejectedTransactionsArchivist\n ?? (boundConnection\n ? await connectArchivist(boundConnection, { name: REJECTED_TRANSACTIONS_ARCHIVIST_ROLE })\n : await MemoryArchivist.create())\n this._account = assertEx(\n this.params.account ?? this.contextSigner,\n () => 'Account is required \u2014 inject params.account or register a context signer',\n )\n this._address = toAddress(this.account.address)\n this._accountBalanceViewer = await this.locateAndCreate<AccountBalanceViewer>(AccountBalanceViewerMoniker)\n this._blockRewardViewer = await this.locateAndCreate<BlockRewardViewer>(BlockRewardViewerMoniker)\n this._blockValidationViewer = await this.locator.getInstance<BlockValidationViewer>(BlockValidationViewerMoniker)\n this._finalizationViewer = await this.locateAndCreate<FinalizationViewer>(FinalizationViewerMoniker)\n this._mempoolViewer = await this.locateAndCreate<MempoolViewer>(MempoolViewerMoniker)\n this._rewardAddress = asAddress(this.params.rewardAddress ?? this.producerTuning.rewardAddress ?? this.account.address, true)\n this._timeSyncViewer = await this.locateAndCreate<TimeSyncViewer>(TimeSyncViewerMoniker)\n this._deadLetterQueueRunner = await this.locator.tryGetInstance<DeadLetterQueueRunner>(DeadLetterQueueRunnerMoniker)\n }\n\n async next(head: WithHashMeta<BlockBoundWitness>): Promise<SignedHydratedBlockWithHashMeta | undefined> {\n // If the block is for another chain, ignore\n // if (head.chain !== this.chainId) return\n // const leadersStart = Date.now()\n // const leaders = await this.electionService.getCreatorCommitteeForNextBlock(head)\n // const leadersDuration = Date.now() - leadersStart\n // if (leadersDuration > 100) {\n // this.logger?.warn(`[Slow] Fetched leaders in ${leadersDuration}ms: ${leaders.map(l => l.slice(0, 6)).join(', ')}`)\n // }\n // TODO: Should we propose block if creator committee is empty?\n // TODO: Handle the case where we're not the 1st leader but they're not responding\n // at a higher level than here as that's a network issue\n // if (!leaders.includes(this.address)) return\n return await this.proposeNextValidBlock(head)\n }\n\n async produceNextBlock(head: SignedBlockBoundWitnessWithHashMeta, force: true): Promise<SignedHydratedBlockWithHashMeta>\n async produceNextBlock(head: SignedBlockBoundWitnessWithHashMeta, force?: false): Promise<SignedHydratedBlockWithHashMeta | undefined>\n async produceNextBlock(head: SignedBlockBoundWitnessWithHashMeta, force?: boolean): Promise<SignedHydratedBlockWithHashMeta | undefined> {\n // assertEx(head.chain === this.chainId, () => 'Block chain ID does not match')\n const result = await this.proposeNextValidBlock(head)\n return force === true ? assertEx(result, () => 'Failed to produce next block') : result\n }\n\n protected async getBlockRewardTransfers(block: number): Promise<Transfer[]> {\n this._blockRewardDiviner ??= await FixedPercentageBlockRewardDiviner.create({\n account: 'random',\n blockRewardViewer: this.blockRewardViewer,\n config: {\n rewardAddress: this.rewardAddress,\n rewardPercentageRatio: defaultRewardRatio,\n schema: FixedPercentageBlockRewardDivinerConfigSchema,\n },\n })\n\n const blockIdBuilder = new PayloadBuilder<BlockNumberPayload>({ schema: BlockNumberSchema })\n const blockId = blockIdBuilder.fields({ block }).build()\n const rewards = await this._blockRewardDiviner.divine([blockId])\n return rewards as Transfer[]\n }\n\n /**\n * Handles the producer redeclaration logic\n * @param head The current head block\n * @returns chain stake intent for the producer redeclaration, or undefined if no redeclaration is needed\n */\n protected getProducerRedeclaration(head: WithHashMeta<BlockBoundWitness>): Promisable<ChainStakeIntent | undefined> {\n if ((this.params.disableIntentRedeclaration ?? this.producerTuning.disableIntentRedeclaration) === true) return\n const currentBlock = head.block\n // Only redeclare when the previous declaration has expired\n if (isDefined(this._lastRedeclarationBlock)) {\n const lastDeclarationExpiry = this._lastRedeclarationBlock + SimpleBlockRunner.RedeclarationDuration\n if (currentBlock < lastDeclarationExpiry) return\n }\n this._lastRedeclarationBlock = currentBlock\n return createDeclarationIntent(this.address, 'producer', currentBlock, currentBlock + SimpleBlockRunner.RedeclarationDuration)\n }\n\n // `validateBalances` resolves from (a) the explicit method argument when\n // passed, (b) the constructor `params.validateBalances`, or (c) `true`.\n // True is the safe default: `filterByFunded` then enforces the same\n // cumulative-outflow rule the post-submit block validator uses\n // (`base + priority + gasLimit + transfer amounts`). With the old default\n // of `false`, a tx whose declared gasLimit exceeded the sender's balance\n // would pass the producer's filter, get submitted, and then land in\n // `rejected_blocks` \u2014 silently wedging the chain because the producer's\n // `_lastProducedBlock` cache muted retries. Reproduced in the\n // api-local-mongodb-beta test rig.\n protected async proposeNextValidBlock(head: WithHashMeta<BlockBoundWitness>, validateBalances?: boolean, force = false) {\n const shouldValidateBalances = validateBalances ?? this.params.validateBalances ?? true\n return await this.spanAsync('proposeNextValidBlock', async () => {\n try {\n // Calculate the next block components\n const { block: previousBlock } = assertEx(asBlockBoundWitness(head), () => 'Invalid head block')\n const nextBlock = previousBlock + 1\n const chainId = await this.finalizationViewer.chainId()\n const pendingTransactionsRaw = await this.mempoolViewer.pendingTransactions({ limit: SimpleBlockRunner.DefaultBlockSize })\n const pendingTransactions = pendingTransactionsRaw.filter(tx => !this._excludedTransactionHashes.has(tx[0]._hash))\n const nextBlockTransactions = await this.rejectWrongChainTransactions(pendingTransactions, chainId)\n\n this.logger?.log(`Pending Tx Count ${nextBlockTransactions.length}`)\n\n const nonTxPayloads: AllowedBlockPayload[] = []\n\n // Calculate the optional producer redeclaration and add it if necessary\n const producerRedeclarationPayload = await this.getProducerRedeclaration(head)\n if (producerRedeclarationPayload) nonTxPayloads.push(producerRedeclarationPayload)\n\n // If there are no transactions, no payloads and no heartbeat required, we don't need to create a block\n if (nextBlockTransactions.length === 0 && !this.heartbeatRequired(head) && !force) return\n\n // Calculate the optional block reward transfer and add if necessary\n const rewardTransferPayloads = await this.getBlockRewardTransfers(nextBlock)\n nonTxPayloads.push(...rewardTransferPayloads)\n\n const transactionTransfers = await generateTransactionFeeTransfers(this.address, nextBlockTransactions)\n const timeStart = Date.now()\n const timePayload = await this.generateTimePayload()\n const timeDuration = Date.now() - timeStart\n if (timeDuration > 100) {\n this.logger?.warn(`[Slow] Generated time payload in ${timeDuration}ms`)\n }\n\n const [initialFundedTransactions, initialFundedTransfers]\n = await this.filterByFunded(head, nextBlockTransactions, transactionTransfers, shouldValidateBalances)\n\n const stepRewardBalances = await this.accountBalanceViewer.accountBalances([XYO_STEP_REWARD_ADDRESS])\n const stepRewardPoolBalance = (stepRewardBalances as Record<string, AttoXL1>)[String(XYO_STEP_REWARD_ADDRESS)]\n\n const result = await this.runBuildValidateRetryLoop({\n head,\n chainId,\n stepRewardPoolBalance,\n nonTxPayloads,\n timePayload,\n initialFundedTransactions,\n initialFundedTransfers,\n })\n const { block: proposedBlock, errors: proposedErrors } = result\n if (isSignedHydratedBlockWithHashMeta(proposedBlock)) {\n // Submission is the producer's responsibility (`ProducerActor.produceBlock`)\n // \u2014 SimpleBlockRunner just builds and validates. Previously this site\n // also called `mempoolRunner.submitBlocks`, double-submitting the\n // same block. The second submit at the producer always failed with\n // \"archivist accepted 0 of 1\" because the inner one had already\n // landed. Removing the inner submit eliminates that false positive\n // and means SimpleBlockRunner no longer needs a MempoolRunner\n // dependency at all.\n return proposedBlock\n }\n if (proposedBlock !== undefined) await this.rejectExhaustedBlock(proposedBlock, proposedErrors)\n } catch (error) {\n this.logger?.error(`Error proposing next valid block: ${(error as Error).message}`)\n throw error\n }\n }, this.context)\n }\n\n /**\n * Compute the cumulative outflow a single tx would charge to its `from`\n * address, using the same rule as `BlockCumulativeBalanceValidator`:\n * `outflow = base + priority + gasLimit + sum(transfer amounts to addresses\n * other than from)`. Mirroring the validator exactly here ensures the\n * producer doesn't include a tx that the post-submit block validator will\n * reject, which would otherwise wedge the chain because the producer's\n * `_lastProducedBlock` cache mutes retries.\n */\n private addTransferOutflow(outflow: bigint, payload: Transfer): bigint {\n let result = outflow\n for (const [to, amount] of Object.entries(payload.transfers)) {\n if (to === payload.from) continue\n result += hexToBigInt((amount ?? '00'))\n }\n return result\n }\n\n private computeTransactionOutflow(tx: SignedHydratedTransactionWithHashMeta): bigint {\n const [bw, payloads] = tx\n const {\n base, gasLimit, priority,\n } = bw.fees\n let outflow = hexToBigInt(base) + hexToBigInt(priority) + hexToBigInt(gasLimit)\n const txPayloadHashes = new Set(bw.payload_hashes)\n for (const payload of payloads) {\n if (!txPayloadHashes.has(payload._hash)) continue\n if (!isTransfer(payload)) continue\n if (payload.from !== bw.from) continue\n outflow = this.addTransferOutflow(outflow, payload)\n }\n return outflow\n }\n\n // remove unfunded transactions and block transfers\n private async filterByFunded(\n head: WithHashMeta<BlockBoundWitness>,\n txs: SignedHydratedTransactionWithHashMeta[],\n transfers: Transfer[],\n validateBalances = false,\n ): Promise<[SignedHydratedTransactionWithHashMeta[], Transfer[]]> {\n const fundedTransfers: Transfer[] = []\n const fundedTransactions: SignedHydratedTransactionWithHashMeta[] = []\n // Outflow already committed to this block per sender, plus a per-sender\n // balance cache (balances are read at the fixed parent `head`). Each tx is\n // gated against the sender's REMAINING balance, not the full balance in\n // isolation. Checking each tx independently (the previous behavior) lets two\n // individually-valid transfers from the same sender \u2014 a double-spend across\n // transactions, each \u2264 balance but jointly > balance \u2014 both pass. The block\n // then carries a cumulative outflow the post-submit validator rejects, and\n // the producer wedges (its `_lastProducedBlock` cache mutes retries).\n // Sequential, cumulative gating includes only the first transfer that fits\n // and drops the rest; the dropped tx stays pending and is pruned once the\n // included one lands and the sender can no longer cover it.\n const committedOutflow = new Map<XyoAddress, bigint>()\n const balanceCache = new Map<XyoAddress, bigint>()\n for (const tx of txs) {\n const transfer: Transfer | undefined = transfers.find(candidate => candidate.from === tx[0].from)\n if (!transfer) continue\n if (!validateBalances) {\n fundedTransfers.push(transfer)\n fundedTransactions.push(tx)\n continue\n }\n const { from } = transfer\n let balance = balanceCache.get(from)\n if (balance === undefined) {\n const accountBalances = await this.accountBalanceViewer.accountBalances([from])\n balance = (accountBalances as Record<string, bigint>)[String(from)] ?? AttoXL1(0n)\n balanceCache.set(from, balance)\n }\n // Mirror the post-submit block validator's cumulative-outflow rule\n // (base + priority + gasLimit + transfer amounts) against the running\n // total for this sender, so the producer never includes a tx the\n // validator will reject.\n const projectedOutflow = (committedOutflow.get(from) ?? 0n) + this.computeTransactionOutflow(tx)\n if (balance >= projectedOutflow) {\n committedOutflow.set(from, projectedOutflow)\n fundedTransfers.push(transfer)\n fundedTransactions.push(tx)\n } else {\n this.logger?.debug(\n `filterByFunded: dropping tx ${tx[0]._hash} from ${from} \u2014 cumulative outflow ${projectedOutflow} > balance ${balance}`,\n )\n }\n }\n return [fundedTransactions, fundedTransfers]\n }\n\n private async generateTimePayload() {\n return await this.timeSyncViewer.currentTimePayload()\n }\n\n /**\n * Check if a heartbeat block is required based on network activity.\n * @param head The current head block\n * @returns True if a heartbeat is required, false otherwise\n */\n private heartbeatRequired(head: WithHashMeta<BlockBoundWitness>): boolean {\n const epoch = head.$epoch\n if (isDefined(epoch) && Date.now() - epoch > this.heartbeatInterval) {\n return true\n }\n return false\n }\n\n private async rejectExhaustedBlock(\n block: SignedHydratedBlockWithHashMeta,\n errors: HydratedBlockValidationError[],\n ): Promise<void> {\n this.logger?.warn(`Validation of produced block failed: ${errors.at(0)?.message}`)\n if (this._deadLetterQueueRunner) {\n const rejectionErrors = errors.map(e => ({\n hash: block[0]._hash, name: 'BlockValidationError', message: String(e.message ?? e),\n }))\n await this._deadLetterQueueRunner.rejectBlock({\n schema: BlockRejectionSchema, block, errors: rejectionErrors, rejector: 'producer',\n })\n } else {\n await this.rejectedTransactionsArchivist.insert(block[1])\n }\n }\n\n // Partition pending transactions by chain-ID match; route mismatches to the transaction DLQ.\n private async rejectWrongChainTransactions(\n transactions: SignedHydratedTransactionWithHashMeta[],\n chainId: ChainId,\n ): Promise<SignedHydratedTransactionWithHashMeta[]> {\n const localChain = chainId.toLowerCase()\n const matched: SignedHydratedTransactionWithHashMeta[] = []\n const mismatched: SignedHydratedTransactionWithHashMeta[] = []\n for (const tx of transactions) {\n if (tx[0].chain.toLowerCase() === localChain) {\n matched.push(tx)\n } else {\n mismatched.push(tx)\n }\n }\n if (mismatched.length > 0) {\n this.logger?.warn(`Rejecting ${mismatched.length} transaction(s) targeting non-local chain`)\n const dlq = this._deadLetterQueueRunner\n await (dlq\n ? Promise.all(mismatched.map(tx => dlq.rejectTransaction({\n schema: TransactionRejectionSchema,\n transaction: tx,\n errors: [{\n hash: tx[0]._hash,\n name: 'TransactionChainMismatch',\n message: `Transaction chain ${tx[0].chain} does not match local chain ${localChain}`,\n }],\n rejector: 'producer',\n })))\n : this.rejectedTransactionsArchivist.insert(mismatched.map(tx => tx[0])))\n }\n return matched\n }\n\n private async runBuildValidateRetryLoop(args: {\n chainId: ChainId\n head: WithHashMeta<BlockBoundWitness>\n initialFundedTransactions: SignedHydratedTransactionWithHashMeta[]\n initialFundedTransfers: Transfer[]\n nonTxPayloads: AllowedBlockPayload[]\n stepRewardPoolBalance: AttoXL1\n timePayload: TimePayload\n }): Promise<{\n block: SignedHydratedBlockWithHashMeta | undefined\n errors: HydratedBlockValidationError[]\n }> {\n const {\n chainId, head, initialFundedTransactions, initialFundedTransfers,\n nonTxPayloads, stepRewardPoolBalance, timePayload,\n } = args\n const maxAttempts = Math.max(1, initialFundedTransactions.length)\n let candidateTransactions = initialFundedTransactions\n let candidateTransfers = initialFundedTransfers\n let lastBlock: SignedHydratedBlockWithHashMeta | undefined\n let lastErrors: HydratedBlockValidationError[] = []\n\n for (let attempt = 0; attempt <= maxAttempts; attempt++) {\n const blockPayloads = [...nonTxPayloads, ...candidateTransfers, timePayload]\n this.logger?.info(`Building block ${head.block + 1}${attempt > 0 ? ` (retry ${attempt})` : ''}`)\n lastBlock = await buildNextBlock(\n head,\n candidateTransactions,\n blockPayloads,\n [this.account],\n XYO_STEP_REWARD_ADDRESS,\n stepRewardPoolBalance,\n undefined,\n chainId,\n )\n const validated = await this.blockValidationViewer.validateBlock(lastBlock, { head: head._hash })\n if (isSignedHydratedBlockWithHashMeta(validated)) {\n return { block: validated, errors: [] }\n }\n lastErrors = validated\n if (attempt === maxAttempts) break\n const { offendingHashes, reason } = await identifyOffendingTransactions({ candidateTransactions, errors: validated })\n if (offendingHashes.length === 0 || reason === 'unknown') break\n for (const offendingHash of offendingHashes) this._excludedTransactionHashes.add(offendingHash)\n const offendingSet = new Set<Hash>(offendingHashes)\n candidateTransactions = candidateTransactions.filter(tx => !offendingSet.has(tx[0]._hash))\n const remainingFromAddresses = new Set<XyoAddress>(candidateTransactions.map(tx => tx[0].from))\n const feeTransfers = await generateTransactionFeeTransfers(this.address, candidateTransactions)\n candidateTransfers = feeTransfers.filter(t => remainingFromAddresses.has(t.from))\n this.logger?.warn(`Block validation failed (attempt ${attempt + 1}); excluded ${offendingHashes.length} tx(s), retrying`)\n }\n return { block: lastBlock, errors: lastErrors }\n }\n}\n", "import { assertEx, hexFromBigInt } from '@ariestools/sdk'\nimport type { XyoAddress } from '@xyo-network/sdk'\nimport { PayloadBuilder } from '@xyo-network/sdk'\nimport type {\n SignedHydratedTransaction,\n Transfer,\n XL1,\n} from '@xyo-network/xl1-sdk'\nimport {\n HydratedTransactionWrapper,\n transactionRequiredGas, TransferSchema, XYO_ZERO_ADDRESS,\n} from '@xyo-network/xl1-sdk'\n\nexport async function generateTransactionFeeTransfers(address: XyoAddress, transactions: SignedHydratedTransaction[]): Promise<Transfer[]> {\n const txs = await Promise.all(transactions.map(async (tx) => {\n return HydratedTransactionWrapper.parse([await PayloadBuilder.addStorageMeta(tx[0]), await PayloadBuilder.addStorageMeta(tx[1])])\n }))\n\n // merge transactions with the same from address\n const txBaseFeeCosts: Record<XyoAddress, bigint> = {}\n for (const tx of txs) {\n txBaseFeeCosts[tx.boundWitness.from] = (txBaseFeeCosts[tx.boundWitness.from] ?? 0n)\n + tx.fees.base\n }\n\n const txGasCosts: Record<XyoAddress, bigint> = {}\n for (const tx of txs) {\n const requiredGas = transactionRequiredGas(tx.data)\n const totalGasCost = requiredGas * tx.fees.gasPrice\n txGasCosts[tx.boundWitness.from] = (txBaseFeeCosts[tx.boundWitness.from] ?? 0n)\n + totalGasCost\n }\n\n // generate actual Transfer Payloads & burn the base fee\n const payloads = (Object.entries(txBaseFeeCosts) as [XyoAddress, XL1][]).map(([from, amount]) => {\n const payload: Transfer = {\n schema: TransferSchema,\n epoch: Date.now(),\n from,\n transfers: Object.fromEntries([[String(XYO_ZERO_ADDRESS), hexFromBigInt(amount)]]),\n }\n return payload\n })\n\n // transfer gas cost to producer\n for (const [from, amount] of Object.entries(txGasCosts)) {\n // every gas from should also be a base fee from\n const fromPayload = assertEx(payloads.find(p => p.from === from), () => 'from payload not found')\n fromPayload.transfers[address] = hexFromBigInt(amount)\n }\n\n return payloads\n}\n", "import type { Hash } from '@ariestools/sdk'\nimport type { HydratedBlockValidationError, SignedHydratedTransactionWithHashMeta } from '@xyo-network/xl1-sdk'\nimport {\n HydratedTransactionWrapper,\n netBalancesForPayloads,\n transactionRequiredGas,\n} from '@xyo-network/xl1-sdk'\n\nexport type OffendingTxReason = 'block-balance' | 'tx-invalid' | 'unknown'\n\nexport interface OffendingTxResult {\n offendingHashes: Hash[]\n reason: OffendingTxReason\n}\n\ninterface TxScore {\n cost: bigint\n gasPrice: bigint\n}\n\nasync function scoreTransaction(tx: SignedHydratedTransactionWithHashMeta): Promise<TxScore> {\n const wrapper = await HydratedTransactionWrapper.parse(tx)\n const from = wrapper.boundWitness.from\n const gasPrice = wrapper.fees.gasPrice\n const gasCost = transactionRequiredGas(tx) * gasPrice\n const baseCost = wrapper.fees.base\n const netBalances = netBalancesForPayloads({ singletons: {} }, tx[1])\n const fromNet = netBalances[from] ?? 0n\n const transferOut = fromNet < 0n ? -fromNet : 0n\n return { cost: gasCost + baseCost + transferOut, gasPrice }\n}\n\nexport async function identifyOffendingTransactions(args: {\n candidateTransactions: SignedHydratedTransactionWithHashMeta[]\n errors: HydratedBlockValidationError[]\n}): Promise<OffendingTxResult> {\n const { errors, candidateTransactions } = args\n const candidateHashes = new Set<Hash>(candidateTransactions.map(tx => tx[0]._hash))\n\n const txInvalidHashes = new Set<Hash>()\n for (const error of errors) {\n if (candidateHashes.has(error.hash)) txInvalidHashes.add(error.hash)\n const cause = error.cause as undefined | { hash?: Hash }\n if (cause?.hash && candidateHashes.has(cause.hash)) txInvalidHashes.add(cause.hash)\n }\n if (txInvalidHashes.size > 0) {\n return { offendingHashes: [...txInvalidHashes], reason: 'tx-invalid' }\n }\n\n const balanceOffenderHashes = new Set<Hash>()\n for (const error of errors) {\n const offendingHashes = (error as { offendingTransactionHashes?: Hash[] }).offendingTransactionHashes ?? []\n for (const hash of offendingHashes) {\n if (candidateHashes.has(hash)) balanceOffenderHashes.add(hash)\n }\n }\n if (balanceOffenderHashes.size === 0) {\n return { offendingHashes: [], reason: 'unknown' }\n }\n\n const offenders = candidateTransactions.filter(tx => balanceOffenderHashes.has(tx[0]._hash))\n const scored = await Promise.all(offenders.map(async tx => ({ tx, ...(await scoreTransaction(tx)) })))\n scored.sort((a, b) => {\n if (a.cost !== b.cost) return a.cost < b.cost ? 1 : -1\n if (a.gasPrice !== b.gasPrice) return a.gasPrice < b.gasPrice ? -1 : 1\n return a.tx[0]._hash < b.tx[0]._hash ? -1 : 1\n })\n return { offendingHashes: [scored[0].tx[0]._hash], reason: 'block-balance' }\n}\n", "/** Producer tuning fields read loosely from the producer actor config. */\nexport interface ProducerTuningFields {\n disableIntentRedeclaration?: boolean\n heartbeatInterval?: number\n rewardAddress?: string\n}\n\n/**\n * Producer tuning from the loose locator config: the lifted `producer` section\n * (see orchestration's providerTuningFromActors), else top-level fields\n * (actor-scoped or test configs).\n */\nexport function producerTuningFromConfig(config: unknown): ProducerTuningFields {\n const withSection = config as ProducerTuningFields & { producer?: ProducerTuningFields }\n return withSection.producer ?? withSection\n}\n", "import type { Promisable } from '@ariestools/sdk'\nimport type { ReadArchivist, XyoAddress } from '@xyo-network/sdk'\nimport type { StepIdentity, StepStakeViewer } from '@xyo-network/xl1-sdk'\nimport { AbstractCreatableProvider, StepStakeViewerMoniker } from '@xyo-network/xl1-sdk'\n\nimport type { BaseServiceParams } from '../model/index.ts'\n\nexport interface BaseStepStakeServiceParams extends BaseServiceParams {\n chainArchivist: ReadArchivist\n}\n\nexport abstract class AbstractStepStakeService extends AbstractCreatableProvider<BaseStepStakeServiceParams> implements StepStakeViewer {\n static readonly defaultMoniker = StepStakeViewerMoniker\n static readonly monikers = [StepStakeViewerMoniker]\n override moniker = AbstractStepStakeService.defaultMoniker\n\n stepStake(_step: StepIdentity): Promisable<Record<XyoAddress, bigint>> {\n throw new Error('Method [stepStake] not implemented.')\n }\n\n stepStakeForAddress(_address: XyoAddress, _step: StepIdentity): Promisable<bigint> {\n throw new Error('Method [stepStakeForAddress] not implemented.')\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;AACA;AAAA,EACE;AAAA,EACA;AAAA,EAAU;AAAA,EAAW;AAAA,OAChB;AACP,SAAS,iCAAiC;AAM1C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AASA,IAAM,uBAAN,cAAmC,kBAA2E;AAAA,EAKnH,UAAU,qBAAqB;AAAA,EAErB;AAAA,EAEV,IAAc,sBAAsB;AAClC,WAAO,SAAS,KAAK,OAAO,qBAAqB,MAAM,iCAAiC;AAAA,EAC1F;AAAA,EAEA,IAAc,k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AO,WAAW,QAAQ,WAAW;AAAA,EAChD;AACF;AAreE,cADW,mBACK,mBAAkB,CAAC,QAAQ,SAAS,QAAQ;AAC5D,cAFW,mBAEK,kBAAiB;AACjC,cAHW,mBAGK,gBAAe;AAAA,EAC7B;AAAA,EACAJ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,cAZW,mBAYK,YAAW,CAAC,kBAAkB;AAC9C,cAbW,mBAaK,WAAU;AAbf,oBAAN;AAAA,EADNO,mBAAkB;AAAA,GACN;;;AI3Eb,SAAS,6BAAAC,4BAA2B,8BAA8B;AAQ3D,IAAe,2BAAf,MAAe,kCAAiCA,2BAAiF;AAAA,EACtI,OAAgB,iBAAiB;AAAA,EACjC,OAAgB,WAAW,CAAC,sBAAsB;AAAA,EACzC,UAAU,0BAAyB;AAAA,EAE5C,UAAU,OAA6D;AACrE,UAAM,IAAI,MAAM,qCAAqC;AAAA,EACvD;AAAA,EAEA,oBAAoB,UAAsB,OAAyC;AACjF,UAAM,IAAI,MAAM,+CAA+C;AAAA,EACjE;AACF;",
6
+ "names": ["assertEx", "AbstractCreatableProvider", "creatableProvider", "AbstractCreatableProvider", "assertEx", "creatableProvider", "assertEx", "AbstractCreatableProvider", "creatableProvider", "AbstractCreatableProvider", "creatableProvider", "assertEx", "isDefined", "toAddress", "PayloadBuilder", "AbstractCreatableProvider", "BlockRejectionSchema", "BlockRewardViewerMoniker", "creatableProvider", "createDeclarationIntent", "isSignedHydratedBlockWithHashMeta", "buildNextBlock", "assertEx", "HydratedTransactionWrapper", "transactionRequiredGas", "AbstractCreatableProvider", "assertEx", "toAddress", "BlockRewardViewerMoniker", "PayloadBuilder", "isDefined", "createDeclarationIntent", "isSignedHydratedBlockWithHashMeta", "BlockRejectionSchema", "buildNextBlock", "creatableProvider", "AbstractCreatableProvider"]
7
7
  }
@@ -0,0 +1,25 @@
1
+ import type { Logger } from '@ariestools/sdk';
2
+ import type { Provider } from 'ethers';
3
+ /**
4
+ * Finds the first block where `address` has code via binary search on
5
+ * `eth_getCode` — `getCode(address, block)` is empty before deployment and
6
+ * non-empty forever after, so the flip point is the deployment block
7
+ * (~log2(head) probes; ~23 on an 11M-block chain).
8
+ *
9
+ * Historical `getCode` needs an archive-capable RPC. Returns undefined when
10
+ * the address has no code at head or any probe fails, so callers can fall
11
+ * back to an estimate.
12
+ */
13
+ export declare function findContractDeploymentBlock(provider: Provider, address: string): Promise<number | undefined>;
14
+ /**
15
+ * Reads `chain.deploymentBlock` from a locator config, structurally — the
16
+ * field ships in the SDK's ChainConfigZod but older SDK versions strip it.
17
+ */
18
+ export declare function configuredDeploymentBlock(config: unknown): number | undefined;
19
+ /**
20
+ * Resolves the deployment block for `address`: exact binary search first,
21
+ * falling back to the date-based estimate (2025-06-01 heuristic) when the RPC
22
+ * cannot answer historical `getCode` probes.
23
+ */
24
+ export declare function resolveContractDeploymentBlock(provider: Provider, address: string, logger?: Logger): Promise<number>;
25
+ //# sourceMappingURL=findContractDeploymentBlock.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"findContractDeploymentBlock.d.ts","sourceRoot":"","sources":["../../../../../src/modules/ethereum/block/findContractDeploymentBlock.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAC7C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAA;AAWtC;;;;;;;;;GASG;AACH,wBAAsB,2BAA2B,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAelH;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAI7E;AAED;;;;GAIG;AACH,wBAAsB,8BAA8B,CAClD,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,MAAM,EACf,MAAM,CAAC,EAAE,MAAM,GACd,OAAO,CAAC,MAAM,CAAC,CASjB"}
@@ -1,4 +1,5 @@
1
1
  export * from './blockRangeChunks.js';
2
2
  export * from './estimateBlockNumberAt.js';
3
+ export * from './findContractDeploymentBlock.js';
3
4
  export * from './rate/index.js';
4
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/modules/ethereum/block/index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAA;AACrC,cAAc,4BAA4B,CAAA;AAC1C,cAAc,iBAAiB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/modules/ethereum/block/index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAA;AACrC,cAAc,4BAA4B,CAAA;AAC1C,cAAc,kCAAkC,CAAA;AAChD,cAAc,iBAAiB,CAAA"}
@@ -46,7 +46,7 @@ export declare const asEvmStakeEvent: {
46
46
  };
47
47
  };
48
48
  export declare const toEvmStakeEvent: {
49
- <T>(value: T): (T & {
49
+ (value: unknown): {
50
50
  address: string;
51
51
  args: [string, string, bigint, bigint];
52
52
  blockHash: string;
@@ -54,8 +54,8 @@ export declare const toEvmStakeEvent: {
54
54
  eventName: "StakeAdded" | "StakeRemoved" | "StakeWithdrawn";
55
55
  transactionHash: string;
56
56
  transactionIndex: number;
57
- }) | undefined;
58
- <T>(value: T, assert: import("@ariestools/sdk").ZodFactoryConfig): T & {
57
+ } | undefined;
58
+ (value: unknown, assert: import("@ariestools/sdk").ZodFactoryConfig): {
59
59
  address: string;
60
60
  args: [string, string, bigint, bigint];
61
61
  blockHash: string;
@@ -105,7 +105,7 @@ export declare const asEvmStakeAddedEvent: {
105
105
  };
106
106
  };
107
107
  export declare const toEvmStakeAddedEvent: {
108
- <T>(value: T): (T & {
108
+ (value: unknown): {
109
109
  address: string;
110
110
  args: [string, string, bigint, bigint];
111
111
  blockHash: string;
@@ -113,8 +113,8 @@ export declare const toEvmStakeAddedEvent: {
113
113
  transactionHash: string;
114
114
  transactionIndex: number;
115
115
  eventName: "StakeAdded";
116
- }) | undefined;
117
- <T>(value: T, assert: import("@ariestools/sdk").ZodFactoryConfig): T & {
116
+ } | undefined;
117
+ (value: unknown, assert: import("@ariestools/sdk").ZodFactoryConfig): {
118
118
  address: string;
119
119
  args: [string, string, bigint, bigint];
120
120
  blockHash: string;
@@ -164,7 +164,7 @@ export declare const asEvmStakeRemovedEvent: {
164
164
  };
165
165
  };
166
166
  export declare const toEvmStakeRemovedEvent: {
167
- <T>(value: T): (T & {
167
+ (value: unknown): {
168
168
  address: string;
169
169
  args: [string, string, bigint, bigint];
170
170
  blockHash: string;
@@ -172,8 +172,8 @@ export declare const toEvmStakeRemovedEvent: {
172
172
  transactionHash: string;
173
173
  transactionIndex: number;
174
174
  eventName: "StakeRemoved";
175
- }) | undefined;
176
- <T>(value: T, assert: import("@ariestools/sdk").ZodFactoryConfig): T & {
175
+ } | undefined;
176
+ (value: unknown, assert: import("@ariestools/sdk").ZodFactoryConfig): {
177
177
  address: string;
178
178
  args: [string, string, bigint, bigint];
179
179
  blockHash: string;
@@ -223,7 +223,7 @@ export declare const asEvmStakeWithdrawnEvent: {
223
223
  };
224
224
  };
225
225
  export declare const toEvmStakeWithdrawnEvent: {
226
- <T>(value: T): (T & {
226
+ (value: unknown): {
227
227
  address: string;
228
228
  args: [string, string, bigint, bigint];
229
229
  blockHash: string;
@@ -231,8 +231,8 @@ export declare const toEvmStakeWithdrawnEvent: {
231
231
  transactionHash: string;
232
232
  transactionIndex: number;
233
233
  eventName: "StakeWithdrawn";
234
- }) | undefined;
235
- <T>(value: T, assert: import("@ariestools/sdk").ZodFactoryConfig): T & {
234
+ } | undefined;
235
+ (value: unknown, assert: import("@ariestools/sdk").ZodFactoryConfig): {
236
236
  address: string;
237
237
  args: [string, string, bigint, bigint];
238
238
  blockHash: string;
@@ -1,23 +1,35 @@
1
1
  import type { EthAddress, Promisable } from '@ariestools/sdk';
2
- import { type IAddressStakingEvents, type TypedEventLog } from '@xyo-network/typechain';
2
+ import { type IAddressStakingEvents } from '@xyo-network/typechain';
3
3
  import { type StakeEvent, type StakeEventFilter, type StakeEventName, type StakeEventsViewer } from '@xyo-network/xl1-sdk';
4
- import type { ReturnTypeForOverload } from '../model/index.js';
5
4
  import type { EvmViewerParams } from '../providers/index.js';
6
5
  import { AbstractEvmViewer } from '../providers/index.js';
7
- type StakeAddedLogEvent = TypedEventLog<ReturnTypeForOverload<IAddressStakingEvents['getEvent'], 'StakeAdded'>>;
8
- type StakeRemovedLogEvent = TypedEventLog<ReturnTypeForOverload<IAddressStakingEvents['getEvent'], 'StakeRemoved'>>;
9
- type StakeWithdrawnLogEvent = TypedEventLog<ReturnTypeForOverload<IAddressStakingEvents['getEvent'], 'StakeWithdrawn'>>;
10
- type StakeLogEvent = StakeAddedLogEvent | StakeRemovedLogEvent | StakeWithdrawnLogEvent;
11
- /** Default max blocks per eth_getLogs / queryFilter call (public RPC safe). */
12
- export declare const DEFAULT_EVENT_QUERY_BLOCK_CHUNK_SIZE = 2000;
6
+ /**
7
+ * Starting max blocks per eth_getLogs / queryFilter call. Providers that cap
8
+ * the range reject with an explicit error and the fetcher adapts downward,
9
+ * jumping straight to an advertised limit when the error states one.
10
+ */
11
+ export declare const DEFAULT_EVENT_QUERY_START_CHUNK_SIZE = 100000;
12
+ /** Floor for adaptive chunk shrinking — a range error below this is rethrown. */
13
+ export declare const MIN_EVENT_QUERY_BLOCK_CHUNK_SIZE = 1000;
13
14
  /** Default attempts (including first) when eth_getLogs hits provider rate limits. */
14
15
  export declare const DEFAULT_EVENT_QUERY_MAX_ATTEMPTS = 8;
15
16
  /** Initial backoff after a rate-limit response before retrying eth_getLogs. */
16
17
  export declare const DEFAULT_EVENT_QUERY_INITIAL_DELAY_MS = 1000;
18
+ /**
19
+ * Structural view of a parsed stake event log — satisfied by both ethers
20
+ * `EventLog` (address-only sweep) and typechain `TypedEventLog` (live
21
+ * listeners). Full shape validation happens via `EvmStakeEventZod`.
22
+ */
23
+ interface StakeEventLogLike {
24
+ blockNumber: number;
25
+ eventName: string;
26
+ }
17
27
  export interface EvmStakeEventsParams extends EvmViewerParams {
18
28
  /**
19
- * Max blocks per eth_getLogs / queryFilter call when loading historical stake events.
20
- * Defaults to {@link DEFAULT_EVENT_QUERY_BLOCK_CHUNK_SIZE}.
29
+ * Fixed max blocks per eth_getLogs / queryFilter call when loading
30
+ * historical stake events. When omitted the fetcher starts at
31
+ * {@link DEFAULT_EVENT_QUERY_START_CHUNK_SIZE} and adapts down to the
32
+ * provider's actual range limit.
21
33
  */
22
34
  eventQueryBlockChunkSize?: number;
23
35
  /**
@@ -34,25 +46,43 @@ export interface EvmStakeEventsParams extends EvmViewerParams {
34
46
  export declare class EvmStakeEventsViewer extends AbstractEvmViewer<EvmStakeEventsParams, IAddressStakingEvents> implements StakeEventsViewer {
35
47
  static readonly connectionTypes: readonly ["evm-rpc"];
36
48
  static readonly defaultMoniker: "StakeEventsViewer";
37
- static readonly dependencies: never[];
49
+ static readonly dependencies: "EvmChainViewer"[];
38
50
  static readonly monikers: "StakeEventsViewer"[];
39
51
  static readonly surface: "node";
40
52
  moniker: "StakeEventsViewer";
41
- /** Set at start when `params.deploymentBlock` is omitted (estimated 2025-06-01). */
53
+ /**
54
+ * Current adaptive chunk size — shrinks when the provider rejects a range
55
+ * and persists across loads so the tail catch-up reuses the learned limit.
56
+ */
57
+ private adaptiveChunkSize?;
58
+ /** Set at start when `params.deploymentBlock` is omitted (getCode binary search, date-estimate fallback). */
42
59
  private defaultDeploymentBlock;
43
60
  private eventCache;
44
61
  get deploymentBlock(): number;
45
62
  get eventQueryBlockChunkSize(): number;
46
63
  get eventQueryInitialDelayMs(): number;
47
64
  get eventQueryMaxAttempts(): number;
65
+ /**
66
+ * Fixed eth_getLogs range: explicit param (deprecated), else the bound evm-rpc
67
+ * connection profile's `eventQueryBlockChunkSize`. Undefined → adaptive sizing.
68
+ */
69
+ protected get fixedEventQueryBlockChunkSize(): number | undefined;
48
70
  positionCount(range: [number, number | 'latest']): Promise<number>;
49
71
  stakeEvents<TName extends StakeEventName>(range?: [number, number | 'latest'], filter?: StakeEventFilter<TName>): Promisable<StakeEvent<TName>[]>;
50
72
  protected connectContract(address: EthAddress): IAddressStakingEvents;
51
- protected onEventHandler(staked: string, staker: string, id: bigint, amount: bigint, event: StakeLogEvent, throwOnInvalid?: boolean): StakeEvent | undefined;
73
+ protected onEventHandler(staked: string, staker: string, id: bigint, amount: bigint, event: StakeEventLogLike, throwOnInvalid?: boolean): StakeEvent | undefined;
52
74
  protected startHandler(): Promise<void>;
53
75
  private attachLiveListeners;
76
+ /**
77
+ * Loads all stake events for the range with a single address-only sweep —
78
+ * one eth_getLogs pass per chunk covers all three event types (demuxed by
79
+ * event name client-side) instead of three filtered sweeps over the same
80
+ * blocks. Chunk size adapts to the provider: on a range/result-limit error
81
+ * the chunk shrinks (to the advertised limit when the error states one,
82
+ * halving otherwise) and the window is retried; rate limits retry at the
83
+ * same size with backoff.
84
+ */
54
85
  private loadHistoricalEvents;
55
- private stakeEventsNative;
56
86
  }
57
87
  export {};
58
88
  //# sourceMappingURL=EvmStakeEventsViewer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"EvmStakeEventsViewer.d.ts","sourceRoot":"","sources":["../../../../../src/modules/ethereum/drivers/EvmStakeEventsViewer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAM7D,OAAO,EACL,KAAK,qBAAqB,EAE1B,KAAK,aAAa,EACnB,MAAM,wBAAwB,CAAA;AAC/B,OAAO,EAEL,KAAK,UAAU,EAAE,KAAK,gBAAgB,EAAE,KAAK,cAAc,EAC3D,KAAK,iBAAiB,EAEvB,MAAM,sBAAsB,CAAA;AAK7B,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAA;AAC9D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAA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AAC,MAAM,CAAC;IAMxE,WAAW,CAAC,KAAK,SAAS,cAAc,EACtC,KAAK,GAAE,CAAC,MAAM,EAAE,MAAM,GAAG,QAAQ,CAAiB,EAClD,MAAM,CAAC,EAAE,gBAAgB,CAAC,KAAK,CAAC,GAC/B,UAAU,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;cA4Bf,eAAe,CAAC,OAAO,EAAE,UAAU;IAItD,SAAS,CAAC,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,iBAAiB,EAAE,cAAc,UAAQ,GAAG,UAAU,GAAG,SAAS;cAgCrI,YAAY;YAwBvB,mBAAmB;IAYjC;;;;;;;;OAQG;YACW,oBAAoB;CA6DnC"}
@@ -8,7 +8,7 @@ export interface EvmStakeViewerParams extends EvmViewerParams {
8
8
  export declare class EvmStakeViewer extends AbstractEvmViewer<EvmStakeViewerParams, IAddressStaking> implements StakeViewer {
9
9
  static readonly connectionTypes: readonly ["evm-rpc"];
10
10
  static readonly defaultMoniker: "StakeViewer";
11
- static readonly dependencies: never[];
11
+ static readonly dependencies: ("EvmChainViewer" | "StakeEventsViewer")[];
12
12
  static readonly monikers: "StakeViewer"[];
13
13
  static readonly surface: "node";
14
14
  readonly moniker: "StakeViewer";
@@ -1 +1 @@
1
- {"version":3,"file":"EvmStakeViewer.d.ts","sourceRoot":"","sources":["../../../../../src/modules/ethereum/drivers/EvmStakeViewer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,OAAO,EAAE,UAAU,EAAE,UAAU,EAChC,MAAM,iBAAiB,CAAA;AAKxB,OAAO,EAAE,KAAK,eAAe,EAA4B,MAAM,wBAAwB,CAAA;AACvF,OAAO,EAEL,KAAK,QAAQ,EAEb,KAAK,iBAAiB,EAEtB,KAAK,WAAW,EAEjB,MAAM,sBAAsB,CAAA;AAK7B,OAAO,KAAK,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