@xyo-network/chain-sdk 4.3.2 → 4.4.0

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.
@@ -307,7 +307,7 @@ import {
307
307
  defaultRewardRatio,
308
308
  FinalizationViewerMoniker,
309
309
  isSignedHydratedBlockWithHashMeta as isSignedHydratedBlockWithHashMeta2,
310
- isTransfer,
310
+ isTransferPayload,
311
311
  MempoolViewerMoniker,
312
312
  REJECTED_TRANSACTIONS_ARCHIVIST_ROLE,
313
313
  TimeSyncViewerMoniker,
@@ -637,7 +637,7 @@ var SimpleBlockRunner = class extends AbstractCreatableProvider4 {
637
637
  const txPayloadHashes = new Set(bw.payload_hashes);
638
638
  for (const payload of payloads) {
639
639
  if (!txPayloadHashes.has(payload._hash)) continue;
640
- if (!isTransfer(payload)) continue;
640
+ if (!isTransferPayload(payload)) continue;
641
641
  if (payload.from !== bw.from) continue;
642
642
  outflow = this.addTransferOutflow(outflow, payload);
643
643
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
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/simple/block/runner/producerTuning.ts", "../../src/modules/services/StepStake/BaseStepStakeService.ts"],
4
- "sourcesContent": ["export { EvmBlockRewardViewer, type EvmBlockRewardViewerParams } from '@xyo-network/xl1-sdk'\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": ";;;;;;;;;;;;;;AAAA,SAAS,4BAA6D;;;ACMtE;AAAA,EACE;AAAA,EAA2B;AAAA,EAAoB;AAAA,OAC1C;AAgBA,IAAM,mBAAmB;AAGzB,IAAM,eAAN,cAAoF,0BAAwD;AAAA,EAMjJ,UAAU,aAAa;AAAA,EACf;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASR,IAAc,cAAc;AAC1B,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;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AK,SAAS,qBAAqB;AAC9F,2BAAqB,aAAa,OAAO,OAAK,uBAAuB,IAAI,EAAE,IAAI,CAAC;AAChF,WAAK,QAAQ,KAAK,oCAAoC,UAAU,CAAC,eAAe,gBAAgB,MAAM,kBAAkB;AAAA,IAC1H;AACA,WAAO,EAAE,OAAO,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,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,cAZW,mBAYK,YAAW,CAAC,kBAAkB;AAC9C,cAbW,mBAaK,WAAU;AAbf,oBAAN;AAAA,EADNG,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;",
4
+ "sourcesContent": ["export { EvmBlockRewardViewer, type EvmBlockRewardViewerParams } from '@xyo-network/xl1-sdk'\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, isTransferPayload, 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 (!isTransferPayload(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": ";;;;;;;;;;;;;;AAAA,SAAS,4BAA6D;;;ACMtE;AAAA,EACE;AAAA,EAA2B;AAAA,EAAoB;AAAA,OAC1C;AAgBA,IAAM,mBAAmB;AAGzB,IAAM,eAAN,cAAoF,0BAAwD;AAAA,EAMjJ,UAAU,aAAa;AAAA,EACf;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASR,IAAc,cAAc;AAC1B,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBA,MAAe,gBAAgB;AAC7B,UAAM,MAAM,cAAc;AAC1B,SAAK,eAAe,MAAM,KAAK,QAAQ,YAAY,kBAAkB;AAAA,EACvE;AAAA,EAEA,qBAAqB,QAAgD;AACnE,WAAO,CAAC;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AAW;AAAA,EAChD;AACF;AAreE,cADW,mBACK,mBAAkB,CAAC,QAAQ,SAAS,QAAQ;AAC5D,cAFW,mBAEK,kBAAiB;AACjC,cAHW,mBAGK,gBAAe;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,cAZW,mBAYK,YAAW,CAAC,kBAAkB;AAC9C,cAbW,mBAaK,WAAU;AAbf,oBAAN;AAAA,EADNG,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
6
  "names": ["AbstractCreatableProvider", "creatableProvider", "AbstractCreatableProvider", "creatableProvider", "assertEx", "AbstractCreatableProvider", "creatableProvider", "AbstractCreatableProvider", "creatableProvider", "assertEx", "isDefined", "toAddress", "PayloadBuilder", "AbstractCreatableProvider", "BlockRejectionSchema", "creatableProvider", "createDeclarationIntent", "isSignedHydratedBlockWithHashMeta", "buildNextBlock", "assertEx", "HydratedTransactionWrapper", "transactionRequiredGas", "AbstractCreatableProvider", "assertEx", "toAddress", "PayloadBuilder", "isDefined", "createDeclarationIntent", "isSignedHydratedBlockWithHashMeta", "BlockRejectionSchema", "buildNextBlock", "creatableProvider", "AbstractCreatableProvider"]
7
7
  }
@@ -473,11 +473,11 @@ var validateTimeInBlock = async (context, payload, block) => {
473
473
 
474
474
  // src/modules/validation/elevatedPayload/payloads/validateTransferInBlock.ts
475
475
  import { ZERO_HASH as ZERO_HASH15 } from "@ariestools/sdk";
476
- import { InBlockPayloadValidationError as InBlockPayloadValidationError11, isTransfer } from "@xyo-network/xl1-sdk";
476
+ import { InBlockPayloadValidationError as InBlockPayloadValidationError11, isTransferPayload } from "@xyo-network/xl1-sdk";
477
477
  var validateTransferInBlock = async (context, payload, block) => {
478
478
  const errors = [];
479
479
  try {
480
- const typedErrors = await validateTypedPayloadInBlock(context, payload, block, isTransfer);
480
+ const typedErrors = await validateTypedPayloadInBlock(context, payload, block, isTransferPayload);
481
481
  for (const typedError of typedErrors) {
482
482
  errors.push(new InBlockPayloadValidationError11(payload._hash, block, payload, `validateTypedPayloadInBlock error: ${typedError}`, typedError));
483
483
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/modules/validation/block/validateBlock.ts", "../../src/modules/validation/block/validators/AllowedPayloadSchemas.ts", "../../src/modules/validation/block/validators/BoundWitness.ts", "../../src/modules/validation/block/validators/Fields.ts", "../../src/modules/validation/block/validators/JsonSchema.ts", "../../src/modules/validation/block/validators/PreviousHash.ts", "../../src/modules/validation/hydratedBlock/validateHydratedBlock.ts", "../../src/modules/validation/hydratedBlock/validators/Payloads.ts", "../../src/modules/validation/elevatedPayload/validatePayloadInBlock.ts", "../../src/modules/validation/elevatedPayload/lib/isElevatedFromBlock.ts", "../../src/modules/validation/elevatedPayload/lib/validateElevatedFromBlock.ts", "../../src/modules/validation/elevatedPayload/lib/validateElevatedFromTransaction.ts", "../../src/modules/validation/elevatedPayload/lib/validateTransactionInBlock.ts", "../../src/modules/validation/elevatedPayload/lib/validateTypedPayloadInBlock.ts", "../../src/modules/validation/elevatedPayload/payloads/validateBridgeDestinationObservationInBlock.ts", "../../src/modules/validation/elevatedPayload/payloads/validateBridgeIntentInBlock.ts", "../../src/modules/validation/elevatedPayload/payloads/validateBridgeSourceObservationInBlock.ts", "../../src/modules/validation/elevatedPayload/payloads/validateChainStakeIntentInBlock.ts", "../../src/modules/validation/elevatedPayload/payloads/validateHashInBlock.ts", "../../src/modules/validation/elevatedPayload/payloads/validateSchemaInBlock.ts", "../../src/modules/validation/elevatedPayload/payloads/validateTimeInBlock.ts", "../../src/modules/validation/elevatedPayload/payloads/validateTransferInBlock.ts", "../../src/modules/validation/hydratedBlock/validators/TransactionTransfersInBlock.ts", "../../src/modules/validation/hydratedBlockState/validateHydratedBlockState.ts", "../../src/modules/validation/hydratedBlockState/validators/RequiredBalance.ts", "../../src/modules/validation/hydratedTransactionState/validateHydratedTransactionState.ts", "../../src/modules/validation/hydratedTransactionState/validators/RequiredBalance.ts"],
4
- "sourcesContent": ["import { ZERO_HASH } from '@ariestools/sdk'\nimport type { WithStorageMeta } from '@xyo-network/sdk'\nimport type {\n BaseContext,\n BlockBoundWitness, BlockValidatorFunction, ChainId,\n} from '@xyo-network/xl1-sdk'\nimport { BlockValidationError } from '@xyo-network/xl1-sdk'\n\nimport {\n BlockAllowedPayloadSchemasValidator,\n BlockBoundWitnessValidator,\n BlockFieldsValidator, BlockPreviousHashValidator,\n} from './validators/index.ts'\n\nexport const validateBlock = async (\n context: BaseContext,\n block: BlockBoundWitness,\n chainId?: ChainId,\n additionalValidators: BlockValidatorFunction[] = [],\n): Promise<BlockValidationError[]> => {\n const errors: BlockValidationError[] = []\n try {\n const validators: BlockValidatorFunction[] = [\n BlockBoundWitnessValidator,\n BlockFieldsValidator,\n BlockPreviousHashValidator,\n BlockAllowedPayloadSchemasValidator,\n ...additionalValidators,\n ]\n for (const validator of validators) {\n errors.push(...(await Promise.resolve(validator(context, block, chainId))))\n }\n } catch (ex) {\n errors.push(new BlockValidationError((block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH, block, 'validation excepted', ex))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { WithStorageMeta } from '@xyo-network/sdk'\nimport type { BlockBoundWitness, BlockValidatorFunction } from '@xyo-network/xl1-sdk'\nimport {\n BlockValidationError,\n isAllowedBlockPayloadSchema,\n} from '@xyo-network/xl1-sdk'\n\nexport const BlockAllowedPayloadSchemasValidator: BlockValidatorFunction = (\n context,\n block,\n) => {\n const errors: BlockValidationError[] = []\n try {\n for (const schema of block.payload_schemas) {\n if (!isAllowedBlockPayloadSchema(schema)) {\n errors.push(new BlockValidationError(\n (block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH,\n block,\n `payload schema not allowed in block: ${String(schema)}`,\n ))\n }\n }\n } catch (ex) {\n errors.push(new BlockValidationError(\n (block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH,\n block,\n `validation excepted: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { WithStorageMeta } from '@xyo-network/sdk'\nimport { BoundWitnessValidator } from '@xyo-network/sdk'\nimport type { BlockBoundWitness, BlockValidatorFunction } from '@xyo-network/xl1-sdk'\nimport { BlockValidationError } from '@xyo-network/xl1-sdk'\n\nconst error = (block: BlockBoundWitness, message: string): BlockValidationError =>\n new BlockValidationError((block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH, block, message)\n\n// Friendly pre-check for the same wallet/producer bug surfaced on the\n// transaction side: signatures emitted under `signatures` instead of\n// `$signatures`. Mirrors TransactionBoundWitnessValidator.\nconst checkSignaturesShape = (block: BlockBoundWitness): BlockValidationError[] => {\n const bw = block as unknown as Record<string, unknown>\n if (bw.$signatures === undefined) {\n return Array.isArray(bw.signatures)\n ? [error(block, 'BoundWitness has `signatures` but expected `$signatures` (signatures must be in the meta-prefixed `$signatures` key)')]\n : [error(block, 'BoundWitness is missing `$signatures`')]\n }\n return []\n}\n\n/**\n * Validates the block's BoundWitness wholistically by delegating to\n * `BoundWitnessValidator.validate()`. Mirrors TransactionBoundWitnessValidator\n * for blocks. Covers signatures (length parity + per-address elliptic-curve\n * verification against the BW data hash), addresses uniqueness,\n * payload_hashes/payload_schemas length parity, schemas, and top-level\n * schema check.\n */\nexport const BlockBoundWitnessValidator: BlockValidatorFunction = async (\n _context,\n block,\n) => {\n try {\n const shapeErrors = checkSignaturesShape(block)\n if (shapeErrors.length > 0) return shapeErrors\n const bwValidator = new BoundWitnessValidator(block)\n const bwErrors = await bwValidator.validate()\n return bwErrors.map(e => error(block, `BoundWitness validation: ${e.message}`))\n } catch (ex) {\n return [error(block, `Failed BlockBoundWitnessValidator: ${String(ex)}`)]\n }\n}\n", "import type { Hash } from '@ariestools/sdk'\nimport { isDefined, ZERO_HASH } from '@ariestools/sdk'\nimport type { WithStorageMeta } from '@xyo-network/sdk'\nimport { BoundWitnessSchema } from '@xyo-network/sdk'\nimport type {\n BaseContext,\n BlockBoundWitness, BlockValidatorFunction, ChainId,\n} from '@xyo-network/xl1-sdk'\nimport { BlockValidationError } from '@xyo-network/xl1-sdk'\n\nexport const BlockFieldsValidator: BlockValidatorFunction = (\n context: BaseContext,\n block: BlockBoundWitness,\n chainId?: ChainId,\n) => {\n const errors: BlockValidationError[] = []\n try {\n if (isDefined(chainId) && block.chain !== chainId.toLowerCase()) {\n errors.push(new BlockValidationError((block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH, block, 'Invalid chain id'))\n }\n\n // get transaction hashes\n const txHashes: Hash[] = []\n for (let i = 0; i < block.payload_hashes.length; i++) {\n if (block.payload_schemas[i] === BoundWitnessSchema) {\n txHashes.push(block.payload_hashes[i])\n }\n }\n\n // check if transaction hashes are unique\n const uniqueTxHashes = new Set(txHashes)\n if (uniqueTxHashes.size < txHashes.length) {\n errors.push(new BlockValidationError(\n (block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH,\n block,\n `Duplicate Transaction Hashes: ${txHashes.join(', ')}`,\n ))\n }\n } catch (ex) {\n errors.push(new BlockValidationError(\n (block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH,\n block,\n `validation excepted: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { WithStorageMeta } from '@xyo-network/sdk'\nimport type {\n BaseContext, BlockBoundWitness, BlockValidatorFunction,\n} from '@xyo-network/xl1-sdk'\nimport { BlockBoundWitnessWithStorageMetaJsonSchema, BlockValidationError } from '@xyo-network/xl1-sdk'\nimport type { AnySchema } from 'ajv'\nimport { Ajv } from 'ajv'\n\nexport const BlockJsonSchemaValidator = (jsonSchema: AnySchema = BlockBoundWitnessWithStorageMetaJsonSchema): BlockValidatorFunction => {\n const ajv = new Ajv({ allErrors: true, strict: true })\n const validate = ajv.compile(jsonSchema)\n return async (\n context: BaseContext,\n block: BlockBoundWitness,\n ) => {\n const errors: BlockValidationError[] = []\n try {\n await validate(block)\n if ((validate.errors ?? []).length > 0) {\n const error = new BlockValidationError(\n (block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH,\n block,\n `failed JSON schema validation: ${ajv.errorsText(validate.errors, { separator: '\\n' })}`,\n )\n error.cause = validate.errors\n errors.push(error)\n }\n } catch (ex) {\n const error = new BlockValidationError(\n (block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH,\n block,\n `validation excepted: ${String(ex)}`,\n )\n error.cause = ex\n errors.push(error)\n }\n return errors\n }\n}\n", "import { isHash, ZERO_HASH } from '@ariestools/sdk'\nimport type { WithStorageMeta } from '@xyo-network/sdk'\nimport type { BlockBoundWitness, BlockValidatorFunction } from '@xyo-network/xl1-sdk'\nimport { BlockValidationError } from '@xyo-network/xl1-sdk'\n\nexport const BlockPreviousHashValidator: BlockValidatorFunction = (\n context,\n block,\n) => {\n const errors: BlockValidationError[] = []\n try {\n const blockNumber = block.block\n if (blockNumber > 0n) {\n // if this is not the first block, validate previous hashes\n if (!isHash(block.previous)) {\n errors.push(new BlockValidationError((block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH, block, 'previous hash is missing or invalid'))\n }\n } else if (blockNumber === 0) {\n // if this is the first block, validate previous hashes\n if (block.previous !== null) {\n errors.push(new BlockValidationError((block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH, block, 'previous hash should not be set'))\n }\n } else {\n // we have a negative block number\n errors.push(new BlockValidationError((block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH, block, 'invalid block number'))\n }\n } catch (ex) {\n const error = new BlockValidationError(\n (block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH,\n block,\n `Failed BlockPreviousHashValidator: ${String(ex)}`,\n )\n error.cause = ex\n errors.push(error)\n }\n return errors\n}\n", "import type { Promisable } from '@ariestools/sdk'\nimport { ZERO_HASH } from '@ariestools/sdk'\nimport type {\n BaseContext,\n BlockValidatorFunction, ChainId, HydratedBlockValidationFunction, HydratedBlockWithHashMeta,\n XL1BlockNumber,\n} from '@xyo-network/xl1-sdk'\nimport { BoundWitnessReferencesValidator, HydratedBlockValidationError } from '@xyo-network/xl1-sdk'\n\nimport { validateBlock } from '../block/index.ts'\nimport { PayloadsInBlockValidator } from './validators/index.ts'\n\nexport const validateHydratedBlock = async (\n context: BaseContext,\n hydratedBlock: HydratedBlockWithHashMeta,\n chainIdAtBlockNumber?: (blockNumber: XL1BlockNumber) => Promisable<ChainId>,\n additionalValidators: HydratedBlockValidationFunction[] = [],\n additionalBlockValidators: BlockValidatorFunction[] = [],\n) => {\n const errors: HydratedBlockValidationError[] = []\n try {\n const validateBlockErrors = await validateBlock(\n context,\n hydratedBlock[0],\n chainIdAtBlockNumber ? await chainIdAtBlockNumber(hydratedBlock[0].block) : undefined,\n additionalBlockValidators,\n )\n for (const validateBlockError of validateBlockErrors) {\n errors.push(new HydratedBlockValidationError(hydratedBlock[0]._hash, hydratedBlock, `validateBlock error: ${validateBlockError}`, validateBlockError))\n }\n const bwRefErrors = await BoundWitnessReferencesValidator()(hydratedBlock)\n for (const bwRefError of bwRefErrors) {\n errors.push(new HydratedBlockValidationError(hydratedBlock[0]._hash, hydratedBlock, `boundwitness reference error: ${bwRefError}`, bwRefError))\n }\n const validators: HydratedBlockValidationFunction[] = [\n PayloadsInBlockValidator,\n ...additionalValidators,\n ]\n for (const validator of validators) {\n errors.push(...(await Promise.resolve(validator(context, hydratedBlock, chainIdAtBlockNumber))))\n }\n } catch (ex) {\n errors.push(new HydratedBlockValidationError(\n hydratedBlock?.[0]?._hash ?? ZERO_HASH,\n hydratedBlock,\n `Failed validateHydratedBlock: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { Payload, WithHashMeta } from '@xyo-network/sdk'\nimport type { HydratedBlockValidationFunction } from '@xyo-network/xl1-sdk'\nimport { HydratedBlockValidationError } from '@xyo-network/xl1-sdk'\n\nimport { validatePayloadInBlock } from '../../elevatedPayload/index.ts'\n\nexport const PayloadsInBlockValidator: HydratedBlockValidationFunction = async (\n context,\n [block, payloads],\n) => {\n const errors: HydratedBlockValidationError[] = []\n try {\n const payloadMap: Partial<Record<string, WithHashMeta<Payload>>> = {}\n for (const payload of payloads) {\n const propertyKey = String(payload._hash)\n payloadMap[propertyKey] = payload\n }\n\n const remainingPayloads = { ...payloadMap }\n\n for (let i = 0; i < block.payload_hashes.length; i++) {\n const propertyKey = String(block.payload_hashes[i])\n const schema = block.payload_schemas[i]\n const payload = payloadMap[propertyKey]\n if (payload) {\n const payloadInBlockErrors = await validatePayloadInBlock(context, payload, [block, payloads])\n for (const payloadInBlockError of payloadInBlockErrors) {\n errors.push(new HydratedBlockValidationError(\n block?._hash ?? ZERO_HASH,\n [block, payloads],\n `validatePayloadInBlock error: ${payloadInBlockError}`,\n payloadInBlockError,\n ))\n }\n delete remainingPayloads[propertyKey]\n } else {\n errors.push(new HydratedBlockValidationError(block?._hash ?? ZERO_HASH, [block, payloads], `missing payload ${propertyKey} ${schema}`))\n }\n }\n\n if (Object.keys(remainingPayloads).length > 0) {\n errors.push(new HydratedBlockValidationError(block?._hash ?? ZERO_HASH, [block, payloads], `extra payloads ${Object.keys(payloadMap).join(', ')}`))\n }\n } catch (ex) {\n errors.push(new HydratedBlockValidationError(\n block?._hash ?? ZERO_HASH,\n [block, payloads],\n `Failed PayloadsInBlockValidator: ${String(ex)}`,\n ex,\n ))\n }\n\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { Schema } from '@xyo-network/sdk'\nimport { BoundWitnessSchema, SchemaSchema } from '@xyo-network/sdk'\nimport type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport {\n BridgeDestinationObservationSchema, BridgeIntentSchema, BridgeSourceObservationSchema, ChainStakeIntentSchema, HashSchema, InBlockPayloadValidationError,\n TimeSchema, TransferSchema,\n} from '@xyo-network/xl1-sdk'\n\nimport { validateTransactionInBlock } from './lib/index.ts'\nimport {\n validateBridgeDestinationObservationInBlock, validateBridgeIntentInBlock, validateBridgeSourceObservationInBlock, validateChainStakeIntentInBlock,\n validateHashInBlock, validateSchemaInBlock, validateTimeInBlock, validateTransferInBlock,\n} from './payloads/index.ts'\n\nconst payloadValidators: Partial<Record<Schema, InBlockPayloadValidationFunction>> = {\n [BoundWitnessSchema]: validateTransactionInBlock,\n [BridgeDestinationObservationSchema]: validateBridgeDestinationObservationInBlock,\n [BridgeIntentSchema]: validateBridgeIntentInBlock,\n [BridgeSourceObservationSchema]: validateBridgeSourceObservationInBlock,\n [ChainStakeIntentSchema]: validateChainStakeIntentInBlock,\n [HashSchema]: validateHashInBlock,\n [SchemaSchema]: validateSchemaInBlock,\n [TimeSchema]: validateTimeInBlock,\n [TransferSchema]: validateTransferInBlock,\n}\n\nexport const validatePayloadInBlock: InBlockPayloadValidationFunction = async (\n context,\n payload,\n block,\n): Promise<InBlockPayloadValidationError[]> => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n const validator = payloadValidators[payload.schema]\n if (validator) {\n errors.push(...(await validator(context, payload, block)))\n } else {\n errors.push(new InBlockPayloadValidationError((block?.[0])?._hash ?? ZERO_HASH, block, payload, `Unsupported payload schema: ${payload.schema}`))\n }\n } catch (ex) {\n const error = new InBlockPayloadValidationError(\n (block?.[0])?._hash ?? ZERO_HASH,\n block,\n payload,\n `validation excepted: ${String(ex)}`,\n ex,\n )\n errors.push(error)\n }\n return errors\n}\n", "import type { Payload, WithHashMeta } from '@xyo-network/sdk'\nimport { type HydratedBlock, isTransactionBoundWitness } from '@xyo-network/xl1-sdk'\n\nexport const isElevatedFromBlock = (payload: WithHashMeta<Payload>, [, payloads]: HydratedBlock): boolean => {\n const txs = payloads.filter(p => isTransactionBoundWitness(p))\n for (const tx of txs) {\n if (tx.payload_hashes.includes(payload._hash)) {\n return false\n }\n }\n return true\n}\n", "import type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport { InBlockPayloadValidationError, transactionsFromHydratedBlock } from '@xyo-network/xl1-sdk'\n\nexport const validateElevatedFromBlock: InBlockPayloadValidationFunction = (\n context,\n payload,\n block,\n) => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n const txs = transactionsFromHydratedBlock(block)\n const allTxPayloadHashes = new Set(txs.flatMap(tx => tx.payload_hashes))\n if (allTxPayloadHashes.has(payload._hash)) {\n errors.push(new InBlockPayloadValidationError(\n block[0]?._hash,\n block,\n payload,\n `Transaction may not include block payload hash [${payload.schema}]: ${payload._hash}`,\n ))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(block[0]?._hash, block, payload, `validation excepted: ${String(ex)}`, ex))\n }\n return errors\n}\n", "import type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport { InBlockPayloadValidationError, transactionsFromHydratedBlock } from '@xyo-network/xl1-sdk'\n\nexport const validateElevatedFromTransaction: InBlockPayloadValidationFunction = (\n context,\n payload,\n block,\n) => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n const txs = transactionsFromHydratedBlock(block)\n if (txs.length > 0) {\n const hashes = txs.flatMap(tx => tx.payload_hashes)\n if (!hashes.includes(payload._hash)) {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, 'Transaction does not include payload'))\n }\n } else {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, 'No Transactions in block'))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(\n payload._hash,\n block,\n payload,\n `Failed validateElevatedFromTransaction: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport { isHashMeta } from '@xyo-network/sdk'\nimport type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport {\n BoundWitnessSignaturesValidator, InBlockPayloadValidationError, isTransactionBoundWitness, validateTransaction,\n} from '@xyo-network/xl1-sdk'\n\nexport const validateTransactionInBlock: InBlockPayloadValidationFunction = async (\n context,\n payload,\n block,\n): Promise<InBlockPayloadValidationError[]> => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n if (isTransactionBoundWitness(payload) && isHashMeta(payload)) {\n const txErrors = await validateTransaction({ ...context, chainId: block[0].chain }, [payload, block[1]])\n for (const txError of txErrors) {\n errors.push(new InBlockPayloadValidationError(\n payload._hash,\n block,\n payload,\n `TransactionValidation error: ${txError}`,\n txError,\n ))\n }\n const txSignatureErrors = await BoundWitnessSignaturesValidator(payload)\n for (const txSignatureError of txSignatureErrors) {\n errors.push(new InBlockPayloadValidationError(\n payload._hash,\n block,\n payload,\n `BoundWitnessSignaturesValidator error: ${txSignatureError}`,\n txSignatureError,\n ))\n }\n } else {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, 'Payload failed isTransactionBoundWitness or isHashMeta'))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(payload._hash ?? ZERO_HASH, block, payload, `validation excepted: ${String(ex)}`, ex))\n }\n return errors\n}\n", "import type { IdentityFunction } from '@ariestools/sdk'\nimport type { Payload } from '@xyo-network/sdk'\nimport { isHashMeta } from '@xyo-network/sdk'\nimport type { HydratedBlockWithHashMeta, InBlockPayloadValidationFunctionContext } from '@xyo-network/xl1-sdk'\n\nimport { isElevatedFromBlock } from './isElevatedFromBlock.ts'\nimport { validateElevatedFromBlock } from './validateElevatedFromBlock.ts'\nimport { validateElevatedFromTransaction } from './validateElevatedFromTransaction.ts'\n\nexport const validateTypedPayloadInBlock = async <T extends Payload>(\n context: InBlockPayloadValidationFunctionContext,\n payload: Payload,\n block: HydratedBlockWithHashMeta,\n identityFunction: IdentityFunction<T>,\n): Promise<Error[]> => {\n const errors: Error[] = []\n try {\n if (identityFunction(payload) && isHashMeta(payload)) {\n if (isElevatedFromBlock(payload, block)) {\n errors.push(...(await validateElevatedFromBlock(context, payload, block)))\n } else {\n errors.push(...(await validateElevatedFromTransaction(context, payload, block)))\n }\n } else {\n errors.push(new Error('Payload failed identityFunction or isElevated or isStorageMeta'))\n }\n } catch (ex) {\n errors.push(new Error(`Failed validateTypedPayloadInBlock: ${String(ex)}`))\n }\n return errors\n}\n//\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport { InBlockPayloadValidationError, isBridgeDestinationObservation } from '@xyo-network/xl1-sdk'\n\nimport { validateTypedPayloadInBlock } from '../lib/index.ts'\n\nexport const validateBridgeDestinationObservationInBlock: InBlockPayloadValidationFunction = async (\n context,\n payload,\n block,\n) => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n const typedErrors = await validateTypedPayloadInBlock(context, payload, block, isBridgeDestinationObservation)\n for (const typedError of typedErrors) {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, `validateTypedPayloadInBlock error: ${typedError}`, typedError))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(\n (block?.[0])?._hash ?? ZERO_HASH,\n block,\n payload,\n `Failed validateBridgeObservationInBlock: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport { InBlockPayloadValidationError, isBridgeIntent } from '@xyo-network/xl1-sdk'\n\nimport { validateTypedPayloadInBlock } from '../lib/index.ts'\n\nexport const validateBridgeIntentInBlock: InBlockPayloadValidationFunction = async (\n context,\n payload,\n block,\n) => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n const typedErrors = await validateTypedPayloadInBlock(context, payload, block, isBridgeIntent)\n for (const typedError of typedErrors) {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, `validateTypedPayloadInBlock error: ${typedError}`, typedError))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(\n (block?.[0])?._hash ?? ZERO_HASH,\n block,\n payload,\n `Failed validateBridgeIntentInBlock: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport { InBlockPayloadValidationError, isBridgeSourceObservation } from '@xyo-network/xl1-sdk'\n\nimport { validateTypedPayloadInBlock } from '../lib/index.ts'\n\nexport const validateBridgeSourceObservationInBlock: InBlockPayloadValidationFunction = async (\n context,\n payload,\n block,\n) => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n const typedErrors = await validateTypedPayloadInBlock(context, payload, block, isBridgeSourceObservation)\n for (const typedError of typedErrors) {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, `validateTypedPayloadInBlock error: ${typedError}`, typedError))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(\n (block?.[0])?._hash ?? ZERO_HASH,\n block,\n payload,\n `Failed validateBridgeObservationInBlock: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport { InBlockPayloadValidationError, isChainStakeIntent } from '@xyo-network/xl1-sdk'\n\nimport { validateTypedPayloadInBlock } from '../lib/index.ts'\n\nexport const validateChainStakeIntentInBlock: InBlockPayloadValidationFunction = async (\n context,\n payload,\n block,\n) => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n const typedErrors = await validateTypedPayloadInBlock(context, payload, block, isChainStakeIntent)\n for (const typedError of typedErrors) {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, `validateTypedPayloadInBlock error: ${typedError}`, typedError))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(\n block[0]?._hash ?? ZERO_HASH,\n block,\n payload,\n `validation excepted: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport { InBlockPayloadValidationError, isHashPayload } from '@xyo-network/xl1-sdk'\n\nimport { validateTypedPayloadInBlock } from '../lib/index.ts'\n\nexport const validateHashInBlock: InBlockPayloadValidationFunction = async (\n context,\n payload,\n block,\n) => {\n const errors: (InBlockPayloadValidationError)[] = []\n try {\n const typedErrors = await validateTypedPayloadInBlock(context, payload, block, isHashPayload)\n for (const typedError of typedErrors) {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, `validateTypedPayloadInBlock error: ${typedError}`, typedError))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(\n (block?.[0])?._hash ?? ZERO_HASH,\n block,\n payload,\n `validation excepted: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport { isSchemaPayload } from '@xyo-network/sdk'\nimport type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport { InBlockPayloadValidationError } from '@xyo-network/xl1-sdk'\n\nimport { validateTypedPayloadInBlock } from '../lib/index.ts'\n\nexport const validateSchemaInBlock: InBlockPayloadValidationFunction = async (\n context,\n payload,\n block,\n) => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n const typedErrors = await validateTypedPayloadInBlock(context, payload, block, isSchemaPayload)\n for (const typedError of typedErrors) {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, `validateTypedPayloadInBlock error: ${typedError}`, typedError))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(\n (block?.[0])?._hash ?? ZERO_HASH,\n block,\n payload,\n `Failed validateSchemaInBlock: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport { InBlockPayloadValidationError, isTimePayload } from '@xyo-network/xl1-sdk'\n\nimport { validateTypedPayloadInBlock } from '../lib/index.ts'\n\nexport const validateTimeInBlock: InBlockPayloadValidationFunction = async (\n context,\n payload,\n block,\n) => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n const typedErrors = await validateTypedPayloadInBlock(context, payload, block, isTimePayload)\n for (const typedError of typedErrors) {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, `validateTypedPayloadInBlock error: ${typedError}`, typedError))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(\n (block?.[0])?._hash ?? ZERO_HASH,\n block,\n payload,\n `Failed validateTimeInBlock: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport { InBlockPayloadValidationError, isTransfer } from '@xyo-network/xl1-sdk'\n\nimport { validateTypedPayloadInBlock } from '../lib/index.ts'\n\nexport const validateTransferInBlock: InBlockPayloadValidationFunction = async (\n context,\n payload,\n block,\n) => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n const typedErrors = await validateTypedPayloadInBlock(context, payload, block, isTransfer)\n for (const typedError of typedErrors) {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, `validateTypedPayloadInBlock error: ${typedError}`, typedError))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(\n (block?.[0])?._hash ?? ZERO_HASH,\n block,\n payload,\n `Failed validateTransferInBlock: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport { isHashMeta } from '@xyo-network/sdk'\nimport type { HydratedBlockValidationFunction, HydratedTransactionValidationFunction } from '@xyo-network/xl1-sdk'\nimport { HydratedBlockValidationError, isTransactionBoundWitness } from '@xyo-network/xl1-sdk'\n\n/**\n * Builds a block-level validator that runs `transfersValidator` against every transaction\n * in the block, mapping any transaction errors to block errors. This is how the\n * reward-redemption signing gate (a `TransactionTransfersValidator`) is enforced during\n * block validation \u2014 pass the result as an `additionalValidators` entry to\n * `validateHydratedBlock`.\n */\nexport function TransactionTransfersInBlockValidatorFactory(\n transfersValidator: HydratedTransactionValidationFunction,\n): HydratedBlockValidationFunction {\n return async (context, hydratedBlock) => {\n const [block, payloads] = hydratedBlock\n const errors: HydratedBlockValidationError[] = []\n try {\n for (const payload of payloads) {\n if (isTransactionBoundWitness(payload) && isHashMeta(payload)) {\n const txErrors = await transfersValidator({ ...context, chainId: block.chain }, [payload, payloads])\n for (const txError of txErrors) {\n errors.push(new HydratedBlockValidationError(payload._hash, hydratedBlock, `transfer authorization error: ${txError}`, txError))\n }\n }\n }\n } catch (ex) {\n errors.push(new HydratedBlockValidationError(\n block?._hash ?? ZERO_HASH,\n hydratedBlock,\n `Failed TransactionTransfersInBlockValidator: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n }\n}\n", "import { spanRootAsync, ZERO_HASH } from '@ariestools/sdk'\nimport type { ChainId, HydratedBlockStateValidationFunction } from '@xyo-network/xl1-sdk'\nimport { HydratedBlockStateValidationError } from '@xyo-network/xl1-sdk'\n\nimport { validateHydratedBlock } from '../hydratedBlock/index.ts'\nimport { RequiredBalanceBlockStateValidator } from './validators/index.ts'\n\nexport const validateHydratedBlockState: HydratedBlockStateValidationFunction = async (\n context,\n hydratedBlock,\n additionalValidators = [],\n) => {\n return await spanRootAsync('validateHydratedBlockState', async () => {\n const errors: HydratedBlockStateValidationError[] = []\n let chainId: ChainId | undefined\n try {\n chainId = await context.chainIdAtBlockNumber(hydratedBlock[0].block)\n const validateHydratedBlockErrors = await validateHydratedBlock(context, hydratedBlock, context.chainIdAtBlockNumber)\n for (const validateHydratedBlockError of validateHydratedBlockErrors) {\n errors.push(new HydratedBlockStateValidationError(\n hydratedBlock[0]._hash,\n chainId,\n hydratedBlock,\n `validateBlock error: ${validateHydratedBlockError}`,\n validateHydratedBlockError,\n ))\n }\n const validators: HydratedBlockStateValidationFunction[] = [\n RequiredBalanceBlockStateValidator,\n ...additionalValidators,\n ]\n for (const validator of validators) {\n errors.push(...(await Promise.resolve(validator(context, hydratedBlock))))\n }\n } catch (ex) {\n errors.push(new HydratedBlockStateValidationError(\n hydratedBlock?.[0]?._hash ?? ZERO_HASH,\n chainId ?? '00' as ChainId,\n hydratedBlock,\n `Failed validateHydratedBlockState: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n }, context)\n}\n", "import type { Address, Hash } from '@ariestools/sdk'\nimport { spanRootAsync, ZERO_HASH } from '@ariestools/sdk'\nimport type { ChainId, HydratedBlockStateValidationFunction } from '@xyo-network/xl1-sdk'\nimport {\n AttoXL1, HydratedBlockStateValidationError,\n isSignedTransactionBoundWitnessWithHashMeta,\n netBalancesForPayloads, XYO_ZERO_ADDRESS,\n} from '@xyo-network/xl1-sdk'\n\nfunction offendingTransactionHashesForAddress(block: Parameters<HydratedBlockStateValidationFunction>[1], address: Address): Hash[] {\n const hashes: Hash[] = []\n for (const payload of block[1]) {\n if (isSignedTransactionBoundWitnessWithHashMeta(payload) && payload.from === address) {\n hashes.push(payload._hash)\n }\n }\n return hashes\n}\n\nexport const RequiredBalanceBlockStateValidator: HydratedBlockStateValidationFunction = async (\n context,\n block,\n) => {\n return await spanRootAsync('RequiredBalanceBlockStateValidator', async () => {\n const errors: HydratedBlockStateValidationError[] = []\n let chainId = '00' as ChainId\n try {\n // TODO: Filter by non-producer elevated payloads\n // to allow for transfers from ZERO address\n const netBalances = netBalancesForPayloads({ singletons: {} }, (block[1]))\n const netBalanceAddresses = Object.keys(netBalances) as Address[]\n const requiredBalances: Record<string, bigint> = {}\n for (const address of netBalanceAddresses) {\n const propertyKey = String(address)\n const netBalance = (netBalances as Record<string, bigint>)[propertyKey]\n if (netBalance < 0n) {\n requiredBalances[propertyKey] = -netBalance\n }\n }\n const previous = block[0].previous\n if (previous === null) return [new HydratedBlockStateValidationError(\n block?.[0]?._hash ?? ZERO_HASH,\n '00' as ChainId,\n block,\n 'Insufficient funds because first block',\n )]\n chainId = await context.chainIdAtBlockNumber(block[0].block)\n await spanRootAsync('RequiredBalanceBlockStateValidator|balancesLoop', async () => {\n for (const [address, reqBalance] of Object.entries(requiredBalances)) {\n const propertyKey = String(address)\n const result = await context.accountBalance.accountBalances([address as Address], { head: previous })\n const balance = (result as Record<string, bigint>)[propertyKey] ?? AttoXL1(0n)\n if (address !== XYO_ZERO_ADDRESS && reqBalance > balance) {\n const offendingTransactionHashes = offendingTransactionHashesForAddress(block, address as Address)\n errors.push(new HydratedBlockStateValidationError(\n block?.[0]?._hash ?? ZERO_HASH,\n chainId,\n block,\n `insufficient balance for ${address} ${balance} < ${reqBalance}`,\n undefined,\n offendingTransactionHashes.length > 0 ? offendingTransactionHashes : undefined,\n ))\n }\n }\n }, context)\n } catch (ex) {\n errors.push(new HydratedBlockStateValidationError(\n block?.[0]?._hash ?? ZERO_HASH,\n chainId,\n block,\n `Failed RequiredBalanceBlockStateValidator: ${String(ex)}`,\n ex,\n ))\n }\n return await Promise.resolve(errors)\n }, context)\n}\n", "import { spanRootAsync, ZERO_HASH } from '@ariestools/sdk'\nimport type { HydratedTransactionStateValidationFunction } from '@xyo-network/xl1-sdk'\nimport { HydratedTransactionValidationError } from '@xyo-network/xl1-sdk'\n\nimport { RequiredBalanceTransactionStateValidator } from './validators/index.ts'\n\nexport const validateHydratedTransactionState: HydratedTransactionStateValidationFunction = async (\n context,\n tx,\n) => {\n return await spanRootAsync('validateHydratedTransactionState', async () => {\n const errors: HydratedTransactionValidationError[] = []\n try {\n const validators: HydratedTransactionStateValidationFunction[] = [\n RequiredBalanceTransactionStateValidator,\n ]\n for (const validator of validators) {\n errors.push(...(await Promise.resolve(validator(context, tx))))\n }\n } catch (ex) {\n errors.push(new HydratedTransactionValidationError(\n tx?.[0]?._hash ?? ZERO_HASH,\n tx,\n `Failed validateHydratedTransactionState: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n }, context)\n}\n", "import type { Address } from '@ariestools/sdk'\nimport { spanRootAsync, ZERO_HASH } from '@ariestools/sdk'\nimport type { HydratedTransactionStateValidationFunction } from '@xyo-network/xl1-sdk'\nimport {\n AttoXL1,\n HydratedTransactionValidationError,\n HydratedTransactionWrapper,\n netBalancesForPayloads,\n transactionRequiredGas,\n XYO_ZERO_ADDRESS,\n} from '@xyo-network/xl1-sdk'\n\ntype ValidatorContext = Parameters<HydratedTransactionStateValidationFunction>[0]\ntype ValidatorTx = Parameters<HydratedTransactionStateValidationFunction>[1]\n\n/**\n * For each address with a negative net balance, look up the actual on-chain\n * balance at the current head and emit an `insufficient balance` error if it\n * can't cover the required amount.\n */\nasync function balanceShortfallErrors(\n context: ValidatorContext,\n tx: ValidatorTx,\n requiredBalances: Record<string, bigint>,\n): Promise<HydratedTransactionValidationError[]> {\n const errors: HydratedTransactionValidationError[] = []\n const requiredAddresses = Object.keys(requiredBalances)\n if (requiredAddresses.length === 0) return errors\n const [headBlock] = await context.blockViewer.currentBlock()\n const balances = await context.accountBalanceViewer.accountBalances(\n requiredAddresses as Address[],\n { head: headBlock._hash },\n )\n const balancesByKey = balances as Record<string, bigint>\n for (const address of requiredAddresses) {\n const propertyKey = String(address)\n const reqBalance = requiredBalances[propertyKey]\n const balance = balancesByKey[propertyKey] ?? AttoXL1(0n)\n if (address !== XYO_ZERO_ADDRESS && reqBalance > balance) {\n errors.push(new HydratedTransactionValidationError(\n tx?.[0]?._hash ?? ZERO_HASH,\n tx,\n `insufficient balance for ${address} ${balance} < ${reqBalance}`,\n ))\n }\n }\n return errors\n}\n\nexport const RequiredBalanceTransactionStateValidator: HydratedTransactionStateValidationFunction = async (\n context,\n tx,\n) => {\n return await spanRootAsync('RequiredBalanceTransactionStateValidator', async () => {\n const errors: HydratedTransactionValidationError[] = []\n try {\n const netBalances = netBalancesForPayloads({ singletons: {} }, tx[1]) as Record<string, bigint>\n\n const wrapper = await HydratedTransactionWrapper.parse(tx)\n const from = wrapper.boundWitness.from as Address\n const gasRequired = transactionRequiredGas(tx)\n // Declared gas limit must cover the gas the tx will actually consume.\n // Without this check a tx could pass admission with `gasLimit < required`\n // and either fail at execution or get unfairly under-charged for the\n // resources it actually uses. Reported alongside any balance shortfall\n // so the caller sees every reason the tx was rejected.\n if (wrapper.fees.gasLimit < gasRequired) {\n errors.push(new HydratedTransactionValidationError(\n tx?.[0]?._hash ?? ZERO_HASH,\n tx,\n `fees.gasLimit ${wrapper.fees.gasLimit} < required gas ${gasRequired}`,\n ))\n }\n // Charge the MAX fee budget at admission \u2014 same rule the block validator\n // (`BlockCumulativeBalanceValidator`) uses post-submit: `base + priority\n // + gasLimit`. Using `gasRequired \u00D7 gasPrice` here (the expected cost)\n // is strictly weaker than the block validator and lets txs whose\n // declared `gasLimit` exceeds the sender's balance through admission.\n // They then fail block validation with \"Cumulative outflow ... exceeds\n // available balance\" and the chain wedges (producer self-mutes for\n // ~150s after a successful-looking submit). Tracked in the\n // api-local-mongodb-beta repro: 783 stuck pending txs of this exact\n // shape, all with gasLimit \u2248 23.6 XL1 against \u2248 12 XL1 balance.\n const baseCost = wrapper.fees.base\n const priorityCost = wrapper.fees.priority\n const maxGasCost = wrapper.fees.gasLimit\n const fromKey = String(from)\n netBalances[fromKey] = (netBalances[fromKey] ?? 0n) - baseCost - priorityCost - maxGasCost\n\n const requiredBalances: Record<string, bigint> = {}\n for (const [address, net] of Object.entries(netBalances)) {\n const propertyKey = String(address)\n if (net < 0n) requiredBalances[propertyKey] = -net\n }\n\n errors.push(...(await balanceShortfallErrors(context, tx, requiredBalances)))\n } catch (ex) {\n errors.push(new HydratedTransactionValidationError(\n tx?.[0]?._hash ?? ZERO_HASH,\n tx,\n `Failed RequiredBalanceTransactionStateValidator: ${String(ex)}`,\n ex,\n ))\n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AI;AACX,aAAO,KAAK,IAAIC;AAAA,QACd,KAAK,CAAC,GAAG,SAASC;AAAA,QAClB;AAAA,QACA,4CAA4C,OAAO,EAAE,CAAC;AAAA,QACtD;AAAA,MACF,CAAC;AAAA,IACH;AACA,WAAO;AAAA,EACT,GAAG,OAAO;AACZ;",
4
+ "sourcesContent": ["import { ZERO_HASH } from '@ariestools/sdk'\nimport type { WithStorageMeta } from '@xyo-network/sdk'\nimport type {\n BaseContext,\n BlockBoundWitness, BlockValidatorFunction, ChainId,\n} from '@xyo-network/xl1-sdk'\nimport { BlockValidationError } from '@xyo-network/xl1-sdk'\n\nimport {\n BlockAllowedPayloadSchemasValidator,\n BlockBoundWitnessValidator,\n BlockFieldsValidator, BlockPreviousHashValidator,\n} from './validators/index.ts'\n\nexport const validateBlock = async (\n context: BaseContext,\n block: BlockBoundWitness,\n chainId?: ChainId,\n additionalValidators: BlockValidatorFunction[] = [],\n): Promise<BlockValidationError[]> => {\n const errors: BlockValidationError[] = []\n try {\n const validators: BlockValidatorFunction[] = [\n BlockBoundWitnessValidator,\n BlockFieldsValidator,\n BlockPreviousHashValidator,\n BlockAllowedPayloadSchemasValidator,\n ...additionalValidators,\n ]\n for (const validator of validators) {\n errors.push(...(await Promise.resolve(validator(context, block, chainId))))\n }\n } catch (ex) {\n errors.push(new BlockValidationError((block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH, block, 'validation excepted', ex))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { WithStorageMeta } from '@xyo-network/sdk'\nimport type { BlockBoundWitness, BlockValidatorFunction } from '@xyo-network/xl1-sdk'\nimport {\n BlockValidationError,\n isAllowedBlockPayloadSchema,\n} from '@xyo-network/xl1-sdk'\n\nexport const BlockAllowedPayloadSchemasValidator: BlockValidatorFunction = (\n context,\n block,\n) => {\n const errors: BlockValidationError[] = []\n try {\n for (const schema of block.payload_schemas) {\n if (!isAllowedBlockPayloadSchema(schema)) {\n errors.push(new BlockValidationError(\n (block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH,\n block,\n `payload schema not allowed in block: ${String(schema)}`,\n ))\n }\n }\n } catch (ex) {\n errors.push(new BlockValidationError(\n (block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH,\n block,\n `validation excepted: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { WithStorageMeta } from '@xyo-network/sdk'\nimport { BoundWitnessValidator } from '@xyo-network/sdk'\nimport type { BlockBoundWitness, BlockValidatorFunction } from '@xyo-network/xl1-sdk'\nimport { BlockValidationError } from '@xyo-network/xl1-sdk'\n\nconst error = (block: BlockBoundWitness, message: string): BlockValidationError =>\n new BlockValidationError((block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH, block, message)\n\n// Friendly pre-check for the same wallet/producer bug surfaced on the\n// transaction side: signatures emitted under `signatures` instead of\n// `$signatures`. Mirrors TransactionBoundWitnessValidator.\nconst checkSignaturesShape = (block: BlockBoundWitness): BlockValidationError[] => {\n const bw = block as unknown as Record<string, unknown>\n if (bw.$signatures === undefined) {\n return Array.isArray(bw.signatures)\n ? [error(block, 'BoundWitness has `signatures` but expected `$signatures` (signatures must be in the meta-prefixed `$signatures` key)')]\n : [error(block, 'BoundWitness is missing `$signatures`')]\n }\n return []\n}\n\n/**\n * Validates the block's BoundWitness wholistically by delegating to\n * `BoundWitnessValidator.validate()`. Mirrors TransactionBoundWitnessValidator\n * for blocks. Covers signatures (length parity + per-address elliptic-curve\n * verification against the BW data hash), addresses uniqueness,\n * payload_hashes/payload_schemas length parity, schemas, and top-level\n * schema check.\n */\nexport const BlockBoundWitnessValidator: BlockValidatorFunction = async (\n _context,\n block,\n) => {\n try {\n const shapeErrors = checkSignaturesShape(block)\n if (shapeErrors.length > 0) return shapeErrors\n const bwValidator = new BoundWitnessValidator(block)\n const bwErrors = await bwValidator.validate()\n return bwErrors.map(e => error(block, `BoundWitness validation: ${e.message}`))\n } catch (ex) {\n return [error(block, `Failed BlockBoundWitnessValidator: ${String(ex)}`)]\n }\n}\n", "import type { Hash } from '@ariestools/sdk'\nimport { isDefined, ZERO_HASH } from '@ariestools/sdk'\nimport type { WithStorageMeta } from '@xyo-network/sdk'\nimport { BoundWitnessSchema } from '@xyo-network/sdk'\nimport type {\n BaseContext,\n BlockBoundWitness, BlockValidatorFunction, ChainId,\n} from '@xyo-network/xl1-sdk'\nimport { BlockValidationError } from '@xyo-network/xl1-sdk'\n\nexport const BlockFieldsValidator: BlockValidatorFunction = (\n context: BaseContext,\n block: BlockBoundWitness,\n chainId?: ChainId,\n) => {\n const errors: BlockValidationError[] = []\n try {\n if (isDefined(chainId) && block.chain !== chainId.toLowerCase()) {\n errors.push(new BlockValidationError((block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH, block, 'Invalid chain id'))\n }\n\n // get transaction hashes\n const txHashes: Hash[] = []\n for (let i = 0; i < block.payload_hashes.length; i++) {\n if (block.payload_schemas[i] === BoundWitnessSchema) {\n txHashes.push(block.payload_hashes[i])\n }\n }\n\n // check if transaction hashes are unique\n const uniqueTxHashes = new Set(txHashes)\n if (uniqueTxHashes.size < txHashes.length) {\n errors.push(new BlockValidationError(\n (block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH,\n block,\n `Duplicate Transaction Hashes: ${txHashes.join(', ')}`,\n ))\n }\n } catch (ex) {\n errors.push(new BlockValidationError(\n (block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH,\n block,\n `validation excepted: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { WithStorageMeta } from '@xyo-network/sdk'\nimport type {\n BaseContext, BlockBoundWitness, BlockValidatorFunction,\n} from '@xyo-network/xl1-sdk'\nimport { BlockBoundWitnessWithStorageMetaJsonSchema, BlockValidationError } from '@xyo-network/xl1-sdk'\nimport type { AnySchema } from 'ajv'\nimport { Ajv } from 'ajv'\n\nexport const BlockJsonSchemaValidator = (jsonSchema: AnySchema = BlockBoundWitnessWithStorageMetaJsonSchema): BlockValidatorFunction => {\n const ajv = new Ajv({ allErrors: true, strict: true })\n const validate = ajv.compile(jsonSchema)\n return async (\n context: BaseContext,\n block: BlockBoundWitness,\n ) => {\n const errors: BlockValidationError[] = []\n try {\n await validate(block)\n if ((validate.errors ?? []).length > 0) {\n const error = new BlockValidationError(\n (block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH,\n block,\n `failed JSON schema validation: ${ajv.errorsText(validate.errors, { separator: '\\n' })}`,\n )\n error.cause = validate.errors\n errors.push(error)\n }\n } catch (ex) {\n const error = new BlockValidationError(\n (block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH,\n block,\n `validation excepted: ${String(ex)}`,\n )\n error.cause = ex\n errors.push(error)\n }\n return errors\n }\n}\n", "import { isHash, ZERO_HASH } from '@ariestools/sdk'\nimport type { WithStorageMeta } from '@xyo-network/sdk'\nimport type { BlockBoundWitness, BlockValidatorFunction } from '@xyo-network/xl1-sdk'\nimport { BlockValidationError } from '@xyo-network/xl1-sdk'\n\nexport const BlockPreviousHashValidator: BlockValidatorFunction = (\n context,\n block,\n) => {\n const errors: BlockValidationError[] = []\n try {\n const blockNumber = block.block\n if (blockNumber > 0n) {\n // if this is not the first block, validate previous hashes\n if (!isHash(block.previous)) {\n errors.push(new BlockValidationError((block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH, block, 'previous hash is missing or invalid'))\n }\n } else if (blockNumber === 0) {\n // if this is the first block, validate previous hashes\n if (block.previous !== null) {\n errors.push(new BlockValidationError((block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH, block, 'previous hash should not be set'))\n }\n } else {\n // we have a negative block number\n errors.push(new BlockValidationError((block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH, block, 'invalid block number'))\n }\n } catch (ex) {\n const error = new BlockValidationError(\n (block as WithStorageMeta<BlockBoundWitness>)?._hash ?? ZERO_HASH,\n block,\n `Failed BlockPreviousHashValidator: ${String(ex)}`,\n )\n error.cause = ex\n errors.push(error)\n }\n return errors\n}\n", "import type { Promisable } from '@ariestools/sdk'\nimport { ZERO_HASH } from '@ariestools/sdk'\nimport type {\n BaseContext,\n BlockValidatorFunction, ChainId, HydratedBlockValidationFunction, HydratedBlockWithHashMeta,\n XL1BlockNumber,\n} from '@xyo-network/xl1-sdk'\nimport { BoundWitnessReferencesValidator, HydratedBlockValidationError } from '@xyo-network/xl1-sdk'\n\nimport { validateBlock } from '../block/index.ts'\nimport { PayloadsInBlockValidator } from './validators/index.ts'\n\nexport const validateHydratedBlock = async (\n context: BaseContext,\n hydratedBlock: HydratedBlockWithHashMeta,\n chainIdAtBlockNumber?: (blockNumber: XL1BlockNumber) => Promisable<ChainId>,\n additionalValidators: HydratedBlockValidationFunction[] = [],\n additionalBlockValidators: BlockValidatorFunction[] = [],\n) => {\n const errors: HydratedBlockValidationError[] = []\n try {\n const validateBlockErrors = await validateBlock(\n context,\n hydratedBlock[0],\n chainIdAtBlockNumber ? await chainIdAtBlockNumber(hydratedBlock[0].block) : undefined,\n additionalBlockValidators,\n )\n for (const validateBlockError of validateBlockErrors) {\n errors.push(new HydratedBlockValidationError(hydratedBlock[0]._hash, hydratedBlock, `validateBlock error: ${validateBlockError}`, validateBlockError))\n }\n const bwRefErrors = await BoundWitnessReferencesValidator()(hydratedBlock)\n for (const bwRefError of bwRefErrors) {\n errors.push(new HydratedBlockValidationError(hydratedBlock[0]._hash, hydratedBlock, `boundwitness reference error: ${bwRefError}`, bwRefError))\n }\n const validators: HydratedBlockValidationFunction[] = [\n PayloadsInBlockValidator,\n ...additionalValidators,\n ]\n for (const validator of validators) {\n errors.push(...(await Promise.resolve(validator(context, hydratedBlock, chainIdAtBlockNumber))))\n }\n } catch (ex) {\n errors.push(new HydratedBlockValidationError(\n hydratedBlock?.[0]?._hash ?? ZERO_HASH,\n hydratedBlock,\n `Failed validateHydratedBlock: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { Payload, WithHashMeta } from '@xyo-network/sdk'\nimport type { HydratedBlockValidationFunction } from '@xyo-network/xl1-sdk'\nimport { HydratedBlockValidationError } from '@xyo-network/xl1-sdk'\n\nimport { validatePayloadInBlock } from '../../elevatedPayload/index.ts'\n\nexport const PayloadsInBlockValidator: HydratedBlockValidationFunction = async (\n context,\n [block, payloads],\n) => {\n const errors: HydratedBlockValidationError[] = []\n try {\n const payloadMap: Partial<Record<string, WithHashMeta<Payload>>> = {}\n for (const payload of payloads) {\n const propertyKey = String(payload._hash)\n payloadMap[propertyKey] = payload\n }\n\n const remainingPayloads = { ...payloadMap }\n\n for (let i = 0; i < block.payload_hashes.length; i++) {\n const propertyKey = String(block.payload_hashes[i])\n const schema = block.payload_schemas[i]\n const payload = payloadMap[propertyKey]\n if (payload) {\n const payloadInBlockErrors = await validatePayloadInBlock(context, payload, [block, payloads])\n for (const payloadInBlockError of payloadInBlockErrors) {\n errors.push(new HydratedBlockValidationError(\n block?._hash ?? ZERO_HASH,\n [block, payloads],\n `validatePayloadInBlock error: ${payloadInBlockError}`,\n payloadInBlockError,\n ))\n }\n delete remainingPayloads[propertyKey]\n } else {\n errors.push(new HydratedBlockValidationError(block?._hash ?? ZERO_HASH, [block, payloads], `missing payload ${propertyKey} ${schema}`))\n }\n }\n\n if (Object.keys(remainingPayloads).length > 0) {\n errors.push(new HydratedBlockValidationError(block?._hash ?? ZERO_HASH, [block, payloads], `extra payloads ${Object.keys(payloadMap).join(', ')}`))\n }\n } catch (ex) {\n errors.push(new HydratedBlockValidationError(\n block?._hash ?? ZERO_HASH,\n [block, payloads],\n `Failed PayloadsInBlockValidator: ${String(ex)}`,\n ex,\n ))\n }\n\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { Schema } from '@xyo-network/sdk'\nimport { BoundWitnessSchema, SchemaSchema } from '@xyo-network/sdk'\nimport type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport {\n BridgeDestinationObservationSchema, BridgeIntentSchema, BridgeSourceObservationSchema, ChainStakeIntentSchema, HashSchema, InBlockPayloadValidationError,\n TimeSchema, TransferSchema,\n} from '@xyo-network/xl1-sdk'\n\nimport { validateTransactionInBlock } from './lib/index.ts'\nimport {\n validateBridgeDestinationObservationInBlock, validateBridgeIntentInBlock, validateBridgeSourceObservationInBlock, validateChainStakeIntentInBlock,\n validateHashInBlock, validateSchemaInBlock, validateTimeInBlock, validateTransferInBlock,\n} from './payloads/index.ts'\n\nconst payloadValidators: Partial<Record<Schema, InBlockPayloadValidationFunction>> = {\n [BoundWitnessSchema]: validateTransactionInBlock,\n [BridgeDestinationObservationSchema]: validateBridgeDestinationObservationInBlock,\n [BridgeIntentSchema]: validateBridgeIntentInBlock,\n [BridgeSourceObservationSchema]: validateBridgeSourceObservationInBlock,\n [ChainStakeIntentSchema]: validateChainStakeIntentInBlock,\n [HashSchema]: validateHashInBlock,\n [SchemaSchema]: validateSchemaInBlock,\n [TimeSchema]: validateTimeInBlock,\n [TransferSchema]: validateTransferInBlock,\n}\n\nexport const validatePayloadInBlock: InBlockPayloadValidationFunction = async (\n context,\n payload,\n block,\n): Promise<InBlockPayloadValidationError[]> => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n const validator = payloadValidators[payload.schema]\n if (validator) {\n errors.push(...(await validator(context, payload, block)))\n } else {\n errors.push(new InBlockPayloadValidationError((block?.[0])?._hash ?? ZERO_HASH, block, payload, `Unsupported payload schema: ${payload.schema}`))\n }\n } catch (ex) {\n const error = new InBlockPayloadValidationError(\n (block?.[0])?._hash ?? ZERO_HASH,\n block,\n payload,\n `validation excepted: ${String(ex)}`,\n ex,\n )\n errors.push(error)\n }\n return errors\n}\n", "import type { Payload, WithHashMeta } from '@xyo-network/sdk'\nimport { type HydratedBlock, isTransactionBoundWitness } from '@xyo-network/xl1-sdk'\n\nexport const isElevatedFromBlock = (payload: WithHashMeta<Payload>, [, payloads]: HydratedBlock): boolean => {\n const txs = payloads.filter(p => isTransactionBoundWitness(p))\n for (const tx of txs) {\n if (tx.payload_hashes.includes(payload._hash)) {\n return false\n }\n }\n return true\n}\n", "import type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport { InBlockPayloadValidationError, transactionsFromHydratedBlock } from '@xyo-network/xl1-sdk'\n\nexport const validateElevatedFromBlock: InBlockPayloadValidationFunction = (\n context,\n payload,\n block,\n) => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n const txs = transactionsFromHydratedBlock(block)\n const allTxPayloadHashes = new Set(txs.flatMap(tx => tx.payload_hashes))\n if (allTxPayloadHashes.has(payload._hash)) {\n errors.push(new InBlockPayloadValidationError(\n block[0]?._hash,\n block,\n payload,\n `Transaction may not include block payload hash [${payload.schema}]: ${payload._hash}`,\n ))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(block[0]?._hash, block, payload, `validation excepted: ${String(ex)}`, ex))\n }\n return errors\n}\n", "import type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport { InBlockPayloadValidationError, transactionsFromHydratedBlock } from '@xyo-network/xl1-sdk'\n\nexport const validateElevatedFromTransaction: InBlockPayloadValidationFunction = (\n context,\n payload,\n block,\n) => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n const txs = transactionsFromHydratedBlock(block)\n if (txs.length > 0) {\n const hashes = txs.flatMap(tx => tx.payload_hashes)\n if (!hashes.includes(payload._hash)) {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, 'Transaction does not include payload'))\n }\n } else {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, 'No Transactions in block'))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(\n payload._hash,\n block,\n payload,\n `Failed validateElevatedFromTransaction: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport { isHashMeta } from '@xyo-network/sdk'\nimport type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport {\n BoundWitnessSignaturesValidator, InBlockPayloadValidationError, isTransactionBoundWitness, validateTransaction,\n} from '@xyo-network/xl1-sdk'\n\nexport const validateTransactionInBlock: InBlockPayloadValidationFunction = async (\n context,\n payload,\n block,\n): Promise<InBlockPayloadValidationError[]> => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n if (isTransactionBoundWitness(payload) && isHashMeta(payload)) {\n const txErrors = await validateTransaction({ ...context, chainId: block[0].chain }, [payload, block[1]])\n for (const txError of txErrors) {\n errors.push(new InBlockPayloadValidationError(\n payload._hash,\n block,\n payload,\n `TransactionValidation error: ${txError}`,\n txError,\n ))\n }\n const txSignatureErrors = await BoundWitnessSignaturesValidator(payload)\n for (const txSignatureError of txSignatureErrors) {\n errors.push(new InBlockPayloadValidationError(\n payload._hash,\n block,\n payload,\n `BoundWitnessSignaturesValidator error: ${txSignatureError}`,\n txSignatureError,\n ))\n }\n } else {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, 'Payload failed isTransactionBoundWitness or isHashMeta'))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(payload._hash ?? ZERO_HASH, block, payload, `validation excepted: ${String(ex)}`, ex))\n }\n return errors\n}\n", "import type { IdentityFunction } from '@ariestools/sdk'\nimport type { Payload } from '@xyo-network/sdk'\nimport { isHashMeta } from '@xyo-network/sdk'\nimport type { HydratedBlockWithHashMeta, InBlockPayloadValidationFunctionContext } from '@xyo-network/xl1-sdk'\n\nimport { isElevatedFromBlock } from './isElevatedFromBlock.ts'\nimport { validateElevatedFromBlock } from './validateElevatedFromBlock.ts'\nimport { validateElevatedFromTransaction } from './validateElevatedFromTransaction.ts'\n\nexport const validateTypedPayloadInBlock = async <T extends Payload>(\n context: InBlockPayloadValidationFunctionContext,\n payload: Payload,\n block: HydratedBlockWithHashMeta,\n identityFunction: IdentityFunction<T>,\n): Promise<Error[]> => {\n const errors: Error[] = []\n try {\n if (identityFunction(payload) && isHashMeta(payload)) {\n if (isElevatedFromBlock(payload, block)) {\n errors.push(...(await validateElevatedFromBlock(context, payload, block)))\n } else {\n errors.push(...(await validateElevatedFromTransaction(context, payload, block)))\n }\n } else {\n errors.push(new Error('Payload failed identityFunction or isElevated or isStorageMeta'))\n }\n } catch (ex) {\n errors.push(new Error(`Failed validateTypedPayloadInBlock: ${String(ex)}`))\n }\n return errors\n}\n//\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport { InBlockPayloadValidationError, isBridgeDestinationObservation } from '@xyo-network/xl1-sdk'\n\nimport { validateTypedPayloadInBlock } from '../lib/index.ts'\n\nexport const validateBridgeDestinationObservationInBlock: InBlockPayloadValidationFunction = async (\n context,\n payload,\n block,\n) => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n const typedErrors = await validateTypedPayloadInBlock(context, payload, block, isBridgeDestinationObservation)\n for (const typedError of typedErrors) {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, `validateTypedPayloadInBlock error: ${typedError}`, typedError))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(\n (block?.[0])?._hash ?? ZERO_HASH,\n block,\n payload,\n `Failed validateBridgeObservationInBlock: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport { InBlockPayloadValidationError, isBridgeIntent } from '@xyo-network/xl1-sdk'\n\nimport { validateTypedPayloadInBlock } from '../lib/index.ts'\n\nexport const validateBridgeIntentInBlock: InBlockPayloadValidationFunction = async (\n context,\n payload,\n block,\n) => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n const typedErrors = await validateTypedPayloadInBlock(context, payload, block, isBridgeIntent)\n for (const typedError of typedErrors) {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, `validateTypedPayloadInBlock error: ${typedError}`, typedError))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(\n (block?.[0])?._hash ?? ZERO_HASH,\n block,\n payload,\n `Failed validateBridgeIntentInBlock: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport { InBlockPayloadValidationError, isBridgeSourceObservation } from '@xyo-network/xl1-sdk'\n\nimport { validateTypedPayloadInBlock } from '../lib/index.ts'\n\nexport const validateBridgeSourceObservationInBlock: InBlockPayloadValidationFunction = async (\n context,\n payload,\n block,\n) => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n const typedErrors = await validateTypedPayloadInBlock(context, payload, block, isBridgeSourceObservation)\n for (const typedError of typedErrors) {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, `validateTypedPayloadInBlock error: ${typedError}`, typedError))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(\n (block?.[0])?._hash ?? ZERO_HASH,\n block,\n payload,\n `Failed validateBridgeObservationInBlock: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport { InBlockPayloadValidationError, isChainStakeIntent } from '@xyo-network/xl1-sdk'\n\nimport { validateTypedPayloadInBlock } from '../lib/index.ts'\n\nexport const validateChainStakeIntentInBlock: InBlockPayloadValidationFunction = async (\n context,\n payload,\n block,\n) => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n const typedErrors = await validateTypedPayloadInBlock(context, payload, block, isChainStakeIntent)\n for (const typedError of typedErrors) {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, `validateTypedPayloadInBlock error: ${typedError}`, typedError))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(\n block[0]?._hash ?? ZERO_HASH,\n block,\n payload,\n `validation excepted: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport { InBlockPayloadValidationError, isHashPayload } from '@xyo-network/xl1-sdk'\n\nimport { validateTypedPayloadInBlock } from '../lib/index.ts'\n\nexport const validateHashInBlock: InBlockPayloadValidationFunction = async (\n context,\n payload,\n block,\n) => {\n const errors: (InBlockPayloadValidationError)[] = []\n try {\n const typedErrors = await validateTypedPayloadInBlock(context, payload, block, isHashPayload)\n for (const typedError of typedErrors) {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, `validateTypedPayloadInBlock error: ${typedError}`, typedError))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(\n (block?.[0])?._hash ?? ZERO_HASH,\n block,\n payload,\n `validation excepted: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport { isSchemaPayload } from '@xyo-network/sdk'\nimport type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport { InBlockPayloadValidationError } from '@xyo-network/xl1-sdk'\n\nimport { validateTypedPayloadInBlock } from '../lib/index.ts'\n\nexport const validateSchemaInBlock: InBlockPayloadValidationFunction = async (\n context,\n payload,\n block,\n) => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n const typedErrors = await validateTypedPayloadInBlock(context, payload, block, isSchemaPayload)\n for (const typedError of typedErrors) {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, `validateTypedPayloadInBlock error: ${typedError}`, typedError))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(\n (block?.[0])?._hash ?? ZERO_HASH,\n block,\n payload,\n `Failed validateSchemaInBlock: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport { InBlockPayloadValidationError, isTimePayload } from '@xyo-network/xl1-sdk'\n\nimport { validateTypedPayloadInBlock } from '../lib/index.ts'\n\nexport const validateTimeInBlock: InBlockPayloadValidationFunction = async (\n context,\n payload,\n block,\n) => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n const typedErrors = await validateTypedPayloadInBlock(context, payload, block, isTimePayload)\n for (const typedError of typedErrors) {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, `validateTypedPayloadInBlock error: ${typedError}`, typedError))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(\n (block?.[0])?._hash ?? ZERO_HASH,\n block,\n payload,\n `Failed validateTimeInBlock: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport type { InBlockPayloadValidationFunction } from '@xyo-network/xl1-sdk'\nimport { InBlockPayloadValidationError, isTransferPayload } from '@xyo-network/xl1-sdk'\n\nimport { validateTypedPayloadInBlock } from '../lib/index.ts'\n\nexport const validateTransferInBlock: InBlockPayloadValidationFunction = async (\n context,\n payload,\n block,\n) => {\n const errors: InBlockPayloadValidationError[] = []\n try {\n const typedErrors = await validateTypedPayloadInBlock(context, payload, block, isTransferPayload)\n for (const typedError of typedErrors) {\n errors.push(new InBlockPayloadValidationError(payload._hash, block, payload, `validateTypedPayloadInBlock error: ${typedError}`, typedError))\n }\n } catch (ex) {\n errors.push(new InBlockPayloadValidationError(\n (block?.[0])?._hash ?? ZERO_HASH,\n block,\n payload,\n `Failed validateTransferInBlock: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n}\n", "import { ZERO_HASH } from '@ariestools/sdk'\nimport { isHashMeta } from '@xyo-network/sdk'\nimport type { HydratedBlockValidationFunction, HydratedTransactionValidationFunction } from '@xyo-network/xl1-sdk'\nimport { HydratedBlockValidationError, isTransactionBoundWitness } from '@xyo-network/xl1-sdk'\n\n/**\n * Builds a block-level validator that runs `transfersValidator` against every transaction\n * in the block, mapping any transaction errors to block errors. This is how the\n * reward-redemption signing gate (a `TransactionTransfersValidator`) is enforced during\n * block validation \u2014 pass the result as an `additionalValidators` entry to\n * `validateHydratedBlock`.\n */\nexport function TransactionTransfersInBlockValidatorFactory(\n transfersValidator: HydratedTransactionValidationFunction,\n): HydratedBlockValidationFunction {\n return async (context, hydratedBlock) => {\n const [block, payloads] = hydratedBlock\n const errors: HydratedBlockValidationError[] = []\n try {\n for (const payload of payloads) {\n if (isTransactionBoundWitness(payload) && isHashMeta(payload)) {\n const txErrors = await transfersValidator({ ...context, chainId: block.chain }, [payload, payloads])\n for (const txError of txErrors) {\n errors.push(new HydratedBlockValidationError(payload._hash, hydratedBlock, `transfer authorization error: ${txError}`, txError))\n }\n }\n }\n } catch (ex) {\n errors.push(new HydratedBlockValidationError(\n block?._hash ?? ZERO_HASH,\n hydratedBlock,\n `Failed TransactionTransfersInBlockValidator: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n }\n}\n", "import { spanRootAsync, ZERO_HASH } from '@ariestools/sdk'\nimport type { ChainId, HydratedBlockStateValidationFunction } from '@xyo-network/xl1-sdk'\nimport { HydratedBlockStateValidationError } from '@xyo-network/xl1-sdk'\n\nimport { validateHydratedBlock } from '../hydratedBlock/index.ts'\nimport { RequiredBalanceBlockStateValidator } from './validators/index.ts'\n\nexport const validateHydratedBlockState: HydratedBlockStateValidationFunction = async (\n context,\n hydratedBlock,\n additionalValidators = [],\n) => {\n return await spanRootAsync('validateHydratedBlockState', async () => {\n const errors: HydratedBlockStateValidationError[] = []\n let chainId: ChainId | undefined\n try {\n chainId = await context.chainIdAtBlockNumber(hydratedBlock[0].block)\n const validateHydratedBlockErrors = await validateHydratedBlock(context, hydratedBlock, context.chainIdAtBlockNumber)\n for (const validateHydratedBlockError of validateHydratedBlockErrors) {\n errors.push(new HydratedBlockStateValidationError(\n hydratedBlock[0]._hash,\n chainId,\n hydratedBlock,\n `validateBlock error: ${validateHydratedBlockError}`,\n validateHydratedBlockError,\n ))\n }\n const validators: HydratedBlockStateValidationFunction[] = [\n RequiredBalanceBlockStateValidator,\n ...additionalValidators,\n ]\n for (const validator of validators) {\n errors.push(...(await Promise.resolve(validator(context, hydratedBlock))))\n }\n } catch (ex) {\n errors.push(new HydratedBlockStateValidationError(\n hydratedBlock?.[0]?._hash ?? ZERO_HASH,\n chainId ?? '00' as ChainId,\n hydratedBlock,\n `Failed validateHydratedBlockState: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n }, context)\n}\n", "import type { Address, Hash } from '@ariestools/sdk'\nimport { spanRootAsync, ZERO_HASH } from '@ariestools/sdk'\nimport type { ChainId, HydratedBlockStateValidationFunction } from '@xyo-network/xl1-sdk'\nimport {\n AttoXL1, HydratedBlockStateValidationError,\n isSignedTransactionBoundWitnessWithHashMeta,\n netBalancesForPayloads, XYO_ZERO_ADDRESS,\n} from '@xyo-network/xl1-sdk'\n\nfunction offendingTransactionHashesForAddress(block: Parameters<HydratedBlockStateValidationFunction>[1], address: Address): Hash[] {\n const hashes: Hash[] = []\n for (const payload of block[1]) {\n if (isSignedTransactionBoundWitnessWithHashMeta(payload) && payload.from === address) {\n hashes.push(payload._hash)\n }\n }\n return hashes\n}\n\nexport const RequiredBalanceBlockStateValidator: HydratedBlockStateValidationFunction = async (\n context,\n block,\n) => {\n return await spanRootAsync('RequiredBalanceBlockStateValidator', async () => {\n const errors: HydratedBlockStateValidationError[] = []\n let chainId = '00' as ChainId\n try {\n // TODO: Filter by non-producer elevated payloads\n // to allow for transfers from ZERO address\n const netBalances = netBalancesForPayloads({ singletons: {} }, (block[1]))\n const netBalanceAddresses = Object.keys(netBalances) as Address[]\n const requiredBalances: Record<string, bigint> = {}\n for (const address of netBalanceAddresses) {\n const propertyKey = String(address)\n const netBalance = (netBalances as Record<string, bigint>)[propertyKey]\n if (netBalance < 0n) {\n requiredBalances[propertyKey] = -netBalance\n }\n }\n const previous = block[0].previous\n if (previous === null) return [new HydratedBlockStateValidationError(\n block?.[0]?._hash ?? ZERO_HASH,\n '00' as ChainId,\n block,\n 'Insufficient funds because first block',\n )]\n chainId = await context.chainIdAtBlockNumber(block[0].block)\n await spanRootAsync('RequiredBalanceBlockStateValidator|balancesLoop', async () => {\n for (const [address, reqBalance] of Object.entries(requiredBalances)) {\n const propertyKey = String(address)\n const result = await context.accountBalance.accountBalances([address as Address], { head: previous })\n const balance = (result as Record<string, bigint>)[propertyKey] ?? AttoXL1(0n)\n if (address !== XYO_ZERO_ADDRESS && reqBalance > balance) {\n const offendingTransactionHashes = offendingTransactionHashesForAddress(block, address as Address)\n errors.push(new HydratedBlockStateValidationError(\n block?.[0]?._hash ?? ZERO_HASH,\n chainId,\n block,\n `insufficient balance for ${address} ${balance} < ${reqBalance}`,\n undefined,\n offendingTransactionHashes.length > 0 ? offendingTransactionHashes : undefined,\n ))\n }\n }\n }, context)\n } catch (ex) {\n errors.push(new HydratedBlockStateValidationError(\n block?.[0]?._hash ?? ZERO_HASH,\n chainId,\n block,\n `Failed RequiredBalanceBlockStateValidator: ${String(ex)}`,\n ex,\n ))\n }\n return await Promise.resolve(errors)\n }, context)\n}\n", "import { spanRootAsync, ZERO_HASH } from '@ariestools/sdk'\nimport type { HydratedTransactionStateValidationFunction } from '@xyo-network/xl1-sdk'\nimport { HydratedTransactionValidationError } from '@xyo-network/xl1-sdk'\n\nimport { RequiredBalanceTransactionStateValidator } from './validators/index.ts'\n\nexport const validateHydratedTransactionState: HydratedTransactionStateValidationFunction = async (\n context,\n tx,\n) => {\n return await spanRootAsync('validateHydratedTransactionState', async () => {\n const errors: HydratedTransactionValidationError[] = []\n try {\n const validators: HydratedTransactionStateValidationFunction[] = [\n RequiredBalanceTransactionStateValidator,\n ]\n for (const validator of validators) {\n errors.push(...(await Promise.resolve(validator(context, tx))))\n }\n } catch (ex) {\n errors.push(new HydratedTransactionValidationError(\n tx?.[0]?._hash ?? ZERO_HASH,\n tx,\n `Failed validateHydratedTransactionState: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n }, context)\n}\n", "import type { Address } from '@ariestools/sdk'\nimport { spanRootAsync, ZERO_HASH } from '@ariestools/sdk'\nimport type { HydratedTransactionStateValidationFunction } from '@xyo-network/xl1-sdk'\nimport {\n AttoXL1,\n HydratedTransactionValidationError,\n HydratedTransactionWrapper,\n netBalancesForPayloads,\n transactionRequiredGas,\n XYO_ZERO_ADDRESS,\n} from '@xyo-network/xl1-sdk'\n\ntype ValidatorContext = Parameters<HydratedTransactionStateValidationFunction>[0]\ntype ValidatorTx = Parameters<HydratedTransactionStateValidationFunction>[1]\n\n/**\n * For each address with a negative net balance, look up the actual on-chain\n * balance at the current head and emit an `insufficient balance` error if it\n * can't cover the required amount.\n */\nasync function balanceShortfallErrors(\n context: ValidatorContext,\n tx: ValidatorTx,\n requiredBalances: Record<string, bigint>,\n): Promise<HydratedTransactionValidationError[]> {\n const errors: HydratedTransactionValidationError[] = []\n const requiredAddresses = Object.keys(requiredBalances)\n if (requiredAddresses.length === 0) return errors\n const [headBlock] = await context.blockViewer.currentBlock()\n const balances = await context.accountBalanceViewer.accountBalances(\n requiredAddresses as Address[],\n { head: headBlock._hash },\n )\n const balancesByKey = balances as Record<string, bigint>\n for (const address of requiredAddresses) {\n const propertyKey = String(address)\n const reqBalance = requiredBalances[propertyKey]\n const balance = balancesByKey[propertyKey] ?? AttoXL1(0n)\n if (address !== XYO_ZERO_ADDRESS && reqBalance > balance) {\n errors.push(new HydratedTransactionValidationError(\n tx?.[0]?._hash ?? ZERO_HASH,\n tx,\n `insufficient balance for ${address} ${balance} < ${reqBalance}`,\n ))\n }\n }\n return errors\n}\n\nexport const RequiredBalanceTransactionStateValidator: HydratedTransactionStateValidationFunction = async (\n context,\n tx,\n) => {\n return await spanRootAsync('RequiredBalanceTransactionStateValidator', async () => {\n const errors: HydratedTransactionValidationError[] = []\n try {\n const netBalances = netBalancesForPayloads({ singletons: {} }, tx[1]) as Record<string, bigint>\n\n const wrapper = await HydratedTransactionWrapper.parse(tx)\n const from = wrapper.boundWitness.from as Address\n const gasRequired = transactionRequiredGas(tx)\n // Declared gas limit must cover the gas the tx will actually consume.\n // Without this check a tx could pass admission with `gasLimit < required`\n // and either fail at execution or get unfairly under-charged for the\n // resources it actually uses. Reported alongside any balance shortfall\n // so the caller sees every reason the tx was rejected.\n if (wrapper.fees.gasLimit < gasRequired) {\n errors.push(new HydratedTransactionValidationError(\n tx?.[0]?._hash ?? ZERO_HASH,\n tx,\n `fees.gasLimit ${wrapper.fees.gasLimit} < required gas ${gasRequired}`,\n ))\n }\n // Charge the MAX fee budget at admission \u2014 same rule the block validator\n // (`BlockCumulativeBalanceValidator`) uses post-submit: `base + priority\n // + gasLimit`. Using `gasRequired \u00D7 gasPrice` here (the expected cost)\n // is strictly weaker than the block validator and lets txs whose\n // declared `gasLimit` exceeds the sender's balance through admission.\n // They then fail block validation with \"Cumulative outflow ... exceeds\n // available balance\" and the chain wedges (producer self-mutes for\n // ~150s after a successful-looking submit). Tracked in the\n // api-local-mongodb-beta repro: 783 stuck pending txs of this exact\n // shape, all with gasLimit \u2248 23.6 XL1 against \u2248 12 XL1 balance.\n const baseCost = wrapper.fees.base\n const priorityCost = wrapper.fees.priority\n const maxGasCost = wrapper.fees.gasLimit\n const fromKey = String(from)\n netBalances[fromKey] = (netBalances[fromKey] ?? 0n) - baseCost - priorityCost - maxGasCost\n\n const requiredBalances: Record<string, bigint> = {}\n for (const [address, net] of Object.entries(netBalances)) {\n const propertyKey = String(address)\n if (net < 0n) requiredBalances[propertyKey] = -net\n }\n\n errors.push(...(await balanceShortfallErrors(context, tx, requiredBalances)))\n } catch (ex) {\n errors.push(new HydratedTransactionValidationError(\n tx?.[0]?._hash ?? ZERO_HASH,\n tx,\n `Failed RequiredBalanceTransactionStateValidator: ${String(ex)}`,\n ex,\n ))\n }\n return errors\n }, context)\n}\n"],
5
+ "mappings": ";AAAA,SAAS,aAAAA,kBAAiB;AAM1B,SAAS,wBAAAC,6BAA4B;;;ACNrC,SAAS,iBAAiB;AAG1B;AAAA,EACE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ACF,CAAC;AAAA,IACH;AACA,WAAO;AAAA,EACT,GAAG,OAAO;AACZ;",
6
6
  "names": ["ZERO_HASH", "BlockValidationError", "ZERO_HASH", "BlockValidationError", "ZERO_HASH", "BlockValidationError", "ZERO_HASH", "BlockValidationError", "error", "ZERO_HASH", "BlockValidationError", "error", "BlockValidationError", "ZERO_HASH", "ZERO_HASH", "HydratedBlockValidationError", "ZERO_HASH", "ZERO_HASH", "BoundWitnessSchema", "InBlockPayloadValidationError", "InBlockPayloadValidationError", "transactionsFromHydratedBlock", "ZERO_HASH", "InBlockPayloadValidationError", "isTransactionBoundWitness", "isHashMeta", "isHashMeta", "ZERO_HASH", "InBlockPayloadValidationError", "InBlockPayloadValidationError", "ZERO_HASH", "ZERO_HASH", "InBlockPayloadValidationError", "InBlockPayloadValidationError", "ZERO_HASH", "ZERO_HASH", "InBlockPayloadValidationError", "InBlockPayloadValidationError", "ZERO_HASH", "ZERO_HASH", "InBlockPayloadValidationError", "InBlockPayloadValidationError", "ZERO_HASH", "ZERO_HASH", "InBlockPayloadValidationError", "InBlockPayloadValidationError", "ZERO_HASH", "ZERO_HASH", "InBlockPayloadValidationError", "InBlockPayloadValidationError", "ZERO_HASH", "ZERO_HASH", "InBlockPayloadValidationError", "InBlockPayloadValidationError", "ZERO_HASH", "ZERO_HASH", "InBlockPayloadValidationError", "InBlockPayloadValidationError", "ZERO_HASH", "BoundWitnessSchema", "InBlockPayloadValidationError", "ZERO_HASH", "error", "ZERO_HASH", "ZERO_HASH", "isHashMeta", "HydratedBlockValidationError", "isTransactionBoundWitness", "HydratedBlockValidationError", "ZERO_HASH", "spanRootAsync", "ZERO_HASH", "HydratedBlockStateValidationError", "ZERO_HASH", "spanRootAsync", "HydratedBlockStateValidationError", "ZERO_HASH", "spanRootAsync", "ZERO_HASH", "HydratedTransactionValidationError", "spanRootAsync", "ZERO_HASH", "AttoXL1", "netBalancesForPayloads", "XYO_ZERO_ADDRESS", "spanRootAsync", "HydratedTransactionValidationError", "ZERO_HASH"]
7
7
  }
@@ -5,7 +5,7 @@ import {
5
5
  createSignatureWrappers,
6
6
  HydratedTransactionWrapper,
7
7
  isSignedTransactionBoundWitnessWithStorageMeta,
8
- isTransfer,
8
+ isTransferPayload,
9
9
  XYO_ZERO_ADDRESS
10
10
  } from "@xyo-network/xl1-sdk";
11
11
  import { validateHydratedBlock, validateHydratedBlockState } from "#validation";
@@ -46,7 +46,7 @@ var HydratedBlockWrapper = class _HydratedBlockWrapper {
46
46
  return [...this.allPayloadsCache];
47
47
  }
48
48
  get reward() {
49
- return this.allPayloadsCache.reduce((acc, payload) => acc + (isTransfer(payload) && payload.from === XYO_ZERO_ADDRESS ? sumTransfers(payload) : 0n), 0n);
49
+ return this.allPayloadsCache.reduce((acc, payload) => acc + (isTransferPayload(payload) && payload.from === XYO_ZERO_ADDRESS ? sumTransfers(payload) : 0n), 0n);
50
50
  }
51
51
  get signatureCount() {
52
52
  return this._signatureCache.length;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/modules/wrappers/block/HydratedBlock.ts", "../../src/modules/wrappers/index.ts"],
4
- "sourcesContent": ["import type { Hash, Hex } from '@ariestools/sdk'\nimport { hexToBigInt } from '@ariestools/sdk'\nimport type { WithHashMeta } from '@xyo-network/sdk'\nimport { PayloadBuilder } from '@xyo-network/sdk'\nimport type {\n AccountBalanceViewer,\n BaseContext,\n HydratedBlockInstance, HydratedBlockWithHashMeta, HydratedTransactionInstance, SignatureInstance,\n SignedHydratedTransactionWithStorageMeta, Transfer,\n} from '@xyo-network/xl1-sdk'\nimport {\n createSignatureWrappers, HydratedTransactionWrapper,\n isSignedTransactionBoundWitnessWithStorageMeta,\n isTransfer, XYO_ZERO_ADDRESS,\n} from '@xyo-network/xl1-sdk'\n\nimport { validateHydratedBlock, validateHydratedBlockState } from '#validation'\n\nconst sumTransfers = (payload: Transfer) => {\n let total = 0n\n for (const i of Object.values(payload.transfers)) {\n total += hexToBigInt(i ?? '00' as Hex)\n }\n return total\n}\n\nexport class HydratedBlockWrapper<T extends HydratedBlockWithHashMeta> implements HydratedBlockInstance<[WithHashMeta<T[0]>, WithHashMeta<T[1][number]>[]]> {\n data: [WithHashMeta<T[0]>, WithHashMeta<T[1][number]>[]]\n protected allPayloadsCache: WithHashMeta<T[1][number]>[] = []\n protected context: BaseContext\n protected transactionsCache: HydratedTransactionInstance[] = []\n private _parseErrors: Error[] = []\n private _signatureCache: SignatureInstance[] = []\n\n protected constructor(data: [WithHashMeta<T[0]>, WithHashMeta<T[1][number]>[]], context?: BaseContext) {\n this.data = data\n this.context = context ?? { singletons: {} }\n }\n\n get block() {\n return this.data[0].block\n }\n\n get boundWitness() {\n return this.data[0]\n }\n\n get chain(): Hex {\n return this.data[0].chain\n }\n\n get parseErrors() {\n return this._parseErrors\n }\n\n get payloadCount(): number {\n return this.allPayloadsCache.length\n }\n\n get payloads(): T[1][number][] {\n return [...this.allPayloadsCache]\n }\n\n get reward(): bigint {\n return this.allPayloadsCache.reduce((acc: bigint, payload) => acc + (\n isTransfer(payload) && (payload.from === XYO_ZERO_ADDRESS) ? sumTransfers(payload) : 0n), 0n)\n }\n\n get signatureCount(): number {\n return this._signatureCache.length\n }\n\n get signatures(): SignatureInstance[] {\n return [...this._signatureCache]\n }\n\n get stepHashes(): Hash[] {\n return this.data[0].step_hashes ?? []\n }\n\n get transactionCount(): number {\n return this.transactionsCache.length\n }\n\n get transactions(): HydratedTransactionInstance[] {\n return this.transactionsCache\n }\n\n static async parse<T extends HydratedBlockWithHashMeta>(block: T, validate = false): Promise<HydratedBlockInstance> {\n const wrapper = new HydratedBlockWrapper(block)\n return await wrapper.parse(validate)\n }\n\n payload(index: number) {\n return this.data[1].at(index)\n }\n\n signature(index: number): SignatureInstance | undefined {\n return this._signatureCache[index]\n }\n\n transaction(index: number): HydratedTransactionInstance | undefined {\n return this.transactionsCache.at(index)\n }\n\n async validate(): Promise<Error[]> {\n return await validateHydratedBlock(this.context, this.data)\n }\n\n async validateState(services: { accountBalance: AccountBalanceViewer }): Promise<Error[]> {\n return await validateHydratedBlockState({\n ...this.context, chainIdAtBlockNumber: () => this.chain, ...services,\n }, this.data)\n }\n\n protected async parse(validate = false): Promise<HydratedBlockInstance<[WithHashMeta<T[0]>, WithHashMeta<T[1][number]>[]]>> {\n const allPayloads = await PayloadBuilder.addStorageMeta(this.data[1])\n for (const payload of allPayloads) {\n if (isSignedTransactionBoundWitnessWithStorageMeta(payload)) {\n const hydratedTransaction: SignedHydratedTransactionWithStorageMeta = [payload, allPayloads.filter(\n p => payload.payload_hashes.includes(p._hash) || payload.payload_hashes.includes(p._dataHash),\n )]\n this.transactionsCache.push(await HydratedTransactionWrapper.parse(hydratedTransaction))\n } else {\n this.allPayloadsCache.push(payload)\n }\n }\n this._signatureCache = await createSignatureWrappers(this.data[0])\n if (validate) {\n this._parseErrors = await this.validate()\n }\n return this\n }\n}\n", "export * from './block/index.ts'\nexport * from '@xyo-network/xl1-sdk/wrappers'\n"],
5
- "mappings": ";AACA,SAAS,mBAAmB;AAE5B,SAAS,sBAAsB;AAO/B;AAAA,EACE;AAAA,EAAyB;AAAA,EACzB;AAAA,EACA;AAAA,EAAY;AAAA,OACP;AAEP,SAAS,uBAAuB,kCAAkC;AAElE,IAAM,eAAe,CAAC,YAAsB;AAC1C,MAAI,QAAQ;AACZ,aAAW,KAAK,OAAO,OAAO,QAAQ,SAAS,GAAG;AAChD,aAAS,YAAY,KAAK,IAAW;AAAA,EACvC;AACA,SAAO;AACT;AAEO,IAAM,uBAAN,MAAM,sBAA+I;AAAA,EAC1J;AAAA,EACU,mBAAiD,CAAC;AAAA,EAClD;AAAA,EACA,oBAAmD,CAAC;AAAA,EACtD,eAAwB,CAAC;AAAA,EACzB,kBAAuC,CAAC;AAAA,EAEtC,YAAY,MAA0D,SAAuB;AACrG,SAAK,OAAO;AACZ,SAAK,UAAU,WAAW,EAAE,YAAY,CAAC,EAAE;AAAA,EAC7C;AAAA,EAEA,IAAI,QAAQ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kB,GAAG,KAAK;AAAA,EACxC;AAAA,EAEA,MAAM,WAA6B;AACjC,WAAO,MAAM,sBAAsB,KAAK,SAAS,KAAK,IAAI;AAAA,EAC5D;AAAA,EAEA,MAAM,cAAc,UAAsE;AACxF,WAAO,MAAM,2BAA2B;AAAA,MACtC,GAAG,KAAK;AAAA,MAAS,sBAAsB,MAAM,KAAK;AAAA,MAAO,GAAG;AAAA,IAC9D,GAAG,KAAK,IAAI;AAAA,EACd;AAAA,EAEA,MAAgB,MAAM,WAAW,OAA2F;AAC1H,UAAM,cAAc,MAAM,eAAe,eAAe,KAAK,KAAK,CAAC,CAAC;AACpE,eAAW,WAAW,aAAa;AACjC,UAAI,+CAA+C,OAAO,GAAG;AAC3D,cAAM,sBAAgE,CAAC,SAAS,YAAY;AAAA,UAC1F,OAAK,QAAQ,eAAe,SAAS,EAAE,KAAK,KAAK,QAAQ,eAAe,SAAS,EAAE,SAAS;AAAA,QAC9F,CAAC;AACD,aAAK,kBAAkB,KAAK,MAAM,2BAA2B,MAAM,mBAAmB,CAAC;AAAA,MACzF,OAAO;AACL,aAAK,iBAAiB,KAAK,OAAO;AAAA,MACpC;AAAA,IACF;AACA,SAAK,kBAAkB,MAAM,wBAAwB,KAAK,KAAK,CAAC,CAAC;AACjE,QAAI,UAAU;AACZ,WAAK,eAAe,MAAM,KAAK,SAAS;AAAA,IAC1C;AACA,WAAO;AAAA,EACT;AACF;;;ACpIA,cAAc;",
4
+ "sourcesContent": ["import type { Hash, Hex } from '@ariestools/sdk'\nimport { hexToBigInt } from '@ariestools/sdk'\nimport type { WithHashMeta } from '@xyo-network/sdk'\nimport { PayloadBuilder } from '@xyo-network/sdk'\nimport type {\n AccountBalanceViewer,\n BaseContext,\n HydratedBlockInstance, HydratedBlockWithHashMeta, HydratedTransactionInstance, SignatureInstance,\n SignedHydratedTransactionWithStorageMeta, Transfer,\n} from '@xyo-network/xl1-sdk'\nimport {\n createSignatureWrappers, HydratedTransactionWrapper,\n isSignedTransactionBoundWitnessWithStorageMeta,\n isTransferPayload, XYO_ZERO_ADDRESS,\n} from '@xyo-network/xl1-sdk'\n\nimport { validateHydratedBlock, validateHydratedBlockState } from '#validation'\n\nconst sumTransfers = (payload: Transfer) => {\n let total = 0n\n for (const i of Object.values(payload.transfers)) {\n total += hexToBigInt(i ?? '00' as Hex)\n }\n return total\n}\n\nexport class HydratedBlockWrapper<T extends HydratedBlockWithHashMeta> implements HydratedBlockInstance<[WithHashMeta<T[0]>, WithHashMeta<T[1][number]>[]]> {\n data: [WithHashMeta<T[0]>, WithHashMeta<T[1][number]>[]]\n protected allPayloadsCache: WithHashMeta<T[1][number]>[] = []\n protected context: BaseContext\n protected transactionsCache: HydratedTransactionInstance[] = []\n private _parseErrors: Error[] = []\n private _signatureCache: SignatureInstance[] = []\n\n protected constructor(data: [WithHashMeta<T[0]>, WithHashMeta<T[1][number]>[]], context?: BaseContext) {\n this.data = data\n this.context = context ?? { singletons: {} }\n }\n\n get block() {\n return this.data[0].block\n }\n\n get boundWitness() {\n return this.data[0]\n }\n\n get chain(): Hex {\n return this.data[0].chain\n }\n\n get parseErrors() {\n return this._parseErrors\n }\n\n get payloadCount(): number {\n return this.allPayloadsCache.length\n }\n\n get payloads(): T[1][number][] {\n return [...this.allPayloadsCache]\n }\n\n get reward(): bigint {\n return this.allPayloadsCache.reduce((acc: bigint, payload) => acc + (\n isTransferPayload(payload) && (payload.from === XYO_ZERO_ADDRESS) ? sumTransfers(payload) : 0n), 0n)\n }\n\n get signatureCount(): number {\n return this._signatureCache.length\n }\n\n get signatures(): SignatureInstance[] {\n return [...this._signatureCache]\n }\n\n get stepHashes(): Hash[] {\n return this.data[0].step_hashes ?? []\n }\n\n get transactionCount(): number {\n return this.transactionsCache.length\n }\n\n get transactions(): HydratedTransactionInstance[] {\n return this.transactionsCache\n }\n\n static async parse<T extends HydratedBlockWithHashMeta>(block: T, validate = false): Promise<HydratedBlockInstance> {\n const wrapper = new HydratedBlockWrapper(block)\n return await wrapper.parse(validate)\n }\n\n payload(index: number) {\n return this.data[1].at(index)\n }\n\n signature(index: number): SignatureInstance | undefined {\n return this._signatureCache[index]\n }\n\n transaction(index: number): HydratedTransactionInstance | undefined {\n return this.transactionsCache.at(index)\n }\n\n async validate(): Promise<Error[]> {\n return await validateHydratedBlock(this.context, this.data)\n }\n\n async validateState(services: { accountBalance: AccountBalanceViewer }): Promise<Error[]> {\n return await validateHydratedBlockState({\n ...this.context, chainIdAtBlockNumber: () => this.chain, ...services,\n }, this.data)\n }\n\n protected async parse(validate = false): Promise<HydratedBlockInstance<[WithHashMeta<T[0]>, WithHashMeta<T[1][number]>[]]>> {\n const allPayloads = await PayloadBuilder.addStorageMeta(this.data[1])\n for (const payload of allPayloads) {\n if (isSignedTransactionBoundWitnessWithStorageMeta(payload)) {\n const hydratedTransaction: SignedHydratedTransactionWithStorageMeta = [payload, allPayloads.filter(\n p => payload.payload_hashes.includes(p._hash) || payload.payload_hashes.includes(p._dataHash),\n )]\n this.transactionsCache.push(await HydratedTransactionWrapper.parse(hydratedTransaction))\n } else {\n this.allPayloadsCache.push(payload)\n }\n }\n this._signatureCache = await createSignatureWrappers(this.data[0])\n if (validate) {\n this._parseErrors = await this.validate()\n }\n return this\n }\n}\n", "export * from './block/index.ts'\nexport * from '@xyo-network/xl1-sdk/wrappers'\n"],
5
+ "mappings": ";AACA,SAAS,mBAAmB;AAE5B,SAAS,sBAAsB;AAO/B;AAAA,EACE;AAAA,EAAyB;AAAA,EACzB;AAAA,EACA;AAAA,EAAmB;AAAA,OACd;AAEP,SAAS,uBAAuB,kCAAkC;AAElE,IAAM,eAAe,CAAC,YAAsB;AAC1C,MAAI,QAAQ;AACZ,aAAW,KAAK,OAAO,OAAO,QAAQ,SAAS,GAAG;AAChD,aAAS,YAAY,KAAK,IAAW;AAAA,EACvC;AACA,SAAO;AACT;AAEO,IAAM,uBAAN,MAAM,sBAA+I;AAAA,EAC1J;AAAA,EACU,mBAAiD,CAAC;AAAA,EAClD;AAAA,EAC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C;AAAA,EAEA,QAAQ,OAAe;AACrB,WAAO,KAAK,KAAK,CAAC,EAAE,GAAG,KAAK;AAAA,EAC9B;AAAA,EAEA,UAAU,OAA8C;AACtD,WAAO,KAAK,gBAAgB,KAAK;AAAA,EACnC;AAAA,EAEA,YAAY,OAAwD;AAClE,WAAO,KAAK,kBAAkB,GAAG,KAAK;AAAA,EACxC;AAAA,EAEA,MAAM,WAA6B;AACjC,WAAO,MAAM,sBAAsB,KAAK,SAAS,KAAK,IAAI;AAAA,EAC5D;AAAA,EAEA,MAAM,cAAc,UAAsE;AACxF,WAAO,MAAM,2BAA2B;AAAA,MACtC,GAAG,KAAK;AAAA,MAAS,sBAAsB,MAAM,KAAK;AAAA,MAAO,GAAG;AAAA,IAC9D,GAAG,KAAK,IAAI;AAAA,EACd;AAAA,EAEA,MAAgB,MAAM,WAAW,OAA2F;AAC1H,UAAM,cAAc,MAAM,eAAe,eAAe,KAAK,KAAK,CAAC,CAAC;AACpE,eAAW,WAAW,aAAa;AACjC,UAAI,+CAA+C,OAAO,GAAG;AAC3D,cAAM,sBAAgE,CAAC,SAAS,YAAY;AAAA,UAC1F,OAAK,QAAQ,eAAe,SAAS,EAAE,KAAK,KAAK,QAAQ,eAAe,SAAS,EAAE,SAAS;AAAA,QAC9F,CAAC;AACD,aAAK,kBAAkB,KAAK,MAAM,2BAA2B,MAAM,mBAAmB,CAAC;AAAA,MACzF,OAAO;AACL,aAAK,iBAAiB,KAAK,OAAO;AAAA,MACpC;AAAA,IACF;AACA,SAAK,kBAAkB,MAAM,wBAAwB,KAAK,KAAK,CAAC,CAAC;AACjE,QAAI,UAAU;AACZ,WAAK,eAAe,MAAM,KAAK,SAAS;AAAA,IAC1C;AACA,WAAO;AAAA,EACT;AACF;;;ACpIA,cAAc;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "http://json.schemastore.org/package.json",
3
3
  "name": "@xyo-network/chain-sdk",
4
- "version": "4.3.2",
4
+ "version": "4.4.0",
5
5
  "description": "XYO Layer One SDK",
6
6
  "homepage": "https://xylabs.com",
7
7
  "bugs": {
@@ -141,17 +141,17 @@
141
141
  "shallowequal": "~1.1.0"
142
142
  },
143
143
  "devDependencies": {
144
- "@ariestools/toolchain": "~8.7.15",
145
- "@ariestools/tsconfig": "~8.7.15",
144
+ "@ariestools/toolchain": "~8.7.16",
145
+ "@ariestools/tsconfig": "~8.7.16",
146
146
  "@ariestools/vitest-extended": "~8.0.3",
147
147
  "@metamask/json-rpc-engine": "~10.5.0",
148
148
  "@opentelemetry/api": "~1.9.1",
149
149
  "@types/shallowequal": "~1.1.5",
150
150
  "@xyo-network/archivist-mongodb": "~7.2.1",
151
151
  "@xyo-network/sdk-protocol": "~7.2.1",
152
- "@xyo-network/xl1-driver-lmdb": "~4.4.8",
153
- "@xyo-network/xl1-driver-mongodb": "~4.4.8",
154
- "@xyo-network/xl1-sdk": "~4.4.8",
152
+ "@xyo-network/xl1-driver-lmdb": "~4.5.0",
153
+ "@xyo-network/xl1-driver-mongodb": "~4.5.0",
154
+ "@xyo-network/xl1-sdk": "~4.5.0",
155
155
  "async-mutex": "~0.5.0",
156
156
  "eslint": "~10.7.0",
157
157
  "ethers": "~6.17.0",
@@ -168,7 +168,7 @@
168
168
  "@opentelemetry/api": "^1.9",
169
169
  "@opentelemetry/sdk-trace-base": "^2.9",
170
170
  "@xyo-network/sdk": "^7.2",
171
- "@xyo-network/xl1-sdk": "^4.4",
171
+ "@xyo-network/xl1-sdk": "^4.5",
172
172
  "async-mutex": "^0.5",
173
173
  "ethers": "^6.17",
174
174
  "web3-types": "^1.10"