@xyo-network/xl1-cli 1.15.26 → 1.15.27

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 (2) hide show
  1. package/dist/cli-min.mjs +1 -1
  2. package/package.json +2 -2
package/dist/cli-min.mjs CHANGED
@@ -352,4 +352,4 @@ if(await(0,o.isDirectory)(a.path))for(const e of this.getSearchPlacesForDir(a,r.
352
352
  if(i.done)throw new Error(`Could not find any folders to iterate through (start from ${e})`);let a=i.value;const s=()=>{
353
353
  /* istanbul ignore if -- @preserve */
354
354
  if((0,o.isDirectorySync)(a.path))for(const e of this.getSearchPlacesForDir(a,r.globalConfigSearchPlacesSync))try{const t=this.#Tn(e);if(!(null===t||t.isEmpty&&this.config.ignoreEmptySearchPlaces))return this.config.transform(t)}catch(e){if("ENOENT"===e.code||"EISDIR"===e.code||"ENOTDIR"===e.code||"EACCES"===e.code)continue;throw e}const e=t.next();return e.done?this.config.transform(null):(a=e.value,this.searchCache?(0,o.emplace)(this.searchCache,a.path,s):s())};return this.searchCache?(0,o.emplace)(this.searchCache,e,s):s()}#Tn(e,n=[]){const r=t.default.readFileSync(e,"utf8");return this.toCosmiconfigResult(e,this.#On(e,r,n))}#On(e,t,r){const i=this.#Fn(e,t);if(!i||!(0,s.hasOwn)(i,"$import"))return i;const a=n.default.dirname(e),{$import:o,...c}=i,u=Array.isArray(o)?o:[o],l=[...r,e];this.validateImports(e,u,l);const d=u.map(e=>{const t=n.default.resolve(a,e),r=this.#Tn(t,l);return r?.config});return(0,s.mergeAll)([...d,c],{mergeArrays:this.config.mergeImportArrays})}#Fn(e,t){if(""===t.trim())return;const r=n.default.extname(e),i=this.config.loaders[r||"noExt"]??this.config.loaders.default;if(!i)throw new Error(`No loader specified for ${(0,a.getExtensionDescription)(r)}`);try{const a=i(e,t);return"package"!==n.default.basename(e,r)?a:(0,o.getPropertyByPath)(a,this.config.packageProp??this.config.moduleName)??null}catch(t){throw t.filepath=e,t}}#Rn(e){try{return t.default.statSync(e),!0}catch(e){return!1}}*#_n(e){switch(this.config.searchStrategy){case"none":return void(yield{path:e,isGlobalConfig:!1});case"project":{let t=e;for(;;){yield{path:t,isGlobalConfig:!1};for(const e of["json","yaml"]){const r=n.default.join(t,`package.${e}`);if(this.#Rn(r))break}const e=n.default.dirname(t);
355
- /* istanbul ignore if -- @preserve */if(e===t)break;t=e}return}case"global":yield*this.getGlobalDirs(e)}}loadSync(e){return this.load(e)}searchSync(e=""){return this.search(e)}};return hFe.ExplorerSync=c,hFe}(),a=aFe(),s=function(e){return e};function o(e,t,n){const r=n.searchPlaces?.map(t=>t.replace("{name}",e));return n.mergeSearchPlaces?[...r??[],...t]:r??t}function c(e,n,i){const c=function(){const e=new r.ExplorerSync({moduleName:"cosmiconfig",stopDir:process.cwd(),searchPlaces:t.metaSearchPlaces,ignoreEmptySearchPlaces:!1,applyPackagePropertyPathToConfiguration:!0,loaders:t.defaultLoaders,transform:s,cache:!0,metaConfigFilePath:null,mergeImportArrays:!0,mergeSearchPlaces:!0,searchStrategy:"none"}).search();if(!e)return null;if(e.config?.loaders)throw new Error("Can not specify loaders in meta config file");if(e.config?.searchStrategy)throw new Error("Can not specify searchStrategy in meta config file");const n={mergeSearchPlaces:!0,...e.config??{}};return{config:(0,a.removeUndefinedValuesFromObject)(n),filepath:e.filepath}}();if(!c)return{...n,...(0,a.removeUndefinedValuesFromObject)(i),loaders:{...n.loaders,...i.loaders}};const u=c.config,l=i.searchPlaces??n.searchPlaces;return{...n,...(0,a.removeUndefinedValuesFromObject)(i),metaConfigFilePath:c.filepath,...u,searchPlaces:o(e,l,u),loaders:{...n.loaders,...i.loaders}}}function u(e){if(null!=e.searchStrategy&&"global"!==e.searchStrategy&&e.stopDir)throw new Error('Can not supply `stopDir` option with `searchStrategy` other than "global"')}e.cosmiconfig=function(e,r={}){const i=function(e,n){return u(n),c(e,{moduleName:e,searchPlaces:(0,t.getDefaultSearchPlaces)(e),ignoreEmptySearchPlaces:!0,cache:!0,transform:s,loaders:t.defaultLoaders,metaConfigFilePath:null,mergeImportArrays:!0,mergeSearchPlaces:!0,searchStrategy:n.stopDir?"global":"none"},n)}(e,r),a=new n.Explorer(i);return{search:a.search.bind(a),load:a.load.bind(a),clearLoadCache:a.clearLoadCache.bind(a),clearSearchCache:a.clearSearchCache.bind(a),clearCaches:a.clearCaches.bind(a)}},e.cosmiconfigSync=function(e,n={}){const i=function(e,n){return u(n),c(e,{moduleName:e,searchPlaces:(0,t.getDefaultSearchPlacesSync)(e),ignoreEmptySearchPlaces:!0,cache:!0,transform:s,loaders:t.defaultLoadersSync,metaConfigFilePath:null,mergeImportArrays:!0,mergeSearchPlaces:!0,searchStrategy:n.stopDir?"global":"none"},n)}(e,n),a=new r.ExplorerSync(i);return{search:a.search.bind(a),load:a.load.bind(a),clearLoadCache:a.clearLoadCache.bind(a),clearSearchCache:a.clearSearchCache.bind(a),clearCaches:a.clearCaches.bind(a)}}}(jTe)),jTe),mFe={exports:{}},gFe={version:"17.2.3"};var yFe=function(){if(fFe)return mFe.exports;fFe=1;const e=L,t=i,r=n,a=b,s=gFe.version,o=["🔐 encrypt with Dotenvx: https://dotenvx.com","🔐 prevent committing .env to code: https://dotenvx.com/precommit","🔐 prevent building .env in docker: https://dotenvx.com/prebuild","📡 add observability to secrets: https://dotenvx.com/ops","👥 sync secrets across teammates & machines: https://dotenvx.com/ops","🗂️ backup and recover secrets: https://dotenvx.com/ops","✅ audit secrets and track compliance: https://dotenvx.com/ops","🔄 add secrets lifecycle management: https://dotenvx.com/ops","🔑 add access controls to secrets: https://dotenvx.com/ops","🛠️ run anywhere with `dotenvx run -- yourcommand`","⚙️ specify custom .env file path with { path: '/custom/path/.env' }","⚙️ enable debug logging with { debug: true }","⚙️ override existing env vars with { override: true }","⚙️ suppress all logs with { quiet: true }","⚙️ write to custom object with { processEnv: myObject }","⚙️ load multiple .env files with { path: ['.env.local', '.env'] }"];function c(e){return"string"==typeof e?!["false","0","no","off",""].includes(e.toLowerCase()):Boolean(e)}function u(e){return process.stdout.isTTY?`${e}`:e}const l=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function d(e){console.log(`[dotenv@${s}][DEBUG] ${e}`)}function p(e){console.log(`[dotenv@${s}] ${e}`)}function h(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function f(e,t){let n;try{n=new URL(t)}catch(e){if("ERR_INVALID_URL"===e.code){const e=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw e.code="INVALID_DOTENV_KEY",e}throw e}const r=n.password;if(!r){const e=new Error("INVALID_DOTENV_KEY: Missing key part");throw e.code="INVALID_DOTENV_KEY",e}const i=n.searchParams.get("environment");if(!i){const e=new Error("INVALID_DOTENV_KEY: Missing environment part");throw e.code="INVALID_DOTENV_KEY",e}const a=`DOTENV_VAULT_${i.toUpperCase()}`,s=e.parsed[a];if(!s){const e=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code="NOT_FOUND_DOTENV_ENVIRONMENT",e}return{ciphertext:s,key:r}}function A(n){let r=null;if(n&&n.path&&n.path.length>0)if(Array.isArray(n.path))for(const t of n.path)e.existsSync(t)&&(r=t.endsWith(".vault")?t:`${t}.vault`);else r=n.path.endsWith(".vault")?n.path:`${n.path}.vault`;else r=t.resolve(process.cwd(),".env.vault");return e.existsSync(r)?r:null}function m(e){return"~"===e[0]?t.join(r.homedir(),e.slice(1)):e}const g={configDotenv:function(n){const r=t.resolve(process.cwd(),".env");let i="utf8",a=process.env;n&&null!=n.processEnv&&(a=n.processEnv);let s=c(a.DOTENV_CONFIG_DEBUG||n&&n.debug),l=c(a.DOTENV_CONFIG_QUIET||n&&n.quiet);n&&n.encoding?i=n.encoding:s&&d("No encoding is specified. UTF-8 is used by default");let h,f=[r];if(n&&n.path)if(Array.isArray(n.path)){f=[];for(const e of n.path)f.push(m(e))}else f=[m(n.path)];const A={};for(const t of f)try{const r=g.parse(e.readFileSync(t,{encoding:i}));g.populate(A,r,n)}catch(e){s&&d(`Failed to load ${t} ${e.message}`),h=e}const y=g.populate(a,A,n);if(s=c(a.DOTENV_CONFIG_DEBUG||s),l=c(a.DOTENV_CONFIG_QUIET||l),s||!l){const e=Object.keys(y).length,n=[];for(const e of f)try{const r=t.relative(process.cwd(),e);n.push(r)}catch(t){s&&d(`Failed to load ${e} ${t.message}`),h=t}p(`injecting env (${e}) from ${n.join(",")} ${u(`-- tip: ${o[Math.floor(Math.random()*o.length)]}`)}`)}return h?{parsed:A,error:h}:{parsed:A}},_configVault:function(e){const t=c(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=c(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);!t&&n||p("Loading env from encrypted .env.vault");const r=g._parseVault(e);let i=process.env;return e&&null!=e.processEnv&&(i=e.processEnv),g.populate(i,r,e),{parsed:r}},_parseVault:function(e){const t=A(e=e||{});e.path=t;const n=g.configDotenv(e);if(!n.parsed){const e=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code="MISSING_DATA",e}const r=h(e).split(","),i=r.length;let a;for(let e=0;e<i;e++)try{const t=f(n,r[e].trim());a=g.decrypt(t.ciphertext,t.key);break}catch(t){if(e+1>=i)throw t}return g.parse(a)},config:function(e){if(0===h(e).length)return g.configDotenv(e);const t=A(e);return t?g._configVault(e):(n=`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`,console.error(`[dotenv@${s}][WARN] ${n}`),g.configDotenv(e));var n},decrypt:function(e,t){const n=Buffer.from(t.slice(-64),"hex");let r=Buffer.from(e,"base64");const i=r.subarray(0,12),s=r.subarray(-16);r=r.subarray(12,-16);try{const e=a.createDecipheriv("aes-256-gcm",n,i);return e.setAuthTag(s),`${e.update(r)}${e.final()}`}catch(e){const t=e instanceof RangeError,n="Invalid key length"===e.message,r="Unsupported state or unable to authenticate data"===e.message;if(t||n){const e=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw e.code="INVALID_DOTENV_KEY",e}if(r){const e=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw e.code="DECRYPTION_FAILED",e}throw e}},parse:function(e){const t={};let n,r=e.toString();for(r=r.replace(/\r\n?/gm,"\n");null!=(n=l.exec(r));){const e=n[1];let r=n[2]||"";r=r.trim();const i=r[0];r=r.replace(/^(['"`])([\s\S]*)\1$/gm,"$2"),'"'===i&&(r=r.replace(/\\n/g,"\n"),r=r.replace(/\\r/g,"\r")),t[e]=r}return t},populate:function(e,t,n={}){const r=Boolean(n&&n.debug),i=Boolean(n&&n.override),a={};if("object"!=typeof t){const e=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw e.code="OBJECT_REQUIRED",e}for(const n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(!0===i&&(e[n]=t[n],a[n]=t[n]),r&&d(!0===i?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}};return mFe.exports.configDotenv=g.configDotenv,mFe.exports._configVault=g._configVault,mFe.exports._parseVault=g._parseVault,mFe.exports.config=g.config,mFe.exports.decrypt=g.decrypt,mFe.exports.parse=g.parse,mFe.exports.populate=g.populate,mFe.exports=g,mFe.exports}(),bFe=Object.defineProperty,vFe=(e,t)=>bFe(e,"name",{value:t,configurable:!0}),EFe=class extends wA{static{vFe(this,"Actor")}_intervals=new Map;_semaphores=new Map;_timeouts=new Map;_active=!1;_displayName;_id;constructor(e,t="Actor",n){const r=n.logger??new MA(wA.defaultLogger??console,()=>`[${t} (${e})] `);super({...n,logger:r}),this._displayName=t,this._id=e}get displayName(){return this._displayName}get id(){return this._id}get name(){return this.constructor.name}get logPrefix(){return`[${this.displayName} (${this.id})] `}registerTimer(e,t,n,r){if(!this._active)return void this.logger?.warn(`Cannot register timer '${e}' because actor is not active.`);let i=!1;this._semaphores.set(e,new bA(1));const a=setTimeout(()=>{const n=setInterval(()=>{const n=this._semaphores.get(e);this._active&&this._intervals.has(e)&&n&&!i&&(n.isLocked()?this.logger?.warn(`Skipping timer '${this.name}:${e}' execution because previous execution is still running.`):n.acquire().then(([,n])=>{const a=Date.now();i=!0,t().then(()=>{const t=Date.now()-a;t>r?this.logger?.warn(`Timer '${this.name}:${e}' execution took longer (${t}ms) than the period (${r}ms).`):t>5e3&&this.logger?.warn(`Timer '${this.name}:${e}' execution took longer (${t}ms) than 5000ms.`)}).catch(t=>{this.logger?.error(`Error in timer '${this.name}:${e}': ${t}`)}).finally(()=>{n(),i=!1})}).catch(t=>{this.logger?.error(`Error acquiring semaphore for timer '${this.name}:${e}': ${t}`)}))},r);this._intervals.set(e,n)},n);this._timeouts.set(e,a),this.logger?.log(`Timer '${this.name}:${e}' registered: first call after ${n}ms, recurring every ${r}ms.`)}span(e,t){return jA(`${this.name}:${e}`,t,this.tracer)}async spanAsync(e,t){return await LA(`${this.name}:${e}`,t,this.tracer)}async start(){await Promise.resolve(),this._active=!0,this.logger?.log("Started.")}async stop(){await Promise.resolve(),this._active=!1,this.logger?.log("Stopping all timers..."),await Promise.all([...this._semaphores.values()].map(async e=>{for(;e.isLocked();)this.logger?.log("Waiting for running timer task to complete..."),await TA(500);await e.acquire()})),this._semaphores.clear();for(const[,e]of this._timeouts.entries())clearTimeout(e);this._timeouts.clear();for(const[,e]of this._intervals.entries())clearInterval(e);this._intervals.clear(),this.logger?.log("Stopped.")}},IFe=class{static{vFe(this,"Orchestrator")}actors=[];keepAliveHandle=null;logger;running=!1;constructor(e){this.logger=e}async registerActor(e){this.running&&await e.start(),this.actors.push(e)}async start(){if(await Promise.resolve(),this.running)this.logger?.warn("[Orchestrator] Already started.");else{this.logger?.log("[Orchestrator] Starting..."),this.running=!0;for(const e of this.actors)await e.start();this.keepAliveHandle=setInterval(()=>{},2147483647)}}async stop(){if(await Promise.resolve(),this.running){this.logger?.log("[Orchestrator] Stopping...");for(const e of this.actors)await e.stop();this.running=!1,this.keepAliveHandle&&clearInterval(this.keepAliveHandle),this.logger?.log("[Orchestrator] Stopped...")}else this.logger?.log("[Orchestrator] Already stopped.")}},wFe=class e extends EFe{static{vFe(this,"BalanceActor")}_updateMutex=new IA;constructor(e){super("BalanceActor","Balance",e)}get balanceService(){return Le(this.params.balance,()=>"balanceService not set")}get chainIterator(){return Le(this.params.chainIterator,()=>"chainIterator not set")}static create(t){return new e(t)}async start(){await super.start(),this.chainIterator.on("headUpdate",async()=>{await this.updateBalance()}),this.registerTimer("BalanceTimer",async()=>{await this.updateBalance()},1e3,1e4)}async updateBalance(){this._updateMutex.isLocked()||await this._updateMutex.runExclusive(async()=>{const e=await mA.hash(await this.chainIterator.head());await this.balanceService.balances(e,[])})}},CFe=class e extends EFe{static{vFe(this,"ChainHeadUpdateActor")}constructor(e){super("ChainHeadUpdate","ChainHeadUpdate",e)}get chainFinalizedArchivist(){return Le(this.params.chainArchivist,()=>"ChainArchivist not set")}get chainIterator(){return Le(this.params.chainIterator,()=>"chainIterator not set")}static create(t){return new e(t)}async start(){await super.start(),this.chainFinalizedArchivist.on("inserted",async e=>{await this.checkInsertedForNewHead(e)}),this.registerTimer("ChainHeadUpdateTimer",async()=>await this.pollForNewHead(),0,2500)}async checkInsertedForNewHead(e){const t=d$(GA(e.payloads,jj)).at(-1);await this.updateHeadIfNewer(t)}async pollForNewHead(){const e=await I$(this.chainFinalizedArchivist);await this.updateHeadIfNewer(e)}async updateHeadIfNewer(e){if(!e)return;const t=await this.chainIterator.head(),n=e.block,r=`0x${_h(n)}`;n>(t?.block??-1)&&(this.logger?.log("Found more recent head:",n,r),await this.chainIterator.updateHead(e),this.logger?.log("Updated head:",n,r))}},BFe=6e5,DFe=class e extends EFe{static{vFe(this,"ProducerActor")}_lastProducedBlock;_lastRedeclarationIntent;constructor(e){super(e.producer.address,"Producer",e)}get account(){return Le(this.params.account,()=>"account not set")}get balanceService(){return Le(this.params.balance,()=>"balanceService not set")}get chainIterator(){return Le(this.params.chainIterator,()=>"chainIterator not set")}get chainStakeViewer(){return Le(this.params.chainStakeViewer,()=>"chainStakeViewer not set")}get chainSubmissionsArchivistWrite(){return Le(this.params.chainSubmissionsArchivistWrite,()=>"chainSubmissionsArchivistWrite not set")}get pendingBundledTransactionsArchivistWrite(){return Le(this.params.pendingBundledTransactionsArchivistWrite,()=>"pendingBundledTransactionsArchivistWrite not set")}get producer(){return Le(this.params.producer,()=>"producer not set")}get stakeIntentService(){return Le(this.params.stakeIntent,()=>"stakeIntentService not set")}static create(t){return new e(t)}async start(){await super.start(),this.registerTimer("BlockProductionTimer",async()=>{await this.produceBlock()},100,1500),this.registerTimer("ProducerRedeclarationTimer",async()=>{await this.redeclareIntent()},BFe,BFe)}async calculateBlocksUntilProducerDeclarationExpiration(e){const t=(await this.stakeIntentService.getDeclaredCandidateRanges(this.account.address,"producer")).toSorted((e,t)=>e[1]>t[1]?1:-1).at(-1),[,n]=t??[void 0,e];return n-e}async produceBlock(){await this.spanAsync("produceBlock",async()=>{const e=Date.now(),t=await this.chainIterator.head(),n=Date.now()-e;n>500&&this.logger?.warn(`[Slow] Fetched head in ${n}ms: 0x${_h(t._hash)}`);const r=t._hash;if(this._lastProducedBlock&&this._lastProducedBlock[0].previous===r)this.logger?.log("Block already produced:",`0x${_h(this._lastProducedBlock[0].block)}`);else{const e=Date.now(),n=await this.producer.next(t),r=Date.now()-e;if(r>1e3&&this.logger?.warn(`[Slow] Generated next block in ${r}ms, block: ${n?.[0]._hash}`),n){const e=`0x${_h(n[0].block)}`;this.logger?.log("Produced block:",e),await this.chainSubmissionsArchivistWrite.insert(mH(n)),this.logger?.log("Published block:",e),this._lastProducedBlock=n}}})}async redeclareIntent(){await this.spanAsync("redeclareIntent",async()=>{if(this.params.config.producer.disableIntentRedeclaration)return;const e=await this.chainIterator.head();if(qe(e))return;const t=e.block;if(await this.calculateBlocksUntilProducerDeclarationExpiration(t)>.1*S5.RedeclarationWindow)return void(this._lastRedeclarationIntent=void 0);if(this._lastRedeclarationIntent){if(this._lastRedeclarationIntent.exp>t)return;this._lastRedeclarationIntent=void 0}if(!await this.validateCurrentBalance())return void this.logger?.error(`Add balance to address ${this.account.address} for the producer to declare it's intent.`);if(!await this.validateCurrentStake())return void this.logger?.error(`Add stake to contract address ${this.params.config.chain.id} for the producer to declare it's intent.`);this.logger?.log("Creating redeclaration intent for producer:",this.account.address);const n=p$(this.account.address,"producer",t,t+S5.RedeclarationDuration);await this.submitRedeclarationIntent(t,n),this._lastRedeclarationIntent=n})}async submitRedeclarationIntent(e,t){this.logger?.log("Submitting redeclaration intent for producer:",this.account.address);const n=await NG(this.chainIterator.chainId,[t],[],this.account,e,e+1e3),r=PG(n),i=n[0]._hash,a=new mA({schema:Uf}).fields({payloads:r,root:i}).build();await this.pendingBundledTransactionsArchivistWrite.insert([a]),this.logger?.log("Submitted redeclaration intent for producer:",this.account.address)}async validateCurrentBalance(){const e=this._lastProducedBlock?.[0]._hash;if(ze(e)){return!(((await this.balanceService.balances(e,[this.account.address]))[this.account.address]??0n)<=0n)||(this.logger?.error(`Producer ${this.account.address} has no balance.`),!1)}return!0}async validateCurrentStake(){const e=this.stakeIntentService.getRequiredMinimumStakeForIntent("producer");return!(await this.chainStakeViewer.activeByStaked(this.account.address)<e)||(this.logger?.error(`Producer ${this.account.address} has insufficient stake.`),!1)}};(class e extends EFe{static{vFe(this,"ValidatorActor")}_lastValidatedBlock;_lastValidatedBlockHash;constructor(e){super("Validator","Validator",e)}get account(){return Le(this.params.account,()=>"account not set")}get balanceService(){return Le(this.params.balance,()=>"balanceService not set")}get chainIterator(){return Le(this.params.chainIterator,()=>"chainIterator not set")}get chainStakeViewer(){return Le(this.params.chainStakeViewer,()=>"chainStakeViewer not set")}get chainSubmissionsArchivistWrite(){return Le(this.params.chainSubmissionsArchivistWrite,()=>"chainSubmissionsArchivistWrite not set")}get pendingBundledTransactionsArchivistWrite(){return Le(this.params.pendingBundledTransactionsArchivistWrite,()=>"pendingBundledTransactionsArchivistWrite not set")}get stakeIntentService(){return Le(this.params.stakeIntent,()=>"stakeIntentService not set")}static create(t){return new e(t)}async start(){await super.start(),this.registerTimer("BlockProductionTimer",async()=>{await this.spanAsync("produceBlock",async()=>{const e=await this.chainIterator.head();if(qe(e))return;const t=await mA.hash(e);if(ze(this._lastValidatedBlock)&&this._lastValidatedBlockHash===t)this.logger?.log("Block already validated:",`0x${_h(e.block)}`);else{this.logger?.log("Validating block:",`0x${_h(e.block)}`);await this.validateBlock(e)?this.logger?.log("Validated block:",`0x${_h(e.block)}`):(this.logger?.log("Invalid block:",`0x${_h(e.block)}`),await this.slashInvalidBlock(e))}})},100,1500)}async slashInvalidBlock(e){return await Promise.resolve(!0)}async validateBlock(e){const t=await Promise.resolve(!0);return this._lastValidatedBlock=e,this._lastValidatedBlockHash=await mA.hash(e),t}});var xFe,SFe,kFe,TFe=vFe((e,t,n)=>{const r="started"===t?200:n;e.writeHead(r,{"Content-Type":"application/json"}),e.end(JSON.stringify({status:t}))},"sendStatus"),_Fe=vFe(e=>{e.writeHead(404,{"Content-Type":"application/json"}),e.end(JSON.stringify({status:"not found"}))},"notFound"),OFe=vFe((e,t,n)=>{const r=N.createServer((e,n)=>{const r=e.url??"",i=t.getGlobalStatus();switch(r){case"/healthz":TFe(n,i,500);break;case"/livez":case"/readyz":TFe(n,i,503);break;default:_Fe(n)}});return r.listen(e,()=>{n.log(`Health server running on http://localhost:${e}`),n.log(" - /healthz"),n.log(" - /livez"),n.log(" - /readyz")}),r},"createHealthServer"),FFe=vFe(e=>{const{config:t,logger:n,statusReporter:r}=e,{healthCheckPort:i}=t.producer;return ze(i)?OFe(i,r,n):void 0},"initHealthEndpoints"),RFe=i.join(process.cwd(),".store"),NFe=vFe((e,t,n,r,i="lmdb")=>{if("lmdb"===i){const i=r??RFe;return E3.create({account:"random",config:{name:e,clearStoreOnStart:!1,dbName:t,location:m$(t,i,"lmdb"),schema:v3,storeName:n}})}},"getLocalPersistentArchivist"),MFe=new IA,QFe=vFe(async({config:e})=>await MFe.runExclusive(async()=>{if(xFe)return xFe;const{root:t}=e.storage;return xFe=await NFe("local-finalized-chain","chain","finalized",t)}),"initLocalChainFinalizedArchivist"),PFe=new IA,jFe=vFe(async({config:e})=>await PFe.runExclusive(async()=>{if(SFe)return SFe;const{host:t,port:n}=e.api,r=jH(t,n),i=await n6(r);return Le(SFe=await s6({bridge:i,moduleName:"XYOChain:Chain:Finalized"}),()=>"Error: RemoteChainFinalizedArchivist failed to initialize")}),"initRemoteChainFinalizedArchivist"),UFe=new IA;async function LFe({config:e,logger:t,traceProvider:n}){return await UFe.runExclusive(async()=>{if(kFe)return kFe;const[r,i]=await Promise.all([m5("ChainFinalizedArchivist:initRemote",()=>jFe({config:e,logger:t})),m5("ChainFinalizedArchivist:initLocal",()=>QFe({config:e,logger:t}))]);return await m5("ChainFinalizedArchivist:initArchivistSync",()=>X2("ChainFinalizedArchivist",r,i,200,Number.MAX_SAFE_INTEGER,n)),kFe=i})}vFe(LFe,"initChainFinalizedArchivist");var HFe,GFe,qFe,zFe,$Fe,KFe,VFe,YFe=new IA,JFe=vFe(async({config:e})=>await YFe.runExclusive(async()=>{if(HFe)return HFe;const{host:t,port:n}=e.api,r=jH(t,n),i=await n6(r);return Le(HFe=await s6({bridge:i,moduleName:"XYOChain:Chain:Submissions"}),()=>new Error("Failed to initialize RemoteChainSubmissionsArchivist"))}),"initRemoteChainSubmissionsArchivist"),WFe=new IA,ZFe=vFe(async e=>await WFe.runExclusive(async()=>{if(GFe)return GFe;const t=await m5("ChainSubmissionsArchivist:initRemote",()=>JFe(e));return Le(GFe=t,()=>new Error("Failed to initialize ChainSubmissionsArchivist"))}),"initChainSubmissionsArchivist"),XFe=new IA,eRe=vFe(async()=>await XFe.runExclusive(async()=>qFe||(qFe=await Jz.create({account:"random",config:{schema:Vz,max:1e3,name:"localPendingTransactions"}}))),"initLocalPendingTransactionsArchivist"),tRe=new IA,nRe=vFe(async({config:e})=>await tRe.runExclusive(async()=>{if(zFe)return zFe;const{host:t,port:n}=e.api,r=jH(t,n),i=await n6(r);return Le(zFe=await s6({bridge:i,moduleName:"XYOChain:Pending:PendingTransactions"}),()=>"Error: RemotePendingBundledTransactionsArchivist is undefined")}),"initRemotePendingTransactionsArchivist"),rRe=new IA,iRe=vFe(async e=>await rRe.runExclusive(async()=>{if($Fe)return $Fe;const t=await m5("PendingBundledTransactionsArchivist:initRemote",()=>nRe(e)),n=await m5("PendingBundledTransactionsArchivist:initLocal",()=>eRe(e)),r=await t.next({limit:1,order:"desc"});return await n.insert(r),await m5("PendingBundledTransactionsArchivist:initArchivistSync",()=>X2("PendingBundledTransactionsArchivist",t,n)),$Fe=[n,t]}),"initPendingBundledTransactionsArchivist"),aRe=new IA,sRe=vFe(async()=>await aRe.runExclusive(async()=>KFe||(KFe=await Jz.create({account:"random",config:{schema:Vz,max:1e3,name:"localRejectedTransactions"}}))),"initLocalRejectedTransactionsArchivist"),oRe=new IA;async function cRe(e){return await oRe.runExclusive(async()=>{if(VFe)return VFe;const t=await m5("RejectedTransactionsArchivist:initLocal",()=>sRe(e));return VFe=t})}vFe(cRe,"initRejectedTransactionsArchivist");var uRe,lRe,dRe,pRe,hRe=new IA,fRe=vFe(async({config:e})=>await hRe.runExclusive(async()=>{if(uRe)return uRe;const{root:t}=e.storage;return Le(uRe=await NFe("local-stake-intent-state","stakeIntent","state",t),()=>new Error("Failed to initialize stake intent state archivist"))}),"initLocalStakeIntentStateArchivist"),ARe=new IA,mRe=vFe(async e=>await ARe.runExclusive(async()=>{if(lRe)return lRe;const t=await m5("StakeIntentStateArchivist:initLocal",()=>fRe(e));return Le(lRe=t,()=>"Error: StakeIntentStateArchivist is undefined")}),"initStakeIntentStateArchivist"),gRe=new IA,yRe=vFe(async e=>await gRe.runExclusive(async()=>{if(ze(dRe))return dRe;const{root:t}=e.config.storage;return dRe=await y$("balance","summary",t)}),"initLocalBalanceSummaryMap"),bRe=new IA;async function vRe(e){return await bRe.runExclusive(async()=>{if(ze(pRe))return pRe;const t=await m5("BalanceSummaryMap:initLocal",()=>yRe(e));return pRe=t})}vFe(vRe,"initBalanceSummaryMap");var ERe,IRe,wRe,CRe=new IA,BRe=vFe(async e=>await CRe.runExclusive(async()=>{if(ze(ERe))return ERe;const{root:t}=e.config.storage;return ERe=await y$("transfer","summary",t)}),"initLocalTransferSummaryMap"),DRe=new IA;async function xRe(e){return await DRe.runExclusive(async()=>{if(ze(IRe))return IRe;const t=await m5("TransferSummaryMap:initLocal",()=>BRe(e));return IRe=t})}vFe(xRe,"initTransferSummaryMap");var SRe,kRe,TRe,_Re,ORe,FRe,RRe,NRe,MRe,QRe,PRe,jRe,URe,LRe,HRe=vFe(async({config:e,logger:t})=>{if(wRe)return wRe;let n=e.producer.mnemonic;if(qe(n)){t?.warn("[Producer] No wallet mnemonic specified!");const e=pH.generateMnemonic();t?.warn(`[Producer] Using randomly generated mnemonic:\n \n${e}\n \n `),n=e}const r=await ZG(n),i=await r.derivePath(WG);return wRe=i},"initAccount"),GRe=vFe(async e=>SRe||(SRe=await w5.create(e)),"initBalanceService"),qRe=vFe(e=>ze(e.evm.chainId),"canUseChainId"),zRe=vFe(e=>{const t=Le(e.evm.chainId,()=>"Missing config.evm.chainId");if(Bh(t,{prefix:!0})){const e=kh(t);return Number.parseInt(e,16)}return Number.parseInt(t,10)},"getChainId"),$Re=vFe(e=>{if(kRe)return kRe;const t=VRe(e);return kRe=Promise.resolve(new Dx(...t))},"initInfuraProvider"),KRe=vFe(e=>qRe(e)&&ze(e.evm?.infura?.projectId)&&ze(e.evm?.infura?.projectSecret),"canUseInfuraProvider"),VRe=vFe(e=>{const t=Le(e.evm?.infura?.projectId,()=>"Missing config.evm.infura.projectId"),n=Le(e.evm?.infura?.projectSecret,()=>"Missing config.evm.infura.projectSecret");return[zRe(e),t,n]},"getInfuraProviderConfig"),YRe=vFe(e=>{const t=WRe(e);return Promise.resolve(new gD(...t))},"initJsonRpcProvider"),JRe=vFe(e=>qRe(e)&&ze(e.evm.jsonRpc?.url),"canUseJsonRpcProvider"),WRe=vFe(e=>[Le(e.evm.jsonRpc?.url,()=>"Missing config.evm.jsonRpc.url"),zRe(e)],"getJsonRpcProviderConfig"),ZRe=vFe(async({config:e})=>TRe||(KRe(e)?TRe=$Re(e):JRe(e)&&(TRe=YRe(e)),Le(await TRe,()=>"Error: No provider available")),"initEvmProvider"),XRe=vFe(({config:e})=>KRe(e)||JRe(e),"canUseEvmProvider"),eNe=vFe(e=>{const{id:t}=e.chain;return ze(t)&&t!==vh&&XRe({config:e})},"canUseEvmContractChainService"),tNe=vFe(async({account:e,config:t,traceProvider:n,meterProvider:r,logger:i})=>{if(_Re)return _Re;const a=Le(t.chain.id,()=>"Error: config.chain.id is required"),s=Le(Nh(a),()=>"Error: config.chain.id is not a valid address"),o=Le(await ZRe({config:t})),c=Le(e.private?.hex,()=>"Error: Account does not have a private key"),u=new Ck(c,o);return _Re=M5.create({id:s,runner:u,traceProvider:n,meterProvider:r,logger:i}),await _Re},"initEvmContractChainService"),nNe=vFe(({account:e,config:t})=>rNe({config:t,name:"ChainService",account:e}),"initChainService"),rNe=vFe(e=>{if(ORe)return ORe;const{config:t}=e;return ORe=eNe(t)?tNe({...e,name:"ChainStakeService"}):Q5.create({...e,name:"ChainStakeService"})},"init"),iNe=vFe(async(e,t)=>{const n=t.chainId,r=[],i=await u$(e,n,10000000n,e.address);r.push(i);const a=p$(e.address,"producer",i[0].block,i[0].block+1e4),s=await o$(i[0],[],[a],[e]);return r.push(s),r},"createBootstrapHead"),aNe=vFe(()=>18000000000n*VP,"getForkBlockReward"),sNe=vFe(()=>_h(aNe()),"getForkBlockRewardHex"),oNe=_h("0x1"),cNe=_h("0xf72aE3E0DA743033AbD7A407557D684c1aE66aed"),uNe=_h("0x0e65b65B10C791942665030402c35023d88B14dA"),lNe=_h("0x950861b10523b52cdbb4a9ee52ed26601db555d2652bfec21c709e5e70d5b7d3"),dNe=vFe(()=>oNe,"getBridgeDestChainId"),pNe=vFe(()=>cNe,"getBridgeDestToken"),hNe=vFe(()=>uNe,"getBridgeDestAddress"),fNe=vFe(()=>sNe(),"getBridgeDestAmount"),ANe=vFe(()=>lNe,"getBridgeDestConfirmation"),mNe=vFe(()=>({dest:dNe(),destToken:pNe(),destAddress:hNe(),destAmount:fNe()}),"getBridgeDestinationDetails"),gNe=vFe(e=>e.chainId,"getBridgeSrcChainId"),yNe=vFe(e=>e.address,"getBridgeSrcAddress"),bNe=vFe(e=>e.chainId,"getBridgeSrcToken"),vNe=vFe(()=>sNe(),"getBridgeSrcAmount"),ENe=vFe((e,t)=>({src:gNe(t),srcAddress:yNe(e),srcToken:bNe(t),srcAmount:vNe()}),"getBridgeSourceDetails"),INe=vFe(async(e,t,n)=>{const r={...ENe(t,n),...mNe(),destConfirmation:ANe()},i=new mA({schema:ej}).fields(r).build();return await o$(e[0],[],[i],[t])},"getBridgeDestinationObservation"),wNe=vFe(async(e,t,n)=>{const r=e$(t.address,{[qj]:aNe()}),i=`${Date.now()}`,a={...ENe(t,n),...mNe(),nonce:i},s=new mA({schema:rj}).fields(a).build();return await o$(e[0],[],[s,r],[t])},"getBridgeIntent"),CNe=vFe(async(e,t,n)=>{const r=e[0]._hash,i={...ENe(t,n),...mNe(),srcConfirmation:r},a=new mA({schema:sj}).fields(i).build();return await o$(e[0],[],[a],[t])},"getBridgeSourceObservation"),BNe=vFe(async(e,t,n)=>{const{_hash:r,block:i,step_hashes:a,protocol:s}=e,o={blockPayloads:[],chainId:n.chainId,previousBlockHash:r,previousBlockNumber:i,previousStepHashes:a,signers:[t],txs:[],protocol:s,chainStepRewardAddress:$j,stepRewardPoolBalance:WP(0n)};return await a$(o)},"getFirstBlockForNewChain"),DNe=vFe(async(e,t,n)=>{const r=[],i=await BNe(e,t,n);r.push(i);const a=await wNe(i,t,n);r.push(a);const s=await CNe(a,t,n);r.push(s);const o=await INe(s,t,n);return r.push(o),r},"createForkedHead"),xNe=vFe(async(e,t,n)=>{if(e.chain!==t.chainId){const e=await t.forkedAtHash(),r=Uh(Sh(e));if(ze(r)){const[e]=await n.get([r]),i=await t.forkedChainId(),a=Number(await t.forkedAtBlockNumber());if(Pj(e)&&e.chain===i&&e.block===a)return e}}},"getForkFromBlock"),SNe=vFe(async(e,t,n)=>{for(const r of e){const[e]=r;for(await n.insert(mH(r));;){if((await t.get([e._hash])).length>0)break;await TA(1e3)}}},"submitNewChain"),kNe=vFe(async e=>{const{account:t,chainArchivist:n,chainSubmissionsArchivistWrite:r,chainService:i}=e;if(FRe)return FRe;let a=await I$(n);if(a){const e=await xNe(a,i,n);if(ze(e)){const s=await DNe(e,t,i);await SNe(s,n,r);a=Le(s.at(-1),()=>new Error("Failed to get new head after forking"))[0]}}else{const e=await iNe(t,i);await SNe(e,n,r);a=Le(e.at(-1),()=>new Error("Failed to get new head after genesis"))[0]}return FRe=a},"initHead"),TNe=vFe(e=>RRe||(RRe=N5.create(e)),"initChainIterator"),_Ne=vFe(e=>NRe||(NRe=Z5.create(e)),"initStakeIntentService"),ONe=vFe(e=>MRe||(MRe=L5.create(e)),"initElectionService"),FNe=vFe(async e=>QRe||(QRe=await V5.create(e)),"initPendingTransactions"),RNe=vFe(async e=>PRe||(PRe=await S5.create(e)),"initBlockProducer"),NNe=vFe(e=>{if(jRe)return jRe;const{config:t}=e;return jRe=QNe({config:t})?PNe(e):MNe(e)},"initBlockRewardService"),MNe=vFe(e=>jRe||(jRe=R5.create(e)),"initXyoBlockRewardService"),QNe=vFe(e=>XRe({config:e.config}),"canUseEvmBlockRewardService"),PNe=vFe(async e=>{if(jRe)return jRe;const{account:t}=e,n=Le(t,()=>"Error: Account is required"),r=Le(await ZRe(e)),i={...e,provider:r,account:n};return jRe=O5.create(i)},"initEvmBlockRewardService"),jNe=vFe(async({chainArchivist:e,chainIterator:t,config:n,logger:r,meterProvider:i,traceProvider:a})=>{if(URe)return URe;const s=XRe({config:n})?await ZRe({config:n}):void 0;return URe=n3.create({chainArchivist:e,chainIterator:t,ethProvider:s,logger:r,meterProvider:i,traceProvider:a}),await URe},"initTimeService"),UNe=vFe(async e=>LRe||(LRe=await B5.create(e)),"initTransferService"),LNe=class{static{vFe(this,"LoggerStatusReporter")}logger;statusMap={};constructor(e){this.logger=e}report(e,t,n){this.statusMap[e]=t;const r=Object.entries(this.statusMap).map(([,e])=>"starting"===e?1:0).reduce((e,t)=>e+t,0),i=Object.entries(this.statusMap).map(([,e])=>"started"===e?1:0).reduce((e,t)=>e+t,0);this.logger.info(`${i}/${r+i} ${e} status: ${t}`,{progress:n})}},HNe={error:0,stopped:1,stopping:2,creating:3,created:4,starting:5,started:6},GNe="starting",qNe=vFe(e=>{let t=GNe,n=1/0;for(const r of e){const e=HNe[r];e<n&&(n=e,t=r)}return t},"reduceToMinimumStatus"),zNe=class extends LNe{static{vFe(this,"RuntimeStatusMonitor")}globalTransitions=[];transitions=[];getGlobalStatus(){return 0===Object.keys(this.statusMap).length?GNe:qNe(Object.values(this.statusMap))}getStatus(e){return this.statusMap[e]}onGlobalTransition(e,t){this.globalTransitions.push({...e,handler:t})}onTransition(e,t){this.transitions.push({...e,handler:t})}report(e,t,n){const r=this.statusMap[e],i=this.getGlobalStatus();if(super.report(e,t,n),r===t)return;this.runTransitions(this.transitions,r,t,e);const a=this.getGlobalStatus();i!==a&&this.runTransitions(this.globalTransitions,i,a)}runTransitions(e,t,n,r){for(const{from:i,to:a,name:s,handler:o}of e)void 0!==s&&s!==r||void 0!==i&&i!==t||void 0!==a&&a!==n||o(t,n)}},$Ne=vFe(e=>ze(e.start)&&"function"==typeof e.start,"isStartable"),KNe=vFe(async e=>{const{config:t,logger:n}=e,r=new zNe(n);r.onGlobalTransition({to:"started"},()=>{n.log("All services started.")}),r.onGlobalTransition({to:"error"},()=>{n.error("Producer encountered an unhandled error!"),process.exit(1)}),await m5("initHealthEndpoints",()=>FFe({...e,statusReporter:r}));const{otlpEndpoint:i}=t.telemetry?.otel??{},a={attributes:{serviceName:"xl1-producer",serviceVersion:"1.0.0"},otlpEndpoint:i,metricsConfig:{endpoint:"/metrics",port:9464}},[{traceProvider:s,meterProvider:o},c]=await Promise.all([m5("initTelemetry",()=>h3(a)),m5("initAccount",()=>HRe(e))]),u=t.validation?.allowedRewardRedeemers??[],l=t.validation?.allowedRewardEscrowAccountSigners??[],d={config:t,logger:n,meterProvider:o,statusReporter:r,traceProvider:s},[p,[h,f],A,m,g,y,b,v]=await Promise.all([m5("ChainFinalizedArchivist",()=>LFe(d)),m5("PendingBundledTransactionsArchivist",()=>iRe(d)),m5("RejectedTransactionsArchivist",()=>cRe(d)),m5("ChainSubmissionsArchivist",()=>ZFe(d)),m5("StakeIntentStateArchivist",()=>mRe(d)),m5("ChainService",()=>nNe({...d,account:c,name:"ChainService"})),m5("BalanceSummaryMap",()=>vRe(d)),m5("TransferSummaryMap",()=>xRe(d))]),E=y.chainId,I=DG(p),w=y,C=y,B=y,D=await m5("initHead",()=>kNe({...d,account:c,chainArchivist:p,chainSubmissionsArchivistWrite:m,chainService:y})),x=[u0([s0,o0(u),c0(l,"reward-escrow")])],[S,k,T]=await Promise.all([m5("PendingTransactions",()=>FNe({name:"PendingTransactionsService",chainArchivist:p,chainId:E,pendingBundledTransactionsArchivist:h,rejectedTransactionsArchivist:A,additionalPendingTransactionValidators:x,...d})),m5("RewardService",()=>NNe({name:"RewardService",account:c,chainService:y,...d})),m5("ChainIterator",()=>TNe({name:"ChainIterator",chainMap:I,head:D,...d}))]),[_]=await Promise.all([m5("BalanceService",()=>GRe({name:"BalanceService",context:{stepSemaphores:Zj.map(()=>new bA(20)),store:{chainMap:I},head:vFe(async()=>mA.hash(await T.head()),"head"),chainId:E,summaryMap:b},...d})),m5("TransferService",()=>UNe({name:"TransferService",context:{stepSemaphores:Zj.map(()=>new bA(20)),store:{chainMap:I},head:vFe(async()=>mA.hash(await T.head()),"head"),chainId:E,summaryMap:v},...d}))]),[O,F]=await Promise.all([m5("StakeIntentService",()=>_Ne({name:"StakeIntentService",chainArchivist:p,chainIterator:T,chainStakeViewer:C,stakeIntentStateArchivist:g,...d})),m5("TimeService",()=>jNe({name:"TimeService",chainArchivist:p,chainIterator:T,...d}))]),R=await m5("ElectionService",()=>ONe({name:"ElectionService",chainIterator:T,chainStakeViewer:C,stakeIntentService:O,...d})),N={name:"Validator",account:c,chainId:E,pendingBundledTransactionsArchivist:h,chainArchivist:p,electionService:R,rewardService:k,stakeIntentService:O,validateHydratedBlockState:M0,...d},M=ze(t.producer.rewardAddress)?Le(Nh(t.producer.rewardAddress),()=>"Invalid block reward address provided"):c.address,Q={...N,name:"Producer",balanceService:_,chainArchivist:p,pendingBundledTransactionsArchivist:h,pendingTransactionsService:S,rejectedTransactionsArchivist:A,rewardAddress:M,time:F,...d},P=await m5("Producer",()=>RNe(Q)),j={account:c,balance:_,chainArchivist:p,chainContractViewer:w,chainIterator:T,chainStaker:B,chainStakeViewer:C,chainSubmissionsArchivistWrite:m,election:R,pendingBundledTransactionsArchivistWrite:f,pendingTransactions:S,producer:P,reward:k,stakeIntent:O};n?.log("All services created. Starting...");const U=[b,...Object.values(j)].filter($Ne);return Le((await Promise.all(U.map(e=>e.start()))).every(Boolean),()=>"One or more services failed to start"),n?.log("All services started successfully."),j},"initServices");function VNe(e){xke(e)}function YNe(e){Jke(e)}vFe(VNe,"runApi"),vFe(YNe,"runBridge");var JNe=vFe(async e=>{const{config:t,logger:n,orchestrator:r}=e;n?.log("Services: Initializing...");const i=await KNe(e);n?.log("Services: Initialized");const a={...i,config:t},s=[await CFe.create(a),await wFe.create(a),await DFe.create(a)];for(const e of s)await r.registerActor(e);await r.start()},"runProducer");function WNe(e){PTe(e)}vFe(WNe,"runRewardRedemptionApi");var ZNe,XNe=vFe(e=>{let t;if(e.silent)t=new QA;else{let n;if(ze(e.logLevel)){const t=FA[e.logLevel.toLowerCase()];ze(t)&&(n=t)}t=new NA(n)}return wA.defaultLogger=t,t},"initLogger"),eMe=vFe(e=>e,"usageMetaToOptions"),tMe=vFe(()=>{const e={};for(const t of Object.values(uu._map))if(dG(t)){if(t.hidden)continue;e[t.title]=eMe(t)}return e},"optionsFromGlobalZodRegistry"),nMe=vFe(()=>{const e=AFe.cosmiconfigSync("xyo").search();if(!$e(e)){const t=e?.config?.xl1;if(ze(t)&&"object"==typeof t)return t}return{}},"tryParseConfig"),rMe=vFe((e,t)=>new Promise(n=>{const r=vFe(()=>{const i=new se.Socket;i.setTimeout(1e3).once("error",()=>{i.destroy(),setTimeout(r,500)}).once("timeout",()=>{i.destroy(),setTimeout(r,500)}).connect(t,e,()=>{i.end(),n()})},"tryConnect");r()}),"waitForHostPort"),iMe=ze("1.15.25")?"1.15.25":"unknown",aMe=vFe(e=>{const t=XNe(e),n=new IFe(t);return process.on("SIGINT",()=>{(async()=>{try{t.log("\nSIGINT received. Attempting graceful shutdown..."),await(n?.stop()),t.log("Orchestrator stopped, exiting now."),process.exit(0)}catch(e){t.error("Error stopping orchestrator:",e),process.exit(1)}})()}),{logger:t,orchestrator:n}},"getContextFromConfig");async function sMe(){const e=b9(function(e){return e.slice(o8()+1)}(process.argv)),t=e.usage(`\n🚀 XL1 Node CLI (${iMe})\n                    _\n                   ╠╠\n                   ╠╠_\n        ╦╦_       [╠╠▒       _╔╦\n        ²╠▒D╦_    ╠╠╠╠    _╔R▒▒╙\n          ╚▒▒▒D╦ j╠╠╠╠H ╔D▒▒▒╠\n           ²▒▒▒▒ ╠╠╠╠╠╠ ╠▒▒▒╙\n             \`_,╓╠╠╠╠╠╠╓_\`\`\n _,╓╓╔╗φ@D▒╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠▒▒Kφ╗╦╖²__\n \`^╙╙╚╝╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╝╩╜╙^\`\n             \`'"╙╠╠╠╠╠╠╜^^\`\`\n           ,╠▒▒╠ ╠╠╠╠╠╠ å╠╠╠,\n          ╔▒▒▒▒╩ [╠╠╠╠H ╚╠╠╠╠H\n        ,╠▒▒╩^    ╠╠╠╠    '╚╠╠╠,\n        ╩╩^       ╚╠╠╠       '╚╩\n                  '╠╠H\n                   ╠╠\n                   ²^\nRun various components of the XL1 ecosystem.\n\nUsage:\n$0 <command> [options]`).parserConfiguration({"dot-notation":!0,"parse-numbers":!1,"populate--":!0}).env("XL1").scriptName("xl1").middleware(e=>{try{const t=nMe(),n=vt(e,t);ZNe=aG.parse(n)}catch(e){throw e instanceof ad&&console.error(`${e.message}`),new Error("Invalid configuration")}}).options(tMe()).wrap(e.terminalWidth()).command("api","Run a XL1 API Node",e=>e.command("$0","Run a XL1 API Node",()=>{},()=>{VNe({...aMe(ZNe),config:ZNe})})).command("bridge","Run a XL1 Bridge Node",e=>e.command("$0","Run a XL1 Bridge Node",()=>{},()=>{YNe({...aMe(ZNe),config:ZNe})})).command("producer","Run a XL1 Producer Node",e=>e.command("$0","Run a XL1 Producer Node",()=>{},async()=>{const e=aMe(ZNe);await JNe({...e,config:ZNe})})).command("reward-redemption-api","Run a XL1 Rewards Redemption API Node",e=>e.command("$0","Run a XL1 Rewards Redemption API Node",()=>{},()=>{WNe({...aMe(ZNe),config:ZNe})})).command("$0","Run a full XL1 Node",()=>{},async()=>{const e=aMe(ZNe);VNe({...e,config:ZNe}),await rMe("localhost",ZNe.api.port),await JNe({...e,config:ZNe})}).help().alias("help","h").version(iMe).argv;await t}vFe(sMe,"runCLI"),vFe(async()=>{yFe.config({quiet:!0}),await sMe()},"start")().catch(e=>{"development"===process.env.NODE_ENV&&console.error("An error occurred during startup:",e),process.exit(1)});
355
+ /* istanbul ignore if -- @preserve */if(e===t)break;t=e}return}case"global":yield*this.getGlobalDirs(e)}}loadSync(e){return this.load(e)}searchSync(e=""){return this.search(e)}};return hFe.ExplorerSync=c,hFe}(),a=aFe(),s=function(e){return e};function o(e,t,n){const r=n.searchPlaces?.map(t=>t.replace("{name}",e));return n.mergeSearchPlaces?[...r??[],...t]:r??t}function c(e,n,i){const c=function(){const e=new r.ExplorerSync({moduleName:"cosmiconfig",stopDir:process.cwd(),searchPlaces:t.metaSearchPlaces,ignoreEmptySearchPlaces:!1,applyPackagePropertyPathToConfiguration:!0,loaders:t.defaultLoaders,transform:s,cache:!0,metaConfigFilePath:null,mergeImportArrays:!0,mergeSearchPlaces:!0,searchStrategy:"none"}).search();if(!e)return null;if(e.config?.loaders)throw new Error("Can not specify loaders in meta config file");if(e.config?.searchStrategy)throw new Error("Can not specify searchStrategy in meta config file");const n={mergeSearchPlaces:!0,...e.config??{}};return{config:(0,a.removeUndefinedValuesFromObject)(n),filepath:e.filepath}}();if(!c)return{...n,...(0,a.removeUndefinedValuesFromObject)(i),loaders:{...n.loaders,...i.loaders}};const u=c.config,l=i.searchPlaces??n.searchPlaces;return{...n,...(0,a.removeUndefinedValuesFromObject)(i),metaConfigFilePath:c.filepath,...u,searchPlaces:o(e,l,u),loaders:{...n.loaders,...i.loaders}}}function u(e){if(null!=e.searchStrategy&&"global"!==e.searchStrategy&&e.stopDir)throw new Error('Can not supply `stopDir` option with `searchStrategy` other than "global"')}e.cosmiconfig=function(e,r={}){const i=function(e,n){return u(n),c(e,{moduleName:e,searchPlaces:(0,t.getDefaultSearchPlaces)(e),ignoreEmptySearchPlaces:!0,cache:!0,transform:s,loaders:t.defaultLoaders,metaConfigFilePath:null,mergeImportArrays:!0,mergeSearchPlaces:!0,searchStrategy:n.stopDir?"global":"none"},n)}(e,r),a=new n.Explorer(i);return{search:a.search.bind(a),load:a.load.bind(a),clearLoadCache:a.clearLoadCache.bind(a),clearSearchCache:a.clearSearchCache.bind(a),clearCaches:a.clearCaches.bind(a)}},e.cosmiconfigSync=function(e,n={}){const i=function(e,n){return u(n),c(e,{moduleName:e,searchPlaces:(0,t.getDefaultSearchPlacesSync)(e),ignoreEmptySearchPlaces:!0,cache:!0,transform:s,loaders:t.defaultLoadersSync,metaConfigFilePath:null,mergeImportArrays:!0,mergeSearchPlaces:!0,searchStrategy:n.stopDir?"global":"none"},n)}(e,n),a=new r.ExplorerSync(i);return{search:a.search.bind(a),load:a.load.bind(a),clearLoadCache:a.clearLoadCache.bind(a),clearSearchCache:a.clearSearchCache.bind(a),clearCaches:a.clearCaches.bind(a)}}}(jTe)),jTe),mFe={exports:{}},gFe={version:"17.2.3"};var yFe=function(){if(fFe)return mFe.exports;fFe=1;const e=L,t=i,r=n,a=b,s=gFe.version,o=["🔐 encrypt with Dotenvx: https://dotenvx.com","🔐 prevent committing .env to code: https://dotenvx.com/precommit","🔐 prevent building .env in docker: https://dotenvx.com/prebuild","📡 add observability to secrets: https://dotenvx.com/ops","👥 sync secrets across teammates & machines: https://dotenvx.com/ops","🗂️ backup and recover secrets: https://dotenvx.com/ops","✅ audit secrets and track compliance: https://dotenvx.com/ops","🔄 add secrets lifecycle management: https://dotenvx.com/ops","🔑 add access controls to secrets: https://dotenvx.com/ops","🛠️ run anywhere with `dotenvx run -- yourcommand`","⚙️ specify custom .env file path with { path: '/custom/path/.env' }","⚙️ enable debug logging with { debug: true }","⚙️ override existing env vars with { override: true }","⚙️ suppress all logs with { quiet: true }","⚙️ write to custom object with { processEnv: myObject }","⚙️ load multiple .env files with { path: ['.env.local', '.env'] }"];function c(e){return"string"==typeof e?!["false","0","no","off",""].includes(e.toLowerCase()):Boolean(e)}function u(e){return process.stdout.isTTY?`${e}`:e}const l=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function d(e){console.log(`[dotenv@${s}][DEBUG] ${e}`)}function p(e){console.log(`[dotenv@${s}] ${e}`)}function h(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function f(e,t){let n;try{n=new URL(t)}catch(e){if("ERR_INVALID_URL"===e.code){const e=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw e.code="INVALID_DOTENV_KEY",e}throw e}const r=n.password;if(!r){const e=new Error("INVALID_DOTENV_KEY: Missing key part");throw e.code="INVALID_DOTENV_KEY",e}const i=n.searchParams.get("environment");if(!i){const e=new Error("INVALID_DOTENV_KEY: Missing environment part");throw e.code="INVALID_DOTENV_KEY",e}const a=`DOTENV_VAULT_${i.toUpperCase()}`,s=e.parsed[a];if(!s){const e=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code="NOT_FOUND_DOTENV_ENVIRONMENT",e}return{ciphertext:s,key:r}}function A(n){let r=null;if(n&&n.path&&n.path.length>0)if(Array.isArray(n.path))for(const t of n.path)e.existsSync(t)&&(r=t.endsWith(".vault")?t:`${t}.vault`);else r=n.path.endsWith(".vault")?n.path:`${n.path}.vault`;else r=t.resolve(process.cwd(),".env.vault");return e.existsSync(r)?r:null}function m(e){return"~"===e[0]?t.join(r.homedir(),e.slice(1)):e}const g={configDotenv:function(n){const r=t.resolve(process.cwd(),".env");let i="utf8",a=process.env;n&&null!=n.processEnv&&(a=n.processEnv);let s=c(a.DOTENV_CONFIG_DEBUG||n&&n.debug),l=c(a.DOTENV_CONFIG_QUIET||n&&n.quiet);n&&n.encoding?i=n.encoding:s&&d("No encoding is specified. UTF-8 is used by default");let h,f=[r];if(n&&n.path)if(Array.isArray(n.path)){f=[];for(const e of n.path)f.push(m(e))}else f=[m(n.path)];const A={};for(const t of f)try{const r=g.parse(e.readFileSync(t,{encoding:i}));g.populate(A,r,n)}catch(e){s&&d(`Failed to load ${t} ${e.message}`),h=e}const y=g.populate(a,A,n);if(s=c(a.DOTENV_CONFIG_DEBUG||s),l=c(a.DOTENV_CONFIG_QUIET||l),s||!l){const e=Object.keys(y).length,n=[];for(const e of f)try{const r=t.relative(process.cwd(),e);n.push(r)}catch(t){s&&d(`Failed to load ${e} ${t.message}`),h=t}p(`injecting env (${e}) from ${n.join(",")} ${u(`-- tip: ${o[Math.floor(Math.random()*o.length)]}`)}`)}return h?{parsed:A,error:h}:{parsed:A}},_configVault:function(e){const t=c(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=c(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);!t&&n||p("Loading env from encrypted .env.vault");const r=g._parseVault(e);let i=process.env;return e&&null!=e.processEnv&&(i=e.processEnv),g.populate(i,r,e),{parsed:r}},_parseVault:function(e){const t=A(e=e||{});e.path=t;const n=g.configDotenv(e);if(!n.parsed){const e=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code="MISSING_DATA",e}const r=h(e).split(","),i=r.length;let a;for(let e=0;e<i;e++)try{const t=f(n,r[e].trim());a=g.decrypt(t.ciphertext,t.key);break}catch(t){if(e+1>=i)throw t}return g.parse(a)},config:function(e){if(0===h(e).length)return g.configDotenv(e);const t=A(e);return t?g._configVault(e):(n=`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`,console.error(`[dotenv@${s}][WARN] ${n}`),g.configDotenv(e));var n},decrypt:function(e,t){const n=Buffer.from(t.slice(-64),"hex");let r=Buffer.from(e,"base64");const i=r.subarray(0,12),s=r.subarray(-16);r=r.subarray(12,-16);try{const e=a.createDecipheriv("aes-256-gcm",n,i);return e.setAuthTag(s),`${e.update(r)}${e.final()}`}catch(e){const t=e instanceof RangeError,n="Invalid key length"===e.message,r="Unsupported state or unable to authenticate data"===e.message;if(t||n){const e=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw e.code="INVALID_DOTENV_KEY",e}if(r){const e=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw e.code="DECRYPTION_FAILED",e}throw e}},parse:function(e){const t={};let n,r=e.toString();for(r=r.replace(/\r\n?/gm,"\n");null!=(n=l.exec(r));){const e=n[1];let r=n[2]||"";r=r.trim();const i=r[0];r=r.replace(/^(['"`])([\s\S]*)\1$/gm,"$2"),'"'===i&&(r=r.replace(/\\n/g,"\n"),r=r.replace(/\\r/g,"\r")),t[e]=r}return t},populate:function(e,t,n={}){const r=Boolean(n&&n.debug),i=Boolean(n&&n.override),a={};if("object"!=typeof t){const e=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw e.code="OBJECT_REQUIRED",e}for(const n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(!0===i&&(e[n]=t[n],a[n]=t[n]),r&&d(!0===i?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}};return mFe.exports.configDotenv=g.configDotenv,mFe.exports._configVault=g._configVault,mFe.exports._parseVault=g._parseVault,mFe.exports.config=g.config,mFe.exports.decrypt=g.decrypt,mFe.exports.parse=g.parse,mFe.exports.populate=g.populate,mFe.exports=g,mFe.exports}(),bFe=Object.defineProperty,vFe=(e,t)=>bFe(e,"name",{value:t,configurable:!0}),EFe=class extends wA{static{vFe(this,"Actor")}_intervals=new Map;_semaphores=new Map;_timeouts=new Map;_active=!1;_displayName;_id;constructor(e,t="Actor",n){const r=n.logger??new MA(wA.defaultLogger??console,()=>`[${t} (${e})] `);super({...n,logger:r}),this._displayName=t,this._id=e}get displayName(){return this._displayName}get id(){return this._id}get name(){return this.constructor.name}get logPrefix(){return`[${this.displayName} (${this.id})] `}registerTimer(e,t,n,r){if(!this._active)return void this.logger?.warn(`Cannot register timer '${e}' because actor is not active.`);let i=!1;this._semaphores.set(e,new bA(1));const a=setTimeout(()=>{const n=setInterval(()=>{const n=this._semaphores.get(e);this._active&&this._intervals.has(e)&&n&&!i&&(n.isLocked()?this.logger?.warn(`Skipping timer '${this.name}:${e}' execution because previous execution is still running.`):n.acquire().then(([,n])=>{const a=Date.now();i=!0,t().then(()=>{const t=Date.now()-a;t>r?this.logger?.warn(`Timer '${this.name}:${e}' execution took longer (${t}ms) than the period (${r}ms).`):t>5e3&&this.logger?.warn(`Timer '${this.name}:${e}' execution took longer (${t}ms) than 5000ms.`)}).catch(t=>{this.logger?.error(`Error in timer '${this.name}:${e}': ${t}`)}).finally(()=>{n(),i=!1})}).catch(t=>{this.logger?.error(`Error acquiring semaphore for timer '${this.name}:${e}': ${t}`)}))},r);this._intervals.set(e,n)},n);this._timeouts.set(e,a),this.logger?.log(`Timer '${this.name}:${e}' registered: first call after ${n}ms, recurring every ${r}ms.`)}span(e,t){return jA(`${this.name}:${e}`,t,this.tracer)}async spanAsync(e,t){return await LA(`${this.name}:${e}`,t,this.tracer)}async start(){await Promise.resolve(),this._active=!0,this.logger?.log("Started.")}async stop(){await Promise.resolve(),this._active=!1,this.logger?.log("Stopping all timers..."),await Promise.all([...this._semaphores.values()].map(async e=>{for(;e.isLocked();)this.logger?.log("Waiting for running timer task to complete..."),await TA(500);await e.acquire()})),this._semaphores.clear();for(const[,e]of this._timeouts.entries())clearTimeout(e);this._timeouts.clear();for(const[,e]of this._intervals.entries())clearInterval(e);this._intervals.clear(),this.logger?.log("Stopped.")}},IFe=class{static{vFe(this,"Orchestrator")}actors=[];keepAliveHandle=null;logger;running=!1;constructor(e){this.logger=e}async registerActor(e){this.running&&await e.start(),this.actors.push(e)}async start(){if(await Promise.resolve(),this.running)this.logger?.warn("[Orchestrator] Already started.");else{this.logger?.log("[Orchestrator] Starting..."),this.running=!0;for(const e of this.actors)await e.start();this.keepAliveHandle=setInterval(()=>{},2147483647)}}async stop(){if(await Promise.resolve(),this.running){this.logger?.log("[Orchestrator] Stopping...");for(const e of this.actors)await e.stop();this.running=!1,this.keepAliveHandle&&clearInterval(this.keepAliveHandle),this.logger?.log("[Orchestrator] Stopped...")}else this.logger?.log("[Orchestrator] Already stopped.")}},wFe=class e extends EFe{static{vFe(this,"BalanceActor")}_updateMutex=new IA;constructor(e){super("BalanceActor","Balance",e)}get balanceService(){return Le(this.params.balance,()=>"balanceService not set")}get chainIterator(){return Le(this.params.chainIterator,()=>"chainIterator not set")}static create(t){return new e(t)}async start(){await super.start(),this.chainIterator.on("headUpdate",async()=>{await this.updateBalance()}),this.registerTimer("BalanceTimer",async()=>{await this.updateBalance()},1e3,1e4)}async updateBalance(){this._updateMutex.isLocked()||await this._updateMutex.runExclusive(async()=>{const e=await mA.hash(await this.chainIterator.head());await this.balanceService.balances(e,[])})}},CFe=class e extends EFe{static{vFe(this,"ChainHeadUpdateActor")}constructor(e){super("ChainHeadUpdate","ChainHeadUpdate",e)}get chainFinalizedArchivist(){return Le(this.params.chainArchivist,()=>"ChainArchivist not set")}get chainIterator(){return Le(this.params.chainIterator,()=>"chainIterator not set")}static create(t){return new e(t)}async start(){await super.start(),this.chainFinalizedArchivist.on("inserted",async e=>{await this.checkInsertedForNewHead(e)}),this.registerTimer("ChainHeadUpdateTimer",async()=>await this.pollForNewHead(),0,2500)}async checkInsertedForNewHead(e){const t=d$(GA(e.payloads,jj)).at(-1);await this.updateHeadIfNewer(t)}async pollForNewHead(){const e=await I$(this.chainFinalizedArchivist);await this.updateHeadIfNewer(e)}async updateHeadIfNewer(e){if(!e)return;const t=await this.chainIterator.head(),n=e.block,r=`0x${_h(n)}`;n>(t?.block??-1)&&(this.logger?.log("Found more recent head:",n,r),await this.chainIterator.updateHead(e),this.logger?.log("Updated head:",n,r))}},BFe=6e5,DFe=class e extends EFe{static{vFe(this,"ProducerActor")}_lastProducedBlock;_lastRedeclarationIntent;constructor(e){super(e.producer.address,"Producer",e)}get account(){return Le(this.params.account,()=>"account not set")}get balanceService(){return Le(this.params.balance,()=>"balanceService not set")}get chainIterator(){return Le(this.params.chainIterator,()=>"chainIterator not set")}get chainStakeViewer(){return Le(this.params.chainStakeViewer,()=>"chainStakeViewer not set")}get chainSubmissionsArchivistWrite(){return Le(this.params.chainSubmissionsArchivistWrite,()=>"chainSubmissionsArchivistWrite not set")}get pendingBundledTransactionsArchivistWrite(){return Le(this.params.pendingBundledTransactionsArchivistWrite,()=>"pendingBundledTransactionsArchivistWrite not set")}get producer(){return Le(this.params.producer,()=>"producer not set")}get stakeIntentService(){return Le(this.params.stakeIntent,()=>"stakeIntentService not set")}static create(t){return new e(t)}async start(){await super.start(),this.registerTimer("BlockProductionTimer",async()=>{await this.produceBlock()},100,1500),this.registerTimer("ProducerRedeclarationTimer",async()=>{await this.redeclareIntent()},BFe,BFe)}async calculateBlocksUntilProducerDeclarationExpiration(e){const t=(await this.stakeIntentService.getDeclaredCandidateRanges(this.account.address,"producer")).toSorted((e,t)=>e[1]>t[1]?1:-1).at(-1),[,n]=t??[void 0,e];return n-e}async produceBlock(){await this.spanAsync("produceBlock",async()=>{const e=Date.now(),t=await this.chainIterator.head(),n=Date.now()-e;n>500&&this.logger?.warn(`[Slow] Fetched head in ${n}ms: 0x${_h(t._hash)}`);const r=t._hash;if(this._lastProducedBlock&&this._lastProducedBlock[0].previous===r)this.logger?.log("Block already produced:",`0x${_h(this._lastProducedBlock[0].block)}`);else{const e=Date.now(),n=await this.producer.next(t),r=Date.now()-e;if(r>1e3&&this.logger?.warn(`[Slow] Generated next block in ${r}ms, block: ${n?.[0]._hash}`),n){const e=`0x${_h(n[0].block)}`;this.logger?.log("Produced block:",e),await this.chainSubmissionsArchivistWrite.insert(mH(n)),this.logger?.log("Published block:",e),this._lastProducedBlock=n}}})}async redeclareIntent(){await this.spanAsync("redeclareIntent",async()=>{if(this.params.config.producer.disableIntentRedeclaration)return;const e=await this.chainIterator.head();if(qe(e))return;const t=e.block;if(await this.calculateBlocksUntilProducerDeclarationExpiration(t)>.1*S5.RedeclarationWindow)return void(this._lastRedeclarationIntent=void 0);if(this._lastRedeclarationIntent){if(this._lastRedeclarationIntent.exp>t)return;this._lastRedeclarationIntent=void 0}if(!await this.validateCurrentBalance())return void this.logger?.error(`Add balance to address ${this.account.address} for the producer to declare it's intent.`);if(!await this.validateCurrentStake())return void this.logger?.error(`Add stake to contract address ${this.params.config.chain.id} for the producer to declare it's intent.`);this.logger?.log("Creating redeclaration intent for producer:",this.account.address);const n=p$(this.account.address,"producer",t,t+S5.RedeclarationDuration);await this.submitRedeclarationIntent(t,n),this._lastRedeclarationIntent=n})}async submitRedeclarationIntent(e,t){this.logger?.log("Submitting redeclaration intent for producer:",this.account.address);const n=await NG(this.chainIterator.chainId,[t],[],this.account,e,e+1e3),r=PG(n),i=n[0]._hash,a=new mA({schema:Uf}).fields({payloads:r,root:i}).build();await this.pendingBundledTransactionsArchivistWrite.insert([a]),this.logger?.log("Submitted redeclaration intent for producer:",this.account.address)}async validateCurrentBalance(){const e=this._lastProducedBlock?.[0]._hash;if(ze(e)){return!(((await this.balanceService.balances(e,[this.account.address]))[this.account.address]??0n)<=0n)||(this.logger?.error(`Producer ${this.account.address} has no balance.`),!1)}return!0}async validateCurrentStake(){const e=this.stakeIntentService.getRequiredMinimumStakeForIntent("producer");return!(await this.chainStakeViewer.activeByStaked(this.account.address)<e)||(this.logger?.error(`Producer ${this.account.address} has insufficient stake.`),!1)}};(class e extends EFe{static{vFe(this,"ValidatorActor")}_lastValidatedBlock;_lastValidatedBlockHash;constructor(e){super("Validator","Validator",e)}get account(){return Le(this.params.account,()=>"account not set")}get balanceService(){return Le(this.params.balance,()=>"balanceService not set")}get chainIterator(){return Le(this.params.chainIterator,()=>"chainIterator not set")}get chainStakeViewer(){return Le(this.params.chainStakeViewer,()=>"chainStakeViewer not set")}get chainSubmissionsArchivistWrite(){return Le(this.params.chainSubmissionsArchivistWrite,()=>"chainSubmissionsArchivistWrite not set")}get pendingBundledTransactionsArchivistWrite(){return Le(this.params.pendingBundledTransactionsArchivistWrite,()=>"pendingBundledTransactionsArchivistWrite not set")}get stakeIntentService(){return Le(this.params.stakeIntent,()=>"stakeIntentService not set")}static create(t){return new e(t)}async start(){await super.start(),this.registerTimer("BlockProductionTimer",async()=>{await this.spanAsync("produceBlock",async()=>{const e=await this.chainIterator.head();if(qe(e))return;const t=await mA.hash(e);if(ze(this._lastValidatedBlock)&&this._lastValidatedBlockHash===t)this.logger?.log("Block already validated:",`0x${_h(e.block)}`);else{this.logger?.log("Validating block:",`0x${_h(e.block)}`);await this.validateBlock(e)?this.logger?.log("Validated block:",`0x${_h(e.block)}`):(this.logger?.log("Invalid block:",`0x${_h(e.block)}`),await this.slashInvalidBlock(e))}})},100,1500)}async slashInvalidBlock(e){return await Promise.resolve(!0)}async validateBlock(e){const t=await Promise.resolve(!0);return this._lastValidatedBlock=e,this._lastValidatedBlockHash=await mA.hash(e),t}});var xFe,SFe,kFe,TFe=vFe((e,t,n)=>{const r="started"===t?200:n;e.writeHead(r,{"Content-Type":"application/json"}),e.end(JSON.stringify({status:t}))},"sendStatus"),_Fe=vFe(e=>{e.writeHead(404,{"Content-Type":"application/json"}),e.end(JSON.stringify({status:"not found"}))},"notFound"),OFe=vFe((e,t,n)=>{const r=N.createServer((e,n)=>{const r=e.url??"",i=t.getGlobalStatus();switch(r){case"/healthz":TFe(n,i,500);break;case"/livez":case"/readyz":TFe(n,i,503);break;default:_Fe(n)}});return r.listen(e,()=>{n.log(`Health server running on http://localhost:${e}`),n.log(" - /healthz"),n.log(" - /livez"),n.log(" - /readyz")}),r},"createHealthServer"),FFe=vFe(e=>{const{config:t,logger:n,statusReporter:r}=e,{healthCheckPort:i}=t.producer;return ze(i)?OFe(i,r,n):void 0},"initHealthEndpoints"),RFe=i.join(process.cwd(),".store"),NFe=vFe((e,t,n,r,i="lmdb")=>{if("lmdb"===i){const i=r??RFe;return E3.create({account:"random",config:{name:e,clearStoreOnStart:!1,dbName:t,location:m$(t,i,"lmdb"),schema:v3,storeName:n}})}},"getLocalPersistentArchivist"),MFe=new IA,QFe=vFe(async({config:e})=>await MFe.runExclusive(async()=>{if(xFe)return xFe;const{root:t}=e.storage;return xFe=await NFe("local-finalized-chain","chain","finalized",t)}),"initLocalChainFinalizedArchivist"),PFe=new IA,jFe=vFe(async({config:e})=>await PFe.runExclusive(async()=>{if(SFe)return SFe;const{host:t,port:n}=e.api,r=jH(t,n),i=await n6(r);return Le(SFe=await s6({bridge:i,moduleName:"XYOChain:Chain:Finalized"}),()=>"Error: RemoteChainFinalizedArchivist failed to initialize")}),"initRemoteChainFinalizedArchivist"),UFe=new IA;async function LFe({config:e,logger:t,traceProvider:n}){return await UFe.runExclusive(async()=>{if(kFe)return kFe;const[r,i]=await Promise.all([m5("ChainFinalizedArchivist:initRemote",()=>jFe({config:e,logger:t})),m5("ChainFinalizedArchivist:initLocal",()=>QFe({config:e,logger:t}))]);return await m5("ChainFinalizedArchivist:initArchivistSync",()=>X2("ChainFinalizedArchivist",r,i,200,Number.MAX_SAFE_INTEGER,n)),kFe=i})}vFe(LFe,"initChainFinalizedArchivist");var HFe,GFe,qFe,zFe,$Fe,KFe,VFe,YFe=new IA,JFe=vFe(async({config:e})=>await YFe.runExclusive(async()=>{if(HFe)return HFe;const{host:t,port:n}=e.api,r=jH(t,n),i=await n6(r);return Le(HFe=await s6({bridge:i,moduleName:"XYOChain:Chain:Submissions"}),()=>new Error("Failed to initialize RemoteChainSubmissionsArchivist"))}),"initRemoteChainSubmissionsArchivist"),WFe=new IA,ZFe=vFe(async e=>await WFe.runExclusive(async()=>{if(GFe)return GFe;const t=await m5("ChainSubmissionsArchivist:initRemote",()=>JFe(e));return Le(GFe=t,()=>new Error("Failed to initialize ChainSubmissionsArchivist"))}),"initChainSubmissionsArchivist"),XFe=new IA,eRe=vFe(async()=>await XFe.runExclusive(async()=>qFe||(qFe=await Jz.create({account:"random",config:{schema:Vz,max:1e3,name:"localPendingTransactions"}}))),"initLocalPendingTransactionsArchivist"),tRe=new IA,nRe=vFe(async({config:e})=>await tRe.runExclusive(async()=>{if(zFe)return zFe;const{host:t,port:n}=e.api,r=jH(t,n),i=await n6(r);return Le(zFe=await s6({bridge:i,moduleName:"XYOChain:Pending:PendingTransactions"}),()=>"Error: RemotePendingBundledTransactionsArchivist is undefined")}),"initRemotePendingTransactionsArchivist"),rRe=new IA,iRe=vFe(async e=>await rRe.runExclusive(async()=>{if($Fe)return $Fe;const t=await m5("PendingBundledTransactionsArchivist:initRemote",()=>nRe(e)),n=await m5("PendingBundledTransactionsArchivist:initLocal",()=>eRe(e)),r=await t.next({limit:1,order:"desc"});return await n.insert(r),await m5("PendingBundledTransactionsArchivist:initArchivistSync",()=>X2("PendingBundledTransactionsArchivist",t,n)),$Fe=[n,t]}),"initPendingBundledTransactionsArchivist"),aRe=new IA,sRe=vFe(async()=>await aRe.runExclusive(async()=>KFe||(KFe=await Jz.create({account:"random",config:{schema:Vz,max:1e3,name:"localRejectedTransactions"}}))),"initLocalRejectedTransactionsArchivist"),oRe=new IA;async function cRe(e){return await oRe.runExclusive(async()=>{if(VFe)return VFe;const t=await m5("RejectedTransactionsArchivist:initLocal",()=>sRe(e));return VFe=t})}vFe(cRe,"initRejectedTransactionsArchivist");var uRe,lRe,dRe,pRe,hRe=new IA,fRe=vFe(async({config:e})=>await hRe.runExclusive(async()=>{if(uRe)return uRe;const{root:t}=e.storage;return Le(uRe=await NFe("local-stake-intent-state","stakeIntent","state",t),()=>new Error("Failed to initialize stake intent state archivist"))}),"initLocalStakeIntentStateArchivist"),ARe=new IA,mRe=vFe(async e=>await ARe.runExclusive(async()=>{if(lRe)return lRe;const t=await m5("StakeIntentStateArchivist:initLocal",()=>fRe(e));return Le(lRe=t,()=>"Error: StakeIntentStateArchivist is undefined")}),"initStakeIntentStateArchivist"),gRe=new IA,yRe=vFe(async e=>await gRe.runExclusive(async()=>{if(ze(dRe))return dRe;const{root:t}=e.config.storage;return dRe=await y$("balance","summary",t)}),"initLocalBalanceSummaryMap"),bRe=new IA;async function vRe(e){return await bRe.runExclusive(async()=>{if(ze(pRe))return pRe;const t=await m5("BalanceSummaryMap:initLocal",()=>yRe(e));return pRe=t})}vFe(vRe,"initBalanceSummaryMap");var ERe,IRe,wRe,CRe=new IA,BRe=vFe(async e=>await CRe.runExclusive(async()=>{if(ze(ERe))return ERe;const{root:t}=e.config.storage;return ERe=await y$("transfer","summary",t)}),"initLocalTransferSummaryMap"),DRe=new IA;async function xRe(e){return await DRe.runExclusive(async()=>{if(ze(IRe))return IRe;const t=await m5("TransferSummaryMap:initLocal",()=>BRe(e));return IRe=t})}vFe(xRe,"initTransferSummaryMap");var SRe,kRe,TRe,_Re,ORe,FRe,RRe,NRe,MRe,QRe,PRe,jRe,URe,LRe,HRe=vFe(async({config:e,logger:t})=>{if(wRe)return wRe;let n=e.producer.mnemonic;if(qe(n)){t?.warn("[Producer] No wallet mnemonic specified!");const e=pH.generateMnemonic();t?.warn(`[Producer] Using randomly generated mnemonic:\n \n${e}\n \n `),n=e}const r=await ZG(n),i=await r.derivePath(WG);return wRe=i},"initAccount"),GRe=vFe(async e=>SRe||(SRe=await w5.create(e)),"initBalanceService"),qRe=vFe(e=>ze(e.evm.chainId),"canUseChainId"),zRe=vFe(e=>{const t=Le(e.evm.chainId,()=>"Missing config.evm.chainId");if(Bh(t,{prefix:!0})){const e=kh(t);return Number.parseInt(e,16)}return Number.parseInt(t,10)},"getChainId"),$Re=vFe(e=>{if(kRe)return kRe;const t=VRe(e);return kRe=Promise.resolve(new Dx(...t))},"initInfuraProvider"),KRe=vFe(e=>qRe(e)&&ze(e.evm?.infura?.projectId)&&ze(e.evm?.infura?.projectSecret),"canUseInfuraProvider"),VRe=vFe(e=>{const t=Le(e.evm?.infura?.projectId,()=>"Missing config.evm.infura.projectId"),n=Le(e.evm?.infura?.projectSecret,()=>"Missing config.evm.infura.projectSecret");return[zRe(e),t,n]},"getInfuraProviderConfig"),YRe=vFe(e=>{const t=WRe(e);return Promise.resolve(new gD(...t))},"initJsonRpcProvider"),JRe=vFe(e=>qRe(e)&&ze(e.evm.jsonRpc?.url),"canUseJsonRpcProvider"),WRe=vFe(e=>[Le(e.evm.jsonRpc?.url,()=>"Missing config.evm.jsonRpc.url"),zRe(e)],"getJsonRpcProviderConfig"),ZRe=vFe(async({config:e})=>TRe||(KRe(e)?TRe=$Re(e):JRe(e)&&(TRe=YRe(e)),Le(await TRe,()=>"Error: No provider available")),"initEvmProvider"),XRe=vFe(({config:e})=>KRe(e)||JRe(e),"canUseEvmProvider"),eNe=vFe(e=>{const{id:t}=e.chain;return ze(t)&&t!==vh&&XRe({config:e})},"canUseEvmContractChainService"),tNe=vFe(async({account:e,config:t,traceProvider:n,meterProvider:r,logger:i})=>{if(_Re)return _Re;const a=Le(t.chain.id,()=>"Error: config.chain.id is required"),s=Le(Nh(a),()=>"Error: config.chain.id is not a valid address"),o=Le(await ZRe({config:t})),c=Le(e.private?.hex,()=>"Error: Account does not have a private key"),u=new Ck(c,o);return _Re=M5.create({id:s,runner:u,traceProvider:n,meterProvider:r,logger:i}),await _Re},"initEvmContractChainService"),nNe=vFe(({account:e,config:t})=>rNe({config:t,name:"ChainService",account:e}),"initChainService"),rNe=vFe(e=>{if(ORe)return ORe;const{config:t}=e;return ORe=eNe(t)?tNe({...e,name:"ChainStakeService"}):Q5.create({...e,name:"ChainStakeService"})},"init"),iNe=vFe(async(e,t)=>{const n=t.chainId,r=[],i=await u$(e,n,10000000n,e.address);r.push(i);const a=p$(e.address,"producer",i[0].block,i[0].block+1e4),s=await o$(i[0],[],[a],[e]);return r.push(s),r},"createBootstrapHead"),aNe=vFe(()=>18000000000n*VP,"getForkBlockReward"),sNe=vFe(()=>_h(aNe()),"getForkBlockRewardHex"),oNe=_h("0x1"),cNe=_h("0xf72aE3E0DA743033AbD7A407557D684c1aE66aed"),uNe=_h("0x0e65b65B10C791942665030402c35023d88B14dA"),lNe=_h("0x950861b10523b52cdbb4a9ee52ed26601db555d2652bfec21c709e5e70d5b7d3"),dNe=vFe(()=>oNe,"getBridgeDestChainId"),pNe=vFe(()=>cNe,"getBridgeDestToken"),hNe=vFe(()=>uNe,"getBridgeDestAddress"),fNe=vFe(()=>sNe(),"getBridgeDestAmount"),ANe=vFe(()=>lNe,"getBridgeDestConfirmation"),mNe=vFe(()=>({dest:dNe(),destToken:pNe(),destAddress:hNe(),destAmount:fNe()}),"getBridgeDestinationDetails"),gNe=vFe(e=>e.chainId,"getBridgeSrcChainId"),yNe=vFe(e=>e.address,"getBridgeSrcAddress"),bNe=vFe(e=>e.chainId,"getBridgeSrcToken"),vNe=vFe(()=>sNe(),"getBridgeSrcAmount"),ENe=vFe((e,t)=>({src:gNe(t),srcAddress:yNe(e),srcToken:bNe(t),srcAmount:vNe()}),"getBridgeSourceDetails"),INe=vFe(async(e,t,n)=>{const r={...ENe(t,n),...mNe(),destConfirmation:ANe()},i=new mA({schema:ej}).fields(r).build();return await o$(e[0],[],[i],[t])},"getBridgeDestinationObservation"),wNe=vFe(async(e,t,n)=>{const r=e$(t.address,{[qj]:aNe()}),i=`${Date.now()}`,a={...ENe(t,n),...mNe(),nonce:i},s=new mA({schema:rj}).fields(a).build();return await o$(e[0],[],[s,r],[t])},"getBridgeIntent"),CNe=vFe(async(e,t,n)=>{const r=e[0]._hash,i={...ENe(t,n),...mNe(),srcConfirmation:r},a=new mA({schema:sj}).fields(i).build();return await o$(e[0],[],[a],[t])},"getBridgeSourceObservation"),BNe=vFe(async(e,t,n)=>{const{_hash:r,block:i,step_hashes:a,protocol:s}=e,o={blockPayloads:[],chainId:n.chainId,previousBlockHash:r,previousBlockNumber:i,previousStepHashes:a,signers:[t],txs:[],protocol:s,chainStepRewardAddress:$j,stepRewardPoolBalance:WP(0n)};return await a$(o)},"getFirstBlockForNewChain"),DNe=vFe(async(e,t,n)=>{const r=[],i=await BNe(e,t,n);r.push(i);const a=await wNe(i,t,n);r.push(a);const s=await CNe(a,t,n);r.push(s);const o=await INe(s,t,n);return r.push(o),r},"createForkedHead"),xNe=vFe(async(e,t,n)=>{if(e.chain!==t.chainId){const e=await t.forkedAtHash(),r=Uh(Sh(e));if(ze(r)){const[e]=await n.get([r]),i=await t.forkedChainId(),a=Number(await t.forkedAtBlockNumber());if(Pj(e)&&e.chain===i&&e.block===a)return e}}},"getForkFromBlock"),SNe=vFe(async(e,t,n)=>{for(const r of e){const[e]=r;for(await n.insert(mH(r));;){if((await t.get([e._hash])).length>0)break;await TA(1e3)}}},"submitNewChain"),kNe=vFe(async e=>{const{account:t,chainArchivist:n,chainSubmissionsArchivistWrite:r,chainService:i}=e;if(FRe)return FRe;let a=await I$(n);if(a){const e=await xNe(a,i,n);if(ze(e)){const s=await DNe(e,t,i);await SNe(s,n,r);a=Le(s.at(-1),()=>new Error("Failed to get new head after forking"))[0]}}else{const e=await iNe(t,i);await SNe(e,n,r);a=Le(e.at(-1),()=>new Error("Failed to get new head after genesis"))[0]}return FRe=a},"initHead"),TNe=vFe(e=>RRe||(RRe=N5.create(e)),"initChainIterator"),_Ne=vFe(e=>NRe||(NRe=Z5.create(e)),"initStakeIntentService"),ONe=vFe(e=>MRe||(MRe=L5.create(e)),"initElectionService"),FNe=vFe(async e=>QRe||(QRe=await V5.create(e)),"initPendingTransactions"),RNe=vFe(async e=>PRe||(PRe=await S5.create(e)),"initBlockProducer"),NNe=vFe(e=>{if(jRe)return jRe;const{config:t}=e;return jRe=QNe({config:t})?PNe(e):MNe(e)},"initBlockRewardService"),MNe=vFe(e=>jRe||(jRe=R5.create(e)),"initXyoBlockRewardService"),QNe=vFe(e=>XRe({config:e.config}),"canUseEvmBlockRewardService"),PNe=vFe(async e=>{if(jRe)return jRe;const{account:t}=e,n=Le(t,()=>"Error: Account is required"),r=Le(await ZRe(e)),i={...e,provider:r,account:n};return jRe=O5.create(i)},"initEvmBlockRewardService"),jNe=vFe(async({chainArchivist:e,chainIterator:t,config:n,logger:r,meterProvider:i,traceProvider:a})=>{if(URe)return URe;const s=XRe({config:n})?await ZRe({config:n}):void 0;return URe=n3.create({chainArchivist:e,chainIterator:t,ethProvider:s,logger:r,meterProvider:i,traceProvider:a}),await URe},"initTimeService"),UNe=vFe(async e=>LRe||(LRe=await B5.create(e)),"initTransferService"),LNe=class{static{vFe(this,"LoggerStatusReporter")}logger;statusMap={};constructor(e){this.logger=e}report(e,t,n){this.statusMap[e]=t;const r=Object.entries(this.statusMap).map(([,e])=>"starting"===e?1:0).reduce((e,t)=>e+t,0),i=Object.entries(this.statusMap).map(([,e])=>"started"===e?1:0).reduce((e,t)=>e+t,0);this.logger.info(`${i}/${r+i} ${e} status: ${t}`,{progress:n})}},HNe={error:0,stopped:1,stopping:2,creating:3,created:4,starting:5,started:6},GNe="starting",qNe=vFe(e=>{let t=GNe,n=1/0;for(const r of e){const e=HNe[r];e<n&&(n=e,t=r)}return t},"reduceToMinimumStatus"),zNe=class extends LNe{static{vFe(this,"RuntimeStatusMonitor")}globalTransitions=[];transitions=[];getGlobalStatus(){return 0===Object.keys(this.statusMap).length?GNe:qNe(Object.values(this.statusMap))}getStatus(e){return this.statusMap[e]}onGlobalTransition(e,t){this.globalTransitions.push({...e,handler:t})}onTransition(e,t){this.transitions.push({...e,handler:t})}report(e,t,n){const r=this.statusMap[e],i=this.getGlobalStatus();if(super.report(e,t,n),r===t)return;this.runTransitions(this.transitions,r,t,e);const a=this.getGlobalStatus();i!==a&&this.runTransitions(this.globalTransitions,i,a)}runTransitions(e,t,n,r){for(const{from:i,to:a,name:s,handler:o}of e)void 0!==s&&s!==r||void 0!==i&&i!==t||void 0!==a&&a!==n||o(t,n)}},$Ne=vFe(e=>ze(e.start)&&"function"==typeof e.start,"isStartable"),KNe=vFe(async e=>{const{config:t,logger:n}=e,r=new zNe(n);r.onGlobalTransition({to:"started"},()=>{n.log("All services started.")}),r.onGlobalTransition({to:"error"},()=>{n.error("Producer encountered an unhandled error!"),process.exit(1)}),await m5("initHealthEndpoints",()=>FFe({...e,statusReporter:r}));const{otlpEndpoint:i}=t.telemetry?.otel??{},a={attributes:{serviceName:"xl1-producer",serviceVersion:"1.0.0"},otlpEndpoint:i,metricsConfig:{endpoint:"/metrics",port:9464}},[{traceProvider:s,meterProvider:o},c]=await Promise.all([m5("initTelemetry",()=>h3(a)),m5("initAccount",()=>HRe(e))]),u=t.validation?.allowedRewardRedeemers??[],l=t.validation?.allowedRewardEscrowAccountSigners??[],d={config:t,logger:n,meterProvider:o,statusReporter:r,traceProvider:s},[p,[h,f],A,m,g,y,b,v]=await Promise.all([m5("ChainFinalizedArchivist",()=>LFe(d)),m5("PendingBundledTransactionsArchivist",()=>iRe(d)),m5("RejectedTransactionsArchivist",()=>cRe(d)),m5("ChainSubmissionsArchivist",()=>ZFe(d)),m5("StakeIntentStateArchivist",()=>mRe(d)),m5("ChainService",()=>nNe({...d,account:c,name:"ChainService"})),m5("BalanceSummaryMap",()=>vRe(d)),m5("TransferSummaryMap",()=>xRe(d))]),E=y.chainId,I=DG(p),w=y,C=y,B=y,D=await m5("initHead",()=>kNe({...d,account:c,chainArchivist:p,chainSubmissionsArchivistWrite:m,chainService:y})),x=[u0([s0,o0(u),c0(l,"reward-escrow")])],[S,k,T]=await Promise.all([m5("PendingTransactions",()=>FNe({name:"PendingTransactionsService",chainArchivist:p,chainId:E,pendingBundledTransactionsArchivist:h,rejectedTransactionsArchivist:A,additionalPendingTransactionValidators:x,...d})),m5("RewardService",()=>NNe({name:"RewardService",account:c,chainService:y,...d})),m5("ChainIterator",()=>TNe({name:"ChainIterator",chainMap:I,head:D,...d}))]),[_]=await Promise.all([m5("BalanceService",()=>GRe({name:"BalanceService",context:{stepSemaphores:Zj.map(()=>new bA(20)),store:{chainMap:I},head:vFe(async()=>mA.hash(await T.head()),"head"),chainId:E,summaryMap:b},...d})),m5("TransferService",()=>UNe({name:"TransferService",context:{stepSemaphores:Zj.map(()=>new bA(20)),store:{chainMap:I},head:vFe(async()=>mA.hash(await T.head()),"head"),chainId:E,summaryMap:v},...d}))]),[O,F]=await Promise.all([m5("StakeIntentService",()=>_Ne({name:"StakeIntentService",chainArchivist:p,chainIterator:T,chainStakeViewer:C,stakeIntentStateArchivist:g,...d})),m5("TimeService",()=>jNe({name:"TimeService",chainArchivist:p,chainIterator:T,...d}))]),R=await m5("ElectionService",()=>ONe({name:"ElectionService",chainIterator:T,chainStakeViewer:C,stakeIntentService:O,...d})),N={name:"Validator",account:c,chainId:E,pendingBundledTransactionsArchivist:h,chainArchivist:p,electionService:R,rewardService:k,stakeIntentService:O,validateHydratedBlockState:M0,...d},M=ze(t.producer.rewardAddress)?Le(Nh(t.producer.rewardAddress),()=>"Invalid block reward address provided"):c.address,Q={...N,name:"Producer",balanceService:_,chainArchivist:p,pendingBundledTransactionsArchivist:h,pendingTransactionsService:S,rejectedTransactionsArchivist:A,rewardAddress:M,time:F,...d},P=await m5("Producer",()=>RNe(Q)),j={account:c,balance:_,chainArchivist:p,chainContractViewer:w,chainIterator:T,chainStaker:B,chainStakeViewer:C,chainSubmissionsArchivistWrite:m,election:R,pendingBundledTransactionsArchivistWrite:f,pendingTransactions:S,producer:P,reward:k,stakeIntent:O};n?.log("All services created. Starting...");const U=[b,...Object.values(j)].filter($Ne);return Le((await Promise.all(U.map(e=>e.start()))).every(Boolean),()=>"One or more services failed to start"),n?.log("All services started successfully."),j},"initServices");function VNe(e){xke(e)}function YNe(e){Jke(e)}vFe(VNe,"runApi"),vFe(YNe,"runBridge");var JNe=vFe(async e=>{const{config:t,logger:n,orchestrator:r}=e;n?.log("Services: Initializing...");const i=await KNe(e);n?.log("Services: Initialized");const a={...i,config:t},s=[await CFe.create(a),await wFe.create(a),await DFe.create(a)];for(const e of s)await r.registerActor(e);await r.start()},"runProducer");function WNe(e){PTe(e)}vFe(WNe,"runRewardRedemptionApi");var ZNe,XNe=vFe(e=>{let t;if(e.silent)t=new QA;else{let n;if(ze(e.logLevel)){const t=FA[e.logLevel.toLowerCase()];ze(t)&&(n=t)}t=new NA(n)}return wA.defaultLogger=t,t},"initLogger"),eMe=vFe(e=>e,"usageMetaToOptions"),tMe=vFe(()=>{const e={};for(const t of Object.values(uu._map))if(dG(t)){if(t.hidden)continue;e[t.title]=eMe(t)}return e},"optionsFromGlobalZodRegistry"),nMe=vFe(()=>{const e=AFe.cosmiconfigSync("xyo").search();if(!$e(e)){const t=e?.config?.xl1;if(ze(t)&&"object"==typeof t)return t}return{}},"tryParseConfig"),rMe=vFe((e,t)=>new Promise(n=>{const r=vFe(()=>{const i=new se.Socket;i.setTimeout(1e3).once("error",()=>{i.destroy(),setTimeout(r,500)}).once("timeout",()=>{i.destroy(),setTimeout(r,500)}).connect(t,e,()=>{i.end(),n()})},"tryConnect");r()}),"waitForHostPort"),iMe=ze("1.15.26")?"1.15.26":"unknown",aMe=vFe(e=>{const t=XNe(e),n=new IFe(t);return process.on("SIGINT",()=>{(async()=>{try{t.log("\nSIGINT received. Attempting graceful shutdown..."),await(n?.stop()),t.log("Orchestrator stopped, exiting now."),process.exit(0)}catch(e){t.error("Error stopping orchestrator:",e),process.exit(1)}})()}),{logger:t,orchestrator:n}},"getContextFromConfig");async function sMe(){const e=b9(function(e){return e.slice(o8()+1)}(process.argv)),t=e.usage(`\n🚀 XL1 Node CLI (${iMe})\n                    _\n                   ╠╠\n                   ╠╠_\n        ╦╦_       [╠╠▒       _╔╦\n        ²╠▒D╦_    ╠╠╠╠    _╔R▒▒╙\n          ╚▒▒▒D╦ j╠╠╠╠H ╔D▒▒▒╠\n           ²▒▒▒▒ ╠╠╠╠╠╠ ╠▒▒▒╙\n             \`_,╓╠╠╠╠╠╠╓_\`\`\n _,╓╓╔╗φ@D▒╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠▒▒Kφ╗╦╖²__\n \`^╙╙╚╝╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╝╩╜╙^\`\n             \`'"╙╠╠╠╠╠╠╜^^\`\`\n           ,╠▒▒╠ ╠╠╠╠╠╠ å╠╠╠,\n          ╔▒▒▒▒╩ [╠╠╠╠H ╚╠╠╠╠H\n        ,╠▒▒╩^    ╠╠╠╠    '╚╠╠╠,\n        ╩╩^       ╚╠╠╠       '╚╩\n                  '╠╠H\n                   ╠╠\n                   ²^\nRun various components of the XL1 ecosystem.\n\nUsage:\n$0 <command> [options]`).parserConfiguration({"dot-notation":!0,"parse-numbers":!1,"populate--":!0}).env("XL1").scriptName("xl1").middleware(e=>{try{const t=nMe(),n=vt(e,t);ZNe=aG.parse(n)}catch(e){throw e instanceof ad&&console.error(`${e.message}`),new Error("Invalid configuration")}}).options(tMe()).wrap(e.terminalWidth()).command("api","Run a XL1 API Node",e=>e.command("$0","Run a XL1 API Node",()=>{},()=>{VNe({...aMe(ZNe),config:ZNe})})).command("bridge","Run a XL1 Bridge Node",e=>e.command("$0","Run a XL1 Bridge Node",()=>{},()=>{YNe({...aMe(ZNe),config:ZNe})})).command("producer","Run a XL1 Producer Node",e=>e.command("$0","Run a XL1 Producer Node",()=>{},async()=>{const e=aMe(ZNe);await JNe({...e,config:ZNe})})).command("reward-redemption-api","Run a XL1 Rewards Redemption API Node",e=>e.command("$0","Run a XL1 Rewards Redemption API Node",()=>{},()=>{WNe({...aMe(ZNe),config:ZNe})})).command("$0","Run a full XL1 Node",()=>{},async()=>{const e=aMe(ZNe);VNe({...e,config:ZNe}),await rMe("localhost",ZNe.api.port),await JNe({...e,config:ZNe})}).help().alias("help","h").version(iMe).argv;await t}vFe(sMe,"runCLI"),vFe(async()=>{yFe.config({quiet:!0}),await sMe()},"start")().catch(e=>{"development"===process.env.NODE_ENV&&console.error("An error occurred during startup:",e),process.exit(1)});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xyo-network/xl1-cli",
3
- "version": "1.15.26",
3
+ "version": "1.15.27",
4
4
  "description": "XYO Layer One CLI",
5
5
  "homepage": "https://xylabs.com",
6
6
  "bugs": {
@@ -86,7 +86,7 @@
86
86
  "@xyo-network/payload-model": "~5.1.15",
87
87
  "@xyo-network/wallet": "~5.1.15",
88
88
  "@xyo-network/wallet-model": "~5.1.15",
89
- "@xyo-network/xl1-cli-lib": "~1.15.26",
89
+ "@xyo-network/xl1-cli-lib": "~1.15.27",
90
90
  "@xyo-network/xl1-protocol": "~1.12.95",
91
91
  "async-mutex": "~0.5.0",
92
92
  "dotenv": "~17.2.3",