@xyo-network/xl1-cli 1.12.2 → 1.12.4

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
@@ -416,4 +416,4 @@ if(await(0,o.isDirectory)(s.path))for(const e of this.getSearchPlacesForDir(s,n.
416
416
  if(i.done)throw new Error(`Could not find any folders to iterate through (start from ${e})`);let s=i.value;const a=()=>{
417
417
  /* istanbul ignore if -- @preserve */
418
418
  if((0,o.isDirectorySync)(s.path))for(const e of this.getSearchPlacesForDir(s,n.globalConfigSearchPlacesSync))try{const t=this.#_r(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):(s=e.value,this.searchCache?(0,o.emplace)(this.searchCache,s.path,a):a())};return this.searchCache?(0,o.emplace)(this.searchCache,e,a):a()}#_r(e,r=[]){const n=t.default.readFileSync(e,"utf8");return this.toCosmiconfigResult(e,this.#Cr(e,n,r))}#Cr(e,t,n){const i=this.#br(e,t);if(!i||!(0,s.hasOwn)(i,"$import"))return i;const o=r.default.dirname(e),{$import:a,...c}=i,u=Array.isArray(a)?a:[a],l=[...n,e];this.validateImports(e,u,l);const d=u.map(e=>{const t=r.default.resolve(o,e),n=this.#_r(t,l);return n?.config});return(0,s.mergeAll)([...d,c],{mergeArrays:this.config.mergeImportArrays})}#br(e,t){if(""===t.trim())return;const n=r.default.extname(e),s=this.config.loaders[n||"noExt"]??this.config.loaders.default;if(!s)throw new Error(`No loader specified for ${(0,i.getExtensionDescription)(n)}`);try{const i=s(e,t);return"package"!==r.default.basename(e,n)?i:(0,o.getPropertyByPath)(i,this.config.packageProp??this.config.moduleName)??null}catch(t){throw t.filepath=e,t}}#Ir(e){try{return t.default.statSync(e),!0}catch(e){return!1}}*#Sr(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 n=r.default.join(t,`package.${e}`);if(this.#Ir(n))break}const e=r.default.dirname(t);
419
- /* 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 ExplorerSync.ExplorerSync=a,ExplorerSync}function requireDist(){return hasRequiredDist||(hasRequiredDist=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.defaultLoadersSync=e.defaultLoaders=e.globalConfigSearchPlacesSync=e.globalConfigSearchPlaces=e.getDefaultSearchPlacesSync=e.getDefaultSearchPlaces=e.cosmiconfigSync=e.cosmiconfig=void 0;const t=requireDefaults();Object.defineProperty(e,"defaultLoaders",{enumerable:!0,get:function(){return t.defaultLoaders}}),Object.defineProperty(e,"defaultLoadersSync",{enumerable:!0,get:function(){return t.defaultLoadersSync}}),Object.defineProperty(e,"getDefaultSearchPlaces",{enumerable:!0,get:function(){return t.getDefaultSearchPlaces}}),Object.defineProperty(e,"getDefaultSearchPlacesSync",{enumerable:!0,get:function(){return t.getDefaultSearchPlacesSync}}),Object.defineProperty(e,"globalConfigSearchPlaces",{enumerable:!0,get:function(){return t.globalConfigSearchPlaces}}),Object.defineProperty(e,"globalConfigSearchPlacesSync",{enumerable:!0,get:function(){return t.globalConfigSearchPlacesSync}});const r=requireExplorer(),n=requireExplorerSync(),i=requireUtil(),s=function(e){return e};function o(e,t,r){const n=r.searchPlaces?.map(t=>t.replace("{name}",e));return r.mergeSearchPlaces?[...n??[],...t]:n??t}function a(e,r,a){const c=function(){const e=new n.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 r={mergeSearchPlaces:!0,...e.config??{}};return{config:(0,i.removeUndefinedValuesFromObject)(r),filepath:e.filepath}}();if(!c)return{...r,...(0,i.removeUndefinedValuesFromObject)(a),loaders:{...r.loaders,...a.loaders}};const u=c.config,l=a.searchPlaces??r.searchPlaces;return{...r,...(0,i.removeUndefinedValuesFromObject)(a),metaConfigFilePath:c.filepath,...u,searchPlaces:o(e,l,u),loaders:{...r.loaders,...a.loaders}}}function c(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,n={}){const i=function(e,r){return c(r),a(e,{moduleName:e,searchPlaces:(0,t.getDefaultSearchPlaces)(e),ignoreEmptySearchPlaces:!0,cache:!0,transform:s,loaders:t.defaultLoaders,metaConfigFilePath:null,mergeImportArrays:!0,mergeSearchPlaces:!0,searchStrategy:r.stopDir?"global":"none"},r)}(e,n),o=new r.Explorer(i);return{search:o.search.bind(o),load:o.load.bind(o),clearLoadCache:o.clearLoadCache.bind(o),clearSearchCache:o.clearSearchCache.bind(o),clearCaches:o.clearCaches.bind(o)}},e.cosmiconfigSync=function(e,r={}){const i=function(e,r){return c(r),a(e,{moduleName:e,searchPlaces:(0,t.getDefaultSearchPlacesSync)(e),ignoreEmptySearchPlaces:!0,cache:!0,transform:s,loaders:t.defaultLoadersSync,metaConfigFilePath:null,mergeImportArrays:!0,mergeSearchPlaces:!0,searchStrategy:r.stopDir?"global":"none"},r)}(e,r),o=new n.ExplorerSync(i);return{search:o.search.bind(o),load:o.load.bind(o),clearLoadCache:o.clearLoadCache.bind(o),clearSearchCache:o.clearSearchCache.bind(o),clearCaches:o.clearCaches.bind(o)}}}(dist)),dist}var distExports=requireDist(),main={exports:{}},version$1="17.2.1",require$$4={version:version$1},hasRequiredMain;function requireMain(){if(hasRequiredMain)return main.exports;hasRequiredMain=1;const e=require$$0$e,t=require$$0__default,r=require$$0$a,n=require$$0$g,i=require$$4.version,s=["🔐 encrypt with Dotenvx: https://dotenvx.com","🔐 prevent committing .env to code: https://dotenvx.com/precommit","🔐 prevent building .env in docker: https://dotenvx.com/prebuild","📡 observe env with Radar: https://dotenvx.com/radar","📡 auto-backup env with Radar: https://dotenvx.com/radar","📡 version env with Radar: https://dotenvx.com/radar","🛠️ 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 o(e){return"string"==typeof e?!["false","0","no","off",""].includes(e.toLowerCase()):Boolean(e)}function a(e){return process.stdout.isTTY?`${e}`:e}const c=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function u(e){console.log(`[dotenv@${i}][DEBUG] ${e}`)}function l(e){console.log(`[dotenv@${i}] ${e}`)}function d(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 p(e,t){let r;try{r=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 n=r.password;if(!n){const e=new Error("INVALID_DOTENV_KEY: Missing key part");throw e.code="INVALID_DOTENV_KEY",e}const i=r.searchParams.get("environment");if(!i){const e=new Error("INVALID_DOTENV_KEY: Missing environment part");throw e.code="INVALID_DOTENV_KEY",e}const s=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[s];if(!o){const e=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${s} in your .env.vault file.`);throw e.code="NOT_FOUND_DOTENV_ENVIRONMENT",e}return{ciphertext:o,key:n}}function f(r){let n=null;if(r&&r.path&&r.path.length>0)if(Array.isArray(r.path))for(const t of r.path)e.existsSync(t)&&(n=t.endsWith(".vault")?t:`${t}.vault`);else n=r.path.endsWith(".vault")?r.path:`${r.path}.vault`;else n=t.resolve(process.cwd(),".env.vault");return e.existsSync(n)?n:null}function h(e){return"~"===e[0]?t.join(r.homedir(),e.slice(1)):e}const A={configDotenv:function(r){const n=t.resolve(process.cwd(),".env");let i="utf8",c=process.env;r&&null!=r.processEnv&&(c=r.processEnv);let d=o(c.DOTENV_CONFIG_DEBUG||r&&r.debug),p=o(c.DOTENV_CONFIG_QUIET||r&&r.quiet);r&&r.encoding?i=r.encoding:d&&u("No encoding is specified. UTF-8 is used by default");let f,g=[n];if(r&&r.path)if(Array.isArray(r.path)){g=[];for(const e of r.path)g.push(h(e))}else g=[h(r.path)];const m={};for(const t of g)try{const n=A.parse(e.readFileSync(t,{encoding:i}));A.populate(m,n,r)}catch(e){d&&u(`Failed to load ${t} ${e.message}`),f=e}const E=A.populate(c,m,r);if(d=o(c.DOTENV_CONFIG_DEBUG||d),p=o(c.DOTENV_CONFIG_QUIET||p),d||!p){const e=Object.keys(E).length,r=[];for(const e of g)try{const n=t.relative(process.cwd(),e);r.push(n)}catch(t){d&&u(`Failed to load ${e} ${t.message}`),f=t}l(`injecting env (${e}) from ${r.join(",")} ${a(`-- tip: ${s[Math.floor(Math.random()*s.length)]}`)}`)}return f?{parsed:m,error:f}:{parsed:m}},_configVault:function(e){const t=o(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),r=o(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);!t&&r||l("Loading env from encrypted .env.vault");const n=A._parseVault(e);let i=process.env;return e&&null!=e.processEnv&&(i=e.processEnv),A.populate(i,n,e),{parsed:n}},_parseVault:function(e){const t=f(e=e||{});e.path=t;const r=A.configDotenv(e);if(!r.parsed){const e=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code="MISSING_DATA",e}const n=d(e).split(","),i=n.length;let s;for(let e=0;e<i;e++)try{const t=p(r,n[e].trim());s=A.decrypt(t.ciphertext,t.key);break}catch(t){if(e+1>=i)throw t}return A.parse(s)},config:function(e){if(0===d(e).length)return A.configDotenv(e);const t=f(e);return t?A._configVault(e):(function(e){console.error(`[dotenv@${i}][WARN] ${e}`)}(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),A.configDotenv(e))},decrypt:function(e,t){const r=Buffer.from(t.slice(-64),"hex");let i=Buffer.from(e,"base64");const s=i.subarray(0,12),o=i.subarray(-16);i=i.subarray(12,-16);try{const e=n.createDecipheriv("aes-256-gcm",r,s);return e.setAuthTag(o),`${e.update(i)}${e.final()}`}catch(e){const t=e instanceof RangeError,r="Invalid key length"===e.message,n="Unsupported state or unable to authenticate data"===e.message;if(t||r){const e=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw e.code="INVALID_DOTENV_KEY",e}if(n){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 r,n=e.toString();for(n=n.replace(/\r\n?/gm,"\n");null!=(r=c.exec(n));){const e=r[1];let n=r[2]||"";n=n.trim();const i=n[0];n=n.replace(/^(['"`])([\s\S]*)\1$/gm,"$2"),'"'===i&&(n=n.replace(/\\n/g,"\n"),n=n.replace(/\\r/g,"\r")),t[e]=n}return t},populate:function(e,t,r={}){const n=Boolean(r&&r.debug),i=Boolean(r&&r.override),s={};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 r of Object.keys(t))Object.prototype.hasOwnProperty.call(e,r)?(!0===i&&(e[r]=t[r],s[r]=t[r]),n&&u(!0===i?`"${r}" is already defined and WAS overwritten`:`"${r}" is already defined and was NOT overwritten`)):(e[r]=t[r],s[r]=t[r]);return s}};return main.exports.configDotenv=A.configDotenv,main.exports._configVault=A._configVault,main.exports._parseVault=A._parseVault,main.exports.config=A.config,main.exports.decrypt=A.decrypt,main.exports.parse=A.parse,main.exports.populate=A.populate,main.exports=A,main.exports}var mainExports=requireMain(),__defProp=Object.defineProperty,__name=(e,t)=>__defProp(e,"name",{value:t,configurable:!0}),Actor=class extends Base$1{static{__name(this,"Actor")}_timers=new Map;_active=!1;_displayName;_id;constructor(e,t="Actor",r){const n=r.logger??new IdLogger(Base$1.defaultLogger??console,()=>`[${t} (${e})] `);super({...r,logger:n}),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,r,n){if(!this._active)return void this.logger?.warn(`Cannot register timer '${e}' because actor is not active.`);const i=__name(async()=>{if(this._active&&this._timers.has(e))try{await t()}catch(t){this.logger?.error(`Error in timer '${this.name}:${e}': ${t}`)}finally{this._timers.set(e,setTimeout(()=>forgetNode(i(),{name:`schedulePeriodicRun:${this.name}:${e}`}),n))}},"schedulePeriodicRun");this._timers.set(e,setTimeout(()=>forgetNode(i(),{name:`schedulePeriodicRun(initial):${this.name}:${e}`}),r)),this.logger?.log(`Timer '${this.name}:${e}' registered: first call after ${r}ms, recurring every ${n}ms.`)}span(e,t){return span(`${this.name}:${e}`,t,this.tracer)}async spanAsync(e,t){return await spanAsync(`${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...");for(const[,e]of this._timers.entries())clearTimeout(e);this._timers.clear(),this.logger?.log("Stopped.")}},Orchestrator=class{static{__name(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.")}},BalanceActor=class e extends Actor{static{__name(this,"BalanceActor")}_updateMutex=new Mutex;constructor(e){super("BalanceActor","Balance",e)}get balanceService(){return assertEx(this.params.balanceService,()=>"balanceService not set")}get chainIterator(){return assertEx(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,1e3)}async updateBalance(){this._updateMutex.isLocked()||await this._updateMutex.runExclusive(async()=>{const e=await PayloadBuilder.hash(await this.chainIterator.head());await this.balanceService.balances(e,[])})}},ChainHeadUpdateActor=class e extends Actor{static{__name(this,"ChainHeadUpdateActor")}constructor(e){super("ChainHeadUpdate","ChainHeadUpdate",e)}get chainFinalizedArchivist(){return assertEx(this.params.chainArchivist,()=>"ChainArchivist not set")}get chainIterator(){return assertEx(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,250)}async checkInsertedForNewHead(e){const t=sortBlocks(filterAs(e.payloads,asBlockBoundWitness)).at(-1);await this.updateHeadIfNewer(t)}async pollForNewHead(){const e=await findMostRecentBlock(this.chainFinalizedArchivist);await this.updateHeadIfNewer(e)}async updateHeadIfNewer(e){if(!e)return;const t=await this.chainIterator.head(),r=e.block,n=`0x${toHex(r)}`;r>(t?.block??-1)&&(this.logger?.log("Found more recent head:",n),await this.chainIterator.updateHead(e),this.logger?.log("Updated head:",n))}},TEN_MINUTES=6e5,ProducerActor=class e extends Actor{static{__name(this,"ProducerActor")}_lastProducedBlock;_lastRedeclarationIntent;constructor(e){super(e.producer.address,"Producer",e)}get account(){return assertEx(this.params.account,()=>"account not set")}get balanceService(){return assertEx(this.params.balanceService,()=>"balanceService not set")}get chainIterator(){return assertEx(this.params.chainIterator,()=>"chainIterator not set")}get chainStakeViewer(){return assertEx(this.params.chainStakeViewer,()=>"chainStakeViewer not set")}get chainSubmissionsArchivistWrite(){return assertEx(this.params.chainSubmissionsArchivistWrite,()=>"chainSubmissionsArchivistWrite not set")}get pendingBundledTransactionsArchivistWrite(){return assertEx(this.params.pendingBundledTransactionsArchivistWrite,()=>"pendingBundledTransactionsArchivistWrite not set")}get producer(){return assertEx(this.params.producer,()=>"producer not set")}get stakeIntentService(){return assertEx(this.params.stakeIntentService,()=>"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(),t=await PayloadBuilder.hash(e);if(this._lastProducedBlock&&this._lastProducedBlock[0].previous===t)this.logger?.log("Block already produced:",`0x${toHex(this._lastProducedBlock[0].block)}`);else{const t=await this.producer.next(e);if(t){const e=`0x${toHex(t[0].block)}`;this.logger?.log("Produced block:",e),await this.chainSubmissionsArchivistWrite.insert(flattenHydratedBlock(t)),this.logger?.log("Published block:",e),this._lastProducedBlock=t}}})},100,500),this.registerTimer("ProducerRedeclarationTimer",async()=>{await this.spanAsync("producerRedeclarationTimer",async()=>{if(this.params.config.producer.disableIntentRedeclaration)return;const e=await this.chainIterator.head();if(isUndefined$1(e))return;const t=e.block;if(await this.calculateBlocksUntilProducerDeclarationExpiration(t)>.1*BaseBlockProducerService.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 r=createDeclarationIntent(this.account.address,"producer",t,t+BaseBlockProducerService.RedeclarationDuration);await this.submitRedeclarationIntent(t,r),this._lastRedeclarationIntent=r})},1e4,TEN_MINUTES)}async calculateBlocksUntilProducerDeclarationExpiration(e){const t=(await this.stakeIntentService.getDeclaredCandidateRanges(this.account.address,"producer")).toSorted((e,t)=>e[1]>t[1]?1:-1).at(-1),[,r]=t||[void 0,e];return r-e}async submitRedeclarationIntent(e,t){this.logger?.log("Submitting redeclaration intent for producer:",this.account.address);const r=await buildTransaction(this.chainIterator.chainId,[t],[],this.account,e,e+1e3),n=flattenHydratedTransaction(r),i=r[0]._hash,s=new PayloadBuilder({schema:PayloadBundleSchema}).fields({payloads:n,root:i}).build();await this.pendingBundledTransactionsArchivistWrite.insert([s]),this.logger?.log("Submitted redeclaration intent for producer:",this.account.address)}async validateCurrentBalance(){const e=this._lastProducedBlock?.[0]._hash;if(isDefined(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.activeByAddressStaked(this.account.address)<e)||(this.logger?.error(`Producer ${this.account.address} has insufficient stake.`),!1)}};(class e extends Actor{static{__name(this,"ValidatorActor")}_lastValidatedBlock;_lastValidatedBlockHash;constructor(e){super("Validator","Validator",e)}get account(){return assertEx(this.params.account,()=>"account not set")}get balanceService(){return assertEx(this.params.balanceService,()=>"balanceService not set")}get chainIterator(){return assertEx(this.params.chainIterator,()=>"chainIterator not set")}get chainStakeViewer(){return assertEx(this.params.chainStakeViewer,()=>"chainStakeViewer not set")}get chainSubmissionsArchivistWrite(){return assertEx(this.params.chainSubmissionsArchivistWrite,()=>"chainSubmissionsArchivistWrite not set")}get pendingBundledTransactionsArchivistWrite(){return assertEx(this.params.pendingBundledTransactionsArchivistWrite,()=>"pendingBundledTransactionsArchivistWrite not set")}get stakeIntentService(){return assertEx(this.params.stakeIntentService,()=>"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(isUndefined$1(e))return;const t=await PayloadBuilder.hash(e);if(isDefined(this._lastValidatedBlock)&&this._lastValidatedBlockHash===t)this.logger?.log("Block already validated:",`0x${toHex(e.block)}`);else{this.logger?.log("Validating block:",`0x${toHex(e.block)}`);await this.validateBlock(e)?this.logger?.log("Validated block:",`0x${toHex(e.block)}`):(this.logger?.log("Invalid block:",`0x${toHex(e.block)}`),await this.slashInvalidBlock(e))}})},100,500)}async slashInvalidBlock(e){return await Promise.resolve(!0)}async validateBlock(e){const t=await Promise.resolve(!0);return this._lastValidatedBlock=e,this._lastValidatedBlockHash=await PayloadBuilder.hash(e),t}});var sendStatus=__name((e,t,r)=>{const n="started"===t?200:r;e.writeHead(n,{"Content-Type":"application/json"}),e.end(JSON.stringify({status:t}))},"sendStatus"),notFound=__name(e=>{e.writeHead(404,{"Content-Type":"application/json"}),e.end(JSON.stringify({status:"not found"}))},"notFound"),createHealthServer=__name((e,t,r)=>{const n=require$$3$3.createServer((e,r)=>{const n=e.url??"",i=t.getGlobalStatus();switch(n){case"/healthz":sendStatus(r,i,500);break;case"/livez":case"/readyz":sendStatus(r,i,503);break;default:notFound(r)}});return n.listen(e,()=>{r.log(`Health server running on http://localhost:${e}`),r.log(" - /healthz"),r.log(" - /livez"),r.log(" - /readyz")}),n},"createHealthServer"),initHealthEndpoints=__name(e=>{const{config:t,logger:r,statusReporter:n}=e,{healthCheckPort:i}=t.producer;return isDefined(i)?createHealthServer(i,n,r):void 0},"initHealthEndpoints"),getStoreDirectory=__name((e,t,r)=>void 0===r?require$$0__default.join(t,e):require$$0__default.join(t,r,e),"getStoreDirectory"),DEFAULT_STORAGE_ROOT=require$$0__default.join(process.cwd(),".store"),getLocalPersistentArchivist=__name((e,t,r,n="lmdb")=>{if("lmdb"===n){const n=r??DEFAULT_STORAGE_ROOT;return LmdbArchivist.create({account:"random",config:{clearStoreOnStart:!1,dbName:e,location:getStoreDirectory(e,n,"lmdb"),schema:LmdbArchivistConfigSchema,storeName:t}})}},"getLocalPersistentArchivist"),mutex=new Mutex,singleton,initLocalChainFinalizedArchivist=__name(async({config:e})=>await mutex.runExclusive(async()=>{if(singleton)return singleton;const{root:t}=e.storage;return singleton=await getLocalPersistentArchivist("chain","finalized",t)}),"initLocalChainFinalizedArchivist"),mutex2=new Mutex,singleton2,initRemoteChainFinalizedArchivist=__name(async({config:e})=>await mutex2.runExclusive(async()=>{if(singleton2)return singleton2;const{host:t,port:r}=e.api,n=getUrl(t,r),i=await initBridge(n);return assertEx(singleton2=await initBridgedArchivistModule({bridge:i,moduleName:"XYOChain:Chain:Finalized"}),()=>"Error: RemoteChainFinalizedArchivist failed to initialize")}),"initRemoteChainFinalizedArchivist"),mutex3=new Mutex,singleton3;async function initChainFinalizedArchivist({config:e,logger:t,traceProvider:r}){return await mutex3.runExclusive(async()=>{if(singleton3)return singleton3;const[n,i]=await Promise.all([startupSpanAsync("ChainFinalizedArchivist:initRemote",()=>initRemoteChainFinalizedArchivist({config:e,logger:t})),startupSpanAsync("ChainFinalizedArchivist:initLocal",()=>initLocalChainFinalizedArchivist({config:e,logger:t}))]);return await startupSpanAsync("ChainFinalizedArchivist:initArchivistSync",()=>initArchivistSync("ChainFinalizedArchivist",n,i,200,Number.MAX_SAFE_INTEGER,r)),singleton3=i})}__name(initChainFinalizedArchivist,"initChainFinalizedArchivist");var mutex4=new Mutex,singleton4,initRemoteChainSubmissionsArchivist=__name(async({config:e})=>await mutex4.runExclusive(async()=>{if(singleton4)return singleton4;const{host:t,port:r}=e.api,n=getUrl(t,r),i=await initBridge(n);return assertEx(singleton4=await initBridgedArchivistModule({bridge:i,moduleName:"XYOChain:Chain:Submissions"}),()=>new Error("Failed to initialize RemoteChainSubmissionsArchivist"))}),"initRemoteChainSubmissionsArchivist"),mutex5=new Mutex,singleton5,initChainSubmissionsArchivist=__name(async e=>await mutex5.runExclusive(async()=>{if(singleton5)return singleton5;const t=await startupSpanAsync("ChainSubmissionsArchivist:initRemote",()=>initRemoteChainSubmissionsArchivist(e));return assertEx(singleton5=t,()=>new Error("Failed to initialize ChainSubmissionsArchivist"))}),"initChainSubmissionsArchivist"),mutex6=new Mutex,singleton6,initLocalPendingTransactionsArchivist=__name(async()=>await mutex6.runExclusive(async()=>singleton6||(singleton6=await MemoryArchivist.create({account:"random",config:{schema:MemoryArchivistConfigSchema,max:1e3,name:"localPendingTransactions"}}))),"initLocalPendingTransactionsArchivist"),mutex7=new Mutex,singleton7,initRemotePendingTransactionsArchivist=__name(async({config:e})=>await mutex7.runExclusive(async()=>{if(singleton7)return singleton7;const{host:t,port:r}=e.api,n=getUrl(t,r),i=await initBridge(n);return assertEx(singleton7=await initBridgedArchivistModule({bridge:i,moduleName:"XYOChain:Pending:PendingTransactions"}),()=>"Error: RemotePendingBundledTransactionsArchivist is undefined")}),"initRemotePendingTransactionsArchivist"),mutex8=new Mutex,singleton8,initPendingBundledTransactionsArchivist=__name(async e=>await mutex8.runExclusive(async()=>{if(singleton8)return singleton8;const t=await startupSpanAsync("PendingBundledTransactionsArchivist:initRemote",()=>initRemotePendingTransactionsArchivist(e)),r=await startupSpanAsync("PendingBundledTransactionsArchivist:initLocal",()=>initLocalPendingTransactionsArchivist(e)),n=await t.next({limit:1,order:"desc"});return await r.insert(n),await startupSpanAsync("PendingBundledTransactionsArchivist:initArchivistSync",()=>initArchivistSync("PendingBundledTransactionsArchivist",t,r)),singleton8=[r,t]}),"initPendingBundledTransactionsArchivist"),mutex9=new Mutex,singleton9,initLocalRejectedTransactionsArchivist=__name(async()=>await mutex9.runExclusive(async()=>singleton9||(singleton9=await MemoryArchivist.create({account:"random",config:{schema:MemoryArchivistConfigSchema,max:1e3,name:"localRejectedTransactions"}}))),"initLocalRejectedTransactionsArchivist"),mutex10=new Mutex,singleton10;async function initRejectedTransactionsArchivist(e){return await mutex10.runExclusive(async()=>{if(singleton10)return singleton10;const t=await startupSpanAsync("RejectedTransactionsArchivist:initLocal",()=>initLocalRejectedTransactionsArchivist(e));return singleton10=t})}__name(initRejectedTransactionsArchivist,"initRejectedTransactionsArchivist");var mutex11=new Mutex,singleton11,initLocalStakeIntentStateArchivist=__name(async({config:e})=>await mutex11.runExclusive(async()=>{if(singleton11)return singleton11;const{root:t}=e.storage;return assertEx(singleton11=await getLocalPersistentArchivist("stakeIntent","state",t),()=>new Error("Failed to initialize stake intent state archivist"))}),"initLocalStakeIntentStateArchivist"),mutex12=new Mutex,singleton12,initStakeIntentStateArchivist=__name(async e=>await mutex12.runExclusive(async()=>{if(singleton12)return singleton12;const t=await startupSpanAsync("StakeIntentStateArchivist:initLocal",()=>initLocalStakeIntentStateArchivist(e));return assertEx(singleton12=t,()=>"Error: StakeIntentStateArchivist is undefined")}),"initStakeIntentStateArchivist");function _ts_decorate(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o}__name(_ts_decorate,"_ts_decorate");var SynchronousLmdbMap=class extends AbstractCreatable{static{__name(this,"SynchronousLmdbMap")}db;rootDatabase;get folderPath(){return`${this.params.location}/${this.params.dbName}`}all(){return[...this.db.getRange({})].map(e=>e.value)}clear(){this.db.clearSync()}delete(e){return this.db.removeSync(e)}get(e){return this.db.get(e)}has(e){return this.db.doesExist(e)}set(e,t){return this.db.putSync(e,t),this}async startHandler(){await super.startHandler(),this.rootDatabase=open({path:this.folderPath}),this.db=this.rootDatabase.openDB({name:this.params.storeName})}};SynchronousLmdbMap=_ts_decorate([creatable()],SynchronousLmdbMap);var DEFAULT_STORAGE_ROOT2=require$$0__default.join(process.cwd(),".store"),getLocalPersistentMap=__name(async(e,t,r,n="lmdb")=>{if("lmdb"===n){const n=getStoreDirectory(e,r??DEFAULT_STORAGE_ROOT2,"lmdb");return await SynchronousLmdbMap.create({location:n,dbName:e,storeName:t})}},"getLocalPersistentMap"),mutex13=new Mutex,singleton13,initLocalBalanceSummaryMap=__name(async e=>await mutex13.runExclusive(async()=>{if(isDefined(singleton13))return singleton13;const{root:t}=e.config.storage;return singleton13=await getLocalPersistentMap("balance","summary",t)}),"initLocalBalanceSummaryMap"),mutex14=new Mutex,singleton14,accountServiceSingleton;async function initBalanceSummaryMap(e){return await mutex14.runExclusive(async()=>{if(isDefined(singleton14))return singleton14;const t=await startupSpanAsync("BalanceSummaryMap:initLocal",()=>initLocalBalanceSummaryMap(e));return singleton14=t})}__name(initBalanceSummaryMap,"initBalanceSummaryMap");var initAccount=__name(async({config:e,logger:t})=>{if(accountServiceSingleton)return accountServiceSingleton;let r=e.producer.mnemonic;if(isUndefined$1(r)){t?.warn("[Producer] No wallet mnemonic specified!");const e=HDWallet.generateMnemonic();t?.warn(`[Producer] Using randomly generated mnemonic:\n \n${e}\n \n `),r=e}const n=await generateXyoBaseWalletFromPhrase(r),i=await n.derivePath(ADDRESS_INDEX.XYO);return accountServiceSingleton=i},"initAccount"),balanceServiceSingleton,initBalanceService=__name(async e=>balanceServiceSingleton||(balanceServiceSingleton=await BaseAccountBalanceService.create(e)),"initBalanceService"),canUseChainId=__name(e=>isDefined(e.evm.chainId),"canUseChainId"),getChainId=__name(e=>{const t=assertEx(e.evm.chainId,()=>"Missing config.evm.chainId");if(isHex(t,{prefix:!0})){const e=hexFrom(t);return Number.parseInt(e,16)}return Number.parseInt(t,10)},"getChainId"),instance,initInfuraProvider=__name(e=>{if(instance)return instance;const t=getInfuraProviderConfig(e);return instance=Promise.resolve(new InfuraProvider(...t))},"initInfuraProvider"),canUseInfuraProvider=__name(e=>canUseChainId(e)&&isDefined(e.evm?.infura?.projectId)&&isDefined(e.evm?.infura?.projectSecret),"canUseInfuraProvider"),getInfuraProviderConfig=__name(e=>{const t=assertEx(e.evm?.infura?.projectId,()=>"Missing config.evm.infura.projectId"),r=assertEx(e.evm?.infura?.projectSecret,()=>"Missing config.evm.infura.projectSecret");return[getChainId(e),t,r]},"getInfuraProviderConfig"),initJsonRpcProvider=__name(e=>{const t=getJsonRpcProviderConfig(e);return Promise.resolve(new JsonRpcProvider(...t))},"initJsonRpcProvider"),canUseJsonRpcProvider=__name(e=>canUseChainId(e)&&isDefined(e.evm.jsonRpc?.url),"canUseJsonRpcProvider"),getJsonRpcProviderConfig=__name(e=>[assertEx(e.evm.jsonRpc?.url,()=>"Missing config.evm.jsonRpc.url"),getChainId(e)],"getJsonRpcProviderConfig"),provider,initEvmProvider=__name(async({config:e})=>provider||(canUseInfuraProvider(e)?provider=initInfuraProvider(e):canUseJsonRpcProvider(e)&&(provider=initJsonRpcProvider(e)),assertEx(await provider,()=>"Error: No provider available")),"initEvmProvider"),canUseEvmProvider=__name(({config:e})=>canUseInfuraProvider(e)||canUseJsonRpcProvider(e),"canUseEvmProvider"),chainStakeServiceSingleton,canUseEvmContractChainService=__name(e=>{const{id:t}=e.chain;return isDefined(t)&&t!==ZERO_ADDRESS&&canUseEvmProvider({config:e})},"canUseEvmContractChainService"),initEvmContractChainService=__name(async({account:e,config:t,traceProvider:r,meterProvider:n,logger:i})=>{if(chainStakeServiceSingleton)return chainStakeServiceSingleton;const s=assertEx(t.chain.id,()=>"Error: config.chain.id is required"),o=assertEx(asAddress(s),()=>"Error: config.chain.id is not a valid address"),a=assertEx(await initEvmProvider({config:t})),c=assertEx(e.private?.hex,()=>"Error: Account does not have a private key"),u=new Wallet(c,a);return chainStakeServiceSingleton=EvmChainService.create({id:o,runner:u,traceProvider:r,meterProvider:n,logger:i}),await chainStakeServiceSingleton},"initEvmContractChainService"),chainStakeServiceSingleton2,initChainService=__name(({account:e,config:t})=>init({config:t,name:"ChainService",account:e}),"initChainService"),init=__name(e=>{if(chainStakeServiceSingleton2)return chainStakeServiceSingleton2;const{config:t}=e;return chainStakeServiceSingleton2=canUseEvmContractChainService(t)?initEvmContractChainService({...e,name:"ChainStakeService"}):MemoryChainService.create({...e,name:"ChainStakeService"})},"init"),headSingleton,createBootstrapHead=__name(async(e,t,r)=>{const n=await createGenesisBlock(r,ZERO_ADDRESS,10000000n,r.address),[i]=n;for(await e.insert(flattenHydratedBlock(n));;){if((await t.get([i._hash])).length>0)break;await delay(1e3)}return i},"createBootstrapHead"),initHead=__name(async e=>{const{account:t,chainArchivist:r,chainSubmissionsArchivistWrite:n}=e;if(headSingleton)return headSingleton;let i=await findMostRecentBlock(r);return i||(i=await createBootstrapHead(n,r,t)),headSingleton=i},"initHead"),chainIteratorServiceSingleton,stakeIntentServiceSingleton,electionServiceSingleton,initChainIterator=__name(e=>chainIteratorServiceSingleton||(chainIteratorServiceSingleton=ChainBlockNumberIterationService.create(e)),"initChainIterator"),initStakeIntentService=__name(e=>stakeIntentServiceSingleton||(stakeIntentServiceSingleton=XyoStakeIntentService.create(e)),"initStakeIntentService"),initElectionService=__name(e=>electionServiceSingleton||(electionServiceSingleton=BaseElectionService.create(e)),"initElectionService"),serviceSingleton,initPendingTransactions=__name(async e=>serviceSingleton||(serviceSingleton=await BasePendingTransactionsService.create(e)),"initPendingTransactions"),serviceSingleton2,initBlockProducer=__name(async e=>serviceSingleton2||(serviceSingleton2=await BaseBlockProducerService.create(e)),"initBlockProducer"),rewardServiceSingleton,initBlockRewardService=__name(e=>{if(rewardServiceSingleton)return rewardServiceSingleton;const{config:t}=e;return rewardServiceSingleton=canUseEvmBlockRewardService({config:t})?initEvmBlockRewardService(e):initXyoBlockRewardService(e)},"initBlockRewardService"),initXyoBlockRewardService=__name(e=>rewardServiceSingleton||(rewardServiceSingleton=MemoryBlockRewardService.create(e)),"initXyoBlockRewardService"),canUseEvmBlockRewardService=__name(e=>canUseEvmProvider({config:e.config}),"canUseEvmBlockRewardService"),initEvmBlockRewardService=__name(async e=>{if(rewardServiceSingleton)return rewardServiceSingleton;const{account:t}=e,r=assertEx(t,()=>"Error: Account is required"),n=assertEx(await initEvmProvider(e)),i={...e,provider:n,account:r};return rewardServiceSingleton=EvmBlockRewardService.create(i)},"initEvmBlockRewardService"),LoggerStatusReporter=class{static{__name(this,"LoggerStatusReporter")}logger;statusMap={};constructor(e){this.logger=e}report(e,t,r){this.statusMap[e]=t;const n=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}/${n+i} ${e} status: ${t}`,{progress:r})}},statusPriority={error:0,stopped:1,stopping:2,creating:3,created:4,starting:5,started:6},SENTINEL_STATUS="starting",reduceToMinimumStatus=__name(e=>{let t=SENTINEL_STATUS,r=1/0;for(const n of e){const e=statusPriority[n];e<r&&(r=e,t=n)}return t},"reduceToMinimumStatus"),RuntimeStatusMonitor=class extends LoggerStatusReporter{static{__name(this,"RuntimeStatusMonitor")}globalTransitions=[];transitions=[];getGlobalStatus(){return 0===Object.keys(this.statusMap).length?SENTINEL_STATUS:reduceToMinimumStatus(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,r){const n=this.statusMap[e],i=this.getGlobalStatus();if(super.report(e,t,r),n===t)return;this.runTransitions(this.transitions,n,t,e);const s=this.getGlobalStatus();i!==s&&this.runTransitions(this.globalTransitions,i,s)}runTransitions(e,t,r,n){for(const{from:i,to:s,name:o,handler:a}of e)void 0!==o&&o!==n||void 0!==i&&i!==t||void 0!==s&&s!==r||a(t,r)}},telemetryConfig={attributes:{serviceName:"xl1-producer",serviceVersion:"1.0.0"},metricsConfig:{endpoint:"/metrics",port:9464}},isStartable=__name(e=>isDefined(e.start)&&"function"==typeof e.start,"isStartable"),initServices=__name(async e=>{const{config:t,logger:r}=e,n=new RuntimeStatusMonitor(r);n.onGlobalTransition({to:"started"},()=>{r.log("All services started.")}),n.onGlobalTransition({to:"error"},()=>{r.error("Producer encountered an unhandled error!"),process.exit(1)}),await startupSpanAsync("initHealthEndpoints",()=>initHealthEndpoints({...e,statusReporter:n}));const[{traceProvider:i,meterProvider:s},o]=await Promise.all([startupSpanAsync("initTelemetry",()=>initTelemetry(telemetryConfig)),startupSpanAsync("initAccount",()=>initAccount(e))]),a={config:t,logger:r,meterProvider:s,statusReporter:n,traceProvider:i},[c,[u,l],d,p,f,h,A]=await Promise.all([startupSpanAsync("ChainFinalizedArchivist",()=>initChainFinalizedArchivist(a)),startupSpanAsync("PendingBundledTransactionsArchivist",()=>initPendingBundledTransactionsArchivist(a)),startupSpanAsync("RejectedTransactionsArchivist",()=>initRejectedTransactionsArchivist(a)),startupSpanAsync("ChainSubmissionsArchivist",()=>initChainSubmissionsArchivist(a)),startupSpanAsync("StakeIntentStateArchivist",()=>initStakeIntentStateArchivist(a)),startupSpanAsync("ChainService",()=>initChainService({...a,account:o,name:"ChainService"})),startupSpanAsync("BalanceSummaryMap",()=>initBalanceSummaryMap(a))]),g=h.chainId,m=h,E=h,y=h,_=await startupSpanAsync("initHead",()=>initHead({...a,account:o,chainArchivist:c,chainSubmissionsArchivistWrite:p})),[S,C,b,I]=await Promise.all([startupSpanAsync("PendingTransactions",()=>initPendingTransactions({name:"PendingTransactionsService",chainArchivist:c,chainId:g,pendingBundledTransactionsArchivist:u,rejectedTransactionsArchivist:d,...a})),startupSpanAsync("RewardService",()=>initBlockRewardService({name:"RewardService",account:o,chainService:h,...a})),startupSpanAsync("ChainIterator",()=>initChainIterator({name:"ChainIterator",chainArchivist:c,head:_,...a})),startupSpanAsync("BalanceService",()=>initBalanceService({name:"BalanceService",chainArchivist:c,summaryRepository:balanceSummaryRepositoryFromMap(A),...a}))]),v=await startupSpanAsync("StakeIntentService",()=>initStakeIntentService({name:"StakeIntentService",chainArchivist:c,chainIterator:b,chainStakeViewer:E,stakeIntentStateArchivist:f,...a})),T=await startupSpanAsync("ElectionService",()=>initElectionService({name:"ElectionService",chainIterator:b,chainStakeViewer:E,stakeIntentService:v,...a})),w={name:"Validator",account:o,chainId:g,pendingBundledTransactionsArchivist:u,chainArchivist:c,electionService:T,rewardService:C,stakeIntentService:v,validateHydratedBlockState:validateHydratedBlockState,...a},B=isDefined(t.producer.rewardAddress)?assertEx(asAddress(t.producer.rewardAddress),()=>"Invalid block reward address provided"):o.address,R={...w,name:"Producer",balanceService:I,chainArchivist:c,pendingBundledTransactionsArchivist:u,pendingTransactionsService:S,rejectedTransactionsArchivist:d,rewardAddress:B,...a},D=await startupSpanAsync("Producer",()=>initBlockProducer(R)),x={account:o,balanceService:I,chainArchivist:c,chainContractViewer:m,chainIterator:b,chainStaker:y,chainStakeViewer:E,chainSubmissionsArchivistWrite:p,electionService:T,pendingBundledTransactionsArchivistWrite:l,pendingTransactionsService:S,producer:D,rewardService:C,stakeIntentService:v};r?.log("All services created. Starting...");const O=[A,...Object.values(x)].filter(isStartable);return await Promise.all(O.map(e=>e.start())),x},"initServices");function runApi(e){getServer(e)}__name(runApi,"runApi");var runProducer=__name(async e=>{const{config:t,logger:r,orchestrator:n}=e;r?.log("Services: Initializing...");const i=await initServices(e);r?.log("Services: Initialized");const s={...i,config:t},o=[await ChainHeadUpdateActor.create(s),await BalanceActor.create(s),await ProducerActor.create(s)];for(const e of o)await n.registerActor(e);await n.start()},"runProducer"),XL1LogoColorizedAscii="                    _\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                   ²^",initLogger=__name(e=>{let t;if(e.silent)t=new SilentLogger;else{let r;if(isDefined(e.logLevel)){const t=LogLevel[e.logLevel.toLowerCase()];isDefined(t)&&(r=t)}t=new ConsoleLogger(r)}return Base$1.defaultLogger=t,t},"initLogger"),usageMetaToOptions=__name(e=>e,"usageMetaToOptions"),optionsFromGlobalZodRegistry=__name(()=>{const e={};for(const t of globalRegistry._map.values())if(isUsageMeta(t)){if(t.hidden)continue;e[t.title]=usageMetaToOptions(t)}return e},"optionsFromGlobalZodRegistry"),configName="xyo",configSection="xl1",tryParseConfig=__name(()=>{const e=distExports.cosmiconfigSync(configName).search();if(!isNull(e)){const t=e?.config?.[configSection];if(isDefined(t)&&"object"==typeof t)return t}return{}},"tryParseConfig"),waitForHostPort=__name((e,t)=>new Promise(r=>{const n=__name(()=>{const i=new require$$0$j.Socket;i.setTimeout(1e3).once("error",()=>{i.destroy(),setTimeout(n,500)}).once("timeout",()=>{i.destroy(),setTimeout(n,500)}).connect(t,e,()=>{i.end(),r()})},"tryConnect");n()}),"waitForHostPort"),config,version=isDefined("1.12.1")?"1.12.1":"unknown",getContextFromConfig=__name(e=>{const t=initLogger(e),r=new Orchestrator(t);return process.on("SIGINT",()=>{(async()=>{try{t.log("\nSIGINT received. Attempting graceful shutdown..."),await(r?.stop()),t.log("Orchestrator stopped, exiting now."),process.exit(0)}catch(e){t.error("Error stopping orchestrator:",e),process.exit(1)}})()}),{logger:t,orchestrator:r}},"getContextFromConfig");async function runCLI(){const e=Yargs(hideBin(process.argv)),t=e.usage(`\n🚀 XL1 Node CLI (${version})\n${XL1LogoColorizedAscii}\nRun various components of the XL1 ecosystem.\n\nUsage:\n$0 <command> [options]`).parserConfiguration({"dot-notation":!0,"populate--":!0}).env("XL1").scriptName("xl1").middleware(e=>{try{const t=tryParseConfig(),r=deepMerge(e,t);config=ConfigZod.parse(r)}catch(e){throw e instanceof ZodError&&console.error(`${e.message}`),new Error("Invalid configuration")}}).options(optionsFromGlobalZodRegistry()).wrap(e.terminalWidth()).command("api","Run a XL1 API Node",e=>e.command("$0","Run a XL1 API Node",()=>{},()=>{runApi({...getContextFromConfig(config),config:config})})).command("producer","Run a XL1 Producer Node",e=>e.command("$0","Run a XL1 Producer Node",()=>{},async()=>{const e=getContextFromConfig(config);await runProducer({...e,config:config})})).command("$0","Run a full XL1 Node",()=>{},async()=>{const e=getContextFromConfig(config);runApi({...e,config:config}),await waitForHostPort("localhost",config.api.port),await runProducer({...e,config:config})}).help().alias("help","h").version(version).argv;await t}__name(runCLI,"runCLI");var start=__name(async()=>{mainExports.config({quiet:!0}),await runCLI()},"start");start().catch(e=>{"development"===process.env.NODE_ENV&&console.error("An error occurred during startup:",e),process.exit(1)});
419
+ /* 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 ExplorerSync.ExplorerSync=a,ExplorerSync}function requireDist(){return hasRequiredDist||(hasRequiredDist=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.defaultLoadersSync=e.defaultLoaders=e.globalConfigSearchPlacesSync=e.globalConfigSearchPlaces=e.getDefaultSearchPlacesSync=e.getDefaultSearchPlaces=e.cosmiconfigSync=e.cosmiconfig=void 0;const t=requireDefaults();Object.defineProperty(e,"defaultLoaders",{enumerable:!0,get:function(){return t.defaultLoaders}}),Object.defineProperty(e,"defaultLoadersSync",{enumerable:!0,get:function(){return t.defaultLoadersSync}}),Object.defineProperty(e,"getDefaultSearchPlaces",{enumerable:!0,get:function(){return t.getDefaultSearchPlaces}}),Object.defineProperty(e,"getDefaultSearchPlacesSync",{enumerable:!0,get:function(){return t.getDefaultSearchPlacesSync}}),Object.defineProperty(e,"globalConfigSearchPlaces",{enumerable:!0,get:function(){return t.globalConfigSearchPlaces}}),Object.defineProperty(e,"globalConfigSearchPlacesSync",{enumerable:!0,get:function(){return t.globalConfigSearchPlacesSync}});const r=requireExplorer(),n=requireExplorerSync(),i=requireUtil(),s=function(e){return e};function o(e,t,r){const n=r.searchPlaces?.map(t=>t.replace("{name}",e));return r.mergeSearchPlaces?[...n??[],...t]:n??t}function a(e,r,a){const c=function(){const e=new n.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 r={mergeSearchPlaces:!0,...e.config??{}};return{config:(0,i.removeUndefinedValuesFromObject)(r),filepath:e.filepath}}();if(!c)return{...r,...(0,i.removeUndefinedValuesFromObject)(a),loaders:{...r.loaders,...a.loaders}};const u=c.config,l=a.searchPlaces??r.searchPlaces;return{...r,...(0,i.removeUndefinedValuesFromObject)(a),metaConfigFilePath:c.filepath,...u,searchPlaces:o(e,l,u),loaders:{...r.loaders,...a.loaders}}}function c(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,n={}){const i=function(e,r){return c(r),a(e,{moduleName:e,searchPlaces:(0,t.getDefaultSearchPlaces)(e),ignoreEmptySearchPlaces:!0,cache:!0,transform:s,loaders:t.defaultLoaders,metaConfigFilePath:null,mergeImportArrays:!0,mergeSearchPlaces:!0,searchStrategy:r.stopDir?"global":"none"},r)}(e,n),o=new r.Explorer(i);return{search:o.search.bind(o),load:o.load.bind(o),clearLoadCache:o.clearLoadCache.bind(o),clearSearchCache:o.clearSearchCache.bind(o),clearCaches:o.clearCaches.bind(o)}},e.cosmiconfigSync=function(e,r={}){const i=function(e,r){return c(r),a(e,{moduleName:e,searchPlaces:(0,t.getDefaultSearchPlacesSync)(e),ignoreEmptySearchPlaces:!0,cache:!0,transform:s,loaders:t.defaultLoadersSync,metaConfigFilePath:null,mergeImportArrays:!0,mergeSearchPlaces:!0,searchStrategy:r.stopDir?"global":"none"},r)}(e,r),o=new n.ExplorerSync(i);return{search:o.search.bind(o),load:o.load.bind(o),clearLoadCache:o.clearLoadCache.bind(o),clearSearchCache:o.clearSearchCache.bind(o),clearCaches:o.clearCaches.bind(o)}}}(dist)),dist}var distExports=requireDist(),main={exports:{}},version$1="17.2.1",require$$4={version:version$1},hasRequiredMain;function requireMain(){if(hasRequiredMain)return main.exports;hasRequiredMain=1;const e=require$$0$e,t=require$$0__default,r=require$$0$a,n=require$$0$g,i=require$$4.version,s=["🔐 encrypt with Dotenvx: https://dotenvx.com","🔐 prevent committing .env to code: https://dotenvx.com/precommit","🔐 prevent building .env in docker: https://dotenvx.com/prebuild","📡 observe env with Radar: https://dotenvx.com/radar","📡 auto-backup env with Radar: https://dotenvx.com/radar","📡 version env with Radar: https://dotenvx.com/radar","🛠️ 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 o(e){return"string"==typeof e?!["false","0","no","off",""].includes(e.toLowerCase()):Boolean(e)}function a(e){return process.stdout.isTTY?`${e}`:e}const c=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function u(e){console.log(`[dotenv@${i}][DEBUG] ${e}`)}function l(e){console.log(`[dotenv@${i}] ${e}`)}function d(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 p(e,t){let r;try{r=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 n=r.password;if(!n){const e=new Error("INVALID_DOTENV_KEY: Missing key part");throw e.code="INVALID_DOTENV_KEY",e}const i=r.searchParams.get("environment");if(!i){const e=new Error("INVALID_DOTENV_KEY: Missing environment part");throw e.code="INVALID_DOTENV_KEY",e}const s=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[s];if(!o){const e=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${s} in your .env.vault file.`);throw e.code="NOT_FOUND_DOTENV_ENVIRONMENT",e}return{ciphertext:o,key:n}}function f(r){let n=null;if(r&&r.path&&r.path.length>0)if(Array.isArray(r.path))for(const t of r.path)e.existsSync(t)&&(n=t.endsWith(".vault")?t:`${t}.vault`);else n=r.path.endsWith(".vault")?r.path:`${r.path}.vault`;else n=t.resolve(process.cwd(),".env.vault");return e.existsSync(n)?n:null}function h(e){return"~"===e[0]?t.join(r.homedir(),e.slice(1)):e}const A={configDotenv:function(r){const n=t.resolve(process.cwd(),".env");let i="utf8",c=process.env;r&&null!=r.processEnv&&(c=r.processEnv);let d=o(c.DOTENV_CONFIG_DEBUG||r&&r.debug),p=o(c.DOTENV_CONFIG_QUIET||r&&r.quiet);r&&r.encoding?i=r.encoding:d&&u("No encoding is specified. UTF-8 is used by default");let f,g=[n];if(r&&r.path)if(Array.isArray(r.path)){g=[];for(const e of r.path)g.push(h(e))}else g=[h(r.path)];const m={};for(const t of g)try{const n=A.parse(e.readFileSync(t,{encoding:i}));A.populate(m,n,r)}catch(e){d&&u(`Failed to load ${t} ${e.message}`),f=e}const E=A.populate(c,m,r);if(d=o(c.DOTENV_CONFIG_DEBUG||d),p=o(c.DOTENV_CONFIG_QUIET||p),d||!p){const e=Object.keys(E).length,r=[];for(const e of g)try{const n=t.relative(process.cwd(),e);r.push(n)}catch(t){d&&u(`Failed to load ${e} ${t.message}`),f=t}l(`injecting env (${e}) from ${r.join(",")} ${a(`-- tip: ${s[Math.floor(Math.random()*s.length)]}`)}`)}return f?{parsed:m,error:f}:{parsed:m}},_configVault:function(e){const t=o(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),r=o(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);!t&&r||l("Loading env from encrypted .env.vault");const n=A._parseVault(e);let i=process.env;return e&&null!=e.processEnv&&(i=e.processEnv),A.populate(i,n,e),{parsed:n}},_parseVault:function(e){const t=f(e=e||{});e.path=t;const r=A.configDotenv(e);if(!r.parsed){const e=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code="MISSING_DATA",e}const n=d(e).split(","),i=n.length;let s;for(let e=0;e<i;e++)try{const t=p(r,n[e].trim());s=A.decrypt(t.ciphertext,t.key);break}catch(t){if(e+1>=i)throw t}return A.parse(s)},config:function(e){if(0===d(e).length)return A.configDotenv(e);const t=f(e);return t?A._configVault(e):(function(e){console.error(`[dotenv@${i}][WARN] ${e}`)}(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),A.configDotenv(e))},decrypt:function(e,t){const r=Buffer.from(t.slice(-64),"hex");let i=Buffer.from(e,"base64");const s=i.subarray(0,12),o=i.subarray(-16);i=i.subarray(12,-16);try{const e=n.createDecipheriv("aes-256-gcm",r,s);return e.setAuthTag(o),`${e.update(i)}${e.final()}`}catch(e){const t=e instanceof RangeError,r="Invalid key length"===e.message,n="Unsupported state or unable to authenticate data"===e.message;if(t||r){const e=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw e.code="INVALID_DOTENV_KEY",e}if(n){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 r,n=e.toString();for(n=n.replace(/\r\n?/gm,"\n");null!=(r=c.exec(n));){const e=r[1];let n=r[2]||"";n=n.trim();const i=n[0];n=n.replace(/^(['"`])([\s\S]*)\1$/gm,"$2"),'"'===i&&(n=n.replace(/\\n/g,"\n"),n=n.replace(/\\r/g,"\r")),t[e]=n}return t},populate:function(e,t,r={}){const n=Boolean(r&&r.debug),i=Boolean(r&&r.override),s={};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 r of Object.keys(t))Object.prototype.hasOwnProperty.call(e,r)?(!0===i&&(e[r]=t[r],s[r]=t[r]),n&&u(!0===i?`"${r}" is already defined and WAS overwritten`:`"${r}" is already defined and was NOT overwritten`)):(e[r]=t[r],s[r]=t[r]);return s}};return main.exports.configDotenv=A.configDotenv,main.exports._configVault=A._configVault,main.exports._parseVault=A._parseVault,main.exports.config=A.config,main.exports.decrypt=A.decrypt,main.exports.parse=A.parse,main.exports.populate=A.populate,main.exports=A,main.exports}var mainExports=requireMain(),__defProp=Object.defineProperty,__name=(e,t)=>__defProp(e,"name",{value:t,configurable:!0}),Actor=class extends Base$1{static{__name(this,"Actor")}_timers=new Map;_active=!1;_displayName;_id;constructor(e,t="Actor",r){const n=r.logger??new IdLogger(Base$1.defaultLogger??console,()=>`[${t} (${e})] `);super({...r,logger:n}),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,r,n){if(!this._active)return void this.logger?.warn(`Cannot register timer '${e}' because actor is not active.`);const i=__name(async()=>{if(this._active&&this._timers.has(e))try{await t()}catch(t){this.logger?.error(`Error in timer '${this.name}:${e}': ${t}`)}finally{this._timers.set(e,setTimeout(()=>forgetNode(i(),{name:`schedulePeriodicRun:${this.name}:${e}`}),n))}},"schedulePeriodicRun");this._timers.set(e,setTimeout(()=>forgetNode(i(),{name:`schedulePeriodicRun(initial):${this.name}:${e}`}),r)),this.logger?.log(`Timer '${this.name}:${e}' registered: first call after ${r}ms, recurring every ${n}ms.`)}span(e,t){return span(`${this.name}:${e}`,t,this.tracer)}async spanAsync(e,t){return await spanAsync(`${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...");for(const[,e]of this._timers.entries())clearTimeout(e);this._timers.clear(),this.logger?.log("Stopped.")}},Orchestrator=class{static{__name(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.")}},BalanceActor=class e extends Actor{static{__name(this,"BalanceActor")}_updateMutex=new Mutex;constructor(e){super("BalanceActor","Balance",e)}get balanceService(){return assertEx(this.params.balanceService,()=>"balanceService not set")}get chainIterator(){return assertEx(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,1e3)}async updateBalance(){this._updateMutex.isLocked()||await this._updateMutex.runExclusive(async()=>{const e=await PayloadBuilder.hash(await this.chainIterator.head());await this.balanceService.balances(e,[])})}},ChainHeadUpdateActor=class e extends Actor{static{__name(this,"ChainHeadUpdateActor")}constructor(e){super("ChainHeadUpdate","ChainHeadUpdate",e)}get chainFinalizedArchivist(){return assertEx(this.params.chainArchivist,()=>"ChainArchivist not set")}get chainIterator(){return assertEx(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,250)}async checkInsertedForNewHead(e){const t=sortBlocks(filterAs(e.payloads,asBlockBoundWitness)).at(-1);await this.updateHeadIfNewer(t)}async pollForNewHead(){const e=await findMostRecentBlock(this.chainFinalizedArchivist);await this.updateHeadIfNewer(e)}async updateHeadIfNewer(e){if(!e)return;const t=await this.chainIterator.head(),r=e.block,n=`0x${toHex(r)}`;r>(t?.block??-1)&&(this.logger?.log("Found more recent head:",n),await this.chainIterator.updateHead(e),this.logger?.log("Updated head:",n))}},TEN_MINUTES=6e5,ProducerActor=class e extends Actor{static{__name(this,"ProducerActor")}_lastProducedBlock;_lastRedeclarationIntent;constructor(e){super(e.producer.address,"Producer",e)}get account(){return assertEx(this.params.account,()=>"account not set")}get balanceService(){return assertEx(this.params.balanceService,()=>"balanceService not set")}get chainIterator(){return assertEx(this.params.chainIterator,()=>"chainIterator not set")}get chainStakeViewer(){return assertEx(this.params.chainStakeViewer,()=>"chainStakeViewer not set")}get chainSubmissionsArchivistWrite(){return assertEx(this.params.chainSubmissionsArchivistWrite,()=>"chainSubmissionsArchivistWrite not set")}get pendingBundledTransactionsArchivistWrite(){return assertEx(this.params.pendingBundledTransactionsArchivistWrite,()=>"pendingBundledTransactionsArchivistWrite not set")}get producer(){return assertEx(this.params.producer,()=>"producer not set")}get stakeIntentService(){return assertEx(this.params.stakeIntentService,()=>"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(),t=await PayloadBuilder.hash(e);if(this._lastProducedBlock&&this._lastProducedBlock[0].previous===t)this.logger?.log("Block already produced:",`0x${toHex(this._lastProducedBlock[0].block)}`);else{const t=await this.producer.next(e);if(t){const e=`0x${toHex(t[0].block)}`;this.logger?.log("Produced block:",e),await this.chainSubmissionsArchivistWrite.insert(flattenHydratedBlock(t)),this.logger?.log("Published block:",e),this._lastProducedBlock=t}}})},100,500),this.registerTimer("ProducerRedeclarationTimer",async()=>{await this.spanAsync("producerRedeclarationTimer",async()=>{if(this.params.config.producer.disableIntentRedeclaration)return;const e=await this.chainIterator.head();if(isUndefined$1(e))return;const t=e.block;if(await this.calculateBlocksUntilProducerDeclarationExpiration(t)>.1*BaseBlockProducerService.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 r=createDeclarationIntent(this.account.address,"producer",t,t+BaseBlockProducerService.RedeclarationDuration);await this.submitRedeclarationIntent(t,r),this._lastRedeclarationIntent=r})},1e4,TEN_MINUTES)}async calculateBlocksUntilProducerDeclarationExpiration(e){const t=(await this.stakeIntentService.getDeclaredCandidateRanges(this.account.address,"producer")).toSorted((e,t)=>e[1]>t[1]?1:-1).at(-1),[,r]=t||[void 0,e];return r-e}async submitRedeclarationIntent(e,t){this.logger?.log("Submitting redeclaration intent for producer:",this.account.address);const r=await buildTransaction(this.chainIterator.chainId,[t],[],this.account,e,e+1e3),n=flattenHydratedTransaction(r),i=r[0]._hash,s=new PayloadBuilder({schema:PayloadBundleSchema}).fields({payloads:n,root:i}).build();await this.pendingBundledTransactionsArchivistWrite.insert([s]),this.logger?.log("Submitted redeclaration intent for producer:",this.account.address)}async validateCurrentBalance(){const e=this._lastProducedBlock?.[0]._hash;if(isDefined(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.activeByAddressStaked(this.account.address)<e)||(this.logger?.error(`Producer ${this.account.address} has insufficient stake.`),!1)}};(class e extends Actor{static{__name(this,"ValidatorActor")}_lastValidatedBlock;_lastValidatedBlockHash;constructor(e){super("Validator","Validator",e)}get account(){return assertEx(this.params.account,()=>"account not set")}get balanceService(){return assertEx(this.params.balanceService,()=>"balanceService not set")}get chainIterator(){return assertEx(this.params.chainIterator,()=>"chainIterator not set")}get chainStakeViewer(){return assertEx(this.params.chainStakeViewer,()=>"chainStakeViewer not set")}get chainSubmissionsArchivistWrite(){return assertEx(this.params.chainSubmissionsArchivistWrite,()=>"chainSubmissionsArchivistWrite not set")}get pendingBundledTransactionsArchivistWrite(){return assertEx(this.params.pendingBundledTransactionsArchivistWrite,()=>"pendingBundledTransactionsArchivistWrite not set")}get stakeIntentService(){return assertEx(this.params.stakeIntentService,()=>"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(isUndefined$1(e))return;const t=await PayloadBuilder.hash(e);if(isDefined(this._lastValidatedBlock)&&this._lastValidatedBlockHash===t)this.logger?.log("Block already validated:",`0x${toHex(e.block)}`);else{this.logger?.log("Validating block:",`0x${toHex(e.block)}`);await this.validateBlock(e)?this.logger?.log("Validated block:",`0x${toHex(e.block)}`):(this.logger?.log("Invalid block:",`0x${toHex(e.block)}`),await this.slashInvalidBlock(e))}})},100,500)}async slashInvalidBlock(e){return await Promise.resolve(!0)}async validateBlock(e){const t=await Promise.resolve(!0);return this._lastValidatedBlock=e,this._lastValidatedBlockHash=await PayloadBuilder.hash(e),t}});var sendStatus=__name((e,t,r)=>{const n="started"===t?200:r;e.writeHead(n,{"Content-Type":"application/json"}),e.end(JSON.stringify({status:t}))},"sendStatus"),notFound=__name(e=>{e.writeHead(404,{"Content-Type":"application/json"}),e.end(JSON.stringify({status:"not found"}))},"notFound"),createHealthServer=__name((e,t,r)=>{const n=require$$3$3.createServer((e,r)=>{const n=e.url??"",i=t.getGlobalStatus();switch(n){case"/healthz":sendStatus(r,i,500);break;case"/livez":case"/readyz":sendStatus(r,i,503);break;default:notFound(r)}});return n.listen(e,()=>{r.log(`Health server running on http://localhost:${e}`),r.log(" - /healthz"),r.log(" - /livez"),r.log(" - /readyz")}),n},"createHealthServer"),initHealthEndpoints=__name(e=>{const{config:t,logger:r,statusReporter:n}=e,{healthCheckPort:i}=t.producer;return isDefined(i)?createHealthServer(i,n,r):void 0},"initHealthEndpoints"),getStoreDirectory=__name((e,t,r)=>void 0===r?require$$0__default.join(t,e):require$$0__default.join(t,r,e),"getStoreDirectory"),DEFAULT_STORAGE_ROOT=require$$0__default.join(process.cwd(),".store"),getLocalPersistentArchivist=__name((e,t,r,n="lmdb")=>{if("lmdb"===n){const n=r??DEFAULT_STORAGE_ROOT;return LmdbArchivist.create({account:"random",config:{clearStoreOnStart:!1,dbName:e,location:getStoreDirectory(e,n,"lmdb"),schema:LmdbArchivistConfigSchema,storeName:t}})}},"getLocalPersistentArchivist"),mutex=new Mutex,singleton,initLocalChainFinalizedArchivist=__name(async({config:e})=>await mutex.runExclusive(async()=>{if(singleton)return singleton;const{root:t}=e.storage;return singleton=await getLocalPersistentArchivist("chain","finalized",t)}),"initLocalChainFinalizedArchivist"),mutex2=new Mutex,singleton2,initRemoteChainFinalizedArchivist=__name(async({config:e})=>await mutex2.runExclusive(async()=>{if(singleton2)return singleton2;const{host:t,port:r}=e.api,n=getUrl(t,r),i=await initBridge(n);return assertEx(singleton2=await initBridgedArchivistModule({bridge:i,moduleName:"XYOChain:Chain:Finalized"}),()=>"Error: RemoteChainFinalizedArchivist failed to initialize")}),"initRemoteChainFinalizedArchivist"),mutex3=new Mutex,singleton3;async function initChainFinalizedArchivist({config:e,logger:t,traceProvider:r}){return await mutex3.runExclusive(async()=>{if(singleton3)return singleton3;const[n,i]=await Promise.all([startupSpanAsync("ChainFinalizedArchivist:initRemote",()=>initRemoteChainFinalizedArchivist({config:e,logger:t})),startupSpanAsync("ChainFinalizedArchivist:initLocal",()=>initLocalChainFinalizedArchivist({config:e,logger:t}))]);return await startupSpanAsync("ChainFinalizedArchivist:initArchivistSync",()=>initArchivistSync("ChainFinalizedArchivist",n,i,200,Number.MAX_SAFE_INTEGER,r)),singleton3=i})}__name(initChainFinalizedArchivist,"initChainFinalizedArchivist");var mutex4=new Mutex,singleton4,initRemoteChainSubmissionsArchivist=__name(async({config:e})=>await mutex4.runExclusive(async()=>{if(singleton4)return singleton4;const{host:t,port:r}=e.api,n=getUrl(t,r),i=await initBridge(n);return assertEx(singleton4=await initBridgedArchivistModule({bridge:i,moduleName:"XYOChain:Chain:Submissions"}),()=>new Error("Failed to initialize RemoteChainSubmissionsArchivist"))}),"initRemoteChainSubmissionsArchivist"),mutex5=new Mutex,singleton5,initChainSubmissionsArchivist=__name(async e=>await mutex5.runExclusive(async()=>{if(singleton5)return singleton5;const t=await startupSpanAsync("ChainSubmissionsArchivist:initRemote",()=>initRemoteChainSubmissionsArchivist(e));return assertEx(singleton5=t,()=>new Error("Failed to initialize ChainSubmissionsArchivist"))}),"initChainSubmissionsArchivist"),mutex6=new Mutex,singleton6,initLocalPendingTransactionsArchivist=__name(async()=>await mutex6.runExclusive(async()=>singleton6||(singleton6=await MemoryArchivist.create({account:"random",config:{schema:MemoryArchivistConfigSchema,max:1e3,name:"localPendingTransactions"}}))),"initLocalPendingTransactionsArchivist"),mutex7=new Mutex,singleton7,initRemotePendingTransactionsArchivist=__name(async({config:e})=>await mutex7.runExclusive(async()=>{if(singleton7)return singleton7;const{host:t,port:r}=e.api,n=getUrl(t,r),i=await initBridge(n);return assertEx(singleton7=await initBridgedArchivistModule({bridge:i,moduleName:"XYOChain:Pending:PendingTransactions"}),()=>"Error: RemotePendingBundledTransactionsArchivist is undefined")}),"initRemotePendingTransactionsArchivist"),mutex8=new Mutex,singleton8,initPendingBundledTransactionsArchivist=__name(async e=>await mutex8.runExclusive(async()=>{if(singleton8)return singleton8;const t=await startupSpanAsync("PendingBundledTransactionsArchivist:initRemote",()=>initRemotePendingTransactionsArchivist(e)),r=await startupSpanAsync("PendingBundledTransactionsArchivist:initLocal",()=>initLocalPendingTransactionsArchivist(e)),n=await t.next({limit:1,order:"desc"});return await r.insert(n),await startupSpanAsync("PendingBundledTransactionsArchivist:initArchivistSync",()=>initArchivistSync("PendingBundledTransactionsArchivist",t,r)),singleton8=[r,t]}),"initPendingBundledTransactionsArchivist"),mutex9=new Mutex,singleton9,initLocalRejectedTransactionsArchivist=__name(async()=>await mutex9.runExclusive(async()=>singleton9||(singleton9=await MemoryArchivist.create({account:"random",config:{schema:MemoryArchivistConfigSchema,max:1e3,name:"localRejectedTransactions"}}))),"initLocalRejectedTransactionsArchivist"),mutex10=new Mutex,singleton10;async function initRejectedTransactionsArchivist(e){return await mutex10.runExclusive(async()=>{if(singleton10)return singleton10;const t=await startupSpanAsync("RejectedTransactionsArchivist:initLocal",()=>initLocalRejectedTransactionsArchivist(e));return singleton10=t})}__name(initRejectedTransactionsArchivist,"initRejectedTransactionsArchivist");var mutex11=new Mutex,singleton11,initLocalStakeIntentStateArchivist=__name(async({config:e})=>await mutex11.runExclusive(async()=>{if(singleton11)return singleton11;const{root:t}=e.storage;return assertEx(singleton11=await getLocalPersistentArchivist("stakeIntent","state",t),()=>new Error("Failed to initialize stake intent state archivist"))}),"initLocalStakeIntentStateArchivist"),mutex12=new Mutex,singleton12,initStakeIntentStateArchivist=__name(async e=>await mutex12.runExclusive(async()=>{if(singleton12)return singleton12;const t=await startupSpanAsync("StakeIntentStateArchivist:initLocal",()=>initLocalStakeIntentStateArchivist(e));return assertEx(singleton12=t,()=>"Error: StakeIntentStateArchivist is undefined")}),"initStakeIntentStateArchivist");function _ts_decorate(e,t,r,n){var i,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o}__name(_ts_decorate,"_ts_decorate");var SynchronousLmdbMap=class extends AbstractCreatable{static{__name(this,"SynchronousLmdbMap")}db;rootDatabase;get folderPath(){return`${this.params.location}/${this.params.dbName}`}all(){return[...this.db.getRange({})].map(e=>e.value)}clear(){this.db.clearSync()}delete(e){return this.db.removeSync(e)}get(e){return this.db.get(e)}has(e){return this.db.doesExist(e)}set(e,t){return this.db.putSync(e,t),this}async startHandler(){await super.startHandler(),this.rootDatabase=open({path:this.folderPath}),this.db=this.rootDatabase.openDB({name:this.params.storeName})}};SynchronousLmdbMap=_ts_decorate([creatable()],SynchronousLmdbMap);var DEFAULT_STORAGE_ROOT2=require$$0__default.join(process.cwd(),".store"),getLocalPersistentMap=__name(async(e,t,r,n="lmdb")=>{if("lmdb"===n){const n=getStoreDirectory(e,r??DEFAULT_STORAGE_ROOT2,"lmdb");return await SynchronousLmdbMap.create({location:n,dbName:e,storeName:t})}},"getLocalPersistentMap"),mutex13=new Mutex,singleton13,initLocalBalanceSummaryMap=__name(async e=>await mutex13.runExclusive(async()=>{if(isDefined(singleton13))return singleton13;const{root:t}=e.config.storage;return singleton13=await getLocalPersistentMap("balance","summary",t)}),"initLocalBalanceSummaryMap"),mutex14=new Mutex,singleton14,accountServiceSingleton;async function initBalanceSummaryMap(e){return await mutex14.runExclusive(async()=>{if(isDefined(singleton14))return singleton14;const t=await startupSpanAsync("BalanceSummaryMap:initLocal",()=>initLocalBalanceSummaryMap(e));return singleton14=t})}__name(initBalanceSummaryMap,"initBalanceSummaryMap");var initAccount=__name(async({config:e,logger:t})=>{if(accountServiceSingleton)return accountServiceSingleton;let r=e.producer.mnemonic;if(isUndefined$1(r)){t?.warn("[Producer] No wallet mnemonic specified!");const e=HDWallet.generateMnemonic();t?.warn(`[Producer] Using randomly generated mnemonic:\n \n${e}\n \n `),r=e}const n=await generateXyoBaseWalletFromPhrase(r),i=await n.derivePath(ADDRESS_INDEX.XYO);return accountServiceSingleton=i},"initAccount"),balanceServiceSingleton,initBalanceService=__name(async e=>balanceServiceSingleton||(balanceServiceSingleton=await BaseAccountBalanceService.create(e)),"initBalanceService"),canUseChainId=__name(e=>isDefined(e.evm.chainId),"canUseChainId"),getChainId=__name(e=>{const t=assertEx(e.evm.chainId,()=>"Missing config.evm.chainId");if(isHex(t,{prefix:!0})){const e=hexFrom(t);return Number.parseInt(e,16)}return Number.parseInt(t,10)},"getChainId"),instance,initInfuraProvider=__name(e=>{if(instance)return instance;const t=getInfuraProviderConfig(e);return instance=Promise.resolve(new InfuraProvider(...t))},"initInfuraProvider"),canUseInfuraProvider=__name(e=>canUseChainId(e)&&isDefined(e.evm?.infura?.projectId)&&isDefined(e.evm?.infura?.projectSecret),"canUseInfuraProvider"),getInfuraProviderConfig=__name(e=>{const t=assertEx(e.evm?.infura?.projectId,()=>"Missing config.evm.infura.projectId"),r=assertEx(e.evm?.infura?.projectSecret,()=>"Missing config.evm.infura.projectSecret");return[getChainId(e),t,r]},"getInfuraProviderConfig"),initJsonRpcProvider=__name(e=>{const t=getJsonRpcProviderConfig(e);return Promise.resolve(new JsonRpcProvider(...t))},"initJsonRpcProvider"),canUseJsonRpcProvider=__name(e=>canUseChainId(e)&&isDefined(e.evm.jsonRpc?.url),"canUseJsonRpcProvider"),getJsonRpcProviderConfig=__name(e=>[assertEx(e.evm.jsonRpc?.url,()=>"Missing config.evm.jsonRpc.url"),getChainId(e)],"getJsonRpcProviderConfig"),provider,initEvmProvider=__name(async({config:e})=>provider||(canUseInfuraProvider(e)?provider=initInfuraProvider(e):canUseJsonRpcProvider(e)&&(provider=initJsonRpcProvider(e)),assertEx(await provider,()=>"Error: No provider available")),"initEvmProvider"),canUseEvmProvider=__name(({config:e})=>canUseInfuraProvider(e)||canUseJsonRpcProvider(e),"canUseEvmProvider"),chainStakeServiceSingleton,canUseEvmContractChainService=__name(e=>{const{id:t}=e.chain;return isDefined(t)&&t!==ZERO_ADDRESS&&canUseEvmProvider({config:e})},"canUseEvmContractChainService"),initEvmContractChainService=__name(async({account:e,config:t,traceProvider:r,meterProvider:n,logger:i})=>{if(chainStakeServiceSingleton)return chainStakeServiceSingleton;const s=assertEx(t.chain.id,()=>"Error: config.chain.id is required"),o=assertEx(asAddress(s),()=>"Error: config.chain.id is not a valid address"),a=assertEx(await initEvmProvider({config:t})),c=assertEx(e.private?.hex,()=>"Error: Account does not have a private key"),u=new Wallet(c,a);return chainStakeServiceSingleton=EvmChainService.create({id:o,runner:u,traceProvider:r,meterProvider:n,logger:i}),await chainStakeServiceSingleton},"initEvmContractChainService"),chainStakeServiceSingleton2,initChainService=__name(({account:e,config:t})=>init({config:t,name:"ChainService",account:e}),"initChainService"),init=__name(e=>{if(chainStakeServiceSingleton2)return chainStakeServiceSingleton2;const{config:t}=e;return chainStakeServiceSingleton2=canUseEvmContractChainService(t)?initEvmContractChainService({...e,name:"ChainStakeService"}):MemoryChainService.create({...e,name:"ChainStakeService"})},"init"),headSingleton,createBootstrapHead=__name(async(e,t,r)=>{const n=await createGenesisBlock(r,ZERO_ADDRESS,10000000n,r.address),[i]=n;for(await e.insert(flattenHydratedBlock(n));;){if((await t.get([i._hash])).length>0)break;await delay(1e3)}return i},"createBootstrapHead"),initHead=__name(async e=>{const{account:t,chainArchivist:r,chainSubmissionsArchivistWrite:n}=e;if(headSingleton)return headSingleton;let i=await findMostRecentBlock(r);return i||(i=await createBootstrapHead(n,r,t)),headSingleton=i},"initHead"),chainIteratorServiceSingleton,stakeIntentServiceSingleton,electionServiceSingleton,initChainIterator=__name(e=>chainIteratorServiceSingleton||(chainIteratorServiceSingleton=ChainBlockNumberIterationService.create(e)),"initChainIterator"),initStakeIntentService=__name(e=>stakeIntentServiceSingleton||(stakeIntentServiceSingleton=XyoStakeIntentService.create(e)),"initStakeIntentService"),initElectionService=__name(e=>electionServiceSingleton||(electionServiceSingleton=BaseElectionService.create(e)),"initElectionService"),serviceSingleton,initPendingTransactions=__name(async e=>serviceSingleton||(serviceSingleton=await BasePendingTransactionsService.create(e)),"initPendingTransactions"),serviceSingleton2,initBlockProducer=__name(async e=>serviceSingleton2||(serviceSingleton2=await BaseBlockProducerService.create(e)),"initBlockProducer"),rewardServiceSingleton,initBlockRewardService=__name(e=>{if(rewardServiceSingleton)return rewardServiceSingleton;const{config:t}=e;return rewardServiceSingleton=canUseEvmBlockRewardService({config:t})?initEvmBlockRewardService(e):initXyoBlockRewardService(e)},"initBlockRewardService"),initXyoBlockRewardService=__name(e=>rewardServiceSingleton||(rewardServiceSingleton=MemoryBlockRewardService.create(e)),"initXyoBlockRewardService"),canUseEvmBlockRewardService=__name(e=>canUseEvmProvider({config:e.config}),"canUseEvmBlockRewardService"),initEvmBlockRewardService=__name(async e=>{if(rewardServiceSingleton)return rewardServiceSingleton;const{account:t}=e,r=assertEx(t,()=>"Error: Account is required"),n=assertEx(await initEvmProvider(e)),i={...e,provider:n,account:r};return rewardServiceSingleton=EvmBlockRewardService.create(i)},"initEvmBlockRewardService"),LoggerStatusReporter=class{static{__name(this,"LoggerStatusReporter")}logger;statusMap={};constructor(e){this.logger=e}report(e,t,r){this.statusMap[e]=t;const n=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}/${n+i} ${e} status: ${t}`,{progress:r})}},statusPriority={error:0,stopped:1,stopping:2,creating:3,created:4,starting:5,started:6},SENTINEL_STATUS="starting",reduceToMinimumStatus=__name(e=>{let t=SENTINEL_STATUS,r=1/0;for(const n of e){const e=statusPriority[n];e<r&&(r=e,t=n)}return t},"reduceToMinimumStatus"),RuntimeStatusMonitor=class extends LoggerStatusReporter{static{__name(this,"RuntimeStatusMonitor")}globalTransitions=[];transitions=[];getGlobalStatus(){return 0===Object.keys(this.statusMap).length?SENTINEL_STATUS:reduceToMinimumStatus(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,r){const n=this.statusMap[e],i=this.getGlobalStatus();if(super.report(e,t,r),n===t)return;this.runTransitions(this.transitions,n,t,e);const s=this.getGlobalStatus();i!==s&&this.runTransitions(this.globalTransitions,i,s)}runTransitions(e,t,r,n){for(const{from:i,to:s,name:o,handler:a}of e)void 0!==o&&o!==n||void 0!==i&&i!==t||void 0!==s&&s!==r||a(t,r)}},telemetryConfig={attributes:{serviceName:"xl1-producer",serviceVersion:"1.0.0"},metricsConfig:{endpoint:"/metrics",port:9464}},isStartable=__name(e=>isDefined(e.start)&&"function"==typeof e.start,"isStartable"),initServices=__name(async e=>{const{config:t,logger:r}=e,n=new RuntimeStatusMonitor(r);n.onGlobalTransition({to:"started"},()=>{r.log("All services started.")}),n.onGlobalTransition({to:"error"},()=>{r.error("Producer encountered an unhandled error!"),process.exit(1)}),await startupSpanAsync("initHealthEndpoints",()=>initHealthEndpoints({...e,statusReporter:n}));const[{traceProvider:i,meterProvider:s},o]=await Promise.all([startupSpanAsync("initTelemetry",()=>initTelemetry(telemetryConfig)),startupSpanAsync("initAccount",()=>initAccount(e))]),a={config:t,logger:r,meterProvider:s,statusReporter:n,traceProvider:i},[c,[u,l],d,p,f,h,A]=await Promise.all([startupSpanAsync("ChainFinalizedArchivist",()=>initChainFinalizedArchivist(a)),startupSpanAsync("PendingBundledTransactionsArchivist",()=>initPendingBundledTransactionsArchivist(a)),startupSpanAsync("RejectedTransactionsArchivist",()=>initRejectedTransactionsArchivist(a)),startupSpanAsync("ChainSubmissionsArchivist",()=>initChainSubmissionsArchivist(a)),startupSpanAsync("StakeIntentStateArchivist",()=>initStakeIntentStateArchivist(a)),startupSpanAsync("ChainService",()=>initChainService({...a,account:o,name:"ChainService"})),startupSpanAsync("BalanceSummaryMap",()=>initBalanceSummaryMap(a))]),g=h.chainId,m=h,E=h,y=h,_=await startupSpanAsync("initHead",()=>initHead({...a,account:o,chainArchivist:c,chainSubmissionsArchivistWrite:p})),[S,C,b,I]=await Promise.all([startupSpanAsync("PendingTransactions",()=>initPendingTransactions({name:"PendingTransactionsService",chainArchivist:c,chainId:g,pendingBundledTransactionsArchivist:u,rejectedTransactionsArchivist:d,...a})),startupSpanAsync("RewardService",()=>initBlockRewardService({name:"RewardService",account:o,chainService:h,...a})),startupSpanAsync("ChainIterator",()=>initChainIterator({name:"ChainIterator",chainArchivist:c,head:_,...a})),startupSpanAsync("BalanceService",()=>initBalanceService({name:"BalanceService",chainArchivist:c,summaryRepository:balanceSummaryRepositoryFromMap(A),...a}))]),v=await startupSpanAsync("StakeIntentService",()=>initStakeIntentService({name:"StakeIntentService",chainArchivist:c,chainIterator:b,chainStakeViewer:E,stakeIntentStateArchivist:f,...a})),T=await startupSpanAsync("ElectionService",()=>initElectionService({name:"ElectionService",chainIterator:b,chainStakeViewer:E,stakeIntentService:v,...a})),w={name:"Validator",account:o,chainId:g,pendingBundledTransactionsArchivist:u,chainArchivist:c,electionService:T,rewardService:C,stakeIntentService:v,validateHydratedBlockState:validateHydratedBlockState,...a},B=isDefined(t.producer.rewardAddress)?assertEx(asAddress(t.producer.rewardAddress),()=>"Invalid block reward address provided"):o.address,R={...w,name:"Producer",balanceService:I,chainArchivist:c,pendingBundledTransactionsArchivist:u,pendingTransactionsService:S,rejectedTransactionsArchivist:d,rewardAddress:B,...a},D=await startupSpanAsync("Producer",()=>initBlockProducer(R)),x={account:o,balanceService:I,chainArchivist:c,chainContractViewer:m,chainIterator:b,chainStaker:y,chainStakeViewer:E,chainSubmissionsArchivistWrite:p,electionService:T,pendingBundledTransactionsArchivistWrite:l,pendingTransactionsService:S,producer:D,rewardService:C,stakeIntentService:v};r?.log("All services created. Starting...");const O=[A,...Object.values(x)].filter(isStartable);return await Promise.all(O.map(e=>e.start())),x},"initServices");function runApi(e){getServer(e)}__name(runApi,"runApi");var runProducer=__name(async e=>{const{config:t,logger:r,orchestrator:n}=e;r?.log("Services: Initializing...");const i=await initServices(e);r?.log("Services: Initialized");const s={...i,config:t},o=[await ChainHeadUpdateActor.create(s),await BalanceActor.create(s),await ProducerActor.create(s)];for(const e of o)await n.registerActor(e);await n.start()},"runProducer"),XL1LogoColorizedAscii="                    _\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                   ²^",initLogger=__name(e=>{let t;if(e.silent)t=new SilentLogger;else{let r;if(isDefined(e.logLevel)){const t=LogLevel[e.logLevel.toLowerCase()];isDefined(t)&&(r=t)}t=new ConsoleLogger(r)}return Base$1.defaultLogger=t,t},"initLogger"),usageMetaToOptions=__name(e=>e,"usageMetaToOptions"),optionsFromGlobalZodRegistry=__name(()=>{const e={};for(const t of globalRegistry._map.values())if(isUsageMeta(t)){if(t.hidden)continue;e[t.title]=usageMetaToOptions(t)}return e},"optionsFromGlobalZodRegistry"),configName="xyo",configSection="xl1",tryParseConfig=__name(()=>{const e=distExports.cosmiconfigSync(configName).search();if(!isNull(e)){const t=e?.config?.[configSection];if(isDefined(t)&&"object"==typeof t)return t}return{}},"tryParseConfig"),waitForHostPort=__name((e,t)=>new Promise(r=>{const n=__name(()=>{const i=new require$$0$j.Socket;i.setTimeout(1e3).once("error",()=>{i.destroy(),setTimeout(n,500)}).once("timeout",()=>{i.destroy(),setTimeout(n,500)}).connect(t,e,()=>{i.end(),r()})},"tryConnect");n()}),"waitForHostPort"),config,version=isDefined("1.12.3")?"1.12.3":"unknown",getContextFromConfig=__name(e=>{const t=initLogger(e),r=new Orchestrator(t);return process.on("SIGINT",()=>{(async()=>{try{t.log("\nSIGINT received. Attempting graceful shutdown..."),await(r?.stop()),t.log("Orchestrator stopped, exiting now."),process.exit(0)}catch(e){t.error("Error stopping orchestrator:",e),process.exit(1)}})()}),{logger:t,orchestrator:r}},"getContextFromConfig");async function runCLI(){const e=Yargs(hideBin(process.argv)),t=e.usage(`\n🚀 XL1 Node CLI (${version})\n${XL1LogoColorizedAscii}\nRun various components of the XL1 ecosystem.\n\nUsage:\n$0 <command> [options]`).parserConfiguration({"dot-notation":!0,"populate--":!0}).env("XL1").scriptName("xl1").middleware(e=>{try{const t=tryParseConfig(),r=deepMerge(e,t);config=ConfigZod.parse(r)}catch(e){throw e instanceof ZodError&&console.error(`${e.message}`),new Error("Invalid configuration")}}).options(optionsFromGlobalZodRegistry()).wrap(e.terminalWidth()).command("api","Run a XL1 API Node",e=>e.command("$0","Run a XL1 API Node",()=>{},()=>{runApi({...getContextFromConfig(config),config:config})})).command("producer","Run a XL1 Producer Node",e=>e.command("$0","Run a XL1 Producer Node",()=>{},async()=>{const e=getContextFromConfig(config);await runProducer({...e,config:config})})).command("$0","Run a full XL1 Node",()=>{},async()=>{const e=getContextFromConfig(config);runApi({...e,config:config}),await waitForHostPort("localhost",config.api.port),await runProducer({...e,config:config})}).help().alias("help","h").version(version).argv;await t}__name(runCLI,"runCLI");var start=__name(async()=>{mainExports.config({quiet:!0}),await runCLI()},"start");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.12.2",
3
+ "version": "1.12.4",
4
4
  "description": "XYO Layer One CLI",
5
5
  "homepage": "https://xylabs.com",
6
6
  "bugs": {
@@ -71,7 +71,7 @@
71
71
  "@xyo-network/payload-model": "~5.0.7",
72
72
  "@xyo-network/wallet": "~5.0.7",
73
73
  "@xyo-network/wallet-model": "~5.0.7",
74
- "@xyo-network/xl1-cli-lib": "~1.12.2",
74
+ "@xyo-network/xl1-cli-lib": "~1.12.4",
75
75
  "@xyo-network/xl1-protocol": "~1.10.15",
76
76
  "async-mutex": "~0.5.0",
77
77
  "dotenv": "~17.2.1",