@xyo-network/chain-bridge 1.23.0 → 1.23.2

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 (30) hide show
  1. package/dist/node/index.mjs +1251 -1083
  2. package/dist/node/index.mjs.map +7 -1
  3. package/dist/node/server/routes/bridge/routeDefinitions/getRouteDefinitions.d.ts.map +1 -1
  4. package/dist/node/server/routes/bridge/routeDefinitions/routes/bridgeFromRemoteEstimate.d.ts +93 -0
  5. package/dist/node/server/routes/bridge/routeDefinitions/routes/bridgeFromRemoteEstimate.d.ts.map +1 -0
  6. package/dist/node/server/routes/bridge/routeDefinitions/routes/bridgeFromRemoteStatus.d.ts.map +1 -1
  7. package/dist/node/server/routes/bridge/routeDefinitions/routes/bridgeToRemoteEstimate.d.ts +1 -1
  8. package/dist/node/server/routes/bridge/routeDefinitions/routes/bridgeToRemoteMaxEstimate.d.ts +1 -1
  9. package/dist/node/server/routes/bridge/routeDefinitions/routes/index.d.ts +1 -0
  10. package/dist/node/server/routes/bridge/routeDefinitions/routes/index.d.ts.map +1 -1
  11. package/dist/node/services/BridgeFulfillmentState.d.ts +1 -1
  12. package/dist/node/services/IBridgeServiceCollection.d.ts +4 -0
  13. package/dist/node/services/IBridgeServiceCollection.d.ts.map +1 -1
  14. package/dist/node/services/evm/getRemoteConfirmationDepth.d.ts.map +1 -1
  15. package/dist/node/services/getServices.d.ts.map +1 -1
  16. package/dist/node/services/queue/flows/createEthToXl1BridgeJob/createEthToXl1BridgeJob.d.ts +1 -1
  17. package/dist/node/services/queue/workers/Xl1ReserveTxFulfillment.d.ts.map +1 -1
  18. package/dist/node/services/queue/workers/util/buildEthToXl1BridgePayloads.d.ts +44 -0
  19. package/dist/node/services/queue/workers/util/buildEthToXl1BridgePayloads.d.ts.map +1 -0
  20. package/dist/node/services/queue/workers/util/buildEthToXl1ReserveTx.d.ts +22 -6
  21. package/dist/node/services/queue/workers/util/buildEthToXl1ReserveTx.d.ts.map +1 -1
  22. package/dist/node/services/queue/workers/util/index.d.ts +1 -0
  23. package/dist/node/services/queue/workers/util/index.d.ts.map +1 -1
  24. package/dist/node/services/queue/workers/util/resolveEvmBlockTagAtDepth.d.ts +18 -7
  25. package/dist/node/services/queue/workers/util/resolveEvmBlockTagAtDepth.d.ts.map +1 -1
  26. package/dist/node/services/validation/index.d.ts +1 -0
  27. package/dist/node/services/validation/index.d.ts.map +1 -1
  28. package/dist/node/services/validation/validateAmountMeetsMinBridgeAmount.d.ts +20 -0
  29. package/dist/node/services/validation/validateAmountMeetsMinBridgeAmount.d.ts.map +1 -0
  30. package/package.json +26 -26
@@ -1 +1,7 @@
1
- {"version":3,"sources":["../../src/BridgeActor.ts","../../src/server/app.ts","../../src/services/queue/connection.ts","../../src/services/queue/flowProducer.ts","../../src/services/queue/prefix.ts","../../src/services/queue/workers/EthEventVerification.ts","../../src/services/queue/workers/util/buildEthToXl1ReserveTx.ts","../../src/services/queue/workers/util/resolveEvmBlockTagAtDepth.ts","../../src/services/queue/workers/util/submitEthTransaction.ts","../../src/services/queue/workers/util/submitXl1Transaction.ts","../../src/services/queue/workers/util/verifyEthBridgeEvent.ts","../../src/services/queue/workers/EthToXl1BridgeParent.ts","../../src/services/queue/workers/EthTransactionMonitor.ts","../../src/services/queue/workers/EthTransactionPreparation.ts","../../src/services/validation/validateBridgeEstimateExact.ts","../../src/services/evm/asChainId.ts","../../src/services/evm/asToken.ts","../../src/services/evm/getBridgeEscrowAddress.ts","../../src/services/evm/getBridgeFeesAddress.ts","../../src/services/evm/getFeeStructure.ts","../../src/services/evm/getMaxBridgeAmount.ts","../../src/services/evm/getMinBridgeAmount.ts","../../src/services/evm/getRemoteChainId.ts","../../src/services/evm/getRemoteTokenAddress.ts","../../src/services/evm/getBridgeWalletAccount.ts","../../src/services/evm/getTransferAddresses.ts","../../src/services/evm/getXl1ChainId.ts","../../src/services/evm/getXl1TokenAddress.ts","../../src/services/evm/getBridgeSettings.ts","../../src/services/evm/getRemoteConfirmationDepth.ts","../../src/services/evm/getScannerIntervalMs.ts","../../src/services/util/calculateBridgeFees.ts","../../src/services/util/calculateMaxBridgeAmount.ts","../../src/services/util/createBridgeTransfer.ts","../../src/services/util/generateBridgeEstimate.ts","../../src/services/validation/validateBridgeTransaction.ts","../../src/services/validation/validateSufficientLiquiditySourceAllowance.ts","../../src/services/validation/validateSufficientLiquiditySourceBalance.ts","../../src/services/validation/validateSufficientRunnerEthBalanceForGas.ts","../../src/services/validation/validateSufficientXl1ReserveBalance.ts","../../src/services/validation/validateSufficientXL1SourceAddressBalance.ts","../../src/services/queue/workers/EthTransactionSubmission.ts","../../src/services/queue/workers/EthTransactionSubmissionStorage.ts","../../src/services/queue/workers/Xl1ReserveTxFulfillment.ts","../../src/services/queue/workers/Xl1ToEthBridgeParent.ts","../../src/services/queue/workers/Xl1TransactionMonitor.ts","../../src/services/queue/workers/Xl1TransactionPreparation.ts","../../src/services/queue/workers/Xl1TransactionSubmission.ts","../../src/services/queue/workers/Xl1TransactionSubmissionStorage.ts","../../src/services/queue/workers/createWorkers.ts","../../src/services/queue/flows/createEthToXl1BridgeJob/getJobIdForEthToXl1BridgeJob.ts","../../src/services/queue/flows/createEthToXl1BridgeJob/createEthToXl1BridgeJob.ts","../../src/services/queue/flows/createXl1ToEthBridgeJob/getJobIdForXl1ToEthBridgeJob.ts","../../src/services/queue/flows/createXl1ToEthBridgeJob/createXl1ToEthBridgeJob.ts","../../src/services/queue/flows/createXl1ToEthBridgeJob/getXl1ToEthBridgeJob.ts","../../src/services/queue/getEthToXl1Queues.ts","../../src/services/queue/getXl1ToEthQueueJobs.ts","../../src/services/queue/getXl1ToEthQueues.ts","../../src/services/queue/scanner/createEnqueueEthToXl1Bridge.ts","../../src/services/queue/scanner/EvmBridgeScanner.ts","../../src/services/queue/scanner/EvmBridgeCursor.ts","../../src/services/queue/scanner/EvmBridgeScannerRunner.ts","../../src/services/queue/scanner/buildEvmBridgeScannerRunner.ts","../../src/services/queue/telemetry.ts","../../src/server/addFlowProducer.ts","../../src/server/instrumentation.ts","../../src/server/routes/livez/get.ts","../../src/server/routes/readyz/get.ts","../../src/server/routes/startupz/get.ts","../../src/server/routes/addProbeRoutes.ts","../../src/server/routes/bridge/routeDefinitions/routes/bridgeConfig.ts","../../src/server/routes/bridge/routeDefinitions/routes/bridgeFromRemoteStatus.ts","../../src/server/routes/bridge/routeDefinitions/pathParams/ChainIdPathParam.ts","../../src/server/routes/bridge/routeDefinitions/routes/bridgeToRemote.ts","../../src/server/routes/bridge/routeDefinitions/routes/bridgeToRemoteEstimate.ts","../../src/server/routes/bridge/routeDefinitions/routes/bridgeToRemoteMaxEstimate.ts","../../src/server/routes/bridge/routeDefinitions/routes/bridgeToRemoteStatus.ts","../../src/server/routes/bridge/routeDefinitions/getRouteDefinitions.ts","../../src/server/routes/bridge/addBridgeRoutes.ts","../../src/server/routes/addRoutes.ts","../../src/services/getServices.ts","../../src/services/getIterableMap.ts","../../src/server/addWorkers.ts","../../src/server/server.ts","../../src/telemetry/createBalanceMonitor.ts","../../src/telemetry/createQueueMetrics.ts","../../src/command.ts","../../src/run.ts"],"sourcesContent":["import type { Server } from 'node:http'\n\nimport { creatable } from '@xylabs/sdk-js'\nimport type {\n ActorCapabilityNeeds, ActorParamsV3, BridgeConfig,\n} from '@xyo-network/chain-orchestration'\nimport { ActorV3, asBridgeConfigContext } from '@xyo-network/chain-orchestration'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\nimport { XyoGatewayRunnerMoniker, XyoViewerMoniker } from '@xyo-network/xl1-sdk'\n\nimport { getServer } from './server/index.ts'\nimport {\n buildEvmBridgeScannerRunner,\n type EvmBridgeScannerRunnerHandle,\n getConnection,\n getEthToXl1Queues,\n getFlowProducer,\n getTelemetry,\n getXl1ToEthQueues,\n} from './services/queue/index.ts'\nimport type { BalanceMonitorHandle, QueueMetricsHandle } from './telemetry/index.ts'\nimport { createBalanceMonitor, createQueueMetrics } from './telemetry/index.ts'\n\nexport type BridgeActorParams = ActorParamsV3<{\n config: BridgeConfig\n}>\n\n@creatable()\nexport class BridgeActor extends ActorV3<BridgeActorParams> {\n static readonly needs: ActorCapabilityNeeds = {\n required: [\n XyoGatewayRunnerMoniker,\n XyoViewerMoniker,\n ],\n }\n\n protected _gatewayRunner!: XyoGatewayRunner\n private _balanceMonitor?: BalanceMonitorHandle\n private _queueMetrics?: QueueMetricsHandle\n private _scannerRunner?: EvmBridgeScannerRunnerHandle\n private server?: Server\n\n protected get gatewayRunner() {\n return this._gatewayRunner\n }\n\n override async createHandler() {\n await super.createHandler()\n this._gatewayRunner = await this.locator.getInstance(XyoGatewayRunnerMoniker)\n }\n\n override async startHandler() {\n await super.startHandler()\n this.stopServer()\n await this.startServer()\n }\n\n override async stopHandler() {\n await super.stopHandler()\n // Stop the scanner first so no new flows enqueue while we're tearing down.\n await this._scannerRunner?.stop()\n this._scannerRunner = undefined\n this._balanceMonitor?.stop()\n this._queueMetrics?.stop()\n this._balanceMonitor = undefined\n this._queueMetrics = undefined\n this.stopServer()\n }\n\n private async startServer() {\n const context = asBridgeConfigContext(this.context, true)\n const config = context.config as BridgeConfig\n const { server, services } = await getServer(context, this._gatewayRunner)\n this.server = server\n\n // Start the EVM->XL1 scanner runner. Reuses the same Redis connection +\n // BullMQ telemetry the workers were registered against in addWorkers.\n const connection = getConnection(config)\n const telemetry = getTelemetry()\n const flowProducer = getFlowProducer(connection, telemetry)\n this._scannerRunner = buildEvmBridgeScannerRunner({\n config,\n connection,\n flowProducer,\n logger: this.logger,\n services,\n telemetry,\n })\n await this._scannerRunner.start()\n\n if (this.meter) {\n this._balanceMonitor = createBalanceMonitor({\n account: services.account,\n bridge: services.bridge,\n bridgeableToken: services.bridgeableToken,\n gateway: services.gateway,\n meter: this.meter,\n provider: services.provider,\n wallet: services.wallet,\n })\n this._balanceMonitor.start()\n\n // Merge both directions' queue handles. Shared queue keys (xl1Transaction*) collide\n // on the same property name so spread-merge dedupes naturally — the EVM->XL1 set\n // adds the new ethEventVerification + ethToXl1BridgeParent without doubling up.\n const queues = {\n ...getXl1ToEthQueues(config),\n ...getEthToXl1Queues(config),\n }\n this._queueMetrics = createQueueMetrics({\n meter: this.meter,\n queues,\n })\n this._queueMetrics.start()\n }\n }\n\n private stopServer() {\n this.server?.close()\n this.server = undefined\n }\n}\n","import { standardErrors } from '@xylabs/express'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { sharedMiddleware } from '@xyo-network/chain-orchestration'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\nimport type { Express } from 'express'\nimport express from 'express'\n\nimport { addFlowProducer } from './addFlowProducer.ts'\nimport { addInstrumentation } from './instrumentation.ts'\nimport { addRoutes } from './routes/index.ts'\n\nexport const getApp = (config: BridgeConfig, gateway: XyoGatewayRunner): Express => {\n addInstrumentation()\n const app = express()\n sharedMiddleware(app)\n addFlowProducer(app, config)\n addRoutes(app, config, gateway)\n app.use(standardErrors)\n return app\n}\n","import { isDefined } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { Redis } from 'ioredis'\n\nlet connection: Redis | undefined\n\nconst maxRetriesPerRequest = null\n\nexport const getConnection = (config: BridgeConfig) => {\n if (isDefined(connection)) return connection\n const { redisHost: host, redisPort: port } = config\n connection = new Redis({\n host, port, maxRetriesPerRequest,\n })\n return connection\n}\n","import { isDefined } from '@xylabs/sdk-js'\nimport { FlowProducer } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport { prefix } from './prefix.ts'\n\nlet flowProducer: FlowProducer | undefined\n\nexport const getFlowProducer = (connection: Redis, telemetry?: BullMQOtel) => {\n if (isDefined(flowProducer)) return flowProducer\n flowProducer = new FlowProducer({\n connection, telemetry, prefix,\n })\n return flowProducer\n}\n","export const prefix = 'xl1-bridge'\n","import { assertEx, isNull } from '@xylabs/sdk-js'\nimport type { Job } from 'bullmq'\nimport { UnrecoverableError, Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport type { IBridgeServiceCollection } from '../../index.ts'\nimport { prefix } from '../prefix.ts'\nimport { verifyEthBridgeEvent } from './util/index.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\n\nexport interface EthEventVerificationJobData {\n /** BigInt as a decimal string — the contract-assigned bridgeToRemote id. */\n bridgeId: string\n /** Bridge identity, used as the bridgeFulfillmentMap key. */\n identity: string\n}\n\n/** Stage 1 returns void. Stage 2 reads canonical fields from bridgeFulfillmentMap. */\nexport type EthEventVerificationJob = Job<EthEventVerificationJobData, void>\n\nconst name = 'Verify ETH Bridge Event at Depth'\nconst queueName = 'eth-event-verify'\n\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel, services?: IBridgeServiceCollection) => {\n const svc = assertEx(services, () => 'services not provided')\n const {\n bridge, bridgeFulfillmentMap, provider, remoteConfirmationDepth,\n } = svc\n\n const worker = new Worker(\n queueName,\n async (job: EthEventVerificationJob) => {\n const { bridgeId, identity } = job.data\n const id = BigInt(bridgeId)\n\n const existing = await bridgeFulfillmentMap.get(identity)\n\n // Idempotent: if a previous Stage 1 already populated canonical, skip the contract\n // read. Stage 1 normally runs once per flow but can re-run on flow-level retry.\n if (existing?.canonical) {\n await job.log(`[${identity}] canonical already set; verification skipped`)\n return\n }\n\n // If this is a manual retry of a previously-failed flow, clear the stale failed\n // marker. We're trying again — if conditions still don't allow, we'll re-mark below.\n const state = existing ?? { identity, previousAttempts: [] }\n if (state.failed) state.failed = undefined\n\n await job.log(`[${identity}] verifying BridgedToRemote(${id}) at depth ${remoteConfirmationDepth}`)\n const data = await verifyEthBridgeEvent(id, bridge, provider, remoteConfirmationDepth)\n\n if (isNull(data)) {\n state.failed = {\n at: Date.now(),\n reason: 'non-canonical at confirmation depth — orphaned by reorg or never reached canonical state',\n }\n await bridgeFulfillmentMap.set(identity, state)\n await job.log(`[${identity}] non-canonical at depth — marked failed`)\n throw new UnrecoverableError(`[${identity}] bridgesToRemote slot empty at confirmation depth ${remoteConfirmationDepth}`)\n }\n\n state.canonical = data\n await bridgeFulfillmentMap.set(identity, state)\n\n await job.log(\n `[${identity}] verified: src=${data.srcAddress} dest=${data.destAddress} `\n + `amount=${data.amount} evmTxHash=${data.evmTxHash}`,\n )\n },\n {\n connection, telemetry, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const EthEventVerification: WorkerDescription = {\n createWorker, name, queueName,\n}\n","import type { Address, Hex } from '@xylabs/sdk-js'\nimport { toHex } from '@xylabs/sdk-js'\nimport type { AccountInstance } from '@xyo-network/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type {\n BridgeIntent, BridgeSourceObservation, ChainId, SignedHydratedTransaction, XL1BlockNumber,\n} from '@xyo-network/xl1-sdk'\nimport {\n BridgeIntentSchema, BridgeSourceObservationSchema, buildTransaction, createTransferPayload,\n} from '@xyo-network/xl1-sdk'\n\nexport interface BuildEthToXl1ReserveTxOptions {\n amount: bigint\n bridgeAccount: AccountInstance\n /** Contract-assigned bridge id from `bridgesToRemote(bridgeId)` storage. */\n bridgeId: bigint\n destAddress: Address\n evmChainId: Hex\n evmContractAddress: Address\n evmSrcAddress: Address\n evmTokenAddress: Hex\n /** Tx hash of the EVM transaction that emitted BridgedToRemote(bridgeId). */\n evmTxHash: Hex\n exp: XL1BlockNumber\n nbf: XL1BlockNumber\n xl1ChainId: ChainId\n xl1TokenAddress: Hex\n}\n\n/**\n * Builds a signed XL1 transaction that credits `destAddress` by transferring `amount` from\n * the bridge's reserve account, with `BridgeIntent` + `BridgeSourceObservation` audit\n * payloads attached off-chain. Used by the EVM→XL1 reverse-bridge flow once the canonical\n * EVM event has been verified at confirmation depth.\n *\n * The Transfer payload is what actually moves balance on XL1 (on-chain). The intent +\n * source observation are off-chain provenance: they record what cross-chain operation this\n * transfer represents and which EVM tx emitted the source-side `BridgedToRemote` event.\n *\n * The BridgeIntent.nonce is the deterministic `evm:{chainId}:{contract}:{bridgeId}` form so\n * it aligns with the BullMQ jobId and the status route's URL `:nonce` parameter — a single\n * canonical id ties the same logical bridge across all surfaces.\n */\nexport async function buildEthToXl1ReserveTx(\n options: BuildEthToXl1ReserveTxOptions,\n): Promise<SignedHydratedTransaction> {\n const {\n amount,\n bridgeAccount,\n bridgeId,\n destAddress,\n evmChainId,\n evmContractAddress,\n evmSrcAddress,\n evmTokenAddress,\n evmTxHash,\n exp,\n nbf,\n xl1ChainId,\n xl1TokenAddress,\n } = options\n\n const amountHex = toHex(amount)\n const nonce = `evm:${evmChainId.toLowerCase()}:${evmContractAddress.toLowerCase()}:${bridgeId.toString()}`\n\n const transfer = createTransferPayload(bridgeAccount.address, { [destAddress]: amount })\n\n const intent = new PayloadBuilder<BridgeIntent>({ schema: BridgeIntentSchema })\n .fields({\n dest: xl1ChainId,\n destAddress,\n destAmount: amountHex,\n destToken: xl1TokenAddress,\n nonce,\n src: evmChainId,\n srcAddress: evmSrcAddress,\n srcAmount: amountHex,\n srcToken: evmTokenAddress,\n })\n .build()\n\n const sourceObservation = new PayloadBuilder<BridgeSourceObservation>({ schema: BridgeSourceObservationSchema })\n .fields({\n dest: xl1ChainId,\n destAddress,\n destAmount: amountHex,\n destToken: xl1TokenAddress,\n src: evmChainId,\n srcAddress: evmSrcAddress,\n srcAmount: amountHex,\n srcConfirmation: evmTxHash,\n srcToken: evmTokenAddress,\n })\n .build()\n\n return buildTransaction(\n xl1ChainId,\n [transfer],\n [intent, sourceObservation],\n bridgeAccount,\n nbf,\n exp,\n )\n}\n","import type { Provider } from 'ethers'\n\nimport type { EvmConfirmationDepth } from '../../../evm/index.ts'\n\n/**\n * Resolves an EvmConfirmationDepth into the concrete block reference used by `eth_call`\n * / `eth_getLogs` / `nextBridgeToId({ blockTag })` / `bridgesToRemote(id, { blockTag })` /\n * `queryFilter(filter, fromBlock, toBlock)`. Return is `number | 'finalized'` to satisfy\n * the typechain overload's narrower `string | number` signature on `queryFilter`.\n *\n * Numeric depth: subtract from the current head and clamp to >= 0. The provider RPC fires\n * exactly once per call.\n *\n * 'finalized': forwarded as-is. ethers and the underlying JSON-RPC accept the string tag\n * directly, so no head fetch is needed — saves a round-trip on every read at depth.\n */\nexport async function resolveEvmBlockTagAtDepth(\n provider: Provider,\n depth: EvmConfirmationDepth,\n): Promise<number | 'finalized'> {\n if (depth === 'finalized') return 'finalized'\n const head = await provider.getBlockNumber()\n return Math.max(head - depth, 0)\n}\n","import {\n assertEx, hexToBigInt, toEthAddress,\n} from '@xylabs/sdk-js'\nimport type { Payload } from '@xyo-network/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type { LiquidityPoolBridge } from '@xyo-network/typechain'\nimport { isBridgeIntent, type SignedHydratedTransaction } from '@xyo-network/xl1-sdk'\nimport type { Wallet } from 'ethers'\n\nexport const submitEthTransaction = async (\n tx: SignedHydratedTransaction,\n offChainPayloads: Payload[],\n bridge: LiquidityPoolBridge,\n wallet: Wallet,\n) => {\n // Approve the bridge to spend tokens\n const xl1Transaction = assertEx(tx[0], () => 'No corresponding XL1 transaction found')\n const allPayloads = [...tx[1], ...offChainPayloads]\n const bridgeIntent = assertEx(allPayloads.find(isBridgeIntent), () => 'No bridge intent found')\n const srcAddress = toEthAddress(bridgeIntent.srcAddress)\n const destAddress = toEthAddress(bridgeIntent.destAddress)\n const amount = hexToBigInt(bridgeIntent.destAmount)\n const nonce = hexToBigInt(await PayloadBuilder.hash(xl1Transaction))\n // Assume approval has already been done out of band for simplicity\n // const contractApprovalTx = await bridgeableToken.connect(wallet).approve(bridge.getAddress(), amount)\n // await contractApprovalTx.wait(1)\n\n // Send tokens to bridge\n const bridgeTx = await bridge.connect(wallet).bridgeFromRemote(srcAddress, destAddress, amount, nonce)\n const receipt = await bridgeTx.wait(1)\n return receipt?.hash\n}\n","import { type BrandedHash } from '@xylabs/sdk-js'\nimport type { Payload } from '@xyo-network/sdk-js'\nimport { type SignedHydratedTransaction, type XyoGatewayRunner } from '@xyo-network/xl1-sdk'\n\nexport const submitXl1Transaction = async (\n preparedTx: SignedHydratedTransaction,\n offChain: Payload[] = [],\n gateway: XyoGatewayRunner,\n): Promise<[BrandedHash, SignedHydratedTransaction]> => {\n // Option 1: Add payloads to chain with addPayloadsToChain\n // Not optimal as it requires reconstructing the transaction from the on-chain payloads, which changes the tx hash\n // const offChainPayloads = preparedTx[1].filter(p => !isAllowedBlockPayload(p))\n // const onChainPayloads = preparedTx[1].filter(isAllowedBlockPayload)\n // const result = await gateway.addPayloadsToChain(onChainPayloads, offChainPayloads)\n // return result\n\n // Option 2: Add transaction to chain with addTransactionToChain\n // Fails due to resigning of transaction in addTransactionToChain, which causes `from` to be invalid\n const result = await gateway.addTransactionToChain(preparedTx, offChain)\n return result\n\n // Option 3: Add transaction to chain with addTransactionToChain, but bypass resigning by passing the preparedTx as an unsigned transaction\n // const runner = assertEx(gateway.connection.runner, () => 'No runner available on gateway connection')\n // const result = await runner.broadcastTransaction(preparedTx)\n // return [result, preparedTx]\n}\n","import type { Address, Hex } from '@xylabs/sdk-js'\nimport { asHex, toAddress } from '@xylabs/sdk-js'\nimport type { LiquidityPoolBridge } from '@xyo-network/typechain'\nimport type { Provider } from 'ethers'\nimport { ZeroAddress } from 'ethers'\n\nimport type { EvmConfirmationDepth } from '../../../evm/index.ts'\nimport { resolveEvmBlockTagAtDepth } from './resolveEvmBlockTagAtDepth.ts'\n\nexport interface EthBridgeEventData {\n amount: bigint\n destAddress: Address\n destToken: Address\n /** Tx hash of the EVM transaction that emitted BridgedToRemote(id). */\n evmTxHash: Hex\n srcAddress: Address\n}\n\n/**\n * Reads the bridge contract's `bridgesToRemote(id)` at the configured confirmation depth\n * (numeric block depth, or 'finalized' for Casper FFG cryptographic finality) and looks up\n * the matching `BridgedToRemote(id)` event log to capture the EVM tx hash. Returns the\n * canonical fields, or `null` when the slot is empty / no canonical event exists at depth.\n *\n * The contract storage at depth is the source of truth for whether a `BridgedToRemote`\n * event is canonical. A non-zero `srcAddress` means the slot was populated at that block\n * and (because the contract has no delete/overwrite path) is permanent on the chain that\n * extends from there. A zero `srcAddress` at depth means the event was orphaned by a reorg\n * or never reached canonical state — the caller must treat this as terminal.\n *\n * The event-log lookup is what surfaces the EVM tx hash for `BridgeSourceObservation`'s\n * `srcConfirmation`. It scans from genesis to the depth-tagged block; on chains with long\n * history this is expensive, so a future optimization should narrow the range (cache the\n * contract's deploy block or accept a fromBlock hint).\n */\nexport async function verifyEthBridgeEvent(\n id: bigint,\n bridge: LiquidityPoolBridge,\n provider: Provider,\n confirmationDepth: EvmConfirmationDepth,\n): Promise<EthBridgeEventData | null> {\n const blockTag = await resolveEvmBlockTagAtDepth(provider, confirmationDepth)\n const data = await bridge.bridgesToRemote(id, { blockTag })\n if (data.srcAddress === ZeroAddress) {\n return null\n }\n\n // Find the BridgedToRemote(id) event log to capture the tx hash. Since `id` is indexed\n // and monotonic-unique, this returns at most one event on a canonical chain.\n const filter = bridge.filters.BridgedToRemote(id)\n const events = await bridge.queryFilter(filter, 0, blockTag)\n const event = events[0]\n if (event === undefined) {\n // Storage said populated but no event found at depth — this would be an inconsistency.\n // Treat like a null verification so the scanner advances past the id rather than getting\n // stuck retrying.\n return null\n }\n\n return {\n amount: data.amount,\n destAddress: toAddress(data.destAddress),\n destToken: toAddress(data.destToken),\n evmTxHash: asHex(event.transactionHash, true),\n srcAddress: toAddress(data.srcAddress),\n }\n}\n","import type { SignedHydratedTransaction } from '@xyo-network/xl1-sdk'\nimport type { Job } from 'bullmq'\nimport { Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport { prefix } from '../prefix.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\n\nexport interface EthToXl1BridgeParentJobData {\n tx: SignedHydratedTransaction\n}\nexport interface EthToXl1BridgeParentJobReturn { }\nexport type EthToXl1BridgeParentJob = Job<EthToXl1BridgeParentJobData, EthToXl1BridgeParentJobReturn>\n\nconst name = 'Bridge Ethereum to XL1'\nconst queueName = 'eth-to-xl1-bridge'\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel) => {\n const worker = new Worker(\n queueName,\n async (job: EthToXl1BridgeParentJob) => {\n await job.log(`[${job.name}] start`)\n // Parent job has no work other than waiting on children\n await job.log(`[${job.name}] done`)\n return {}\n },\n {\n connection, telemetry, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const EthToXl1BridgeParent: WorkerDescription = {\n createWorker, name, queueName,\n}\n","import { assertEx } from '@xylabs/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type { Job } from 'bullmq'\nimport { Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport type { IBridgeServiceCollection } from '../../index.ts'\nimport { prefix } from '../prefix.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\nimport type { Xl1TransactionJobData } from './Xl1TransactionJobData.ts'\n\nexport type EthTransactionMonitorJobData = Xl1TransactionJobData\nexport interface EthTransactionMonitorJobReturn {\n blockHash: string\n blockNumber: number\n submissionHash: string\n}\nexport type EthTransactionMonitorJob = Job<EthTransactionMonitorJobData, EthTransactionMonitorJobReturn>\n\nconst name = 'Monitor Submitted ETH Transaction'\nconst queueName = 'eth-tx-monitor'\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel, services?: IBridgeServiceCollection) => {\n const provider = assertEx(services?.provider, () => 'provider service not provided')\n const stateMap = assertEx(services?.ethTxStateMap, () => 'ethTxStateMap service not provided')\n\n const worker = new Worker(\n queueName,\n async (job: EthTransactionMonitorJob) => {\n const { tx } = job.data\n const hash = await PayloadBuilder.hash(tx[0])\n const state = assertEx(await stateMap.get(hash), () => 'State not found')\n const submissionHash = assertEx(state?.submissionHash, () => 'submissionHash not found')\n const receipt = assertEx(await provider.getTransactionReceipt(submissionHash), () => 'Transaction receipt not found')\n await job.log(`[${hash}] confirmed ETH tx ${submissionHash} in block ${receipt.blockNumber}`)\n const { blockHash, blockNumber } = receipt\n state.confirmationHash = blockHash\n await stateMap.set(hash, state)\n return {\n blockHash, blockNumber, submissionHash,\n }\n },\n {\n connection, telemetry, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const EthTransactionMonitor: WorkerDescription = {\n createWorker, name, queueName,\n}\n","import { assertEx, hexToBigInt } from '@xylabs/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport { isBridgeIntent } from '@xyo-network/xl1-sdk'\nimport type { Job } from 'bullmq'\nimport { Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport { getAddress } from 'ethers'\nimport type { Redis } from 'ioredis'\n\nimport type { IBridgeServiceCollection } from '../../index.ts'\nimport {\n validateSufficientLiquiditySourceAllowance, validateSufficientLiquiditySourceBalance, validateSufficientRunnerEthBalanceForGas,\n} from '../../validation/index.ts'\nimport { prefix } from '../prefix.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\nimport type { Xl1DataLakeTransactionJobData } from './Xl1TransactionJobData.ts'\n\nexport type EthTransactionPreparationJobData = Xl1DataLakeTransactionJobData\nexport type EthTransactionPreparationJobReturn = Record<string, never>\nexport type EthTransactionPreparationJob = Job<EthTransactionPreparationJobData, EthTransactionPreparationJobReturn>\n\nconst name = 'Prepare ETH Transaction'\nconst queueName = 'eth-tx-prepare'\n\nexport const createWorker = (connection: Redis, telemetry?: BullMQOtel, services?: IBridgeServiceCollection) => {\n const bridge = assertEx(services?.bridge, () => 'bridge service not provided')\n const bridgeableToken = assertEx(services?.bridgeableToken, () => 'bridgeableToken service not provided')\n const stateMap = assertEx(services?.ethTxStateMap, () => 'ethTxStateMap service not provided')\n const wallet = assertEx(services?.wallet, () => 'wallet service not provided')\n\n const worker = new Worker(\n queueName,\n async (job: EthTransactionPreparationJob) => {\n const { tx, offChainPayloads } = job.data\n const hash = await PayloadBuilder.hash(tx[0])\n await job.log(`[${hash}] preparing ETH transaction`)\n await job.log(`[${hash}] validating liquiditySource has sufficient allowance`)\n if (!(await validateSufficientLiquiditySourceAllowance(tx, offChainPayloads, bridgeableToken, bridge, job))) {\n throw new Error('Liquidity source does not have sufficient allowance for the bridge to execute the transaction')\n }\n await job.log(`[${hash}] validated liquiditySource has sufficient allowance`)\n await job.log(`[${hash}] validating liquiditySource has sufficient balance`)\n if (!(await validateSufficientLiquiditySourceBalance(tx, offChainPayloads, bridgeableToken, bridge, job))) {\n throw new Error('Liquidity source does not have sufficient balance for the bridge to execute the transaction')\n }\n await job.log(`[${hash}] validated liquiditySource has sufficient balance`)\n await job.log(`[${hash}] building ETH transaction`)\n const allPayloads = [...tx[1], ...offChainPayloads]\n const bridgeIntent = assertEx(allPayloads.find(isBridgeIntent), () => 'No bridge intent found')\n const amount = hexToBigInt(bridgeIntent.destAmount)\n const srcAddress = getAddress(bridgeIntent.srcAddress)\n const destAddress = getAddress(bridgeIntent.destAddress)\n const nonce = hexToBigInt(await PayloadBuilder.hash(tx[0]))\n const preparedTx = await bridge.getFunction('bridgeFromRemote').populateTransaction(srcAddress, destAddress, amount, nonce)\n await job.log(`[${hash}] built ETH transaction`)\n await job.log(`[${hash}] validating tx runner has sufficient ETH for gas`)\n if (!(await validateSufficientRunnerEthBalanceForGas(preparedTx, wallet, job))) {\n throw new Error('Transaction runner does not have sufficient ETH to cover estimated gas (with buffer)')\n }\n await job.log(`[${hash}] validated tx runner has sufficient ETH for gas`)\n await job.log(`[${hash}] storing ETH preparedTx`)\n await stateMap.set(hash, { preparedTx })\n await job.log(`[${hash}] stored ETH preparedTx`)\n await job.log(`[${hash}] prepared ETH transaction`)\n return {}\n },\n {\n connection, telemetry, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const EthTransactionPreparation: WorkerDescription = {\n createWorker, name, queueName,\n}\n","import { hexToBigInt, isUndefined } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type { BridgeIntent, Transfer } from '@xyo-network/xl1-sdk'\n\nimport { getMaxBridgeAmount, getMinBridgeAmount } from '../evm/index.ts'\nimport { generateBridgeEstimate } from '../util/index.ts'\n\n/**\n * Validates a bridge estimate by checking the intent and transfer against the provided configuration. This method\n * only returns true if the bridge estimate matches exactly.\n * @param intent The BridgeIntent\n * @param transfer The Transfer\n * @param config The Config\n * @returns True if the bridge estimate satisfies bridging conditions, false otherwise.\n */\nexport const validateBridgeEstimateExact = async (\n intent: BridgeIntent,\n transfer: Transfer,\n config: BridgeConfig,\n): Promise<boolean> => {\n const {\n srcAddress, srcAmount, destAddress,\n } = intent\n\n // Reject if the requested amount is outside the configured bounds\n if (hexToBigInt(srcAmount) < hexToBigInt(getMinBridgeAmount(config))) return false\n if (hexToBigInt(srcAmount) > hexToBigInt(getMaxBridgeAmount(config))) return false\n\n const [calculatedIntent, calculatedTransfer] = await generateBridgeEstimate(srcAddress, srcAmount, destAddress, config)\n if (isUndefined(calculatedIntent) || isUndefined(calculatedTransfer)) return false\n const { nonce: expectedIntentNonce, ...expectedIntentStatic } = calculatedIntent\n const { nonce: actualIntentNonce, ...actualIntentStatic } = intent\n if ((await PayloadBuilder.dataHash(expectedIntentStatic)) !== (await PayloadBuilder.dataHash(actualIntentStatic))) return false\n const { epoch: expectedTransferEpoch, ...expectedTransferStatic } = calculatedTransfer\n const { epoch: actualTransferEpoch, ...actualTransferStatic } = transfer\n if ((await PayloadBuilder.dataHash(expectedTransferStatic)) !== (await PayloadBuilder.dataHash(actualTransferStatic))) return false\n\n return true\n}\n","import { asHex } from '@xylabs/sdk-js'\nimport type { ChainId } from '@xyo-network/xl1-sdk'\n\nexport const asChainId = (value: unknown): ChainId | undefined => {\n const chainId = asHex(value)\n return chainId\n}\n","import type { Address } from '@xylabs/sdk-js'\nimport { asAddress } from '@xylabs/sdk-js'\n\nexport const asToken = (value: unknown): Address | undefined => {\n const token = asAddress(value)\n return token\n}\n","import type { Address } from '@xylabs/sdk-js'\nimport { asAddress, assertEx } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nexport const tryGetBridgeEscrowAddress = (config: BridgeConfig): Address | undefined => {\n const address = asAddress(config.escrowAddress)\n return address\n}\n\nexport const getBridgeEscrowAddress = (config: BridgeConfig): Address => {\n const address = assertEx(tryGetBridgeEscrowAddress(config), () => `Invalid bridge escrow address: ${config.escrowAddress}`)\n return address\n}\n","import type { Address } from '@xylabs/sdk-js'\nimport { asAddress, assertEx } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nexport const tryGetBridgeFeesAddress = (config: BridgeConfig): Address | undefined => {\n const address = asAddress(config.feesAddress)\n return address\n}\n\nexport const getBridgeFeesAddress = (config: BridgeConfig): Address => {\n const address = assertEx(tryGetBridgeFeesAddress(config), () => `Invalid bridge fees address: ${config.feesAddress}`)\n return address\n}\n","import type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nimport type { FeeStructure } from '../util/index.ts'\n\nexport const getFeeStructure = (config: BridgeConfig): FeeStructure => {\n const { feeFixed, feeRateBasisPoints } = config\n return { feeFixed, feeRateBasisPoints }\n}\n","import type { Hex } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nexport const getMaxBridgeAmount = (config: BridgeConfig): Hex => {\n const { maxBridgeAmount } = config\n return maxBridgeAmount\n}\n","import type { Hex } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nexport const getMinBridgeAmount = (config: BridgeConfig): Hex => {\n const { minBridgeAmount } = config\n return minBridgeAmount\n}\n","import { assertEx } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport type { ChainId } from '@xyo-network/xl1-sdk'\n\nimport { asChainId } from './asChainId.ts'\n\nexport const getRemoteChainId = (config: BridgeConfig): ChainId => {\n const remoteChainId = assertEx(asChainId(config.remoteChainId), () => 'Invalid remote chain ID in config')\n return remoteChainId\n}\n","import type { Address } from '@xylabs/sdk-js'\nimport { assertEx } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nimport { asToken } from './asToken.ts'\n\nexport const getRemoteTokenAddress = (config: BridgeConfig): Address => {\n const token = asToken(config.remoteTokenAddress)\n return assertEx(token, () => 'Remote token address is not defined in bridge configuration')\n}\n","import type { Address, Promisable } from '@xylabs/sdk-js'\nimport { isDefined } from '@xylabs/sdk-js'\nimport { resolveWalletForActor } from '@xyo-network/chain-orchestration'\nimport type { WalletInstance } from '@xyo-network/wallet-model'\nimport type { ActorConfig } from '@xyo-network/xl1-sdk'\n\nlet accountServiceSingleton: Promisable<WalletInstance> | undefined\n\nexport const getBridgeWalletAccount = async (config: ActorConfig): Promise<WalletInstance> => {\n if (accountServiceSingleton) return accountServiceSingleton\n const accountPath = typeof config.accountPath === 'string' ? config.accountPath : undefined\n const account = await resolveWalletForActor(config.name, accountPath)\n accountServiceSingleton = account\n return accountServiceSingleton\n}\n\nexport const getAddressOrBridgeWalletAccountAddress = async (\n getConfigAccount: (config: ActorConfig) => Address | undefined,\n config: ActorConfig,\n): Promise<Address> => {\n const address = getConfigAccount(config)\n if (isDefined(address)) return address\n const walletAccount = await getBridgeWalletAccount(config)\n return walletAccount.address\n}\n","import type { Address } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nimport { tryGetBridgeEscrowAddress } from './getBridgeEscrowAddress.ts'\nimport { tryGetBridgeFeesAddress } from './getBridgeFeesAddress.ts'\nimport { getBridgeWalletAccount } from './getBridgeWalletAccount.ts'\n\nexport interface TransferAddresses {\n escrowAddress: Address\n feesAddress: Address\n}\n\nexport const getTransferAddresses = async (config: BridgeConfig): Promise<TransferAddresses> => {\n const escrowAddress = tryGetBridgeEscrowAddress(config) ?? (await getBridgeWalletAccount(config)).address\n const feesAddress = tryGetBridgeFeesAddress(config) ?? (await getBridgeWalletAccount(config)).address\n return { escrowAddress, feesAddress }\n}\n","import { assertEx, isDefined } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport type { ChainId } from '@xyo-network/xl1-sdk'\n\nimport { asChainId } from './asChainId.ts'\n\nexport const getXl1ChainId = (config: BridgeConfig): ChainId => {\n const xl1ChainId = config.xl1ChainId\n if (isDefined(xl1ChainId)) {\n return assertEx(asChainId(xl1ChainId), () => 'Invalid xl1ChainId in bridge config')\n }\n return assertEx(asChainId(config.chain.id), () => 'Invalid chain.id in config')\n}\n","import type { Hex } from '@xylabs/sdk-js'\nimport { isDefined } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nimport { asToken } from './asToken.ts'\nimport { getXl1ChainId } from './getXl1ChainId.ts'\n\nexport const getXl1TokenAddress = (config: BridgeConfig): Hex => {\n const token = asToken(config.xl1TokenAddress)\n if (isDefined(token)) return token\n return getXl1ChainId(config)\n}\n","import type { BridgeConfig, BridgeSettings } from '@xyo-network/chain-orchestration'\n\nimport { getFeeStructure } from './getFeeStructure.ts'\nimport { getMaxBridgeAmount } from './getMaxBridgeAmount.ts'\nimport { getMinBridgeAmount } from './getMinBridgeAmount.ts'\nimport { getRemoteChainId } from './getRemoteChainId.ts'\nimport { getRemoteTokenAddress } from './getRemoteTokenAddress.ts'\nimport { getTransferAddresses } from './getTransferAddresses.ts'\nimport { getXl1ChainId } from './getXl1ChainId.ts'\nimport { getXl1TokenAddress } from './getXl1TokenAddress.ts'\n\nexport const getBridgeSettings = async (config: BridgeConfig): Promise<BridgeSettings> => {\n const { feeFixed, feeRateBasisPoints } = getFeeStructure(config)\n const { feesAddress, escrowAddress } = await getTransferAddresses(config)\n const maxBridgeAmount = getMaxBridgeAmount(config)\n const minBridgeAmount = getMinBridgeAmount(config)\n const remoteChainId = getRemoteChainId(config)\n const remoteTokenAddress = getRemoteTokenAddress(config)\n const xl1TokenAddress = getXl1TokenAddress(config)\n const xl1ChainId = getXl1ChainId(config)\n return {\n feeFixed, feeRateBasisPoints, feesAddress, escrowAddress, maxBridgeAmount, minBridgeAmount, remoteChainId, remoteTokenAddress, xl1TokenAddress, xl1ChainId,\n }\n}\n","import { isDefined } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nimport { getRemoteChainId } from './getRemoteChainId.ts'\n\n// Confirmation depth options for the remote (EVM) chain. Numeric values are in BLOCKS;\n// the string 'finalized' is the ethers BlockTag for Casper FFG cryptographic finality.\n// Reading the bridge contract's storage at depth (latest - N) or at 'finalized' is what\n// buys reorg protection; depth 0 means \"trust head\" and is only safe for non-reorging chains.\n//\n// On Ethereum mainnet (~12s blocks):\n// 0 — Hardhat / dev. Test node never reorgs.\n// 12 — Legacy \"safe\" (~2.4 min). Was the pre-merge default; thin margin post-merge.\n// 32 — Practical safe (~6.4 min). One epoch's worth of blocks; current default below.\n// 64 — ~12.8 min. Comparable to Casper finality wall-clock time without using the tag.\n// 'finalized' — Casper FFG cryptographic finality, ~12-13 min on mainnet. Strongest available\n// guarantee — economically irreversible barring a 1/3 stake slashing. Set this\n// via env (BRIDGE_REMOTE_CONFIRMATION_DEPTH=finalized) when you want the\n// verifier and scanner to read at the finalized block tag instead of a numeric\n// depth offset.\n\nexport type EvmConfirmationDepth = number | 'finalized'\n\nconst HARDHAT_CHAIN_ID = '0x7a69'\nconst ETHEREUM_MAINNET_CHAIN_ID = '0x1'\n\nconst FALLBACK_CONFIRMATION_DEPTH: EvmConfirmationDepth = 32\n\nconst DEFAULT_CONFIRMATION_DEPTH_BY_CHAIN_ID: Record<string, EvmConfirmationDepth> = {\n [HARDHAT_CHAIN_ID]: 0,\n [ETHEREUM_MAINNET_CHAIN_ID]: 32,\n}\n\nexport function getRemoteConfirmationDepth(config: BridgeConfig): EvmConfirmationDepth {\n if (isDefined(config.remoteConfirmationDepth)) return config.remoteConfirmationDepth\n const chainId = getRemoteChainId(config).toLowerCase()\n return DEFAULT_CONFIRMATION_DEPTH_BY_CHAIN_ID[chainId] ?? FALLBACK_CONFIRMATION_DEPTH\n}\n","import type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\n/**\n * How often the EVM→XL1 scanner ticks. The interval is the configured value verbatim —\n * BridgeConfigZod already supplies a 30s default, so an unset config still resolves\n * cleanly. Kept as a getter for symmetry with the rest of the bridge config accessors,\n * and so future logic (e.g. per-chain overrides) has a single seam to extend.\n */\nexport function getScannerIntervalMs(config: BridgeConfig): number {\n return config.scannerIntervalMs\n}\n","import type { Hex } from '@xylabs/sdk-js'\nimport { hexToBigInt, toHex } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nimport type { BridgeFees } from './BridgeFees.ts'\n\nexport type FeeStructure = Pick<BridgeConfig, 'feeFixed' | 'feeRateBasisPoints'>\n\nexport const calculateBridgeFees = (srcAmount: Hex, feeStructure: FeeStructure): BridgeFees => {\n const { feeFixed, feeRateBasisPoints } = feeStructure\n\n // Format source input\n const srcAmountBigInt = hexToBigInt(srcAmount)\n\n // Calculate fixed fee\n // const feeFixedBigInt = hexToBigInt(feeFixed)\n\n // Integer-safe basis point calculation (floor division)\n const feeVariableBigInt\n = (srcAmountBigInt * BigInt(feeRateBasisPoints)) / 10_000n\n const feeVariable = toHex(feeVariableBigInt)\n\n // Calculate total fee\n // const feeTotalBigInt = feeFixedBigInt + feeVariableBigInt\n\n // Calculate destination amount\n // const destAmountBigInt = srcAmountBigInt > feeTotalBigInt ? srcAmountBigInt - feeTotalBigInt : 0n\n // const destAmount = toHex(destAmountBigInt)\n\n return {\n feeFixed, feeVariable, srcAmount,\n }\n}\n","import type { Hex } from '@xylabs/sdk-js'\nimport { hexToBigInt, toHex } from '@xylabs/sdk-js'\n\nimport type { FeeStructure } from './calculateBridgeFees.ts'\n\n/**\n * Given a user's total available balance, calculates the maximum amount they can bridge\n * after accounting for the fixed and variable bridge fees.\n *\n * Solving for M where: M + feeFixed + (M * basisPoints / 10_000) = balance\n * => M = (balance - feeFixed) * 10_000 / (10_000 + basisPoints)\n */\nexport const calculateMaxBridgeAmount = (balance: Hex, feeStructure: FeeStructure): Hex => {\n const { feeFixed, feeRateBasisPoints } = feeStructure\n const balanceBigInt = hexToBigInt(balance)\n const feeFixedBigInt = hexToBigInt(feeFixed)\n\n if (balanceBigInt <= feeFixedBigInt) return toHex(0n)\n\n const maxAmount = ((balanceBigInt - feeFixedBigInt) * 10_000n) / (10_000n + BigInt(feeRateBasisPoints))\n return toHex(maxAmount)\n}\n","import type { Address, Hex } from '@xylabs/sdk-js'\nimport { hexToBigInt } from '@xylabs/sdk-js'\nimport type { Transfer } from '@xyo-network/xl1-sdk'\nimport { createTransferPayload } from '@xyo-network/xl1-sdk'\n\nimport type { BridgeFees } from './BridgeFees.ts'\n\n/**\n * Calculates the transfer representing the bridging of funds including the appropriate amounts for the bridge fees\n * @param sender The client attempting to bridge\n * @param srcAmount The amount the client is attempting to bridge\n * @param escrowAddress The address in which bridged funds will be held until the transfer is executed on the destination chain\n * @param feesAddress The address to which bridge fees will be paid\n * @param context An object containing the necessary fee and amount information to construct the transfer context\n * @returns A transfer representing the bridging of funds including the appropriate amounts for the bridge fees\n */\nexport const createBridgeTransfer = (sender: Address, srcAmount: Hex, escrowAddress: Address, feesAddress: Address, context: BridgeFees): Transfer => {\n const { feeFixed, feeVariable } = context\n const escrowAmount = hexToBigInt(srcAmount)\n const feesAmount = hexToBigInt(feeFixed) + hexToBigInt(feeVariable)\n const transfers: Record<Address, bigint>\n // If the escrow and fee addresses are the same\n = escrowAddress === feesAddress\n // combine the amounts into a single transfer to that address\n ? { [feesAddress]: escrowAmount + feesAmount }\n // otherwise, create separate transfers to the escrow and fees addresses\n : { [escrowAddress]: escrowAmount, [feesAddress]: feesAmount }\n const transfer = createTransferPayload(sender, transfers, context)\n\n return transfer\n}\n","import type { Hex } from '@xylabs/sdk-js'\nimport { toAddress } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type {\n BridgeIntent, BridgeIntentFields, Transfer,\n} from '@xyo-network/xl1-sdk'\nimport { BridgeIntentSchema } from '@xyo-network/xl1-sdk'\nimport { v4 } from 'uuid'\n\nimport { getBridgeSettings } from '../evm/index.ts'\nimport { calculateBridgeFees } from './calculateBridgeFees.ts'\nimport { createBridgeTransfer } from './createBridgeTransfer.ts'\n\nexport const generateBridgeEstimate = async (\n srcAddress: Hex,\n srcAmount: Hex,\n destAddress: Hex,\n config: BridgeConfig,\n nonceOverride?: string,\n): Promise<[BridgeIntent, Transfer]> => {\n const {\n escrowAddress, feeFixed, feeRateBasisPoints, feesAddress, remoteChainId, remoteTokenAddress, xl1ChainId, xl1TokenAddress,\n } = await getBridgeSettings(config)\n\n const sender = toAddress(srcAddress)\n\n // Calculate fees and destination amount\n const fees = calculateBridgeFees(srcAmount, { feeFixed, feeRateBasisPoints })\n\n // Generate a unique nonce for the bridge intent\n const nonce = nonceOverride ?? v4()\n\n // Build the bridge intent\n const bridgeIntentFields: BridgeIntentFields = {\n // Source\n src: xl1ChainId,\n srcAddress: sender,\n srcAmount,\n srcToken: xl1TokenAddress,\n\n // Destination\n dest: remoteChainId,\n destAddress,\n destAmount: srcAmount, // This is a 1:1 bridge. Fees are handled at the transfer level, not the bridge intent level.\n destToken: remoteTokenAddress,\n nonce,\n }\n const bridgeIntent: BridgeIntent = new PayloadBuilder<BridgeIntent>({ schema: BridgeIntentSchema }).fields(bridgeIntentFields).build()\n\n // Build the transfer\n const transfer = createBridgeTransfer(sender, srcAmount, escrowAddress, feesAddress, fees)\n\n return [bridgeIntent, transfer]\n}\n","import { asAddress } from '@xylabs/sdk-js'\nimport {\n addressesContains, BoundWitnessValidator, payloadHashesContainsAll, payloadSchemasContainsAll,\n} from '@xyo-network/boundwitness-validator'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type {\n BridgeIntent, TransactionBoundWitness, Transfer,\n} from '@xyo-network/xl1-sdk'\nimport { BridgeIntentSchema, TransferSchema } from '@xyo-network/xl1-sdk'\n\nimport { getXl1ChainId } from '../evm/index.ts'\n\n/**\n * Validates a bridge estimate by checking the intent and transfer against the provided configuration. This method\n * exists to allow for \"at least\" validation of a bridge estimates in case we want to allow for some flexibility in\n * the bridge estimate.\n * @ param signedTransaction The signed transaction bound witness\n * @param signedTxBw The signed transaction bound witness\n * @param intent The BridgeIntent\n * @param transfer The Transfer\n * @param config The Config\n * @returns True if the bridge estimate satisfies bridging conditions, false otherwise.\n */\nexport const validateBridgeTransaction = async (\n signedTxBw: TransactionBoundWitness,\n intent: BridgeIntent,\n transfer: Transfer,\n config: BridgeConfig,\n): Promise<boolean> => {\n const { srcAddress } = intent\n\n // Ensure the transaction is for the correct source chain\n const chainId = getXl1ChainId(config)\n if (signedTxBw.chain !== chainId) return false\n\n // Ensure only the expected number of payloads exist (do not allow ambiguous extras)\n if (signedTxBw.payload_hashes.length != 2) return false\n // Ensure the payloads match the expected schemas\n if (!payloadSchemasContainsAll(signedTxBw, [BridgeIntentSchema, TransferSchema])) return false\n // Ensure the hashes match the intent and transfer\n const hashes = await PayloadBuilder.hashes([intent, transfer])\n if (!payloadHashesContainsAll(signedTxBw, hashes)) return false\n // Ensure the BoundWitness is valid and signed by the sender\n const errors = await new BoundWitnessValidator(signedTxBw).validate()\n if (errors.length > 0) return false\n\n // Ensure the sender's address is included in the addresses\n const sender = asAddress(srcAddress, true)\n if (!addressesContains(signedTxBw, sender)) return false\n\n return true\n}\n","import { assertEx, hexToBigInt } from '@xylabs/sdk-js'\nimport type { Payload } from '@xyo-network/sdk-js'\nimport type { BridgeableToken, LiquidityPoolBridge } from '@xyo-network/typechain'\nimport { isBridgeIntent, type SignedHydratedTransaction } from '@xyo-network/xl1-sdk'\n\nimport type { AsyncLogger } from './AsyncLogger.ts'\n\n/**\n * Checks if the liquidity source has sufficient allowance for the bridge to execute the transaction. This doesn't\n * ensure that (due to race conditions) the transaction will succeed, but is a quick check to avoid\n * submitting transactions that are likely to fail.\n * @param tx The transaction containing a bridge intent\n * @param offChainPayloads The payloads to put off chain\n * @param bridgeableToken The contract for the token being bridged\n * @param bridge The contract for the liquidity bridge\n * @param logger Optional logger for asynchronous logging\n * @returns True if the liquidity source allowance is sufficient to execute the bridge\n */\nexport const validateSufficientLiquiditySourceAllowance = async (\n tx: SignedHydratedTransaction,\n offChainPayloads: Payload[],\n bridgeableToken: BridgeableToken,\n bridge: LiquidityPoolBridge,\n logger?: AsyncLogger,\n) => {\n // Get the amount being bridged from the bridge intent\n const allPayloads = [...tx[1], ...offChainPayloads]\n const bridgeIntent = assertEx(allPayloads.find(isBridgeIntent), () => 'No bridge intent found')\n const amount = hexToBigInt(bridgeIntent.destAmount)\n\n // Get the addresses\n const liquiditySourceAddress = await bridge.liquiditySource()\n const bridgeAddress = await bridge.getAddress()\n\n // Check the allowance of the liquidity source for the bridge\n const remainingAllowance = await bridgeableToken.allowance(liquiditySourceAddress, bridgeAddress)\n await logger?.log(`Remaining allowance: ${remainingAllowance.toString()}`)\n return remainingAllowance >= amount\n}\n","import { assertEx, hexToBigInt } from '@xylabs/sdk-js'\nimport type { Payload } from '@xyo-network/sdk-js'\nimport type { BridgeableToken, LiquidityPoolBridge } from '@xyo-network/typechain'\nimport { isBridgeIntent, type SignedHydratedTransaction } from '@xyo-network/xl1-sdk'\n\nimport type { AsyncLogger } from './AsyncLogger.ts'\n\n/**\n * Checks if the liquidity source has sufficient balance for the bridge to execute the transaction. This doesn't\n * ensure that (due to race conditions) the transaction will succeed, but is a quick check to avoid\n * submitting transactions that are likely to fail.\n * @param tx The transaction containing a bridge intent\n * @param offChainPayloads The payloads to put off chain\n * @param bridgeableToken The contract for the token being bridged\n * @param bridge The contract for the liquidity bridge\n * @param logger Optional logger for asynchronous logging\n * @returns True if the liquidity source balance is sufficient to execute the bridge\n */\nexport const validateSufficientLiquiditySourceBalance = async (\n tx: SignedHydratedTransaction,\n offChainPayloads: Payload[],\n bridgeableToken: BridgeableToken,\n bridge: LiquidityPoolBridge,\n logger?: AsyncLogger,\n) => {\n // Get the amount being bridged from the bridge intent\n const allPayloads = [...tx[1], ...offChainPayloads]\n const bridgeIntent = assertEx(allPayloads.find(isBridgeIntent), () => 'No bridge intent found')\n const amount = hexToBigInt(bridgeIntent.destAmount)\n\n // Get the addresses\n const liquiditySourceAddress = await bridge.liquiditySource()\n\n // Check the balance of the liquidity source for the bridge\n const balance = await bridgeableToken.balanceOf(liquiditySourceAddress)\n await logger?.log(`Remaining balance: ${balance.toString()}`)\n return balance >= amount\n}\n","import { assertEx } from '@xylabs/sdk-js'\nimport type { ContractTransaction, Wallet } from 'ethers'\n\nimport type { AsyncLogger } from './AsyncLogger.ts'\n\nconst DEFAULT_GAS_BUFFER_BPS = 2000n // 20%\n\n/**\n * Validates that the wallet (the account that will submit the tx) has enough ETH\n * to cover the estimated gas cost (plus a buffer) for the transaction.\n * @param preparedTx The transaction that is being prepared for submission.\n * This should be a fully populated transaction (to/from/data/value) except for gas fields.\n * @param wallet The wallet that will be used to submit the transaction.\n * @param logger Optional logger for asynchronous logging.\n * @param bufferBps The buffer to apply to the estimated gas cost, in basis points (1/100th of a percent).\n * @returns A boolean indicating whether the wallet has sufficient ETH to cover the estimated gas cost with the buffer applied.\n */\nexport const validateSufficientRunnerEthBalanceForGas = async (\n preparedTx: ContractTransaction,\n wallet: Wallet,\n logger?: AsyncLogger,\n bufferBps: bigint = DEFAULT_GAS_BUFFER_BPS,\n) => {\n const provider = assertEx(wallet.provider, () => 'Wallet provider is not defined')\n\n // Fee data (EIP-1559 preferred, gasPrice fallback)\n const feeData = await provider.getFeeData()\n const perGas = feeData.maxFeePerGas ?? feeData.gasPrice\n if (perGas == null) {\n await logger?.log('[gas] unable to resolve gas price / maxFeePerGas from provider')\n return true // don’t hard-fail; provider may not support fee data\n }\n\n // Estimate gas\n const transactionRequest = {\n ...preparedTx,\n from: await wallet.getAddress(),\n }\n const estGas = await provider.estimateGas(transactionRequest)\n\n // Include any value sent with the tx\n const txValue = preparedTx?.value ?? 0n\n\n // Required = (gas * perGas + value) * (1 + buffer)\n const baseRequired = estGas * perGas + txValue\n const required = (baseRequired * (10_000n + bufferBps)) / 10_000n\n\n const balance = await provider.getBalance(await wallet.getAddress())\n\n await logger?.log(\n `[gas] runner=${await wallet.getAddress()} balance=${balance.toString()} `\n + `estGas=${estGas.toString()} perGas=${perGas.toString()} value=${txValue.toString()} `\n + `requiredWithBuffer=${required.toString()} bufferBps=${bufferBps.toString()}`,\n )\n\n return balance >= required\n}\n","import { assertEx } from '@xylabs/sdk-js'\nimport type { AccountInstance } from '@xyo-network/sdk-js'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\n\nimport type { AsyncLogger } from './AsyncLogger.ts'\n\nexport interface ValidateSufficientXl1ReserveBalanceArgs {\n amount: bigint\n bridgeAccount: AccountInstance\n gateway: XyoGatewayRunner\n logger?: AsyncLogger\n}\n\n/**\n * Checks that the bridge's XL1 reserve account has at least `amount` of native balance\n * available to cover an inbound (EVM → XL1) reserve transfer. Mirrors the XL1 → EVM\n * direction's `validateSufficientXL1SourceAddressBalance` in spirit: a quick pre-flight\n * gate to avoid building, signing, and dispatching a transaction the chain will then\n * reject for insufficient funds.\n *\n * Race conditions: a concurrent submission could deplete the reserve between this check\n * and the actual XL1 submission. That's acceptable — the worker chain will fail the\n * submission, BullMQ will retry, and the next retry will re-validate. The check exists to\n * filter the bulk of insufficient-balance cases cheaply, not to be perfectly atomic.\n *\n * Network fees are not included in the comparison (matching the XL1 → EVM validator's\n * convention). Operators are expected to keep the reserve sufficiently above any single\n * bridge amount; tiny network-fee deltas would only flip the outcome at the margin and\n * BullMQ retry handles those.\n */\nexport async function validateSufficientXl1ReserveBalance({\n amount,\n bridgeAccount,\n gateway,\n logger,\n}: ValidateSufficientXl1ReserveBalanceArgs): Promise<boolean> {\n const viewer = assertEx(gateway.connection.viewer, () => 'Gateway connection does not have a viewer')\n const balance = await viewer.account.balance.accountBalance(bridgeAccount.address)\n await logger?.log(`XL1 reserve account ${bridgeAccount.address} balance: ${balance.toString()}; required: ${amount.toString()}`)\n return balance >= amount\n}\n","import {\n asAddress, assertEx, hexToBigInt,\n} from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport type { BridgeIntent, XyoGatewayRunner } from '@xyo-network/xl1-sdk'\n\nimport { generateBridgeEstimate } from '../util/index.ts'\nimport type { AsyncLogger } from './AsyncLogger.ts'\n\n/**\n * Checks if the liquidity source has sufficient balance for the bridge to execute the transaction. This doesn't\n * ensure that (due to race conditions) the transaction will succeed, but is a quick check to avoid\n * submitting transactions that are likely to fail.\n * @param bridgeIntent The bridge intent containing the details of the bridge transaction, including the source address and amount being bridged\n * @param gateway The XyoGatewayRunner to check the balance of the source address on XL1\n * @param config The bridge configuration, used to generate a bridge estimate for the transaction\n * @param logger Optional logger for asynchronous logging\n * @returns True if the liquidity source balance is sufficient to execute the bridge\n */\nexport const validateSufficientXL1SourceAddressBalance = async (\n bridgeIntent: BridgeIntent,\n gateway: XyoGatewayRunner,\n config: BridgeConfig,\n logger?: AsyncLogger,\n) => {\n // Get the amount being bridged from the bridge intent\n const viewer = assertEx(gateway.connection.viewer, () => 'Gateway connection does not have a viewer')\n const {\n srcAddress, srcAmount, destAddress,\n } = bridgeIntent\n const srcAddressBranded = asAddress(srcAddress, () => `Invalid source address in bridge intent: ${srcAddress}`)\n const [_, calculatedTransfer] = await generateBridgeEstimate(srcAddress, srcAmount, destAddress, config)\n const totalAmount = Object.values(calculatedTransfer.transfers).reduce((acc, transfer) => acc + hexToBigInt(transfer), 0n)\n\n // Check the srcAddress balance on XL1 for the bridge\n const accountBalance = await viewer.account.balance.accountBalance(srcAddressBranded)\n await logger?.log(`Account balance for ${srcAddressBranded}: ${accountBalance.toString()}`)\n return accountBalance >= totalAmount\n}\n","import { assertEx, isDefined } from '@xylabs/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type { Job } from 'bullmq'\nimport { Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport type { EthTxState, IBridgeServiceCollection } from '../../index.ts'\nimport { prefix } from '../prefix.ts'\nimport { submitEthTransaction } from './util/index.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\nimport type { Xl1DataLakeTransactionJobData } from './Xl1TransactionJobData.ts'\n\nexport type EthTransactionSubmissionJobData = Xl1DataLakeTransactionJobData\nexport interface EthTransactionSubmissionJobReturn {\n submissionHash: Required<EthTxState>['submissionHash']\n}\nexport type EthTransactionSubmissionJob = Job<EthTransactionSubmissionJobData, EthTransactionSubmissionJobReturn>\n\nconst name = 'Submit ETH Transaction'\nconst queueName = 'eth-tx-submit'\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel, services?: IBridgeServiceCollection) => {\n const bridge = assertEx(services?.bridge, () => 'bridge service not provided')\n const wallet = assertEx(services?.wallet, () => 'wallet service not provided')\n const stateMap = assertEx(services?.ethTxStateMap, () => 'ethTxStateMap service not provided')\n\n const worker = new Worker(\n queueName,\n async (job: EthTransactionSubmissionJob) => {\n const { tx, offChainPayloads } = job.data\n const hash = await PayloadBuilder.hash(tx[0])\n const state = assertEx(await stateMap.get(hash), () => `[${hash}] state not found`)\n\n // Idempotency check against resubmission\n const { submissionHash: existingSubmissionHash } = state\n if (isDefined(existingSubmissionHash)) {\n await job.log(`[${hash}] Tx already submitted with submission response hash ${existingSubmissionHash}`)\n return { submissionHash: existingSubmissionHash }\n }\n\n // Submit the transaction to the Ethereum network\n await job.log(`[${hash}] Submitting ETH tx`)\n const submissionHash = assertEx(await submitEthTransaction(tx, offChainPayloads, bridge, wallet), () => `[${hash}] submissionHash not found in receipt`)\n await job.log(`[${hash}] Submitted ETH tx and received submission response hash ${submissionHash}`)\n return { submissionHash }\n },\n {\n connection, telemetry, concurrency: 1, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const EthTransactionSubmission: WorkerDescription = {\n createWorker, name, queueName,\n}\n","import { assertEx, isDefined } from '@xylabs/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type { Job } from 'bullmq'\nimport { Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport type { EthTxState, IBridgeServiceCollection } from '../../index.ts'\nimport { prefix } from '../prefix.ts'\nimport type { EthTransactionSubmissionJobReturn } from './EthTransactionSubmission.ts'\nimport { EthTransactionSubmission } from './EthTransactionSubmission.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\nimport type { Xl1TransactionJobData } from './Xl1TransactionJobData.ts'\n\nexport type EthTransactionSubmissionStorageJobData = Xl1TransactionJobData\nexport interface EthTransactionSubmissionStorageJobReturn {\n submissionHash: Required<EthTxState>['submissionHash']\n}\nexport type EthTransactionSubmissionStorageJob = Job<EthTransactionSubmissionStorageJobData, EthTransactionSubmissionStorageJobReturn>\n\nconst name = 'Store ETH Transaction Submission'\nconst queueName = 'eth-tx-store-submission'\n\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel, services?: IBridgeServiceCollection) => {\n const stateMap = assertEx(services?.ethTxStateMap, () => 'ethTxStateMap service not provided')\n\n const worker = new Worker(\n queueName,\n async (job: EthTransactionSubmissionStorageJob) => {\n const { tx } = job.data\n // Get the hash of the transaction\n const hash = await PayloadBuilder.hash(tx[0])\n\n // Get the state of the transaction\n const state = assertEx(await stateMap.get(hash), () => `[${hash}] state not found`)\n\n // Idempotency check against re-store\n const { submissionHash: existingSubmissionHash } = state\n if (isDefined(existingSubmissionHash)) {\n await job.log(`[${hash}] submissionHash already stored as ${existingSubmissionHash}`)\n return { submissionHash: existingSubmissionHash }\n }\n\n // In a Flow, this job should be the PARENT and the submit job should be a CHILD.\n // That lets us read the child job’s return value(s) here.\n const childrenValues = await job.getChildrenValues()\n const jobKey = `${prefix}:${EthTransactionSubmission.queueName}:${hash}`\n const childValues = childrenValues?.[jobKey] as EthTransactionSubmissionJobReturn | undefined\n const submissionHash = childValues?.submissionHash\n\n const resolvedSubmissionHash = assertEx(submissionHash, () => `[${hash}] child submissionHash not found in children values`)\n\n // Store the submission hash in the state\n await job.log(`[${hash}] Storing ETH submissionHash`)\n state.submissionHash = resolvedSubmissionHash\n await stateMap.set(hash, state)\n await job.log(`[${hash}] Stored ETH submissionHash`)\n return { submissionHash: resolvedSubmissionHash }\n },\n {\n connection, telemetry, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const EthTransactionSubmissionStorage: WorkerDescription = {\n createWorker, name, queueName,\n}\n","import type {\n Address, BrandedHash, Hex,\n} from '@xylabs/sdk-js'\nimport {\n assertEx, delay, isDefined, isNull,\n} from '@xylabs/sdk-js'\nimport type { AccountInstance } from '@xyo-network/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type {\n ChainId, IterableMap, SignedHydratedTransaction, XyoGatewayRunner, XyoViewer,\n} from '@xyo-network/xl1-sdk'\nimport { asXL1BlockNumber } from '@xyo-network/xl1-sdk'\nimport type { Job } from 'bullmq'\nimport { Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport type { BridgeFulfillmentState } from '../../BridgeFulfillmentState.ts'\nimport type { IBridgeServiceCollection } from '../../index.ts'\nimport { validateSufficientXl1ReserveBalance } from '../../validation/index.ts'\nimport { prefix } from '../prefix.ts'\nimport { buildEthToXl1ReserveTx, submitXl1Transaction } from './util/index.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\n\nexport interface Xl1ReserveTxFulfillmentJobData {\n /** BigInt as a decimal string. */\n bridgeId: string\n /** EVM bridge contract address. */\n contractAddress: Address\n /** EVM chain id. */\n evmChainId: Hex\n /** Bridge identity, used as the bridgeFulfillmentMap key. */\n identity: string\n /** XL1 chain id (resolved from config at scan time). */\n xl1ChainId: ChainId\n /** XL1 token \"address\" (chain id of the token, resolved from config at scan time). */\n xl1TokenAddress: Hex\n}\n\nexport type Xl1ReserveTxFulfillmentJob = Job<Xl1ReserveTxFulfillmentJobData, void>\n\nconst name = 'XL1 Reserve Transfer Fulfillment'\nconst queueName = 'eth-to-xl1-fulfill'\n\n// Per-attempt window. nbf = build-time XL1 head, exp = head + EXP_BLOCKS_AHEAD. Once head\n// passes exp, the chain refuses the tx and we throw retryable so BullMQ schedules another\n// invocation to build a fresh attempt.\nconst EXP_BLOCKS_AHEAD = 1000\n\n// Polling cadence inside the wait-for-inclusion loop. BullMQ's auto lock-renewal runs at\n// half the worker's lockDuration; polling every 5s keeps the event loop turning so the\n// renewal heartbeat fires and the lock stays fresh.\nconst POLL_INTERVAL_MS = 5000\n\n// Worker concurrency. Each worker invocation holds a slot for up to one EXP_BLOCKS_AHEAD\n// XL1 window; with 32 concurrent slots we can process 32 distinct bridge ids in parallel.\nconst CONCURRENCY = 32\n\ninterface ResumeContext {\n fulfillmentMap: IterableMap<string, BridgeFulfillmentState>\n identity: string\n job: Xl1ReserveTxFulfillmentJob\n state: BridgeFulfillmentState\n viewer: XyoViewer\n}\n\n/**\n * Check an existing currentAttempt for inclusion or expiration. Mutates `state` in place\n * (and writes it back) on either resolution. Leaves currentAttempt untouched if the attempt\n * is still in window.\n */\nasync function tryResumeCurrentAttempt(ctx: ResumeContext): Promise<void> {\n const {\n fulfillmentMap, identity, job, state, viewer,\n } = ctx\n const attempt = assertEx(state.currentAttempt, () => 'tryResumeCurrentAttempt called without currentAttempt')\n const found = await viewer.transaction.byHash(attempt.txHash)\n if (isDefined(found) && !isNull(found)) {\n state.fulfilled = attempt\n state.currentAttempt = undefined\n await fulfillmentMap.set(identity, state)\n await job.log(`[${identity}] tx ${attempt.txHash} included on resume`)\n return\n }\n const head = await viewer.currentBlockNumber()\n if (head > attempt.exp) {\n state.previousAttempts.push(attempt)\n state.currentAttempt = undefined\n await fulfillmentMap.set(identity, state)\n await job.log(`[${identity}] resumed attempt expired (head=${head}); will build fresh`)\n }\n}\n\ninterface BuildSubmitContext extends ResumeContext {\n account: AccountInstance\n bridgeId: bigint\n contractAddress: Address\n evmChainId: Hex\n gateway: XyoGatewayRunner\n xl1ChainId: ChainId\n xl1TokenAddress: Hex\n}\n\n/**\n * Validate reserve balance, build a fresh tx with new nbf/exp, save state pre-broadcast,\n * then broadcast. On success, state.currentAttempt is populated. Throws retryable if\n * reserve is insufficient.\n */\nasync function buildAndSubmitFreshAttempt(ctx: BuildSubmitContext): Promise<void> {\n const {\n account, bridgeId, contractAddress, evmChainId,\n fulfillmentMap, gateway, identity, job, state, viewer, xl1ChainId, xl1TokenAddress,\n } = ctx\n const canonical = assertEx(state.canonical, () => 'buildAndSubmitFreshAttempt requires canonical')\n\n const sufficient = await validateSufficientXl1ReserveBalance({\n amount: canonical.amount,\n bridgeAccount: account,\n gateway,\n })\n if (!sufficient) {\n const msg = `[${identity}] XL1 reserve below required ${canonical.amount.toString()}; will retry`\n await job.log(msg)\n throw new Error(msg)\n }\n\n const head = await viewer.currentBlockNumber()\n const nbf = asXL1BlockNumber(head, true)\n const exp = asXL1BlockNumber(head + EXP_BLOCKS_AHEAD, true)\n const tx: SignedHydratedTransaction = await buildEthToXl1ReserveTx({\n amount: canonical.amount,\n bridgeAccount: account,\n bridgeId,\n destAddress: canonical.destAddress,\n evmChainId,\n evmContractAddress: contractAddress,\n evmSrcAddress: canonical.srcAddress,\n evmTokenAddress: canonical.destToken,\n evmTxHash: canonical.evmTxHash,\n exp,\n nbf,\n xl1ChainId,\n xl1TokenAddress,\n })\n const txHash: BrandedHash = await PayloadBuilder.hash(tx[0])\n\n // SAVE BEFORE BROADCAST. txHash equals the gateway's submission hash per the gateway\n // contract, so saving it pre-broadcast gives crash-recovery a polling key even if the\n // broadcast didn't return.\n state.currentAttempt = {\n exp: head + EXP_BLOCKS_AHEAD,\n nbf: head,\n submittedAt: Date.now(),\n txHash,\n }\n await fulfillmentMap.set(identity, state)\n\n await submitXl1Transaction(tx, [], gateway)\n await job.log(\n `[${identity}] attempt ${state.previousAttempts.length + 1} submitted: `\n + `txHash=${txHash} nbf=${head} exp=${head + EXP_BLOCKS_AHEAD}`,\n )\n}\n\n/**\n * Block in a polling loop until the active attempt is either included on chain or its exp\n * passes. On inclusion: mark fulfilled. On expiration: throw retryable so BullMQ schedules\n * another invocation with a fresh attempt.\n */\nasync function pollUntilIncludedOrExpired(ctx: ResumeContext): Promise<void> {\n const {\n fulfillmentMap, identity, job, state, viewer,\n } = ctx\n const attempt = assertEx(state.currentAttempt, () => 'pollUntilIncludedOrExpired requires currentAttempt')\n while (true) {\n const found = await viewer.transaction.byHash(attempt.txHash)\n if (isDefined(found) && !isNull(found)) {\n state.fulfilled = attempt\n state.currentAttempt = undefined\n await fulfillmentMap.set(identity, state)\n await job.log(`[${identity}] tx ${attempt.txHash} included`)\n return\n }\n const head = await viewer.currentBlockNumber()\n if (head > attempt.exp) {\n state.previousAttempts.push(attempt)\n state.currentAttempt = undefined\n await fulfillmentMap.set(identity, state)\n const msg = `[${identity}] attempt ${state.previousAttempts.length} expired (head=${head}, exp=${attempt.exp})`\n await job.log(msg)\n throw new Error(msg)\n }\n await delay(POLL_INTERVAL_MS)\n }\n}\n\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel, services?: IBridgeServiceCollection) => {\n const svc = assertEx(services, () => 'services not provided')\n const {\n account, bridgeFulfillmentMap, gateway,\n } = svc\n\n const worker = new Worker(\n queueName,\n async (job: Xl1ReserveTxFulfillmentJob) => {\n const {\n bridgeId, contractAddress, evmChainId, identity, xl1ChainId, xl1TokenAddress,\n } = job.data\n\n const initialState = await bridgeFulfillmentMap.get(identity)\n if (initialState?.fulfilled) {\n await job.log(`[${identity}] already fulfilled — skipping`)\n return\n }\n const state = assertEx(initialState, () => `[${identity}] no fulfillment state — Stage 1 did not run`)\n assertEx(state.canonical, () => `[${identity}] canonical missing — Stage 1 did not write canonical`)\n\n // Manual-retry: clear stale failed marker. We're trying again.\n if (state.failed) {\n state.failed = undefined\n await bridgeFulfillmentMap.set(identity, state)\n }\n\n const viewer = assertEx(gateway.connection.viewer, () => `[${identity}] gateway viewer not available`)\n\n const ctx: ResumeContext = {\n fulfillmentMap: bridgeFulfillmentMap,\n identity,\n job,\n state,\n viewer,\n }\n\n if (state.currentAttempt) {\n await tryResumeCurrentAttempt(ctx)\n if (state.fulfilled) return\n }\n\n if (!state.currentAttempt) {\n await buildAndSubmitFreshAttempt({\n ...ctx,\n account,\n bridgeId: BigInt(bridgeId),\n contractAddress,\n evmChainId,\n gateway,\n xl1ChainId,\n xl1TokenAddress,\n })\n }\n\n await pollUntilIncludedOrExpired(ctx)\n },\n {\n concurrency: CONCURRENCY,\n connection,\n prefix,\n telemetry,\n },\n )\n\n // Permanent-failure marker. BullMQ retries until job.attemptsMade >= job.opts.attempts;\n // after that the job is permanently failed. Record state.failed so the status route\n // returns 504 with reason. Manual retry from BullBoard clears state.failed in the\n // worker's entry path and re-runs the cycle.\n worker.on('failed', async (job, err) => {\n if (!isDefined(job)) return\n const attemptsAllowed = job.opts.attempts ?? Infinity\n if (job.attemptsMade < attemptsAllowed) return\n const identity = job.data?.identity\n if (!isDefined(identity)) return\n const state = await bridgeFulfillmentMap.get(identity)\n if (!isDefined(state)) return\n state.failed = {\n at: Date.now(),\n reason: `attempts exhausted (${job.attemptsMade}/${attemptsAllowed}): ${err.message}`,\n }\n await bridgeFulfillmentMap.set(identity, state)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const Xl1ReserveTxFulfillment: WorkerDescription = {\n createWorker, name, queueName,\n}\n","import type { Job } from 'bullmq'\nimport { Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport { prefix } from '../prefix.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\nimport type { Xl1DataLakeTransactionJobData } from './Xl1TransactionJobData.ts'\n\nexport type Xl1ToEthBridgeParentJobData = Xl1DataLakeTransactionJobData\nexport interface Xl1ToEthBridgeParentJobReturn { }\nexport type Xl1ToEthBridgeParentJob = Job<Xl1ToEthBridgeParentJobData, Xl1ToEthBridgeParentJobReturn>\n\nconst name = 'Bridge XL1 to Ethereum'\nconst queueName = 'xl1-to-eth-bridge'\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel) => {\n const worker = new Worker(\n queueName,\n async (job: Xl1ToEthBridgeParentJob) => {\n await job.log(`[${job.name}] start`)\n // Parent job has no work other than waiting on children\n await job.log(`[${job.name}] done`)\n return {}\n },\n {\n connection, telemetry, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const Xl1ToEthBridgeParent: WorkerDescription = {\n createWorker, name, queueName,\n}\n","import type { BrandedHash } from '@xylabs/sdk-js'\nimport {\n assertEx, isDefined, isNull,\n} from '@xylabs/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type { Job } from 'bullmq'\nimport { UnrecoverableError, Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport type { IBridgeServiceCollection } from '../../index.ts'\nimport { prefix } from '../prefix.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\nimport type { Xl1TransactionJobData } from './Xl1TransactionJobData.ts'\n\nexport type Xl1TransactionMonitorJobData = Xl1TransactionJobData\nexport interface Xl1TransactionMonitorJobReturn {\n submissionHash: BrandedHash\n}\nexport type Xl1TransactionMonitorJob = Job<Xl1TransactionMonitorJobData, Xl1TransactionMonitorJobReturn>\n\nconst name = 'Monitor Submitted XL1 Transaction'\nconst queueName = 'xl1-tx-monitor'\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel, services?: IBridgeServiceCollection) => {\n const gateway = assertEx(services?.gateway, () => 'gateway service not provided')\n const stateMap = assertEx(services?.xl1TxStateMap, () => 'xl1TxStateMap service not provided')\n const viewer = assertEx(gateway.connection.viewer, () => 'viewer not defined on gateway')\n\n const worker = new Worker(\n queueName,\n async (job: Xl1TransactionMonitorJob) => {\n const { tx } = job.data\n // Get the hash of the transaction\n const hash = await PayloadBuilder.hash(tx[0])\n // Get the state of the transaction\n const state = assertEx(await stateMap.get(hash), () => `[${hash}] state not found`)\n const submissionHash = assertEx(state.submissionHash, () => `[${hash}] submissionHash not found`)\n\n // Check for transaction inclusion on chain\n await job.log(`[${hash}] Checking for XL1 transaction inclusion on chain`)\n const foundTx = await viewer.transaction.byHash(submissionHash)\n // const foundTx = await viewer.transaction.byHash(submissionHash)\n\n // Transaction found on chain\n if (isDefined(foundTx) && !isNull(foundTx)) {\n await job.log(`[${hash}] Found transaction on chain`)\n // Store the block hash\n const submissionHash = await PayloadBuilder.hash(foundTx[0])\n return { submissionHash }\n }\n\n // Check for transaction expiration\n const currentBlockNumber = await viewer.currentBlockNumber()\n if (tx[0].exp < currentBlockNumber) {\n await job.log(\n `[${hash}] Transaction expired at block ${tx[0].exp}, current block ${currentBlockNumber}`,\n )\n // Throw unrecoverable error to stop retries\n throw new UnrecoverableError(`[${hash}] Transaction expired and will never be included`)\n }\n\n // Transaction not yet found, but still valid — retry later\n await job.log(`[${hash}] Transaction not yet included, retrying later`)\n throw new Error(`[${hash}] Transaction not yet included`)\n },\n {\n connection, telemetry, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const Xl1TransactionMonitor: WorkerDescription = {\n createWorker, name, queueName,\n}\n","import { assertEx } from '@xylabs/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type { SignedHydratedTransaction } from '@xyo-network/xl1-sdk'\nimport type { Job } from 'bullmq'\nimport { Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport type { IBridgeServiceCollection } from '../../index.ts'\nimport { prefix } from '../prefix.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\nimport type { Xl1DataLakeTransactionJobData } from './Xl1TransactionJobData.ts'\n\nexport type Xl1TransactionPreparationJobData = Xl1DataLakeTransactionJobData\nexport interface Xl1TransactionPreparationJobReturn { preparedTx: SignedHydratedTransaction }\nexport type Xl1TransactionPreparationJob = Job<Xl1TransactionPreparationJobData, Xl1TransactionPreparationJobReturn>\n\nconst name = 'Prepare XL1 Transaction'\nconst queueName = 'xl1-tx-prepare'\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel, services?: IBridgeServiceCollection) => {\n const stateMap = assertEx(services?.xl1TxStateMap, () => 'xl1TxStateMap service not provided')\n\n const worker = new Worker(\n queueName,\n async (job: Xl1TransactionPreparationJob) => {\n const { tx, offChainPayloads = [] } = job.data\n const hash = await PayloadBuilder.hash(tx[0])\n await job.log(`[${hash}] preparing XL1 transaction`)\n const preparedTx = tx\n await job.log(`[${hash}] storing XL1 preparedTx`)\n await stateMap.set(hash, { offChainPayloads, preparedTx })\n await job.log(`[${hash}] stored XL1 preparedTx`)\n await job.log(`[${hash}] prepared XL1 transaction`)\n return { preparedTx }\n },\n {\n connection, telemetry, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const Xl1TransactionPreparation: WorkerDescription = {\n createWorker, name, queueName,\n}\n","import { assertEx, isDefined } from '@xylabs/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type { Job } from 'bullmq'\nimport { Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport type { IBridgeServiceCollection, Xl1TxState } from '../../index.ts'\nimport { prefix } from '../prefix.ts'\nimport { submitXl1Transaction } from './util/index.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\nimport type { Xl1TransactionJobData } from './Xl1TransactionJobData.ts'\n\nexport type Xl1TransactionSubmissionJobData = Xl1TransactionJobData\nexport interface Xl1TransactionSubmissionJobReturn {\n submissionHash: Required<Xl1TxState>['submissionHash']\n}\nexport type Xl1TransactionSubmissionJob = Job<Xl1TransactionSubmissionJobData, Xl1TransactionSubmissionJobReturn>\n\nconst name = 'Submit XL1 Transaction'\nconst queueName = 'xl1-tx-submit'\n\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel, services?: IBridgeServiceCollection) => {\n const gateway = assertEx(services?.gateway, () => 'gateway service not provided')\n const stateMap = assertEx(services?.xl1TxStateMap, () => 'xl1TxStateMap service not provided')\n\n const worker = new Worker(\n queueName,\n async (job: Xl1TransactionSubmissionJob) => {\n const { tx } = job.data\n // Get the hash of the transaction\n const hash = await PayloadBuilder.hash(tx[0])\n // Get the state of the transaction\n const state = assertEx(await stateMap.get(hash), () => `[${hash}] state not found`)\n const {\n preparedTx, offChainPayloads = [], submissionHash: existingSubmissionHash,\n } = state\n\n // Idempotency check against resubmission\n if (isDefined(existingSubmissionHash)) {\n await job.log(`[${hash}] Tx already submitted with submission response hash ${existingSubmissionHash}`)\n return { submissionHash: existingSubmissionHash }\n }\n const txToSubmit = assertEx(preparedTx, () => `[${hash}] preparedTx not found`)\n\n // Submit the transaction to the XL1 network\n await job.log(`[${hash}] Submitting XL1 tx`)\n const [submissionHash] = await submitXl1Transaction(txToSubmit, offChainPayloads, gateway)\n await job.log(`[${hash}] Submitted XL1 tx`)\n\n // This worker intentionally does NOT store state as subsequent steps will do that.\n return { submissionHash }\n },\n {\n connection, telemetry, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const Xl1TransactionSubmission: WorkerDescription = {\n createWorker, name, queueName,\n}\n","import { assertEx, isDefined } from '@xylabs/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type { Job } from 'bullmq'\nimport { Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport type { IBridgeServiceCollection, Xl1TxState } from '../../index.ts'\nimport { prefix } from '../prefix.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\nimport type { Xl1TransactionJobData } from './Xl1TransactionJobData.ts'\nimport type { Xl1TransactionSubmissionJobReturn } from './Xl1TransactionSubmission.ts'\nimport { Xl1TransactionSubmission } from './Xl1TransactionSubmission.ts'\n\nexport type Xl1TransactionSubmissionStorageJobData = Xl1TransactionJobData\nexport interface Xl1TransactionSubmissionStorageJobReturn {\n submissionHash: Required<Xl1TxState>['submissionHash']\n}\nexport type Xl1TransactionSubmissionStorageJob = Job<Xl1TransactionSubmissionStorageJobData, Xl1TransactionSubmissionStorageJobReturn>\n\nconst name = 'Store XL1 Transaction Submission'\nconst queueName = 'xl1-tx-store-submission'\n\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel, services?: IBridgeServiceCollection) => {\n const stateMap = assertEx(services?.xl1TxStateMap, () => 'xl1TxStateMap service not provided')\n\n const worker = new Worker(\n queueName,\n async (job: Xl1TransactionSubmissionStorageJob) => {\n const { tx } = job.data\n // Get the hash of the transaction\n const hash = await PayloadBuilder.hash(tx[0])\n\n // Get the state of the transaction\n const state = assertEx(await stateMap.get(hash), () => `[${hash}] state not found`)\n\n // Idempotency check against re-store\n const { submissionHash: existingSubmissionHash } = state\n if (isDefined(existingSubmissionHash)) {\n await job.log(`[${hash}] submissionHash already stored as ${existingSubmissionHash}`)\n return { submissionHash: existingSubmissionHash }\n }\n\n // In a Flow, this job should be the PARENT and the submit job should be a CHILD.\n // That lets us read the child job’s return value(s) here.\n const childrenValues = await job.getChildrenValues()\n const jobKey = `${prefix}:${Xl1TransactionSubmission.queueName}:${hash}`\n const childValues = childrenValues?.[jobKey] as Xl1TransactionSubmissionJobReturn | undefined\n const submissionHash = childValues?.submissionHash\n\n const resolvedSubmissionHash = assertEx(submissionHash, () => `[${hash}] child submissionHash not found in children values`)\n\n // Store the submission hash in the state\n await job.log(`[${hash}] Storing XL1 submissionHash`)\n state.submissionHash = resolvedSubmissionHash\n await stateMap.set(hash, state)\n await job.log(`[${hash}] Stored XL1 submissionHash`)\n\n return { submissionHash: resolvedSubmissionHash }\n },\n {\n connection, telemetry, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const Xl1TransactionSubmissionStorage: WorkerDescription = {\n createWorker, name, queueName,\n}\n","import type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport type { IBridgeServiceCollection } from '../../index.ts'\nimport { EthEventVerification } from './EthEventVerification.ts'\nimport { EthToXl1BridgeParent } from './EthToXl1BridgeParent.ts'\nimport { EthTransactionMonitor } from './EthTransactionMonitor.ts'\nimport { EthTransactionPreparation } from './EthTransactionPreparation.ts'\nimport { EthTransactionSubmission } from './EthTransactionSubmission.ts'\nimport { EthTransactionSubmissionStorage } from './EthTransactionSubmissionStorage.ts'\nimport { Xl1ReserveTxFulfillment } from './Xl1ReserveTxFulfillment.ts'\nimport { Xl1ToEthBridgeParent } from './Xl1ToEthBridgeParent.ts'\nimport { Xl1TransactionMonitor } from './Xl1TransactionMonitor.ts'\nimport { Xl1TransactionPreparation } from './Xl1TransactionPreparation.ts'\nimport { Xl1TransactionSubmission } from './Xl1TransactionSubmission.ts'\nimport { Xl1TransactionSubmissionStorage } from './Xl1TransactionSubmissionStorage.ts'\n\n// EVM→XL1 path: EthEventVerification (Stage 1) → Xl1ReserveTxFulfillment (Stage 2)\n// → EthToXl1BridgeParent (top, no-op coordinator).\n// XL1→EVM path: Xl1Transaction* + EthTransaction* sequence under Xl1ToEthBridgeParent.\n// The Xl1Transaction*/EthTransaction* workers are direction-agnostic — they take a signed\n// tx and submit/monitor it — so they remain registered for the XL1→EVM flow even though\n// the EVM→XL1 flow no longer uses them.\nexport const createWorkers = (connection: Redis, telemetry: BullMQOtel, services: IBridgeServiceCollection) => {\n EthEventVerification.createWorker(connection, telemetry, services)\n EthToXl1BridgeParent.createWorker(connection, telemetry)\n EthTransactionMonitor.createWorker(connection, telemetry, services)\n EthTransactionPreparation.createWorker(connection, telemetry, services)\n EthTransactionSubmission.createWorker(connection, telemetry, services)\n EthTransactionSubmissionStorage.createWorker(connection, telemetry, services)\n Xl1ReserveTxFulfillment.createWorker(connection, telemetry, services)\n Xl1ToEthBridgeParent.createWorker(connection, telemetry)\n Xl1TransactionMonitor.createWorker(connection, telemetry, services)\n Xl1TransactionPreparation.createWorker(connection, telemetry, services)\n Xl1TransactionSubmission.createWorker(connection, telemetry, services)\n Xl1TransactionSubmissionStorage.createWorker(connection, telemetry, services)\n}\n","import type { Address, Hex } from '@xylabs/sdk-js'\n\nexport interface EthToXl1BridgeJobIdContext {\n /** The LiquidityPoolBridge contract's `bridgeToRemote` counter — assigned by\n * `nextBridgeToId++` and stored at `bridgesToRemote[bridgeId]`. Source of truth is\n * contract storage, not the event log. */\n bridgeId: bigint\n contractAddress: Address\n evmChainId: Hex\n}\n\n/**\n * Deterministic BullMQ jobId for an EVM→XL1 bridge flow. The id is derived from the\n * contract-assigned bridge id so that:\n * - The same (chainId, contract, bridgeId) always maps to the same job — BullMQ will\n * dedup duplicate enqueues automatically (e.g. if the scanner runs across the same\n * bridge id during backfill).\n * - The status route can derive the jobId from the URL `:id` parameter without\n * touching the contract or hashing a transaction.\n * - Replay is the same id; manual `Job.retry()` re-runs the existing job rather than\n * creating a parallel one.\n *\n * Both hex-string components are lowercased for a single canonical form. The bridgeId is\n * a uint256, so it's stringified as decimal.\n */\nexport function getJobIdForEthToXl1BridgeJob(context: EthToXl1BridgeJobIdContext): string {\n return `evm:${context.evmChainId.toLowerCase()}:${context.contractAddress.toLowerCase()}:${context.bridgeId.toString()}`\n}\n","import type { Address, Hex } from '@xylabs/sdk-js'\nimport type { ChainId } from '@xyo-network/xl1-sdk'\nimport type { FlowProducer } from 'bullmq'\n\nimport {\n EthEventVerification, EthToXl1BridgeParent, Xl1ReserveTxFulfillment,\n} from '../../workers/index.ts'\nimport { getJobIdForEthToXl1BridgeJob } from './getJobIdForEthToXl1BridgeJob.ts'\n\nexport interface EthToXl1BridgeJobContext {\n /** The LiquidityPoolBridge contract's bridgeToRemote counter. */\n bridgeId: bigint\n /** EVM bridge contract address. */\n contractAddress: Address\n /** EVM chain id. */\n evmChainId: Hex\n /** XL1 chain id (resolved from config at scan time). */\n xl1ChainId: ChainId\n /** XL1 token \"address\" (chain id of the token, resolved from config at scan time). */\n xl1TokenAddress: Hex\n}\n\n// Stage 2 carries the long-running retry posture: 1000 attempts × 10s fixed backoff per\n// the design spec. Each attempt is one full submission cycle (build → submit → poll until\n// included or expired), so 1000 retries is \"keep trying until ops intervenes.\" Linear or\n// exponential growth is a polish item to evaluate when we have outage data; for MVP fixed\n// 10s avoids the multi-day total backoff that pure linear would produce.\nconst STAGE_2_RETRY = {\n attempts: 1000,\n backoff: {\n delay: 10_000,\n type: 'fixed' as const,\n },\n}\n\n// Stage 1 is one-shot. UnrecoverableError on null-at-depth, no transient retry path.\nconst STAGE_1_RETRY = { attempts: 1 }\n\n/**\n * Creates the three-tier BullMQ flow for an EVM→XL1 bridge:\n *\n * eth-to-xl1-bridge (top — no-op coordinator, completes when children done)\n * └─ eth-to-xl1-fulfill (Stage 2 — build/submit/poll, 1000 attempts × 10s backoff)\n * └─ eth-event-verify (Stage 1 — verify once, write canonical, deepest-first)\n *\n * All three jobs share the same jobId from getJobIdForEthToXl1BridgeJob — the deterministic\n * `evm:{chainId}:{contract}:{bridgeId}` form. That id IS the bridge's immutable identity:\n * - BullMQ dedup makes scanner re-enqueues no-ops automatically.\n * - The status route reconstructs the jobId from the URL parameter without contract reads.\n * - Manual retry from BullBoard re-runs the *same* job rather than creating a parallel one.\n *\n * Stage 1 (deepest child) runs first per BullMQ flow semantics. It writes `canonical` to\n * bridgeFulfillmentMap. Stage 2 reads it from there. The two stages don't communicate via\n * children-values — the state map is their contract.\n */\nexport const createEthToXl1BridgeJob = async (\n flowProducer: FlowProducer,\n context: EthToXl1BridgeJobContext,\n) => {\n const jobId = getJobIdForEthToXl1BridgeJob(context)\n const identity = jobId\n\n const stageJobData = {\n bridgeId: context.bridgeId.toString(),\n contractAddress: context.contractAddress,\n evmChainId: context.evmChainId,\n identity,\n xl1ChainId: context.xl1ChainId,\n xl1TokenAddress: context.xl1TokenAddress,\n }\n\n return flowProducer.add({\n name: EthToXl1BridgeParent.name,\n queueName: EthToXl1BridgeParent.queueName,\n data: stageJobData,\n opts: { jobId },\n children: [\n {\n name: Xl1ReserveTxFulfillment.name,\n queueName: Xl1ReserveTxFulfillment.queueName,\n data: stageJobData,\n opts: { jobId, ...STAGE_2_RETRY },\n children: [\n {\n name: EthEventVerification.name,\n queueName: EthEventVerification.queueName,\n data: stageJobData,\n opts: { jobId, ...STAGE_1_RETRY },\n },\n ],\n },\n ],\n })\n}\n","import { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type { SignedHydratedTransaction } from '@xyo-network/xl1-sdk'\n\n/**\n * Returns a deterministic & repeatable job ID based off the Transaction hash. This is to ensure\n * that if the same transaction is attempted to be bridged multiple times, it will have the same\n * job ID and not create duplicate jobs.\n * https://docs.bullmq.io/guide/jobs/job-ids\n * \"The main reason to be able to specify a custom id is in cases when you want to avoid duplicated\n * jobs. Since ids must be unique, if you add a job with an existing id then that job will just be\n * ignored and not added to the queue at all.\"\n * @param tx The transaction to bridge from XL1 to ETH\n * @returns A deterministic job ID for the bridge job\n */\nexport const getJobIdForXl1ToEthBridgeJob = async (tx: SignedHydratedTransaction) => {\n const jobId = await PayloadBuilder.hash(tx[0])\n return jobId\n}\n","import type { Payload } from '@xyo-network/sdk-js'\nimport type { SignedHydratedTransaction } from '@xyo-network/xl1-sdk'\nimport type { FlowProducer } from 'bullmq'\n\nimport type {\n EthTransactionMonitorJobData,\n EthTransactionPreparationJobData,\n EthTransactionSubmissionJobData,\n EthTransactionSubmissionStorageJobData,\n Xl1ToEthBridgeParentJobData,\n Xl1TransactionMonitorJobData,\n Xl1TransactionPreparationJobData,\n Xl1TransactionSubmissionJobData,\n Xl1TransactionSubmissionStorageJobData,\n} from '../../workers/index.ts'\nimport {\n EthTransactionMonitor, EthTransactionPreparation, EthTransactionSubmission, EthTransactionSubmissionStorage, Xl1ToEthBridgeParent, Xl1TransactionMonitor,\n Xl1TransactionPreparation, Xl1TransactionSubmission, Xl1TransactionSubmissionStorage,\n} from '../../workers/index.ts'\nimport { getJobIdForXl1ToEthBridgeJob } from './getJobIdForXl1ToEthBridgeJob.ts'\n\n/**\n * Creates a job flow for bridging a transaction from XL1 to Ethereum.\n * @param flowProducer The flow producer to run the job\n * @param tx The bridge transaction\n * @param offChainPayloads The payloads to put off chain\n * @returns The JobNode representing the XL1 to ETH bridge job\n */\nexport const createXl1ToEthBridgeJob = async (\n flowProducer: FlowProducer,\n tx: SignedHydratedTransaction,\n offChainPayloads: Payload[] = [],\n) => {\n const jobId = await getJobIdForXl1ToEthBridgeJob(tx)\n const flow = await flowProducer.add({\n // Step 0 (runs first as parent job)\n name: Xl1ToEthBridgeParent.name,\n queueName: Xl1ToEthBridgeParent.queueName,\n data: { tx, offChainPayloads } as Xl1ToEthBridgeParentJobData,\n opts: { jobId },\n children: [\n {\n // Step 8\n name: EthTransactionMonitor.name,\n queueName: EthTransactionMonitor.queueName,\n data: { tx } as EthTransactionMonitorJobData,\n opts: {\n jobId, attempts: 60, backoff: { type: 'fixed', delay: 5000 },\n },\n children: [\n {\n // Step 7\n name: EthTransactionSubmissionStorage.name,\n queueName: EthTransactionSubmissionStorage.queueName,\n data: { tx } as EthTransactionSubmissionStorageJobData,\n opts: {\n jobId, attempts: 60, backoff: { type: 'fixed', delay: 5000 },\n },\n children: [\n {\n // Step 6\n name: EthTransactionSubmission.name,\n queueName: EthTransactionSubmission.queueName,\n data: { tx, offChainPayloads } as EthTransactionSubmissionJobData,\n opts: { jobId },\n children: [\n {\n // Step 5\n name: EthTransactionPreparation.name,\n queueName: EthTransactionPreparation.queueName,\n data: { tx, offChainPayloads } as EthTransactionPreparationJobData,\n opts: {\n jobId, attempts: 60, backoff: { type: 'fixed', delay: 5000 },\n },\n children: [\n {\n // Step 4\n name: Xl1TransactionMonitor.name,\n queueName: Xl1TransactionMonitor.queueName,\n data: { tx } as Xl1TransactionMonitorJobData,\n opts: {\n jobId, attempts: 60, backoff: { type: 'fixed', delay: 5000 },\n },\n children: [\n {\n // Step 3\n name: Xl1TransactionSubmissionStorage.name,\n queueName: Xl1TransactionSubmissionStorage.queueName,\n data: { tx } as Xl1TransactionSubmissionStorageJobData,\n opts: {\n jobId, attempts: 60, backoff: { type: 'fixed', delay: 5000 },\n },\n children: [\n {\n // Step 2\n name: Xl1TransactionSubmission.name,\n queueName: Xl1TransactionSubmission.queueName,\n data: { tx } as Xl1TransactionSubmissionJobData,\n opts: { jobId },\n children: [\n {\n // Step 1 (runs first as deepest child)\n name: Xl1TransactionPreparation.name,\n queueName: Xl1TransactionPreparation.queueName,\n data: { tx, offChainPayloads } as Xl1TransactionPreparationJobData,\n opts: {\n jobId, attempts: 60, backoff: { type: 'fixed', delay: 5000 },\n },\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n })\n return flow\n}\n","import type { SignedHydratedTransaction } from '@xyo-network/xl1-sdk'\nimport type { FlowProducer } from 'bullmq'\n\nimport { Xl1ToEthBridgeParent } from '../../workers/index.ts'\nimport { getJobIdForXl1ToEthBridgeJob } from './getJobIdForXl1ToEthBridgeJob.ts'\n\nexport const getXl1ToEthBridgeJob = async (flowProducer: FlowProducer, tx: SignedHydratedTransaction) => {\n const id = await getJobIdForXl1ToEthBridgeJob(tx)\n const flow = await flowProducer.getFlow({ queueName: Xl1ToEthBridgeParent.queueName, id })\n return flow\n}\n","import type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { Queue } from 'bullmq'\n\nimport { getConnection } from './connection.ts'\nimport { prefix } from './prefix.ts'\nimport {\n EthEventVerification, EthToXl1BridgeParent, Xl1ReserveTxFulfillment,\n} from './workers/index.ts'\n\nexport interface EthToXl1Queues {\n ethEventVerification: Queue\n ethToXl1BridgeParent: Queue\n xl1ReserveTxFulfillment: Queue\n}\n\nlet ethToXl1Queues: EthToXl1Queues | undefined\n\n/**\n * Lazily-constructed Queue handles for the EVM→XL1 direction. Used by the status route to\n * look up flow progress and (eventually) by createQueueMetrics for telemetry. Singleton-cached\n * so repeated calls don't re-create connections.\n *\n * Three queues, matching the three-tier flow under Path A:\n * - ethToXl1BridgeParent — no-op coordinator (presence ⇒ flow exists)\n * - xl1ReserveTxFulfillment — Stage 2 build/submit/poll\n * - ethEventVerification — Stage 1 canonical verify (deepest child)\n *\n * The XL1Transaction* / EthTransaction* queues that the old EVM→XL1 flow shared with the\n * XL1→EVM direction are now used only by the XL1→EVM flow; they're listed in\n * `getXl1ToEthQueues` and don't belong here.\n */\nexport const getEthToXl1Queues = (config: BridgeConfig): EthToXl1Queues => {\n if (ethToXl1Queues) return ethToXl1Queues\n const connection = getConnection(config)\n ethToXl1Queues = {\n ethEventVerification: new Queue(EthEventVerification.queueName, { connection, prefix }),\n ethToXl1BridgeParent: new Queue(EthToXl1BridgeParent.queueName, { connection, prefix }),\n xl1ReserveTxFulfillment: new Queue(Xl1ReserveTxFulfillment.queueName, { connection, prefix }),\n }\n return ethToXl1Queues\n}\n","import type { Xl1ToEthQueues } from './getXl1ToEthQueues.ts'\nimport type {\n EthTransactionMonitorJob, EthTransactionPreparationJob,\n EthTransactionSubmissionJob,\n Xl1ToEthBridgeParentJob,\n Xl1TransactionMonitorJob, Xl1TransactionPreparationJob, Xl1TransactionSubmissionJob,\n Xl1TransactionSubmissionStorageJob,\n} from './workers/index.ts'\n\nexport interface StatusQueueJobs {\n ethTransactionMonitorJob?: EthTransactionMonitorJob\n ethTransactionPreparationJob?: EthTransactionPreparationJob\n ethTransactionSubmissionJob?: EthTransactionSubmissionJob\n xl1ToEthBridgeParentJob?: Xl1ToEthBridgeParentJob\n xl1TransactionMonitorJob?: Xl1TransactionMonitorJob\n xl1TransactionPreparationJob?: Xl1TransactionPreparationJob\n xl1TransactionSubmissionJob?: Xl1TransactionSubmissionJob\n xl1TransactionSubmissionStorageJob?: Xl1TransactionSubmissionStorageJob\n}\n\n/**\n * Checks all the relevant status queues for a job with the given id and returns the jobs found in an object\n * @param queues The status queues to check for jobs\n * @param jobId The job id to look for in the queues, which is the same as the tx hash of the bridge transaction\n * @returns An object containing the jobs found in the status queues corresponding to the given job id\n */\nexport const getStatusQueueJobs = async (queues: Xl1ToEthQueues, jobId: string): Promise<StatusQueueJobs> => {\n const [\n ethTransactionMonitorJob,\n ethTransactionPreparationJob,\n ethTransactionSubmissionJob,\n xl1ToEthBridgeParentJob,\n xl1TransactionMonitorJob,\n xl1TransactionPreparationJob,\n xl1TransactionSubmissionJob,\n xl1TransactionSubmissionStorageJob,\n ] = await Promise.all([\n queues.ethTransactionMonitor.getJob(jobId),\n queues.ethTransactionPreparation.getJob(jobId),\n queues.ethTransactionSubmission.getJob(jobId),\n queues.xl1ToEthBridgeParent.getJob(jobId),\n queues.xl1TransactionMonitor.getJob(jobId),\n queues.xl1TransactionPreparation.getJob(jobId),\n queues.xl1TransactionSubmission.getJob(jobId),\n queues.xl1TransactionSubmissionStorage.getJob(jobId),\n ])\n return {\n ethTransactionMonitorJob,\n ethTransactionPreparationJob,\n ethTransactionSubmissionJob,\n xl1ToEthBridgeParentJob,\n xl1TransactionMonitorJob,\n xl1TransactionPreparationJob,\n xl1TransactionSubmissionStorageJob,\n xl1TransactionSubmissionJob,\n }\n}\n","import type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { Queue } from 'bullmq'\n\nimport { getConnection } from './connection.ts'\nimport { prefix } from './prefix.ts'\nimport {\n EthTransactionMonitor, EthTransactionPreparation, EthTransactionSubmission, Xl1ToEthBridgeParent, Xl1TransactionMonitor, Xl1TransactionPreparation,\n Xl1TransactionSubmission,\n Xl1TransactionSubmissionStorage,\n} from './workers/index.ts'\n\nexport interface Xl1ToEthQueues {\n ethTransactionMonitor: Queue\n ethTransactionPreparation: Queue\n ethTransactionSubmission: Queue\n xl1ToEthBridgeParent: Queue\n xl1TransactionMonitor: Queue\n xl1TransactionPreparation: Queue\n xl1TransactionSubmission: Queue\n xl1TransactionSubmissionStorage: Queue\n}\n\nlet xl1ToEthQueues: Xl1ToEthQueues | undefined\n\nexport const getXl1ToEthQueues = (config: BridgeConfig): Xl1ToEthQueues => {\n if (xl1ToEthQueues) return xl1ToEthQueues\n const connection = getConnection(config)\n xl1ToEthQueues = {\n ethTransactionMonitor: new Queue(EthTransactionMonitor.queueName, { connection, prefix }),\n ethTransactionPreparation: new Queue(EthTransactionPreparation.queueName, { connection, prefix }),\n ethTransactionSubmission: new Queue(EthTransactionSubmission.queueName, { connection, prefix }),\n xl1ToEthBridgeParent: new Queue(Xl1ToEthBridgeParent.queueName, { connection, prefix }),\n xl1TransactionMonitor: new Queue(Xl1TransactionMonitor.queueName, { connection, prefix }),\n xl1TransactionPreparation: new Queue(Xl1TransactionPreparation.queueName, { connection, prefix }),\n xl1TransactionSubmission: new Queue(Xl1TransactionSubmission.queueName, { connection, prefix }),\n xl1TransactionSubmissionStorage: new Queue(Xl1TransactionSubmissionStorage.queueName, { connection, prefix }),\n }\n return xl1ToEthQueues\n}\n","import type { Address, Hex } from '@xylabs/sdk-js'\nimport type { ChainId } from '@xyo-network/xl1-sdk'\nimport type { FlowProducer } from 'bullmq'\n\nimport { createEthToXl1BridgeJob } from '../flows/index.ts'\nimport type { EvmBridgeJobLog, EvmBridgeScannerEnqueue } from './EvmBridgeScanner.ts'\n\nexport interface CreateEnqueueEthToXl1BridgeOptions {\n evmChainId: Hex\n evmContractAddress: Address\n flowProducer: FlowProducer\n xl1ChainId: ChainId\n xl1TokenAddress: Hex\n}\n\n/**\n * Builds the production enqueue callback the EVM->XL1 scanner hands each new bridgeId.\n *\n * Path A (MVP) split: the scanner is now pure cursor + enqueue. All chain reads beyond the\n * scanner's own cursor advance happen *inside* the BullMQ flow:\n * - Stage 1 (`EthEventVerification`, deepest child) reads `bridgesToRemote(id)` at depth\n * and writes the canonical fulfillment record. A null slot at depth means orphaned and\n * terminally fails the flow without any reserve-side work.\n * - Stage 2 (`Xl1ReserveTxFulfillment`) consumes the canonical record and runs the\n * build/submit/poll cycle with its own retry posture.\n *\n * Why scanner-side verify was removed: keeping it here as a \"skip orphans\" gate produced\n * two divergent code paths for the same canonical-data read. Stage 1 already does the read\n * idempotently, and BullMQ dedups on the deterministic jobId — re-ticking over an already\n * enqueued id is a no-op. Letting Stage 1 own the verification keeps the scanner cheap\n * (one cursor read per tick) and the orphan-handling logic in one place.\n */\nexport function createEnqueueEthToXl1Bridge(options: CreateEnqueueEthToXl1BridgeOptions): EvmBridgeScannerEnqueue {\n const {\n evmChainId,\n evmContractAddress,\n flowProducer,\n xl1ChainId,\n xl1TokenAddress,\n } = options\n\n return async (bridgeId: bigint, jobLog?: EvmBridgeJobLog): Promise<void> => {\n await createEthToXl1BridgeJob(flowProducer, {\n bridgeId,\n contractAddress: evmContractAddress,\n evmChainId,\n xl1ChainId,\n xl1TokenAddress,\n })\n await jobLog?.(`[bridge-scanner] bridgeId ${bridgeId} enqueued`)\n }\n}\n","import type { Address, Hex } from '@xylabs/sdk-js'\nimport { isUndefined } from '@xylabs/sdk-js'\nimport type { LiquidityPoolBridge } from '@xyo-network/typechain'\nimport type { IterableMap } from '@xyo-network/xl1-sdk'\nimport type { Provider } from 'ethers'\n\nimport type { EvmConfirmationDepth } from '../../evm/index.ts'\nimport { resolveEvmBlockTagAtDepth } from '../workers/util/index.ts'\nimport type { EvmBridgeCursor } from './EvmBridgeCursor.ts'\nimport { getEvmBridgeCursorKey } from './EvmBridgeCursor.ts'\n\n/**\n * Per-tick log adapter — typically `(msg) => job.log(msg)` from the BullMQ Worker\n * processor that drives the scanner. Lets the scanner and the enqueue callback record\n * lines into the current tick's BullMQ job log so they're visible per-tick in dashboards.\n * Optional so the scanner remains usable without BullMQ context (tests, scripts).\n */\nexport type EvmBridgeJobLog = (message: string) => Promise<unknown>\n\nexport type EvmBridgeScannerEnqueue = (id: bigint, jobLog?: EvmBridgeJobLog) => Promise<void> | void\n\nexport interface EvmBridgeScannerOptions {\n bridge: LiquidityPoolBridge\n bridgeAddress: Address\n chainId: Hex\n confirmationDepth: EvmConfirmationDepth\n cursors: IterableMap<string, EvmBridgeCursor>\n enqueue: EvmBridgeScannerEnqueue\n provider: Provider\n}\n\nexport interface EvmBridgeScanOptions {\n jobLog?: EvmBridgeJobLog\n}\n\nexport interface EvmBridgeScanResult {\n confirmedHigh: bigint\n enqueued: number\n lastProcessedId: bigint\n}\n\nexport interface EvmBridgeScanner {\n scan(options?: EvmBridgeScanOptions): Promise<EvmBridgeScanResult>\n}\n\nexport function createEvmBridgeScanner(options: EvmBridgeScannerOptions): EvmBridgeScanner {\n const {\n bridge, bridgeAddress, chainId, confirmationDepth, cursors, enqueue, provider,\n } = options\n const cursorKey = getEvmBridgeCursorKey(chainId, bridgeAddress)\n\n return {\n async scan(options?: EvmBridgeScanOptions): Promise<EvmBridgeScanResult> {\n const jobLog = options?.jobLog\n const blockTag = await resolveEvmBlockTagAtDepth(provider, confirmationDepth)\n const confirmedHigh = await bridge.nextBridgeToId({ blockTag })\n\n const cursor = await cursors.get(cursorKey)\n const lastProcessedId = isUndefined(cursor) ? 0n : BigInt(cursor.lastProcessedId)\n\n if (confirmedHigh <= lastProcessedId) {\n return {\n confirmedHigh,\n enqueued: 0,\n lastProcessedId,\n }\n }\n\n let enqueued = 0\n for (let id = lastProcessedId + 1n; id <= confirmedHigh; id++) {\n await enqueue(id, jobLog)\n enqueued++\n }\n\n await cursors.set(cursorKey, { lastProcessedId: confirmedHigh.toString() })\n return {\n confirmedHigh,\n enqueued,\n lastProcessedId,\n }\n },\n }\n}\n","import type { Address, Hex } from '@xylabs/sdk-js'\n\n// Tracks how far an EVM bridge contract has been scanned. Stored in a persistent IterableMap\n// keyed by getEvmBridgeCursorKey(chainId, contractAddress) so a service restart resumes\n// where it left off rather than re-enqueuing every historical event.\n//\n// `lastProcessedId` is the highest BridgedToRemote id (a uint256 from the contract's\n// nextBridgeToId counter) that has been observed at confirmation depth and handed to the\n// enqueue callback. Stored as a decimal string because BigInt is not JSON-serializable and\n// the IterableMap backing store may be MongoDB.\nexport interface EvmBridgeCursor {\n lastProcessedId: string\n}\n\nexport function getEvmBridgeCursorKey(chainId: Hex, contractAddress: Address): string {\n return `${chainId.toLowerCase()}:${contractAddress.toLowerCase()}`\n}\n","import type { Logger } from '@xylabs/sdk-js'\nimport { Queue, Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport { prefix } from '../prefix.ts'\nimport type { EvmBridgeScanner } from './EvmBridgeScanner.ts'\n\nconst QUEUE_NAME = 'eth-to-xl1-scanner'\nconst REPEATABLE_JOB_NAME = 'scan'\n\n// Stable jobId so an actor restart re-attaches to the existing repeatable schedule rather\n// than accumulating duplicate schedules with each restart. BullMQ dedups by jobId on add.\nconst REPEATABLE_JOB_ID = 'eth-to-xl1-scanner-tick'\n\nexport interface EvmBridgeScannerRunnerOptions {\n connection: Redis\n intervalMs: number\n /** Defaults to the global `console` so the runner is usable without explicit wiring. */\n logger?: Logger\n scanner: EvmBridgeScanner\n telemetry?: BullMQOtel\n}\n\nexport interface EvmBridgeScannerRunnerHandle {\n start(): Promise<void>\n stop(): Promise<void>\n}\n\n/**\n * Wraps the EVM bridge scanner in a BullMQ repeatable job so it ticks at `intervalMs`.\n *\n * Each tick calls `scanner.scan()`, which reads the contract's `nextBridgeToId` at depth,\n * walks any new ids past the persisted cursor, hands each to the configured enqueue\n * callback (which dispatches a flow), and advances the cursor. If a tick throws, BullMQ\n * marks that tick failed; the next tick fires at the regular interval — failures of one\n * tick do not block subsequent ticks.\n *\n * Lifecycle is managed by start()/stop() so the actor can wire it into its own lifecycle.\n */\nexport function createEvmBridgeScannerRunner(options: EvmBridgeScannerRunnerOptions): EvmBridgeScannerRunnerHandle {\n const {\n connection, intervalMs, scanner, telemetry,\n } = options\n const logger: Logger = options.logger ?? console\n let queue: Queue | undefined\n let worker: Worker | undefined\n\n return {\n async start(): Promise<void> {\n queue = new Queue(QUEUE_NAME, {\n connection,\n prefix,\n telemetry,\n })\n worker = new Worker(QUEUE_NAME, async (job) => {\n await job.log('[scanner] tick start')\n const result = await scanner.scan({ jobLog: msg => job.log(msg) })\n await job.log(\n `[scanner] tick complete: enqueued=${result.enqueued} `\n + `confirmedHigh=${result.confirmedHigh.toString()} `\n + `lastProcessedId=${result.lastProcessedId.toString()}`,\n )\n }, {\n connection,\n prefix,\n telemetry,\n })\n\n worker.on('failed', (job, err) => {\n logger.error(`[scanner] tick ${job?.id} failed:`, err.message)\n })\n worker.on('error', (err) => {\n logger.error('[scanner] worker error:', err)\n })\n\n await queue.add(REPEATABLE_JOB_NAME, {}, {\n jobId: REPEATABLE_JOB_ID,\n repeat: { every: intervalMs },\n })\n },\n async stop(): Promise<void> {\n await worker?.close()\n await queue?.close()\n worker = undefined\n queue = undefined\n },\n }\n}\n","import type { Logger } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport type { FlowProducer } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport {\n getRemoteChainId, getScannerIntervalMs, getXl1ChainId, getXl1TokenAddress,\n} from '../../evm/index.ts'\nimport type { IBridgeServiceCollection } from '../../IBridgeServiceCollection.ts'\nimport { createEnqueueEthToXl1Bridge } from './createEnqueueEthToXl1Bridge.ts'\nimport { createEvmBridgeScanner } from './EvmBridgeScanner.ts'\nimport type { EvmBridgeScannerRunnerHandle } from './EvmBridgeScannerRunner.ts'\nimport { createEvmBridgeScannerRunner } from './EvmBridgeScannerRunner.ts'\n\nexport interface BuildEvmBridgeScannerRunnerOptions {\n config: BridgeConfig\n connection: Redis\n flowProducer: FlowProducer\n /** Threaded through to the runner + enqueue callback. Falls back to console downstream. */\n logger?: Logger\n services: IBridgeServiceCollection\n telemetry?: BullMQOtel\n}\n\n/**\n * Composes the scanner runner from config + services + queue infrastructure. Pulls the\n * remote chain/contract addresses and the scan interval from config; uses services' bridge\n * contract handle and provider for cursor-side reads; wires the (now identity-only)\n * enqueue callback. Verification + reserve-side work has moved into the BullMQ flow.\n */\nexport function buildEvmBridgeScannerRunner(options: BuildEvmBridgeScannerRunnerOptions): EvmBridgeScannerRunnerHandle {\n const {\n config, connection, flowProducer, logger, services, telemetry,\n } = options\n const evmChainId = getRemoteChainId(config)\n const evmContractAddress = config.remoteBridgeContractAddress\n const xl1ChainId = getXl1ChainId(config)\n const xl1TokenAddress = getXl1TokenAddress(config)\n const intervalMs = getScannerIntervalMs(config)\n\n const enqueue = createEnqueueEthToXl1Bridge({\n evmChainId,\n evmContractAddress,\n flowProducer,\n xl1ChainId,\n xl1TokenAddress,\n })\n\n const scanner = createEvmBridgeScanner({\n bridge: services.bridge,\n bridgeAddress: evmContractAddress,\n chainId: evmChainId,\n confirmationDepth: services.remoteConfirmationDepth,\n cursors: services.evmBridgeCursorMap,\n enqueue,\n provider: services.provider,\n })\n\n return createEvmBridgeScannerRunner({\n connection,\n intervalMs,\n logger,\n scanner,\n telemetry,\n })\n}\n","import { isDefined } from '@xylabs/sdk-js'\nimport type { BullMQOtelOptions } from 'bullmq-otel'\nimport { BullMQOtel } from 'bullmq-otel'\n\nlet telemetry: BullMQOtel | undefined\nconst options: BullMQOtelOptions = { enableMetrics: true }\n\nexport const getTelemetry = () => {\n if (isDefined(telemetry)) return telemetry\n telemetry = new BullMQOtel(options)\n return telemetry\n}\n","import type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport type { Express } from 'express'\n\nimport {\n getConnection, getFlowProducer, getTelemetry,\n} from '../services/queue/index.ts'\n\nexport const addFlowProducer = (app: Express, config: BridgeConfig): Express => {\n const connection = getConnection(config)\n const telemetry = getTelemetry()\n const flowProducer = getFlowProducer(connection, telemetry)\n app.flowProducer = flowProducer\n return app\n}\n","import { registerInstrumentations } from '@opentelemetry/instrumentation'\nimport { ExpressInstrumentation } from '@opentelemetry/instrumentation-express'\nimport { HttpInstrumentation } from '@opentelemetry/instrumentation-http'\n\n/**\n * Registers OpenTelemetry instrumentations for HTTP and Express.\n * This function is used to set up the necessary instrumentations for monitoring\n * HTTP requests and Express applications. Since it monkey patches the Express\n * router & middleware system, it should be called before any Express applications\n * are defined.\n */\nexport const addInstrumentation = () => {\n const instrumentations = [new HttpInstrumentation(), new ExpressInstrumentation()]\n registerInstrumentations({ instrumentations })\n}\n","import type { NoReqParams } from '@xylabs/express'\nimport { setRawResponseFormat } from '@xylabs/express'\nimport type { RequestHandler } from 'express'\nimport { ReasonPhrases } from 'http-status-codes'\n\nconst message = ReasonPhrases.OK\n\nconst handler: RequestHandler<NoReqParams> = (_req, res) => {\n setRawResponseFormat(res)\n res.status(200).send({ message })\n}\n\nexport const getLivez: RequestHandler<NoReqParams> = handler\n","import type { NoReqParams } from '@xylabs/express'\nimport { setRawResponseFormat } from '@xylabs/express'\nimport type { RequestHandler } from 'express'\nimport { ReasonPhrases } from 'http-status-codes'\n\nconst message = ReasonPhrases.OK\n\nconst handler: RequestHandler<NoReqParams> = (_req, res) => {\n setRawResponseFormat(res)\n res.status(200).send({ message })\n}\n\nexport const getReadyz: RequestHandler<NoReqParams> = handler\n","import type { NoReqParams } from '@xylabs/express'\nimport { setRawResponseFormat } from '@xylabs/express'\nimport type { RequestHandler } from 'express'\nimport { ReasonPhrases } from 'http-status-codes'\n\nconst message = ReasonPhrases.OK\n\nconst handler: RequestHandler<NoReqParams> = (_req, res) => {\n setRawResponseFormat(res)\n res.status(200).send({ message })\n}\n\nexport const getStartupz: RequestHandler<NoReqParams> = handler\n","import type { Express } from 'express'\n\nimport { getLivez } from './livez/index.ts'\nimport { getReadyz } from './readyz/index.ts'\nimport { getStartupz } from './startupz/index.ts'\n\nexport const addProbeRoutes = (app: Express) => {\n app.get('/livez', getLivez)\n app.get('/readyz', getReadyz)\n app.get('/startupz', getStartupz)\n}\n","import type { RouteDefinition } from '@xylabs/express'\nimport { requestHandlerValidator } from '@xylabs/express'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { BridgeSettingsZod } from '@xyo-network/chain-orchestration'\nimport type { z } from 'zod'\n\nimport { getBridgeSettings } from '../../../../../services/evm/index.ts'\n\nexport const BridgeConfigResponseZod = BridgeSettingsZod\nexport type BridgeConfigResponse = z.infer<typeof BridgeConfigResponseZod>\n\nconst validateRequest = requestHandlerValidator({ response: BridgeConfigResponseZod })\n\nexport const makeBridgeConfigRoute = (config: BridgeConfig): RouteDefinition => {\n return {\n method: 'get',\n path: '/bridge/chains/:chainId/config',\n handlers: validateRequest(async (_, res) => {\n const {\n escrowAddress,\n feeFixed,\n feeRateBasisPoints,\n feesAddress,\n maxBridgeAmount,\n minBridgeAmount,\n remoteChainId,\n remoteTokenAddress,\n xl1ChainId,\n xl1TokenAddress,\n } = await getBridgeSettings(config)\n const sanitizedConfig = {\n escrowAddress,\n feeFixed,\n feeRateBasisPoints,\n feesAddress,\n maxBridgeAmount,\n minBridgeAmount,\n remoteChainId,\n remoteTokenAddress,\n xl1ChainId,\n xl1TokenAddress,\n }\n res.json(sanitizedConfig)\n }),\n }\n}\n","import type { RouteDefinition } from '@xylabs/express'\nimport { requestHandlerValidator } from '@xylabs/express'\nimport { isDefined, toHex } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { PayloadZodStrictOfSchema } from '@xyo-network/sdk-js'\nimport type {\n BridgeDestinationObservation, BridgeIntent, BridgeSourceObservation,\n} from '@xyo-network/xl1-sdk'\nimport {\n BridgeDestinationObservationFieldsZod, BridgeDestinationObservationSchema,\n BridgeIntentFieldsZod, BridgeIntentSchema,\n BridgeSourceObservationFieldsZod, BridgeSourceObservationSchema,\n} from '@xyo-network/xl1-sdk'\nimport { z } from 'zod'\n\nimport {\n getRemoteTokenAddress, getXl1ChainId, getXl1TokenAddress,\n} from '../../../../../services/evm/index.ts'\nimport { getJobIdForEthToXl1BridgeJob } from '../../../../../services/queue/flows/createEthToXl1BridgeJob/index.ts'\nimport { getEthToXl1Queues } from '../../../../../services/queue/index.ts'\nimport type { EthBridgeEventData } from '../../../../../services/queue/workers/util/index.ts'\nimport { getRemoteChainIdZod } from '../pathParams/index.ts'\n\nconst BridgeIntentResponseZod = PayloadZodStrictOfSchema(BridgeIntentSchema)\n .extend(BridgeIntentFieldsZod.shape)\n\nconst BridgeSourceResponseZod = PayloadZodStrictOfSchema(BridgeSourceObservationSchema)\n .extend(BridgeSourceObservationFieldsZod.shape)\n\nconst BridgeDestinationResponseZod = PayloadZodStrictOfSchema(BridgeDestinationObservationSchema)\n .extend(BridgeDestinationObservationFieldsZod.shape)\n\n// 0 / 1 / 2 / 3 elements representing the flow's progression — empty (parent enqueued but\n// Stage 1 hasn't run), intent only (state.canonical present, source observation hasn't\n// been derived yet — currently unreachable since we always have evmTxHash on canonical),\n// intent + source (Stage 1 success), or all three (Stage 2 fulfilled).\nexport const BridgeFromRemoteStatusResponseZod = z.union([\n z.tuple([]),\n z.tuple([BridgeIntentResponseZod]),\n z.tuple([BridgeIntentResponseZod, BridgeSourceResponseZod]),\n z.tuple([BridgeIntentResponseZod, BridgeSourceResponseZod, BridgeDestinationResponseZod]),\n])\nexport type BridgeFromRemoteStatusResponse = z.infer<typeof BridgeFromRemoteStatusResponseZod>\n\ninterface BuildPayloadsContext {\n canonical: EthBridgeEventData\n config: BridgeConfig\n nonce: string\n}\n\nfunction buildIntentAndSource(ctx: BuildPayloadsContext): [BridgeIntent, BridgeSourceObservation] {\n const {\n canonical, config, nonce,\n } = ctx\n const amountHex = toHex(canonical.amount)\n const xl1ChainId = getXl1ChainId(config)\n const xl1TokenAddress = getXl1TokenAddress(config)\n const evmChainId = config.remoteChainId\n const evmTokenAddress = getRemoteTokenAddress(config)\n\n const intentFields = BridgeIntentFieldsZod.parse({\n dest: xl1ChainId,\n destAddress: canonical.destAddress,\n destAmount: amountHex,\n destToken: xl1TokenAddress,\n nonce,\n src: evmChainId,\n srcAddress: canonical.srcAddress,\n srcAmount: amountHex,\n srcToken: evmTokenAddress,\n })\n const intent: BridgeIntent = { schema: BridgeIntentSchema, ...intentFields }\n\n const sourceFields = BridgeSourceObservationFieldsZod.parse({\n ...intentFields,\n srcConfirmation: canonical.evmTxHash,\n })\n const source: BridgeSourceObservation = { schema: BridgeSourceObservationSchema, ...sourceFields }\n\n return [intent, source]\n}\n\nexport const makeBridgeFromRemoteStatusRoute = (config: BridgeConfig): RouteDefinition => {\n const params = z.object({\n chainId: getRemoteChainIdZod(config),\n nonce: z.string().regex(/^\\d+$/, 'nonce must be a non-negative integer (the bridge contract\\'s id)'),\n })\n const validateRequest = requestHandlerValidator({ params, response: BridgeFromRemoteStatusResponseZod })\n\n return {\n method: 'get',\n path: '/bridge/chains/:chainId/bridgeFromRemote/status/:nonce',\n handlers: validateRequest(async (req, res) => {\n const bridgeId = BigInt(req.params.nonce)\n const contractAddress = config.remoteBridgeContractAddress\n const evmChainId = config.remoteChainId\n\n const identity = getJobIdForEthToXl1BridgeJob({\n bridgeId,\n contractAddress,\n evmChainId,\n })\n\n const services = req.app.services\n const state = await services.bridgeFulfillmentMap.get(identity)\n\n // Stage 1 or Stage 2 wrote a terminal failure record — surface as 504 (server-side\n // fulfillment failure, not a client error). The reason lives in state.failed and is\n // visible via BullBoard / the state map for ops.\n if (state?.failed) return res.sendStatus(504)\n\n // No state yet — either the parent hasn't been enqueued or Stage 1 hasn't run.\n // Differentiate via the parent queue: present ⇒ in-flight (empty tuple), absent ⇒ 404.\n if (!state?.canonical) {\n const queues = getEthToXl1Queues(config)\n const parentJob = await queues.ethToXl1BridgeParent.getJob(identity)\n if (!isDefined(parentJob)) return res.sendStatus(404)\n return res.json([])\n }\n\n const [intent, source] = buildIntentAndSource({\n canonical: state.canonical, config, nonce: identity,\n })\n if (!state.fulfilled) return res.json([intent, source])\n\n const destinationFields = BridgeDestinationObservationFieldsZod.parse({\n ...intent,\n destConfirmation: state.fulfilled.txHash,\n })\n const destination: BridgeDestinationObservation = { schema: BridgeDestinationObservationSchema, ...destinationFields }\n res.json([intent, source, destination])\n }),\n }\n}\n","import {\n asHex, HexZod, isUndefined,\n} from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport type { ChainId } from '@xyo-network/xl1-sdk'\n\nimport { getRemoteChainId } from '../../../../../services/evm/index.ts'\n\nexport const getRemoteChainIdZod = (config: BridgeConfig) => {\n const remoteChainId: ChainId = getRemoteChainId(config)\n return HexZod.superRefine((val, ctx) => {\n const chainId = asHex(val)\n if (isUndefined(chainId)) {\n ctx.addIssue('Not a valid chain id')\n return\n }\n if (chainId !== remoteChainId) {\n ctx.addIssue(`Only ${remoteChainId} is supported`)\n }\n })\n}\n","import type { RouteDefinition } from '@xylabs/express'\nimport { requestHandlerValidator } from '@xylabs/express'\nimport { isDefined } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport {\n PayloadBuilder, PayloadZodLooseOfSchema, PayloadZodStrictOfSchema,\n} from '@xyo-network/sdk-js'\nimport type {\n BridgeSourceObservation, BridgeSourceObservationFields, SignedHydratedTransaction,\n} from '@xyo-network/xl1-sdk'\nimport {\n BridgeIntentFieldsZod, BridgeIntentSchema, BridgeSourceObservationFieldsZod, BridgeSourceObservationSchema, SignedTransactionBoundWitnessZod, TransferZod,\n} from '@xyo-network/xl1-sdk'\nimport { z } from 'zod'\n\nimport { createXl1ToEthBridgeJob, getXl1ToEthBridgeJob } from '../../../../../services/queue/index.ts'\nimport {\n validateBridgeEstimateExact, validateBridgeTransaction, validateSufficientXL1SourceAddressBalance,\n} from '../../../../../services/validation/index.ts'\nimport { getRemoteChainIdZod } from '../pathParams/index.ts'\n\nexport const BridgeToRemoteBodyZod = z.tuple([\n SignedTransactionBoundWitnessZod,\n PayloadZodLooseOfSchema(BridgeIntentSchema).extend(BridgeIntentFieldsZod.shape),\n TransferZod,\n])\nexport type BridgeToRemoteBody = z.infer<typeof BridgeToRemoteBodyZod>\n\nexport const BridgeToRemoteResponseZod = PayloadZodStrictOfSchema(BridgeSourceObservationSchema).extend(BridgeSourceObservationFieldsZod.shape)\nexport type BridgeToRemoteResponse = z.infer<typeof BridgeToRemoteResponseZod>\n\nexport const makeBridgeToRemoteRoute = (config: BridgeConfig): RouteDefinition => {\n const params = z.object({ chainId: getRemoteChainIdZod(config) })\n\n const validateRequest = requestHandlerValidator({\n params, body: BridgeToRemoteBodyZod, response: BridgeToRemoteResponseZod,\n })\n return {\n method: 'post',\n path: '/bridge/chains/:chainId/bridgeToRemote',\n handlers: validateRequest(async (req, res) => {\n const [signedTxBw, bridgeIntent, transfer] = req.body\n const { flowProducer } = req.app\n const { gateway } = req.app.services\n\n // Validate request\n const transactionValid = await validateBridgeTransaction(signedTxBw, bridgeIntent, transfer, config)\n if (!transactionValid) {\n res.status(400).send()\n return\n }\n\n // Validate estimate\n const estimateValid = await validateBridgeEstimateExact(bridgeIntent, transfer, config)\n if (!estimateValid) {\n res.status(400).send()\n return\n }\n\n // Validate sufficient balance\n const sufficientBalance = await validateSufficientXL1SourceAddressBalance(bridgeIntent, gateway, config)\n if (!sufficientBalance) {\n res.status(400).send()\n return\n }\n\n // Create the signed hydrated transaction for the job\n const singedHydratedTransaction: SignedHydratedTransaction = [signedTxBw, [transfer]]\n\n // Check if a job already exists for this transaction\n const existingFlow = await getXl1ToEthBridgeJob(flowProducer, singedHydratedTransaction)\n if (isDefined(existingFlow)) {\n res.status(200).send()\n return\n }\n\n // Submit to job queue\n await createXl1ToEthBridgeJob(flowProducer, singedHydratedTransaction, [bridgeIntent])\n\n // Create BridgeObservation\n const srcConfirmation = await PayloadBuilder.hash(signedTxBw)\n const bridgeCommonFieldsZod = z.object({}).extend(BridgeSourceObservationFieldsZod.shape)\n const bridgeCommonFields = bridgeCommonFieldsZod.parse(bridgeIntent)\n const bridgeObservationFields: BridgeSourceObservationFields = { ...bridgeCommonFields, srcConfirmation }\n const bridgeObservation: BridgeSourceObservation = new PayloadBuilder<BridgeSourceObservation>(\n { schema: BridgeSourceObservationSchema },\n ).fields(bridgeObservationFields).build()\n\n // Return bridge observation to caller\n res.status(202).json(bridgeObservation)\n }),\n }\n}\n","import type { RouteDefinition } from '@xylabs/express'\nimport { requestHandlerValidator } from '@xylabs/express'\nimport {\n assertEx, hexToBigInt, toAddress,\n} from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { PayloadZodStrictOfSchema } from '@xyo-network/sdk-js'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\nimport {\n BridgeIntentFieldsZod, BridgeIntentSchema, buildUnsignedTransaction, toXL1BlockNumber, TransactionBoundWitnessZod, TransferZod,\n} from '@xyo-network/xl1-sdk'\nimport { z } from 'zod'\n\nimport { getBridgeSettings, getXl1ChainId } from '../../../../../services/evm/index.ts'\nimport { generateBridgeEstimate } from '../../../../../services/util/index.ts'\nimport { getRemoteChainIdZod } from '../pathParams/index.ts'\n\nexport const BridgeToRemoteEstimateBodyZod = BridgeIntentFieldsZod.pick({\n destAddress: true,\n srcAddress: true,\n srcAmount: true,\n})\nexport type BridgeToRemoteEstimateBody = z.infer<typeof BridgeToRemoteEstimateBodyZod>\n\nexport const BridgeToRemoteEstimateResponseZod = z.tuple([\n TransactionBoundWitnessZod,\n PayloadZodStrictOfSchema(BridgeIntentSchema).extend(BridgeIntentFieldsZod.shape),\n TransferZod,\n])\n\nexport type BridgeToRemoteEstimateResponse = z.infer<typeof BridgeToRemoteEstimateResponseZod>\n\nexport const makeBridgeToRemoteEstimateRoute = (config: BridgeConfig, gateway: XyoGatewayRunner): RouteDefinition => {\n const params = z.object({ chainId: getRemoteChainIdZod(config) })\n const validateRequest = requestHandlerValidator({\n params, body: BridgeToRemoteEstimateBodyZod, response: BridgeToRemoteEstimateResponseZod,\n })\n return {\n method: 'post',\n path: '/bridge/chains/:chainId/bridgeToRemote/estimate',\n handlers: validateRequest(async (req, res) => {\n const xl1ChainId = getXl1ChainId(config)\n const {\n srcAddress, srcAmount, destAddress,\n } = req.body\n\n const { maxBridgeAmount, minBridgeAmount } = await getBridgeSettings(config)\n if (hexToBigInt(srcAmount) < hexToBigInt(minBridgeAmount) || hexToBigInt(srcAmount) > hexToBigInt(maxBridgeAmount)) {\n res.status(400).send()\n return\n }\n\n const [bridgeIntent, transfer] = await generateBridgeEstimate(srcAddress, srcAmount, destAddress, config)\n const sender = toAddress(srcAddress)\n\n // Use viewer to get current block\n const viewer = assertEx(gateway.connection.viewer, () => new Error('Viewer not available on gateway connection'))\n const currentBlockNumber = await viewer.currentBlockNumber()\n // Calculate nbf/exp\n const nbf = toXL1BlockNumber(currentBlockNumber, true)\n const exp = toXL1BlockNumber(currentBlockNumber + 1000, true)\n // Build unsigned transaction representing the transfer that will be signed by srcAddress\n const [txBw] = await buildUnsignedTransaction(xl1ChainId, [transfer], [bridgeIntent], nbf, exp, sender)\n\n // Return the TX to the caller for signing\n res.json([txBw, bridgeIntent, transfer])\n }),\n }\n}\n","import type { RouteDefinition } from '@xylabs/express'\nimport { requestHandlerValidator } from '@xylabs/express'\nimport {\n assertEx, hexToBigInt, toAddress, toHex,\n} from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { PayloadZodStrictOfSchema } from '@xyo-network/sdk-js'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\nimport {\n BridgeIntentFieldsZod, BridgeIntentSchema, buildUnsignedTransaction, toXL1BlockNumber, TransactionBoundWitnessZod, TransferZod,\n} from '@xyo-network/xl1-sdk'\nimport { z } from 'zod'\n\nimport { getBridgeSettings } from '../../../../../services/evm/index.ts'\nimport { calculateMaxBridgeAmount, generateBridgeEstimate } from '../../../../../services/util/index.ts'\nimport { getRemoteChainIdZod } from '../pathParams/index.ts'\n\nexport const BridgeToRemoteMaxEstimateBodyZod = BridgeIntentFieldsZod.pick({\n destAddress: true,\n srcAddress: true,\n srcAmount: true,\n})\nexport type BridgeToRemoteMaxEstimateBody = z.infer<typeof BridgeToRemoteMaxEstimateBodyZod>\n\nexport const BridgeToRemoteMaxEstimateResponseZod = z.tuple([\n TransactionBoundWitnessZod,\n PayloadZodStrictOfSchema(BridgeIntentSchema).extend(BridgeIntentFieldsZod.shape),\n TransferZod,\n])\n\nexport type BridgeToRemoteMaxEstimateResponse = z.infer<typeof BridgeToRemoteMaxEstimateResponseZod>\n\nexport const makeBridgeToRemoteMaxEstimateRoute = (config: BridgeConfig, gateway: XyoGatewayRunner): RouteDefinition => {\n const params = z.object({ chainId: getRemoteChainIdZod(config) })\n const validateRequest = requestHandlerValidator({\n params, body: BridgeToRemoteMaxEstimateBodyZod, response: BridgeToRemoteMaxEstimateResponseZod,\n })\n return {\n method: 'post',\n path: '/bridge/chains/:chainId/bridgeToRemote/maxEstimate',\n handlers: validateRequest(async (req, res) => {\n const {\n feeFixed, feeRateBasisPoints, maxBridgeAmount: configMax, xl1ChainId,\n } = await getBridgeSettings(config)\n const {\n srcAddress, srcAmount: balance, destAddress,\n } = req.body\n\n const balanceMax = calculateMaxBridgeAmount(balance, { feeFixed, feeRateBasisPoints })\n const maxBridgeAmount = toHex(hexToBigInt(balanceMax) < hexToBigInt(configMax) ? balanceMax : configMax)\n\n const [bridgeIntent, transfer] = await generateBridgeEstimate(srcAddress, maxBridgeAmount, destAddress, config)\n const sender = toAddress(srcAddress)\n\n const viewer = assertEx(gateway.connection.viewer, () => new Error('Viewer not available on gateway connection'))\n const currentBlockNumber = await viewer.currentBlockNumber()\n const nbf = toXL1BlockNumber(currentBlockNumber, true)\n const exp = toXL1BlockNumber(currentBlockNumber + 1000, true)\n const [txBw] = await buildUnsignedTransaction(xl1ChainId, [transfer], [bridgeIntent], nbf, exp, sender)\n\n res.json([txBw, bridgeIntent, transfer])\n }),\n }\n}\n","import type { RouteDefinition } from '@xylabs/express'\nimport { requestHandlerValidator } from '@xylabs/express'\nimport { asHex, isDefined } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { PayloadBuilder, PayloadZodStrictOfSchema } from '@xyo-network/sdk-js'\nimport type { BridgeDestinationObservation, BridgeSourceObservation } from '@xyo-network/xl1-sdk'\nimport {\n asBridgeIntent, BridgeDestinationObservationFieldsZod, BridgeDestinationObservationSchema, BridgeIntentFieldsZod, BridgeIntentSchema,\n BridgeSourceObservationFieldsZod, BridgeSourceObservationSchema, isBridgeIntent,\n} from '@xyo-network/xl1-sdk'\nimport { z } from 'zod'\n\nimport { getStatusQueueJobs, getXl1ToEthQueues } from '../../../../../services/queue/index.ts'\nimport { getRemoteChainIdZod } from '../pathParams/index.ts'\n\nconst BridgeIntentResponseZod = PayloadZodStrictOfSchema(BridgeIntentSchema)\n .extend(BridgeIntentFieldsZod.shape)\n\nconst BridgeSourceResponseZod = PayloadZodStrictOfSchema(BridgeSourceObservationSchema)\n .extend(BridgeSourceObservationFieldsZod.shape)\n\nconst BridgeDestinationResponseZod = PayloadZodStrictOfSchema(BridgeDestinationObservationSchema)\n .extend(BridgeDestinationObservationFieldsZod.shape)\n\nexport const BridgeToRemoteStatusResponseZod = z.union([\n z.tuple([]),\n z.tuple([BridgeIntentResponseZod]),\n z.tuple([BridgeIntentResponseZod, BridgeSourceResponseZod]),\n z.tuple([BridgeIntentResponseZod, BridgeSourceResponseZod, BridgeDestinationResponseZod]),\n])\nexport type BridgeToRemoteStatusResponse = z.infer<typeof BridgeToRemoteStatusResponseZod>\n\nexport const makeBridgeToRemoteStatusRoute = (config: BridgeConfig): RouteDefinition => {\n const params = z.object({\n chainId: getRemoteChainIdZod(config),\n nonce: z.string().nonempty(),\n })\n\n const validateRequest = requestHandlerValidator({ params, response: BridgeToRemoteStatusResponseZod })\n\n return {\n method: 'get',\n path: '/bridge/chains/:chainId/bridgeToRemote/status/:nonce',\n handlers: validateRequest(async (req, res) => {\n const jobId = req.params.nonce\n const result: z.infer<typeof BridgeToRemoteStatusResponseZod> = [] as z.infer<typeof BridgeToRemoteStatusResponseZod>\n const queues = getXl1ToEthQueues(config)\n\n const statusQueueJobs = await getStatusQueueJobs(queues, jobId)\n\n // Check for the transaction hash in the parent job\n const { tx, offChainPayloads = [] } = statusQueueJobs.xl1ToEthBridgeParentJob?.data ?? {}\n\n // If the job does not exist return Not Found\n if (!tx) return res.sendStatus(404)\n\n // If the tx is not the right shape for bridging return Not Found\n const allPayloads = [...tx[1], ...offChainPayloads]\n const bridgeIntent = allPayloads.find(isBridgeIntent)\n if (!bridgeIntent) return res.sendStatus(404)\n\n // At this point we know we have a valid bridge intent, so we can start building the response\n result[0] = asBridgeIntent(PayloadBuilder.omitMeta(bridgeIntent))\n\n // Check the state of the XL1 monitor job to determine if we can include the source observation\n const { xl1TransactionMonitorJob } = statusQueueJobs\n const xl1MonitorState = xl1TransactionMonitorJob ? await xl1TransactionMonitorJob.getState() : undefined\n if (xl1MonitorState === 'completed') {\n const srcConfirmation = xl1TransactionMonitorJob?.returnvalue?.submissionHash\n if (isDefined(srcConfirmation)) {\n const schema = BridgeSourceObservationSchema\n const bridgeSourceObservationFields = BridgeSourceObservationFieldsZod.parse(bridgeIntent)\n const observation: BridgeSourceObservation = {\n schema, ...bridgeSourceObservationFields, srcConfirmation,\n }\n result[1] = observation\n }\n }\n\n // Check the state of the ETH monitor job to determine if we can include the destination observation\n const { ethTransactionMonitorJob } = statusQueueJobs\n const ethMonitorState = ethTransactionMonitorJob ? await ethTransactionMonitorJob.getState() : undefined\n if (ethMonitorState === 'completed') {\n const destConfirmation = asHex(ethTransactionMonitorJob?.returnvalue?.submissionHash)\n if (isDefined(destConfirmation)) {\n const schema = BridgeDestinationObservationSchema\n const bridgeDestinationObservationFields = BridgeDestinationObservationFieldsZod.parse(bridgeIntent)\n const observation: BridgeDestinationObservation = {\n schema, ...bridgeDestinationObservationFields, destConfirmation,\n }\n result[2] = observation\n }\n }\n\n res.json(result)\n }),\n }\n}\n","import type { RouteDefinition } from '@xylabs/express'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\n\nimport {\n makeBridgeConfigRoute, makeBridgeFromRemoteStatusRoute, makeBridgeToRemoteEstimateRoute, makeBridgeToRemoteMaxEstimateRoute, makeBridgeToRemoteRoute, makeBridgeToRemoteStatusRoute,\n} from './routes/index.ts'\n\nexport const getRouteDefinitions = (config: BridgeConfig, gateway: XyoGatewayRunner): RouteDefinition[] => {\n return [\n makeBridgeConfigRoute(config),\n makeBridgeToRemoteEstimateRoute(config, gateway),\n makeBridgeToRemoteMaxEstimateRoute(config, gateway),\n makeBridgeToRemoteRoute(config),\n makeBridgeToRemoteStatusRoute(config),\n makeBridgeFromRemoteStatusRoute(config),\n ]\n}\n","import type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\nimport type { Express } from 'express'\n\nimport { getRouteDefinitions } from './routeDefinitions/index.ts'\n\nexport const addBridgeRoutes = (app: Express, config: BridgeConfig, gateway: XyoGatewayRunner) => {\n const routeDefinitions = getRouteDefinitions(config, gateway)\n for (const definition of routeDefinitions) {\n app[definition.method](definition.path, definition.handlers)\n }\n}\n","import type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\nimport type { Express } from 'express'\n\nimport { addProbeRoutes } from './addProbeRoutes.ts'\nimport { addBridgeRoutes } from './bridge/index.ts'\n\nexport const addRoutes = (app: Express, config: BridgeConfig, gateway: XyoGatewayRunner) => {\n addProbeRoutes(app)\n addBridgeRoutes(app, config, gateway)\n}\n","import type { Hash } from '@xylabs/sdk-js'\nimport { assertEx } from '@xylabs/sdk-js'\nimport type { BridgeConfig, BridgeConfigContext } from '@xyo-network/chain-orchestration'\nimport { initEvmProvider, resolveWalletForActor } from '@xyo-network/chain-orchestration'\nimport { BridgeableToken__factory, LiquidityPoolBridge__factory } from '@xyo-network/typechain'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\nimport { getAddress, Wallet } from 'ethers'\n\nimport type { BridgeFulfillmentState } from './BridgeFulfillmentState.ts'\nimport type { EthTxState } from './EthTxState.ts'\nimport { getRemoteConfirmationDepth } from './evm/index.ts'\nimport { getIterableMap } from './getIterableMap.ts'\nimport type { IBridgeServiceCollection } from './IBridgeServiceCollection.ts'\nimport type { EvmBridgeCursor } from './queue/index.ts'\nimport type { Xl1TxState } from './Xl1TxState.ts'\n\n/**\n * Used for retrieving a service collection\n * @returns A service collection\n */\nexport const getServices = async (context: BridgeConfigContext, gateway: XyoGatewayRunner): Promise<IBridgeServiceCollection> => {\n const { config } = context\n\n const ethTxStateMap = await getIterableMap<Hash, EthTxState>(config, 'liquidity_bridge_xl1_to_eth_eth_tx_state')\n const xl1TxStateMap = await getIterableMap<Hash, Xl1TxState>(config, 'liquidity_bridge_xl1_to_eth_xl1_tx_state')\n const evmBridgeCursorMap = await getIterableMap<string, EvmBridgeCursor>(config, 'liquidity_bridge_eth_to_xl1_scanner_cursor')\n const bridgeFulfillmentMap = await getIterableMap<string, BridgeFulfillmentState>(config, 'liquidity_bridge_eth_to_xl1_fulfillment')\n const provider = await initEvmProvider(context)\n const {\n remoteBridgeContractAddress, remoteChainWalletPrivateKey, remoteTokenAddress, accountPath,\n } = config as BridgeConfig\n const account = await resolveWalletForActor(config.name, accountPath)\n const wallet = new Wallet(remoteChainWalletPrivateKey, provider)\n const bridgeableToken = BridgeableToken__factory.connect(getAddress(remoteTokenAddress), wallet)\n const bridge = LiquidityPoolBridge__factory.connect(getAddress(remoteBridgeContractAddress), wallet)\n // const approvalAmount = 18n * 10n ** 9n * 10n ** 18n // 18 billion tokens with 18 decimals\n // const contractApprovalTx = await bridgeableToken.connect(wallet).approve(bridge.getAddress(), approvalAmount)\n // await contractApprovalTx.wait(1)\n // Assert we are contract owner so we can call ownable methods\n const bridgeOwner = await bridge.owner()\n assertEx(bridgeOwner.toLowerCase() === wallet.address.toLowerCase(), () => 'Wallet is not the owner of the bridge contract')\n const remoteConfirmationDepth = getRemoteConfirmationDepth(config as BridgeConfig)\n return {\n account,\n bridge,\n bridgeableToken,\n bridgeFulfillmentMap,\n ethTxStateMap,\n evmBridgeCursorMap,\n gateway,\n provider,\n remoteConfirmationDepth,\n wallet,\n xl1TxStateMap,\n }\n}\n","import { BaseMongoSdk, type BaseMongoSdkPrivateConfig } from '@xylabs/mongo'\nimport { MongoMap } from '@xyo-network/chain-protocol-driver-mongodb'\nimport type { BaseConfig, IterableMap } from '@xyo-network/xl1-sdk'\nimport { hasMongoConfig, mapToMapType } from '@xyo-network/xl1-sdk'\nimport type { Document } from 'mongodb'\n\n/**\n * Gets an iterable map based on the storage instructions in the config\n * @param config The config containing storage instructions\n * @param collection The collection to use if using MongoDB for persistence\n * @returns The iterable map\n */\nexport const getIterableMap = async <K extends {} = string, V extends Document = Document>(\n config: BaseConfig,\n collection: string,\n): Promise<IterableMap<K, V>> => {\n const mongoConfig = config.storage?.mongo\n if (hasMongoConfig(mongoConfig)) {\n const {\n connectionString: dbConnectionString, database: dbName, domain: dbDomain, password: dbPassword, username: dbUserName,\n } = mongoConfig\n const payloadSdkConfig: BaseMongoSdkPrivateConfig = {\n dbConnectionString, dbDomain, dbName, dbPassword, dbUserName,\n }\n const sdkBalanceSummaryMap = new BaseMongoSdk<V>({ ...payloadSdkConfig, collection })\n const result = await MongoMap.create<MongoMap<K, V>>({\n sdk: sdkBalanceSummaryMap,\n getCache: { enabled: true, maxEntries: 5000 },\n })\n return result\n } else {\n return mapToMapType(new Map<K, V>())\n }\n}\n","import type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nimport type { IBridgeServiceCollection } from '../services/index.ts'\nimport {\n createWorkers, getConnection,\n getTelemetry,\n} from '../services/queue/index.ts'\n\nexport const addWorkers = (config: BridgeConfig, services: IBridgeServiceCollection) => {\n const connection = getConnection(config)\n const telemetry = getTelemetry()\n createWorkers(connection, telemetry, services)\n}\n","import type { Server } from 'node:http'\n\nimport type { BridgeConfigContext } from '@xyo-network/chain-orchestration'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\n\nimport type { IBridgeServiceCollection } from '../services/index.ts'\nimport { getServices } from '../services/index.ts'\nimport { addWorkers } from './addWorkers.ts'\nimport { getApp } from './app.ts'\n\nexport interface GetServerResult {\n server: Server\n services: IBridgeServiceCollection\n}\n\nconst hostname = '::'\n// const hostname = '0.0.0.0'\n\nexport const getServer = async (context: BridgeConfigContext, gateway: XyoGatewayRunner): Promise<GetServerResult> => {\n const { logger, config } = context\n const { port } = config\n const app = getApp(config, gateway)\n const services = await getServices(context, gateway)\n app.services = services\n addWorkers(config, services)\n const server = await new Promise<ReturnType<typeof app.listen>>((resolve, reject) => {\n const srv = app.listen(port, hostname, () => {\n logger?.log(`[Bridge] Server listening at http://${hostname}:${port}`)\n resolve(srv)\n })\n srv.once('error', reject)\n })\n server.setTimeout(20_000)\n return { server, services }\n}\n","import type { Gauge, Meter } from '@opentelemetry/api'\nimport type { AccountInstance } from '@xyo-network/sdk-js'\nimport type { BridgeableToken, LiquidityPoolBridge } from '@xyo-network/typechain'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\nimport type { Provider, Wallet } from 'ethers'\n\nexport interface BalanceMonitorConfig {\n account: AccountInstance\n bridge: LiquidityPoolBridge\n bridgeableToken: BridgeableToken\n gateway: XyoGatewayRunner\n intervalMs?: number\n meter: Meter\n provider: Provider\n wallet: Wallet\n}\n\nexport interface BalanceMonitorHandle {\n start: () => void\n stop: () => void\n}\n\nconst DEFAULT_INTERVAL_MS = 60_000\n\nconst WEI_PER_GWEI = 10n ** 9n\nconst TOKEN_DECIMALS = 10n ** 18n\n\nexport function createBalanceMonitor(config: BalanceMonitorConfig): BalanceMonitorHandle {\n const {\n account, bridge, bridgeableToken, gateway, meter, provider, wallet,\n intervalMs = DEFAULT_INTERVAL_MS,\n } = config\n\n let timer: ReturnType<typeof setInterval> | undefined\n\n const ethWalletGasBalance: Gauge = meter.createGauge(\n 'bridge_eth_wallet_gas_balance_gwei',\n { description: 'ETH balance of the bridge runner wallet (in gwei)', unit: 'gwei' },\n )\n\n const liquidityTokenBalance: Gauge = meter.createGauge(\n 'bridge_eth_liquidity_token_balance',\n { description: 'ERC-20 token balance of the liquidity source (in whole tokens)', unit: 'tokens' },\n )\n\n const liquidityTokenAllowance: Gauge = meter.createGauge(\n 'bridge_eth_liquidity_token_allowance',\n { description: 'ERC-20 token allowance from liquidity source to bridge contract (in whole tokens)', unit: 'tokens' },\n )\n\n // This is the XL1 reserve balance — the account that signs EVM->XL1 reserve transfers\n // (services.account, resolved by BRIDGE_NAME / BRIDGE_ACCOUNT_PATH). Watch this gauge\n // for reserve depletion; the scanner's pre-flight check (validateSufficientXl1ReserveBalance)\n // will start rejecting flows once it falls below the bridge amount.\n const xl1AccountBalance: Gauge = meter.createGauge(\n 'bridge_xl1_account_balance',\n { description: 'XL1 native balance of the bridge reserve account (in whole XL1)', unit: 'xl1' },\n )\n\n const walletAddress = wallet.address\n\n async function poll(): Promise<void> {\n // ETH wallet gas balance\n try {\n const balance = await provider.getBalance(walletAddress)\n ethWalletGasBalance.record(Number(balance / WEI_PER_GWEI), { address: walletAddress })\n } catch (err) {\n console.error('[BalanceMonitor] Failed to read ETH wallet gas balance:', err)\n }\n\n // Liquidity source token balance\n try {\n const liquiditySourceAddress = await bridge.liquiditySource()\n const balance = await bridgeableToken.balanceOf(liquiditySourceAddress)\n liquidityTokenBalance.record(Number(balance / TOKEN_DECIMALS), { address: liquiditySourceAddress })\n } catch (err) {\n console.error('[BalanceMonitor] Failed to read liquidity source token balance:', err)\n }\n\n // Liquidity source token allowance\n try {\n const liquiditySourceAddress = await bridge.liquiditySource()\n const bridgeAddress = await bridge.getAddress()\n const allowance = await bridgeableToken.allowance(liquiditySourceAddress, bridgeAddress)\n liquidityTokenAllowance.record(Number(allowance / TOKEN_DECIMALS), { address: liquiditySourceAddress })\n } catch (err) {\n console.error('[BalanceMonitor] Failed to read liquidity source token allowance:', err)\n }\n\n // XL1 account balance\n try {\n const viewer = gateway.connection.viewer\n if (viewer) {\n const balance = await viewer.account.balance.accountBalance(account.address)\n xl1AccountBalance.record(Number(balance / TOKEN_DECIMALS), { address: account.address.toString() })\n }\n } catch (err) {\n console.error('[BalanceMonitor] Failed to read XL1 account balance:', err)\n }\n }\n\n return {\n start() {\n void poll()\n timer = setInterval(() => void poll(), intervalMs)\n },\n stop() {\n if (timer) {\n clearInterval(timer)\n timer = undefined\n }\n },\n }\n}\n","import type { Gauge, Meter } from '@opentelemetry/api'\nimport type { Queue } from 'bullmq'\n\nexport interface QueueMetricsConfig {\n intervalMs?: number\n meter: Meter\n /**\n * Map of queue handles keyed by a human-friendly name (used as the `queue_name` label\n * on emitted gauges). Caller is responsible for deduping shared queues — passing two\n * different handles for the same Redis queue under different names will emit duplicate\n * metrics. BridgeActor merges getXl1ToEthQueues + getEthToXl1Queues here, where the\n * shared XL1 queues collide on identical key names so spread-merge dedupes naturally.\n */\n queues: Record<string, Queue>\n}\n\nexport interface QueueMetricsHandle {\n start: () => void\n stop: () => void\n}\n\nconst DEFAULT_INTERVAL_MS = 30_000\n\nexport function createQueueMetrics(config: QueueMetricsConfig): QueueMetricsHandle {\n const {\n meter, queues,\n intervalMs = DEFAULT_INTERVAL_MS,\n } = config\n\n let timer: ReturnType<typeof setInterval> | undefined\n\n const waitingGauge: Gauge = meter.createGauge(\n 'bridge_queue_waiting',\n { description: 'Number of waiting jobs in the bridge queue' },\n )\n\n const activeGauge: Gauge = meter.createGauge(\n 'bridge_queue_active',\n { description: 'Number of active jobs in the bridge queue' },\n )\n\n const completedGauge: Gauge = meter.createGauge(\n 'bridge_queue_completed',\n { description: 'Number of completed jobs in the bridge queue' },\n )\n\n const failedGauge: Gauge = meter.createGauge(\n 'bridge_queue_failed',\n { description: 'Number of failed jobs in the bridge queue' },\n )\n\n const delayedGauge: Gauge = meter.createGauge(\n 'bridge_queue_delayed',\n { description: 'Number of delayed jobs in the bridge queue' },\n )\n\n async function poll(): Promise<void> {\n for (const [name, queue] of Object.entries(queues)) {\n try {\n const counts = await queue.getJobCounts('waiting', 'active', 'completed', 'failed', 'delayed')\n const attrs = { queue_name: name }\n waitingGauge.record(counts.waiting ?? 0, attrs)\n activeGauge.record(counts.active ?? 0, attrs)\n completedGauge.record(counts.completed ?? 0, attrs)\n failedGauge.record(counts.failed ?? 0, attrs)\n delayedGauge.record(counts.delayed ?? 0, attrs)\n } catch (err) {\n console.error(`[QueueMetrics] Failed to read job counts for queue ${name}:`, err)\n }\n }\n }\n\n return {\n start() {\n void poll()\n timer = setInterval(() => void poll(), intervalMs)\n },\n stop() {\n if (timer) {\n clearInterval(timer)\n timer = undefined\n }\n },\n }\n}\n","import type { GetLocatorsFromConfig } from '@xyo-network/chain-orchestration'\nimport { BridgeConfigZod } from '@xyo-network/chain-orchestration'\nimport type { Config } from '@xyo-network/xl1-sdk'\nimport type { CommandModule } from 'yargs'\n\nimport { runBridge } from './run.ts'\n\nexport function bridgeCommand(getConfiguration: () => Config, getLocatorsFromConfig: GetLocatorsFromConfig): CommandModule {\n return {\n command: 'bridge',\n deprecated: 'Use \"start bridge\" instead',\n describe: 'Run a XL1 Bridge Node',\n handler: async () => {\n const configuration = getConfiguration()\n const { locators, orchestrator } = await getLocatorsFromConfig(['bridge'], configuration)\n await runBridge(BridgeConfigZod.parse(locators['bridge'].context.config), orchestrator, locators['bridge'])\n },\n }\n}\n","import { exists } from '@xylabs/sdk-js'\nimport type { BridgeConfig, OrchestratorInstance } from '@xyo-network/chain-orchestration'\nimport { initActorWallet } from '@xyo-network/chain-orchestration'\nimport type { ProviderFactoryLocatorInstance } from '@xyo-network/xl1-sdk'\n\nimport { BridgeActor } from './BridgeActor.ts'\n\nexport const getBridgeActor = async (\n config: BridgeConfig,\n locator: ProviderFactoryLocatorInstance,\n) => {\n const account = await initActorWallet({\n config, logger: locator.context.logger, singletons: {}, caches: {},\n })\n return await BridgeActor.create({\n account, config, locator,\n })\n}\n\nexport const runBridge = async (\n config: BridgeConfig,\n orchestrator: OrchestratorInstance,\n locator: ProviderFactoryLocatorInstance,\n) => {\n const bridge = await getBridgeActor(config, locator)\n const actors = [bridge].filter(exists)\n\n for (const actor of actors) {\n await orchestrator.registerActor(actor)\n }\n await orchestrator.start()\n}\n"],"mappings":";;;;AAEA,SAASA,iBAAiB;AAI1B,SAASC,SAASC,6BAA6B;AAE/C,SAASC,yBAAyBC,wBAAwB;;;ACR1D,SAASC,sBAAsB;AAE/B,SAASC,wBAAwB;AAGjC,OAAOC,aAAa;;;ACLpB,SAASC,iBAAiB;AAE1B,SAASC,aAAa;AAEtB,IAAIC;AAEJ,IAAMC,uBAAuB;AAEtB,IAAMC,gBAAgB,wBAACC,WAAAA;AAC5B,MAAIC,UAAUJ,UAAAA,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QACZQ;MACF,CAAA;AACA,WAAKnC,cAAc0B,MAAK;IAC1B;EACF;EAEQlB,aAAa;AACnB,SAAKN,QAAQqC,MAAAA;AACb,SAAKrC,SAASU;EAChB;AACF;;;;;;AsFxHA,SAAS4B,uBAAuB;;;ACDhC,SAASC,cAAc;AAEvB,SAASC,uBAAuB;AAKzB,IAAMC,iBAAiB,8BAC5BC,QACAC,YAAAA;AAEA,QAAMC,UAAU,MAAMC,gBAAgB;IACpCH;IAAQI,QAAQH,QAAQI,QAAQD;IAAQE,YAAY,CAAC;IAAGC,QAAQ,CAAC;EACnE,CAAA;AACA,SAAO,MAAMC,YAAYC,OAAO;IAC9BP;IAASF;IAAQC;EACnB,CAAA;AACF,GAV8B;AAYvB,IAAMS,YAAY,8BACvBV,QACAW,cACAV,YAAAA;AAEA,QAAMW,SAAS,MAAMb,eAAeC,QAAQC,OAAAA;AAC5C,QAAMY,SAAS;IAACD;IAAQE,OAAOC,MAAAA;AAE/B,aAAWC,SAASH,QAAQ;AAC1B,UAAMF,aAAaM,cAAcD,KAAAA;EACnC;AACA,QAAML,aAAaO,MAAK;AAC1B,GAZyB;;;ADZlB,SAASC,cAAcC,kBAAgCC,uBAA4C;AACxG,SAAO;IACLC,SAAS;IACTC,YAAY;IACZC,UAAU;IACVC,SAAS,mCAAA;AACP,YAAMC,gBAAgBN,iBAAAA;AACtB,YAAM,EAAEO,UAAUC,aAAY,IAAK,MAAMP,sBAAsB;QAAC;SAAWK,aAAAA;AAC3E,YAAMG,UAAUC,gBAAgBC,MAAMJ,SAAS,QAAA,EAAUK,QAAQC,MAAM,GAAGL,cAAcD,SAAS,QAAA,CAAS;IAC5G,GAJS;EAKX;AACF;AAXgBR;","names":["creatable","ActorV3","asBridgeConfigContext","XyoGatewayRunnerMoniker","XyoViewerMoniker","standardErrors","sharedMiddleware","express","isDefined","Redis","connection","maxRetriesPerRequest","getConnection","config","isDefined","redisHost","host","redisPort","port","Redis","isDefined","FlowProducer","prefix","flowProducer","getFlowProducer","connection","telemetry","isDefined","FlowProducer","prefix","assertEx","isNull","UnrecoverableError","Worker","toHex","PayloadBuilder","BridgeIntentSchema","BridgeSourceObservationSchema","buildTransaction","createTransferPayload","buildEthToXl1ReserveTx","options","amount","bridgeAccount","bridgeId","destAddress","evmChainId","evmContractAddress","evmSrcAddress","evmTokenAddress","evmTxHash","exp","nbf","xl1ChainId","xl1TokenAddress","amountHex","toHex","nonce","toLowerCase","toString","transfer","createTransferPayload","address","intent","PayloadBuilder","schema","BridgeIntentSchema","fields","dest","destAmount","destToken","src","srcAddress","srcAmount","srcToken","build","sourceObservation","BridgeSourceObservationSchema","srcConfirmation","buildTransaction","resolveEvmBlockTagAtDepth","provider","depth","head","getBlockNumber","Math","max","assertEx","hexToBigInt","toEthAddress","PayloadBuilder","isBridgeIntent","submitEthTransaction","tx","offChainPayloads","bridge","wallet","xl1Transaction","assertEx","allPayloads","bridgeIntent","find","isBridgeIntent","srcAddress","toEthAddress","destAddress","amount","hexToBigInt","destAmount","nonce","PayloadBuilder","hash","bridgeTx","connect","bridgeFromRemote","receipt","wait","submitXl1Transaction","preparedTx","offChain","gateway","result","addTransactionToChain","asHex","toAddress","ZeroAddress","verifyEthBridgeEvent","id","bridge","provider","confirmationDepth","blockTag","resolveEvmBlockTagAtDepth","data","bridgesToRemote","srcAddress","ZeroAddress","filter","filters","BridgedToRemote","events","queryFilter","event","undefined","amount","destAddress","toAddress","destToken","evmTxHash","asHex","transactionHash","name","queueName","createWorker","connection","telemetry","services","svc","assertEx","bridge","bridgeFulfillmentMap","provider","remoteConfirmationDepth","worker","Worker","job","bridgeId","identity","data","id","BigInt","existing","get","canonical","log","state","previousAttempts","failed","undefined","verifyEthBridgeEvent","isNull","at","Date","now","reason","set","UnrecoverableError","srcAddress","destAddress","amount","evmTxHash","prefix","on","err","console","error","message","EthEventVerification","Worker","name","queueName","createWorker","connection","telemetry","worker","Worker","job","log","prefix","on","err","console","error","id","message","EthToXl1BridgeParent","assertEx","PayloadBuilder","Worker","name","queueName","createWorker","connection","telemetry","services","provider","assertEx","stateMap","ethTxStateMap","worker","Worker","job","tx","data","hash","PayloadBuilder","state","get","submissionHash","receipt","getTransactionReceipt","log","blockNumber","blockHash","confirmationHash","set","prefix","on","err","console","error","id","message","EthTransactionMonitor","assertEx","hexToBigInt","PayloadBuilder","isBridgeIntent","Worker","getAddress","hexToBigInt","isUndefined","PayloadBuilder","asHex","asChainId","value","chainId","asHex","asAddress","asToken","value","token","asAddress","asAddress","assertEx","tryGetBridgeEscrowAddress","config","address","asAddress","escrowAddress","asAddress","assertEx","tryGetBridgeFeesAddress","config","address","asAddress","feesAddress","getFeeStructure","config","feeFixed","feeRateBasisPoints","getMaxBridgeAmount","config","maxBridgeAmount","getMinBridgeAmount","config","minBridgeAmount","assertEx","getRemoteChainId","config","remoteChainId","assertEx","asChainId","assertEx","getRemoteTokenAddress","config","token","asToken","remoteTokenAddress","assertEx","isDefined","resolveWalletForActor","accountServiceSingleton","getBridgeWalletAccount","config","accountPath","undefined","account","resolveWalletForActor","name","getTransferAddresses","config","escrowAddress","tryGetBridgeEscrowAddress","getBridgeWalletAccount","address","feesAddress","tryGetBridgeFeesAddress","assertEx","isDefined","getXl1ChainId","config","xl1ChainId","isDefined","assertEx","asChainId","chain","id","isDefined","getXl1TokenAddress","config","token","asToken","xl1TokenAddress","isDefined","getXl1ChainId","getBridgeSettings","config","feeFixed","feeRateBasisPoints","getFeeStructure","feesAddress","escrowAddress","getTransferAddresses","maxBridgeAmount","getMaxBridgeAmount","minBridgeAmount","getMinBridgeAmount","remoteChainId","getRemoteChainId","remoteTokenAddress","getRemoteTokenAddress","xl1TokenAddress","getXl1TokenAddress","xl1ChainId","getXl1ChainId","isDefined","HARDHAT_CHAIN_ID","ETHEREUM_MAINNET_CHAIN_ID","FALLBACK_CONFIRMATION_DEPTH","DEFAULT_CONFIRMATION_DEPTH_BY_CHAIN_ID","getRemoteConfirmationDepth","config","isDefined","remoteConfirmationDepth","chainId","getRemoteChainId","toLowerCase","getScannerIntervalMs","config","scannerIntervalMs","hexToBigInt","toHex","calculateBridgeFees","srcAmount","feeStructure","feeFixed","feeRateBasisPoints","srcAmountBigInt","hexToBigInt","feeVariableBigInt","BigInt","feeVariable","toHex","hexToBigInt","toHex","calculateMaxBridgeAmount","balance","feeStructure","feeFixed","feeRateBasisPoints","balanceBigInt","hexToBigInt","feeFixedBigInt","toHex","maxAmount","BigInt","hexToBigInt","createTransferPayload","createBridgeTransfer","sender","srcAmount","escrowAddress","feesAddress","context","feeFixed","feeVariable","escrowAmount","hexToBigInt","feesAmount","transfers","transfer","createTransferPayload","toAddress","PayloadBuilder","BridgeIntentSchema","v4","generateBridgeEstimate","srcAddress","srcAmount","destAddress","config","nonceOverride","escrowAddress","feeFixed","feeRateBasisPoints","feesAddress","remoteChainId","remoteTokenAddress","xl1ChainId","xl1TokenAddress","getBridgeSettings","sender","toAddress","fees","calculateBridgeFees","nonce","v4","bridgeIntentFields","src","srcToken","dest","destAmount","destToken","bridgeIntent","PayloadBuilder","schema","BridgeIntentSchema","fields","build","transfer","createBridgeTransfer","validateBridgeEstimateExact","intent","transfer","config","srcAddress","srcAmount","destAddress","hexToBigInt","getMinBridgeAmount","getMaxBridgeAmount","calculatedIntent","calculatedTransfer","generateBridgeEstimate","isUndefined","nonce","expectedIntentNonce","expectedIntentStatic","actualIntentNonce","actualIntentStatic","PayloadBuilder","dataHash","epoch","expectedTransferEpoch","expectedTransferStatic","actualTransferEpoch","actualTransferStatic","asAddress","addressesContains","BoundWitnessValidator","payloadHashesContainsAll","payloadSchemasContainsAll","PayloadBuilder","BridgeIntentSchema","TransferSchema","validateBridgeTransaction","signedTxBw","intent","transfer","config","srcAddress","chainId","getXl1ChainId","chain","payload_hashes","length","payloadSchemasContainsAll","BridgeIntentSchema","TransferSchema","hashes","PayloadBuilder","payloadHashesContainsAll","errors","BoundWitnessValidator","validate","sender","asAddress","addressesContains","assertEx","hexToBigInt","isBridgeIntent","validateSufficientLiquiditySourceAllowance","tx","offChainPayloads","bridgeableToken","bridge","logger","allPayloads","bridgeIntent","assertEx","find","isBridgeIntent","amount","hexToBigInt","destAmount","liquiditySourceAddress","liquiditySource","bridgeAddress","getAddress","remainingAllowance","allowance","log","toString","assertEx","hexToBigInt","isBridgeIntent","validateSufficientLiquiditySourceBalance","tx","offChainPayloads","bridgeableToken","bridge","logger","allPayloads","bridgeIntent","assertEx","find","isBridgeIntent","amount","hexToBigInt","destAmount","liquiditySourceAddress","liquiditySource","balance","balanceOf","log","toString","assertEx","DEFAULT_GAS_BUFFER_BPS","validateSufficientRunnerEthBalanceForGas","preparedTx","wallet","logger","bufferBps","provider","assertEx","feeData","getFeeData","perGas","maxFeePerGas","gasPrice","log","transactionRequest","from","getAddress","estGas","estimateGas","txValue","value","baseRequired","required","balance","getBalance","toString","assertEx","validateSufficientXl1ReserveBalance","amount","bridgeAccount","gateway","logger","viewer","assertEx","connection","balance","account","accountBalance","address","log","toString","asAddress","assertEx","hexToBigInt","validateSufficientXL1SourceAddressBalance","bridgeIntent","gateway","config","logger","viewer","assertEx","connection","srcAddress","srcAmount","destAddress","srcAddressBranded","asAddress","_","calculatedTransfer","generateBridgeEstimate","totalAmount","Object","values","transfers","reduce","acc","transfer","hexToBigInt","accountBalance","account","balance","log","toString","name","queueName","createWorker","connection","telemetry","services","bridge","assertEx","bridgeableToken","stateMap","ethTxStateMap","wallet","worker","Worker","job","tx","offChainPayloads","data","hash","PayloadBuilder","log","validateSufficientLiquiditySourceAllowance","Error","validateSufficientLiquiditySourceBalance","allPayloads","bridgeIntent","find","isBridgeIntent","amount","hexToBigInt","destAmount","srcAddress","getAddress","destAddress","nonce","preparedTx","getFunction","populateTransaction","validateSufficientRunnerEthBalanceForGas","set","prefix","on","err","console","error","id","message","EthTransactionPreparation","assertEx","isDefined","PayloadBuilder","Worker","name","queueName","createWorker","connection","telemetry","services","bridge","assertEx","wallet","stateMap","ethTxStateMap","worker","Worker","job","tx","offChainPayloads","data","hash","PayloadBuilder","state","get","submissionHash","existingSubmissionHash","isDefined","log","submitEthTransaction","concurrency","prefix","on","err","console","error","id","message","EthTransactionSubmission","assertEx","isDefined","PayloadBuilder","Worker","name","queueName","createWorker","connection","telemetry","services","stateMap","assertEx","ethTxStateMap","worker","Worker","job","tx","data","hash","PayloadBuilder","state","get","submissionHash","existingSubmissionHash","isDefined","log","childrenValues","getChildrenValues","jobKey","prefix","EthTransactionSubmission","childValues","resolvedSubmissionHash","set","on","err","console","error","id","message","EthTransactionSubmissionStorage","assertEx","delay","isDefined","isNull","PayloadBuilder","asXL1BlockNumber","Worker","name","queueName","EXP_BLOCKS_AHEAD","POLL_INTERVAL_MS","CONCURRENCY","tryResumeCurrentAttempt","ctx","fulfillmentMap","identity","job","state","viewer","attempt","assertEx","currentAttempt","found","transaction","byHash","txHash","isDefined","isNull","fulfilled","undefined","set","log","head","currentBlockNumber","exp","previousAttempts","push","buildAndSubmitFreshAttempt","account","bridgeId","contractAddress","evmChainId","gateway","xl1ChainId","xl1TokenAddress","canonical","sufficient","validateSufficientXl1ReserveBalance","amount","bridgeAccount","msg","toString","Error","nbf","asXL1BlockNumber","tx","buildEthToXl1ReserveTx","destAddress","evmContractAddress","evmSrcAddress","srcAddress","evmTokenAddress","destToken","evmTxHash","PayloadBuilder","hash","submittedAt","Date","now","submitXl1Transaction","length","pollUntilIncludedOrExpired","delay","createWorker","connection","telemetry","services","svc","bridgeFulfillmentMap","worker","Worker","data","initialState","get","failed","BigInt","concurrency","prefix","on","err","attemptsAllowed","opts","attempts","Infinity","attemptsMade","at","reason","message","console","error","Xl1ReserveTxFulfillment","Worker","name","queueName","createWorker","connection","telemetry","worker","Worker","job","log","prefix","on","err","console","error","id","message","Xl1ToEthBridgeParent","assertEx","isDefined","isNull","PayloadBuilder","UnrecoverableError","Worker","name","queueName","createWorker","connection","telemetry","services","gateway","assertEx","stateMap","xl1TxStateMap","viewer","worker","Worker","job","tx","data","hash","PayloadBuilder","state","get","submissionHash","log","foundTx","transaction","byHash","isDefined","isNull","currentBlockNumber","exp","UnrecoverableError","Error","prefix","on","err","console","error","id","message","Xl1TransactionMonitor","assertEx","PayloadBuilder","Worker","name","queueName","createWorker","connection","telemetry","services","stateMap","assertEx","xl1TxStateMap","worker","Worker","job","tx","offChainPayloads","data","hash","PayloadBuilder","log","preparedTx","set","prefix","on","err","console","error","id","message","Xl1TransactionPreparation","assertEx","isDefined","PayloadBuilder","Worker","name","queueName","createWorker","connection","telemetry","services","gateway","assertEx","stateMap","xl1TxStateMap","worker","Worker","job","tx","data","hash","PayloadBuilder","state","get","preparedTx","offChainPayloads","submissionHash","existingSubmissionHash","isDefined","log","txToSubmit","submitXl1Transaction","prefix","on","err","console","error","id","message","Xl1TransactionSubmission","assertEx","isDefined","PayloadBuilder","Worker","name","queueName","createWorker","connection","telemetry","services","stateMap","assertEx","xl1TxStateMap","worker","Worker","job","tx","data","hash","PayloadBuilder","state","get","submissionHash","existingSubmissionHash","isDefined","log","childrenValues","getChildrenValues","jobKey","prefix","Xl1TransactionSubmission","childValues","resolvedSubmissionHash","set","on","err","console","error","id","message","Xl1TransactionSubmissionStorage","createWorkers","connection","telemetry","services","EthEventVerification","createWorker","EthToXl1BridgeParent","EthTransactionMonitor","EthTransactionPreparation","EthTransactionSubmission","EthTransactionSubmissionStorage","Xl1ReserveTxFulfillment","Xl1ToEthBridgeParent","Xl1TransactionMonitor","Xl1TransactionPreparation","Xl1TransactionSubmission","Xl1TransactionSubmissionStorage","getJobIdForEthToXl1BridgeJob","context","evmChainId","toLowerCase","contractAddress","bridgeId","toString","STAGE_2_RETRY","attempts","backoff","delay","type","STAGE_1_RETRY","createEthToXl1BridgeJob","flowProducer","context","jobId","getJobIdForEthToXl1BridgeJob","identity","stageJobData","bridgeId","toString","contractAddress","evmChainId","xl1ChainId","xl1TokenAddress","add","name","EthToXl1BridgeParent","queueName","data","opts","children","Xl1ReserveTxFulfillment","EthEventVerification","PayloadBuilder","getJobIdForXl1ToEthBridgeJob","tx","jobId","PayloadBuilder","hash","createXl1ToEthBridgeJob","flowProducer","tx","offChainPayloads","jobId","getJobIdForXl1ToEthBridgeJob","flow","add","name","Xl1ToEthBridgeParent","queueName","data","opts","children","EthTransactionMonitor","attempts","backoff","type","delay","EthTransactionSubmissionStorage","EthTransactionSubmission","EthTransactionPreparation","Xl1TransactionMonitor","Xl1TransactionSubmissionStorage","Xl1TransactionSubmission","Xl1TransactionPreparation","getXl1ToEthBridgeJob","flowProducer","tx","id","getJobIdForXl1ToEthBridgeJob","flow","getFlow","queueName","Xl1ToEthBridgeParent","Queue","ethToXl1Queues","getEthToXl1Queues","config","connection","getConnection","ethEventVerification","Queue","EthEventVerification","queueName","prefix","ethToXl1BridgeParent","EthToXl1BridgeParent","xl1ReserveTxFulfillment","Xl1ReserveTxFulfillment","getStatusQueueJobs","queues","jobId","ethTransactionMonitorJob","ethTransactionPreparationJob","ethTransactionSubmissionJob","xl1ToEthBridgeParentJob","xl1TransactionMonitorJob","xl1TransactionPreparationJob","xl1TransactionSubmissionJob","xl1TransactionSubmissionStorageJob","Promise","all","ethTransactionMonitor","getJob","ethTransactionPreparation","ethTransactionSubmission","xl1ToEthBridgeParent","xl1TransactionMonitor","xl1TransactionPreparation","xl1TransactionSubmission","xl1TransactionSubmissionStorage","Queue","xl1ToEthQueues","getXl1ToEthQueues","config","connection","getConnection","ethTransactionMonitor","Queue","EthTransactionMonitor","queueName","prefix","ethTransactionPreparation","EthTransactionPreparation","ethTransactionSubmission","EthTransactionSubmission","xl1ToEthBridgeParent","Xl1ToEthBridgeParent","xl1TransactionMonitor","Xl1TransactionMonitor","xl1TransactionPreparation","Xl1TransactionPreparation","xl1TransactionSubmission","Xl1TransactionSubmission","xl1TransactionSubmissionStorage","Xl1TransactionSubmissionStorage","createEnqueueEthToXl1Bridge","options","evmChainId","evmContractAddress","flowProducer","xl1ChainId","xl1TokenAddress","bridgeId","jobLog","createEthToXl1BridgeJob","contractAddress","isUndefined","getEvmBridgeCursorKey","chainId","contractAddress","toLowerCase","createEvmBridgeScanner","options","bridge","bridgeAddress","chainId","confirmationDepth","cursors","enqueue","provider","cursorKey","getEvmBridgeCursorKey","scan","jobLog","blockTag","resolveEvmBlockTagAtDepth","confirmedHigh","nextBridgeToId","cursor","get","lastProcessedId","isUndefined","BigInt","enqueued","id","set","toString","Queue","Worker","QUEUE_NAME","REPEATABLE_JOB_NAME","REPEATABLE_JOB_ID","createEvmBridgeScannerRunner","options","connection","intervalMs","scanner","telemetry","logger","console","queue","worker","start","Queue","prefix","Worker","job","log","result","scan","jobLog","msg","enqueued","confirmedHigh","toString","lastProcessedId","on","err","error","id","message","add","jobId","repeat","every","stop","close","undefined","buildEvmBridgeScannerRunner","options","config","connection","flowProducer","logger","services","telemetry","evmChainId","getRemoteChainId","evmContractAddress","remoteBridgeContractAddress","xl1ChainId","getXl1ChainId","xl1TokenAddress","getXl1TokenAddress","intervalMs","getScannerIntervalMs","enqueue","createEnqueueEthToXl1Bridge","scanner","createEvmBridgeScanner","bridge","bridgeAddress","chainId","confirmationDepth","remoteConfirmationDepth","cursors","evmBridgeCursorMap","provider","createEvmBridgeScannerRunner","isDefined","BullMQOtel","telemetry","options","enableMetrics","getTelemetry","isDefined","BullMQOtel","addFlowProducer","app","config","connection","getConnection","telemetry","getTelemetry","flowProducer","getFlowProducer","registerInstrumentations","ExpressInstrumentation","HttpInstrumentation","addInstrumentation","instrumentations","HttpInstrumentation","ExpressInstrumentation","registerInstrumentations","setRawResponseFormat","ReasonPhrases","message","ReasonPhrases","OK","handler","_req","res","setRawResponseFormat","status","send","getLivez","setRawResponseFormat","ReasonPhrases","message","ReasonPhrases","OK","handler","_req","res","setRawResponseFormat","status","send","getReadyz","setRawResponseFormat","ReasonPhrases","message","ReasonPhrases","OK","handler","_req","res","setRawResponseFormat","status","send","getStartupz","addProbeRoutes","app","get","getLivez","getReadyz","getStartupz","requestHandlerValidator","BridgeSettingsZod","BridgeConfigResponseZod","BridgeSettingsZod","validateRequest","requestHandlerValidator","response","makeBridgeConfigRoute","config","method","path","handlers","_","res","escrowAddress","feeFixed","feeRateBasisPoints","feesAddress","maxBridgeAmount","minBridgeAmount","remoteChainId","remoteTokenAddress","xl1ChainId","xl1TokenAddress","getBridgeSettings","sanitizedConfig","json","requestHandlerValidator","isDefined","toHex","PayloadZodStrictOfSchema","BridgeDestinationObservationFieldsZod","BridgeDestinationObservationSchema","BridgeIntentFieldsZod","BridgeIntentSchema","BridgeSourceObservationFieldsZod","BridgeSourceObservationSchema","z","asHex","HexZod","isUndefined","getRemoteChainIdZod","config","remoteChainId","getRemoteChainId","HexZod","superRefine","val","ctx","chainId","asHex","isUndefined","addIssue","BridgeIntentResponseZod","PayloadZodStrictOfSchema","BridgeIntentSchema","extend","BridgeIntentFieldsZod","shape","BridgeSourceResponseZod","BridgeSourceObservationSchema","BridgeSourceObservationFieldsZod","BridgeDestinationResponseZod","BridgeDestinationObservationSchema","BridgeDestinationObservationFieldsZod","BridgeFromRemoteStatusResponseZod","z","union","tuple","buildIntentAndSource","ctx","canonical","config","nonce","amountHex","toHex","amount","xl1ChainId","getXl1ChainId","xl1TokenAddress","getXl1TokenAddress","evmChainId","remoteChainId","evmTokenAddress","getRemoteTokenAddress","intentFields","parse","dest","destAddress","destAmount","destToken","src","srcAddress","srcAmount","srcToken","intent","schema","sourceFields","srcConfirmation","evmTxHash","source","makeBridgeFromRemoteStatusRoute","params","object","chainId","getRemoteChainIdZod","string","regex","validateRequest","requestHandlerValidator","response","method","path","handlers","req","res","bridgeId","BigInt","contractAddress","remoteBridgeContractAddress","identity","getJobIdForEthToXl1BridgeJob","services","app","state","bridgeFulfillmentMap","get","failed","sendStatus","queues","getEthToXl1Queues","parentJob","ethToXl1BridgeParent","getJob","isDefined","json","fulfilled","destinationFields","destConfirmation","txHash","destination","requestHandlerValidator","isDefined","PayloadBuilder","PayloadZodLooseOfSchema","PayloadZodStrictOfSchema","BridgeIntentFieldsZod","BridgeIntentSchema","BridgeSourceObservationFieldsZod","BridgeSourceObservationSchema","SignedTransactionBoundWitnessZod","TransferZod","z","BridgeToRemoteBodyZod","z","tuple","SignedTransactionBoundWitnessZod","PayloadZodLooseOfSchema","BridgeIntentSchema","extend","BridgeIntentFieldsZod","shape","TransferZod","BridgeToRemoteResponseZod","PayloadZodStrictOfSchema","BridgeSourceObservationSchema","BridgeSourceObservationFieldsZod","makeBridgeToRemoteRoute","config","params","object","chainId","getRemoteChainIdZod","validateRequest","requestHandlerValidator","body","response","method","path","handlers","req","res","signedTxBw","bridgeIntent","transfer","flowProducer","app","gateway","services","transactionValid","validateBridgeTransaction","status","send","estimateValid","validateBridgeEstimateExact","sufficientBalance","validateSufficientXL1SourceAddressBalance","singedHydratedTransaction","existingFlow","getXl1ToEthBridgeJob","isDefined","createXl1ToEthBridgeJob","srcConfirmation","PayloadBuilder","hash","bridgeCommonFieldsZod","bridgeCommonFields","parse","bridgeObservationFields","bridgeObservation","schema","fields","build","json","requestHandlerValidator","assertEx","hexToBigInt","toAddress","PayloadZodStrictOfSchema","BridgeIntentFieldsZod","BridgeIntentSchema","buildUnsignedTransaction","toXL1BlockNumber","TransactionBoundWitnessZod","TransferZod","z","BridgeToRemoteEstimateBodyZod","BridgeIntentFieldsZod","pick","destAddress","srcAddress","srcAmount","BridgeToRemoteEstimateResponseZod","z","tuple","TransactionBoundWitnessZod","PayloadZodStrictOfSchema","BridgeIntentSchema","extend","shape","TransferZod","makeBridgeToRemoteEstimateRoute","config","gateway","params","object","chainId","getRemoteChainIdZod","validateRequest","requestHandlerValidator","body","response","method","path","handlers","req","res","xl1ChainId","getXl1ChainId","maxBridgeAmount","minBridgeAmount","getBridgeSettings","hexToBigInt","status","send","bridgeIntent","transfer","generateBridgeEstimate","sender","toAddress","viewer","assertEx","connection","Error","currentBlockNumber","nbf","toXL1BlockNumber","exp","txBw","buildUnsignedTransaction","json","requestHandlerValidator","assertEx","hexToBigInt","toAddress","toHex","PayloadZodStrictOfSchema","BridgeIntentFieldsZod","BridgeIntentSchema","buildUnsignedTransaction","toXL1BlockNumber","TransactionBoundWitnessZod","TransferZod","z","BridgeToRemoteMaxEstimateBodyZod","BridgeIntentFieldsZod","pick","destAddress","srcAddress","srcAmount","BridgeToRemoteMaxEstimateResponseZod","z","tuple","TransactionBoundWitnessZod","PayloadZodStrictOfSchema","BridgeIntentSchema","extend","shape","TransferZod","makeBridgeToRemoteMaxEstimateRoute","config","gateway","params","object","chainId","getRemoteChainIdZod","validateRequest","requestHandlerValidator","body","response","method","path","handlers","req","res","feeFixed","feeRateBasisPoints","maxBridgeAmount","configMax","xl1ChainId","getBridgeSettings","balance","balanceMax","calculateMaxBridgeAmount","toHex","hexToBigInt","bridgeIntent","transfer","generateBridgeEstimate","sender","toAddress","viewer","assertEx","connection","Error","currentBlockNumber","nbf","toXL1BlockNumber","exp","txBw","buildUnsignedTransaction","json","requestHandlerValidator","asHex","isDefined","PayloadBuilder","PayloadZodStrictOfSchema","asBridgeIntent","BridgeDestinationObservationFieldsZod","BridgeDestinationObservationSchema","BridgeIntentFieldsZod","BridgeIntentSchema","BridgeSourceObservationFieldsZod","BridgeSourceObservationSchema","isBridgeIntent","z","BridgeIntentResponseZod","PayloadZodStrictOfSchema","BridgeIntentSchema","extend","BridgeIntentFieldsZod","shape","BridgeSourceResponseZod","BridgeSourceObservationSchema","BridgeSourceObservationFieldsZod","BridgeDestinationResponseZod","BridgeDestinationObservationSchema","BridgeDestinationObservationFieldsZod","BridgeToRemoteStatusResponseZod","z","union","tuple","makeBridgeToRemoteStatusRoute","config","params","object","chainId","getRemoteChainIdZod","nonce","string","nonempty","validateRequest","requestHandlerValidator","response","method","path","handlers","req","res","jobId","result","queues","getXl1ToEthQueues","statusQueueJobs","getStatusQueueJobs","tx","offChainPayloads","xl1ToEthBridgeParentJob","data","sendStatus","allPayloads","bridgeIntent","find","isBridgeIntent","asBridgeIntent","PayloadBuilder","omitMeta","xl1TransactionMonitorJob","xl1MonitorState","getState","undefined","srcConfirmation","returnvalue","submissionHash","isDefined","schema","bridgeSourceObservationFields","parse","observation","ethTransactionMonitorJob","ethMonitorState","destConfirmation","asHex","bridgeDestinationObservationFields","json","getRouteDefinitions","config","gateway","makeBridgeConfigRoute","makeBridgeToRemoteEstimateRoute","makeBridgeToRemoteMaxEstimateRoute","makeBridgeToRemoteRoute","makeBridgeToRemoteStatusRoute","makeBridgeFromRemoteStatusRoute","addBridgeRoutes","app","config","gateway","routeDefinitions","getRouteDefinitions","definition","method","path","handlers","addRoutes","app","config","gateway","addProbeRoutes","addBridgeRoutes","getApp","config","gateway","addInstrumentation","app","express","sharedMiddleware","addFlowProducer","addRoutes","use","standardErrors","assertEx","initEvmProvider","resolveWalletForActor","BridgeableToken__factory","LiquidityPoolBridge__factory","getAddress","Wallet","BaseMongoSdk","MongoMap","hasMongoConfig","mapToMapType","getIterableMap","config","collection","mongoConfig","storage","mongo","hasMongoConfig","connectionString","dbConnectionString","database","dbName","domain","dbDomain","password","dbPassword","username","dbUserName","payloadSdkConfig","sdkBalanceSummaryMap","BaseMongoSdk","result","MongoMap","create","sdk","getCache","enabled","maxEntries","mapToMapType","Map","getServices","context","gateway","config","ethTxStateMap","getIterableMap","xl1TxStateMap","evmBridgeCursorMap","bridgeFulfillmentMap","provider","initEvmProvider","remoteBridgeContractAddress","remoteChainWalletPrivateKey","remoteTokenAddress","accountPath","account","resolveWalletForActor","name","wallet","Wallet","bridgeableToken","BridgeableToken__factory","connect","getAddress","bridge","LiquidityPoolBridge__factory","bridgeOwner","owner","assertEx","toLowerCase","address","remoteConfirmationDepth","getRemoteConfirmationDepth","addWorkers","config","services","connection","getConnection","telemetry","getTelemetry","createWorkers","hostname","getServer","context","gateway","logger","config","port","app","getApp","services","getServices","addWorkers","server","Promise","resolve","reject","srv","listen","log","once","setTimeout","DEFAULT_INTERVAL_MS","WEI_PER_GWEI","TOKEN_DECIMALS","createBalanceMonitor","config","account","bridge","bridgeableToken","gateway","meter","provider","wallet","intervalMs","timer","ethWalletGasBalance","createGauge","description","unit","liquidityTokenBalance","liquidityTokenAllowance","xl1AccountBalance","walletAddress","address","poll","balance","getBalance","record","Number","err","console","error","liquiditySourceAddress","liquiditySource","balanceOf","bridgeAddress","getAddress","allowance","viewer","connection","accountBalance","toString","start","setInterval","stop","clearInterval","undefined","DEFAULT_INTERVAL_MS","createQueueMetrics","config","meter","queues","intervalMs","timer","waitingGauge","createGauge","description","activeGauge","completedGauge","failedGauge","delayedGauge","poll","name","queue","Object","entries","counts","getJobCounts","attrs","queue_name","record","waiting","active","completed","failed","delayed","err","console","error","start","setInterval","stop","clearInterval","undefined","BridgeActor","ActorV3","needs","required","XyoGatewayRunnerMoniker","XyoViewerMoniker","_gatewayRunner","_balanceMonitor","_queueMetrics","_scannerRunner","server","gatewayRunner","createHandler","locator","getInstance","startHandler","stopServer","startServer","stopHandler","stop","undefined","context","asBridgeConfigContext","config","services","getServer","connection","getConnection","telemetry","getTelemetry","flowProducer","getFlowProducer","buildEvmBridgeScannerRunner","logger","start","meter","createBalanceMonitor","account","bridge","bridgeableToken","gateway","provider","wallet","queues","getXl1ToEthQueues","getEthToXl1Queues","createQueueMetrics","close","BridgeConfigZod","exists","initActorWallet","getBridgeActor","config","locator","account","initActorWallet","logger","context","singletons","caches","BridgeActor","create","runBridge","orchestrator","bridge","actors","filter","exists","actor","registerActor","start","bridgeCommand","getConfiguration","getLocatorsFromConfig","command","deprecated","describe","handler","configuration","locators","orchestrator","runBridge","BridgeConfigZod","parse","context","config"]}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/BridgeActor.ts", "../../src/server/app.ts", "../../src/services/queue/connection.ts", "../../src/services/queue/flowProducer.ts", "../../src/services/queue/prefix.ts", "../../src/services/queue/workers/EthEventVerification.ts", "../../src/services/queue/workers/util/buildEthToXl1BridgePayloads.ts", "../../src/services/queue/workers/util/buildEthToXl1ReserveTx.ts", "../../src/services/queue/workers/util/resolveEvmBlockTagAtDepth.ts", "../../src/services/queue/workers/util/submitEthTransaction.ts", "../../src/services/queue/workers/util/submitXl1Transaction.ts", "../../src/services/queue/workers/util/verifyEthBridgeEvent.ts", "../../src/services/queue/workers/EthToXl1BridgeParent.ts", "../../src/services/queue/workers/EthTransactionMonitor.ts", "../../src/services/queue/workers/EthTransactionPreparation.ts", "../../src/services/validation/validateAmountMeetsMinBridgeAmount.ts", "../../src/services/validation/validateBridgeEstimateExact.ts", "../../src/services/evm/asChainId.ts", "../../src/services/evm/asToken.ts", "../../src/services/evm/getBridgeEscrowAddress.ts", "../../src/services/evm/getBridgeFeesAddress.ts", "../../src/services/evm/getFeeStructure.ts", "../../src/services/evm/getMaxBridgeAmount.ts", "../../src/services/evm/getMinBridgeAmount.ts", "../../src/services/evm/getRemoteChainId.ts", "../../src/services/evm/getRemoteTokenAddress.ts", "../../src/services/evm/getBridgeWalletAccount.ts", "../../src/services/evm/getTransferAddresses.ts", "../../src/services/evm/getXl1ChainId.ts", "../../src/services/evm/getXl1TokenAddress.ts", "../../src/services/evm/getBridgeSettings.ts", "../../src/services/evm/getRemoteConfirmationDepth.ts", "../../src/services/evm/getScannerIntervalMs.ts", "../../src/services/util/calculateBridgeFees.ts", "../../src/services/util/calculateMaxBridgeAmount.ts", "../../src/services/util/createBridgeTransfer.ts", "../../src/services/util/generateBridgeEstimate.ts", "../../src/services/validation/validateBridgeTransaction.ts", "../../src/services/validation/validateSufficientLiquiditySourceAllowance.ts", "../../src/services/validation/validateSufficientLiquiditySourceBalance.ts", "../../src/services/validation/validateSufficientRunnerEthBalanceForGas.ts", "../../src/services/validation/validateSufficientXl1ReserveBalance.ts", "../../src/services/validation/validateSufficientXL1SourceAddressBalance.ts", "../../src/services/queue/workers/EthTransactionSubmission.ts", "../../src/services/queue/workers/EthTransactionSubmissionStorage.ts", "../../src/services/queue/workers/Xl1ReserveTxFulfillment.ts", "../../src/services/queue/workers/Xl1ToEthBridgeParent.ts", "../../src/services/queue/workers/Xl1TransactionMonitor.ts", "../../src/services/queue/workers/Xl1TransactionPreparation.ts", "../../src/services/queue/workers/Xl1TransactionSubmission.ts", "../../src/services/queue/workers/Xl1TransactionSubmissionStorage.ts", "../../src/services/queue/workers/createWorkers.ts", "../../src/services/queue/flows/createEthToXl1BridgeJob/getJobIdForEthToXl1BridgeJob.ts", "../../src/services/queue/flows/createEthToXl1BridgeJob/createEthToXl1BridgeJob.ts", "../../src/services/queue/flows/createXl1ToEthBridgeJob/getJobIdForXl1ToEthBridgeJob.ts", "../../src/services/queue/flows/createXl1ToEthBridgeJob/createXl1ToEthBridgeJob.ts", "../../src/services/queue/flows/createXl1ToEthBridgeJob/getXl1ToEthBridgeJob.ts", "../../src/services/queue/getEthToXl1Queues.ts", "../../src/services/queue/getXl1ToEthQueueJobs.ts", "../../src/services/queue/getXl1ToEthQueues.ts", "../../src/services/queue/scanner/createEnqueueEthToXl1Bridge.ts", "../../src/services/queue/scanner/EvmBridgeScanner.ts", "../../src/services/queue/scanner/EvmBridgeCursor.ts", "../../src/services/queue/scanner/EvmBridgeScannerRunner.ts", "../../src/services/queue/scanner/buildEvmBridgeScannerRunner.ts", "../../src/services/queue/telemetry.ts", "../../src/server/addFlowProducer.ts", "../../src/server/instrumentation.ts", "../../src/server/routes/livez/get.ts", "../../src/server/routes/readyz/get.ts", "../../src/server/routes/startupz/get.ts", "../../src/server/routes/addProbeRoutes.ts", "../../src/server/routes/bridge/routeDefinitions/routes/bridgeConfig.ts", "../../src/server/routes/bridge/routeDefinitions/routes/bridgeFromRemoteEstimate.ts", "../../src/server/routes/bridge/routeDefinitions/pathParams/ChainIdPathParam.ts", "../../src/server/routes/bridge/routeDefinitions/routes/bridgeFromRemoteStatus.ts", "../../src/server/routes/bridge/routeDefinitions/routes/bridgeToRemote.ts", "../../src/server/routes/bridge/routeDefinitions/routes/bridgeToRemoteEstimate.ts", "../../src/server/routes/bridge/routeDefinitions/routes/bridgeToRemoteMaxEstimate.ts", "../../src/server/routes/bridge/routeDefinitions/routes/bridgeToRemoteStatus.ts", "../../src/server/routes/bridge/routeDefinitions/getRouteDefinitions.ts", "../../src/server/routes/bridge/addBridgeRoutes.ts", "../../src/server/routes/addRoutes.ts", "../../src/services/getServices.ts", "../../src/services/getIterableMap.ts", "../../src/server/addWorkers.ts", "../../src/server/server.ts", "../../src/telemetry/createBalanceMonitor.ts", "../../src/telemetry/createQueueMetrics.ts", "../../src/command.ts", "../../src/run.ts"],
4
+ "sourcesContent": ["import type { Server } from 'node:http'\n\nimport { creatable } from '@xylabs/sdk-js'\nimport type {\n ActorCapabilityNeeds, ActorParamsV3, BridgeConfig,\n} from '@xyo-network/chain-orchestration'\nimport { ActorV3, asBridgeConfigContext } from '@xyo-network/chain-orchestration'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\nimport { XyoGatewayRunnerMoniker, XyoViewerMoniker } from '@xyo-network/xl1-sdk'\n\nimport { getServer } from './server/index.ts'\nimport {\n buildEvmBridgeScannerRunner,\n type EvmBridgeScannerRunnerHandle,\n getConnection,\n getEthToXl1Queues,\n getFlowProducer,\n getTelemetry,\n getXl1ToEthQueues,\n} from './services/queue/index.ts'\nimport type { BalanceMonitorHandle, QueueMetricsHandle } from './telemetry/index.ts'\nimport { createBalanceMonitor, createQueueMetrics } from './telemetry/index.ts'\n\nexport type BridgeActorParams = ActorParamsV3<{\n config: BridgeConfig\n}>\n\n@creatable()\nexport class BridgeActor extends ActorV3<BridgeActorParams> {\n static readonly needs: ActorCapabilityNeeds = {\n required: [\n XyoGatewayRunnerMoniker,\n XyoViewerMoniker,\n ],\n }\n\n protected _gatewayRunner!: XyoGatewayRunner\n private _balanceMonitor?: BalanceMonitorHandle\n private _queueMetrics?: QueueMetricsHandle\n private _scannerRunner?: EvmBridgeScannerRunnerHandle\n private server?: Server\n\n protected get gatewayRunner() {\n return this._gatewayRunner\n }\n\n override async createHandler() {\n await super.createHandler()\n this._gatewayRunner = await this.locator.getInstance(XyoGatewayRunnerMoniker)\n }\n\n override async startHandler() {\n await super.startHandler()\n this.stopServer()\n await this.startServer()\n }\n\n override async stopHandler() {\n await super.stopHandler()\n // Stop the scanner first so no new flows enqueue while we're tearing down.\n await this._scannerRunner?.stop()\n this._scannerRunner = undefined\n this._balanceMonitor?.stop()\n this._queueMetrics?.stop()\n this._balanceMonitor = undefined\n this._queueMetrics = undefined\n this.stopServer()\n }\n\n private async startServer() {\n const context = asBridgeConfigContext(this.context, true)\n const config = context.config as BridgeConfig\n const { server, services } = await getServer(context, this._gatewayRunner)\n this.server = server\n\n // Start the EVM->XL1 scanner runner. Reuses the same Redis connection +\n // BullMQ telemetry the workers were registered against in addWorkers.\n const connection = getConnection(config)\n const telemetry = getTelemetry()\n const flowProducer = getFlowProducer(connection, telemetry)\n this._scannerRunner = buildEvmBridgeScannerRunner({\n config,\n connection,\n flowProducer,\n logger: this.logger,\n services,\n telemetry,\n })\n await this._scannerRunner.start()\n\n if (this.meter) {\n this._balanceMonitor = createBalanceMonitor({\n account: services.account,\n bridge: services.bridge,\n bridgeableToken: services.bridgeableToken,\n gateway: services.gateway,\n meter: this.meter,\n provider: services.provider,\n wallet: services.wallet,\n })\n this._balanceMonitor.start()\n\n // Merge both directions' queue handles. Shared queue keys (xl1Transaction*) collide\n // on the same property name so spread-merge dedupes naturally \u2014 the EVM->XL1 set\n // adds the new ethEventVerification + ethToXl1BridgeParent without doubling up.\n const queues = {\n ...getXl1ToEthQueues(config),\n ...getEthToXl1Queues(config),\n }\n this._queueMetrics = createQueueMetrics({\n meter: this.meter,\n queues,\n })\n this._queueMetrics.start()\n }\n }\n\n private stopServer() {\n this.server?.close()\n this.server = undefined\n }\n}\n", "import { standardErrors } from '@xylabs/express'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { sharedMiddleware } from '@xyo-network/chain-orchestration'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\nimport type { Express } from 'express'\nimport express from 'express'\n\nimport { addFlowProducer } from './addFlowProducer.ts'\nimport { addInstrumentation } from './instrumentation.ts'\nimport { addRoutes } from './routes/index.ts'\n\nexport const getApp = (config: BridgeConfig, gateway: XyoGatewayRunner): Express => {\n addInstrumentation()\n const app = express()\n sharedMiddleware(app)\n addFlowProducer(app, config)\n addRoutes(app, config, gateway)\n app.use(standardErrors)\n return app\n}\n", "import { isDefined } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { Redis } from 'ioredis'\n\nlet connection: Redis | undefined\n\nconst maxRetriesPerRequest = null\n\nexport const getConnection = (config: BridgeConfig) => {\n if (isDefined(connection)) return connection\n const { redisHost: host, redisPort: port } = config\n connection = new Redis({\n host, port, maxRetriesPerRequest,\n })\n return connection\n}\n", "import { isDefined } from '@xylabs/sdk-js'\nimport { FlowProducer } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport { prefix } from './prefix.ts'\n\nlet flowProducer: FlowProducer | undefined\n\nexport const getFlowProducer = (connection: Redis, telemetry?: BullMQOtel) => {\n if (isDefined(flowProducer)) return flowProducer\n flowProducer = new FlowProducer({\n connection, telemetry, prefix,\n })\n return flowProducer\n}\n", "export const prefix = 'xl1-bridge'\n", "import { assertEx, isNull } from '@xylabs/sdk-js'\nimport type { Job } from 'bullmq'\nimport { UnrecoverableError, Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport type { IBridgeServiceCollection } from '../../index.ts'\nimport { prefix } from '../prefix.ts'\nimport { verifyEthBridgeEvent } from './util/index.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\n\nexport interface EthEventVerificationJobData {\n /** BigInt as a decimal string \u2014 the contract-assigned bridgeToRemote id. */\n bridgeId: string\n /** Bridge identity, used as the bridgeFulfillmentMap key. */\n identity: string\n}\n\n/** Stage 1 returns void. Stage 2 reads canonical fields from bridgeFulfillmentMap. */\nexport type EthEventVerificationJob = Job<EthEventVerificationJobData, void>\n\nconst name = 'Verify ETH Bridge Event at Depth'\nconst queueName = 'eth-event-verify'\n\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel, services?: IBridgeServiceCollection) => {\n const svc = assertEx(services, () => 'services not provided')\n const {\n bridge, bridgeFulfillmentMap, provider, remoteConfirmationDepth,\n } = svc\n\n const worker = new Worker(\n queueName,\n async (job: EthEventVerificationJob) => {\n const { bridgeId, identity } = job.data\n const id = BigInt(bridgeId)\n\n const existing = await bridgeFulfillmentMap.get(identity)\n\n // Idempotent: if a previous Stage 1 already populated canonical, skip the contract\n // read. Stage 1 normally runs once per flow but can re-run on flow-level retry.\n if (existing?.canonical) {\n await job.log(`[${identity}] canonical already set; verification skipped`)\n return\n }\n\n // If this is a manual retry of a previously-failed flow, clear the stale failed\n // marker. We're trying again \u2014 if conditions still don't allow, we'll re-mark below.\n const state = existing ?? { identity, previousAttempts: [] }\n if (state.failed) state.failed = undefined\n\n await job.log(`[${identity}] verifying BridgedToRemote(${id}) at depth ${remoteConfirmationDepth}`)\n const data = await verifyEthBridgeEvent(id, bridge, provider, remoteConfirmationDepth)\n\n if (isNull(data)) {\n state.failed = {\n at: Date.now(),\n reason: 'non-canonical at confirmation depth \u2014 orphaned by reorg or never reached canonical state',\n }\n await bridgeFulfillmentMap.set(identity, state)\n await job.log(`[${identity}] non-canonical at depth \u2014 marked failed`)\n throw new UnrecoverableError(`[${identity}] bridgesToRemote slot empty at confirmation depth ${remoteConfirmationDepth}`)\n }\n\n state.canonical = data\n await bridgeFulfillmentMap.set(identity, state)\n\n await job.log(\n `[${identity}] verified: src=${data.srcAddress} dest=${data.destAddress} `\n + `amount=${data.amount} evmTxHash=${data.evmTxHash}`,\n )\n },\n {\n connection, telemetry, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const EthEventVerification: WorkerDescription = {\n createWorker, name, queueName,\n}\n", "import type { Address, Hex } from '@xylabs/sdk-js'\nimport { assertEx, toHex } from '@xylabs/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type {\n BridgeIntent, ChainId, Transfer,\n} from '@xyo-network/xl1-sdk'\nimport { BridgeIntentSchema, createTransferPayload } from '@xyo-network/xl1-sdk'\n\nexport interface BuildEthToXl1BridgePayloadsOptions {\n /** Gross EVM deposit, in atto. */\n amount: bigint\n /** XL1 address that signs the Transfer (the bridge wallet for Stage 2; the bridge wallet\n * is also the projected `from` for the inbound estimate route). */\n bridgeAccountAddress: Address\n /** Contract-assigned bridge id for Stage 2; projected `nextBridgeToId + 1` for the\n * estimate route. */\n bridgeId: bigint\n destAddress: Address\n evmChainId: Hex\n evmContractAddress: Address\n evmSrcAddress: Address\n evmTokenAddress: Hex\n feesAddress: Address\n feesAmount: bigint\n xl1ChainId: ChainId\n xl1TokenAddress: Hex\n}\n\nexport interface EthToXl1BridgePayloads {\n intent: BridgeIntent\n transfer: Transfer\n}\n\n/**\n * Builds the Transfer + BridgeIntent pair that defines an EVM\u2192XL1 reserve transfer at the\n * payload level \u2014 without committing to whether the transaction will be signed (Stage 2\n * fulfillment) or returned as a projection (`/bridgeFromRemote/estimate`). Both code paths\n * route through here so the fee split, intent semantics, and nonce format stay in lockstep.\n *\n * Field semantics in the intent: `srcAmount = amount` (gross EVM deposit) and\n * `destAmount = amount - feesAmount` (net XL1 credit). The fee is directly derivable as\n * `srcAmount - destAmount` \u2014 mirrors the outbound semantic where `destAmount` is what hits\n * destAddress.\n *\n * Transfer outputs collapse to a single entry when `feesAmount === 0n` or when\n * `destAddress === feesAddress` (mirrors `createBridgeTransfer.ts:23-27`).\n *\n * The caller is responsible for ensuring `amount >= feesAmount` (typically by enforcing\n * `minBridgeAmount` upstream). An assertEx guards against negative destination amounts.\n */\nexport function buildEthToXl1BridgePayloads(options: BuildEthToXl1BridgePayloadsOptions): EthToXl1BridgePayloads {\n const {\n amount,\n bridgeAccountAddress,\n bridgeId,\n destAddress,\n evmChainId,\n evmContractAddress,\n evmSrcAddress,\n evmTokenAddress,\n feesAddress,\n feesAmount,\n xl1ChainId,\n xl1TokenAddress,\n } = options\n\n assertEx(amount >= feesAmount, () => `buildEthToXl1BridgePayloads: amount (${amount}) < feesAmount (${feesAmount})`)\n\n const destAmount = amount - feesAmount\n const srcAmountHex = toHex(amount)\n const destAmountHex = toHex(destAmount)\n const nonce = `evm-${evmChainId.toLowerCase()}-${evmContractAddress.toLowerCase()}-${bridgeId.toString()}`\n\n const transfers: Record<Address, bigint>\n = feesAmount === 0n || destAddress === feesAddress\n ? { [destAddress]: amount }\n : { [destAddress]: destAmount, [feesAddress]: feesAmount }\n const transfer = createTransferPayload(bridgeAccountAddress, transfers)\n\n const intent = new PayloadBuilder<BridgeIntent>({ schema: BridgeIntentSchema })\n .fields({\n dest: xl1ChainId,\n destAddress,\n destAmount: destAmountHex,\n destToken: xl1TokenAddress,\n nonce,\n src: evmChainId,\n srcAddress: evmSrcAddress,\n srcAmount: srcAmountHex,\n srcToken: evmTokenAddress,\n })\n .build()\n\n return { intent, transfer }\n}\n", "import type { Address, Hex } from '@xylabs/sdk-js'\nimport { toHex } from '@xylabs/sdk-js'\nimport type { AccountInstance } from '@xyo-network/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type {\n BridgeSourceObservation, ChainId, SignedHydratedTransaction, XL1BlockNumber,\n} from '@xyo-network/xl1-sdk'\nimport { BridgeSourceObservationSchema, buildTransaction } from '@xyo-network/xl1-sdk'\n\nimport { buildEthToXl1BridgePayloads } from './buildEthToXl1BridgePayloads.ts'\n\nexport interface BuildEthToXl1ReserveTxOptions {\n /** Gross deposit on the EVM side (from `bridgesToRemote[id].amount`). The user's destination\n * credit is `amount - feesAmount`; the fees address receives `feesAmount`. */\n amount: bigint\n bridgeAccount: AccountInstance\n /** Contract-assigned bridge id from `bridgesToRemote(bridgeId)` storage. */\n bridgeId: bigint\n destAddress: Address\n evmChainId: Hex\n evmContractAddress: Address\n evmSrcAddress: Address\n evmTokenAddress: Hex\n /** Tx hash of the EVM transaction that emitted BridgedToRemote(bridgeId). */\n evmTxHash: Hex\n exp: XL1BlockNumber\n /** XL1 address that receives the bridge fee. Pass the same value as `destAddress` to\n * collapse to a single-output Transfer (the user effectively pays themselves). */\n feesAddress: Address\n /** Total fee, in atto, to be credited to `feesAddress`. Caller is responsible for ensuring\n * `amount >= feesAmount` (typically by enforcing `amount >= minBridgeAmount` upstream).\n * Computed as `hexToBigInt(feeFixed) + hexToBigInt(feeVariable)`. */\n feesAmount: bigint\n nbf: XL1BlockNumber\n xl1ChainId: ChainId\n xl1TokenAddress: Hex\n}\n\n/**\n * Builds a signed XL1 transaction that settles an EVM\u2192XL1 inbound bridge. The Transfer\n * splits the gross `amount` between `destAddress` (net = amount - feesAmount) and\n * `feesAddress`, mirroring the XL1\u2192EVM outbound model where `createBridgeTransfer` splits\n * the user's source amount between escrow and fees. `BridgeIntent` + `BridgeSourceObservation`\n * attach the cross-chain provenance off-chain.\n *\n * The Transfer payload is what actually moves balance on XL1 (on-chain). The intent +\n * source observation are off-chain provenance: they record what cross-chain operation this\n * transfer represents and which EVM tx emitted the source-side `BridgedToRemote` event.\n *\n * Field semantics in the intent/observation: `srcAmount = amount` (gross EVM deposit) and\n * `destAmount = amount - feesAmount` (net XL1 credit). This makes the fee directly derivable\n * from the intent (`srcAmount - destAmount`) without consulting external config \u2014 the\n * inbound mirror of how the outbound flow records what hits destAddress as `destAmount`.\n *\n * The BridgeIntent.nonce is the deterministic `evm-{chainId}-{contract}-{bridgeId}` form so\n * it aligns with the BullMQ jobId and the status route's URL `:nonce` parameter \u2014 a single\n * canonical id ties the same logical bridge across all surfaces. Dash delimiter is used\n * because BullMQ rejects custom jobIds containing `:`.\n */\nexport async function buildEthToXl1ReserveTx(\n options: BuildEthToXl1ReserveTxOptions,\n): Promise<SignedHydratedTransaction> {\n const {\n amount,\n bridgeAccount,\n bridgeId,\n destAddress,\n evmChainId,\n evmContractAddress,\n evmSrcAddress,\n evmTokenAddress,\n evmTxHash,\n exp,\n feesAddress,\n feesAmount,\n nbf,\n xl1ChainId,\n xl1TokenAddress,\n } = options\n\n // Build the shared shape (Transfer + BridgeIntent). The same helper drives the\n // `/bridgeFromRemote/estimate` route so the projected estimate matches the signed Stage 2\n // tx byte-for-byte modulo bridgeId/evmTxHash. The min-amount / amount >= feesAmount\n // invariant is enforced inside the helper.\n const { intent, transfer } = buildEthToXl1BridgePayloads({\n amount,\n bridgeAccountAddress: bridgeAccount.address,\n bridgeId,\n destAddress,\n evmChainId,\n evmContractAddress,\n evmSrcAddress,\n evmTokenAddress,\n feesAddress,\n feesAmount,\n xl1ChainId,\n xl1TokenAddress,\n })\n\n // Source observation requires evmTxHash and is only knowable after Stage 1 verifies the\n // EVM event \u2014 so it lives outside the shared payloads helper.\n const destAmountHex = toHex(amount - feesAmount)\n const srcAmountHex = toHex(amount)\n const sourceObservation = new PayloadBuilder<BridgeSourceObservation>({ schema: BridgeSourceObservationSchema })\n .fields({\n dest: xl1ChainId,\n destAddress,\n destAmount: destAmountHex,\n destToken: xl1TokenAddress,\n src: evmChainId,\n srcAddress: evmSrcAddress,\n srcAmount: srcAmountHex,\n srcConfirmation: evmTxHash,\n srcToken: evmTokenAddress,\n })\n .build()\n\n return buildTransaction(\n xl1ChainId,\n [transfer],\n [intent, sourceObservation],\n bridgeAccount,\n nbf,\n exp,\n )\n}\n", "import type { Provider } from 'ethers'\n\nimport type { EvmConfirmationDepth } from '../../../evm/index.ts'\n\n/**\n * Resolves an EvmConfirmationDepth into the concrete block reference used by `eth_call`\n * / `eth_getLogs` / `nextBridgeToId({ blockTag })` / `bridgesToRemote(id, { blockTag })` /\n * `queryFilter(filter, fromBlock, toBlock)`. Return type covers all three forms ethers\n * accepts as BlockTag and that typechain's `queryFilter` overload tolerates (`string |\n * number`).\n *\n * Three branches, picked to avoid an unnecessary RPC round-trip *and* to avoid a class of\n * pre-deploy-block bugs:\n *\n * - 'finalized': forwarded as-is. Resolved server-side, so no head fetch needed.\n *\n * - depth === 0: returns 'latest' rather than computing `head - 0`. Semantically\n * identical (\"trust head, no reorg buffer\"), but materially safer. ethers v6 caches\n * `getBlockNumber()` for up to `pollingInterval` ms (~1s WS, ~4s JSON-RPC), so a\n * stale read can hand back a block number from BEFORE the contract was deployed \u2014\n * then `eth_call` at that historical block returns `0x` (no code at that address\n * yet) and ethers throws BAD_DATA. Letting the server resolve 'latest' at call time\n * sidesteps the race entirely. Also saves the head-fetch round-trip.\n *\n * - numeric depth > 0: subtract from the current head and clamp to >= 0. The head fetch\n * is unavoidable here \u2014 we need a specific past block, not the live head.\n */\nexport async function resolveEvmBlockTagAtDepth(\n provider: Provider,\n depth: EvmConfirmationDepth,\n): Promise<number | 'latest' | 'finalized'> {\n if (depth === 'finalized') return 'finalized'\n if (depth === 0) return 'latest'\n const head = await provider.getBlockNumber()\n return Math.max(head - depth, 0)\n}\n", "import {\n assertEx, hexToBigInt, toEthAddress,\n} from '@xylabs/sdk-js'\nimport type { Payload } from '@xyo-network/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type { LiquidityPoolBridge } from '@xyo-network/typechain'\nimport { isBridgeIntent, type SignedHydratedTransaction } from '@xyo-network/xl1-sdk'\nimport type { Wallet } from 'ethers'\n\nexport const submitEthTransaction = async (\n tx: SignedHydratedTransaction,\n offChainPayloads: Payload[],\n bridge: LiquidityPoolBridge,\n wallet: Wallet,\n) => {\n // Approve the bridge to spend tokens\n const xl1Transaction = assertEx(tx[0], () => 'No corresponding XL1 transaction found')\n const allPayloads = [...tx[1], ...offChainPayloads]\n const bridgeIntent = assertEx(allPayloads.find(isBridgeIntent), () => 'No bridge intent found')\n const srcAddress = toEthAddress(bridgeIntent.srcAddress)\n const destAddress = toEthAddress(bridgeIntent.destAddress)\n const amount = hexToBigInt(bridgeIntent.destAmount)\n const nonce = hexToBigInt(await PayloadBuilder.hash(xl1Transaction))\n // Assume approval has already been done out of band for simplicity\n // const contractApprovalTx = await bridgeableToken.connect(wallet).approve(bridge.getAddress(), amount)\n // await contractApprovalTx.wait(1)\n\n // Send tokens to bridge\n const bridgeTx = await bridge.connect(wallet).bridgeFromRemote(srcAddress, destAddress, amount, nonce)\n const receipt = await bridgeTx.wait(1)\n return receipt?.hash\n}\n", "import { type BrandedHash } from '@xylabs/sdk-js'\nimport type { Payload } from '@xyo-network/sdk-js'\nimport { type SignedHydratedTransaction, type XyoGatewayRunner } from '@xyo-network/xl1-sdk'\n\nexport const submitXl1Transaction = async (\n preparedTx: SignedHydratedTransaction,\n offChain: Payload[] = [],\n gateway: XyoGatewayRunner,\n): Promise<[BrandedHash, SignedHydratedTransaction]> => {\n // Option 1: Add payloads to chain with addPayloadsToChain\n // Not optimal as it requires reconstructing the transaction from the on-chain payloads, which changes the tx hash\n // const offChainPayloads = preparedTx[1].filter(p => !isAllowedBlockPayload(p))\n // const onChainPayloads = preparedTx[1].filter(isAllowedBlockPayload)\n // const result = await gateway.addPayloadsToChain(onChainPayloads, offChainPayloads)\n // return result\n\n // Option 2: Add transaction to chain with addTransactionToChain\n // Fails due to resigning of transaction in addTransactionToChain, which causes `from` to be invalid\n const result = await gateway.addTransactionToChain(preparedTx, offChain)\n return result\n\n // Option 3: Add transaction to chain with addTransactionToChain, but bypass resigning by passing the preparedTx as an unsigned transaction\n // const runner = assertEx(gateway.connection.runner, () => 'No runner available on gateway connection')\n // const result = await runner.broadcastTransaction(preparedTx)\n // return [result, preparedTx]\n}\n", "import type { Address, Hex } from '@xylabs/sdk-js'\nimport { asHex, toAddress } from '@xylabs/sdk-js'\nimport type { LiquidityPoolBridge } from '@xyo-network/typechain'\nimport type { Provider } from 'ethers'\nimport { ZeroAddress } from 'ethers'\n\nimport type { EvmConfirmationDepth } from '../../../evm/index.ts'\nimport { resolveEvmBlockTagAtDepth } from './resolveEvmBlockTagAtDepth.ts'\n\nexport interface EthBridgeEventData {\n amount: bigint\n destAddress: Address\n destToken: Address\n /** Tx hash of the EVM transaction that emitted BridgedToRemote(id). */\n evmTxHash: Hex\n srcAddress: Address\n}\n\n/**\n * Reads the bridge contract's `bridgesToRemote(id)` at the configured confirmation depth\n * (numeric block depth, or 'finalized' for Casper FFG cryptographic finality) and looks up\n * the matching `BridgedToRemote(id)` event log to capture the EVM tx hash. Returns the\n * canonical fields, or `null` when the slot is empty / no canonical event exists at depth.\n *\n * The contract storage at depth is the source of truth for whether a `BridgedToRemote`\n * event is canonical. A non-zero `srcAddress` means the slot was populated at that block\n * and (because the contract has no delete/overwrite path) is permanent on the chain that\n * extends from there. A zero `srcAddress` at depth means the event was orphaned by a reorg\n * or never reached canonical state \u2014 the caller must treat this as terminal.\n *\n * The event-log lookup is what surfaces the EVM tx hash for `BridgeSourceObservation`'s\n * `srcConfirmation`. It scans from genesis to the depth-tagged block; on chains with long\n * history this is expensive, so a future optimization should narrow the range (cache the\n * contract's deploy block or accept a fromBlock hint).\n */\nexport async function verifyEthBridgeEvent(\n id: bigint,\n bridge: LiquidityPoolBridge,\n provider: Provider,\n confirmationDepth: EvmConfirmationDepth,\n): Promise<EthBridgeEventData | null> {\n const blockTag = await resolveEvmBlockTagAtDepth(provider, confirmationDepth)\n const data = await bridge.bridgesToRemote(id, { blockTag })\n if (data.srcAddress === ZeroAddress) {\n return null\n }\n\n // Find the BridgedToRemote(id) event log to capture the tx hash. Since `id` is indexed\n // and monotonic-unique, this returns at most one event on a canonical chain.\n const filter = bridge.filters.BridgedToRemote(id)\n const events = await bridge.queryFilter(filter, 0, blockTag)\n const event = events[0]\n if (event === undefined) {\n // Storage said populated but no event found at depth \u2014 this would be an inconsistency.\n // Treat like a null verification so the scanner advances past the id rather than getting\n // stuck retrying.\n return null\n }\n\n return {\n amount: data.amount,\n destAddress: toAddress(data.destAddress),\n destToken: toAddress(data.destToken),\n evmTxHash: asHex(event.transactionHash, true),\n srcAddress: toAddress(data.srcAddress),\n }\n}\n", "import type { SignedHydratedTransaction } from '@xyo-network/xl1-sdk'\nimport type { Job } from 'bullmq'\nimport { Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport { prefix } from '../prefix.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\n\nexport interface EthToXl1BridgeParentJobData {\n tx: SignedHydratedTransaction\n}\nexport interface EthToXl1BridgeParentJobReturn { }\nexport type EthToXl1BridgeParentJob = Job<EthToXl1BridgeParentJobData, EthToXl1BridgeParentJobReturn>\n\nconst name = 'Bridge Ethereum to XL1'\nconst queueName = 'eth-to-xl1-bridge'\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel) => {\n const worker = new Worker(\n queueName,\n async (job: EthToXl1BridgeParentJob) => {\n await job.log(`[${job.name}] start`)\n // Parent job has no work other than waiting on children\n await job.log(`[${job.name}] done`)\n return {}\n },\n {\n connection, telemetry, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const EthToXl1BridgeParent: WorkerDescription = {\n createWorker, name, queueName,\n}\n", "import { assertEx } from '@xylabs/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type { Job } from 'bullmq'\nimport { Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport type { IBridgeServiceCollection } from '../../index.ts'\nimport { prefix } from '../prefix.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\nimport type { Xl1TransactionJobData } from './Xl1TransactionJobData.ts'\n\nexport type EthTransactionMonitorJobData = Xl1TransactionJobData\nexport interface EthTransactionMonitorJobReturn {\n blockHash: string\n blockNumber: number\n submissionHash: string\n}\nexport type EthTransactionMonitorJob = Job<EthTransactionMonitorJobData, EthTransactionMonitorJobReturn>\n\nconst name = 'Monitor Submitted ETH Transaction'\nconst queueName = 'eth-tx-monitor'\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel, services?: IBridgeServiceCollection) => {\n const provider = assertEx(services?.provider, () => 'provider service not provided')\n const stateMap = assertEx(services?.ethTxStateMap, () => 'ethTxStateMap service not provided')\n\n const worker = new Worker(\n queueName,\n async (job: EthTransactionMonitorJob) => {\n const { tx } = job.data\n const hash = await PayloadBuilder.hash(tx[0])\n const state = assertEx(await stateMap.get(hash), () => 'State not found')\n const submissionHash = assertEx(state?.submissionHash, () => 'submissionHash not found')\n const receipt = assertEx(await provider.getTransactionReceipt(submissionHash), () => 'Transaction receipt not found')\n await job.log(`[${hash}] confirmed ETH tx ${submissionHash} in block ${receipt.blockNumber}`)\n const { blockHash, blockNumber } = receipt\n state.confirmationHash = blockHash\n await stateMap.set(hash, state)\n return {\n blockHash, blockNumber, submissionHash,\n }\n },\n {\n connection, telemetry, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const EthTransactionMonitor: WorkerDescription = {\n createWorker, name, queueName,\n}\n", "import { assertEx, hexToBigInt } from '@xylabs/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport { isBridgeIntent } from '@xyo-network/xl1-sdk'\nimport type { Job } from 'bullmq'\nimport { Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport { getAddress } from 'ethers'\nimport type { Redis } from 'ioredis'\n\nimport type { IBridgeServiceCollection } from '../../index.ts'\nimport {\n validateSufficientLiquiditySourceAllowance, validateSufficientLiquiditySourceBalance, validateSufficientRunnerEthBalanceForGas,\n} from '../../validation/index.ts'\nimport { prefix } from '../prefix.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\nimport type { Xl1DataLakeTransactionJobData } from './Xl1TransactionJobData.ts'\n\nexport type EthTransactionPreparationJobData = Xl1DataLakeTransactionJobData\nexport type EthTransactionPreparationJobReturn = Record<string, never>\nexport type EthTransactionPreparationJob = Job<EthTransactionPreparationJobData, EthTransactionPreparationJobReturn>\n\nconst name = 'Prepare ETH Transaction'\nconst queueName = 'eth-tx-prepare'\n\nexport const createWorker = (connection: Redis, telemetry?: BullMQOtel, services?: IBridgeServiceCollection) => {\n const bridge = assertEx(services?.bridge, () => 'bridge service not provided')\n const bridgeableToken = assertEx(services?.bridgeableToken, () => 'bridgeableToken service not provided')\n const stateMap = assertEx(services?.ethTxStateMap, () => 'ethTxStateMap service not provided')\n const wallet = assertEx(services?.wallet, () => 'wallet service not provided')\n\n const worker = new Worker(\n queueName,\n async (job: EthTransactionPreparationJob) => {\n const { tx, offChainPayloads } = job.data\n const hash = await PayloadBuilder.hash(tx[0])\n await job.log(`[${hash}] preparing ETH transaction`)\n await job.log(`[${hash}] validating liquiditySource has sufficient allowance`)\n if (!(await validateSufficientLiquiditySourceAllowance(tx, offChainPayloads, bridgeableToken, bridge, job))) {\n throw new Error('Liquidity source does not have sufficient allowance for the bridge to execute the transaction')\n }\n await job.log(`[${hash}] validated liquiditySource has sufficient allowance`)\n await job.log(`[${hash}] validating liquiditySource has sufficient balance`)\n if (!(await validateSufficientLiquiditySourceBalance(tx, offChainPayloads, bridgeableToken, bridge, job))) {\n throw new Error('Liquidity source does not have sufficient balance for the bridge to execute the transaction')\n }\n await job.log(`[${hash}] validated liquiditySource has sufficient balance`)\n await job.log(`[${hash}] building ETH transaction`)\n const allPayloads = [...tx[1], ...offChainPayloads]\n const bridgeIntent = assertEx(allPayloads.find(isBridgeIntent), () => 'No bridge intent found')\n const amount = hexToBigInt(bridgeIntent.destAmount)\n const srcAddress = getAddress(bridgeIntent.srcAddress)\n const destAddress = getAddress(bridgeIntent.destAddress)\n const nonce = hexToBigInt(await PayloadBuilder.hash(tx[0]))\n const preparedTx = await bridge.getFunction('bridgeFromRemote').populateTransaction(srcAddress, destAddress, amount, nonce)\n await job.log(`[${hash}] built ETH transaction`)\n await job.log(`[${hash}] validating tx runner has sufficient ETH for gas`)\n if (!(await validateSufficientRunnerEthBalanceForGas(preparedTx, wallet, job))) {\n throw new Error('Transaction runner does not have sufficient ETH to cover estimated gas (with buffer)')\n }\n await job.log(`[${hash}] validated tx runner has sufficient ETH for gas`)\n await job.log(`[${hash}] storing ETH preparedTx`)\n await stateMap.set(hash, { preparedTx })\n await job.log(`[${hash}] stored ETH preparedTx`)\n await job.log(`[${hash}] prepared ETH transaction`)\n return {}\n },\n {\n connection, telemetry, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const EthTransactionPreparation: WorkerDescription = {\n createWorker, name, queueName,\n}\n", "import type { Hex } from '@xylabs/sdk-js'\nimport { hexToBigInt } from '@xylabs/sdk-js'\n\nexport interface ValidateAmountMeetsMinBridgeAmountArgs {\n /** Gross deposit amount in atto. For EVM\u2192XL1 this is `bridgesToRemote[id].amount`. */\n amount: bigint\n /** Configured floor (Hex-encoded atto), shared with the XL1\u2192EVM outbound direction\n * (BridgeConfig.minBridgeAmount). */\n minBridgeAmount: Hex\n}\n\n/**\n * Returns true if `amount >= minBridgeAmount`. Used by Stage 2 of the EVM\u2192XL1 inbound flow\n * to short-circuit fulfillment for deposits below the bridge's configured floor.\n *\n * The contract (`LiquidityPoolBridge.bridgeToRemote`) does NOT enforce a minimum \u2014 it only\n * rejects zero and over-max. So any inbound deposit smaller than what the bridge service\n * considers economical (post-fee) reaches Stage 2 and must be filtered here. Failed\n * inbound deposits sit in the EVM-side `liquiditySource` reserve and are operator-refundable\n * out-of-band; this is documented behavior, not a protocol guarantee.\n */\nexport function validateAmountMeetsMinBridgeAmount({\n amount,\n minBridgeAmount,\n}: ValidateAmountMeetsMinBridgeAmountArgs): boolean {\n return amount >= hexToBigInt(minBridgeAmount)\n}\n", "import { hexToBigInt, isUndefined } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type { BridgeIntent, Transfer } from '@xyo-network/xl1-sdk'\n\nimport { getMaxBridgeAmount, getMinBridgeAmount } from '../evm/index.ts'\nimport { generateBridgeEstimate } from '../util/index.ts'\n\n/**\n * Validates a bridge estimate by checking the intent and transfer against the provided configuration. This method\n * only returns true if the bridge estimate matches exactly.\n * @param intent The BridgeIntent\n * @param transfer The Transfer\n * @param config The Config\n * @returns True if the bridge estimate satisfies bridging conditions, false otherwise.\n */\nexport const validateBridgeEstimateExact = async (\n intent: BridgeIntent,\n transfer: Transfer,\n config: BridgeConfig,\n): Promise<boolean> => {\n const {\n srcAddress, srcAmount, destAddress,\n } = intent\n\n // Reject if the requested amount is outside the configured bounds\n if (hexToBigInt(srcAmount) < hexToBigInt(getMinBridgeAmount(config))) return false\n if (hexToBigInt(srcAmount) > hexToBigInt(getMaxBridgeAmount(config))) return false\n\n const [calculatedIntent, calculatedTransfer] = await generateBridgeEstimate(srcAddress, srcAmount, destAddress, config)\n if (isUndefined(calculatedIntent) || isUndefined(calculatedTransfer)) return false\n const { nonce: expectedIntentNonce, ...expectedIntentStatic } = calculatedIntent\n const { nonce: actualIntentNonce, ...actualIntentStatic } = intent\n if ((await PayloadBuilder.dataHash(expectedIntentStatic)) !== (await PayloadBuilder.dataHash(actualIntentStatic))) return false\n const { epoch: expectedTransferEpoch, ...expectedTransferStatic } = calculatedTransfer\n const { epoch: actualTransferEpoch, ...actualTransferStatic } = transfer\n if ((await PayloadBuilder.dataHash(expectedTransferStatic)) !== (await PayloadBuilder.dataHash(actualTransferStatic))) return false\n\n return true\n}\n", "import { asHex } from '@xylabs/sdk-js'\nimport type { ChainId } from '@xyo-network/xl1-sdk'\n\nexport const asChainId = (value: unknown): ChainId | undefined => {\n const chainId = asHex(value)\n return chainId\n}\n", "import type { Address } from '@xylabs/sdk-js'\nimport { asAddress } from '@xylabs/sdk-js'\n\nexport const asToken = (value: unknown): Address | undefined => {\n const token = asAddress(value)\n return token\n}\n", "import type { Address } from '@xylabs/sdk-js'\nimport { asAddress, assertEx } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nexport const tryGetBridgeEscrowAddress = (config: BridgeConfig): Address | undefined => {\n const address = asAddress(config.escrowAddress)\n return address\n}\n\nexport const getBridgeEscrowAddress = (config: BridgeConfig): Address => {\n const address = assertEx(tryGetBridgeEscrowAddress(config), () => `Invalid bridge escrow address: ${config.escrowAddress}`)\n return address\n}\n", "import type { Address } from '@xylabs/sdk-js'\nimport { asAddress, assertEx } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nexport const tryGetBridgeFeesAddress = (config: BridgeConfig): Address | undefined => {\n const address = asAddress(config.feesAddress)\n return address\n}\n\nexport const getBridgeFeesAddress = (config: BridgeConfig): Address => {\n const address = assertEx(tryGetBridgeFeesAddress(config), () => `Invalid bridge fees address: ${config.feesAddress}`)\n return address\n}\n", "import type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nimport type { FeeStructure } from '../util/index.ts'\n\nexport const getFeeStructure = (config: BridgeConfig): FeeStructure => {\n const { feeFixed, feeRateBasisPoints } = config\n return { feeFixed, feeRateBasisPoints }\n}\n", "import type { Hex } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nexport const getMaxBridgeAmount = (config: BridgeConfig): Hex => {\n const { maxBridgeAmount } = config\n return maxBridgeAmount\n}\n", "import type { Hex } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nexport const getMinBridgeAmount = (config: BridgeConfig): Hex => {\n const { minBridgeAmount } = config\n return minBridgeAmount\n}\n", "import { assertEx } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport type { ChainId } from '@xyo-network/xl1-sdk'\n\nimport { asChainId } from './asChainId.ts'\n\nexport const getRemoteChainId = (config: BridgeConfig): ChainId => {\n const remoteChainId = assertEx(asChainId(config.remoteChainId), () => 'Invalid remote chain ID in config')\n return remoteChainId\n}\n", "import type { Address } from '@xylabs/sdk-js'\nimport { assertEx } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nimport { asToken } from './asToken.ts'\n\nexport const getRemoteTokenAddress = (config: BridgeConfig): Address => {\n const token = asToken(config.remoteTokenAddress)\n return assertEx(token, () => 'Remote token address is not defined in bridge configuration')\n}\n", "import type { Address, Promisable } from '@xylabs/sdk-js'\nimport { isDefined } from '@xylabs/sdk-js'\nimport { resolveWalletForActor } from '@xyo-network/chain-orchestration'\nimport type { WalletInstance } from '@xyo-network/wallet-model'\nimport type { ActorConfig } from '@xyo-network/xl1-sdk'\n\nlet accountServiceSingleton: Promisable<WalletInstance> | undefined\n\nexport const getBridgeWalletAccount = async (config: ActorConfig): Promise<WalletInstance> => {\n if (accountServiceSingleton) return accountServiceSingleton\n const accountPath = typeof config.accountPath === 'string' ? config.accountPath : undefined\n const account = await resolveWalletForActor(config.name, accountPath)\n accountServiceSingleton = account\n return accountServiceSingleton\n}\n\nexport const getAddressOrBridgeWalletAccountAddress = async (\n getConfigAccount: (config: ActorConfig) => Address | undefined,\n config: ActorConfig,\n): Promise<Address> => {\n const address = getConfigAccount(config)\n if (isDefined(address)) return address\n const walletAccount = await getBridgeWalletAccount(config)\n return walletAccount.address\n}\n", "import type { Address } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nimport { tryGetBridgeEscrowAddress } from './getBridgeEscrowAddress.ts'\nimport { tryGetBridgeFeesAddress } from './getBridgeFeesAddress.ts'\nimport { getBridgeWalletAccount } from './getBridgeWalletAccount.ts'\n\nexport interface TransferAddresses {\n escrowAddress: Address\n feesAddress: Address\n}\n\nexport const getTransferAddresses = async (config: BridgeConfig): Promise<TransferAddresses> => {\n const escrowAddress = tryGetBridgeEscrowAddress(config) ?? (await getBridgeWalletAccount(config)).address\n const feesAddress = tryGetBridgeFeesAddress(config) ?? (await getBridgeWalletAccount(config)).address\n return { escrowAddress, feesAddress }\n}\n", "import { assertEx, isDefined } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport type { ChainId } from '@xyo-network/xl1-sdk'\n\nimport { asChainId } from './asChainId.ts'\n\nexport const getXl1ChainId = (config: BridgeConfig): ChainId => {\n const xl1ChainId = config.xl1ChainId\n if (isDefined(xl1ChainId)) {\n return assertEx(asChainId(xl1ChainId), () => 'Invalid xl1ChainId in bridge config')\n }\n return assertEx(asChainId(config.chain.id), () => 'Invalid chain.id in config')\n}\n", "import type { Hex } from '@xylabs/sdk-js'\nimport { isDefined } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nimport { asToken } from './asToken.ts'\nimport { getXl1ChainId } from './getXl1ChainId.ts'\n\nexport const getXl1TokenAddress = (config: BridgeConfig): Hex => {\n const token = asToken(config.xl1TokenAddress)\n if (isDefined(token)) return token\n return getXl1ChainId(config)\n}\n", "import type { BridgeConfig, BridgeSettings } from '@xyo-network/chain-orchestration'\n\nimport { getFeeStructure } from './getFeeStructure.ts'\nimport { getMaxBridgeAmount } from './getMaxBridgeAmount.ts'\nimport { getMinBridgeAmount } from './getMinBridgeAmount.ts'\nimport { getRemoteChainId } from './getRemoteChainId.ts'\nimport { getRemoteTokenAddress } from './getRemoteTokenAddress.ts'\nimport { getTransferAddresses } from './getTransferAddresses.ts'\nimport { getXl1ChainId } from './getXl1ChainId.ts'\nimport { getXl1TokenAddress } from './getXl1TokenAddress.ts'\n\nexport const getBridgeSettings = async (config: BridgeConfig): Promise<BridgeSettings> => {\n const { feeFixed, feeRateBasisPoints } = getFeeStructure(config)\n const { feesAddress, escrowAddress } = await getTransferAddresses(config)\n const maxBridgeAmount = getMaxBridgeAmount(config)\n const minBridgeAmount = getMinBridgeAmount(config)\n const remoteChainId = getRemoteChainId(config)\n const remoteTokenAddress = getRemoteTokenAddress(config)\n const xl1TokenAddress = getXl1TokenAddress(config)\n const xl1ChainId = getXl1ChainId(config)\n return {\n feeFixed, feeRateBasisPoints, feesAddress, escrowAddress, maxBridgeAmount, minBridgeAmount, remoteChainId, remoteTokenAddress, xl1TokenAddress, xl1ChainId,\n }\n}\n", "import { isDefined, toHex } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nimport { getRemoteChainId } from './getRemoteChainId.ts'\n\n// Confirmation depth options for the remote (EVM) chain. Numeric values are in BLOCKS;\n// the string 'finalized' is the ethers BlockTag for Casper FFG cryptographic finality.\n// Reading the bridge contract's storage at depth (latest - N) or at 'finalized' is what\n// buys reorg protection; depth 0 means \"trust head\" and is only safe for non-reorging chains.\n//\n// On Ethereum mainnet (~12s blocks):\n// 0 \u2014 Hardhat / dev. Test node never reorgs.\n// 12 \u2014 Legacy \"safe\" (~2.4 min). Was the pre-merge default; thin margin post-merge.\n// 32 \u2014 Practical safe (~6.4 min). One epoch's worth of blocks; current default below.\n// 64 \u2014 ~12.8 min. Comparable to Casper finality wall-clock time without using the tag.\n// 'finalized' \u2014 Casper FFG cryptographic finality, ~12-13 min on mainnet. Strongest available\n// guarantee \u2014 economically irreversible barring a 1/3 stake slashing. Set this\n// via env (BRIDGE_REMOTE_CONFIRMATION_DEPTH=finalized) when you want the\n// verifier and scanner to read at the finalized block tag instead of a numeric\n// depth offset.\n\nexport type EvmConfirmationDepth = number | 'finalized'\n\n// Both keys and lookup value pass through `toHex` so that any input form (`'0x7a69'`,\n// `'7a69'`, `'0x7A69'`, the @xylabs Hex brand) normalizes to the same string \u2014 `toHex`\n// strips the `0x` prefix, lowercases, and pads to an 8-nibble byte boundary, so all forms\n// collapse to e.g. `'00007a69'`. Direct string equality on the result is reliable. The\n// previous version compared `chainId.toLowerCase()` against a literal `'0x7a69'` key, but\n// the Hex brand strips `0x` in its stringified form, so the lookup silently missed and\n// fell through to FALLBACK_CONFIRMATION_DEPTH.\nconst HARDHAT_CHAIN_ID = toHex('0x7a69')\nconst ETHEREUM_MAINNET_CHAIN_ID = toHex('0x1')\n\nconst FALLBACK_CONFIRMATION_DEPTH: EvmConfirmationDepth = 32\n\nconst DEFAULT_CONFIRMATION_DEPTH_BY_CHAIN_ID = new Map<string, EvmConfirmationDepth>([\n [HARDHAT_CHAIN_ID, 0],\n [ETHEREUM_MAINNET_CHAIN_ID, 32],\n])\n\nexport function getRemoteConfirmationDepth(config: BridgeConfig): EvmConfirmationDepth {\n if (isDefined(config.remoteConfirmationDepth)) return config.remoteConfirmationDepth\n const chainId = toHex(getRemoteChainId(config))\n return DEFAULT_CONFIRMATION_DEPTH_BY_CHAIN_ID.get(chainId) ?? FALLBACK_CONFIRMATION_DEPTH\n}\n", "import type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\n/**\n * How often the EVM\u2192XL1 scanner ticks. The interval is the configured value verbatim \u2014\n * BridgeConfigZod already supplies a 30s default, so an unset config still resolves\n * cleanly. Kept as a getter for symmetry with the rest of the bridge config accessors,\n * and so future logic (e.g. per-chain overrides) has a single seam to extend.\n */\nexport function getScannerIntervalMs(config: BridgeConfig): number {\n return config.scannerIntervalMs\n}\n", "import type { Hex } from '@xylabs/sdk-js'\nimport { hexToBigInt, toHex } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nimport type { BridgeFees } from './BridgeFees.ts'\n\nexport type FeeStructure = Pick<BridgeConfig, 'feeFixed' | 'feeRateBasisPoints'>\n\nexport const calculateBridgeFees = (srcAmount: Hex, feeStructure: FeeStructure): BridgeFees => {\n const { feeFixed, feeRateBasisPoints } = feeStructure\n\n // Format source input\n const srcAmountBigInt = hexToBigInt(srcAmount)\n\n // Calculate fixed fee\n // const feeFixedBigInt = hexToBigInt(feeFixed)\n\n // Integer-safe basis point calculation (floor division)\n const feeVariableBigInt\n = (srcAmountBigInt * BigInt(feeRateBasisPoints)) / 10_000n\n const feeVariable = toHex(feeVariableBigInt)\n\n // Calculate total fee\n // const feeTotalBigInt = feeFixedBigInt + feeVariableBigInt\n\n // Calculate destination amount\n // const destAmountBigInt = srcAmountBigInt > feeTotalBigInt ? srcAmountBigInt - feeTotalBigInt : 0n\n // const destAmount = toHex(destAmountBigInt)\n\n return {\n feeFixed, feeVariable, srcAmount,\n }\n}\n", "import type { Hex } from '@xylabs/sdk-js'\nimport { hexToBigInt, toHex } from '@xylabs/sdk-js'\n\nimport type { FeeStructure } from './calculateBridgeFees.ts'\n\n/**\n * Given a user's total available balance, calculates the maximum amount they can bridge\n * after accounting for the fixed and variable bridge fees.\n *\n * Solving for M where: M + feeFixed + (M * basisPoints / 10_000) = balance\n * => M = (balance - feeFixed) * 10_000 / (10_000 + basisPoints)\n */\nexport const calculateMaxBridgeAmount = (balance: Hex, feeStructure: FeeStructure): Hex => {\n const { feeFixed, feeRateBasisPoints } = feeStructure\n const balanceBigInt = hexToBigInt(balance)\n const feeFixedBigInt = hexToBigInt(feeFixed)\n\n if (balanceBigInt <= feeFixedBigInt) return toHex(0n)\n\n const maxAmount = ((balanceBigInt - feeFixedBigInt) * 10_000n) / (10_000n + BigInt(feeRateBasisPoints))\n return toHex(maxAmount)\n}\n", "import type { Address, Hex } from '@xylabs/sdk-js'\nimport { hexToBigInt } from '@xylabs/sdk-js'\nimport type { Transfer } from '@xyo-network/xl1-sdk'\nimport { createTransferPayload } from '@xyo-network/xl1-sdk'\n\nimport type { BridgeFees } from './BridgeFees.ts'\n\n/**\n * Calculates the transfer representing the bridging of funds including the appropriate amounts for the bridge fees\n * @param sender The client attempting to bridge\n * @param srcAmount The amount the client is attempting to bridge\n * @param escrowAddress The address in which bridged funds will be held until the transfer is executed on the destination chain\n * @param feesAddress The address to which bridge fees will be paid\n * @param context An object containing the necessary fee and amount information to construct the transfer context\n * @returns A transfer representing the bridging of funds including the appropriate amounts for the bridge fees\n */\nexport const createBridgeTransfer = (sender: Address, srcAmount: Hex, escrowAddress: Address, feesAddress: Address, context: BridgeFees): Transfer => {\n const { feeFixed, feeVariable } = context\n const escrowAmount = hexToBigInt(srcAmount)\n const feesAmount = hexToBigInt(feeFixed) + hexToBigInt(feeVariable)\n const transfers: Record<Address, bigint>\n // If the escrow and fee addresses are the same\n = escrowAddress === feesAddress\n // combine the amounts into a single transfer to that address\n ? { [feesAddress]: escrowAmount + feesAmount }\n // otherwise, create separate transfers to the escrow and fees addresses\n : { [escrowAddress]: escrowAmount, [feesAddress]: feesAmount }\n const transfer = createTransferPayload(sender, transfers, context)\n\n return transfer\n}\n", "import type { Hex } from '@xylabs/sdk-js'\nimport { toAddress } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type {\n BridgeIntent, BridgeIntentFields, Transfer,\n} from '@xyo-network/xl1-sdk'\nimport { BridgeIntentSchema } from '@xyo-network/xl1-sdk'\nimport { v4 } from 'uuid'\n\nimport { getBridgeSettings } from '../evm/index.ts'\nimport { calculateBridgeFees } from './calculateBridgeFees.ts'\nimport { createBridgeTransfer } from './createBridgeTransfer.ts'\n\nexport const generateBridgeEstimate = async (\n srcAddress: Hex,\n srcAmount: Hex,\n destAddress: Hex,\n config: BridgeConfig,\n nonceOverride?: string,\n): Promise<[BridgeIntent, Transfer]> => {\n const {\n escrowAddress, feeFixed, feeRateBasisPoints, feesAddress, remoteChainId, remoteTokenAddress, xl1ChainId, xl1TokenAddress,\n } = await getBridgeSettings(config)\n\n const sender = toAddress(srcAddress)\n\n // Calculate fees and destination amount\n const fees = calculateBridgeFees(srcAmount, { feeFixed, feeRateBasisPoints })\n\n // Generate a unique nonce for the bridge intent\n const nonce = nonceOverride ?? v4()\n\n // Build the bridge intent\n const bridgeIntentFields: BridgeIntentFields = {\n // Source\n src: xl1ChainId,\n srcAddress: sender,\n srcAmount,\n srcToken: xl1TokenAddress,\n\n // Destination\n dest: remoteChainId,\n destAddress,\n destAmount: srcAmount, // This is a 1:1 bridge. Fees are handled at the transfer level, not the bridge intent level.\n destToken: remoteTokenAddress,\n nonce,\n }\n const bridgeIntent: BridgeIntent = new PayloadBuilder<BridgeIntent>({ schema: BridgeIntentSchema }).fields(bridgeIntentFields).build()\n\n // Build the transfer\n const transfer = createBridgeTransfer(sender, srcAmount, escrowAddress, feesAddress, fees)\n\n return [bridgeIntent, transfer]\n}\n", "import { asAddress } from '@xylabs/sdk-js'\nimport {\n addressesContains, BoundWitnessValidator, payloadHashesContainsAll, payloadSchemasContainsAll,\n} from '@xyo-network/boundwitness-validator'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type {\n BridgeIntent, TransactionBoundWitness, Transfer,\n} from '@xyo-network/xl1-sdk'\nimport { BridgeIntentSchema, TransferSchema } from '@xyo-network/xl1-sdk'\n\nimport { getXl1ChainId } from '../evm/index.ts'\n\n/**\n * Validates a bridge estimate by checking the intent and transfer against the provided configuration. This method\n * exists to allow for \"at least\" validation of a bridge estimates in case we want to allow for some flexibility in\n * the bridge estimate.\n * @ param signedTransaction The signed transaction bound witness\n * @param signedTxBw The signed transaction bound witness\n * @param intent The BridgeIntent\n * @param transfer The Transfer\n * @param config The Config\n * @returns True if the bridge estimate satisfies bridging conditions, false otherwise.\n */\nexport const validateBridgeTransaction = async (\n signedTxBw: TransactionBoundWitness,\n intent: BridgeIntent,\n transfer: Transfer,\n config: BridgeConfig,\n): Promise<boolean> => {\n const { srcAddress } = intent\n\n // Ensure the transaction is for the correct source chain\n const chainId = getXl1ChainId(config)\n if (signedTxBw.chain !== chainId) return false\n\n // Ensure only the expected number of payloads exist (do not allow ambiguous extras)\n if (signedTxBw.payload_hashes.length != 2) return false\n // Ensure the payloads match the expected schemas\n if (!payloadSchemasContainsAll(signedTxBw, [BridgeIntentSchema, TransferSchema])) return false\n // Ensure the hashes match the intent and transfer\n const hashes = await PayloadBuilder.hashes([intent, transfer])\n if (!payloadHashesContainsAll(signedTxBw, hashes)) return false\n // Ensure the BoundWitness is valid and signed by the sender\n const errors = await new BoundWitnessValidator(signedTxBw).validate()\n if (errors.length > 0) return false\n\n // Ensure the sender's address is included in the addresses\n const sender = asAddress(srcAddress, true)\n if (!addressesContains(signedTxBw, sender)) return false\n\n return true\n}\n", "import { assertEx, hexToBigInt } from '@xylabs/sdk-js'\nimport type { Payload } from '@xyo-network/sdk-js'\nimport type { BridgeableToken, LiquidityPoolBridge } from '@xyo-network/typechain'\nimport { isBridgeIntent, type SignedHydratedTransaction } from '@xyo-network/xl1-sdk'\n\nimport type { AsyncLogger } from './AsyncLogger.ts'\n\n/**\n * Checks if the liquidity source has sufficient allowance for the bridge to execute the transaction. This doesn't\n * ensure that (due to race conditions) the transaction will succeed, but is a quick check to avoid\n * submitting transactions that are likely to fail.\n * @param tx The transaction containing a bridge intent\n * @param offChainPayloads The payloads to put off chain\n * @param bridgeableToken The contract for the token being bridged\n * @param bridge The contract for the liquidity bridge\n * @param logger Optional logger for asynchronous logging\n * @returns True if the liquidity source allowance is sufficient to execute the bridge\n */\nexport const validateSufficientLiquiditySourceAllowance = async (\n tx: SignedHydratedTransaction,\n offChainPayloads: Payload[],\n bridgeableToken: BridgeableToken,\n bridge: LiquidityPoolBridge,\n logger?: AsyncLogger,\n) => {\n // Get the amount being bridged from the bridge intent\n const allPayloads = [...tx[1], ...offChainPayloads]\n const bridgeIntent = assertEx(allPayloads.find(isBridgeIntent), () => 'No bridge intent found')\n const amount = hexToBigInt(bridgeIntent.destAmount)\n\n // Get the addresses\n const liquiditySourceAddress = await bridge.liquiditySource()\n const bridgeAddress = await bridge.getAddress()\n\n // Check the allowance of the liquidity source for the bridge\n const remainingAllowance = await bridgeableToken.allowance(liquiditySourceAddress, bridgeAddress)\n await logger?.log(`Remaining allowance: ${remainingAllowance.toString()}`)\n return remainingAllowance >= amount\n}\n", "import { assertEx, hexToBigInt } from '@xylabs/sdk-js'\nimport type { Payload } from '@xyo-network/sdk-js'\nimport type { BridgeableToken, LiquidityPoolBridge } from '@xyo-network/typechain'\nimport { isBridgeIntent, type SignedHydratedTransaction } from '@xyo-network/xl1-sdk'\n\nimport type { AsyncLogger } from './AsyncLogger.ts'\n\n/**\n * Checks if the liquidity source has sufficient balance for the bridge to execute the transaction. This doesn't\n * ensure that (due to race conditions) the transaction will succeed, but is a quick check to avoid\n * submitting transactions that are likely to fail.\n * @param tx The transaction containing a bridge intent\n * @param offChainPayloads The payloads to put off chain\n * @param bridgeableToken The contract for the token being bridged\n * @param bridge The contract for the liquidity bridge\n * @param logger Optional logger for asynchronous logging\n * @returns True if the liquidity source balance is sufficient to execute the bridge\n */\nexport const validateSufficientLiquiditySourceBalance = async (\n tx: SignedHydratedTransaction,\n offChainPayloads: Payload[],\n bridgeableToken: BridgeableToken,\n bridge: LiquidityPoolBridge,\n logger?: AsyncLogger,\n) => {\n // Get the amount being bridged from the bridge intent\n const allPayloads = [...tx[1], ...offChainPayloads]\n const bridgeIntent = assertEx(allPayloads.find(isBridgeIntent), () => 'No bridge intent found')\n const amount = hexToBigInt(bridgeIntent.destAmount)\n\n // Get the addresses\n const liquiditySourceAddress = await bridge.liquiditySource()\n\n // Check the balance of the liquidity source for the bridge\n const balance = await bridgeableToken.balanceOf(liquiditySourceAddress)\n await logger?.log(`Remaining balance: ${balance.toString()}`)\n return balance >= amount\n}\n", "import { assertEx } from '@xylabs/sdk-js'\nimport type { ContractTransaction, Wallet } from 'ethers'\n\nimport type { AsyncLogger } from './AsyncLogger.ts'\n\nconst DEFAULT_GAS_BUFFER_BPS = 2000n // 20%\n\n/**\n * Validates that the wallet (the account that will submit the tx) has enough ETH\n * to cover the estimated gas cost (plus a buffer) for the transaction.\n * @param preparedTx The transaction that is being prepared for submission.\n * This should be a fully populated transaction (to/from/data/value) except for gas fields.\n * @param wallet The wallet that will be used to submit the transaction.\n * @param logger Optional logger for asynchronous logging.\n * @param bufferBps The buffer to apply to the estimated gas cost, in basis points (1/100th of a percent).\n * @returns A boolean indicating whether the wallet has sufficient ETH to cover the estimated gas cost with the buffer applied.\n */\nexport const validateSufficientRunnerEthBalanceForGas = async (\n preparedTx: ContractTransaction,\n wallet: Wallet,\n logger?: AsyncLogger,\n bufferBps: bigint = DEFAULT_GAS_BUFFER_BPS,\n) => {\n const provider = assertEx(wallet.provider, () => 'Wallet provider is not defined')\n\n // Fee data (EIP-1559 preferred, gasPrice fallback)\n const feeData = await provider.getFeeData()\n const perGas = feeData.maxFeePerGas ?? feeData.gasPrice\n if (perGas == null) {\n await logger?.log('[gas] unable to resolve gas price / maxFeePerGas from provider')\n return true // don\u2019t hard-fail; provider may not support fee data\n }\n\n // Estimate gas\n const transactionRequest = {\n ...preparedTx,\n from: await wallet.getAddress(),\n }\n const estGas = await provider.estimateGas(transactionRequest)\n\n // Include any value sent with the tx\n const txValue = preparedTx?.value ?? 0n\n\n // Required = (gas * perGas + value) * (1 + buffer)\n const baseRequired = estGas * perGas + txValue\n const required = (baseRequired * (10_000n + bufferBps)) / 10_000n\n\n const balance = await provider.getBalance(await wallet.getAddress())\n\n await logger?.log(\n `[gas] runner=${await wallet.getAddress()} balance=${balance.toString()} `\n + `estGas=${estGas.toString()} perGas=${perGas.toString()} value=${txValue.toString()} `\n + `requiredWithBuffer=${required.toString()} bufferBps=${bufferBps.toString()}`,\n )\n\n return balance >= required\n}\n", "import { assertEx } from '@xylabs/sdk-js'\nimport type { AccountInstance } from '@xyo-network/sdk-js'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\n\nimport type { AsyncLogger } from './AsyncLogger.ts'\n\nexport interface ValidateSufficientXl1ReserveBalanceArgs {\n amount: bigint\n bridgeAccount: AccountInstance\n gateway: XyoGatewayRunner\n logger?: AsyncLogger\n}\n\n/**\n * Checks that the bridge's XL1 reserve account has at least `amount` of native balance\n * available to cover an inbound (EVM \u2192 XL1) reserve transfer. Mirrors the XL1 \u2192 EVM\n * direction's `validateSufficientXL1SourceAddressBalance` in spirit: a quick pre-flight\n * gate to avoid building, signing, and dispatching a transaction the chain will then\n * reject for insufficient funds.\n *\n * Race conditions: a concurrent submission could deplete the reserve between this check\n * and the actual XL1 submission. That's acceptable \u2014 the worker chain will fail the\n * submission, BullMQ will retry, and the next retry will re-validate. The check exists to\n * filter the bulk of insufficient-balance cases cheaply, not to be perfectly atomic.\n *\n * Network fees are not included in the comparison (matching the XL1 \u2192 EVM validator's\n * convention). Operators are expected to keep the reserve sufficiently above any single\n * bridge amount; tiny network-fee deltas would only flip the outcome at the margin and\n * BullMQ retry handles those.\n */\nexport async function validateSufficientXl1ReserveBalance({\n amount,\n bridgeAccount,\n gateway,\n logger,\n}: ValidateSufficientXl1ReserveBalanceArgs): Promise<boolean> {\n const viewer = assertEx(gateway.connection.viewer, () => 'Gateway connection does not have a viewer')\n const balance = await viewer.account.balance.accountBalance(bridgeAccount.address)\n await logger?.log(`XL1 reserve account ${bridgeAccount.address} balance: ${balance.toString()}; required: ${amount.toString()}`)\n return balance >= amount\n}\n", "import {\n asAddress, assertEx, hexToBigInt,\n} from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport type { BridgeIntent, XyoGatewayRunner } from '@xyo-network/xl1-sdk'\n\nimport { generateBridgeEstimate } from '../util/index.ts'\nimport type { AsyncLogger } from './AsyncLogger.ts'\n\n/**\n * Checks if the liquidity source has sufficient balance for the bridge to execute the transaction. This doesn't\n * ensure that (due to race conditions) the transaction will succeed, but is a quick check to avoid\n * submitting transactions that are likely to fail.\n * @param bridgeIntent The bridge intent containing the details of the bridge transaction, including the source address and amount being bridged\n * @param gateway The XyoGatewayRunner to check the balance of the source address on XL1\n * @param config The bridge configuration, used to generate a bridge estimate for the transaction\n * @param logger Optional logger for asynchronous logging\n * @returns True if the liquidity source balance is sufficient to execute the bridge\n */\nexport const validateSufficientXL1SourceAddressBalance = async (\n bridgeIntent: BridgeIntent,\n gateway: XyoGatewayRunner,\n config: BridgeConfig,\n logger?: AsyncLogger,\n) => {\n // Get the amount being bridged from the bridge intent\n const viewer = assertEx(gateway.connection.viewer, () => 'Gateway connection does not have a viewer')\n const {\n srcAddress, srcAmount, destAddress,\n } = bridgeIntent\n const srcAddressBranded = asAddress(srcAddress, () => `Invalid source address in bridge intent: ${srcAddress}`)\n const [_, calculatedTransfer] = await generateBridgeEstimate(srcAddress, srcAmount, destAddress, config)\n const totalAmount = Object.values(calculatedTransfer.transfers).reduce((acc, transfer) => acc + hexToBigInt(transfer), 0n)\n\n // Check the srcAddress balance on XL1 for the bridge\n const accountBalance = await viewer.account.balance.accountBalance(srcAddressBranded)\n await logger?.log(`Account balance for ${srcAddressBranded}: ${accountBalance.toString()}`)\n return accountBalance >= totalAmount\n}\n", "import { assertEx, isDefined } from '@xylabs/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type { Job } from 'bullmq'\nimport { Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport type { EthTxState, IBridgeServiceCollection } from '../../index.ts'\nimport { prefix } from '../prefix.ts'\nimport { submitEthTransaction } from './util/index.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\nimport type { Xl1DataLakeTransactionJobData } from './Xl1TransactionJobData.ts'\n\nexport type EthTransactionSubmissionJobData = Xl1DataLakeTransactionJobData\nexport interface EthTransactionSubmissionJobReturn {\n submissionHash: Required<EthTxState>['submissionHash']\n}\nexport type EthTransactionSubmissionJob = Job<EthTransactionSubmissionJobData, EthTransactionSubmissionJobReturn>\n\nconst name = 'Submit ETH Transaction'\nconst queueName = 'eth-tx-submit'\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel, services?: IBridgeServiceCollection) => {\n const bridge = assertEx(services?.bridge, () => 'bridge service not provided')\n const wallet = assertEx(services?.wallet, () => 'wallet service not provided')\n const stateMap = assertEx(services?.ethTxStateMap, () => 'ethTxStateMap service not provided')\n\n const worker = new Worker(\n queueName,\n async (job: EthTransactionSubmissionJob) => {\n const { tx, offChainPayloads } = job.data\n const hash = await PayloadBuilder.hash(tx[0])\n const state = assertEx(await stateMap.get(hash), () => `[${hash}] state not found`)\n\n // Idempotency check against resubmission\n const { submissionHash: existingSubmissionHash } = state\n if (isDefined(existingSubmissionHash)) {\n await job.log(`[${hash}] Tx already submitted with submission response hash ${existingSubmissionHash}`)\n return { submissionHash: existingSubmissionHash }\n }\n\n // Submit the transaction to the Ethereum network\n await job.log(`[${hash}] Submitting ETH tx`)\n const submissionHash = assertEx(await submitEthTransaction(tx, offChainPayloads, bridge, wallet), () => `[${hash}] submissionHash not found in receipt`)\n await job.log(`[${hash}] Submitted ETH tx and received submission response hash ${submissionHash}`)\n return { submissionHash }\n },\n {\n connection, telemetry, concurrency: 1, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const EthTransactionSubmission: WorkerDescription = {\n createWorker, name, queueName,\n}\n", "import { assertEx, isDefined } from '@xylabs/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type { Job } from 'bullmq'\nimport { Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport type { EthTxState, IBridgeServiceCollection } from '../../index.ts'\nimport { prefix } from '../prefix.ts'\nimport type { EthTransactionSubmissionJobReturn } from './EthTransactionSubmission.ts'\nimport { EthTransactionSubmission } from './EthTransactionSubmission.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\nimport type { Xl1TransactionJobData } from './Xl1TransactionJobData.ts'\n\nexport type EthTransactionSubmissionStorageJobData = Xl1TransactionJobData\nexport interface EthTransactionSubmissionStorageJobReturn {\n submissionHash: Required<EthTxState>['submissionHash']\n}\nexport type EthTransactionSubmissionStorageJob = Job<EthTransactionSubmissionStorageJobData, EthTransactionSubmissionStorageJobReturn>\n\nconst name = 'Store ETH Transaction Submission'\nconst queueName = 'eth-tx-store-submission'\n\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel, services?: IBridgeServiceCollection) => {\n const stateMap = assertEx(services?.ethTxStateMap, () => 'ethTxStateMap service not provided')\n\n const worker = new Worker(\n queueName,\n async (job: EthTransactionSubmissionStorageJob) => {\n const { tx } = job.data\n // Get the hash of the transaction\n const hash = await PayloadBuilder.hash(tx[0])\n\n // Get the state of the transaction\n const state = assertEx(await stateMap.get(hash), () => `[${hash}] state not found`)\n\n // Idempotency check against re-store\n const { submissionHash: existingSubmissionHash } = state\n if (isDefined(existingSubmissionHash)) {\n await job.log(`[${hash}] submissionHash already stored as ${existingSubmissionHash}`)\n return { submissionHash: existingSubmissionHash }\n }\n\n // In a Flow, this job should be the PARENT and the submit job should be a CHILD.\n // That lets us read the child job\u2019s return value(s) here.\n const childrenValues = await job.getChildrenValues()\n const jobKey = `${prefix}:${EthTransactionSubmission.queueName}:${hash}`\n const childValues = childrenValues?.[jobKey] as EthTransactionSubmissionJobReturn | undefined\n const submissionHash = childValues?.submissionHash\n\n const resolvedSubmissionHash = assertEx(submissionHash, () => `[${hash}] child submissionHash not found in children values`)\n\n // Store the submission hash in the state\n await job.log(`[${hash}] Storing ETH submissionHash`)\n state.submissionHash = resolvedSubmissionHash\n await stateMap.set(hash, state)\n await job.log(`[${hash}] Stored ETH submissionHash`)\n return { submissionHash: resolvedSubmissionHash }\n },\n {\n connection, telemetry, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const EthTransactionSubmissionStorage: WorkerDescription = {\n createWorker, name, queueName,\n}\n", "import type {\n Address, BrandedHash, Hex,\n} from '@xylabs/sdk-js'\nimport {\n assertEx, delay, hexToBigInt, isDefined, isNull, toHex,\n} from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport type { AccountInstance } from '@xyo-network/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type {\n ChainId, IterableMap, SignedHydratedTransaction, XyoGatewayRunner, XyoViewer,\n} from '@xyo-network/xl1-sdk'\nimport { asXL1BlockNumber } from '@xyo-network/xl1-sdk'\nimport type { Job } from 'bullmq'\nimport { Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport type { BridgeFulfillmentState } from '../../BridgeFulfillmentState.ts'\nimport {\n getFeeStructure, getMinBridgeAmount, getTransferAddresses,\n} from '../../evm/index.ts'\nimport type { IBridgeServiceCollection } from '../../index.ts'\nimport { calculateBridgeFees } from '../../util/index.ts'\nimport { validateAmountMeetsMinBridgeAmount, validateSufficientXl1ReserveBalance } from '../../validation/index.ts'\nimport { prefix } from '../prefix.ts'\nimport { buildEthToXl1ReserveTx, submitXl1Transaction } from './util/index.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\n\nexport interface Xl1ReserveTxFulfillmentJobData {\n /** BigInt as a decimal string. */\n bridgeId: string\n /** EVM bridge contract address. */\n contractAddress: Address\n /** EVM chain id. */\n evmChainId: Hex\n /** Bridge identity, used as the bridgeFulfillmentMap key. */\n identity: string\n /** XL1 chain id (resolved from config at scan time). */\n xl1ChainId: ChainId\n /** XL1 token \"address\" (chain id of the token, resolved from config at scan time). */\n xl1TokenAddress: Hex\n}\n\nexport type Xl1ReserveTxFulfillmentJob = Job<Xl1ReserveTxFulfillmentJobData, void>\n\nconst name = 'XL1 Reserve Transfer Fulfillment'\nconst queueName = 'eth-to-xl1-fulfill'\n\n// Per-attempt window. nbf = build-time XL1 head, exp = head + EXP_BLOCKS_AHEAD. Once head\n// passes exp, the chain refuses the tx and we throw retryable so BullMQ schedules another\n// invocation to build a fresh attempt.\nconst EXP_BLOCKS_AHEAD = 1000\n\n// Polling cadence inside the wait-for-inclusion loop. BullMQ's auto lock-renewal runs at\n// half the worker's lockDuration; polling every 5s keeps the event loop turning so the\n// renewal heartbeat fires and the lock stays fresh.\nconst POLL_INTERVAL_MS = 5000\n\n// Worker concurrency. Each worker invocation holds a slot for up to one EXP_BLOCKS_AHEAD\n// XL1 window; with 32 concurrent slots we can process 32 distinct bridge ids in parallel.\nconst CONCURRENCY = 32\n\ninterface ResumeContext {\n fulfillmentMap: IterableMap<string, BridgeFulfillmentState>\n identity: string\n job: Xl1ReserveTxFulfillmentJob\n state: BridgeFulfillmentState\n viewer: XyoViewer\n}\n\n/**\n * Check an existing currentAttempt for inclusion or expiration. Mutates `state` in place\n * (and writes it back) on either resolution. Leaves currentAttempt untouched if the attempt\n * is still in window.\n */\nasync function tryResumeCurrentAttempt(ctx: ResumeContext): Promise<void> {\n const {\n fulfillmentMap, identity, job, state, viewer,\n } = ctx\n const attempt = assertEx(state.currentAttempt, () => 'tryResumeCurrentAttempt called without currentAttempt')\n const found = await viewer.transaction.byHash(attempt.txHash)\n if (isDefined(found) && !isNull(found)) {\n state.fulfilled = attempt\n state.currentAttempt = undefined\n await fulfillmentMap.set(identity, state)\n await job.log(`[${identity}] tx ${attempt.txHash} included on resume`)\n return\n }\n const head = await viewer.currentBlockNumber()\n if (head > attempt.exp) {\n state.previousAttempts.push(attempt)\n state.currentAttempt = undefined\n await fulfillmentMap.set(identity, state)\n await job.log(`[${identity}] resumed attempt expired (head=${head}); will build fresh`)\n }\n}\n\ninterface BuildSubmitContext extends ResumeContext {\n account: AccountInstance\n bridgeId: bigint\n /** Live BridgeConfig read at fulfillment time \u2014 fees are computed at settlement against\n * current rates, not snapshotted at scan time. */\n config: BridgeConfig\n contractAddress: Address\n evmChainId: Hex\n gateway: XyoGatewayRunner\n xl1ChainId: ChainId\n xl1TokenAddress: Hex\n}\n\n/**\n * Validate reserve balance, build a fresh tx with new nbf/exp, save state pre-broadcast,\n * then broadcast. On success, state.currentAttempt is populated. Throws retryable if\n * reserve is insufficient.\n */\nasync function buildAndSubmitFreshAttempt(ctx: BuildSubmitContext): Promise<void> {\n const {\n account, bridgeId, config, contractAddress, evmChainId,\n fulfillmentMap, gateway, identity, job, state, viewer, xl1ChainId, xl1TokenAddress,\n } = ctx\n const canonical = assertEx(state.canonical, () => 'buildAndSubmitFreshAttempt requires canonical')\n\n // Compute fees at current config (no snapshotting). srcAmount = canonical.amount; fees =\n // feeFixed + (srcAmount * feeRateBasisPoints / 10_000). Total reserve required is the\n // gross `amount` \u2014 the bridge wallet funds both the user's net credit AND the fees output.\n const fees = calculateBridgeFees(toHex(canonical.amount), getFeeStructure(config))\n const feesAmount = hexToBigInt(fees.feeFixed) + hexToBigInt(fees.feeVariable)\n const { feesAddress } = await getTransferAddresses(config)\n\n const sufficient = await validateSufficientXl1ReserveBalance({\n amount: canonical.amount,\n bridgeAccount: account,\n gateway,\n })\n if (!sufficient) {\n const msg = `[${identity}] XL1 reserve below required ${canonical.amount.toString()}; will retry`\n await job.log(msg)\n throw new Error(msg)\n }\n\n const head = await viewer.currentBlockNumber()\n const nbf = asXL1BlockNumber(head, true)\n const exp = asXL1BlockNumber(head + EXP_BLOCKS_AHEAD, true)\n const tx: SignedHydratedTransaction = await buildEthToXl1ReserveTx({\n amount: canonical.amount,\n bridgeAccount: account,\n bridgeId,\n destAddress: canonical.destAddress,\n evmChainId,\n evmContractAddress: contractAddress,\n evmSrcAddress: canonical.srcAddress,\n evmTokenAddress: canonical.destToken,\n evmTxHash: canonical.evmTxHash,\n exp,\n feesAddress,\n feesAmount,\n nbf,\n xl1ChainId,\n xl1TokenAddress,\n })\n const txHash: BrandedHash = await PayloadBuilder.hash(tx[0])\n\n // SAVE BEFORE BROADCAST. txHash equals the gateway's submission hash per the gateway\n // contract, so saving it pre-broadcast gives crash-recovery a polling key even if the\n // broadcast didn't return.\n state.currentAttempt = {\n exp: head + EXP_BLOCKS_AHEAD,\n nbf: head,\n submittedAt: Date.now(),\n txHash,\n }\n await fulfillmentMap.set(identity, state)\n\n await submitXl1Transaction(tx, [], gateway)\n await job.log(\n `[${identity}] attempt ${state.previousAttempts.length + 1} submitted: `\n + `txHash=${txHash} nbf=${head} exp=${head + EXP_BLOCKS_AHEAD}`,\n )\n}\n\n/**\n * Block in a polling loop until the active attempt is either included on chain or its exp\n * passes. On inclusion: mark fulfilled. On expiration: throw retryable so BullMQ schedules\n * another invocation with a fresh attempt.\n */\nasync function pollUntilIncludedOrExpired(ctx: ResumeContext): Promise<void> {\n const {\n fulfillmentMap, identity, job, state, viewer,\n } = ctx\n const attempt = assertEx(state.currentAttempt, () => 'pollUntilIncludedOrExpired requires currentAttempt')\n while (true) {\n const found = await viewer.transaction.byHash(attempt.txHash)\n if (isDefined(found) && !isNull(found)) {\n state.fulfilled = attempt\n state.currentAttempt = undefined\n await fulfillmentMap.set(identity, state)\n await job.log(`[${identity}] tx ${attempt.txHash} included`)\n return\n }\n const head = await viewer.currentBlockNumber()\n if (head > attempt.exp) {\n state.previousAttempts.push(attempt)\n state.currentAttempt = undefined\n await fulfillmentMap.set(identity, state)\n const msg = `[${identity}] attempt ${state.previousAttempts.length} expired (head=${head}, exp=${attempt.exp})`\n await job.log(msg)\n throw new Error(msg)\n }\n await delay(POLL_INTERVAL_MS)\n }\n}\n\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel, services?: IBridgeServiceCollection) => {\n const svc = assertEx(services, () => 'services not provided')\n const {\n account, bridgeFulfillmentMap, config, gateway,\n } = svc\n\n const worker = new Worker(\n queueName,\n async (job: Xl1ReserveTxFulfillmentJob) => {\n const {\n bridgeId, contractAddress, evmChainId, identity, xl1ChainId, xl1TokenAddress,\n } = job.data\n\n const initialState = await bridgeFulfillmentMap.get(identity)\n if (initialState?.fulfilled) {\n await job.log(`[${identity}] already fulfilled \u2014 skipping`)\n return\n }\n const state = assertEx(initialState, () => `[${identity}] no fulfillment state \u2014 Stage 1 did not run`)\n const canonical = assertEx(state.canonical, () => `[${identity}] canonical missing \u2014 Stage 1 did not write canonical`)\n\n // Manual-retry: clear stale failed marker. We're trying again.\n if (state.failed) {\n state.failed = undefined\n await bridgeFulfillmentMap.set(identity, state)\n }\n\n // Inbound min-amount gate. The EVM contract has no minimum-amount check\n // (LiquidityPoolBridge.bridgeToRemote only rejects zero / over-max), so deposits below\n // the configured floor reach here. Mark terminal-failed and surface via /status \u2014 the\n // funds remain in the EVM-side liquiditySource reserve, refundable out-of-band at\n // operator discretion.\n const minBridgeAmount = getMinBridgeAmount(config)\n if (!validateAmountMeetsMinBridgeAmount({ amount: canonical.amount, minBridgeAmount })) {\n state.failed = {\n at: Date.now(),\n reason: `below_min_bridge_amount: amount=${canonical.amount} minBridgeAmount=${minBridgeAmount}`,\n }\n await bridgeFulfillmentMap.set(identity, state)\n await job.log(`[${identity}] amount ${canonical.amount} below minBridgeAmount ${minBridgeAmount}; terminal`)\n return\n }\n\n const viewer = assertEx(gateway.connection.viewer, () => `[${identity}] gateway viewer not available`)\n\n const ctx: ResumeContext = {\n fulfillmentMap: bridgeFulfillmentMap,\n identity,\n job,\n state,\n viewer,\n }\n\n if (state.currentAttempt) {\n await tryResumeCurrentAttempt(ctx)\n if (state.fulfilled) return\n }\n\n if (!state.currentAttempt) {\n await buildAndSubmitFreshAttempt({\n ...ctx,\n account,\n bridgeId: BigInt(bridgeId),\n config,\n contractAddress,\n evmChainId,\n gateway,\n xl1ChainId,\n xl1TokenAddress,\n })\n }\n\n await pollUntilIncludedOrExpired(ctx)\n },\n {\n concurrency: CONCURRENCY,\n connection,\n prefix,\n telemetry,\n },\n )\n\n // Permanent-failure marker. BullMQ retries until job.attemptsMade >= job.opts.attempts;\n // after that the job is permanently failed. Record state.failed so the status route\n // returns 504 with reason. Manual retry from BullBoard clears state.failed in the\n // worker's entry path and re-runs the cycle.\n worker.on('failed', async (job, err) => {\n if (!isDefined(job)) return\n const attemptsAllowed = job.opts.attempts ?? Infinity\n if (job.attemptsMade < attemptsAllowed) return\n const identity = job.data?.identity\n if (!isDefined(identity)) return\n const state = await bridgeFulfillmentMap.get(identity)\n if (!isDefined(state)) return\n state.failed = {\n at: Date.now(),\n reason: `attempts exhausted (${job.attemptsMade}/${attemptsAllowed}): ${err.message}`,\n }\n await bridgeFulfillmentMap.set(identity, state)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const Xl1ReserveTxFulfillment: WorkerDescription = {\n createWorker, name, queueName,\n}\n", "import type { Job } from 'bullmq'\nimport { Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport { prefix } from '../prefix.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\nimport type { Xl1DataLakeTransactionJobData } from './Xl1TransactionJobData.ts'\n\nexport type Xl1ToEthBridgeParentJobData = Xl1DataLakeTransactionJobData\nexport interface Xl1ToEthBridgeParentJobReturn { }\nexport type Xl1ToEthBridgeParentJob = Job<Xl1ToEthBridgeParentJobData, Xl1ToEthBridgeParentJobReturn>\n\nconst name = 'Bridge XL1 to Ethereum'\nconst queueName = 'xl1-to-eth-bridge'\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel) => {\n const worker = new Worker(\n queueName,\n async (job: Xl1ToEthBridgeParentJob) => {\n await job.log(`[${job.name}] start`)\n // Parent job has no work other than waiting on children\n await job.log(`[${job.name}] done`)\n return {}\n },\n {\n connection, telemetry, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const Xl1ToEthBridgeParent: WorkerDescription = {\n createWorker, name, queueName,\n}\n", "import type { BrandedHash } from '@xylabs/sdk-js'\nimport {\n assertEx, isDefined, isNull,\n} from '@xylabs/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type { Job } from 'bullmq'\nimport { UnrecoverableError, Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport type { IBridgeServiceCollection } from '../../index.ts'\nimport { prefix } from '../prefix.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\nimport type { Xl1TransactionJobData } from './Xl1TransactionJobData.ts'\n\nexport type Xl1TransactionMonitorJobData = Xl1TransactionJobData\nexport interface Xl1TransactionMonitorJobReturn {\n submissionHash: BrandedHash\n}\nexport type Xl1TransactionMonitorJob = Job<Xl1TransactionMonitorJobData, Xl1TransactionMonitorJobReturn>\n\nconst name = 'Monitor Submitted XL1 Transaction'\nconst queueName = 'xl1-tx-monitor'\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel, services?: IBridgeServiceCollection) => {\n const gateway = assertEx(services?.gateway, () => 'gateway service not provided')\n const stateMap = assertEx(services?.xl1TxStateMap, () => 'xl1TxStateMap service not provided')\n const viewer = assertEx(gateway.connection.viewer, () => 'viewer not defined on gateway')\n\n const worker = new Worker(\n queueName,\n async (job: Xl1TransactionMonitorJob) => {\n const { tx } = job.data\n // Get the hash of the transaction\n const hash = await PayloadBuilder.hash(tx[0])\n // Get the state of the transaction\n const state = assertEx(await stateMap.get(hash), () => `[${hash}] state not found`)\n const submissionHash = assertEx(state.submissionHash, () => `[${hash}] submissionHash not found`)\n\n // Check for transaction inclusion on chain\n await job.log(`[${hash}] Checking for XL1 transaction inclusion on chain`)\n const foundTx = await viewer.transaction.byHash(submissionHash)\n // const foundTx = await viewer.transaction.byHash(submissionHash)\n\n // Transaction found on chain\n if (isDefined(foundTx) && !isNull(foundTx)) {\n await job.log(`[${hash}] Found transaction on chain`)\n // Store the block hash\n const submissionHash = await PayloadBuilder.hash(foundTx[0])\n return { submissionHash }\n }\n\n // Check for transaction expiration\n const currentBlockNumber = await viewer.currentBlockNumber()\n if (tx[0].exp < currentBlockNumber) {\n await job.log(\n `[${hash}] Transaction expired at block ${tx[0].exp}, current block ${currentBlockNumber}`,\n )\n // Throw unrecoverable error to stop retries\n throw new UnrecoverableError(`[${hash}] Transaction expired and will never be included`)\n }\n\n // Transaction not yet found, but still valid \u2014 retry later\n await job.log(`[${hash}] Transaction not yet included, retrying later`)\n throw new Error(`[${hash}] Transaction not yet included`)\n },\n {\n connection, telemetry, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const Xl1TransactionMonitor: WorkerDescription = {\n createWorker, name, queueName,\n}\n", "import { assertEx } from '@xylabs/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type { SignedHydratedTransaction } from '@xyo-network/xl1-sdk'\nimport type { Job } from 'bullmq'\nimport { Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport type { IBridgeServiceCollection } from '../../index.ts'\nimport { prefix } from '../prefix.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\nimport type { Xl1DataLakeTransactionJobData } from './Xl1TransactionJobData.ts'\n\nexport type Xl1TransactionPreparationJobData = Xl1DataLakeTransactionJobData\nexport interface Xl1TransactionPreparationJobReturn { preparedTx: SignedHydratedTransaction }\nexport type Xl1TransactionPreparationJob = Job<Xl1TransactionPreparationJobData, Xl1TransactionPreparationJobReturn>\n\nconst name = 'Prepare XL1 Transaction'\nconst queueName = 'xl1-tx-prepare'\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel, services?: IBridgeServiceCollection) => {\n const stateMap = assertEx(services?.xl1TxStateMap, () => 'xl1TxStateMap service not provided')\n\n const worker = new Worker(\n queueName,\n async (job: Xl1TransactionPreparationJob) => {\n const { tx, offChainPayloads = [] } = job.data\n const hash = await PayloadBuilder.hash(tx[0])\n await job.log(`[${hash}] preparing XL1 transaction`)\n const preparedTx = tx\n await job.log(`[${hash}] storing XL1 preparedTx`)\n await stateMap.set(hash, { offChainPayloads, preparedTx })\n await job.log(`[${hash}] stored XL1 preparedTx`)\n await job.log(`[${hash}] prepared XL1 transaction`)\n return { preparedTx }\n },\n {\n connection, telemetry, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const Xl1TransactionPreparation: WorkerDescription = {\n createWorker, name, queueName,\n}\n", "import { assertEx, isDefined } from '@xylabs/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type { Job } from 'bullmq'\nimport { Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport type { IBridgeServiceCollection, Xl1TxState } from '../../index.ts'\nimport { prefix } from '../prefix.ts'\nimport { submitXl1Transaction } from './util/index.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\nimport type { Xl1TransactionJobData } from './Xl1TransactionJobData.ts'\n\nexport type Xl1TransactionSubmissionJobData = Xl1TransactionJobData\nexport interface Xl1TransactionSubmissionJobReturn {\n submissionHash: Required<Xl1TxState>['submissionHash']\n}\nexport type Xl1TransactionSubmissionJob = Job<Xl1TransactionSubmissionJobData, Xl1TransactionSubmissionJobReturn>\n\nconst name = 'Submit XL1 Transaction'\nconst queueName = 'xl1-tx-submit'\n\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel, services?: IBridgeServiceCollection) => {\n const gateway = assertEx(services?.gateway, () => 'gateway service not provided')\n const stateMap = assertEx(services?.xl1TxStateMap, () => 'xl1TxStateMap service not provided')\n\n const worker = new Worker(\n queueName,\n async (job: Xl1TransactionSubmissionJob) => {\n const { tx } = job.data\n // Get the hash of the transaction\n const hash = await PayloadBuilder.hash(tx[0])\n // Get the state of the transaction\n const state = assertEx(await stateMap.get(hash), () => `[${hash}] state not found`)\n const {\n preparedTx, offChainPayloads = [], submissionHash: existingSubmissionHash,\n } = state\n\n // Idempotency check against resubmission\n if (isDefined(existingSubmissionHash)) {\n await job.log(`[${hash}] Tx already submitted with submission response hash ${existingSubmissionHash}`)\n return { submissionHash: existingSubmissionHash }\n }\n const txToSubmit = assertEx(preparedTx, () => `[${hash}] preparedTx not found`)\n\n // Submit the transaction to the XL1 network\n await job.log(`[${hash}] Submitting XL1 tx`)\n const [submissionHash] = await submitXl1Transaction(txToSubmit, offChainPayloads, gateway)\n await job.log(`[${hash}] Submitted XL1 tx`)\n\n // This worker intentionally does NOT store state as subsequent steps will do that.\n return { submissionHash }\n },\n {\n connection, telemetry, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const Xl1TransactionSubmission: WorkerDescription = {\n createWorker, name, queueName,\n}\n", "import { assertEx, isDefined } from '@xylabs/sdk-js'\nimport { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type { Job } from 'bullmq'\nimport { Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport type { IBridgeServiceCollection, Xl1TxState } from '../../index.ts'\nimport { prefix } from '../prefix.ts'\nimport type { WorkerDescription } from './WorkerDescription.ts'\nimport type { Xl1TransactionJobData } from './Xl1TransactionJobData.ts'\nimport type { Xl1TransactionSubmissionJobReturn } from './Xl1TransactionSubmission.ts'\nimport { Xl1TransactionSubmission } from './Xl1TransactionSubmission.ts'\n\nexport type Xl1TransactionSubmissionStorageJobData = Xl1TransactionJobData\nexport interface Xl1TransactionSubmissionStorageJobReturn {\n submissionHash: Required<Xl1TxState>['submissionHash']\n}\nexport type Xl1TransactionSubmissionStorageJob = Job<Xl1TransactionSubmissionStorageJobData, Xl1TransactionSubmissionStorageJobReturn>\n\nconst name = 'Store XL1 Transaction Submission'\nconst queueName = 'xl1-tx-store-submission'\n\nconst createWorker = (connection: Redis, telemetry?: BullMQOtel, services?: IBridgeServiceCollection) => {\n const stateMap = assertEx(services?.xl1TxStateMap, () => 'xl1TxStateMap service not provided')\n\n const worker = new Worker(\n queueName,\n async (job: Xl1TransactionSubmissionStorageJob) => {\n const { tx } = job.data\n // Get the hash of the transaction\n const hash = await PayloadBuilder.hash(tx[0])\n\n // Get the state of the transaction\n const state = assertEx(await stateMap.get(hash), () => `[${hash}] state not found`)\n\n // Idempotency check against re-store\n const { submissionHash: existingSubmissionHash } = state\n if (isDefined(existingSubmissionHash)) {\n await job.log(`[${hash}] submissionHash already stored as ${existingSubmissionHash}`)\n return { submissionHash: existingSubmissionHash }\n }\n\n // In a Flow, this job should be the PARENT and the submit job should be a CHILD.\n // That lets us read the child job\u2019s return value(s) here.\n const childrenValues = await job.getChildrenValues()\n const jobKey = `${prefix}:${Xl1TransactionSubmission.queueName}:${hash}`\n const childValues = childrenValues?.[jobKey] as Xl1TransactionSubmissionJobReturn | undefined\n const submissionHash = childValues?.submissionHash\n\n const resolvedSubmissionHash = assertEx(submissionHash, () => `[${hash}] child submissionHash not found in children values`)\n\n // Store the submission hash in the state\n await job.log(`[${hash}] Storing XL1 submissionHash`)\n state.submissionHash = resolvedSubmissionHash\n await stateMap.set(hash, state)\n await job.log(`[${hash}] Stored XL1 submissionHash`)\n\n return { submissionHash: resolvedSubmissionHash }\n },\n {\n connection, telemetry, prefix,\n },\n )\n\n worker.on('failed', (job, err) => {\n console.error(`[${name}] Job ${job?.id} failed:`, err.message)\n })\n\n worker.on('error', (err) => {\n console.error(`[${name}] Worker error:`, err)\n })\n}\n\nexport const Xl1TransactionSubmissionStorage: WorkerDescription = {\n createWorker, name, queueName,\n}\n", "import type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport type { IBridgeServiceCollection } from '../../index.ts'\nimport { EthEventVerification } from './EthEventVerification.ts'\nimport { EthToXl1BridgeParent } from './EthToXl1BridgeParent.ts'\nimport { EthTransactionMonitor } from './EthTransactionMonitor.ts'\nimport { EthTransactionPreparation } from './EthTransactionPreparation.ts'\nimport { EthTransactionSubmission } from './EthTransactionSubmission.ts'\nimport { EthTransactionSubmissionStorage } from './EthTransactionSubmissionStorage.ts'\nimport { Xl1ReserveTxFulfillment } from './Xl1ReserveTxFulfillment.ts'\nimport { Xl1ToEthBridgeParent } from './Xl1ToEthBridgeParent.ts'\nimport { Xl1TransactionMonitor } from './Xl1TransactionMonitor.ts'\nimport { Xl1TransactionPreparation } from './Xl1TransactionPreparation.ts'\nimport { Xl1TransactionSubmission } from './Xl1TransactionSubmission.ts'\nimport { Xl1TransactionSubmissionStorage } from './Xl1TransactionSubmissionStorage.ts'\n\n// EVM\u2192XL1 path: EthEventVerification (Stage 1) \u2192 Xl1ReserveTxFulfillment (Stage 2)\n// \u2192 EthToXl1BridgeParent (top, no-op coordinator).\n// XL1\u2192EVM path: Xl1Transaction* + EthTransaction* sequence under Xl1ToEthBridgeParent.\n// The Xl1Transaction*/EthTransaction* workers are direction-agnostic \u2014 they take a signed\n// tx and submit/monitor it \u2014 so they remain registered for the XL1\u2192EVM flow even though\n// the EVM\u2192XL1 flow no longer uses them.\nexport const createWorkers = (connection: Redis, telemetry: BullMQOtel, services: IBridgeServiceCollection) => {\n EthEventVerification.createWorker(connection, telemetry, services)\n EthToXl1BridgeParent.createWorker(connection, telemetry)\n EthTransactionMonitor.createWorker(connection, telemetry, services)\n EthTransactionPreparation.createWorker(connection, telemetry, services)\n EthTransactionSubmission.createWorker(connection, telemetry, services)\n EthTransactionSubmissionStorage.createWorker(connection, telemetry, services)\n Xl1ReserveTxFulfillment.createWorker(connection, telemetry, services)\n Xl1ToEthBridgeParent.createWorker(connection, telemetry)\n Xl1TransactionMonitor.createWorker(connection, telemetry, services)\n Xl1TransactionPreparation.createWorker(connection, telemetry, services)\n Xl1TransactionSubmission.createWorker(connection, telemetry, services)\n Xl1TransactionSubmissionStorage.createWorker(connection, telemetry, services)\n}\n", "import type { Address, Hex } from '@xylabs/sdk-js'\n\nexport interface EthToXl1BridgeJobIdContext {\n /** The LiquidityPoolBridge contract's `bridgeToRemote` counter \u2014 assigned by\n * `nextBridgeToId++` and stored at `bridgesToRemote[bridgeId]`. Source of truth is\n * contract storage, not the event log. */\n bridgeId: bigint\n contractAddress: Address\n evmChainId: Hex\n}\n\n/**\n * Deterministic BullMQ jobId for an EVM\u2192XL1 bridge flow. The id is derived from the\n * contract-assigned bridge id so that:\n * - The same (chainId, contract, bridgeId) always maps to the same job \u2014 BullMQ will\n * dedup duplicate enqueues automatically (e.g. if the scanner runs across the same\n * bridge id during backfill).\n * - The status route can derive the jobId from the URL `:id` parameter without\n * touching the contract or hashing a transaction.\n * - Replay is the same id; manual `Job.retry()` re-runs the existing job rather than\n * creating a parallel one.\n *\n * Both hex-string components are lowercased for a single canonical form. The bridgeId is\n * a uint256, so it's stringified as decimal.\n */\nexport function getJobIdForEthToXl1BridgeJob(context: EthToXl1BridgeJobIdContext): string {\n return `evm-${context.evmChainId.toLowerCase()}-${context.contractAddress.toLowerCase()}-${context.bridgeId.toString()}`\n}\n", "import type { Address, Hex } from '@xylabs/sdk-js'\nimport type { ChainId } from '@xyo-network/xl1-sdk'\nimport type { FlowProducer } from 'bullmq'\n\nimport {\n EthEventVerification, EthToXl1BridgeParent, Xl1ReserveTxFulfillment,\n} from '../../workers/index.ts'\nimport { getJobIdForEthToXl1BridgeJob } from './getJobIdForEthToXl1BridgeJob.ts'\n\nexport interface EthToXl1BridgeJobContext {\n /** The LiquidityPoolBridge contract's bridgeToRemote counter. */\n bridgeId: bigint\n /** EVM bridge contract address. */\n contractAddress: Address\n /** EVM chain id. */\n evmChainId: Hex\n /** XL1 chain id (resolved from config at scan time). */\n xl1ChainId: ChainId\n /** XL1 token \"address\" (chain id of the token, resolved from config at scan time). */\n xl1TokenAddress: Hex\n}\n\n// Stage 2 carries the long-running retry posture: 1000 attempts \u00D7 10s fixed backoff per\n// the design spec. Each attempt is one full submission cycle (build \u2192 submit \u2192 poll until\n// included or expired), so 1000 retries is \"keep trying until ops intervenes.\" Linear or\n// exponential growth is a polish item to evaluate when we have outage data; for MVP fixed\n// 10s avoids the multi-day total backoff that pure linear would produce.\nconst STAGE_2_RETRY = {\n attempts: 1000,\n backoff: {\n delay: 10_000,\n type: 'fixed' as const,\n },\n}\n\n// Stage 1 is one-shot. UnrecoverableError on null-at-depth, no transient retry path.\nconst STAGE_1_RETRY = { attempts: 1 }\n\n/**\n * Creates the three-tier BullMQ flow for an EVM\u2192XL1 bridge:\n *\n * eth-to-xl1-bridge (top \u2014 no-op coordinator, completes when children done)\n * \u2514\u2500 eth-to-xl1-fulfill (Stage 2 \u2014 build/submit/poll, 1000 attempts \u00D7 10s backoff)\n * \u2514\u2500 eth-event-verify (Stage 1 \u2014 verify once, write canonical, deepest-first)\n *\n * All three jobs share the same jobId from getJobIdForEthToXl1BridgeJob \u2014 the deterministic\n * `evm-{chainId}-{contract}-{bridgeId}` form. That id IS the bridge's immutable identity:\n * - BullMQ dedup makes scanner re-enqueues no-ops automatically.\n * - The status route reconstructs the jobId from the URL parameter without contract reads.\n * - Manual retry from BullBoard re-runs the *same* job rather than creating a parallel one.\n *\n * Stage 1 (deepest child) runs first per BullMQ flow semantics. It writes `canonical` to\n * bridgeFulfillmentMap. Stage 2 reads it from there. The two stages don't communicate via\n * children-values \u2014 the state map is their contract.\n */\nexport const createEthToXl1BridgeJob = async (\n flowProducer: FlowProducer,\n context: EthToXl1BridgeJobContext,\n) => {\n const jobId = getJobIdForEthToXl1BridgeJob(context)\n const identity = jobId\n\n const stageJobData = {\n bridgeId: context.bridgeId.toString(),\n contractAddress: context.contractAddress,\n evmChainId: context.evmChainId,\n identity,\n xl1ChainId: context.xl1ChainId,\n xl1TokenAddress: context.xl1TokenAddress,\n }\n\n return flowProducer.add({\n name: EthToXl1BridgeParent.name,\n queueName: EthToXl1BridgeParent.queueName,\n data: stageJobData,\n opts: { jobId },\n children: [\n {\n name: Xl1ReserveTxFulfillment.name,\n queueName: Xl1ReserveTxFulfillment.queueName,\n data: stageJobData,\n opts: { jobId, ...STAGE_2_RETRY },\n children: [\n {\n name: EthEventVerification.name,\n queueName: EthEventVerification.queueName,\n data: stageJobData,\n opts: { jobId, ...STAGE_1_RETRY },\n },\n ],\n },\n ],\n })\n}\n", "import { PayloadBuilder } from '@xyo-network/sdk-js'\nimport type { SignedHydratedTransaction } from '@xyo-network/xl1-sdk'\n\n/**\n * Returns a deterministic & repeatable job ID based off the Transaction hash. This is to ensure\n * that if the same transaction is attempted to be bridged multiple times, it will have the same\n * job ID and not create duplicate jobs.\n * https://docs.bullmq.io/guide/jobs/job-ids\n * \"The main reason to be able to specify a custom id is in cases when you want to avoid duplicated\n * jobs. Since ids must be unique, if you add a job with an existing id then that job will just be\n * ignored and not added to the queue at all.\"\n * @param tx The transaction to bridge from XL1 to ETH\n * @returns A deterministic job ID for the bridge job\n */\nexport const getJobIdForXl1ToEthBridgeJob = async (tx: SignedHydratedTransaction) => {\n const jobId = await PayloadBuilder.hash(tx[0])\n return jobId\n}\n", "import type { Payload } from '@xyo-network/sdk-js'\nimport type { SignedHydratedTransaction } from '@xyo-network/xl1-sdk'\nimport type { FlowProducer } from 'bullmq'\n\nimport type {\n EthTransactionMonitorJobData,\n EthTransactionPreparationJobData,\n EthTransactionSubmissionJobData,\n EthTransactionSubmissionStorageJobData,\n Xl1ToEthBridgeParentJobData,\n Xl1TransactionMonitorJobData,\n Xl1TransactionPreparationJobData,\n Xl1TransactionSubmissionJobData,\n Xl1TransactionSubmissionStorageJobData,\n} from '../../workers/index.ts'\nimport {\n EthTransactionMonitor, EthTransactionPreparation, EthTransactionSubmission, EthTransactionSubmissionStorage, Xl1ToEthBridgeParent, Xl1TransactionMonitor,\n Xl1TransactionPreparation, Xl1TransactionSubmission, Xl1TransactionSubmissionStorage,\n} from '../../workers/index.ts'\nimport { getJobIdForXl1ToEthBridgeJob } from './getJobIdForXl1ToEthBridgeJob.ts'\n\n/**\n * Creates a job flow for bridging a transaction from XL1 to Ethereum.\n * @param flowProducer The flow producer to run the job\n * @param tx The bridge transaction\n * @param offChainPayloads The payloads to put off chain\n * @returns The JobNode representing the XL1 to ETH bridge job\n */\nexport const createXl1ToEthBridgeJob = async (\n flowProducer: FlowProducer,\n tx: SignedHydratedTransaction,\n offChainPayloads: Payload[] = [],\n) => {\n const jobId = await getJobIdForXl1ToEthBridgeJob(tx)\n const flow = await flowProducer.add({\n // Step 0 (runs first as parent job)\n name: Xl1ToEthBridgeParent.name,\n queueName: Xl1ToEthBridgeParent.queueName,\n data: { tx, offChainPayloads } as Xl1ToEthBridgeParentJobData,\n opts: { jobId },\n children: [\n {\n // Step 8\n name: EthTransactionMonitor.name,\n queueName: EthTransactionMonitor.queueName,\n data: { tx } as EthTransactionMonitorJobData,\n opts: {\n jobId, attempts: 60, backoff: { type: 'fixed', delay: 5000 },\n },\n children: [\n {\n // Step 7\n name: EthTransactionSubmissionStorage.name,\n queueName: EthTransactionSubmissionStorage.queueName,\n data: { tx } as EthTransactionSubmissionStorageJobData,\n opts: {\n jobId, attempts: 60, backoff: { type: 'fixed', delay: 5000 },\n },\n children: [\n {\n // Step 6\n name: EthTransactionSubmission.name,\n queueName: EthTransactionSubmission.queueName,\n data: { tx, offChainPayloads } as EthTransactionSubmissionJobData,\n opts: { jobId },\n children: [\n {\n // Step 5\n name: EthTransactionPreparation.name,\n queueName: EthTransactionPreparation.queueName,\n data: { tx, offChainPayloads } as EthTransactionPreparationJobData,\n opts: {\n jobId, attempts: 60, backoff: { type: 'fixed', delay: 5000 },\n },\n children: [\n {\n // Step 4\n name: Xl1TransactionMonitor.name,\n queueName: Xl1TransactionMonitor.queueName,\n data: { tx } as Xl1TransactionMonitorJobData,\n opts: {\n jobId, attempts: 60, backoff: { type: 'fixed', delay: 5000 },\n },\n children: [\n {\n // Step 3\n name: Xl1TransactionSubmissionStorage.name,\n queueName: Xl1TransactionSubmissionStorage.queueName,\n data: { tx } as Xl1TransactionSubmissionStorageJobData,\n opts: {\n jobId, attempts: 60, backoff: { type: 'fixed', delay: 5000 },\n },\n children: [\n {\n // Step 2\n name: Xl1TransactionSubmission.name,\n queueName: Xl1TransactionSubmission.queueName,\n data: { tx } as Xl1TransactionSubmissionJobData,\n opts: { jobId },\n children: [\n {\n // Step 1 (runs first as deepest child)\n name: Xl1TransactionPreparation.name,\n queueName: Xl1TransactionPreparation.queueName,\n data: { tx, offChainPayloads } as Xl1TransactionPreparationJobData,\n opts: {\n jobId, attempts: 60, backoff: { type: 'fixed', delay: 5000 },\n },\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n })\n return flow\n}\n", "import type { SignedHydratedTransaction } from '@xyo-network/xl1-sdk'\nimport type { FlowProducer } from 'bullmq'\n\nimport { Xl1ToEthBridgeParent } from '../../workers/index.ts'\nimport { getJobIdForXl1ToEthBridgeJob } from './getJobIdForXl1ToEthBridgeJob.ts'\n\nexport const getXl1ToEthBridgeJob = async (flowProducer: FlowProducer, tx: SignedHydratedTransaction) => {\n const id = await getJobIdForXl1ToEthBridgeJob(tx)\n const flow = await flowProducer.getFlow({ queueName: Xl1ToEthBridgeParent.queueName, id })\n return flow\n}\n", "import type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { Queue } from 'bullmq'\n\nimport { getConnection } from './connection.ts'\nimport { prefix } from './prefix.ts'\nimport {\n EthEventVerification, EthToXl1BridgeParent, Xl1ReserveTxFulfillment,\n} from './workers/index.ts'\n\nexport interface EthToXl1Queues {\n ethEventVerification: Queue\n ethToXl1BridgeParent: Queue\n xl1ReserveTxFulfillment: Queue\n}\n\nlet ethToXl1Queues: EthToXl1Queues | undefined\n\n/**\n * Lazily-constructed Queue handles for the EVM\u2192XL1 direction. Used by the status route to\n * look up flow progress and (eventually) by createQueueMetrics for telemetry. Singleton-cached\n * so repeated calls don't re-create connections.\n *\n * Three queues, matching the three-tier flow under Path A:\n * - ethToXl1BridgeParent \u2014 no-op coordinator (presence \u21D2 flow exists)\n * - xl1ReserveTxFulfillment \u2014 Stage 2 build/submit/poll\n * - ethEventVerification \u2014 Stage 1 canonical verify (deepest child)\n *\n * The XL1Transaction* / EthTransaction* queues that the old EVM\u2192XL1 flow shared with the\n * XL1\u2192EVM direction are now used only by the XL1\u2192EVM flow; they're listed in\n * `getXl1ToEthQueues` and don't belong here.\n */\nexport const getEthToXl1Queues = (config: BridgeConfig): EthToXl1Queues => {\n if (ethToXl1Queues) return ethToXl1Queues\n const connection = getConnection(config)\n ethToXl1Queues = {\n ethEventVerification: new Queue(EthEventVerification.queueName, { connection, prefix }),\n ethToXl1BridgeParent: new Queue(EthToXl1BridgeParent.queueName, { connection, prefix }),\n xl1ReserveTxFulfillment: new Queue(Xl1ReserveTxFulfillment.queueName, { connection, prefix }),\n }\n return ethToXl1Queues\n}\n", "import type { Xl1ToEthQueues } from './getXl1ToEthQueues.ts'\nimport type {\n EthTransactionMonitorJob, EthTransactionPreparationJob,\n EthTransactionSubmissionJob,\n Xl1ToEthBridgeParentJob,\n Xl1TransactionMonitorJob, Xl1TransactionPreparationJob, Xl1TransactionSubmissionJob,\n Xl1TransactionSubmissionStorageJob,\n} from './workers/index.ts'\n\nexport interface StatusQueueJobs {\n ethTransactionMonitorJob?: EthTransactionMonitorJob\n ethTransactionPreparationJob?: EthTransactionPreparationJob\n ethTransactionSubmissionJob?: EthTransactionSubmissionJob\n xl1ToEthBridgeParentJob?: Xl1ToEthBridgeParentJob\n xl1TransactionMonitorJob?: Xl1TransactionMonitorJob\n xl1TransactionPreparationJob?: Xl1TransactionPreparationJob\n xl1TransactionSubmissionJob?: Xl1TransactionSubmissionJob\n xl1TransactionSubmissionStorageJob?: Xl1TransactionSubmissionStorageJob\n}\n\n/**\n * Checks all the relevant status queues for a job with the given id and returns the jobs found in an object\n * @param queues The status queues to check for jobs\n * @param jobId The job id to look for in the queues, which is the same as the tx hash of the bridge transaction\n * @returns An object containing the jobs found in the status queues corresponding to the given job id\n */\nexport const getStatusQueueJobs = async (queues: Xl1ToEthQueues, jobId: string): Promise<StatusQueueJobs> => {\n const [\n ethTransactionMonitorJob,\n ethTransactionPreparationJob,\n ethTransactionSubmissionJob,\n xl1ToEthBridgeParentJob,\n xl1TransactionMonitorJob,\n xl1TransactionPreparationJob,\n xl1TransactionSubmissionJob,\n xl1TransactionSubmissionStorageJob,\n ] = await Promise.all([\n queues.ethTransactionMonitor.getJob(jobId),\n queues.ethTransactionPreparation.getJob(jobId),\n queues.ethTransactionSubmission.getJob(jobId),\n queues.xl1ToEthBridgeParent.getJob(jobId),\n queues.xl1TransactionMonitor.getJob(jobId),\n queues.xl1TransactionPreparation.getJob(jobId),\n queues.xl1TransactionSubmission.getJob(jobId),\n queues.xl1TransactionSubmissionStorage.getJob(jobId),\n ])\n return {\n ethTransactionMonitorJob,\n ethTransactionPreparationJob,\n ethTransactionSubmissionJob,\n xl1ToEthBridgeParentJob,\n xl1TransactionMonitorJob,\n xl1TransactionPreparationJob,\n xl1TransactionSubmissionStorageJob,\n xl1TransactionSubmissionJob,\n }\n}\n", "import type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { Queue } from 'bullmq'\n\nimport { getConnection } from './connection.ts'\nimport { prefix } from './prefix.ts'\nimport {\n EthTransactionMonitor, EthTransactionPreparation, EthTransactionSubmission, Xl1ToEthBridgeParent, Xl1TransactionMonitor, Xl1TransactionPreparation,\n Xl1TransactionSubmission,\n Xl1TransactionSubmissionStorage,\n} from './workers/index.ts'\n\nexport interface Xl1ToEthQueues {\n ethTransactionMonitor: Queue\n ethTransactionPreparation: Queue\n ethTransactionSubmission: Queue\n xl1ToEthBridgeParent: Queue\n xl1TransactionMonitor: Queue\n xl1TransactionPreparation: Queue\n xl1TransactionSubmission: Queue\n xl1TransactionSubmissionStorage: Queue\n}\n\nlet xl1ToEthQueues: Xl1ToEthQueues | undefined\n\nexport const getXl1ToEthQueues = (config: BridgeConfig): Xl1ToEthQueues => {\n if (xl1ToEthQueues) return xl1ToEthQueues\n const connection = getConnection(config)\n xl1ToEthQueues = {\n ethTransactionMonitor: new Queue(EthTransactionMonitor.queueName, { connection, prefix }),\n ethTransactionPreparation: new Queue(EthTransactionPreparation.queueName, { connection, prefix }),\n ethTransactionSubmission: new Queue(EthTransactionSubmission.queueName, { connection, prefix }),\n xl1ToEthBridgeParent: new Queue(Xl1ToEthBridgeParent.queueName, { connection, prefix }),\n xl1TransactionMonitor: new Queue(Xl1TransactionMonitor.queueName, { connection, prefix }),\n xl1TransactionPreparation: new Queue(Xl1TransactionPreparation.queueName, { connection, prefix }),\n xl1TransactionSubmission: new Queue(Xl1TransactionSubmission.queueName, { connection, prefix }),\n xl1TransactionSubmissionStorage: new Queue(Xl1TransactionSubmissionStorage.queueName, { connection, prefix }),\n }\n return xl1ToEthQueues\n}\n", "import type { Address, Hex } from '@xylabs/sdk-js'\nimport type { ChainId } from '@xyo-network/xl1-sdk'\nimport type { FlowProducer } from 'bullmq'\n\nimport { createEthToXl1BridgeJob } from '../flows/index.ts'\nimport type { EvmBridgeJobLog, EvmBridgeScannerEnqueue } from './EvmBridgeScanner.ts'\n\nexport interface CreateEnqueueEthToXl1BridgeOptions {\n evmChainId: Hex\n evmContractAddress: Address\n flowProducer: FlowProducer\n xl1ChainId: ChainId\n xl1TokenAddress: Hex\n}\n\n/**\n * Builds the production enqueue callback the EVM->XL1 scanner hands each new bridgeId.\n *\n * Path A (MVP) split: the scanner is now pure cursor + enqueue. All chain reads beyond the\n * scanner's own cursor advance happen *inside* the BullMQ flow:\n * - Stage 1 (`EthEventVerification`, deepest child) reads `bridgesToRemote(id)` at depth\n * and writes the canonical fulfillment record. A null slot at depth means orphaned and\n * terminally fails the flow without any reserve-side work.\n * - Stage 2 (`Xl1ReserveTxFulfillment`) consumes the canonical record and runs the\n * build/submit/poll cycle with its own retry posture.\n *\n * Why scanner-side verify was removed: keeping it here as a \"skip orphans\" gate produced\n * two divergent code paths for the same canonical-data read. Stage 1 already does the read\n * idempotently, and BullMQ dedups on the deterministic jobId \u2014 re-ticking over an already\n * enqueued id is a no-op. Letting Stage 1 own the verification keeps the scanner cheap\n * (one cursor read per tick) and the orphan-handling logic in one place.\n */\nexport function createEnqueueEthToXl1Bridge(options: CreateEnqueueEthToXl1BridgeOptions): EvmBridgeScannerEnqueue {\n const {\n evmChainId,\n evmContractAddress,\n flowProducer,\n xl1ChainId,\n xl1TokenAddress,\n } = options\n\n return async (bridgeId: bigint, jobLog?: EvmBridgeJobLog): Promise<void> => {\n await createEthToXl1BridgeJob(flowProducer, {\n bridgeId,\n contractAddress: evmContractAddress,\n evmChainId,\n xl1ChainId,\n xl1TokenAddress,\n })\n await jobLog?.(`[bridge-scanner] bridgeId ${bridgeId} enqueued`)\n }\n}\n", "import type { Address, Hex } from '@xylabs/sdk-js'\nimport { isUndefined } from '@xylabs/sdk-js'\nimport type { LiquidityPoolBridge } from '@xyo-network/typechain'\nimport type { IterableMap } from '@xyo-network/xl1-sdk'\nimport type { Provider } from 'ethers'\n\nimport type { EvmConfirmationDepth } from '../../evm/index.ts'\nimport { resolveEvmBlockTagAtDepth } from '../workers/util/index.ts'\nimport type { EvmBridgeCursor } from './EvmBridgeCursor.ts'\nimport { getEvmBridgeCursorKey } from './EvmBridgeCursor.ts'\n\n/**\n * Per-tick log adapter \u2014 typically `(msg) => job.log(msg)` from the BullMQ Worker\n * processor that drives the scanner. Lets the scanner and the enqueue callback record\n * lines into the current tick's BullMQ job log so they're visible per-tick in dashboards.\n * Optional so the scanner remains usable without BullMQ context (tests, scripts).\n */\nexport type EvmBridgeJobLog = (message: string) => Promise<unknown>\n\nexport type EvmBridgeScannerEnqueue = (id: bigint, jobLog?: EvmBridgeJobLog) => Promise<void> | void\n\nexport interface EvmBridgeScannerOptions {\n bridge: LiquidityPoolBridge\n bridgeAddress: Address\n chainId: Hex\n confirmationDepth: EvmConfirmationDepth\n cursors: IterableMap<string, EvmBridgeCursor>\n enqueue: EvmBridgeScannerEnqueue\n provider: Provider\n}\n\nexport interface EvmBridgeScanOptions {\n jobLog?: EvmBridgeJobLog\n}\n\nexport interface EvmBridgeScanResult {\n confirmedHigh: bigint\n enqueued: number\n lastProcessedId: bigint\n}\n\nexport interface EvmBridgeScanner {\n scan(options?: EvmBridgeScanOptions): Promise<EvmBridgeScanResult>\n}\n\nexport function createEvmBridgeScanner(options: EvmBridgeScannerOptions): EvmBridgeScanner {\n const {\n bridge, bridgeAddress, chainId, confirmationDepth, cursors, enqueue, provider,\n } = options\n const cursorKey = getEvmBridgeCursorKey(chainId, bridgeAddress)\n\n return {\n async scan(options?: EvmBridgeScanOptions): Promise<EvmBridgeScanResult> {\n const jobLog = options?.jobLog\n const blockTag = await resolveEvmBlockTagAtDepth(provider, confirmationDepth)\n const confirmedHigh = await bridge.nextBridgeToId({ blockTag })\n\n const cursor = await cursors.get(cursorKey)\n const lastProcessedId = isUndefined(cursor) ? 0n : BigInt(cursor.lastProcessedId)\n\n if (confirmedHigh <= lastProcessedId) {\n return {\n confirmedHigh,\n enqueued: 0,\n lastProcessedId,\n }\n }\n\n let enqueued = 0\n for (let id = lastProcessedId + 1n; id <= confirmedHigh; id++) {\n await enqueue(id, jobLog)\n enqueued++\n }\n\n await cursors.set(cursorKey, { lastProcessedId: confirmedHigh.toString() })\n return {\n confirmedHigh,\n enqueued,\n lastProcessedId,\n }\n },\n }\n}\n", "import type { Address, Hex } from '@xylabs/sdk-js'\n\n// Tracks how far an EVM bridge contract has been scanned. Stored in a persistent IterableMap\n// keyed by getEvmBridgeCursorKey(chainId, contractAddress) so a service restart resumes\n// where it left off rather than re-enqueuing every historical event.\n//\n// `lastProcessedId` is the highest BridgedToRemote id (a uint256 from the contract's\n// nextBridgeToId counter) that has been observed at confirmation depth and handed to the\n// enqueue callback. Stored as a decimal string because BigInt is not JSON-serializable and\n// the IterableMap backing store may be MongoDB.\nexport interface EvmBridgeCursor {\n lastProcessedId: string\n}\n\nexport function getEvmBridgeCursorKey(chainId: Hex, contractAddress: Address): string {\n return `${chainId.toLowerCase()}:${contractAddress.toLowerCase()}`\n}\n", "import type { Logger } from '@xylabs/sdk-js'\nimport { Queue, Worker } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport { prefix } from '../prefix.ts'\nimport type { EvmBridgeScanner } from './EvmBridgeScanner.ts'\n\nconst QUEUE_NAME = 'eth-to-xl1-scanner'\nconst REPEATABLE_JOB_NAME = 'scan'\n\n// Stable jobId so an actor restart re-attaches to the existing repeatable schedule rather\n// than accumulating duplicate schedules with each restart. BullMQ dedups by jobId on add.\nconst REPEATABLE_JOB_ID = 'eth-to-xl1-scanner-tick'\n\nexport interface EvmBridgeScannerRunnerOptions {\n connection: Redis\n intervalMs: number\n /** Defaults to the global `console` so the runner is usable without explicit wiring. */\n logger?: Logger\n scanner: EvmBridgeScanner\n telemetry?: BullMQOtel\n}\n\nexport interface EvmBridgeScannerRunnerHandle {\n start(): Promise<void>\n stop(): Promise<void>\n}\n\n/**\n * Wraps the EVM bridge scanner in a BullMQ repeatable job so it ticks at `intervalMs`.\n *\n * Each tick calls `scanner.scan()`, which reads the contract's `nextBridgeToId` at depth,\n * walks any new ids past the persisted cursor, hands each to the configured enqueue\n * callback (which dispatches a flow), and advances the cursor. If a tick throws, BullMQ\n * marks that tick failed; the next tick fires at the regular interval \u2014 failures of one\n * tick do not block subsequent ticks.\n *\n * Lifecycle is managed by start()/stop() so the actor can wire it into its own lifecycle.\n */\nexport function createEvmBridgeScannerRunner(options: EvmBridgeScannerRunnerOptions): EvmBridgeScannerRunnerHandle {\n const {\n connection, intervalMs, scanner, telemetry,\n } = options\n const logger: Logger = options.logger ?? console\n let queue: Queue | undefined\n let worker: Worker | undefined\n\n return {\n async start(): Promise<void> {\n queue = new Queue(QUEUE_NAME, {\n connection,\n prefix,\n telemetry,\n })\n worker = new Worker(QUEUE_NAME, async (job) => {\n await job.log('[scanner] tick start')\n const result = await scanner.scan({ jobLog: msg => job.log(msg) })\n await job.log(\n `[scanner] tick complete: enqueued=${result.enqueued} `\n + `confirmedHigh=${result.confirmedHigh.toString()} `\n + `lastProcessedId=${result.lastProcessedId.toString()}`,\n )\n }, {\n connection,\n prefix,\n telemetry,\n })\n\n worker.on('failed', (job, err) => {\n logger.error(`[scanner] tick ${job?.id} failed:`, err.message)\n })\n worker.on('error', (err) => {\n logger.error('[scanner] worker error:', err)\n })\n\n await queue.add(REPEATABLE_JOB_NAME, {}, {\n jobId: REPEATABLE_JOB_ID,\n repeat: { every: intervalMs },\n })\n },\n async stop(): Promise<void> {\n await worker?.close()\n await queue?.close()\n worker = undefined\n queue = undefined\n },\n }\n}\n", "import type { Logger } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport type { FlowProducer } from 'bullmq'\nimport type { BullMQOtel } from 'bullmq-otel'\nimport type { Redis } from 'ioredis'\n\nimport {\n getRemoteChainId, getScannerIntervalMs, getXl1ChainId, getXl1TokenAddress,\n} from '../../evm/index.ts'\nimport type { IBridgeServiceCollection } from '../../IBridgeServiceCollection.ts'\nimport { createEnqueueEthToXl1Bridge } from './createEnqueueEthToXl1Bridge.ts'\nimport { createEvmBridgeScanner } from './EvmBridgeScanner.ts'\nimport type { EvmBridgeScannerRunnerHandle } from './EvmBridgeScannerRunner.ts'\nimport { createEvmBridgeScannerRunner } from './EvmBridgeScannerRunner.ts'\n\nexport interface BuildEvmBridgeScannerRunnerOptions {\n config: BridgeConfig\n connection: Redis\n flowProducer: FlowProducer\n /** Threaded through to the runner + enqueue callback. Falls back to console downstream. */\n logger?: Logger\n services: IBridgeServiceCollection\n telemetry?: BullMQOtel\n}\n\n/**\n * Composes the scanner runner from config + services + queue infrastructure. Pulls the\n * remote chain/contract addresses and the scan interval from config; uses services' bridge\n * contract handle and provider for cursor-side reads; wires the (now identity-only)\n * enqueue callback. Verification + reserve-side work has moved into the BullMQ flow.\n */\nexport function buildEvmBridgeScannerRunner(options: BuildEvmBridgeScannerRunnerOptions): EvmBridgeScannerRunnerHandle {\n const {\n config, connection, flowProducer, logger, services, telemetry,\n } = options\n const evmChainId = getRemoteChainId(config)\n const evmContractAddress = config.remoteBridgeContractAddress\n const xl1ChainId = getXl1ChainId(config)\n const xl1TokenAddress = getXl1TokenAddress(config)\n const intervalMs = getScannerIntervalMs(config)\n\n const enqueue = createEnqueueEthToXl1Bridge({\n evmChainId,\n evmContractAddress,\n flowProducer,\n xl1ChainId,\n xl1TokenAddress,\n })\n\n const scanner = createEvmBridgeScanner({\n bridge: services.bridge,\n bridgeAddress: evmContractAddress,\n chainId: evmChainId,\n confirmationDepth: services.remoteConfirmationDepth,\n cursors: services.evmBridgeCursorMap,\n enqueue,\n provider: services.provider,\n })\n\n return createEvmBridgeScannerRunner({\n connection,\n intervalMs,\n logger,\n scanner,\n telemetry,\n })\n}\n", "import { isDefined } from '@xylabs/sdk-js'\nimport type { BullMQOtelOptions } from 'bullmq-otel'\nimport { BullMQOtel } from 'bullmq-otel'\n\nlet telemetry: BullMQOtel | undefined\nconst options: BullMQOtelOptions = { enableMetrics: true }\n\nexport const getTelemetry = () => {\n if (isDefined(telemetry)) return telemetry\n telemetry = new BullMQOtel(options)\n return telemetry\n}\n", "import type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport type { Express } from 'express'\n\nimport {\n getConnection, getFlowProducer, getTelemetry,\n} from '../services/queue/index.ts'\n\nexport const addFlowProducer = (app: Express, config: BridgeConfig): Express => {\n const connection = getConnection(config)\n const telemetry = getTelemetry()\n const flowProducer = getFlowProducer(connection, telemetry)\n app.flowProducer = flowProducer\n return app\n}\n", "import { registerInstrumentations } from '@opentelemetry/instrumentation'\nimport { ExpressInstrumentation } from '@opentelemetry/instrumentation-express'\nimport { HttpInstrumentation } from '@opentelemetry/instrumentation-http'\n\n/**\n * Registers OpenTelemetry instrumentations for HTTP and Express.\n * This function is used to set up the necessary instrumentations for monitoring\n * HTTP requests and Express applications. Since it monkey patches the Express\n * router & middleware system, it should be called before any Express applications\n * are defined.\n */\nexport const addInstrumentation = () => {\n const instrumentations = [new HttpInstrumentation(), new ExpressInstrumentation()]\n registerInstrumentations({ instrumentations })\n}\n", "import type { NoReqParams } from '@xylabs/express'\nimport { setRawResponseFormat } from '@xylabs/express'\nimport type { RequestHandler } from 'express'\nimport { ReasonPhrases } from 'http-status-codes'\n\nconst message = ReasonPhrases.OK\n\nconst handler: RequestHandler<NoReqParams> = (_req, res) => {\n setRawResponseFormat(res)\n res.status(200).send({ message })\n}\n\nexport const getLivez: RequestHandler<NoReqParams> = handler\n", "import type { NoReqParams } from '@xylabs/express'\nimport { setRawResponseFormat } from '@xylabs/express'\nimport type { RequestHandler } from 'express'\nimport { ReasonPhrases } from 'http-status-codes'\n\nconst message = ReasonPhrases.OK\n\nconst handler: RequestHandler<NoReqParams> = (_req, res) => {\n setRawResponseFormat(res)\n res.status(200).send({ message })\n}\n\nexport const getReadyz: RequestHandler<NoReqParams> = handler\n", "import type { NoReqParams } from '@xylabs/express'\nimport { setRawResponseFormat } from '@xylabs/express'\nimport type { RequestHandler } from 'express'\nimport { ReasonPhrases } from 'http-status-codes'\n\nconst message = ReasonPhrases.OK\n\nconst handler: RequestHandler<NoReqParams> = (_req, res) => {\n setRawResponseFormat(res)\n res.status(200).send({ message })\n}\n\nexport const getStartupz: RequestHandler<NoReqParams> = handler\n", "import type { Express } from 'express'\n\nimport { getLivez } from './livez/index.ts'\nimport { getReadyz } from './readyz/index.ts'\nimport { getStartupz } from './startupz/index.ts'\n\nexport const addProbeRoutes = (app: Express) => {\n app.get('/livez', getLivez)\n app.get('/readyz', getReadyz)\n app.get('/startupz', getStartupz)\n}\n", "import type { RouteDefinition } from '@xylabs/express'\nimport { requestHandlerValidator } from '@xylabs/express'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { BridgeSettingsZod } from '@xyo-network/chain-orchestration'\nimport type { z } from 'zod'\n\nimport { getBridgeSettings } from '../../../../../services/evm/index.ts'\n\nexport const BridgeConfigResponseZod = BridgeSettingsZod\nexport type BridgeConfigResponse = z.infer<typeof BridgeConfigResponseZod>\n\nconst validateRequest = requestHandlerValidator({ response: BridgeConfigResponseZod })\n\nexport const makeBridgeConfigRoute = (config: BridgeConfig): RouteDefinition => {\n return {\n method: 'get',\n path: '/bridge/chains/:chainId/config',\n handlers: validateRequest(async (_, res) => {\n const {\n escrowAddress,\n feeFixed,\n feeRateBasisPoints,\n feesAddress,\n maxBridgeAmount,\n minBridgeAmount,\n remoteChainId,\n remoteTokenAddress,\n xl1ChainId,\n xl1TokenAddress,\n } = await getBridgeSettings(config)\n const sanitizedConfig = {\n escrowAddress,\n feeFixed,\n feeRateBasisPoints,\n feesAddress,\n maxBridgeAmount,\n minBridgeAmount,\n remoteChainId,\n remoteTokenAddress,\n xl1ChainId,\n xl1TokenAddress,\n }\n res.json(sanitizedConfig)\n }),\n }\n}\n", "import type { RouteDefinition } from '@xylabs/express'\nimport { requestHandlerValidator } from '@xylabs/express'\nimport {\n assertEx, hexToBigInt, toAddress,\n} from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { PayloadZodStrictOfSchema } from '@xyo-network/sdk-js'\nimport {\n BridgeIntentFieldsZod, BridgeIntentSchema, buildUnsignedTransaction, toXL1BlockNumber, TransactionBoundWitnessZod, TransferZod,\n} from '@xyo-network/xl1-sdk'\nimport { z } from 'zod'\n\nimport {\n getBridgeSettings, getFeeStructure, getRemoteTokenAddress, getTransferAddresses,\n getXl1ChainId, getXl1TokenAddress,\n} from '../../../../../services/evm/index.ts'\nimport { buildEthToXl1BridgePayloads } from '../../../../../services/queue/workers/util/index.ts'\nimport { calculateBridgeFees } from '../../../../../services/util/index.ts'\nimport { getRemoteChainIdZod } from '../pathParams/index.ts'\n\n/**\n * Request body mirrors `BridgeToRemoteEstimateBodyZod` exactly. The semantic flips:\n * - `srcAddress` is the user's EVM source\n * - `destAddress` is the user's XL1 destination\n * - `srcAmount` is the gross EVM deposit\n */\nexport const BridgeFromRemoteEstimateBodyZod = BridgeIntentFieldsZod.pick({\n destAddress: true,\n srcAddress: true,\n srcAmount: true,\n})\nexport type BridgeFromRemoteEstimateBody = z.infer<typeof BridgeFromRemoteEstimateBodyZod>\n\n/**\n * 3-tuple matching the outbound estimate response shape. The TransactionBoundWitness here is\n * unsigned and represents what the BRIDGE will sign at Stage 2 fulfillment (sender =\n * bridgeAccount.address) \u2014 not signable by the user. It's purely informational: a projection\n * of the XL1 transaction that will appear on-chain after the user deposits on EVM.\n *\n * Outbound's TxBw is *both* signable-by-user AND a preview of on-chain artifact (because the\n * user is the signer). Inbound separates these \u2014 the user's initiating action is on EVM, the\n * concluding artifact is on XL1 signed by someone else. The estimate aligns on the \"on-chain\n * artifact\" view for cross-direction symmetry.\n */\nexport const BridgeFromRemoteEstimateResponseZod = z.tuple([\n TransactionBoundWitnessZod,\n PayloadZodStrictOfSchema(BridgeIntentSchema).extend(BridgeIntentFieldsZod.shape),\n TransferZod,\n])\n\nexport type BridgeFromRemoteEstimateResponse = z.infer<typeof BridgeFromRemoteEstimateResponseZod>\n\nexport const makeBridgeFromRemoteEstimateRoute = (config: BridgeConfig): RouteDefinition => {\n const params = z.object({ chainId: getRemoteChainIdZod(config) })\n const validateRequest = requestHandlerValidator({\n params, body: BridgeFromRemoteEstimateBodyZod, response: BridgeFromRemoteEstimateResponseZod,\n })\n return {\n method: 'post',\n path: '/bridge/chains/:chainId/bridgeFromRemote/estimate',\n handlers: validateRequest(async (req, res) => {\n const services = req.app.services\n const {\n account, bridge, gateway,\n } = services\n const {\n srcAddress, srcAmount, destAddress,\n } = req.body\n\n // Same min/max gate as the outbound estimate. Shared knob per the symmetry decision.\n const { maxBridgeAmount, minBridgeAmount } = await getBridgeSettings(config)\n if (hexToBigInt(srcAmount) < hexToBigInt(minBridgeAmount) || hexToBigInt(srcAmount) > hexToBigInt(maxBridgeAmount)) {\n res.status(400).send()\n return\n }\n\n // Fees applied at quote time. The user explicitly accepted \"current rates apply at\n // settlement\" \u2014 this projection shows what would happen if they deposited right now.\n const fees = calculateBridgeFees(srcAmount, getFeeStructure(config))\n const feesAmount = hexToBigInt(fees.feeFixed) + hexToBigInt(fees.feeVariable)\n const { feesAddress } = await getTransferAddresses(config)\n\n // Project the bridge id. The contract increments BEFORE writing (LiquidityPoolBridge:114),\n // so the next call to bridgeToRemote will use `nextBridgeToId + 1`. Read 'latest' to\n // avoid pre-deploy staleness (matches the scanner's depth-0 path). Race: another caller\n // could deposit between this read and the user's call \u2014 the realized intent (visible\n // via /status) is the source of truth post-deposit.\n const currentNextId = await bridge.nextBridgeToId({ blockTag: 'latest' })\n const projectedBridgeId = currentNextId + 1n\n\n const xl1ChainId = getXl1ChainId(config)\n const xl1TokenAddress = getXl1TokenAddress(config)\n const evmChainId = config.remoteChainId\n const evmContractAddress = config.remoteBridgeContractAddress\n const evmTokenAddress = getRemoteTokenAddress(config)\n\n const viewer = assertEx(gateway.connection.viewer, () => new Error('Viewer not available on gateway connection'))\n const currentBlockNumber = await viewer.currentBlockNumber()\n const nbf = toXL1BlockNumber(currentBlockNumber, true)\n const exp = toXL1BlockNumber(currentBlockNumber + 1000, true)\n\n // Shared payload construction with Stage 2's buildEthToXl1ReserveTx \u2014 Transfer split\n // and intent semantics stay in lockstep. Source observation is omitted from the\n // estimate (requires evmTxHash, which doesn't exist until Stage 1 verifies the deposit).\n const { intent, transfer } = buildEthToXl1BridgePayloads({\n amount: hexToBigInt(srcAmount),\n bridgeAccountAddress: account.address,\n bridgeId: projectedBridgeId,\n destAddress: toAddress(destAddress),\n evmChainId,\n evmContractAddress,\n evmSrcAddress: toAddress(srcAddress),\n evmTokenAddress,\n feesAddress,\n feesAmount,\n xl1ChainId,\n xl1TokenAddress,\n })\n\n // Unsigned tx with sender = bridge account. The recipient of this response cannot\n // sign or submit \u2014 that's expected. The TxBw is a projection of the realized on-chain\n // shape, mirroring outbound's TxBw-as-on-chain-preview view.\n const [txBw] = await buildUnsignedTransaction(xl1ChainId, [transfer], [intent], nbf, exp, account.address)\n\n res.json([txBw, intent, transfer])\n }),\n }\n}\n", "import {\n asHex, HexZod, isUndefined,\n} from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport type { ChainId } from '@xyo-network/xl1-sdk'\n\nimport { getRemoteChainId } from '../../../../../services/evm/index.ts'\n\nexport const getRemoteChainIdZod = (config: BridgeConfig) => {\n const remoteChainId: ChainId = getRemoteChainId(config)\n return HexZod.superRefine((val, ctx) => {\n const chainId = asHex(val)\n if (isUndefined(chainId)) {\n ctx.addIssue('Not a valid chain id')\n return\n }\n if (chainId !== remoteChainId) {\n ctx.addIssue(`Only ${remoteChainId} is supported`)\n }\n })\n}\n", "import type { RouteDefinition } from '@xylabs/express'\nimport { requestHandlerValidator } from '@xylabs/express'\nimport {\n hexToBigInt, isDefined, toHex,\n} from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { PayloadZodStrictOfSchema } from '@xyo-network/sdk-js'\nimport type {\n BridgeDestinationObservation, BridgeIntent, BridgeSourceObservation,\n} from '@xyo-network/xl1-sdk'\nimport {\n BridgeDestinationObservationFieldsZod, BridgeDestinationObservationSchema,\n BridgeIntentFieldsZod, BridgeIntentSchema,\n BridgeSourceObservationFieldsZod, BridgeSourceObservationSchema,\n} from '@xyo-network/xl1-sdk'\nimport { z } from 'zod'\n\nimport {\n getFeeStructure, getRemoteTokenAddress, getXl1ChainId, getXl1TokenAddress,\n} from '../../../../../services/evm/index.ts'\nimport { getJobIdForEthToXl1BridgeJob } from '../../../../../services/queue/flows/createEthToXl1BridgeJob/index.ts'\nimport { getEthToXl1Queues } from '../../../../../services/queue/index.ts'\nimport type { EthBridgeEventData } from '../../../../../services/queue/workers/util/index.ts'\nimport { calculateBridgeFees } from '../../../../../services/util/index.ts'\nimport { getRemoteChainIdZod } from '../pathParams/index.ts'\n\nconst BridgeIntentResponseZod = PayloadZodStrictOfSchema(BridgeIntentSchema)\n .extend(BridgeIntentFieldsZod.shape)\n\nconst BridgeSourceResponseZod = PayloadZodStrictOfSchema(BridgeSourceObservationSchema)\n .extend(BridgeSourceObservationFieldsZod.shape)\n\nconst BridgeDestinationResponseZod = PayloadZodStrictOfSchema(BridgeDestinationObservationSchema)\n .extend(BridgeDestinationObservationFieldsZod.shape)\n\n// 0 / 1 / 2 / 3 elements representing the flow's progression \u2014 empty (parent enqueued but\n// Stage 1 hasn't run), intent only (state.canonical present, source observation hasn't\n// been derived yet \u2014 currently unreachable since we always have evmTxHash on canonical),\n// intent + source (Stage 1 success), or all three (Stage 2 fulfilled).\nexport const BridgeFromRemoteStatusResponseZod = z.union([\n z.tuple([]),\n z.tuple([BridgeIntentResponseZod]),\n z.tuple([BridgeIntentResponseZod, BridgeSourceResponseZod]),\n z.tuple([BridgeIntentResponseZod, BridgeSourceResponseZod, BridgeDestinationResponseZod]),\n])\nexport type BridgeFromRemoteStatusResponse = z.infer<typeof BridgeFromRemoteStatusResponseZod>\n\ninterface BuildPayloadsContext {\n canonical: EthBridgeEventData\n config: BridgeConfig\n nonce: string\n}\n\nfunction buildIntentAndSource(ctx: BuildPayloadsContext): [BridgeIntent, BridgeSourceObservation] {\n const {\n canonical, config, nonce,\n } = ctx\n const srcAmountHex = toHex(canonical.amount)\n // Mirror Stage 2's fee math (buildEthToXl1BridgePayloads) so the status response's\n // destAmount matches what the bridge actually credited on XL1. Reads current fee config\n // at query time, consistent with the no-snapshot policy applied at settlement.\n const fees = calculateBridgeFees(srcAmountHex, getFeeStructure(config))\n const feesAmount = hexToBigInt(fees.feeFixed) + hexToBigInt(fees.feeVariable)\n const destAmountHex = toHex(canonical.amount - feesAmount)\n const xl1ChainId = getXl1ChainId(config)\n const xl1TokenAddress = getXl1TokenAddress(config)\n const evmChainId = config.remoteChainId\n const evmTokenAddress = getRemoteTokenAddress(config)\n\n const intentFields = BridgeIntentFieldsZod.parse({\n dest: xl1ChainId,\n destAddress: canonical.destAddress,\n destAmount: destAmountHex,\n destToken: xl1TokenAddress,\n nonce,\n src: evmChainId,\n srcAddress: canonical.srcAddress,\n srcAmount: srcAmountHex,\n srcToken: evmTokenAddress,\n })\n const intent: BridgeIntent = { schema: BridgeIntentSchema, ...intentFields }\n\n const sourceFields = BridgeSourceObservationFieldsZod.parse({\n ...intentFields,\n srcConfirmation: canonical.evmTxHash,\n })\n const source: BridgeSourceObservation = { schema: BridgeSourceObservationSchema, ...sourceFields }\n\n return [intent, source]\n}\n\nexport const makeBridgeFromRemoteStatusRoute = (config: BridgeConfig): RouteDefinition => {\n const params = z.object({\n chainId: getRemoteChainIdZod(config),\n nonce: z.string().regex(/^\\d+$/, 'nonce must be a non-negative integer (the bridge contract\\'s id)'),\n })\n const validateRequest = requestHandlerValidator({ params, response: BridgeFromRemoteStatusResponseZod })\n\n return {\n method: 'get',\n path: '/bridge/chains/:chainId/bridgeFromRemote/status/:nonce',\n handlers: validateRequest(async (req, res) => {\n const bridgeId = BigInt(req.params.nonce)\n const contractAddress = config.remoteBridgeContractAddress\n const evmChainId = config.remoteChainId\n\n const identity = getJobIdForEthToXl1BridgeJob({\n bridgeId,\n contractAddress,\n evmChainId,\n })\n\n const services = req.app.services\n const state = await services.bridgeFulfillmentMap.get(identity)\n\n // Stage 1 or Stage 2 wrote a terminal failure record \u2014 surface as 504 (server-side\n // fulfillment failure, not a client error). The reason lives in state.failed and is\n // visible via BullBoard / the state map for ops.\n if (state?.failed) return res.sendStatus(504)\n\n // No state yet \u2014 either the parent hasn't been enqueued or Stage 1 hasn't run.\n // Differentiate via the parent queue: present \u21D2 in-flight (empty tuple), absent \u21D2 404.\n if (!state?.canonical) {\n const queues = getEthToXl1Queues(config)\n const parentJob = await queues.ethToXl1BridgeParent.getJob(identity)\n if (!isDefined(parentJob)) return res.sendStatus(404)\n return res.json([])\n }\n\n const [intent, source] = buildIntentAndSource({\n canonical: state.canonical, config, nonce: identity,\n })\n if (!state.fulfilled) return res.json([intent, source])\n\n const destinationFields = BridgeDestinationObservationFieldsZod.parse({\n ...intent,\n destConfirmation: state.fulfilled.txHash,\n })\n const destination: BridgeDestinationObservation = { schema: BridgeDestinationObservationSchema, ...destinationFields }\n res.json([intent, source, destination])\n }),\n }\n}\n", "import type { RouteDefinition } from '@xylabs/express'\nimport { requestHandlerValidator } from '@xylabs/express'\nimport { isDefined } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport {\n PayloadBuilder, PayloadZodLooseOfSchema, PayloadZodStrictOfSchema,\n} from '@xyo-network/sdk-js'\nimport type {\n BridgeSourceObservation, BridgeSourceObservationFields, SignedHydratedTransaction,\n} from '@xyo-network/xl1-sdk'\nimport {\n BridgeIntentFieldsZod, BridgeIntentSchema, BridgeSourceObservationFieldsZod, BridgeSourceObservationSchema, SignedTransactionBoundWitnessZod, TransferZod,\n} from '@xyo-network/xl1-sdk'\nimport { z } from 'zod'\n\nimport { createXl1ToEthBridgeJob, getXl1ToEthBridgeJob } from '../../../../../services/queue/index.ts'\nimport {\n validateBridgeEstimateExact, validateBridgeTransaction, validateSufficientXL1SourceAddressBalance,\n} from '../../../../../services/validation/index.ts'\nimport { getRemoteChainIdZod } from '../pathParams/index.ts'\n\nexport const BridgeToRemoteBodyZod = z.tuple([\n SignedTransactionBoundWitnessZod,\n PayloadZodLooseOfSchema(BridgeIntentSchema).extend(BridgeIntentFieldsZod.shape),\n TransferZod,\n])\nexport type BridgeToRemoteBody = z.infer<typeof BridgeToRemoteBodyZod>\n\nexport const BridgeToRemoteResponseZod = PayloadZodStrictOfSchema(BridgeSourceObservationSchema).extend(BridgeSourceObservationFieldsZod.shape)\nexport type BridgeToRemoteResponse = z.infer<typeof BridgeToRemoteResponseZod>\n\nexport const makeBridgeToRemoteRoute = (config: BridgeConfig): RouteDefinition => {\n const params = z.object({ chainId: getRemoteChainIdZod(config) })\n\n const validateRequest = requestHandlerValidator({\n params, body: BridgeToRemoteBodyZod, response: BridgeToRemoteResponseZod,\n })\n return {\n method: 'post',\n path: '/bridge/chains/:chainId/bridgeToRemote',\n handlers: validateRequest(async (req, res) => {\n const [signedTxBw, bridgeIntent, transfer] = req.body\n const { flowProducer } = req.app\n const { gateway } = req.app.services\n\n // Validate request\n const transactionValid = await validateBridgeTransaction(signedTxBw, bridgeIntent, transfer, config)\n if (!transactionValid) {\n res.status(400).send()\n return\n }\n\n // Validate estimate\n const estimateValid = await validateBridgeEstimateExact(bridgeIntent, transfer, config)\n if (!estimateValid) {\n res.status(400).send()\n return\n }\n\n // Validate sufficient balance\n const sufficientBalance = await validateSufficientXL1SourceAddressBalance(bridgeIntent, gateway, config)\n if (!sufficientBalance) {\n res.status(400).send()\n return\n }\n\n // Create the signed hydrated transaction for the job\n const singedHydratedTransaction: SignedHydratedTransaction = [signedTxBw, [transfer]]\n\n // Check if a job already exists for this transaction\n const existingFlow = await getXl1ToEthBridgeJob(flowProducer, singedHydratedTransaction)\n if (isDefined(existingFlow)) {\n res.status(200).send()\n return\n }\n\n // Submit to job queue\n await createXl1ToEthBridgeJob(flowProducer, singedHydratedTransaction, [bridgeIntent])\n\n // Create BridgeObservation\n const srcConfirmation = await PayloadBuilder.hash(signedTxBw)\n const bridgeCommonFieldsZod = z.object({}).extend(BridgeSourceObservationFieldsZod.shape)\n const bridgeCommonFields = bridgeCommonFieldsZod.parse(bridgeIntent)\n const bridgeObservationFields: BridgeSourceObservationFields = { ...bridgeCommonFields, srcConfirmation }\n const bridgeObservation: BridgeSourceObservation = new PayloadBuilder<BridgeSourceObservation>(\n { schema: BridgeSourceObservationSchema },\n ).fields(bridgeObservationFields).build()\n\n // Return bridge observation to caller\n res.status(202).json(bridgeObservation)\n }),\n }\n}\n", "import type { RouteDefinition } from '@xylabs/express'\nimport { requestHandlerValidator } from '@xylabs/express'\nimport {\n assertEx, hexToBigInt, toAddress,\n} from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { PayloadZodStrictOfSchema } from '@xyo-network/sdk-js'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\nimport {\n BridgeIntentFieldsZod, BridgeIntentSchema, buildUnsignedTransaction, toXL1BlockNumber, TransactionBoundWitnessZod, TransferZod,\n} from '@xyo-network/xl1-sdk'\nimport { z } from 'zod'\n\nimport { getBridgeSettings, getXl1ChainId } from '../../../../../services/evm/index.ts'\nimport { generateBridgeEstimate } from '../../../../../services/util/index.ts'\nimport { getRemoteChainIdZod } from '../pathParams/index.ts'\n\nexport const BridgeToRemoteEstimateBodyZod = BridgeIntentFieldsZod.pick({\n destAddress: true,\n srcAddress: true,\n srcAmount: true,\n})\nexport type BridgeToRemoteEstimateBody = z.infer<typeof BridgeToRemoteEstimateBodyZod>\n\nexport const BridgeToRemoteEstimateResponseZod = z.tuple([\n TransactionBoundWitnessZod,\n PayloadZodStrictOfSchema(BridgeIntentSchema).extend(BridgeIntentFieldsZod.shape),\n TransferZod,\n])\n\nexport type BridgeToRemoteEstimateResponse = z.infer<typeof BridgeToRemoteEstimateResponseZod>\n\nexport const makeBridgeToRemoteEstimateRoute = (config: BridgeConfig, gateway: XyoGatewayRunner): RouteDefinition => {\n const params = z.object({ chainId: getRemoteChainIdZod(config) })\n const validateRequest = requestHandlerValidator({\n params, body: BridgeToRemoteEstimateBodyZod, response: BridgeToRemoteEstimateResponseZod,\n })\n return {\n method: 'post',\n path: '/bridge/chains/:chainId/bridgeToRemote/estimate',\n handlers: validateRequest(async (req, res) => {\n const xl1ChainId = getXl1ChainId(config)\n const {\n srcAddress, srcAmount, destAddress,\n } = req.body\n\n const { maxBridgeAmount, minBridgeAmount } = await getBridgeSettings(config)\n if (hexToBigInt(srcAmount) < hexToBigInt(minBridgeAmount) || hexToBigInt(srcAmount) > hexToBigInt(maxBridgeAmount)) {\n res.status(400).send()\n return\n }\n\n const [bridgeIntent, transfer] = await generateBridgeEstimate(srcAddress, srcAmount, destAddress, config)\n const sender = toAddress(srcAddress)\n\n // Use viewer to get current block\n const viewer = assertEx(gateway.connection.viewer, () => new Error('Viewer not available on gateway connection'))\n const currentBlockNumber = await viewer.currentBlockNumber()\n // Calculate nbf/exp\n const nbf = toXL1BlockNumber(currentBlockNumber, true)\n const exp = toXL1BlockNumber(currentBlockNumber + 1000, true)\n // Build unsigned transaction representing the transfer that will be signed by srcAddress\n const [txBw] = await buildUnsignedTransaction(xl1ChainId, [transfer], [bridgeIntent], nbf, exp, sender)\n\n // Return the TX to the caller for signing\n res.json([txBw, bridgeIntent, transfer])\n }),\n }\n}\n", "import type { RouteDefinition } from '@xylabs/express'\nimport { requestHandlerValidator } from '@xylabs/express'\nimport {\n assertEx, hexToBigInt, toAddress, toHex,\n} from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { PayloadZodStrictOfSchema } from '@xyo-network/sdk-js'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\nimport {\n BridgeIntentFieldsZod, BridgeIntentSchema, buildUnsignedTransaction, toXL1BlockNumber, TransactionBoundWitnessZod, TransferZod,\n} from '@xyo-network/xl1-sdk'\nimport { z } from 'zod'\n\nimport { getBridgeSettings } from '../../../../../services/evm/index.ts'\nimport { calculateMaxBridgeAmount, generateBridgeEstimate } from '../../../../../services/util/index.ts'\nimport { getRemoteChainIdZod } from '../pathParams/index.ts'\n\nexport const BridgeToRemoteMaxEstimateBodyZod = BridgeIntentFieldsZod.pick({\n destAddress: true,\n srcAddress: true,\n srcAmount: true,\n})\nexport type BridgeToRemoteMaxEstimateBody = z.infer<typeof BridgeToRemoteMaxEstimateBodyZod>\n\nexport const BridgeToRemoteMaxEstimateResponseZod = z.tuple([\n TransactionBoundWitnessZod,\n PayloadZodStrictOfSchema(BridgeIntentSchema).extend(BridgeIntentFieldsZod.shape),\n TransferZod,\n])\n\nexport type BridgeToRemoteMaxEstimateResponse = z.infer<typeof BridgeToRemoteMaxEstimateResponseZod>\n\nexport const makeBridgeToRemoteMaxEstimateRoute = (config: BridgeConfig, gateway: XyoGatewayRunner): RouteDefinition => {\n const params = z.object({ chainId: getRemoteChainIdZod(config) })\n const validateRequest = requestHandlerValidator({\n params, body: BridgeToRemoteMaxEstimateBodyZod, response: BridgeToRemoteMaxEstimateResponseZod,\n })\n return {\n method: 'post',\n path: '/bridge/chains/:chainId/bridgeToRemote/maxEstimate',\n handlers: validateRequest(async (req, res) => {\n const {\n feeFixed, feeRateBasisPoints, maxBridgeAmount: configMax, xl1ChainId,\n } = await getBridgeSettings(config)\n const {\n srcAddress, srcAmount: balance, destAddress,\n } = req.body\n\n const balanceMax = calculateMaxBridgeAmount(balance, { feeFixed, feeRateBasisPoints })\n const maxBridgeAmount = toHex(hexToBigInt(balanceMax) < hexToBigInt(configMax) ? balanceMax : configMax)\n\n const [bridgeIntent, transfer] = await generateBridgeEstimate(srcAddress, maxBridgeAmount, destAddress, config)\n const sender = toAddress(srcAddress)\n\n const viewer = assertEx(gateway.connection.viewer, () => new Error('Viewer not available on gateway connection'))\n const currentBlockNumber = await viewer.currentBlockNumber()\n const nbf = toXL1BlockNumber(currentBlockNumber, true)\n const exp = toXL1BlockNumber(currentBlockNumber + 1000, true)\n const [txBw] = await buildUnsignedTransaction(xl1ChainId, [transfer], [bridgeIntent], nbf, exp, sender)\n\n res.json([txBw, bridgeIntent, transfer])\n }),\n }\n}\n", "import type { RouteDefinition } from '@xylabs/express'\nimport { requestHandlerValidator } from '@xylabs/express'\nimport { asHex, isDefined } from '@xylabs/sdk-js'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport { PayloadBuilder, PayloadZodStrictOfSchema } from '@xyo-network/sdk-js'\nimport type { BridgeDestinationObservation, BridgeSourceObservation } from '@xyo-network/xl1-sdk'\nimport {\n asBridgeIntent, BridgeDestinationObservationFieldsZod, BridgeDestinationObservationSchema, BridgeIntentFieldsZod, BridgeIntentSchema,\n BridgeSourceObservationFieldsZod, BridgeSourceObservationSchema, isBridgeIntent,\n} from '@xyo-network/xl1-sdk'\nimport { z } from 'zod'\n\nimport { getStatusQueueJobs, getXl1ToEthQueues } from '../../../../../services/queue/index.ts'\nimport { getRemoteChainIdZod } from '../pathParams/index.ts'\n\nconst BridgeIntentResponseZod = PayloadZodStrictOfSchema(BridgeIntentSchema)\n .extend(BridgeIntentFieldsZod.shape)\n\nconst BridgeSourceResponseZod = PayloadZodStrictOfSchema(BridgeSourceObservationSchema)\n .extend(BridgeSourceObservationFieldsZod.shape)\n\nconst BridgeDestinationResponseZod = PayloadZodStrictOfSchema(BridgeDestinationObservationSchema)\n .extend(BridgeDestinationObservationFieldsZod.shape)\n\nexport const BridgeToRemoteStatusResponseZod = z.union([\n z.tuple([]),\n z.tuple([BridgeIntentResponseZod]),\n z.tuple([BridgeIntentResponseZod, BridgeSourceResponseZod]),\n z.tuple([BridgeIntentResponseZod, BridgeSourceResponseZod, BridgeDestinationResponseZod]),\n])\nexport type BridgeToRemoteStatusResponse = z.infer<typeof BridgeToRemoteStatusResponseZod>\n\nexport const makeBridgeToRemoteStatusRoute = (config: BridgeConfig): RouteDefinition => {\n const params = z.object({\n chainId: getRemoteChainIdZod(config),\n nonce: z.string().nonempty(),\n })\n\n const validateRequest = requestHandlerValidator({ params, response: BridgeToRemoteStatusResponseZod })\n\n return {\n method: 'get',\n path: '/bridge/chains/:chainId/bridgeToRemote/status/:nonce',\n handlers: validateRequest(async (req, res) => {\n const jobId = req.params.nonce\n const result: z.infer<typeof BridgeToRemoteStatusResponseZod> = [] as z.infer<typeof BridgeToRemoteStatusResponseZod>\n const queues = getXl1ToEthQueues(config)\n\n const statusQueueJobs = await getStatusQueueJobs(queues, jobId)\n\n // Check for the transaction hash in the parent job\n const { tx, offChainPayloads = [] } = statusQueueJobs.xl1ToEthBridgeParentJob?.data ?? {}\n\n // If the job does not exist return Not Found\n if (!tx) return res.sendStatus(404)\n\n // If the tx is not the right shape for bridging return Not Found\n const allPayloads = [...tx[1], ...offChainPayloads]\n const bridgeIntent = allPayloads.find(isBridgeIntent)\n if (!bridgeIntent) return res.sendStatus(404)\n\n // At this point we know we have a valid bridge intent, so we can start building the response\n result[0] = asBridgeIntent(PayloadBuilder.omitMeta(bridgeIntent))\n\n // Check the state of the XL1 monitor job to determine if we can include the source observation\n const { xl1TransactionMonitorJob } = statusQueueJobs\n const xl1MonitorState = xl1TransactionMonitorJob ? await xl1TransactionMonitorJob.getState() : undefined\n if (xl1MonitorState === 'completed') {\n const srcConfirmation = xl1TransactionMonitorJob?.returnvalue?.submissionHash\n if (isDefined(srcConfirmation)) {\n const schema = BridgeSourceObservationSchema\n const bridgeSourceObservationFields = BridgeSourceObservationFieldsZod.parse(bridgeIntent)\n const observation: BridgeSourceObservation = {\n schema, ...bridgeSourceObservationFields, srcConfirmation,\n }\n result[1] = observation\n }\n }\n\n // Check the state of the ETH monitor job to determine if we can include the destination observation\n const { ethTransactionMonitorJob } = statusQueueJobs\n const ethMonitorState = ethTransactionMonitorJob ? await ethTransactionMonitorJob.getState() : undefined\n if (ethMonitorState === 'completed') {\n const destConfirmation = asHex(ethTransactionMonitorJob?.returnvalue?.submissionHash)\n if (isDefined(destConfirmation)) {\n const schema = BridgeDestinationObservationSchema\n const bridgeDestinationObservationFields = BridgeDestinationObservationFieldsZod.parse(bridgeIntent)\n const observation: BridgeDestinationObservation = {\n schema, ...bridgeDestinationObservationFields, destConfirmation,\n }\n result[2] = observation\n }\n }\n\n res.json(result)\n }),\n }\n}\n", "import type { RouteDefinition } from '@xylabs/express'\nimport type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\n\nimport {\n makeBridgeConfigRoute, makeBridgeFromRemoteEstimateRoute, makeBridgeFromRemoteStatusRoute,\n makeBridgeToRemoteEstimateRoute, makeBridgeToRemoteMaxEstimateRoute, makeBridgeToRemoteRoute, makeBridgeToRemoteStatusRoute,\n} from './routes/index.ts'\n\nexport const getRouteDefinitions = (config: BridgeConfig, gateway: XyoGatewayRunner): RouteDefinition[] => {\n return [\n makeBridgeConfigRoute(config),\n makeBridgeToRemoteEstimateRoute(config, gateway),\n makeBridgeToRemoteMaxEstimateRoute(config, gateway),\n makeBridgeToRemoteRoute(config),\n makeBridgeToRemoteStatusRoute(config),\n makeBridgeFromRemoteEstimateRoute(config),\n makeBridgeFromRemoteStatusRoute(config),\n ]\n}\n", "import type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\nimport type { Express } from 'express'\n\nimport { getRouteDefinitions } from './routeDefinitions/index.ts'\n\nexport const addBridgeRoutes = (app: Express, config: BridgeConfig, gateway: XyoGatewayRunner) => {\n const routeDefinitions = getRouteDefinitions(config, gateway)\n for (const definition of routeDefinitions) {\n app[definition.method](definition.path, definition.handlers)\n }\n}\n", "import type { BridgeConfig } from '@xyo-network/chain-orchestration'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\nimport type { Express } from 'express'\n\nimport { addProbeRoutes } from './addProbeRoutes.ts'\nimport { addBridgeRoutes } from './bridge/index.ts'\n\nexport const addRoutes = (app: Express, config: BridgeConfig, gateway: XyoGatewayRunner) => {\n addProbeRoutes(app)\n addBridgeRoutes(app, config, gateway)\n}\n", "import type { Hash } from '@xylabs/sdk-js'\nimport { assertEx } from '@xylabs/sdk-js'\nimport type { BridgeConfig, BridgeConfigContext } from '@xyo-network/chain-orchestration'\nimport { initEvmProvider, resolveWalletForActor } from '@xyo-network/chain-orchestration'\nimport { BridgeableToken__factory, LiquidityPoolBridge__factory } from '@xyo-network/typechain'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\nimport { getAddress, Wallet } from 'ethers'\n\nimport type { BridgeFulfillmentState } from './BridgeFulfillmentState.ts'\nimport type { EthTxState } from './EthTxState.ts'\nimport { getRemoteConfirmationDepth } from './evm/index.ts'\nimport { getIterableMap } from './getIterableMap.ts'\nimport type { IBridgeServiceCollection } from './IBridgeServiceCollection.ts'\nimport type { EvmBridgeCursor } from './queue/index.ts'\nimport type { Xl1TxState } from './Xl1TxState.ts'\n\n/**\n * Used for retrieving a service collection\n * @returns A service collection\n */\nexport const getServices = async (context: BridgeConfigContext, gateway: XyoGatewayRunner): Promise<IBridgeServiceCollection> => {\n const { config } = context\n\n const ethTxStateMap = await getIterableMap<Hash, EthTxState>(config, 'liquidity_bridge_xl1_to_eth_eth_tx_state')\n const xl1TxStateMap = await getIterableMap<Hash, Xl1TxState>(config, 'liquidity_bridge_xl1_to_eth_xl1_tx_state')\n const evmBridgeCursorMap = await getIterableMap<string, EvmBridgeCursor>(config, 'liquidity_bridge_eth_to_xl1_scanner_cursor')\n const bridgeFulfillmentMap = await getIterableMap<string, BridgeFulfillmentState>(config, 'liquidity_bridge_eth_to_xl1_fulfillment')\n const provider = await initEvmProvider(context)\n const {\n remoteBridgeContractAddress, remoteChainWalletPrivateKey, remoteTokenAddress, accountPath,\n } = config as BridgeConfig\n const account = await resolveWalletForActor(config.name, accountPath)\n const wallet = new Wallet(remoteChainWalletPrivateKey, provider)\n const bridgeableToken = BridgeableToken__factory.connect(getAddress(remoteTokenAddress), wallet)\n const bridge = LiquidityPoolBridge__factory.connect(getAddress(remoteBridgeContractAddress), wallet)\n // const approvalAmount = 18n * 10n ** 9n * 10n ** 18n // 18 billion tokens with 18 decimals\n // const contractApprovalTx = await bridgeableToken.connect(wallet).approve(bridge.getAddress(), approvalAmount)\n // await contractApprovalTx.wait(1)\n // Assert we are contract owner so we can call ownable methods\n const bridgeOwner = await bridge.owner()\n assertEx(bridgeOwner.toLowerCase() === wallet.address.toLowerCase(), () => 'Wallet is not the owner of the bridge contract')\n const remoteConfirmationDepth = getRemoteConfirmationDepth(config as BridgeConfig)\n return {\n account,\n bridge,\n bridgeableToken,\n bridgeFulfillmentMap,\n config: config as BridgeConfig,\n ethTxStateMap,\n evmBridgeCursorMap,\n gateway,\n provider,\n remoteConfirmationDepth,\n wallet,\n xl1TxStateMap,\n }\n}\n", "import { BaseMongoSdk, type BaseMongoSdkPrivateConfig } from '@xylabs/mongo'\nimport { MongoMap } from '@xyo-network/chain-protocol-driver-mongodb'\nimport type { BaseConfig, IterableMap } from '@xyo-network/xl1-sdk'\nimport { hasMongoConfig, mapToMapType } from '@xyo-network/xl1-sdk'\nimport type { Document } from 'mongodb'\n\n/**\n * Gets an iterable map based on the storage instructions in the config\n * @param config The config containing storage instructions\n * @param collection The collection to use if using MongoDB for persistence\n * @returns The iterable map\n */\nexport const getIterableMap = async <K extends {} = string, V extends Document = Document>(\n config: BaseConfig,\n collection: string,\n): Promise<IterableMap<K, V>> => {\n const mongoConfig = config.storage?.mongo\n if (hasMongoConfig(mongoConfig)) {\n const {\n connectionString: dbConnectionString, database: dbName, domain: dbDomain, password: dbPassword, username: dbUserName,\n } = mongoConfig\n const payloadSdkConfig: BaseMongoSdkPrivateConfig = {\n dbConnectionString, dbDomain, dbName, dbPassword, dbUserName,\n }\n const sdkBalanceSummaryMap = new BaseMongoSdk<V>({ ...payloadSdkConfig, collection })\n const result = await MongoMap.create<MongoMap<K, V>>({\n sdk: sdkBalanceSummaryMap,\n getCache: { enabled: true, maxEntries: 5000 },\n })\n return result\n } else {\n return mapToMapType(new Map<K, V>())\n }\n}\n", "import type { BridgeConfig } from '@xyo-network/chain-orchestration'\n\nimport type { IBridgeServiceCollection } from '../services/index.ts'\nimport {\n createWorkers, getConnection,\n getTelemetry,\n} from '../services/queue/index.ts'\n\nexport const addWorkers = (config: BridgeConfig, services: IBridgeServiceCollection) => {\n const connection = getConnection(config)\n const telemetry = getTelemetry()\n createWorkers(connection, telemetry, services)\n}\n", "import type { Server } from 'node:http'\n\nimport type { BridgeConfigContext } from '@xyo-network/chain-orchestration'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\n\nimport type { IBridgeServiceCollection } from '../services/index.ts'\nimport { getServices } from '../services/index.ts'\nimport { addWorkers } from './addWorkers.ts'\nimport { getApp } from './app.ts'\n\nexport interface GetServerResult {\n server: Server\n services: IBridgeServiceCollection\n}\n\nconst hostname = '::'\n// const hostname = '0.0.0.0'\n\nexport const getServer = async (context: BridgeConfigContext, gateway: XyoGatewayRunner): Promise<GetServerResult> => {\n const { logger, config } = context\n const { port } = config\n const app = getApp(config, gateway)\n const services = await getServices(context, gateway)\n app.services = services\n addWorkers(config, services)\n const server = await new Promise<ReturnType<typeof app.listen>>((resolve, reject) => {\n const srv = app.listen(port, hostname, () => {\n logger?.log(`[Bridge] Server listening at http://${hostname}:${port}`)\n resolve(srv)\n })\n srv.once('error', reject)\n })\n server.setTimeout(20_000)\n return { server, services }\n}\n", "import type { Gauge, Meter } from '@opentelemetry/api'\nimport type { AccountInstance } from '@xyo-network/sdk-js'\nimport type { BridgeableToken, LiquidityPoolBridge } from '@xyo-network/typechain'\nimport type { XyoGatewayRunner } from '@xyo-network/xl1-sdk'\nimport type { Provider, Wallet } from 'ethers'\n\nexport interface BalanceMonitorConfig {\n account: AccountInstance\n bridge: LiquidityPoolBridge\n bridgeableToken: BridgeableToken\n gateway: XyoGatewayRunner\n intervalMs?: number\n meter: Meter\n provider: Provider\n wallet: Wallet\n}\n\nexport interface BalanceMonitorHandle {\n start: () => void\n stop: () => void\n}\n\nconst DEFAULT_INTERVAL_MS = 60_000\n\nconst WEI_PER_GWEI = 10n ** 9n\nconst TOKEN_DECIMALS = 10n ** 18n\n\nexport function createBalanceMonitor(config: BalanceMonitorConfig): BalanceMonitorHandle {\n const {\n account, bridge, bridgeableToken, gateway, meter, provider, wallet,\n intervalMs = DEFAULT_INTERVAL_MS,\n } = config\n\n let timer: ReturnType<typeof setInterval> | undefined\n\n const ethWalletGasBalance: Gauge = meter.createGauge(\n 'bridge_eth_wallet_gas_balance_gwei',\n { description: 'ETH balance of the bridge runner wallet (in gwei)', unit: 'gwei' },\n )\n\n const liquidityTokenBalance: Gauge = meter.createGauge(\n 'bridge_eth_liquidity_token_balance',\n { description: 'ERC-20 token balance of the liquidity source (in whole tokens)', unit: 'tokens' },\n )\n\n const liquidityTokenAllowance: Gauge = meter.createGauge(\n 'bridge_eth_liquidity_token_allowance',\n { description: 'ERC-20 token allowance from liquidity source to bridge contract (in whole tokens)', unit: 'tokens' },\n )\n\n // This is the XL1 reserve balance \u2014 the account that signs EVM->XL1 reserve transfers\n // (services.account, resolved by BRIDGE_NAME / BRIDGE_ACCOUNT_PATH). Watch this gauge\n // for reserve depletion; the scanner's pre-flight check (validateSufficientXl1ReserveBalance)\n // will start rejecting flows once it falls below the bridge amount.\n const xl1AccountBalance: Gauge = meter.createGauge(\n 'bridge_xl1_account_balance',\n { description: 'XL1 native balance of the bridge reserve account (in whole XL1)', unit: 'xl1' },\n )\n\n const walletAddress = wallet.address\n\n async function poll(): Promise<void> {\n // ETH wallet gas balance\n try {\n const balance = await provider.getBalance(walletAddress)\n ethWalletGasBalance.record(Number(balance / WEI_PER_GWEI), { address: walletAddress })\n } catch (err) {\n console.error('[BalanceMonitor] Failed to read ETH wallet gas balance:', err)\n }\n\n // Liquidity source token balance\n try {\n const liquiditySourceAddress = await bridge.liquiditySource()\n const balance = await bridgeableToken.balanceOf(liquiditySourceAddress)\n liquidityTokenBalance.record(Number(balance / TOKEN_DECIMALS), { address: liquiditySourceAddress })\n } catch (err) {\n console.error('[BalanceMonitor] Failed to read liquidity source token balance:', err)\n }\n\n // Liquidity source token allowance\n try {\n const liquiditySourceAddress = await bridge.liquiditySource()\n const bridgeAddress = await bridge.getAddress()\n const allowance = await bridgeableToken.allowance(liquiditySourceAddress, bridgeAddress)\n liquidityTokenAllowance.record(Number(allowance / TOKEN_DECIMALS), { address: liquiditySourceAddress })\n } catch (err) {\n console.error('[BalanceMonitor] Failed to read liquidity source token allowance:', err)\n }\n\n // XL1 account balance\n try {\n const viewer = gateway.connection.viewer\n if (viewer) {\n const balance = await viewer.account.balance.accountBalance(account.address)\n xl1AccountBalance.record(Number(balance / TOKEN_DECIMALS), { address: account.address.toString() })\n }\n } catch (err) {\n console.error('[BalanceMonitor] Failed to read XL1 account balance:', err)\n }\n }\n\n return {\n start() {\n void poll()\n timer = setInterval(() => void poll(), intervalMs)\n },\n stop() {\n if (timer) {\n clearInterval(timer)\n timer = undefined\n }\n },\n }\n}\n", "import type { Gauge, Meter } from '@opentelemetry/api'\nimport type { Queue } from 'bullmq'\n\nexport interface QueueMetricsConfig {\n intervalMs?: number\n meter: Meter\n /**\n * Map of queue handles keyed by a human-friendly name (used as the `queue_name` label\n * on emitted gauges). Caller is responsible for deduping shared queues \u2014 passing two\n * different handles for the same Redis queue under different names will emit duplicate\n * metrics. BridgeActor merges getXl1ToEthQueues + getEthToXl1Queues here, where the\n * shared XL1 queues collide on identical key names so spread-merge dedupes naturally.\n */\n queues: Record<string, Queue>\n}\n\nexport interface QueueMetricsHandle {\n start: () => void\n stop: () => void\n}\n\nconst DEFAULT_INTERVAL_MS = 30_000\n\nexport function createQueueMetrics(config: QueueMetricsConfig): QueueMetricsHandle {\n const {\n meter, queues,\n intervalMs = DEFAULT_INTERVAL_MS,\n } = config\n\n let timer: ReturnType<typeof setInterval> | undefined\n\n const waitingGauge: Gauge = meter.createGauge(\n 'bridge_queue_waiting',\n { description: 'Number of waiting jobs in the bridge queue' },\n )\n\n const activeGauge: Gauge = meter.createGauge(\n 'bridge_queue_active',\n { description: 'Number of active jobs in the bridge queue' },\n )\n\n const completedGauge: Gauge = meter.createGauge(\n 'bridge_queue_completed',\n { description: 'Number of completed jobs in the bridge queue' },\n )\n\n const failedGauge: Gauge = meter.createGauge(\n 'bridge_queue_failed',\n { description: 'Number of failed jobs in the bridge queue' },\n )\n\n const delayedGauge: Gauge = meter.createGauge(\n 'bridge_queue_delayed',\n { description: 'Number of delayed jobs in the bridge queue' },\n )\n\n async function poll(): Promise<void> {\n for (const [name, queue] of Object.entries(queues)) {\n try {\n const counts = await queue.getJobCounts('waiting', 'active', 'completed', 'failed', 'delayed')\n const attrs = { queue_name: name }\n waitingGauge.record(counts.waiting ?? 0, attrs)\n activeGauge.record(counts.active ?? 0, attrs)\n completedGauge.record(counts.completed ?? 0, attrs)\n failedGauge.record(counts.failed ?? 0, attrs)\n delayedGauge.record(counts.delayed ?? 0, attrs)\n } catch (err) {\n console.error(`[QueueMetrics] Failed to read job counts for queue ${name}:`, err)\n }\n }\n }\n\n return {\n start() {\n void poll()\n timer = setInterval(() => void poll(), intervalMs)\n },\n stop() {\n if (timer) {\n clearInterval(timer)\n timer = undefined\n }\n },\n }\n}\n", "import type { GetLocatorsFromConfig } from '@xyo-network/chain-orchestration'\nimport { BridgeConfigZod } from '@xyo-network/chain-orchestration'\nimport type { Config } from '@xyo-network/xl1-sdk'\nimport type { CommandModule } from 'yargs'\n\nimport { runBridge } from './run.ts'\n\nexport function bridgeCommand(getConfiguration: () => Config, getLocatorsFromConfig: GetLocatorsFromConfig): CommandModule {\n return {\n command: 'bridge',\n deprecated: 'Use \"start bridge\" instead',\n describe: 'Run a XL1 Bridge Node',\n handler: async () => {\n const configuration = getConfiguration()\n const { locators, orchestrator } = await getLocatorsFromConfig(['bridge'], configuration)\n await runBridge(BridgeConfigZod.parse(locators['bridge'].context.config), orchestrator, locators['bridge'])\n },\n }\n}\n", "import { exists } from '@xylabs/sdk-js'\nimport type { BridgeConfig, OrchestratorInstance } from '@xyo-network/chain-orchestration'\nimport { initActorWallet } from '@xyo-network/chain-orchestration'\nimport type { ProviderFactoryLocatorInstance } from '@xyo-network/xl1-sdk'\n\nimport { BridgeActor } from './BridgeActor.ts'\n\nexport const getBridgeActor = async (\n config: BridgeConfig,\n locator: ProviderFactoryLocatorInstance,\n) => {\n const account = await initActorWallet({\n config, logger: locator.context.logger, singletons: {}, caches: {},\n })\n return await BridgeActor.create({\n account, config, locator,\n })\n}\n\nexport const runBridge = async (\n config: BridgeConfig,\n orchestrator: OrchestratorInstance,\n locator: ProviderFactoryLocatorInstance,\n) => {\n const bridge = await getBridgeActor(config, locator)\n const actors = [bridge].filter(exists)\n\n for (const actor of actors) {\n await orchestrator.registerActor(actor)\n }\n await orchestrator.start()\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;AAEA,SAAS,iBAAiB;AAI1B,SAAS,SAAS,6BAA6B;AAE/C,SAAS,yBAAyB,wBAAwB;;;ACR1D,SAAS,sBAAsB;AAE/B,SAAS,wBAAwB;AAGjC,OAAO,aAAa;;;ACLpB,SAAS,iBAAiB;AAE1B,SAAS,aAAa;AAEtB,IAAI;AAEJ,IAAM,uBAAuB;AAEtB,IAAM,gBAAgB,CAAC,WAAyB;AACrD,MAAI,UAAU,UAAU,EAAG,QAAO;AAClC,QAAM,EAAE,WAAW,MAAM,WAAW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,QAAQ,OAAO;AACnD,QAAM,SAAS,CAAC,MAAM,EAAE,OAAO,MAAM;AAErC,aAAW,SAAS,QAAQ;AAC1B,UAAM,aAAa,cAAc,KAAK;AAAA,EACxC;AACA,QAAM,aAAa,MAAM;AAC3B;;;ADxBO,SAAS,cAAc,kBAAgC,uBAA6D;AACzH,SAAO;AAAA,IACL,SAAS;AAAA,IACT,YAAY;AAAA,IACZ,UAAU;AAAA,IACV,SAAS,YAAY;AACnB,YAAM,gBAAgB,iBAAiB;AACvC,YAAM,EAAE,UAAU,aAAa,IAAI,MAAM,sBAAsB,CAAC,QAAQ,GAAG,aAAa;AACxF,YAAM,UAAU,gBAAgB,MAAM,SAAS,QAAQ,EAAE,QAAQ,MAAM,GAAG,cAAc,SAAS,QAAQ,CAAC;AAAA,IAC5G;AAAA,EACF;AACF;",
6
+ "names": ["isDefined", "connection", "telemetry", "isDefined", "assertEx", "options", "toHex", "PayloadBuilder", "options", "toHex", "PayloadBuilder", "assertEx", "PayloadBuilder", "connection", "telemetry", "assertEx", "Worker", "name", "queueName", "createWorker", "connection", "telemetry", "Worker", "assertEx", "PayloadBuilder", "Worker", "name", "queueName", "createWorker", "connection", "telemetry", "assertEx", "Worker", "PayloadBuilder", "assertEx", "hexToBigInt", "PayloadBuilder", "isBridgeIntent", "Worker", "hexToBigInt", "hexToBigInt", "PayloadBuilder", "asHex", "asAddress", "assertEx", "asAddress", "assertEx", "assertEx", "assertEx", "assertEx", "assertEx", "isDefined", "assertEx", "isDefined", "isDefined", "assertEx", "isDefined", "isDefined", "isDefined", "toHex", "toHex", "isDefined", "hexToBigInt", "toHex", "hexToBigInt", "toHex", "hexToBigInt", "createTransferPayload", "toAddress", "PayloadBuilder", "BridgeIntentSchema", "toAddress", "PayloadBuilder", "BridgeIntentSchema", "hexToBigInt", "PayloadBuilder", "asAddress", "PayloadBuilder", "BridgeIntentSchema", "BridgeIntentSchema", "PayloadBuilder", "asAddress", "assertEx", "hexToBigInt", "isBridgeIntent", "assertEx", "hexToBigInt", "isBridgeIntent", "assertEx", "assertEx", "asAddress", "assertEx", "hexToBigInt", "assertEx", "asAddress", "hexToBigInt", "name", "queueName", "createWorker", "connection", "telemetry", "assertEx", "Worker", "PayloadBuilder", "isBridgeIntent", "hexToBigInt", "assertEx", "isDefined", "PayloadBuilder", "Worker", "name", "queueName", "createWorker", "connection", "telemetry", "assertEx", "Worker", "PayloadBuilder", "isDefined", "assertEx", "isDefined", "PayloadBuilder", "Worker", "name", "queueName", "createWorker", "connection", "telemetry", "assertEx", "Worker", "PayloadBuilder", "isDefined", "assertEx", "hexToBigInt", "isDefined", "isNull", "toHex", "PayloadBuilder", "Worker", "name", "queueName", "assertEx", "isDefined", "isNull", "toHex", "hexToBigInt", "PayloadBuilder", "createWorker", "connection", "telemetry", "Worker", "Worker", "name", "queueName", "createWorker", "connection", "telemetry", "Worker", "assertEx", "isDefined", "isNull", "PayloadBuilder", "UnrecoverableError", "Worker", "name", "queueName", "createWorker", "connection", "telemetry", "assertEx", "Worker", "PayloadBuilder", "isDefined", "isNull", "submissionHash", "UnrecoverableError", "assertEx", "PayloadBuilder", "Worker", "name", "queueName", "createWorker", "connection", "telemetry", "assertEx", "Worker", "PayloadBuilder", "assertEx", "isDefined", "PayloadBuilder", "Worker", "name", "queueName", "createWorker", "connection", "telemetry", "assertEx", "Worker", "PayloadBuilder", "isDefined", "assertEx", "isDefined", "PayloadBuilder", "Worker", "name", "queueName", "createWorker", "connection", "telemetry", "assertEx", "Worker", "PayloadBuilder", "isDefined", "connection", "telemetry", "flowProducer", "PayloadBuilder", "flowProducer", "flowProducer", "connection", "Queue", "connection", "Queue", "options", "flowProducer", "isUndefined", "options", "isUndefined", "Queue", "Worker", "options", "connection", "telemetry", "Queue", "Worker", "options", "connection", "flowProducer", "telemetry", "isDefined", "connection", "telemetry", "flowProducer", "setRawResponseFormat", "ReasonPhrases", "message", "handler", "setRawResponseFormat", "ReasonPhrases", "message", "handler", "requestHandlerValidator", "assertEx", "hexToBigInt", "toAddress", "BridgeIntentSchema", "asHex", "isUndefined", "asHex", "isUndefined", "BridgeIntentSchema", "validateRequest", "requestHandlerValidator", "hexToBigInt", "assertEx", "toAddress", "requestHandlerValidator", "hexToBigInt", "isDefined", "toHex", "PayloadZodStrictOfSchema", "BridgeIntentFieldsZod", "BridgeIntentSchema", "BridgeSourceObservationSchema", "z", "PayloadZodStrictOfSchema", "BridgeIntentSchema", "BridgeIntentFieldsZod", "BridgeSourceObservationSchema", "z", "toHex", "hexToBigInt", "validateRequest", "requestHandlerValidator", "isDefined", "requestHandlerValidator", "isDefined", "PayloadBuilder", "PayloadZodStrictOfSchema", "BridgeIntentFieldsZod", "BridgeIntentSchema", "BridgeSourceObservationFieldsZod", "BridgeSourceObservationSchema", "TransferZod", "z", "z", "BridgeIntentSchema", "BridgeIntentFieldsZod", "TransferZod", "PayloadZodStrictOfSchema", "BridgeSourceObservationSchema", "BridgeSourceObservationFieldsZod", "validateRequest", "requestHandlerValidator", "flowProducer", "isDefined", "PayloadBuilder", "requestHandlerValidator", "assertEx", "hexToBigInt", "toAddress", "PayloadZodStrictOfSchema", "BridgeIntentFieldsZod", "BridgeIntentSchema", "buildUnsignedTransaction", "toXL1BlockNumber", "TransactionBoundWitnessZod", "TransferZod", "z", "BridgeIntentFieldsZod", "z", "TransactionBoundWitnessZod", "PayloadZodStrictOfSchema", "BridgeIntentSchema", "TransferZod", "validateRequest", "requestHandlerValidator", "hexToBigInt", "toAddress", "assertEx", "toXL1BlockNumber", "buildUnsignedTransaction", "requestHandlerValidator", "assertEx", "hexToBigInt", "toAddress", "toHex", "PayloadZodStrictOfSchema", "BridgeIntentFieldsZod", "BridgeIntentSchema", "buildUnsignedTransaction", "toXL1BlockNumber", "TransactionBoundWitnessZod", "TransferZod", "z", "BridgeIntentFieldsZod", "z", "TransactionBoundWitnessZod", "PayloadZodStrictOfSchema", "BridgeIntentSchema", "TransferZod", "validateRequest", "requestHandlerValidator", "toHex", "hexToBigInt", "toAddress", "assertEx", "toXL1BlockNumber", "buildUnsignedTransaction", "requestHandlerValidator", "asHex", "isDefined", "PayloadBuilder", "PayloadZodStrictOfSchema", "BridgeDestinationObservationFieldsZod", "BridgeDestinationObservationSchema", "BridgeIntentFieldsZod", "BridgeIntentSchema", "BridgeSourceObservationFieldsZod", "BridgeSourceObservationSchema", "isBridgeIntent", "z", "BridgeIntentResponseZod", "PayloadZodStrictOfSchema", "BridgeIntentSchema", "BridgeIntentFieldsZod", "BridgeSourceResponseZod", "BridgeSourceObservationSchema", "BridgeSourceObservationFieldsZod", "BridgeDestinationResponseZod", "BridgeDestinationObservationSchema", "BridgeDestinationObservationFieldsZod", "z", "validateRequest", "requestHandlerValidator", "isBridgeIntent", "PayloadBuilder", "isDefined", "asHex", "assertEx", "resolveWalletForActor", "getAddress", "resolveWalletForActor", "getAddress", "assertEx", "connection", "telemetry", "DEFAULT_INTERVAL_MS", "name", "connection", "telemetry", "flowProducer"]
7
+ }