@xyo-network/chain-sdk 5.0.2 → 5.0.3

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.
@@ -1,4 +1,5 @@
1
1
  import type { Address, Logger } from '@ariestools/sdk';
2
+ import type { AccountInstance } from '@xyo-network/sdk';
2
3
  import type { BaseContext, BlockValidationViewer, BlockViewer, DeadLetterQueueRunner, FinalizationRunner, MempoolViewer } from '@xyo-network/xl1-sdk';
3
4
  interface ProcessPendingBlocksParams {
4
5
  allowedProducers?: Address[];
@@ -11,8 +12,13 @@ interface ProcessPendingBlocksParams {
11
12
  logger?: Logger;
12
13
  mempoolViewer: MempoolViewer;
13
14
  minCandidates?: number;
15
+ /**
16
+ * Account this node observes with. When supplied, rejection records name it as the rejector and
17
+ * carry its signature, which is what makes them attributable evidence rather than a local note.
18
+ */
19
+ observer?: AccountInstance;
14
20
  }
15
- export declare function processPendingBlocks({ blockValidationViewer, blockViewer, context, logger, mempoolViewer, finalizationRunner, allowedProducers, backoffMs, minCandidates, deadLetterQueueRunner, }: ProcessPendingBlocksParams): Promise<[{
21
+ export declare function processPendingBlocks({ blockValidationViewer, blockViewer, context, logger, mempoolViewer, finalizationRunner, allowedProducers, backoffMs, minCandidates, deadLetterQueueRunner, observer, }: ProcessPendingBlocksParams): Promise<[{
16
22
  schema: "network.xyo.boundwitness" & {
17
23
  readonly __schema: true;
18
24
  };
@@ -1 +1 @@
1
- {"version":3,"file":"processPendingBlocks.d.ts","sourceRoot":"","sources":["../../../../../src/modules/services/implementation/processPendingBlocks.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAEtD,OAAO,KAAK,EACV,WAAW,EAAE,qBAAqB,EAAE,WAAW,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,aAAa,EAC1G,MAAM,sBAAsB,CAAA;AAO7B,UAAU,0BAA0B;IAClC,gBAAgB,CAAC,EAAE,OAAO,EAAE,CAAA;IAC5B,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,qBAAqB,EAAE,qBAAqB,CAAA;IAC5C,WAAW,EAAE,WAAW,CAAA;IACxB,OAAO,EAAE,WAAW,CAAA;IACpB,qBAAqB,CAAC,EAAE,qBAAqB,CAAA;IAC7C,kBAAkB,EAAE,kBAAkB,CAAA;IACtC,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,aAAa,EAAE,aAAa,CAAA;IAC5B,aAAa,CAAC,EAAE,MAAM,CAAA;CACvB;AAGD,wBAAsB,oBAAoB,CAAC,EACzC,qBAAqB,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,SAAS,EAAE,aAAa,EAAE,qBAAqB,GAC1J,EAAE,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;oBA0E5B"}
1
+ {"version":3,"file":"processPendingBlocks.d.ts","sourceRoot":"","sources":["../../../../../src/modules/services/implementation/processPendingBlocks.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAEtD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AACvD,OAAO,KAAK,EACV,WAAW,EAAE,qBAAqB,EAAE,WAAW,EAAE,qBAAqB,EAAE,kBAAkB,EAA6B,aAAa,EACrI,MAAM,sBAAsB,CAAA;AAS7B,UAAU,0BAA0B;IAClC,gBAAgB,CAAC,EAAE,OAAO,EAAE,CAAA;IAC5B,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,qBAAqB,EAAE,qBAAqB,CAAA;IAC5C,WAAW,EAAE,WAAW,CAAA;IACxB,OAAO,EAAE,WAAW,CAAA;IACpB,qBAAqB,CAAC,EAAE,qBAAqB,CAAA;IAC7C,kBAAkB,EAAE,kBAAkB,CAAA;IACtC,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,aAAa,EAAE,aAAa,CAAA;IAC5B,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB;;;OAGG;IACH,QAAQ,CAAC,EAAE,eAAe,CAAA;CAC3B;AAgCD,wBAAsB,oBAAoB,CAAC,EACzC,qBAAqB,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,SAAS,EAAE,aAAa,EAAE,qBAAqB,EAAE,QAAQ,GACpK,EAAE,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;oBAiE5B"}
@@ -1,4 +1,5 @@
1
1
  import type { Address, Logger } from '@ariestools/sdk';
2
+ import type { AccountInstance } from '@xyo-network/sdk';
2
3
  import type { BaseContext, BlockValidationViewer, BlockViewer, DeadLetterQueueRunner, FinalizationRunner, MempoolViewer } from '@xyo-network/xl1-sdk';
3
4
  interface ProcessPendingBlocksParams {
4
5
  allowedProducers?: Address[];
@@ -11,8 +12,13 @@ interface ProcessPendingBlocksParams {
11
12
  logger?: Logger;
12
13
  mempoolViewer: MempoolViewer;
13
14
  minCandidates?: number;
15
+ /**
16
+ * Account this node observes with. When supplied, rejection records name it as the rejector and
17
+ * carry its signature, which is what makes them attributable evidence rather than a local note.
18
+ */
19
+ observer?: AccountInstance;
14
20
  }
15
- export declare function processPendingBlocks({ blockValidationViewer, blockViewer, context, logger, mempoolViewer, finalizationRunner, allowedProducers, backoffMs, minCandidates, deadLetterQueueRunner, }: ProcessPendingBlocksParams): Promise<[{
21
+ export declare function processPendingBlocks({ blockValidationViewer, blockViewer, context, logger, mempoolViewer, finalizationRunner, allowedProducers, backoffMs, minCandidates, deadLetterQueueRunner, observer, }: ProcessPendingBlocksParams): Promise<[{
16
22
  schema: "network.xyo.boundwitness" & {
17
23
  readonly __schema: true;
18
24
  };
@@ -1 +1 @@
1
- {"version":3,"file":"processPendingBlocks.d.ts","sourceRoot":"","sources":["../../../../../src/modules/services/implementation/processPendingBlocks.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAEtD,OAAO,KAAK,EACV,WAAW,EAAE,qBAAqB,EAAE,WAAW,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,aAAa,EAC1G,MAAM,sBAAsB,CAAA;AAO7B,UAAU,0BAA0B;IAClC,gBAAgB,CAAC,EAAE,OAAO,EAAE,CAAA;IAC5B,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,qBAAqB,EAAE,qBAAqB,CAAA;IAC5C,WAAW,EAAE,WAAW,CAAA;IACxB,OAAO,EAAE,WAAW,CAAA;IACpB,qBAAqB,CAAC,EAAE,qBAAqB,CAAA;IAC7C,kBAAkB,EAAE,kBAAkB,CAAA;IACtC,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,aAAa,EAAE,aAAa,CAAA;IAC5B,aAAa,CAAC,EAAE,MAAM,CAAA;CACvB;AAGD,wBAAsB,oBAAoB,CAAC,EACzC,qBAAqB,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,SAAS,EAAE,aAAa,EAAE,qBAAqB,GAC1J,EAAE,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;oBA0E5B"}
1
+ {"version":3,"file":"processPendingBlocks.d.ts","sourceRoot":"","sources":["../../../../../src/modules/services/implementation/processPendingBlocks.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAEtD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AACvD,OAAO,KAAK,EACV,WAAW,EAAE,qBAAqB,EAAE,WAAW,EAAE,qBAAqB,EAAE,kBAAkB,EAA6B,aAAa,EACrI,MAAM,sBAAsB,CAAA;AAS7B,UAAU,0BAA0B;IAClC,gBAAgB,CAAC,EAAE,OAAO,EAAE,CAAA;IAC5B,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,qBAAqB,EAAE,qBAAqB,CAAA;IAC5C,WAAW,EAAE,WAAW,CAAA;IACxB,OAAO,EAAE,WAAW,CAAA;IACpB,qBAAqB,CAAC,EAAE,qBAAqB,CAAA;IAC7C,kBAAkB,EAAE,kBAAkB,CAAA;IACtC,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,aAAa,EAAE,aAAa,CAAA;IAC5B,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB;;;OAGG;IACH,QAAQ,CAAC,EAAE,eAAe,CAAA;CAC3B;AAgCD,wBAAsB,oBAAoB,CAAC,EACzC,qBAAqB,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,SAAS,EAAE,aAAa,EAAE,qBAAqB,EAAE,QAAQ,GACpK,EAAE,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;oBAiE5B"}
@@ -135,8 +135,30 @@ var createBootstrapHead = async (account, chainId, genesisBlockRewardAmount, gen
135
135
 
136
136
  // src/modules/services/implementation/processPendingBlocks.ts
137
137
  import { assertEx as assertEx2, isDefined } from "@ariestools/sdk";
138
- import { BlockRejectionSchema, isSignedHydratedBlockWithHashMeta } from "@xyo-network/xl1-sdk";
138
+ import {
139
+ BlockRejectionSchema,
140
+ buildSignedBlockRejection,
141
+ isSignedHydratedBlockWithHashMeta
142
+ } from "@xyo-network/xl1-sdk";
139
143
  import { ChainHeadSelector } from "#analyze";
144
+ function hasMessage(value) {
145
+ return typeof value === "object" && value !== null && "message" in value;
146
+ }
147
+ async function reportRejectedBlock(deadLetterQueueRunner, block, result, observer) {
148
+ const errors = Array.isArray(result) ? result.map((error) => ({
149
+ hash: block[0]._hash,
150
+ name: "BlockValidationError",
151
+ message: String(hasMessage(error) ? error.message : error)
152
+ })) : [{ hash: block[0]._hash, name: "BlockValidationError" }];
153
+ const rejection = {
154
+ schema: BlockRejectionSchema,
155
+ block,
156
+ errors,
157
+ rejector: observer?.address ?? "validator"
158
+ };
159
+ const signed = observer === void 0 ? void 0 : await buildSignedBlockRejection(rejection, observer);
160
+ await deadLetterQueueRunner.rejectBlock(rejection, signed);
161
+ }
140
162
  async function processPendingBlocks({
141
163
  blockValidationViewer,
142
164
  blockViewer,
@@ -147,7 +169,8 @@ async function processPendingBlocks({
147
169
  allowedProducers,
148
170
  backoffMs,
149
171
  minCandidates,
150
- deadLetterQueueRunner
172
+ deadLetterQueueRunner,
173
+ observer
151
174
  }) {
152
175
  const start = Date.now();
153
176
  const currentBlock = await blockViewer.currentBlock();
@@ -183,19 +206,7 @@ async function processPendingBlocks({
183
206
  blocksToFinalize.push(block);
184
207
  } else {
185
208
  logger?.error("Block validation failed", block[0].block, block[0]._hash, JSON.stringify(result, null, 2));
186
- if (deadLetterQueueRunner) {
187
- const errors = Array.isArray(result) ? result.map((e) => ({
188
- hash: block[0]._hash,
189
- name: "BlockValidationError",
190
- message: String(e.message ?? e)
191
- })) : [{ hash: block[0]._hash, name: "BlockValidationError" }];
192
- await deadLetterQueueRunner.rejectBlock({
193
- schema: BlockRejectionSchema,
194
- block,
195
- errors,
196
- rejector: "validator"
197
- });
198
- }
209
+ if (deadLetterQueueRunner) await reportRejectedBlock(deadLetterQueueRunner, block, result, observer);
199
210
  }
200
211
  }
201
212
  logger?.info("Validated new HeadBlock head from (block) in", `${Date.now() - start}ms`, newHeadBlock.block, "to", oldHeadBlock?.block);
@@ -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 } 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 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 backoffMs?: number\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, backoffMs, 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, backoffMs, 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.contextAccount,\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", "import { z } from 'zod'\n\n/**\n * Producer tuning read from the materialized provider config's `options`\n * (`providerBindings.BlockRunner.options` \u2014 orchestration lifts the producer\n * actor slice there at config load).\n */\nexport const ProducerTuningOptionsZod = z.object({\n disableIntentRedeclaration: z.coerce.boolean().optional(),\n heartbeatInterval: z.coerce.number().optional(),\n rewardAddress: z.string().optional(),\n})\n\n/** Producer tuning fields resolved from provider options. */\nexport type ProducerTuningFields = z.infer<typeof ProducerTuningOptionsZod>\n\n/** Producer tuning from the materialized provider config. */\nexport function producerTuningFromConfig(config: unknown): ProducerTuningFields {\n const options = (config as { options?: Record<string, unknown> }).options ?? {}\n const parsed = ProducerTuningOptionsZod.safeParse(options)\n return parsed.success ? parsed.data : {}\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,4BAA4B;;;ACMrC;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;AAAA,EACV;AAAA;AAAA,EAGA,MAAM,2BAA2B,qBAAiF;AAChH,UAAM,CAAC,EAAE,IAAI;AAEb,QAAK,MAAM,KAAK,YAAY,YAAY,GAAG,KAAK,MAAO,OAAW,QAAO;AAGzE,WAAO;AAAA,EACT;AACF;AArDE,cADW,cACK,mBAAkB,CAAC;AACnC,cAFW,cAEK,kBAAiB;AACjC,cAHW,cAGK,gBAAe,CAAC,kBAAkB;AAClD,cAJW,cAIK,YAAW,CAAC,gBAAgB;AAC5C,cALW,cAKK,WAAU;AALf,eAAN;AAAA,EADN,kBAAkB;AAAA,GACN;;;AC1Bb,SAAS,gBAAgB;AAEzB;AAAA,EACE,6BAAAA;AAAA,EAGuB,qBAAAC;AAAA,OAElB;AAEP,SAAS,oBAAoB,uBAAuB;AAW7C,IAAM,sBAAN,cAAkCC,2BAAiF;AAAA,EAKxH,UAAU,oBAAoB;AAAA,E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AAA,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 } 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 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 { AccountInstance } from '@xyo-network/sdk'\nimport type {\n BaseContext, BlockValidationViewer, BlockViewer, DeadLetterQueueRunner, FinalizationRunner, HydratedBlockWithHashMeta, MempoolViewer,\n} from '@xyo-network/xl1-sdk'\nimport {\n BlockRejectionSchema, buildSignedBlockRejection, isSignedHydratedBlockWithHashMeta,\n} from '@xyo-network/xl1-sdk'\n\nimport { ChainHeadSelector } from '#analyze'\n\n// type FinalizedBlockAttributes = { producer: Address }\n\ninterface ProcessPendingBlocksParams {\n allowedProducers?: Address[]\n backoffMs?: number\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 * Account this node observes with. When supplied, rejection records name it as the rejector and\n * carry its signature, which is what makes them attributable evidence rather than a local note.\n */\n observer?: AccountInstance\n}\n\nfunction hasMessage(value: unknown): value is { message: unknown } {\n return typeof value === 'object' && value !== null && 'message' in value\n}\n\n/**\n * Records a block that failed validation.\n *\n * With an observer account the record names and is signed by this node, which is what turns a\n * local diagnostic into evidence someone else can check; without one it keeps the legacy\n * unsigned form.\n */\nasync function reportRejectedBlock(\n deadLetterQueueRunner: DeadLetterQueueRunner,\n block: HydratedBlockWithHashMeta,\n result: unknown,\n observer?: AccountInstance,\n): Promise<void> {\n const errors = Array.isArray(result)\n ? (result as unknown[]).map(error => ({\n hash: block[0]._hash, name: 'BlockValidationError', message: String(hasMessage(error) ? error.message : error),\n }))\n : [{ hash: block[0]._hash, name: 'BlockValidationError' }]\n const rejection = {\n schema: BlockRejectionSchema, block, errors, rejector: observer?.address ?? 'validator',\n }\n const signed = observer === undefined ? undefined : await buildSignedBlockRejection(rejection, observer)\n await deadLetterQueueRunner.rejectBlock(rejection, signed)\n}\n\n// eslint-disable-next-line complexity\nexport async function processPendingBlocks({\n blockValidationViewer, blockViewer, context, logger, mempoolViewer, finalizationRunner, allowedProducers, backoffMs, minCandidates, deadLetterQueueRunner, observer,\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, backoffMs, 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) await reportRejectedBlock(deadLetterQueueRunner, block, result, observer)\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.contextAccount,\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", "import { z } from 'zod'\n\n/**\n * Producer tuning read from the materialized provider config's `options`\n * (`providerBindings.BlockRunner.options` \u2014 orchestration lifts the producer\n * actor slice there at config load).\n */\nexport const ProducerTuningOptionsZod = z.object({\n disableIntentRedeclaration: z.coerce.boolean().optional(),\n heartbeatInterval: z.coerce.number().optional(),\n rewardAddress: z.string().optional(),\n})\n\n/** Producer tuning fields resolved from provider options. */\nexport type ProducerTuningFields = z.infer<typeof ProducerTuningOptionsZod>\n\n/** Producer tuning from the materialized provider config. */\nexport function producerTuningFromConfig(config: unknown): ProducerTuningFields {\n const options = (config as { options?: Record<string, unknown> }).options ?? {}\n const parsed = ProducerTuningOptionsZod.safeParse(options)\n return parsed.success ? parsed.data : {}\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,4BAA4B;;;ACMrC;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;A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F;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
  }
@@ -1,4 +1,5 @@
1
1
  import type { Address, Logger } from '@ariestools/sdk';
2
+ import type { AccountInstance } from '@xyo-network/sdk';
2
3
  import type { BaseContext, BlockValidationViewer, BlockViewer, DeadLetterQueueRunner, FinalizationRunner, MempoolViewer } from '@xyo-network/xl1-sdk';
3
4
  interface ProcessPendingBlocksParams {
4
5
  allowedProducers?: Address[];
@@ -11,8 +12,13 @@ interface ProcessPendingBlocksParams {
11
12
  logger?: Logger;
12
13
  mempoolViewer: MempoolViewer;
13
14
  minCandidates?: number;
15
+ /**
16
+ * Account this node observes with. When supplied, rejection records name it as the rejector and
17
+ * carry its signature, which is what makes them attributable evidence rather than a local note.
18
+ */
19
+ observer?: AccountInstance;
14
20
  }
15
- export declare function processPendingBlocks({ blockValidationViewer, blockViewer, context, logger, mempoolViewer, finalizationRunner, allowedProducers, backoffMs, minCandidates, deadLetterQueueRunner, }: ProcessPendingBlocksParams): Promise<[{
21
+ export declare function processPendingBlocks({ blockValidationViewer, blockViewer, context, logger, mempoolViewer, finalizationRunner, allowedProducers, backoffMs, minCandidates, deadLetterQueueRunner, observer, }: ProcessPendingBlocksParams): Promise<[{
16
22
  schema: "network.xyo.boundwitness" & {
17
23
  readonly __schema: true;
18
24
  };
@@ -1 +1 @@
1
- {"version":3,"file":"processPendingBlocks.d.ts","sourceRoot":"","sources":["../../../../../src/modules/services/implementation/processPendingBlocks.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAEtD,OAAO,KAAK,EACV,WAAW,EAAE,qBAAqB,EAAE,WAAW,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,aAAa,EAC1G,MAAM,sBAAsB,CAAA;AAO7B,UAAU,0BAA0B;IAClC,gBAAgB,CAAC,EAAE,OAAO,EAAE,CAAA;IAC5B,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,qBAAqB,EAAE,qBAAqB,CAAA;IAC5C,WAAW,EAAE,WAAW,CAAA;IACxB,OAAO,EAAE,WAAW,CAAA;IACpB,qBAAqB,CAAC,EAAE,qBAAqB,CAAA;IAC7C,kBAAkB,EAAE,kBAAkB,CAAA;IACtC,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,aAAa,EAAE,aAAa,CAAA;IAC5B,aAAa,CAAC,EAAE,MAAM,CAAA;CACvB;AAGD,wBAAsB,oBAAoB,CAAC,EACzC,qBAAqB,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,SAAS,EAAE,aAAa,EAAE,qBAAqB,GAC1J,EAAE,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;oBA0E5B"}
1
+ {"version":3,"file":"processPendingBlocks.d.ts","sourceRoot":"","sources":["../../../../../src/modules/services/implementation/processPendingBlocks.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAEtD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AACvD,OAAO,KAAK,EACV,WAAW,EAAE,qBAAqB,EAAE,WAAW,EAAE,qBAAqB,EAAE,kBAAkB,EAA6B,aAAa,EACrI,MAAM,sBAAsB,CAAA;AAS7B,UAAU,0BAA0B;IAClC,gBAAgB,CAAC,EAAE,OAAO,EAAE,CAAA;IAC5B,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,qBAAqB,EAAE,qBAAqB,CAAA;IAC5C,WAAW,EAAE,WAAW,CAAA;IACxB,OAAO,EAAE,WAAW,CAAA;IACpB,qBAAqB,CAAC,EAAE,qBAAqB,CAAA;IAC7C,kBAAkB,EAAE,kBAAkB,CAAA;IACtC,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,aAAa,EAAE,aAAa,CAAA;IAC5B,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB;;;OAGG;IACH,QAAQ,CAAC,EAAE,eAAe,CAAA;CAC3B;AAgCD,wBAAsB,oBAAoB,CAAC,EACzC,qBAAqB,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,SAAS,EAAE,aAAa,EAAE,qBAAqB,EAAE,QAAQ,GACpK,EAAE,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;oBAiE5B"}
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": "5.0.2",
4
+ "version": "5.0.3",
5
5
  "description": "XYO Layer One SDK",
6
6
  "homepage": "https://xylabs.com",
7
7
  "bugs": {
@@ -141,16 +141,16 @@
141
141
  "shallowequal": "~1.1.0"
142
142
  },
143
143
  "devDependencies": {
144
- "@ariestools/toolchain": "~9.0.0",
145
- "@ariestools/tsconfig": "~9.0.0",
144
+ "@ariestools/toolchain": "~9.0.1",
145
+ "@ariestools/tsconfig": "~9.0.1",
146
146
  "@ariestools/vitest-extended": "~8.0.3",
147
147
  "@opentelemetry/api": "~1.9.1",
148
148
  "@types/shallowequal": "~1.1.5",
149
149
  "@xyo-network/archivist-mongodb": "~7.2.3",
150
150
  "@xyo-network/sdk-protocol": "~7.2.3",
151
- "@xyo-network/xl1-driver-lmdb": "~5.1.2",
152
- "@xyo-network/xl1-driver-mongodb": "~5.1.2",
153
- "@xyo-network/xl1-sdk": "~5.1.2",
151
+ "@xyo-network/xl1-driver-lmdb": "~5.1.4",
152
+ "@xyo-network/xl1-driver-mongodb": "~5.1.4",
153
+ "@xyo-network/xl1-sdk": "~5.1.4",
154
154
  "async-mutex": "~0.5.0",
155
155
  "eslint": "~10.8.1",
156
156
  "eslint-import-resolver-typescript": "~4.4.5",