@xyo-network/xl1-cli-lib 1.16.1 → 1.16.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.
Files changed (20) hide show
  1. package/dist/node/index.mjs +2 -2
  2. package/dist/node/index.mjs.map +1 -1
  3. package/dist/node/orchestration/actor/implementation/ProducerActor.d.ts +1 -5
  4. package/dist/node/orchestration/actor/implementation/ProducerActor.d.ts.map +1 -1
  5. package/dist/node/orchestration/actor/implementation/ValidatorActor.d.ts +1 -5
  6. package/dist/node/orchestration/actor/implementation/ValidatorActor.d.ts.map +1 -1
  7. package/dist/node/orchestration/repository/lib/repositoryFromArchivist.d.ts +2 -5
  8. package/dist/node/orchestration/repository/lib/repositoryFromArchivist.d.ts.map +1 -1
  9. package/dist/node/orchestration/services/implementation/head/createForkedHead/config/getBridgeDestinationDetails.d.ts +5 -15
  10. package/dist/node/orchestration/services/implementation/head/createForkedHead/config/getBridgeDestinationDetails.d.ts.map +1 -1
  11. package/dist/node/orchestration/services/implementation/head/createForkedHead/config/getBridgeSourceDetails.d.ts +2 -6
  12. package/dist/node/orchestration/services/implementation/head/createForkedHead/config/getBridgeSourceDetails.d.ts.map +1 -1
  13. package/dist/node/orchestration/services/implementation/time.d.ts +2 -2
  14. package/dist/node/orchestration/services/implementation/time.d.ts.map +1 -1
  15. package/dist/node/xl1.mjs +2 -2
  16. package/dist/node/xl1.mjs.map +1 -1
  17. package/package.json +21 -21
  18. package/src/commands/mempool/runMempool.ts +1 -1
  19. package/src/orchestration/actor/implementation/ProducerActor.ts +0 -1
  20. package/src/orchestration/services/implementation/time.ts +3 -3
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/start.ts","../../src/runCLI.ts","../../src/commands/api/runApi.ts","../../src/commands/bridge/runBridge.ts","../../src/commands/mempool/runMempool.ts","../../src/orchestration/actor/implementation/BalanceActor.ts","../../src/orchestration/actor/model/Actor.ts","../../src/orchestration/actor/model/Orchestrator.ts","../../src/orchestration/actor/implementation/ChainHeadUpdateActor.ts","../../src/orchestration/actor/implementation/ProducerActor.ts","../../src/orchestration/health/initHealthEndpoints.ts","../../src/orchestration/initServices.ts","../../src/orchestration/archivists/ChainFinalized/archivist.ts","../../src/orchestration/archivists/ChainFinalized/local.ts","../../src/orchestration/archivists/lib/localPersistentArchivist.ts","../../src/orchestration/archivists/ChainFinalized/remote.ts","../../src/orchestration/archivists/ChainSubmissions/archivist.ts","../../src/orchestration/archivists/ChainSubmissions/remote.ts","../../src/orchestration/archivists/PendingTransactions/archivist.ts","../../src/orchestration/archivists/PendingTransactions/local.ts","../../src/orchestration/archivists/PendingTransactions/remote.ts","../../src/orchestration/archivists/RejectedTransactions/archivist.ts","../../src/orchestration/archivists/RejectedTransactions/local.ts","../../src/orchestration/archivists/StakeIntentState/archivist.ts","../../src/orchestration/archivists/StakeIntentState/local.ts","../../src/orchestration/map/BalanceSummary/initBalanceSummaryMap.ts","../../src/orchestration/map/BalanceSummary/initLocalBalanceSummaryMap.ts","../../src/orchestration/map/BalanceSummary/initTransferSummaryMap.ts","../../src/orchestration/map/BalanceSummary/initLocalTransferSummaryMap.ts","../../src/orchestration/services/implementation/account.ts","../../src/orchestration/services/implementation/balance.ts","../../src/orchestration/services/implementation/chain/index.ts","../../src/orchestration/services/implementation/chain/evm.ts","../../src/orchestration/services/implementation/evm/initEvmProvider.ts","../../src/orchestration/services/implementation/evm/initInfuraProvider.ts","../../src/orchestration/services/implementation/evm/initChainId.ts","../../src/orchestration/services/implementation/evm/initJsonRpcProvider.ts","../../src/orchestration/services/implementation/head/head.ts","../../src/orchestration/services/implementation/head/createBootstrapHead.ts","../../src/orchestration/services/implementation/head/createForkedHead/getBridgeDestinationObservation.ts","../../src/orchestration/services/implementation/head/createForkedHead/config/getBridgeDestinationDetails.ts","../../src/orchestration/services/implementation/head/createForkedHead/config/getForkDetails.ts","../../src/orchestration/services/implementation/head/createForkedHead/config/getBridgeSourceDetails.ts","../../src/orchestration/services/implementation/head/createForkedHead/getBridgeIntent.ts","../../src/orchestration/services/implementation/head/createForkedHead/getBridgeSourceObservation.ts","../../src/orchestration/services/implementation/head/createForkedHead/getFirstBlockForNewChain.ts","../../src/orchestration/services/implementation/head/createForkedHead/createForkedHead.ts","../../src/orchestration/services/implementation/head/getForkFromBlock.ts","../../src/orchestration/services/implementation/head/submitNewChain.ts","../../src/orchestration/services/implementation/iterator.ts","../../src/orchestration/services/implementation/pendingTransactions.ts","../../src/orchestration/services/implementation/producer.ts","../../src/orchestration/services/implementation/reward.ts","../../src/orchestration/services/implementation/time.ts","../../src/orchestration/services/implementation/transfer.ts","../../src/orchestration/status/ServiceStatus.ts","../../src/orchestration/status/RuntimeStatusMonitor.ts","../../src/commands/producer/runProducer.ts","../../src/commands/rewardRedemption/runRewardRedemptionApi.ts","../../src/images.ts","../../src/initLogger.ts","../../src/optionsFromGlobalZodRegistry.ts","../../src/tryParseConfig.ts","../../src/waitForHostPort.ts","../../src/xl1.ts"],"sourcesContent":["import { config } from 'dotenv'\n\nimport { runCLI } from './runCLI.ts'\n\nexport const start = async () => {\n config({ quiet: true })\n await runCLI()\n}\n","import type { Logger } from '@xylabs/logger'\nimport { deepMerge } from '@xylabs/object'\nimport { isDefined } from '@xylabs/typeof'\nimport { type Config, ConfigZod } from '@xyo-network/xl1-protocol-sdk'\nimport type { Argv } from 'yargs'\nimport yargs from 'yargs'\nimport { hideBin } from 'yargs/helpers'\nimport { ZodError } from 'zod'\n\nimport {\n runApi, runBridge, runMempool, runProducer, runRewardRedemptionApi,\n} from './commands/index.ts'\nimport { XL1LogoColorizedAscii } from './images.ts'\nimport { initLogger } from './initLogger.ts'\nimport { optionsFromGlobalZodRegistry } from './optionsFromGlobalZodRegistry.ts'\nimport { Orchestrator } from './orchestration/index.ts'\nimport { tryParseConfig } from './tryParseConfig.ts'\nimport { waitForHostPort } from './waitForHostPort.ts'\n\n/** Version string injected by Rollup at build time. */\ndeclare const __VERSION__: string\n\ninterface RunCliContext {\n logger: Logger\n orchestrator: Orchestrator\n}\n\n/**\n * The configuration that will be used throughout the CLI.\n * This is materialized after parsing the command-line arguments,\n * environment variables, and defaults.\n */\nlet configuration: Config\n\nconst version = isDefined(__VERSION__) ? __VERSION__ : 'unknown'\n\nconst getContextFromConfig = (configuration: Config): RunCliContext => {\n const logger = initLogger(configuration)\n const orchestrator = new Orchestrator(logger)\n // Handle cancellation (Ctrl+C)\n process.on('SIGINT', () => {\n void (async () => {\n try {\n logger.log('\\nSIGINT received. Attempting graceful shutdown...')\n await orchestrator?.stop()\n logger.log('Orchestrator stopped, exiting now.')\n process.exit(0)\n } catch (err) {\n logger.error('Error stopping orchestrator:', err)\n process.exit(1)\n }\n })()\n })\n return { logger, orchestrator }\n}\n\n// Main entry point\nexport async function runCLI() {\n // Parse command-line arguments using Yargs\n const y = yargs(hideBin(process.argv)) as Argv<Config>\n const argv = y\n .usage(`\nšŸš€ XL1 Node CLI (${version})\n${XL1LogoColorizedAscii}\nRun various components of the XL1 ecosystem.\n\nUsage:\n$0 <command> [options]`)\n .parserConfiguration({\n 'dot-notation': true, // foo.bar → { foo: { bar } }\n 'parse-numbers': false, // Don't auto-parse numbers to allow strings like \"0x1\"\n 'populate--': true, // Populate -- with all options so we can detected user-supplied vs defaults\n })\n .env('XL1')\n .scriptName('xl1')\n .middleware((argv) => {\n try {\n // Parse the various config sources\n const parsedConfigFile = tryParseConfig() // Config file\n const parsedConfigArgs = argv // Command-line arguments & ENV VARs\n // Deep merge with precedence\n // TODO: Would like precedence to be defaults < file < ENV < CLI Args\n // but there is currently no way to determine which are defaults vs\n // user-supplied CLI Args since we set the CLI args to the defaults\n // and receive a flattened object. We might need to manually invoke\n // the parser without the defaults to achieve this.\n const mergedConfig = deepMerge(parsedConfigArgs, parsedConfigFile)\n // Validate the merged configuration\n configuration = ConfigZod.parse(mergedConfig)\n } catch (err) {\n if (err instanceof ZodError) {\n console.error(`${err.message}`)\n }\n throw new Error('Invalid configuration')\n }\n })\n .options(optionsFromGlobalZodRegistry())\n // .commandDir('./command/commands', opts) // Not yet supported for ESM\n .wrap(y.terminalWidth())\n .command('api', 'Run a XL1 API Node', (yargs) => {\n return yargs\n .command('$0', 'Run a XL1 API Node', () => {}, () => {\n const context = getContextFromConfig(configuration)\n runApi({ ...context, config: configuration })\n })\n })\n .command('bridge', 'Run a XL1 Bridge Node', (yargs) => {\n return yargs\n .command('$0', 'Run a XL1 Bridge Node', () => {}, () => {\n const context = getContextFromConfig(configuration)\n runBridge({ ...context, config: configuration })\n })\n })\n .command('mempool', 'Run a XL1 Mempool Node', (yargs) => {\n return yargs\n .command('$0', 'Run a XL1 Mempool Node', () => {}, () => {\n const context = getContextFromConfig(configuration)\n runMempool({ ...context, config: configuration })\n })\n })\n .command('producer', 'Run a XL1 Producer Node', (yargs) => {\n return yargs\n .command('$0', 'Run a XL1 Producer Node', () => {}, async () => {\n const context = getContextFromConfig(configuration)\n await runProducer({ ...context, config: configuration })\n })\n })\n .command('reward-redemption-api', 'Run a XL1 Rewards Redemption API Node', (yargs) => {\n return yargs\n .command('$0', 'Run a XL1 Rewards Redemption API Node', () => {}, () => {\n const context = getContextFromConfig(configuration)\n runRewardRedemptionApi({ ...context, config: configuration })\n })\n })\n .command('$0', 'Run a full XL1 Node', () => {}, async () => {\n const context = getContextFromConfig(configuration)\n if (configuration.mempool.enabled) {\n // Start Mempool but do not block\n runMempool({ ...context, config: configuration })\n // Wait for Mempool to be ready\n await waitForHostPort(configuration.mempool.host, configuration.mempool.port)\n }\n // Start API but do not block\n runApi({ ...context, config: configuration })\n // Wait for API to be ready\n await waitForHostPort(configuration.api.host, configuration.api.port)\n // Start Producer and block on it\n await runProducer({ ...context, config: configuration })\n })\n .help()\n .alias('help', 'h')\n .version(version)\n .argv\n\n await argv\n}\n","import type { Logger } from '@xylabs/logger'\nimport { getServer } from '@xyo-network/chain-api'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\n\ninterface RunApiContext {\n config: Config\n logger?: Logger\n}\n\nexport function runApi(context: RunApiContext) {\n void getServer(context)\n}\n","import type { Logger } from '@xylabs/logger'\nimport { getServer } from '@xyo-network/chain-bridge'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\n\ninterface RunBridgeContext {\n config: Config\n logger?: Logger\n}\n\nexport function runBridge(context: RunBridgeContext) {\n void getServer(context)\n}\n","import type { Logger } from '@xylabs/logger'\nimport { getServer } from '@xyo-network/chain-head-reducer'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\n\ninterface RunMempoolContext {\n config: Config\n logger?: Logger\n}\n\nexport function runMempool(context: RunMempoolContext) {\n void getServer(context)\n}\n","import { assertEx } from '@xylabs/assert'\nimport type { Promisable } from '@xylabs/promise'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport type { ChainServiceCollectionV2, Config } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nimport type { ActorParams } from '../model/index.ts'\nimport { Actor } from '../model/index.ts'\n\nexport type BalanceActorParams = ActorParams<\n Pick<ChainServiceCollectionV2, 'balance' | 'chainIterator'>\n & { config: Config }>\n\nexport class BalanceActor extends Actor<BalanceActorParams> {\n protected _updateMutex = new Mutex()\n\n protected constructor(params: BalanceActorParams) {\n super('BalanceActor', 'Balance', params)\n }\n\n protected get balanceService() {\n return assertEx(this.params.balance, () => 'balanceService not set')\n }\n\n protected get chainIterator() {\n return assertEx(this.params.chainIterator, () => 'chainIterator not set')\n }\n\n static create(params: BalanceActorParams): Promisable<BalanceActor> {\n return new BalanceActor(params)\n }\n\n override async start(): Promise<void> {\n await super.start()\n this.chainIterator.on('headUpdate', async () => {\n await this.updateBalance()\n })\n this.registerTimer('BalanceTimer', async () => {\n await this.updateBalance()\n }, 1000, 10_000/* 1000 */)\n }\n\n protected async updateBalance(): Promise<void> {\n if (this._updateMutex.isLocked()) return\n await this._updateMutex.runExclusive(async () => {\n const head = await PayloadBuilder.hash(await this.chainIterator.head())\n await this.balanceService.balances(head, [])\n })\n }\n}\n","import type { TracerProvider } from '@opentelemetry/api'\nimport { Base, type BaseParams } from '@xylabs/base'\nimport { delay } from '@xylabs/delay'\nimport { IdLogger } from '@xylabs/logger'\nimport type { EmptyObject } from '@xylabs/object'\nimport { span, spanRootAsync } from '@xylabs/telemetry'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport { Semaphore } from 'async-mutex'\n\nexport interface IActor {\n start(): Promise<void>\n stop(): Promise<void>\n}\n\nexport type ActorParams<T extends EmptyObject | void = void> = BaseParams<{\n config: Config\n name: string\n traceProvider?: TracerProvider\n} & (T extends void ? EmptyObject : T)>\n\nexport class Actor<TParams extends ActorParams = ActorParams> extends Base<TParams> implements IActor {\n protected readonly _intervals: Map<string, ReturnType<typeof setInterval>> = new Map()\n protected readonly _semaphores: Map<string, Semaphore> = new Map()\n protected readonly _timeouts: Map<string, ReturnType<typeof setTimeout>> = new Map()\n private _active = false\n private readonly _displayName: string\n private readonly _id: string\n\n constructor(id: string, displayName: string = 'Actor', params: TParams) {\n const logger = params.logger ?? new IdLogger(Base.defaultLogger ?? console, () => `[${displayName} (${id})] `)\n super({ ...params, logger })\n this._displayName = displayName\n this._id = id\n }\n\n get displayName() {\n return this._displayName\n }\n\n get id() {\n return this._id\n }\n\n get name() {\n return this.params.name\n }\n\n protected get logPrefix() {\n return `[${this.displayName} (${this.id})] `\n }\n\n /**\n * The timer runs until the actor is deactivated (or you manually stop it).\n */\n registerTimer(timerName: string, callback: () => Promise<void>, dueTimeMs: number, periodMs: number) {\n if (!this._active) {\n this.logger?.warn(\n `Cannot register timer '${timerName}' because actor is not active.`,\n )\n return\n }\n\n let running = false\n\n this._semaphores.set(timerName, new Semaphore(1))\n\n const timeoutId = setTimeout(() => {\n const intervalId = setInterval(() => {\n const semaphore = this._semaphores.get(timerName)\n if (!this._active || !this._intervals.has(timerName) || !semaphore || running) return\n if (semaphore.isLocked()) {\n this.logger?.warn(\n `Skipping timer '${this.name}:${timerName}' execution because previous execution is still running.`,\n )\n return\n }\n semaphore.acquire().then(([, release]) => {\n const startTime = Date.now()\n running = true\n callback()\n .then(() => {\n const duration = Date.now() - startTime\n if (duration > periodMs) {\n this.logger?.warn(\n `Timer '${this.name}:${timerName}' execution took longer (${duration}ms) than the period (${periodMs}ms).`,\n )\n } else if (duration > 5000) {\n this.logger?.warn(\n `Timer '${this.name}:${timerName}' execution took longer (${duration}ms) than 5000ms.`,\n )\n }\n })\n .catch((error) => {\n this.logger?.error(`Error in timer '${this.name}:${timerName}': ${error}`)\n })\n .finally(() => {\n release()\n running = false\n })\n }).catch((error) => {\n this.logger?.error(`Error acquiring semaphore for timer '${this.name}:${timerName}': ${error}`)\n })\n }, periodMs)\n\n // store interval so we can clear it on stop()\n this._intervals.set(timerName, intervalId)\n }, dueTimeMs)\n\n // store timeout so we can clear it on stop() if interval hasn't started yet\n this._timeouts.set(timerName, timeoutId)\n\n this.logger?.log(\n `Timer '${this.name}:${timerName}' registered: first call after ${dueTimeMs}ms, recurring every ${periodMs}ms.`,\n )\n }\n\n span<T>(name: string, fn: () => T): T {\n return span(`${this.name}:${name}`, fn, this.tracer)\n }\n\n async spanAsync<T>(name: string, fn: () => Promise<T>): Promise<T> {\n return await spanRootAsync(`${this.name}:${name}`, fn, this.tracer)\n }\n\n /**\n * Called by the Orchestrator when the actor is activated.\n */\n async start() {\n await Promise.resolve()\n this._active = true\n this.logger?.log('Started.')\n }\n\n /**\n * Called by the Orchestrator when the actor is deactivated.\n * Stop all running timers.\n */\n async stop() {\n await Promise.resolve()\n this._active = false\n this.logger?.log('Stopping all timers...')\n\n // wait for all semaphores to be free and acquire them to prevent new tasks from starting\n await Promise.all(\n [...this._semaphores.values()].map(async (semaphore) => {\n // Wait for any running tasks to complete\n while (semaphore.isLocked()) {\n this.logger?.log('Waiting for running timer task to complete...')\n await delay(500)\n }\n await semaphore.acquire()\n }),\n )\n\n this._semaphores.clear()\n\n for (const [, timeoutRef] of this._timeouts.entries()) {\n clearTimeout(timeoutRef)\n }\n this._timeouts.clear()\n\n for (const [, intervalRef] of this._intervals.entries()) {\n clearInterval(intervalRef)\n }\n this._intervals.clear()\n\n this.logger?.log('Stopped.')\n }\n}\n","import type { Logger } from '@xylabs/logger'\n\nimport type { IActor } from './Actor.ts'\n\nexport interface IOrchestrator {\n start(): Promise<void>\n stop(): Promise<void>\n}\n\nexport class Orchestrator implements IOrchestrator {\n protected actors: IActor[] = []\n protected keepAliveHandle: NodeJS.Timeout | null = null\n protected readonly logger?: Logger\n protected running = false\n\n constructor(logger?: Logger) {\n this.logger = logger\n }\n\n /**\n * Registers an actor.\n * (We won't activate the actor until `start()` is called.)\n */\n async registerActor(actor: IActor) {\n if (this.running) {\n // If the orchestrator is already running, activate the actor immediately\n await actor.start()\n }\n this.actors.push(actor)\n }\n\n /**\n * Starts the orchestrator: activates all actors.\n */\n async start() {\n await Promise.resolve()\n if (this.running) {\n this.logger?.warn('[Orchestrator] Already started.')\n return\n }\n\n this.logger?.log('[Orchestrator] Starting...')\n this.running = true\n for (const actor of this.actors) {\n await actor.start()\n }\n // This interval will fire every 24.8 days (2^31 - 1 ms), effectively never finishing\n this.keepAliveHandle = setInterval(() => {\n // No-op\n }, 2_147_483_647)\n }\n\n /**\n * Stops the orchestrator: deactivates all actors.\n */\n async stop() {\n await Promise.resolve()\n if (!this.running) {\n this.logger?.log('[Orchestrator] Already stopped.')\n return\n }\n\n this.logger?.log('[Orchestrator] Stopping...')\n for (const actor of this.actors) {\n await actor.stop()\n }\n this.running = false\n if (this.keepAliveHandle) clearInterval(this.keepAliveHandle)\n this.logger?.log('[Orchestrator] Stopped...')\n }\n}\n","import { filterAs } from '@xylabs/array'\nimport { assertEx } from '@xylabs/assert'\nimport { toHex } from '@xylabs/hex'\nimport type { Promisable } from '@xylabs/promise'\nimport { findMostRecentBlock, sortBlocks } from '@xyo-network/chain-sdk'\nimport type { Payload } from '@xyo-network/payload-model'\nimport type { BlockBoundWitness } from '@xyo-network/xl1-protocol'\nimport { asBlockBoundWitness } from '@xyo-network/xl1-protocol'\nimport type { ChainServiceCollectionV2, Config } from '@xyo-network/xl1-protocol-sdk'\n\nimport type { ActorParams } from '../model/index.ts'\nimport { Actor } from '../model/index.ts'\n\nexport type ChainHeadUpdateActorParams = ActorParams<Pick<ChainServiceCollectionV2, 'chainIterator' | 'chainArchivist'> & { config: Config }>\n\nexport class ChainHeadUpdateActor extends Actor<ChainHeadUpdateActorParams> {\n protected constructor(params: ChainHeadUpdateActorParams) {\n super('ChainHeadUpdate', 'ChainHeadUpdate', params)\n }\n\n protected get chainFinalizedArchivist() {\n return assertEx(this.params.chainArchivist, () => 'ChainArchivist not set')\n }\n\n protected get chainIterator() {\n return assertEx(this.params.chainIterator, () => 'chainIterator not set')\n }\n\n static create(params: ChainHeadUpdateActorParams): Promisable<ChainHeadUpdateActor> {\n return new ChainHeadUpdateActor(params)\n }\n\n override async start(): Promise<void> {\n await super.start()\n // Register event handler on all insert event to check for new head\n this.chainFinalizedArchivist.on('inserted', async (data: { payloads: Payload[] }) => {\n await this.checkInsertedForNewHead(data)\n })\n // Poll in case we missed an event\n this.registerTimer('ChainHeadUpdateTimer', async () => await this.pollForNewHead(), 0, 2500/* 250 */)\n }\n\n private async checkInsertedForNewHead(data: { payloads: Payload[] }) {\n const candidateBlock = sortBlocks(filterAs(data.payloads, asBlockBoundWitness)).at(-1)\n await this.updateHeadIfNewer(candidateBlock)\n }\n\n private async pollForNewHead() {\n const candidateBlock = await findMostRecentBlock(this.chainFinalizedArchivist)\n await this.updateHeadIfNewer(candidateBlock)\n }\n\n private async updateHeadIfNewer(candidateBlock?: BlockBoundWitness) {\n if (!candidateBlock) return\n const currentHead = await this.chainIterator.head()\n const candidateBlockNumber = candidateBlock.block\n const candidateBlockNumberDisplay = `0x${toHex(candidateBlockNumber)}`\n const currentBlockNumber = currentHead?.block ?? -1\n if (candidateBlockNumber > currentBlockNumber) {\n this.logger?.log('Found more recent head:', candidateBlockNumber, candidateBlockNumberDisplay)\n await this.chainIterator.updateHead(candidateBlock)\n this.logger?.log('Updated head:', candidateBlockNumber, candidateBlockNumberDisplay)\n }\n }\n}\n","import { assertEx } from '@xylabs/assert'\nimport type { BaseParams } from '@xylabs/base'\nimport { toHex } from '@xylabs/hex'\nimport type { Promisable } from '@xylabs/promise'\nimport { isDefined, isUndefined } from '@xylabs/typeof'\nimport { BaseBlockProducerService, createDeclarationIntent } from '@xyo-network/chain-sdk'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport type { PayloadBundle } from '@xyo-network/payload-model'\nimport { PayloadBundleSchema } from '@xyo-network/payload-model'\nimport type { ChainStakeIntent, HydratedBlock } from '@xyo-network/xl1-protocol'\nimport type { ChainServiceCollectionV2, Config } from '@xyo-network/xl1-protocol-sdk'\nimport {\n buildTransaction, flattenHydratedBlock, flattenHydratedTransaction,\n} from '@xyo-network/xl1-protocol-sdk'\n\nimport type { ActorParams } from '../model/index.ts'\nimport { Actor } from '../model/index.ts'\n\nexport type ProducerActorParams = ActorParams<\n Pick<ChainServiceCollectionV2,\n 'account'\n | 'balance'\n | 'chainIterator'\n | 'chainStakeViewer'\n | 'chainSubmissionsArchivistWrite'\n | 'pendingBundledTransactionsArchivistWrite'\n | 'producer'\n | 'stakeIntent'\n > & {\n config: Config\n }>\n\nconst SHOULD_REGISTER_REDECLARATION_INTENT_TIMER = true\nconst TEN_MINUTES = 10 * 60 * 1000 // 10 minutes in milliseconds\n\nexport class ProducerActor extends Actor<ProducerActorParams> {\n protected _lastProducedBlock: HydratedBlock | undefined\n protected _lastRedeclarationIntent: ChainStakeIntent | undefined\n\n protected constructor(params: ProducerActorParams) {\n super(params.producer.address, 'Producer', params)\n }\n\n protected get account() {\n return assertEx(this.params.account, () => 'account not set')\n }\n\n protected get balanceService() {\n return assertEx(this.params.balance, () => 'balanceService not set')\n }\n\n protected get chainIterator() {\n return assertEx(this.params.chainIterator, () => 'chainIterator not set')\n }\n\n protected get chainStakeViewer() {\n return assertEx(this.params.chainStakeViewer, () => 'chainStakeViewer not set')\n }\n\n protected get chainSubmissionsArchivistWrite() {\n return assertEx(this.params.chainSubmissionsArchivistWrite, () => 'chainSubmissionsArchivistWrite not set')\n }\n\n protected get pendingBundledTransactionsArchivistWrite() {\n return assertEx(this.params.pendingBundledTransactionsArchivistWrite, () => 'pendingBundledTransactionsArchivistWrite not set')\n }\n\n protected get producer() {\n return assertEx(this.params.producer, () => 'producer not set')\n }\n\n protected get stakeIntentService() {\n return assertEx(this.params.stakeIntent, () => 'stakeIntentService not set')\n }\n\n static create(params: ProducerActorParams): Promisable<ProducerActor> {\n return new ProducerActor(params)\n }\n\n override async start(): Promise<void> {\n await super.start()\n // Register a timer to check if we should produce a block\n this.registerTimer('BlockProductionTimer', async () => {\n await this.produceBlock()\n }, 100, 1500/* 500 */)\n\n if (SHOULD_REGISTER_REDECLARATION_INTENT_TIMER) {\n // Register a timer to check if we should redeclare the producer\n this.registerTimer('ProducerRedeclarationTimer', async () => {\n await this.redeclareIntent()\n }, TEN_MINUTES, TEN_MINUTES)\n }\n }\n\n protected async calculateBlocksUntilProducerDeclarationExpiration(currentBlock: number): Promise<number> {\n // Decide if we need to redeclare intent\n const ranges = await this.stakeIntentService.getDeclaredCandidateRanges(this.account.address, 'producer')\n // TODO: This doesn't handle the case where the producer had declared a range for the future\n // but we're in a range that's not the future\n // Sort in ascending order based on ending range to get range with highest ending block\n const lastRange = ranges.toSorted((a, b) => a[1] > b[1] ? 1 : -1).at(-1)\n\n // Use the most recent range's end block as the current declaration end OR\n const [, currentDeclarationEnd] = lastRange\n // If we have no ranges, we need to declare intent, so use the current block\n ?? [undefined, currentBlock]\n\n // Calculate the time until the producer's declaration expires\n const timeToProducerExpiration = currentDeclarationEnd - currentBlock\n return timeToProducerExpiration\n }\n\n protected async produceBlock(): Promise<void> {\n await this.spanAsync('produceBlock', async () => {\n // Get the updated head\n const headStart = Date.now()\n const head = await this.chainIterator.head()\n const headDuration = Date.now() - headStart\n if (headDuration > 500) {\n this.logger?.warn(`[Slow] Fetched head in ${headDuration}ms: 0x${toHex(head._hash)}`)\n }\n // Check if we've already produced the next block for this head\n const headHash = head._hash\n // If our last produced block was the next block for the current head, we do not\n // need to produce another. This prevents duplicate blocks from being produced\n if (this._lastProducedBlock && this._lastProducedBlock[0].previous === headHash) {\n this.logger?.log('Block already produced:', `0x${toHex(this._lastProducedBlock[0].block)}`)\n } else {\n // Produce the next block\n const nextStart = Date.now()\n const nextBlock = await this.producer.next(head)\n const nextDuration = Date.now() - nextStart\n if (nextDuration > 1000) {\n this.logger?.warn(`[Slow] Generated next block in ${nextDuration}ms, block: ${nextBlock?.[0]._hash}`)\n }\n // If it was produced\n if (nextBlock) {\n const displayBlockNumber = `0x${toHex(nextBlock[0].block)}`\n this.logger?.log('Produced block:', displayBlockNumber)\n // Insert the block into the chain\n await this.chainSubmissionsArchivistWrite.insert(flattenHydratedBlock(nextBlock))\n this.logger?.log('Published block:', displayBlockNumber)\n // Record that we have produced a block so we do not produce it again\n this._lastProducedBlock = nextBlock\n }\n }\n })\n }\n\n protected async redeclareIntent(): Promise<void> {\n await this.spanAsync('redeclareIntent', async () => {\n // Decide if we should redeclare intent\n if (this.params.config.producer.disableIntentRedeclaration) return\n\n // Get the current block\n const head = await this.chainIterator.head()\n if (isUndefined(head)) return\n const currentBlock = head.block\n\n // Calculate the time until the producer's declaration expires\n const blocksUntilExpiration = await this.calculateBlocksUntilProducerDeclarationExpiration(currentBlock)\n\n // Allow the producer time to redeclare itself via block production\n // (for free) before submitting a redeclaration intent transaction.\n if (blocksUntilExpiration > BaseBlockProducerService.RedeclarationWindow * 0.1) {\n // Clear any previous redeclaration intent\n this._lastRedeclarationIntent = undefined\n // No need to redeclare yet\n return\n }\n\n // If we already have a valid redeclaration intent, do not create another\n // unless it has expired.\n if (this._lastRedeclarationIntent) {\n // Check if the last redeclaration intent is still valid\n if (this._lastRedeclarationIntent.exp > currentBlock) return\n // If it has expired, clear the last redeclaration intent\n this._lastRedeclarationIntent = undefined\n }\n\n // Check if we have a valid balance before declaring intent\n if (!await this.validateCurrentBalance()) {\n this.logger?.error(\n `Add balance to address ${this.account.address} for the producer to declare it's intent.`,\n )\n return\n }\n\n // Check if we have a valid stake before declaring intent\n if (!(await this.validateCurrentStake())) {\n this.logger?.error(\n `Add stake to contract address ${this.params.config.chain.id}`\n + ' for the producer to declare it\\'s intent.',\n )\n return\n }\n\n // Create a redeclaration intent\n this.logger?.log('Creating redeclaration intent for producer:', this.account.address)\n const redeclarationIntent = createDeclarationIntent(\n this.account.address,\n 'producer',\n currentBlock,\n currentBlock + BaseBlockProducerService.RedeclarationDuration,\n )\n\n // Submit the redeclaration intent\n await this.submitRedeclarationIntent(currentBlock, redeclarationIntent)\n\n // On successful submission, save the redeclaration intent\n this._lastRedeclarationIntent = redeclarationIntent\n })\n }\n\n protected async submitRedeclarationIntent(currentBlock: number, redeclarationIntent: ChainStakeIntent): Promise<void> {\n this.logger?.log('Submitting redeclaration intent for producer:', this.account.address)\n // Create a transaction to submit the redeclaration intent\n const tx = await buildTransaction(\n this.chainIterator.chainId,\n [redeclarationIntent],\n [],\n this.account,\n currentBlock,\n currentBlock + 1000,\n )\n const payloads = flattenHydratedTransaction(tx)\n const root = tx[0]._hash\n const payloadBundle = new PayloadBuilder<PayloadBundle>({ schema: PayloadBundleSchema }).fields({ payloads, root }).build()\n\n // Submit the redeclaration intent\n await this.pendingBundledTransactionsArchivistWrite.insert([payloadBundle])\n\n this.logger?.log('Submitted redeclaration intent for producer:', this.account.address)\n }\n\n protected async validateCurrentBalance(): Promise<boolean> {\n // Check if we have a valid balance before declaring intent\n const head = this._lastProducedBlock?.[0]._hash\n if (isDefined(head)) {\n const balances = await this.balanceService.balances(head, [this.account.address])\n const currentBalance = balances[this.account.address] ?? 0n\n if (currentBalance <= 0n) {\n this.logger?.error(`Producer ${this.account.address} has no balance.`)\n return false\n }\n return true\n }\n return true\n }\n\n protected async validateCurrentStake(): Promise<boolean> {\n // Use StakeIntentService to get the required minimum stake\n const requiredMinimumStake = this.stakeIntentService.getRequiredMinimumStakeForIntent('producer')\n // Check if we have a valid stake before declaring intent\n const currentStake = await this.chainStakeViewer.activeByStaked(this.account.address)\n if (currentStake < requiredMinimumStake) {\n this.logger?.error(`Producer ${this.account.address} has insufficient stake.`)\n return false\n }\n return true\n }\n}\n","import type {\n IncomingMessage, Server, ServerResponse,\n} from 'node:http'\nimport http from 'node:http'\n\nimport type { CreatableStatus } from '@xylabs/creatable'\nimport type { Logger } from '@xylabs/logger'\nimport { isDefined } from '@xylabs/typeof'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\n\nimport type { RuntimeStatusMonitor } from '../status/index.ts'\n\nconst sendStatus = (res: ServerResponse, status: CreatableStatus, errorCode: number) => {\n const statusCode = status === 'started' ? 200 : errorCode\n res.writeHead(statusCode, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ status }))\n}\n\nconst notFound = (res: ServerResponse) => {\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ status: 'not found' }))\n}\n\n/**\n * Starts an HTTP server with Kubernetes health endpoints:\n * - /healthz\n * - /livez\n * - /readyz\n * @param port The port to listen on (default: 8080)\n */\nconst createHealthServer = (port: number, statusMonitor: RuntimeStatusMonitor, logger: Logger) => {\n const server = http.createServer((req: IncomingMessage, res: ServerResponse) => {\n const url = req.url ?? ''\n\n const status = statusMonitor.getGlobalStatus()\n\n switch (url) {\n case '/healthz': {\n sendStatus(res, status, 500)\n break\n }\n case '/livez': {\n sendStatus(res, status, 503)\n break\n }\n case '/readyz': {\n sendStatus(res, status, 503)\n break\n }\n default: {\n notFound(res)\n }\n }\n })\n\n server.listen(port, () => {\n logger.log(`Health server running on http://localhost:${port}`)\n logger.log(' - /healthz')\n logger.log(' - /livez')\n logger.log(' - /readyz')\n })\n return server\n}\n\nexport const initHealthEndpoints: Initializable<{ config: Config; logger: Logger; statusReporter: RuntimeStatusMonitor }, Server | undefined> = (params) => {\n const {\n config, logger, statusReporter,\n } = params\n const { healthCheckPort } = config.producer\n return isDefined(healthCheckPort) ? createHealthServer(healthCheckPort, statusReporter, logger) : undefined\n}\n","/* eslint-disable max-statements */\nimport { assertEx } from '@xylabs/assert'\nimport type { CreatableName } from '@xylabs/creatable'\nimport type { Address } from '@xylabs/hex'\nimport { asAddress } from '@xylabs/hex'\nimport type { Logger } from '@xylabs/logger'\nimport { isDefined } from '@xylabs/typeof'\nimport type { BaseBlockProducerServiceParams, XyoValidatorParams } from '@xyo-network/chain-sdk'\nimport {\n initTelemetry, startupSpanAsync, StepSizes, validateHydratedBlockState,\n} from '@xyo-network/chain-sdk'\nimport type { Payload, WithStorageMeta } from '@xyo-network/payload-model'\nimport {\n type ChainServiceCollectionV2, type Config, readPayloadMapFromStore,\n} from '@xyo-network/xl1-protocol-sdk'\nimport {\n CompletedStepRewardAddressValidatorFactory, DerivedReceiveAddressValidatorFactory, SelfSignerValidator, TransactionTransfersValidatorFactory,\n} from '@xyo-network/xl1-validation'\nimport { Semaphore } from 'async-mutex'\n\nimport {\n initChainFinalizedArchivist, initChainSubmissionsArchivist, initPendingBundledTransactionsArchivist, initRejectedTransactionsArchivist,\n initStakeIntentStateArchivist,\n} from './archivists/index.ts'\nimport type { ChainInitializableParams } from './ChainInitializableParams.ts'\nimport { initHealthEndpoints } from './health/index.ts'\nimport { initBalanceSummaryMap, initTransferSummaryMap } from './map/index.ts'\nimport {\n initAccount, initBalanceService, initBlockProducer,\n initBlockRewardService, initChainIterator, initChainService, initElectionService, initHead,\n initPendingTransactions, initStakeIntentService,\n initTimeService, initTransferService,\n} from './services/index.ts'\nimport { RuntimeStatusMonitor } from './status/index.ts'\n\ninterface Startable {\n start: () => Promise<boolean>\n}\n\nconst isStartable = (value: unknown): value is Startable => {\n return isDefined((value as Startable).start) && typeof (value as Startable).start === 'function'\n}\n\ninterface InitServicesContext {\n config: Config\n logger: Logger\n}\n\nexport const initServices = async (context: InitServicesContext): Promise<ChainServiceCollectionV2> => {\n const { config, logger } = context\n const statusReporter = new RuntimeStatusMonitor(logger)\n statusReporter.onGlobalTransition({ to: 'started' }, () => {\n logger.log('All services started.')\n })\n statusReporter.onGlobalTransition({ to: 'error' }, () => {\n logger.error('Producer encountered an unhandled error!')\n // eslint-disable-next-line unicorn/no-process-exit\n process.exit(1)\n })\n\n await startupSpanAsync('initHealthEndpoints', () => initHealthEndpoints({ ...context, statusReporter }))\n const { otlpEndpoint } = config.telemetry?.otel ?? {}\n const telemetryConfig = {\n attributes: {\n serviceName: 'xl1-producer',\n serviceVersion: '1.0.0',\n },\n otlpEndpoint,\n metricsConfig: {\n endpoint: '/metrics',\n port: 9464,\n },\n }\n const [\n { traceProvider, meterProvider },\n account,\n ] = await Promise.all([\n startupSpanAsync('initTelemetry', () => initTelemetry(telemetryConfig)),\n startupSpanAsync('initAccount', () => initAccount(context)),\n ])\n\n const allowedRewardRedeemers: Address[] = config.validation?.allowedRewardRedeemers ?? []\n const allowedRewardEscrowAccountSigners: Address[] = config.validation?.allowedRewardEscrowAccountSigners ?? []\n\n const initParams: ChainInitializableParams = {\n config, logger, meterProvider, statusReporter, traceProvider,\n }\n\n // Archivists\n const [\n chainArchivist,\n [pendingBundledTransactionsArchivist, pendingBundledTransactionsArchivistWrite],\n rejectedTransactionsArchivist,\n chainSubmissionsArchivistWrite,\n stakeIntentStateArchivist,\n chainService,\n balanceSummaryMap,\n transferSummaryMap,\n ] = await Promise.all([\n startupSpanAsync(\n 'ChainFinalizedArchivist',\n () => initChainFinalizedArchivist(initParams),\n ),\n startupSpanAsync(\n 'PendingBundledTransactionsArchivist',\n () => initPendingBundledTransactionsArchivist(initParams),\n ),\n startupSpanAsync(\n 'RejectedTransactionsArchivist',\n () => initRejectedTransactionsArchivist(initParams),\n ),\n startupSpanAsync(\n 'ChainSubmissionsArchivist',\n () => initChainSubmissionsArchivist(initParams),\n ),\n startupSpanAsync(\n 'StakeIntentStateArchivist',\n () => initStakeIntentStateArchivist(initParams),\n ),\n startupSpanAsync(\n 'ChainService',\n () => initChainService({\n ...initParams, account, name: 'ChainService' as CreatableName,\n }),\n ),\n startupSpanAsync(\n 'BalanceSummaryMap',\n () => initBalanceSummaryMap(initParams),\n ),\n startupSpanAsync(\n 'TransferSummaryMap',\n () => initTransferSummaryMap(initParams),\n ),\n ])\n\n const chainId = chainService.chainId\n const chainMap = readPayloadMapFromStore<WithStorageMeta<Payload>>(chainArchivist)\n const chainContractViewer = chainService\n const chainStakeViewer = chainService\n const chainStaker = chainService\n const head = await startupSpanAsync('initHead', () => initHead({\n ...initParams, account, chainArchivist, chainSubmissionsArchivistWrite, chainService,\n }))\n\n const additionalPendingTransactionValidators = [TransactionTransfersValidatorFactory(\n [\n SelfSignerValidator,\n CompletedStepRewardAddressValidatorFactory(allowedRewardRedeemers),\n DerivedReceiveAddressValidatorFactory(allowedRewardEscrowAccountSigners, 'reward-escrow'),\n ],\n )]\n\n const [\n pendingTransactionsService,\n rewardService,\n chainIterator,\n ] = await Promise.all([\n startupSpanAsync('PendingTransactions', () => initPendingTransactions({\n name: 'PendingTransactionsService' as CreatableName,\n chainArchivist,\n chainId,\n pendingBundledTransactionsArchivist,\n rejectedTransactionsArchivist,\n additionalPendingTransactionValidators,\n ...initParams,\n })),\n startupSpanAsync(\n 'RewardService',\n () => initBlockRewardService({\n name: 'RewardService' as CreatableName,\n account,\n chainService,\n ...initParams,\n }),\n ),\n startupSpanAsync(\n 'ChainIterator',\n () => initChainIterator({\n name: 'ChainIterator' as CreatableName,\n chainMap,\n head,\n ...initParams,\n }),\n ),\n ])\n const [\n balanceService,\n ] = await Promise.all([\n startupSpanAsync(\n 'BalanceService',\n () => initBalanceService({\n name: 'BalanceService' as CreatableName,\n context: {\n stepSemaphores: StepSizes.map(() => new Semaphore(20)),\n store: { chainMap },\n head: async () => {\n const head = await chainIterator.head()\n return [head._hash, head.block]\n },\n chainId,\n summaryMap: balanceSummaryMap,\n },\n ...initParams,\n }),\n ),\n startupSpanAsync(\n 'TransferService',\n () => initTransferService({\n name: 'TransferService' as CreatableName,\n context: {\n stepSemaphores: StepSizes.map(() => new Semaphore(20)),\n store: { chainMap },\n head: async () => {\n const head = await chainIterator.head()\n return [head._hash, head.block]\n },\n chainId,\n summaryMap: transferSummaryMap,\n },\n ...initParams,\n }),\n ),\n ])\n\n const [stakeIntentService, time] = await Promise.all([\n startupSpanAsync(\n 'StakeIntentService',\n () => initStakeIntentService({\n name: 'StakeIntentService' as CreatableName,\n chainArchivist,\n chainIterator,\n chainStakeViewer,\n stakeIntentStateArchivist,\n ...initParams,\n }),\n ),\n startupSpanAsync(\n 'TimeService',\n () => initTimeService({\n name: 'TimeService' as CreatableName,\n chainArchivist,\n chainIterator,\n ...initParams,\n }),\n ),\n ])\n\n const electionService = await startupSpanAsync(\n 'ElectionService',\n () => initElectionService({\n name: 'ElectionService' as CreatableName,\n chainIterator,\n chainStakeViewer,\n stakeIntentService,\n ...initParams,\n }),\n )\n\n const validatorParams: XyoValidatorParams = {\n name: 'Validator' as CreatableName,\n account,\n chainId,\n pendingBundledTransactionsArchivist,\n chainArchivist,\n electionService,\n rewardService,\n stakeIntentService,\n validateHydratedBlockState,\n ...initParams,\n }\n\n const rewardAddress = isDefined(config.producer.rewardAddress)\n ? assertEx(asAddress(config.producer.rewardAddress), () => 'Invalid block reward address provided')\n : account.address\n const producerParams: BaseBlockProducerServiceParams = {\n ...validatorParams,\n name: 'Producer' as CreatableName,\n balanceService,\n chainArchivist,\n pendingBundledTransactionsArchivist,\n pendingTransactionsService,\n rejectedTransactionsArchivist,\n rewardAddress,\n time,\n ...initParams,\n }\n const producer = await startupSpanAsync('Producer', () => initBlockProducer(producerParams))\n // TODO: Add to base service collection\n const result: ChainServiceCollectionV2 = {\n account,\n balance: balanceService,\n chainArchivist,\n chainContractViewer,\n chainIterator,\n chainStaker,\n chainStakeViewer,\n chainSubmissionsArchivistWrite,\n election: electionService,\n pendingBundledTransactionsArchivistWrite,\n pendingTransactions: pendingTransactionsService,\n producer,\n reward: rewardService,\n stakeIntent: stakeIntentService,\n }\n\n logger?.log('All services created. Starting...')\n const startableServices = [balanceSummaryMap, ...Object.values(result)].filter(isStartable)\n // Start all services that have a start method and assert that they all started successfully\n assertEx(\n (await Promise.all(startableServices.map(service => service.start()))).every(Boolean),\n () => 'One or more services failed to start',\n )\n logger?.log('All services started successfully.')\n return result\n}\n","import type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { initArchivistSync, startupSpanAsync } from '@xyo-network/chain-sdk'\nimport { Mutex } from 'async-mutex'\n\nimport type { ChainInitializableParams } from '../../ChainInitializableParams.ts'\nimport { initLocalChainFinalizedArchivist } from './local.ts'\nimport { initRemoteChainFinalizedArchivist } from './remote.ts'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport async function initChainFinalizedArchivist({\n config, logger, traceProvider,\n}: ChainInitializableParams) {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n const [remote, local] = await Promise.all([\n startupSpanAsync('ChainFinalizedArchivist:initRemote', () => initRemoteChainFinalizedArchivist({ config, logger })),\n startupSpanAsync('ChainFinalizedArchivist:initLocal', () => initLocalChainFinalizedArchivist({ config, logger })),\n ])\n await startupSpanAsync(\n 'ChainFinalizedArchivist:initArchivistSync',\n () => initArchivistSync('ChainFinalizedArchivist', remote, local, 200, Number.MAX_SAFE_INTEGER, traceProvider),\n )\n singleton = local\n return singleton\n })\n}\n","import type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nimport { getLocalPersistentArchivist } from '../lib/index.ts'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport const initLocalChainFinalizedArchivist: Initializable<{ config: Config }, ArchivistInstance> = async ({ config }): Promise<ArchivistInstance> => {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n const { root } = config.storage\n singleton = await getLocalPersistentArchivist('local-finalized-chain', 'chain', 'finalized', root)\n return singleton\n })\n}\n","import { rm } from 'node:fs/promises'\nimport Path from 'node:path'\n\nimport { LmdbArchivist, LmdbArchivistConfigSchema } from '@xyo-network/archivist-lmdb'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { getStoreDirectory, type StoreKind } from '@xyo-network/chain-sdk'\n\nconst DEFAULT_STORAGE_ROOT = Path.join(process.cwd(), '.store')\n\n/**\n * Returns a local persistent archivist\n * @param name The name of the archivist\n * @param dbName The name of the database\n * @param storeName The name of the store\n * @param storageRoot The root directory for storage (default is '.store' in the current working directory)\n * @param kind The kind of the archivist\n * @returns an archivist instance\n */\nexport const getLocalPersistentArchivist = (\n name: string,\n dbName: string,\n storeName: string,\n storageRoot?: string,\n kind: StoreKind = 'lmdb',\n): Promise<ArchivistInstance> => {\n switch (kind) {\n case 'lmdb': {\n const root = storageRoot ?? DEFAULT_STORAGE_ROOT\n return LmdbArchivist.create({\n account: 'random',\n config: {\n name,\n clearStoreOnStart: false,\n dbName,\n location: getStoreDirectory(dbName, root, 'lmdb'),\n schema: LmdbArchivistConfigSchema,\n storeName,\n },\n })\n }\n }\n}\n\n/**\n * Deletes a local persistent archivist\n * @param dbName The name of the database\n * @param storageRoot The root directory for storage (default is '.store' in the current working directory)\n * @param kind The kind of the archivist\n * @returns A promise that resolves when the archivist is deleted\n */\nexport const deleteLocalPersistentArchivist = async (dbName: string, storageRoot?: string, kind: StoreKind = 'lmdb'): Promise<void> => {\n await Promise.resolve()\n console.warn(`Deleting local persistent archivist for ${dbName} of kind ${kind}.`)\n let location = ''\n switch (kind) {\n case 'lmdb': {\n const root = storageRoot ?? DEFAULT_STORAGE_ROOT\n location = getStoreDirectory(dbName, root, 'lmdb')\n break\n }\n }\n await rm(location, { recursive: true, force: true })\n}\n","import { assertEx } from '@xylabs/assert'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { initBridge, initBridgedArchivistModule } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport { type Config, getUrl } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport const initRemoteChainFinalizedArchivist: Initializable<{ config: Config }, ArchivistInstance> = async ({ config }): Promise<ArchivistInstance> => {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n const { host, port } = config.mempool.enabled ? config.mempool : config.api\n const nodeUrl = getUrl(host, port)\n const bridge = await initBridge(nodeUrl)\n singleton = await initBridgedArchivistModule({ bridge, moduleName: 'XYOChain:Chain:Finalized' })\n return assertEx(singleton, () => 'Error: RemoteChainFinalizedArchivist failed to initialize')\n })\n}\n","import { assertEx } from '@xylabs/assert'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { startupSpanAsync } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nimport { initRemoteChainSubmissionsArchivist } from './remote.ts'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport const initChainSubmissionsArchivist: Initializable<{ config: Config }, ArchivistInstance> = async (params): Promise<ArchivistInstance> => {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n const remote = await startupSpanAsync('ChainSubmissionsArchivist:initRemote', () => initRemoteChainSubmissionsArchivist(params))\n singleton = remote\n return assertEx(singleton, () => new Error('Failed to initialize ChainSubmissionsArchivist'))\n })\n}\n","import { assertEx } from '@xylabs/assert'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { initBridge, initBridgedArchivistModule } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport { type Config, getUrl } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport const initRemoteChainSubmissionsArchivist: Initializable<{ config: Config }, ArchivistInstance> = async ({ config }): Promise<ArchivistInstance> => {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n const { host, port } = config.mempool.enabled ? config.mempool : config.api\n const nodeUrl = getUrl(host, port)\n const bridge = await initBridge(nodeUrl)\n singleton = await initBridgedArchivistModule({ bridge, moduleName: 'XYOChain:Chain:Submissions' })\n return assertEx(singleton, () => new Error('Failed to initialize RemoteChainSubmissionsArchivist'))\n })\n}\n","import type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { initArchivistSync, startupSpanAsync } from '@xyo-network/chain-sdk'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nimport { initLocalPendingTransactionsArchivist } from './local.ts'\nimport { initRemotePendingTransactionsArchivist } from './remote.ts'\n\nconst mutex = new Mutex()\nlet singleton: [local: ArchivistInstance, remote: ArchivistInstance] | undefined\n\nexport const initPendingBundledTransactionsArchivist = async (params: { config: Config }): Promise<[local: ArchivistInstance, remote: ArchivistInstance]> => {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n const remote = await startupSpanAsync('PendingBundledTransactionsArchivist:initRemote', () => initRemotePendingTransactionsArchivist(params))\n const local = await startupSpanAsync('PendingBundledTransactionsArchivist:initLocal', () => initLocalPendingTransactionsArchivist(params))\n // Grab the most recent payload from the remote archivist\n const start = await remote.next({ limit: 1, order: 'desc' })\n // Write it locally so we have a starting point for syncing\n await local.insert(start)\n await startupSpanAsync(\n 'PendingBundledTransactionsArchivist:initArchivistSync',\n () => initArchivistSync('PendingBundledTransactionsArchivist', remote, local),\n )\n singleton = [local, remote]\n return singleton\n })\n}\n","import { MemoryArchivist, MemoryArchivistConfigSchema } from '@xyo-network/archivist-memory'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport const initLocalPendingTransactionsArchivist: Initializable<{ config: Config }, ArchivistInstance> = async (): Promise<ArchivistInstance> => {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n singleton = await MemoryArchivist.create({\n account: 'random',\n config: {\n schema: MemoryArchivistConfigSchema, max: 1000, name: 'localPendingTransactions',\n },\n })\n return singleton\n })\n}\n","import { assertEx } from '@xylabs/assert'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { initBridge, initBridgedArchivistModule } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport { type Config, getUrl } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport const initRemotePendingTransactionsArchivist: Initializable<{ config: Config }, ArchivistInstance> = async ({ config }): Promise<ArchivistInstance> => {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n const { host, port } = config.mempool.enabled ? config.mempool : config.api\n const nodeUrl = getUrl(host, port)\n const bridge = await initBridge(nodeUrl)\n singleton = await initBridgedArchivistModule({ bridge, moduleName: 'XYOChain:Pending:PendingTransactions' })\n return assertEx(singleton, () => 'Error: RemotePendingBundledTransactionsArchivist is undefined')\n })\n}\n","import type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { startupSpanAsync } from '@xyo-network/chain-sdk'\nimport type { InitializableParams } from '@xyo-network/xl1-protocol'\nimport { Mutex } from 'async-mutex'\n\nimport { initLocalRejectedTransactionsArchivist } from './local.ts'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport async function initRejectedTransactionsArchivist(params: InitializableParams) {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n const local = await startupSpanAsync('RejectedTransactionsArchivist:initLocal', () => initLocalRejectedTransactionsArchivist(params))\n singleton = local\n return singleton\n })\n}\n","import { MemoryArchivist, MemoryArchivistConfigSchema } from '@xyo-network/archivist-memory'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport { Mutex } from 'async-mutex'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport const initLocalRejectedTransactionsArchivist: Initializable<{}, ArchivistInstance> = async (): Promise<ArchivistInstance> => {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n singleton = await MemoryArchivist.create({\n account: 'random',\n config: {\n schema: MemoryArchivistConfigSchema, max: 1000, name: 'localRejectedTransactions',\n },\n })\n return singleton\n })\n}\n","import { assertEx } from '@xylabs/assert'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { startupSpanAsync } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport { Mutex } from 'async-mutex'\n\nimport type { ChainInitializableParams } from '../../ChainInitializableParams.ts'\nimport { initLocalStakeIntentStateArchivist } from './local.ts'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport const initStakeIntentStateArchivist: Initializable<ChainInitializableParams, ArchivistInstance>\n = async (params: ChainInitializableParams): Promise<ArchivistInstance> => {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n const local = await startupSpanAsync('StakeIntentStateArchivist:initLocal', () => initLocalStakeIntentStateArchivist(params))\n singleton = local\n return assertEx(singleton, () => 'Error: StakeIntentStateArchivist is undefined')\n })\n }\n","import { assertEx } from '@xylabs/assert'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nimport { getLocalPersistentArchivist } from '../lib/index.ts'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport const initLocalStakeIntentStateArchivist: Initializable<{ config: Config }, ArchivistInstance> = async ({ config }): Promise<ArchivistInstance> => {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n const { root } = config.storage\n singleton = await getLocalPersistentArchivist('local-stake-intent-state', 'stakeIntent', 'state', root)\n return assertEx(singleton, () => new Error('Failed to initialize stake intent state archivist'))\n })\n}\n","import { isDefined } from '@xylabs/typeof'\nimport { startupSpanAsync } from '@xyo-network/chain-sdk'\nimport type { WithStorageMeta } from '@xyo-network/payload-model'\nimport type { BalancesStepSummary, MapType } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nimport type { ChainInitializableParams } from '../../ChainInitializableParams.ts'\nimport { initLocalBalanceSummaryMap } from './initLocalBalanceSummaryMap.ts'\n\nconst mutex = new Mutex()\nlet singleton: MapType<string, WithStorageMeta<BalancesStepSummary>> | undefined\n\nexport async function initBalanceSummaryMap(params: ChainInitializableParams): Promise<MapType<string, WithStorageMeta<BalancesStepSummary>>> {\n return await mutex.runExclusive(async () => {\n if (isDefined(singleton)) return singleton\n const local = await startupSpanAsync('BalanceSummaryMap:initLocal', () => initLocalBalanceSummaryMap(params))\n singleton = local\n return singleton\n })\n}\n","import { isDefined } from '@xylabs/typeof'\nimport { getLocalPersistentMap } from '@xyo-network/chain-sdk'\nimport type { WithStorageMeta } from '@xyo-network/payload-model'\nimport type { BalancesStepSummary, MapType } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nimport type { ChainInitializableParams } from '../../ChainInitializableParams.ts'\n\nconst mutex = new Mutex()\nlet singleton: MapType<string, WithStorageMeta<BalancesStepSummary>> | undefined\n\nexport const initLocalBalanceSummaryMap = async (params: ChainInitializableParams): Promise<MapType<string, WithStorageMeta<BalancesStepSummary>>> => {\n return await mutex.runExclusive(async () => {\n if (isDefined(singleton)) return singleton\n const { root } = params.config.storage\n singleton = await getLocalPersistentMap<string, WithStorageMeta<BalancesStepSummary>>('balance', 'summary', root)\n return singleton\n })\n}\n","import { isDefined } from '@xylabs/typeof'\nimport { startupSpanAsync } from '@xyo-network/chain-sdk'\nimport type { WithStorageMeta } from '@xyo-network/payload-model'\nimport type { MapType, TransfersStepSummary } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nimport type { ChainInitializableParams } from '../../ChainInitializableParams.ts'\nimport { initLocalTransferSummaryMap } from './initLocalTransferSummaryMap.ts'\n\nconst mutex = new Mutex()\nlet singleton: MapType<string, WithStorageMeta<TransfersStepSummary>> | undefined\n\nexport async function initTransferSummaryMap(params: Pick<ChainInitializableParams, 'config'>):\nPromise<MapType<string, WithStorageMeta<TransfersStepSummary>>> {\n return await mutex.runExclusive(async () => {\n if (isDefined(singleton)) return singleton\n const local = await startupSpanAsync('TransferSummaryMap:initLocal', () => initLocalTransferSummaryMap(params))\n singleton = local\n return singleton\n })\n}\n","import { isDefined } from '@xylabs/typeof'\nimport { getLocalPersistentMap } from '@xyo-network/chain-sdk'\nimport type { WithStorageMeta } from '@xyo-network/payload-model'\nimport type { MapType, TransfersStepSummary } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nimport type { ChainInitializableParams } from '../../ChainInitializableParams.ts'\n\nconst mutex = new Mutex()\nlet singleton: MapType<string, WithStorageMeta<TransfersStepSummary>> | undefined\n\nexport const initLocalTransferSummaryMap = async (params: Pick<ChainInitializableParams, 'config'>):\nPromise<MapType<string, WithStorageMeta<TransfersStepSummary>>> => {\n return await mutex.runExclusive(async () => {\n if (isDefined(singleton)) return singleton\n const { root } = params.config.storage\n singleton = await getLocalPersistentMap<string, WithStorageMeta<TransfersStepSummary>>('transfer', 'summary', root)\n return singleton\n })\n}\n","import type { Promisable } from '@xylabs/promise'\nimport { isUndefined } from '@xylabs/typeof'\nimport { HDWallet } from '@xyo-network/wallet'\nimport type { WalletInstance } from '@xyo-network/wallet-model'\nimport type { Initializable, InitializableParams } from '@xyo-network/xl1-protocol'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport { ADDRESS_INDEX, generateXyoBaseWalletFromPhrase } from '@xyo-network/xl1-protocol-sdk'\n\nlet accountServiceSingleton: Promisable<WalletInstance> | undefined\n\nexport const initAccount: Initializable<InitializableParams<{ config: Config }>, WalletInstance> = async ({ config, logger }): Promise<WalletInstance> => {\n if (accountServiceSingleton) return accountServiceSingleton\n let walletPhrase = config.producer.mnemonic\n if (isUndefined(walletPhrase)) {\n logger?.warn('[Producer] No wallet mnemonic specified!')\n const randomMnemonic = HDWallet.generateMnemonic()\n logger?.warn(`[Producer] Using randomly generated mnemonic:\n \n${randomMnemonic}\n \n `)\n walletPhrase = randomMnemonic\n }\n const wallet = await generateXyoBaseWalletFromPhrase(walletPhrase)\n const account = await wallet.derivePath(ADDRESS_INDEX.XYO)\n accountServiceSingleton = account\n return accountServiceSingleton\n}\n","import type { Promisable } from '@xylabs/promise'\nimport type { BaseAccountBalanceServiceParams } from '@xyo-network/chain-sdk'\nimport { BaseAccountBalanceService } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { AccountBalanceServiceV2 } from '@xyo-network/xl1-protocol-sdk'\n\nlet balanceServiceSingleton: Promisable<AccountBalanceServiceV2> | undefined\n\nexport const initBalanceService: Initializable<BaseAccountBalanceServiceParams, AccountBalanceServiceV2>\n = async (params): Promise<AccountBalanceServiceV2> => {\n if (balanceServiceSingleton) return balanceServiceSingleton\n balanceServiceSingleton = await BaseAccountBalanceService.create(params)\n return balanceServiceSingleton\n }\n","import type { CreatableName } from '@xylabs/creatable'\nimport type { Promisable } from '@xylabs/promise'\nimport type { BaseAccountableServiceParams } from '@xyo-network/chain-sdk'\nimport { MemoryChainService } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { ChainService } from '@xyo-network/xl1-protocol-sdk'\n\nimport { canUseEvmContractChainService, initEvmContractChainService } from './evm.ts'\n\nlet chainStakeServiceSingleton: Promisable<ChainService> | undefined\n\nexport const initChainService: Initializable<BaseAccountableServiceParams, ChainService> = ({ account, config }) => init({\n config, name: 'ChainService' as CreatableName, account,\n})\n\nconst init: Initializable<BaseAccountableServiceParams, ChainService> = (params): Promisable<ChainService> => {\n if (chainStakeServiceSingleton) return chainStakeServiceSingleton\n const { config } = params\n chainStakeServiceSingleton = canUseEvmContractChainService(config)\n ? initEvmContractChainService({ ...params, name: 'ChainStakeService' as CreatableName })\n : MemoryChainService.create({ ...params, name: 'ChainStakeService' as CreatableName })\n // Create service\n return chainStakeServiceSingleton\n}\n","import { assertEx } from '@xylabs/assert'\nimport type { Address } from '@xylabs/hex'\nimport { asAddress, ZERO_ADDRESS } from '@xylabs/hex'\nimport type { Promisable } from '@xylabs/promise'\nimport { isDefined } from '@xylabs/typeof'\nimport type { BaseAccountableServiceParams } from '@xyo-network/chain-sdk'\nimport { EvmChainService } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport type { ContractRunner } from 'ethers'\nimport { Wallet } from 'ethers/wallet'\n\nimport { canUseEvmProvider, initEvmProvider } from '../evm/index.ts'\n\nlet chainStakeServiceSingleton: Promisable<EvmChainService> | undefined\n\nexport const canUseEvmContractChainService = (config: Config) => {\n const { id } = config.chain\n return isDefined(id) && id !== ZERO_ADDRESS && canUseEvmProvider({ config })\n}\n\nexport const initEvmContractChainService: Initializable<BaseAccountableServiceParams, EvmChainService> = async ({\n account, config, traceProvider, meterProvider, logger,\n}) => {\n if (chainStakeServiceSingleton) return chainStakeServiceSingleton\n // Parse config\n const emvStakingContractAddress = assertEx(config.chain.id, () => 'Error: config.chain.id is required')\n // Configure ContractRunner\n const id: Address = assertEx(asAddress(emvStakingContractAddress), () => 'Error: config.chain.id is not a valid address')\n const provider = assertEx(await initEvmProvider({ config }))\n const privateKey = assertEx(account.private?.hex, () => 'Error: Account does not have a private key')\n const runner: ContractRunner = new Wallet(privateKey, provider)\n // Create service\n chainStakeServiceSingleton = EvmChainService.create({\n id, runner, traceProvider, meterProvider, logger,\n })\n return await chainStakeServiceSingleton\n}\n","import { assertEx } from '@xylabs/assert'\nimport type { Logger } from '@xylabs/logger'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport type { Provider } from 'ethers'\nimport type { JsonRpcProvider } from 'ethers/providers'\n\nimport { canUseInfuraProvider, initInfuraProvider } from './initInfuraProvider.ts'\nimport { canUseJsonRpcProvider, initJsonRpcProvider } from './initJsonRpcProvider.ts'\n\nlet provider: Promise<JsonRpcProvider> | undefined\n\nexport const initEvmProvider = async ({ config }: { config: Config; logger?: Logger }): Promise<Provider> => {\n if (provider) return provider\n if (canUseInfuraProvider(config)) {\n provider = initInfuraProvider(config)\n } else if (canUseJsonRpcProvider(config)) {\n provider = initJsonRpcProvider(config)\n }\n return assertEx(await provider, () => 'Error: No provider available')\n}\n\nexport const canUseEvmProvider = ({ config }: { config: Config }) => {\n return canUseInfuraProvider(config) || canUseJsonRpcProvider(config)\n}\n","import { assertEx } from '@xylabs/assert'\nimport { isDefined } from '@xylabs/typeof'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport { InfuraProvider } from 'ethers/providers'\n\nimport { canUseChainId, getChainId } from './initChainId.ts'\n\nlet instance: Promise<InfuraProvider> | undefined\n\nexport const initInfuraProvider = (config: Config) => {\n if (instance) return instance\n const providerConfig = getInfuraProviderConfig(config)\n instance = Promise.resolve(new InfuraProvider(...providerConfig))\n return instance\n}\n\nexport const canUseInfuraProvider = (config: Config): boolean => {\n return canUseChainId(config)\n && isDefined(config.evm?.infura?.projectId)\n && isDefined(config.evm?.infura?.projectSecret)\n}\n\nexport const getInfuraProviderConfig = (config: Config) => {\n const projectId = assertEx(config.evm?.infura?.projectId, () => 'Missing config.evm.infura.projectId')\n const projectSecret = assertEx(config.evm?.infura?.projectSecret, () => 'Missing config.evm.infura.projectSecret')\n return [getChainId(config), projectId, projectSecret] as const\n}\n","import { assertEx } from '@xylabs/assert'\nimport { hexFrom, isHex } from '@xylabs/hex'\nimport { isDefined } from '@xylabs/typeof'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\n\nexport const canUseChainId = (config: Config): boolean => {\n return isDefined(config.evm.chainId)\n}\n\nexport const getChainId = (config: Config) => {\n const chainId = assertEx(config.evm.chainId, () => 'Missing config.evm.chainId')\n if (isHex(chainId, { prefix: true })) {\n const hex = hexFrom(chainId)\n const parsed = Number.parseInt(hex, 16)\n return parsed\n } else {\n const parsed = Number.parseInt(chainId, 10)\n return parsed\n }\n}\n","import { assertEx } from '@xylabs/assert'\nimport { isDefined } from '@xylabs/typeof'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport { JsonRpcProvider } from 'ethers/providers'\n\nimport { canUseChainId, getChainId } from './initChainId.ts'\n\nexport const initJsonRpcProvider = (config: Config) => {\n const providerConfig = getJsonRpcProviderConfig(config)\n return Promise.resolve(new JsonRpcProvider(...providerConfig))\n}\n\nexport const canUseJsonRpcProvider = (config: Config) => {\n return canUseChainId(config)\n && isDefined(config.evm.jsonRpc?.url)\n}\n\nexport const getJsonRpcProviderConfig = (config: Config) => {\n const jsonRpcUrl = assertEx(config.evm.jsonRpc?.url, () => 'Missing config.evm.jsonRpc.url')\n return [jsonRpcUrl, getChainId(config)] as const\n}\n","import { assertEx } from '@xylabs/assert'\nimport type { Promisable } from '@xylabs/promise'\nimport { isDefined } from '@xylabs/typeof'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { findMostRecentBlock } from '@xyo-network/chain-sdk'\nimport type { WithStorageMeta } from '@xyo-network/payload-model'\nimport type { WalletInstance } from '@xyo-network/wallet-model'\nimport type { BlockBoundWitness, Initializable } from '@xyo-network/xl1-protocol'\nimport type { ChainService } from '@xyo-network/xl1-protocol-sdk'\n\nimport { createBootstrapHead } from './createBootstrapHead.ts'\nimport { createForkedHead } from './createForkedHead/index.ts'\nimport { getForkFromBlock } from './getForkFromBlock.ts'\nimport { submitNewChain } from './submitNewChain.ts'\n\nlet headSingleton: Promisable<WithStorageMeta<BlockBoundWitness>> | undefined\n\nexport const initHead: Initializable<{\n account: WalletInstance\n chainArchivist: ArchivistInstance\n chainService: ChainService\n chainSubmissionsArchivistWrite: ArchivistInstance\n}, WithStorageMeta<BlockBoundWitness>>\n = async (params): Promise<WithStorageMeta<BlockBoundWitness>> => {\n const {\n account, chainArchivist, chainSubmissionsArchivistWrite, chainService,\n } = params\n if (headSingleton) return headSingleton\n let head = await findMostRecentBlock(chainArchivist)\n\n // If there is a head\n if (head) {\n // If there is a head but check if it matches our chainId or we should fork from it\n const forkFromBlock = await getForkFromBlock(head, chainService, chainArchivist)\n // If we should fork form a block in the current chain\n if (isDefined(forkFromBlock)) {\n // Create a new chain from the fork from block\n const chain = await createForkedHead(forkFromBlock, account, chainService)\n await submitNewChain(chain, chainArchivist, chainSubmissionsArchivistWrite)\n const newBlock = assertEx(chain.at(-1), () => new Error('Failed to get new head after forking'))\n head = newBlock[0]\n }\n } else {\n // If there is no head, create one\n const chain = await createBootstrapHead(account, chainService)\n await submitNewChain(chain, chainArchivist, chainSubmissionsArchivistWrite)\n const newBlock = assertEx(chain.at(-1), () => new Error('Failed to get new head after genesis'))\n head = newBlock[0]\n }\n headSingleton = head\n return headSingleton\n }\n","import {\n buildNextBlock, createDeclarationIntent, createGenesisBlock,\n} from '@xyo-network/chain-sdk'\nimport type { WalletInstance } from '@xyo-network/wallet-model'\nimport type { HydratedBlock } from '@xyo-network/xl1-protocol'\nimport type { ChainService } from '@xyo-network/xl1-protocol-sdk'\n\nexport const createBootstrapHead = async (account: WalletInstance, chainService: ChainService): Promise<HydratedBlock[]> => {\n const chainId = chainService.chainId\n const chain: HydratedBlock[] = []\n\n // Create genesis block\n const genesisBlock = await createGenesisBlock(account, chainId, 10_000_000n, account.address)\n chain.push(genesisBlock)\n\n // Create producer declaration block\n const producerDeclarationPayload = createDeclarationIntent(\n 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 { BridgeDestinationObservationSchema, buildNextBlock } from '@xyo-network/chain-sdk'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport type { WalletInstance } from '@xyo-network/wallet-model'\nimport type {\n BridgeDestinationObservation, BridgeDestinationObservationFields, HydratedBlock,\n} from '@xyo-network/xl1-protocol'\nimport type { ChainService } from '@xyo-network/xl1-protocol-sdk'\n\nimport {\n getBridgeDestConfirmation, getBridgeDestinationDetails, getBridgeSourceDetails,\n} from './config/index.ts'\n\n/**\n * Get the bridge destination observation for a given block.\n * @param previousBlock The previous block to base the observation on.\n * @param account The wallet account to use for the observation.\n * @param chainService The chain service to use for the observation.\n */\nexport const getBridgeDestinationObservation = async (\n previousBlock: HydratedBlock,\n account: WalletInstance,\n chainService: ChainService,\n): Promise<HydratedBlock> => {\n const bridgeDestinationObservationFields: BridgeDestinationObservationFields = {\n ...getBridgeSourceDetails(account, chainService),\n ...getBridgeDestinationDetails(),\n destConfirmation: getBridgeDestConfirmation(),\n }\n const bridgeDestinationObservation = new PayloadBuilder<BridgeDestinationObservation>({ schema: BridgeDestinationObservationSchema })\n .fields(bridgeDestinationObservationFields)\n .build()\n\n return await buildNextBlock(\n previousBlock[0],\n [],\n [bridgeDestinationObservation],\n [account],\n )\n}\n","import { toHex } from '@xylabs/hex'\nimport type { BridgeDetailsDestinationFields } from '@xyo-network/xl1-protocol'\n\nimport { getForkBlockRewardHex } from './getForkDetails.ts'\n\n// const bridgeableTokenContract = toHex('0x4865Cb10d55cfB0E60DD2B4F9b888f6a49B76733')\n// const bridgeDestAddress = toHex('0xe53218d47913b5f9E58bb74F0a0eD790bbF21972')\n// const destConfirmation = toHex('0x4fa05d7e799f36f1d45c441a4866eb4570a00a753a39377f404a8d113c01a657') // Eth TX for mint\nconst ethChainId = toHex('0x1')\nconst bridgeableTokenContract = toHex('0xf72aE3E0DA743033AbD7A407557D684c1aE66aed')\nconst bridgeDestAddress = toHex('0x0e65b65B10C791942665030402c35023d88B14dA')\nconst destConfirmation = toHex('0x950861b10523b52cdbb4a9ee52ed26601db555d2652bfec21c709e5e70d5b7d3') // Eth TX for mint\n\nexport const getBridgeDestChainId = () => ethChainId\nexport const getBridgeDestToken = () => bridgeableTokenContract\nexport const getBridgeDestAddress = () => bridgeDestAddress\nexport const getBridgeDestAmount = () => getForkBlockRewardHex()\nexport const getBridgeDestConfirmation = () => destConfirmation\n\nexport const getBridgeDestinationDetails = (): BridgeDetailsDestinationFields => {\n return {\n dest: getBridgeDestChainId(),\n destToken: getBridgeDestToken(),\n destAddress: getBridgeDestAddress(),\n destAmount: getBridgeDestAmount(),\n }\n}\n","import { type Hex, toHex } from '@xylabs/hex'\nimport { AttoXL1ConvertFactor } from '@xyo-network/xl1-protocol'\n\nexport const getForkBlockReward = (): bigint => {\n return 18_000_000_000n * AttoXL1ConvertFactor.xl1 // 18b XL1 in AttoXL1\n}\n\nexport const getForkBlockRewardHex = (): Hex => {\n return toHex(getForkBlockReward())\n}\n","import type { AccountInstance } from '@xyo-network/account-model'\nimport type { BridgeDetailsSourceFields } from '@xyo-network/xl1-protocol'\nimport type { ChainService } from '@xyo-network/xl1-protocol-sdk'\n\nimport { getForkBlockRewardHex } from './getForkDetails.ts'\n\nexport const getBridgeSrcChainId = (chainService: ChainService) => chainService.chainId\nexport const getBridgeSrcAddress = (account: AccountInstance) => account.address\nexport const getBridgeSrcToken = (chainService: ChainService) => chainService.chainId\nexport const getBridgeSrcAmount = () => getForkBlockRewardHex()\n\nexport const getBridgeSourceDetails = (account: AccountInstance, chainService: ChainService): BridgeDetailsSourceFields => {\n return {\n src: getBridgeSrcChainId(chainService),\n srcAddress: getBridgeSrcAddress(account),\n srcToken: getBridgeSrcToken(chainService),\n srcAmount: getBridgeSrcAmount(),\n }\n}\n","import {\n BridgeIntentSchema, buildNextBlock, createTransferPayload, XYO_BRIDGE_ADDRESS,\n} from '@xyo-network/chain-sdk'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport type { WalletInstance } from '@xyo-network/wallet-model'\nimport type {\n BridgeIntent, BridgeIntentFields, HydratedBlock,\n} from '@xyo-network/xl1-protocol'\nimport type { ChainService } from '@xyo-network/xl1-protocol-sdk'\n\nimport {\n getBridgeDestinationDetails, getBridgeSourceDetails, getForkBlockReward,\n} from './config/index.ts'\n\n/**\n * Get the bridge intent for a given block.\n * @param previousBlock The previous block to base the intent on.\n * @param account The wallet account to use for the intent.\n * @param chainService The chain service to use for the intent.\n */\nexport const getBridgeIntent = async (\n previousBlock: HydratedBlock,\n account: WalletInstance,\n chainService: ChainService,\n): Promise<HydratedBlock> => {\n // Create transfer to bridge address\n const transferPayload = createTransferPayload(\n account.address,\n { [XYO_BRIDGE_ADDRESS]: getForkBlockReward() },\n )\n\n // Use timestamp as nonce\n const nonce = `${Date.now()}`\n\n // Create Bridge Intent\n const bridgeIntentFields: BridgeIntentFields = {\n ...getBridgeSourceDetails(account, chainService),\n ...getBridgeDestinationDetails(),\n nonce,\n }\n const bridgeIntent = new PayloadBuilder<BridgeIntent>({ schema: BridgeIntentSchema })\n .fields(bridgeIntentFields)\n .build()\n\n return await buildNextBlock(\n previousBlock[0],\n [],\n [bridgeIntent, transferPayload],\n [account],\n )\n}\n","import { BridgeSourceObservationSchema, buildNextBlock } from '@xyo-network/chain-sdk'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport type { WalletInstance } from '@xyo-network/wallet-model'\nimport type {\n BridgeSourceObservation, BridgeSourceObservationFields, HydratedBlock,\n} from '@xyo-network/xl1-protocol'\nimport type { ChainService } from '@xyo-network/xl1-protocol-sdk'\n\nimport { getBridgeDestinationDetails, getBridgeSourceDetails } from './config/index.ts'\n\n/**\n * Get the bridge source observation for a given block.\n * @param previousBlock The previous block to base the observation on.\n * @param account The wallet account to use for the observation.\n * @param chainService The chain service to use for the observation.\n */\nexport const getBridgeSourceObservation = async (\n previousBlock: HydratedBlock,\n account: WalletInstance,\n chainService: ChainService,\n): Promise<HydratedBlock> => {\n // TODO: Find actual transfer TX from previous block/source intent?\n // This hash should contain both the source intent and the transfer to the bridge address\n // As the block is itself both a block and a transaction, we can use its hash for now\n const srcTxHash = previousBlock[0]._hash\n\n const bridgeSourceObservationFields: BridgeSourceObservationFields = {\n ...getBridgeSourceDetails(account, chainService),\n ...getBridgeDestinationDetails(),\n // Observation\n srcConfirmation: srcTxHash,\n }\n\n const bridgeSourceObservation = new PayloadBuilder<BridgeSourceObservation>({ schema: BridgeSourceObservationSchema })\n .fields(bridgeSourceObservationFields)\n .build()\n\n return await buildNextBlock(\n previousBlock[0],\n [],\n [bridgeSourceObservation],\n [account],\n )\n}\n","import type { BuildNextBlockOptions } from '@xyo-network/chain-sdk'\nimport {\n AttoXL1, buildBlock, XYO_STEP_REWARD_ADDRESS,\n} from '@xyo-network/chain-sdk'\nimport type { WithHashMeta } from '@xyo-network/payload-model'\nimport type { WalletInstance } from '@xyo-network/wallet-model'\nimport type { BlockBoundWitness, HydratedBlock } from '@xyo-network/xl1-protocol'\nimport type { ChainService } from '@xyo-network/xl1-protocol-sdk'\n\n/**\n * Get the first block for the new forked chain.\n * @param forkBlock The block to fork from\n * @param account The wallet account to sign the block\n * @param chainService The chain service instance\n * @returns The first block for the new forked chain\n */\nexport const getFirstBlockForNewChain = async (\n forkBlock: WithHashMeta<BlockBoundWitness>,\n account: WalletInstance,\n chainService: ChainService,\n): Promise<HydratedBlock> => {\n const {\n _hash: previousBlockHash, block: previousBlockNumber, step_hashes: previousStepHashes, protocol,\n } = forkBlock\n const chainId = chainService.chainId\n const options: BuildNextBlockOptions = {\n blockPayloads: [],\n chainId,\n previousBlockHash,\n previousBlockNumber,\n previousStepHashes,\n signers: [account],\n txs: [],\n protocol,\n chainStepRewardAddress: XYO_STEP_REWARD_ADDRESS,\n stepRewardPoolBalance: AttoXL1(0n),\n }\n // NOTE: Can not use buildNextBlock because we need to control the chain id change here\n return await buildBlock(options)\n}\n","import type { WithHashMeta } from '@xyo-network/payload-model'\nimport type { WalletInstance } from '@xyo-network/wallet-model'\nimport type { BlockBoundWitness, HydratedBlock } from '@xyo-network/xl1-protocol'\nimport type { ChainService } from '@xyo-network/xl1-protocol-sdk'\n\nimport { getBridgeDestinationObservation } from './getBridgeDestinationObservation.ts'\nimport { getBridgeIntent } from './getBridgeIntent.ts'\nimport { getBridgeSourceObservation } from './getBridgeSourceObservation.ts'\nimport { getFirstBlockForNewChain } from './getFirstBlockForNewChain.ts'\n\nexport const createForkedHead = async (\n forkFromBlock: WithHashMeta<BlockBoundWitness>,\n account: WalletInstance,\n chainService: ChainService,\n): Promise<HydratedBlock[]> => {\n const chain: HydratedBlock[] = []\n // Build the first block for the new chain\n const firstBlockForNewChain = await getFirstBlockForNewChain(forkFromBlock, account, chainService)\n chain.push(firstBlockForNewChain)\n // Build the bridge intent\n const bridgeIntent = await getBridgeIntent(firstBlockForNewChain, account, chainService)\n chain.push(bridgeIntent)\n // Build the bridge source observation\n const bridgeSourceObservation = await getBridgeSourceObservation(bridgeIntent, account, chainService)\n chain.push(bridgeSourceObservation)\n // Build the bridge destination observation\n const bridgeDestinationObservation = await getBridgeDestinationObservation(bridgeSourceObservation, account, chainService)\n chain.push(bridgeDestinationObservation)\n return chain\n}\n","import type { Address, Hash } from '@xylabs/hex'\nimport { asHash, hexFromBigInt } from '@xylabs/hex'\nimport { isDefined } from '@xylabs/typeof'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { isBlockBoundWitnessWithHashMeta } from '@xyo-network/chain-sdk'\nimport type { WithHashMeta, WithStorageMeta } from '@xyo-network/payload-model'\nimport type { BlockBoundWitness } from '@xyo-network/xl1-protocol'\nimport type { ChainService } from '@xyo-network/xl1-protocol-sdk'\n\n/**\n * Determine if the chain should fork based on the current head and chain configuration.\n * @param head The current head block\n * @param chainService The chain service instance\n * @param chainArchivist The chain archivist instance\n * @returns The block to fork from if the chain should fork, undefined otherwise\n */\nexport const getForkFromBlock = async (\n head: WithStorageMeta<BlockBoundWitness>,\n chainService: ChainService,\n chainArchivist: ArchivistInstance,\n): Promise<WithHashMeta<BlockBoundWitness> | undefined> => {\n // If the head's chain doesn't match our chainId, we may need to fork\n if (head.chain !== chainService.chainId) {\n // Get the forked at hash from the chain service\n const forkedAtBigInt = await chainService.forkedAtHash()\n const forkedAtHex = hexFromBigInt(forkedAtBigInt) // Validate it's a proper hex string\n const forkedAtHash: Hash | undefined = asHash(forkedAtHex)\n if (isDefined(forkedAtHash)) {\n // If we have a forkedAtHash, we need to check if the correct block exists\n const [forkedAtBlock] = await chainArchivist.get([forkedAtHash])\n const forkedChainId: Address = await chainService.forkedChainId()\n const forkedAtBlockNumber: number = Number(await chainService.forkedAtBlockNumber())\n // If we found the block hash we should fork at, check if it's a valid BlockBoundWitness\n if (isBlockBoundWitnessWithHashMeta(forkedAtBlock)\n // And it is on the correct forked from chain\n && forkedAtBlock.chain === forkedChainId\n // And it is the correct forked at block number\n && forkedAtBlock.block === forkedAtBlockNumber) {\n return forkedAtBlock\n }\n }\n }\n}\n","import { delay } from '@xylabs/delay'\nimport type { ArchivistInstance, WriteArchivist } from '@xyo-network/archivist-model'\nimport type { HydratedBlock } from '@xyo-network/xl1-protocol'\nimport { flattenHydratedBlock } from '@xyo-network/xl1-protocol-sdk'\n\n/**\n * Submit a new chain to the archivist.\n * @param chain The new chain to submit\n * @param chainArchivist The chain archivist instance\n * @param chainSubmissionsArchivistWrite The chain submissions archivist instance\n */\nexport const submitNewChain = async (\n chain: HydratedBlock[],\n chainArchivist: ArchivistInstance,\n chainSubmissionsArchivistWrite: WriteArchivist,\n): Promise<void> => {\n for (const block of chain) {\n const [bw] = block\n await chainSubmissionsArchivistWrite.insert(flattenHydratedBlock(block))\n // Wait for block to show up in finalized archivist\n while (true) {\n const result = await chainArchivist.get([bw._hash])\n if (result.length > 0) break\n await delay(1000) // Wait 1 second before retrying\n }\n }\n}\n","import type {\n BaseElectionServicesParams,\n Initializable,\n XyoChainIteratorParams,\n XyoStakeIntentServiceParams,\n} from '@xyo-network/chain-sdk'\nimport {\n BaseElectionService, ChainBlockNumberIterationService,\n XyoStakeIntentService,\n} from '@xyo-network/chain-sdk'\nimport type {\n ElectionService, EventingChainBlockNumberIteratorService, StakeIntentService,\n} from '@xyo-network/xl1-protocol-sdk'\n\nlet chainIteratorServiceSingleton: Promise<EventingChainBlockNumberIteratorService> | undefined\nlet stakeIntentServiceSingleton: Promise<StakeIntentService> | undefined\nlet electionServiceSingleton: Promise<ElectionService> | undefined\n\nexport const initChainIterator: Initializable<XyoChainIteratorParams, EventingChainBlockNumberIteratorService> = (params) => {\n if (chainIteratorServiceSingleton) return chainIteratorServiceSingleton\n chainIteratorServiceSingleton = ChainBlockNumberIterationService.create(params)\n return chainIteratorServiceSingleton\n}\n\nexport const initStakeIntentService: Initializable<XyoStakeIntentServiceParams, StakeIntentService>\n = (params) => {\n if (stakeIntentServiceSingleton) return stakeIntentServiceSingleton\n stakeIntentServiceSingleton = XyoStakeIntentService.create(params)\n return stakeIntentServiceSingleton\n }\n\nexport const initElectionService: Initializable<BaseElectionServicesParams, ElectionService>\n = (params) => {\n if (electionServiceSingleton) return electionServiceSingleton\n electionServiceSingleton = BaseElectionService.create(params)\n return electionServiceSingleton\n }\n","import type { Promisable } from '@xylabs/promise'\nimport type { BasePendingTransactionsServiceParams } from '@xyo-network/chain-sdk'\nimport { BasePendingTransactionsService } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { PendingTransactionsService } from '@xyo-network/xl1-protocol-sdk'\n\nlet serviceSingleton: Promisable<PendingTransactionsService> | undefined\n\nexport const initPendingTransactions: Initializable<BasePendingTransactionsServiceParams, PendingTransactionsService> = async (\n params: BasePendingTransactionsServiceParams,\n): Promise<PendingTransactionsService> => {\n if (serviceSingleton) return serviceSingleton\n serviceSingleton = await BasePendingTransactionsService.create(params)\n return serviceSingleton\n}\n","import type { Promisable } from '@xylabs/promise'\nimport type { BaseBlockProducerServiceParams } from '@xyo-network/chain-sdk'\nimport { BaseBlockProducerService } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { BlockProducerService } from '@xyo-network/xl1-protocol-sdk'\n\nlet serviceSingleton: Promisable<BlockProducerService> | undefined\n\nexport const initBlockProducer: Initializable<BaseBlockProducerServiceParams, BlockProducerService>\n = async (params: BaseBlockProducerServiceParams): Promise<BlockProducerService> => {\n if (serviceSingleton) return serviceSingleton\n serviceSingleton = await BaseBlockProducerService.create(params)\n return serviceSingleton\n }\n","import { assertEx } from '@xylabs/assert'\nimport type { BaseBlockRewardServiceParams, EvmBlockRewardServiceParams } from '@xyo-network/chain-sdk'\nimport { EvmBlockRewardService, MemoryBlockRewardService } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { BlockRewardService, Config } from '@xyo-network/xl1-protocol-sdk'\n\nimport { canUseEvmProvider, initEvmProvider } from './evm/index.ts'\n\nlet rewardServiceSingleton: Promise<BlockRewardService> | undefined\n\nexport const initBlockRewardService: Initializable<\n BaseBlockRewardServiceParams | EvmBlockRewardServiceParams,\n BlockRewardService\n> = (params): Promise<BlockRewardService> => {\n if (rewardServiceSingleton) return rewardServiceSingleton\n const { config } = params\n rewardServiceSingleton = canUseEvmBlockRewardService({ config })\n ? initEvmBlockRewardService(params as EvmBlockRewardServiceParams)\n : initXyoBlockRewardService(params)\n return rewardServiceSingleton\n}\n\nconst initXyoBlockRewardService = (params: BaseBlockRewardServiceParams): Promise<BlockRewardService> => {\n if (rewardServiceSingleton) return rewardServiceSingleton\n rewardServiceSingleton = MemoryBlockRewardService.create(params)\n return rewardServiceSingleton\n}\n\nconst canUseEvmBlockRewardService = (params: { config: Config }) => canUseEvmProvider({ config: params.config })\n\nconst initEvmBlockRewardService = async (params: EvmBlockRewardServiceParams): Promise<BlockRewardService> => {\n if (rewardServiceSingleton) return rewardServiceSingleton\n const { account: paramsAccount } = params\n const account = assertEx(paramsAccount, () => 'Error: Account is required')\n const provider = assertEx(await initEvmProvider(params))\n const evmBlockRewardServiceParams: EvmBlockRewardServiceParams = {\n ...params, provider, account,\n }\n rewardServiceSingleton = EvmBlockRewardService.create(evmBlockRewardServiceParams)\n return rewardServiceSingleton\n}\n","import type { Promisable } from '@xylabs/promise'\nimport type { BaseTimeServiceParams } from '@xyo-network/chain-sdk'\nimport { BaseTimeSyncService } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { TimeSyncServiceV2 } from '@xyo-network/xl1-protocol-sdk'\n\nimport { canUseEvmProvider, initEvmProvider } from './evm/index.ts'\n\nlet timeSyncServiceSingleton: Promisable<TimeSyncServiceV2> | undefined\n\nexport const initTimeService: Initializable<BaseTimeServiceParams, TimeSyncServiceV2> = async ({\n chainArchivist, chainIterator, config, logger, meterProvider, traceProvider,\n}) => {\n if (timeSyncServiceSingleton) return timeSyncServiceSingleton\n\n // Configure provider for optional Ethereum time sync\n const ethProvider = canUseEvmProvider({ config }) ? await initEvmProvider({ config }) : undefined\n\n // Create service\n timeSyncServiceSingleton = BaseTimeSyncService.create({\n chainArchivist, chainIterator, ethProvider, logger, meterProvider, traceProvider,\n })\n return await timeSyncServiceSingleton\n}\n","import type { Promisable } from '@xylabs/promise'\nimport type { BaseAccountTransferServiceParams } from '@xyo-network/chain-sdk'\nimport { BaseAccountTransfersService } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { AccountTransfersService } from '@xyo-network/xl1-protocol-sdk'\n\nlet transferServiceSingleton: Promisable<AccountTransfersService> | undefined\n\nexport const initTransferService: Initializable<BaseAccountTransferServiceParams, AccountTransfersService>\n = async (params): Promise<AccountTransfersService> => {\n if (transferServiceSingleton) return transferServiceSingleton\n transferServiceSingleton = await BaseAccountTransfersService.create(params)\n return transferServiceSingleton\n }\n","import type {\n CreatableName, CreatableStatus, CreatableStatusReporter,\n} from '@xylabs/creatable'\nimport type { Logger } from '@xylabs/logger'\n\nexport class LoggerStatusReporter implements CreatableStatusReporter {\n protected logger: Logger\n\n protected statusMap: Record<CreatableName, CreatableStatus> = {}\n\n constructor(logger: Logger) {\n this.logger = logger\n }\n\n report(name: CreatableName, status: CreatableStatus, progress?: number | Error): void {\n this.statusMap[name] = status\n const starting = (Object.entries(this.statusMap).map(([, value]): number => value === 'starting' ? 1 : 0)).reduce((a, b) => a + b, 0)\n const started = (Object.entries(this.statusMap).map(([, value]): number => value === 'started' ? 1 : 0)).reduce((a, b) => a + b, 0)\n this.logger.info(`${started}/${starting + started} ${name} status: ${status}`, { progress })\n }\n}\n","import type { CreatableName, CreatableStatus } from '@xylabs/creatable'\n\nimport { LoggerStatusReporter } from './ServiceStatus.ts'\n\n/**\n * Enum-like record for statuses with priority allowing\n * for determination of the aggregated status.\n */\nconst statusPriority: Record<CreatableStatus, number> = {\n error: 0,\n stopped: 1,\n stopping: 2,\n creating: 3,\n created: 4,\n starting: 5,\n started: 6,\n}\n\n/**\n * A sentinel status that represents the initial state\n * before any statuses are reported.\n * It is used to ensure that the monitor has a valid status\n * even when no statuses have been reported yet and to\n * prevent the system from showing an \"error\" state\n * when no statuses are available.\n */\nconst SENTINEL_STATUS: CreatableStatus = 'starting'\n\n/**\n * Given an array of statuses, this function reduces them\n * to the minimum status based on the defined priority.\n * @param statuses An array of statuses to reduce.\n * @returns The minimum status based on priority.\n */\nconst reduceToMinimumStatus = (statuses: CreatableStatus[]): CreatableStatus => {\n let minStatus: CreatableStatus = SENTINEL_STATUS\n let minPriority = Infinity\n\n for (const status of statuses) {\n const priority = statusPriority[status]\n if (priority < minPriority) {\n minPriority = priority\n minStatus = status\n }\n }\n return minStatus\n}\n\nexport type GlobalTransitionHandler = {\n from?: CreatableStatus\n handler: (from: CreatableStatus, to: CreatableStatus) => void\n to?: CreatableStatus\n}\nexport type TransitionHandler = GlobalTransitionHandler & {\n name?: string\n}\n\nexport class RuntimeStatusMonitor extends LoggerStatusReporter {\n private globalTransitions: GlobalTransitionHandler[] = []\n private transitions: TransitionHandler[] = []\n\n getGlobalStatus(): CreatableStatus {\n // If no statuses have been reported, return the sentinel status\n if (Object.keys(this.statusMap).length === 0) return SENTINEL_STATUS\n return reduceToMinimumStatus(Object.values(this.statusMap))\n }\n\n getStatus(name: CreatableName): CreatableStatus | undefined {\n return this.statusMap[name]\n }\n\n onGlobalTransition(match: { from?: CreatableStatus; to?: CreatableStatus }, handler: (from: CreatableStatus, to: CreatableStatus) => void) {\n this.globalTransitions.push({ ...match, handler })\n }\n\n /**\n * Register a callback to be called on a specific transition.\n */\n onTransition(match: { from?: CreatableStatus; name: string; to?: CreatableStatus }, handler: (from: CreatableStatus, to: CreatableStatus) => void) {\n this.transitions.push({ ...match, handler })\n }\n\n override report(name: CreatableName, status: CreatableStatus, progress?: number | Error): void {\n // Capture the current status before updating\n const previous = this.statusMap[name]\n const previousGlobal = this.getGlobalStatus()\n\n // Update the status map with the new status\n super.report(name, status, progress)\n\n // If the status hasn't changed, do not run handlers\n if (previous === status) return\n this.runTransitions(this.transitions, previous, status, name)\n\n // If the global status hasn't changed, do not run handlers\n const globalStatus = this.getGlobalStatus()\n if (previousGlobal === globalStatus) return\n this.runTransitions(this.globalTransitions, previousGlobal, globalStatus)\n }\n\n private runTransitions(\n transitions: (TransitionHandler | GlobalTransitionHandler)[],\n prev: CreatableStatus,\n next: CreatableStatus,\n name?: string,\n ) {\n for (const {\n from, to, name: matchName, handler,\n } of transitions as TransitionHandler[]) {\n if ((matchName === undefined || matchName === name)\n && (from === undefined || from === prev)\n && (to === undefined || to === next)) {\n handler(prev, next)\n }\n }\n }\n}\n","import type { Logger } from '@xylabs/logger'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\n\nimport type { Orchestrator } from '../../orchestration/index.ts'\nimport {\n BalanceActor, ChainHeadUpdateActor, initServices, ProducerActor,\n} from '../../orchestration/index.ts'\n\ninterface RunProducerContext {\n config: Config\n logger: Logger\n orchestrator: Orchestrator\n}\n\nexport const runProducer = async (context: RunProducerContext) => {\n const {\n config, logger, orchestrator,\n } = context\n\n // Initialize services\n logger?.log('Services: Initializing...')\n const services = await initServices(context)\n logger?.log('Services: Initialized')\n\n // Create actors\n const params = { ...services, config }\n const chainHeadUpdate = await ChainHeadUpdateActor.create({ ...params, name: 'ChainHeadUpdateActor' })\n const balances = await BalanceActor.create({ ...params, name: 'BalanceActor' })\n const producer = await ProducerActor.create({ ...params, name: 'ProducerActor' })\n const actors = [chainHeadUpdate, balances, producer]\n\n for (const actor of actors) {\n // Register the actor with the orchestrator\n await orchestrator.registerActor(actor)\n }\n // Start the orchestrator => automatically activates the actor\n await orchestrator.start()\n}\n","import type { Logger } from '@xylabs/logger'\nimport { getServer } from '@xyo-network/chain-reward-redemption'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\n\ninterface RunRewardRedemptionApiContext {\n config: Config\n logger?: Logger\n}\n\nexport function runRewardRedemptionApi(context: RunRewardRedemptionApiContext) {\n void getServer(context)\n}\n","/* eslint-disable @stylistic/max-len */\nexport const XL1LogoColorizedAscii = `\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;118;111;144m_\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;72;32;223mā• \u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā ā• ā• \u001b[0m\u001b[38;2;103;85;170m_\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;79;121;152m╦\u001b[0m\u001b[38;2;82;121;151m╦\u001b[0m\u001b[38;2;112;125;136m_Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;88;59;196m[\u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;73;34;221mā–’Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;121;121;127m_\u001b[0m\u001b[38;2;100;101;128mā•”\u001b[0m\u001b[38;2;93;94;127m╦\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;82;121;151m²\u001b[0m\u001b[38;2;44;116;170mā• \u001b[0m\u001b[38;2;44;116;171mā–’\u001b[0m\u001b[38;2;51;117;167mD\u001b[0m\u001b[38;2;80;121;152m╦\u001b[0m\u001b[38;2;111;125;136m_Ā Ā Ā Ā \u001b[0m\u001b[38;2;67;23;232mā• \u001b[0m\u001b[38;2;66;21;234mā• ā• ā• Ā Ā Ā Ā \u001b[0m\u001b[38;2;120;121;128m_\u001b[0m\u001b[38;2;100;101;127mā•”\u001b[0m\u001b[38;2;79;81;127mR\u001b[0m\u001b[38;2;71;73;128mā–’\u001b[0m\u001b[38;2;71;73;128mā–’\u001b[0m\u001b[38;2;88;90;127mā•™\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;55;117;165mā•š\u001b[0m\u001b[38;2;44;116;171mā–’\u001b[0m\u001b[38;2;44;116;171mā–’ā–’\u001b[0m\u001b[38;2;50;116;167mD\u001b[0m\u001b[38;2;80;121;152m╦ \u001b[0m\u001b[38;2;106;90;165mj\u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;66;21;234mā• ā• ā• \u001b[0m\u001b[38;2;89;61;194mHĀ \u001b[0m\u001b[38;2;99;100;127mā•”\u001b[0m\u001b[38;2;79;80;127mD\u001b[0m\u001b[38;2;71;73;128mā–’\u001b[0m\u001b[38;2;71;73;128mā–’ā–’ā• \u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;83;121;150m²\u001b[0m\u001b[38;2;44;116;170mā–’\u001b[0m\u001b[38;2;44;116;171mā–’ā–’ā–’Ā \u001b[0m\u001b[38;2;76;38;217mā• \u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;66;21;234mā• ā• ā• ā• Ā \u001b[0m\u001b[38;2;74;76;128mā• \u001b[0m\u001b[38;2;71;73;128mā–’ā–’ā–’\u001b[0m\u001b[38;2;89;90;128mā•™\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;90;118;148m\\`\u001b[0m\u001b[38;2;89;107;153m_\u001b[0m\u001b[38;2;93;97;154m,\u001b[0m\u001b[38;2;105;89;166mā•“\u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;66;21;234mā• ā• ā• ā• ā• \u001b[0m\u001b[38;2;95;72;183mā•“\u001b[0m\u001b[38;2;106;96;152m_\u001b[0m\u001b[38;2;100;94;143m\\`\u001b[0m\u001b[38;2;101;100;133m\\`\u001b[0m\n\u001b[38;2;128;128;128mĀ \u001b[0m\u001b[38;2;122;118;137m_\u001b[0m\u001b[38;2;113;102;153m,\u001b[0m\u001b[38;2;108;94;161mā•“\u001b[0m\u001b[38;2;104;86;169mā•“\u001b[0m\u001b[38;2;98;77;178mā•”\u001b[0m\u001b[38;2;93;67;188mā•—\u001b[0m\u001b[38;2;88;59;196mφ\u001b[0m\u001b[38;2;83;51;204m@\u001b[0m\u001b[38;2;78;42;213mD\u001b[0m\u001b[38;2;72;32;223mā–’\u001b[0m\u001b[38;2;68;24;231mā• \u001b[0m\u001b[38;2;66;21;234mā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• \u001b[0m\u001b[38;2;71;30;225mā–’\u001b[0m\u001b[38;2;77;40;215mā–’\u001b[0m\u001b[38;2;82;49;206mK\u001b[0m\u001b[38;2;87;57;198mφ\u001b[0m\u001b[38;2;91;65;190mā•—\u001b[0m\u001b[38;2;97;75;180m╦\u001b[0m\u001b[38;2;103;84;171mā•–\u001b[0m\u001b[38;2;107;92;163m²\u001b[0m\u001b[38;2;112;101;154m_\u001b[0m\u001b[38;2;119;112;143m_\u001b[0m\n\u001b[38;2;128;128;128mĀ \u001b[0m\u001b[38;2;106;91;164m\\`\u001b[0m\u001b[38;2;94;70;185m^\u001b[0m\u001b[38;2;89;62;193mā•™\u001b[0m\u001b[38;2;85;54;201mā•™\u001b[0m\u001b[38;2;80;45;210mā•š\u001b[0m\u001b[38;2;74;35;220mā•\u001b[0m\u001b[38;2;69;26;229mā• \u001b[0m\u001b[38;2;66;22;233mā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• \u001b[0m\u001b[38;2;73;33;222mā•\u001b[0m\u001b[38;2;79;43;212mā•©\u001b[0m\u001b[38;2;84;52;203mā•œ\u001b[0m\u001b[38;2;88;60;195mā•™\u001b[0m\u001b[38;2;93;68;187m^\u001b[0m\u001b[38;2;100;80;175m\\`\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;113;84;152m\\`\u001b[0m\u001b[38;2;103;79;169m'\u001b[0m\u001b[38;2;95;72;183m\"\u001b[0m\u001b[38;2;87;57;198mā•™\u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;66;21;234mā• ā• ā• ā• ā• \u001b[0m\u001b[38;2;80;46;209mā•œ\u001b[0m\u001b[38;2;94;70;185m^\u001b[0m\u001b[38;2;102;77;175m^\u001b[0m\u001b[38;2;112;81;162m\\`\u001b[0m\u001b[38;2;115;92;155m\\`\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;145;116;107m,\u001b[0m\u001b[38;2;199;82;45mā• \u001b[0m\u001b[38;2;207;77;35mā–’\u001b[0m\u001b[38;2;207;77;35mā–’ā• Ā \u001b[0m\u001b[38;2;70;28;227mā• \u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;66;21;234mā• ā• ā• ā• Ā \u001b[0m\u001b[38;2;189;49;97mĆ„\u001b[0m\u001b[38;2;203;32;90mā• \u001b[0m\u001b[38;2;203;32;90mā• ā• \u001b[0m\u001b[38;2;155;92;114m,\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;175;98;73mā•”\u001b[0m\u001b[38;2;207;77;35mā–’\u001b[0m\u001b[38;2;207;77;35mā–’ā–’ā–’\u001b[0m\u001b[38;2;197;83;47mā•©Ā \u001b[0m\u001b[38;2;98;76;179m[\u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;66;21;234mā• ā• ā• \u001b[0m\u001b[38;2;81;48;207mHĀ \u001b[0m\u001b[38;2;188;51;98mā•š\u001b[0m\u001b[38;2;203;32;90mā• \u001b[0m\u001b[38;2;203;32;90mā• ā• ā• \u001b[0m\u001b[38;2;183;57;100mH\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;146;116;106m,\u001b[0m\u001b[38;2;199;82;44mā• \u001b[0m\u001b[38;2;207;77;35mā–’\u001b[0m\u001b[38;2;207;77;35mā–’\u001b[0m\u001b[38;2;196;84;48mā•©\u001b[0m\u001b[38;2;168;102;81m^Ā Ā Ā Ā \u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;66;21;234mā• ā• ā• Ā Ā Ā Ā \u001b[0m\u001b[38;2;160;87;111m'\u001b[0m\u001b[38;2;187;52;98mā•š\u001b[0m\u001b[38;2;203;32;90mā• \u001b[0m\u001b[38;2;203;32;90mā• ā• \u001b[0m\u001b[38;2;156;91;113m,\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;198;83;46mā•©\u001b[0m\u001b[38;2;194;85;50mā•©\u001b[0m\u001b[38;2;167;102;82m^Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;81;46;209mā•š\u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;66;21;234mā• ā• Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;159;88;112m'\u001b[0m\u001b[38;2;186;53;98mā•š\u001b[0m\u001b[38;2;197;40;93mā•©\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;110;97;158m'\u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;94;69;186mH\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;68;25;230mā• \u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;108;93;162m²\u001b[0m\u001b[38;2;99;79;176m^\u001b[0m`\n","import { Base } from '@xylabs/base'\nimport type { Logger, LogLevelValue } from '@xylabs/logger'\nimport {\n ConsoleLogger, LogLevel, SilentLogger,\n} from '@xylabs/logger'\nimport { isDefined } from '@xylabs/typeof'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\n\nexport const initLogger = (config: Config): Logger => {\n let logger: Logger\n if (config.silent) {\n logger = new SilentLogger()\n } else {\n let level: LogLevelValue | undefined\n if (isDefined(config.logLevel)) {\n const parsed = LogLevel[config.logLevel.toLowerCase() as keyof typeof LogLevel]\n if (isDefined(parsed)) level = parsed\n }\n logger = new ConsoleLogger(level)\n }\n Base.defaultLogger = logger\n return logger\n}\n","import type { UsageMeta } from '@xyo-network/xl1-protocol-sdk'\nimport { isUsageMeta } from '@xyo-network/xl1-protocol-sdk'\nimport type { Options } from 'yargs'\nimport { globalRegistry } from 'zod'\n\nconst usageMetaToOptions = (meta: UsageMeta): Options => {\n return meta\n}\n\nexport const optionsFromGlobalZodRegistry = (): Record<string, Options> => {\n const opts: Record<string, Options> = {}\n for (const schema of Object.values(globalRegistry._map)) {\n if (isUsageMeta(schema)) {\n if (schema.hidden) continue // skip hidden options\n opts[schema.title] = usageMetaToOptions(schema)\n }\n }\n return opts\n}\n","import { isDefined, isNull } from '@xylabs/typeof'\nimport { cosmiconfigSync } from 'cosmiconfig'\n\n/**\n * The name of the configuration file to search for.\n */\nconst configName = 'xyo'\n\n/**\n * The name of the section within the configuration file to parse.\n */\nconst configSection = 'xl1' // Default section in the config file\n\n/**\n * Attempts to parse the configuration from a file using cosmiconfig.\n * @returns The parsed configuration object if found and valid, otherwise undefined.\n */\nexport const tryParseConfig = (): Record<string, unknown> => {\n const explorer = cosmiconfigSync(\n configName,\n /* {\n searchPlaces: [\n 'package.json', // Looks under `xyo` key in package.json\n '.xyorc.json', // Supports common dotfile format\n 'xyo.config.json', // Supports custom-named config file\n ],\n loaders: {\n '.json': defaultLoaders['.json'],\n 'noExt': defaultLoaders['.json'],\n },\n }, */\n )\n const result = explorer.search()\n if (!isNull(result)) {\n const section = result?.config?.[configSection]\n if (isDefined(section) && typeof section === 'object') {\n return section\n }\n }\n return {}\n}\n","import net from 'node:net'\n\nexport const waitForHostPort = (host: string, port: number): Promise<void> => {\n return new Promise((resolve) => {\n const tryConnect = () => {\n const socket = new net.Socket()\n\n socket\n .setTimeout(1000)\n .once('error', () => {\n socket.destroy()\n setTimeout(tryConnect, 500) // retry after 500ms\n })\n .once('timeout', () => {\n socket.destroy()\n setTimeout(tryConnect, 500)\n })\n .connect(port, host, () => {\n socket.end()\n resolve()\n })\n }\n\n tryConnect()\n })\n}\n","import { start } from './start.ts'\n\nstart().catch((err) => {\n // If we're in development mode, log the stack trace to the console\n if (process.env.NODE_ENV === 'development') console.error('An error occurred during startup:', err)\n // eslint-disable-next-line unicorn/no-process-exit\n process.exit(1)\n})\n"],"mappings":";;;;AAAA,SAASA,cAAc;;;ACCvB,SAASC,iBAAiB;AAC1B,SAASC,aAAAA,mBAAiB;AAC1B,SAAsBC,iBAAiB;AAEvC,OAAOC,WAAW;AAClB,SAASC,eAAe;AACxB,SAASC,gBAAgB;;;ACNzB,SAASC,iBAAiB;AAQnB,SAASC,OAAOC,SAAsB;AAC3C,OAAKC,UAAUD,OAAAA;AACjB;AAFgBD;;;ACRhB,SAASG,aAAAA,kBAAiB;AAQnB,SAASC,UAAUC,SAAyB;AACjD,OAAKC,WAAUD,OAAAA;AACjB;AAFgBD;;;ACRhB,SAASG,aAAAA,kBAAiB;AAQnB,SAASC,WAAWC,SAA0B;AACnD,OAAKC,WAAUD,OAAAA;AACjB;AAFgBD;;;ACThB,SAASG,gBAAgB;AAEzB,SAASC,sBAAsB;AAE/B,SAASC,aAAa;;;ACHtB,SAASC,YAA6B;AACtC,SAASC,aAAa;AACtB,SAASC,gBAAgB;AAEzB,SAASC,MAAMC,qBAAqB;AAEpC,SAASC,iBAAiB;AAanB,IAAMC,QAAN,cAA+DC,KAAAA;EAnBtE,OAmBsEA;;;EACjDC,aAA0D,oBAAIC,IAAAA;EAC9DC,cAAsC,oBAAID,IAAAA;EAC1CE,YAAwD,oBAAIF,IAAAA;EACvEG,UAAU;EACDC;EACAC;EAEjB,YAAYC,IAAYC,cAAsB,SAASC,QAAiB;AACtE,UAAMC,SAASD,OAAOC,UAAU,IAAIC,SAASZ,KAAKa,iBAAiBC,SAAS,MAAM,IAAIL,WAAAA,KAAgBD,EAAAA,KAAO;AAC7G,UAAM;MAAE,GAAGE;MAAQC;IAAO,CAAA;AAC1B,SAAKL,eAAeG;AACpB,SAAKF,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A;AAC9C,UAAMC,UAAUvC,qBAAqBJ,aAAAA;AACrC,QAAIA,cAAckD,QAAQC,SAAS;AAEjCJ,iBAAW;QAAE,GAAGJ;QAASE,QAAQ7C;MAAc,CAAA;AAE/C,YAAMoD,gBAAgBpD,cAAckD,QAAQG,MAAMrD,cAAckD,QAAQI,IAAI;IAC9E;AAEAV,WAAO;MAAE,GAAGD;MAASE,QAAQ7C;IAAc,CAAA;AAE3C,UAAMoD,gBAAgBpD,cAAcuD,IAAIF,MAAMrD,cAAcuD,IAAID,IAAI;AAEpE,UAAMN,YAAY;MAAE,GAAGL;MAASE,QAAQ7C;IAAc,CAAA;EACxD,CAAA,EACCwD,KAAI,EACJC,MAAM,QAAQ,GAAA,EACdxD,QAAQA,OAAAA,EACRmB;AAEH,QAAMA;AACR;AAlGsBJ;;;ADrDf,IAAM0C,QAAQ,mCAAA;AACnBC,SAAO;IAAEC,OAAO;EAAK,CAAA;AACrB,QAAMC,OAAAA;AACR,GAHqB;;;AgEFrBC,MAAAA,EAAQC,MAAM,CAACC,QAAAA;AAEb,MAAIC,QAAQC,IAAIC,aAAa,cAAeC,SAAQC,MAAM,qCAAqCL,GAAAA;AAE/FC,UAAQK,KAAK,CAAA;AACf,CAAA;","names":["config","deepMerge","isDefined","ConfigZod","yargs","hideBin","ZodError","getServer","runApi","context","getServer","getServer","runBridge","context","getServer","getServer","runMempool","context","getServer","assertEx","PayloadBuilder","Mutex","Base","delay","IdLogger","span","spanRootAsync","Semaphore","Actor","Base","_intervals","Map","_semaphores","_timeouts","_active","_displayName","_id","id","displayName","params","logger","IdLogger","defaultLogger","console","name","logPrefix","registerTimer","timerName","callback","dueTimeMs","periodMs","warn","running","set","Semaphore","timeoutId","setTimeout","intervalId","setInterval","semaphore","get","has","isLocked","acquire","then","release","startTime","Date","now","duration","catch","error","finally","log","span","fn","tracer","spanAsync","spanRootAsync","start","Promise","resolve","stop","all","values","map","delay","clear","timeoutRef","entries","clearTimeout","intervalRef","clearInterval","Orchestrator","actors","keepAliveHandle","logger","running","registerActor","actor","start","push","Promise","resolve","warn","log","setInterval","stop","clearInterval","BalanceActor","Actor","_updateMutex","Mutex","params","balanceService","assertEx","balance","chainIterator","create","start","on","updateBalance","registerTimer","isLocked","runExclusive","head","PayloadBuilder","hash","balances","filterAs","assertEx","toHex","findMostRecentBlock","sortBlocks","asBlockBoundWitness","ChainHeadUpdateActor","Actor","params","chainFinalizedArchivist","assertEx","chainArchivist","chainIterator","create","start","on","data","checkInsertedForNewHead","registerTimer","pollForNewHead","candidateBlock","sortBlocks","filterAs","payloads","asBlockBoundWitness","at","updateHeadIfNewer","findMostRecentBlock","currentHead","head","candidateBlockNumber","block","candidateBlockNumberDisplay","toHex","currentBlockNumber","logger","log","updateHead","assertEx","toHex","isDefined","isUndefined","BaseBlockProducerService","createDeclarationIntent","PayloadBuilder","PayloadBundleSchema","buildTransaction","flattenHydratedBlock","flattenHydratedTransaction","SHOULD_REGISTER_REDECLARATION_INTENT_TIMER","TEN_MINUTES","ProducerActor","Actor","_lastProducedBlock","_lastRedeclarationIntent","params","producer","address","account","assertEx","balanceService","balance","chainIterator","chainStakeViewer","chainSubmissionsArchivistWrite","pendingBundledTransactionsArchivistWrite","stakeIntentService","stakeIntent","create","start","registerTimer","produceBlock","redeclareIntent","calculateBlocksUntilProducerDeclarationExpiration","currentBlock","ranges","getDeclaredCandidateRanges","lastRange","toSorted","a","b","at","currentDeclarationEnd","undefined","timeToProducerExpiration","spanAsync","headStart","Date","now","head","headDuration","logger","warn","toHex","_hash","headHash","previous","log","block","nextStart","nextBlock","next","nextDuration","displayBlockNumber","insert","flattenHydratedBlock","config","disableIntentRedeclaration","isUndefined","blocksUntilExpiration","BaseBlockProducerService","RedeclarationWindow","exp","validateCurrentBalance","error","validateCurrentStake","chain","id","redeclarationIntent","createDeclarationIntent","RedeclarationDuration","submitRedeclarationIntent","tx","buildTransaction","chainId","payloads","flattenHydratedTransaction","root","payloadBundle","PayloadBuilder","schema","PayloadBundleSchema","fields","build","isDefined","balances","currentBalance","requiredMinimumStake","getRequiredMinimumStakeForIntent","currentStake","activeByStaked","http","isDefined","sendStatus","res","status","errorCode","statusCode","writeHead","end","JSON","stringify","notFound","createHealthServer","port","statusMonitor","logger","server","http","createServer","req","url","getGlobalStatus","listen","log","initHealthEndpoints","params","config","statusReporter","healthCheckPort","producer","isDefined","undefined","assertEx","asAddress","isDefined","initTelemetry","startupSpanAsync","StepSizes","validateHydratedBlockState","readPayloadMapFromStore","CompletedStepRewardAddressValidatorFactory","DerivedReceiveAddressValidatorFactory","SelfSignerValidator","TransactionTransfersValidatorFactory","Semaphore","initArchivistSync","startupSpanAsync","Mutex","Mutex","rm","Path","LmdbArchivist","LmdbArchivistConfigSchema","getStoreDirectory","DEFAULT_STORAGE_ROOT","Path","join","process","cwd","getLocalPersistentArchivist","name","dbName","storeName","storageRoot","kind","root","LmdbArchivist","create","account","config","clearStoreOnStart","location","getStoreDirectory","schema","LmdbArchivistConfigSchema","mutex","Mutex","singleton","initLocalChainFinalizedArchivist","config","runExclusive","root","storage","getLocalPersistentArchivist","assertEx","initBridge","initBridgedArchivistModule","getUrl","Mutex","mutex","Mutex","singleton","initRemoteChainFinalizedArchivist","config","runExclusive","host","port","mempool","enabled","api","nodeUrl","getUrl","bridge","initBridge","initBridgedArchivistModule","moduleName","assertEx","mutex","Mutex","singleton","initChainFinalizedArchivist","config","logger","traceProvider","runExclusive","remote","local","Promise","all","startupSpanAsync","initRemoteChainFinalizedArchivist","initLocalChainFinalizedArchivist","initArchivistSync","Number","MAX_SAFE_INTEGER","assertEx","startupSpanAsync","Mutex","assertEx","initBridge","initBridgedArchivistModule","getUrl","Mutex","mutex","Mutex","singleton","initRemoteChainSubmissionsArchivist","config","runExclusive","host","port","mempool","enabled","api","nodeUrl","getUrl","bridge","initBridge","initBridgedArchivistModule","moduleName","assertEx","Error","mutex","Mutex","singleton","initChainSubmissionsArchivist","params","runExclusive","remote","startupSpanAsync","initRemoteChainSubmissionsArchivist","assertEx","Error","initArchivistSync","startupSpanAsync","Mutex","MemoryArchivist","MemoryArchivistConfigSchema","Mutex","mutex","Mutex","singleton","initLocalPendingTransactionsArchivist","runExclusive","MemoryArchivist","create","account","config","schema","MemoryArchivistConfigSchema","max","name","assertEx","initBridge","initBridgedArchivistModule","getUrl","Mutex","mutex","Mutex","singleton","initRemotePendingTransactionsArchivist","config","runExclusive","host","port","mempool","enabled","api","nodeUrl","getUrl","bridge","initBridge","initBridgedArchivistModule","moduleName","assertEx","mutex","Mutex","singleton","initPendingBundledTransactionsArchivist","params","runExclusive","remote","startupSpanAsync","initRemotePendingTransactionsArchivist","local","initLocalPendingTransactionsArchivist","start","next","limit","order","insert","initArchivistSync","startupSpanAsync","Mutex","MemoryArchivist","MemoryArchivistConfigSchema","Mutex","mutex","Mutex","singleton","initLocalRejectedTransactionsArchivist","runExclusive","MemoryArchivist","create","account","config","schema","MemoryArchivistConfigSchema","max","name","mutex","Mutex","singleton","initRejectedTransactionsArchivist","params","runExclusive","local","startupSpanAsync","initLocalRejectedTransactionsArchivist","assertEx","startupSpanAsync","Mutex","assertEx","Mutex","mutex","Mutex","singleton","initLocalStakeIntentStateArchivist","config","runExclusive","root","storage","getLocalPersistentArchivist","assertEx","Error","mutex","Mutex","singleton","initStakeIntentStateArchivist","params","runExclusive","local","startupSpanAsync","initLocalStakeIntentStateArchivist","assertEx","isDefined","startupSpanAsync","Mutex","isDefined","getLocalPersistentMap","Mutex","mutex","Mutex","singleton","initLocalBalanceSummaryMap","params","runExclusive","isDefined","root","config","storage","getLocalPersistentMap","mutex","Mutex","singleton","initBalanceSummaryMap","params","runExclusive","isDefined","local","startupSpanAsync","initLocalBalanceSummaryMap","isDefined","startupSpanAsync","Mutex","isDefined","getLocalPersistentMap","Mutex","mutex","Mutex","singleton","initLocalTransferSummaryMap","params","runExclusive","isDefined","root","config","storage","getLocalPersistentMap","mutex","Mutex","singleton","initTransferSummaryMap","params","runExclusive","isDefined","local","startupSpanAsync","initLocalTransferSummaryMap","isUndefined","HDWallet","ADDRESS_INDEX","generateXyoBaseWalletFromPhrase","accountServiceSingleton","initAccount","config","logger","walletPhrase","producer","mnemonic","isUndefined","warn","randomMnemonic","HDWallet","generateMnemonic","wallet","generateXyoBaseWalletFromPhrase","account","derivePath","ADDRESS_INDEX","XYO","BaseAccountBalanceService","balanceServiceSingleton","initBalanceService","params","BaseAccountBalanceService","create","MemoryChainService","assertEx","asAddress","ZERO_ADDRESS","isDefined","EvmChainService","Wallet","assertEx","assertEx","isDefined","InfuraProvider","assertEx","hexFrom","isHex","isDefined","canUseChainId","config","isDefined","evm","chainId","getChainId","assertEx","isHex","prefix","hex","hexFrom","parsed","Number","parseInt","instance","initInfuraProvider","config","providerConfig","getInfuraProviderConfig","Promise","resolve","InfuraProvider","canUseInfuraProvider","canUseChainId","isDefined","evm","infura","projectId","projectSecret","assertEx","getChainId","assertEx","isDefined","JsonRpcProvider","initJsonRpcProvider","config","providerConfig","getJsonRpcProviderConfig","Promise","resolve","JsonRpcProvider","canUseJsonRpcProvider","canUseChainId","isDefined","evm","jsonRpc","url","jsonRpcUrl","assertEx","getChainId","provider","initEvmProvider","config","canUseInfuraProvider","initInfuraProvider","canUseJsonRpcProvider","initJsonRpcProvider","assertEx","canUseEvmProvider","chainStakeServiceSingleton","canUseEvmContractChainService","config","id","chain","isDefined","ZERO_ADDRESS","canUseEvmProvider","initEvmContractChainService","account","traceProvider","meterProvider","logger","emvStakingContractAddress","assertEx","asAddress","provider","initEvmProvider","privateKey","private","hex","runner","Wallet","EvmChainService","create","chainStakeServiceSingleton","initChainService","account","config","init","name","params","canUseEvmContractChainService","initEvmContractChainService","MemoryChainService","create","assertEx","isDefined","findMostRecentBlock","buildNextBlock","createDeclarationIntent","createGenesisBlock","createBootstrapHead","account","chainService","chainId","chain","genesisBlock","createGenesisBlock","address","push","producerDeclarationPayload","createDeclarationIntent","block","producerDeclarationBlock","buildNextBlock","BridgeDestinationObservationSchema","buildNextBlock","PayloadBuilder","toHex","toHex","AttoXL1ConvertFactor","getForkBlockReward","AttoXL1ConvertFactor","xl1","getForkBlockRewardHex","toHex","ethChainId","toHex","bridgeableTokenContract","bridgeDestAddress","destConfirmation","getBridgeDestChainId","getBridgeDestToken","getBridgeDestAddress","getBridgeDestAmount","getForkBlockRewardHex","getBridgeDestConfirmation","getBridgeDestinationDetails","dest","destToken","destAddress","destAmount","getBridgeSrcChainId","chainService","chainId","getBridgeSrcAddress","account","address","getBridgeSrcToken","getBridgeSrcAmount","getForkBlockRewardHex","getBridgeSourceDetails","src","srcAddress","srcToken","srcAmount","getBridgeDestinationObservation","previousBlock","account","chainService","bridgeDestinationObservationFields","getBridgeSourceDetails","getBridgeDestinationDetails","destConfirmation","getBridgeDestConfirmation","bridgeDestinationObservation","PayloadBuilder","schema","BridgeDestinationObservationSchema","fields","build","buildNextBlock","BridgeIntentSchema","buildNextBlock","createTransferPayload","XYO_BRIDGE_ADDRESS","PayloadBuilder","getBridgeIntent","previousBlock","account","chainService","transferPayload","createTransferPayload","address","XYO_BRIDGE_ADDRESS","getForkBlockReward","nonce","Date","now","bridgeIntentFields","getBridgeSourceDetails","getBridgeDestinationDetails","bridgeIntent","PayloadBuilder","schema","BridgeIntentSchema","fields","build","buildNextBlock","BridgeSourceObservationSchema","buildNextBlock","PayloadBuilder","getBridgeSourceObservation","previousBlock","account","chainService","srcTxHash","_hash","bridgeSourceObservationFields","getBridgeSourceDetails","getBridgeDestinationDetails","srcConfirmation","bridgeSourceObservation","PayloadBuilder","schema","BridgeSourceObservationSchema","fields","build","buildNextBlock","AttoXL1","buildBlock","XYO_STEP_REWARD_ADDRESS","getFirstBlockForNewChain","forkBlock","account","chainService","_hash","previousBlockHash","block","previousBlockNumber","step_hashes","previousStepHashes","protocol","chainId","options","blockPayloads","signers","txs","chainStepRewardAddress","XYO_STEP_REWARD_ADDRESS","stepRewardPoolBalance","AttoXL1","buildBlock","createForkedHead","forkFromBlock","account","chainService","chain","firstBlockForNewChain","getFirstBlockForNewChain","push","bridgeIntent","getBridgeIntent","bridgeSourceObservation","getBridgeSourceObservation","bridgeDestinationObservation","getBridgeDestinationObservation","asHash","hexFromBigInt","isDefined","isBlockBoundWitnessWithHashMeta","getForkFromBlock","head","chainService","chainArchivist","chain","chainId","forkedAtBigInt","forkedAtHash","forkedAtHex","hexFromBigInt","asHash","isDefined","forkedAtBlock","get","forkedChainId","forkedAtBlockNumber","Number","isBlockBoundWitnessWithHashMeta","block","delay","flattenHydratedBlock","submitNewChain","chain","chainArchivist","chainSubmissionsArchivistWrite","block","bw","insert","flattenHydratedBlock","result","get","_hash","length","delay","headSingleton","initHead","params","account","chainArchivist","chainSubmissionsArchivistWrite","chainService","head","findMostRecentBlock","forkFromBlock","getForkFromBlock","isDefined","chain","createForkedHead","submitNewChain","newBlock","assertEx","at","Error","createBootstrapHead","BaseElectionService","ChainBlockNumberIterationService","XyoStakeIntentService","chainIteratorServiceSingleton","stakeIntentServiceSingleton","electionServiceSingleton","initChainIterator","params","ChainBlockNumberIterationService","create","initStakeIntentService","XyoStakeIntentService","initElectionService","BaseElectionService","BasePendingTransactionsService","serviceSingleton","initPendingTransactions","params","BasePendingTransactionsService","create","BaseBlockProducerService","serviceSingleton","initBlockProducer","params","BaseBlockProducerService","create","assertEx","EvmBlockRewardService","MemoryBlockRewardService","rewardServiceSingleton","initBlockRewardService","params","config","canUseEvmBlockRewardService","initEvmBlockRewardService","initXyoBlockRewardService","MemoryBlockRewardService","create","canUseEvmProvider","account","paramsAccount","assertEx","provider","initEvmProvider","evmBlockRewardServiceParams","EvmBlockRewardService","BaseTimeSyncService","timeSyncServiceSingleton","initTimeService","chainArchivist","chainIterator","config","logger","meterProvider","traceProvider","ethProvider","canUseEvmProvider","initEvmProvider","undefined","BaseTimeSyncService","create","BaseAccountTransfersService","transferServiceSingleton","initTransferService","params","BaseAccountTransfersService","create","LoggerStatusReporter","logger","statusMap","report","name","status","progress","starting","Object","entries","map","value","reduce","a","b","started","info","statusPriority","error","stopped","stopping","creating","created","starting","started","SENTINEL_STATUS","reduceToMinimumStatus","statuses","minStatus","minPriority","Infinity","status","priority","RuntimeStatusMonitor","LoggerStatusReporter","globalTransitions","transitions","getGlobalStatus","Object","keys","statusMap","length","values","getStatus","name","onGlobalTransition","match","handler","push","onTransition","report","progress","previous","previousGlobal","runTransitions","globalStatus","prev","next","from","to","matchName","undefined","isStartable","value","isDefined","start","initServices","context","config","logger","statusReporter","RuntimeStatusMonitor","onGlobalTransition","to","log","error","process","exit","startupSpanAsync","initHealthEndpoints","otlpEndpoint","telemetry","otel","telemetryConfig","attributes","serviceName","serviceVersion","metricsConfig","endpoint","port","traceProvider","meterProvider","account","Promise","all","initTelemetry","initAccount","allowedRewardRedeemers","validation","allowedRewardEscrowAccountSigners","initParams","chainArchivist","pendingBundledTransactionsArchivist","pendingBundledTransactionsArchivistWrite","rejectedTransactionsArchivist","chainSubmissionsArchivistWrite","stakeIntentStateArchivist","chainService","balanceSummaryMap","transferSummaryMap","initChainFinalizedArchivist","initPendingBundledTransactionsArchivist","initRejectedTransactionsArchivist","initChainSubmissionsArchivist","initStakeIntentStateArchivist","initChainService","name","initBalanceSummaryMap","initTransferSummaryMap","chainId","chainMap","readPayloadMapFromStore","chainContractViewer","chainStakeViewer","chainStaker","head","initHead","additionalPendingTransactionValidators","TransactionTransfersValidatorFactory","SelfSignerValidator","CompletedStepRewardAddressValidatorFactory","DerivedReceiveAddressValidatorFactory","pendingTransactionsService","rewardService","chainIterator","initPendingTransactions","initBlockRewardService","initChainIterator","balanceService","initBalanceService","stepSemaphores","StepSizes","map","Semaphore","store","_hash","block","summaryMap","initTransferService","stakeIntentService","time","initStakeIntentService","initTimeService","electionService","initElectionService","validatorParams","validateHydratedBlockState","rewardAddress","producer","assertEx","asAddress","address","producerParams","initBlockProducer","result","balance","election","pendingTransactions","reward","stakeIntent","startableServices","Object","values","filter","service","every","Boolean","runProducer","context","config","logger","orchestrator","log","services","initServices","params","chainHeadUpdate","ChainHeadUpdateActor","create","name","balances","BalanceActor","producer","ProducerActor","actors","actor","registerActor","start","getServer","runRewardRedemptionApi","context","getServer","XL1LogoColorizedAscii","Base","ConsoleLogger","LogLevel","SilentLogger","isDefined","initLogger","config","logger","silent","SilentLogger","level","isDefined","logLevel","parsed","LogLevel","toLowerCase","ConsoleLogger","Base","defaultLogger","isUsageMeta","globalRegistry","usageMetaToOptions","meta","optionsFromGlobalZodRegistry","opts","schema","Object","values","globalRegistry","_map","isUsageMeta","hidden","title","isDefined","isNull","cosmiconfigSync","configName","configSection","tryParseConfig","explorer","cosmiconfigSync","result","search","isNull","section","config","isDefined","net","waitForHostPort","host","port","Promise","resolve","tryConnect","socket","net","Socket","setTimeout","once","destroy","connect","end","configuration","version","isDefined","__VERSION__","getContextFromConfig","logger","initLogger","orchestrator","Orchestrator","process","on","log","stop","exit","err","error","runCLI","y","yargs","hideBin","argv","usage","XL1LogoColorizedAscii","parserConfiguration","env","scriptName","middleware","parsedConfigFile","tryParseConfig","parsedConfigArgs","mergedConfig","deepMerge","ConfigZod","parse","ZodError","console","message","Error","options","optionsFromGlobalZodRegistry","wrap","terminalWidth","command","context","runApi","config","runBridge","runMempool","runProducer","runRewardRedemptionApi","mempool","enabled","waitForHostPort","host","port","api","help","alias","start","config","quiet","runCLI","start","catch","err","process","env","NODE_ENV","console","error","exit"]}
1
+ {"version":3,"sources":["../../src/start.ts","../../src/runCLI.ts","../../src/commands/api/runApi.ts","../../src/commands/bridge/runBridge.ts","../../src/commands/mempool/runMempool.ts","../../src/orchestration/actor/implementation/BalanceActor.ts","../../src/orchestration/actor/model/Actor.ts","../../src/orchestration/actor/model/Orchestrator.ts","../../src/orchestration/actor/implementation/ChainHeadUpdateActor.ts","../../src/orchestration/actor/implementation/ProducerActor.ts","../../src/orchestration/health/initHealthEndpoints.ts","../../src/orchestration/initServices.ts","../../src/orchestration/archivists/ChainFinalized/archivist.ts","../../src/orchestration/archivists/ChainFinalized/local.ts","../../src/orchestration/archivists/lib/localPersistentArchivist.ts","../../src/orchestration/archivists/ChainFinalized/remote.ts","../../src/orchestration/archivists/ChainSubmissions/archivist.ts","../../src/orchestration/archivists/ChainSubmissions/remote.ts","../../src/orchestration/archivists/PendingTransactions/archivist.ts","../../src/orchestration/archivists/PendingTransactions/local.ts","../../src/orchestration/archivists/PendingTransactions/remote.ts","../../src/orchestration/archivists/RejectedTransactions/archivist.ts","../../src/orchestration/archivists/RejectedTransactions/local.ts","../../src/orchestration/archivists/StakeIntentState/archivist.ts","../../src/orchestration/archivists/StakeIntentState/local.ts","../../src/orchestration/map/BalanceSummary/initBalanceSummaryMap.ts","../../src/orchestration/map/BalanceSummary/initLocalBalanceSummaryMap.ts","../../src/orchestration/map/BalanceSummary/initTransferSummaryMap.ts","../../src/orchestration/map/BalanceSummary/initLocalTransferSummaryMap.ts","../../src/orchestration/services/implementation/account.ts","../../src/orchestration/services/implementation/balance.ts","../../src/orchestration/services/implementation/chain/index.ts","../../src/orchestration/services/implementation/chain/evm.ts","../../src/orchestration/services/implementation/evm/initEvmProvider.ts","../../src/orchestration/services/implementation/evm/initInfuraProvider.ts","../../src/orchestration/services/implementation/evm/initChainId.ts","../../src/orchestration/services/implementation/evm/initJsonRpcProvider.ts","../../src/orchestration/services/implementation/head/head.ts","../../src/orchestration/services/implementation/head/createBootstrapHead.ts","../../src/orchestration/services/implementation/head/createForkedHead/getBridgeDestinationObservation.ts","../../src/orchestration/services/implementation/head/createForkedHead/config/getBridgeDestinationDetails.ts","../../src/orchestration/services/implementation/head/createForkedHead/config/getForkDetails.ts","../../src/orchestration/services/implementation/head/createForkedHead/config/getBridgeSourceDetails.ts","../../src/orchestration/services/implementation/head/createForkedHead/getBridgeIntent.ts","../../src/orchestration/services/implementation/head/createForkedHead/getBridgeSourceObservation.ts","../../src/orchestration/services/implementation/head/createForkedHead/getFirstBlockForNewChain.ts","../../src/orchestration/services/implementation/head/createForkedHead/createForkedHead.ts","../../src/orchestration/services/implementation/head/getForkFromBlock.ts","../../src/orchestration/services/implementation/head/submitNewChain.ts","../../src/orchestration/services/implementation/iterator.ts","../../src/orchestration/services/implementation/pendingTransactions.ts","../../src/orchestration/services/implementation/producer.ts","../../src/orchestration/services/implementation/reward.ts","../../src/orchestration/services/implementation/time.ts","../../src/orchestration/services/implementation/transfer.ts","../../src/orchestration/status/ServiceStatus.ts","../../src/orchestration/status/RuntimeStatusMonitor.ts","../../src/commands/producer/runProducer.ts","../../src/commands/rewardRedemption/runRewardRedemptionApi.ts","../../src/images.ts","../../src/initLogger.ts","../../src/optionsFromGlobalZodRegistry.ts","../../src/tryParseConfig.ts","../../src/waitForHostPort.ts","../../src/xl1.ts"],"sourcesContent":["import { config } from 'dotenv'\n\nimport { runCLI } from './runCLI.ts'\n\nexport const start = async () => {\n config({ quiet: true })\n await runCLI()\n}\n","import type { Logger } from '@xylabs/logger'\nimport { deepMerge } from '@xylabs/object'\nimport { isDefined } from '@xylabs/typeof'\nimport { type Config, ConfigZod } from '@xyo-network/xl1-protocol-sdk'\nimport type { Argv } from 'yargs'\nimport yargs from 'yargs'\nimport { hideBin } from 'yargs/helpers'\nimport { ZodError } from 'zod'\n\nimport {\n runApi, runBridge, runMempool, runProducer, runRewardRedemptionApi,\n} from './commands/index.ts'\nimport { XL1LogoColorizedAscii } from './images.ts'\nimport { initLogger } from './initLogger.ts'\nimport { optionsFromGlobalZodRegistry } from './optionsFromGlobalZodRegistry.ts'\nimport { Orchestrator } from './orchestration/index.ts'\nimport { tryParseConfig } from './tryParseConfig.ts'\nimport { waitForHostPort } from './waitForHostPort.ts'\n\n/** Version string injected by Rollup at build time. */\ndeclare const __VERSION__: string\n\ninterface RunCliContext {\n logger: Logger\n orchestrator: Orchestrator\n}\n\n/**\n * The configuration that will be used throughout the CLI.\n * This is materialized after parsing the command-line arguments,\n * environment variables, and defaults.\n */\nlet configuration: Config\n\nconst version = isDefined(__VERSION__) ? __VERSION__ : 'unknown'\n\nconst getContextFromConfig = (configuration: Config): RunCliContext => {\n const logger = initLogger(configuration)\n const orchestrator = new Orchestrator(logger)\n // Handle cancellation (Ctrl+C)\n process.on('SIGINT', () => {\n void (async () => {\n try {\n logger.log('\\nSIGINT received. Attempting graceful shutdown...')\n await orchestrator?.stop()\n logger.log('Orchestrator stopped, exiting now.')\n process.exit(0)\n } catch (err) {\n logger.error('Error stopping orchestrator:', err)\n process.exit(1)\n }\n })()\n })\n return { logger, orchestrator }\n}\n\n// Main entry point\nexport async function runCLI() {\n // Parse command-line arguments using Yargs\n const y = yargs(hideBin(process.argv)) as Argv<Config>\n const argv = y\n .usage(`\nšŸš€ XL1 Node CLI (${version})\n${XL1LogoColorizedAscii}\nRun various components of the XL1 ecosystem.\n\nUsage:\n$0 <command> [options]`)\n .parserConfiguration({\n 'dot-notation': true, // foo.bar → { foo: { bar } }\n 'parse-numbers': false, // Don't auto-parse numbers to allow strings like \"0x1\"\n 'populate--': true, // Populate -- with all options so we can detected user-supplied vs defaults\n })\n .env('XL1')\n .scriptName('xl1')\n .middleware((argv) => {\n try {\n // Parse the various config sources\n const parsedConfigFile = tryParseConfig() // Config file\n const parsedConfigArgs = argv // Command-line arguments & ENV VARs\n // Deep merge with precedence\n // TODO: Would like precedence to be defaults < file < ENV < CLI Args\n // but there is currently no way to determine which are defaults vs\n // user-supplied CLI Args since we set the CLI args to the defaults\n // and receive a flattened object. We might need to manually invoke\n // the parser without the defaults to achieve this.\n const mergedConfig = deepMerge(parsedConfigArgs, parsedConfigFile)\n // Validate the merged configuration\n configuration = ConfigZod.parse(mergedConfig)\n } catch (err) {\n if (err instanceof ZodError) {\n console.error(`${err.message}`)\n }\n throw new Error('Invalid configuration')\n }\n })\n .options(optionsFromGlobalZodRegistry())\n // .commandDir('./command/commands', opts) // Not yet supported for ESM\n .wrap(y.terminalWidth())\n .command('api', 'Run a XL1 API Node', (yargs) => {\n return yargs\n .command('$0', 'Run a XL1 API Node', () => {}, () => {\n const context = getContextFromConfig(configuration)\n runApi({ ...context, config: configuration })\n })\n })\n .command('bridge', 'Run a XL1 Bridge Node', (yargs) => {\n return yargs\n .command('$0', 'Run a XL1 Bridge Node', () => {}, () => {\n const context = getContextFromConfig(configuration)\n runBridge({ ...context, config: configuration })\n })\n })\n .command('mempool', 'Run a XL1 Mempool Node', (yargs) => {\n return yargs\n .command('$0', 'Run a XL1 Mempool Node', () => {}, () => {\n const context = getContextFromConfig(configuration)\n runMempool({ ...context, config: configuration })\n })\n })\n .command('producer', 'Run a XL1 Producer Node', (yargs) => {\n return yargs\n .command('$0', 'Run a XL1 Producer Node', () => {}, async () => {\n const context = getContextFromConfig(configuration)\n await runProducer({ ...context, config: configuration })\n })\n })\n .command('reward-redemption-api', 'Run a XL1 Rewards Redemption API Node', (yargs) => {\n return yargs\n .command('$0', 'Run a XL1 Rewards Redemption API Node', () => {}, () => {\n const context = getContextFromConfig(configuration)\n runRewardRedemptionApi({ ...context, config: configuration })\n })\n })\n .command('$0', 'Run a full XL1 Node', () => {}, async () => {\n const context = getContextFromConfig(configuration)\n if (configuration.mempool.enabled) {\n // Start Mempool but do not block\n runMempool({ ...context, config: configuration })\n // Wait for Mempool to be ready\n await waitForHostPort(configuration.mempool.host, configuration.mempool.port)\n }\n // Start API but do not block\n runApi({ ...context, config: configuration })\n // Wait for API to be ready\n await waitForHostPort(configuration.api.host, configuration.api.port)\n // Start Producer and block on it\n await runProducer({ ...context, config: configuration })\n })\n .help()\n .alias('help', 'h')\n .version(version)\n .argv\n\n await argv\n}\n","import type { Logger } from '@xylabs/logger'\nimport { getServer } from '@xyo-network/chain-api'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\n\ninterface RunApiContext {\n config: Config\n logger?: Logger\n}\n\nexport function runApi(context: RunApiContext) {\n void getServer(context)\n}\n","import type { Logger } from '@xylabs/logger'\nimport { getServer } from '@xyo-network/chain-bridge'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\n\ninterface RunBridgeContext {\n config: Config\n logger?: Logger\n}\n\nexport function runBridge(context: RunBridgeContext) {\n void getServer(context)\n}\n","import type { Logger } from '@xylabs/logger'\nimport { getServer } from '@xyo-network/chain-mempool'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\n\ninterface RunMempoolContext {\n config: Config\n logger?: Logger\n}\n\nexport function runMempool(context: RunMempoolContext) {\n void getServer(context)\n}\n","import { assertEx } from '@xylabs/assert'\nimport type { Promisable } from '@xylabs/promise'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport type { ChainServiceCollectionV2, Config } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nimport type { ActorParams } from '../model/index.ts'\nimport { Actor } from '../model/index.ts'\n\nexport type BalanceActorParams = ActorParams<\n Pick<ChainServiceCollectionV2, 'balance' | 'chainIterator'>\n & { config: Config }>\n\nexport class BalanceActor extends Actor<BalanceActorParams> {\n protected _updateMutex = new Mutex()\n\n protected constructor(params: BalanceActorParams) {\n super('BalanceActor', 'Balance', params)\n }\n\n protected get balanceService() {\n return assertEx(this.params.balance, () => 'balanceService not set')\n }\n\n protected get chainIterator() {\n return assertEx(this.params.chainIterator, () => 'chainIterator not set')\n }\n\n static create(params: BalanceActorParams): Promisable<BalanceActor> {\n return new BalanceActor(params)\n }\n\n override async start(): Promise<void> {\n await super.start()\n this.chainIterator.on('headUpdate', async () => {\n await this.updateBalance()\n })\n this.registerTimer('BalanceTimer', async () => {\n await this.updateBalance()\n }, 1000, 10_000/* 1000 */)\n }\n\n protected async updateBalance(): Promise<void> {\n if (this._updateMutex.isLocked()) return\n await this._updateMutex.runExclusive(async () => {\n const head = await PayloadBuilder.hash(await this.chainIterator.head())\n await this.balanceService.balances(head, [])\n })\n }\n}\n","import type { TracerProvider } from '@opentelemetry/api'\nimport { Base, type BaseParams } from '@xylabs/base'\nimport { delay } from '@xylabs/delay'\nimport { IdLogger } from '@xylabs/logger'\nimport type { EmptyObject } from '@xylabs/object'\nimport { span, spanRootAsync } from '@xylabs/telemetry'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport { Semaphore } from 'async-mutex'\n\nexport interface IActor {\n start(): Promise<void>\n stop(): Promise<void>\n}\n\nexport type ActorParams<T extends EmptyObject | void = void> = BaseParams<{\n config: Config\n name: string\n traceProvider?: TracerProvider\n} & (T extends void ? EmptyObject : T)>\n\nexport class Actor<TParams extends ActorParams = ActorParams> extends Base<TParams> implements IActor {\n protected readonly _intervals: Map<string, ReturnType<typeof setInterval>> = new Map()\n protected readonly _semaphores: Map<string, Semaphore> = new Map()\n protected readonly _timeouts: Map<string, ReturnType<typeof setTimeout>> = new Map()\n private _active = false\n private readonly _displayName: string\n private readonly _id: string\n\n constructor(id: string, displayName: string = 'Actor', params: TParams) {\n const logger = params.logger ?? new IdLogger(Base.defaultLogger ?? console, () => `[${displayName} (${id})] `)\n super({ ...params, logger })\n this._displayName = displayName\n this._id = id\n }\n\n get displayName() {\n return this._displayName\n }\n\n get id() {\n return this._id\n }\n\n get name() {\n return this.params.name\n }\n\n protected get logPrefix() {\n return `[${this.displayName} (${this.id})] `\n }\n\n /**\n * The timer runs until the actor is deactivated (or you manually stop it).\n */\n registerTimer(timerName: string, callback: () => Promise<void>, dueTimeMs: number, periodMs: number) {\n if (!this._active) {\n this.logger?.warn(\n `Cannot register timer '${timerName}' because actor is not active.`,\n )\n return\n }\n\n let running = false\n\n this._semaphores.set(timerName, new Semaphore(1))\n\n const timeoutId = setTimeout(() => {\n const intervalId = setInterval(() => {\n const semaphore = this._semaphores.get(timerName)\n if (!this._active || !this._intervals.has(timerName) || !semaphore || running) return\n if (semaphore.isLocked()) {\n this.logger?.warn(\n `Skipping timer '${this.name}:${timerName}' execution because previous execution is still running.`,\n )\n return\n }\n semaphore.acquire().then(([, release]) => {\n const startTime = Date.now()\n running = true\n callback()\n .then(() => {\n const duration = Date.now() - startTime\n if (duration > periodMs) {\n this.logger?.warn(\n `Timer '${this.name}:${timerName}' execution took longer (${duration}ms) than the period (${periodMs}ms).`,\n )\n } else if (duration > 5000) {\n this.logger?.warn(\n `Timer '${this.name}:${timerName}' execution took longer (${duration}ms) than 5000ms.`,\n )\n }\n })\n .catch((error) => {\n this.logger?.error(`Error in timer '${this.name}:${timerName}': ${error}`)\n })\n .finally(() => {\n release()\n running = false\n })\n }).catch((error) => {\n this.logger?.error(`Error acquiring semaphore for timer '${this.name}:${timerName}': ${error}`)\n })\n }, periodMs)\n\n // store interval so we can clear it on stop()\n this._intervals.set(timerName, intervalId)\n }, dueTimeMs)\n\n // store timeout so we can clear it on stop() if interval hasn't started yet\n this._timeouts.set(timerName, timeoutId)\n\n this.logger?.log(\n `Timer '${this.name}:${timerName}' registered: first call after ${dueTimeMs}ms, recurring every ${periodMs}ms.`,\n )\n }\n\n span<T>(name: string, fn: () => T): T {\n return span(`${this.name}:${name}`, fn, this.tracer)\n }\n\n async spanAsync<T>(name: string, fn: () => Promise<T>): Promise<T> {\n return await spanRootAsync(`${this.name}:${name}`, fn, this.tracer)\n }\n\n /**\n * Called by the Orchestrator when the actor is activated.\n */\n async start() {\n await Promise.resolve()\n this._active = true\n this.logger?.log('Started.')\n }\n\n /**\n * Called by the Orchestrator when the actor is deactivated.\n * Stop all running timers.\n */\n async stop() {\n await Promise.resolve()\n this._active = false\n this.logger?.log('Stopping all timers...')\n\n // wait for all semaphores to be free and acquire them to prevent new tasks from starting\n await Promise.all(\n [...this._semaphores.values()].map(async (semaphore) => {\n // Wait for any running tasks to complete\n while (semaphore.isLocked()) {\n this.logger?.log('Waiting for running timer task to complete...')\n await delay(500)\n }\n await semaphore.acquire()\n }),\n )\n\n this._semaphores.clear()\n\n for (const [, timeoutRef] of this._timeouts.entries()) {\n clearTimeout(timeoutRef)\n }\n this._timeouts.clear()\n\n for (const [, intervalRef] of this._intervals.entries()) {\n clearInterval(intervalRef)\n }\n this._intervals.clear()\n\n this.logger?.log('Stopped.')\n }\n}\n","import type { Logger } from '@xylabs/logger'\n\nimport type { IActor } from './Actor.ts'\n\nexport interface IOrchestrator {\n start(): Promise<void>\n stop(): Promise<void>\n}\n\nexport class Orchestrator implements IOrchestrator {\n protected actors: IActor[] = []\n protected keepAliveHandle: NodeJS.Timeout | null = null\n protected readonly logger?: Logger\n protected running = false\n\n constructor(logger?: Logger) {\n this.logger = logger\n }\n\n /**\n * Registers an actor.\n * (We won't activate the actor until `start()` is called.)\n */\n async registerActor(actor: IActor) {\n if (this.running) {\n // If the orchestrator is already running, activate the actor immediately\n await actor.start()\n }\n this.actors.push(actor)\n }\n\n /**\n * Starts the orchestrator: activates all actors.\n */\n async start() {\n await Promise.resolve()\n if (this.running) {\n this.logger?.warn('[Orchestrator] Already started.')\n return\n }\n\n this.logger?.log('[Orchestrator] Starting...')\n this.running = true\n for (const actor of this.actors) {\n await actor.start()\n }\n // This interval will fire every 24.8 days (2^31 - 1 ms), effectively never finishing\n this.keepAliveHandle = setInterval(() => {\n // No-op\n }, 2_147_483_647)\n }\n\n /**\n * Stops the orchestrator: deactivates all actors.\n */\n async stop() {\n await Promise.resolve()\n if (!this.running) {\n this.logger?.log('[Orchestrator] Already stopped.')\n return\n }\n\n this.logger?.log('[Orchestrator] Stopping...')\n for (const actor of this.actors) {\n await actor.stop()\n }\n this.running = false\n if (this.keepAliveHandle) clearInterval(this.keepAliveHandle)\n this.logger?.log('[Orchestrator] Stopped...')\n }\n}\n","import { filterAs } from '@xylabs/array'\nimport { assertEx } from '@xylabs/assert'\nimport { toHex } from '@xylabs/hex'\nimport type { Promisable } from '@xylabs/promise'\nimport { findMostRecentBlock, sortBlocks } from '@xyo-network/chain-sdk'\nimport type { Payload } from '@xyo-network/payload-model'\nimport type { BlockBoundWitness } from '@xyo-network/xl1-protocol'\nimport { asBlockBoundWitness } from '@xyo-network/xl1-protocol'\nimport type { ChainServiceCollectionV2, Config } from '@xyo-network/xl1-protocol-sdk'\n\nimport type { ActorParams } from '../model/index.ts'\nimport { Actor } from '../model/index.ts'\n\nexport type ChainHeadUpdateActorParams = ActorParams<Pick<ChainServiceCollectionV2, 'chainIterator' | 'chainArchivist'> & { config: Config }>\n\nexport class ChainHeadUpdateActor extends Actor<ChainHeadUpdateActorParams> {\n protected constructor(params: ChainHeadUpdateActorParams) {\n super('ChainHeadUpdate', 'ChainHeadUpdate', params)\n }\n\n protected get chainFinalizedArchivist() {\n return assertEx(this.params.chainArchivist, () => 'ChainArchivist not set')\n }\n\n protected get chainIterator() {\n return assertEx(this.params.chainIterator, () => 'chainIterator not set')\n }\n\n static create(params: ChainHeadUpdateActorParams): Promisable<ChainHeadUpdateActor> {\n return new ChainHeadUpdateActor(params)\n }\n\n override async start(): Promise<void> {\n await super.start()\n // Register event handler on all insert event to check for new head\n this.chainFinalizedArchivist.on('inserted', async (data: { payloads: Payload[] }) => {\n await this.checkInsertedForNewHead(data)\n })\n // Poll in case we missed an event\n this.registerTimer('ChainHeadUpdateTimer', async () => await this.pollForNewHead(), 0, 2500/* 250 */)\n }\n\n private async checkInsertedForNewHead(data: { payloads: Payload[] }) {\n const candidateBlock = sortBlocks(filterAs(data.payloads, asBlockBoundWitness)).at(-1)\n await this.updateHeadIfNewer(candidateBlock)\n }\n\n private async pollForNewHead() {\n const candidateBlock = await findMostRecentBlock(this.chainFinalizedArchivist)\n await this.updateHeadIfNewer(candidateBlock)\n }\n\n private async updateHeadIfNewer(candidateBlock?: BlockBoundWitness) {\n if (!candidateBlock) return\n const currentHead = await this.chainIterator.head()\n const candidateBlockNumber = candidateBlock.block\n const candidateBlockNumberDisplay = `0x${toHex(candidateBlockNumber)}`\n const currentBlockNumber = currentHead?.block ?? -1\n if (candidateBlockNumber > currentBlockNumber) {\n this.logger?.log('Found more recent head:', candidateBlockNumber, candidateBlockNumberDisplay)\n await this.chainIterator.updateHead(candidateBlock)\n this.logger?.log('Updated head:', candidateBlockNumber, candidateBlockNumberDisplay)\n }\n }\n}\n","import { assertEx } from '@xylabs/assert'\nimport { toHex } from '@xylabs/hex'\nimport type { Promisable } from '@xylabs/promise'\nimport { isDefined, isUndefined } from '@xylabs/typeof'\nimport { BaseBlockProducerService, createDeclarationIntent } from '@xyo-network/chain-sdk'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport type { PayloadBundle } from '@xyo-network/payload-model'\nimport { PayloadBundleSchema } from '@xyo-network/payload-model'\nimport type { ChainStakeIntent, HydratedBlock } from '@xyo-network/xl1-protocol'\nimport type { ChainServiceCollectionV2, Config } from '@xyo-network/xl1-protocol-sdk'\nimport {\n buildTransaction, flattenHydratedBlock, flattenHydratedTransaction,\n} from '@xyo-network/xl1-protocol-sdk'\n\nimport type { ActorParams } from '../model/index.ts'\nimport { Actor } from '../model/index.ts'\n\nexport type ProducerActorParams = ActorParams<\n Pick<ChainServiceCollectionV2,\n 'account'\n | 'balance'\n | 'chainIterator'\n | 'chainStakeViewer'\n | 'chainSubmissionsArchivistWrite'\n | 'pendingBundledTransactionsArchivistWrite'\n | 'producer'\n | 'stakeIntent'\n > & {\n config: Config\n }>\n\nconst SHOULD_REGISTER_REDECLARATION_INTENT_TIMER = true\nconst TEN_MINUTES = 10 * 60 * 1000 // 10 minutes in milliseconds\n\nexport class ProducerActor extends Actor<ProducerActorParams> {\n protected _lastProducedBlock: HydratedBlock | undefined\n protected _lastRedeclarationIntent: ChainStakeIntent | undefined\n\n protected constructor(params: ProducerActorParams) {\n super(params.producer.address, 'Producer', params)\n }\n\n protected get account() {\n return assertEx(this.params.account, () => 'account not set')\n }\n\n protected get balanceService() {\n return assertEx(this.params.balance, () => 'balanceService not set')\n }\n\n protected get chainIterator() {\n return assertEx(this.params.chainIterator, () => 'chainIterator not set')\n }\n\n protected get chainStakeViewer() {\n return assertEx(this.params.chainStakeViewer, () => 'chainStakeViewer not set')\n }\n\n protected get chainSubmissionsArchivistWrite() {\n return assertEx(this.params.chainSubmissionsArchivistWrite, () => 'chainSubmissionsArchivistWrite not set')\n }\n\n protected get pendingBundledTransactionsArchivistWrite() {\n return assertEx(this.params.pendingBundledTransactionsArchivistWrite, () => 'pendingBundledTransactionsArchivistWrite not set')\n }\n\n protected get producer() {\n return assertEx(this.params.producer, () => 'producer not set')\n }\n\n protected get stakeIntentService() {\n return assertEx(this.params.stakeIntent, () => 'stakeIntentService not set')\n }\n\n static create(params: ProducerActorParams): Promisable<ProducerActor> {\n return new ProducerActor(params)\n }\n\n override async start(): Promise<void> {\n await super.start()\n // Register a timer to check if we should produce a block\n this.registerTimer('BlockProductionTimer', async () => {\n await this.produceBlock()\n }, 100, 1500/* 500 */)\n\n if (SHOULD_REGISTER_REDECLARATION_INTENT_TIMER) {\n // Register a timer to check if we should redeclare the producer\n this.registerTimer('ProducerRedeclarationTimer', async () => {\n await this.redeclareIntent()\n }, TEN_MINUTES, TEN_MINUTES)\n }\n }\n\n protected async calculateBlocksUntilProducerDeclarationExpiration(currentBlock: number): Promise<number> {\n // Decide if we need to redeclare intent\n const ranges = await this.stakeIntentService.getDeclaredCandidateRanges(this.account.address, 'producer')\n // TODO: This doesn't handle the case where the producer had declared a range for the future\n // but we're in a range that's not the future\n // Sort in ascending order based on ending range to get range with highest ending block\n const lastRange = ranges.toSorted((a, b) => a[1] > b[1] ? 1 : -1).at(-1)\n\n // Use the most recent range's end block as the current declaration end OR\n const [, currentDeclarationEnd] = lastRange\n // If we have no ranges, we need to declare intent, so use the current block\n ?? [undefined, currentBlock]\n\n // Calculate the time until the producer's declaration expires\n const timeToProducerExpiration = currentDeclarationEnd - currentBlock\n return timeToProducerExpiration\n }\n\n protected async produceBlock(): Promise<void> {\n await this.spanAsync('produceBlock', async () => {\n // Get the updated head\n const headStart = Date.now()\n const head = await this.chainIterator.head()\n const headDuration = Date.now() - headStart\n if (headDuration > 500) {\n this.logger?.warn(`[Slow] Fetched head in ${headDuration}ms: 0x${toHex(head._hash)}`)\n }\n // Check if we've already produced the next block for this head\n const headHash = head._hash\n // If our last produced block was the next block for the current head, we do not\n // need to produce another. This prevents duplicate blocks from being produced\n if (this._lastProducedBlock && this._lastProducedBlock[0].previous === headHash) {\n this.logger?.log('Block already produced:', `0x${toHex(this._lastProducedBlock[0].block)}`)\n } else {\n // Produce the next block\n const nextStart = Date.now()\n const nextBlock = await this.producer.next(head)\n const nextDuration = Date.now() - nextStart\n if (nextDuration > 1000) {\n this.logger?.warn(`[Slow] Generated next block in ${nextDuration}ms, block: ${nextBlock?.[0]._hash}`)\n }\n // If it was produced\n if (nextBlock) {\n const displayBlockNumber = `0x${toHex(nextBlock[0].block)}`\n this.logger?.log('Produced block:', displayBlockNumber)\n // Insert the block into the chain\n await this.chainSubmissionsArchivistWrite.insert(flattenHydratedBlock(nextBlock))\n this.logger?.log('Published block:', displayBlockNumber)\n // Record that we have produced a block so we do not produce it again\n this._lastProducedBlock = nextBlock\n }\n }\n })\n }\n\n protected async redeclareIntent(): Promise<void> {\n await this.spanAsync('redeclareIntent', async () => {\n // Decide if we should redeclare intent\n if (this.params.config.producer.disableIntentRedeclaration) return\n\n // Get the current block\n const head = await this.chainIterator.head()\n if (isUndefined(head)) return\n const currentBlock = head.block\n\n // Calculate the time until the producer's declaration expires\n const blocksUntilExpiration = await this.calculateBlocksUntilProducerDeclarationExpiration(currentBlock)\n\n // Allow the producer time to redeclare itself via block production\n // (for free) before submitting a redeclaration intent transaction.\n if (blocksUntilExpiration > BaseBlockProducerService.RedeclarationWindow * 0.1) {\n // Clear any previous redeclaration intent\n this._lastRedeclarationIntent = undefined\n // No need to redeclare yet\n return\n }\n\n // If we already have a valid redeclaration intent, do not create another\n // unless it has expired.\n if (this._lastRedeclarationIntent) {\n // Check if the last redeclaration intent is still valid\n if (this._lastRedeclarationIntent.exp > currentBlock) return\n // If it has expired, clear the last redeclaration intent\n this._lastRedeclarationIntent = undefined\n }\n\n // Check if we have a valid balance before declaring intent\n if (!await this.validateCurrentBalance()) {\n this.logger?.error(\n `Add balance to address ${this.account.address} for the producer to declare it's intent.`,\n )\n return\n }\n\n // Check if we have a valid stake before declaring intent\n if (!(await this.validateCurrentStake())) {\n this.logger?.error(\n `Add stake to contract address ${this.params.config.chain.id}`\n + ' for the producer to declare it\\'s intent.',\n )\n return\n }\n\n // Create a redeclaration intent\n this.logger?.log('Creating redeclaration intent for producer:', this.account.address)\n const redeclarationIntent = createDeclarationIntent(\n this.account.address,\n 'producer',\n currentBlock,\n currentBlock + BaseBlockProducerService.RedeclarationDuration,\n )\n\n // Submit the redeclaration intent\n await this.submitRedeclarationIntent(currentBlock, redeclarationIntent)\n\n // On successful submission, save the redeclaration intent\n this._lastRedeclarationIntent = redeclarationIntent\n })\n }\n\n protected async submitRedeclarationIntent(currentBlock: number, redeclarationIntent: ChainStakeIntent): Promise<void> {\n this.logger?.log('Submitting redeclaration intent for producer:', this.account.address)\n // Create a transaction to submit the redeclaration intent\n const tx = await buildTransaction(\n this.chainIterator.chainId,\n [redeclarationIntent],\n [],\n this.account,\n currentBlock,\n currentBlock + 1000,\n )\n const payloads = flattenHydratedTransaction(tx)\n const root = tx[0]._hash\n const payloadBundle = new PayloadBuilder<PayloadBundle>({ schema: PayloadBundleSchema }).fields({ payloads, root }).build()\n\n // Submit the redeclaration intent\n await this.pendingBundledTransactionsArchivistWrite.insert([payloadBundle])\n\n this.logger?.log('Submitted redeclaration intent for producer:', this.account.address)\n }\n\n protected async validateCurrentBalance(): Promise<boolean> {\n // Check if we have a valid balance before declaring intent\n const head = this._lastProducedBlock?.[0]._hash\n if (isDefined(head)) {\n const balances = await this.balanceService.balances(head, [this.account.address])\n const currentBalance = balances[this.account.address] ?? 0n\n if (currentBalance <= 0n) {\n this.logger?.error(`Producer ${this.account.address} has no balance.`)\n return false\n }\n return true\n }\n return true\n }\n\n protected async validateCurrentStake(): Promise<boolean> {\n // Use StakeIntentService to get the required minimum stake\n const requiredMinimumStake = this.stakeIntentService.getRequiredMinimumStakeForIntent('producer')\n // Check if we have a valid stake before declaring intent\n const currentStake = await this.chainStakeViewer.activeByStaked(this.account.address)\n if (currentStake < requiredMinimumStake) {\n this.logger?.error(`Producer ${this.account.address} has insufficient stake.`)\n return false\n }\n return true\n }\n}\n","import type {\n IncomingMessage, Server, ServerResponse,\n} from 'node:http'\nimport http from 'node:http'\n\nimport type { CreatableStatus } from '@xylabs/creatable'\nimport type { Logger } from '@xylabs/logger'\nimport { isDefined } from '@xylabs/typeof'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\n\nimport type { RuntimeStatusMonitor } from '../status/index.ts'\n\nconst sendStatus = (res: ServerResponse, status: CreatableStatus, errorCode: number) => {\n const statusCode = status === 'started' ? 200 : errorCode\n res.writeHead(statusCode, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ status }))\n}\n\nconst notFound = (res: ServerResponse) => {\n res.writeHead(404, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify({ status: 'not found' }))\n}\n\n/**\n * Starts an HTTP server with Kubernetes health endpoints:\n * - /healthz\n * - /livez\n * - /readyz\n * @param port The port to listen on (default: 8080)\n */\nconst createHealthServer = (port: number, statusMonitor: RuntimeStatusMonitor, logger: Logger) => {\n const server = http.createServer((req: IncomingMessage, res: ServerResponse) => {\n const url = req.url ?? ''\n\n const status = statusMonitor.getGlobalStatus()\n\n switch (url) {\n case '/healthz': {\n sendStatus(res, status, 500)\n break\n }\n case '/livez': {\n sendStatus(res, status, 503)\n break\n }\n case '/readyz': {\n sendStatus(res, status, 503)\n break\n }\n default: {\n notFound(res)\n }\n }\n })\n\n server.listen(port, () => {\n logger.log(`Health server running on http://localhost:${port}`)\n logger.log(' - /healthz')\n logger.log(' - /livez')\n logger.log(' - /readyz')\n })\n return server\n}\n\nexport const initHealthEndpoints: Initializable<{ config: Config; logger: Logger; statusReporter: RuntimeStatusMonitor }, Server | undefined> = (params) => {\n const {\n config, logger, statusReporter,\n } = params\n const { healthCheckPort } = config.producer\n return isDefined(healthCheckPort) ? createHealthServer(healthCheckPort, statusReporter, logger) : undefined\n}\n","/* eslint-disable max-statements */\nimport { assertEx } from '@xylabs/assert'\nimport type { CreatableName } from '@xylabs/creatable'\nimport type { Address } from '@xylabs/hex'\nimport { asAddress } from '@xylabs/hex'\nimport type { Logger } from '@xylabs/logger'\nimport { isDefined } from '@xylabs/typeof'\nimport type { BaseBlockProducerServiceParams, XyoValidatorParams } from '@xyo-network/chain-sdk'\nimport {\n initTelemetry, startupSpanAsync, StepSizes, validateHydratedBlockState,\n} from '@xyo-network/chain-sdk'\nimport type { Payload, WithStorageMeta } from '@xyo-network/payload-model'\nimport {\n type ChainServiceCollectionV2, type Config, readPayloadMapFromStore,\n} from '@xyo-network/xl1-protocol-sdk'\nimport {\n CompletedStepRewardAddressValidatorFactory, DerivedReceiveAddressValidatorFactory, SelfSignerValidator, TransactionTransfersValidatorFactory,\n} from '@xyo-network/xl1-validation'\nimport { Semaphore } from 'async-mutex'\n\nimport {\n initChainFinalizedArchivist, initChainSubmissionsArchivist, initPendingBundledTransactionsArchivist, initRejectedTransactionsArchivist,\n initStakeIntentStateArchivist,\n} from './archivists/index.ts'\nimport type { ChainInitializableParams } from './ChainInitializableParams.ts'\nimport { initHealthEndpoints } from './health/index.ts'\nimport { initBalanceSummaryMap, initTransferSummaryMap } from './map/index.ts'\nimport {\n initAccount, initBalanceService, initBlockProducer,\n initBlockRewardService, initChainIterator, initChainService, initElectionService, initHead,\n initPendingTransactions, initStakeIntentService,\n initTimeService, initTransferService,\n} from './services/index.ts'\nimport { RuntimeStatusMonitor } from './status/index.ts'\n\ninterface Startable {\n start: () => Promise<boolean>\n}\n\nconst isStartable = (value: unknown): value is Startable => {\n return isDefined((value as Startable).start) && typeof (value as Startable).start === 'function'\n}\n\ninterface InitServicesContext {\n config: Config\n logger: Logger\n}\n\nexport const initServices = async (context: InitServicesContext): Promise<ChainServiceCollectionV2> => {\n const { config, logger } = context\n const statusReporter = new RuntimeStatusMonitor(logger)\n statusReporter.onGlobalTransition({ to: 'started' }, () => {\n logger.log('All services started.')\n })\n statusReporter.onGlobalTransition({ to: 'error' }, () => {\n logger.error('Producer encountered an unhandled error!')\n // eslint-disable-next-line unicorn/no-process-exit\n process.exit(1)\n })\n\n await startupSpanAsync('initHealthEndpoints', () => initHealthEndpoints({ ...context, statusReporter }))\n const { otlpEndpoint } = config.telemetry?.otel ?? {}\n const telemetryConfig = {\n attributes: {\n serviceName: 'xl1-producer',\n serviceVersion: '1.0.0',\n },\n otlpEndpoint,\n metricsConfig: {\n endpoint: '/metrics',\n port: 9464,\n },\n }\n const [\n { traceProvider, meterProvider },\n account,\n ] = await Promise.all([\n startupSpanAsync('initTelemetry', () => initTelemetry(telemetryConfig)),\n startupSpanAsync('initAccount', () => initAccount(context)),\n ])\n\n const allowedRewardRedeemers: Address[] = config.validation?.allowedRewardRedeemers ?? []\n const allowedRewardEscrowAccountSigners: Address[] = config.validation?.allowedRewardEscrowAccountSigners ?? []\n\n const initParams: ChainInitializableParams = {\n config, logger, meterProvider, statusReporter, traceProvider,\n }\n\n // Archivists\n const [\n chainArchivist,\n [pendingBundledTransactionsArchivist, pendingBundledTransactionsArchivistWrite],\n rejectedTransactionsArchivist,\n chainSubmissionsArchivistWrite,\n stakeIntentStateArchivist,\n chainService,\n balanceSummaryMap,\n transferSummaryMap,\n ] = await Promise.all([\n startupSpanAsync(\n 'ChainFinalizedArchivist',\n () => initChainFinalizedArchivist(initParams),\n ),\n startupSpanAsync(\n 'PendingBundledTransactionsArchivist',\n () => initPendingBundledTransactionsArchivist(initParams),\n ),\n startupSpanAsync(\n 'RejectedTransactionsArchivist',\n () => initRejectedTransactionsArchivist(initParams),\n ),\n startupSpanAsync(\n 'ChainSubmissionsArchivist',\n () => initChainSubmissionsArchivist(initParams),\n ),\n startupSpanAsync(\n 'StakeIntentStateArchivist',\n () => initStakeIntentStateArchivist(initParams),\n ),\n startupSpanAsync(\n 'ChainService',\n () => initChainService({\n ...initParams, account, name: 'ChainService' as CreatableName,\n }),\n ),\n startupSpanAsync(\n 'BalanceSummaryMap',\n () => initBalanceSummaryMap(initParams),\n ),\n startupSpanAsync(\n 'TransferSummaryMap',\n () => initTransferSummaryMap(initParams),\n ),\n ])\n\n const chainId = chainService.chainId\n const chainMap = readPayloadMapFromStore<WithStorageMeta<Payload>>(chainArchivist)\n const chainContractViewer = chainService\n const chainStakeViewer = chainService\n const chainStaker = chainService\n const head = await startupSpanAsync('initHead', () => initHead({\n ...initParams, account, chainArchivist, chainSubmissionsArchivistWrite, chainService,\n }))\n\n const additionalPendingTransactionValidators = [TransactionTransfersValidatorFactory(\n [\n SelfSignerValidator,\n CompletedStepRewardAddressValidatorFactory(allowedRewardRedeemers),\n DerivedReceiveAddressValidatorFactory(allowedRewardEscrowAccountSigners, 'reward-escrow'),\n ],\n )]\n\n const [\n pendingTransactionsService,\n rewardService,\n chainIterator,\n ] = await Promise.all([\n startupSpanAsync('PendingTransactions', () => initPendingTransactions({\n name: 'PendingTransactionsService' as CreatableName,\n chainArchivist,\n chainId,\n pendingBundledTransactionsArchivist,\n rejectedTransactionsArchivist,\n additionalPendingTransactionValidators,\n ...initParams,\n })),\n startupSpanAsync(\n 'RewardService',\n () => initBlockRewardService({\n name: 'RewardService' as CreatableName,\n account,\n chainService,\n ...initParams,\n }),\n ),\n startupSpanAsync(\n 'ChainIterator',\n () => initChainIterator({\n name: 'ChainIterator' as CreatableName,\n chainMap,\n head,\n ...initParams,\n }),\n ),\n ])\n const [\n balanceService,\n ] = await Promise.all([\n startupSpanAsync(\n 'BalanceService',\n () => initBalanceService({\n name: 'BalanceService' as CreatableName,\n context: {\n stepSemaphores: StepSizes.map(() => new Semaphore(20)),\n store: { chainMap },\n head: async () => {\n const head = await chainIterator.head()\n return [head._hash, head.block]\n },\n chainId,\n summaryMap: balanceSummaryMap,\n },\n ...initParams,\n }),\n ),\n startupSpanAsync(\n 'TransferService',\n () => initTransferService({\n name: 'TransferService' as CreatableName,\n context: {\n stepSemaphores: StepSizes.map(() => new Semaphore(20)),\n store: { chainMap },\n head: async () => {\n const head = await chainIterator.head()\n return [head._hash, head.block]\n },\n chainId,\n summaryMap: transferSummaryMap,\n },\n ...initParams,\n }),\n ),\n ])\n\n const [stakeIntentService, time] = await Promise.all([\n startupSpanAsync(\n 'StakeIntentService',\n () => initStakeIntentService({\n name: 'StakeIntentService' as CreatableName,\n chainArchivist,\n chainIterator,\n chainStakeViewer,\n stakeIntentStateArchivist,\n ...initParams,\n }),\n ),\n startupSpanAsync(\n 'TimeService',\n () => initTimeService({\n name: 'TimeService' as CreatableName,\n chainArchivist,\n chainIterator,\n ...initParams,\n }),\n ),\n ])\n\n const electionService = await startupSpanAsync(\n 'ElectionService',\n () => initElectionService({\n name: 'ElectionService' as CreatableName,\n chainIterator,\n chainStakeViewer,\n stakeIntentService,\n ...initParams,\n }),\n )\n\n const validatorParams: XyoValidatorParams = {\n name: 'Validator' as CreatableName,\n account,\n chainId,\n pendingBundledTransactionsArchivist,\n chainArchivist,\n electionService,\n rewardService,\n stakeIntentService,\n validateHydratedBlockState,\n ...initParams,\n }\n\n const rewardAddress = isDefined(config.producer.rewardAddress)\n ? assertEx(asAddress(config.producer.rewardAddress), () => 'Invalid block reward address provided')\n : account.address\n const producerParams: BaseBlockProducerServiceParams = {\n ...validatorParams,\n name: 'Producer' as CreatableName,\n balanceService,\n chainArchivist,\n pendingBundledTransactionsArchivist,\n pendingTransactionsService,\n rejectedTransactionsArchivist,\n rewardAddress,\n time,\n ...initParams,\n }\n const producer = await startupSpanAsync('Producer', () => initBlockProducer(producerParams))\n // TODO: Add to base service collection\n const result: ChainServiceCollectionV2 = {\n account,\n balance: balanceService,\n chainArchivist,\n chainContractViewer,\n chainIterator,\n chainStaker,\n chainStakeViewer,\n chainSubmissionsArchivistWrite,\n election: electionService,\n pendingBundledTransactionsArchivistWrite,\n pendingTransactions: pendingTransactionsService,\n producer,\n reward: rewardService,\n stakeIntent: stakeIntentService,\n }\n\n logger?.log('All services created. Starting...')\n const startableServices = [balanceSummaryMap, ...Object.values(result)].filter(isStartable)\n // Start all services that have a start method and assert that they all started successfully\n assertEx(\n (await Promise.all(startableServices.map(service => service.start()))).every(Boolean),\n () => 'One or more services failed to start',\n )\n logger?.log('All services started successfully.')\n return result\n}\n","import type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { initArchivistSync, startupSpanAsync } from '@xyo-network/chain-sdk'\nimport { Mutex } from 'async-mutex'\n\nimport type { ChainInitializableParams } from '../../ChainInitializableParams.ts'\nimport { initLocalChainFinalizedArchivist } from './local.ts'\nimport { initRemoteChainFinalizedArchivist } from './remote.ts'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport async function initChainFinalizedArchivist({\n config, logger, traceProvider,\n}: ChainInitializableParams) {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n const [remote, local] = await Promise.all([\n startupSpanAsync('ChainFinalizedArchivist:initRemote', () => initRemoteChainFinalizedArchivist({ config, logger })),\n startupSpanAsync('ChainFinalizedArchivist:initLocal', () => initLocalChainFinalizedArchivist({ config, logger })),\n ])\n await startupSpanAsync(\n 'ChainFinalizedArchivist:initArchivistSync',\n () => initArchivistSync('ChainFinalizedArchivist', remote, local, 200, Number.MAX_SAFE_INTEGER, traceProvider),\n )\n singleton = local\n return singleton\n })\n}\n","import type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nimport { getLocalPersistentArchivist } from '../lib/index.ts'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport const initLocalChainFinalizedArchivist: Initializable<{ config: Config }, ArchivistInstance> = async ({ config }): Promise<ArchivistInstance> => {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n const { root } = config.storage\n singleton = await getLocalPersistentArchivist('local-finalized-chain', 'chain', 'finalized', root)\n return singleton\n })\n}\n","import { rm } from 'node:fs/promises'\nimport Path from 'node:path'\n\nimport { LmdbArchivist, LmdbArchivistConfigSchema } from '@xyo-network/archivist-lmdb'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { getStoreDirectory, type StoreKind } from '@xyo-network/chain-sdk'\n\nconst DEFAULT_STORAGE_ROOT = Path.join(process.cwd(), '.store')\n\n/**\n * Returns a local persistent archivist\n * @param name The name of the archivist\n * @param dbName The name of the database\n * @param storeName The name of the store\n * @param storageRoot The root directory for storage (default is '.store' in the current working directory)\n * @param kind The kind of the archivist\n * @returns an archivist instance\n */\nexport const getLocalPersistentArchivist = (\n name: string,\n dbName: string,\n storeName: string,\n storageRoot?: string,\n kind: StoreKind = 'lmdb',\n): Promise<ArchivistInstance> => {\n switch (kind) {\n case 'lmdb': {\n const root = storageRoot ?? DEFAULT_STORAGE_ROOT\n return LmdbArchivist.create({\n account: 'random',\n config: {\n name,\n clearStoreOnStart: false,\n dbName,\n location: getStoreDirectory(dbName, root, 'lmdb'),\n schema: LmdbArchivistConfigSchema,\n storeName,\n },\n })\n }\n }\n}\n\n/**\n * Deletes a local persistent archivist\n * @param dbName The name of the database\n * @param storageRoot The root directory for storage (default is '.store' in the current working directory)\n * @param kind The kind of the archivist\n * @returns A promise that resolves when the archivist is deleted\n */\nexport const deleteLocalPersistentArchivist = async (dbName: string, storageRoot?: string, kind: StoreKind = 'lmdb'): Promise<void> => {\n await Promise.resolve()\n console.warn(`Deleting local persistent archivist for ${dbName} of kind ${kind}.`)\n let location = ''\n switch (kind) {\n case 'lmdb': {\n const root = storageRoot ?? DEFAULT_STORAGE_ROOT\n location = getStoreDirectory(dbName, root, 'lmdb')\n break\n }\n }\n await rm(location, { recursive: true, force: true })\n}\n","import { assertEx } from '@xylabs/assert'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { initBridge, initBridgedArchivistModule } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport { type Config, getUrl } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport const initRemoteChainFinalizedArchivist: Initializable<{ config: Config }, ArchivistInstance> = async ({ config }): Promise<ArchivistInstance> => {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n const { host, port } = config.mempool.enabled ? config.mempool : config.api\n const nodeUrl = getUrl(host, port)\n const bridge = await initBridge(nodeUrl)\n singleton = await initBridgedArchivistModule({ bridge, moduleName: 'XYOChain:Chain:Finalized' })\n return assertEx(singleton, () => 'Error: RemoteChainFinalizedArchivist failed to initialize')\n })\n}\n","import { assertEx } from '@xylabs/assert'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { startupSpanAsync } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nimport { initRemoteChainSubmissionsArchivist } from './remote.ts'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport const initChainSubmissionsArchivist: Initializable<{ config: Config }, ArchivistInstance> = async (params): Promise<ArchivistInstance> => {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n const remote = await startupSpanAsync('ChainSubmissionsArchivist:initRemote', () => initRemoteChainSubmissionsArchivist(params))\n singleton = remote\n return assertEx(singleton, () => new Error('Failed to initialize ChainSubmissionsArchivist'))\n })\n}\n","import { assertEx } from '@xylabs/assert'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { initBridge, initBridgedArchivistModule } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport { type Config, getUrl } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport const initRemoteChainSubmissionsArchivist: Initializable<{ config: Config }, ArchivistInstance> = async ({ config }): Promise<ArchivistInstance> => {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n const { host, port } = config.mempool.enabled ? config.mempool : config.api\n const nodeUrl = getUrl(host, port)\n const bridge = await initBridge(nodeUrl)\n singleton = await initBridgedArchivistModule({ bridge, moduleName: 'XYOChain:Chain:Submissions' })\n return assertEx(singleton, () => new Error('Failed to initialize RemoteChainSubmissionsArchivist'))\n })\n}\n","import type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { initArchivistSync, startupSpanAsync } from '@xyo-network/chain-sdk'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nimport { initLocalPendingTransactionsArchivist } from './local.ts'\nimport { initRemotePendingTransactionsArchivist } from './remote.ts'\n\nconst mutex = new Mutex()\nlet singleton: [local: ArchivistInstance, remote: ArchivistInstance] | undefined\n\nexport const initPendingBundledTransactionsArchivist = async (params: { config: Config }): Promise<[local: ArchivistInstance, remote: ArchivistInstance]> => {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n const remote = await startupSpanAsync('PendingBundledTransactionsArchivist:initRemote', () => initRemotePendingTransactionsArchivist(params))\n const local = await startupSpanAsync('PendingBundledTransactionsArchivist:initLocal', () => initLocalPendingTransactionsArchivist(params))\n // Grab the most recent payload from the remote archivist\n const start = await remote.next({ limit: 1, order: 'desc' })\n // Write it locally so we have a starting point for syncing\n await local.insert(start)\n await startupSpanAsync(\n 'PendingBundledTransactionsArchivist:initArchivistSync',\n () => initArchivistSync('PendingBundledTransactionsArchivist', remote, local),\n )\n singleton = [local, remote]\n return singleton\n })\n}\n","import { MemoryArchivist, MemoryArchivistConfigSchema } from '@xyo-network/archivist-memory'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport const initLocalPendingTransactionsArchivist: Initializable<{ config: Config }, ArchivistInstance> = async (): Promise<ArchivistInstance> => {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n singleton = await MemoryArchivist.create({\n account: 'random',\n config: {\n schema: MemoryArchivistConfigSchema, max: 1000, name: 'localPendingTransactions',\n },\n })\n return singleton\n })\n}\n","import { assertEx } from '@xylabs/assert'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { initBridge, initBridgedArchivistModule } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport { type Config, getUrl } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport const initRemotePendingTransactionsArchivist: Initializable<{ config: Config }, ArchivistInstance> = async ({ config }): Promise<ArchivistInstance> => {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n const { host, port } = config.mempool.enabled ? config.mempool : config.api\n const nodeUrl = getUrl(host, port)\n const bridge = await initBridge(nodeUrl)\n singleton = await initBridgedArchivistModule({ bridge, moduleName: 'XYOChain:Pending:PendingTransactions' })\n return assertEx(singleton, () => 'Error: RemotePendingBundledTransactionsArchivist is undefined')\n })\n}\n","import type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { startupSpanAsync } from '@xyo-network/chain-sdk'\nimport type { InitializableParams } from '@xyo-network/xl1-protocol'\nimport { Mutex } from 'async-mutex'\n\nimport { initLocalRejectedTransactionsArchivist } from './local.ts'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport async function initRejectedTransactionsArchivist(params: InitializableParams) {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n const local = await startupSpanAsync('RejectedTransactionsArchivist:initLocal', () => initLocalRejectedTransactionsArchivist(params))\n singleton = local\n return singleton\n })\n}\n","import { MemoryArchivist, MemoryArchivistConfigSchema } from '@xyo-network/archivist-memory'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport { Mutex } from 'async-mutex'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport const initLocalRejectedTransactionsArchivist: Initializable<{}, ArchivistInstance> = async (): Promise<ArchivistInstance> => {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n singleton = await MemoryArchivist.create({\n account: 'random',\n config: {\n schema: MemoryArchivistConfigSchema, max: 1000, name: 'localRejectedTransactions',\n },\n })\n return singleton\n })\n}\n","import { assertEx } from '@xylabs/assert'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { startupSpanAsync } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport { Mutex } from 'async-mutex'\n\nimport type { ChainInitializableParams } from '../../ChainInitializableParams.ts'\nimport { initLocalStakeIntentStateArchivist } from './local.ts'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport const initStakeIntentStateArchivist: Initializable<ChainInitializableParams, ArchivistInstance>\n = async (params: ChainInitializableParams): Promise<ArchivistInstance> => {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n const local = await startupSpanAsync('StakeIntentStateArchivist:initLocal', () => initLocalStakeIntentStateArchivist(params))\n singleton = local\n return assertEx(singleton, () => 'Error: StakeIntentStateArchivist is undefined')\n })\n }\n","import { assertEx } from '@xylabs/assert'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nimport { getLocalPersistentArchivist } from '../lib/index.ts'\n\nconst mutex = new Mutex()\nlet singleton: ArchivistInstance | undefined\n\nexport const initLocalStakeIntentStateArchivist: Initializable<{ config: Config }, ArchivistInstance> = async ({ config }): Promise<ArchivistInstance> => {\n return await mutex.runExclusive(async () => {\n if (singleton) return singleton\n const { root } = config.storage\n singleton = await getLocalPersistentArchivist('local-stake-intent-state', 'stakeIntent', 'state', root)\n return assertEx(singleton, () => new Error('Failed to initialize stake intent state archivist'))\n })\n}\n","import { isDefined } from '@xylabs/typeof'\nimport { startupSpanAsync } from '@xyo-network/chain-sdk'\nimport type { WithStorageMeta } from '@xyo-network/payload-model'\nimport type { BalancesStepSummary, MapType } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nimport type { ChainInitializableParams } from '../../ChainInitializableParams.ts'\nimport { initLocalBalanceSummaryMap } from './initLocalBalanceSummaryMap.ts'\n\nconst mutex = new Mutex()\nlet singleton: MapType<string, WithStorageMeta<BalancesStepSummary>> | undefined\n\nexport async function initBalanceSummaryMap(params: ChainInitializableParams): Promise<MapType<string, WithStorageMeta<BalancesStepSummary>>> {\n return await mutex.runExclusive(async () => {\n if (isDefined(singleton)) return singleton\n const local = await startupSpanAsync('BalanceSummaryMap:initLocal', () => initLocalBalanceSummaryMap(params))\n singleton = local\n return singleton\n })\n}\n","import { isDefined } from '@xylabs/typeof'\nimport { getLocalPersistentMap } from '@xyo-network/chain-sdk'\nimport type { WithStorageMeta } from '@xyo-network/payload-model'\nimport type { BalancesStepSummary, MapType } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nimport type { ChainInitializableParams } from '../../ChainInitializableParams.ts'\n\nconst mutex = new Mutex()\nlet singleton: MapType<string, WithStorageMeta<BalancesStepSummary>> | undefined\n\nexport const initLocalBalanceSummaryMap = async (params: ChainInitializableParams): Promise<MapType<string, WithStorageMeta<BalancesStepSummary>>> => {\n return await mutex.runExclusive(async () => {\n if (isDefined(singleton)) return singleton\n const { root } = params.config.storage\n singleton = await getLocalPersistentMap<string, WithStorageMeta<BalancesStepSummary>>('balance', 'summary', root)\n return singleton\n })\n}\n","import { isDefined } from '@xylabs/typeof'\nimport { startupSpanAsync } from '@xyo-network/chain-sdk'\nimport type { WithStorageMeta } from '@xyo-network/payload-model'\nimport type { MapType, TransfersStepSummary } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nimport type { ChainInitializableParams } from '../../ChainInitializableParams.ts'\nimport { initLocalTransferSummaryMap } from './initLocalTransferSummaryMap.ts'\n\nconst mutex = new Mutex()\nlet singleton: MapType<string, WithStorageMeta<TransfersStepSummary>> | undefined\n\nexport async function initTransferSummaryMap(params: Pick<ChainInitializableParams, 'config'>):\nPromise<MapType<string, WithStorageMeta<TransfersStepSummary>>> {\n return await mutex.runExclusive(async () => {\n if (isDefined(singleton)) return singleton\n const local = await startupSpanAsync('TransferSummaryMap:initLocal', () => initLocalTransferSummaryMap(params))\n singleton = local\n return singleton\n })\n}\n","import { isDefined } from '@xylabs/typeof'\nimport { getLocalPersistentMap } from '@xyo-network/chain-sdk'\nimport type { WithStorageMeta } from '@xyo-network/payload-model'\nimport type { MapType, TransfersStepSummary } from '@xyo-network/xl1-protocol-sdk'\nimport { Mutex } from 'async-mutex'\n\nimport type { ChainInitializableParams } from '../../ChainInitializableParams.ts'\n\nconst mutex = new Mutex()\nlet singleton: MapType<string, WithStorageMeta<TransfersStepSummary>> | undefined\n\nexport const initLocalTransferSummaryMap = async (params: Pick<ChainInitializableParams, 'config'>):\nPromise<MapType<string, WithStorageMeta<TransfersStepSummary>>> => {\n return await mutex.runExclusive(async () => {\n if (isDefined(singleton)) return singleton\n const { root } = params.config.storage\n singleton = await getLocalPersistentMap<string, WithStorageMeta<TransfersStepSummary>>('transfer', 'summary', root)\n return singleton\n })\n}\n","import type { Promisable } from '@xylabs/promise'\nimport { isUndefined } from '@xylabs/typeof'\nimport { HDWallet } from '@xyo-network/wallet'\nimport type { WalletInstance } from '@xyo-network/wallet-model'\nimport type { Initializable, InitializableParams } from '@xyo-network/xl1-protocol'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport { ADDRESS_INDEX, generateXyoBaseWalletFromPhrase } from '@xyo-network/xl1-protocol-sdk'\n\nlet accountServiceSingleton: Promisable<WalletInstance> | undefined\n\nexport const initAccount: Initializable<InitializableParams<{ config: Config }>, WalletInstance> = async ({ config, logger }): Promise<WalletInstance> => {\n if (accountServiceSingleton) return accountServiceSingleton\n let walletPhrase = config.producer.mnemonic\n if (isUndefined(walletPhrase)) {\n logger?.warn('[Producer] No wallet mnemonic specified!')\n const randomMnemonic = HDWallet.generateMnemonic()\n logger?.warn(`[Producer] Using randomly generated mnemonic:\n \n${randomMnemonic}\n \n `)\n walletPhrase = randomMnemonic\n }\n const wallet = await generateXyoBaseWalletFromPhrase(walletPhrase)\n const account = await wallet.derivePath(ADDRESS_INDEX.XYO)\n accountServiceSingleton = account\n return accountServiceSingleton\n}\n","import type { Promisable } from '@xylabs/promise'\nimport type { BaseAccountBalanceServiceParams } from '@xyo-network/chain-sdk'\nimport { BaseAccountBalanceService } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { AccountBalanceServiceV2 } from '@xyo-network/xl1-protocol-sdk'\n\nlet balanceServiceSingleton: Promisable<AccountBalanceServiceV2> | undefined\n\nexport const initBalanceService: Initializable<BaseAccountBalanceServiceParams, AccountBalanceServiceV2>\n = async (params): Promise<AccountBalanceServiceV2> => {\n if (balanceServiceSingleton) return balanceServiceSingleton\n balanceServiceSingleton = await BaseAccountBalanceService.create(params)\n return balanceServiceSingleton\n }\n","import type { CreatableName } from '@xylabs/creatable'\nimport type { Promisable } from '@xylabs/promise'\nimport type { BaseAccountableServiceParams } from '@xyo-network/chain-sdk'\nimport { MemoryChainService } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { ChainService } from '@xyo-network/xl1-protocol-sdk'\n\nimport { canUseEvmContractChainService, initEvmContractChainService } from './evm.ts'\n\nlet chainStakeServiceSingleton: Promisable<ChainService> | undefined\n\nexport const initChainService: Initializable<BaseAccountableServiceParams, ChainService> = ({ account, config }) => init({\n config, name: 'ChainService' as CreatableName, account,\n})\n\nconst init: Initializable<BaseAccountableServiceParams, ChainService> = (params): Promisable<ChainService> => {\n if (chainStakeServiceSingleton) return chainStakeServiceSingleton\n const { config } = params\n chainStakeServiceSingleton = canUseEvmContractChainService(config)\n ? initEvmContractChainService({ ...params, name: 'ChainStakeService' as CreatableName })\n : MemoryChainService.create({ ...params, name: 'ChainStakeService' as CreatableName })\n // Create service\n return chainStakeServiceSingleton\n}\n","import { assertEx } from '@xylabs/assert'\nimport type { Address } from '@xylabs/hex'\nimport { asAddress, ZERO_ADDRESS } from '@xylabs/hex'\nimport type { Promisable } from '@xylabs/promise'\nimport { isDefined } from '@xylabs/typeof'\nimport type { BaseAccountableServiceParams } from '@xyo-network/chain-sdk'\nimport { EvmChainService } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport type { ContractRunner } from 'ethers'\nimport { Wallet } from 'ethers/wallet'\n\nimport { canUseEvmProvider, initEvmProvider } from '../evm/index.ts'\n\nlet chainStakeServiceSingleton: Promisable<EvmChainService> | undefined\n\nexport const canUseEvmContractChainService = (config: Config) => {\n const { id } = config.chain\n return isDefined(id) && id !== ZERO_ADDRESS && canUseEvmProvider({ config })\n}\n\nexport const initEvmContractChainService: Initializable<BaseAccountableServiceParams, EvmChainService> = async ({\n account, config, traceProvider, meterProvider, logger,\n}) => {\n if (chainStakeServiceSingleton) return chainStakeServiceSingleton\n // Parse config\n const emvStakingContractAddress = assertEx(config.chain.id, () => 'Error: config.chain.id is required')\n // Configure ContractRunner\n const id: Address = assertEx(asAddress(emvStakingContractAddress), () => 'Error: config.chain.id is not a valid address')\n const provider = assertEx(await initEvmProvider({ config }))\n const privateKey = assertEx(account.private?.hex, () => 'Error: Account does not have a private key')\n const runner: ContractRunner = new Wallet(privateKey, provider)\n // Create service\n chainStakeServiceSingleton = EvmChainService.create({\n id, runner, traceProvider, meterProvider, logger,\n })\n return await chainStakeServiceSingleton\n}\n","import { assertEx } from '@xylabs/assert'\nimport type { Logger } from '@xylabs/logger'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport type { Provider } from 'ethers'\nimport type { JsonRpcProvider } from 'ethers/providers'\n\nimport { canUseInfuraProvider, initInfuraProvider } from './initInfuraProvider.ts'\nimport { canUseJsonRpcProvider, initJsonRpcProvider } from './initJsonRpcProvider.ts'\n\nlet provider: Promise<JsonRpcProvider> | undefined\n\nexport const initEvmProvider = async ({ config }: { config: Config; logger?: Logger }): Promise<Provider> => {\n if (provider) return provider\n if (canUseInfuraProvider(config)) {\n provider = initInfuraProvider(config)\n } else if (canUseJsonRpcProvider(config)) {\n provider = initJsonRpcProvider(config)\n }\n return assertEx(await provider, () => 'Error: No provider available')\n}\n\nexport const canUseEvmProvider = ({ config }: { config: Config }) => {\n return canUseInfuraProvider(config) || canUseJsonRpcProvider(config)\n}\n","import { assertEx } from '@xylabs/assert'\nimport { isDefined } from '@xylabs/typeof'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport { InfuraProvider } from 'ethers/providers'\n\nimport { canUseChainId, getChainId } from './initChainId.ts'\n\nlet instance: Promise<InfuraProvider> | undefined\n\nexport const initInfuraProvider = (config: Config) => {\n if (instance) return instance\n const providerConfig = getInfuraProviderConfig(config)\n instance = Promise.resolve(new InfuraProvider(...providerConfig))\n return instance\n}\n\nexport const canUseInfuraProvider = (config: Config): boolean => {\n return canUseChainId(config)\n && isDefined(config.evm?.infura?.projectId)\n && isDefined(config.evm?.infura?.projectSecret)\n}\n\nexport const getInfuraProviderConfig = (config: Config) => {\n const projectId = assertEx(config.evm?.infura?.projectId, () => 'Missing config.evm.infura.projectId')\n const projectSecret = assertEx(config.evm?.infura?.projectSecret, () => 'Missing config.evm.infura.projectSecret')\n return [getChainId(config), projectId, projectSecret] as const\n}\n","import { assertEx } from '@xylabs/assert'\nimport { hexFrom, isHex } from '@xylabs/hex'\nimport { isDefined } from '@xylabs/typeof'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\n\nexport const canUseChainId = (config: Config): boolean => {\n return isDefined(config.evm.chainId)\n}\n\nexport const getChainId = (config: Config) => {\n const chainId = assertEx(config.evm.chainId, () => 'Missing config.evm.chainId')\n if (isHex(chainId, { prefix: true })) {\n const hex = hexFrom(chainId)\n const parsed = Number.parseInt(hex, 16)\n return parsed\n } else {\n const parsed = Number.parseInt(chainId, 10)\n return parsed\n }\n}\n","import { assertEx } from '@xylabs/assert'\nimport { isDefined } from '@xylabs/typeof'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\nimport { JsonRpcProvider } from 'ethers/providers'\n\nimport { canUseChainId, getChainId } from './initChainId.ts'\n\nexport const initJsonRpcProvider = (config: Config) => {\n const providerConfig = getJsonRpcProviderConfig(config)\n return Promise.resolve(new JsonRpcProvider(...providerConfig))\n}\n\nexport const canUseJsonRpcProvider = (config: Config) => {\n return canUseChainId(config)\n && isDefined(config.evm.jsonRpc?.url)\n}\n\nexport const getJsonRpcProviderConfig = (config: Config) => {\n const jsonRpcUrl = assertEx(config.evm.jsonRpc?.url, () => 'Missing config.evm.jsonRpc.url')\n return [jsonRpcUrl, getChainId(config)] as const\n}\n","import { assertEx } from '@xylabs/assert'\nimport type { Promisable } from '@xylabs/promise'\nimport { isDefined } from '@xylabs/typeof'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { findMostRecentBlock } from '@xyo-network/chain-sdk'\nimport type { WithStorageMeta } from '@xyo-network/payload-model'\nimport type { WalletInstance } from '@xyo-network/wallet-model'\nimport type { BlockBoundWitness, Initializable } from '@xyo-network/xl1-protocol'\nimport type { ChainService } from '@xyo-network/xl1-protocol-sdk'\n\nimport { createBootstrapHead } from './createBootstrapHead.ts'\nimport { createForkedHead } from './createForkedHead/index.ts'\nimport { getForkFromBlock } from './getForkFromBlock.ts'\nimport { submitNewChain } from './submitNewChain.ts'\n\nlet headSingleton: Promisable<WithStorageMeta<BlockBoundWitness>> | undefined\n\nexport const initHead: Initializable<{\n account: WalletInstance\n chainArchivist: ArchivistInstance\n chainService: ChainService\n chainSubmissionsArchivistWrite: ArchivistInstance\n}, WithStorageMeta<BlockBoundWitness>>\n = async (params): Promise<WithStorageMeta<BlockBoundWitness>> => {\n const {\n account, chainArchivist, chainSubmissionsArchivistWrite, chainService,\n } = params\n if (headSingleton) return headSingleton\n let head = await findMostRecentBlock(chainArchivist)\n\n // If there is a head\n if (head) {\n // If there is a head but check if it matches our chainId or we should fork from it\n const forkFromBlock = await getForkFromBlock(head, chainService, chainArchivist)\n // If we should fork form a block in the current chain\n if (isDefined(forkFromBlock)) {\n // Create a new chain from the fork from block\n const chain = await createForkedHead(forkFromBlock, account, chainService)\n await submitNewChain(chain, chainArchivist, chainSubmissionsArchivistWrite)\n const newBlock = assertEx(chain.at(-1), () => new Error('Failed to get new head after forking'))\n head = newBlock[0]\n }\n } else {\n // If there is no head, create one\n const chain = await createBootstrapHead(account, chainService)\n await submitNewChain(chain, chainArchivist, chainSubmissionsArchivistWrite)\n const newBlock = assertEx(chain.at(-1), () => new Error('Failed to get new head after genesis'))\n head = newBlock[0]\n }\n headSingleton = head\n return headSingleton\n }\n","import {\n buildNextBlock, createDeclarationIntent, createGenesisBlock,\n} from '@xyo-network/chain-sdk'\nimport type { WalletInstance } from '@xyo-network/wallet-model'\nimport type { HydratedBlock } from '@xyo-network/xl1-protocol'\nimport type { ChainService } from '@xyo-network/xl1-protocol-sdk'\n\nexport const createBootstrapHead = async (account: WalletInstance, chainService: ChainService): Promise<HydratedBlock[]> => {\n const chainId = chainService.chainId\n const chain: HydratedBlock[] = []\n\n // Create genesis block\n const genesisBlock = await createGenesisBlock(account, chainId, 10_000_000n, account.address)\n chain.push(genesisBlock)\n\n // Create producer declaration block\n const producerDeclarationPayload = createDeclarationIntent(\n 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 { BridgeDestinationObservationSchema, buildNextBlock } from '@xyo-network/chain-sdk'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport type { WalletInstance } from '@xyo-network/wallet-model'\nimport type {\n BridgeDestinationObservation, BridgeDestinationObservationFields, HydratedBlock,\n} from '@xyo-network/xl1-protocol'\nimport type { ChainService } from '@xyo-network/xl1-protocol-sdk'\n\nimport {\n getBridgeDestConfirmation, getBridgeDestinationDetails, getBridgeSourceDetails,\n} from './config/index.ts'\n\n/**\n * Get the bridge destination observation for a given block.\n * @param previousBlock The previous block to base the observation on.\n * @param account The wallet account to use for the observation.\n * @param chainService The chain service to use for the observation.\n */\nexport const getBridgeDestinationObservation = async (\n previousBlock: HydratedBlock,\n account: WalletInstance,\n chainService: ChainService,\n): Promise<HydratedBlock> => {\n const bridgeDestinationObservationFields: BridgeDestinationObservationFields = {\n ...getBridgeSourceDetails(account, chainService),\n ...getBridgeDestinationDetails(),\n destConfirmation: getBridgeDestConfirmation(),\n }\n const bridgeDestinationObservation = new PayloadBuilder<BridgeDestinationObservation>({ schema: BridgeDestinationObservationSchema })\n .fields(bridgeDestinationObservationFields)\n .build()\n\n return await buildNextBlock(\n previousBlock[0],\n [],\n [bridgeDestinationObservation],\n [account],\n )\n}\n","import { toHex } from '@xylabs/hex'\nimport type { BridgeDetailsDestinationFields } from '@xyo-network/xl1-protocol'\n\nimport { getForkBlockRewardHex } from './getForkDetails.ts'\n\n// const bridgeableTokenContract = toHex('0x4865Cb10d55cfB0E60DD2B4F9b888f6a49B76733')\n// const bridgeDestAddress = toHex('0xe53218d47913b5f9E58bb74F0a0eD790bbF21972')\n// const destConfirmation = toHex('0x4fa05d7e799f36f1d45c441a4866eb4570a00a753a39377f404a8d113c01a657') // Eth TX for mint\nconst ethChainId = toHex('0x1')\nconst bridgeableTokenContract = toHex('0xf72aE3E0DA743033AbD7A407557D684c1aE66aed')\nconst bridgeDestAddress = toHex('0x0e65b65B10C791942665030402c35023d88B14dA')\nconst destConfirmation = toHex('0x950861b10523b52cdbb4a9ee52ed26601db555d2652bfec21c709e5e70d5b7d3') // Eth TX for mint\n\nexport const getBridgeDestChainId = () => ethChainId\nexport const getBridgeDestToken = () => bridgeableTokenContract\nexport const getBridgeDestAddress = () => bridgeDestAddress\nexport const getBridgeDestAmount = () => getForkBlockRewardHex()\nexport const getBridgeDestConfirmation = () => destConfirmation\n\nexport const getBridgeDestinationDetails = (): BridgeDetailsDestinationFields => {\n return {\n dest: getBridgeDestChainId(),\n destToken: getBridgeDestToken(),\n destAddress: getBridgeDestAddress(),\n destAmount: getBridgeDestAmount(),\n }\n}\n","import { type Hex, toHex } from '@xylabs/hex'\nimport { AttoXL1ConvertFactor } from '@xyo-network/xl1-protocol'\n\nexport const getForkBlockReward = (): bigint => {\n return 18_000_000_000n * AttoXL1ConvertFactor.xl1 // 18b XL1 in AttoXL1\n}\n\nexport const getForkBlockRewardHex = (): Hex => {\n return toHex(getForkBlockReward())\n}\n","import type { AccountInstance } from '@xyo-network/account-model'\nimport type { BridgeDetailsSourceFields } from '@xyo-network/xl1-protocol'\nimport type { ChainService } from '@xyo-network/xl1-protocol-sdk'\n\nimport { getForkBlockRewardHex } from './getForkDetails.ts'\n\nexport const getBridgeSrcChainId = (chainService: ChainService) => chainService.chainId\nexport const getBridgeSrcAddress = (account: AccountInstance) => account.address\nexport const getBridgeSrcToken = (chainService: ChainService) => chainService.chainId\nexport const getBridgeSrcAmount = () => getForkBlockRewardHex()\n\nexport const getBridgeSourceDetails = (account: AccountInstance, chainService: ChainService): BridgeDetailsSourceFields => {\n return {\n src: getBridgeSrcChainId(chainService),\n srcAddress: getBridgeSrcAddress(account),\n srcToken: getBridgeSrcToken(chainService),\n srcAmount: getBridgeSrcAmount(),\n }\n}\n","import {\n BridgeIntentSchema, buildNextBlock, createTransferPayload, XYO_BRIDGE_ADDRESS,\n} from '@xyo-network/chain-sdk'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport type { WalletInstance } from '@xyo-network/wallet-model'\nimport type {\n BridgeIntent, BridgeIntentFields, HydratedBlock,\n} from '@xyo-network/xl1-protocol'\nimport type { ChainService } from '@xyo-network/xl1-protocol-sdk'\n\nimport {\n getBridgeDestinationDetails, getBridgeSourceDetails, getForkBlockReward,\n} from './config/index.ts'\n\n/**\n * Get the bridge intent for a given block.\n * @param previousBlock The previous block to base the intent on.\n * @param account The wallet account to use for the intent.\n * @param chainService The chain service to use for the intent.\n */\nexport const getBridgeIntent = async (\n previousBlock: HydratedBlock,\n account: WalletInstance,\n chainService: ChainService,\n): Promise<HydratedBlock> => {\n // Create transfer to bridge address\n const transferPayload = createTransferPayload(\n account.address,\n { [XYO_BRIDGE_ADDRESS]: getForkBlockReward() },\n )\n\n // Use timestamp as nonce\n const nonce = `${Date.now()}`\n\n // Create Bridge Intent\n const bridgeIntentFields: BridgeIntentFields = {\n ...getBridgeSourceDetails(account, chainService),\n ...getBridgeDestinationDetails(),\n nonce,\n }\n const bridgeIntent = new PayloadBuilder<BridgeIntent>({ schema: BridgeIntentSchema })\n .fields(bridgeIntentFields)\n .build()\n\n return await buildNextBlock(\n previousBlock[0],\n [],\n [bridgeIntent, transferPayload],\n [account],\n )\n}\n","import { BridgeSourceObservationSchema, buildNextBlock } from '@xyo-network/chain-sdk'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport type { WalletInstance } from '@xyo-network/wallet-model'\nimport type {\n BridgeSourceObservation, BridgeSourceObservationFields, HydratedBlock,\n} from '@xyo-network/xl1-protocol'\nimport type { ChainService } from '@xyo-network/xl1-protocol-sdk'\n\nimport { getBridgeDestinationDetails, getBridgeSourceDetails } from './config/index.ts'\n\n/**\n * Get the bridge source observation for a given block.\n * @param previousBlock The previous block to base the observation on.\n * @param account The wallet account to use for the observation.\n * @param chainService The chain service to use for the observation.\n */\nexport const getBridgeSourceObservation = async (\n previousBlock: HydratedBlock,\n account: WalletInstance,\n chainService: ChainService,\n): Promise<HydratedBlock> => {\n // TODO: Find actual transfer TX from previous block/source intent?\n // This hash should contain both the source intent and the transfer to the bridge address\n // As the block is itself both a block and a transaction, we can use its hash for now\n const srcTxHash = previousBlock[0]._hash\n\n const bridgeSourceObservationFields: BridgeSourceObservationFields = {\n ...getBridgeSourceDetails(account, chainService),\n ...getBridgeDestinationDetails(),\n // Observation\n srcConfirmation: srcTxHash,\n }\n\n const bridgeSourceObservation = new PayloadBuilder<BridgeSourceObservation>({ schema: BridgeSourceObservationSchema })\n .fields(bridgeSourceObservationFields)\n .build()\n\n return await buildNextBlock(\n previousBlock[0],\n [],\n [bridgeSourceObservation],\n [account],\n )\n}\n","import type { BuildNextBlockOptions } from '@xyo-network/chain-sdk'\nimport {\n AttoXL1, buildBlock, XYO_STEP_REWARD_ADDRESS,\n} from '@xyo-network/chain-sdk'\nimport type { WithHashMeta } from '@xyo-network/payload-model'\nimport type { WalletInstance } from '@xyo-network/wallet-model'\nimport type { BlockBoundWitness, HydratedBlock } from '@xyo-network/xl1-protocol'\nimport type { ChainService } from '@xyo-network/xl1-protocol-sdk'\n\n/**\n * Get the first block for the new forked chain.\n * @param forkBlock The block to fork from\n * @param account The wallet account to sign the block\n * @param chainService The chain service instance\n * @returns The first block for the new forked chain\n */\nexport const getFirstBlockForNewChain = async (\n forkBlock: WithHashMeta<BlockBoundWitness>,\n account: WalletInstance,\n chainService: ChainService,\n): Promise<HydratedBlock> => {\n const {\n _hash: previousBlockHash, block: previousBlockNumber, step_hashes: previousStepHashes, protocol,\n } = forkBlock\n const chainId = chainService.chainId\n const options: BuildNextBlockOptions = {\n blockPayloads: [],\n chainId,\n previousBlockHash,\n previousBlockNumber,\n previousStepHashes,\n signers: [account],\n txs: [],\n protocol,\n chainStepRewardAddress: XYO_STEP_REWARD_ADDRESS,\n stepRewardPoolBalance: AttoXL1(0n),\n }\n // NOTE: Can not use buildNextBlock because we need to control the chain id change here\n return await buildBlock(options)\n}\n","import type { WithHashMeta } from '@xyo-network/payload-model'\nimport type { WalletInstance } from '@xyo-network/wallet-model'\nimport type { BlockBoundWitness, HydratedBlock } from '@xyo-network/xl1-protocol'\nimport type { ChainService } from '@xyo-network/xl1-protocol-sdk'\n\nimport { getBridgeDestinationObservation } from './getBridgeDestinationObservation.ts'\nimport { getBridgeIntent } from './getBridgeIntent.ts'\nimport { getBridgeSourceObservation } from './getBridgeSourceObservation.ts'\nimport { getFirstBlockForNewChain } from './getFirstBlockForNewChain.ts'\n\nexport const createForkedHead = async (\n forkFromBlock: WithHashMeta<BlockBoundWitness>,\n account: WalletInstance,\n chainService: ChainService,\n): Promise<HydratedBlock[]> => {\n const chain: HydratedBlock[] = []\n // Build the first block for the new chain\n const firstBlockForNewChain = await getFirstBlockForNewChain(forkFromBlock, account, chainService)\n chain.push(firstBlockForNewChain)\n // Build the bridge intent\n const bridgeIntent = await getBridgeIntent(firstBlockForNewChain, account, chainService)\n chain.push(bridgeIntent)\n // Build the bridge source observation\n const bridgeSourceObservation = await getBridgeSourceObservation(bridgeIntent, account, chainService)\n chain.push(bridgeSourceObservation)\n // Build the bridge destination observation\n const bridgeDestinationObservation = await getBridgeDestinationObservation(bridgeSourceObservation, account, chainService)\n chain.push(bridgeDestinationObservation)\n return chain\n}\n","import type { Address, Hash } from '@xylabs/hex'\nimport { asHash, hexFromBigInt } from '@xylabs/hex'\nimport { isDefined } from '@xylabs/typeof'\nimport type { ArchivistInstance } from '@xyo-network/archivist-model'\nimport { isBlockBoundWitnessWithHashMeta } from '@xyo-network/chain-sdk'\nimport type { WithHashMeta, WithStorageMeta } from '@xyo-network/payload-model'\nimport type { BlockBoundWitness } from '@xyo-network/xl1-protocol'\nimport type { ChainService } from '@xyo-network/xl1-protocol-sdk'\n\n/**\n * Determine if the chain should fork based on the current head and chain configuration.\n * @param head The current head block\n * @param chainService The chain service instance\n * @param chainArchivist The chain archivist instance\n * @returns The block to fork from if the chain should fork, undefined otherwise\n */\nexport const getForkFromBlock = async (\n head: WithStorageMeta<BlockBoundWitness>,\n chainService: ChainService,\n chainArchivist: ArchivistInstance,\n): Promise<WithHashMeta<BlockBoundWitness> | undefined> => {\n // If the head's chain doesn't match our chainId, we may need to fork\n if (head.chain !== chainService.chainId) {\n // Get the forked at hash from the chain service\n const forkedAtBigInt = await chainService.forkedAtHash()\n const forkedAtHex = hexFromBigInt(forkedAtBigInt) // Validate it's a proper hex string\n const forkedAtHash: Hash | undefined = asHash(forkedAtHex)\n if (isDefined(forkedAtHash)) {\n // If we have a forkedAtHash, we need to check if the correct block exists\n const [forkedAtBlock] = await chainArchivist.get([forkedAtHash])\n const forkedChainId: Address = await chainService.forkedChainId()\n const forkedAtBlockNumber: number = Number(await chainService.forkedAtBlockNumber())\n // If we found the block hash we should fork at, check if it's a valid BlockBoundWitness\n if (isBlockBoundWitnessWithHashMeta(forkedAtBlock)\n // And it is on the correct forked from chain\n && forkedAtBlock.chain === forkedChainId\n // And it is the correct forked at block number\n && forkedAtBlock.block === forkedAtBlockNumber) {\n return forkedAtBlock\n }\n }\n }\n}\n","import { delay } from '@xylabs/delay'\nimport type { ArchivistInstance, WriteArchivist } from '@xyo-network/archivist-model'\nimport type { HydratedBlock } from '@xyo-network/xl1-protocol'\nimport { flattenHydratedBlock } from '@xyo-network/xl1-protocol-sdk'\n\n/**\n * Submit a new chain to the archivist.\n * @param chain The new chain to submit\n * @param chainArchivist The chain archivist instance\n * @param chainSubmissionsArchivistWrite The chain submissions archivist instance\n */\nexport const submitNewChain = async (\n chain: HydratedBlock[],\n chainArchivist: ArchivistInstance,\n chainSubmissionsArchivistWrite: WriteArchivist,\n): Promise<void> => {\n for (const block of chain) {\n const [bw] = block\n await chainSubmissionsArchivistWrite.insert(flattenHydratedBlock(block))\n // Wait for block to show up in finalized archivist\n while (true) {\n const result = await chainArchivist.get([bw._hash])\n if (result.length > 0) break\n await delay(1000) // Wait 1 second before retrying\n }\n }\n}\n","import type {\n BaseElectionServicesParams,\n Initializable,\n XyoChainIteratorParams,\n XyoStakeIntentServiceParams,\n} from '@xyo-network/chain-sdk'\nimport {\n BaseElectionService, ChainBlockNumberIterationService,\n XyoStakeIntentService,\n} from '@xyo-network/chain-sdk'\nimport type {\n ElectionService, EventingChainBlockNumberIteratorService, StakeIntentService,\n} from '@xyo-network/xl1-protocol-sdk'\n\nlet chainIteratorServiceSingleton: Promise<EventingChainBlockNumberIteratorService> | undefined\nlet stakeIntentServiceSingleton: Promise<StakeIntentService> | undefined\nlet electionServiceSingleton: Promise<ElectionService> | undefined\n\nexport const initChainIterator: Initializable<XyoChainIteratorParams, EventingChainBlockNumberIteratorService> = (params) => {\n if (chainIteratorServiceSingleton) return chainIteratorServiceSingleton\n chainIteratorServiceSingleton = ChainBlockNumberIterationService.create(params)\n return chainIteratorServiceSingleton\n}\n\nexport const initStakeIntentService: Initializable<XyoStakeIntentServiceParams, StakeIntentService>\n = (params) => {\n if (stakeIntentServiceSingleton) return stakeIntentServiceSingleton\n stakeIntentServiceSingleton = XyoStakeIntentService.create(params)\n return stakeIntentServiceSingleton\n }\n\nexport const initElectionService: Initializable<BaseElectionServicesParams, ElectionService>\n = (params) => {\n if (electionServiceSingleton) return electionServiceSingleton\n electionServiceSingleton = BaseElectionService.create(params)\n return electionServiceSingleton\n }\n","import type { Promisable } from '@xylabs/promise'\nimport type { BasePendingTransactionsServiceParams } from '@xyo-network/chain-sdk'\nimport { BasePendingTransactionsService } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { PendingTransactionsService } from '@xyo-network/xl1-protocol-sdk'\n\nlet serviceSingleton: Promisable<PendingTransactionsService> | undefined\n\nexport const initPendingTransactions: Initializable<BasePendingTransactionsServiceParams, PendingTransactionsService> = async (\n params: BasePendingTransactionsServiceParams,\n): Promise<PendingTransactionsService> => {\n if (serviceSingleton) return serviceSingleton\n serviceSingleton = await BasePendingTransactionsService.create(params)\n return serviceSingleton\n}\n","import type { Promisable } from '@xylabs/promise'\nimport type { BaseBlockProducerServiceParams } from '@xyo-network/chain-sdk'\nimport { BaseBlockProducerService } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { BlockProducerService } from '@xyo-network/xl1-protocol-sdk'\n\nlet serviceSingleton: Promisable<BlockProducerService> | undefined\n\nexport const initBlockProducer: Initializable<BaseBlockProducerServiceParams, BlockProducerService>\n = async (params: BaseBlockProducerServiceParams): Promise<BlockProducerService> => {\n if (serviceSingleton) return serviceSingleton\n serviceSingleton = await BaseBlockProducerService.create(params)\n return serviceSingleton\n }\n","import { assertEx } from '@xylabs/assert'\nimport type { BaseBlockRewardServiceParams, EvmBlockRewardServiceParams } from '@xyo-network/chain-sdk'\nimport { EvmBlockRewardService, MemoryBlockRewardService } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { BlockRewardService, Config } from '@xyo-network/xl1-protocol-sdk'\n\nimport { canUseEvmProvider, initEvmProvider } from './evm/index.ts'\n\nlet rewardServiceSingleton: Promise<BlockRewardService> | undefined\n\nexport const initBlockRewardService: Initializable<\n BaseBlockRewardServiceParams | EvmBlockRewardServiceParams,\n BlockRewardService\n> = (params): Promise<BlockRewardService> => {\n if (rewardServiceSingleton) return rewardServiceSingleton\n const { config } = params\n rewardServiceSingleton = canUseEvmBlockRewardService({ config })\n ? initEvmBlockRewardService(params as EvmBlockRewardServiceParams)\n : initXyoBlockRewardService(params)\n return rewardServiceSingleton\n}\n\nconst initXyoBlockRewardService = (params: BaseBlockRewardServiceParams): Promise<BlockRewardService> => {\n if (rewardServiceSingleton) return rewardServiceSingleton\n rewardServiceSingleton = MemoryBlockRewardService.create(params)\n return rewardServiceSingleton\n}\n\nconst canUseEvmBlockRewardService = (params: { config: Config }) => canUseEvmProvider({ config: params.config })\n\nconst initEvmBlockRewardService = async (params: EvmBlockRewardServiceParams): Promise<BlockRewardService> => {\n if (rewardServiceSingleton) return rewardServiceSingleton\n const { account: paramsAccount } = params\n const account = assertEx(paramsAccount, () => 'Error: Account is required')\n const provider = assertEx(await initEvmProvider(params))\n const evmBlockRewardServiceParams: EvmBlockRewardServiceParams = {\n ...params, provider, account,\n }\n rewardServiceSingleton = EvmBlockRewardService.create(evmBlockRewardServiceParams)\n return rewardServiceSingleton\n}\n","import type { Promisable } from '@xylabs/promise'\nimport type { BaseTimeServiceParams } from '@xyo-network/chain-sdk'\nimport { BaseTimeSyncService } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { TimeSyncService } from '@xyo-network/xl1-protocol-sdk'\n\nimport { canUseEvmProvider, initEvmProvider } from './evm/index.ts'\n\nlet timeSyncServiceSingleton: Promisable<TimeSyncService> | undefined\n\nexport const initTimeService: Initializable<BaseTimeServiceParams, TimeSyncService> = async ({\n chainArchivist, chainIterator, config, logger, meterProvider, traceProvider,\n}) => {\n if (timeSyncServiceSingleton) return timeSyncServiceSingleton\n\n // Configure provider for optional Ethereum time sync\n const ethProvider = canUseEvmProvider({ config }) ? await initEvmProvider({ config }) : undefined\n\n // Create service\n timeSyncServiceSingleton = BaseTimeSyncService.create({\n chainArchivist, chainIterator, ethProvider, logger, meterProvider, traceProvider,\n })\n return await timeSyncServiceSingleton\n}\n","import type { Promisable } from '@xylabs/promise'\nimport type { BaseAccountTransferServiceParams } from '@xyo-network/chain-sdk'\nimport { BaseAccountTransfersService } from '@xyo-network/chain-sdk'\nimport type { Initializable } from '@xyo-network/xl1-protocol'\nimport type { AccountTransfersService } from '@xyo-network/xl1-protocol-sdk'\n\nlet transferServiceSingleton: Promisable<AccountTransfersService> | undefined\n\nexport const initTransferService: Initializable<BaseAccountTransferServiceParams, AccountTransfersService>\n = async (params): Promise<AccountTransfersService> => {\n if (transferServiceSingleton) return transferServiceSingleton\n transferServiceSingleton = await BaseAccountTransfersService.create(params)\n return transferServiceSingleton\n }\n","import type {\n CreatableName, CreatableStatus, CreatableStatusReporter,\n} from '@xylabs/creatable'\nimport type { Logger } from '@xylabs/logger'\n\nexport class LoggerStatusReporter implements CreatableStatusReporter {\n protected logger: Logger\n\n protected statusMap: Record<CreatableName, CreatableStatus> = {}\n\n constructor(logger: Logger) {\n this.logger = logger\n }\n\n report(name: CreatableName, status: CreatableStatus, progress?: number | Error): void {\n this.statusMap[name] = status\n const starting = (Object.entries(this.statusMap).map(([, value]): number => value === 'starting' ? 1 : 0)).reduce((a, b) => a + b, 0)\n const started = (Object.entries(this.statusMap).map(([, value]): number => value === 'started' ? 1 : 0)).reduce((a, b) => a + b, 0)\n this.logger.info(`${started}/${starting + started} ${name} status: ${status}`, { progress })\n }\n}\n","import type { CreatableName, CreatableStatus } from '@xylabs/creatable'\n\nimport { LoggerStatusReporter } from './ServiceStatus.ts'\n\n/**\n * Enum-like record for statuses with priority allowing\n * for determination of the aggregated status.\n */\nconst statusPriority: Record<CreatableStatus, number> = {\n error: 0,\n stopped: 1,\n stopping: 2,\n creating: 3,\n created: 4,\n starting: 5,\n started: 6,\n}\n\n/**\n * A sentinel status that represents the initial state\n * before any statuses are reported.\n * It is used to ensure that the monitor has a valid status\n * even when no statuses have been reported yet and to\n * prevent the system from showing an \"error\" state\n * when no statuses are available.\n */\nconst SENTINEL_STATUS: CreatableStatus = 'starting'\n\n/**\n * Given an array of statuses, this function reduces them\n * to the minimum status based on the defined priority.\n * @param statuses An array of statuses to reduce.\n * @returns The minimum status based on priority.\n */\nconst reduceToMinimumStatus = (statuses: CreatableStatus[]): CreatableStatus => {\n let minStatus: CreatableStatus = SENTINEL_STATUS\n let minPriority = Infinity\n\n for (const status of statuses) {\n const priority = statusPriority[status]\n if (priority < minPriority) {\n minPriority = priority\n minStatus = status\n }\n }\n return minStatus\n}\n\nexport type GlobalTransitionHandler = {\n from?: CreatableStatus\n handler: (from: CreatableStatus, to: CreatableStatus) => void\n to?: CreatableStatus\n}\nexport type TransitionHandler = GlobalTransitionHandler & {\n name?: string\n}\n\nexport class RuntimeStatusMonitor extends LoggerStatusReporter {\n private globalTransitions: GlobalTransitionHandler[] = []\n private transitions: TransitionHandler[] = []\n\n getGlobalStatus(): CreatableStatus {\n // If no statuses have been reported, return the sentinel status\n if (Object.keys(this.statusMap).length === 0) return SENTINEL_STATUS\n return reduceToMinimumStatus(Object.values(this.statusMap))\n }\n\n getStatus(name: CreatableName): CreatableStatus | undefined {\n return this.statusMap[name]\n }\n\n onGlobalTransition(match: { from?: CreatableStatus; to?: CreatableStatus }, handler: (from: CreatableStatus, to: CreatableStatus) => void) {\n this.globalTransitions.push({ ...match, handler })\n }\n\n /**\n * Register a callback to be called on a specific transition.\n */\n onTransition(match: { from?: CreatableStatus; name: string; to?: CreatableStatus }, handler: (from: CreatableStatus, to: CreatableStatus) => void) {\n this.transitions.push({ ...match, handler })\n }\n\n override report(name: CreatableName, status: CreatableStatus, progress?: number | Error): void {\n // Capture the current status before updating\n const previous = this.statusMap[name]\n const previousGlobal = this.getGlobalStatus()\n\n // Update the status map with the new status\n super.report(name, status, progress)\n\n // If the status hasn't changed, do not run handlers\n if (previous === status) return\n this.runTransitions(this.transitions, previous, status, name)\n\n // If the global status hasn't changed, do not run handlers\n const globalStatus = this.getGlobalStatus()\n if (previousGlobal === globalStatus) return\n this.runTransitions(this.globalTransitions, previousGlobal, globalStatus)\n }\n\n private runTransitions(\n transitions: (TransitionHandler | GlobalTransitionHandler)[],\n prev: CreatableStatus,\n next: CreatableStatus,\n name?: string,\n ) {\n for (const {\n from, to, name: matchName, handler,\n } of transitions as TransitionHandler[]) {\n if ((matchName === undefined || matchName === name)\n && (from === undefined || from === prev)\n && (to === undefined || to === next)) {\n handler(prev, next)\n }\n }\n }\n}\n","import type { Logger } from '@xylabs/logger'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\n\nimport type { Orchestrator } from '../../orchestration/index.ts'\nimport {\n BalanceActor, ChainHeadUpdateActor, initServices, ProducerActor,\n} from '../../orchestration/index.ts'\n\ninterface RunProducerContext {\n config: Config\n logger: Logger\n orchestrator: Orchestrator\n}\n\nexport const runProducer = async (context: RunProducerContext) => {\n const {\n config, logger, orchestrator,\n } = context\n\n // Initialize services\n logger?.log('Services: Initializing...')\n const services = await initServices(context)\n logger?.log('Services: Initialized')\n\n // Create actors\n const params = { ...services, config }\n const chainHeadUpdate = await ChainHeadUpdateActor.create({ ...params, name: 'ChainHeadUpdateActor' })\n const balances = await BalanceActor.create({ ...params, name: 'BalanceActor' })\n const producer = await ProducerActor.create({ ...params, name: 'ProducerActor' })\n const actors = [chainHeadUpdate, balances, producer]\n\n for (const actor of actors) {\n // Register the actor with the orchestrator\n await orchestrator.registerActor(actor)\n }\n // Start the orchestrator => automatically activates the actor\n await orchestrator.start()\n}\n","import type { Logger } from '@xylabs/logger'\nimport { getServer } from '@xyo-network/chain-reward-redemption'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\n\ninterface RunRewardRedemptionApiContext {\n config: Config\n logger?: Logger\n}\n\nexport function runRewardRedemptionApi(context: RunRewardRedemptionApiContext) {\n void getServer(context)\n}\n","/* eslint-disable @stylistic/max-len */\nexport const XL1LogoColorizedAscii = `\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;118;111;144m_\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;72;32;223mā• \u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā ā• ā• \u001b[0m\u001b[38;2;103;85;170m_\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;79;121;152m╦\u001b[0m\u001b[38;2;82;121;151m╦\u001b[0m\u001b[38;2;112;125;136m_Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;88;59;196m[\u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;73;34;221mā–’Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;121;121;127m_\u001b[0m\u001b[38;2;100;101;128mā•”\u001b[0m\u001b[38;2;93;94;127m╦\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;82;121;151m²\u001b[0m\u001b[38;2;44;116;170mā• \u001b[0m\u001b[38;2;44;116;171mā–’\u001b[0m\u001b[38;2;51;117;167mD\u001b[0m\u001b[38;2;80;121;152m╦\u001b[0m\u001b[38;2;111;125;136m_Ā Ā Ā Ā \u001b[0m\u001b[38;2;67;23;232mā• \u001b[0m\u001b[38;2;66;21;234mā• ā• ā• Ā Ā Ā Ā \u001b[0m\u001b[38;2;120;121;128m_\u001b[0m\u001b[38;2;100;101;127mā•”\u001b[0m\u001b[38;2;79;81;127mR\u001b[0m\u001b[38;2;71;73;128mā–’\u001b[0m\u001b[38;2;71;73;128mā–’\u001b[0m\u001b[38;2;88;90;127mā•™\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;55;117;165mā•š\u001b[0m\u001b[38;2;44;116;171mā–’\u001b[0m\u001b[38;2;44;116;171mā–’ā–’\u001b[0m\u001b[38;2;50;116;167mD\u001b[0m\u001b[38;2;80;121;152m╦ \u001b[0m\u001b[38;2;106;90;165mj\u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;66;21;234mā• ā• ā• \u001b[0m\u001b[38;2;89;61;194mHĀ \u001b[0m\u001b[38;2;99;100;127mā•”\u001b[0m\u001b[38;2;79;80;127mD\u001b[0m\u001b[38;2;71;73;128mā–’\u001b[0m\u001b[38;2;71;73;128mā–’ā–’ā• \u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;83;121;150m²\u001b[0m\u001b[38;2;44;116;170mā–’\u001b[0m\u001b[38;2;44;116;171mā–’ā–’ā–’Ā \u001b[0m\u001b[38;2;76;38;217mā• \u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;66;21;234mā• ā• ā• ā• Ā \u001b[0m\u001b[38;2;74;76;128mā• \u001b[0m\u001b[38;2;71;73;128mā–’ā–’ā–’\u001b[0m\u001b[38;2;89;90;128mā•™\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;90;118;148m\\`\u001b[0m\u001b[38;2;89;107;153m_\u001b[0m\u001b[38;2;93;97;154m,\u001b[0m\u001b[38;2;105;89;166mā•“\u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;66;21;234mā• ā• ā• ā• ā• \u001b[0m\u001b[38;2;95;72;183mā•“\u001b[0m\u001b[38;2;106;96;152m_\u001b[0m\u001b[38;2;100;94;143m\\`\u001b[0m\u001b[38;2;101;100;133m\\`\u001b[0m\n\u001b[38;2;128;128;128mĀ \u001b[0m\u001b[38;2;122;118;137m_\u001b[0m\u001b[38;2;113;102;153m,\u001b[0m\u001b[38;2;108;94;161mā•“\u001b[0m\u001b[38;2;104;86;169mā•“\u001b[0m\u001b[38;2;98;77;178mā•”\u001b[0m\u001b[38;2;93;67;188mā•—\u001b[0m\u001b[38;2;88;59;196mφ\u001b[0m\u001b[38;2;83;51;204m@\u001b[0m\u001b[38;2;78;42;213mD\u001b[0m\u001b[38;2;72;32;223mā–’\u001b[0m\u001b[38;2;68;24;231mā• \u001b[0m\u001b[38;2;66;21;234mā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• \u001b[0m\u001b[38;2;71;30;225mā–’\u001b[0m\u001b[38;2;77;40;215mā–’\u001b[0m\u001b[38;2;82;49;206mK\u001b[0m\u001b[38;2;87;57;198mφ\u001b[0m\u001b[38;2;91;65;190mā•—\u001b[0m\u001b[38;2;97;75;180m╦\u001b[0m\u001b[38;2;103;84;171mā•–\u001b[0m\u001b[38;2;107;92;163m²\u001b[0m\u001b[38;2;112;101;154m_\u001b[0m\u001b[38;2;119;112;143m_\u001b[0m\n\u001b[38;2;128;128;128mĀ \u001b[0m\u001b[38;2;106;91;164m\\`\u001b[0m\u001b[38;2;94;70;185m^\u001b[0m\u001b[38;2;89;62;193mā•™\u001b[0m\u001b[38;2;85;54;201mā•™\u001b[0m\u001b[38;2;80;45;210mā•š\u001b[0m\u001b[38;2;74;35;220mā•\u001b[0m\u001b[38;2;69;26;229mā• \u001b[0m\u001b[38;2;66;22;233mā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• ā• \u001b[0m\u001b[38;2;73;33;222mā•\u001b[0m\u001b[38;2;79;43;212mā•©\u001b[0m\u001b[38;2;84;52;203mā•œ\u001b[0m\u001b[38;2;88;60;195mā•™\u001b[0m\u001b[38;2;93;68;187m^\u001b[0m\u001b[38;2;100;80;175m\\`\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;113;84;152m\\`\u001b[0m\u001b[38;2;103;79;169m'\u001b[0m\u001b[38;2;95;72;183m\"\u001b[0m\u001b[38;2;87;57;198mā•™\u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;66;21;234mā• ā• ā• ā• ā• \u001b[0m\u001b[38;2;80;46;209mā•œ\u001b[0m\u001b[38;2;94;70;185m^\u001b[0m\u001b[38;2;102;77;175m^\u001b[0m\u001b[38;2;112;81;162m\\`\u001b[0m\u001b[38;2;115;92;155m\\`\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;145;116;107m,\u001b[0m\u001b[38;2;199;82;45mā• \u001b[0m\u001b[38;2;207;77;35mā–’\u001b[0m\u001b[38;2;207;77;35mā–’ā• Ā \u001b[0m\u001b[38;2;70;28;227mā• \u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;66;21;234mā• ā• ā• ā• Ā \u001b[0m\u001b[38;2;189;49;97mĆ„\u001b[0m\u001b[38;2;203;32;90mā• \u001b[0m\u001b[38;2;203;32;90mā• ā• \u001b[0m\u001b[38;2;155;92;114m,\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;175;98;73mā•”\u001b[0m\u001b[38;2;207;77;35mā–’\u001b[0m\u001b[38;2;207;77;35mā–’ā–’ā–’\u001b[0m\u001b[38;2;197;83;47mā•©Ā \u001b[0m\u001b[38;2;98;76;179m[\u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;66;21;234mā• ā• ā• \u001b[0m\u001b[38;2;81;48;207mHĀ \u001b[0m\u001b[38;2;188;51;98mā•š\u001b[0m\u001b[38;2;203;32;90mā• \u001b[0m\u001b[38;2;203;32;90mā• ā• ā• \u001b[0m\u001b[38;2;183;57;100mH\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;146;116;106m,\u001b[0m\u001b[38;2;199;82;44mā• \u001b[0m\u001b[38;2;207;77;35mā–’\u001b[0m\u001b[38;2;207;77;35mā–’\u001b[0m\u001b[38;2;196;84;48mā•©\u001b[0m\u001b[38;2;168;102;81m^Ā Ā Ā Ā \u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;66;21;234mā• ā• ā• Ā Ā Ā Ā \u001b[0m\u001b[38;2;160;87;111m'\u001b[0m\u001b[38;2;187;52;98mā•š\u001b[0m\u001b[38;2;203;32;90mā• \u001b[0m\u001b[38;2;203;32;90mā• ā• \u001b[0m\u001b[38;2;156;91;113m,\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;198;83;46mā•©\u001b[0m\u001b[38;2;194;85;50mā•©\u001b[0m\u001b[38;2;167;102;82m^Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;81;46;209mā•š\u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;66;21;234mā• ā• Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;159;88;112m'\u001b[0m\u001b[38;2;186;53;98mā•š\u001b[0m\u001b[38;2;197;40;93mā•©\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;110;97;158m'\u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\u001b[38;2;94;69;186mH\u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;68;25;230mā• \u001b[0m\u001b[38;2;66;21;234mā• \u001b[0m\n\u001b[38;2;128;128;128mĀ Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā \u001b[0m\u001b[38;2;108;93;162m²\u001b[0m\u001b[38;2;99;79;176m^\u001b[0m`\n","import { Base } from '@xylabs/base'\nimport type { Logger, LogLevelValue } from '@xylabs/logger'\nimport {\n ConsoleLogger, LogLevel, SilentLogger,\n} from '@xylabs/logger'\nimport { isDefined } from '@xylabs/typeof'\nimport type { Config } from '@xyo-network/xl1-protocol-sdk'\n\nexport const initLogger = (config: Config): Logger => {\n let logger: Logger\n if (config.silent) {\n logger = new SilentLogger()\n } else {\n let level: LogLevelValue | undefined\n if (isDefined(config.logLevel)) {\n const parsed = LogLevel[config.logLevel.toLowerCase() as keyof typeof LogLevel]\n if (isDefined(parsed)) level = parsed\n }\n logger = new ConsoleLogger(level)\n }\n Base.defaultLogger = logger\n return logger\n}\n","import type { UsageMeta } from '@xyo-network/xl1-protocol-sdk'\nimport { isUsageMeta } from '@xyo-network/xl1-protocol-sdk'\nimport type { Options } from 'yargs'\nimport { globalRegistry } from 'zod'\n\nconst usageMetaToOptions = (meta: UsageMeta): Options => {\n return meta\n}\n\nexport const optionsFromGlobalZodRegistry = (): Record<string, Options> => {\n const opts: Record<string, Options> = {}\n for (const schema of Object.values(globalRegistry._map)) {\n if (isUsageMeta(schema)) {\n if (schema.hidden) continue // skip hidden options\n opts[schema.title] = usageMetaToOptions(schema)\n }\n }\n return opts\n}\n","import { isDefined, isNull } from '@xylabs/typeof'\nimport { cosmiconfigSync } from 'cosmiconfig'\n\n/**\n * The name of the configuration file to search for.\n */\nconst configName = 'xyo'\n\n/**\n * The name of the section within the configuration file to parse.\n */\nconst configSection = 'xl1' // Default section in the config file\n\n/**\n * Attempts to parse the configuration from a file using cosmiconfig.\n * @returns The parsed configuration object if found and valid, otherwise undefined.\n */\nexport const tryParseConfig = (): Record<string, unknown> => {\n const explorer = cosmiconfigSync(\n configName,\n /* {\n searchPlaces: [\n 'package.json', // Looks under `xyo` key in package.json\n '.xyorc.json', // Supports common dotfile format\n 'xyo.config.json', // Supports custom-named config file\n ],\n loaders: {\n '.json': defaultLoaders['.json'],\n 'noExt': defaultLoaders['.json'],\n },\n }, */\n )\n const result = explorer.search()\n if (!isNull(result)) {\n const section = result?.config?.[configSection]\n if (isDefined(section) && typeof section === 'object') {\n return section\n }\n }\n return {}\n}\n","import net from 'node:net'\n\nexport const waitForHostPort = (host: string, port: number): Promise<void> => {\n return new Promise((resolve) => {\n const tryConnect = () => {\n const socket = new net.Socket()\n\n socket\n .setTimeout(1000)\n .once('error', () => {\n socket.destroy()\n setTimeout(tryConnect, 500) // retry after 500ms\n })\n .once('timeout', () => {\n socket.destroy()\n setTimeout(tryConnect, 500)\n })\n .connect(port, host, () => {\n socket.end()\n resolve()\n })\n }\n\n tryConnect()\n })\n}\n","import { start } from './start.ts'\n\nstart().catch((err) => {\n // If we're in development mode, log the stack trace to the console\n if (process.env.NODE_ENV === 'development') console.error('An error occurred during startup:', err)\n // eslint-disable-next-line unicorn/no-process-exit\n process.exit(1)\n})\n"],"mappings":";;;;AAAA,SAASA,cAAc;;;ACCvB,SAASC,iBAAiB;AAC1B,SAASC,a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IAAc,CAAA;AAE3C,UAAMoD,gBAAgBpD,cAAcuD,IAAIF,MAAMrD,cAAcuD,IAAID,IAAI;AAEpE,UAAMN,YAAY;MAAE,GAAGL;MAASE,QAAQ7C;IAAc,CAAA;EACxD,CAAA,EACCwD,KAAI,EACJC,MAAM,QAAQ,GAAA,EACdxD,QAAQA,OAAAA,EACRmB;AAEH,QAAMA;AACR;AAlGsBJ;;;ADrDf,IAAM0C,QAAQ,mCAAA;AACnBC,SAAO;IAAEC,OAAO;EAAK,CAAA;AACrB,QAAMC,OAAAA;AACR,GAHqB;;;AgEFrBC,MAAAA,EAAQC,MAAM,CAACC,QAAAA;AAEb,MAAIC,QAAQC,IAAIC,aAAa,cAAeC,SAAQC,MAAM,qCAAqCL,GAAAA;AAE/FC,UAAQK,KAAK,CAAA;AACf,CAAA;","names":["config","deepMerge","isDefined","ConfigZod","yargs","hideBin","ZodError","getServer","runApi","context","getServer","getServer","runBridge","context","getServer","getServer","runMempool","context","getServer","assertEx","PayloadBuilder","Mutex","Base","delay","IdLogger","span","spanRootAsync","Semaphore","Actor","Base","_intervals","Map","_semaphores","_timeouts","_active","_displayName","_id","id","displayName","params","logger","IdLogger","defaultLogger","console","name","logPrefix","registerTimer","timerName","callback","dueTimeMs","periodMs","warn","running","set","Semaphore","timeoutId","setTimeout","intervalId","setInterval","semaphore","get","has","isLocked","acquire","then","release","startTime","Date","now","duration","catch","error","finally","log","span","fn","tracer","spanAsync","spanRootAsync","start","Promise","resolve","stop","all","values","map","delay","clear","timeoutRef","entries","clearTimeout","intervalRef","clearInterval","Orchestrator","actors","keepAliveHandle","logger","running","registerActor","actor","start","push","Promise","resolve","warn","log","setInterval","stop","clearInterval","BalanceActor","Actor","_updateMutex","Mutex","params","balanceService","assertEx","balance","chainIterator","create","start","on","updateBalance","registerTimer","isLocked","runExclusive","head","PayloadBuilder","hash","balances","filterAs","assertEx","toHex","findMostRecentBlock","sortBlocks","asBlockBoundWitness","ChainHeadUpdateActor","Actor","params","chainFinalizedArchivist","assertEx","chainArchivist","chainIterator","create","start","on","data","checkInsertedForNewHead","registerTimer","pollForNewHead","candidateBlock","sortBlocks","filterAs","payloads","asBlockBoundWitness","at","updateHeadIfNewer","findMostRecentBlock","currentHead","head","candidateBlockNumber","block","candidateBlockNumberDisplay","toHex","currentBlockNumber","logger","log","updateHead","assertEx","toHex","isDefined","isUndefined","BaseBlockProducerService","createDeclarationIntent","PayloadBuilder","PayloadBundleSchema","buildTransaction","flattenHydratedBlock","flattenHydratedTransaction","SHOULD_REGISTER_REDECLARATION_INTENT_TIMER","TEN_MINUTES","ProducerActor","Actor","_lastProducedBlock","_lastRedeclarationIntent","params","producer","address","account","assertEx","balanceService","balance","chainIterator","chainStakeViewer","chainSubmissionsArchivistWrite","pendingBundledTransactionsArchivistWrite","stakeIntentService","stakeIntent","create","start","registerTimer","produceBlock","redeclareIntent","calculateBlocksUntilProducerDeclarationExpiration","currentBlock","ranges","getDeclaredCandidateRanges","lastRange","toSorted","a","b","at","currentDeclarationEnd","undefined","timeToProducerExpiration","spanAsync","headStart","Date","now","head","headDuration","logger","warn","toHex","_hash","headHash","previous","log","block","nextStart","nextBlock","next","nextDuration","displayBlockNumber","insert","flattenHydratedBlock","config","disableIntentRedeclaration","isUndefined","blocksUntilExpiration","BaseBlockProducerService","RedeclarationWindow","exp","validateCurrentBalance","error","validateCurrentStake","chain","id","redeclarationIntent","createDeclarationIntent","RedeclarationDuration","submitRedeclarationIntent","tx","buildTransaction","chainId","payloads","flattenHydratedTransaction","root","payloadBundle","PayloadBuilder","schema","PayloadBundleSchema","fields","build","isDefined","balances","currentBalance","requiredMinimumStake","getRequiredMinimumStakeForIntent","currentStake","activeByStaked","http","isDefined","sendStatus","res","status","errorCode","statusCode","writeHead","end","JSON","stringify","notFound","createHealthServer","port","statusMonitor","logger","server","http","createServer","req","url","getGlobalStatus","listen","log","initHealthEndpoints","params","config","statusReporter","healthCheckPort","producer","isDefined","undefined","assertEx","asAddress","isDefined","initTelemetry","startupSpanAsync","StepSizes","validateHydratedBlockState","readPayloadMapFromStore","CompletedStepRewardAddressValidatorFactory","DerivedReceiveAddressValidatorFactory","SelfSignerValidator","TransactionTransfersValidatorFactory","Semaphore","initArchivistSync","startupSpanAsync","Mutex","Mutex","rm","Path","LmdbArchivist","LmdbArchivistConfigSchema","getStoreDirectory","DEFAULT_STORAGE_ROOT","Path","join","process","cwd","getLocalPersistentArchivist","name","dbName","storeName","storageRoot","kind","root","LmdbArchivist","create","account","config","clearStoreOnStart","location","getStoreDirectory","schema","LmdbArchivistConfigSchema","mutex","Mutex","singleton","initLocalChainFinalizedArchivist","config","runExclusive","root","storage","getLocalPersistentArchivist","assertEx","initBridge","initBridgedArchivistModule","getUrl","Mutex","mutex","Mutex","singleton","initRemoteChainFinalizedArchivist","config","runExclusive","host","port","mempool","enabled","api","nodeUrl","getUrl","bridge","initBridge","initBridgedArchivistModule","moduleName","assertEx","mutex","Mutex","singleton","initChainFinalizedArchivist","config","logger","traceProvider","runExclusive","remote","local","Promise","all","startupSpanAsync","initRemoteChainFinalizedArchivist","initLocalChainFinalizedArchivist","initArchivistSync","Number","MAX_SAFE_INTEGER","assertEx","startupSpanAsync","Mutex","assertEx","initBridge","initBridgedArchivistModule","getUrl","Mutex","mutex","Mutex","singleton","initRemoteChainSubmissionsArchivist","config","runExclusive","host","port","mempool","enabled","api","nodeUrl","getUrl","bridge","initBridge","initBridgedArchivistModule","moduleName","assertEx","Error","mutex","Mutex","singleton","initChainSubmissionsArchivist","params","runExclusive","remote","startupSpanAsync","initRemoteChainSubmissionsArchivist","assertEx","Error","initArchivistSync","startupSpanAsync","Mutex","MemoryArchivist","MemoryArchivistConfigSchema","Mutex","mutex","Mutex","singleton","initLocalPendingTransactionsArchivist","runExclusive","MemoryArchivist","create","account","config","schema","MemoryArchivistConfigSchema","max","name","assertEx","initBridge","initBridgedArchivistModule","getUrl","Mutex","mutex","Mutex","singleton","initRemotePendingTransactionsArchivist","config","runExclusive","host","port","mempool","enabled","api","nodeUrl","getUrl","bridge","initBridge","initBridgedArchivistModule","moduleName","assertEx","mutex","Mutex","singleton","initPendingBundledTransactionsArchivist","params","runExclusive","remote","startupSpanAsync","initRemotePendingTransactionsArchivist","local","initLocalPendingTransactionsArchivist","start","next","limit","order","insert","initArchivistSync","startupSpanAsync","Mutex","MemoryArchivist","MemoryArchivistConfigSchema","Mutex","mutex","Mutex","singleton","initLocalRejectedTransactionsArchivist","runExclusive","MemoryArchivist","create","account","config","schema","MemoryArchivistConfigSchema","max","name","mutex","Mutex","singleton","initRejectedTransactionsArchivist","params","runExclusive","local","startupSpanAsync","initLocalRejectedTransactionsArchivist","assertEx","startupSpanAsync","Mutex","assertEx","Mutex","mutex","Mutex","singleton","initLocalStakeIntentStateArchivist","config","runExclusive","root","storage","getLocalPersistentArchivist","assertEx","Error","mutex","Mutex","singleton","initStakeIntentStateArchivist","params","runExclusive","local","startupSpanAsync","initLocalStakeIntentStateArchivist","assertEx","isDefined","startupSpanAsync","Mutex","isDefined","getLocalPersistentMap","Mutex","mutex","Mutex","singleton","initLocalBalanceSummaryMap","params","runExclusive","isDefined","root","config","storage","getLocalPersistentMap","mutex","Mutex","singleton","initBalanceSummaryMap","params","runExclusive","isDefined","local","startupSpanAsync","initLocalBalanceSummaryMap","isDefined","startupSpanAsync","Mutex","isDefined","getLocalPersistentMap","Mutex","mutex","Mutex","singleton","initLocalTransferSummaryMap","params","runExclusive","isDefined","root","config","storage","getLocalPersistentMap","mutex","Mutex","singleton","initTransferSummaryMap","params","runExclusive","isDefined","local","startupSpanAsync","initLocalTransferSummaryMap","isUndefined","HDWallet","ADDRESS_INDEX","generateXyoBaseWalletFromPhrase","accountServiceSingleton","initAccount","config","logger","walletPhrase","producer","mnemonic","isUndefined","warn","randomMnemonic","HDWallet","generateMnemonic","wallet","generateXyoBaseWalletFromPhrase","account","derivePath","ADDRESS_INDEX","XYO","BaseAccountBalanceService","balanceServiceSingleton","initBalanceService","params","BaseAccountBalanceService","create","MemoryChainService","assertEx","asAddress","ZERO_ADDRESS","isDefined","EvmChainService","Wallet","assertEx","assertEx","isDefined","InfuraProvider","assertEx","hexFrom","isHex","isDefined","canUseChainId","config","isDefined","evm","chainId","getChainId","assertEx","isHex","prefix","hex","hexFrom","parsed","Number","parseInt","instance","initInfuraProvider","config","providerConfig","getInfuraProviderConfig","Promise","resolve","InfuraProvider","canUseInfuraProvider","canUseChainId","isDefined","evm","infura","projectId","projectSecret","assertEx","getChainId","assertEx","isDefined","JsonRpcProvider","initJsonRpcProvider","config","providerConfig","getJsonRpcProviderConfig","Promise","resolve","JsonRpcProvider","canUseJsonRpcProvider","canUseChainId","isDefined","evm","jsonRpc","url","jsonRpcUrl","assertEx","getChainId","provider","initEvmProvider","config","canUseInfuraProvider","initInfuraProvider","canUseJsonRpcProvider","initJsonRpcProvider","assertEx","canUseEvmProvider","chainStakeServiceSingleton","canUseEvmContractChainService","config","id","chain","isDefined","ZERO_ADDRESS","canUseEvmProvider","initEvmContractChainService","account","traceProvider","meterProvider","logger","emvStakingContractAddress","assertEx","asAddress","provider","initEvmProvider","privateKey","private","hex","runner","Wallet","EvmChainService","create","chainStakeServiceSingleton","initChainService","account","config","init","name","params","canUseEvmContractChainService","initEvmContractChainService","MemoryChainService","create","assertEx","isDefined","findMostRecentBlock","buildNextBlock","createDeclarationIntent","createGenesisBlock","createBootstrapHead","account","chainService","chainId","chain","genesisBlock","createGenesisBlock","address","push","producerDeclarationPayload","createDeclarationIntent","block","producerDeclarationBlock","buildNextBlock","BridgeDestinationObservationSchema","buildNextBlock","PayloadBuilder","toHex","toHex","AttoXL1ConvertFactor","getForkBlockReward","AttoXL1ConvertFactor","xl1","getForkBlockRewardHex","toHex","ethChainId","toHex","bridgeableTokenContract","bridgeDestAddress","destConfirmation","getBridgeDestChainId","getBridgeDestToken","getBridgeDestAddress","getBridgeDestAmount","getForkBlockRewardHex","getBridgeDestConfirmation","getBridgeDestinationDetails","dest","destToken","destAddress","destAmount","getBridgeSrcChainId","chainService","chainId","getBridgeSrcAddress","account","address","getBridgeSrcToken","getBridgeSrcAmount","getForkBlockRewardHex","getBridgeSourceDetails","src","srcAddress","srcToken","srcAmount","getBridgeDestinationObservation","previousBlock","account","chainService","bridgeDestinationObservationFields","getBridgeSourceDetails","getBridgeDestinationDetails","destConfirmation","getBridgeDestConfirmation","bridgeDestinationObservation","PayloadBuilder","schema","BridgeDestinationObservationSchema","fields","build","buildNextBlock","BridgeIntentSchema","buildNextBlock","createTransferPayload","XYO_BRIDGE_ADDRESS","PayloadBuilder","getBridgeIntent","previousBlock","account","chainService","transferPayload","createTransferPayload","address","XYO_BRIDGE_ADDRESS","getForkBlockReward","nonce","Date","now","bridgeIntentFields","getBridgeSourceDetails","getBridgeDestinationDetails","bridgeIntent","PayloadBuilder","schema","BridgeIntentSchema","fields","build","buildNextBlock","BridgeSourceObservationSchema","buildNextBlock","PayloadBuilder","getBridgeSourceObservation","previousBlock","account","chainService","srcTxHash","_hash","bridgeSourceObservationFields","getBridgeSourceDetails","getBridgeDestinationDetails","srcConfirmation","bridgeSourceObservation","PayloadBuilder","schema","BridgeSourceObservationSchema","fields","build","buildNextBlock","AttoXL1","buildBlock","XYO_STEP_REWARD_ADDRESS","getFirstBlockForNewChain","forkBlock","account","chainService","_hash","previousBlockHash","block","previousBlockNumber","step_hashes","previousStepHashes","protocol","chainId","options","blockPayloads","signers","txs","chainStepRewardAddress","XYO_STEP_REWARD_ADDRESS","stepRewardPoolBalance","AttoXL1","buildBlock","createForkedHead","forkFromBlock","account","chainService","chain","firstBlockForNewChain","getFirstBlockForNewChain","push","bridgeIntent","getBridgeIntent","bridgeSourceObservation","getBridgeSourceObservation","bridgeDestinationObservation","getBridgeDestinationObservation","asHash","hexFromBigInt","isDefined","isBlockBoundWitnessWithHashMeta","getForkFromBlock","head","chainService","chainArchivist","chain","chainId","forkedAtBigInt","forkedAtHash","forkedAtHex","hexFromBigInt","asHash","isDefined","forkedAtBlock","get","forkedChainId","forkedAtBlockNumber","Number","isBlockBoundWitnessWithHashMeta","block","delay","flattenHydratedBlock","submitNewChain","chain","chainArchivist","chainSubmissionsArchivistWrite","block","bw","insert","flattenHydratedBlock","result","get","_hash","length","delay","headSingleton","initHead","params","account","chainArchivist","chainSubmissionsArchivistWrite","chainService","head","findMostRecentBlock","forkFromBlock","getForkFromBlock","isDefined","chain","createForkedHead","submitNewChain","newBlock","assertEx","at","Error","createBootstrapHead","BaseElectionService","ChainBlockNumberIterationService","XyoStakeIntentService","chainIteratorServiceSingleton","stakeIntentServiceSingleton","electionServiceSingleton","initChainIterator","params","ChainBlockNumberIterationService","create","initStakeIntentService","XyoStakeIntentService","initElectionService","BaseElectionService","BasePendingTransactionsService","serviceSingleton","initPendingTransactions","params","BasePendingTransactionsService","create","BaseBlockProducerService","serviceSingleton","initBlockProducer","params","BaseBlockProducerService","create","assertEx","EvmBlockRewardService","MemoryBlockRewardService","rewardServiceSingleton","initBlockRewardService","params","config","canUseEvmBlockRewardService","initEvmBlockRewardService","initXyoBlockRewardService","MemoryBlockRewardService","create","canUseEvmProvider","account","paramsAccount","assertEx","provider","initEvmProvider","evmBlockRewardServiceParams","EvmBlockRewardService","BaseTimeSyncService","timeSyncServiceSingleton","initTimeService","chainArchivist","chainIterator","config","logger","meterProvider","traceProvider","ethProvider","canUseEvmProvider","initEvmProvider","undefined","BaseTimeSyncService","create","BaseAccountTransfersService","transferServiceSingleton","initTransferService","params","BaseAccountTransfersService","create","LoggerStatusReporter","logger","statusMap","report","name","status","progress","starting","Object","entries","map","value","reduce","a","b","started","info","statusPriority","error","stopped","stopping","creating","created","starting","started","SENTINEL_STATUS","reduceToMinimumStatus","statuses","minStatus","minPriority","Infinity","status","priority","RuntimeStatusMonitor","LoggerStatusReporter","globalTransitions","transitions","getGlobalStatus","Object","keys","statusMap","length","values","getStatus","name","onGlobalTransition","match","handler","push","onTransition","report","progress","previous","previousGlobal","runTransitions","globalStatus","prev","next","from","to","matchName","undefined","isStartable","value","isDefined","start","initServices","context","config","logger","statusReporter","RuntimeStatusMonitor","onGlobalTransition","to","log","error","process","exit","startupSpanAsync","initHealthEndpoints","otlpEndpoint","telemetry","otel","telemetryConfig","attributes","serviceName","serviceVersion","metricsConfig","endpoint","port","traceProvider","meterProvider","account","Promise","all","initTelemetry","initAccount","allowedRewardRedeemers","validation","allowedRewardEscrowAccountSigners","initParams","chainArchivist","pendingBundledTransactionsArchivist","pendingBundledTransactionsArchivistWrite","rejectedTransactionsArchivist","chainSubmissionsArchivistWrite","stakeIntentStateArchivist","chainService","balanceSummaryMap","transferSummaryMap","initChainFinalizedArchivist","initPendingBundledTransactionsArchivist","initRejectedTransactionsArchivist","initChainSubmissionsArchivist","initStakeIntentStateArchivist","initChainService","name","initBalanceSummaryMap","initTransferSummaryMap","chainId","chainMap","readPayloadMapFromStore","chainContractViewer","chainStakeViewer","chainStaker","head","initHead","additionalPendingTransactionValidators","TransactionTransfersValidatorFactory","SelfSignerValidator","CompletedStepRewardAddressValidatorFactory","DerivedReceiveAddressValidatorFactory","pendingTransactionsService","rewardService","chainIterator","initPendingTransactions","initBlockRewardService","initChainIterator","balanceService","initBalanceService","stepSemaphores","StepSizes","map","Semaphore","store","_hash","block","summaryMap","initTransferService","stakeIntentService","time","initStakeIntentService","initTimeService","electionService","initElectionService","validatorParams","validateHydratedBlockState","rewardAddress","producer","assertEx","asAddress","address","producerParams","initBlockProducer","result","balance","election","pendingTransactions","reward","stakeIntent","startableServices","Object","values","filter","service","every","Boolean","runProducer","context","config","logger","orchestrator","log","services","initServices","params","chainHeadUpdate","ChainHeadUpdateActor","create","name","balances","BalanceActor","producer","ProducerActor","actors","actor","registerActor","start","getServer","runRewardRedemptionApi","context","getServer","XL1LogoColorizedAscii","Base","ConsoleLogger","LogLevel","SilentLogger","isDefined","initLogger","config","logger","silent","SilentLogger","level","isDefined","logLevel","parsed","LogLevel","toLowerCase","ConsoleLogger","Base","defaultLogger","isUsageMeta","globalRegistry","usageMetaToOptions","meta","optionsFromGlobalZodRegistry","opts","schema","Object","values","globalRegistry","_map","isUsageMeta","hidden","title","isDefined","isNull","cosmiconfigSync","configName","configSection","tryParseConfig","explorer","cosmiconfigSync","result","search","isNull","section","config","isDefined","net","waitForHostPort","host","port","Promise","resolve","tryConnect","socket","net","Socket","setTimeout","once","destroy","connect","end","configuration","version","isDefined","__VERSION__","getContextFromConfig","logger","initLogger","orchestrator","Orchestrator","process","on","log","stop","exit","err","error","runCLI","y","yargs","hideBin","argv","usage","XL1LogoColorizedAscii","parserConfiguration","env","scriptName","middleware","parsedConfigFile","tryParseConfig","parsedConfigArgs","mergedConfig","deepMerge","ConfigZod","parse","ZodError","console","message","Error","options","optionsFromGlobalZodRegistry","wrap","terminalWidth","command","context","runApi","config","runBridge","runMempool","runProducer","runRewardRedemptionApi","mempool","enabled","waitForHostPort","host","port","api","help","alias","start","config","quiet","runCLI","start","catch","err","process","env","NODE_ENV","console","error","exit"]}