@xyo-network/xl1-cli 1.16.4 → 1.16.5
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.
- package/dist/cli-min.mjs +1 -1
- package/package.json +2 -2
package/dist/cli-min.mjs
CHANGED
|
@@ -349,4 +349,4 @@ if(await(0,o.isDirectory)(a.path))for(const e of this.getSearchPlacesForDir(a,r.
|
|
|
349
349
|
if(i.done)throw new Error(`Could not find any folders to iterate through (start from ${e})`);let a=i.value;const s=()=>{
|
|
350
350
|
/* istanbul ignore if -- @preserve */
|
|
351
351
|
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);
|
|
352
|
-
/* 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 $Fe.ExplorerSync=c,$Fe}(),a=PFe(),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)}}}(y_e)),y_e),YFe={exports:{}},JFe={version:"17.2.3"};var WFe=function(){if(KFe)return YFe.exports;KFe=1;const e=P,t=i,r=n,a=b,s=JFe.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?`[2m${e}[0m`: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 YFe.exports.configDotenv=g.configDotenv,YFe.exports._configVault=g._configVault,YFe.exports._parseVault=g._parseVault,YFe.exports.config=g.config,YFe.exports.decrypt=g.decrypt,YFe.exports.parse=g.parse,YFe.exports.populate=g.populate,YFe.exports=g,YFe.exports}(),ZFe=Object.defineProperty,XFe=(e,t)=>ZFe(e,"name",{value:t,configurable:!0}),eRe=class extends SA{static{XFe(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 LA(SA.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.params.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 CA(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 qA(`${this.name}:${e}`,t,this.tracer)}async spanAsync(e,t){return await $A(`${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 NA(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.")}},tRe=class{static{XFe(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.")}},nRe=class e extends eRe{static{XFe(this,"BalanceActor")}_updateMutex=new DA;constructor(e){super("BalanceActor","Balance",e)}get balanceService(){return $e(this.params.balance,()=>"balanceService not set")}get chainIterator(){return $e(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 EA.hash(await this.chainIterator.head());await this.balanceService.balances(e,[])})}},rRe=class e extends eRe{static{XFe(this,"ChainHeadUpdateActor")}constructor(e){super("ChainHeadUpdate","ChainHeadUpdate",e)}get chainFinalizedArchivist(){return $e(this.params.chainArchivist,()=>"ChainArchivist not set")}get chainIterator(){return $e(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$(VA(e.payloads,jj)).at(-1);await this.updateHeadIfNewer(t)}async pollForNewHead(){const e=await U$(this.chainFinalizedArchivist);await this.updateHeadIfNewer(e)}async updateHeadIfNewer(e){if(!e)return;const t=await this.chainIterator.head(),n=e.block,r=`0x${Qh(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))}},iRe=6e5,aRe=class e extends eRe{static{XFe(this,"ProducerActor")}_lastProducedBlock;_lastRedeclarationIntent;constructor(e){super(e.producer.address,"Producer",e)}get account(){return $e(this.params.account,()=>"account not set")}get balanceService(){return $e(this.params.balance,()=>"balanceService not set")}get chainIterator(){return $e(this.params.chainIterator,()=>"chainIterator not set")}get chainStakeViewer(){return $e(this.params.chainStakeViewer,()=>"chainStakeViewer not set")}get chainSubmissionsArchivistWrite(){return $e(this.params.chainSubmissionsArchivistWrite,()=>"chainSubmissionsArchivistWrite not set")}get pendingBundledTransactionsArchivistWrite(){return $e(this.params.pendingBundledTransactionsArchivistWrite,()=>"pendingBundledTransactionsArchivistWrite not set")}get producer(){return $e(this.params.producer,()=>"producer not set")}get stakeIntentService(){return $e(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()},iRe,iRe)}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${Qh(t._hash)}`);const r=t._hash;if(this._lastProducedBlock&&this._lastProducedBlock[0].previous===r)this.logger?.log("Block already produced:",`0x${Qh(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${Qh(n[0].block)}`;this.logger?.log("Produced block:",e),await this.chainSubmissionsArchivistWrite.insert($G(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(Ye(e))return;const t=e.block;if(await this.calculateBlocksUntilProducerDeclarationExpiration(t)>.1*U5.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=S$(this.account.address,"producer",t,t+U5.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 Sz(this.chainIterator.chainId,[t],[],this.account,e,e+1e3),r=_z(n),i=n[0]._hash,a=new EA({schema:zf}).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(Je(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 eRe{static{XFe(this,"ValidatorActor")}_lastValidatedBlock;_lastValidatedBlockHash;constructor(e){super("Validator","Validator",e)}get account(){return $e(this.params.account,()=>"account not set")}get balanceService(){return $e(this.params.balance,()=>"balanceService not set")}get chainIterator(){return $e(this.params.chainIterator,()=>"chainIterator not set")}get chainStakeViewer(){return $e(this.params.chainStakeViewer,()=>"chainStakeViewer not set")}get chainSubmissionsArchivistWrite(){return $e(this.params.chainSubmissionsArchivistWrite,()=>"chainSubmissionsArchivistWrite not set")}get pendingBundledTransactionsArchivistWrite(){return $e(this.params.pendingBundledTransactionsArchivistWrite,()=>"pendingBundledTransactionsArchivistWrite not set")}get stakeIntentService(){return $e(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(Ye(e))return;const t=await EA.hash(e);if(Je(this._lastValidatedBlock)&&this._lastValidatedBlockHash===t)this.logger?.log("Block already validated:",`0x${Qh(e.block)}`);else{this.logger?.log("Validating block:",`0x${Qh(e.block)}`);await this.validateBlock(e)?this.logger?.log("Validated block:",`0x${Qh(e.block)}`):(this.logger?.log("Invalid block:",`0x${Qh(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 EA.hash(e),t}});var sRe,oRe,cRe,uRe=XFe((e,t,n)=>{const r="started"===t?200:n;e.writeHead(r,{"Content-Type":"application/json"}),e.end(JSON.stringify({status:t}))},"sendStatus"),lRe=XFe(e=>{e.writeHead(404,{"Content-Type":"application/json"}),e.end(JSON.stringify({status:"not found"}))},"notFound"),dRe=XFe((e,t,n)=>{const r=R.createServer((e,n)=>{const r=e.url??"",i=t.getGlobalStatus();switch(r){case"/healthz":uRe(n,i,500);break;case"/livez":case"/readyz":uRe(n,i,503);break;default:lRe(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"),pRe=XFe(e=>{const{config:t,logger:n,statusReporter:r}=e,{healthCheckPort:i}=t.producer;return Je(i)?dRe(i,r,n):void 0},"initHealthEndpoints"),hRe=i.join(process.cwd(),".store"),fRe=XFe((e,t,n,r,i="lmdb")=>{if("lmdb"===i){const i=r??hRe;return F3.create({account:"random",config:{name:e,clearStoreOnStart:!1,dbName:t,location:R$(t,i,"lmdb"),schema:O3,storeName:n}})}},"getLocalPersistentArchivist"),ARe=new DA,mRe=XFe(async({config:e})=>await ARe.runExclusive(async()=>{if(sRe)return sRe;const{root:t}=e.storage;return sRe=await fRe("local-finalized-chain","chain","finalized",t)}),"initLocalChainFinalizedArchivist"),gRe=new DA,yRe=XFe(async({config:e})=>await gRe.runExclusive(async()=>{if(oRe)return oRe;const{host:t,port:n}=e.mempool.enabled?e.mempool:e.api,r=Cq(t,n),i=await m6(r);return $e(oRe=await v6({bridge:i,moduleName:"XYOChain:Chain:Finalized"}),()=>"Error: RemoteChainFinalizedArchivist failed to initialize")}),"initRemoteChainFinalizedArchivist"),bRe=new DA;async function vRe({config:e,logger:t,traceProvider:n}){return await bRe.runExclusive(async()=>{if(cRe)return cRe;const[r,i]=await Promise.all([S5("ChainFinalizedArchivist:initRemote",()=>yRe({config:e,logger:t})),S5("ChainFinalizedArchivist:initLocal",()=>mRe({config:e,logger:t}))]);return await S5("ChainFinalizedArchivist:initArchivistSync",()=>h6("ChainFinalizedArchivist",r,i,200,Number.MAX_SAFE_INTEGER,n)),cRe=i})}XFe(vRe,"initChainFinalizedArchivist");var ERe,IRe,wRe,CRe,BRe,xRe,DRe,SRe=new DA,kRe=XFe(async({config:e})=>await SRe.runExclusive(async()=>{if(ERe)return ERe;const{host:t,port:n}=e.mempool.enabled?e.mempool:e.api,r=Cq(t,n),i=await m6(r);return $e(ERe=await v6({bridge:i,moduleName:"XYOChain:Chain:Submissions"}),()=>new Error("Failed to initialize RemoteChainSubmissionsArchivist"))}),"initRemoteChainSubmissionsArchivist"),TRe=new DA,_Re=XFe(async e=>await TRe.runExclusive(async()=>{if(IRe)return IRe;const t=await S5("ChainSubmissionsArchivist:initRemote",()=>kRe(e));return $e(IRe=t,()=>new Error("Failed to initialize ChainSubmissionsArchivist"))}),"initChainSubmissionsArchivist"),ORe=new DA,FRe=XFe(async()=>await ORe.runExclusive(async()=>wRe||(wRe=await sG.create({account:"random",config:{schema:iG,max:1e3,name:"localPendingTransactions"}}))),"initLocalPendingTransactionsArchivist"),RRe=new DA,NRe=XFe(async({config:e})=>await RRe.runExclusive(async()=>{if(CRe)return CRe;const{host:t,port:n}=e.mempool.enabled?e.mempool:e.api,r=Cq(t,n),i=await m6(r);return $e(CRe=await v6({bridge:i,moduleName:"XYOChain:Pending:PendingTransactions"}),()=>"Error: RemotePendingBundledTransactionsArchivist is undefined")}),"initRemotePendingTransactionsArchivist"),MRe=new DA,QRe=XFe(async e=>await MRe.runExclusive(async()=>{if(BRe)return BRe;const t=await S5("PendingBundledTransactionsArchivist:initRemote",()=>NRe(e)),n=await S5("PendingBundledTransactionsArchivist:initLocal",()=>FRe(e)),r=await t.next({limit:1,order:"desc"});return await n.insert(r),await S5("PendingBundledTransactionsArchivist:initArchivistSync",()=>h6("PendingBundledTransactionsArchivist",t,n)),BRe=[n,t]}),"initPendingBundledTransactionsArchivist"),PRe=new DA,jRe=XFe(async()=>await PRe.runExclusive(async()=>xRe||(xRe=await sG.create({account:"random",config:{schema:iG,max:1e3,name:"localRejectedTransactions"}}))),"initLocalRejectedTransactionsArchivist"),URe=new DA;async function LRe(e){return await URe.runExclusive(async()=>{if(DRe)return DRe;const t=await S5("RejectedTransactionsArchivist:initLocal",()=>jRe(e));return DRe=t})}XFe(LRe,"initRejectedTransactionsArchivist");var HRe,GRe,qRe,zRe,$Re=new DA,KRe=XFe(async({config:e})=>await $Re.runExclusive(async()=>{if(HRe)return HRe;const{root:t}=e.storage;return $e(HRe=await fRe("local-stake-intent-state","stakeIntent","state",t),()=>new Error("Failed to initialize stake intent state archivist"))}),"initLocalStakeIntentStateArchivist"),VRe=new DA,YRe=XFe(async e=>await VRe.runExclusive(async()=>{if(GRe)return GRe;const t=await S5("StakeIntentStateArchivist:initLocal",()=>KRe(e));return $e(GRe=t,()=>"Error: StakeIntentStateArchivist is undefined")}),"initStakeIntentStateArchivist"),JRe=new DA,WRe=XFe(async e=>await JRe.runExclusive(async()=>{if(Je(qRe))return qRe;const{root:t}=e.config.storage;return qRe=await M$("balance","summary",t)}),"initLocalBalanceSummaryMap"),ZRe=new DA;async function XRe(e){return await ZRe.runExclusive(async()=>{if(Je(zRe))return zRe;const t=await S5("BalanceSummaryMap:initLocal",()=>WRe(e));return zRe=t})}XFe(XRe,"initBalanceSummaryMap");var eNe,tNe,nNe,rNe=new DA,iNe=XFe(async e=>await rNe.runExclusive(async()=>{if(Je(eNe))return eNe;const{root:t}=e.config.storage;return eNe=await M$("transfer","summary",t)}),"initLocalTransferSummaryMap"),aNe=new DA;async function sNe(e){return await aNe.runExclusive(async()=>{if(Je(tNe))return tNe;const t=await S5("TransferSummaryMap:initLocal",()=>iNe(e));return tNe=t})}XFe(sNe,"initTransferSummaryMap");var oNe,cNe,uNe,lNe,dNe,pNe,hNe,fNe,ANe,mNe,gNe,yNe,bNe,vNe,ENe=XFe(async({config:e,logger:t})=>{if(nNe)return nNe;let n=e.producer.mnemonic;if(Ye(n)){t?.warn("[Producer] No wallet mnemonic specified!");const e=HG.generateMnemonic();t?.warn(`[Producer] Using randomly generated mnemonic:\n \n${e}\n \n `),n=e}const r=await Jz(n),i=await r.derivePath(Yz);return nNe=i},"initAccount"),INe=XFe(async e=>oNe||(oNe=await N5.create(e)),"initBalanceService"),wNe=XFe(e=>Je(e.evm.chainId),"canUseChainId"),CNe=XFe(e=>{const t=$e(e.evm.chainId,()=>"Missing config.evm.chainId");if(_h(t,{prefix:!0})){const e=Nh(t);return Number.parseInt(e,16)}return Number.parseInt(t,10)},"getChainId"),BNe=XFe(e=>{if(cNe)return cNe;const t=DNe(e);return cNe=Promise.resolve(new _D(...t))},"initInfuraProvider"),xNe=XFe(e=>wNe(e)&&Je(e.evm?.infura?.projectId)&&Je(e.evm?.infura?.projectSecret),"canUseInfuraProvider"),DNe=XFe(e=>{const t=$e(e.evm?.infura?.projectId,()=>"Missing config.evm.infura.projectId"),n=$e(e.evm?.infura?.projectSecret,()=>"Missing config.evm.infura.projectSecret");return[CNe(e),t,n]},"getInfuraProviderConfig"),SNe=XFe(e=>{const t=TNe(e);return Promise.resolve(new Ix(...t))},"initJsonRpcProvider"),kNe=XFe(e=>wNe(e)&&Je(e.evm.jsonRpc?.url),"canUseJsonRpcProvider"),TNe=XFe(e=>[$e(e.evm.jsonRpc?.url,()=>"Missing config.evm.jsonRpc.url"),CNe(e)],"getJsonRpcProviderConfig"),_Ne=XFe(async({config:e})=>uNe||(xNe(e)?uNe=BNe(e):kNe(e)&&(uNe=SNe(e)),$e(await uNe,()=>"Error: No provider available")),"initEvmProvider"),ONe=XFe(({config:e})=>xNe(e)||kNe(e),"canUseEvmProvider"),FNe=XFe(e=>{const{id:t}=e.chain;return Je(t)&&t!==xh&&ONe({config:e})},"canUseEvmContractChainService"),RNe=XFe(async({account:e,config:t,traceProvider:n,meterProvider:r,logger:i})=>{if(lNe)return lNe;const a=$e(t.chain.id,()=>"Error: config.chain.id is required"),s=$e(Lh(a),()=>"Error: config.chain.id is not a valid address"),o=$e(await _Ne({config:t})),c=$e(e.private?.hex,()=>"Error: Account does not have a private key"),u=new kk(c,o);return lNe=V5.create({id:s,runner:u,traceProvider:n,meterProvider:r,logger:i}),await lNe},"initEvmContractChainService"),NNe=XFe(({account:e,config:t})=>MNe({config:t,name:"ChainService",account:e}),"initChainService"),MNe=XFe(e=>{if(dNe)return dNe;const{config:t}=e;return dNe=FNe(t)?RNe({...e,name:"ChainStakeService"}):Y5.create({...e,name:"ChainStakeService"})},"init"),QNe=XFe(async(e,t)=>{const n=t.chainId,r=[],i=await B$(e,n,10000000n,e.address);r.push(i);const a=S$(e.address,"producer",i[0].block,i[0].block+1e4),s=await w$(i[0],[],[a],[e]);return r.push(s),r},"createBootstrapHead"),PNe=XFe(()=>18000000000n*YP,"getForkBlockReward"),jNe=XFe(()=>Qh(PNe()),"getForkBlockRewardHex"),UNe=Qh("0x1"),LNe=Qh("0xf72aE3E0DA743033AbD7A407557D684c1aE66aed"),HNe=Qh("0x0e65b65B10C791942665030402c35023d88B14dA"),GNe=Qh("0x950861b10523b52cdbb4a9ee52ed26601db555d2652bfec21c709e5e70d5b7d3"),qNe=XFe(()=>UNe,"getBridgeDestChainId"),zNe=XFe(()=>LNe,"getBridgeDestToken"),$Ne=XFe(()=>HNe,"getBridgeDestAddress"),KNe=XFe(()=>jNe(),"getBridgeDestAmount"),VNe=XFe(()=>GNe,"getBridgeDestConfirmation"),YNe=XFe(()=>({dest:qNe(),destToken:zNe(),destAddress:$Ne(),destAmount:KNe()}),"getBridgeDestinationDetails"),JNe=XFe(e=>e.chainId,"getBridgeSrcChainId"),WNe=XFe(e=>e.address,"getBridgeSrcAddress"),ZNe=XFe(e=>e.chainId,"getBridgeSrcToken"),XNe=XFe(()=>jNe(),"getBridgeSrcAmount"),eMe=XFe((e,t)=>({src:JNe(t),srcAddress:WNe(e),srcToken:ZNe(t),srcAmount:XNe()}),"getBridgeSourceDetails"),tMe=XFe(async(e,t,n)=>{const r={...eMe(t,n),...YNe(),destConfirmation:VNe()},i=new EA({schema:tj}).fields(r).build();return await w$(e[0],[],[i],[t])},"getBridgeDestinationObservation"),nMe=XFe(async(e,t,n)=>{const r=m$(t.address,{[qj]:PNe()}),i=`${Date.now()}`,a={...eMe(t,n),...YNe(),nonce:i},s=new EA({schema:ij}).fields(a).build();return await w$(e[0],[],[s,r],[t])},"getBridgeIntent"),rMe=XFe(async(e,t,n)=>{const r=e[0]._hash,i={...eMe(t,n),...YNe(),srcConfirmation:r},a=new EA({schema:oj}).fields(i).build();return await w$(e[0],[],[a],[t])},"getBridgeSourceObservation"),iMe=XFe(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:ZP(0n)};return await E$(o)},"getFirstBlockForNewChain"),aMe=XFe(async(e,t,n)=>{const r=[],i=await iMe(e,t,n);r.push(i);const a=await nMe(i,t,n);r.push(a);const s=await rMe(a,t,n);r.push(s);const o=await tMe(s,t,n);return r.push(o),r},"createForkedHead"),sMe=XFe(async(e,t,n)=>{if(e.chain!==t.chainId){const e=await t.forkedAtHash(),r=$h(Rh(e));if(Je(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"),oMe=XFe(async(e,t,n)=>{for(const r of e){const[e]=r;for(await n.insert($G(r));;){if((await t.get([e._hash])).length>0)break;await NA(1e3)}}},"submitNewChain"),cMe=XFe(async e=>{const{account:t,chainArchivist:n,chainSubmissionsArchivistWrite:r,chainService:i}=e;if(pNe)return pNe;let a=await U$(n);if(a){const e=await sMe(a,i,n);if(Je(e)){const s=await aMe(e,t,i);await oMe(s,n,r);a=$e(s.at(-1),()=>new Error("Failed to get new head after forking"))[0]}}else{const e=await QNe(t,i);await oMe(e,n,r);a=$e(e.at(-1),()=>new Error("Failed to get new head after genesis"))[0]}return pNe=a},"initHead"),uMe=XFe(e=>hNe||(hNe=K5.create(e)),"initChainIterator"),lMe=XFe(e=>fNe||(fNe=l3.create(e)),"initStakeIntentService"),dMe=XFe(e=>ANe||(ANe=X5.create(e)),"initElectionService"),pMe=XFe(async e=>mNe||(mNe=await s3.create(e)),"initPendingTransactions"),hMe=XFe(async e=>gNe||(gNe=await U5.create(e)),"initBlockProducer"),fMe=XFe(e=>{if(yNe)return yNe;const{config:t}=e;return yNe=mMe({config:t})?gMe(e):AMe(e)},"initBlockRewardService"),AMe=XFe(e=>yNe||(yNe=$5.create(e)),"initXyoBlockRewardService"),mMe=XFe(e=>ONe({config:e.config}),"canUseEvmBlockRewardService"),gMe=XFe(async e=>{if(yNe)return yNe;const{account:t}=e,n=$e(t,()=>"Error: Account is required"),r=$e(await _Ne(e)),i={...e,provider:r,account:n};return yNe=q5.create(i)},"initEvmBlockRewardService"),yMe=XFe(async({chainArchivist:e,chainIterator:t,config:n,logger:r,meterProvider:i,traceProvider:a})=>{if(bNe)return bNe;const s=ONe({config:n})?await _Ne({config:n}):void 0;return bNe=f3.create({chainArchivist:e,chainIterator:t,ethProvider:s,logger:r,meterProvider:i,traceProvider:a}),await bNe},"initTimeService"),bMe=XFe(async e=>vNe||(vNe=await Q5.create(e)),"initTransferService"),vMe=class{static{XFe(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})}},EMe={error:0,stopped:1,stopping:2,creating:3,created:4,starting:5,started:6},IMe="starting",wMe=XFe(e=>{let t=IMe,n=1/0;for(const r of e){const e=EMe[r];e<n&&(n=e,t=r)}return t},"reduceToMinimumStatus"),CMe=class extends vMe{static{XFe(this,"RuntimeStatusMonitor")}globalTransitions=[];transitions=[];getGlobalStatus(){return 0===Object.keys(this.statusMap).length?IMe:wMe(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)}},BMe=XFe(e=>Je(e.start)&&"function"==typeof e.start,"isStartable"),xMe=XFe(async e=>{const{config:t,logger:n}=e,r=new CMe(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 S5("initHealthEndpoints",()=>pRe({...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([S5("initTelemetry",()=>B3(a)),S5("initAccount",()=>ENe(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([S5("ChainFinalizedArchivist",()=>vRe(d)),S5("PendingBundledTransactionsArchivist",()=>QRe(d)),S5("RejectedTransactionsArchivist",()=>LRe(d)),S5("ChainSubmissionsArchivist",()=>_Re(d)),S5("StakeIntentStateArchivist",()=>YRe(d)),S5("ChainService",()=>NNe({...d,account:c,name:"ChainService"})),S5("BalanceSummaryMap",()=>XRe(d)),S5("TransferSummaryMap",()=>sNe(d))]),E=y.chainId,I=pz(p),w=y,C=y,B=y,x=await S5("initHead",()=>cMe({...d,account:c,chainArchivist:p,chainSubmissionsArchivistWrite:m,chainService:y})),D=[x0([w0,C0(u),B0(l,"reward-escrow")])],[S,k,T]=await Promise.all([S5("PendingTransactions",()=>pMe({name:"PendingTransactionsService",chainArchivist:p,chainId:E,pendingBundledTransactionsArchivist:h,rejectedTransactionsArchivist:A,additionalPendingTransactionValidators:D,...d})),S5("RewardService",()=>fMe({name:"RewardService",account:c,chainService:y,...d})),S5("ChainIterator",()=>uMe({name:"ChainIterator",chainMap:I,head:x,...d}))]),[_]=await Promise.all([S5("BalanceService",()=>INe({name:"BalanceService",context:{stepSemaphores:Zj.map(()=>new CA(20)),store:{chainMap:I},head:XFe(async()=>{const e=await T.head();return[e._hash,e.block]},"head"),chainId:E,summaryMap:b},...d})),S5("TransferService",()=>bMe({name:"TransferService",context:{stepSemaphores:Zj.map(()=>new CA(20)),store:{chainMap:I},head:XFe(async()=>{const e=await T.head();return[e._hash,e.block]},"head"),chainId:E,summaryMap:v},...d}))]),[O,F]=await Promise.all([S5("StakeIntentService",()=>lMe({name:"StakeIntentService",chainArchivist:p,chainIterator:T,chainStakeViewer:C,stakeIntentStateArchivist:g,...d})),S5("TimeService",()=>yMe({name:"TimeService",chainArchivist:p,chainIterator:T,...d}))]),R=await S5("ElectionService",()=>dMe({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:X0,...d},M=Je(t.producer.rewardAddress)?$e(Lh(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 S5("Producer",()=>hMe(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(BMe);return $e((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 DMe(e){Mke(e)}function SMe(e){sTe(e)}function kMe(e){kTe(e)}XFe(DMe,"runApi"),XFe(SMe,"runBridge"),XFe(kMe,"runMempool");var TMe=XFe(async e=>{const{config:t,logger:n,orchestrator:r}=e;n?.log("Services: Initializing...");const i=await xMe(e);n?.log("Services: Initialized");const a={...i,config:t},s=[await rRe.create({...a,name:"ChainHeadUpdateActor"}),await nRe.create({...a,name:"BalanceActor"}),await aRe.create({...a,name:"ProducerActor"})];for(const e of s)await r.registerActor(e);await r.start()},"runProducer");function _Me(e){g_e(e)}XFe(_Me,"runRewardRedemptionApi");var OMe,FMe=XFe(e=>{let t;if(e.silent)t=new HA;else{let n;if(Je(e.logLevel)){const t=PA[e.logLevel.toLowerCase()];Je(t)&&(n=t)}t=new UA(n)}return SA.defaultLogger=t,t},"initLogger"),RMe=XFe(e=>e,"usageMetaToOptions"),NMe=XFe(()=>{const e={};for(const t of Object.values(fu._map))if(Wq(t)){if(t.hidden)continue;e[t.title]=RMe(t)}return e},"optionsFromGlobalZodRegistry"),MMe=XFe(()=>{const e=VFe.cosmiconfigSync("xyo").search();if(!We(e)){const t=e?.config?.xl1;if(Je(t)&&"object"==typeof t)return t}return{}},"tryParseConfig"),QMe=XFe((e,t)=>new Promise(n=>{const r=XFe(()=>{const i=new oe.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"),PMe=Je("1.16.3")?"1.16.3":"unknown",jMe=XFe(e=>{const t=FMe(e),n=new tRe(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 UMe(){const e=_9(function(e){return e.slice(b8()+1)}(process.argv)),t=e.usage(`\n🚀 XL1 Node CLI (${PMe})\n[38;2;128;128;128m [0m[38;2;118;111;144m_[0m\n[38;2;128;128;128m [0m[38;2;72;32;223m╠[0m[38;2;66;21;234m╠[0m\n[38;2;128;128;128m ╠╠[0m[38;2;103;85;170m_[0m\n[38;2;128;128;128m [0m[38;2;79;121;152m╦[0m[38;2;82;121;151m╦[0m[38;2;112;125;136m_ [0m[38;2;88;59;196m[[0m[38;2;66;21;234m╠[0m[38;2;66;21;234m╠[0m[38;2;73;34;221m▒ [0m[38;2;121;121;127m_[0m[38;2;100;101;128m╔[0m[38;2;93;94;127m╦[0m\n[38;2;128;128;128m [0m[38;2;82;121;151m²[0m[38;2;44;116;170m╠[0m[38;2;44;116;171m▒[0m[38;2;51;117;167mD[0m[38;2;80;121;152m╦[0m[38;2;111;125;136m_ [0m[38;2;67;23;232m╠[0m[38;2;66;21;234m╠╠╠ [0m[38;2;120;121;128m_[0m[38;2;100;101;127m╔[0m[38;2;79;81;127mR[0m[38;2;71;73;128m▒[0m[38;2;71;73;128m▒[0m[38;2;88;90;127m╙[0m\n[38;2;128;128;128m [0m[38;2;55;117;165m╚[0m[38;2;44;116;171m▒[0m[38;2;44;116;171m▒▒[0m[38;2;50;116;167mD[0m[38;2;80;121;152m╦ [0m[38;2;106;90;165mj[0m[38;2;66;21;234m╠[0m[38;2;66;21;234m╠╠╠[0m[38;2;89;61;194mH [0m[38;2;99;100;127m╔[0m[38;2;79;80;127mD[0m[38;2;71;73;128m▒[0m[38;2;71;73;128m▒▒╠[0m\n[38;2;128;128;128m [0m[38;2;83;121;150m²[0m[38;2;44;116;170m▒[0m[38;2;44;116;171m▒▒▒ [0m[38;2;76;38;217m╠[0m[38;2;66;21;234m╠[0m[38;2;66;21;234m╠╠╠╠ [0m[38;2;74;76;128m╠[0m[38;2;71;73;128m▒▒▒[0m[38;2;89;90;128m╙[0m\n[38;2;128;128;128m [0m[38;2;90;118;148m\`[0m[38;2;89;107;153m_[0m[38;2;93;97;154m,[0m[38;2;105;89;166m╓[0m[38;2;66;21;234m╠[0m[38;2;66;21;234m╠╠╠╠╠[0m[38;2;95;72;183m╓[0m[38;2;106;96;152m_[0m[38;2;100;94;143m\`[0m[38;2;101;100;133m\`[0m\n[38;2;128;128;128m [0m[38;2;122;118;137m_[0m[38;2;113;102;153m,[0m[38;2;108;94;161m╓[0m[38;2;104;86;169m╓[0m[38;2;98;77;178m╔[0m[38;2;93;67;188m╗[0m[38;2;88;59;196mφ[0m[38;2;83;51;204m@[0m[38;2;78;42;213mD[0m[38;2;72;32;223m▒[0m[38;2;68;24;231m╠[0m[38;2;66;21;234m╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠[0m[38;2;71;30;225m▒[0m[38;2;77;40;215m▒[0m[38;2;82;49;206mK[0m[38;2;87;57;198mφ[0m[38;2;91;65;190m╗[0m[38;2;97;75;180m╦[0m[38;2;103;84;171m╖[0m[38;2;107;92;163m²[0m[38;2;112;101;154m_[0m[38;2;119;112;143m_[0m\n[38;2;128;128;128m [0m[38;2;106;91;164m\`[0m[38;2;94;70;185m^[0m[38;2;89;62;193m╙[0m[38;2;85;54;201m╙[0m[38;2;80;45;210m╚[0m[38;2;74;35;220m╝[0m[38;2;69;26;229m╠[0m[38;2;66;22;233m╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠[0m[38;2;73;33;222m╝[0m[38;2;79;43;212m╩[0m[38;2;84;52;203m╜[0m[38;2;88;60;195m╙[0m[38;2;93;68;187m^[0m[38;2;100;80;175m\`[0m\n[38;2;128;128;128m [0m[38;2;113;84;152m\`[0m[38;2;103;79;169m'[0m[38;2;95;72;183m"[0m[38;2;87;57;198m╙[0m[38;2;66;21;234m╠[0m[38;2;66;21;234m╠╠╠╠╠[0m[38;2;80;46;209m╜[0m[38;2;94;70;185m^[0m[38;2;102;77;175m^[0m[38;2;112;81;162m\`[0m[38;2;115;92;155m\`[0m\n[38;2;128;128;128m [0m[38;2;145;116;107m,[0m[38;2;199;82;45m╠[0m[38;2;207;77;35m▒[0m[38;2;207;77;35m▒╠ [0m[38;2;70;28;227m╠[0m[38;2;66;21;234m╠[0m[38;2;66;21;234m╠╠╠╠ [0m[38;2;189;49;97må[0m[38;2;203;32;90m╠[0m[38;2;203;32;90m╠╠[0m[38;2;155;92;114m,[0m\n[38;2;128;128;128m [0m[38;2;175;98;73m╔[0m[38;2;207;77;35m▒[0m[38;2;207;77;35m▒▒▒[0m[38;2;197;83;47m╩ [0m[38;2;98;76;179m[[0m[38;2;66;21;234m╠[0m[38;2;66;21;234m╠╠╠[0m[38;2;81;48;207mH [0m[38;2;188;51;98m╚[0m[38;2;203;32;90m╠[0m[38;2;203;32;90m╠╠╠[0m[38;2;183;57;100mH[0m\n[38;2;128;128;128m [0m[38;2;146;116;106m,[0m[38;2;199;82;44m╠[0m[38;2;207;77;35m▒[0m[38;2;207;77;35m▒[0m[38;2;196;84;48m╩[0m[38;2;168;102;81m^ [0m[38;2;66;21;234m╠[0m[38;2;66;21;234m╠╠╠ [0m[38;2;160;87;111m'[0m[38;2;187;52;98m╚[0m[38;2;203;32;90m╠[0m[38;2;203;32;90m╠╠[0m[38;2;156;91;113m,[0m\n[38;2;128;128;128m [0m[38;2;198;83;46m╩[0m[38;2;194;85;50m╩[0m[38;2;167;102;82m^ [0m[38;2;81;46;209m╚[0m[38;2;66;21;234m╠[0m[38;2;66;21;234m╠╠ [0m[38;2;159;88;112m'[0m[38;2;186;53;98m╚[0m[38;2;197;40;93m╩[0m\n[38;2;128;128;128m [0m[38;2;110;97;158m'[0m[38;2;66;21;234m╠[0m[38;2;66;21;234m╠[0m[38;2;94;69;186mH[0m\n[38;2;128;128;128m [0m[38;2;68;25;230m╠[0m[38;2;66;21;234m╠[0m\n[38;2;128;128;128m [0m[38;2;108;93;162m²[0m[38;2;99;79;176m^[0m\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=MMe(),n=Bt(e,t);OMe=zq.parse(n)}catch(e){throw e instanceof ld&&console.error(`${e.message}`),new Error("Invalid configuration")}}).options(NMe()).wrap(e.terminalWidth()).command("api","Run a XL1 API Node",e=>e.command("$0","Run a XL1 API Node",()=>{},()=>{DMe({...jMe(OMe),config:OMe})})).command("bridge","Run a XL1 Bridge Node",e=>e.command("$0","Run a XL1 Bridge Node",()=>{},()=>{SMe({...jMe(OMe),config:OMe})})).command("mempool","Run a XL1 Mempool Node",e=>e.command("$0","Run a XL1 Mempool Node",()=>{},()=>{kMe({...jMe(OMe),config:OMe})})).command("producer","Run a XL1 Producer Node",e=>e.command("$0","Run a XL1 Producer Node",()=>{},async()=>{const e=jMe(OMe);await TMe({...e,config:OMe})})).command("reward-redemption-api","Run a XL1 Rewards Redemption API Node",e=>e.command("$0","Run a XL1 Rewards Redemption API Node",()=>{},()=>{_Me({...jMe(OMe),config:OMe})})).command("$0","Run a full XL1 Node",()=>{},async()=>{const e=jMe(OMe);OMe.mempool.enabled&&(kMe({...e,config:OMe}),await QMe(OMe.mempool.host,OMe.mempool.port)),DMe({...e,config:OMe}),await QMe(OMe.api.host,OMe.api.port),await TMe({...e,config:OMe})}).help().alias("help","h").version(PMe).argv;await t}XFe(UMe,"runCLI"),XFe(async()=>{WFe.config({quiet:!0}),await UMe()},"start")().catch(e=>{"development"===process.env.NODE_ENV&&console.error("An error occurred during startup:",e),process.exit(1)});
|
|
352
|
+
/* 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 $Fe.ExplorerSync=c,$Fe}(),a=PFe(),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)}}}(y_e)),y_e),YFe={exports:{}},JFe={version:"17.2.3"};var WFe=function(){if(KFe)return YFe.exports;KFe=1;const e=P,t=i,r=n,a=b,s=JFe.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?`[2m${e}[0m`: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 YFe.exports.configDotenv=g.configDotenv,YFe.exports._configVault=g._configVault,YFe.exports._parseVault=g._parseVault,YFe.exports.config=g.config,YFe.exports.decrypt=g.decrypt,YFe.exports.parse=g.parse,YFe.exports.populate=g.populate,YFe.exports=g,YFe.exports}(),ZFe=Object.defineProperty,XFe=(e,t)=>ZFe(e,"name",{value:t,configurable:!0}),eRe=class extends SA{static{XFe(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 LA(SA.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.params.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 CA(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 qA(`${this.name}:${e}`,t,this.tracer)}async spanAsync(e,t){return await $A(`${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 NA(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.")}},tRe=class{static{XFe(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.")}},nRe=class e extends eRe{static{XFe(this,"BalanceActor")}_updateMutex=new DA;constructor(e){super("BalanceActor","Balance",e)}get balanceService(){return $e(this.params.balance,()=>"balanceService not set")}get chainIterator(){return $e(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 EA.hash(await this.chainIterator.head());await this.balanceService.balances(e,[])})}},rRe=class e extends eRe{static{XFe(this,"ChainHeadUpdateActor")}constructor(e){super("ChainHeadUpdate","ChainHeadUpdate",e)}get chainFinalizedArchivist(){return $e(this.params.chainArchivist,()=>"ChainArchivist not set")}get chainIterator(){return $e(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$(VA(e.payloads,jj)).at(-1);await this.updateHeadIfNewer(t)}async pollForNewHead(){const e=await U$(this.chainFinalizedArchivist);await this.updateHeadIfNewer(e)}async updateHeadIfNewer(e){if(!e)return;const t=await this.chainIterator.head(),n=e.block,r=`0x${Qh(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))}},iRe=6e5,aRe=class e extends eRe{static{XFe(this,"ProducerActor")}_lastProducedBlock;_lastRedeclarationIntent;constructor(e){super(e.producer.address,"Producer",e)}get account(){return $e(this.params.account,()=>"account not set")}get balanceService(){return $e(this.params.balance,()=>"balanceService not set")}get chainIterator(){return $e(this.params.chainIterator,()=>"chainIterator not set")}get chainStakeViewer(){return $e(this.params.chainStakeViewer,()=>"chainStakeViewer not set")}get chainSubmissionsArchivistWrite(){return $e(this.params.chainSubmissionsArchivistWrite,()=>"chainSubmissionsArchivistWrite not set")}get pendingBundledTransactionsArchivistWrite(){return $e(this.params.pendingBundledTransactionsArchivistWrite,()=>"pendingBundledTransactionsArchivistWrite not set")}get producer(){return $e(this.params.producer,()=>"producer not set")}get stakeIntentService(){return $e(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()},iRe,iRe)}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${Qh(t._hash)}`);const r=t._hash;if(this._lastProducedBlock&&this._lastProducedBlock[0].previous===r)this.logger?.log("Block already produced:",`0x${Qh(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${Qh(n[0].block)}`;this.logger?.log("Produced block:",e),await this.chainSubmissionsArchivistWrite.insert($G(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(Ye(e))return;const t=e.block;if(await this.calculateBlocksUntilProducerDeclarationExpiration(t)>.1*U5.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=S$(this.account.address,"producer",t,t+U5.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 Sz(this.chainIterator.chainId,[t],[],this.account,e,e+1e3),r=_z(n),i=n[0]._hash,a=new EA({schema:zf}).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(Je(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 eRe{static{XFe(this,"ValidatorActor")}_lastValidatedBlock;_lastValidatedBlockHash;constructor(e){super("Validator","Validator",e)}get account(){return $e(this.params.account,()=>"account not set")}get balanceService(){return $e(this.params.balance,()=>"balanceService not set")}get chainIterator(){return $e(this.params.chainIterator,()=>"chainIterator not set")}get chainStakeViewer(){return $e(this.params.chainStakeViewer,()=>"chainStakeViewer not set")}get chainSubmissionsArchivistWrite(){return $e(this.params.chainSubmissionsArchivistWrite,()=>"chainSubmissionsArchivistWrite not set")}get pendingBundledTransactionsArchivistWrite(){return $e(this.params.pendingBundledTransactionsArchivistWrite,()=>"pendingBundledTransactionsArchivistWrite not set")}get stakeIntentService(){return $e(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(Ye(e))return;const t=await EA.hash(e);if(Je(this._lastValidatedBlock)&&this._lastValidatedBlockHash===t)this.logger?.log("Block already validated:",`0x${Qh(e.block)}`);else{this.logger?.log("Validating block:",`0x${Qh(e.block)}`);await this.validateBlock(e)?this.logger?.log("Validated block:",`0x${Qh(e.block)}`):(this.logger?.log("Invalid block:",`0x${Qh(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 EA.hash(e),t}});var sRe,oRe,cRe,uRe=XFe((e,t,n)=>{const r="started"===t?200:n;e.writeHead(r,{"Content-Type":"application/json"}),e.end(JSON.stringify({status:t}))},"sendStatus"),lRe=XFe(e=>{e.writeHead(404,{"Content-Type":"application/json"}),e.end(JSON.stringify({status:"not found"}))},"notFound"),dRe=XFe((e,t,n)=>{const r=R.createServer((e,n)=>{const r=e.url??"",i=t.getGlobalStatus();switch(r){case"/healthz":uRe(n,i,500);break;case"/livez":case"/readyz":uRe(n,i,503);break;default:lRe(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"),pRe=XFe(e=>{const{config:t,logger:n,statusReporter:r}=e,{healthCheckPort:i}=t.producer;return Je(i)?dRe(i,r,n):void 0},"initHealthEndpoints"),hRe=i.join(process.cwd(),".store"),fRe=XFe((e,t,n,r,i="lmdb")=>{if("lmdb"===i){const i=r??hRe;return F3.create({account:"random",config:{name:e,clearStoreOnStart:!1,dbName:t,location:R$(t,i,"lmdb"),schema:O3,storeName:n}})}},"getLocalPersistentArchivist"),ARe=new DA,mRe=XFe(async({config:e})=>await ARe.runExclusive(async()=>{if(sRe)return sRe;const{root:t}=e.storage;return sRe=await fRe("local-finalized-chain","chain","finalized",t)}),"initLocalChainFinalizedArchivist"),gRe=new DA,yRe=XFe(async({config:e})=>await gRe.runExclusive(async()=>{if(oRe)return oRe;const{host:t,port:n}=e.mempool.enabled?e.mempool:e.api,r=Cq(t,n),i=await m6(r);return $e(oRe=await v6({bridge:i,moduleName:"XYOChain:Chain:Finalized"}),()=>"Error: RemoteChainFinalizedArchivist failed to initialize")}),"initRemoteChainFinalizedArchivist"),bRe=new DA;async function vRe({config:e,logger:t,traceProvider:n}){return await bRe.runExclusive(async()=>{if(cRe)return cRe;const[r,i]=await Promise.all([S5("ChainFinalizedArchivist:initRemote",()=>yRe({config:e,logger:t})),S5("ChainFinalizedArchivist:initLocal",()=>mRe({config:e,logger:t}))]);return await S5("ChainFinalizedArchivist:initArchivistSync",()=>h6("ChainFinalizedArchivist",r,i,200,Number.MAX_SAFE_INTEGER,n)),cRe=i})}XFe(vRe,"initChainFinalizedArchivist");var ERe,IRe,wRe,CRe,BRe,xRe,DRe,SRe=new DA,kRe=XFe(async({config:e})=>await SRe.runExclusive(async()=>{if(ERe)return ERe;const{host:t,port:n}=e.mempool.enabled?e.mempool:e.api,r=Cq(t,n),i=await m6(r);return $e(ERe=await v6({bridge:i,moduleName:"XYOChain:Chain:Submissions"}),()=>new Error("Failed to initialize RemoteChainSubmissionsArchivist"))}),"initRemoteChainSubmissionsArchivist"),TRe=new DA,_Re=XFe(async e=>await TRe.runExclusive(async()=>{if(IRe)return IRe;const t=await S5("ChainSubmissionsArchivist:initRemote",()=>kRe(e));return $e(IRe=t,()=>new Error("Failed to initialize ChainSubmissionsArchivist"))}),"initChainSubmissionsArchivist"),ORe=new DA,FRe=XFe(async()=>await ORe.runExclusive(async()=>wRe||(wRe=await sG.create({account:"random",config:{schema:iG,max:1e3,name:"localPendingTransactions"}}))),"initLocalPendingTransactionsArchivist"),RRe=new DA,NRe=XFe(async({config:e})=>await RRe.runExclusive(async()=>{if(CRe)return CRe;const{host:t,port:n}=e.mempool.enabled?e.mempool:e.api,r=Cq(t,n),i=await m6(r);return $e(CRe=await v6({bridge:i,moduleName:"XYOChain:Pending:PendingTransactions"}),()=>"Error: RemotePendingBundledTransactionsArchivist is undefined")}),"initRemotePendingTransactionsArchivist"),MRe=new DA,QRe=XFe(async e=>await MRe.runExclusive(async()=>{if(BRe)return BRe;const t=await S5("PendingBundledTransactionsArchivist:initRemote",()=>NRe(e)),n=await S5("PendingBundledTransactionsArchivist:initLocal",()=>FRe(e)),r=await t.next({limit:1,order:"desc"});return await n.insert(r),await S5("PendingBundledTransactionsArchivist:initArchivistSync",()=>h6("PendingBundledTransactionsArchivist",t,n)),BRe=[n,t]}),"initPendingBundledTransactionsArchivist"),PRe=new DA,jRe=XFe(async()=>await PRe.runExclusive(async()=>xRe||(xRe=await sG.create({account:"random",config:{schema:iG,max:1e3,name:"localRejectedTransactions"}}))),"initLocalRejectedTransactionsArchivist"),URe=new DA;async function LRe(e){return await URe.runExclusive(async()=>{if(DRe)return DRe;const t=await S5("RejectedTransactionsArchivist:initLocal",()=>jRe(e));return DRe=t})}XFe(LRe,"initRejectedTransactionsArchivist");var HRe,GRe,qRe,zRe,$Re=new DA,KRe=XFe(async({config:e})=>await $Re.runExclusive(async()=>{if(HRe)return HRe;const{root:t}=e.storage;return $e(HRe=await fRe("local-stake-intent-state","stakeIntent","state",t),()=>new Error("Failed to initialize stake intent state archivist"))}),"initLocalStakeIntentStateArchivist"),VRe=new DA,YRe=XFe(async e=>await VRe.runExclusive(async()=>{if(GRe)return GRe;const t=await S5("StakeIntentStateArchivist:initLocal",()=>KRe(e));return $e(GRe=t,()=>"Error: StakeIntentStateArchivist is undefined")}),"initStakeIntentStateArchivist"),JRe=new DA,WRe=XFe(async e=>await JRe.runExclusive(async()=>{if(Je(qRe))return qRe;const{root:t}=e.config.storage;return qRe=await M$("balance","summary",t)}),"initLocalBalanceSummaryMap"),ZRe=new DA;async function XRe(e){return await ZRe.runExclusive(async()=>{if(Je(zRe))return zRe;const t=await S5("BalanceSummaryMap:initLocal",()=>WRe(e));return zRe=t})}XFe(XRe,"initBalanceSummaryMap");var eNe,tNe,nNe,rNe=new DA,iNe=XFe(async e=>await rNe.runExclusive(async()=>{if(Je(eNe))return eNe;const{root:t}=e.config.storage;return eNe=await M$("transfer","summary",t)}),"initLocalTransferSummaryMap"),aNe=new DA;async function sNe(e){return await aNe.runExclusive(async()=>{if(Je(tNe))return tNe;const t=await S5("TransferSummaryMap:initLocal",()=>iNe(e));return tNe=t})}XFe(sNe,"initTransferSummaryMap");var oNe,cNe,uNe,lNe,dNe,pNe,hNe,fNe,ANe,mNe,gNe,yNe,bNe,vNe,ENe=XFe(async({config:e,logger:t})=>{if(nNe)return nNe;let n=e.producer.mnemonic;if(Ye(n)){t?.warn("[Producer] No wallet mnemonic specified!");const e=HG.generateMnemonic();t?.warn(`[Producer] Using randomly generated mnemonic:\n \n${e}\n \n `),n=e}const r=await Jz(n),i=await r.derivePath(Yz);return nNe=i},"initAccount"),INe=XFe(async e=>oNe||(oNe=await N5.create(e)),"initBalanceService"),wNe=XFe(e=>Je(e.evm.chainId),"canUseChainId"),CNe=XFe(e=>{const t=$e(e.evm.chainId,()=>"Missing config.evm.chainId");if(_h(t,{prefix:!0})){const e=Nh(t);return Number.parseInt(e,16)}return Number.parseInt(t,10)},"getChainId"),BNe=XFe(e=>{if(cNe)return cNe;const t=DNe(e);return cNe=Promise.resolve(new _D(...t))},"initInfuraProvider"),xNe=XFe(e=>wNe(e)&&Je(e.evm?.infura?.projectId)&&Je(e.evm?.infura?.projectSecret),"canUseInfuraProvider"),DNe=XFe(e=>{const t=$e(e.evm?.infura?.projectId,()=>"Missing config.evm.infura.projectId"),n=$e(e.evm?.infura?.projectSecret,()=>"Missing config.evm.infura.projectSecret");return[CNe(e),t,n]},"getInfuraProviderConfig"),SNe=XFe(e=>{const t=TNe(e);return Promise.resolve(new Ix(...t))},"initJsonRpcProvider"),kNe=XFe(e=>wNe(e)&&Je(e.evm.jsonRpc?.url),"canUseJsonRpcProvider"),TNe=XFe(e=>[$e(e.evm.jsonRpc?.url,()=>"Missing config.evm.jsonRpc.url"),CNe(e)],"getJsonRpcProviderConfig"),_Ne=XFe(async({config:e})=>uNe||(xNe(e)?uNe=BNe(e):kNe(e)&&(uNe=SNe(e)),$e(await uNe,()=>"Error: No provider available")),"initEvmProvider"),ONe=XFe(({config:e})=>xNe(e)||kNe(e),"canUseEvmProvider"),FNe=XFe(e=>{const{id:t}=e.chain;return Je(t)&&t!==xh&&ONe({config:e})},"canUseEvmContractChainService"),RNe=XFe(async({account:e,config:t,traceProvider:n,meterProvider:r,logger:i})=>{if(lNe)return lNe;const a=$e(t.chain.id,()=>"Error: config.chain.id is required"),s=$e(Lh(a),()=>"Error: config.chain.id is not a valid address"),o=$e(await _Ne({config:t})),c=$e(e.private?.hex,()=>"Error: Account does not have a private key"),u=new kk(c,o);return lNe=V5.create({id:s,runner:u,traceProvider:n,meterProvider:r,logger:i}),await lNe},"initEvmContractChainService"),NNe=XFe(({account:e,config:t})=>MNe({config:t,name:"ChainService",account:e}),"initChainService"),MNe=XFe(e=>{if(dNe)return dNe;const{config:t}=e;return dNe=FNe(t)?RNe({...e,name:"ChainStakeService"}):Y5.create({...e,name:"ChainStakeService"})},"init"),QNe=XFe(async(e,t)=>{const n=t.chainId,r=[],i=await B$(e,n,10000000n,e.address);r.push(i);const a=S$(e.address,"producer",i[0].block,i[0].block+1e4),s=await w$(i[0],[],[a],[e]);return r.push(s),r},"createBootstrapHead"),PNe=XFe(()=>18000000000n*YP,"getForkBlockReward"),jNe=XFe(()=>Qh(PNe()),"getForkBlockRewardHex"),UNe=Qh("0x1"),LNe=Qh("0xf72aE3E0DA743033AbD7A407557D684c1aE66aed"),HNe=Qh("0x0e65b65B10C791942665030402c35023d88B14dA"),GNe=Qh("0x950861b10523b52cdbb4a9ee52ed26601db555d2652bfec21c709e5e70d5b7d3"),qNe=XFe(()=>UNe,"getBridgeDestChainId"),zNe=XFe(()=>LNe,"getBridgeDestToken"),$Ne=XFe(()=>HNe,"getBridgeDestAddress"),KNe=XFe(()=>jNe(),"getBridgeDestAmount"),VNe=XFe(()=>GNe,"getBridgeDestConfirmation"),YNe=XFe(()=>({dest:qNe(),destToken:zNe(),destAddress:$Ne(),destAmount:KNe()}),"getBridgeDestinationDetails"),JNe=XFe(e=>e.chainId,"getBridgeSrcChainId"),WNe=XFe(e=>e.address,"getBridgeSrcAddress"),ZNe=XFe(e=>e.chainId,"getBridgeSrcToken"),XNe=XFe(()=>jNe(),"getBridgeSrcAmount"),eMe=XFe((e,t)=>({src:JNe(t),srcAddress:WNe(e),srcToken:ZNe(t),srcAmount:XNe()}),"getBridgeSourceDetails"),tMe=XFe(async(e,t,n)=>{const r={...eMe(t,n),...YNe(),destConfirmation:VNe()},i=new EA({schema:tj}).fields(r).build();return await w$(e[0],[],[i],[t])},"getBridgeDestinationObservation"),nMe=XFe(async(e,t,n)=>{const r=m$(t.address,{[qj]:PNe()}),i=`${Date.now()}`,a={...eMe(t,n),...YNe(),nonce:i},s=new EA({schema:ij}).fields(a).build();return await w$(e[0],[],[s,r],[t])},"getBridgeIntent"),rMe=XFe(async(e,t,n)=>{const r=e[0]._hash,i={...eMe(t,n),...YNe(),srcConfirmation:r},a=new EA({schema:oj}).fields(i).build();return await w$(e[0],[],[a],[t])},"getBridgeSourceObservation"),iMe=XFe(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:ZP(0n)};return await E$(o)},"getFirstBlockForNewChain"),aMe=XFe(async(e,t,n)=>{const r=[],i=await iMe(e,t,n);r.push(i);const a=await nMe(i,t,n);r.push(a);const s=await rMe(a,t,n);r.push(s);const o=await tMe(s,t,n);return r.push(o),r},"createForkedHead"),sMe=XFe(async(e,t,n)=>{if(e.chain!==t.chainId){const e=await t.forkedAtHash(),r=$h(Rh(e));if(Je(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"),oMe=XFe(async(e,t,n)=>{for(const r of e){const[e]=r;for(await n.insert($G(r));;){if((await t.get([e._hash])).length>0)break;await NA(1e3)}}},"submitNewChain"),cMe=XFe(async e=>{const{account:t,chainArchivist:n,chainSubmissionsArchivistWrite:r,chainService:i}=e;if(pNe)return pNe;let a=await U$(n);if(a){const e=await sMe(a,i,n);if(Je(e)){const s=await aMe(e,t,i);await oMe(s,n,r);a=$e(s.at(-1),()=>new Error("Failed to get new head after forking"))[0]}}else{const e=await QNe(t,i);await oMe(e,n,r);a=$e(e.at(-1),()=>new Error("Failed to get new head after genesis"))[0]}return pNe=a},"initHead"),uMe=XFe(e=>hNe||(hNe=K5.create(e)),"initChainIterator"),lMe=XFe(e=>fNe||(fNe=l3.create(e)),"initStakeIntentService"),dMe=XFe(e=>ANe||(ANe=X5.create(e)),"initElectionService"),pMe=XFe(async e=>mNe||(mNe=await s3.create(e)),"initPendingTransactions"),hMe=XFe(async e=>gNe||(gNe=await U5.create(e)),"initBlockProducer"),fMe=XFe(e=>{if(yNe)return yNe;const{config:t}=e;return yNe=mMe({config:t})?gMe(e):AMe(e)},"initBlockRewardService"),AMe=XFe(e=>yNe||(yNe=$5.create(e)),"initXyoBlockRewardService"),mMe=XFe(e=>ONe({config:e.config}),"canUseEvmBlockRewardService"),gMe=XFe(async e=>{if(yNe)return yNe;const{account:t}=e,n=$e(t,()=>"Error: Account is required"),r=$e(await _Ne(e)),i={...e,provider:r,account:n};return yNe=q5.create(i)},"initEvmBlockRewardService"),yMe=XFe(async({chainArchivist:e,chainIterator:t,config:n,logger:r,meterProvider:i,traceProvider:a})=>{if(bNe)return bNe;const s=ONe({config:n})?await _Ne({config:n}):void 0;return bNe=f3.create({chainArchivist:e,chainIterator:t,ethProvider:s,logger:r,meterProvider:i,traceProvider:a}),await bNe},"initTimeService"),bMe=XFe(async e=>vNe||(vNe=await Q5.create(e)),"initTransferService"),vMe=class{static{XFe(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})}},EMe={error:0,stopped:1,stopping:2,creating:3,created:4,starting:5,started:6},IMe="starting",wMe=XFe(e=>{let t=IMe,n=1/0;for(const r of e){const e=EMe[r];e<n&&(n=e,t=r)}return t},"reduceToMinimumStatus"),CMe=class extends vMe{static{XFe(this,"RuntimeStatusMonitor")}globalTransitions=[];transitions=[];getGlobalStatus(){return 0===Object.keys(this.statusMap).length?IMe:wMe(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)}},BMe=XFe(e=>Je(e.start)&&"function"==typeof e.start,"isStartable"),xMe=XFe(async e=>{const{config:t,logger:n}=e,r=new CMe(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 S5("initHealthEndpoints",()=>pRe({...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([S5("initTelemetry",()=>B3(a)),S5("initAccount",()=>ENe(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([S5("ChainFinalizedArchivist",()=>vRe(d)),S5("PendingBundledTransactionsArchivist",()=>QRe(d)),S5("RejectedTransactionsArchivist",()=>LRe(d)),S5("ChainSubmissionsArchivist",()=>_Re(d)),S5("StakeIntentStateArchivist",()=>YRe(d)),S5("ChainService",()=>NNe({...d,account:c,name:"ChainService"})),S5("BalanceSummaryMap",()=>XRe(d)),S5("TransferSummaryMap",()=>sNe(d))]),E=y.chainId,I=pz(p),w=y,C=y,B=y,x=await S5("initHead",()=>cMe({...d,account:c,chainArchivist:p,chainSubmissionsArchivistWrite:m,chainService:y})),D=[x0([w0,C0(u),B0(l,"reward-escrow")])],[S,k,T]=await Promise.all([S5("PendingTransactions",()=>pMe({name:"PendingTransactionsService",chainArchivist:p,chainId:E,pendingBundledTransactionsArchivist:h,rejectedTransactionsArchivist:A,additionalPendingTransactionValidators:D,...d})),S5("RewardService",()=>fMe({name:"RewardService",account:c,chainService:y,...d})),S5("ChainIterator",()=>uMe({name:"ChainIterator",chainMap:I,head:x,...d}))]),[_]=await Promise.all([S5("BalanceService",()=>INe({name:"BalanceService",context:{stepSemaphores:Zj.map(()=>new CA(20)),store:{chainMap:I},head:XFe(async()=>{const e=await T.head();return[e._hash,e.block]},"head"),chainId:E,summaryMap:b},...d})),S5("TransferService",()=>bMe({name:"TransferService",context:{stepSemaphores:Zj.map(()=>new CA(20)),store:{chainMap:I},head:XFe(async()=>{const e=await T.head();return[e._hash,e.block]},"head"),chainId:E,summaryMap:v},...d}))]),[O,F]=await Promise.all([S5("StakeIntentService",()=>lMe({name:"StakeIntentService",chainArchivist:p,chainIterator:T,chainStakeViewer:C,stakeIntentStateArchivist:g,...d})),S5("TimeService",()=>yMe({name:"TimeService",chainArchivist:p,chainIterator:T,...d}))]),R=await S5("ElectionService",()=>dMe({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:X0,...d},M=Je(t.producer.rewardAddress)?$e(Lh(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 S5("Producer",()=>hMe(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(BMe);return $e((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 DMe(e){Mke(e)}function SMe(e){sTe(e)}function kMe(e){kTe(e)}XFe(DMe,"runApi"),XFe(SMe,"runBridge"),XFe(kMe,"runMempool");var TMe=XFe(async e=>{const{config:t,logger:n,orchestrator:r}=e;n?.log("Services: Initializing...");const i=await xMe(e);n?.log("Services: Initialized");const a={...i,config:t},s=[await rRe.create({...a,name:"ChainHeadUpdateActor"}),await nRe.create({...a,name:"BalanceActor"}),await aRe.create({...a,name:"ProducerActor"})];for(const e of s)await r.registerActor(e);await r.start()},"runProducer");function _Me(e){g_e(e)}XFe(_Me,"runRewardRedemptionApi");var OMe,FMe=XFe(e=>{let t;if(e.silent)t=new HA;else{let n;if(Je(e.logLevel)){const t=PA[e.logLevel.toLowerCase()];Je(t)&&(n=t)}t=new UA(n)}return SA.defaultLogger=t,t},"initLogger"),RMe=XFe(e=>e,"usageMetaToOptions"),NMe=XFe(()=>{const e={};for(const t of Object.values(fu._map))if(Wq(t)){if(t.hidden)continue;e[t.title]=RMe(t)}return e},"optionsFromGlobalZodRegistry"),MMe=XFe(()=>{const e=VFe.cosmiconfigSync("xyo").search();if(!We(e)){const t=e?.config?.xl1;if(Je(t)&&"object"==typeof t)return t}return{}},"tryParseConfig"),QMe=XFe((e,t)=>new Promise(n=>{const r=XFe(()=>{const i=new oe.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"),PMe=Je("1.16.4")?"1.16.4":"unknown",jMe=XFe(e=>{const t=FMe(e),n=new tRe(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 UMe(){const e=_9(function(e){return e.slice(b8()+1)}(process.argv)),t=e.usage(`\n🚀 XL1 Node CLI (${PMe})\n[38;2;128;128;128m [0m[38;2;118;111;144m_[0m\n[38;2;128;128;128m [0m[38;2;72;32;223m╠[0m[38;2;66;21;234m╠[0m\n[38;2;128;128;128m ╠╠[0m[38;2;103;85;170m_[0m\n[38;2;128;128;128m [0m[38;2;79;121;152m╦[0m[38;2;82;121;151m╦[0m[38;2;112;125;136m_ [0m[38;2;88;59;196m[[0m[38;2;66;21;234m╠[0m[38;2;66;21;234m╠[0m[38;2;73;34;221m▒ [0m[38;2;121;121;127m_[0m[38;2;100;101;128m╔[0m[38;2;93;94;127m╦[0m\n[38;2;128;128;128m [0m[38;2;82;121;151m²[0m[38;2;44;116;170m╠[0m[38;2;44;116;171m▒[0m[38;2;51;117;167mD[0m[38;2;80;121;152m╦[0m[38;2;111;125;136m_ [0m[38;2;67;23;232m╠[0m[38;2;66;21;234m╠╠╠ [0m[38;2;120;121;128m_[0m[38;2;100;101;127m╔[0m[38;2;79;81;127mR[0m[38;2;71;73;128m▒[0m[38;2;71;73;128m▒[0m[38;2;88;90;127m╙[0m\n[38;2;128;128;128m [0m[38;2;55;117;165m╚[0m[38;2;44;116;171m▒[0m[38;2;44;116;171m▒▒[0m[38;2;50;116;167mD[0m[38;2;80;121;152m╦ [0m[38;2;106;90;165mj[0m[38;2;66;21;234m╠[0m[38;2;66;21;234m╠╠╠[0m[38;2;89;61;194mH [0m[38;2;99;100;127m╔[0m[38;2;79;80;127mD[0m[38;2;71;73;128m▒[0m[38;2;71;73;128m▒▒╠[0m\n[38;2;128;128;128m [0m[38;2;83;121;150m²[0m[38;2;44;116;170m▒[0m[38;2;44;116;171m▒▒▒ [0m[38;2;76;38;217m╠[0m[38;2;66;21;234m╠[0m[38;2;66;21;234m╠╠╠╠ [0m[38;2;74;76;128m╠[0m[38;2;71;73;128m▒▒▒[0m[38;2;89;90;128m╙[0m\n[38;2;128;128;128m [0m[38;2;90;118;148m\`[0m[38;2;89;107;153m_[0m[38;2;93;97;154m,[0m[38;2;105;89;166m╓[0m[38;2;66;21;234m╠[0m[38;2;66;21;234m╠╠╠╠╠[0m[38;2;95;72;183m╓[0m[38;2;106;96;152m_[0m[38;2;100;94;143m\`[0m[38;2;101;100;133m\`[0m\n[38;2;128;128;128m [0m[38;2;122;118;137m_[0m[38;2;113;102;153m,[0m[38;2;108;94;161m╓[0m[38;2;104;86;169m╓[0m[38;2;98;77;178m╔[0m[38;2;93;67;188m╗[0m[38;2;88;59;196mφ[0m[38;2;83;51;204m@[0m[38;2;78;42;213mD[0m[38;2;72;32;223m▒[0m[38;2;68;24;231m╠[0m[38;2;66;21;234m╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠[0m[38;2;71;30;225m▒[0m[38;2;77;40;215m▒[0m[38;2;82;49;206mK[0m[38;2;87;57;198mφ[0m[38;2;91;65;190m╗[0m[38;2;97;75;180m╦[0m[38;2;103;84;171m╖[0m[38;2;107;92;163m²[0m[38;2;112;101;154m_[0m[38;2;119;112;143m_[0m\n[38;2;128;128;128m [0m[38;2;106;91;164m\`[0m[38;2;94;70;185m^[0m[38;2;89;62;193m╙[0m[38;2;85;54;201m╙[0m[38;2;80;45;210m╚[0m[38;2;74;35;220m╝[0m[38;2;69;26;229m╠[0m[38;2;66;22;233m╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠[0m[38;2;73;33;222m╝[0m[38;2;79;43;212m╩[0m[38;2;84;52;203m╜[0m[38;2;88;60;195m╙[0m[38;2;93;68;187m^[0m[38;2;100;80;175m\`[0m\n[38;2;128;128;128m [0m[38;2;113;84;152m\`[0m[38;2;103;79;169m'[0m[38;2;95;72;183m"[0m[38;2;87;57;198m╙[0m[38;2;66;21;234m╠[0m[38;2;66;21;234m╠╠╠╠╠[0m[38;2;80;46;209m╜[0m[38;2;94;70;185m^[0m[38;2;102;77;175m^[0m[38;2;112;81;162m\`[0m[38;2;115;92;155m\`[0m\n[38;2;128;128;128m [0m[38;2;145;116;107m,[0m[38;2;199;82;45m╠[0m[38;2;207;77;35m▒[0m[38;2;207;77;35m▒╠ [0m[38;2;70;28;227m╠[0m[38;2;66;21;234m╠[0m[38;2;66;21;234m╠╠╠╠ [0m[38;2;189;49;97må[0m[38;2;203;32;90m╠[0m[38;2;203;32;90m╠╠[0m[38;2;155;92;114m,[0m\n[38;2;128;128;128m [0m[38;2;175;98;73m╔[0m[38;2;207;77;35m▒[0m[38;2;207;77;35m▒▒▒[0m[38;2;197;83;47m╩ [0m[38;2;98;76;179m[[0m[38;2;66;21;234m╠[0m[38;2;66;21;234m╠╠╠[0m[38;2;81;48;207mH [0m[38;2;188;51;98m╚[0m[38;2;203;32;90m╠[0m[38;2;203;32;90m╠╠╠[0m[38;2;183;57;100mH[0m\n[38;2;128;128;128m [0m[38;2;146;116;106m,[0m[38;2;199;82;44m╠[0m[38;2;207;77;35m▒[0m[38;2;207;77;35m▒[0m[38;2;196;84;48m╩[0m[38;2;168;102;81m^ [0m[38;2;66;21;234m╠[0m[38;2;66;21;234m╠╠╠ [0m[38;2;160;87;111m'[0m[38;2;187;52;98m╚[0m[38;2;203;32;90m╠[0m[38;2;203;32;90m╠╠[0m[38;2;156;91;113m,[0m\n[38;2;128;128;128m [0m[38;2;198;83;46m╩[0m[38;2;194;85;50m╩[0m[38;2;167;102;82m^ [0m[38;2;81;46;209m╚[0m[38;2;66;21;234m╠[0m[38;2;66;21;234m╠╠ [0m[38;2;159;88;112m'[0m[38;2;186;53;98m╚[0m[38;2;197;40;93m╩[0m\n[38;2;128;128;128m [0m[38;2;110;97;158m'[0m[38;2;66;21;234m╠[0m[38;2;66;21;234m╠[0m[38;2;94;69;186mH[0m\n[38;2;128;128;128m [0m[38;2;68;25;230m╠[0m[38;2;66;21;234m╠[0m\n[38;2;128;128;128m [0m[38;2;108;93;162m²[0m[38;2;99;79;176m^[0m\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=MMe(),n=Bt(e,t);OMe=zq.parse(n)}catch(e){throw e instanceof ld&&console.error(`${e.message}`),new Error("Invalid configuration")}}).options(NMe()).wrap(e.terminalWidth()).command("api","Run a XL1 API Node",e=>e.command("$0","Run a XL1 API Node",()=>{},()=>{DMe({...jMe(OMe),config:OMe})})).command("bridge","Run a XL1 Bridge Node",e=>e.command("$0","Run a XL1 Bridge Node",()=>{},()=>{SMe({...jMe(OMe),config:OMe})})).command("mempool","Run a XL1 Mempool Node",e=>e.command("$0","Run a XL1 Mempool Node",()=>{},()=>{kMe({...jMe(OMe),config:OMe})})).command("producer","Run a XL1 Producer Node",e=>e.command("$0","Run a XL1 Producer Node",()=>{},async()=>{const e=jMe(OMe);await TMe({...e,config:OMe})})).command("reward-redemption-api","Run a XL1 Rewards Redemption API Node",e=>e.command("$0","Run a XL1 Rewards Redemption API Node",()=>{},()=>{_Me({...jMe(OMe),config:OMe})})).command("$0","Run a full XL1 Node",()=>{},async()=>{const e=jMe(OMe);OMe.mempool.enabled&&(kMe({...e,config:OMe}),await QMe(OMe.mempool.host,OMe.mempool.port)),DMe({...e,config:OMe}),await QMe(OMe.api.host,OMe.api.port),await TMe({...e,config:OMe})}).help().alias("help","h").version(PMe).argv;await t}XFe(UMe,"runCLI"),XFe(async()=>{WFe.config({quiet:!0}),await UMe()},"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.16.
|
|
3
|
+
"version": "1.16.5",
|
|
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.19",
|
|
87
87
|
"@xyo-network/wallet": "~5.1.19",
|
|
88
88
|
"@xyo-network/wallet-model": "~5.1.19",
|
|
89
|
-
"@xyo-network/xl1-cli-lib": "~1.16.
|
|
89
|
+
"@xyo-network/xl1-cli-lib": "~1.16.5",
|
|
90
90
|
"@xyo-network/xl1-protocol": "~1.13.1",
|
|
91
91
|
"async-mutex": "~0.5.0",
|
|
92
92
|
"dotenv": "~17.2.3",
|