@xyo-network/xl1-cli 5.7.2 → 5.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -4
- package/dist/cli-min.mjs +3 -3
- package/package.json +2 -2
package/dist/cli-min.mjs
CHANGED
|
@@ -34574,7 +34574,7 @@ return ''
|
|
|
34574
34574
|
`:`
|
|
34575
34575
|
`)+i,u=a+1,a=e.indexOf(`
|
|
34576
34576
|
`,u)}while(a!==-1);return p+=e.slice(u),p}const O6=/* @__PURE__ */ __name((e=0)=>t=>`\u{1B}[${t+e}m`,`wrapAnsi16`),k6=/* @__PURE__ */ __name((e=0)=>t=>`\u{1B}[${38+e};5;${t}m`,`wrapAnsi256`),A6=/* @__PURE__ */ __name((e=0)=>(t,i,a)=>`\u{1B}[${38+e};2;${t};${i};${a}m`,`wrapAnsi16m`),wrapUnderlineAnsi=e=>`\u{1B}[58;5;${e<90?e-30:e-90+8}m`,j6={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],underlineDouble:[`4:2`,24],underlineCurly:[`4:3`,24],underlineDotted:[`4:4`,24],underlineDashed:[`4:5`,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]},underlineColor:{underlineBlack:[`58;5;0`,59],underlineRed:[`58;5;1`,59],underlineGreen:[`58;5;2`,59],underlineYellow:[`58;5;3`,59],underlineBlue:[`58;5;4`,59],underlineMagenta:[`58;5;5`,59],underlineCyan:[`58;5;6`,59],underlineWhite:[`58;5;7`,59],underlineBlackBright:[`58;5;8`,59],underlineGray:[`58;5;8`,59],underlineGrey:[`58;5;8`,59],underlineRedBright:[`58;5;9`,59],underlineGreenBright:[`58;5;10`,59],underlineYellowBright:[`58;5;11`,59],underlineBlueBright:[`58;5;12`,59],underlineMagentaBright:[`58;5;13`,59],underlineCyanBright:[`58;5;14`,59],underlineWhiteBright:[`58;5;15`,59]}};Object.keys(j6.modifier);const pde=Object.keys(j6.color),mde=Object.keys(j6.bgColor);Object.keys(j6.underlineColor),[...pde,...mde];function assembleStyles$1(){let e=/* @__PURE__ */ new Map;for(let[t,i]of Object.entries(j6)){for(let[t,a]of Object.entries(i))j6[t]={open:`\u{1B}[${a[0]}m`,close:`\u{1B}[${a[1]}m`},i[t]=j6[t],e.set(Number.parseInt(a[0],10),a[1]);Object.defineProperty(j6,t,{value:i,enumerable:!1})}return Object.defineProperty(j6,"codes",{value:e,enumerable:!1}),j6.color.close=`\x1B[39m`,j6.bgColor.close=`\x1B[49m`,j6.underlineColor.close=`\x1B[59m`,j6.color.ansi=O6(),j6.color.ansi256=k6(),j6.color.ansi16m=A6(),j6.bgColor.ansi=O6(10),j6.bgColor.ansi256=k6(10),j6.bgColor.ansi16m=A6(10),j6.underlineColor.ansi=wrapUnderlineAnsi,j6.underlineColor.ansi256=k6(20),j6.underlineColor.ansi16m=A6(20),Object.defineProperties(j6,{rgbToAnsi256:{value(e,t,i){return e===t&&t===i?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(i/255*5)},enumerable:!1},hexToRgb:{value(e){let t=/[\da-f]{6}|[\da-f]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[i]=t;i.length===3&&(i=[...i].map(e=>e+e).join(``));let a=Number.parseInt(i,16);return[a>>16&255,a>>8&255,a&255]},enumerable:!1},hexToAnsi256:{value:e=>j6.rgbToAnsi256(...j6.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,i,a;if(e>=232)t=((e-232)*10+8)/255,i=t,a=t;else{e-=16;let u=e%36;t=Math.floor(e/36)/5,i=Math.floor(u/6)/5,a=u%6/5}let u=Math.max(t,i,a)*2;if(u===0)return 30;let p=30+(Math.round(a)<<2|Math.round(i)<<1|Math.round(t));return u===2&&(p+=60),p},enumerable:!1},rgbToAnsi:{value:(e,t,i)=>j6.ansi256ToAnsi(j6.rgbToAnsi256(e,t,i)),enumerable:!1},hexToAnsi:{value:e=>j6.ansi256ToAnsi(j6.hexToAnsi256(e)),enumerable:!1}}),j6}__name(assembleStyles$1,`assembleStyles`);const M6=assembleStyles$1();function hasFlag(e,t=globalThis.Deno?globalThis.Deno.args:A.argv){let i=e.startsWith(`-`)?``:e.length===1?`-`:`--`,a=t.indexOf(i+e),u=t.indexOf(`--`);return a!==-1&&(u===-1||a<u)}const{env:N6}=A;let P6;hasFlag(`no-color`)||hasFlag(`no-colors`)||hasFlag(`color=false`)||hasFlag(`color=never`)?P6=0:(hasFlag(`color`)||hasFlag(`colors`)||hasFlag(`color=true`)||hasFlag(`color=always`))&&(P6=1);function hasNumericForceColor(){return/^\d+$/.test(N6.FORCE_COLOR)}function envForceColor(){if(`FORCE_COLOR`in N6){if(N6.FORCE_COLOR===`false`)return 0;if(N6.FORCE_COLOR===`true`||N6.FORCE_COLOR.length===0)return 1;if(hasNumericForceColor())return Math.min(Number.parseInt(N6.FORCE_COLOR,10),3)}}function translateLevel(e){return e!==0&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function _supportsColor(e,{streamIsTTY:t,sniffFlags:i=!0}={}){let a=envForceColor();a!==void 0&&(P6=a);let u=i?P6:a;if(u===0)return 0;if(i){if(hasFlag(`color=16m`)||hasFlag(`color=full`)||hasFlag(`color=truecolor`))return 3;if(hasFlag(`color=256`))return 2}if(u!==void 0&&hasNumericForceColor())return u;if(`TF_BUILD`in N6&&`AGENT_NAME`in N6)return 1;if(e&&!t&&u===void 0)return 0;let p=u||0;if(N6.TERM===`dumb`)return p;if(A.platform===`win32`){let e=w.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in N6)return[`GITHUB_ACTIONS`,`GITEA_ACTIONS`,`CIRCLECI`].some(e=>e in N6)?3:[`TRAVIS`,`APPVEYOR`,`GITLAB_CI`,`BUILDKITE`,`DRONE`].some(e=>e in N6)||N6.CI_NAME===`codeship`?1:p;if(`TEAMCITY_VERSION`in N6)return+!!/^(?:9\.0*[1-9]\d*\.|\d{2,}\.)/.test(N6.TEAMCITY_VERSION);if(N6.COLORTERM===`truecolor`||N6.TERM===`xterm-kitty`||N6.TERM===`xterm-ghostty`||N6.TERM===`wezterm`)return 3;if(`TERM_PROGRAM`in N6){let e=Number.parseInt((N6.TERM_PROGRAM_VERSION||``).split(`.`,1)[0],10);switch(N6.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(?:color)?$/i.test(N6.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(N6.TERM)||`COLORTERM`in N6?1:p}function createSupportsColor(e,t={}){return translateLevel(_supportsColor(e,{streamIsTTY:e&&e.isTTY,...t}))}const{stdout:F6,stderr:I6}={stdout:createSupportsColor({isTTY:Ue.isatty(1)}),stderr:createSupportsColor({isTTY:Ue.isatty(2)})},L6=Symbol(`GENERATOR`),R6=Symbol(`STYLER`),z6=Symbol(`IS_EMPTY`),B6=Symbol(`LEVEL`),V6=Object.create(null),assertValidLevel=e=>{if(!Number.isSafeInteger(e)||e<0||e>3)throw Error("The `level` should be an integer from 0 to 3")},hde={enumerable:!0,get(){return this[B6]},set(e){assertValidLevel(e),this[B6]=e}},applyOptions=(e,t={})=>{t.level!==void 0&&assertValidLevel(t.level);let i=F6?F6.level:0;e[B6]=t.level===void 0?i:t.level},chalkFactory=e=>{let chalk=(...e)=>e.join(` `);return applyOptions(chalk,e),Object.setPrototypeOf(chalk,createChalk.prototype),chalk};function createChalk(e){return chalkFactory(e)}Object.setPrototypeOf(createChalk.prototype,Function.prototype);for(let[e,t]of Object.entries(M6))V6[e]={get(){let i=createBuilder(this,createStyler(t.open,t.close,this[R6]),this[z6]);return Object.defineProperty(this,e,{value:i}),i}};V6.visible={get(){let e=createBuilder(this,this[R6],!0);return Object.defineProperty(this,"visible",{value:e}),e}};const createModelConverters=(e,t)=>{let i=M6[t];if(e===`rgb`){let ansi=(e,t,a)=>i.ansi(M6.rgbToAnsi(e,t,a)),ansi256=(e,t,a)=>i.ansi256(M6.rgbToAnsi256(e,t,a));return[ansi,ansi,ansi256,i.ansi16m]}if(e===`hex`){let ansi=e=>i.ansi(M6.hexToAnsi(e)),ansi256=e=>i.ansi256(M6.hexToAnsi256(e));return[ansi,ansi,ansi256,e=>i.ansi16m(...M6.hexToRgb(e))]}let ansi=e=>i.ansi(M6.ansi256ToAnsi(e));return[ansi,ansi,i.ansi256,i.ansi256]};for(let e of[`rgb`,`hex`,`ansi256`]){let t=e[0].toUpperCase()+e.slice(1);for(let[i,a]of[[e,`color`],[`bg`+t,`bgColor`],[`underline`+t,`underlineColor`]]){let{close:t}=M6[a],u=createModelConverters(e,a);V6[i]={get(){let styleFunction=function(e,i,a){let p=u[this.level](e,i,a);return createBuilder(this,createStyler(p,t,this[R6]),this[z6])};return Object.defineProperty(this,i,{value:styleFunction}),styleFunction}}}}const gde=Object.defineProperties(()=>{},{...V6,level:{enumerable:!0,get(){return this[L6].level},set(e){this[L6].level=e}}}),createStyler=(e,t,i)=>{let a,u;return i===void 0?(a=e,u=t):(a=i.openAll+e,u=t+i.closeAll),{open:e,close:t,openAll:a,closeAll:u,parent:i}},createBuilder=(e,t,i)=>{let builder=(...e)=>e.length===1?applyStyle(builder,``+e[0]):e.length===2?applyStyle(builder,`${e[0]??``} ${e[1]??``}`):applyStyle(builder,e.join(` `));return Object.setPrototypeOf(builder,gde),builder[L6]=e[L6]??e,builder[R6]=t,builder[z6]=i,builder},applyStyle=(e,t)=>{if(e[L6][B6]<=0||!t)return e[z6]?``:t;let i=e[R6];if(i===void 0)return t;let{openAll:a,closeAll:u}=i;if(t.includes(`\x1B`))for(;i!==void 0;)t=stringReplaceAll(t,i.close,i.open),i=i.parent;let p=t.indexOf(`
|
|
34577
|
-
`);return p!==-1&&(t=stringEncaseCRLFWithFirstIndex(t,u,a,p)),a+t+u};Object.defineProperties(createChalk.prototype,{...V6,level:hde});const H6=createChalk();createChalk({level:I6?I6.level:0}),Uo();function hexToLast4BytesInt(e){assertEx$1(oo(e),()=>`value must be a hex string`);let t=e.slice(-8);return Number.parseInt(t,16)}function seededRandom(e){return function(){let t=Math.sin(e++)*1e4;return t-Math.floor(t)}}function shuffleWithSeed(e,t){let i=[...e].toSorted((e,t)=>String(e).localeCompare(String(t))),a=seededRandom(t);for(let e=i.length-1;e>0;e--){let t=Math.floor(a()*(e+1)),u=i[e];i[e]=i[t],i[t]=u}return i}function spanDurationInMillis(e){return e.duration[0]*1e3+e.duration[1]/1e6}(class _XyoConsoleSpanExporter extends He{static durationToLogLevel=[0,1,10,100,1e3];static logLevelToChalkColor=[H6.grey,H6.white,H6.green,H6.yellow,H6.red];_logLevel;constructor(e=0){super(),this._logLevel=e}get logLevel(){return this._logLevel}export(e){for(let t of e){let e=this.spanLevel(t);if(e<this.logLevel)continue;let i=spanDurationInMillis(t);console.log(H6.grey([`Span [${t.name}]`,this.logColor(e)(`${i}ms`),`TraceId: ${t.spanContext().traceId}`].join(`, `)))}}logColor(e){return _XyoConsoleSpanExporter.logLevelToChalkColor[e]??H6.magenta}spanLevel(e){let t=0,i=spanDurationInMillis(e);for(let e=_XyoConsoleSpanExporter.durationToLogLevel.length-1;e>=0;e--)if(i>_XyoConsoleSpanExporter.durationToLogLevel[e]){t=e;break}return t}}),Uo(),hM(),_Z();var isBaseBuildBlockOptions=e=>{if(!isObject$5(e))return!1;let t=e;return isArray(t.blockPayloads)&&isAddress(t.chainId)&&isArray(t.signers)&&isArray(t.txs)},isBuildGenesisBlockOptions=e=>{if(!isBaseBuildBlockOptions(e))return!1;let t=e;return t.previousBlockHash===null&&t.previousBlockNumber===void 0},isBuildNextBlockOptions=e=>{if(!isBaseBuildBlockOptions(e))return!1;let t=e;return isHash(t.previousBlockHash)&&isNumber(t.previousBlockNumber)&&isArray(t.previousStepHashes)};function calculateCompletedStepReward(e,t){return uP(pI[e][0]*t/pI[e][1])}function supersedesField(e){return isBuildNextBlockOptions(e)&&e.supersedes!==void 0?{supersedes:e.supersedes}:{}}function legacyEpochMeta(e){return e.find(e=>RF(e))?.epoch??Date.now()}async function buildBlock(e){let t=isBuildGenesisBlockOptions(e)?-1:e.previousBlockNumber,i=rP(t+1,!0),a=isBuildNextBlockOptions(e)?e.previousStepHashes:[],u=isBuildNextBlockOptions(e)?e.previousBlockHash:void 0,p=isBuildNextBlockOptions(e)?e.stepRewardPoolBalance:uP(0n),{chainId:y,txs:x,chainStepRewardAddress:w=AL,blockPayloads:E,protocol:D=PR,signers:A}=e,N=[];for(let[e]of x){if(e.nbf>i)throw Error(`Transaction ${await al.hash(e)} not valid for block ${i} - NBF is ${e.nbf}`);if(e.exp<i)throw Error(`Transaction ${await al.hash(e)} not valid for block ${i} - EXP is ${e.exp}`)}let P=[];for(let[e,t]of dI.entries()){if(i<t)break;if(i%t===0){if(pI[e][0]>0&&w!==`0000000000000000000000000000000000000000`){let a=rewardAddressFromStepIdentity({block:i,step:t}),u=calculateCompletedStepReward(e,p);P.push(createTransferPayload(w,{[a]:u}))}N.push(assertEx$1(u,()=>`Previous block hash is required for step ${t} at block ${i}`))}else isDefined$1(a.at(e))&&N.push(a[e])}let F=u??null,I=i,L=await validateTransactionsOpcodes(x),B=[...x.map(([e])=>e),...E,...L,...P].map(e=>Ks(e,!0)),[ee,G]=await new Aw().fields({block:I,chain:y,previous:F,step_hashes:N,protocol:D,...supersedesField(e)}).meta({$epoch:legacyEpochMeta(E),$signatures:[]}).signers(A).payloads(await al.addStorageMeta(B)).build();return assertEx$1(MI(ee),()=>`Build of BlockBoundWitness failed`),[await al.addStorageMeta(ee),G]}async function buildGenesisBlock(e,t,i,a,u=OL,p){return await buildBlock({previousBlockHash:null,chainId:e,txs:t,blockPayloads:i,signers:a,chainStepRewardAddress:u,protocol:p})}async function buildNextBlock(e,t,i,a,u=AL,p=uP(0n),y,x,w){return await buildBlock({chainId:x??e.chain,previousBlockNumber:e.block,previousStepHashes:e.step_hashes??[],previousBlockHash:e._hash,txs:t,blockPayloads:i,signers:a,protocol:y,chainStepRewardAddress:u,stepRewardPoolBalance:p,supersedes:w})}async function createProducerChainStakeIntent(e,t,i=0){let a=new al({schema:mF});return await al.addHashMeta(a.fields({from:e,exp:t,nbf:i,intent:`producer`}).build())}var createGenesisBlock=async(e,t,i,a)=>{let u=await al.addHashMeta([EH,dH,mH,_H,yH,xH,wH]),p=await createProducerChainStakeIntent(toAddress(e.address),1,0);return u.push(p),i>0n&&u.push(await al.addHashMeta(createTransferPayload(t,{[a]:i}))),await buildGenesisBlock(t,[],u,[e])};hM(),Uo(),_Z(),Ha();var U6=Object.defineProperty,_de=Object.getOwnPropertyDescriptor,vde=Object.getPrototypeOf,yde=Reflect.get,bde=/* @__PURE__ */ __name((e,t,i)=>t in e?U6(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,`__defNormalProp`),W6=/* @__PURE__ */ __name((e,t,i,a)=>{for(var u=a>1?void 0:a?_de(t,i):t,p=e.length-1,y;p>=0;p--)(y=e[p])&&(u=(a?y(t,i,u):y(u))||u);return a&&u&&U6(t,i,u),u},`__decorateClass`),G6=/* @__PURE__ */ __name((e,t,i)=>bde(e,typeof t==`symbol`?t:t+``,i),`__publicField`),xde=/* @__PURE__ */ __name((e,t,i)=>yde(vde(e),i,t),`__superGet`),K6=Cs(`network.xyo.diviner.chain.block.reward.config`,!0),BlockRewardDiviner=class extends AbstractDiviner{static configSchemas=[K6]},q6=Cs(`network.xyo.block.reward`,!0),J6=isPayloadOfSchemaType(q6);Ro.create(J6),Ro.createOptional(J6);var Y6=isPayloadOfSchemaTypeWithSources(q6);Ro.create(Y6),Ro.createOptional(Y6);var X6=Cs(`network.xyo.diviner.chain.block.reward.fixed.percent.config`,!0),FixedPercentageBlockRewardDiviner=class extends BlockRewardDiviner{_fixedPercentageDenominator;_fixedPercentageNumerator;_percentageScale;get blockRewardViewer(){return assertEx$1(this.params.blockRewardViewer,()=>`blockRewardViewer is required`)}get fixedPercentageDenominator(){return isDefined$1(this._fixedPercentageDenominator)||(this._fixedPercentageDenominator=BigInt(this.percentageScaleNumeric)),this._fixedPercentageDenominator}get fixedPercentageNumerator(){return isDefined$1(this._fixedPercentageNumerator)||(this._fixedPercentageNumerator=BigInt(Math.round(this.rewardPercentageRatio*this.percentageScaleNumeric))),this._fixedPercentageNumerator}get percentageScaleNumeric(){return isDefined$1(this._percentageScale)||(this._percentageScale=10**countDecimalPlaces(this.rewardPercentageRatio)),this._percentageScale}get rewardAddress(){return assertEx$1(asAddress(this.config.rewardAddress),()=>`rewardAddress is required`)}get rewardPercentageRatio(){return assertEx$1(this.config.rewardPercentageRatio!==void 0,()=>`rewardPercentageRatio is required`),this.config.rewardPercentageRatio}async divineHandler(e=[]){let t=filterAs(e,mL);return(await Promise.all(t.map(async e=>{let t=e.block,i=await this.blockRewardViewer.allowedRewardForBlock(t),a=i*this.fixedPercentageNumerator/this.fixedPercentageDenominator,u=i-a;assertEx$1(a>=0n,()=>`producerReward must be greater than or equal to 0`);let p=Object.fromEntries([[this.rewardAddress,toHex(a)],[AL,toHex(u)]]);return[new al({schema:SI}).fields({epoch:Date.now(),from:OL,transfers:p}).build()]}))).flat().filter(eo)}};G6(FixedPercentageBlockRewardDiviner,`configSchemas`,[K6,X6]),G6(FixedPercentageBlockRewardDiviner,`defaultConfigSchema`,X6),FixedPercentageBlockRewardDiviner=W6([creatableModule()],FixedPercentageBlockRewardDiviner);var countDecimalPlaces=e=>{if(!Number.isFinite(e))throw TypeError(`Input must be a finite number`);let t=e.toString(),i=t.indexOf(`.`);return i===-1?0:t.length-i-1},Z6=Cs(`network.xyo.diviner.chain.head.validation.config`,!0),HeadValidationDiviner=class extends AbstractDiviner{_context;_headValidationDivinerHeadUpdateTotal;_headSelector;_outArchivist;_startingHead;divineMutex=new Mutex;get allowedProducers(){return this.params.allowedProducers??this.config.allowedProducers??[]}get blockViewer(){return assertEx$1(this.params.blockViewer,()=>`Missing block viewer`)}get chainId(){return assertEx$1(this.params.chainId??this.config.chainId,()=>`Missing chain information`)}get context(){return this._context}get headSelector(){return assertEx$1(this._headSelector,()=>`Missing head selector`)}get mempoolViewer(){return assertEx$1(this.params.mempoolViewer,()=>`Missing mempool viewer`)}async createHandler(){await super.createHandler(),this._context=this.params.context??{singletons:{}},this._headValidationDivinerHeadUpdateTotal=this.meter?.createCounter(`head_validation_diviner_head_update_total`,{description:`Count of head updates performed by the diviner during head validation`}),this._headSelector=new D6({context:this.context,allowedProducers:this.allowedProducers,blockViewer:this.blockViewer,mempoolViewer:this.mempoolViewer,maxWindowSize:1e3})}async resolveOutArchivist(){if(this._outArchivist)return this._outArchivist;let e=assertEx$1(await this.resolve(assertEx$1(this.config.outArchivist,()=>`Missing outArchivist`)),()=>`Unable to resolve outArchivist [${this.config.outArchivist}]`),t=assertEx$1(rO(e),()=>`Invalid outArchivist resolved`);return this._outArchivist=t,this._outArchivist}async divineHandler(){return this.divineMutex.isLocked()?[]:await this.divineMutex.runExclusive(async()=>await this.spanAsync(`HeadValidationDiviner:divineHandler`,async()=>{try{let e=Date.now(),t=await this.headSelector.findBestHead()??this._startingHead;if(isDefined$1(t)){let i=await this.resolveOutArchivist(),a=this._startingHead?.[0],u=assertEx$1(t.at(-1),()=>`Missing best head block [HeadValidationDiviner]`),p=u[0],y=[];if(this.logger?.debug(`Validating new HeadBlock head from (block) `,a?.block,`to`,p.block),this.logger?.debug(`Validating new HeadBlock head from (hash) `,a?._hash,`to`,p._hash),p._hash===a?._hash){this.logger?.debug(`No new blocks found`,a?.block,`to`,p.block);return}let x=t.filter(e=>!isDefined$1(a)||e[0].block>a.block),w=x.flatMap(e=>flattenHydratedBlock(e));return y=[{producer:toAddress(p.addresses[0])},...y],this.logger?.info(`Validated new HeadBlock head from (block) in`,`${Date.now()-e}ms`,p.block,`to`,a?.block),this.logger?.info(`Validated new HeadBlock head from (hash) in`,`${Date.now()-e}ms`,p._hash,`to`,a?._hash),await this.spanAsync(`HeadValidationDiviner:commitToOutArchivist`,async()=>{if(w.length!==0){await i.insert(w);for(let e of y)this._headValidationDivinerHeadUpdateTotal?.add(1,e)}},this.context),await this.headSelector.finalizeChainFragment(x),this._startingHead=u,w}this.logger?.info(`No head found to validate`,this._startingHead?.[0]._hash)}catch(e){this.logger?.error(`Error in divineHandler`,e)}},this.context)??[])}};G6(HeadValidationDiviner,`configSchemas`,[...xde(HeadValidationDiviner,HeadValidationDiviner,`configSchemas`),Z6]),G6(HeadValidationDiviner,`targetSchema`,Z6),HeadValidationDiviner=W6([creatableModule()],HeadValidationDiviner);var Q6=Cs(`network.xyo.witness.archivist.next.config`,!0),ArchivistNextWitness=class extends AbstractWitness{static configSchemas=[...super.configSchemas,Q6];static defaultConfigSchema=Q6;_cursor;async getSourceArchivist(){return assertEx$1(rO(await this.resolve(assertEx$1(this.config.sourceArchivist,()=>`Missing sourceArchivist`))),()=>`Invalid sourceArchivist`)}async observeHandler(){let e=await(await this.getSourceArchivist()).next({cursor:this._cursor,order:`asc`}),t=e.at(-1);return t&&(this._cursor=t._sequence),e}},$6=isPayloadOfSchemaType(Cs(`network.xyo.witness.chain.stake.network.weighted`,!0));Ro.create($6),Ro.create($6);var e8=isPayloadOfSchemaType(Cs(`network.xyo.witness.chain.stake.network.observe`,!0));Ro.create(e8),Ro.create(e8),_Z(),Uo(),hM(),VN();var t8=Object.defineProperty,Sde=Object.getOwnPropertyDescriptor,Cde=/* @__PURE__ */ __name((e,t,i)=>t in e?t8(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,`__defNormalProp`),n8=/* @__PURE__ */ __name((e,t,i,a)=>{for(var u=a>1?void 0:a?Sde(t,i):t,p=e.length-1,y;p>=0;p--)(y=e[p])&&(u=(a?y(t,i,u):y(u))||u);return a&&u&&t8(t,i,u),u},`__decorateClass`),r8=/* @__PURE__ */ __name((e,t,i)=>Cde(e,typeof t==`symbol`?t:t+``,i),`__publicField`),i8=`Validator`,XyoValidator=class extends AbstractCreatableProvider{moniker=XyoValidator.defaultMoniker;_blockViewer;get blockViewer(){return this._blockViewer}async createHandler(){await super.createHandler(),this._blockViewer=await this.locator.getInstance(Hz)}validatePendingBlock(e){return[]}async validatePendingTransaction(e){let[t]=e;return await this.blockViewer.blockByHash(t._hash)===void 0}};r8(XyoValidator,`connectionTypes`,[]),r8(XyoValidator,`defaultMoniker`,i8),r8(XyoValidator,`dependencies`,[Hz]),r8(XyoValidator,`monikers`,[i8]),r8(XyoValidator,`providerId`,`XyoValidator`),r8(XyoValidator,`surface`,`node`),XyoValidator=n8([creatableProvider()],XyoValidator);var BaseElectionService=class extends AbstractCreatableProvider{moniker=BaseElectionService.defaultMoniker;get blockViewer(){return assertEx$1(this.params.blockViewer,()=>`No block viewer`)}get chainStakeViewer(){return assertEx$1(this.params.chainStakeViewer,()=>`No chain stake viewer`)}get stakeIntentService(){return assertEx$1(this.params.stakeIntentService,()=>`No staked intent service`)}async getCreatorCommitteeForNextBlock(e){return await this.spanAsync(`getCreatorCommitteeForNextBlock`,async()=>{let t=e.block+1,i=await this.stakeIntentService.getDeclaredCandidatesForBlock(t,`producer`),a=e._hash;return this.generateCreatorCommittee(i,a)},this.context)}generateCreatorCommittee(e,t,i=3){return shuffleWithSeed(new Set(e),hexToLast4BytesInt(t)).slice(0,i)}};r8(BaseElectionService,`connectionTypes`,[]),r8(BaseElectionService,`defaultMoniker`,`Election`),r8(BaseElectionService,`dependencies`,[]),r8(BaseElectionService,`monikers`,[`Election`]),r8(BaseElectionService,`providerId`,`BaseElectionService`),BaseElectionService=n8([creatableProvider()],BaseElectionService);var createBootstrapHead=async(e,t,i,a)=>{let u=[],p=await createGenesisBlock(e,t,i,a);u.push(p);let y=createDeclarationIntent(toAddress(e.address),`producer`,p[0].block,p[0].block+1e4),x=await buildNextBlock(p[0],[],[y],[e]);return u.push(x),u};function hasMessage(e){return typeof e==`object`&&!!e&&`message`in e}async function reportRejectedBlock(e,t,i,a){let u=Array.isArray(i)?i.map(e=>({hash:t[0]._hash,name:`BlockValidationError`,message:String(hasMessage(e)?e.message:e)})):[{hash:t[0]._hash,name:`BlockValidationError`}],p={schema:IR,block:t,errors:u,rejector:a?.address??`validator`},y=a===void 0?void 0:await buildSignedBlockRejection(p,a);await e.rejectBlock(p,y)}async function processPendingBlocks({blockValidationViewer:e,blockViewer:t,context:i,logger:a,mempoolViewer:u,finalizationRunner:p,allowedProducers:y,backoffMs:x,heartbeatInterval:w,minCandidates:E,deadLetterQueueRunner:D,observer:A,admission:N,eligibility:P,licensing:F,publishAdmissionShadow:I,timeRules:L}){let B=Date.now(),ee=await t.currentBlock(),G=new D6({context:i,logger:a,mempoolViewer:u,blockViewer:t,windowedFinalizedChain:[ee],allowedProducers:y,backoffMs:x,heartbeatInterval:w,minCandidates:E,admission:N,eligibility:P,licensing:F,publishAdmissionShadow:I,timeRules:L}),q=await G.findBestHead();if(isDefined$1(q)&&q.length>0){let t=ee[0],i=assertEx$1(q.at(-1),()=>`Missing best head block [processPendingBlocks]`)[0];if(a?.debug(`Validating new HeadBlock head from (block) `,t?.block,`to`,i.block),a?.debug(`Validating new HeadBlock head from (hash) `,t?._hash,`to`,i._hash),i._hash===t?._hash){a?.debug(`No new blocks found`,t?.block,`to`,i.block);return}let u=q.filter(e=>!isDefined$1(t)||e[0].block>t.block),y=await Promise.all(u.map(t=>Promise.resolve(e.validateBlocks([t],{value:!0,state:!0})))),x=[];for(let[e,t]of u.entries()){let i=y[e][0];qI(i)?x.push(t):(a?.error(`Block validation failed`,t[0].block,t[0]._hash,JSON.stringify(i,null,2)),D&&await reportRejectedBlock(D,t,i,A))}return a?.info(`Validated new HeadBlock head from (block) in`,`${Date.now()-B}ms`,i.block,`to`,t?.block),a?.info(`Validated new HeadBlock head from (hash) in`,`${Date.now()-B}ms`,i._hash,`to`,t?._hash),x.length>0&&await p.finalizeBlocks(x),await G.finalizeChainFragment(x),x}a?.info(`No head found to validate`,ee?.[0]._hash)}var BaseNetworkStakeStepRewardService=class extends AbstractCreatableProvider{moniker=BaseNetworkStakeStepRewardService.defaultMoniker;networkStakeStepRewardAddressHistory(e){throw Error(`Method [networkStakeStepRewardAddressHistory] not implemented.`)}networkStakeStepRewardAddressReward(e,t){throw Error(`Method [networkStakeStepRewardAddressReward] not implemented.`)}networkStakeStepRewardAddressShare(e,t){throw Error(`Method [networkStakeStepRewardAddressShare] not implemented.`)}networkStakeStepRewardAllocationsForStep(e){throw Error(`Method [networkStakeStepRewardAllocationsForStep] not implemented.`)}networkStakeStepRewardClaimedByAddress(e){throw Error(`Method [networkStakeStepRewardClaimedByAddress] not implemented.`)}networkStakeStepRewardForPosition(e,t){throw Error(`Method [networkStakeStepRewardForPosition] not implemented.`)}networkStakeStepRewardForStep(e){throw Error(`Method [networkStakeStepRewardForStep] not implemented.`)}networkStakeStepRewardForStepForPosition(e,t){throw Error(`Method [networkStakeStepRewardForStepForPosition] not implemented.`)}networkStakeStepRewardPoolRewards(e){throw Error(`Method [networkStakeStepRewardPoolRewards] not implemented.`)}networkStakeStepRewardPoolShares(e){throw Error(`Method [networkStakeStepRewardPoolShares] not implemented.`)}networkStakeStepRewardPositionWeight(e,t){throw Error(`Method [networkStakeStepRewardPositionWeight] not implemented.`)}networkStakeStepRewardPotentialPositionLoss(e,t){throw Error(`Method [networkStakeStepRewardPotentialPositionLoss] not implemented.`)}networkStakeStepRewardRandomizer(e){throw Error(`Method [networkStakeStepRewardRandomizer] not implemented.`)}networkStakeStepRewardStakerCount(e){throw Error(`Method [networkStakeStepRewardStakerCount] not implemented.`)}networkStakeStepRewardUnclaimedByAddress(e){throw Error(`Method [networkStakeStepRewardUnclaimedByAddress] not implemented.`)}networkStakeStepRewardWeightForAddress(e,t){throw Error(`Method [networkStakeStepRewardWeightForAddress] not implemented.`)}networkStakeStepRewardsForPosition(e,t){throw Error(`Method [networkStakeStepRewardsForPosition] not implemented.`)}networkStakeStepRewardsForRange(e){throw Error(`Method [networkStakeStepRewardsForRange] not implemented.`)}networkStakeStepRewardsForStepLevel(e,t){throw Error(`Method [networkStakeStepRewardsForStepLevel] not implemented.`)}};r8(BaseNetworkStakeStepRewardService,`connectionTypes`,[]),r8(BaseNetworkStakeStepRewardService,`defaultMoniker`,dB),r8(BaseNetworkStakeStepRewardService,`dependencies`,[]),r8(BaseNetworkStakeStepRewardService,`monikers`,[dB]),r8(BaseNetworkStakeStepRewardService,`providerId`,`BaseNetworkStakeStepRewardService`),BaseNetworkStakeStepRewardService=n8([creatableProvider()],BaseNetworkStakeStepRewardService);function selectSupersededCandidate(e,t,i,a){let u=e.filter(e=>e.block===i&&e.previous===a&&e.addresses.includes(t));if(u.length===0)return;let p=new Set(u.map(e=>e.supersedes).filter(isDefined$1));return(u.find(e=>!p.has(e._dataHash))??u[0])._dataHash}async function generateTransactionFeeTransfers(e,t){let i=await Promise.all(t.map(async e=>gZ.parse([await al.addStorageMeta(e[0]),await al.addStorageMeta(e[1])]))),a={};for(let e of i)a[e.boundWitness.from]=(a[e.boundWitness.from]??0n)+e.fees.base;let u={};for(let e of i){let t=transactionRequiredGas(e.data)*e.fees.gasPrice;u[e.boundWitness.from]=(u[e.boundWitness.from]??0n)+t+e.fees.priority}let p=Object.entries(a).map(([e,t])=>({schema:SI,epoch:Date.now(),from:e,transfers:Object.fromEntries([[OL,hexFromBigInt(t)]])}));for(let[t,i]of Object.entries(u)){let a=assertEx$1(p.find(e=>e.from===t),()=>`from payload not found`);a.transfers[e]=hexFromBigInt(i)}return p}async function scoreTransaction(e){let t=await gZ.parse(e),i=t.boundWitness.from,a=t.fees.gasPrice,u=transactionRequiredGas(e)*a,p=t.fees.base,y=netBalancesForPayloads({singletons:{}},e[1])[i]??0n,x=y<0n?-y:0n;return{cost:u+p+x,gasPrice:a}}async function identifyOffendingTransactions(e){let{errors:t,candidateTransactions:i}=e,a=new Set(i.map(e=>e[0]._hash)),u=/* @__PURE__ */ new Set;for(let e of t){a.has(e.hash)&&u.add(e.hash);let t=e.cause;t?.hash&&a.has(t.hash)&&u.add(t.hash)}if(u.size>0)return{offendingHashes:[...u],reason:`tx-invalid`};let p=/* @__PURE__ */ new Set;for(let e of t){let t=e.offendingTransactionHashes??[];for(let e of t)a.has(e)&&p.add(e)}if(p.size===0)return{offendingHashes:[],reason:`unknown`};let y=i.filter(e=>p.has(e[0]._hash)),x=await Promise.all(y.map(async e=>({tx:e,...await scoreTransaction(e)})));return x.sort((e,t)=>e.cost===t.cost?e.gasPrice===t.gasPrice?e.tx[0]._hash<t.tx[0]._hash?-1:1:e.gasPrice<t.gasPrice?-1:1:e.cost<t.cost?1:-1),{offendingHashes:[x[0].tx[0]._hash],reason:`block-balance`}}var wde=object$3({disableIntentRedeclaration:boolean().optional(),heartbeatInterval:number$1().optional(),rewardAddress:string$1().optional()});function producerTuningFromConfig(e){let t=e.options??{},i=wde.safeParse(t);return i.success?i.data:{}}var a8=`simpleBlockRunnerInstrumentation`;function registerSimpleBlockRunnerInstrumentation(e,t){e.singletons[a8]=t}function tryGetSimpleBlockRunnerInstrumentation(e){let t=e.singletons[a8];if(typeof t==`object`&&t&&`recordTiming`in t)return typeof t.recordTiming==`function`?t:void 0}var o8=3e5,SimpleBlockRunner=class extends AbstractCreatableProvider{moniker=SimpleBlockRunner.defaultMoniker;_blockRewardDiviner;_deadLetterQueueRunner;_excludedTransactionHashes=/* @__PURE__ */ new Map;_lastRedeclarationBlock;_rejectedTransactionsArchivist;_account;_accountBalanceViewer;_address;_blockRewardViewer;_blockValidationViewer;_chainParamsViewer;_finalizationViewer;_headEpochCache;_lastRejectedBuildAt=0;_lastSignedCandidate;_mempoolViewer;_rewardAddress;_timeSyncViewer;static get DefaultBlockSize(){return 10}static get RedeclarationDuration(){return 100}static get RedeclarationWindow(){return 100}get account(){return this._account}get accountBalanceViewer(){return this._accountBalanceViewer}get address(){return this._address}get blockRewardViewer(){return this._blockRewardViewer}get blockValidationViewer(){return this._blockValidationViewer}get finalizationViewer(){return this._finalizationViewer}get heartbeatInterval(){return this.params.heartbeatInterval??this.producerTuning.heartbeatInterval??3e5}get instrumentation(){return this.params.instrumentation??tryGetSimpleBlockRunnerInstrumentation(this.context)}get mempoolViewer(){return this._mempoolViewer}get producerTuning(){return producerTuningFromConfig(this.config)}get rejectedTransactionsArchivist(){return this._rejectedTransactionsArchivist}get rewardAddress(){return this._rewardAddress}get timeSyncViewer(){return this._timeSyncViewer}async createHandler(){let e=this.boundConnection;this._rejectedTransactionsArchivist=this.params.rejectedTransactionsArchivist??(e?await connectArchivist(e,{name:`rejected-transactions`}):await MemoryArchivist.create()),this._account=assertEx$1(this.params.account??this.contextAccount,()=>`Account is required — inject params.account or register a context signer`),this._address=toAddress(this.account.address),this._accountBalanceViewer=await this.locateAndCreate(DL),this._blockRewardViewer=await this.locateAndCreate(Wz),this._blockValidationViewer=await this.locator.getInstance(Kz),this._finalizationViewer=await this.locateAndCreate(eB),this._mempoolViewer=await this.locateAndCreate(iB),this._rewardAddress=asAddress(this.params.rewardAddress??this.producerTuning.rewardAddress??this.account.address,!0),this._timeSyncViewer=await this.locateAndCreate(bB),this._deadLetterQueueRunner=await this.locator.tryGetInstance(sz),this._chainParamsViewer=await this.locator.tryGetInstance(Jz)}async next(e){return await this.proposeNextValidBlock(e)}async produceNextBlock(e,t){let i=await this.proposeNextValidBlock(e);return t===!0?assertEx$1(i,()=>`Failed to produce next block`):i}async getBlockRewardTransfers(e){this._blockRewardDiviner??=await FixedPercentageBlockRewardDiviner.create({account:`random`,blockRewardViewer:this.blockRewardViewer,config:{rewardAddress:this.rewardAddress,rewardPercentageRatio:qL,schema:X6}});let t=new al({schema:dL}).fields({block:e}).build(),i=this._blockRewardDiviner;return await this.instrument(`blockRewardTransfers`,async()=>await i.divine([t]))}getProducerRedeclaration(e){if((this.params.disableIntentRedeclaration??this.producerTuning.disableIntentRedeclaration)===!0)return;let t=e.block;if(!(isDefined$1(this._lastRedeclarationBlock)&&t<this._lastRedeclarationBlock+SimpleBlockRunner.RedeclarationDuration))return this._lastRedeclarationBlock=t,createDeclarationIntent(this.address,`producer`,t,t+SimpleBlockRunner.RedeclarationDuration)}async proposeNextValidBlock(e,t,i=!1){let a=t??this.params.validateBalances??!0;return await this.spanAsync(`proposeNextValidBlock`,async()=>{try{if(this.isWithinRejectedBuildBackoff(i))return;let{block:t}=assertEx$1(NI(e),()=>`Invalid head block`),u=t+1,p=await this.finalizationViewer.chainId(),y=await this.instrument(`mempoolPendingTransactionsFetch`,async()=>await this.mempoolViewer.pendingTransactions({limit:SimpleBlockRunner.DefaultBlockSize}));this.evictStaleExclusions(t);let x=y.filter(e=>!this._excludedTransactionHashes.has(e[0]._hash)),w=await this.rejectWrongChainTransactions(x,p);this.logger?.log(`Pending Tx Count ${w.length}`);let E=[],D=await this.getProducerRedeclaration(e);if(D&&E.push(D),w.length===0&&!i&&!await this.heartbeatRequired(e))return;let A=await this.getBlockRewardTransfers(u);E.push(...A);let N=await this.generateTimePayload(),P=await this.filterByFunded(e._hash,w,a),F=await generateTransactionFeeTransfers(this.address,P),I=(await this.accountBalanceViewer.accountBalances([AL]))[AL],{block:L,errors:B}=await this.runBuildValidateRetryLoop({head:e,chainId:p,stepRewardPoolBalance:I,nonTxPayloads:E,timePayload:N,initialFundedTransactions:P,initialFundedTransfers:F});return await this.commitProposedBlock(L,B)}catch(e){throw this.logger?.error(`Error proposing next valid block: ${e.message}`),e}},this.context)}addTransferOutflow(e,t){let i=e;for(let[e,a=`00`]of Object.entries(t.transfers))e!==t.from&&(i+=hexToBigInt(a));return i}async commitProposedBlock(e,t){if(t.length===0&&qI(e))return this._lastRejectedBuildAt=0,e;e!==void 0&&(this._lastRejectedBuildAt=Date.now(),await this.rejectExhaustedBlock(e,t))}computeTransactionOutflow(e){let[t,i]=e,{base:a,gasLimit:u,priority:p}=t.fees,y=hexToBigInt(a)+hexToBigInt(p)+hexToBigInt(u),x=new Set(t.payload_hashes);for(let e of i)x.has(e._hash)&&TI(e)&&e.from===t.from&&(y=this.addTransferOutflow(y,e));return y}evictStaleExclusions(e){for(let[t,i]of this._excludedTransactionHashes)i.reason===`block-balance`&&e>i.excludedAtBlock&&this._excludedTransactionHashes.delete(t)}async filterByFunded(e,t,i=!1){if(!i)return t;let a=[],u=await this.readSenderBalances(e,t),p=/* @__PURE__ */ new Map;for(let e of t){let{from:t}=e[0],i=u.get(t)??uP(0n),y=(p.get(t)??0n)+this.computeTransactionOutflow(e);i>=y?(p.set(t,y),a.push(e)):this.logger?.debug(`filterByFunded: dropping tx ${e[0]._hash} from ${t} \u2014 cumulative outflow ${y} > balance ${i}`)}return a}async generateTimePayload(){let e=Date.now(),t=await this.instrument(`timePayloadGeneration`,async()=>await this.timeSyncViewer.currentTimePayload()),i=Date.now()-e;return i>100&&this.logger?.warn(`[Slow] Generated time payload in ${i}ms`),t}async headEpoch(e){let t=this._headEpochCache;if(t?.hash===e._hash)return t.epoch;try{let t=await this.timeSyncViewer.convertTime(`xl1`,`epoch`,e.block);return t<=0?void 0:(this._headEpochCache={epoch:t,hash:e._hash},t)}catch(e){this.logger?.warn(`Could not read the head's signed epoch for heartbeat pacing: ${String(e)}`);return}}async heartbeatRequired(e){let t=await this.headEpoch(e);return!isDefined$1(t)||Date.now()-t>this.heartbeatInterval}async instrument(e,t){let i=this.instrumentation;if(i===void 0)return await t();let a=Date.now();try{return await t()}finally{try{i.recordTiming(e,Date.now()-a)}catch(e){this.logger?.warn(`SimpleBlockRunner instrumentation failed: ${String(e)}`)}}}isWithinRejectedBuildBackoff(e){return e||Date.now()-this._lastRejectedBuildAt>=SimpleBlockRunner.RejectedBuildBackoffMs?!1:(this.logger?.debug(`Skipping block production during rejected-build backoff`),!0)}async previousOwnCandidateHash(e,t){let i=this._lastSignedCandidate;return i?.block===e&&i.previous===t?i.hash:selectSupersededCandidate((await this.instrument(`mempoolPendingBlocksFetch`,async()=>await this.mempoolViewer.pendingBlocks())).map(([e])=>e),this.address,e,t)}async readSenderBalances(e,t){let i=[...new Set(t.map(e=>e[0].from))];if(i.length===0)return/* @__PURE__ */ new Map;let a=await this.accountBalanceViewer.accountBalances(i,{head:e});return new Map(i.map(e=>[e,a[e]??uP(0n)]))}async rejectExhaustedBlock(e,t){if(this.logger?.warn(`Validation of produced block failed: ${t.at(0)?.message}`),this._deadLetterQueueRunner){let i=t.map(t=>({hash:e[0]._hash,name:`BlockValidationError`,message:t.message??t}));await this._deadLetterQueueRunner.rejectBlock({schema:IR,block:e,errors:i,rejector:`producer`})}else await this.rejectedTransactionsArchivist.insert(e[1])}async rejectWrongChainTransactions(e,t){let i=t.toLowerCase(),a=[],u=[];for(let t of e)t[0].chain.toLowerCase()===i?a.push(t):u.push(t);if(u.length>0){this.logger?.warn(`Rejecting ${u.length} transaction(s) targeting non-local chain`);let e=this._deadLetterQueueRunner;await(e?Promise.all(u.map(t=>e.rejectTransaction({schema:BR,transaction:t,errors:[{hash:t[0]._hash,name:`TransactionChainMismatch`,message:`Transaction chain ${t[0].chain} does not match local chain ${i}`}],rejector:`producer`}))):this.rejectedTransactionsArchivist.insert(u.map(e=>e[0])))}return a}async resolveSupersedes(e){let t=this._chainParamsViewer;if(t===void 0)return;let i=await t.tryCurrentParams(),a=e.block+1;return i===void 0||!isRuleActiveAt(i,`supersedes-field`,a)?void 0:await this.previousOwnCandidateHash(a,e._hash)}async runBuildValidateRetryLoop(e){let{chainId:t,head:i,initialFundedTransactions:a,initialFundedTransfers:u,nonTxPayloads:p,stepRewardPoolBalance:y,timePayload:x}=e,w=await this.resolveSupersedes(i),E=Math.max(1,a.length),D=a,A=u,N,P=[];for(let e=0;e<=E;e++){let a=[...p,...A,x];this.logger?.info(`Building block ${i.block+1}${e>0?` (retry ${e})`:``}`),N=await buildNextBlock(i,D,a,[this.account],AL,y,void 0,t,w);let u=await this.blockValidationViewer.validateBlock(N,{value:!0,state:!0,head:i._hash});if(qI(u))return this._lastSignedCandidate={block:u[0].block,hash:u[0]._dataHash,previous:i._hash},{block:u,errors:[]};if(P=u,e===E)break;let{offendingHashes:F,reason:I}=await identifyOffendingTransactions({candidateTransactions:D,errors:u});if(F.length===0||I===`unknown`)break;for(let e of F)this._excludedTransactionHashes.set(e,{excludedAtBlock:i.block,reason:I});let L=new Set(F);D=D.filter(e=>!L.has(e[0]._hash)),A=await generateTransactionFeeTransfers(this.address,D),this.logger?.warn(`Block validation failed (attempt ${e+1}); excluded ${F.length} tx(s), retrying`)}return{block:N,errors:P}}};r8(SimpleBlockRunner,`RejectedBuildBackoffMs`,1e3),r8(SimpleBlockRunner,`connectionTypes`,[`lmdb`,`mongo`,`memory`]),r8(SimpleBlockRunner,`defaultMoniker`,rz),r8(SimpleBlockRunner,`dependencies`,[DL,Wz,Kz,eB,iB,bB]),r8(SimpleBlockRunner,`monikers`,[rz]),r8(SimpleBlockRunner,`providerId`,`SimpleBlockRunner`),r8(SimpleBlockRunner,`surface`,`node`),SimpleBlockRunner=n8([creatableProvider()],SimpleBlockRunner),_Z();function createArtifactLedger(){return{artifacts:/* @__PURE__ */ new Map,byOwner:/* @__PURE__ */ new Map}}function cloneArtifactLedger(e){return{artifacts:new Map([...e.artifacts].map(([e,t])=>[e,{...t}])),byOwner:new Map([...e.byOwner].map(([e,t])=>[e,new Set(t)]))}}function indexOwner(e,t,i){let a=e.get(t)??/* @__PURE__ */ new Set;a.add(i),e.set(t,a)}function unindexOwner(e,t,i){let a=e.get(t);a!==void 0&&(a.delete(i),a.size===0&&e.delete(t))}function registerArtifact(e,t,i){return e.artifacts.has(t.hash)?`already-registered`:(e.artifacts.set(t.hash,{creator:t.signer,id:t.hash,inscribedAt:i,inscribedBy:t.txHash,owner:t.signer,schema:t.schema}),indexOwner(e.byOwner,t.signer,t.hash),`registered`)}function transferArtifact(e,t,i){let a=e.artifacts.get(t.inscriptionId);return a===void 0?`unknown-artifact`:a.owner===i?(unindexOwner(e.byOwner,a.owner,a.id),a.owner=t.to,indexOwner(e.byOwner,t.to,a.id),`transferred`):`not-owner`}var s8=`network.xyo.ordinal`;sentinelAddressFromSchema(s8);function inscribeMarkAddress(e){return sentinelAddressFromSchema(s8,e)}function transferRecipients(e,t){let i=/* @__PURE__ */ new Set;for(let a of e.payload_hashes){let u=t.get(a);if(TI(u)&&u.from===e.from)for(let e of Object.keys(u.transfers))i.add(e)}return i}function inscribeMarkedHashes(e,t){let i=/* @__PURE__ */ new Set,a=transferRecipients(e,t);if(a.size===0)return i;for(let t of e.payload_hashes)a.has(inscribeMarkAddress(t))&&i.add(t);return i}function collectSubstrateRefs(e,t){let[i,a]=e,u=new Map(a.map(e=>[e._hash,e])),p=[];for(let e of i.payload_hashes){let i=u.get(e);if(!TP(i))continue;let a=inscribeMarkedHashes(i,u);for(let[u,y]of i.payload_hashes.entries()){let x=i.payload_schemas[u];if(x===void 0)continue;let w=a.has(y);(w||t.has(x))&&p.push({hash:y,index:u,isInscribeMarked:w,schema:x,signer:i.from,txHash:e})}}return p}hM(),Uo(),za(),_Z(),DX(),VN();var c8=Object.defineProperty,Tde=Object.getOwnPropertyDescriptor,Ede=/* @__PURE__ */ __name((e,t,i)=>t in e?c8(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,`__defNormalProp`),l8=/* @__PURE__ */ __name((e,t,i,a)=>{for(var u=a>1?void 0:a?Tde(t,i):t,p=e.length-1,y;p>=0;p--)(y=e[p])&&(u=(a?y(t,i,u):y(u))||u);return a&&u&&c8(t,i,u),u},`__decorateClass`),u8=/* @__PURE__ */ __name((e,t,i)=>Ede(e,typeof t==`symbol`?t:t+``,i),`__publicField`),d8=Cs(`network.xyo.license.assign`,!0),f8=/* @__PURE__ */ object$5({address:us,exp:/* @__PURE__ */ optional$2(int$1().check(/* @__PURE__ */ _gte(0)))}),Dde=/* @__PURE__ */ object$5({license:po,operators:/* @__PURE__ */ array$2(f8)}),Ode=zodIsFactory(/* @__PURE__ */ extend(PayloadZodOfSchema(d8),Dde.shape)),p8=Cs(`network.xyo.license.issue`,!0),kde=/* @__PURE__ */ object$5({nbf:int$1().check(/* @__PURE__ */ _gte(0)),offering:po,serial:int$1().check(/* @__PURE__ */ _gte(0))}),Ade=zodIsFactory(/* @__PURE__ */ extend(PayloadZodOfSchema(p8),kde.shape)),m8=Cs(`network.xyo.license.offering`,!0),h8=/* @__PURE__ */ _enum$1([`none`,`owner`,`issuer`]),jde=/* @__PURE__ */ object$5({cap:/* @__PURE__ */ nullable$2(int$1().check(/* @__PURE__ */ _gte(1))),capacity:int$1().check(/* @__PURE__ */ _gte(1)),name:/* @__PURE__ */ string$3(),renewal:h8,term:/* @__PURE__ */ nullable$2(int$1().check(/* @__PURE__ */ _gte(1)))}),Mde=zodIsFactory(/* @__PURE__ */ extend(PayloadZodOfSchema(m8),jde.shape)),g8=Cs(`network.xyo.license.renew`,!0),Nde=/* @__PURE__ */ object$5({license:po}),Pde=zodIsFactory(/* @__PURE__ */ extend(PayloadZodOfSchema(g8),Nde.shape));function createLicenseLedger(){return{byOperator:/* @__PURE__ */ new Map,byOwner:/* @__PURE__ */ new Map,licenses:/* @__PURE__ */ new Map,offerings:/* @__PURE__ */ new Map}}function cloneIndex(e){return new Map([...e].map(([e,t])=>[e,new Set(t)]))}function cloneLicenseLedger(e){return{byOperator:cloneIndex(e.byOperator),byOwner:cloneIndex(e.byOwner),licenses:new Map([...e.licenses].map(([e,t])=>[e,{...t,operators:t.operators.map(e=>({...e}))}])),offerings:new Map([...e.offerings].map(([e,t])=>[e,{...t}]))}}function indexLicense(e,t,i){let a=e.get(t)??/* @__PURE__ */ new Set;a.add(i),e.set(t,a)}function unindexLicense(e,t,i){let a=e.get(t);a!==void 0&&(a.delete(i),a.size===0&&e.delete(t))}function applyLicenseOffering(e,t,i){return e.offerings.has(t.id)?`offering-exists`:(e.offerings.set(t.id,{cap:i.cap,capacity:i.capacity,createdAt:t.inscribedAt,id:t.id,issued:0,issuer:t.creator,name:i.name,renewal:i.renewal,term:i.term}),`offering-created`)}function applyLicenseIssue(e,t,i){if(e.licenses.has(t.id))return`license-exists`;let a=e.offerings.get(i.offering);return a===void 0?`unknown-offering`:t.creator===a.issuer?a.cap!==null&&a.issued>=a.cap?`cap-reached`:(a.issued+=1,e.licenses.set(t.id,{exp:a.term===null?null:i.nbf+a.term,id:t.id,issuedAt:t.inscribedAt,nbf:i.nbf,offering:a.id,operators:[],owner:t.owner,serial:i.serial}),indexLicense(e.byOwner,t.owner,t.id),`issued`):`not-issuer`}function reindexOperators(e,t,i){for(let i of t.operators)unindexLicense(e.byOperator,i.address,t.id);t.operators=i.map(e=>({...e}));for(let i of t.operators)indexLicense(e.byOperator,i.address,t.id)}function applyLicenseAssign(e,t,i){let a=e.licenses.get(t.license);if(a===void 0)return`unknown-license`;if(a.owner!==i)return`not-owner`;let u=e.offerings.get(a.offering);return u!==void 0&&t.operators.length>u.capacity?`over-capacity`:new Set(t.operators.map(e=>e.address)).size===t.operators.length?(reindexOperators(e,a,t.operators),`assigned`):`duplicate-operator`}function applyLicenseRenew(e,t,i,a){let u=e.licenses.get(t.license);if(u===void 0)return`unknown-license`;let p=e.offerings.get(u.offering);return p===void 0||p.term===null||u.exp===null?`perpetual`:p.renewal===`none`?`not-renewable`:i===(p.renewal===`owner`?u.owner:p.issuer)?(u.exp=Math.max(u.exp,a)+p.term,`renewed`):`not-authorized`}function onLicenseTransferred(e,t,i){let a=e.licenses.get(t);return a===void 0?`unknown-license`:(unindexLicense(e.byOwner,a.owner,a.id),a.owner=i,indexLicense(e.byOwner,i,a.id),reindexOperators(e,a,[]),`cleared`)}var Fde=/* @__PURE__ */ new Set([d8,p8,m8,g8,BP]),_8=class _LicenseLedgerFold{static schemas=Fde;_artifacts=createArtifactLedger();_bodies=/* @__PURE__ */ new Map;_dropped=[];_graceBlocks;_head;_licenses=createLicenseLedger();_window=[];constructor(e){if(!Number.isInteger(e.graceBlocks)||e.graceBlocks<0)throw Error(`LicenseLedgerFold: graceBlocks must be a non-negative integer, got ${e.graceBlocks}`);this._graceBlocks=e.graceBlocks}get artifacts(){return this._artifacts}get dropped(){return this._dropped}get head(){return this._head}get licenses(){return this._licenses}applyBlock(e,t=[]){let i=e[0].block;if(this._head!==void 0&&i!==this._head.block+1)throw Error(`LicenseLedgerFold: expected block ${this._head.block+1}, got ${i}`);this.learn(t);let a=collectSubstrateRefs(e,_LicenseLedgerFold.schemas);if(a.length>0){let e={before:this.snapshot(),height:i,refs:a};this._window.push(e),this.applyEntry(e)}return this._head={block:i,hash:e[0]._hash},this.prune(),this.pending()}bodies(){return[...this._bodies.values()]}hasBody(e){return this._bodies.has(e)}learn(e){let t;for(let i of e){if(this._bodies.has(i._hash))continue;this._bodies.set(i._hash,i);let e=this._window.findIndex(e=>e.refs.some(e=>e.hash===i._hash));e!==-1&&(t===void 0||e<t)&&(t=e)}return t!==void 0&&this.replayFrom(t),this.pending()}pending(){return this._window.flatMap(e=>e.refs.filter(e=>!this._bodies.has(e.hash)).map(t=>({...t,height:e.height})))}applyEntry(e){for(let t of e.refs)this.applyRef(t,e.height)}applyRef(e,t){e.isInscribeMarked&®isterArtifact(this._artifacts,e,t);let i=this._bodies.get(e.hash);if(i===void 0)return;let a=this._artifacts.artifacts.get(e.hash);switch(e.schema){case m8:a!==void 0&&Mde(i)&&applyLicenseOffering(this._licenses,a,i);break;case p8:a!==void 0&&Ade(i)&&applyLicenseIssue(this._licenses,a,i);break;case d8:Ode(i)&&applyLicenseAssign(this._licenses,i,e.signer);break;case g8:Pde(i)&&applyLicenseRenew(this._licenses,i,e.signer,t);break;case BP:UP(i)&&transferArtifact(this._artifacts,i,e.signer)===`transferred`&&onLicenseTransferred(this._licenses,i.inscriptionId,i.to)}}prune(){if(this._head===void 0)return;let e=this._head.block-this._graceBlocks;for(;this._window.length>0&&this._window[0]!==void 0&&this._window[0].height<e;){let[e]=this._window.splice(0,1);if(e===void 0)break;for(let t of e.refs)this._bodies.has(t.hash)||this._dropped.push({...t,height:e.height})}}replayFrom(e){let t=this._window[e];if(t!==void 0){this._artifacts=cloneArtifactLedger(t.before.artifacts),this._licenses=cloneLicenseLedger(t.before.licenses);for(let t of this._window.slice(e))t.before=this.snapshot(),this.applyEntry(t)}}snapshot(){return{artifacts:cloneArtifactLedger(this._artifacts),licenses:cloneLicenseLedger(this._licenses)}}},v8=`license/v1`;function licenseIndexHeadPath(){return`${v8}/head.json`}function licenseIndexSnapshotPath(e){return`${v8}/snapshots/${e}.json`}function licenseIndexBodyPath(e){return`${v8}/bodies/${e}.json`}var y8=Cs(`network.xyo.license.index.snapshot`,!0),b8=int$1().check(/* @__PURE__ */ _gte(0)),Ide=/* @__PURE__ */ object$5({cap:/* @__PURE__ */ nullable$2(int$1()),capacity:int$1(),createdAt:b8,id:po,issued:int$1(),issuer:us,name:/* @__PURE__ */ string$3(),renewal:h8,term:/* @__PURE__ */ nullable$2(int$1())}),Lde=/* @__PURE__ */ object$5({exp:/* @__PURE__ */ nullable$2(b8),id:po,issuedAt:b8,nbf:b8,offering:po,operators:/* @__PURE__ */ array$2(f8),owner:us,serial:int$1()}),Rde=/* @__PURE__ */ object$5({hash:po,height:b8,snapshot:po}),zde=/* @__PURE__ */ object$5({head:/* @__PURE__ */ object$5({block:b8,hash:po}),licenses:/* @__PURE__ */ array$2(Lde),offerings:/* @__PURE__ */ array$2(Ide),schema:/* @__PURE__ */ literal$2(y8)}),x8=zodIsFactory(Rde),Bde=zodIsFactory(zde),byId=(e,t)=>e.id.localeCompare(t.id);function snapshotFromLedger(e,t){return{head:{block:t.block,hash:t.hash},licenses:[...e.licenses.values()].toSorted(byId).map(e=>({...e,operators:e.operators.map(e=>({...e}))})),offerings:[...e.offerings.values()].toSorted(byId).map(e=>({...e})),schema:y8}}function ledgerFromSnapshot(e){let t=createLicenseLedger();for(let i of e.offerings)t.offerings.set(i.id,{...i});for(let i of e.licenses){let e={...i,operators:i.operators.map(e=>({...e}))};t.licenses.set(e.id,e),indexLicense(t.byOwner,e.owner,e.id);for(let i of e.operators)indexLicense(t.byOperator,i.address,e.id)}return t}async function snapshotFingerprint(e){return await al.dataHash({licenses:e.licenses,offerings:e.offerings,schema:e.schema})}async function publishedHead(e){let t=await e.readObject(licenseIndexHeadPath());if(t!==void 0){if(!x8(t))throw Error(`publishLicenseIndex: the published head at ${licenseIndexHeadPath()} does not parse`);return t}}async function writeBodies(e,t){let i=0;for(let a of t){let t=licenseIndexBodyPath(a._hash);await e.hasObject(t)||(await e.writeObject(t,a,!0),i+=1)}return i}async function publishLicenseIndex(e){let{head:t,ledger:i,store:a}=e,u=await publishedHead(a);if(u!==void 0&&u.height>t.block)return null;let p=await writeBodies(a,e.bodies??[]),y=snapshotFromLedger(i,t),x=await snapshotFingerprint(y),w=licenseIndexSnapshotPath(x),E=!await a.hasObject(w);E&&await a.writeObject(w,y,!0);let D={hash:t.hash,height:t.block,snapshot:x},A=u?.height!==D.height||u.hash!==D.hash||u.snapshot!==D.snapshot;return A&&await a.writeObject(licenseIndexHeadPath(),D,!1),!A&&!E&&p===0?null:{bodiesWritten:p,head:D,snapshotWritten:E}}var S8=`LicenseViewer`;function isLicenseViewer(e){let t=e;return typeof t?.sync==`function`&&typeof t.head==`function`&&typeof t.ledger==`function`&&typeof t.licensingOperatorAt==`function`}function isLicenseCurrentAt(e,t){return e.nbf<=t&&(e.exp===null||t<=e.exp)}function isOperatorActiveAt(e,t){return e.exp===void 0||t<=e.exp}function recordsFor(e,t){let i=[];for(let a of t??[]){let t=e.licenses.get(a);t!==void 0&&i.push(t)}return i}function licensesByOwner(e,t){return recordsFor(e,e.byOwner.get(t))}function licensesByOperator(e,t){return recordsFor(e,e.byOperator.get(t))}function isLicenseRecognized(e,t,i){let a=e.offerings.get(t.offering);return a!==void 0&&i.issuers.has(a.issuer)&&(i.offerings===void 0||i.offerings.has(a.id))}function licensingOperatorAt(e,t,i,a){return licensesByOperator(e,t).find(u=>isLicenseCurrentAt(u,i)&&isLicenseRecognized(e,u,a)&&u.operators.some(e=>e.address===t&&isOperatorActiveAt(e,i)))}var RestLicenseViewer=class extends AbstractRestReader{moniker=RestLicenseViewer.defaultMoniker;_head;_ledger=createLicenseLedger();_snapshot;get baseUrl(){let{config:e}=RestLicenseViewer.requireBoundConnection(this.config);if(e.type!==`rest`)throw Error(`Provider "${this.moniker}" requires a rest connection`);return e.baseUrl.replace(/\/+$/,``)}async createHandler(){await super.createHandler(),RestLicenseViewer.requireBoundConnection(this.config)}head(){return this._head}ledger(){return this._ledger}license(e){return this._ledger.licenses.get(e)}licensesByOperator(e){return licensesByOperator(this._ledger,e)}licensesByOwner(e){return licensesByOwner(this._ledger,e)}licensingOperatorAt(e,t,i){return licensingOperatorAt(this._ledger,e,t,i)}offering(e){return this._ledger.offerings.get(e)}async sync(){let e=await this.readJson(`${this.baseUrl}/${licenseIndexHeadPath()}`);if(!e.ok||!x8(e.data))return this._head;let t=e.data;if(t.snapshot!==this._snapshot){let e=await this.readJson(`${this.baseUrl}/${licenseIndexSnapshotPath(t.snapshot)}`);if(!e.ok||!Bde(e.data)||await snapshotFingerprint(e.data)!==t.snapshot)return this._head;this._ledger=ledgerFromSnapshot(e.data),this._snapshot=t.snapshot}return this._head={block:t.height,hash:t.hash},this._head}};u8(RestLicenseViewer,`connectionTypes`,[`rest`]),u8(RestLicenseViewer,`defaultMoniker`,S8),u8(RestLicenseViewer,`dependencies`,[]),u8(RestLicenseViewer,`monikers`,[S8]),u8(RestLicenseViewer,`providerId`,`RestLicenseViewer`),u8(RestLicenseViewer,`surface`,`node`),RestLicenseViewer=l8([creatableProvider()],RestLicenseViewer);var Vde=100;function continuingRun$1(e,t){let i=[];for(let a of t.toSorted((e,t)=>e[0].block-t[0].block)){let t=a[0].block,u=e+i.length;if(!(t<u)){if(t>u)break;i.push(a)}}return i}__name(continuingRun$1,`continuingRun`);var LicenseLedgerSync=class{fold;_floorBlock;_inFlight;_isCatchingUp=!1;_pageSize;_pagesPerPass;_sources;constructor(e,t){this._sources=e,this._floorBlock=Math.max(0,Math.floor(t.floorBlock)),this._pageSize=Math.max(1,Math.floor(t.pageSize??Vde)),this._pagesPerPass=Math.max(1,Math.floor(t.pagesPerPass??5)),this.fold=new _8({graceBlocks:t.graceBlocks})}async sync(e){let t=this._inFlight;if(t!==void 0)return await t;let i=this.run(Math.max(1,Math.floor(e?.maxPages??this._pagesPerPass)));this._inFlight=i;try{return await i}finally{this._inFlight=void 0}}async fetch(e){let t=[...new Set(e)].filter(e=>!this.fold.hasBody(e)),i=this._sources.bodies;if(i===void 0||t.length===0)return[];let a=(await i.get(t)).filter(e=>Gs(e));return await al.addHashMeta(a)}async foldBlock(e){let t=collectSubstrateRefs(e,_8.schemas),i=await this.fetch(t.map(e=>e.hash));this.fold.applyBlock(e,i)}async retryPending(){let e=this.fold.pending();e.length!==0&&this.fold.learn(await this.fetch(e.map(e=>e.hash)))}async run(e){let t=(await this._sources.blockViewer.currentBlock())[0].block;await this.retryPending();let i=this.fold.head===void 0?this._floorBlock:this.fold.head.block+1;for(let a=0;a<e&&i<=t;a++){let e=Math.min(i+this._pageSize-1,t),a=await this._sources.blockViewer.blocksByNumber(rP(e,!0),e-i+1),u=continuingRun$1(i,a);if(u.length===0){this._sources.logger?.warn(`LicenseLedgerSync: no blocks returned for ${i}..${e}; stopping this pass`);break}for(let e of u)await this.foldBlock(e);if(i+=u.length,i<=e)break}let a=this.fold.head;return a!==void 0&&a.block<t?(this._isCatchingUp=!0,this._sources.logger?.info(`LicenseLedgerSync: ledger folded to block ${a.block}, catching up to ${t}`)):this._isCatchingUp&&(this._isCatchingUp=!1,this._sources.logger?.info(`LicenseLedgerSync: ledger caught up at block ${t}`)),a}},Hde=object$3({floorBlock:number$1().int().nonnegative().default(0),graceBlocks:number$1().int().nonnegative().default(100),pageSize:number$1().int().positive().optional(),pagesPerPass:number$1().int().positive().default(5)}),SimpleLicenseViewer=class extends AbstractCreatableProvider{moniker=SimpleLicenseViewer.defaultMoniker;_options;_sync;get ledgerSync(){return assertEx$1(this._sync,()=>`SimpleLicenseViewer: not created`)}get options(){return this._options??=Hde.parse(this.config.options??{}),this._options}bodies(){return this.ledgerSync.fold.bodies()}async createHandler(){await super.createHandler();let e=await this.locator.getInstance(Hz),t=await this.locator.tryGetInstance(ZR);t===void 0&&this.logger?.warn(`SimpleLicenseViewer: no DataLakeViewer is bound — no body is findable, so no license will ever be usable; bind a rest-datalake connection`);let{floorBlock:i,graceBlocks:a,pageSize:u,pagesPerPass:p}=this.options;this._sync=new LicenseLedgerSync({blockViewer:e,bodies:t,logger:this.logger},{floorBlock:i,graceBlocks:a,pageSize:u,pagesPerPass:p})}head(){return this.ledgerSync.fold.head}ledger(){return this.ledgerSync.fold.licenses}license(e){return this.ledgerSync.fold.licenses.licenses.get(e)}licensesByOperator(e){return licensesByOperator(this.ledgerSync.fold.licenses,e)}licensesByOwner(e){return licensesByOwner(this.ledgerSync.fold.licenses,e)}licensingOperatorAt(e,t,i){return licensingOperatorAt(this.ledgerSync.fold.licenses,e,t,i)}offering(e){return this.ledgerSync.fold.licenses.offerings.get(e)}async sync(e){return await this.ledgerSync.sync(e)}};u8(SimpleLicenseViewer,`connectionTypes`,[`none`]),u8(SimpleLicenseViewer,`defaultMoniker`,S8),u8(SimpleLicenseViewer,`dependencies`,[Hz]),u8(SimpleLicenseViewer,`monikers`,[S8]),u8(SimpleLicenseViewer,`providerId`,`SimpleLicenseViewer`),u8(SimpleLicenseViewer,`surface`,`node`),SimpleLicenseViewer=l8([creatableProvider()],SimpleLicenseViewer);function findElevatingTransaction(e,[,t]){let i=`${iR}|${e._hash}`;return t.filter(e=>TP(e)).find(t=>t.payload_hashes.includes(e._hash)&&t.script?.includes(i)===!0)}async function validateSlashPayloadInBlock(e,t,i,a,u,p){let y=i[0].block,x=await resolveRuleParams(e,y),w=requireRuleActive(x,`slash-payloads`,y,p);if(w!==void 0)return{errors:[Error(w)],params:x};if(!a(t)||!Rs(t))return{errors:[/* @__PURE__ */ Error(`${p} failed its identity check`)],params:x};let E=findElevatingTransaction(t,i);return E===void 0?{errors:[/* @__PURE__ */ Error(`${p} must be elevated from a transaction`)],params:x}:u(t)===E.from?{errors:[],params:x,transaction:E}:{errors:[/* @__PURE__ */ Error(`${p} from must equal elevating transaction from`)],params:x}}function validateStrictClaimFields(e){let t=Object.keys(e).filter(e=>!C8.has(e)).map(e=>`Unknown Claim field ${e}`),i=`$sources`in e?e.$sources:void 0;if(i!==void 0){if(Array.isArray(i))for(let[e,a]of i.entries())typeof a==`string`&&fo.test(a)||t.push(`Claim $sources/${e} must be a hash`);else t.push(`Claim $sources must be an array of hashes`)}return t}function claimError(e,t,i,a){return new InBlockPayloadValidationError(e._hash??t[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,e,i,a)}function indexesOf(e,t){let i=[];for(let[a,u]of e.entries())u===t&&i.push(a);return i}function validateClaimSchemaPairs(e,t,i){let a=i??t[0],u=i===void 0?`Block`:`Transaction ${i._hash}`,p=indexesOf(a.payload_hashes,e._hash);return p.length===0?[claimError(e,t,`${u} does not commit Claim root hash ${e._hash}`)]:p.some(e=>a.payload_schemas[e]!==vF)?[claimError(e,t,`${u} does not pair every Claim root hash with ${vF}`)]:[]}function claimElevationAttempts(e,[,t]){let i=`${iR}|${e._hash}`,a=`${i}|`;return t.filter(e=>TP(e)).flatMap(e=>{let t=e.script??[],u=t.filter(e=>e===i).length,p=t.filter(e=>e.startsWith(a));return u===0&&p.length===0?[]:{malformedOperations:p,transaction:e,validOperationCount:u}})}function validateElevatingTransaction(e,t,i,a){let u=[],{malformedOperations:p,transaction:y,validOperationCount:x}=a;if(p.length>0&&u.push(claimError(t,i,`Transaction ${y._hash} contains malformed Claim elevation operations: ${p.join(`, `)}`)),x>1&&u.push(claimError(t,i,`Transaction ${y._hash} contains duplicate Claim elevation operations`)),x!==1)return u;u.push(...validateClaimSchemaPairs(t,i,y)),y.addresses.includes(e.source)||u.push(claimError(t,i,`Claim source ${e.source} is not a signer of transaction ${y._hash}`));let w=new Set(y.payload_hashes),E=e.hashes.filter(e=>!w.has(e));return E.length>0&&u.push(claimError(t,i,`Transaction ${y._hash} does not commit every Claim hash: ${E.join(`, `)}`)),u}function toAmount(e){return BigInt(e.startsWith(`0x`)?e:`0x${e}`)}function isDepositRequired(e,t){return isRuleActiveAt(e,`eligibility-admission`,t)&&!isRuleActiveAt(e,`invalid-slash-request.adjudicable`,t)}function depositedInTransaction(e,t,i){let a=derivedReceiveAddress(e.from,`slash-deposit`),u=new Set(t.payload_hashes);return i.filter(e=>u.has(e._hash)).filter(e=>TI(e)).reduce((e,t)=>e+toAmount(t.transfers[a]??`0x0`),0n)}async function carriedArtifactHashes(e,t){let i=new Set(e.payload_hashes),a=t.filter(e=>i.has(e._hash)).filter(e=>rI(e)).flatMap(e=>e.artifacts);return new Set(await Promise.all(a.map(e=>al.dataHash(e))))}async function evidenceResolutionErrors(e,t,i,a){let u=t.evidence.filter(e=>!i.has(e));if(u.length===0)return[];let p=e.hasFinalizedEvidenceArtifact;return p===void 0?[`evidence resolver unavailable: cannot certify a block whose evidence it cannot check`]:(await Promise.all(u.map(async e=>({found:await p(e,a),hash:e})))).filter(({found:e})=>!e).map(({hash:e})=>`unresolvable evidence artifact ${e}`)}function isOffenseReportable(e,t){return isRuleObservedAt(e,reportableRuleId(t.offense),t.block)}function TransactionTransfersInBlockValidatorFactory(e){return async(t,i)=>{let[a,u]=i,p=[];try{for(let y of u)if(CP(y)&&Rs(y)){let x=await e({...t,chainId:a.chain},[y,u]);for(let e of x)p.push(new HydratedBlockValidationError(y._hash,i,`transfer authorization error: ${e}`,e))}}catch(e){p.push(new HydratedBlockValidationError(a?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,`Failed TransactionTransfersInBlockValidator: ${String(e)}`,e))}return p}}function offendingTransactionHashesForAddress(e,t){let i=[];for(let a of e[1])MP(a)&&a.from===t&&i.push(a._hash);return i}async function balanceShortfallErrors(e,t,i){let a=[],u=Object.keys(i);if(u.length===0)return a;let[p]=await e.blockViewer.currentBlock(),y=await e.accountBalanceViewer.accountBalances(u,{head:p._hash});for(let e of u){let u=e,p=i[u],x=y[u]??uP(0n);e!==`0000000000000000000000000000000000000000`&&p>x&&a.push(new HydratedTransactionValidationError(t?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`insufficient balance for ${e} ${x} < ${p}`))}return a}var BlockAllowedPayloadSchemasValidator,error,checkSignaturesShape,BlockBoundWitnessValidator,BlockFieldsValidator,BlockPreviousHashValidator,validateBlock,isElevatedFromBlock,validateElevatedFromBlock,validateElevatedFromTransaction,validateTransactionInBlock,validateTypedPayloadInBlock,validateBridgeDestinationObservationInBlock,validateBridgeIntentInBlock,validateBridgeSourceObservationInBlock,validateChainStakeIntentInBlock,C8,validateClaimInBlock,validateHashInBlock,validateSchemaInBlock,validateSlashAdjudicationInBlock,validateSlashChallengeInBlock,validateSlashCommitInBlock,validateSlashEvidenceInBlock,validateSlashRequestInBlock,validateTimeInBlock,validateTransferInBlock,w8,validatePayloadInBlock,PayloadsInBlockValidator,validateHydratedBlock,RequiredBalanceBlockStateValidator,validateHydratedBlockState,RequiredBalanceTransactionStateValidator,validateHydratedTransactionState,T8=__esmMin((()=>{Uo(),_Z(),hM(),BlockAllowedPayloadSchemasValidator=(e,t)=>{let i=[];try{for(let e of t.payload_schemas)OI(e)||i.push(new BlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`payload schema not allowed in block: ${String(e)}`))}catch(e){i.push(new BlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`validation excepted: ${String(e)}`,e))}return i},error=(e,t)=>new BlockValidationError(e?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,e,t),checkSignaturesShape=e=>{let t=e;return t.$signatures===void 0?[error(e,Array.isArray(t.signatures)?"BoundWitness has `signatures` but expected `$signatures` (signatures must be in the meta-prefixed `$signatures` key)":"BoundWitness is missing `$signatures`")]:[]},BlockBoundWitnessValidator=async(e,t)=>{try{let e=checkSignaturesShape(t);return e.length>0?e:(await new jw(t).validate()).map(e=>error(t,`BoundWitness validation: ${e.message}`))}catch(e){return[error(t,`Failed BlockBoundWitnessValidator: ${String(e)}`)]}},BlockFieldsValidator=(e,t,i)=>{let a=[];try{isDefined$1(i)&&t.chain!==i.toLowerCase()&&a.push(new BlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`Invalid chain id`));let e=[];for(let i=0;i<t.payload_hashes.length;i++)t.payload_schemas[i]===sw&&e.push(t.payload_hashes[i]);new Set(e).size<e.length&&a.push(new BlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`Duplicate Transaction Hashes: ${e.join(`, `)}`))}catch(e){a.push(new BlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`validation excepted: ${String(e)}`,e))}return a},BlockPreviousHashValidator=(e,t)=>{let i=[];try{let e=t.block;e>0n?isHash(t.previous)||i.push(new BlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`previous hash is missing or invalid`)):e===0?t.previous!==null&&i.push(new BlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`previous hash should not be set`)):i.push(new BlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`invalid block number`))}catch(e){let a=new BlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`Failed BlockPreviousHashValidator: ${String(e)}`);a.cause=e,i.push(a)}return i},validateBlock=async(e,t,i,a=[])=>{let u=[];try{let p=[BlockBoundWitnessValidator,BlockFieldsValidator,BlockPreviousHashValidator,BlockAllowedPayloadSchemasValidator,...a];for(let a of p)u.push(...await Promise.resolve(a(e,t,i)))}catch(e){u.push(new BlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`validation excepted`,e))}return u},isElevatedFromBlock=(e,[,t])=>{let i=t.filter(e=>CP(e));for(let t of i)if(t.payload_hashes.includes(e._hash))return!1;return!0},validateElevatedFromBlock=(e,t,i)=>{let a=[];try{let e=transactionsFromHydratedBlock(i);new Set(e.flatMap(e=>e.payload_hashes)).has(t._hash)&&a.push(new InBlockPayloadValidationError(i[0]?._hash,i,t,`Transaction may not include block payload hash [${t.schema}]: ${t._hash}`))}catch(e){a.push(new InBlockPayloadValidationError(i[0]?._hash,i,t,`validation excepted: ${String(e)}`,e))}return a},validateElevatedFromTransaction=(e,t,i)=>{let a=[];try{let e=transactionsFromHydratedBlock(i);e.length>0?e.flatMap(e=>e.payload_hashes).includes(t._hash)||a.push(new InBlockPayloadValidationError(t._hash,i,t,`Transaction does not include payload`)):a.push(new InBlockPayloadValidationError(t._hash,i,t,`No Transactions in block`))}catch(e){a.push(new InBlockPayloadValidationError(t._hash,i,t,`Failed validateElevatedFromTransaction: ${String(e)}`,e))}return a},validateTransactionInBlock=async(e,t,i)=>{let a=[];try{if(CP(t)&&Rs(t)){let u=[...new Set(t.payload_hashes)].flatMap(e=>{let t=i[1].find(t=>Rs(t)&&(t._hash===e||t._dataHash===e));return t===void 0?[]:[t]}),p=await validateTransaction({...e,chainId:i[0].chain},[t,u]);for(let e of p)a.push(new InBlockPayloadValidationError(t._hash,i,t,`TransactionValidation error: ${e}`,e));let y=await BoundWitnessSignaturesValidator(t);for(let e of y)a.push(new InBlockPayloadValidationError(t._hash,i,t,`BoundWitnessSignaturesValidator error: ${e}`,e))}else a.push(new InBlockPayloadValidationError(t._hash,i,t,`Payload failed isTransactionBoundWitness or isHashMeta`))}catch(e){a.push(new InBlockPayloadValidationError(t._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`validation excepted: ${String(e)}`,e))}return a},validateTypedPayloadInBlock=async(e,t,i,a)=>{let u=[];try{a(t)&&Rs(t)?isElevatedFromBlock(t,i)?u.push(...await validateElevatedFromBlock(e,t,i)):u.push(...await validateElevatedFromTransaction(e,t,i)):u.push(/* @__PURE__ */ Error(`Payload failed identityFunction or isElevated or isStorageMeta`))}catch(e){u.push(/* @__PURE__ */ Error(`Failed validateTypedPayloadInBlock: ${String(e)}`))}return u},validateBridgeDestinationObservationInBlock=async(e,t,i)=>{let a=[];try{let u=await validateTypedPayloadInBlock(e,t,i,iF);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,`validateTypedPayloadInBlock error: ${e}`,e))}catch(e){a.push(new InBlockPayloadValidationError(i?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`Failed validateBridgeObservationInBlock: ${String(e)}`,e))}return a},validateBridgeIntentInBlock=async(e,t,i)=>{let a=[];try{let u=await validateTypedPayloadInBlock(e,t,i,cF);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,`validateTypedPayloadInBlock error: ${e}`,e))}catch(e){a.push(new InBlockPayloadValidationError(i?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`Failed validateBridgeIntentInBlock: ${String(e)}`,e))}return a},validateBridgeSourceObservationInBlock=async(e,t,i)=>{let a=[];try{let u=await validateTypedPayloadInBlock(e,t,i,pF);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,`validateTypedPayloadInBlock error: ${e}`,e))}catch(e){a.push(new InBlockPayloadValidationError(i?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`Failed validateBridgeObservationInBlock: ${String(e)}`,e))}return a},validateChainStakeIntentInBlock=async(e,t,i)=>{let a=[];try{let u=await validateTypedPayloadInBlock(e,t,i,_F);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,`validateTypedPayloadInBlock error: ${e}`,e))}catch(e){a.push(new InBlockPayloadValidationError(i[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`validation excepted: ${String(e)}`,e))}return a},C8=/* @__PURE__ */ new Set([`schema`,`hashes`,`source`,`subject`,`$version`,`$sources`]),validateClaimInBlock=async(e,t,i)=>{try{let e=al.omitStorageMeta(t);if(e.schema!==vF||!SF(e))return[claimError(t,i,`Claim failed its complete payload identity check`)];let a=validateStrictClaimFields(e);if(a.length>0)return[claimError(t,i,`Claim failed strict payload validation: ${a.join(`; `)}`,a)];let u=await al.hash(e);if(u!==t._hash)return[claimError(t,i,`Claim canonical root hash ${u} does not match asserted hash ${t._hash}`)];let p=validateClaimSchemaPairs(t,i),y=claimElevationAttempts(t,i),x=y.filter(e=>e.validOperationCount>0);for(let a of y)p.push(...validateElevatingTransaction(e,t,i,a));return x.length===0&&p.push(claimError(t,i,`Claim must be elevated from a transaction with an exact elevate operation`)),p}catch(e){return[claimError(t,i,`Failed validateClaimInBlock: ${String(e)}`,e)]}},validateHashInBlock=async(e,t,i)=>{let a=[];try{let u=await validateTypedPayloadInBlock(e,t,i,EF);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,`validateTypedPayloadInBlock error: ${e}`,e))}catch(e){a.push(new InBlockPayloadValidationError(i?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`validation excepted: ${String(e)}`,e))}return a},validateSchemaInBlock=async(e,t,i)=>{let a=[];try{let u=await validateTypedPayloadInBlock(e,t,i,JC);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,`validateTypedPayloadInBlock error: ${e}`,e))}catch(e){a.push(new InBlockPayloadValidationError(i?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`Failed validateSchemaInBlock: ${String(e)}`,e))}return a},validateSlashAdjudicationInBlock=async(e,t,i)=>{let a=[];try{let{errors:u,params:p}=await validateSlashPayloadInBlock(e,t,i,GF,e=>e.from,`slash adjudication`);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,e.message,e));u.length===0&&GF(t)&&(p?.arbiter===void 0||t.from!==p.arbiter)&&a.push(new InBlockPayloadValidationError(t._hash,i,t,`slash adjudication from must equal the register arbiter`))}catch(e){a.push(new InBlockPayloadValidationError(i[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`validation excepted: ${String(e)}`,e))}return a},validateSlashChallengeInBlock=async(e,t,i)=>{let a=[];try{let{errors:u}=await validateSlashPayloadInBlock(e,t,i,YF,e=>e.from,`slash challenge`);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,e.message,e))}catch(e){a.push(new InBlockPayloadValidationError(i[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`validation excepted: ${String(e)}`,e))}return a},validateSlashCommitInBlock=async(e,t,i)=>{let a=[];try{let{errors:u,params:p,transaction:y}=await validateSlashPayloadInBlock(e,t,i,$F,e=>e.from,`slash commit`);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,e.message,e));if(u.length>0||p===void 0||y===void 0||!$F(t))return a;if(isDepositRequired(p,i[0].block)){let e=toAmount(p.reporterDepositAtto??`0x0`),u=depositedInTransaction(t,y,i[1]);u<e&&a.push(new InBlockPayloadValidationError(t._hash,i,t,`slash commit escrows ${u} but the register requires ${e}`))}}catch(e){a.push(new InBlockPayloadValidationError(i[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`validation excepted: ${String(e)}`,e))}return a},validateSlashEvidenceInBlock=async(e,t,i)=>{let a=[];try{let{errors:u}=await validateSlashPayloadInBlock(e,t,i,rI,e=>e.from,`slash evidence`);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,e.message,e))}catch(e){a.push(new InBlockPayloadValidationError(i[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`validation excepted: ${String(e)}`,e))}return a},validateSlashRequestInBlock=async(e,t,i)=>{let a=[],fail=e=>{a.push(new InBlockPayloadValidationError(t._hash,i,t,e))};try{let{errors:u,params:p,transaction:y}=await validateSlashPayloadInBlock(e,t,i,lI,e=>e.from,`slash request`);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,e.message,e));if(u.length>0||p===void 0||y===void 0||!lI(t))return a;isOffenseReportable(p,t)||fail(`offense '${t.offense}' was not reportable at block ${t.block}`);let x=await carriedArtifactHashes(y,i[1]);for(let a of await evidenceResolutionErrors(e,t,x,i[0].block))fail(a)}catch(e){a.push(new InBlockPayloadValidationError(i[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`validation excepted: ${String(e)}`,e))}return a},validateTimeInBlock=async(e,t,i)=>{let a=[];try{let u=await validateTypedPayloadInBlock(e,t,i,RF);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,`validateTypedPayloadInBlock error: ${e}`,e))}catch(e){a.push(new InBlockPayloadValidationError(i?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`Failed validateTimeInBlock: ${String(e)}`,e))}return a},validateTransferInBlock=async(e,t,i)=>{let a=[];try{let u=await validateTypedPayloadInBlock(e,t,i,TI);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,`validateTypedPayloadInBlock error: ${e}`,e))}catch(e){a.push(new InBlockPayloadValidationError(i?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`Failed validateTransferInBlock: ${String(e)}`,e))}return a},w8={[sw]:validateTransactionInBlock,[tF]:validateBridgeDestinationObservationInBlock,[aF]:validateBridgeIntentInBlock,[uF]:validateBridgeSourceObservationInBlock,[mF]:validateChainStakeIntentInBlock,[vF]:validateClaimInBlock,[CF]:validateHashInBlock,[WC]:validateSchemaInBlock,[HF]:validateSlashAdjudicationInBlock,[KF]:validateSlashChallengeInBlock,[XF]:validateSlashCommitInBlock,[eI]:validateSlashEvidenceInBlock,[oI]:validateSlashRequestInBlock,[jF]:validateTimeInBlock,[SI]:validateTransferInBlock},validatePayloadInBlock=async(e,t,i)=>{let a=[];try{let u=w8[t.schema];u?a.push(...await u(e,t,i)):a.push(new InBlockPayloadValidationError(i?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`Unsupported payload schema: ${t.schema}`))}catch(e){let u=new InBlockPayloadValidationError(i?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`validation excepted: ${String(e)}`,e);a.push(u)}return a},PayloadsInBlockValidator=async(e,[t,i])=>{let a=[];try{let u={};for(let e of i){let t=e._hash;u[t]=e}let p={...u};for(let y=0;y<t.payload_hashes.length;y++){let x=t.payload_hashes[y],w=t.payload_schemas[y],E=u[x];if(E){let u=await validatePayloadInBlock(e,E,[t,i]);for(let e of u)a.push(new HydratedBlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,[t,i],`validatePayloadInBlock error: ${e}`,e));delete p[x]}else a.push(new HydratedBlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,[t,i],`missing payload ${x} ${w}`))}Object.keys(p).length>0&&a.push(new HydratedBlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,[t,i],`extra payloads ${Object.keys(u).join(`, `)}`))}catch(e){a.push(new HydratedBlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,[t,i],`Failed PayloadsInBlockValidator: ${String(e)}`,e))}return a},validateHydratedBlock=async(e,t,i,a=[],u=[])=>{let p=[];try{let y=await validateBlock(e,t[0],i?await i(t[0].block):void 0,u);for(let e of y)p.push(new HydratedBlockValidationError(t[0]._hash,t,`validateBlock error: ${e}`,e));let x=await BoundWitnessReferencesValidator()(t);for(let e of x)p.push(new HydratedBlockValidationError(t[0]._hash,t,`boundwitness reference error: ${e}`,e));let w=[PayloadsInBlockValidator,...a];for(let a of w)p.push(...await Promise.resolve(a(e,t,i)))}catch(e){p.push(new HydratedBlockValidationError(t?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`Failed validateHydratedBlock: ${String(e)}`,e))}return p},RequiredBalanceBlockStateValidator=async(e,t)=>await spanRootAsync(`RequiredBalanceBlockStateValidator`,async()=>{let i=[],a=`00`;try{let u=netBalancesForPayloads({singletons:{}},t[1]),p=Object.keys(u),y={};for(let e of p){let t=e,i=u[t];i<0n&&(y[t]=-i)}let x=t[0].previous;if(x===null)return[new HydratedBlockStateValidationError(t?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,`00`,t,`Insufficient funds because first block`)];a=await e.chainIdAtBlockNumber(t[0].block),await spanRootAsync(`RequiredBalanceBlockStateValidator|balancesLoop`,async()=>{let u=Object.keys(y);if(u.length===0)return;let p=await e.accountBalance.accountBalances(u,{head:x});for(let e of u){let u=y[e],x=p[e]??uP(0n);if(e!==`0000000000000000000000000000000000000000`&&u>x){let p=offendingTransactionHashesForAddress(t,e);i.push(new HydratedBlockStateValidationError(t?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,a,t,`insufficient balance for ${e} ${x} < ${u}`,void 0,p.length>0?p:void 0))}}},e)}catch(e){i.push(new HydratedBlockStateValidationError(t?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,a,t,`Failed RequiredBalanceBlockStateValidator: ${String(e)}`,e))}return i},e),validateHydratedBlockState=async(e,t,i=[])=>await spanRootAsync(`validateHydratedBlockState`,async()=>{let a=[],u;try{u=await e.chainIdAtBlockNumber(t[0].block);let p=await validateHydratedBlock(e,t,e.chainIdAtBlockNumber);for(let e of p)a.push(new HydratedBlockStateValidationError(t[0]._hash,u,t,`validateBlock error: ${e}`,e));let y=[RequiredBalanceBlockStateValidator,...i];for(let i of y)a.push(...await Promise.resolve(i(e,t)))}catch(e){a.push(new HydratedBlockStateValidationError(t?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,u??`00`,t,`Failed validateHydratedBlockState: ${String(e)}`,e))}return a},e),RequiredBalanceTransactionStateValidator=async(e,t)=>await spanRootAsync(`RequiredBalanceTransactionStateValidator`,async()=>{let i=[];try{let a=netBalancesForPayloads({singletons:{}},t[1]),u=await gZ.parse(t),p=u.boundWitness.from,y=transactionRequiredGas(t);u.fees.gasLimit<y&&i.push(new HydratedTransactionValidationError(t?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`fees.gasLimit ${u.fees.gasLimit} < required gas ${y}`));let x=u.fees.base,w=u.fees.priority,E=u.fees.gasLimit,D=p;a[D]=(a[D]??0n)-x-w-E;let A={};for(let[e,t]of Object.entries(a)){let i=e;t<0n&&(A[i]=-t)}i.push(...await balanceShortfallErrors(e,t,A))}catch(e){i.push(new HydratedTransactionValidationError(t?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`Failed RequiredBalanceTransactionStateValidator: ${String(e)}`,e))}return i},e),validateHydratedTransactionState=async(e,t)=>await spanRootAsync(`validateHydratedTransactionState`,async()=>{let i=[];try{let a=[RequiredBalanceTransactionStateValidator];for(let u of a)i.push(...await Promise.resolve(u(e,t)))}catch(e){i.push(new HydratedTransactionValidationError(t?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`Failed validateHydratedTransactionState: ${String(e)}`,e))}return i},e)}));_Z(),hM(),Uo(),T8();function competes(e,t){return e.dataHash!==t.dataHash&&(e.block===t.block||e.previous===t.previous)}function linked(e,t){return e.supersedes===t.dataHash||t.supersedes===e.dataHash}function findCandidatePairs(e){let t=/* @__PURE__ */ new Map;for(let i of e){let e=t.get(i.producer)??[];e.every(e=>e.dataHash!==i.dataHash)&&e.push(i),t.set(i.producer,e)}let i=[];for(let[e,a]of t)for(let[t,u]of a.entries())for(let p of a.slice(t+1))competes(u,p)&&!linked(u,p)&&i.push({block:Math.max(u.block,p.block),first:u,producer:e,second:p});return i}function isOffenseWatchable(e,t,i){return isOffenseReportableAt(e,t,i)&&(t!==`equivocation`||isRuleObservedAt(e,`supersedes-field`,i))}async function suppressionFor(e,t){return await e.adjudicationByKey(t)===void 0?(await e.requestsByKey(t)).length>0?`already-reported`:void 0:`adjudicated`}async function evaluateProducerEligibility(e){let{accused:t,blockAnchor:i,height:a,intent:u,params:p,parentAnchor:y,snapshot:x}=e;if(i===void 0||y===void 0)return{resolvable:!1};if(x===void 0)return{eStar:evaluationPoint(y,i,p.freshnessBandEvmBlocks),resolvable:!1};let w=evaluationPoint(y,i,p.freshnessBandEvmBlocks),E=p.minStakeAgeEvmBlocks,[D,A,N,P]=await Promise.all([x.seasonedActiveByStakedAt(t,w,E),x.seasonedSelfBondAt(t,w,E),x.activeByStakedAt(t,w),u(t,a)]);if(P===void 0)return{activeStake:D,eStar:w,resolvable:!1,selfBond:A};let F=producerIneligibility({active:N,seasonedActive:D,seasonedSelfBond:A},{minSelfBond:hexAtto(p.minProducerSelfBondAtto),minStake:hexAtto(p.minProducerStakeAtto)},P);return{activeStake:D,eStar:w,eligible:F===null,intentValid:P,reason:F??void 0,resolvable:!0,selfBond:A}}function hexAtto(e){return e===``?0n:BigInt(e.startsWith(`0x`)?e:`0x${e}`)}function offenseKeyOf(e){return{accused:e.accused,block:e.block,chain:e.chain,offense:e.offense}}function offenseKeyString(e){return`${e.chain}|${e.accused}|${e.offense}|${e.block}`}var emptyDelta=()=>({accused:/* @__PURE__ */ new Map,keys:/* @__PURE__ */ new Map,pending:[],records:[]}),recordAt=(e,t)=>({immutable:!0,path:e,value:t});function foldSlashIndex(e){let t=emptyDelta(),i=/* @__PURE__ */ new Map;for(let[,a]of e)for(let e of a)foldPayload(t,i,e);return t}function keyPathFor(e,t){let i=offenseKeyOf(t),a=slashIndexKeyPath(i.accused,i.offense,i.block);if(!e.keys.has(a)){e.keys.set(a,{accused:i.accused,block:i.block,challenges:[],chain:i.chain,offense:i.offense,requests:[],schema:tH});let t=slashIndexAccusedPath(i.accused);e.accused.set(t,[...e.accused.get(t)??[],offenseKeyString(i)])}return a}function foldPayload(e,t,i){if(lI(i)){e.records.push(recordAt(slashIndexRequestPath(i._dataHash),i));let a=keyPathFor(e,i);t.set(i._dataHash,a);let u=e.keys.get(a);u!==void 0&&!u.requests.includes(i._dataHash)&&u.requests.push(i._dataHash);return}if($F(i)){e.records.push(recordAt(slashIndexCommitPath(i._dataHash),i));return}if(YF(i)){e.records.push(recordAt(slashIndexChallengePath(i._dataHash),i)),linkToRequest(e,t,{hash:i._dataHash,kind:`challenge`,request:i.request});return}if(!GF(i))return;e.records.push(recordAt(slashIndexAdjudicationPath(i._dataHash),i));let a=linkToRequest(e,t,{hash:i._dataHash,kind:`adjudication`,outcome:i.outcome,request:i.request}),u=a===void 0?void 0:e.keys.get(a);u!==void 0&&u.adjudication===void 0&&(u.adjudication=i._dataHash,u.outcome=i.outcome)}function linkToRequest(e,t,i){let a=t.get(i.request),u=e.pending.some(e=>e.kind===`adjudication`);if(a===void 0||i.kind===`adjudication`&&u)e.pending.push(i);else{if(i.kind===`challenge`){let t=e.keys.get(a);t!==void 0&&!t.challenges.includes(i.hash)&&t.challenges.push(i.hash)}return a}}function mergeKeyRecord(e,t){if(e===void 0)return t;let union=(e,t)=>[.../* @__PURE__ */ new Set([...e,...t])],i=e.adjudication===void 0?t:e;return{...e,...t,adjudication:i.adjudication,challenges:union(e.challenges,t.challenges),outcome:i.outcome,requests:union(e.requests,t.requests)}}var E8=`SlashIndexStore`;function isSlashIndexStore(e){let t=e;return typeof t?.readObject==`function`&&typeof t.hasObject==`function`&&typeof t.writeObject==`function`}function verdict(e,t,i={},a){return a===void 0?{outcome:e,reason:t,transcript:i}:{outcome:e,provisional:a,reason:t,transcript:i}}async function verifyArtifacts(e,t){let i=/* @__PURE__ */ new Map;for(let a of t){let t=e.get(a);if(t===void 0)return{missing:!0,ok:!1,reason:`cited artifact ${a} is not available to this verifier`};let u=t,p=await al.dataHash(u);if(p!==a)return{ok:!1,reason:`artifact cited as ${a} hashes to ${p}`};if(vw(u)&&(await BoundWitnessSignaturesValidator(u)).length>0)return{ok:!1,reason:`artifact ${p} carries an invalid signature`};i.set(p,{dataHash:p,payload:u,storageHash:await al.hash(u)})}return{byHash:i,ok:!0}}async function referencesArtifact(e,t){return e==null?!1:e===t.dataHash||e===(t.storageHash??await al.hash(t.payload))}async function freshnessGate(e,t){let i=await e.chain.validatedAnchorAt(t.block);if(i===void 0)return{reason:`no anchor resolvable at the offense height`,verdict:verdict(`indeterminate`,`no anchor resolvable at the offense height`)};let a=e.submission.commitCarryingHeight??e.submission.requestCarryingHeight,u=await e.chain.validatedAnchorAt(a);if(u===void 0)return{eOff:i,reason:`no anchor resolvable at the submission height`,verdict:verdict(`indeterminate`,`no anchor resolvable at the submission height`)};let p=u-i;if(p>e.params.evidenceFreshnessEvmBlocks){let t=`offense is ${p} EVM blocks old, past the ${e.params.evidenceFreshnessEvmBlocks} limit`;return{eOff:i,eSub:u,reason:t,verdict:verdict(`provably-invalid`,t,{age:p,eOff:i,eSub:u})}}return{eOff:i,eSub:u,reason:`offense is ${p} EVM blocks old`}}var asCitedBlock=e=>{let t=NI(e.payload);return t===void 0?void 0:{block:t,dataHash:e.dataHash}},verifyEquivocation=async(e,t,i)=>{let a=Array.from(i.values());if(a.length!==2)return verdict(`provably-invalid`,`equivocation needs two distinct blocks, got ${a.length}`);let u=a.map(e=>asCitedBlock(e)),[p,y]=u;if(p===void 0||y===void 0)return verdict(`provably-invalid`,`cited artifacts are not both blocks`);let x={accused:t.accused,first:{block:p.block.block,dataHash:p.dataHash,previous:p.block.previous,supersedes:p.block.supersedes??null},second:{block:y.block.block,dataHash:y.dataHash,previous:y.block.previous,supersedes:y.block.supersedes??null}};if(u.some(e=>!e?.block.addresses.includes(t.accused)))return verdict(`provably-invalid`,`the accused did not sign both blocks`,x);if(p.block.chain!==y.block.chain)return verdict(`provably-invalid`,`the blocks are on different chains`,x);if(p.block.chain!==t.chain)return verdict(`provably-invalid`,`the blocks are not on the chain the report names`,x);if(p.block.block!==t.block&&y.block.block!==t.block)return verdict(`provably-invalid`,`the report does not locate the offense at either cited block`,x);if(p.block.block!==y.block.block&&p.block.previous!==y.block.previous)return verdict(`provably-invalid`,`the blocks neither share a height nor a parent`,x);let w=/* @__PURE__ */ new Set([p.block.supersedes,y.block.supersedes]);return w.has(p.dataHash)||w.has(y.dataHash)?verdict(`provably-invalid`,`one block supersedes the other, so this is a re-proposal`,x):verdict(`verified`,`two competing candidates with no supersedes link between them`,x)};async function anchoredBlocks(e){let t=Array.from(e.values()),i=await Promise.all(t.filter(e=>RF(e.payload)).map(async e=>({hashes:[e.dataHash,e.storageHash??await al.hash(e.payload)].filter(e=>isDefined$1(e)),time:e.payload})));return t.flatMap(e=>{let t=NI(e.payload);return t===void 0?[]:{artifact:e,block:t}}).map(({artifact:e,block:t})=>{let a=new Set(t.payload_hashes),u=i.find(e=>e.hashes.some(e=>a.has(e)));return{artifact:e,block:t,evm:u?.time?.ethereum,evmHash:u?.time?.ethereumHash}})}async function parentOf(e,t){for(let i of t)if(i!==e&&await referencesArtifact(e.block.previous,i.artifact))return i}var verifyFalseAnchor=async(e,t,i)=>{let a=await anchoredBlocks(i),u=a.find(e=>e.block.block===t.block);if(u===void 0)return verdict(`provably-invalid`,`the accused block was not among the cited artifacts`);let p=await parentOf(u,a);if(u.evm===void 0||u.evmHash===void 0)return verdict(`provably-invalid`,`the accused block carries no EVM anchor to be false about`);if(!u.block.addresses.includes(t.accused))return verdict(`provably-invalid`,`the accused did not sign the cited block`);let y={accused:t.accused,block:u.block.block,claimedEvm:u.evm,claimedEvmHash:u.evmHash,parentEvm:p?.evm??null};if(p?.evm!==void 0&&u.evm<p.evm)return verdict(`verified`,`the anchor went backwards, from ${p.evm} to ${u.evm}`,y);if(t.evm!==u.evm)return verdict(`provably-invalid`,`the report does not name the anchor the block claims`,y);if(e.evm===void 0)return verdict(`indeterminate`,`no EVM view, so the claimed anchor cannot be checked`,y);let x=await e.evm.head();if(x===void 0)return verdict(`indeterminate`,`the EVM head is not resolvable`,y);if(x-u.evm<e.params.maturityEvmBlocks)return verdict(`indeterminate`,`the anchor is only ${x-u.evm} EVM blocks deep and has not matured`,{...y,head:x});let w=await e.evm.canonicalHashAt(u.evm);return w===void 0?verdict(`indeterminate`,`the canonical hash at that EVM height is not resolvable`,y):w===u.evmHash?verdict(`provably-invalid`,`the block anchored to the canonical hash at that height`,{...y,canonical:w}):verdict(`verified`,`the block anchored to a hash the EVM never had at that height`,{...y,canonical:w})},citedAttestation=e=>{let t=e.find(e=>bI(e.payload));return t===void 0?void 0:{artifact:t,attestation:t.payload}};async function boundToAccused(e,t,i){for(let a of e){let e=a.payload;if(vw(a.payload)&&(e.addresses?.includes(i)??!1)){for(let i of e.payload_hashes??[])if(await referencesArtifact(i,t.artifact))return!0}}return!1}var verifyFalseAttestation=async(e,t,i)=>{let a=Array.from(i.values()),u=citedAttestation(a);if(u===void 0)return verdict(`provably-invalid`,`no attestation among the cited artifacts`);let{attestation:p}=u,y={accused:t.accused,attestedBlock:p.blockNumber,attestedBlockHash:p.blockHash,attestedStepHash:p.stepHash,stepSize:p.stepSize};if(p.witness!==t.accused||!await boundToAccused(a,u,t.accused))return verdict(`provably-invalid`,`the attestation is not bound to the accused by any cited signed carrier`,y);let x=dI.indexOf(p.stepSize);if(x===-1)return verdict(`provably-invalid`,`the attestation names an unknown step size ${p.stepSize}`,y);let w=a.map(e=>({block:NI(e.payload),dataHash:e.dataHash})).find(e=>e.block!==void 0&&e.dataHash===p.blockHash);if(w?.block!==void 0){let e=w.block.step_hashes?.[x];return e===p.stepHash?verdict(`provably-invalid`,`the block carries the step hash the attestation names at that level`,y):verdict(`verified`,`the attested block says something else at that level`,{...y,blockStepHashes:w.block.step_hashes??[],carried:e??null})}let E=e.submission.requestCarryingHeight-p.blockNumber;if(E>e.params.evidenceRetentionXl1Blocks)return verdict(`indeterminate`,`the attested block is ${E} blocks back, past the retention window`,y);let D=await e.chain.blockAtHeight(p.blockNumber);if(D===void 0)return verdict(`indeterminate`,`the attested height is not resolvable on this canonical chain`,y);let A=D[0]._dataHash;return A===p.blockHash?verdict(`provably-invalid`,`the attested block is the one finalized at that height`,y):verdict(`verified`,`no block with the attested hash was finalized at that height`,{...y,finalizedHash:A??null},!0)};async function anchorOf$2(e,t){for(let i of t.values())if(RF(i.payload)){for(let t of e.payload_hashes)if(await referencesArtifact(t,i))return i.payload.ethereum}}__name(anchorOf$2,`anchorOf`);var blockAt=(e,t)=>Array.from(t.values()).map(e=>NI(e.payload)).find(t=>t?.block===e);async function blockByReference(e,t){if(e!==null)for(let i of t.values()){let t=NI(i.payload);if(t!==void 0&&await referencesArtifact(e,i))return t}}var verifyIneligibleProduction=async(e,t,i)=>{let a=blockAt(t.block,i),u=a===void 0?void 0:await blockByReference(a.previous,i);if(a===void 0||u===void 0)return verdict(`provably-invalid`,`the accused block and its signed parent were not both cited`);if(!a.addresses.includes(t.accused))return verdict(`provably-invalid`,`the accused did not sign the cited block`);let p=await anchorOf$2(a,i),y=await anchorOf$2(u,i);if(p===void 0||y===void 0)return verdict(`indeterminate`,`the blocks do not both carry an anchor to measure against`);let x=await evaluateProducerEligibility({accused:t.accused,blockAnchor:p,height:t.block,intent:()=>a.addresses.includes(t.accused),params:e.params,parentAnchor:y,snapshot:e.snapshot}),w={accused:t.accused,blockAnchor:p,eStar:x.eStar??null,parentAnchor:y};if(t.evm!==x.eStar)return verdict(`provably-invalid`,`the report measures at ${t.evm}, but the rule measures at ${x.eStar}`,w);if(!x.resolvable)return verdict(`indeterminate`,`no stake snapshot, so standing cannot be measured`,w);let E={...w,seasonedActive:x.activeStake?.toString()??null,seasonedSelfBond:x.selfBond?.toString()??null};return x.eligible===!0?verdict(`provably-invalid`,`the accused met every participation requirement at that point`,E):verdict(`verified`,`the accused was ineligible at that point: ${x.reason}`,{...E,reason:x.reason??null})};function citedHydratedBlock(e){let t=Array.from(e.values()),i=t.find(e=>NI(e.payload)!==void 0),a=i===void 0?void 0:NI(i.payload);if(a===void 0)return;let u=new Set(a.payload_hashes.map(String));return{block:a,payloads:t.filter(e=>e!==i).map(e=>e.payload).filter(e=>{let{_hash:t,_dataHash:i}=e;return t!==void 0&&u.has(t)||i!==void 0&&u.has(i)})}}var Ude=BlockTransactionUniquenessValidatorFactory();async function replayReplayRule(e,t){let i=await Ude({chainIdAtBlockNumber:()=>e.block.chain,singletons:{}},[e.block,e.payloads]);return i.length>0?verdict(`verified`,`the cited block breaks a replay rule: ${i[0]?.message}`,{...t,errors:i.map(e=>e.message),rule:`replay`}):void 0}async function replayStateRules(e,t,i){if(e.balances===void 0)return verdict(`indeterminate`,`no balance view, so state rules cannot be replayed`,i);let a=await BlockCumulativeBalanceValidatorFactory()({accountBalance:e.balances,chainIdAtBlockNumber:()=>t.block.chain,singletons:{}},[t.block,t.payloads]);return a.length>0?verdict(`verified`,`the cited block breaks a state rule: ${a[0]?.message}`,{...i,errors:a.map(e=>e.message),rule:`state`}):verdict(`provably-invalid`,`the cited block satisfies every rule this procedure can replay`,i)}var verifyInvalidBlock=async(e,t,i)=>{let a=citedHydratedBlock(i);if(a===void 0)return verdict(`provably-invalid`,`no block among the cited artifacts`);let u={accused:t.accused,block:a.block.block,catalogVersion:e.catalogVersion,payloadCount:a.payloads.length};if(a.block.block!==t.block)return verdict(`provably-invalid`,`the cited block is not at the height the report names`,u);if(!a.block.addresses.includes(t.accused))return verdict(`provably-invalid`,`the accused did not sign the cited block`,u);let p=await validateBlock({singletons:{}},a.block,a.block.chain);if(p.length>0)return verdict(`verified`,`the cited block breaks a protocol rule: ${p[0]?.message}`,{...u,errors:p.map(e=>e.message),rule:`protocol`});let y=await replayReplayRule(a,u);if(y!==void 0)return y;if(a.block.previous===null)return verdict(`provably-invalid`,`the cited block is a genesis block, which has no parent to judge it against`,u);let x=await e.chain.blockByHash(a.block.previous);return x===void 0?verdict(`indeterminate`,`the parent is not resolvable on this canonical chain`,u):a.block.block===x[0].block+1?await replayStateRules(e,a,u):verdict(`verified`,`the cited block does not follow its own parent in height`,{...u,parentBlock:x[0].block,rule:`height`})},Wde={indeterminate:`indeterminate`,"provably-invalid":`verified`,verified:`provably-invalid`};function createVerifyInvalidSlashRequest(e){return async(t,i,a)=>{let u=a.values().find(e=>lI(e.payload));if(u===void 0)return verdict(`provably-invalid`,`no slash request among the cited artifacts`);let p=u.payload,y=offenseKeyOf(p),x=(await t.history.requestsByKey(y)).find(e=>e.hash===u.dataHash);if(x===void 0)return verdict(`indeterminate`,`the accused request is not visible in finalized history`);let w={accusedRequest:u.dataHash,innerOffense:p.offense,originalCarryingHeight:x.carryingHeight,reporter:i.accused},E=await t.history.adjudicationByKey(y);if(E!==void 0){let e={...w,adjudicationHeight:E.carryingHeight};return E.carryingHeight>=x.carryingHeight?verdict(`provably-invalid`,`timing-excused: the offense was not yet adjudicated when the report was filed`,e):verdict(`verified`,`re-litigation: the offense was already adjudicated on-chain when the report was filed`,e)}let D=e()[p.offense];if(D===void 0)return verdict(`indeterminate`,`no verification procedure for the inner offense '${p.offense}'`,w);let A={...t,catalogVersion:p.catalog,submission:{requestCarryingHeight:x.carryingHeight}},N=await verifyArtifacts(t.artifacts,p.evidence);if(!N.ok)return N.missing===!0?verdict(`indeterminate`,`the original's evidence is not available to re-run: ${N.reason}`,w):verdict(`verified`,`the original's evidence fails the preamble: ${N.reason}`,w);let P=(await freshnessGate(A,p)).verdict??await D(A,p,N.byHash);return verdict(Wde[P.outcome],`the original report verified as '${P.outcome}': ${P.reason}`,{...w,inner:P.transcript,innerOutcome:P.outcome})}}function mintedBy(e){return e.filter(e=>TI(e)).filter(e=>e.from===OL).reduce((e,t)=>e+Object.values(t.transfers).reduce((e,t)=>e+hexToBigInt(t),0n),0n)}async function allowedEmission(e,t,i){return e.params.rewardSource===`schedule`?rewardFromBlockNumber(t):i===void 0||e.blockRewardAt===void 0?void 0:await e.blockRewardAt(i)}var verifyRewardOvermint=async(e,t,i)=>{let a=Array.from(i.values()),u=a.find(e=>NI(e.payload)!==void 0),p=u===void 0?void 0:NI(u.payload);if(p===void 0)return verdict(`provably-invalid`,`no block among the cited artifacts`);if(p.block!==t.block)return verdict(`provably-invalid`,`the cited block is not at the height the report names`);if(!p.addresses.includes(t.accused))return verdict(`provably-invalid`,`the accused did not sign the cited block`);let y=mintedBy(a.filter(e=>e!==u).map(e=>e.payload)),x=p.previous===null?void 0:await e.chain.validatedAnchorAt(p.block-1),w=await allowedEmission(e,p.block,x),E={accused:t.accused,allowed:w===void 0?null:w.toString(),block:p.block,minted:y.toString(),parentAnchor:x??null,rewardSource:e.params.rewardSource};return w===void 0?verdict(`indeterminate`,`the allowed emission for this block cannot be established`,E):y>w?verdict(`verified`,`the block minted ${y} against an allowance of ${w}`,E):verdict(`provably-invalid`,`the block minted ${y}, within its allowance of ${w}`,E)},Gde={equivocation:verifyEquivocation,"false-anchor":verifyFalseAnchor,"false-attestation":verifyFalseAttestation,"ineligible-production":verifyIneligibleProduction,"invalid-block":verifyInvalidBlock,"invalid-slash-request":createVerifyInvalidSlashRequest(()=>Gde),"reward-overmint":verifyRewardOvermint};Uo();function createTelemetryGlobalCleanup({contextManager:e,isGlobalContextManagerOwner:t,isGlobalMeterProviderOwner:i,isGlobalPropagatorOwner:a,isGlobalTracerProviderOwner:w,runtimeInstrumentation:E}){let D=[];return E!==void 0&&D.push(()=>E.disable()),w&&D.push(()=>x.disable()),i&&D.push(()=>p.disable()),a&&D.push(()=>y.disable()),e!==void 0&&D.push(()=>t?u.disable():e.disable()),D}function isShutdownResource$1(e){return typeof e==`object`&&!!e&&`shutdown`in e&&typeof e.shutdown==`function`}__name(isShutdownResource$1,`isShutdownResource`);function attemptRollback(e){try{Promise.resolve(e()).catch(()=>null)}catch{}}function rollbackTelemetryInitialization({beforeShutdown:e=[],meterProvider:t,traceProvider:i}){for(let t of e)attemptRollback(t);for(let e of/* @__PURE__ */ new Set([t,i]))isShutdownResource$1(e)&&attemptRollback(()=>e.shutdown())}function createTelemetryShutdown({beforeShutdown:e=[],meterProvider:t,traceProvider:i}){let a;return()=>(a??=(async()=>{let a,u=!1,attempt=async e=>{try{await e()}catch(e){u||(a=e),u=!0}};for(let t of e)await attempt(t);for(let e of/* @__PURE__ */ new Set([t,i]))isShutdownResource$1(e)&&await attempt(async()=>await e.shutdown());if(u)throw a})(),a)}var Kde=`0.0.0.0`,createContextManager=()=>new ut,createPropagator=()=>new dt({propagators:[new pt,new ft]}),initResource=e=>{let t=bt({detectors:[St]}),i=xt({[oe]:e.serviceName,[se]:e.serviceName});return t.merge(i)},initHostMetrics=e=>{new vt({meterProvider:e,name:`host-metrics`}).start()},createNodeMetrics=()=>new yt({enabled:!1,monitoringPrecision:5e3}),initMetricsExporter=e=>{let{port:t,endpoint:i}=e;if(!(t<=0))return new mt({endpoint:i,host:Kde,port:t},e=>{e&&console.error(`Error initializing Prometheus exporter`,e)})},initMeterProvider=(e,t)=>new Ct({readers:t,resource:e,views:[{aggregation:void 0,instrumentName:`*`,instrumentType:void 0,meterName:`*`}]}),initTraceProvider=(e,t)=>{let i=[];if(isDefined$1(e)){let t=e.includes(`/v1/traces`)||e.includes(`:4318`)||e.startsWith(`http`)?new _t({url:e}):new ht({url:e}),a=new Ve(t,{});i.push(a)}let a={resource:t,sampler:new ze,spanProcessors:i};return new Be(a)};function registerTelemetryJson(e,t){Object.defineProperty(e,"toJSON",{value:()=>({type:`MeterProvider`}),enumerable:!1,configurable:!0}),Object.defineProperty(t,"toJSON",{value:()=>({type:`TracerProvider`}),enumerable:!1,configurable:!0})}function initTelemetry(e){let{attributes:t,metricsConfig:i,otlpEndpoint:a}=e,w,E,D={isGlobalContextManagerOwner:!1,isGlobalMeterProviderOwner:!1,isGlobalPropagatorOwner:!1,isGlobalTracerProviderOwner:!1},A,N,P;try{let e=createContextManager();w=e,e.enable(),D.isGlobalContextManagerOwner=u.setGlobalContextManager(e),D.isGlobalPropagatorOwner=y.setGlobalPropagator(createPropagator());let F=initResource(t);E=initMetricsExporter(i);let I=initMeterProvider(F,E?[E]:[]);A=I,D.isGlobalMeterProviderOwner=p.setGlobalMeterProvider(I),initHostMetrics(I);let L=createNodeMetrics();N=L,L.setMeterProvider(I),L.enable();let B=initTraceProvider(a,F);P=B,D.isGlobalTracerProviderOwner=x.setGlobalTracerProvider(B);let ee=createTelemetryShutdown({beforeShutdown:createTelemetryGlobalCleanup({contextManager:e,...D,runtimeInstrumentation:L}),meterProvider:I,traceProvider:B});return registerTelemetryJson(I,B),{meterProvider:I,shutdownTelemetry:ee,traceProvider:B}}catch(e){throw rollbackTelemetryInitialization({beforeShutdown:createTelemetryGlobalCleanup({contextManager:w,...D,runtimeInstrumentation:N}),meterProvider:A??E,traceProvider:P}),e}}Uo(),_Z(),za(),hM();var D8=Object.defineProperty,qde=Object.getOwnPropertyDescriptor,Jde=/* @__PURE__ */ __name((e,t,i)=>t in e?D8(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,`__defNormalProp`),Yde=/* @__PURE__ */ __name((e,t,i,a)=>{for(var u=a>1?void 0:a?qde(t,i):t,p=e.length-1,y;p>=0;p--)(y=e[p])&&(u=(a?y(t,i,u):y(u))||u);return a&&u&&D8(t,i,u),u},`__decorateClass`),O8=/* @__PURE__ */ __name((e,t,i)=>Jde(e,typeof t==`symbol`?t:t+``,i),`__publicField`),Xde=/* @__PURE__ */ __name(e=>[`1`,`true`,!0,1].includes(e),`toBooleanDefaultFalse`),Zde=/* @__PURE__ */ object$5({issuers:/* @__PURE__ */ array$2(ao),mode:/* @__PURE__ */ _default$1(/* @__PURE__ */ _enum$1(dde),`off`),offerings:/* @__PURE__ */ optional$2(/* @__PURE__ */ array$2(po))}),k8=/* @__PURE__ */ extend(CZ,{admission:/* @__PURE__ */ _default$1(/* @__PURE__ */ _enum$1(ude),`allowlist`),allowedProducers:/* @__PURE__ */ optional$2(/* @__PURE__ */ array$2(ao)),paramsFile:/* @__PURE__ */ optional$2(/* @__PURE__ */ string$3()),backoffMs:/* @__PURE__ */ _default$1(/* @__PURE__ */ number$4(),MU),finalizationCheckInterval:/* @__PURE__ */ _default$1(/* @__PURE__ */ number$4(),500),heartbeatInterval:/* @__PURE__ */ _default$1(/* @__PURE__ */ number$4(),o8),maxClockSkewMs:/* @__PURE__ */ _default$1((/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _nonnegative()),fde),maxEvmLeadBlocks:/* @__PURE__ */ _default$1((/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _multipleOf(1),/* @__PURE__ */ _nonnegative()),2),minCandidates:/* @__PURE__ */ _default$1((/* @__PURE__ */ number$5()).check(/* @__PURE__ */ _multipleOf(1),/* @__PURE__ */ _nonnegative()),1),producerLicenses:/* @__PURE__ */ optional$2(Zde),publishContentEncoding:/* @__PURE__ */ optional$2(/* @__PURE__ */ _enum$1([`br`,`gzip`,`none`])),publishOnFinalize:/* @__PURE__ */ _default$1(/* @__PURE__ */ pipe$1(/* @__PURE__ */ union$3([/* @__PURE__ */ number$5(),/* @__PURE__ */ string$3(),/* @__PURE__ */ boolean$2()]),/* @__PURE__ */ transform$1(Xde)),!1),publishProgressInterval:/* @__PURE__ */ optional$2(/* @__PURE__ */ number$4()),stallWarningMs:/* @__PURE__ */ _default$1((/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _positive()),6e4)}),Qde=zodToFactory(k8,`toFinalizerConfig`);function anchorOfBlock(e){return e[1].find(e=>RF(e))?.ethereum}function anchorHealth(e){let t={anchored:0,unanchored:0};for(let i of e){let e=anchorOfBlock(i);e===void 0?t.unanchored+=1:(t.anchored+=1,(t.latestAnchoredHeight===void 0||i[0].block>=t.latestAnchoredHeight)&&(t.latestAnchor=e,t.latestAnchoredHeight=i[0].block))}return t}function licensePolicyFromConfig(e){return{issuers:new Set(e.issuers.map(e=>ds(e,!0))),...e.offerings===void 0?{}:{offerings:new Set(e.offerings)}}}function unresolvable(e,t){return new Map(e.map(e=>[e[0]._dataHash,{reason:t,resolvable:!1}]))}async function evaluateLicenses(e,t,i){let a=e.viewer;if(a===void 0)return unresolvable(i,`no-license-viewer`);let u=await a.sync(),p=(await e.blockViewer.currentBlock())[0].block;if(u===void 0||u.block<p)return unresolvable(i,`ledger-behind`);let y=/* @__PURE__ */ new Map;for(let e of i){let i=e[0].addresses[0];if(i===void 0){y.set(e[0]._dataHash,{reason:`no-producer`,resolvable:!1});continue}let u=await a.licensingOperatorAt(i,e[0].block,t);y.set(e[0]._dataHash,u===void 0?{licensed:!1,reason:`no-license`,resolvable:!0}:{licenseId:u.id,licensed:!0,resolvable:!0})}return y}function buildLicenseAdmission(e){if(e.config.mode===`off`)return;let t=licensePolicyFromConfig(e.config);return{evaluate:async i=>await evaluateLicenses(e,t,i),mode:e.config.mode}}var PassWatchdog=class{_pass;now;thresholdMs;constructor(e,t=Date.now){this.thresholdMs=e,this.now=t}begin(e){this._pass={phase:e,startedAt:this.now()}}check(){let e=this._pass;if(e===void 0)return;let t=this.now();if(!(t-(e.reportedAt??e.startedAt)<this.thresholdMs))return e.reportedAt=t,{elapsedMs:t-e.startedAt,phase:e.phase}}elapsedMs(){return this._pass===void 0?0:this.now()-this._pass.startedAt}end(){let e=this._pass;if(this._pass=void 0,e?.reportedAt!==void 0)return{elapsedMs:this.now()-e.startedAt,phase:e.phase}}enter(e){this._pass!==void 0&&(this._pass.phase=e)}};function describePassStall({elapsedMs:e,phase:t},{finalized:i,published:a}){let u=Math.round(e/1e3);return t===`finalize`?`FinalizerActor: finalization pass in flight for ${u}s; nothing more is finalized until it returns`:`FinalizerActor: S3 publish in flight for ${u}s${a===void 0?``:`; the published head is still ${a}${i!==void 0&&i>a?` (finalized ${i})`:``}`}; nothing more is finalized or published until it returns`}var A8=/* @__PURE__ */ __name(e=>e[1].find(e=>RF(e))?.ethereum,`anchorOf`),intentCovers=(e,t)=>e.nbf<=t&&t<=e.exp;async function hasCurrentIntent(e,t,i,a){if(t[1].find(e=>_F(e)&&e.from===i&&intentCovers(e,a))!==void 0)return!0;if(e===void 0)return;let u=await e.intentByAddress(i);return u!==null&&intentCovers(u,a)}function createProducerEligibilityEvaluator(e){return async t=>{let i=await e.params?.tryCurrentParams();if(i===void 0)return{resolvable:!1};let a=t[0].addresses[0];if(a===void 0)return{resolvable:!1};let u=t[0].previous,p=u===null?void 0:(await e.blockViewer.blocksByHash(u,1))[0];return await evaluateProducerEligibility({accused:a,blockAnchor:A8(t),height:t[0].block,intent:async(i,a)=>await hasCurrentIntent(e.intent,t,i,a),params:i,parentAnchor:p===void 0?void 0:A8(p),snapshot:e.snapshot})}}var claimOf=e=>{let t=e[1].find(e=>RF(e));return{hash:t?.ethereumHash,height:t?.ethereum}};async function checkCanonical(e,t,i){if(e.height===void 0||e.hash===void 0)return;let a=await t.head();if(a===void 0||a-e.height<i)return;let u=await t.canonicalHashAt(e.height);if(u!==void 0)return u===e.hash?void 0:`claims EVM ${e.height} is ${e.hash} but canonically it is ${u}`}async function evaluateAnchorRules(e,t,i,a=32){let u=[],p=t;for(let t of e){let e=claimOf(t),y={block:t[0].block,producer:t[0].addresses[0]};if(e.height===void 0)u.push({...y,detail:`carries no EVM anchor`,rule:`anchor-present`});else{if(p!==void 0&&e.height<p&&u.push({...y,detail:`anchor went backwards, from ${p} to ${e.height}`,rule:`anchor-monotonic`}),i!==void 0){let t=await checkCanonical(e,i,a);t!==void 0&&u.push({...y,detail:t,rule:`anchor-canonical`})}p=e.height}}return u}function hasCatchUpProbe(e){return typeof e.findCatchUpStart==`function`}async function syncFinalizedChain(e){let{blockPublishRunner:t,chainStatePublishRunner:i,chainStateViewer:a}=e,u=await a.tryCurrentBlock(),p=rP(u===void 0?0:u[0].block+1,!0),y=hasCatchUpProbe(t)?await t.findCatchUpStart(p):p,x=await t.sync(y);return x===null?(y>p&&await i.publishHead(),null):(await i.publishHead(),x)}function isChainParamsPublisher(e){let t=e;return typeof t?.publishParams==`function`&&typeof t.currentPublished==`function`}function assertSatisfiableMinCandidates(e,t){if(t>0&&e>t)throw Error(`FinalizerActor: minCandidates (${e}) exceeds allowedProducers count (${t}) \u2014 head selection can never reach quorum and every block would stall for the backoff window. Lower minCandidates or add producers to allowedProducers.`)}var FinalizerActor=class extends ChainActor{_blockPublishRunner;_blockValidationViewer;_blockViewer;_chainStatePublishRunner;_chainStateViewer;_deadLetterQueueRunner;_finalizationRunner;_mempoolViewer;_admissionDivergenceCounter;_admissionShadowPublishRunner;_anchorEvmView;_anchorGapGauge;_anchorRuleFindingCounter;_blocksFinalizedCounter;_chainParamsViewer;_divergenceSeen=/* @__PURE__ */ new Set;_eligibility;_evmHeadCache;_lastAnchoredHeight;_lastFinalizedHead;_lastPostureMismatch;_lastPublishedHead;_lastShadowAnchor;_lastShadowFingerprint;_licenseDivergenceCounter;_licenseDivergenceSeen=/* @__PURE__ */ new Set;_licenseViewer;_licensing;_passInFlightGauge;_passWatchdog;_postureMismatchGauge;_publishPending=!1;_timeRuleRejectionCounter;get admission(){return this.params.config.admission}get allowedProducers(){return this.params.config.allowedProducers??[]}get backoffMs(){return this.params.config.backoffMs}get blockValidationViewer(){return this._blockValidationViewer}get blockViewer(){return this._blockViewer}get canPublish(){return isDefined$1(this._blockPublishRunner)&&isDefined$1(this._chainStatePublishRunner)&&isDefined$1(this._chainStateViewer)}get finalizationRunner(){return this._finalizationRunner}get heartbeatInterval(){return this.params.config.heartbeatInterval}get mempoolViewer(){return this._mempoolViewer}get minCandidates(){return this.params.config.minCandidates}get producerLicenses(){return this.params.config.producerLicenses}async createHandler(){if(await super.createHandler(),this.admission===`enforce`)throw Error(`FinalizerActor: admission 'enforce' is not yet operable — its companions (emergencyAllowlist brake, enforce-posture runbook, arbiter adjudication) have not shipped. Use 'shadow' to measure standing without gating, or 'allowlist' for trusted admission.`);if(this.producerLicenses?.mode!==`admit`&&assertSatisfiableMinCandidates(this.minCandidates??1,this.allowedProducers.length),this._blockValidationViewer=await this.locator.getInstance(Kz),this._blockViewer=await this.locator.getInstance(Hz),this._finalizationRunner=await this.locator.getInstance(uz),this._mempoolViewer=await this.locator.getInstance(iB),this._deadLetterQueueRunner=await this.locator.tryGetInstance(sz),this._anchorGapGauge=this.gauge(`finalizer_actor_anchor_gap_blocks`,`XL1 blocks since a finalized block last carried an EVM anchor`),this._blocksFinalizedCounter=this.counter(`finalizer_actor_blocks_finalized`,`Blocks finalized, split by whether they carried an EVM anchor`),this._anchorRuleFindingCounter=this.counter(`finalizer_actor_anchor_rule_findings`,`Finalized blocks that would have failed an anchor rule, had it been active`),this._anchorEvmView=await this.tryCreateAnchorEvmView(),this._timeRuleRejectionCounter=this.counter(`finalizer_actor_time_rule_rejections`,`Candidates refused by a time rule, split by rule`),this._passInFlightGauge=this.gauge(`finalizer_actor_pass_in_flight_ms`,`How long the running finalization pass has been in flight; 0 while idle`),this._passWatchdog=new PassWatchdog(this.params.config.stallWarningMs),this._anchorEvmView===void 0&&this.logger?.warn(`FinalizerActor: no EvmChainViewer is bound — candidate EVM anchors will not be bounded by the EVM head`),this.admission!==`allowlist`&&await this.createEligibilityEvaluator(),this.producerLicenses!==void 0&&this.producerLicenses.mode!==`off`&&await this.createLicenseAdmission(),this.params.config.publishOnFinalize&&(this._blockPublishRunner=await this.locator.tryGetInstance(iz),this._chainStatePublishRunner=await this.locator.tryGetInstance(az),this._chainStateViewer=await this.locator.tryGetInstance(Yz),!this.canPublish))throw Error(`publishOnFinalize is enabled but S3 publish providers are not configured`);this.params.config.paramsFile!==void 0&&await this.publishRegisterFromFile(this.params.config.paramsFile)}async startHandler(){await super.startHandler();let e=this.params.config.finalizationCheckInterval??500;this.registerTimer(`FinalizerActor`,async()=>{await this.runFinalizationPass()},2e3,e);let t=FinalizerActor.StallWatchdogIntervalMs;this.registerTimer(`FinalizerStallWatchdog`,async()=>{this.checkPassStall()},t,t)}async createEligibilityEvaluator(){this._admissionDivergenceCounter=this.counter(`finalizer_actor_shadow_admission_divergence`,`Distinct candidates where the allow-list and participation rules disagreed`),this._postureMismatchGauge=this.gauge(`finalizer_actor_posture_mismatch`,`Whether the configured admission posture disagrees with the register's eligibility-admission state`);let e=await this.locator.tryGetInstance(E6);this._admissionShadowPublishRunner=isAdmissionShadowPublishRunner(e)?e:void 0;let t=await this.locator.tryGetInstance(hB),i=await this.locator.tryGetInstance(Jz),a=await this.locator.tryGetInstance(gB);this._chainParamsViewer=i,i!==void 0&&(i.finalizedHeight=async()=>(await this.blockViewer.currentBlock())[0]?.block),this._eligibility=createProducerEligibilityEvaluator({blockViewer:this._blockViewer,intent:t,params:i,snapshot:a});let u=[i===void 0?Jz:void 0,a===void 0?gB:void 0,t===void 0?hB:void 0].filter(isDefined$1);u.length>0&&this.logger?.warn(`FinalizerActor: admission posture '${this.admission}' is missing ${u.join(`, `)} \u2014 every assessment will publish as unresolvable and divergence will read zero regardless of standing`),this.logger?.log(`FinalizerActor: admission posture '${this.admission}'`)}async createLicenseAdmission(){let e=this.producerLicenses;if(e===void 0||e.mode===`off`)return;let t=e.mode;if(this._licenseDivergenceCounter=this.counter(`finalizer_actor_license_admission_divergence`,`Distinct candidates where the allow-list and the license ledger disagreed`),this._admissionShadowPublishRunner===void 0){let e=await this.locator.tryGetInstance(E6);this._admissionShadowPublishRunner=isAdmissionShadowPublishRunner(e)?e:void 0}let i=await this.locator.tryGetInstance(S8);this._licenseViewer=isLicenseViewer(i)?i:void 0,this._licenseViewer===void 0&&this.logger?.warn(`FinalizerActor: producerLicenses mode '${t}' but no LicenseViewer is bound \u2014 bind a rest-datalake connection; every license verdict will be unresolvable${t===`admit`?` and only the allow-list admits`:``}`),this._licensing=buildLicenseAdmission({blockViewer:this.blockViewer,config:e,viewer:this._licenseViewer}),this.logger?.log(`FinalizerActor: producer licensing '${t}', recognizing ${e.issuers.length} issuer(s)`)}async publishRegisterFromFile(e){let t=await this.locator.tryGetInstance(`ChainParamsPublishRunner`);if(!isChainParamsPublisher(t))throw Error(`paramsFile is configured but no ChainParamsPublishRunner is available — bind an s3 connection for it`);let i=JSON.parse(await We.readFile(e,`utf8`)),a=oV(i,!0),u=await t.currentPublished(a.chainId);if(u!==void 0&&u.version>=a.version){this.logger?.log(`FinalizerActor: register v${u.version} already published; ${e} carries v${a.version}`);return}let p=await t.publishParams(a);this.logger?.log(`FinalizerActor: published register v${a.version} (${p}) from ${e}`)}async readyHandler(){this._publishPending=this.canPublish,await this.finalizeOnce()}async recordAdmissionShadow(e){let t=`${e.head}|${e.assessments.map(e=>`${e.dataHash}:${e.eligibility.resolvable}:${e.eligibility.eligible??`?`}:${e.license?.resolvable??`-`}:${e.license?.licensed??`?`}`).toSorted().join(`,`)}`;if(t!==this._lastShadowFingerprint){try{await this._admissionShadowPublishRunner?.publish(e),this._lastShadowFingerprint=t}catch(e){this.logger?.warn(`[shadow] could not publish admission report: ${e.message}`)}for(let t of e.divergent){let e=t.admittedByAllowList?`would_reject`:`would_accept`,i=`${t.producer}:${t.block}:${e}`;this._divergenceSeen.has(i)||(this._divergenceSeen.size>=1e4&&this._divergenceSeen.clear(),this._divergenceSeen.add(i),this._admissionDivergenceCounter?.add(1,{producer:t.producer,verdict:e}),this.logger?.warn(`[shadow] admission divergence at block ${t.block} for ${t.producer}: allow-list ${t.admittedByAllowList?`admits`:`rejects`}, participation ${t.eligibility.eligible===!0?`admits`:`rejects`} (${t.eligibility.reason??`no reason given`})`))}this.recordLicenseDivergence(e)}}recordLicenseDivergence(e){for(let t of e.assessments.filter(e=>isLicenseDivergent(e))){let e=t.admittedByAllowList?`listed_unlicensed`:`licensed_unlisted`,i=`${t.producer}:${t.block}:${e}`;this._licenseDivergenceSeen.has(i)||(this._licenseDivergenceSeen.size>=1e4&&this._licenseDivergenceSeen.clear(),this._licenseDivergenceSeen.add(i),this._licenseDivergenceCounter?.add(1,{producer:t.producer,verdict:e}),this.logger?.log(`[license] at block ${t.block} ${t.producer} is ${t.license?.licensed===!0?`licensed (${t.license.licenseId??`unknown license`})`:`unlicensed (${t.license?.reason??`no reason given`})`} and ${t.admittedByAllowList?`listed`:`not listed`}`))}}async recordPostureAlignment(e){let t=this._chainParamsViewer;if(t===void 0)return;let i=await t.tryCurrentParams();if(i===void 0)return;let a=ruleActivationStateAt(i,`eligibility-admission`,e)!==`inactive`,u=a!==(this.admission===`enforce`);this._postureMismatchGauge?.record(+!!u,{admission:this.admission}),u&&this._lastPostureMismatch!==!0&&this.logger?.warn(`FinalizerActor: register ${a?`activates`:`does not activate`} eligibility-admission at ${e} but this finalizer's admission posture is '${this.admission}'`),this._lastPostureMismatch=u}async cachedEvmHead(){let e=Date.now(),t=this._evmHeadCache;if(t!==void 0&&e-t.at<FinalizerActor.EvmHeadCacheMs)return t.value;let i=await this._anchorEvmView?.head();return this._evmHeadCache={at:e,value:i},i}checkPassStall(){let e=this._passWatchdog;if(e===void 0)return;this._passInFlightGauge?.record(e.elapsedMs());let t=e.check();t!==void 0&&this.logger?.error(describePassStall(t,{finalized:this._lastFinalizedHead,published:this._lastPublishedHead}))}async finalizeOnce(){let e=await this.spanAsync(`processPendingBlocks`,async()=>(this.logger?.debug(`FinalizerActor: Processing pending blocks...`),await processPendingBlocks({blockValidationViewer:this.blockValidationViewer,context:this.context,logger:this.logger,mempoolViewer:this.mempoolViewer,blockViewer:this.blockViewer,finalizationRunner:this.finalizationRunner,allowedProducers:this.allowedProducers,backoffMs:this.backoffMs,heartbeatInterval:this.heartbeatInterval,minCandidates:this.minCandidates,timeRules:this.timeRules(),admission:this.admission,eligibility:this._eligibility,licensing:this._licensing,publishAdmissionShadow:async e=>await this.recordAdmissionShadow(e),deadLetterQueueRunner:this._deadLetterQueueRunner,observer:this.account})),{...this.context,timeBudgetLimit:1500});if((e?.length??0)>0&&(this._publishPending=!0),e===void 0||!(e.length>0))return;this.recordAnchorHealth(e),await this.recordShadowAnchorRules(e);let t=Math.max(...e.map(e=>e[0].block));this._lastFinalizedHead=t,await this.recordPostureAlignment(t)}async publishIfPending(){this.canPublish&&this._publishPending&&await this.spanAsync(`publishFinalized`,async()=>{try{let e=await syncFinalizedChain({blockPublishRunner:this._blockPublishRunner,chainStatePublishRunner:this._chainStatePublishRunner,chainStateViewer:this._chainStateViewer});this._publishPending=!1,e!==null&&(this._lastPublishedHead=e[1],this.logger?.info(`FinalizerActor: published blocks [${e[0]}..${e[1]}] to S3`))}catch(e){this.logger?.warn(`FinalizerActor: S3 publish failed; will retry next pass`,e)}},this.context)}recordAnchorHealth(e){let t=anchorHealth(e);t.anchored>0&&this._blocksFinalizedCounter?.add(t.anchored,{anchored:!0}),t.unanchored>0&&this._blocksFinalizedCounter?.add(t.unanchored,{anchored:!1}),t.latestAnchoredHeight!==void 0&&(this._lastAnchoredHeight=t.latestAnchoredHeight);let i=e.at(-1)?.[0].block;i!==void 0&&this._anchorGapGauge?.record(i-(this._lastAnchoredHeight??0),{head:i})}async recordShadowAnchorRules(e){try{let t=(await this._chainParamsViewer?.tryCurrentParams())?.maturityEvmBlocks,i=await evaluateAnchorRules(e,this._lastShadowAnchor,this._anchorEvmView,t);for(let e of i)this._anchorRuleFindingCounter?.add(1,{rule:e.rule}),this.logger?.warn(`[shadow] block ${e.block} would fail '${e.rule}': ${e.detail}`);for(let t of e.toReversed()){let e=anchorOfBlock(t);if(e!==void 0){this._lastShadowAnchor=e;break}}}catch(e){this.logger?.warn(`[shadow] anchor rule pass failed: ${e.message}`)}}async runFinalizationPass(){let e=this._passWatchdog;e?.begin(`finalize`);try{await this.finalizeOnce(),e?.enter(`publish`),await this.publishIfPending()}finally{let t=e?.end();t!==void 0&&this.logger?.warn(`FinalizerActor: stalled ${t.phase} pass returned after ${Math.round(t.elapsedMs/1e3)}s`)}}timeRules(){return{evmHead:this._anchorEvmView===void 0?void 0:async()=>await this.cachedEvmHead(),maxClockSkewMs:this.params.config.maxClockSkewMs,maxEvmLeadBlocks:this.params.config.maxEvmLeadBlocks,onRejection:e=>this._timeRuleRejectionCounter?.add(1,{rule:e.rule})}}async tryCreateAnchorEvmView(){let e=await this.locator.tryGetInstance($z);if(e!==void 0)return{canonicalHashAt:async t=>{try{return(await(await e.provider()).getBlock(t))?.hash??void 0}catch{return}},head:async()=>{try{return await(await e.provider()).getBlockNumber()}catch{return}}}}};O8(FinalizerActor,`EvmHeadCacheMs`,5e3),O8(FinalizerActor,`StallWatchdogIntervalMs`,1e4),O8(FinalizerActor,`dependencies`,[Kz,Hz,uz,iB]),FinalizerActor=Yde([creatable()],FinalizerActor);var $de={bootExtras:({process:e})=>restDataLakeViewerExtras(e),configParser:k8,create:async e=>await FinalizerActor.create({account:e.wallet,config:Qde(e.actor),locator:e.locator}),defaultAccountPath:`5`,dependencies:[`BlockValidationViewer`,`BlockViewer`,`FinalizationRunner`,`MempoolViewer`],name:`finalizer`,optionalProviderRoots:[`AdmissionShadowPublishRunner`,`BlockPublishRunner`,`ChainParamsPublishRunner`,`ChainParamsViewer`,`ChainStatePublishRunner`,`ChainStateViewer`,`DataLakeViewer`,`DeadLetterQueueRunner`,`EvidenceProtectionViewer`,`EvmChainViewer`,`IndexViewer`,`LicenseViewer`,`StakeIntentViewer`,`StakeSnapshotViewer`]};Uo(),_Z(),za(),hM();var j8=Object.defineProperty,efe=Object.getOwnPropertyDescriptor,tfe=/* @__PURE__ */ __name((e,t,i)=>t in e?j8(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,`__defNormalProp`),M8=/* @__PURE__ */ __name((e,t,i,a)=>{for(var u=a>1?void 0:a?efe(t,i):t,p=e.length-1,y;p>=0;p--)(y=e[p])&&(u=(a?y(t,i,u):y(u))||u);return a&&u&&j8(t,i,u),u},`__decorateClass`),N8=/* @__PURE__ */ __name((e,t,i)=>tfe(e,typeof t==`symbol`?t:t+``,i),`__publicField`),nfe=100;function continuingRun(e,t){let i=[];for(let a of t.toSorted((e,t)=>e[0].block-t[0].block)){let t=e+i.length+1;if(!(a[0].block<t)){if(a[0].block>t)break;i.push(a)}}return i}async function publishedHeight(e){let t=await e.readObject(slashIndexHeadPath());return t===void 0?void 0:eH(t,!0).height}async function writeRecords(e,t){for(let i of t.records)await e.hasObject(i.path)||await e.writeObject(i.path,i.value,!0)}async function writeKeyAggregates(e,t){for(let[i,a]of t.keys){let t=mergeKeyRecord(await e.readObject(i),a);await e.writeObject(i,t,!1)}}async function writeAccusedAggregates(e,t){for(let[i,a]of t.accused){let t=await e.readObject(i),u=[.../* @__PURE__ */ new Set([...t?.keys??[],...a])];await e.writeObject(i,{keys:u},!1)}}async function resolvePending(e,t){for(let i of t.pending){let t=await e.readObject(slashIndexRequestPath(i.request));if(t?.accused===void 0||t.block===void 0||t.offense===void 0)continue;let a=slashIndexKeyPath(t.accused,t.offense,t.block),u=await e.readObject(a);if(u===void 0||i.kind===`adjudication`&&u.adjudication!==void 0)continue;let p=i.kind===`challenge`?{...u,challenges:[.../* @__PURE__ */ new Set([...u.challenges,i.hash])]}:{...u,adjudication:i.hash,outcome:i.outcome};await e.writeObject(a,p,!1)}}async function syncSlashIndex(e){let{ceiling:t,floorBlock:i=0,maxPages:a=10,reader:u,store:p}=e,y=Math.max(0,Math.floor(i))-1,x=Math.max(1,Math.floor(a)),w=Math.max(await publishedHeight(p)??0,y);if(t<=w)return null;let E=w;for(let e=0;e<x&&E<t;e++){let e=Math.min(E+nfe,t),i=await u.blocksByNumber(e,e-E),a=continuingRun(E,i);if(a.length===0)break;let y=foldSlashIndex(a);if(await writeRecords(p,y),await writeKeyAggregates(p,y),await writeAccusedAggregates(p,y),await resolvePending(p,y),E+=a.length,E<e)break}if(E<=w)return null;let D=createSlashIndexHead(E);return await p.writeObject(slashIndexHeadPath(),D,!1),D}var P8=/* @__PURE__ */ extend(CZ,{publishContentEncoding:/* @__PURE__ */ optional$2(/* @__PURE__ */ _enum$1([`br`,`gzip`,`none`])),publishProgressInterval:/* @__PURE__ */ optional$2(/* @__PURE__ */ number$4()),publishSyncInterval:/* @__PURE__ */ _default$1(/* @__PURE__ */ number$4(),5e3),slashIndexFloorBlock:/* @__PURE__ */ _default$1((/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _multipleOf(1),/* @__PURE__ */ _nonnegative()),0),slashIndexPagesPerPass:/* @__PURE__ */ _default$1((/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _multipleOf(1),/* @__PURE__ */ _positive()),10)}),rfe=zodToFactory(P8,`toIndexerConfig`);async function runChainParamsMirrorPass(e){let{label:t,logger:i,mirroredVersion:a,store:u,viewer:p}=e;try{let e=await p.tryCurrentParams();if(e===void 0||e.version===a)return a;let y=chainParamsVersionPath(e.chainId,e.version);await u.hasObject(y)||await u.writeObject(y,e,!0);let x=await al.dataHash(e);return await u.writeObject(chainParamsHeadPath(e.chainId),createChainParamsHead(e.version,x),!1),i?.info(`${t}: mirrored register v${e.version} into the index bucket`),e.version}catch(e){return i?.warn(`${t}: register mirror pass failed: ${e.message}`),a}}async function runLicenseIndexPass(e){let{label:t,logger:i,store:a,viewer:u}=e;try{let e=await u.sync();if(e===void 0)return null;let p=await publishLicenseIndex({bodies:await u.bodies?.()??[],head:e,ledger:await u.ledger(),store:a});return p!==null&&i?.info(`${t}: license index at block ${p.head.height}${p.snapshotWritten?`, new snapshot`:``}${p.bodiesWritten>0?`, ${p.bodiesWritten} bodies`:``}`),p}catch(e){return i?.warn(`${t}: license index pass failed: ${e.message}`),null}}async function runPayloadsIndexPass(e){let{label:t,logger:i,runner:a}=e;try{let e=await a.publishCompletedFrames();return e!==null&&i?.info(`${t}: payloads index complete through block ${e.block}`),e}catch(e){return i?.warn(`${t}: payloads index pass failed: ${e.message}`),null}}async function runSlashIndexPass(e){let{chainStateViewer:t,floorBlock:i,label:a,logger:u,maxPages:p,reader:y,store:x}=e;try{let e=await t.tryCurrentBlock();if(e===void 0)return null;let w=e[0].block,E=await syncSlashIndex({ceiling:w,floorBlock:i,maxPages:p,reader:y,store:x});return E===null?null:(u?.info(E.height<w?`${a}: slash index at block ${E.height}, catching up to ${w}`:`${a}: slash index complete through block ${E.height}`),E)}catch(e){return u?.warn(`${a}: slash index pass failed: ${e.message}`),null}}async function syncPublishedIndex(e){let{chainStateViewer:t,indexPublishRunner:i}=e,a=await t.tryCurrentBlock();if(a===void 0)return null;let u=rP(a[0].block,!0);return await i.publishCompletedFramesUpTo(u)}async function syncPublishedIndexes(e){let[t,i]=await Promise.all([e.syncXl1(),e.syncEvm()]);return t!==null&&i!==null&&await e.syncRewards(t,i),{evmHead:i,xl1Head:t}}var IndexerActor=class extends ChainActor{_blockViewer;_chainParamsViewer;_chainStateViewer;_evmEventIndexPublishRunner;_indexPublishRunner;_licenseViewer;_networkStakeRewardsIndexPublishRunner;_payloadIndexPublishRunner;_slashIndexStore;_mirroredParamsVersion;async createHandler(){await super.createHandler(),this._chainStateViewer=await this.locator.getInstance(Yz),this._evmEventIndexPublishRunner=await this.locator.tryGetInstance(lz),this._indexPublishRunner=await this.locator.getInstance(dz),this._networkStakeRewardsIndexPublishRunner=await this.locator.tryGetInstance(mz),assertEx$1(this._networkStakeRewardsIndexPublishRunner===void 0||this._evmEventIndexPublishRunner!==void 0,()=>`NetworkStakeRewardsIndexPublishRunner requires EvmEventIndexPublishRunner in the indexer process`),this._payloadIndexPublishRunner=await this.locator.tryGetInstance(hz);let e=await this.locator.tryGetInstance(E8);this._slashIndexStore=isSlashIndexStore(e)?e:void 0,this._blockViewer=await this.locator.tryGetInstance(Hz),this._chainParamsViewer=await this.locator.tryGetInstance(Jz);let t=await this.locator.tryGetInstance(S8);this._licenseViewer=isLicenseViewer(t)?t:void 0}async startHandler(){await super.startHandler();let e=this.params.config.publishSyncInterval??5e3;this.registerTimer(`IndexerActor`,async()=>{await syncPublishedIndexes({syncEvm:async()=>await this.runEvmEventSyncPass(),syncRewards:async(e,t)=>await this.runRewardsSyncPass(e,t),syncXl1:async()=>await this.runSyncPass()})},2e3,e),this._slashIndexStore!==void 0&&this.registerTimer(`IndexerSlashStore`,async()=>{await this.runSlashSyncPass(),await this.runParamsMirrorPass(),await this.runLicenseIndexPass()},2e3,e),this._payloadIndexPublishRunner!==void 0&&this.registerTimer(`IndexerPayloads`,async()=>{await this.runPayloadsSyncPass()},2e3,e)}async runEvmEventSyncPass(){let e=this._evmEventIndexPublishRunner;return e===void 0?null:await this.spanAsync(`evmEventIndexerSync`,async()=>{let t=await e.publishFinalizedEvents();return t!==null&&this.logger?.info(`IndexerActor: EVM event index complete through finalized block ${t.block}`),t},this.context)}async runLicenseIndexPass(){let e=this._slashIndexStore,t=this._licenseViewer;e!==void 0&&t!==void 0&&await runLicenseIndexPass({label:`IndexerActor`,logger:this.logger,store:e,viewer:t})}async runParamsMirrorPass(){let e=this._chainParamsViewer,t=this._slashIndexStore;e!==void 0&&t!==void 0&&(this._mirroredParamsVersion=await runChainParamsMirrorPass({label:`IndexerActor`,logger:this.logger,mirroredVersion:this._mirroredParamsVersion,store:t,viewer:e}))}async runPayloadsSyncPass(){let e=this._payloadIndexPublishRunner;e!==void 0&&await this.spanAsync(`payloadsIndexerSync`,async()=>{await runPayloadsIndexPass({label:`IndexerActor`,logger:this.logger,runner:e})},this.context)}async runRewardsSyncPass(e,t){let i=this._networkStakeRewardsIndexPublishRunner;i!==void 0&&await this.spanAsync(`rewardsIndexerSync`,async()=>{let a=await i.publishRewardsIndex(e,t);this.logger?.info(`IndexerActor: rewards index complete through XL1 block ${a.processedThroughBlock} (${a.stepCount} steps)`)},this.context)}async runSlashSyncPass(){let e=this._slashIndexStore,t=this._blockViewer;e!==void 0&&t!==void 0&&await runSlashIndexPass({chainStateViewer:this._chainStateViewer,floorBlock:this.params.config.slashIndexFloorBlock,label:`IndexerActor`,logger:this.logger,maxPages:this.params.config.slashIndexPagesPerPass,reader:t,store:e})}async runSyncPass(){return await this.spanAsync(`indexerSync`,async()=>{let e=await syncPublishedIndex({chainStateViewer:this._chainStateViewer,indexPublishRunner:this._indexPublishRunner});return e!==null&&this.logger?.info(`IndexerActor: index complete through block ${e.block}`),e},this.context)}};N8(IndexerActor,`dependencies`,[Yz,dz]),IndexerActor=M8([creatable()],IndexerActor);var ife={bootExtras:({process:e})=>restDataLakeViewerExtras(e),configParser:P8,create:async e=>await IndexerActor.create({account:e.wallet,config:rfe(e.actor),locator:e.locator}),defaultAccountPath:`6`,dependencies:[`ChainStateViewer`,`IndexPublishRunner`],name:`indexer`,optionalProviderRoots:[`ChainParamsViewer`,`DataLakeViewer`,`EvmEventIndexPublishRunner`,`LicenseViewer`,`NetworkStakeRewardsIndexPublishRunner`,`PayloadIndexPublishRunner`,`SlashIndexStore`]},IndexerLicenseActor=class extends ChainActor{_store;_viewer;async createHandler(){await super.createHandler();let e=await this.locator.getInstance(S8);this._viewer=assertEx$1(isLicenseViewer(e)?e:void 0,()=>`${S8} did not resolve to a license ledger reader for actor ${this.name}`);let t=await this.locator.getInstance(E8);this._store=assertEx$1(isSlashIndexStore(t)?t:void 0,()=>`${E8} did not resolve to an object store for actor ${this.name}`)}async startHandler(){await super.startHandler(),this.registerTimer(`IndexerLicenseActor`,async()=>{await this.publishPass()},2e3,this.params.config.syncInterval)}async publishPass(){await runLicenseIndexPass({label:`IndexerLicenseActor`,logger:this.logger,store:this._store,viewer:this._viewer})}};N8(IndexerLicenseActor,`dependencies`,[S8,E8]),IndexerLicenseActor=M8([creatable()],IndexerLicenseActor);var F8=/* @__PURE__ */ _default$1((/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _multipleOf(1),/* @__PURE__ */ _positive()),5e3),I8=/* @__PURE__ */ extend(CZ,{syncInterval:F8}),afe=zodToFactory(I8,`toIndexerLicenseConfig`),IndexerPayloadsActor=class extends ChainActor{_runner;async createHandler(){await super.createHandler(),this._runner=await this.locator.getInstance(hz)}async startHandler(){await super.startHandler(),this.registerTimer(`IndexerPayloadsActor`,async()=>{await this.publishPass()},2e3,this.params.config.syncInterval)}async publishPass(){await this.spanAsync(`payloadsIndexerSync`,async()=>{await runPayloadsIndexPass({label:`IndexerPayloadsActor`,logger:this.logger,runner:this._runner})},this.context)}};N8(IndexerPayloadsActor,`dependencies`,[hz]),IndexerPayloadsActor=M8([creatable()],IndexerPayloadsActor);var L8=/* @__PURE__ */ extend(CZ,{syncInterval:F8}),ofe=zodToFactory(L8,`toIndexerPayloadsConfig`),IndexerSlashActor=class extends ChainActor{_blockViewer;_chainParamsViewer;_chainStateViewer;_store;_mirroredParamsVersion;async createHandler(){await super.createHandler(),this._blockViewer=await this.locator.getInstance(Hz),this._chainStateViewer=await this.locator.getInstance(Yz);let e=await this.locator.getInstance(E8);this._store=assertEx$1(isSlashIndexStore(e)?e:void 0,()=>`${E8} did not resolve to an object store for actor ${this.name}`),this._chainParamsViewer=await this.locator.tryGetInstance(Jz)}async startHandler(){await super.startHandler(),this.registerTimer(`IndexerSlashActor`,async()=>{await this.publishPass()},2e3,this.params.config.syncInterval)}async publishPass(){await runSlashIndexPass({chainStateViewer:this._chainStateViewer,floorBlock:this.params.config.floorBlock,label:`IndexerSlashActor`,logger:this.logger,maxPages:this.params.config.pagesPerPass,reader:this._blockViewer,store:this._store});let e=this._chainParamsViewer;e!==void 0&&(this._mirroredParamsVersion=await runChainParamsMirrorPass({label:`IndexerSlashActor`,logger:this.logger,mirroredVersion:this._mirroredParamsVersion,store:this._store,viewer:e}))}};N8(IndexerSlashActor,`dependencies`,[Hz,Yz,E8]),IndexerSlashActor=M8([creatable()],IndexerSlashActor);var R8=/* @__PURE__ */ extend(CZ,{floorBlock:/* @__PURE__ */ _default$1((/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _multipleOf(1),/* @__PURE__ */ _nonnegative()),0),pagesPerPass:/* @__PURE__ */ _default$1((/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _multipleOf(1),/* @__PURE__ */ _positive()),10),syncInterval:F8}),sfe=zodToFactory(R8,`toIndexerSlashConfig`),cfe={configParser:R8,create:async e=>await IndexerSlashActor.create({account:e.wallet,config:sfe(e.actor),locator:e.locator}),defaultAccountPath:`10`,dependencies:[`BlockViewer`,`ChainStateViewer`,`SlashIndexStore`],name:`indexerSlash`,optionalProviderRoots:[`ChainParamsViewer`]},lfe={bootExtras:({process:e})=>restDataLakeViewerExtras(e),configParser:I8,create:async e=>await IndexerLicenseActor.create({account:e.wallet,config:afe(e.actor),locator:e.locator}),defaultAccountPath:`11`,dependencies:[`LicenseViewer`,`SlashIndexStore`],name:`indexerLicense`,optionalProviderRoots:[`DataLakeViewer`]},ufe={configParser:L8,create:async e=>await IndexerPayloadsActor.create({account:e.wallet,config:ofe(e.actor),locator:e.locator}),defaultAccountPath:`12`,dependencies:[`PayloadIndexPublishRunner`],name:`indexerPayloads`};Uo(),_Z(),za(),GK();var z8=Object.defineProperty,dfe=Object.getOwnPropertyDescriptor,ffe=/* @__PURE__ */ __name((e,t,i)=>t in e?z8(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,`__defNormalProp`),pfe=/* @__PURE__ */ __name((e,t,i,a)=>{for(var u=a>1?void 0:a?dfe(t,i):t,p=e.length-1,y;p>=0;p--)(y=e[p])&&(u=(a?y(t,i,u):y(u))||u);return a&&u&&z8(t,i,u),u},`__decorateClass`),B8=/* @__PURE__ */ __name((e,t,i)=>ffe(e,typeof t==`symbol`?t:t+``,i),`__publicField`),mfe=1e3,hfe=6e4,gfe=1e3,toBooleanDefaultFalse=e=>e===!0||e===`true`||e===`1`||e===1,V8=/* @__PURE__ */ extend(CZ,{blockPruneInterval:(/* @__PURE__ */ _default$1(/* @__PURE__ */ number$4(),mfe)).register(Ji,{description:`The interval time (in milliseconds) between pending block prune attempts`,title:`mempool.blockPruneInterval`,type:`number`}),demotionThreshold:(/* @__PURE__ */ _default$1((/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _multipleOf(1),/* @__PURE__ */ _positive()),3)).register(Ji,{description:`Number of times a transaction may be handed out to producers without being included in a block before it is considered demoted`,title:`mempool.demotionThreshold`,type:`number`}),evidencePruneInterval:(/* @__PURE__ */ _default$1(/* @__PURE__ */ number$4(),hfe)).register(Ji,{description:`The interval time (in milliseconds) between evidence retention sweeps. Evidence is retained for windows measured in days, so this sweeps far less often than the pending pools.`,title:`mempool.evidencePruneInterval`,type:`number`}),maxPendingTransactions:(/* @__PURE__ */ _default$1((/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _multipleOf(1),/* @__PURE__ */ _nonnegative()),0)).register(Ji,{description:`Maximum number of pending transactions in the pool. When exceeded, demoted transactions are evicted first, then oldest by sequence. 0 disables the cap.`,title:`mempool.maxPendingTransactions`,type:`number`}),serveRpc:(/* @__PURE__ */ _default$1(/* @__PURE__ */ pipe$1(/* @__PURE__ */ union$3([/* @__PURE__ */ number$5(),/* @__PURE__ */ string$3(),/* @__PURE__ */ boolean$2()]),/* @__PURE__ */ transform$1(toBooleanDefaultFalse)),!1)).register(Ji,{description:`Host an HTTP JSON-RPC server (mempool methods only) on the actor host/port. Off by default; enable for a standalone mempool service.`,title:`mempool.serveRpc`,type:`boolean`}),transactionPruneInterval:(/* @__PURE__ */ _default$1(/* @__PURE__ */ number$4(),gfe)).register(Ji,{description:`The interval time (in milliseconds) between pending transaction prune attempts`,title:`mempool.transactionPruneInterval`,type:`number`})}),_fe=zodToFactory(V8,`toMempoolConfig`),vfe=N2.ReasonPhrases.OK,yfe=/* @__PURE__ */ __name((e,t)=>{setRawResponseFormat(t),t.status(200).send({message:vfe})},`handler`),bfe=N2.ReasonPhrases.OK,xfe=/* @__PURE__ */ __name((e,t)=>{setRawResponseFormat(t),t.status(200).send({message:bfe})},`handler2`),Sfe=N2.ReasonPhrases.OK,Cfe=/* @__PURE__ */ __name((e,t)=>{setRawResponseFormat(t),t.status(200).send({message:Sfe})},`handler3`),wfe=/* @__PURE__ */ __name(e=>{e.get(`/livez`,yfe),e.get(`/readyz`,xfe),e.get(`/startupz`,Cfe)},`addProbeRoutes`);function addRpcRoutes(e,t){let{logger:i,mempoolRunner:a,mempoolViewer:u}=t,p={...sq,...oq},y={...rpcMethodHandlersFromMempoolViewer(u),...rpcMethodHandlersFromMempoolRunner(a)},x=createRpcDispatchMiddleware(p,y,{logger:i}),w=new WK({engine:HK.create({middleware:[x]})});e.post(`/rpc`,async(e,t)=>{await spanAsync(`mempool:rpc`,async()=>{setRawResponseFormat(t);let i=await w.handle(e.body);t.json(i)},{logger:i,timeBudgetLimit:1e3})})}function addRoutes$1(e,t){wfe(e),addRpcRoutes(e,t)}__name(addRoutes$1,`addRoutes`);function getApp$1(e){let t=(0,M2.default)();return sharedMiddleware(t,{telemetry:e.telemetry}),addRoutes$1(t,e),t.use(standardErrors),t}__name(getApp$1,`getApp`);function formatHostPort(e,t){return`${e.includes(`:`)?`[${e}]`:e}:${t}`}async function getServer$1(e){let{logger:t,config:i}=e,{host:a,port:u}=i,p=getApp$1(e),y=await new Promise((e,i)=>{let y=p.listen(u,a,()=>{let i=y.address(),p=typeof i==`object`&&i?formatHostPort(i.address,i.port):formatHostPort(a,u);t?.info(`[Mempool] Server listening at http://${p}`),e(y)});y.once(`error`,e=>{t?.error(`[Mempool] Failed to bind HTTP server on ${formatHostPort(a,u)}: ${e.message}`),i(e),(e.code===`EADDRINUSE`||e.code===`EACCES`)&&process.exit(1)})});return y.setTimeout(2e4),y}__name(getServer$1,`getServer`);var MempoolActor=class extends ChainActor{_evidenceStoreRunner;_evidenceViewer;_mempoolRunner;_mempoolViewer;_pairCounter;_pairsSeen=/* @__PURE__ */ new Set;server;get blockPruneInterval(){return this.params.config.blockPruneInterval}get evidencePruneInterval(){return this.params.config.evidencePruneInterval}get mempoolRunner(){return this._mempoolRunner}get serveRpc(){return this.params.config.serveRpc}get transactionPruneInterval(){return this.params.config.transactionPruneInterval}async createHandler(){await super.createHandler(),this._mempoolRunner=await this.locator.getInstance(fz),this._evidenceStoreRunner=await this.locator.tryGetInstance(cz),this._evidenceViewer=await this.locator.tryGetInstance(Zz),this._pairCounter=this.counter(`mempool_actor_candidate_pairs_detected`,`Distinct same-height candidate pairs recorded in the evidence index`),this.serveRpc&&(this._mempoolViewer=assertEx$1(await this.locator.tryGetInstance(iB),()=>`[MempoolActor] serveRpc requires a MempoolViewer provider — bind MempoolViewer to the mempool store connection`))}async startHandler(){await super.startHandler(),this.serveRpc&&(this.stopServer(),await this.startServer()),this.registerTimer(`mempoolBlockPrune`,async()=>{await this.prunePendingBlocks()},2e3,this.blockPruneInterval),this.registerTimer(`mempoolTransactionPrune`,async()=>{await this.prunePendingTransactions()},2e3,this.transactionPruneInterval),this.registerTimer(`mempoolEvidencePrune`,async()=>{await this.pruneEvidence()},2e3,this.evidencePruneInterval)}async stopHandler(){await super.stopHandler(),this.stopServer()}async readyHandler(){await this.prunePendingBlocks(),await this.prunePendingTransactions()}async pruneEvidence(){await this.recordCandidatePairs(),this._evidenceStoreRunner!==void 0&&await this.spanAsync(`mempool:pruneEvidence`,async()=>{try{await this._evidenceStoreRunner?.pruneEvidence({batchSize:100,maxCheck:1e4,maxPrune:5e3})}catch(e){this.logger?.error(`[MempoolActor] Error pruning evidence: ${e.message}`)}},{...this.context,timeBudgetLimit:5e3})}async prunePendingBlocks(){await this.spanAsync(`mempool:prunePendingBlocks`,async()=>{try{await this.mempoolRunner.prunePendingBlocks({batchSize:100,maxCheck:1e4,maxPrune:5e3})}catch(e){throw this.logger?.error(`[MempoolActor] Error pruning pending blocks: ${e.message}`),e}},{...this.context,timeBudgetLimit:1e3})}async prunePendingTransactions(){await this.spanAsync(`mempool:prunePendingTransactions`,async()=>{try{await this.mempoolRunner.prunePendingTransactions({batchSize:100,maxCheck:1e4,maxPrune:5e3})}catch(e){throw this.logger?.error(`[MempoolActor] Error pruning pending transactions: ${e.message}`),e}},{...this.context,timeBudgetLimit:1e3})}async recordCandidatePairs(){let e=this._evidenceViewer;if(e!==void 0)try{let t=(await e.candidatePairs()).filter(e=>eL(e));for(let e of t){let t=e._hash;this._pairsSeen.has(t)||(this._pairsSeen.size>=1e4&&this._pairsSeen.clear(),this._pairsSeen.add(t),this._pairCounter?.add(1,{producer:e.producer}),this.logger?.warn(`[MempoolActor] candidate pair recorded at ${e.height} by ${e.producer}`))}}catch(e){this.logger?.debug(`[MempoolActor] could not read the candidate-pair index: ${e.message}`)}}async startServer(){this.server=await getServer$1({config:this.params.config,logger:this.logger,mempoolRunner:this._mempoolRunner,mempoolViewer:assertEx$1(this._mempoolViewer,()=>`[MempoolActor] MempoolViewer was not resolved`),telemetry:httpTelemetryConfig(this.params.process)})}stopServer(){this.server?.close(),this.server=void 0}};B8(MempoolActor,`dependencies`,[fz]),B8(MempoolActor,`optionalDependencies`,[iB,cz,Zz]),MempoolActor=pfe([creatable()],MempoolActor);var Tfe={configParser:V8,create:async e=>await MempoolActor.create({account:e.wallet,config:_fe(e.actor),locator:e.locator,process:e.process}),defaultAccountPath:`4`,dependencies:[`MempoolRunner`],name:`mempool`,optionalProviderRoots:[`EvidenceProtectionViewer`,`EvidenceStoreRunner`,`EvidenceViewer`,`MempoolViewer`]};Uo(),vG(),VN(),cH(),DB(),Ha(),hM(),pZ();var H8=Object.defineProperty,Efe=Object.getOwnPropertyDescriptor,Dfe=/* @__PURE__ */ __name((e,t,i)=>t in e?H8(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,`__defNormalProp`),U8=/* @__PURE__ */ __name((e,t,i,a)=>{for(var u=a>1?void 0:a?Efe(t,i):t,p=e.length-1,y;p>=0;p--)(y=e[p])&&(u=(a?y(t,i,u):y(u))||u);return a&&u&&H8(t,i,u),u},`__decorateClass`),W8=/* @__PURE__ */ __name((e,t,i)=>Dfe(e,typeof t==`symbol`?t:t+``,i),`__publicField`);function encodeBody(e,t){switch(t){case`br`:return{body:Ge.brotliCompressSync(e),contentEncoding:`br`};case`gzip`:return{body:Ge.gzipSync(e),contentEncoding:`gzip`};case`none`:return{body:new TextEncoder().encode(e)}}}function decodeBody(e,t){switch(t){case`br`:return Ge.brotliDecompressSync(e).toString(`utf8`);case`gzip`:return Ge.gunzipSync(e).toString(`utf8`);default:return new TextDecoder().decode(e)}}var Ofe=object$3({contentEncoding:_enum([`br`,`gzip`,`none`]).default(`br`)});function r2EndpointFor(e){return`https://${e}.r2.cloudflarestorage.com`}function httpsAgentForCaFile(e){return new rt.Agent({ca:et.readFileSync(e)})}var kfe=5e3,Afe=3e4;function s3ClientForConnection(e,t={}){let i=e.endpoint??r2EndpointFor(assertEx$1(e.accountId,()=>`s3 connection requires an endpoint or an accountId`)),a=i.includes(`r2.cloudflarestorage`),{caFile:u}=e,{connectionTimeoutMs:p=kfe,maxAttempts:y=5,socketTimeoutMs:x=Afe}=t;return new $e({region:a?`auto`:`us-east-1`,endpoint:i,forcePathStyle:!a,maxAttempts:y,credentials:{accessKeyId:assertEx$1(e.accessKeyId,()=>`s3 connection requires accessKeyId`),secretAccessKey:assertEx$1(e.secretAccessKey,()=>`s3 connection requires secretAccessKey`)},requestHandler:{connectionTimeout:p,socketTimeout:x,...isDefined$1(u)&&{httpsAgent:httpsAgentForCaFile(u)}}})}var G8=`public, max-age=31536000, immutable`,K8=`public, max-age=1`,q8=`public, max-age=300`,AbstractS3Provider=class extends AbstractCreatableProvider{_resolvedClient;_s3Connection;_s3Options;get bucket(){return assertEx$1(this._s3Connection?.config.bucket,()=>`No bucket specified`)}get client(){return assertEx$1(this._resolvedClient,()=>`No client specified`)}get contentEncoding(){return this.s3Options.contentEncoding}get prefix(){return this._s3Connection?.config.prefix??``}get readUrl(){return this._s3Connection?.config.readUrl}get s3Options(){return this._s3Options??=Ofe.parse(this.config.options),this._s3Options}async createHandler(){await super.createHandler();let e=this.s3Binding();this._s3Connection=e,this._resolvedClient=await this.connectionHandles.getOrOpen(`s3:${e.name}`,()=>s3ClientForConnection(e.config))}async getJson(e){try{let t=await this.client.send(new Xe({Bucket:this.bucket,Key:`${this.prefix}${e}`})),i=await t.Body?.transformToByteArray();return i===void 0?void 0:JSON.parse(decodeBody(i,t.ContentEncoding))}catch(e){if(J8(e))return;throw e}}async hasJson(e){try{return await this.client.send(new Ze({Bucket:this.bucket,Key:`${this.prefix}${e}`})),!0}catch(e){if(J8(e))return!1;throw e}}async putJson(e,t,i){let{body:a,contentEncoding:u}=encodeBody(t,this.contentEncoding);await this.client.send(new Qe({Bucket:this.bucket,Key:`${this.prefix}${e}`,Body:a,CacheControl:i,ContentEncoding:u,ContentType:`application/json`}))}s3Binding(){let e=this.constructor.requireBoundConnection(this.config),t=e.config;if(t.type!==`s3`)throw Error(`Provider [${this.moniker}] is bound to connection "${e.name}" of type "${t.type}" \u2014 expected "s3"`);return{config:t,name:e.name}}},J8=/* @__PURE__ */ __name(e=>{if(typeof e!=`object`||!e)return!1;let{name:t,$metadata:i}=e;return t===`NoSuchKey`||t===`NotFound`||i?.httpStatusCode===404},`isNotFoundError`),jfe=object$3({concurrency:number$1().default(8),progressInterval:number$1().default(100)}),S3BlockPublishRunner=class extends AbstractS3Provider{moniker=S3BlockPublishRunner.defaultMoniker;onProgress;_source;_options;get concurrency(){return this.options.concurrency}get progressInterval(){return this.options.progressInterval}get source(){return assertEx$1(this._source,()=>`No source specified`)}get options(){return this._options??=jfe.parse(this.config.options),this._options}async createHandler(){await super.createHandler(),this._source=await this.locator.getInstance(Hz)}async findCatchUpStart(e=rP(0,!0)){let t=(await this.source.currentBlock())[0].block;if(e>t||e===0&&!await this.hasBlock(rP(0,!0)))return e;for(let i=t;i>=e;i-=this.concurrency){let t=Math.max(e,i-this.concurrency+1),a=await Promise.all(Array.from({length:i-t+1},(e,i)=>this.hasBlock(rP(t+i,!0))));for(let e=i;e>=t;e--){let i=e-t;if(a.at(i)===!0)return rP(e+1,!0)}}return e}async hasBlock(e){return await this.hasJson(blockNumberPath(e))}async publishBlock(e){let t=await this.source.blockByNumber(e);if(isNull(t))return null;let i=JSON.stringify(t);await this.putJson(blockNumberPath(t[0].block),i,G8),await this.putJson(blockHashPath(t[0]._hash),i,G8);let a=t[1];for(let e of a)await this.putJson(payloadPath(e._hash),JSON.stringify(e),G8);return t}async publishManifest(){let e=createChainManifest(this.contentEncoding);await this.putJson(manifestPath(),JSON.stringify(e),q8)}async sync(e=rP(0,!0)){let t=(await this.source.currentBlock())[0].block;if(e>t)return null;await this.publishManifest();let i=new Semaphore(this.concurrency),a=Array.from({length:t-e+1},(t,i)=>rP(e+i,!0)),u=a.length,p=0;return await Promise.all(a.map(e=>i.runExclusive(async()=>{assertEx$1(await this.publishBlock(e),()=>`Block not found in source [${e}]`),p+=1,(p===u||p%this.progressInterval===0)&&this.report({blockNumber:e,published:p,total:u})}))),[e,t]}report(e){let t=this.onProgress;t?t(e):this.logger?.info(`S3BlockPublishRunner: published block ${e.blockNumber} (${e.published}/${e.total})`)}};W8(S3BlockPublishRunner,`connectionTypes`,[`s3`]),W8(S3BlockPublishRunner,`defaultMoniker`,iz),W8(S3BlockPublishRunner,`dependencies`,[Hz]),W8(S3BlockPublishRunner,`monikers`,[iz]),W8(S3BlockPublishRunner,`providerId`,`S3BlockPublishRunner`),W8(S3BlockPublishRunner,`surface`,`node`),S3BlockPublishRunner=U8([creatableProvider()],S3BlockPublishRunner);var Y8=`ChainParamsPublishRunner`,S3ChainParamsPublishRunner=class extends AbstractS3Provider{moniker=S3ChainParamsPublishRunner.defaultMoniker;_blockViewer;get blockViewer(){return assertEx$1(this._blockViewer,()=>`No BlockViewer specified`)}async createHandler(){await super.createHandler(),this._blockViewer=await this.locator.getInstance(Hz)}async currentPublished(e){let t=await this.tryGetJson(chainParamsHeadPath(e));if(t===void 0)return;let i=t.version;if(i===void 0)return;let a=await this.tryGetJson(chainParamsVersionPath(e,i));return a===void 0?void 0:oV(a,!0)}async publishParams(e){let t=e.chainId,i=[...chainParamsSuccessionErrors(await this.currentPublished(t),e,(await this.blockViewer.currentBlock())[0].block),...chainParamsInvariantErrors(e)];assertEx$1(i.length===0,()=>`Refusing to publish register version: ${i.join(`; `)}`);let a=chainParamsVersionPath(t,e.version);assertEx$1(!await this.hasJson(a),()=>`Register version ${e.version} is already published and versions are immutable`);let u=await al.dataHash(e);return await this.putJson(a,JSON.stringify(e),G8),await this.putJson(chainParamsHeadPath(t),JSON.stringify(createChainParamsHead(e.version,u)),K8),u}async tryGetJson(e){try{return await this.getJson(e)}catch{return}}};W8(S3ChainParamsPublishRunner,`connectionTypes`,[`s3`]),W8(S3ChainParamsPublishRunner,`defaultMoniker`,Y8),W8(S3ChainParamsPublishRunner,`dependencies`,[Hz]),W8(S3ChainParamsPublishRunner,`monikers`,[Y8]),W8(S3ChainParamsPublishRunner,`providerId`,`S3ChainParamsPublishRunner`),S3ChainParamsPublishRunner=U8([creatableProvider()],S3ChainParamsPublishRunner);var S3ChainStatePublishRunner=class extends AbstractS3Provider{moniker=S3ChainStatePublishRunner.defaultMoniker;_blockViewer;_chainContractViewer;get blockViewer(){return assertEx$1(this._blockViewer,()=>`No BlockViewer specified`)}get chainContractViewer(){return assertEx$1(this._chainContractViewer,()=>`No ChainContractViewer specified`)}async createHandler(){await super.createHandler(),this._blockViewer=await this.locator.getInstance(Hz),this._chainContractViewer=await this.locator.getInstance(qz)}async publishChainContract(){let e=this.chainContractViewer;for(;e!==null;)await this.ensureChainContractPublished(e),e=await e.forkedChainContractViewer()}async publishHead(){let e=await this.blockViewer.currentBlock();return await this.putJson(headPath(),JSON.stringify(e),K8),this.logger?.info(`S3ChainStatePublishRunner: published head ${e[0].block}`),e}async startHandler(){await super.startHandler(),await this.publishChainContract()}async buildChainContractManifest(e,t){let[i,a,u,p,y,x]=await Promise.all([e.minWithdrawalBlocks(),e.rewardsContract(),e.stakingTokenAddress(),e.forkedAtBlockNumber(),e.forkedAtHash(),e.forkedChainId()]);return createChainContractManifest({chainId:t,forkedAtBlockNumber:p,forkedAtHash:y,forkedChainId:x,minWithdrawalBlocks:i,rewardsContract:a,stakingTokenAddress:u})}async ensureChainContractPublished(e){let t=await e.chainId(),i=chainContractByIdPath(t);if(await this.hasJson(i))return;let a=await this.buildChainContractManifest(e,t);await this.putJson(i,JSON.stringify(a),G8),this.logger?.info(`S3ChainStatePublishRunner: published chain contract [${t}]`)}};W8(S3ChainStatePublishRunner,`connectionTypes`,[`s3`]),W8(S3ChainStatePublishRunner,`defaultMoniker`,az),W8(S3ChainStatePublishRunner,`dependencies`,[Hz,qz]),W8(S3ChainStatePublishRunner,`monikers`,[az]),W8(S3ChainStatePublishRunner,`providerId`,`S3ChainStatePublishRunner`),S3ChainStatePublishRunner=U8([creatableProvider()],S3ChainStatePublishRunner);var S3ChainStateViewer=class extends AbstractS3Provider{moniker=S3ChainStateViewer.defaultMoniker;async currentBlock(){return await this.spanAsync(`currentBlock`,async()=>{let e=assertEx$1(await this.getJson(headPath()),()=>`Head not found`);return JI(e,!0)},this.context)}async currentBlockHash(){return(await this.currentBlock())[0]._hash}async currentBlockNumber(){return(await this.currentBlock())[0].block}async tryCurrentBlock(){let e=await this.getJson(headPath());return e===void 0?void 0:JI(e,!0)}};W8(S3ChainStateViewer,`connectionTypes`,[`s3`]),W8(S3ChainStateViewer,`defaultMoniker`,Yz),W8(S3ChainStateViewer,`dependencies`,[]),W8(S3ChainStateViewer,`monikers`,[Yz]),W8(S3ChainStateViewer,`providerId`,`S3ChainStateViewer`),S3ChainStateViewer=U8([creatableProvider()],S3ChainStateViewer);var Mfe=object$3({allowedSchemas:array$1(string$1()).optional(),concurrency:number$1().default(8),disallowedSchemas:array$1(string$1()).optional()}),S3DataLakePublishRunner=class extends AbstractS3Provider{moniker=S3DataLakePublishRunner.defaultMoniker;_options;get allowedSchemas(){return this.options.allowedSchemas?.map(e=>Cs(e,!0))}get concurrency(){return this.options.concurrency}get disallowedSchemas(){return this.options.disallowedSchemas?.map(e=>Cs(e,!0))}get options(){return this._options??=Mfe.parse(this.config.options),this._options}async insert(e){let t=e.filter(e=>Gs(e)&&isSchemaAllowed(e.schema,this.allowedSchemas,this.disallowedSchemas));if(t.length===0)return[];let i=await al.addHashMeta(t),a=new Semaphore(this.concurrency);return await Promise.all(i.map(e=>a.runExclusive(async()=>{await this.putJson(payloadPath(e._hash),JSON.stringify(e),G8)}))),i}};W8(S3DataLakePublishRunner,`connectionTypes`,[`s3`]),W8(S3DataLakePublishRunner,`defaultMoniker`,oz),W8(S3DataLakePublishRunner,`dependencies`,[]),W8(S3DataLakePublishRunner,`monikers`,[oz]),W8(S3DataLakePublishRunner,`providerId`,`S3DataLakePublishRunner`),W8(S3DataLakePublishRunner,`surface`,`node`),S3DataLakePublishRunner=U8([creatableProvider()],S3DataLakePublishRunner);var Nfe=object$3({eventQueryBlockChunkSize:number$1().optional(),eventQueryInitialDelayMs:number$1().default(WX),eventQueryMaxAttempts:number$1().default(8),frameSize:number$1().default(1e5)}),S3EvmEventIndexPublishRunner=class extends AbstractS3Provider{moniker=S3EvmEventIndexPublishRunner.defaultMoniker;_options;adaptiveChunkSize;source;get address(){return toEthAddress(assertEx$1(this.config.chain.id,()=>`EVM event index requires config.chain.id`))}get configuredDeploymentBlock(){return this.config.chain.deploymentBlock}get eventQueryBlockChunkSize(){return this.fixedEventQueryBlockChunkSize??this.adaptiveChunkSize??1e5}get eventQueryInitialDelayMs(){return this.options.eventQueryInitialDelayMs}get eventQueryMaxAttempts(){return this.options.eventQueryMaxAttempts}get fixedEventQueryBlockChunkSize(){return this.options.eventQueryBlockChunkSize}get frameSize(){return this.options.frameSize}get options(){return this._options??=Nfe.parse(this.config.options),this._options}async createHandler(){await super.createHandler(),this.source=await this.locator.getInstance($z)}async publishFinalizedEvents(){let e=await assertEx$1(this.source,()=>`EVM event source is not initialized`).provider(),t=(await e.getNetwork()).chainId.toString(),i=await this.readManifest(),a=await this.resolveDeploymentBlock(e,i),u=this.createManifest(t,a);this.assertManifestCompatible(i,u);let p=assertEx$1(await e.getBlock(`finalized`),()=>`EVM provider did not return a finalized block`),y=assertEx$1(p.hash,()=>`Finalized EVM block is missing its hash`);if(p.number<a)return null;let x=await this.readHead();if(x!==void 0){if(this.assertHeadCompatible(x,u),assertEx$1(x.block<=p.number,()=>`EVM event index head is ahead of the provider finalized head`),x.block===p.number)return assertEx$1(y===x.hash,()=>`Finalized EVM index reorg detected at block ${x.block}`),x;assertEx$1(assertEx$1(await e.getBlock(x.block),()=>`Indexed EVM block ${x.block} is no longer available`).hash===x.hash,()=>`Finalized EVM index reorg detected at block ${x.block}`)}await this.publishFrames(e,u,x?.block??a-1,p.number),i===void 0&&await this.putJson(evmEventIndexManifestPath(this.address),JSON.stringify(u),q8);let w={address:this.address,block:p.number,chainId:t,hash:y};return await this.putJson(evmEventIndexHeadPath(this.address),JSON.stringify(w),K8),this.logger?.info(`S3EvmEventIndexPublishRunner: index complete through finalized EVM block ${w.block}`),w}assertHeadCompatible(e,t){assertEx$1(e.address.toLowerCase()===t.address.toLowerCase(),()=>`EVM event index head address mismatch`),assertEx$1(e.chainId===t.chainId,()=>`EVM event index head chain mismatch`)}assertManifestCompatible(e,t){e!==void 0&&(assertEx$1(e.address.toLowerCase()===t.address.toLowerCase(),()=>`EVM event index manifest address mismatch`),assertEx$1(e.chainId===t.chainId,()=>`EVM event index manifest chain mismatch`),assertEx$1(e.deploymentBlock===t.deploymentBlock,()=>`EVM event index deployment block cannot change`),assertEx$1(e.frameSize===t.frameSize,()=>`EVM event index frame size cannot change`),assertEx$1(e.layout===t.layout,()=>`Unsupported EVM event index layout`))}createManifest(e,t){return assertEx$1(Number.isSafeInteger(this.frameSize)&&this.frameSize>0,()=>`EVM event index frameSize must be a positive integer`),{address:this.address,chainId:e,deploymentBlock:t,frameSize:this.frameSize,layout:`evm-contract-events-v1`}}parseFrame(e){return _V(e,!0)}async publishFrames(e,t,i,a){let u=i+1,p;for(i>=t.deploymentBlock&&(i-t.deploymentBlock+1)%t.frameSize!==0&&(p=await this.readFrameThroughHead(t,i));u<=a;){let i=Math.floor((u-t.deploymentBlock)/t.frameSize),y=t.deploymentBlock+i*t.frameSize,x=y+t.frameSize-1,w=Math.min(x,a),E={fromBlock:y,logs:[...p?.fromBlock===y?p.logs:[],...await this.queryLogs(e,u,w)],toBlock:w};w===x?await this.putJson(evmEventIndexFramePath(this.address,i),JSON.stringify(E),G8):await this.putJson(evmEventIndexTailPath(this.address),JSON.stringify(E),K8),p=void 0,u=w+1}}async queryLogs(e,t,i){let a=[],u=t;for(;u<=i;){let t=this.eventQueryBlockChunkSize,p=Math.min(u+t-1,i),y;try{y=await withRpcRateLimitBackoff(()=>e.getLogs({address:this.address,fromBlock:u,toBlock:p}),{initialDelayMs:this.eventQueryInitialDelayMs,maxAttempts:this.eventQueryMaxAttempts})}catch(e){if(!isDefined$1(this.fixedEventQueryBlockChunkSize)&&isRpcRangeLimitError(e)&&t>1e3){let i=rpcRangeLimitFromError(e);this.adaptiveChunkSize=Math.max(UX,Math.min(i??2**53-1,Math.floor(t/2)));continue}throw e}a.push(...y.filter(e=>!e.removed).map(e=>this.toIndexedLog(e))),u=p+1}return a}async readFrameThroughHead(e,t){let i=Math.floor((t-e.deploymentBlock)/e.frameSize),a=e.deploymentBlock+i*e.frameSize,u=await this.getJson(evmEventIndexTailPath(this.address)),p=u===void 0?void 0:this.parseFrame(u);if(p?.fromBlock===a&&p.toBlock>=t)return this.trimFrameThrough(p,t);let y=await this.getJson(evmEventIndexFramePath(this.address,i)),x=y===void 0?void 0:this.parseFrame(y),w=a+e.frameSize-1,E=assertEx$1(x?.fromBlock===a&&x.toBlock===w?x:void 0,()=>`EVM event index has no published frame covering its head`);return this.trimFrameThrough(E,t)}async readHead(){let e=await this.getJson(evmEventIndexHeadPath(this.address));return e===void 0?void 0:vV(e,!0)}async readManifest(){let e=await this.getJson(evmEventIndexManifestPath(this.address));return e===void 0?void 0:yV(e,!0)}async resolveDeploymentBlock(e,t){let i=this.configuredDeploymentBlock;return t===void 0?i??await resolveContractDeploymentBlock(e,this.address,this.logger):(isDefined$1(i)&&assertEx$1(i===t.deploymentBlock,()=>`Configured EVM deployment block does not match the index manifest`),t.deploymentBlock)}toIndexedLog(e){return{address:asEthAddress(e.address,!0),blockHash:e.blockHash,blockNumber:e.blockNumber,data:e.data,index:e.index,topics:[...e.topics],transactionHash:e.transactionHash,transactionIndex:e.transactionIndex}}trimFrameThrough(e,t){return{...e,logs:e.logs.filter(e=>e.blockNumber<=t),toBlock:t}}};W8(S3EvmEventIndexPublishRunner,`connectionTypes`,[`s3`]),W8(S3EvmEventIndexPublishRunner,`defaultMoniker`,lz),W8(S3EvmEventIndexPublishRunner,`dependencies`,[$z]),W8(S3EvmEventIndexPublishRunner,`monikers`,[lz]),W8(S3EvmEventIndexPublishRunner,`providerId`,`S3EvmEventIndexPublishRunner`),W8(S3EvmEventIndexPublishRunner,`surface`,`node`),S3EvmEventIndexPublishRunner=U8([creatableProvider()],S3EvmEventIndexPublishRunner);var Pfe=5,S3IndexSummaryMap=class{family;read;window;write;constructor(e,t,i,a){this.family=e,this.window=t,this.read=i,this.write=a}clear(){}delete(e){return!1}async get(e){let[t,i]=e.split(`|`,2),{path:a}=this.locateFrame(t,Number(i)),u=await this.read(a);if(u===void 0)return;let p=u;return assertEx$1(p.hash===t,()=>`Published ${this.family} frame ${a} has head ${p.hash}, not canonical ${t}`),p}async getMany(e){return(await Promise.all(e.map(e=>this.get(e)))).flatMap(e=>e===void 0?[]:[e])}async has(e){return await this.get(e)!==void 0}async set(e,t){let{path:i,start:a}=this.locateFrame(t.hash,t.stepSize);xz(t)&&assertLinkedBlocksStepSummary(t,this.window.hashAt(a-1)),await this.write(i,JSON.stringify(t))}async setMany(e){await Promise.all(e.map(([e,t])=>this.set(e,t)))}locateFrame(e,t){let i=assertEx$1(this.window.numberOf(e),()=>`${this.family} frame head ${e} is not a block of the verified canonical window [${this.window.from}, ${this.window.to}]`),a=assertEx$1(stepPlacementForBlockNumber(i,t),()=>`Block ${i} does not end a ${t}-block ${this.family} frame`);return{path:indexSummaryPath(this.family,a.stepLevel,a.stepIndex),start:i-t+1}}},S3IndexPublishRunner=class extends AbstractS3Provider{moniker=S3IndexPublishRunner.defaultMoniker;_source;_summaryContext;get source(){return assertEx$1(this._source,()=>`No source specified`)}get fetchFn(){return this.context.fetchFn??fetch.bind(globalThis)}get summaryContext(){return this._summaryContext??={...this.context,caches:{}},this._summaryContext}async createHandler(){await super.createHandler(),this._source=await this.locator.getInstance(Hz)}async publishCompletedFramesUpTo(e){let t=await this.source.currentBlockNumber();assertEx$1(e<=t,()=>`Ceiling ${e} exceeds source head ${t}`);let i=await this.readWatermark(),a=i?.block??-1;assertEx$1(e>=a,()=>`Ceiling ${e} is behind index head ${a}`);let u=await this.readTransactionHead(),p=u?.block??-1;assertEx$1(e>=p,()=>`Ceiling ${e} is behind transaction-inclusion head ${p}`);let y=[];i&&y.push({block:i.block,hash:i.hash,name:`Index watermark`}),u&&y.push({block:u.block,hash:u.blockHash,name:`Transaction-inclusion head`});let x=await loadCanonicalBlockWindow(this.source,{anchors:y,from:Math.min(completedFramesReadStart(a,e,Pfe),p+1),to:e}),w=x.top;u&&assertEx$1(u.chain===w[0].chain,()=>`Transaction-inclusion chain ${u.chain} does not match source chain ${w[0].chain}`);let E={balances:await this.publishFamily(`balances`,5,balancesStepSummaryFromRange,x,a,e),blocks:await this.publishFamily(`blocks`,3,blocksStepSummaryFromRange,x,a,e),schemas:await this.publishFamily(`schemas`,5,schemasStepSummaryFromRange,x,a,e),transfers:await this.publishFamily(`transfers`,4,transfersStepSummaryFromRange,x,a,e)},D=await this.publishTransactionInclusions(x,p,e),A={block:e,hash:w[0]._hash,families:E};return await this.writeManifest(),await this.writeTransactionManifest(w[0].chain),await this.writeTransactionHead(createTransactionInclusionHead({block:e,blockHash:w[0]._hash,chain:w[0].chain,entries:(u?.entries??0)+D})),await this.writeHead(A),this.logger?.info(`S3IndexPublishRunner: index complete through block ${e}`),A}async publishFrame(e,t,i){let a=dI[t],u=(i+1)*a-1,p=await this.source.currentBlockNumber();assertEx$1(u<=p,()=>`Frame ${e} ${t}/${i} is not complete (head ${p})`);let y=yL([i*a,u],!0),x=await loadCanonicalBlockWindow(this.source,{from:y[0],to:y[1]});await this.buildFamilyFrame(e,y,x),this.logger?.info(`S3IndexPublishRunner: published frame ${e} ${t}/${i}`)}async buildFamilyFrame(e,t,i){let a=dI.map(()=>new Semaphore(20));switch(e){case`balances`:await balancesStepSummaryFromRange(this.summaryContext,a,i,this.summaryMap(`balances`,i),t);break;case`blocks`:await blocksStepSummaryFromRange(this.summaryContext,a,i,this.summaryMap(`blocks`,i),t);break;case`schemas`:await schemasStepSummaryFromRange(this.summaryContext,a,i,this.summaryMap(`schemas`,i),t);break;case`transfers`:await transfersStepSummaryFromRange(this.summaryContext,a,i,this.summaryMap(`transfers`,i),t)}}async publishFamily(e,t,i,a,u,p){let y=this.summaryMap(e,a),x=dI.map(()=>new Semaphore(20)),w=0;for(let e=0;e<=t;e++){let t=dI[e],E=Math.floor((u+1)/t),D=Math.floor((p+1)/t);w+=D;for(let e=E;e<D;e++){let u=e*t;await i(this.summaryContext,x,a,y,yL([u,u+t-1],!0))}}return w}async publishTransactionInclusion(e){let t=transactionInclusionPath(e.transactionHash),i=await this.readFrame(t);if(i!==void 0){let t=NR(i,!0);assertEx$1(t.transactionHash===e.transactionHash&&t.blockHash===e.blockHash&&t.blockNumber===e.blockNumber&&t.transactionIndex===e.transactionIndex,()=>`Conflicting transaction inclusion for ${e.transactionHash}`)}else await this.putJson(t,JSON.stringify(e),G8)}async publishTransactionInclusions(e,t,i){let a=new Semaphore(20),u=0,p=i;for(;p>t;){let i=Math.min(50,p-t),y=(await e.blocksByNumber(rP(p,!0),i)).flatMap(e=>transactionInclusionsFromHydratedBlock(e));await Promise.all(y.map(e=>a.runExclusive(async()=>{await this.publishTransactionInclusion(e)}))),u+=y.length,p-=i}return u}async readFrame(e){let t=this.readUrl;if(t===void 0)return await this.getJson(e);try{let i=await this.fetchFn(`${t}/${e}`);return i.status===404?void 0:i.ok?await i.json():await this.getJson(e)}catch{return await this.getJson(e)}}async readTransactionHead(){let e=await this.getJson(transactionInclusionHeadPath());return e===void 0?void 0:oH(e,!0)}async readWatermark(){let e=await this.getJson(indexHeadPath());return e===void 0?void 0:OV(e,!0)}summaryMap(e,t){return new S3IndexSummaryMap(e,t,e=>this.readFrame(e),(e,t)=>this.putJson(e,t,G8))}async writeHead(e){let t=createIndexHead(e);await this.putJson(indexHeadPath(),JSON.stringify(t),K8)}async writeManifest(){let e=createIndexManifest({balances:5,blocks:3,schemas:5,transfers:4});await this.putJson(indexManifestPath(),JSON.stringify(e),q8)}async writeTransactionHead(e){await this.putJson(transactionInclusionHeadPath(),JSON.stringify(e),K8)}async writeTransactionManifest(e){let t=createTransactionInclusionManifest(e),i=await this.getJson(transactionInclusionManifestPath());if(i!==void 0){let a=aH(i,!0);assertEx$1(a.chain===t.chain&&a.layout===t.layout&&a.path===t.path,()=>`Transaction-inclusion manifest does not match source chain ${e}`)}await this.putJson(transactionInclusionManifestPath(),JSON.stringify(t),q8)}};W8(S3IndexPublishRunner,`connectionTypes`,[`s3`]),W8(S3IndexPublishRunner,`defaultMoniker`,dz),W8(S3IndexPublishRunner,`dependencies`,[Hz]),W8(S3IndexPublishRunner,`monikers`,[dz]),W8(S3IndexPublishRunner,`providerId`,`S3IndexPublishRunner`),S3IndexPublishRunner=U8([creatableProvider()],S3IndexPublishRunner);var X8=[3,4,5,6,7],Z8=32,Ffe=object$3({policyId:NV.default(AV),stepConcurrency:number$1().int().min(1).max(8).default(4),timeAnchor:qX.optional()}),S3NetworkStakeRewardsIndexPublishRunner=class extends AbstractS3Provider{moniker=S3NetworkStakeRewardsIndexPublishRunner.defaultMoniker;_blockViewer;_stakeViewer;_options;get options(){return this._options??=Ffe.parse(this.config.options),this._options}get policyId(){return this.options.policyId}get timeAnchor(){return this.options.timeAnchor}async createHandler(){await super.createHandler(),this._blockViewer=await this.locator.getInstance(Hz),this._stakeViewer=await this.locator.getInstance(pB)}async publishRewardsIndex(e,t){let i=await this.readManifest(),a=this.createManifest(t);this.assertManifestCompatible(i,a);let u=await this.readHead();if(await this.assertHeadCompatible(u,e,t),await this.publishManifestIfMissing(i,a),u!==void 0&&this.isCurrent(u,e,t))return u;let p=await this.resolvePublishableSteps(rP(u?.processedThroughBlock??0,!0),e.block,t.block),y=this.processedThroughBlock(p,e.block),x=await this._stakeViewer.stakeEvents.positionCount([0,t.block]),w=await this.advanceRewards(u,p.publishable,t.block,x),E=u!==void 0&&p.publishable.length===0?u.snapshotHash:await this.publishSnapshot(w.stepCount,w.positionTotals,w.totalReward),D=WV({layout:kV,policyId:this.policyId,positionCount:x,processedThroughBlock:y,snapshotHash:E,source:{evm:{block:t.block,hash:t.hash},xl1:{block:e.block,hash:e.hash}},stepCount:w.stepCount},!0);return await this.putJson(networkStakeRewardsIndexHeadPath(this.policyId),JSON.stringify(D),K8),this.logger?.info(`S3NetworkStakeRewardsIndexPublishRunner: ${w.stepCount} reward steps complete through XL1 block ${y} (XL1 source ${e.block}, EVM source ${t.block})`),D}async advanceRewards(e,t,i,a){let u=e===void 0?void 0:await this.readSnapshot(e.snapshotHash);u!==void 0&&assertEx$1(u.stepCount===e?.stepCount,()=>`Rewards snapshot step count mismatch`);let p={positionTotals:this.positionTotals(u),stepCount:e?.stepCount??0,totalReward:BigInt(u?.totalReward??`0`)};if(t.length===0)return p;let y=await this.loadPositions(a),x=indexStakeEventsByPosition(await this._stakeViewer.stakeEvents.stakeEvents([0,i]));for(let e=0;e<t.length;e+=this.options.stepConcurrency){this.signal.throwIfAborted();let i=t.slice(e,e+this.options.stepConcurrency),a=await Promise.all(i.map(async e=>await this.resolveStepRecord(e,y,x)));for(let e of a){p.stepCount++,p.totalReward+=BigInt(e.totalReward);for(let[t,i]of Object.entries(e.positionRewards)){let e=Number(t);p.positionTotals.set(e,(p.positionTotals.get(e)??0n)+BigInt(i))}}}return p}async assertHeadCompatible(e,t,i){assertEx$1((await this._blockViewer.blockByNumber(t.block))?.[0]._hash===t.hash,()=>`Rewards index XL1 watermark hash mismatch`),e!==void 0&&(assertEx$1(e.policyId===this.policyId,()=>`Rewards index head policy mismatch`),assertEx$1(e.source.xl1.block<=t.block,()=>`Rewards index XL1 source moved backwards`),assertEx$1(e.source.evm.block<=i.block,()=>`Rewards index EVM source moved backwards`),e.source.evm.block===i.block&&assertEx$1(e.source.evm.hash===i.hash,()=>`Rewards index EVM source hash changed`),assertEx$1((await this._blockViewer.blockByNumber(rP(e.source.xl1.block,!0)))?.[0]._hash===e.source.xl1.hash,()=>`Rewards index XL1 source reorg detected`))}assertManifestCompatible(e,t){e!==void 0&&(assertEx$1(e.layout===t.layout,()=>`Unsupported rewards index layout`),assertEx$1(e.policyId===t.policyId,()=>`Rewards index manifest policy mismatch`),assertEx$1(e.evmAddress.toLowerCase()===t.evmAddress.toLowerCase(),()=>`Rewards index EVM address mismatch`),assertEx$1(e.evmChainId===t.evmChainId,()=>`Rewards index EVM chain mismatch`),assertEx$1(JSON.stringify(e.stepLevels)===JSON.stringify(t.stepLevels),()=>`Rewards index step levels changed`),assertEx$1(JSON.stringify(e.timeAnchor)===JSON.stringify(t.timeAnchor),()=>`Rewards index time anchor changed`))}createManifest(e){return VV({evmAddress:e.address,evmChainId:e.chainId,layout:kV,policyId:this.policyId,stepLevels:[...X8],timeAnchor:this.timeAnchor},!0)}isCurrent(e,t,i){return e.source.xl1.block===t.block&&e.source.xl1.hash===t.hash&&e.source.evm.block===i.block&&e.source.evm.hash===i.hash}async loadPositions(e){let t=[];for(let i=0;i<e;i+=Z8){this.signal.throwIfAborted();let a=Array.from({length:Math.min(Z8,e-i)},(e,t)=>i+t);t.push(...await Promise.all(a.map(async e=>await this._stakeViewer.stakeById(e))))}return t}positionTotals(e){return new Map(Object.entries(e?.positionRewards??{}).map(([e,t])=>[Number(e),BigInt(t)]))}processedThroughBlock(e,t){return e.firstBlockedStep===void 0?t:rP(e.firstBlockedStep.block-1,!0)}async publishManifestIfMissing(e,t){e===void 0&&await this.putJson(networkStakeRewardsIndexManifestPath(this.policyId),JSON.stringify(t),q8)}async publishSnapshot(e,t,i){let a=t.entries().filter(([,e])=>e>0n).toArray(),u=Object.fromEntries(a.toSorted(([e],[t])=>e-t).map(([e,t])=>[String(e),t.toString()])),p=new al({schema:jV}),y=UV(p.fields({layout:kV,policyId:this.policyId,positionRewards:u,stepCount:e,totalReward:i.toString()}).build(),!0),x=await al.hash(y),w=networkStakeRewardsIndexSnapshotPath(this.policyId,x);return await this.putJson(w,JSON.stringify(y),G8),x}async readHead(){let e=await this.getJson(networkStakeRewardsIndexHeadPath(this.policyId));return e===void 0?void 0:WV(e,!0)}async readManifest(){let e=await this.getJson(networkStakeRewardsIndexManifestPath(this.policyId));return e===void 0?void 0:VV(e,!0)}async readSnapshot(e){let t=networkStakeRewardsIndexSnapshotPath(this.policyId,e),i=UV(assertEx$1(await this.getJson(t),()=>`Rewards index snapshot is missing: ${t}`),!0);return assertEx$1(await al.hash(i)===e,()=>`Rewards index snapshot hash mismatch: ${t}`),assertEx$1(i.policyId===this.policyId,()=>`Rewards snapshot policy mismatch`),i}async resolvePublishableSteps(e,t,i){let a=blockRangeSteps(yL([e,t],{name:`S3NetworkStakeRewardsIndexPublishRunner`}),[...X8]).toSorted((e,t)=>e.block-t.block||e.step-t.step),u=[];for(let e of a){let t=await externalBlockRangeFromStep(this.context,this._blockViewer,e,this.timeAnchor);if(t[1]>i)return{firstBlockedStep:e,publishable:u};u.push({externalRange:t,step:e})}return{publishable:u}}async resolveStepRecord(e,t,i){let a=networkStakeRewardsIndexStepPath(this.policyId,e.step),u=await this.getJson(a);if(isDefined$1(u)){let t=HV(u,!0);return assertEx$1(t.policyId===this.policyId,()=>`Rewards step policy mismatch`),assertEx$1(t.step.block===e.step.block&&t.step.step===e.step.step,()=>`Rewards step identity mismatch`),assertEx$1(t.externalRange[0]===e.externalRange[0]&&t.externalRange[1]===e.externalRange[1],()=>`Rewards step external range mismatch`),t}let p=await networkStakeStepRewardsForPositions(this.context,this._blockViewer,e.step,t,i,{},this.timeAnchor,e.externalRange),y=Object.fromEntries(p.positionRewards.entries().filter(([,e])=>e>0n).map(([e,t])=>[String(e),t.toString()])),x=assertEx$1(dI[e.step.step],()=>`Unknown step level ${e.step.step}`),w=HV({denominator:p.denominator.toString(),externalRange:e.externalRange,layout:kV,policyId:this.policyId,positionRewards:y,step:e.step,totalReward:p.totalReward.toString(),xl1Range:[e.step.block-x,e.step.block-1]},!0);return await this.putJson(a,JSON.stringify(w),G8),w}};W8(S3NetworkStakeRewardsIndexPublishRunner,`connectionTypes`,[`s3`]),W8(S3NetworkStakeRewardsIndexPublishRunner,`defaultMoniker`,mz),W8(S3NetworkStakeRewardsIndexPublishRunner,`dependencies`,[Hz,pB]),W8(S3NetworkStakeRewardsIndexPublishRunner,`monikers`,[mz]),W8(S3NetworkStakeRewardsIndexPublishRunner,`providerId`,`S3NetworkStakeRewardsIndexPublishRunner`),W8(S3NetworkStakeRewardsIndexPublishRunner,`surface`,`node`),S3NetworkStakeRewardsIndexPublishRunner=U8([creatableProvider()],S3NetworkStakeRewardsIndexPublishRunner);var Q8=3,$8=dI[Q8],e5=dI[0],Ife=object$3({concurrency:int().positive().default(32),limits:Tz.default({...Ez}),maxBlocksPerPass:int().positive().default(8*$8)}),PublishedBlocksSource=class{blocks=/* @__PURE__ */ new Map;loaded=[];maxCachedBlocks;numbers=/* @__PURE__ */ new Map;pending=/* @__PURE__ */ new Map;published;read;constructor(e,t,i=3*$8){this.read=e,this.published=t,this.maxCachedBlocks=i}async blockByNumber(e){let t=this.blocks.get(e);return t===void 0?(await this.load(e,`smallest`),assertEx$1(this.blocks.get(e),()=>`Block ${e} is not in its published blocks frame`).block):t.block}numberOf(e){return this.numbers.get(e)}async prefetch(e,t){let i=e;for(;i<=t;)this.blocks.has(i)?i+=1:i=(await this.load(i,`largest`)).to+1}evict(){let e=this.blocks.size;for(;e>this.maxCachedBlocks&&this.loaded.length>1;){let t=this.loaded.shift();for(let e=t.from;e<=t.to;e++){let t=this.blocks.get(e);t!==void 0&&(--t.refs,t.refs===0&&this.blocks.delete(e))}e=this.blocks.size}}frameFor(e,t){let i=t===`largest`?[3,2,1,0]:[0,1,2,3];for(let t of i){let i=dI[t],a=Math.floor(e/i);if((a+1)*i-1<=this.published)return{stepIndex:a,stepLevel:t}}throw Error(`Block ${e} is in no complete blocks frame (index head ${this.published})`)}async load(e,t){let{stepIndex:i,stepLevel:a}=this.frameFor(e,t),u=indexSummaryPath(`blocks`,a,i),p=this.pending.get(u);if(p!==void 0)return await p;let y=this.loadFrame(u,a,i);this.pending.set(u,y);try{return await y}finally{this.pending.delete(u)}}async loadFrame(e,t,i){let a=assertEx$1(await this.read(e),()=>`Blocks frame ${e} is not published`),u=Sz(a,{required:!0});await verifyBlocksFrame(u);let p=dI[t],y=i*p,x=y+p-1,[w]=u.blocks[0],[E]=u.blocks.at(-1);assertEx$1(w.block===y&&E.block===x,()=>`Blocks frame ${e} holds [${w.block}, ${E.block}], not [${y}, ${x}]`);let D=this.blocks.get(y-1);assertEx$1(D===void 0||w.previous===D.block[0]._hash,()=>`Blocks frame ${e} does not link to block ${y-1}`);let A=this.blocks.get(x+1);assertEx$1(A===void 0||A.block[0].previous===E._hash,()=>`Block ${x+1} does not link to blocks frame ${e}`);for(let t of u.blocks){let i=this.blocks.get(t[0].block);i===void 0?this.blocks.set(t[0].block,{block:t,refs:1}):(assertEx$1(i.block[0]._hash===t[0]._hash,()=>`Blocks frame ${e} disagrees with a loaded frame at block ${t[0].block}`),i.refs+=1),this.numbers.set(t[0]._hash,t[0].block)}return this.loaded.push({from:y,to:x}),this.evict(),{from:y,to:x}}};async function verifyBlocksFrame(e){assertLinkedBlocksStepSummary(e);for(let[t,i]of e.blocks){assertEx$1(await al.hash(t)===t._hash,()=>`Block ${t.block} does not rehash to ${t._hash}`);let e=/* @__PURE__ */ new Set;for(let a of i)TP(a)&&(assertEx$1(await al.hash(a)===a._hash,()=>`Transaction ${a._hash} in block ${t.block} does not rehash`),assertEx$1(t.payload_hashes.includes(a._hash),()=>`Block ${t.block} hydrates transaction ${a._hash} it does not list`),e.add(a._hash));for(let[a,u]of t.payload_schemas.entries()){if(u!==sw)continue;let p=t.payload_hashes[a];assertEx$1(e.has(p)||i.some(e=>e._hash===p),()=>`Block ${t.block} lists bound witness ${p} but does not hydrate it`)}}}async function verifyDataHash(e,t,i){let a=await al.dataHash(e),u=e._dataHash;return assertEx$1(u===a,()=>`${i} claims data hash ${String(u)} but rehashes to ${a}`),assertEx$1(t===void 0||a===t,()=>`${i} rehashes to ${a}, not ${t}`),a}var S3PayloadIndexPublishRunner=class extends AbstractS3Provider{moniker=S3PayloadIndexPublishRunner.defaultMoniker;_options;get limits(){return this.options.limits}get maxBlocksPerPass(){return this.options.maxBlocksPerPass}get fetchFn(){return this.context.fetchFn??fetch.bind(globalThis)}get options(){return this._options??=Ife.parse(this.config.options??{}),this._options}async publishCompletedFrames(){let e=await this.getJson(indexHeadPath());if(e===void 0)return null;let t=OV(e,!0),i=await this.readManifest(),a=await this.readHead(),u=a?.block??-1,p=Math.floor((t.block+1)/e5)*e5-1,y=Math.min(p,u+this.maxBlocksPerPass),x=Math.floor((y+1)/e5)*e5-1;if(x<=u)return a===void 0?null:toWatermark(a);let w=new PublishedBlocksSource(e=>this.readFrame(e),t.block);if(a!==void 0){let e=await w.blockByNumber(rP(a.block,!0));assertEx$1(e[0]._hash===a.hash,()=>`Payloads head ${a.block} (${a.hash}) is not the indexed block ${e[0]._hash}`)}await this.buildFrames(w,u,x);let[E]=await w.blockByNumber(rP(x,!0));x===t.block&&assertEx$1(E._hash===t.hash,()=>`Indexed block ${x} is ${E._hash}, but the index head names ${t.hash}`),await this.writeManifest(i,E.chain);let D={block:rP(x,!0),frames:dI.slice(0,6).map(e=>Math.floor((x+1)/e)),hash:E._hash};return await this.putJson(payloadsHeadPath(),JSON.stringify(createPayloadIndexHead(D)),K8),this.logger?.info(`S3PayloadIndexPublishRunner: payloads index complete through block ${x}`),D}async buildFrames(e,t,i){let a=new PassCache,u=this.summaryMap(e,t,a),p=this.pageStore(a),y=dI.map(()=>new Semaphore(20)),build=async(t,i)=>{let a=dI[t];await payloadsStepSummaryFromRange({...this.context,caches:{}},y,e,u,p,yL([i*a,i*a+a-1],!0),this.limits)};for(let a=Math.floor((t+1)/$8)*$8;a<=i;a+=$8){let u=Math.max(a,t+1),p=Math.min(a+$8-1,i);await e.prefetch(u,p);for(let e=0;e<=Math.min(Q8,5);e++)await runPool(framesEndingIn(e,u,p),this.options.concurrency,t=>build(e,t))}for(let e=Q8+1;e<=5;e++)await runPool(framesEndingIn(e,t+1,i),this.options.concurrency,t=>build(e,t))}pageStore(e){return{get:async t=>{let i=e.pages.get(t);if(i!==void 0)return i;let a=await this.readFrame(payloadsPagePath(t));if(a!==void 0)return assertEx$1(Rz(a),()=>`Payloads page ${t} is not a locator page`),await verifyDataHash(a,t,`Payloads page ${t}`),e.pages.set(t,a),a},set:async t=>{await this.putJson(payloadsPagePath(t._dataHash),JSON.stringify(t),G8),e.pages.set(t._dataHash,t)}}}async readFrame(e){let t=this.readUrl;if(t===void 0)return await this.getJson(e);try{let i=await this.fetchFn(`${t}/${e}`);return i.status===404?void 0:i.ok?await i.json():await this.getJson(e)}catch{return await this.getJson(e)}}async readHead(){let e=await this.getJson(payloadsHeadPath());if(e===void 0)return;let t=XV(e,!0);return assertEx$1(t.version===1,()=>`Payloads head is layout version ${t.version}, not 1`),t}async readManifest(){let e=await this.getJson(payloadsManifestPath());if(e===void 0)return;let t=JV(e,!0),i=this.limits;return assertEx$1(t.version===1&&t.maxStep===5&&t.limits.delegateAbove===i.delegateAbove&&t.limits.inlinePerSchema===i.inlinePerSchema&&t.limits.inlinePerSummary===i.inlinePerSummary&&t.limits.pageLocators===i.pageLocators,()=>`The published payloads manifest describes a different layout; a new layout needs a new family root`),t}summaryMap(e,t,i){let locate=(t,i)=>{let a=assertEx$1(e.numberOf(t),()=>`Payloads frame head ${t} is not a loaded indexed block`);return assertEx$1(stepPlacementForBlockNumber(a,i),()=>`Block ${a} does not end a ${i}-block frame`)},get=async e=>{let[a,u]=e.split(`|`,2),p=Number(u),{stepIndex:y,stepLevel:x}=locate(a,p),w=payloadsSummaryPath(x,y),E=i.summaries.get(w);if(E!==void 0)return E;if((y+1)*p-1>t)return;let D=await this.readFrame(w);if(D===void 0)return;assertEx$1(Fz(D),()=>`Published ${w} is not a payloads summary`);let A=D;return assertEx$1(A.hash===a,()=>`Published ${w} has head ${A.hash}, not ${a}`),await verifyDataHash(A,void 0,`Published ${w}`),i.summaries.set(w,A),A},set=async(e,t)=>{let{stepIndex:a,stepLevel:u}=locate(t.hash,t.stepSize),p=indexSummaryPath(`schemas`,u,a);assertPayloadsSchemasParity(t,assertEx$1(await this.readFrame(p),()=>`Schemas frame ${p} is not published`));let y=payloadsSummaryPath(u,a);await this.putJson(y,JSON.stringify(t),G8),i.summaries.set(y,t)};return{clear:()=>{},delete:()=>!1,get,getMany:async e=>(await Promise.all(e.map(e=>get(e)))).filter(e=>e!==void 0),has:async e=>await get(e)!==void 0,set,setMany:async e=>{for(let[t,i]of e)await set(t,i)}}}async writeManifest(e,t){if(e!==void 0){assertEx$1(e.chain===t,()=>`The payloads manifest names chain ${e.chain}, not ${t}`);return}let i=createPayloadIndexManifest({chain:t,limits:this.limits,maxStep:5});await this.putJson(payloadsManifestPath(),JSON.stringify(i),q8)}};W8(S3PayloadIndexPublishRunner,`connectionTypes`,[`s3`]),W8(S3PayloadIndexPublishRunner,`defaultMoniker`,hz),W8(S3PayloadIndexPublishRunner,`dependencies`,[]),W8(S3PayloadIndexPublishRunner,`monikers`,[hz]),W8(S3PayloadIndexPublishRunner,`providerId`,`S3PayloadIndexPublishRunner`),S3PayloadIndexPublishRunner=U8([creatableProvider()],S3PayloadIndexPublishRunner);var BoundedMap=class{max;values=/* @__PURE__ */ new Map;constructor(e){this.max=e}get(e){return this.values.get(e)}set(e,t){for(this.values.delete(e),this.values.set(e,t);this.values.size>this.max;)this.values.delete(this.values.keys().next().value)}},PassCache=class{pages=new BoundedMap(512);summaries=new BoundedMap(4096)};async function runPool(e,t,i){let a=0,u,worker=async()=>{for(;u===void 0&&a<e.length;){let t=e[a];a+=1;try{await i(t)}catch(e){u??={error:e}}}};if(await Promise.all(Array.from({length:Math.min(t,e.length)},()=>worker())),u!==void 0)throw u.error}function framesEndingIn(e,t,i){let a=dI[e],u=Math.ceil((t+1)/a)-1,p=Math.floor((i+1)/a)-1,y=[];for(let e=Math.max(u,0);e<=p;e++)y.push(e);return y}function toWatermark(e){return{block:rP(e.block,!0),frames:e.frames,hash:e.hash}}_Z(),za(),hM(),Uo();var t5=Object.defineProperty,Lfe=Object.getOwnPropertyDescriptor,Rfe=/* @__PURE__ */ __name((e,t,i)=>t in e?t5(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,`__defNormalProp`),n5=/* @__PURE__ */ __name((e,t,i,a)=>{for(var u=a>1?void 0:a?Lfe(t,i):t,p=e.length-1,y;p>=0;p--)(y=e[p])&&(u=(a?y(t,i,u):y(u))||u);return a&&u&&t5(t,i,u),u},`__decorateClass`),r5=/* @__PURE__ */ __name((e,t,i)=>Rfe(e,typeof t==`symbol`?t:t+``,i),`__publicField`),MirrorVerificationError=class extends Error{block;constructor(e,t){super(`Mirror verification failed at block ${e}: ${t}`),this.name=`MirrorVerificationError`,this.block=e}};async function isPayloadHashVerified(e,t,i){let a=await al.hash(t);return a===t._hash||findPayloadHashVariance(e,t,a,i)!==void 0}async function verifyHydratedBlock(e,t,i=RB){if(!qI(e))throw new MirrorVerificationError(t.block,`the source is not a signed hydrated block with hash metadata`);let[a,u]=e,p=a.block;if(p!==t.block)throw new MirrorVerificationError(t.block,`the source returned block ${p} instead`);if(t.hash!==void 0&&a._hash!==t.hash)throw new MirrorVerificationError(p,`the block does not match the pinned head hash`);let y=a.previous??null;if(t.previous!==void 0&&y!==t.previous)throw new MirrorVerificationError(p,`previous is ${y}, expected ${t.previous}`);if(await al.hash(a)!==a._hash)throw new MirrorVerificationError(p,`the block hash does not match its contents`);if(await al.dataHash(a)!==a._dataHash)throw new MirrorVerificationError(p,`the block data hash does not match its contents`);if(a.payload_hashes.length!==a.payload_schemas.length)throw new MirrorVerificationError(p,`the hydrated payloads do not cover the block references`);let x=/* @__PURE__ */ new Set;for(let[e,t]of a.payload_hashes.entries()){let i=JSON.stringify([t,a.payload_schemas[e]]);x.add(i)}if(u.length<x.size)throw new MirrorVerificationError(p,`the hydrated payloads do not cover the block references`);let w=/* @__PURE__ */ new Set;for(let t of u){if(!await isPayloadHashVerified(e,t,i))throw new MirrorVerificationError(p,`payload ${t._hash} does not match its contents`);let a=JSON.stringify([t._hash,t.schema]);if(!x.has(a))throw new MirrorVerificationError(p,`the hydrated payloads do not match the block references`);w.add(a)}if(w.size!==x.size)throw new MirrorVerificationError(p,`the hydrated payloads do not match the block references`)}function sha256(e){return ot(`sha256`).update(e).digest(`hex`)}async function verifyBlockRollup(e,t){let i=dI[t.level];if(!Number.isSafeInteger(t.level)||t.level<0||t.level>3||!Number.isSafeInteger(t.index)||t.index<0||i===void 0)throw RangeError(`Block rollups require a published level 0–3 and a nonnegative safe index`);let a=t.index*i,u=a+i-1;if(!Number.isSafeInteger(u))throw RangeError(`The rollup range exceeds safe block numbers`);if(typeof e!=`object`||!e)throw new MirrorVerificationError(u,`the step is not an object`);let p=e;if(p.schema!==bz||p.stepSize!==i||!Array.isArray(p.blocks)||p.blocks.length!==i||p.hash!==t.hash)throw new MirrorVerificationError(u,`the rollup schema, size, count, or pinned last hash is wrong`);if(!p.blocks.every(qI))throw new MirrorVerificationError(u,`the rollup contains a malformed hydrated block`);let y=await verifyDescendingBlocks(p.blocks.toSorted((e,t)=>t[0].block-e[0].block),u,t.hash);if(a===0&&y!==null)throw new MirrorVerificationError(0,`genesis must not have a previous block`);let x=JSON.stringify(e);return{bytes:Buffer.byteLength(x),firstPreviousHash:y,from:a,index:t.index,json:x,lastBlockHash:t.hash,level:t.level,sha256:sha256(x),to:u}}async function verifyDescendingBlocks(e,t,i){let a=i;for(let[i,u]of e.entries()){let e=t-i;if(a===null)throw new MirrorVerificationError(e,`the chain ended before genesis`);await verifyHydratedBlock(u,{block:e,hash:a,previous:e===0?null:void 0}),a=u[0].previous??null}return a}var ArchiveOutcomeUnknownError=class extends Error{constructor(e){super(`Archive upload outcome remains unknown at ${e}; reconcile the prior attempt before retrying`),this.name=`ArchiveOutcomeUnknownError`}};function isNotFound(e){return e?.$metadata?.httpStatusCode===404}function journaledAttempts(e){let t=`attempts`in e?e:{};return{attemptedAt:t.attemptedAt===void 0?-1/0:Date.parse(t.attemptedAt),attempts:t.attempts??1}}function assertMatchingIntent(e,t){for(let i of[`key`,`sha256`,`storedSha256`,`bytes`,`storedBytes`,`contentEncoding`])if(e[i]!==t[i])throw Error(`Archive journal conflicts at ${t.key}`)}function decodePublishedBody(e,t,i){let a=new TextDecoder(`utf-8`,{fatal:!0});if(t!==`none`)try{let u=t===`br`?qe(e,{maxOutputLength:i}):Ye(e,{maxOutputLength:i}),p=a.decode(u);return JSON.parse(p),{json:p,stored:e}}catch{}if(e.byteLength>i)throw Error(`Published archive object exceeds its read bound`);let u=a.decode(e);return JSON.parse(u),{json:u,stored:encodeArchiveBody(u,t).body}}function isArchiveCid(e){return typeof e==`string`&&/^[a-zA-Z0-9]{10,256}$/.test(e)}function encodeArchiveBody(e,t){return t===`br`?{body:Ke(e,{params:{[Je.BROTLI_PARAM_QUALITY]:6}}),contentEncoding:`br`}:encodeBody(e,t)}function decodeArchivedBody(e,t){let i=sha256(e),a;if(i===t.storedSha256&&e.byteLength===t.storedBytes)switch(t.contentEncoding){case`br`:a=qe(e,{maxOutputLength:t.bytes});break;case`gzip`:a=Ye(e,{maxOutputLength:t.bytes});break;default:a=e}else a=e;if(a.byteLength!==t.bytes||sha256(a)!==t.sha256)throw Error(`Archive content checksum fails at ${t.key}`);return new TextDecoder(`utf-8`,{fatal:!0}).decode(a)}var S3ArchiveObjectStore=class{bucket;client;encoding;journal;now;retry;signal;constructor(e){this.bucket=e.bucket,this.client=e.client,this.encoding=e.contentEncoding,this.journal=e.journal,this.now=e.now??Date.now,this.retry=e.retry,this.signal=e.signal}async exists(e){try{return await this.client.send(new Ze({Bucket:this.bucket,Key:e}),{abortSignal:this.signal?.()}),!0}catch(e){if(isNotFound(e))return!1;throw e}}async readPublishedJson(e,t){let i=await this.readMapped(e,t);if(i===void 0)return;let{json:a,stored:u}=decodePublishedBody(i.body,this.encoding,t),p=/* @__PURE__ */ new Date;return{json:a,receipt:{bytes:Buffer.byteLength(a),cid:i.cid,contentEncoding:this.encoding,key:e,readBackAt:p.toISOString(),sha256:sha256(a),storedBytes:u.byteLength,storedSha256:sha256(u)}}}async writeJson(e,t){let{body:i,contentEncoding:a}=encodeArchiveBody(t,this.encoding),u={bytes:Buffer.byteLength(t),contentEncoding:this.encoding,key:e,sha256:sha256(t),storedBytes:i.byteLength,storedSha256:sha256(i)},p=await this.journal.read(e);if(p!==void 0&&(assertMatchingIntent(p,u),`cid`in p&&isArchiveCid(p.cid)))return p;let y=await this.readReceipt(u);if(y!==void 0)return await this.journal.finish(y),y;if(p!==void 0&&!this.mayRetry(p))throw new ArchiveOutcomeUnknownError(e);let x=new Date(this.now());await this.journal.begin({...u,attemptedAt:x.toISOString(),attempts:p===void 0?1:journaledAttempts(p).attempts+1}),await this.client.send(new Qe({Body:i,Bucket:this.bucket,CacheControl:G8,ContentEncoding:a,ContentType:`application/json`,IfNoneMatch:`*`,Key:e,Metadata:{sha256:u.sha256,"stored-sha256":u.storedSha256}}),{abortSignal:this.signal?.()});let w=await this.readReceipt(u);if(w===void 0)throw new ArchiveOutcomeUnknownError(e);return await this.journal.finish(w),w}mayRetry(e){if(this.retry===void 0)return!1;let{attemptedAt:t,attempts:i}=journaledAttempts(e);return i<this.retry.maxAttempts&&this.now()-t>=this.retry.retryAfterMs}async readMapped(e,t){let i;try{i=await this.client.send(new Ze({Bucket:this.bucket,Key:e}),{abortSignal:this.signal?.()})}catch(e){if(isNotFound(e))return;throw e}let a=i.Metadata?.cid;if(!isArchiveCid(a))throw Error(`Archive object has no CID at ${e}`);if(t!==void 0&&(i.ContentLength??0)>t)throw Error(`Published archive object exceeds its read bound`);let u=await this.client.send(new Xe({Bucket:this.bucket,Key:e,VersionId:i.VersionId}),{abortSignal:this.signal?.()}),p=await u.Body?.transformToByteArray();if(p===void 0||u.Metadata?.cid!==a)throw Error(`Archive readback CID changed at ${e}`);return{body:p,cid:a}}async readReceipt(e){let t=await this.readMapped(e.key);if(t===void 0)return;decodeArchivedBody(t.body,e);let i=/* @__PURE__ */ new Date;return{...e,cid:t.cid,readBackAt:i.toISOString()}}},i5=dI[3],zfe={fromIndex:0,previousHash:null};async function prepareRollupArchive(e,t,i=zfe,a){let u={block:t[0].block,hash:t[0]._hash},p=Math.floor((u.block+1)/i5);if(!Number.isSafeInteger(i.fromIndex)||i.fromIndex<0||i.fromIndex>p||i.fromIndex===0&&i.previousHash!==null)throw RangeError(`Invalid verified archive checkpoint`);let y=(u.block+1)%i5,x=y===0?[]:await e.reader.blocksByNumber(rP(u.block,!0),y);if(x.length!==y)throw new MirrorVerificationError(u.block,`the open tail has missing blocks`);let w=await verifyDescendingBlocks(x,u.block,u.hash);await e.staging.stageTail(x);let E=p===0||w===null?void 0:{block:p*i5-1,hash:w},D=0;for(let t=p-1;t>=i.fromIndex;t--){if(w===null)throw new MirrorVerificationError(t*i5,`the chain ended before genesis`);let i={hash:w,index:t,level:3},u=await verifyBlockRollup(e.index.canonicalStep===void 0?await e.index.stepSummary(`blocks`,3,t):await e.index.canonicalStep(i),i);await e.staging.stageRollup(u),D+=u.bytes,w=u.firstPreviousHash,a?.(t,u.bytes)}if(w!==i.previousHash)throw new MirrorVerificationError(i.fromIndex*i5,`the archive does not connect to its verified checkpoint`);return{archiveHead:E,completedSteps:p,fromIndex:i.fromIndex,pinnedHead:u,tailBlocks:y,verifiedBytes:D}}var a5=(/* @__PURE__ */ string$3()).check(/* @__PURE__ */ _regex(/^[0-9a-f]{64}$/)),o5=(/* @__PURE__ */ string$3()).check(/* @__PURE__ */ _regex(/^[a-zA-Z0-9]{10,256}$/)),s5=(/* @__PURE__ */ number$5()).check(int$1(),/* @__PURE__ */ _nonnegative()),c5=/* @__PURE__ */ object$5({block:s5,hash:a5}),l5={archiveHead:c5,level:/* @__PURE__ */ literal$2(3),previousManifestCid:/* @__PURE__ */ optional$2(o5),schema:/* @__PURE__ */ literal$2(`network.xyo.archive.manifest`),sourceHead:c5,steps:/* @__PURE__ */ array$2(/* @__PURE__ */ object$5({bytes:s5,cid:o5,contentEncoding:/* @__PURE__ */ _enum$1([`br`,`gzip`,`none`]),firstPreviousHash:/* @__PURE__ */ nullable$2(a5),index:s5,key:/* @__PURE__ */ string$3(),lastBlockHash:a5,readBackAt:/* @__PURE__ */ string$3(),sha256:a5,storedBytes:s5,storedSha256:a5,version:(/* @__PURE__ */ number$5()).check(int$1(),/* @__PURE__ */ _positive())})),version:(/* @__PURE__ */ number$5()).check(int$1(),/* @__PURE__ */ _positive())},Bfe=/* @__PURE__ */ union$3([/* @__PURE__ */ object$5({...l5,formatVersion:/* @__PURE__ */ literal$2(1)}),/* @__PURE__ */ object$5({...l5,formatVersion:/* @__PURE__ */ literal$2(2),genesisHash:a5,network:/* @__PURE__ */ _enum$1([`mainnet`,`sequence`])})]);function validNetwork(e){if(e!==`mainnet`&&e!==`sequence`)throw RangeError(`Invalid archive network`)}function namedArchiveStepKey(e,t,i=1){validNetwork(e),archiveStepKey(t,i);let a=t*i5,u=a+i5-1;if(!Number.isSafeInteger(a)||!Number.isSafeInteger(u))throw RangeError(`Invalid archive block range`);return`blocks/3/xl1-${e}-blocks-${a}-${u}-v${i}.json.br`}function namedArchiveManifestKey(e,t){return validNetwork(e),archiveManifestKey(t),`xl1-${e}-manifest-v${t}.json.br`}function archiveRollupGenesisHash(e){let t=JSON.parse(e);if(typeof t!=`object`||!t||!(`blocks`in t)||!Array.isArray(t.blocks))throw Error(`A verified genesis rollup is required`);let i=t.blocks.find(e=>qI(e)&&e[0].block===0);if(!qI(i)||i[0].previous!==null)throw Error(`Archive genesis is missing`);return i[0]._hash}function archiveStepKey(e,t=1){if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t)||t<1)throw RangeError(`Invalid archive step index/version`);return`blocks/3/${e}${t===1?``:`_${t}`}.json`}function archiveManifestKey(e){if(!Number.isSafeInteger(e)||e<1)throw RangeError(`Invalid archive manifest version`);return`manifest${e===1?``:`_${e}`}.json`}function parseArchiveManifest(e){let t=Bfe.parse(e);if(t.steps.length===0)throw Error(`An archive manifest cannot claim empty coverage`);let i=null;for(let[e,a]of t.steps.entries()){let u=t.formatVersion===2?namedArchiveStepKey(t.network,e,a.version):archiveStepKey(e,a.version);if(a.index!==e||a.key!==u||a.firstPreviousHash!==i||t.formatVersion===2&&a.contentEncoding!==`br`)throw Error(`Archive manifest has a gap, wrong key, or conflicting link at step ${e}`);i=a.lastBlockHash}if(t.archiveHead.block!==t.steps.length*i5-1||t.archiveHead.hash!==i||t.sourceHead.block<t.archiveHead.block)throw Error(`Archive manifest head does not match its coverage`);return t}function createArchiveManifest(e,t,i,a,u){if(e.archiveHead===void 0||t.length!==e.completedSteps)throw Error(`A manifest requires a readback receipt for every completed step`);let p=t.map(({receipt:e,rollup:t,version:i})=>{if(t.level!==3||e.sha256!==t.sha256||e.bytes!==t.bytes)throw Error(`Archive receipt does not match verified rollup ${t.index}`);return{...e,firstPreviousHash:t.firstPreviousHash,index:t.index,lastBlockHash:t.lastBlockHash,version:i}});return parseArchiveManifest({archiveHead:e.archiveHead,...u===void 0?{formatVersion:1}:{formatVersion:2,...u},level:3,previousManifestCid:a,schema:`network.xyo.archive.manifest`,sourceHead:e.pinnedHead,steps:p,version:i})}var u5=`https://s3.auto-drive.autonomys.xyz`,Vfe=`https://mainnet.auto-drive.autonomys.xyz/api`,d5=int$1(),Hfe=/* @__PURE__ */ object$5({downloadLimit:d5,id:(/* @__PURE__ */ string$3()).check(/* @__PURE__ */ _minLength(1)),model:/* @__PURE__ */ _enum$1([`monthly`,`one_off`]),organizationId:(/* @__PURE__ */ string$3()).check(/* @__PURE__ */ _minLength(1)),pendingDownloadCredits:d5,pendingUploadCredits:d5,uploadLimit:d5});function createAutoDriveS3Client(e){if(e.trim().length===0)throw Error(`An Auto Drive API key is required`);return new $e({credentials:{accessKeyId:e,secretAccessKey:`unused`},endpoint:u5,forcePathStyle:!0,maxAttempts:1,region:`us-east-1`,requestHandler:{connectionTimeout:1e4,requestTimeout:12e4}})}function parseAutoDriveAccount(e){return Hfe.parse(e)}async function readAutoDriveAccount(e,t=fetch){if(e.trim().length===0)throw Error(`An Auto Drive API key is required`);let i=await t(`${Vfe}/accounts/@me`,{headers:{Authorization:`Bearer ${e}`,"X-Auth-Provider":`apikey`},redirect:`error`,signal:AbortSignal.timeout(3e4)});if(!i.ok)throw Error(`Auto Drive account lookup failed with HTTP ${i.status}`);return parseAutoDriveAccount(await i.json())}function assertAutoDriveUploadBudget(e,t,i){if(!Number.isSafeInteger(i)||i<0)throw RangeError(`Invalid Auto Drive upload size`);if(e.id!==t)throw Error(`Auto Drive account does not match the selected archive account`);if(i>0&&e.pendingUploadCredits<i)throw Error(`Auto Drive available upload bytes do not cover the archive plan`)}function publishedBlockMap(e){let t=/* @__PURE__ */ new Map;if(typeof e!=`object`||!e||!(`blocks`in e)||!Array.isArray(e.blocks))return t;let i=e.blocks;for(let e of i)qI(e)&&t.set(e[0]._hash,e);return t}async function reconstructBlockRollup(e,t,i){let a=dI[t.level];if(!Number.isSafeInteger(t.level)||t.level<0||t.level>3||!Number.isSafeInteger(t.index)||t.index<0||a===void 0)throw RangeError(`Invalid rollup reconstruction range`);let u=(t.index+1)*a-1;if(!Number.isSafeInteger(u))throw RangeError(`The rollup range exceeds safe block numbers`);let p=publishedBlockMap(e),y=[],x=t.hash;for(let e=0;e<a;e++){let t=u-e;if(x===null)throw new MirrorVerificationError(t,`reconstruction reached genesis too early`);let a=p.get(x)??await i(x);if(a===null)throw new MirrorVerificationError(t,`canonical block ${x} is unavailable`);await verifyHydratedBlock(a,{block:t,hash:x,previous:t===0?null:void 0}),y.push(a),x=a[0].previous??null}return await verifyBlockRollup({blocks:y.toReversed(),hash:t.hash,schema:bz,stepSize:a},t)}var BackupSourceConflictError=class extends Error{constructor(e){super(e),this.name=`BackupSourceConflictError`}},f5=/* @__PURE__ */ Symbol(`backupPassStage`);async function atBackupPassStage(e,t){try{return await t()}catch(t){throw typeof t==`object`&&t&&!Object.hasOwn(t,f5)&&Object.defineProperty(t,f5,{value:e}),t}}function backupPassStage(e){return typeof e==`object`&&e?e[f5]:void 0}var BackupArchiveAdvancedError=class extends Error{constructor(e){super(`Archive manifest ${e} was published by another writer; adopt it before continuing`),this.name=`BackupArchiveAdvancedError`}},BackupIndexPendingError=class extends Error{index;constructor(e){super(`Index step ${e} is not published yet`),this.name=`BackupIndexPendingError`,this.index=e}};function checkBudget(e){for(let t of[e.maxPassBytes,e.maxStepsPerPass,e.manifestReserveBytes])ct.ok(Number.isSafeInteger(t)&&t>0,`Backup pass limits must be positive safe integers`);ct.ok(Number.isSafeInteger(e.maxTotalUploadBytes)&&e.maxTotalUploadBytes>=0),ct.ok(e.deadline===void 0||Number.isFinite(e.deadline)),e.dryRun||ct.ok(e.maxTotalUploadBytes>0,`Paid backup requires an explicit positive upload ceiling`)}function stripJson(e){let{json:t,...i}=e;return i}async function latestPublishedManifestVersion(e,t,i,a){async function published(i){return a(),await atBackupPassStage(`archive-provider`,()=>e.exists(namedArchiveManifestKey(t,i)))}if(!await published(i+1))return i;let u=i+1,p=i+2;for(;await published(p);)u=p,p=i+2*(p-i);for(;p-u>1;){let e=Math.floor((u+p)/2);await published(e)?u=e:p=e}return u}async function adoptPublishedArchive(e,t,i,a){let{store:u}=e;if(t.dryRun||u===void 0)return!1;let p=await latestPublishedManifestVersion(u,t.network,i.manifestVersion,a);if(p===i.manifestVersion)return!1;let y=await atBackupPassStage(`archive-provider`,()=>u.readPublishedJson(namedArchiveManifestKey(t.network,p),t.maxPassBytes));if(a(),y===void 0)throw new BackupSourceConflictError(`A published archive manifest disappeared during adoption`);let x=parseArchiveManifest(JSON.parse(y.json));if(x.version!==p)throw new BackupSourceConflictError(`A published archive manifest is stored under another version`);let w=await atBackupPassStage(`source-read`,async()=>await e.reader.blocksByNumber(rP(x.archiveHead.block,!0),1));a(),ct.equal(w.length,1,`Source is missing the published archive head`);let E=w[0];if(await verifyHydratedBlock(E,{block:x.archiveHead.block,hash:E[0]._hash}),E[0].chain!==t.expectedChainId||E[0]._hash!==x.archiveHead.hash)throw new BackupSourceConflictError(`A published archive head differs from the source chain`);return a(),await e.state.adopt(x,y.receipt),!0}async function selectWindow(e,t,i,a){let u=await atBackupPassStage(`source-read`,async()=>await e.source.tryCurrentBlock());if(a(),u===void 0)return{status:`idle`};if(ct.ok(qI(u),`Source head is not a signed hydrated block`),u[0].chain!==t.expectedChainId)throw new BackupSourceConflictError(`Current source chain differs from the selected network identity`);if(await verifyHydratedBlock(u,{block:u[0].block,hash:u[0]._hash}),a(),i.archiveHead!==void 0&&(u[0].block<i.archiveHead.block||u[0].block===i.archiveHead.block&&u[0]._hash!==i.archiveHead.hash))throw new BackupSourceConflictError(`Source conflicts with the durable archive head`);let p={block:u[0].block,hash:u[0]._hash},y=Math.floor((u[0].block+1)/i5);if(y<=i.nextIndex&&i.pendingWindow===void 0)return{sourceHead:p,status:`idle`};let x=i.pendingWindow?.toIndex??Math.min(i.nextIndex+t.maxStepsPerPass,y)-1;if(x>=y||x-i.nextIndex+1>t.maxStepsPerPass)throw new BackupSourceConflictError(`Unfinished window no longer fits the source or selected pass bound`);let w=(x+1)*i5-1;ct.ok(Number.isSafeInteger(w));let E=await atBackupPassStage(`source-read`,async()=>await e.reader.blocksByNumber(rP(w,!0),1));a(),ct.equal(E.length,1,`Source is missing the selected sealed tip`);let D=E[0];if(await verifyHydratedBlock(D,{block:w,hash:D[0]._hash}),w===p.block&&D[0]._hash!==p.hash)throw new BackupSourceConflictError(`Selected tip conflicts with the pinned source head`);if(i.pendingWindow!==void 0&&D[0]._hash!==i.pendingWindow.pinnedHead.hash)throw new BackupSourceConflictError(`Source changed an unfinished paid window`);return a(),{sourceHead:p,status:`window`,tip:D,toIndex:x}}async function prepareWindow(e,t,i,a,u){let p={fromIndex:i.nextIndex,pinnedHead:{block:a.tip[0].block,hash:a.tip[0]._hash},toIndex:a.toIndex},y=[],x=[],w=0;async function stepSummary(t,i,a){u();let p=await atBackupPassStage(`source-read`,async()=>await e.index.stepSummary(t,i,a));return u(),p}let{blockByHash:E}=e,D=await prepareRollupArchive({index:{canonicalStep:E===void 0?void 0:async e=>{let t=await stepSummary(`blocks`,e.level,e.index);if(t==null)throw new BackupIndexPendingError(e.index);try{return await verifyBlockRollup(t,e),t}catch(i){if(!(i instanceof MirrorVerificationError))throw i;let a=await reconstructBlockRollup(t,e,async e=>(u(),await atBackupPassStage(`source-read`,async()=>await E(e))));return u(),x.push({index:e.index,rejectedBlock:i.block}),JSON.parse(a.json)}},stepSummary},reader:{blocksByNumber:async(t,i)=>await atBackupPassStage(`source-read`,async()=>await e.reader.blocksByNumber(t,i))},staging:{stageRollup:e=>(u(),w+=e.bytes,ct.ok(w<=t.maxPassBytes,`Backup pass source bytes exceed the finite window budget`),y.push(e),Promise.resolve()),stageTail:e=>(ct.equal(e.length,0,`Backup may only publish sealed steps`),Promise.resolve())}},a.tip,{fromIndex:i.nextIndex,previousHash:i.archiveHead?.hash??null});u(),y.sort((e,t)=>e.index-t.index),ct.equal(y.length,a.toIndex-i.nextIndex+1);let A=y.find(e=>e.index===0),N=i.genesisHash??(A===void 0?void 0:archiveRollupGenesisHash(A.json));if(ct.ok(N!==void 0,`A backup needs its verified genesis identity`),t.expectedGenesisHash!==void 0&&N!==t.expectedGenesisHash)throw new BackupSourceConflictError(`Source genesis differs from the selected archive identity`);let P=new Set(x.map(e=>e.index)),F=y.map(e=>{let i=encodeArchiveBody(e.json,`br`).body,a=P.has(e.index)?2:1;return{bytes:i.byteLength,index:e.index,key:namedArchiveStepKey(t.network,e.index,a),sha256:sha256(i),version:a}}),I=i.manifestVersion+1,L=namedArchiveManifestKey(t.network,I),B=F.reduce((e,t)=>e+t.bytes,t.manifestReserveBytes);return ct.ok(Number.isSafeInteger(B)&&B<=t.maxPassBytes,`Backup pass upload reservation exceeds its finite byte budget`),{genesisHash:N,manifestKey:L,manifestVersion:I,plannedUploadBytes:B,prepared:D,reconstructedSteps:x,rollups:y,sourceHead:a.sourceHead,stepIntents:F,window:p}}async function prepareWindowOrWait(e,t,i,a,u){try{return await prepareWindow(e,t,i,a,u)}catch(e){if(e instanceof BackupIndexPendingError)return;throw e}}async function publishWindow(e,t,i,a,u){ct.ok(e.store!==void 0&&e.checkAccount!==void 0,`Paid backup requires a selected object writer and live account preflight`),u(),await atBackupPassStage(`account`,()=>e.checkAccount(0)),u(),await e.state.reserveWindow(a.window,[...a.stepIntents,{bytes:t.manifestReserveBytes,key:a.manifestKey}],t.maxTotalUploadBytes);let p=e.state.createJournal(t.maxTotalUploadBytes),y=[...i.steps];for(let t of a.rollups){u();let i=a.stepIntents.find(e=>e.index===t.index);ct.ok(i!==void 0,`Every prepared step requires an upload intent`);let x=await p.read(i.key);await atBackupPassStage(`account`,()=>e.checkAccount(x!==void 0&&`cid`in x?0:i.bytes)),u();let w=await atBackupPassStage(`archive-provider`,()=>e.store.writeJson(i.key,t.json));u(),ct.ok(w.key===i.key&&w.contentEncoding===`br`&&w.sha256===t.sha256&&w.bytes===t.bytes&&w.storedBytes===i.bytes&&w.storedSha256===i.sha256,`Backup readback receipt differs from the verified prepared step`),y.push({receipt:w,rollup:stripJson(t),version:i.version})}let x=createArchiveManifest({...a.prepared,verifiedBytes:y.reduce((e,t)=>e+t.rollup.bytes,0)},y,a.manifestVersion,i.manifestReceipt?.cid,{genesisHash:a.genesisHash,network:t.network}),w=JSON.stringify(x);ct.ok(encodeArchiveBody(w,`br`).body.byteLength<=t.manifestReserveBytes,`Manifest exceeds the reserved upload bytes`),u();let E=await p.read(a.manifestKey);if(E===void 0&&await atBackupPassStage(`archive-provider`,()=>e.store.exists(a.manifestKey)))throw new BackupArchiveAdvancedError(a.manifestKey);await atBackupPassStage(`account`,()=>e.checkAccount(E!==void 0&&`cid`in E?0:encodeArchiveBody(w,`br`).body.byteLength)),u();let D=await atBackupPassStage(`archive-provider`,()=>e.store.writeJson(a.manifestKey,w));u(),await e.state.commit(x,D,y);let A=e.state.read();return{archiveHead:A.archiveHead,chargedBytes:e.state.chargedBytes(),fromIndex:i.nextIndex,manifestCid:A.manifestReceipt?.cid,nextIndex:A.nextIndex,plannedUploadBytes:a.plannedUploadBytes,preparedSteps:a.rollups.length,reconstructedSteps:a.reconstructedSteps,sourceHead:a.sourceHead,status:`published`}}async function backupPass(e,t){checkBudget(t);let i=t.now??Date.now;function check(){if(t.signal?.throwIfAborted(),t.deadline!==void 0&&i()>=t.deadline)throw Error(`Backup pass deadline reached`)}return await e.state.withPass(async()=>{check();let i=e.state.read();ct.equal(i.scope.network,t.network),ct.equal(i.scope.chainId,t.expectedChainId),ct.equal(i.scope.expectedGenesisHash,t.expectedGenesisHash);let a=await adoptPublishedArchive(e,t,i,check),u=e.state.read(),p={archiveHead:u.archiveHead,chargedBytes:e.state.chargedBytes(),fromIndex:u.nextIndex,manifestCid:u.manifestReceipt?.cid,nextIndex:u.nextIndex,plannedUploadBytes:0,preparedSteps:0,status:`idle`};if(a)return{...p,fromIndex:i.nextIndex,status:`adopted`};let y=await selectWindow(e,t,u,check);if(y.status===`idle`)return{...p,sourceHead:y.sourceHead};let x=await prepareWindowOrWait(e,t,u,y,check);return x===void 0?{...p,sourceHead:y.sourceHead,status:`waiting-for-index`}:t.dryRun?{...p,plannedUploadBytes:x.plannedUploadBytes,preparedSteps:x.rollups.length,reconstructedSteps:x.reconstructedSteps,sourceHead:x.sourceHead,status:`dry-run`}:await publishWindow(e,t,u,x,check)})}async function writeDurableJson(e,t){let i=D.dirname(e);await We.mkdir(i,{mode:448,recursive:!0});let a=`${e}.${st()}.tmp`,u=await We.open(a,`wx`,384);try{await u.writeFile(JSON.stringify(t)),await u.sync()}finally{await u.close()}await We.rename(a,e);let p=await We.open(i,`r`);try{await p.sync()}finally{await p.close()}}var FileArchiveWriteJournal=class{directory;constructor(e){this.directory=e}async begin(e){await writeDurableJson(this.path(e.key),e)}async finish(e){await writeDurableJson(this.path(e.key),e)}async read(e){try{return JSON.parse(await We.readFile(this.path(e),`utf8`))}catch(e){if(e.code===`ENOENT`)return;throw e}}path(e){return D.join(this.directory,`${sha256(e)}.json`)}},BackupPassOverlapError=class extends Error{constructor(){super(`A backup pass is already active for this state store`),this.name=`BackupPassOverlapError`}};function serviceUid(){let e=process.getuid;return ct.ok(e!==void 0,`Backup state requires POSIX user identity`),e()}function safeInteger(e){ct.ok(typeof e==`number`&&Number.isSafeInteger(e)&&e>=0,`Invalid backup state integer`)}function hash(e){ct.ok(typeof e==`string`&&/^[0-9a-f]{64}$/.test(e),`Invalid backup state hash`)}function checkIntent(e,t){e.attempts!==void 0&&(safeInteger(e.attempts),ct.ok(e.attempts>0,`Invalid backup upload attempt count`)),e.attemptedAt!==void 0&&ct.ok(Number.isFinite(Date.parse(e.attemptedAt)),`Invalid backup upload attempt time`),safeInteger(e.bytes),safeInteger(e.storedBytes),ct.ok(e.bytes>0&&e.storedBytes>0&&e.contentEncoding===`br`,`Invalid backup object encoding or length`),hash(e.sha256),hash(e.storedSha256);let i=/^blocks\/3\/xl1-(mainnet|sequence)-blocks-(\d+)-(\d+)-v(\d+)\.json\.br$/.exec(e.key),a=/^xl1-(mainnet|sequence)-manifest-v(\d+)\.json\.br$/.exec(e.key);if(i===null)ct.ok(a!==null,`Unexpected backup journal key`),ct.equal(e.key,namedArchiveManifestKey(t.network,Number(a[2])));else{let a=Number(i[2]);ct.equal(e.key,namedArchiveStepKey(t.network,a/i5,Number(i[4])))}}function checkReceipt(e,t){checkIntent(e,t),ct.ok(isArchiveCid(e.cid),`Invalid backup receipt CID`),ct.ok(typeof e.readBackAt==`string`&&Number.isFinite(Date.parse(e.readBackAt)),`Invalid backup receipt time`)}function chargedBytes(e){let t=Object.values(e.reservations).reduce((e,t)=>e+t.bytes*(t.attempts??1),0);return safeInteger(t),t}function checkCommittedSteps(e,t,i){let a=null;for(let[u,p]of e.steps.entries())i(p.receipt),ct.ok(p.version===1||p.version===2,`Invalid backup step version`),ct.equal(p.rollup.index,u),ct.equal(p.rollup.level,3),ct.equal(p.rollup.from,u*i5),ct.equal(p.rollup.to,(u+1)*i5-1),ct.equal(p.rollup.firstPreviousHash,a),hash(p.rollup.lastBlockHash),ct.equal(p.receipt.key,namedArchiveStepKey(t.network,u,p.version)),ct.equal(p.receipt.sha256,p.rollup.sha256),ct.equal(p.receipt.bytes,p.rollup.bytes),a=p.rollup.lastBlockHash;return a}function isSameStoredStep(e,t){let{receipt:i,rollup:a}=e;return t?.key===i.key&&t.cid===i.cid&&t.contentEncoding===i.contentEncoding&&t.bytes===i.bytes&&t.sha256===i.sha256&&t.storedBytes===i.storedBytes&&t.storedSha256===i.storedSha256&&t.firstPreviousHash===a.firstPreviousHash&&t.lastBlockHash===a.lastBlockHash&&t.version===e.version}function committedStepFromManifest(e){return{receipt:{bytes:e.bytes,cid:e.cid,contentEncoding:e.contentEncoding,key:e.key,readBackAt:e.readBackAt,sha256:e.sha256,storedBytes:e.storedBytes,storedSha256:e.storedSha256},rollup:{bytes:e.bytes,firstPreviousHash:e.firstPreviousHash,from:e.index*i5,index:e.index,lastBlockHash:e.lastBlockHash,level:3,sha256:e.sha256,to:(e.index+1)*i5-1},version:e.version}}function checkCommittedState(e,t,i){if(e.nextIndex===0)ct.equal(e.archiveHead,void 0),ct.equal(e.manifestReceipt,void 0),ct.equal(e.genesisHash,void 0),ct.equal(e.manifestVersion,0);else{ct.ok(e.archiveHead!==void 0&&e.manifestReceipt!==void 0&&e.genesisHash!==void 0),hash(e.genesisHash),t.expectedGenesisHash!==void 0&&ct.equal(e.genesisHash,t.expectedGenesisHash),i(e.manifestReceipt),ct.deepEqual(e.manifestReceipt,e.manifestReceipts.at(-1)),ct.equal(e.manifestReceipt.key,namedArchiveManifestKey(t.network,e.manifestVersion));let a=checkCommittedSteps(e,t,i);ct.equal(e.archiveHead.block,e.nextIndex*i5-1),ct.equal(e.archiveHead.hash,a)}}function checkPendingWindow(e){if(e.pendingWindow===void 0)return;let t=e.pendingWindow;safeInteger(t.fromIndex),safeInteger(t.toIndex),ct.equal(t.fromIndex,e.nextIndex),ct.ok(t.toIndex>=t.fromIndex),ct.equal(t.pinnedHead.block,(t.toIndex+1)*i5-1),hash(t.pinnedHead.hash)}function validateState(e,t){ct.ok(typeof e==`object`&&!!e&&!Array.isArray(e),`Invalid backup checkpoint`);let i=e;ct.equal(i.schema,`network.xyo.backup.state/1`),ct.deepEqual(i.scope,t,`Backup state scope differs from selected network/account/bucket/endpoint`),safeInteger(i.nextIndex),safeInteger(i.manifestVersion);let a=i.manifestReceiptsFrom??1;safeInteger(a),ct.ok(a>=1&&(i.manifestVersion===0?a===1:a<=i.manifestVersion),`Invalid backup manifest receipt history start`),ct.ok(Array.isArray(i.manifestReceipts)&&i.manifestReceipts.length===(i.manifestVersion===0?0:i.manifestVersion-a+1),`Backup manifest receipt history is incomplete`),ct.ok(Array.isArray(i.steps)&&i.steps.length===i.nextIndex,`Backup coverage is incomplete`),ct.ok(typeof i.reservations==`object`&&i.reservations!==null&&!Array.isArray(i.reservations));for(let[e,a]of Object.entries(i.reservations))ct.ok(typeof a==`object`&&!!a),safeInteger(a.bytes),ct.ok(a.bytes>0&&typeof a.confirmed==`boolean`),a.attempts!==void 0&&(safeInteger(a.attempts),ct.ok(a.attempts>0,`Invalid backup reservation attempt count`)),a.sha256!==void 0&&hash(a.sha256),ct.ok(e.startsWith(`xl1-${t.network}-manifest-v`)||e.startsWith(`blocks/3/xl1-${t.network}-blocks-`));chargedBytes(i);function confirmedReceipt(e){checkReceipt(e,t);let a=i.reservations[e.key];ct.ok(a?.confirmed,`Committed receipt lacks its paid reservation`),ct.equal(a.bytes,e.storedBytes,`Committed byte accounting differs from its receipt`),ct.equal(a.sha256,e.storedSha256,`Committed accounting hash differs from its receipt`)}for(let[e,u]of i.manifestReceipts.entries())confirmedReceipt(u),ct.equal(u.key,namedArchiveManifestKey(t.network,a+e));return checkCommittedState(i,t,confirmedReceipt),checkPendingWindow(i),i}async function assertFreshJournal(e){let t=D.join(e,`journal`),i;try{i=await We.lstat(t)}catch(e){if(e.code===`ENOENT`)return;throw e}ct.ok(i.isDirectory()&&i.uid===serviceUid(),`Backup journal must be a service-owned directory`);let a=await We.opendir(t);try{ct.equal(await a.read(),null,`Missing backup checkpoint with a nonempty durable journal; refusing budget reset`)}finally{await a.close()}}async function verifyBackupWriterLock(e,t){ct.equal(process.platform,`linux`,`Backup state requires a Linux inherited advisory flock`),ct.ok(Number.isSafeInteger(t)&&t>=3,`Invalid backup lock descriptor`);let i=et.fstatSync(t,{bigint:!0}),a=await We.lstat(D.join(e,`.writer.lock`),{bigint:!0});ct.ok(i.isFile()&&a.isFile()&&i.nlink===1n&&a.nlink===1n,`Backup lock must be a regular single-link file`),ct.equal(i.dev,a.dev),ct.equal(i.ino,a.ino),ct.equal(Number(a.uid),serviceUid(),`Backup lock must belong to the service user`);let u=i.dev>>8n&4095n|i.dev>>32n&-4096n,p=i.dev&255n|i.dev>>12n&-256n,y=await We.readFile(`/proc/locks`,`utf8`);ct.ok(y.split(`
|
|
34577
|
+
`);return p!==-1&&(t=stringEncaseCRLFWithFirstIndex(t,u,a,p)),a+t+u};Object.defineProperties(createChalk.prototype,{...V6,level:hde});const H6=createChalk();createChalk({level:I6?I6.level:0}),Uo();function hexToLast4BytesInt(e){assertEx$1(oo(e),()=>`value must be a hex string`);let t=e.slice(-8);return Number.parseInt(t,16)}function seededRandom(e){return function(){let t=Math.sin(e++)*1e4;return t-Math.floor(t)}}function shuffleWithSeed(e,t){let i=[...e].toSorted((e,t)=>String(e).localeCompare(String(t))),a=seededRandom(t);for(let e=i.length-1;e>0;e--){let t=Math.floor(a()*(e+1)),u=i[e];i[e]=i[t],i[t]=u}return i}function spanDurationInMillis(e){return e.duration[0]*1e3+e.duration[1]/1e6}(class _XyoConsoleSpanExporter extends He{static durationToLogLevel=[0,1,10,100,1e3];static logLevelToChalkColor=[H6.grey,H6.white,H6.green,H6.yellow,H6.red];_logLevel;constructor(e=0){super(),this._logLevel=e}get logLevel(){return this._logLevel}export(e){for(let t of e){let e=this.spanLevel(t);if(e<this.logLevel)continue;let i=spanDurationInMillis(t);console.log(H6.grey([`Span [${t.name}]`,this.logColor(e)(`${i}ms`),`TraceId: ${t.spanContext().traceId}`].join(`, `)))}}logColor(e){return _XyoConsoleSpanExporter.logLevelToChalkColor[e]??H6.magenta}spanLevel(e){let t=0,i=spanDurationInMillis(e);for(let e=_XyoConsoleSpanExporter.durationToLogLevel.length-1;e>=0;e--)if(i>_XyoConsoleSpanExporter.durationToLogLevel[e]){t=e;break}return t}}),Uo(),hM(),_Z();var isBaseBuildBlockOptions=e=>{if(!isObject$5(e))return!1;let t=e;return isArray(t.blockPayloads)&&isAddress(t.chainId)&&isArray(t.signers)&&isArray(t.txs)},isBuildGenesisBlockOptions=e=>{if(!isBaseBuildBlockOptions(e))return!1;let t=e;return t.previousBlockHash===null&&t.previousBlockNumber===void 0},isBuildNextBlockOptions=e=>{if(!isBaseBuildBlockOptions(e))return!1;let t=e;return isHash(t.previousBlockHash)&&isNumber(t.previousBlockNumber)&&isArray(t.previousStepHashes)};function calculateCompletedStepReward(e,t){return uP(pI[e][0]*t/pI[e][1])}function supersedesField(e){return isBuildNextBlockOptions(e)&&e.supersedes!==void 0?{supersedes:e.supersedes}:{}}function legacyEpochMeta(e){return e.find(e=>RF(e))?.epoch??Date.now()}async function buildBlock(e){let t=isBuildGenesisBlockOptions(e)?-1:e.previousBlockNumber,i=rP(t+1,!0),a=isBuildNextBlockOptions(e)?e.previousStepHashes:[],u=isBuildNextBlockOptions(e)?e.previousBlockHash:void 0,p=isBuildNextBlockOptions(e)?e.stepRewardPoolBalance:uP(0n),{chainId:y,txs:x,chainStepRewardAddress:w=AL,blockPayloads:E,protocol:D=PR,signers:A}=e,N=[];for(let[e]of x){if(e.nbf>i)throw Error(`Transaction ${await al.hash(e)} not valid for block ${i} - NBF is ${e.nbf}`);if(e.exp<i)throw Error(`Transaction ${await al.hash(e)} not valid for block ${i} - EXP is ${e.exp}`)}let P=[];for(let[e,t]of dI.entries()){if(i<t)break;if(i%t===0){if(pI[e][0]>0&&w!==`0000000000000000000000000000000000000000`){let a=rewardAddressFromStepIdentity({block:i,step:t}),u=calculateCompletedStepReward(e,p);P.push(createTransferPayload(w,{[a]:u}))}N.push(assertEx$1(u,()=>`Previous block hash is required for step ${t} at block ${i}`))}else isDefined$1(a.at(e))&&N.push(a[e])}let F=u??null,I=i,L=await validateTransactionsOpcodes(x),B=[...x.map(([e])=>e),...E,...L,...P].map(e=>Ks(e,!0)),[ee,G]=await new Aw().fields({block:I,chain:y,previous:F,step_hashes:N,protocol:D,...supersedesField(e)}).meta({$epoch:legacyEpochMeta(E),$signatures:[]}).signers(A).payloads(await al.addStorageMeta(B)).build();return assertEx$1(MI(ee),()=>`Build of BlockBoundWitness failed`),[await al.addStorageMeta(ee),G]}async function buildGenesisBlock(e,t,i,a,u=OL,p){return await buildBlock({previousBlockHash:null,chainId:e,txs:t,blockPayloads:i,signers:a,chainStepRewardAddress:u,protocol:p})}async function buildNextBlock(e,t,i,a,u=AL,p=uP(0n),y,x,w){return await buildBlock({chainId:x??e.chain,previousBlockNumber:e.block,previousStepHashes:e.step_hashes??[],previousBlockHash:e._hash,txs:t,blockPayloads:i,signers:a,protocol:y,chainStepRewardAddress:u,stepRewardPoolBalance:p,supersedes:w})}async function createProducerChainStakeIntent(e,t,i=0){let a=new al({schema:mF});return await al.addHashMeta(a.fields({from:e,exp:t,nbf:i,intent:`producer`}).build())}var createGenesisBlock=async(e,t,i,a)=>{let u=await al.addHashMeta([EH,dH,mH,_H,yH,xH,wH]),p=await createProducerChainStakeIntent(toAddress(e.address),1,0);return u.push(p),i>0n&&u.push(await al.addHashMeta(createTransferPayload(t,{[a]:i}))),await buildGenesisBlock(t,[],u,[e])};hM(),Uo(),_Z(),Ha();var U6=Object.defineProperty,_de=Object.getOwnPropertyDescriptor,vde=Object.getPrototypeOf,yde=Reflect.get,bde=/* @__PURE__ */ __name((e,t,i)=>t in e?U6(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,`__defNormalProp`),W6=/* @__PURE__ */ __name((e,t,i,a)=>{for(var u=a>1?void 0:a?_de(t,i):t,p=e.length-1,y;p>=0;p--)(y=e[p])&&(u=(a?y(t,i,u):y(u))||u);return a&&u&&U6(t,i,u),u},`__decorateClass`),G6=/* @__PURE__ */ __name((e,t,i)=>bde(e,typeof t==`symbol`?t:t+``,i),`__publicField`),xde=/* @__PURE__ */ __name((e,t,i)=>yde(vde(e),i,t),`__superGet`),K6=Cs(`network.xyo.diviner.chain.block.reward.config`,!0),BlockRewardDiviner=class extends AbstractDiviner{static configSchemas=[K6]},q6=Cs(`network.xyo.block.reward`,!0),J6=isPayloadOfSchemaType(q6);Ro.create(J6),Ro.createOptional(J6);var Y6=isPayloadOfSchemaTypeWithSources(q6);Ro.create(Y6),Ro.createOptional(Y6);var X6=Cs(`network.xyo.diviner.chain.block.reward.fixed.percent.config`,!0),FixedPercentageBlockRewardDiviner=class extends BlockRewardDiviner{_fixedPercentageDenominator;_fixedPercentageNumerator;_percentageScale;get blockRewardViewer(){return assertEx$1(this.params.blockRewardViewer,()=>`blockRewardViewer is required`)}get fixedPercentageDenominator(){return isDefined$1(this._fixedPercentageDenominator)||(this._fixedPercentageDenominator=BigInt(this.percentageScaleNumeric)),this._fixedPercentageDenominator}get fixedPercentageNumerator(){return isDefined$1(this._fixedPercentageNumerator)||(this._fixedPercentageNumerator=BigInt(Math.round(this.rewardPercentageRatio*this.percentageScaleNumeric))),this._fixedPercentageNumerator}get percentageScaleNumeric(){return isDefined$1(this._percentageScale)||(this._percentageScale=10**countDecimalPlaces(this.rewardPercentageRatio)),this._percentageScale}get rewardAddress(){return assertEx$1(asAddress(this.config.rewardAddress),()=>`rewardAddress is required`)}get rewardPercentageRatio(){return assertEx$1(this.config.rewardPercentageRatio!==void 0,()=>`rewardPercentageRatio is required`),this.config.rewardPercentageRatio}async divineHandler(e=[]){let t=filterAs(e,mL);return(await Promise.all(t.map(async e=>{let t=e.block,i=await this.blockRewardViewer.allowedRewardForBlock(t),a=i*this.fixedPercentageNumerator/this.fixedPercentageDenominator,u=i-a;assertEx$1(a>=0n,()=>`producerReward must be greater than or equal to 0`);let p=Object.fromEntries([[this.rewardAddress,toHex(a)],[AL,toHex(u)]]);return[new al({schema:SI}).fields({epoch:Date.now(),from:OL,transfers:p}).build()]}))).flat().filter(eo)}};G6(FixedPercentageBlockRewardDiviner,`configSchemas`,[K6,X6]),G6(FixedPercentageBlockRewardDiviner,`defaultConfigSchema`,X6),FixedPercentageBlockRewardDiviner=W6([creatableModule()],FixedPercentageBlockRewardDiviner);var countDecimalPlaces=e=>{if(!Number.isFinite(e))throw TypeError(`Input must be a finite number`);let t=e.toString(),i=t.indexOf(`.`);return i===-1?0:t.length-i-1},Z6=Cs(`network.xyo.diviner.chain.head.validation.config`,!0),HeadValidationDiviner=class extends AbstractDiviner{_context;_headValidationDivinerHeadUpdateTotal;_headSelector;_outArchivist;_startingHead;divineMutex=new Mutex;get allowedProducers(){return this.params.allowedProducers??this.config.allowedProducers??[]}get blockViewer(){return assertEx$1(this.params.blockViewer,()=>`Missing block viewer`)}get chainId(){return assertEx$1(this.params.chainId??this.config.chainId,()=>`Missing chain information`)}get context(){return this._context}get headSelector(){return assertEx$1(this._headSelector,()=>`Missing head selector`)}get mempoolViewer(){return assertEx$1(this.params.mempoolViewer,()=>`Missing mempool viewer`)}async createHandler(){await super.createHandler(),this._context=this.params.context??{singletons:{}},this._headValidationDivinerHeadUpdateTotal=this.meter?.createCounter(`head_validation_diviner_head_update_total`,{description:`Count of head updates performed by the diviner during head validation`}),this._headSelector=new D6({context:this.context,allowedProducers:this.allowedProducers,blockViewer:this.blockViewer,mempoolViewer:this.mempoolViewer,maxWindowSize:1e3})}async resolveOutArchivist(){if(this._outArchivist)return this._outArchivist;let e=assertEx$1(await this.resolve(assertEx$1(this.config.outArchivist,()=>`Missing outArchivist`)),()=>`Unable to resolve outArchivist [${this.config.outArchivist}]`),t=assertEx$1(rO(e),()=>`Invalid outArchivist resolved`);return this._outArchivist=t,this._outArchivist}async divineHandler(){return this.divineMutex.isLocked()?[]:await this.divineMutex.runExclusive(async()=>await this.spanAsync(`HeadValidationDiviner:divineHandler`,async()=>{try{let e=Date.now(),t=await this.headSelector.findBestHead()??this._startingHead;if(isDefined$1(t)){let i=await this.resolveOutArchivist(),a=this._startingHead?.[0],u=assertEx$1(t.at(-1),()=>`Missing best head block [HeadValidationDiviner]`),p=u[0],y=[];if(this.logger?.debug(`Validating new HeadBlock head from (block) `,a?.block,`to`,p.block),this.logger?.debug(`Validating new HeadBlock head from (hash) `,a?._hash,`to`,p._hash),p._hash===a?._hash){this.logger?.debug(`No new blocks found`,a?.block,`to`,p.block);return}let x=t.filter(e=>!isDefined$1(a)||e[0].block>a.block),w=x.flatMap(e=>flattenHydratedBlock(e));return y=[{producer:toAddress(p.addresses[0])},...y],this.logger?.info(`Validated new HeadBlock head from (block) in`,`${Date.now()-e}ms`,p.block,`to`,a?.block),this.logger?.info(`Validated new HeadBlock head from (hash) in`,`${Date.now()-e}ms`,p._hash,`to`,a?._hash),await this.spanAsync(`HeadValidationDiviner:commitToOutArchivist`,async()=>{if(w.length!==0){await i.insert(w);for(let e of y)this._headValidationDivinerHeadUpdateTotal?.add(1,e)}},this.context),await this.headSelector.finalizeChainFragment(x),this._startingHead=u,w}this.logger?.info(`No head found to validate`,this._startingHead?.[0]._hash)}catch(e){this.logger?.error(`Error in divineHandler`,e)}},this.context)??[])}};G6(HeadValidationDiviner,`configSchemas`,[...xde(HeadValidationDiviner,HeadValidationDiviner,`configSchemas`),Z6]),G6(HeadValidationDiviner,`targetSchema`,Z6),HeadValidationDiviner=W6([creatableModule()],HeadValidationDiviner);var Q6=Cs(`network.xyo.witness.archivist.next.config`,!0),ArchivistNextWitness=class extends AbstractWitness{static configSchemas=[...super.configSchemas,Q6];static defaultConfigSchema=Q6;_cursor;async getSourceArchivist(){return assertEx$1(rO(await this.resolve(assertEx$1(this.config.sourceArchivist,()=>`Missing sourceArchivist`))),()=>`Invalid sourceArchivist`)}async observeHandler(){let e=await(await this.getSourceArchivist()).next({cursor:this._cursor,order:`asc`}),t=e.at(-1);return t&&(this._cursor=t._sequence),e}},$6=isPayloadOfSchemaType(Cs(`network.xyo.witness.chain.stake.network.weighted`,!0));Ro.create($6),Ro.create($6);var e8=isPayloadOfSchemaType(Cs(`network.xyo.witness.chain.stake.network.observe`,!0));Ro.create(e8),Ro.create(e8),_Z(),Uo(),hM(),VN();var t8=Object.defineProperty,Sde=Object.getOwnPropertyDescriptor,Cde=/* @__PURE__ */ __name((e,t,i)=>t in e?t8(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,`__defNormalProp`),n8=/* @__PURE__ */ __name((e,t,i,a)=>{for(var u=a>1?void 0:a?Sde(t,i):t,p=e.length-1,y;p>=0;p--)(y=e[p])&&(u=(a?y(t,i,u):y(u))||u);return a&&u&&t8(t,i,u),u},`__decorateClass`),r8=/* @__PURE__ */ __name((e,t,i)=>Cde(e,typeof t==`symbol`?t:t+``,i),`__publicField`),i8=`Validator`,XyoValidator=class extends AbstractCreatableProvider{moniker=XyoValidator.defaultMoniker;_blockViewer;get blockViewer(){return this._blockViewer}async createHandler(){await super.createHandler(),this._blockViewer=await this.locator.getInstance(Hz)}validatePendingBlock(e){return[]}async validatePendingTransaction(e){let[t]=e;return await this.blockViewer.blockByHash(t._hash)===void 0}};r8(XyoValidator,`connectionTypes`,[]),r8(XyoValidator,`defaultMoniker`,i8),r8(XyoValidator,`dependencies`,[Hz]),r8(XyoValidator,`monikers`,[i8]),r8(XyoValidator,`providerId`,`XyoValidator`),r8(XyoValidator,`surface`,`node`),XyoValidator=n8([creatableProvider()],XyoValidator);var BaseElectionService=class extends AbstractCreatableProvider{moniker=BaseElectionService.defaultMoniker;get blockViewer(){return assertEx$1(this.params.blockViewer,()=>`No block viewer`)}get chainStakeViewer(){return assertEx$1(this.params.chainStakeViewer,()=>`No chain stake viewer`)}get stakeIntentService(){return assertEx$1(this.params.stakeIntentService,()=>`No staked intent service`)}async getCreatorCommitteeForNextBlock(e){return await this.spanAsync(`getCreatorCommitteeForNextBlock`,async()=>{let t=e.block+1,i=await this.stakeIntentService.getDeclaredCandidatesForBlock(t,`producer`),a=e._hash;return this.generateCreatorCommittee(i,a)},this.context)}generateCreatorCommittee(e,t,i=3){return shuffleWithSeed(new Set(e),hexToLast4BytesInt(t)).slice(0,i)}};r8(BaseElectionService,`connectionTypes`,[]),r8(BaseElectionService,`defaultMoniker`,`Election`),r8(BaseElectionService,`dependencies`,[]),r8(BaseElectionService,`monikers`,[`Election`]),r8(BaseElectionService,`providerId`,`BaseElectionService`),BaseElectionService=n8([creatableProvider()],BaseElectionService);var createBootstrapHead=async(e,t,i,a)=>{let u=[],p=await createGenesisBlock(e,t,i,a);u.push(p);let y=createDeclarationIntent(toAddress(e.address),`producer`,p[0].block,p[0].block+1e4),x=await buildNextBlock(p[0],[],[y],[e]);return u.push(x),u};function hasMessage(e){return typeof e==`object`&&!!e&&`message`in e}async function reportRejectedBlock(e,t,i,a){let u=Array.isArray(i)?i.map(e=>({hash:t[0]._hash,name:`BlockValidationError`,message:String(hasMessage(e)?e.message:e)})):[{hash:t[0]._hash,name:`BlockValidationError`}],p={schema:IR,block:t,errors:u,rejector:a?.address??`validator`},y=a===void 0?void 0:await buildSignedBlockRejection(p,a);await e.rejectBlock(p,y)}async function processPendingBlocks({blockValidationViewer:e,blockViewer:t,context:i,logger:a,mempoolViewer:u,finalizationRunner:p,allowedProducers:y,backoffMs:x,heartbeatInterval:w,minCandidates:E,deadLetterQueueRunner:D,observer:A,admission:N,eligibility:P,licensing:F,publishAdmissionShadow:I,timeRules:L}){let B=Date.now(),ee=await t.currentBlock(),G=new D6({context:i,logger:a,mempoolViewer:u,blockViewer:t,windowedFinalizedChain:[ee],allowedProducers:y,backoffMs:x,heartbeatInterval:w,minCandidates:E,admission:N,eligibility:P,licensing:F,publishAdmissionShadow:I,timeRules:L}),q=await G.findBestHead();if(isDefined$1(q)&&q.length>0){let t=ee[0],i=assertEx$1(q.at(-1),()=>`Missing best head block [processPendingBlocks]`)[0];if(a?.debug(`Validating new HeadBlock head from (block) `,t?.block,`to`,i.block),a?.debug(`Validating new HeadBlock head from (hash) `,t?._hash,`to`,i._hash),i._hash===t?._hash){a?.debug(`No new blocks found`,t?.block,`to`,i.block);return}let u=q.filter(e=>!isDefined$1(t)||e[0].block>t.block),y=await Promise.all(u.map(t=>Promise.resolve(e.validateBlocks([t],{value:!0,state:!0})))),x=[];for(let[e,t]of u.entries()){let i=y[e][0];qI(i)?x.push(t):(a?.error(`Block validation failed`,t[0].block,t[0]._hash,JSON.stringify(i,null,2)),D&&await reportRejectedBlock(D,t,i,A))}return a?.info(`Validated new HeadBlock head from (block) in`,`${Date.now()-B}ms`,i.block,`to`,t?.block),a?.info(`Validated new HeadBlock head from (hash) in`,`${Date.now()-B}ms`,i._hash,`to`,t?._hash),x.length>0&&await p.finalizeBlocks(x),await G.finalizeChainFragment(x),x}a?.info(`No head found to validate`,ee?.[0]._hash)}var BaseNetworkStakeStepRewardService=class extends AbstractCreatableProvider{moniker=BaseNetworkStakeStepRewardService.defaultMoniker;networkStakeStepRewardAddressHistory(e){throw Error(`Method [networkStakeStepRewardAddressHistory] not implemented.`)}networkStakeStepRewardAddressReward(e,t){throw Error(`Method [networkStakeStepRewardAddressReward] not implemented.`)}networkStakeStepRewardAddressShare(e,t){throw Error(`Method [networkStakeStepRewardAddressShare] not implemented.`)}networkStakeStepRewardAllocationsForStep(e){throw Error(`Method [networkStakeStepRewardAllocationsForStep] not implemented.`)}networkStakeStepRewardClaimedByAddress(e){throw Error(`Method [networkStakeStepRewardClaimedByAddress] not implemented.`)}networkStakeStepRewardForPosition(e,t){throw Error(`Method [networkStakeStepRewardForPosition] not implemented.`)}networkStakeStepRewardForStep(e){throw Error(`Method [networkStakeStepRewardForStep] not implemented.`)}networkStakeStepRewardForStepForPosition(e,t){throw Error(`Method [networkStakeStepRewardForStepForPosition] not implemented.`)}networkStakeStepRewardPoolRewards(e){throw Error(`Method [networkStakeStepRewardPoolRewards] not implemented.`)}networkStakeStepRewardPoolShares(e){throw Error(`Method [networkStakeStepRewardPoolShares] not implemented.`)}networkStakeStepRewardPositionWeight(e,t){throw Error(`Method [networkStakeStepRewardPositionWeight] not implemented.`)}networkStakeStepRewardPotentialPositionLoss(e,t){throw Error(`Method [networkStakeStepRewardPotentialPositionLoss] not implemented.`)}networkStakeStepRewardRandomizer(e){throw Error(`Method [networkStakeStepRewardRandomizer] not implemented.`)}networkStakeStepRewardStakerCount(e){throw Error(`Method [networkStakeStepRewardStakerCount] not implemented.`)}networkStakeStepRewardUnclaimedByAddress(e){throw Error(`Method [networkStakeStepRewardUnclaimedByAddress] not implemented.`)}networkStakeStepRewardWeightForAddress(e,t){throw Error(`Method [networkStakeStepRewardWeightForAddress] not implemented.`)}networkStakeStepRewardsForPosition(e,t){throw Error(`Method [networkStakeStepRewardsForPosition] not implemented.`)}networkStakeStepRewardsForRange(e){throw Error(`Method [networkStakeStepRewardsForRange] not implemented.`)}networkStakeStepRewardsForStepLevel(e,t){throw Error(`Method [networkStakeStepRewardsForStepLevel] not implemented.`)}};r8(BaseNetworkStakeStepRewardService,`connectionTypes`,[]),r8(BaseNetworkStakeStepRewardService,`defaultMoniker`,dB),r8(BaseNetworkStakeStepRewardService,`dependencies`,[]),r8(BaseNetworkStakeStepRewardService,`monikers`,[dB]),r8(BaseNetworkStakeStepRewardService,`providerId`,`BaseNetworkStakeStepRewardService`),BaseNetworkStakeStepRewardService=n8([creatableProvider()],BaseNetworkStakeStepRewardService);function selectSupersededCandidate(e,t,i,a){let u=e.filter(e=>e.block===i&&e.previous===a&&e.addresses.includes(t));if(u.length===0)return;let p=new Set(u.map(e=>e.supersedes).filter(isDefined$1));return(u.find(e=>!p.has(e._dataHash))??u[0])._dataHash}async function generateTransactionFeeTransfers(e,t){let i=await Promise.all(t.map(async e=>gZ.parse([await al.addStorageMeta(e[0]),await al.addStorageMeta(e[1])]))),a={};for(let e of i)a[e.boundWitness.from]=(a[e.boundWitness.from]??0n)+e.fees.base;let u={};for(let e of i){let t=transactionRequiredGas(e.data)*e.fees.gasPrice;u[e.boundWitness.from]=(u[e.boundWitness.from]??0n)+t+e.fees.priority}let p=Object.entries(a).map(([e,t])=>({schema:SI,epoch:Date.now(),from:e,transfers:Object.fromEntries([[OL,hexFromBigInt(t)]])}));for(let[t,i]of Object.entries(u)){let a=assertEx$1(p.find(e=>e.from===t),()=>`from payload not found`);a.transfers[e]=hexFromBigInt(i)}return p}async function scoreTransaction(e){let t=await gZ.parse(e),i=t.boundWitness.from,a=t.fees.gasPrice,u=transactionRequiredGas(e)*a,p=t.fees.base,y=netBalancesForPayloads({singletons:{}},e[1])[i]??0n,x=y<0n?-y:0n;return{cost:u+p+x,gasPrice:a}}async function identifyOffendingTransactions(e){let{errors:t,candidateTransactions:i}=e,a=new Set(i.map(e=>e[0]._hash)),u=/* @__PURE__ */ new Set;for(let e of t){a.has(e.hash)&&u.add(e.hash);let t=e.cause;t?.hash&&a.has(t.hash)&&u.add(t.hash)}if(u.size>0)return{offendingHashes:[...u],reason:`tx-invalid`};let p=/* @__PURE__ */ new Set;for(let e of t){let t=e.offendingTransactionHashes??[];for(let e of t)a.has(e)&&p.add(e)}if(p.size===0)return{offendingHashes:[],reason:`unknown`};let y=i.filter(e=>p.has(e[0]._hash)),x=await Promise.all(y.map(async e=>({tx:e,...await scoreTransaction(e)})));return x.sort((e,t)=>e.cost===t.cost?e.gasPrice===t.gasPrice?e.tx[0]._hash<t.tx[0]._hash?-1:1:e.gasPrice<t.gasPrice?-1:1:e.cost<t.cost?1:-1),{offendingHashes:[x[0].tx[0]._hash],reason:`block-balance`}}var wde=object$3({disableIntentRedeclaration:boolean().optional(),heartbeatInterval:number$1().optional(),rewardAddress:string$1().optional()});function producerTuningFromConfig(e){let t=e.options??{},i=wde.safeParse(t);return i.success?i.data:{}}var a8=`simpleBlockRunnerInstrumentation`;function registerSimpleBlockRunnerInstrumentation(e,t){e.singletons[a8]=t}function tryGetSimpleBlockRunnerInstrumentation(e){let t=e.singletons[a8];if(typeof t==`object`&&t&&`recordTiming`in t)return typeof t.recordTiming==`function`?t:void 0}var o8=3e5,SimpleBlockRunner=class extends AbstractCreatableProvider{moniker=SimpleBlockRunner.defaultMoniker;_blockRewardDiviner;_deadLetterQueueRunner;_excludedTransactionHashes=/* @__PURE__ */ new Map;_lastRedeclarationBlock;_rejectedTransactionsArchivist;_account;_accountBalanceViewer;_address;_blockRewardViewer;_blockValidationViewer;_chainParamsViewer;_finalizationViewer;_headEpochCache;_lastRejectedBuildAt=0;_lastSignedCandidate;_mempoolViewer;_rewardAddress;_timeSyncViewer;static get DefaultBlockSize(){return 10}static get RedeclarationDuration(){return 100}static get RedeclarationWindow(){return 100}get account(){return this._account}get accountBalanceViewer(){return this._accountBalanceViewer}get address(){return this._address}get blockRewardViewer(){return this._blockRewardViewer}get blockValidationViewer(){return this._blockValidationViewer}get finalizationViewer(){return this._finalizationViewer}get heartbeatInterval(){return this.params.heartbeatInterval??this.producerTuning.heartbeatInterval??3e5}get instrumentation(){return this.params.instrumentation??tryGetSimpleBlockRunnerInstrumentation(this.context)}get mempoolViewer(){return this._mempoolViewer}get producerTuning(){return producerTuningFromConfig(this.config)}get rejectedTransactionsArchivist(){return this._rejectedTransactionsArchivist}get rewardAddress(){return this._rewardAddress}get timeSyncViewer(){return this._timeSyncViewer}async createHandler(){let e=this.boundConnection;this._rejectedTransactionsArchivist=this.params.rejectedTransactionsArchivist??(e?await connectArchivist(e,{name:`rejected-transactions`}):await MemoryArchivist.create()),this._account=assertEx$1(this.params.account??this.contextAccount,()=>`Account is required — inject params.account or register a context signer`),this._address=toAddress(this.account.address),this._accountBalanceViewer=await this.locateAndCreate(DL),this._blockRewardViewer=await this.locateAndCreate(Wz),this._blockValidationViewer=await this.locator.getInstance(Kz),this._finalizationViewer=await this.locateAndCreate(eB),this._mempoolViewer=await this.locateAndCreate(iB),this._rewardAddress=asAddress(this.params.rewardAddress??this.producerTuning.rewardAddress??this.account.address,!0),this._timeSyncViewer=await this.locateAndCreate(bB),this._deadLetterQueueRunner=await this.locator.tryGetInstance(sz),this._chainParamsViewer=await this.locator.tryGetInstance(Jz)}async next(e){return await this.proposeNextValidBlock(e)}async produceNextBlock(e,t){let i=await this.proposeNextValidBlock(e);return t===!0?assertEx$1(i,()=>`Failed to produce next block`):i}async getBlockRewardTransfers(e){this._blockRewardDiviner??=await FixedPercentageBlockRewardDiviner.create({account:`random`,blockRewardViewer:this.blockRewardViewer,config:{rewardAddress:this.rewardAddress,rewardPercentageRatio:qL,schema:X6}});let t=new al({schema:dL}).fields({block:e}).build(),i=this._blockRewardDiviner;return await this.instrument(`blockRewardTransfers`,async()=>await i.divine([t]))}getProducerRedeclaration(e){if((this.params.disableIntentRedeclaration??this.producerTuning.disableIntentRedeclaration)===!0)return;let t=e.block;if(!(isDefined$1(this._lastRedeclarationBlock)&&t<this._lastRedeclarationBlock+SimpleBlockRunner.RedeclarationDuration))return this._lastRedeclarationBlock=t,createDeclarationIntent(this.address,`producer`,t,t+SimpleBlockRunner.RedeclarationDuration)}async proposeNextValidBlock(e,t,i=!1){let a=t??this.params.validateBalances??!0;return await this.spanAsync(`proposeNextValidBlock`,async()=>{try{if(this.isWithinRejectedBuildBackoff(i))return;let{block:t}=assertEx$1(NI(e),()=>`Invalid head block`),u=t+1,p=await this.finalizationViewer.chainId(),y=await this.instrument(`mempoolPendingTransactionsFetch`,async()=>await this.mempoolViewer.pendingTransactions({limit:SimpleBlockRunner.DefaultBlockSize}));this.evictStaleExclusions(t);let x=y.filter(e=>!this._excludedTransactionHashes.has(e[0]._hash)),w=await this.rejectWrongChainTransactions(x,p);this.logger?.log(`Pending Tx Count ${w.length}`);let E=[],D=await this.getProducerRedeclaration(e);if(D&&E.push(D),w.length===0&&!i&&!await this.heartbeatRequired(e))return;let A=await this.getBlockRewardTransfers(u);E.push(...A);let N=await this.generateTimePayload(),P=await this.filterByFunded(e._hash,w,a),F=await generateTransactionFeeTransfers(this.address,P),I=(await this.accountBalanceViewer.accountBalances([AL]))[AL],{block:L,errors:B}=await this.runBuildValidateRetryLoop({head:e,chainId:p,stepRewardPoolBalance:I,nonTxPayloads:E,timePayload:N,initialFundedTransactions:P,initialFundedTransfers:F});return await this.commitProposedBlock(L,B)}catch(e){throw this.logger?.error(`Error proposing next valid block: ${e.message}`),e}},this.context)}addTransferOutflow(e,t){let i=e;for(let[e,a=`00`]of Object.entries(t.transfers))e!==t.from&&(i+=hexToBigInt(a));return i}async commitProposedBlock(e,t){if(t.length===0&&qI(e))return this._lastRejectedBuildAt=0,e;e!==void 0&&(this._lastRejectedBuildAt=Date.now(),await this.rejectExhaustedBlock(e,t))}computeTransactionOutflow(e){let[t,i]=e,{base:a,gasLimit:u,priority:p}=t.fees,y=hexToBigInt(a)+hexToBigInt(p)+hexToBigInt(u),x=new Set(t.payload_hashes);for(let e of i)x.has(e._hash)&&TI(e)&&e.from===t.from&&(y=this.addTransferOutflow(y,e));return y}evictStaleExclusions(e){for(let[t,i]of this._excludedTransactionHashes)i.reason===`block-balance`&&e>i.excludedAtBlock&&this._excludedTransactionHashes.delete(t)}async filterByFunded(e,t,i=!1){if(!i)return t;let a=[],u=await this.readSenderBalances(e,t),p=/* @__PURE__ */ new Map;for(let e of t){let{from:t}=e[0],i=u.get(t)??uP(0n),y=(p.get(t)??0n)+this.computeTransactionOutflow(e);i>=y?(p.set(t,y),a.push(e)):this.logger?.debug(`filterByFunded: dropping tx ${e[0]._hash} from ${t} \u2014 cumulative outflow ${y} > balance ${i}`)}return a}async generateTimePayload(){let e=Date.now(),t=await this.instrument(`timePayloadGeneration`,async()=>await this.timeSyncViewer.currentTimePayload()),i=Date.now()-e;return i>100&&this.logger?.warn(`[Slow] Generated time payload in ${i}ms`),t}async headEpoch(e){let t=this._headEpochCache;if(t?.hash===e._hash)return t.epoch;try{let t=await this.timeSyncViewer.convertTime(`xl1`,`epoch`,e.block);return t<=0?void 0:(this._headEpochCache={epoch:t,hash:e._hash},t)}catch(e){this.logger?.warn(`Could not read the head's signed epoch for heartbeat pacing: ${String(e)}`);return}}async heartbeatRequired(e){let t=await this.headEpoch(e);return!isDefined$1(t)||Date.now()-t>this.heartbeatInterval}async instrument(e,t){let i=this.instrumentation;if(i===void 0)return await t();let a=Date.now();try{return await t()}finally{try{i.recordTiming(e,Date.now()-a)}catch(e){this.logger?.warn(`SimpleBlockRunner instrumentation failed: ${String(e)}`)}}}isWithinRejectedBuildBackoff(e){return e||Date.now()-this._lastRejectedBuildAt>=SimpleBlockRunner.RejectedBuildBackoffMs?!1:(this.logger?.debug(`Skipping block production during rejected-build backoff`),!0)}async previousOwnCandidateHash(e,t){let i=this._lastSignedCandidate;return i?.block===e&&i.previous===t?i.hash:selectSupersededCandidate((await this.instrument(`mempoolPendingBlocksFetch`,async()=>await this.mempoolViewer.pendingBlocks())).map(([e])=>e),this.address,e,t)}async readSenderBalances(e,t){let i=[...new Set(t.map(e=>e[0].from))];if(i.length===0)return/* @__PURE__ */ new Map;let a=await this.accountBalanceViewer.accountBalances(i,{head:e});return new Map(i.map(e=>[e,a[e]??uP(0n)]))}async rejectExhaustedBlock(e,t){if(this.logger?.warn(`Validation of produced block failed: ${t.at(0)?.message}`),this._deadLetterQueueRunner){let i=t.map(t=>({hash:e[0]._hash,name:`BlockValidationError`,message:t.message??t}));await this._deadLetterQueueRunner.rejectBlock({schema:IR,block:e,errors:i,rejector:`producer`})}else await this.rejectedTransactionsArchivist.insert(e[1])}async rejectWrongChainTransactions(e,t){let i=t.toLowerCase(),a=[],u=[];for(let t of e)t[0].chain.toLowerCase()===i?a.push(t):u.push(t);if(u.length>0){this.logger?.warn(`Rejecting ${u.length} transaction(s) targeting non-local chain`);let e=this._deadLetterQueueRunner;await(e?Promise.all(u.map(t=>e.rejectTransaction({schema:BR,transaction:t,errors:[{hash:t[0]._hash,name:`TransactionChainMismatch`,message:`Transaction chain ${t[0].chain} does not match local chain ${i}`}],rejector:`producer`}))):this.rejectedTransactionsArchivist.insert(u.map(e=>e[0])))}return a}async resolveSupersedes(e){let t=this._chainParamsViewer;if(t===void 0)return;let i=await t.tryCurrentParams(),a=e.block+1;return i===void 0||!isRuleActiveAt(i,`supersedes-field`,a)?void 0:await this.previousOwnCandidateHash(a,e._hash)}async runBuildValidateRetryLoop(e){let{chainId:t,head:i,initialFundedTransactions:a,initialFundedTransfers:u,nonTxPayloads:p,stepRewardPoolBalance:y,timePayload:x}=e,w=await this.resolveSupersedes(i),E=Math.max(1,a.length),D=a,A=u,N,P=[];for(let e=0;e<=E;e++){let a=[...p,...A,x];this.logger?.info(`Building block ${i.block+1}${e>0?` (retry ${e})`:``}`),N=await buildNextBlock(i,D,a,[this.account],AL,y,void 0,t,w);let u=await this.blockValidationViewer.validateBlock(N,{value:!0,state:!0,head:i._hash});if(qI(u))return this._lastSignedCandidate={block:u[0].block,hash:u[0]._dataHash,previous:i._hash},{block:u,errors:[]};if(P=u,e===E)break;let{offendingHashes:F,reason:I}=await identifyOffendingTransactions({candidateTransactions:D,errors:u});if(F.length===0||I===`unknown`)break;for(let e of F)this._excludedTransactionHashes.set(e,{excludedAtBlock:i.block,reason:I});let L=new Set(F);D=D.filter(e=>!L.has(e[0]._hash)),A=await generateTransactionFeeTransfers(this.address,D),this.logger?.warn(`Block validation failed (attempt ${e+1}); excluded ${F.length} tx(s), retrying`)}return{block:N,errors:P}}};r8(SimpleBlockRunner,`RejectedBuildBackoffMs`,1e3),r8(SimpleBlockRunner,`connectionTypes`,[`lmdb`,`mongo`,`memory`]),r8(SimpleBlockRunner,`defaultMoniker`,rz),r8(SimpleBlockRunner,`dependencies`,[DL,Wz,Kz,eB,iB,bB]),r8(SimpleBlockRunner,`monikers`,[rz]),r8(SimpleBlockRunner,`providerId`,`SimpleBlockRunner`),r8(SimpleBlockRunner,`surface`,`node`),SimpleBlockRunner=n8([creatableProvider()],SimpleBlockRunner),_Z();function createArtifactLedger(){return{artifacts:/* @__PURE__ */ new Map,byOwner:/* @__PURE__ */ new Map}}function cloneArtifactLedger(e){return{artifacts:new Map([...e.artifacts].map(([e,t])=>[e,{...t}])),byOwner:new Map([...e.byOwner].map(([e,t])=>[e,new Set(t)]))}}function indexOwner(e,t,i){let a=e.get(t)??/* @__PURE__ */ new Set;a.add(i),e.set(t,a)}function unindexOwner(e,t,i){let a=e.get(t);a!==void 0&&(a.delete(i),a.size===0&&e.delete(t))}function registerArtifact(e,t,i){return e.artifacts.has(t.hash)?`already-registered`:(e.artifacts.set(t.hash,{creator:t.signer,id:t.hash,inscribedAt:i,inscribedBy:t.txHash,owner:t.signer,schema:t.schema}),indexOwner(e.byOwner,t.signer,t.hash),`registered`)}function transferArtifact(e,t,i){let a=e.artifacts.get(t.inscriptionId);return a===void 0?`unknown-artifact`:a.owner===i?(unindexOwner(e.byOwner,a.owner,a.id),a.owner=t.to,indexOwner(e.byOwner,t.to,a.id),`transferred`):`not-owner`}var s8=`network.xyo.ordinal`;sentinelAddressFromSchema(s8);function inscribeMarkAddress(e){return sentinelAddressFromSchema(s8,e)}function transferRecipients(e,t){let i=/* @__PURE__ */ new Set;for(let a of e.payload_hashes){let u=t.get(a);if(TI(u)&&u.from===e.from)for(let e of Object.keys(u.transfers))i.add(e)}return i}function inscribeMarkedHashes(e,t){let i=/* @__PURE__ */ new Set,a=transferRecipients(e,t);if(a.size===0)return i;for(let t of e.payload_hashes)a.has(inscribeMarkAddress(t))&&i.add(t);return i}function collectSubstrateRefs(e,t){let[i,a]=e,u=new Map(a.map(e=>[e._hash,e])),p=[];for(let e of i.payload_hashes){let i=u.get(e);if(!TP(i))continue;let a=inscribeMarkedHashes(i,u);for(let[u,y]of i.payload_hashes.entries()){let x=i.payload_schemas[u];if(x===void 0)continue;let w=a.has(y);(w||t.has(x))&&p.push({hash:y,index:u,isInscribeMarked:w,schema:x,signer:i.from,txHash:e})}}return p}hM(),Uo(),za(),_Z(),DX(),VN();var c8=Object.defineProperty,Tde=Object.getOwnPropertyDescriptor,Ede=/* @__PURE__ */ __name((e,t,i)=>t in e?c8(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,`__defNormalProp`),l8=/* @__PURE__ */ __name((e,t,i,a)=>{for(var u=a>1?void 0:a?Tde(t,i):t,p=e.length-1,y;p>=0;p--)(y=e[p])&&(u=(a?y(t,i,u):y(u))||u);return a&&u&&c8(t,i,u),u},`__decorateClass`),u8=/* @__PURE__ */ __name((e,t,i)=>Ede(e,typeof t==`symbol`?t:t+``,i),`__publicField`),d8=Cs(`network.xyo.license.assign`,!0),f8=/* @__PURE__ */ object$5({address:us,exp:/* @__PURE__ */ optional$2(int$1().check(/* @__PURE__ */ _gte(0)))}),Dde=/* @__PURE__ */ object$5({license:po,operators:/* @__PURE__ */ array$2(f8)}),Ode=zodIsFactory(/* @__PURE__ */ extend(PayloadZodOfSchema(d8),Dde.shape)),p8=Cs(`network.xyo.license.issue`,!0),kde=/* @__PURE__ */ object$5({nbf:int$1().check(/* @__PURE__ */ _gte(0)),offering:po,serial:int$1().check(/* @__PURE__ */ _gte(0))}),Ade=zodIsFactory(/* @__PURE__ */ extend(PayloadZodOfSchema(p8),kde.shape)),m8=Cs(`network.xyo.license.offering`,!0),h8=/* @__PURE__ */ _enum$1([`none`,`owner`,`issuer`]),jde=/* @__PURE__ */ object$5({cap:/* @__PURE__ */ nullable$2(int$1().check(/* @__PURE__ */ _gte(1))),capacity:int$1().check(/* @__PURE__ */ _gte(1)),name:/* @__PURE__ */ string$3(),renewal:h8,term:/* @__PURE__ */ nullable$2(int$1().check(/* @__PURE__ */ _gte(1)))}),Mde=zodIsFactory(/* @__PURE__ */ extend(PayloadZodOfSchema(m8),jde.shape)),g8=Cs(`network.xyo.license.renew`,!0),Nde=/* @__PURE__ */ object$5({license:po}),Pde=zodIsFactory(/* @__PURE__ */ extend(PayloadZodOfSchema(g8),Nde.shape));function createLicenseLedger(){return{byOperator:/* @__PURE__ */ new Map,byOwner:/* @__PURE__ */ new Map,licenses:/* @__PURE__ */ new Map,offerings:/* @__PURE__ */ new Map}}function cloneIndex(e){return new Map([...e].map(([e,t])=>[e,new Set(t)]))}function cloneLicenseLedger(e){return{byOperator:cloneIndex(e.byOperator),byOwner:cloneIndex(e.byOwner),licenses:new Map([...e.licenses].map(([e,t])=>[e,{...t,operators:t.operators.map(e=>({...e}))}])),offerings:new Map([...e.offerings].map(([e,t])=>[e,{...t}]))}}function indexLicense(e,t,i){let a=e.get(t)??/* @__PURE__ */ new Set;a.add(i),e.set(t,a)}function unindexLicense(e,t,i){let a=e.get(t);a!==void 0&&(a.delete(i),a.size===0&&e.delete(t))}function applyLicenseOffering(e,t,i){return e.offerings.has(t.id)?`offering-exists`:(e.offerings.set(t.id,{cap:i.cap,capacity:i.capacity,createdAt:t.inscribedAt,id:t.id,issued:0,issuer:t.creator,name:i.name,renewal:i.renewal,term:i.term}),`offering-created`)}function applyLicenseIssue(e,t,i){if(e.licenses.has(t.id))return`license-exists`;let a=e.offerings.get(i.offering);return a===void 0?`unknown-offering`:t.creator===a.issuer?a.cap!==null&&a.issued>=a.cap?`cap-reached`:(a.issued+=1,e.licenses.set(t.id,{exp:a.term===null?null:i.nbf+a.term,id:t.id,issuedAt:t.inscribedAt,nbf:i.nbf,offering:a.id,operators:[],owner:t.owner,serial:i.serial}),indexLicense(e.byOwner,t.owner,t.id),`issued`):`not-issuer`}function reindexOperators(e,t,i){for(let i of t.operators)unindexLicense(e.byOperator,i.address,t.id);t.operators=i.map(e=>({...e}));for(let i of t.operators)indexLicense(e.byOperator,i.address,t.id)}function applyLicenseAssign(e,t,i){let a=e.licenses.get(t.license);if(a===void 0)return`unknown-license`;if(a.owner!==i)return`not-owner`;let u=e.offerings.get(a.offering);return u!==void 0&&t.operators.length>u.capacity?`over-capacity`:new Set(t.operators.map(e=>e.address)).size===t.operators.length?(reindexOperators(e,a,t.operators),`assigned`):`duplicate-operator`}function applyLicenseRenew(e,t,i,a){let u=e.licenses.get(t.license);if(u===void 0)return`unknown-license`;let p=e.offerings.get(u.offering);return p===void 0||p.term===null||u.exp===null?`perpetual`:p.renewal===`none`?`not-renewable`:i===(p.renewal===`owner`?u.owner:p.issuer)?(u.exp=Math.max(u.exp,a)+p.term,`renewed`):`not-authorized`}function onLicenseTransferred(e,t,i){let a=e.licenses.get(t);return a===void 0?`unknown-license`:(unindexLicense(e.byOwner,a.owner,a.id),a.owner=i,indexLicense(e.byOwner,i,a.id),reindexOperators(e,a,[]),`cleared`)}var Fde=/* @__PURE__ */ new Set([d8,p8,m8,g8,BP]),_8=class _LicenseLedgerFold{static schemas=Fde;_artifacts=createArtifactLedger();_bodies=/* @__PURE__ */ new Map;_dropped=[];_graceBlocks;_head;_licenses=createLicenseLedger();_window=[];constructor(e){if(!Number.isInteger(e.graceBlocks)||e.graceBlocks<0)throw Error(`LicenseLedgerFold: graceBlocks must be a non-negative integer, got ${e.graceBlocks}`);this._graceBlocks=e.graceBlocks}get artifacts(){return this._artifacts}get dropped(){return this._dropped}get head(){return this._head}get licenses(){return this._licenses}applyBlock(e,t=[]){let i=e[0].block;if(this._head!==void 0&&i!==this._head.block+1)throw Error(`LicenseLedgerFold: expected block ${this._head.block+1}, got ${i}`);this.learn(t);let a=collectSubstrateRefs(e,_LicenseLedgerFold.schemas);if(a.length>0){let e={before:this.snapshot(),height:i,refs:a};this._window.push(e),this.applyEntry(e)}return this._head={block:i,hash:e[0]._hash},this.prune(),this.pending()}bodies(){return[...this._bodies.values()]}hasBody(e){return this._bodies.has(e)}learn(e){let t;for(let i of e){if(this._bodies.has(i._hash))continue;this._bodies.set(i._hash,i);let e=this._window.findIndex(e=>e.refs.some(e=>e.hash===i._hash));e!==-1&&(t===void 0||e<t)&&(t=e)}return t!==void 0&&this.replayFrom(t),this.pending()}pending(){return this._window.flatMap(e=>e.refs.filter(e=>!this._bodies.has(e.hash)).map(t=>({...t,height:e.height})))}applyEntry(e){for(let t of e.refs)this.applyRef(t,e.height)}applyRef(e,t){e.isInscribeMarked&®isterArtifact(this._artifacts,e,t);let i=this._bodies.get(e.hash);if(i===void 0)return;let a=this._artifacts.artifacts.get(e.hash);switch(e.schema){case m8:a!==void 0&&Mde(i)&&applyLicenseOffering(this._licenses,a,i);break;case p8:a!==void 0&&Ade(i)&&applyLicenseIssue(this._licenses,a,i);break;case d8:Ode(i)&&applyLicenseAssign(this._licenses,i,e.signer);break;case g8:Pde(i)&&applyLicenseRenew(this._licenses,i,e.signer,t);break;case BP:UP(i)&&transferArtifact(this._artifacts,i,e.signer)===`transferred`&&onLicenseTransferred(this._licenses,i.inscriptionId,i.to)}}prune(){if(this._head===void 0)return;let e=this._head.block-this._graceBlocks;for(;this._window.length>0&&this._window[0]!==void 0&&this._window[0].height<e;){let[e]=this._window.splice(0,1);if(e===void 0)break;for(let t of e.refs)this._bodies.has(t.hash)||this._dropped.push({...t,height:e.height})}}replayFrom(e){let t=this._window[e];if(t!==void 0){this._artifacts=cloneArtifactLedger(t.before.artifacts),this._licenses=cloneLicenseLedger(t.before.licenses);for(let t of this._window.slice(e))t.before=this.snapshot(),this.applyEntry(t)}}snapshot(){return{artifacts:cloneArtifactLedger(this._artifacts),licenses:cloneLicenseLedger(this._licenses)}}},v8=`license/v1`;function licenseIndexHeadPath(){return`${v8}/head.json`}function licenseIndexSnapshotPath(e){return`${v8}/snapshots/${e}.json`}function licenseIndexBodyPath(e){return`${v8}/bodies/${e}.json`}var y8=Cs(`network.xyo.license.index.snapshot`,!0),b8=int$1().check(/* @__PURE__ */ _gte(0)),Ide=/* @__PURE__ */ object$5({cap:/* @__PURE__ */ nullable$2(int$1()),capacity:int$1(),createdAt:b8,id:po,issued:int$1(),issuer:us,name:/* @__PURE__ */ string$3(),renewal:h8,term:/* @__PURE__ */ nullable$2(int$1())}),Lde=/* @__PURE__ */ object$5({exp:/* @__PURE__ */ nullable$2(b8),id:po,issuedAt:b8,nbf:b8,offering:po,operators:/* @__PURE__ */ array$2(f8),owner:us,serial:int$1()}),Rde=/* @__PURE__ */ object$5({hash:po,height:b8,snapshot:po}),zde=/* @__PURE__ */ object$5({head:/* @__PURE__ */ object$5({block:b8,hash:po}),licenses:/* @__PURE__ */ array$2(Lde),offerings:/* @__PURE__ */ array$2(Ide),schema:/* @__PURE__ */ literal$2(y8)}),x8=zodIsFactory(Rde),Bde=zodIsFactory(zde),byId=(e,t)=>e.id.localeCompare(t.id);function snapshotFromLedger(e,t){return{head:{block:t.block,hash:t.hash},licenses:[...e.licenses.values()].toSorted(byId).map(e=>({...e,operators:e.operators.map(e=>({...e}))})),offerings:[...e.offerings.values()].toSorted(byId).map(e=>({...e})),schema:y8}}function ledgerFromSnapshot(e){let t=createLicenseLedger();for(let i of e.offerings)t.offerings.set(i.id,{...i});for(let i of e.licenses){let e={...i,operators:i.operators.map(e=>({...e}))};t.licenses.set(e.id,e),indexLicense(t.byOwner,e.owner,e.id);for(let i of e.operators)indexLicense(t.byOperator,i.address,e.id)}return t}async function snapshotFingerprint(e){return await al.dataHash({licenses:e.licenses,offerings:e.offerings,schema:e.schema})}async function publishedHead(e){let t=await e.readObject(licenseIndexHeadPath());if(t!==void 0){if(!x8(t))throw Error(`publishLicenseIndex: the published head at ${licenseIndexHeadPath()} does not parse`);return t}}async function writeBodies(e,t){let i=0;for(let a of t){let t=licenseIndexBodyPath(a._hash);await e.hasObject(t)||(await e.writeObject(t,a,!0),i+=1)}return i}async function publishLicenseIndex(e){let{head:t,ledger:i,store:a}=e,u=await publishedHead(a);if(u!==void 0&&u.height>t.block)return null;let p=await writeBodies(a,e.bodies??[]),y=snapshotFromLedger(i,t),x=await snapshotFingerprint(y),w=licenseIndexSnapshotPath(x),E=!await a.hasObject(w);E&&await a.writeObject(w,y,!0);let D={hash:t.hash,height:t.block,snapshot:x},A=u?.height!==D.height||u.hash!==D.hash||u.snapshot!==D.snapshot;return A&&await a.writeObject(licenseIndexHeadPath(),D,!1),!A&&!E&&p===0?null:{bodiesWritten:p,head:D,snapshotWritten:E}}var S8=`LicenseViewer`;function isLicenseViewer(e){let t=e;return typeof t?.sync==`function`&&typeof t.head==`function`&&typeof t.ledger==`function`&&typeof t.licensingOperatorAt==`function`}function isLicenseCurrentAt(e,t){return e.nbf<=t&&(e.exp===null||t<=e.exp)}function isOperatorActiveAt(e,t){return e.exp===void 0||t<=e.exp}function recordsFor(e,t){let i=[];for(let a of t??[]){let t=e.licenses.get(a);t!==void 0&&i.push(t)}return i}function licensesByOwner(e,t){return recordsFor(e,e.byOwner.get(t))}function licensesByOperator(e,t){return recordsFor(e,e.byOperator.get(t))}function isLicenseRecognized(e,t,i){let a=e.offerings.get(t.offering);return a!==void 0&&i.issuers.has(a.issuer)&&(i.offerings===void 0||i.offerings.has(a.id))}function licensingOperatorAt(e,t,i,a){return licensesByOperator(e,t).find(u=>isLicenseCurrentAt(u,i)&&isLicenseRecognized(e,u,a)&&u.operators.some(e=>e.address===t&&isOperatorActiveAt(e,i)))}var RestLicenseViewer=class extends AbstractRestReader{moniker=RestLicenseViewer.defaultMoniker;_head;_ledger=createLicenseLedger();_snapshot;get baseUrl(){let{config:e}=RestLicenseViewer.requireBoundConnection(this.config);if(e.type!==`rest`)throw Error(`Provider "${this.moniker}" requires a rest connection`);return e.baseUrl.replace(/\/+$/,``)}async createHandler(){await super.createHandler(),RestLicenseViewer.requireBoundConnection(this.config)}head(){return this._head}ledger(){return this._ledger}license(e){return this._ledger.licenses.get(e)}licensesByOperator(e){return licensesByOperator(this._ledger,e)}licensesByOwner(e){return licensesByOwner(this._ledger,e)}licensingOperatorAt(e,t,i){return licensingOperatorAt(this._ledger,e,t,i)}offering(e){return this._ledger.offerings.get(e)}async sync(){let e=await this.readJson(`${this.baseUrl}/${licenseIndexHeadPath()}`);if(!e.ok||!x8(e.data))return this._head;let t=e.data;if(t.snapshot!==this._snapshot){let e=await this.readJson(`${this.baseUrl}/${licenseIndexSnapshotPath(t.snapshot)}`);if(!e.ok||!Bde(e.data)||await snapshotFingerprint(e.data)!==t.snapshot)return this._head;this._ledger=ledgerFromSnapshot(e.data),this._snapshot=t.snapshot}return this._head={block:t.height,hash:t.hash},this._head}};u8(RestLicenseViewer,`connectionTypes`,[`rest`]),u8(RestLicenseViewer,`defaultMoniker`,S8),u8(RestLicenseViewer,`dependencies`,[]),u8(RestLicenseViewer,`monikers`,[S8]),u8(RestLicenseViewer,`providerId`,`RestLicenseViewer`),u8(RestLicenseViewer,`surface`,`node`),RestLicenseViewer=l8([creatableProvider()],RestLicenseViewer);var Vde=100;function continuingRun$1(e,t){let i=[];for(let a of t.toSorted((e,t)=>e[0].block-t[0].block)){let t=a[0].block,u=e+i.length;if(!(t<u)){if(t>u)break;i.push(a)}}return i}__name(continuingRun$1,`continuingRun`);var LicenseLedgerSync=class{fold;_floorBlock;_inFlight;_isCatchingUp=!1;_pageSize;_pagesPerPass;_sources;constructor(e,t){this._sources=e,this._floorBlock=Math.max(0,Math.floor(t.floorBlock)),this._pageSize=Math.max(1,Math.floor(t.pageSize??Vde)),this._pagesPerPass=Math.max(1,Math.floor(t.pagesPerPass??5)),this.fold=new _8({graceBlocks:t.graceBlocks})}async sync(e){let t=this._inFlight;if(t!==void 0)return await t;let i=this.run(Math.max(1,Math.floor(e?.maxPages??this._pagesPerPass)));this._inFlight=i;try{return await i}finally{this._inFlight=void 0}}async fetch(e){let t=[...new Set(e)].filter(e=>!this.fold.hasBody(e)),i=this._sources.bodies;if(i===void 0||t.length===0)return[];let a=(await i.get(t)).filter(e=>Gs(e));return await al.addHashMeta(a)}async foldBlock(e){let t=collectSubstrateRefs(e,_8.schemas),i=await this.fetch(t.map(e=>e.hash));this.fold.applyBlock(e,i)}async retryPending(){let e=this.fold.pending();e.length!==0&&this.fold.learn(await this.fetch(e.map(e=>e.hash)))}async run(e){let t=(await this._sources.blockViewer.currentBlock())[0].block;await this.retryPending();let i=this.fold.head===void 0?this._floorBlock:this.fold.head.block+1;for(let a=0;a<e&&i<=t;a++){let e=Math.min(i+this._pageSize-1,t),a=await this._sources.blockViewer.blocksByNumber(rP(e,!0),e-i+1),u=continuingRun$1(i,a);if(u.length===0){this._sources.logger?.warn(`LicenseLedgerSync: no blocks returned for ${i}..${e}; stopping this pass`);break}for(let e of u)await this.foldBlock(e);if(i+=u.length,i<=e)break}let a=this.fold.head;return a!==void 0&&a.block<t?(this._isCatchingUp=!0,this._sources.logger?.info(`LicenseLedgerSync: ledger folded to block ${a.block}, catching up to ${t}`)):this._isCatchingUp&&(this._isCatchingUp=!1,this._sources.logger?.info(`LicenseLedgerSync: ledger caught up at block ${t}`)),a}},Hde=object$3({floorBlock:number$1().int().nonnegative().default(0),graceBlocks:number$1().int().nonnegative().default(100),pageSize:number$1().int().positive().optional(),pagesPerPass:number$1().int().positive().default(5)}),SimpleLicenseViewer=class extends AbstractCreatableProvider{moniker=SimpleLicenseViewer.defaultMoniker;_options;_sync;get ledgerSync(){return assertEx$1(this._sync,()=>`SimpleLicenseViewer: not created`)}get options(){return this._options??=Hde.parse(this.config.options??{}),this._options}bodies(){return this.ledgerSync.fold.bodies()}async createHandler(){await super.createHandler();let e=await this.locator.getInstance(Hz),t=await this.locator.tryGetInstance(ZR);t===void 0&&this.logger?.warn(`SimpleLicenseViewer: no DataLakeViewer is bound — no body is findable, so no license will ever be usable; bind a rest-datalake connection`);let{floorBlock:i,graceBlocks:a,pageSize:u,pagesPerPass:p}=this.options;this._sync=new LicenseLedgerSync({blockViewer:e,bodies:t,logger:this.logger},{floorBlock:i,graceBlocks:a,pageSize:u,pagesPerPass:p})}head(){return this.ledgerSync.fold.head}ledger(){return this.ledgerSync.fold.licenses}license(e){return this.ledgerSync.fold.licenses.licenses.get(e)}licensesByOperator(e){return licensesByOperator(this.ledgerSync.fold.licenses,e)}licensesByOwner(e){return licensesByOwner(this.ledgerSync.fold.licenses,e)}licensingOperatorAt(e,t,i){return licensingOperatorAt(this.ledgerSync.fold.licenses,e,t,i)}offering(e){return this.ledgerSync.fold.licenses.offerings.get(e)}async sync(e){return await this.ledgerSync.sync(e)}};u8(SimpleLicenseViewer,`connectionTypes`,[`none`]),u8(SimpleLicenseViewer,`defaultMoniker`,S8),u8(SimpleLicenseViewer,`dependencies`,[Hz]),u8(SimpleLicenseViewer,`monikers`,[S8]),u8(SimpleLicenseViewer,`providerId`,`SimpleLicenseViewer`),u8(SimpleLicenseViewer,`surface`,`node`),SimpleLicenseViewer=l8([creatableProvider()],SimpleLicenseViewer);function findElevatingTransaction(e,[,t]){let i=`${iR}|${e._hash}`;return t.filter(e=>TP(e)).find(t=>t.payload_hashes.includes(e._hash)&&t.script?.includes(i)===!0)}async function validateSlashPayloadInBlock(e,t,i,a,u,p){let y=i[0].block,x=await resolveRuleParams(e,y),w=requireRuleActive(x,`slash-payloads`,y,p);if(w!==void 0)return{errors:[Error(w)],params:x};if(!a(t)||!Rs(t))return{errors:[/* @__PURE__ */ Error(`${p} failed its identity check`)],params:x};let E=findElevatingTransaction(t,i);return E===void 0?{errors:[/* @__PURE__ */ Error(`${p} must be elevated from a transaction`)],params:x}:u(t)===E.from?{errors:[],params:x,transaction:E}:{errors:[/* @__PURE__ */ Error(`${p} from must equal elevating transaction from`)],params:x}}function validateStrictClaimFields(e){let t=Object.keys(e).filter(e=>!C8.has(e)).map(e=>`Unknown Claim field ${e}`),i=`$sources`in e?e.$sources:void 0;if(i!==void 0){if(Array.isArray(i))for(let[e,a]of i.entries())typeof a==`string`&&fo.test(a)||t.push(`Claim $sources/${e} must be a hash`);else t.push(`Claim $sources must be an array of hashes`)}return t}function claimError(e,t,i,a){return new InBlockPayloadValidationError(e._hash??t[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,e,i,a)}function indexesOf(e,t){let i=[];for(let[a,u]of e.entries())u===t&&i.push(a);return i}function validateClaimSchemaPairs(e,t,i){let a=i??t[0],u=i===void 0?`Block`:`Transaction ${i._hash}`,p=indexesOf(a.payload_hashes,e._hash);return p.length===0?[claimError(e,t,`${u} does not commit Claim root hash ${e._hash}`)]:p.some(e=>a.payload_schemas[e]!==vF)?[claimError(e,t,`${u} does not pair every Claim root hash with ${vF}`)]:[]}function claimElevationAttempts(e,[,t]){let i=`${iR}|${e._hash}`,a=`${i}|`;return t.filter(e=>TP(e)).flatMap(e=>{let t=e.script??[],u=t.filter(e=>e===i).length,p=t.filter(e=>e.startsWith(a));return u===0&&p.length===0?[]:{malformedOperations:p,transaction:e,validOperationCount:u}})}function validateElevatingTransaction(e,t,i,a){let u=[],{malformedOperations:p,transaction:y,validOperationCount:x}=a;if(p.length>0&&u.push(claimError(t,i,`Transaction ${y._hash} contains malformed Claim elevation operations: ${p.join(`, `)}`)),x>1&&u.push(claimError(t,i,`Transaction ${y._hash} contains duplicate Claim elevation operations`)),x!==1)return u;u.push(...validateClaimSchemaPairs(t,i,y)),y.addresses.includes(e.source)||u.push(claimError(t,i,`Claim source ${e.source} is not a signer of transaction ${y._hash}`));let w=new Set(y.payload_hashes),E=e.hashes.filter(e=>!w.has(e));return E.length>0&&u.push(claimError(t,i,`Transaction ${y._hash} does not commit every Claim hash: ${E.join(`, `)}`)),u}function toAmount(e){return BigInt(e.startsWith(`0x`)?e:`0x${e}`)}function isDepositRequired(e,t){return isRuleActiveAt(e,`eligibility-admission`,t)&&!isRuleActiveAt(e,`invalid-slash-request.adjudicable`,t)}function depositedInTransaction(e,t,i){let a=derivedReceiveAddress(e.from,`slash-deposit`),u=new Set(t.payload_hashes);return i.filter(e=>u.has(e._hash)).filter(e=>TI(e)).reduce((e,t)=>e+toAmount(t.transfers[a]??`0x0`),0n)}async function carriedArtifactHashes(e,t){let i=new Set(e.payload_hashes),a=t.filter(e=>i.has(e._hash)).filter(e=>rI(e)).flatMap(e=>e.artifacts);return new Set(await Promise.all(a.map(e=>al.dataHash(e))))}async function evidenceResolutionErrors(e,t,i,a){let u=t.evidence.filter(e=>!i.has(e));if(u.length===0)return[];let p=e.hasFinalizedEvidenceArtifact;return p===void 0?[`evidence resolver unavailable: cannot certify a block whose evidence it cannot check`]:(await Promise.all(u.map(async e=>({found:await p(e,a),hash:e})))).filter(({found:e})=>!e).map(({hash:e})=>`unresolvable evidence artifact ${e}`)}function isOffenseReportable(e,t){return isRuleObservedAt(e,reportableRuleId(t.offense),t.block)}function TransactionTransfersInBlockValidatorFactory(e){return async(t,i)=>{let[a,u]=i,p=[];try{for(let y of u)if(CP(y)&&Rs(y)){let x=await e({...t,chainId:a.chain},[y,u]);for(let e of x)p.push(new HydratedBlockValidationError(y._hash,i,`transfer authorization error: ${e}`,e))}}catch(e){p.push(new HydratedBlockValidationError(a?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,`Failed TransactionTransfersInBlockValidator: ${String(e)}`,e))}return p}}function offendingTransactionHashesForAddress(e,t){let i=[];for(let a of e[1])MP(a)&&a.from===t&&i.push(a._hash);return i}async function balanceShortfallErrors(e,t,i){let a=[],u=Object.keys(i);if(u.length===0)return a;let[p]=await e.blockViewer.currentBlock(),y=await e.accountBalanceViewer.accountBalances(u,{head:p._hash});for(let e of u){let u=e,p=i[u],x=y[u]??uP(0n);e!==`0000000000000000000000000000000000000000`&&p>x&&a.push(new HydratedTransactionValidationError(t?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`insufficient balance for ${e} ${x} < ${p}`))}return a}var BlockAllowedPayloadSchemasValidator,error,checkSignaturesShape,BlockBoundWitnessValidator,BlockFieldsValidator,BlockPreviousHashValidator,validateBlock,isElevatedFromBlock,validateElevatedFromBlock,validateElevatedFromTransaction,validateTransactionInBlock,validateTypedPayloadInBlock,validateBridgeDestinationObservationInBlock,validateBridgeIntentInBlock,validateBridgeSourceObservationInBlock,validateChainStakeIntentInBlock,C8,validateClaimInBlock,validateHashInBlock,validateSchemaInBlock,validateSlashAdjudicationInBlock,validateSlashChallengeInBlock,validateSlashCommitInBlock,validateSlashEvidenceInBlock,validateSlashRequestInBlock,validateTimeInBlock,validateTransferInBlock,w8,validatePayloadInBlock,PayloadsInBlockValidator,validateHydratedBlock,RequiredBalanceBlockStateValidator,validateHydratedBlockState,RequiredBalanceTransactionStateValidator,validateHydratedTransactionState,T8=__esmMin((()=>{Uo(),_Z(),hM(),BlockAllowedPayloadSchemasValidator=(e,t)=>{let i=[];try{for(let e of t.payload_schemas)OI(e)||i.push(new BlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`payload schema not allowed in block: ${String(e)}`))}catch(e){i.push(new BlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`validation excepted: ${String(e)}`,e))}return i},error=(e,t)=>new BlockValidationError(e?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,e,t),checkSignaturesShape=e=>{let t=e;return t.$signatures===void 0?[error(e,Array.isArray(t.signatures)?"BoundWitness has `signatures` but expected `$signatures` (signatures must be in the meta-prefixed `$signatures` key)":"BoundWitness is missing `$signatures`")]:[]},BlockBoundWitnessValidator=async(e,t)=>{try{let e=checkSignaturesShape(t);return e.length>0?e:(await new jw(t).validate()).map(e=>error(t,`BoundWitness validation: ${e.message}`))}catch(e){return[error(t,`Failed BlockBoundWitnessValidator: ${String(e)}`)]}},BlockFieldsValidator=(e,t,i)=>{let a=[];try{isDefined$1(i)&&t.chain!==i.toLowerCase()&&a.push(new BlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`Invalid chain id`));let e=[];for(let i=0;i<t.payload_hashes.length;i++)t.payload_schemas[i]===sw&&e.push(t.payload_hashes[i]);new Set(e).size<e.length&&a.push(new BlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`Duplicate Transaction Hashes: ${e.join(`, `)}`))}catch(e){a.push(new BlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`validation excepted: ${String(e)}`,e))}return a},BlockPreviousHashValidator=(e,t)=>{let i=[];try{let e=t.block;e>0n?isHash(t.previous)||i.push(new BlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`previous hash is missing or invalid`)):e===0?t.previous!==null&&i.push(new BlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`previous hash should not be set`)):i.push(new BlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`invalid block number`))}catch(e){let a=new BlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`Failed BlockPreviousHashValidator: ${String(e)}`);a.cause=e,i.push(a)}return i},validateBlock=async(e,t,i,a=[])=>{let u=[];try{let p=[BlockBoundWitnessValidator,BlockFieldsValidator,BlockPreviousHashValidator,BlockAllowedPayloadSchemasValidator,...a];for(let a of p)u.push(...await Promise.resolve(a(e,t,i)))}catch(e){u.push(new BlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`validation excepted`,e))}return u},isElevatedFromBlock=(e,[,t])=>{let i=t.filter(e=>CP(e));for(let t of i)if(t.payload_hashes.includes(e._hash))return!1;return!0},validateElevatedFromBlock=(e,t,i)=>{let a=[];try{let e=transactionsFromHydratedBlock(i);new Set(e.flatMap(e=>e.payload_hashes)).has(t._hash)&&a.push(new InBlockPayloadValidationError(i[0]?._hash,i,t,`Transaction may not include block payload hash [${t.schema}]: ${t._hash}`))}catch(e){a.push(new InBlockPayloadValidationError(i[0]?._hash,i,t,`validation excepted: ${String(e)}`,e))}return a},validateElevatedFromTransaction=(e,t,i)=>{let a=[];try{let e=transactionsFromHydratedBlock(i);e.length>0?e.flatMap(e=>e.payload_hashes).includes(t._hash)||a.push(new InBlockPayloadValidationError(t._hash,i,t,`Transaction does not include payload`)):a.push(new InBlockPayloadValidationError(t._hash,i,t,`No Transactions in block`))}catch(e){a.push(new InBlockPayloadValidationError(t._hash,i,t,`Failed validateElevatedFromTransaction: ${String(e)}`,e))}return a},validateTransactionInBlock=async(e,t,i)=>{let a=[];try{if(CP(t)&&Rs(t)){let u=[...new Set(t.payload_hashes)].flatMap(e=>{let t=i[1].find(t=>Rs(t)&&(t._hash===e||t._dataHash===e));return t===void 0?[]:[t]}),p=await validateTransaction({...e,chainId:i[0].chain},[t,u]);for(let e of p)a.push(new InBlockPayloadValidationError(t._hash,i,t,`TransactionValidation error: ${e}`,e));let y=await BoundWitnessSignaturesValidator(t);for(let e of y)a.push(new InBlockPayloadValidationError(t._hash,i,t,`BoundWitnessSignaturesValidator error: ${e}`,e))}else a.push(new InBlockPayloadValidationError(t._hash,i,t,`Payload failed isTransactionBoundWitness or isHashMeta`))}catch(e){a.push(new InBlockPayloadValidationError(t._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`validation excepted: ${String(e)}`,e))}return a},validateTypedPayloadInBlock=async(e,t,i,a)=>{let u=[];try{a(t)&&Rs(t)?isElevatedFromBlock(t,i)?u.push(...await validateElevatedFromBlock(e,t,i)):u.push(...await validateElevatedFromTransaction(e,t,i)):u.push(/* @__PURE__ */ Error(`Payload failed identityFunction or isElevated or isStorageMeta`))}catch(e){u.push(/* @__PURE__ */ Error(`Failed validateTypedPayloadInBlock: ${String(e)}`))}return u},validateBridgeDestinationObservationInBlock=async(e,t,i)=>{let a=[];try{let u=await validateTypedPayloadInBlock(e,t,i,iF);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,`validateTypedPayloadInBlock error: ${e}`,e))}catch(e){a.push(new InBlockPayloadValidationError(i?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`Failed validateBridgeObservationInBlock: ${String(e)}`,e))}return a},validateBridgeIntentInBlock=async(e,t,i)=>{let a=[];try{let u=await validateTypedPayloadInBlock(e,t,i,cF);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,`validateTypedPayloadInBlock error: ${e}`,e))}catch(e){a.push(new InBlockPayloadValidationError(i?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`Failed validateBridgeIntentInBlock: ${String(e)}`,e))}return a},validateBridgeSourceObservationInBlock=async(e,t,i)=>{let a=[];try{let u=await validateTypedPayloadInBlock(e,t,i,pF);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,`validateTypedPayloadInBlock error: ${e}`,e))}catch(e){a.push(new InBlockPayloadValidationError(i?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`Failed validateBridgeObservationInBlock: ${String(e)}`,e))}return a},validateChainStakeIntentInBlock=async(e,t,i)=>{let a=[];try{let u=await validateTypedPayloadInBlock(e,t,i,_F);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,`validateTypedPayloadInBlock error: ${e}`,e))}catch(e){a.push(new InBlockPayloadValidationError(i[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`validation excepted: ${String(e)}`,e))}return a},C8=/* @__PURE__ */ new Set([`schema`,`hashes`,`source`,`subject`,`$version`,`$sources`]),validateClaimInBlock=async(e,t,i)=>{try{let e=al.omitStorageMeta(t);if(e.schema!==vF||!SF(e))return[claimError(t,i,`Claim failed its complete payload identity check`)];let a=validateStrictClaimFields(e);if(a.length>0)return[claimError(t,i,`Claim failed strict payload validation: ${a.join(`; `)}`,a)];let u=await al.hash(e);if(u!==t._hash)return[claimError(t,i,`Claim canonical root hash ${u} does not match asserted hash ${t._hash}`)];let p=validateClaimSchemaPairs(t,i),y=claimElevationAttempts(t,i),x=y.filter(e=>e.validOperationCount>0);for(let a of y)p.push(...validateElevatingTransaction(e,t,i,a));return x.length===0&&p.push(claimError(t,i,`Claim must be elevated from a transaction with an exact elevate operation`)),p}catch(e){return[claimError(t,i,`Failed validateClaimInBlock: ${String(e)}`,e)]}},validateHashInBlock=async(e,t,i)=>{let a=[];try{let u=await validateTypedPayloadInBlock(e,t,i,EF);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,`validateTypedPayloadInBlock error: ${e}`,e))}catch(e){a.push(new InBlockPayloadValidationError(i?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`validation excepted: ${String(e)}`,e))}return a},validateSchemaInBlock=async(e,t,i)=>{let a=[];try{let u=await validateTypedPayloadInBlock(e,t,i,JC);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,`validateTypedPayloadInBlock error: ${e}`,e))}catch(e){a.push(new InBlockPayloadValidationError(i?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`Failed validateSchemaInBlock: ${String(e)}`,e))}return a},validateSlashAdjudicationInBlock=async(e,t,i)=>{let a=[];try{let{errors:u,params:p}=await validateSlashPayloadInBlock(e,t,i,GF,e=>e.from,`slash adjudication`);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,e.message,e));u.length===0&&GF(t)&&(p?.arbiter===void 0||t.from!==p.arbiter)&&a.push(new InBlockPayloadValidationError(t._hash,i,t,`slash adjudication from must equal the register arbiter`))}catch(e){a.push(new InBlockPayloadValidationError(i[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`validation excepted: ${String(e)}`,e))}return a},validateSlashChallengeInBlock=async(e,t,i)=>{let a=[];try{let{errors:u}=await validateSlashPayloadInBlock(e,t,i,YF,e=>e.from,`slash challenge`);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,e.message,e))}catch(e){a.push(new InBlockPayloadValidationError(i[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`validation excepted: ${String(e)}`,e))}return a},validateSlashCommitInBlock=async(e,t,i)=>{let a=[];try{let{errors:u,params:p,transaction:y}=await validateSlashPayloadInBlock(e,t,i,$F,e=>e.from,`slash commit`);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,e.message,e));if(u.length>0||p===void 0||y===void 0||!$F(t))return a;if(isDepositRequired(p,i[0].block)){let e=toAmount(p.reporterDepositAtto??`0x0`),u=depositedInTransaction(t,y,i[1]);u<e&&a.push(new InBlockPayloadValidationError(t._hash,i,t,`slash commit escrows ${u} but the register requires ${e}`))}}catch(e){a.push(new InBlockPayloadValidationError(i[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`validation excepted: ${String(e)}`,e))}return a},validateSlashEvidenceInBlock=async(e,t,i)=>{let a=[];try{let{errors:u}=await validateSlashPayloadInBlock(e,t,i,rI,e=>e.from,`slash evidence`);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,e.message,e))}catch(e){a.push(new InBlockPayloadValidationError(i[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`validation excepted: ${String(e)}`,e))}return a},validateSlashRequestInBlock=async(e,t,i)=>{let a=[],fail=e=>{a.push(new InBlockPayloadValidationError(t._hash,i,t,e))};try{let{errors:u,params:p,transaction:y}=await validateSlashPayloadInBlock(e,t,i,lI,e=>e.from,`slash request`);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,e.message,e));if(u.length>0||p===void 0||y===void 0||!lI(t))return a;isOffenseReportable(p,t)||fail(`offense '${t.offense}' was not reportable at block ${t.block}`);let x=await carriedArtifactHashes(y,i[1]);for(let a of await evidenceResolutionErrors(e,t,x,i[0].block))fail(a)}catch(e){a.push(new InBlockPayloadValidationError(i[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`validation excepted: ${String(e)}`,e))}return a},validateTimeInBlock=async(e,t,i)=>{let a=[];try{let u=await validateTypedPayloadInBlock(e,t,i,RF);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,`validateTypedPayloadInBlock error: ${e}`,e))}catch(e){a.push(new InBlockPayloadValidationError(i?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`Failed validateTimeInBlock: ${String(e)}`,e))}return a},validateTransferInBlock=async(e,t,i)=>{let a=[];try{let u=await validateTypedPayloadInBlock(e,t,i,TI);for(let e of u)a.push(new InBlockPayloadValidationError(t._hash,i,t,`validateTypedPayloadInBlock error: ${e}`,e))}catch(e){a.push(new InBlockPayloadValidationError(i?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`Failed validateTransferInBlock: ${String(e)}`,e))}return a},w8={[sw]:validateTransactionInBlock,[tF]:validateBridgeDestinationObservationInBlock,[aF]:validateBridgeIntentInBlock,[uF]:validateBridgeSourceObservationInBlock,[mF]:validateChainStakeIntentInBlock,[vF]:validateClaimInBlock,[CF]:validateHashInBlock,[WC]:validateSchemaInBlock,[HF]:validateSlashAdjudicationInBlock,[KF]:validateSlashChallengeInBlock,[XF]:validateSlashCommitInBlock,[eI]:validateSlashEvidenceInBlock,[oI]:validateSlashRequestInBlock,[jF]:validateTimeInBlock,[SI]:validateTransferInBlock},validatePayloadInBlock=async(e,t,i)=>{let a=[];try{let u=w8[t.schema];u?a.push(...await u(e,t,i)):a.push(new InBlockPayloadValidationError(i?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`Unsupported payload schema: ${t.schema}`))}catch(e){let u=new InBlockPayloadValidationError(i?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,i,t,`validation excepted: ${String(e)}`,e);a.push(u)}return a},PayloadsInBlockValidator=async(e,[t,i])=>{let a=[];try{let u={};for(let e of i){let t=e._hash;u[t]=e}let p={...u};for(let y=0;y<t.payload_hashes.length;y++){let x=t.payload_hashes[y],w=t.payload_schemas[y],E=u[x];if(E){let u=await validatePayloadInBlock(e,E,[t,i]);for(let e of u)a.push(new HydratedBlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,[t,i],`validatePayloadInBlock error: ${e}`,e));delete p[x]}else a.push(new HydratedBlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,[t,i],`missing payload ${x} ${w}`))}Object.keys(p).length>0&&a.push(new HydratedBlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,[t,i],`extra payloads ${Object.keys(u).join(`, `)}`))}catch(e){a.push(new HydratedBlockValidationError(t?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,[t,i],`Failed PayloadsInBlockValidator: ${String(e)}`,e))}return a},validateHydratedBlock=async(e,t,i,a=[],u=[])=>{let p=[];try{let y=await validateBlock(e,t[0],i?await i(t[0].block):void 0,u);for(let e of y)p.push(new HydratedBlockValidationError(t[0]._hash,t,`validateBlock error: ${e}`,e));let x=await BoundWitnessReferencesValidator()(t);for(let e of x)p.push(new HydratedBlockValidationError(t[0]._hash,t,`boundwitness reference error: ${e}`,e));let w=[PayloadsInBlockValidator,...a];for(let a of w)p.push(...await Promise.resolve(a(e,t,i)))}catch(e){p.push(new HydratedBlockValidationError(t?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`Failed validateHydratedBlock: ${String(e)}`,e))}return p},RequiredBalanceBlockStateValidator=async(e,t)=>await spanRootAsync(`RequiredBalanceBlockStateValidator`,async()=>{let i=[],a=`00`;try{let u=netBalancesForPayloads({singletons:{}},t[1]),p=Object.keys(u),y={};for(let e of p){let t=e,i=u[t];i<0n&&(y[t]=-i)}let x=t[0].previous;if(x===null)return[new HydratedBlockStateValidationError(t?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,`00`,t,`Insufficient funds because first block`)];a=await e.chainIdAtBlockNumber(t[0].block),await spanRootAsync(`RequiredBalanceBlockStateValidator|balancesLoop`,async()=>{let u=Object.keys(y);if(u.length===0)return;let p=await e.accountBalance.accountBalances(u,{head:x});for(let e of u){let u=y[e],x=p[e]??uP(0n);if(e!==`0000000000000000000000000000000000000000`&&u>x){let p=offendingTransactionHashesForAddress(t,e);i.push(new HydratedBlockStateValidationError(t?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,a,t,`insufficient balance for ${e} ${x} < ${u}`,void 0,p.length>0?p:void 0))}}},e)}catch(e){i.push(new HydratedBlockStateValidationError(t?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,a,t,`Failed RequiredBalanceBlockStateValidator: ${String(e)}`,e))}return i},e),validateHydratedBlockState=async(e,t,i=[])=>await spanRootAsync(`validateHydratedBlockState`,async()=>{let a=[],u;try{u=await e.chainIdAtBlockNumber(t[0].block);let p=await validateHydratedBlock(e,t,e.chainIdAtBlockNumber);for(let e of p)a.push(new HydratedBlockStateValidationError(t[0]._hash,u,t,`validateBlock error: ${e}`,e));let y=[RequiredBalanceBlockStateValidator,...i];for(let i of y)a.push(...await Promise.resolve(i(e,t)))}catch(e){a.push(new HydratedBlockStateValidationError(t?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,u??`00`,t,`Failed validateHydratedBlockState: ${String(e)}`,e))}return a},e),RequiredBalanceTransactionStateValidator=async(e,t)=>await spanRootAsync(`RequiredBalanceTransactionStateValidator`,async()=>{let i=[];try{let a=netBalancesForPayloads({singletons:{}},t[1]),u=await gZ.parse(t),p=u.boundWitness.from,y=transactionRequiredGas(t);u.fees.gasLimit<y&&i.push(new HydratedTransactionValidationError(t?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`fees.gasLimit ${u.fees.gasLimit} < required gas ${y}`));let x=u.fees.base,w=u.fees.priority,E=u.fees.gasLimit,D=p;a[D]=(a[D]??0n)-x-w-E;let A={};for(let[e,t]of Object.entries(a)){let i=e;t<0n&&(A[i]=-t)}i.push(...await balanceShortfallErrors(e,t,A))}catch(e){i.push(new HydratedTransactionValidationError(t?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`Failed RequiredBalanceTransactionStateValidator: ${String(e)}`,e))}return i},e),validateHydratedTransactionState=async(e,t)=>await spanRootAsync(`validateHydratedTransactionState`,async()=>{let i=[];try{let a=[RequiredBalanceTransactionStateValidator];for(let u of a)i.push(...await Promise.resolve(u(e,t)))}catch(e){i.push(new HydratedTransactionValidationError(t?.[0]?._hash??`0000000000000000000000000000000000000000000000000000000000000000`,t,`Failed validateHydratedTransactionState: ${String(e)}`,e))}return i},e)}));_Z(),hM(),Uo(),T8();function competes(e,t){return e.dataHash!==t.dataHash&&(e.block===t.block||e.previous===t.previous)}function linked(e,t){return e.supersedes===t.dataHash||t.supersedes===e.dataHash}function findCandidatePairs(e){let t=/* @__PURE__ */ new Map;for(let i of e){let e=t.get(i.producer)??[];e.every(e=>e.dataHash!==i.dataHash)&&e.push(i),t.set(i.producer,e)}let i=[];for(let[e,a]of t)for(let[t,u]of a.entries())for(let p of a.slice(t+1))competes(u,p)&&!linked(u,p)&&i.push({block:Math.max(u.block,p.block),first:u,producer:e,second:p});return i}function isOffenseWatchable(e,t,i){return isOffenseReportableAt(e,t,i)&&(t!==`equivocation`||isRuleObservedAt(e,`supersedes-field`,i))}async function suppressionFor(e,t){return await e.adjudicationByKey(t)===void 0?(await e.requestsByKey(t)).length>0?`already-reported`:void 0:`adjudicated`}async function evaluateProducerEligibility(e){let{accused:t,blockAnchor:i,height:a,intent:u,params:p,parentAnchor:y,snapshot:x}=e;if(i===void 0||y===void 0)return{resolvable:!1};if(x===void 0)return{eStar:evaluationPoint(y,i,p.freshnessBandEvmBlocks),resolvable:!1};let w=evaluationPoint(y,i,p.freshnessBandEvmBlocks),E=p.minStakeAgeEvmBlocks,[D,A,N,P]=await Promise.all([x.seasonedActiveByStakedAt(t,w,E),x.seasonedSelfBondAt(t,w,E),x.activeByStakedAt(t,w),u(t,a)]);if(P===void 0)return{activeStake:D,eStar:w,resolvable:!1,selfBond:A};let F=producerIneligibility({active:N,seasonedActive:D,seasonedSelfBond:A},{minSelfBond:hexAtto(p.minProducerSelfBondAtto),minStake:hexAtto(p.minProducerStakeAtto)},P);return{activeStake:D,eStar:w,eligible:F===null,intentValid:P,reason:F??void 0,resolvable:!0,selfBond:A}}function hexAtto(e){return e===``?0n:BigInt(e.startsWith(`0x`)?e:`0x${e}`)}function offenseKeyOf(e){return{accused:e.accused,block:e.block,chain:e.chain,offense:e.offense}}function offenseKeyString(e){return`${e.chain}|${e.accused}|${e.offense}|${e.block}`}var emptyDelta=()=>({accused:/* @__PURE__ */ new Map,keys:/* @__PURE__ */ new Map,pending:[],records:[]}),recordAt=(e,t)=>({immutable:!0,path:e,value:t});function foldSlashIndex(e){let t=emptyDelta(),i=/* @__PURE__ */ new Map;for(let[,a]of e)for(let e of a)foldPayload(t,i,e);return t}function keyPathFor(e,t){let i=offenseKeyOf(t),a=slashIndexKeyPath(i.accused,i.offense,i.block);if(!e.keys.has(a)){e.keys.set(a,{accused:i.accused,block:i.block,challenges:[],chain:i.chain,offense:i.offense,requests:[],schema:tH});let t=slashIndexAccusedPath(i.accused);e.accused.set(t,[...e.accused.get(t)??[],offenseKeyString(i)])}return a}function foldPayload(e,t,i){if(lI(i)){e.records.push(recordAt(slashIndexRequestPath(i._dataHash),i));let a=keyPathFor(e,i);t.set(i._dataHash,a);let u=e.keys.get(a);u!==void 0&&!u.requests.includes(i._dataHash)&&u.requests.push(i._dataHash);return}if($F(i)){e.records.push(recordAt(slashIndexCommitPath(i._dataHash),i));return}if(YF(i)){e.records.push(recordAt(slashIndexChallengePath(i._dataHash),i)),linkToRequest(e,t,{hash:i._dataHash,kind:`challenge`,request:i.request});return}if(!GF(i))return;e.records.push(recordAt(slashIndexAdjudicationPath(i._dataHash),i));let a=linkToRequest(e,t,{hash:i._dataHash,kind:`adjudication`,outcome:i.outcome,request:i.request}),u=a===void 0?void 0:e.keys.get(a);u!==void 0&&u.adjudication===void 0&&(u.adjudication=i._dataHash,u.outcome=i.outcome)}function linkToRequest(e,t,i){let a=t.get(i.request),u=e.pending.some(e=>e.kind===`adjudication`);if(a===void 0||i.kind===`adjudication`&&u)e.pending.push(i);else{if(i.kind===`challenge`){let t=e.keys.get(a);t!==void 0&&!t.challenges.includes(i.hash)&&t.challenges.push(i.hash)}return a}}function mergeKeyRecord(e,t){if(e===void 0)return t;let union=(e,t)=>[.../* @__PURE__ */ new Set([...e,...t])],i=e.adjudication===void 0?t:e;return{...e,...t,adjudication:i.adjudication,challenges:union(e.challenges,t.challenges),outcome:i.outcome,requests:union(e.requests,t.requests)}}var E8=`SlashIndexStore`;function isSlashIndexStore(e){let t=e;return typeof t?.readObject==`function`&&typeof t.hasObject==`function`&&typeof t.writeObject==`function`}function verdict(e,t,i={},a){return a===void 0?{outcome:e,reason:t,transcript:i}:{outcome:e,provisional:a,reason:t,transcript:i}}async function verifyArtifacts(e,t){let i=/* @__PURE__ */ new Map;for(let a of t){let t=e.get(a);if(t===void 0)return{missing:!0,ok:!1,reason:`cited artifact ${a} is not available to this verifier`};let u=t,p=await al.dataHash(u);if(p!==a)return{ok:!1,reason:`artifact cited as ${a} hashes to ${p}`};if(vw(u)&&(await BoundWitnessSignaturesValidator(u)).length>0)return{ok:!1,reason:`artifact ${p} carries an invalid signature`};i.set(p,{dataHash:p,payload:u,storageHash:await al.hash(u)})}return{byHash:i,ok:!0}}async function referencesArtifact(e,t){return e==null?!1:e===t.dataHash||e===(t.storageHash??await al.hash(t.payload))}async function freshnessGate(e,t){let i=await e.chain.validatedAnchorAt(t.block);if(i===void 0)return{reason:`no anchor resolvable at the offense height`,verdict:verdict(`indeterminate`,`no anchor resolvable at the offense height`)};let a=e.submission.commitCarryingHeight??e.submission.requestCarryingHeight,u=await e.chain.validatedAnchorAt(a);if(u===void 0)return{eOff:i,reason:`no anchor resolvable at the submission height`,verdict:verdict(`indeterminate`,`no anchor resolvable at the submission height`)};let p=u-i;if(p>e.params.evidenceFreshnessEvmBlocks){let t=`offense is ${p} EVM blocks old, past the ${e.params.evidenceFreshnessEvmBlocks} limit`;return{eOff:i,eSub:u,reason:t,verdict:verdict(`provably-invalid`,t,{age:p,eOff:i,eSub:u})}}return{eOff:i,eSub:u,reason:`offense is ${p} EVM blocks old`}}var asCitedBlock=e=>{let t=NI(e.payload);return t===void 0?void 0:{block:t,dataHash:e.dataHash}},verifyEquivocation=async(e,t,i)=>{let a=Array.from(i.values());if(a.length!==2)return verdict(`provably-invalid`,`equivocation needs two distinct blocks, got ${a.length}`);let u=a.map(e=>asCitedBlock(e)),[p,y]=u;if(p===void 0||y===void 0)return verdict(`provably-invalid`,`cited artifacts are not both blocks`);let x={accused:t.accused,first:{block:p.block.block,dataHash:p.dataHash,previous:p.block.previous,supersedes:p.block.supersedes??null},second:{block:y.block.block,dataHash:y.dataHash,previous:y.block.previous,supersedes:y.block.supersedes??null}};if(u.some(e=>!e?.block.addresses.includes(t.accused)))return verdict(`provably-invalid`,`the accused did not sign both blocks`,x);if(p.block.chain!==y.block.chain)return verdict(`provably-invalid`,`the blocks are on different chains`,x);if(p.block.chain!==t.chain)return verdict(`provably-invalid`,`the blocks are not on the chain the report names`,x);if(p.block.block!==t.block&&y.block.block!==t.block)return verdict(`provably-invalid`,`the report does not locate the offense at either cited block`,x);if(p.block.block!==y.block.block&&p.block.previous!==y.block.previous)return verdict(`provably-invalid`,`the blocks neither share a height nor a parent`,x);let w=/* @__PURE__ */ new Set([p.block.supersedes,y.block.supersedes]);return w.has(p.dataHash)||w.has(y.dataHash)?verdict(`provably-invalid`,`one block supersedes the other, so this is a re-proposal`,x):verdict(`verified`,`two competing candidates with no supersedes link between them`,x)};async function anchoredBlocks(e){let t=Array.from(e.values()),i=await Promise.all(t.filter(e=>RF(e.payload)).map(async e=>({hashes:[e.dataHash,e.storageHash??await al.hash(e.payload)].filter(e=>isDefined$1(e)),time:e.payload})));return t.flatMap(e=>{let t=NI(e.payload);return t===void 0?[]:{artifact:e,block:t}}).map(({artifact:e,block:t})=>{let a=new Set(t.payload_hashes),u=i.find(e=>e.hashes.some(e=>a.has(e)));return{artifact:e,block:t,evm:u?.time?.ethereum,evmHash:u?.time?.ethereumHash}})}async function parentOf(e,t){for(let i of t)if(i!==e&&await referencesArtifact(e.block.previous,i.artifact))return i}var verifyFalseAnchor=async(e,t,i)=>{let a=await anchoredBlocks(i),u=a.find(e=>e.block.block===t.block);if(u===void 0)return verdict(`provably-invalid`,`the accused block was not among the cited artifacts`);let p=await parentOf(u,a);if(u.evm===void 0||u.evmHash===void 0)return verdict(`provably-invalid`,`the accused block carries no EVM anchor to be false about`);if(!u.block.addresses.includes(t.accused))return verdict(`provably-invalid`,`the accused did not sign the cited block`);let y={accused:t.accused,block:u.block.block,claimedEvm:u.evm,claimedEvmHash:u.evmHash,parentEvm:p?.evm??null};if(p?.evm!==void 0&&u.evm<p.evm)return verdict(`verified`,`the anchor went backwards, from ${p.evm} to ${u.evm}`,y);if(t.evm!==u.evm)return verdict(`provably-invalid`,`the report does not name the anchor the block claims`,y);if(e.evm===void 0)return verdict(`indeterminate`,`no EVM view, so the claimed anchor cannot be checked`,y);let x=await e.evm.head();if(x===void 0)return verdict(`indeterminate`,`the EVM head is not resolvable`,y);if(x-u.evm<e.params.maturityEvmBlocks)return verdict(`indeterminate`,`the anchor is only ${x-u.evm} EVM blocks deep and has not matured`,{...y,head:x});let w=await e.evm.canonicalHashAt(u.evm);return w===void 0?verdict(`indeterminate`,`the canonical hash at that EVM height is not resolvable`,y):w===u.evmHash?verdict(`provably-invalid`,`the block anchored to the canonical hash at that height`,{...y,canonical:w}):verdict(`verified`,`the block anchored to a hash the EVM never had at that height`,{...y,canonical:w})},citedAttestation=e=>{let t=e.find(e=>bI(e.payload));return t===void 0?void 0:{artifact:t,attestation:t.payload}};async function boundToAccused(e,t,i){for(let a of e){let e=a.payload;if(vw(a.payload)&&(e.addresses?.includes(i)??!1)){for(let i of e.payload_hashes??[])if(await referencesArtifact(i,t.artifact))return!0}}return!1}var verifyFalseAttestation=async(e,t,i)=>{let a=Array.from(i.values()),u=citedAttestation(a);if(u===void 0)return verdict(`provably-invalid`,`no attestation among the cited artifacts`);let{attestation:p}=u,y={accused:t.accused,attestedBlock:p.blockNumber,attestedBlockHash:p.blockHash,attestedStepHash:p.stepHash,stepSize:p.stepSize};if(p.witness!==t.accused||!await boundToAccused(a,u,t.accused))return verdict(`provably-invalid`,`the attestation is not bound to the accused by any cited signed carrier`,y);let x=dI.indexOf(p.stepSize);if(x===-1)return verdict(`provably-invalid`,`the attestation names an unknown step size ${p.stepSize}`,y);let w=a.map(e=>({block:NI(e.payload),dataHash:e.dataHash})).find(e=>e.block!==void 0&&e.dataHash===p.blockHash);if(w?.block!==void 0){let e=w.block.step_hashes?.[x];return e===p.stepHash?verdict(`provably-invalid`,`the block carries the step hash the attestation names at that level`,y):verdict(`verified`,`the attested block says something else at that level`,{...y,blockStepHashes:w.block.step_hashes??[],carried:e??null})}let E=e.submission.requestCarryingHeight-p.blockNumber;if(E>e.params.evidenceRetentionXl1Blocks)return verdict(`indeterminate`,`the attested block is ${E} blocks back, past the retention window`,y);let D=await e.chain.blockAtHeight(p.blockNumber);if(D===void 0)return verdict(`indeterminate`,`the attested height is not resolvable on this canonical chain`,y);let A=D[0]._dataHash;return A===p.blockHash?verdict(`provably-invalid`,`the attested block is the one finalized at that height`,y):verdict(`verified`,`no block with the attested hash was finalized at that height`,{...y,finalizedHash:A??null},!0)};async function anchorOf$2(e,t){for(let i of t.values())if(RF(i.payload)){for(let t of e.payload_hashes)if(await referencesArtifact(t,i))return i.payload.ethereum}}__name(anchorOf$2,`anchorOf`);var blockAt=(e,t)=>Array.from(t.values()).map(e=>NI(e.payload)).find(t=>t?.block===e);async function blockByReference(e,t){if(e!==null)for(let i of t.values()){let t=NI(i.payload);if(t!==void 0&&await referencesArtifact(e,i))return t}}var verifyIneligibleProduction=async(e,t,i)=>{let a=blockAt(t.block,i),u=a===void 0?void 0:await blockByReference(a.previous,i);if(a===void 0||u===void 0)return verdict(`provably-invalid`,`the accused block and its signed parent were not both cited`);if(!a.addresses.includes(t.accused))return verdict(`provably-invalid`,`the accused did not sign the cited block`);let p=await anchorOf$2(a,i),y=await anchorOf$2(u,i);if(p===void 0||y===void 0)return verdict(`indeterminate`,`the blocks do not both carry an anchor to measure against`);let x=await evaluateProducerEligibility({accused:t.accused,blockAnchor:p,height:t.block,intent:()=>a.addresses.includes(t.accused),params:e.params,parentAnchor:y,snapshot:e.snapshot}),w={accused:t.accused,blockAnchor:p,eStar:x.eStar??null,parentAnchor:y};if(t.evm!==x.eStar)return verdict(`provably-invalid`,`the report measures at ${t.evm}, but the rule measures at ${x.eStar}`,w);if(!x.resolvable)return verdict(`indeterminate`,`no stake snapshot, so standing cannot be measured`,w);let E={...w,seasonedActive:x.activeStake?.toString()??null,seasonedSelfBond:x.selfBond?.toString()??null};return x.eligible===!0?verdict(`provably-invalid`,`the accused met every participation requirement at that point`,E):verdict(`verified`,`the accused was ineligible at that point: ${x.reason}`,{...E,reason:x.reason??null})};function citedHydratedBlock(e){let t=Array.from(e.values()),i=t.find(e=>NI(e.payload)!==void 0),a=i===void 0?void 0:NI(i.payload);if(a===void 0)return;let u=new Set(a.payload_hashes.map(String));return{block:a,payloads:t.filter(e=>e!==i).map(e=>e.payload).filter(e=>{let{_hash:t,_dataHash:i}=e;return t!==void 0&&u.has(t)||i!==void 0&&u.has(i)})}}var Ude=BlockTransactionUniquenessValidatorFactory();async function replayReplayRule(e,t){let i=await Ude({chainIdAtBlockNumber:()=>e.block.chain,singletons:{}},[e.block,e.payloads]);return i.length>0?verdict(`verified`,`the cited block breaks a replay rule: ${i[0]?.message}`,{...t,errors:i.map(e=>e.message),rule:`replay`}):void 0}async function replayStateRules(e,t,i){if(e.balances===void 0)return verdict(`indeterminate`,`no balance view, so state rules cannot be replayed`,i);let a=await BlockCumulativeBalanceValidatorFactory()({accountBalance:e.balances,chainIdAtBlockNumber:()=>t.block.chain,singletons:{}},[t.block,t.payloads]);return a.length>0?verdict(`verified`,`the cited block breaks a state rule: ${a[0]?.message}`,{...i,errors:a.map(e=>e.message),rule:`state`}):verdict(`provably-invalid`,`the cited block satisfies every rule this procedure can replay`,i)}var verifyInvalidBlock=async(e,t,i)=>{let a=citedHydratedBlock(i);if(a===void 0)return verdict(`provably-invalid`,`no block among the cited artifacts`);let u={accused:t.accused,block:a.block.block,catalogVersion:e.catalogVersion,payloadCount:a.payloads.length};if(a.block.block!==t.block)return verdict(`provably-invalid`,`the cited block is not at the height the report names`,u);if(!a.block.addresses.includes(t.accused))return verdict(`provably-invalid`,`the accused did not sign the cited block`,u);let p=await validateBlock({singletons:{}},a.block,a.block.chain);if(p.length>0)return verdict(`verified`,`the cited block breaks a protocol rule: ${p[0]?.message}`,{...u,errors:p.map(e=>e.message),rule:`protocol`});let y=await replayReplayRule(a,u);if(y!==void 0)return y;if(a.block.previous===null)return verdict(`provably-invalid`,`the cited block is a genesis block, which has no parent to judge it against`,u);let x=await e.chain.blockByHash(a.block.previous);return x===void 0?verdict(`indeterminate`,`the parent is not resolvable on this canonical chain`,u):a.block.block===x[0].block+1?await replayStateRules(e,a,u):verdict(`verified`,`the cited block does not follow its own parent in height`,{...u,parentBlock:x[0].block,rule:`height`})},Wde={indeterminate:`indeterminate`,"provably-invalid":`verified`,verified:`provably-invalid`};function createVerifyInvalidSlashRequest(e){return async(t,i,a)=>{let u=a.values().find(e=>lI(e.payload));if(u===void 0)return verdict(`provably-invalid`,`no slash request among the cited artifacts`);let p=u.payload,y=offenseKeyOf(p),x=(await t.history.requestsByKey(y)).find(e=>e.hash===u.dataHash);if(x===void 0)return verdict(`indeterminate`,`the accused request is not visible in finalized history`);let w={accusedRequest:u.dataHash,innerOffense:p.offense,originalCarryingHeight:x.carryingHeight,reporter:i.accused},E=await t.history.adjudicationByKey(y);if(E!==void 0){let e={...w,adjudicationHeight:E.carryingHeight};return E.carryingHeight>=x.carryingHeight?verdict(`provably-invalid`,`timing-excused: the offense was not yet adjudicated when the report was filed`,e):verdict(`verified`,`re-litigation: the offense was already adjudicated on-chain when the report was filed`,e)}let D=e()[p.offense];if(D===void 0)return verdict(`indeterminate`,`no verification procedure for the inner offense '${p.offense}'`,w);let A={...t,catalogVersion:p.catalog,submission:{requestCarryingHeight:x.carryingHeight}},N=await verifyArtifacts(t.artifacts,p.evidence);if(!N.ok)return N.missing===!0?verdict(`indeterminate`,`the original's evidence is not available to re-run: ${N.reason}`,w):verdict(`verified`,`the original's evidence fails the preamble: ${N.reason}`,w);let P=(await freshnessGate(A,p)).verdict??await D(A,p,N.byHash);return verdict(Wde[P.outcome],`the original report verified as '${P.outcome}': ${P.reason}`,{...w,inner:P.transcript,innerOutcome:P.outcome})}}function mintedBy(e){return e.filter(e=>TI(e)).filter(e=>e.from===OL).reduce((e,t)=>e+Object.values(t.transfers).reduce((e,t)=>e+hexToBigInt(t),0n),0n)}async function allowedEmission(e,t,i){return e.params.rewardSource===`schedule`?rewardFromBlockNumber(t):i===void 0||e.blockRewardAt===void 0?void 0:await e.blockRewardAt(i)}var verifyRewardOvermint=async(e,t,i)=>{let a=Array.from(i.values()),u=a.find(e=>NI(e.payload)!==void 0),p=u===void 0?void 0:NI(u.payload);if(p===void 0)return verdict(`provably-invalid`,`no block among the cited artifacts`);if(p.block!==t.block)return verdict(`provably-invalid`,`the cited block is not at the height the report names`);if(!p.addresses.includes(t.accused))return verdict(`provably-invalid`,`the accused did not sign the cited block`);let y=mintedBy(a.filter(e=>e!==u).map(e=>e.payload)),x=p.previous===null?void 0:await e.chain.validatedAnchorAt(p.block-1),w=await allowedEmission(e,p.block,x),E={accused:t.accused,allowed:w===void 0?null:w.toString(),block:p.block,minted:y.toString(),parentAnchor:x??null,rewardSource:e.params.rewardSource};return w===void 0?verdict(`indeterminate`,`the allowed emission for this block cannot be established`,E):y>w?verdict(`verified`,`the block minted ${y} against an allowance of ${w}`,E):verdict(`provably-invalid`,`the block minted ${y}, within its allowance of ${w}`,E)},Gde={equivocation:verifyEquivocation,"false-anchor":verifyFalseAnchor,"false-attestation":verifyFalseAttestation,"ineligible-production":verifyIneligibleProduction,"invalid-block":verifyInvalidBlock,"invalid-slash-request":createVerifyInvalidSlashRequest(()=>Gde),"reward-overmint":verifyRewardOvermint};Uo();function createTelemetryGlobalCleanup({contextManager:e,isGlobalContextManagerOwner:t,isGlobalMeterProviderOwner:i,isGlobalPropagatorOwner:a,isGlobalTracerProviderOwner:w,runtimeInstrumentation:E}){let D=[];return E!==void 0&&D.push(()=>E.disable()),w&&D.push(()=>x.disable()),i&&D.push(()=>p.disable()),a&&D.push(()=>y.disable()),e!==void 0&&D.push(()=>t?u.disable():e.disable()),D}function isShutdownResource$1(e){return typeof e==`object`&&!!e&&`shutdown`in e&&typeof e.shutdown==`function`}__name(isShutdownResource$1,`isShutdownResource`);function attemptRollback(e){try{Promise.resolve(e()).catch(()=>null)}catch{}}function rollbackTelemetryInitialization({beforeShutdown:e=[],meterProvider:t,traceProvider:i}){for(let t of e)attemptRollback(t);for(let e of/* @__PURE__ */ new Set([t,i]))isShutdownResource$1(e)&&attemptRollback(()=>e.shutdown())}function createTelemetryShutdown({beforeShutdown:e=[],meterProvider:t,traceProvider:i}){let a;return()=>(a??=(async()=>{let a,u=!1,attempt=async e=>{try{await e()}catch(e){u||(a=e),u=!0}};for(let t of e)await attempt(t);for(let e of/* @__PURE__ */ new Set([t,i]))isShutdownResource$1(e)&&await attempt(async()=>await e.shutdown());if(u)throw a})(),a)}var Kde=`0.0.0.0`,createContextManager=()=>new ut,createPropagator=()=>new dt({propagators:[new pt,new ft]}),initResource=e=>{let t=bt({detectors:[St]}),i=xt({[oe]:e.serviceName,[se]:e.serviceName});return t.merge(i)},initHostMetrics=e=>{new vt({meterProvider:e,name:`host-metrics`}).start()},createNodeMetrics=()=>new yt({enabled:!1,monitoringPrecision:5e3}),initMetricsExporter=e=>{let{port:t,endpoint:i}=e;if(!(t<=0))return new mt({endpoint:i,host:Kde,port:t},e=>{e&&console.error(`Error initializing Prometheus exporter`,e)})},initMeterProvider=(e,t)=>new Ct({readers:t,resource:e,views:[{aggregation:void 0,instrumentName:`*`,instrumentType:void 0,meterName:`*`}]}),initTraceProvider=(e,t)=>{let i=[];if(isDefined$1(e)){let t=e.includes(`/v1/traces`)||e.includes(`:4318`)||e.startsWith(`http`)?new _t({url:e}):new ht({url:e}),a=new Ve(t,{});i.push(a)}let a={resource:t,sampler:new ze,spanProcessors:i};return new Be(a)};function registerTelemetryJson(e,t){Object.defineProperty(e,"toJSON",{value:()=>({type:`MeterProvider`}),enumerable:!1,configurable:!0}),Object.defineProperty(t,"toJSON",{value:()=>({type:`TracerProvider`}),enumerable:!1,configurable:!0})}function initTelemetry(e){let{attributes:t,metricsConfig:i,otlpEndpoint:a}=e,w,E,D={isGlobalContextManagerOwner:!1,isGlobalMeterProviderOwner:!1,isGlobalPropagatorOwner:!1,isGlobalTracerProviderOwner:!1},A,N,P;try{let e=createContextManager();w=e,e.enable(),D.isGlobalContextManagerOwner=u.setGlobalContextManager(e),D.isGlobalPropagatorOwner=y.setGlobalPropagator(createPropagator());let F=initResource(t);E=initMetricsExporter(i);let I=initMeterProvider(F,E?[E]:[]);A=I,D.isGlobalMeterProviderOwner=p.setGlobalMeterProvider(I),initHostMetrics(I);let L=createNodeMetrics();N=L,L.setMeterProvider(I),L.enable();let B=initTraceProvider(a,F);P=B,D.isGlobalTracerProviderOwner=x.setGlobalTracerProvider(B);let ee=createTelemetryShutdown({beforeShutdown:createTelemetryGlobalCleanup({contextManager:e,...D,runtimeInstrumentation:L}),meterProvider:I,traceProvider:B});return registerTelemetryJson(I,B),{meterProvider:I,shutdownTelemetry:ee,traceProvider:B}}catch(e){throw rollbackTelemetryInitialization({beforeShutdown:createTelemetryGlobalCleanup({contextManager:w,...D,runtimeInstrumentation:N}),meterProvider:A??E,traceProvider:P}),e}}Uo(),_Z(),za(),hM();var D8=Object.defineProperty,qde=Object.getOwnPropertyDescriptor,Jde=/* @__PURE__ */ __name((e,t,i)=>t in e?D8(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,`__defNormalProp`),Yde=/* @__PURE__ */ __name((e,t,i,a)=>{for(var u=a>1?void 0:a?qde(t,i):t,p=e.length-1,y;p>=0;p--)(y=e[p])&&(u=(a?y(t,i,u):y(u))||u);return a&&u&&D8(t,i,u),u},`__decorateClass`),O8=/* @__PURE__ */ __name((e,t,i)=>Jde(e,typeof t==`symbol`?t:t+``,i),`__publicField`),Xde=/* @__PURE__ */ __name(e=>[`1`,`true`,!0,1].includes(e),`toBooleanDefaultFalse`),Zde=/* @__PURE__ */ object$5({issuers:/* @__PURE__ */ array$2(ao),mode:/* @__PURE__ */ _default$1(/* @__PURE__ */ _enum$1(dde),`off`),offerings:/* @__PURE__ */ optional$2(/* @__PURE__ */ array$2(po))}),k8=/* @__PURE__ */ extend(CZ,{admission:/* @__PURE__ */ _default$1(/* @__PURE__ */ _enum$1(ude),`allowlist`),allowedProducers:/* @__PURE__ */ optional$2(/* @__PURE__ */ array$2(ao)),paramsFile:/* @__PURE__ */ optional$2(/* @__PURE__ */ string$3()),backoffMs:/* @__PURE__ */ _default$1(/* @__PURE__ */ number$4(),MU),finalizationCheckInterval:/* @__PURE__ */ _default$1(/* @__PURE__ */ number$4(),500),heartbeatInterval:/* @__PURE__ */ _default$1(/* @__PURE__ */ number$4(),o8),maxClockSkewMs:/* @__PURE__ */ _default$1((/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _nonnegative()),fde),maxEvmLeadBlocks:/* @__PURE__ */ _default$1((/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _multipleOf(1),/* @__PURE__ */ _nonnegative()),2),minCandidates:/* @__PURE__ */ _default$1((/* @__PURE__ */ number$5()).check(/* @__PURE__ */ _multipleOf(1),/* @__PURE__ */ _nonnegative()),1),producerLicenses:/* @__PURE__ */ optional$2(Zde),publishContentEncoding:/* @__PURE__ */ optional$2(/* @__PURE__ */ _enum$1([`br`,`gzip`,`none`])),publishOnFinalize:/* @__PURE__ */ _default$1(/* @__PURE__ */ pipe$1(/* @__PURE__ */ union$3([/* @__PURE__ */ number$5(),/* @__PURE__ */ string$3(),/* @__PURE__ */ boolean$2()]),/* @__PURE__ */ transform$1(Xde)),!1),publishProgressInterval:/* @__PURE__ */ optional$2(/* @__PURE__ */ number$4()),stallWarningMs:/* @__PURE__ */ _default$1((/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _positive()),6e4)}),Qde=zodToFactory(k8,`toFinalizerConfig`);function anchorOfBlock(e){return e[1].find(e=>RF(e))?.ethereum}function anchorHealth(e){let t={anchored:0,unanchored:0};for(let i of e){let e=anchorOfBlock(i);e===void 0?t.unanchored+=1:(t.anchored+=1,(t.latestAnchoredHeight===void 0||i[0].block>=t.latestAnchoredHeight)&&(t.latestAnchor=e,t.latestAnchoredHeight=i[0].block))}return t}function licensePolicyFromConfig(e){return{issuers:new Set(e.issuers.map(e=>ds(e,!0))),...e.offerings===void 0?{}:{offerings:new Set(e.offerings)}}}function unresolvable(e,t){return new Map(e.map(e=>[e[0]._dataHash,{reason:t,resolvable:!1}]))}async function evaluateLicenses(e,t,i){let a=e.viewer;if(a===void 0)return unresolvable(i,`no-license-viewer`);let u=await a.sync(),p=(await e.blockViewer.currentBlock())[0].block;if(u===void 0||u.block<p)return unresolvable(i,`ledger-behind`);let y=/* @__PURE__ */ new Map;for(let e of i){let i=e[0].addresses[0];if(i===void 0){y.set(e[0]._dataHash,{reason:`no-producer`,resolvable:!1});continue}let u=await a.licensingOperatorAt(i,e[0].block,t);y.set(e[0]._dataHash,u===void 0?{licensed:!1,reason:`no-license`,resolvable:!0}:{licenseId:u.id,licensed:!0,resolvable:!0})}return y}function buildLicenseAdmission(e){if(e.config.mode===`off`)return;let t=licensePolicyFromConfig(e.config);return{evaluate:async i=>await evaluateLicenses(e,t,i),mode:e.config.mode}}var PassWatchdog=class{_pass;now;thresholdMs;constructor(e,t=Date.now){this.thresholdMs=e,this.now=t}begin(e){this._pass={phase:e,startedAt:this.now()}}check(){let e=this._pass;if(e===void 0)return;let t=this.now();if(!(t-(e.reportedAt??e.startedAt)<this.thresholdMs))return e.reportedAt=t,{elapsedMs:t-e.startedAt,phase:e.phase}}elapsedMs(){return this._pass===void 0?0:this.now()-this._pass.startedAt}end(){let e=this._pass;if(this._pass=void 0,e?.reportedAt!==void 0)return{elapsedMs:this.now()-e.startedAt,phase:e.phase}}enter(e){this._pass!==void 0&&(this._pass.phase=e)}};function describePassStall({elapsedMs:e,phase:t},{finalized:i,published:a}){let u=Math.round(e/1e3);return t===`finalize`?`FinalizerActor: finalization pass in flight for ${u}s; nothing more is finalized until it returns`:`FinalizerActor: S3 publish in flight for ${u}s${a===void 0?``:`; the published head is still ${a}${i!==void 0&&i>a?` (finalized ${i})`:``}`}; nothing more is finalized or published until it returns`}var A8=/* @__PURE__ */ __name(e=>e[1].find(e=>RF(e))?.ethereum,`anchorOf`),intentCovers=(e,t)=>e.nbf<=t&&t<=e.exp;async function hasCurrentIntent(e,t,i,a){if(t[1].find(e=>_F(e)&&e.from===i&&intentCovers(e,a))!==void 0)return!0;if(e===void 0)return;let u=await e.intentByAddress(i);return u!==null&&intentCovers(u,a)}function createProducerEligibilityEvaluator(e){return async t=>{let i=await e.params?.tryCurrentParams();if(i===void 0)return{resolvable:!1};let a=t[0].addresses[0];if(a===void 0)return{resolvable:!1};let u=t[0].previous,p=u===null?void 0:(await e.blockViewer.blocksByHash(u,1))[0];return await evaluateProducerEligibility({accused:a,blockAnchor:A8(t),height:t[0].block,intent:async(i,a)=>await hasCurrentIntent(e.intent,t,i,a),params:i,parentAnchor:p===void 0?void 0:A8(p),snapshot:e.snapshot})}}var claimOf=e=>{let t=e[1].find(e=>RF(e));return{hash:t?.ethereumHash,height:t?.ethereum}};async function checkCanonical(e,t,i){if(e.height===void 0||e.hash===void 0)return;let a=await t.head();if(a===void 0||a-e.height<i)return;let u=await t.canonicalHashAt(e.height);if(u!==void 0)return u===e.hash?void 0:`claims EVM ${e.height} is ${e.hash} but canonically it is ${u}`}async function evaluateAnchorRules(e,t,i,a=32){let u=[],p=t;for(let t of e){let e=claimOf(t),y={block:t[0].block,producer:t[0].addresses[0]};if(e.height===void 0)u.push({...y,detail:`carries no EVM anchor`,rule:`anchor-present`});else{if(p!==void 0&&e.height<p&&u.push({...y,detail:`anchor went backwards, from ${p} to ${e.height}`,rule:`anchor-monotonic`}),i!==void 0){let t=await checkCanonical(e,i,a);t!==void 0&&u.push({...y,detail:t,rule:`anchor-canonical`})}p=e.height}}return u}function hasCatchUpProbe(e){return typeof e.findCatchUpStart==`function`}async function syncFinalizedChain(e){let{blockPublishRunner:t,chainStatePublishRunner:i,chainStateViewer:a}=e,u=await a.tryCurrentBlock(),p=rP(u===void 0?0:u[0].block+1,!0),y=hasCatchUpProbe(t)?await t.findCatchUpStart(p):p,x=await t.sync(y);return x===null?(y>p&&await i.publishHead(),null):(await i.publishHead(),x)}function isChainParamsPublisher(e){let t=e;return typeof t?.publishParams==`function`&&typeof t.currentPublished==`function`}function assertSatisfiableMinCandidates(e,t){if(t>0&&e>t)throw Error(`FinalizerActor: minCandidates (${e}) exceeds allowedProducers count (${t}) \u2014 head selection can never reach quorum and every block would stall for the backoff window. Lower minCandidates or add producers to allowedProducers.`)}var FinalizerActor=class extends ChainActor{_blockPublishRunner;_blockValidationViewer;_blockViewer;_chainStatePublishRunner;_chainStateViewer;_deadLetterQueueRunner;_finalizationRunner;_mempoolViewer;_admissionDivergenceCounter;_admissionShadowPublishRunner;_anchorEvmView;_anchorGapGauge;_anchorRuleFindingCounter;_blocksFinalizedCounter;_chainParamsViewer;_divergenceSeen=/* @__PURE__ */ new Set;_eligibility;_evmHeadCache;_lastAnchoredHeight;_lastFinalizedHead;_lastPostureMismatch;_lastPublishedHead;_lastShadowAnchor;_lastShadowFingerprint;_licenseDivergenceCounter;_licenseDivergenceSeen=/* @__PURE__ */ new Set;_licenseViewer;_licensing;_passInFlightGauge;_passWatchdog;_postureMismatchGauge;_publishPending=!1;_timeRuleRejectionCounter;get admission(){return this.params.config.admission}get allowedProducers(){return this.params.config.allowedProducers??[]}get backoffMs(){return this.params.config.backoffMs}get blockValidationViewer(){return this._blockValidationViewer}get blockViewer(){return this._blockViewer}get canPublish(){return isDefined$1(this._blockPublishRunner)&&isDefined$1(this._chainStatePublishRunner)&&isDefined$1(this._chainStateViewer)}get finalizationRunner(){return this._finalizationRunner}get heartbeatInterval(){return this.params.config.heartbeatInterval}get mempoolViewer(){return this._mempoolViewer}get minCandidates(){return this.params.config.minCandidates}get producerLicenses(){return this.params.config.producerLicenses}async createHandler(){if(await super.createHandler(),this.admission===`enforce`)throw Error(`FinalizerActor: admission 'enforce' is not yet operable — its companions (emergencyAllowlist brake, enforce-posture runbook, arbiter adjudication) have not shipped. Use 'shadow' to measure standing without gating, or 'allowlist' for trusted admission.`);if(this.producerLicenses?.mode!==`admit`&&assertSatisfiableMinCandidates(this.minCandidates??1,this.allowedProducers.length),this._blockValidationViewer=await this.locator.getInstance(Kz),this._blockViewer=await this.locator.getInstance(Hz),this._finalizationRunner=await this.locator.getInstance(uz),this._mempoolViewer=await this.locator.getInstance(iB),this._deadLetterQueueRunner=await this.locator.tryGetInstance(sz),this._anchorGapGauge=this.gauge(`finalizer_actor_anchor_gap_blocks`,`XL1 blocks since a finalized block last carried an EVM anchor`),this._blocksFinalizedCounter=this.counter(`finalizer_actor_blocks_finalized`,`Blocks finalized, split by whether they carried an EVM anchor`),this._anchorRuleFindingCounter=this.counter(`finalizer_actor_anchor_rule_findings`,`Finalized blocks that would have failed an anchor rule, had it been active`),this._anchorEvmView=await this.tryCreateAnchorEvmView(),this._timeRuleRejectionCounter=this.counter(`finalizer_actor_time_rule_rejections`,`Candidates refused by a time rule, split by rule`),this._passInFlightGauge=this.gauge(`finalizer_actor_pass_in_flight_ms`,`How long the running finalization pass has been in flight; 0 while idle`),this._passWatchdog=new PassWatchdog(this.params.config.stallWarningMs),this._anchorEvmView===void 0&&this.logger?.warn(`FinalizerActor: no EvmChainViewer is bound — candidate EVM anchors will not be bounded by the EVM head`),this.admission!==`allowlist`&&await this.createEligibilityEvaluator(),this.producerLicenses!==void 0&&this.producerLicenses.mode!==`off`&&await this.createLicenseAdmission(),this.params.config.publishOnFinalize&&(this._blockPublishRunner=await this.locator.tryGetInstance(iz),this._chainStatePublishRunner=await this.locator.tryGetInstance(az),this._chainStateViewer=await this.locator.tryGetInstance(Yz),!this.canPublish))throw Error(`publishOnFinalize is enabled but S3 publish providers are not configured`);this.params.config.paramsFile!==void 0&&await this.publishRegisterFromFile(this.params.config.paramsFile)}async startHandler(){await super.startHandler();let e=this.params.config.finalizationCheckInterval??500;this.registerTimer(`FinalizerActor`,async()=>{await this.runFinalizationPass()},2e3,e);let t=FinalizerActor.StallWatchdogIntervalMs;this.registerTimer(`FinalizerStallWatchdog`,async()=>{this.checkPassStall()},t,t)}async createEligibilityEvaluator(){this._admissionDivergenceCounter=this.counter(`finalizer_actor_shadow_admission_divergence`,`Distinct candidates where the allow-list and participation rules disagreed`),this._postureMismatchGauge=this.gauge(`finalizer_actor_posture_mismatch`,`Whether the configured admission posture disagrees with the register's eligibility-admission state`);let e=await this.locator.tryGetInstance(E6);this._admissionShadowPublishRunner=isAdmissionShadowPublishRunner(e)?e:void 0;let t=await this.locator.tryGetInstance(hB),i=await this.locator.tryGetInstance(Jz),a=await this.locator.tryGetInstance(gB);this._chainParamsViewer=i,i!==void 0&&(i.finalizedHeight=async()=>(await this.blockViewer.currentBlock())[0]?.block),this._eligibility=createProducerEligibilityEvaluator({blockViewer:this._blockViewer,intent:t,params:i,snapshot:a});let u=[i===void 0?Jz:void 0,a===void 0?gB:void 0,t===void 0?hB:void 0].filter(isDefined$1);u.length>0&&this.logger?.warn(`FinalizerActor: admission posture '${this.admission}' is missing ${u.join(`, `)} \u2014 every assessment will publish as unresolvable and divergence will read zero regardless of standing`),this.logger?.log(`FinalizerActor: admission posture '${this.admission}'`)}async createLicenseAdmission(){let e=this.producerLicenses;if(e===void 0||e.mode===`off`)return;let t=e.mode;if(this._licenseDivergenceCounter=this.counter(`finalizer_actor_license_admission_divergence`,`Distinct candidates where the allow-list and the license ledger disagreed`),this._admissionShadowPublishRunner===void 0){let e=await this.locator.tryGetInstance(E6);this._admissionShadowPublishRunner=isAdmissionShadowPublishRunner(e)?e:void 0}let i=await this.locator.tryGetInstance(S8);this._licenseViewer=isLicenseViewer(i)?i:void 0,this._licenseViewer===void 0&&this.logger?.warn(`FinalizerActor: producerLicenses mode '${t}' but no LicenseViewer is bound \u2014 bind a rest-datalake connection; every license verdict will be unresolvable${t===`admit`?` and only the allow-list admits`:``}`),this._licensing=buildLicenseAdmission({blockViewer:this.blockViewer,config:e,viewer:this._licenseViewer}),this.logger?.log(`FinalizerActor: producer licensing '${t}', recognizing ${e.issuers.length} issuer(s)`)}async publishRegisterFromFile(e){let t=await this.locator.tryGetInstance(`ChainParamsPublishRunner`);if(!isChainParamsPublisher(t))throw Error(`paramsFile is configured but no ChainParamsPublishRunner is available — bind an s3 connection for it`);let i=JSON.parse(await We.readFile(e,`utf8`)),a=oV(i,!0),u=await t.currentPublished(a.chainId);if(u!==void 0&&u.version>=a.version){this.logger?.log(`FinalizerActor: register v${u.version} already published; ${e} carries v${a.version}`);return}let p=await t.publishParams(a);this.logger?.log(`FinalizerActor: published register v${a.version} (${p}) from ${e}`)}async readyHandler(){this._publishPending=this.canPublish,await this.finalizeOnce()}async recordAdmissionShadow(e){let t=`${e.head}|${e.assessments.map(e=>`${e.dataHash}:${e.eligibility.resolvable}:${e.eligibility.eligible??`?`}:${e.license?.resolvable??`-`}:${e.license?.licensed??`?`}`).toSorted().join(`,`)}`;if(t!==this._lastShadowFingerprint){try{await this._admissionShadowPublishRunner?.publish(e),this._lastShadowFingerprint=t}catch(e){this.logger?.warn(`[shadow] could not publish admission report: ${e.message}`)}for(let t of e.divergent){let e=t.admittedByAllowList?`would_reject`:`would_accept`,i=`${t.producer}:${t.block}:${e}`;this._divergenceSeen.has(i)||(this._divergenceSeen.size>=1e4&&this._divergenceSeen.clear(),this._divergenceSeen.add(i),this._admissionDivergenceCounter?.add(1,{producer:t.producer,verdict:e}),this.logger?.warn(`[shadow] admission divergence at block ${t.block} for ${t.producer}: allow-list ${t.admittedByAllowList?`admits`:`rejects`}, participation ${t.eligibility.eligible===!0?`admits`:`rejects`} (${t.eligibility.reason??`no reason given`})`))}this.recordLicenseDivergence(e)}}recordLicenseDivergence(e){for(let t of e.assessments.filter(e=>isLicenseDivergent(e))){let e=t.admittedByAllowList?`listed_unlicensed`:`licensed_unlisted`,i=`${t.producer}:${t.block}:${e}`;this._licenseDivergenceSeen.has(i)||(this._licenseDivergenceSeen.size>=1e4&&this._licenseDivergenceSeen.clear(),this._licenseDivergenceSeen.add(i),this._licenseDivergenceCounter?.add(1,{producer:t.producer,verdict:e}),this.logger?.log(`[license] at block ${t.block} ${t.producer} is ${t.license?.licensed===!0?`licensed (${t.license.licenseId??`unknown license`})`:`unlicensed (${t.license?.reason??`no reason given`})`} and ${t.admittedByAllowList?`listed`:`not listed`}`))}}async recordPostureAlignment(e){let t=this._chainParamsViewer;if(t===void 0)return;let i=await t.tryCurrentParams();if(i===void 0)return;let a=ruleActivationStateAt(i,`eligibility-admission`,e)!==`inactive`,u=a!==(this.admission===`enforce`);this._postureMismatchGauge?.record(+!!u,{admission:this.admission}),u&&this._lastPostureMismatch!==!0&&this.logger?.warn(`FinalizerActor: register ${a?`activates`:`does not activate`} eligibility-admission at ${e} but this finalizer's admission posture is '${this.admission}'`),this._lastPostureMismatch=u}async cachedEvmHead(){let e=Date.now(),t=this._evmHeadCache;if(t!==void 0&&e-t.at<FinalizerActor.EvmHeadCacheMs)return t.value;let i=await this._anchorEvmView?.head();return this._evmHeadCache={at:e,value:i},i}checkPassStall(){let e=this._passWatchdog;if(e===void 0)return;this._passInFlightGauge?.record(e.elapsedMs());let t=e.check();t!==void 0&&this.logger?.error(describePassStall(t,{finalized:this._lastFinalizedHead,published:this._lastPublishedHead}))}async finalizeOnce(){let e=await this.spanAsync(`processPendingBlocks`,async()=>(this.logger?.debug(`FinalizerActor: Processing pending blocks...`),await processPendingBlocks({blockValidationViewer:this.blockValidationViewer,context:this.context,logger:this.logger,mempoolViewer:this.mempoolViewer,blockViewer:this.blockViewer,finalizationRunner:this.finalizationRunner,allowedProducers:this.allowedProducers,backoffMs:this.backoffMs,heartbeatInterval:this.heartbeatInterval,minCandidates:this.minCandidates,timeRules:this.timeRules(),admission:this.admission,eligibility:this._eligibility,licensing:this._licensing,publishAdmissionShadow:async e=>await this.recordAdmissionShadow(e),deadLetterQueueRunner:this._deadLetterQueueRunner,observer:this.account})),{...this.context,timeBudgetLimit:1500});if((e?.length??0)>0&&(this._publishPending=!0),e===void 0||!(e.length>0))return;this.recordAnchorHealth(e),await this.recordShadowAnchorRules(e);let t=Math.max(...e.map(e=>e[0].block));this._lastFinalizedHead=t,await this.recordPostureAlignment(t)}async publishIfPending(){this.canPublish&&this._publishPending&&await this.spanAsync(`publishFinalized`,async()=>{try{let e=await syncFinalizedChain({blockPublishRunner:this._blockPublishRunner,chainStatePublishRunner:this._chainStatePublishRunner,chainStateViewer:this._chainStateViewer});this._publishPending=!1,e!==null&&(this._lastPublishedHead=e[1],this.logger?.info(`FinalizerActor: published blocks [${e[0]}..${e[1]}] to S3`))}catch(e){this.logger?.warn(`FinalizerActor: S3 publish failed; will retry next pass`,e)}},this.context)}recordAnchorHealth(e){let t=anchorHealth(e);t.anchored>0&&this._blocksFinalizedCounter?.add(t.anchored,{anchored:!0}),t.unanchored>0&&this._blocksFinalizedCounter?.add(t.unanchored,{anchored:!1}),t.latestAnchoredHeight!==void 0&&(this._lastAnchoredHeight=t.latestAnchoredHeight);let i=e.at(-1)?.[0].block;i!==void 0&&this._anchorGapGauge?.record(i-(this._lastAnchoredHeight??0),{head:i})}async recordShadowAnchorRules(e){try{let t=(await this._chainParamsViewer?.tryCurrentParams())?.maturityEvmBlocks,i=await evaluateAnchorRules(e,this._lastShadowAnchor,this._anchorEvmView,t);for(let e of i)this._anchorRuleFindingCounter?.add(1,{rule:e.rule}),this.logger?.warn(`[shadow] block ${e.block} would fail '${e.rule}': ${e.detail}`);for(let t of e.toReversed()){let e=anchorOfBlock(t);if(e!==void 0){this._lastShadowAnchor=e;break}}}catch(e){this.logger?.warn(`[shadow] anchor rule pass failed: ${e.message}`)}}async runFinalizationPass(){let e=this._passWatchdog;e?.begin(`finalize`);try{await this.finalizeOnce(),e?.enter(`publish`),await this.publishIfPending()}finally{let t=e?.end();t!==void 0&&this.logger?.warn(`FinalizerActor: stalled ${t.phase} pass returned after ${Math.round(t.elapsedMs/1e3)}s`)}}timeRules(){return{evmHead:this._anchorEvmView===void 0?void 0:async()=>await this.cachedEvmHead(),maxClockSkewMs:this.params.config.maxClockSkewMs,maxEvmLeadBlocks:this.params.config.maxEvmLeadBlocks,onRejection:e=>this._timeRuleRejectionCounter?.add(1,{rule:e.rule})}}async tryCreateAnchorEvmView(){let e=await this.locator.tryGetInstance($z);if(e!==void 0)return{canonicalHashAt:async t=>{try{return(await(await e.provider()).getBlock(t))?.hash??void 0}catch{return}},head:async()=>{try{return await(await e.provider()).getBlockNumber()}catch{return}}}}};O8(FinalizerActor,`EvmHeadCacheMs`,5e3),O8(FinalizerActor,`StallWatchdogIntervalMs`,1e4),O8(FinalizerActor,`dependencies`,[Kz,Hz,uz,iB]),FinalizerActor=Yde([creatable()],FinalizerActor);var $de={bootExtras:({process:e})=>restDataLakeViewerExtras(e),configParser:k8,create:async e=>await FinalizerActor.create({account:e.wallet,config:Qde(e.actor),locator:e.locator}),defaultAccountPath:`5`,dependencies:[`BlockValidationViewer`,`BlockViewer`,`FinalizationRunner`,`MempoolViewer`],name:`finalizer`,optionalProviderRoots:[`AdmissionShadowPublishRunner`,`BlockPublishRunner`,`ChainParamsPublishRunner`,`ChainParamsViewer`,`ChainStatePublishRunner`,`ChainStateViewer`,`DataLakeViewer`,`DeadLetterQueueRunner`,`EvidenceProtectionViewer`,`EvmChainViewer`,`IndexViewer`,`LicenseViewer`,`StakeIntentViewer`,`StakeSnapshotViewer`]};Uo(),_Z(),za(),hM();var j8=Object.defineProperty,efe=Object.getOwnPropertyDescriptor,tfe=/* @__PURE__ */ __name((e,t,i)=>t in e?j8(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,`__defNormalProp`),M8=/* @__PURE__ */ __name((e,t,i,a)=>{for(var u=a>1?void 0:a?efe(t,i):t,p=e.length-1,y;p>=0;p--)(y=e[p])&&(u=(a?y(t,i,u):y(u))||u);return a&&u&&j8(t,i,u),u},`__decorateClass`),N8=/* @__PURE__ */ __name((e,t,i)=>tfe(e,typeof t==`symbol`?t:t+``,i),`__publicField`),P8=/* @__PURE__ */ extend(CZ,{publishContentEncoding:/* @__PURE__ */ optional$2(/* @__PURE__ */ _enum$1([`br`,`gzip`,`none`])),publishProgressInterval:/* @__PURE__ */ optional$2(/* @__PURE__ */ number$4()),publishSyncInterval:/* @__PURE__ */ _default$1(/* @__PURE__ */ number$4(),5e3)}),nfe=zodToFactory(P8,`toIndexerConfig`);async function syncPublishedIndex(e){let{chainStateViewer:t,indexPublishRunner:i}=e,a=await t.tryCurrentBlock();if(a===void 0)return null;let u=rP(a[0].block,!0);return await i.publishCompletedFramesUpTo(u)}async function syncPublishedIndexes(e){let[t,i]=await Promise.all([e.syncXl1(),e.syncEvm()]);return t!==null&&i!==null&&await e.syncRewards(t,i),{evmHead:i,xl1Head:t}}var IndexerActor=class extends ChainActor{_chainStateViewer;_evmEventIndexPublishRunner;_indexPublishRunner;_networkStakeRewardsIndexPublishRunner;async createHandler(){await super.createHandler(),this._chainStateViewer=await this.locator.getInstance(Yz),this._evmEventIndexPublishRunner=await this.locator.tryGetInstance(lz),this._indexPublishRunner=await this.locator.getInstance(dz),this._networkStakeRewardsIndexPublishRunner=await this.locator.tryGetInstance(mz),assertEx$1(this._networkStakeRewardsIndexPublishRunner===void 0||this._evmEventIndexPublishRunner!==void 0,()=>`NetworkStakeRewardsIndexPublishRunner requires EvmEventIndexPublishRunner in the indexer process`)}async startHandler(){await super.startHandler();let e=this.params.config.publishSyncInterval??5e3;this.registerTimer(`IndexerActor`,async()=>{await syncPublishedIndexes({syncEvm:async()=>await this.runEvmEventSyncPass(),syncRewards:async(e,t)=>await this.runRewardsSyncPass(e,t),syncXl1:async()=>await this.runSyncPass()})},2e3,e)}async runEvmEventSyncPass(){let e=this._evmEventIndexPublishRunner;return e===void 0?null:await this.spanAsync(`evmEventIndexerSync`,async()=>{let t=await e.publishFinalizedEvents();return t!==null&&this.logger?.info(`IndexerActor: EVM event index complete through finalized block ${t.block}`),t},this.context)}async runRewardsSyncPass(e,t){let i=this._networkStakeRewardsIndexPublishRunner;i!==void 0&&await this.spanAsync(`rewardsIndexerSync`,async()=>{let a=await i.publishRewardsIndex(e,t);this.logger?.info(`IndexerActor: rewards index complete through XL1 block ${a.processedThroughBlock} (${a.stepCount} steps)`)},this.context)}async runSyncPass(){return await this.spanAsync(`indexerSync`,async()=>{let e=await syncPublishedIndex({chainStateViewer:this._chainStateViewer,indexPublishRunner:this._indexPublishRunner});return e!==null&&this.logger?.info(`IndexerActor: index complete through block ${e.block}`),e},this.context)}};N8(IndexerActor,`dependencies`,[Yz,dz]),IndexerActor=M8([creatable()],IndexerActor);var rfe={configParser:P8,create:async e=>await IndexerActor.create({account:e.wallet,config:nfe(e.actor),locator:e.locator}),defaultAccountPath:`6`,dependencies:[`ChainStateViewer`,`IndexPublishRunner`],name:`indexer`,optionalProviderRoots:[`EvmEventIndexPublishRunner`,`NetworkStakeRewardsIndexPublishRunner`]};async function runLicenseIndexPass(e){let{label:t,logger:i,store:a,viewer:u}=e;try{let e=await u.sync();if(e===void 0)return null;let p=await publishLicenseIndex({bodies:await u.bodies?.()??[],head:e,ledger:await u.ledger(),store:a});return p!==null&&i?.info(`${t}: license index at block ${p.head.height}${p.snapshotWritten?`, new snapshot`:``}${p.bodiesWritten>0?`, ${p.bodiesWritten} bodies`:``}`),p}catch(e){return i?.warn(`${t}: license index pass failed: ${e.message}`),null}}var IndexerLicenseActor=class extends ChainActor{_store;_viewer;async createHandler(){await super.createHandler();let e=await this.locator.getInstance(S8);this._viewer=assertEx$1(isLicenseViewer(e)?e:void 0,()=>`${S8} did not resolve to a license ledger reader for actor ${this.name}`);let t=await this.locator.getInstance(E8);this._store=assertEx$1(isSlashIndexStore(t)?t:void 0,()=>`${E8} did not resolve to an object store for actor ${this.name}`)}async startHandler(){await super.startHandler(),this.registerTimer(`IndexerLicenseActor`,async()=>{await this.publishPass()},2e3,this.params.config.syncInterval)}async publishPass(){await runLicenseIndexPass({label:`IndexerLicenseActor`,logger:this.logger,store:this._store,viewer:this._viewer})}};N8(IndexerLicenseActor,`dependencies`,[S8,E8]),IndexerLicenseActor=M8([creatable()],IndexerLicenseActor);var F8=/* @__PURE__ */ _default$1((/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _multipleOf(1),/* @__PURE__ */ _positive()),5e3),I8=/* @__PURE__ */ extend(CZ,{syncInterval:F8}),ife=zodToFactory(I8,`toIndexerLicenseConfig`);async function runPayloadsIndexPass(e){let{label:t,logger:i,runner:a}=e;try{let e=await a.publishCompletedFrames();return e!==null&&i?.info(`${t}: payloads index complete through block ${e.block}`),e}catch(e){return i?.warn(`${t}: payloads index pass failed: ${e.message}`),null}}var IndexerPayloadsActor=class extends ChainActor{_runner;async createHandler(){await super.createHandler(),this._runner=await this.locator.getInstance(hz)}async startHandler(){await super.startHandler(),this.registerTimer(`IndexerPayloadsActor`,async()=>{await this.publishPass()},2e3,this.params.config.syncInterval)}async publishPass(){await this.spanAsync(`payloadsIndexerSync`,async()=>{await runPayloadsIndexPass({label:`IndexerPayloadsActor`,logger:this.logger,runner:this._runner})},this.context)}};N8(IndexerPayloadsActor,`dependencies`,[hz]),IndexerPayloadsActor=M8([creatable()],IndexerPayloadsActor);var L8=/* @__PURE__ */ extend(CZ,{syncInterval:F8}),afe=zodToFactory(L8,`toIndexerPayloadsConfig`);async function runChainParamsMirrorPass(e){let{label:t,logger:i,mirroredVersion:a,store:u,viewer:p}=e;try{let e=await p.tryCurrentParams();if(e===void 0||e.version===a)return a;let y=chainParamsVersionPath(e.chainId,e.version);await u.hasObject(y)||await u.writeObject(y,e,!0);let x=await al.dataHash(e);return await u.writeObject(chainParamsHeadPath(e.chainId),createChainParamsHead(e.version,x),!1),i?.info(`${t}: mirrored register v${e.version} into the index bucket`),e.version}catch(e){return i?.warn(`${t}: register mirror pass failed: ${e.message}`),a}}var ofe=100;function continuingRun(e,t){let i=[];for(let a of t.toSorted((e,t)=>e[0].block-t[0].block)){let t=e+i.length+1;if(!(a[0].block<t)){if(a[0].block>t)break;i.push(a)}}return i}async function publishedHeight(e){let t=await e.readObject(slashIndexHeadPath());return t===void 0?void 0:eH(t,!0).height}async function writeRecords(e,t){for(let i of t.records)await e.hasObject(i.path)||await e.writeObject(i.path,i.value,!0)}async function writeKeyAggregates(e,t){for(let[i,a]of t.keys){let t=mergeKeyRecord(await e.readObject(i),a);await e.writeObject(i,t,!1)}}async function writeAccusedAggregates(e,t){for(let[i,a]of t.accused){let t=await e.readObject(i),u=[.../* @__PURE__ */ new Set([...t?.keys??[],...a])];await e.writeObject(i,{keys:u},!1)}}async function resolvePending(e,t){for(let i of t.pending){let t=await e.readObject(slashIndexRequestPath(i.request));if(t?.accused===void 0||t.block===void 0||t.offense===void 0)continue;let a=slashIndexKeyPath(t.accused,t.offense,t.block),u=await e.readObject(a);if(u===void 0||i.kind===`adjudication`&&u.adjudication!==void 0)continue;let p=i.kind===`challenge`?{...u,challenges:[.../* @__PURE__ */ new Set([...u.challenges,i.hash])]}:{...u,adjudication:i.hash,outcome:i.outcome};await e.writeObject(a,p,!1)}}async function syncSlashIndex(e){let{ceiling:t,floorBlock:i=0,maxPages:a=10,reader:u,store:p}=e,y=Math.max(0,Math.floor(i))-1,x=Math.max(1,Math.floor(a)),w=Math.max(await publishedHeight(p)??0,y);if(t<=w)return null;let E=w;for(let e=0;e<x&&E<t;e++){let e=Math.min(E+ofe,t),i=await u.blocksByNumber(e,e-E),a=continuingRun(E,i);if(a.length===0)break;let y=foldSlashIndex(a);if(await writeRecords(p,y),await writeKeyAggregates(p,y),await writeAccusedAggregates(p,y),await resolvePending(p,y),E+=a.length,E<e)break}if(E<=w)return null;let D=createSlashIndexHead(E);return await p.writeObject(slashIndexHeadPath(),D,!1),D}async function runSlashIndexPass(e){let{chainStateViewer:t,floorBlock:i,label:a,logger:u,maxPages:p,reader:y,store:x}=e;try{let e=await t.tryCurrentBlock();if(e===void 0)return null;let w=e[0].block,E=await syncSlashIndex({ceiling:w,floorBlock:i,maxPages:p,reader:y,store:x});return E===null?null:(u?.info(E.height<w?`${a}: slash index at block ${E.height}, catching up to ${w}`:`${a}: slash index complete through block ${E.height}`),E)}catch(e){return u?.warn(`${a}: slash index pass failed: ${e.message}`),null}}var IndexerSlashActor=class extends ChainActor{_blockViewer;_chainParamsViewer;_chainStateViewer;_store;_mirroredParamsVersion;async createHandler(){await super.createHandler(),this._blockViewer=await this.locator.getInstance(Hz),this._chainStateViewer=await this.locator.getInstance(Yz);let e=await this.locator.getInstance(E8);this._store=assertEx$1(isSlashIndexStore(e)?e:void 0,()=>`${E8} did not resolve to an object store for actor ${this.name}`),this._chainParamsViewer=await this.locator.tryGetInstance(Jz)}async startHandler(){await super.startHandler(),this.registerTimer(`IndexerSlashActor`,async()=>{await this.publishPass()},2e3,this.params.config.syncInterval)}async publishPass(){await runSlashIndexPass({chainStateViewer:this._chainStateViewer,floorBlock:this.params.config.floorBlock,label:`IndexerSlashActor`,logger:this.logger,maxPages:this.params.config.pagesPerPass,reader:this._blockViewer,store:this._store});let e=this._chainParamsViewer;e!==void 0&&(this._mirroredParamsVersion=await runChainParamsMirrorPass({label:`IndexerSlashActor`,logger:this.logger,mirroredVersion:this._mirroredParamsVersion,store:this._store,viewer:e}))}};N8(IndexerSlashActor,`dependencies`,[Hz,Yz,E8]),IndexerSlashActor=M8([creatable()],IndexerSlashActor);var R8=/* @__PURE__ */ extend(CZ,{floorBlock:/* @__PURE__ */ _default$1((/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _multipleOf(1),/* @__PURE__ */ _nonnegative()),0),pagesPerPass:/* @__PURE__ */ _default$1((/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _multipleOf(1),/* @__PURE__ */ _positive()),10),syncInterval:F8}),sfe=zodToFactory(R8,`toIndexerSlashConfig`),cfe={configParser:R8,create:async e=>await IndexerSlashActor.create({account:e.wallet,config:sfe(e.actor),locator:e.locator}),defaultAccountPath:`10`,dependencies:[`BlockViewer`,`ChainStateViewer`,`SlashIndexStore`],name:`indexerSlash`,optionalProviderRoots:[`ChainParamsViewer`]},lfe={bootExtras:({process:e})=>restDataLakeViewerExtras(e),configParser:I8,create:async e=>await IndexerLicenseActor.create({account:e.wallet,config:ife(e.actor),locator:e.locator}),defaultAccountPath:`11`,dependencies:[`LicenseViewer`,`SlashIndexStore`],name:`indexerLicense`,optionalProviderRoots:[`DataLakeViewer`]},ufe={configParser:L8,create:async e=>await IndexerPayloadsActor.create({account:e.wallet,config:afe(e.actor),locator:e.locator}),defaultAccountPath:`12`,dependencies:[`PayloadIndexPublishRunner`],name:`indexerPayloads`};Uo(),_Z(),za(),GK();var z8=Object.defineProperty,dfe=Object.getOwnPropertyDescriptor,ffe=/* @__PURE__ */ __name((e,t,i)=>t in e?z8(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,`__defNormalProp`),pfe=/* @__PURE__ */ __name((e,t,i,a)=>{for(var u=a>1?void 0:a?dfe(t,i):t,p=e.length-1,y;p>=0;p--)(y=e[p])&&(u=(a?y(t,i,u):y(u))||u);return a&&u&&z8(t,i,u),u},`__decorateClass`),B8=/* @__PURE__ */ __name((e,t,i)=>ffe(e,typeof t==`symbol`?t:t+``,i),`__publicField`),mfe=1e3,hfe=6e4,gfe=1e3,toBooleanDefaultFalse=e=>e===!0||e===`true`||e===`1`||e===1,V8=/* @__PURE__ */ extend(CZ,{blockPruneInterval:(/* @__PURE__ */ _default$1(/* @__PURE__ */ number$4(),mfe)).register(Ji,{description:`The interval time (in milliseconds) between pending block prune attempts`,title:`mempool.blockPruneInterval`,type:`number`}),demotionThreshold:(/* @__PURE__ */ _default$1((/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _multipleOf(1),/* @__PURE__ */ _positive()),3)).register(Ji,{description:`Number of times a transaction may be handed out to producers without being included in a block before it is considered demoted`,title:`mempool.demotionThreshold`,type:`number`}),evidencePruneInterval:(/* @__PURE__ */ _default$1(/* @__PURE__ */ number$4(),hfe)).register(Ji,{description:`The interval time (in milliseconds) between evidence retention sweeps. Evidence is retained for windows measured in days, so this sweeps far less often than the pending pools.`,title:`mempool.evidencePruneInterval`,type:`number`}),maxPendingTransactions:(/* @__PURE__ */ _default$1((/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _multipleOf(1),/* @__PURE__ */ _nonnegative()),0)).register(Ji,{description:`Maximum number of pending transactions in the pool. When exceeded, demoted transactions are evicted first, then oldest by sequence. 0 disables the cap.`,title:`mempool.maxPendingTransactions`,type:`number`}),serveRpc:(/* @__PURE__ */ _default$1(/* @__PURE__ */ pipe$1(/* @__PURE__ */ union$3([/* @__PURE__ */ number$5(),/* @__PURE__ */ string$3(),/* @__PURE__ */ boolean$2()]),/* @__PURE__ */ transform$1(toBooleanDefaultFalse)),!1)).register(Ji,{description:`Host an HTTP JSON-RPC server (mempool methods only) on the actor host/port. Off by default; enable for a standalone mempool service.`,title:`mempool.serveRpc`,type:`boolean`}),transactionPruneInterval:(/* @__PURE__ */ _default$1(/* @__PURE__ */ number$4(),gfe)).register(Ji,{description:`The interval time (in milliseconds) between pending transaction prune attempts`,title:`mempool.transactionPruneInterval`,type:`number`})}),_fe=zodToFactory(V8,`toMempoolConfig`),vfe=N2.ReasonPhrases.OK,yfe=/* @__PURE__ */ __name((e,t)=>{setRawResponseFormat(t),t.status(200).send({message:vfe})},`handler`),bfe=N2.ReasonPhrases.OK,xfe=/* @__PURE__ */ __name((e,t)=>{setRawResponseFormat(t),t.status(200).send({message:bfe})},`handler2`),Sfe=N2.ReasonPhrases.OK,Cfe=/* @__PURE__ */ __name((e,t)=>{setRawResponseFormat(t),t.status(200).send({message:Sfe})},`handler3`),wfe=/* @__PURE__ */ __name(e=>{e.get(`/livez`,yfe),e.get(`/readyz`,xfe),e.get(`/startupz`,Cfe)},`addProbeRoutes`);function addRpcRoutes(e,t){let{logger:i,mempoolRunner:a,mempoolViewer:u}=t,p={...sq,...oq},y={...rpcMethodHandlersFromMempoolViewer(u),...rpcMethodHandlersFromMempoolRunner(a)},x=createRpcDispatchMiddleware(p,y,{logger:i}),w=new WK({engine:HK.create({middleware:[x]})});e.post(`/rpc`,async(e,t)=>{await spanAsync(`mempool:rpc`,async()=>{setRawResponseFormat(t);let i=await w.handle(e.body);t.json(i)},{logger:i,timeBudgetLimit:1e3})})}function addRoutes$1(e,t){wfe(e),addRpcRoutes(e,t)}__name(addRoutes$1,`addRoutes`);function getApp$1(e){let t=(0,M2.default)();return sharedMiddleware(t,{telemetry:e.telemetry}),addRoutes$1(t,e),t.use(standardErrors),t}__name(getApp$1,`getApp`);function formatHostPort(e,t){return`${e.includes(`:`)?`[${e}]`:e}:${t}`}async function getServer$1(e){let{logger:t,config:i}=e,{host:a,port:u}=i,p=getApp$1(e),y=await new Promise((e,i)=>{let y=p.listen(u,a,()=>{let i=y.address(),p=typeof i==`object`&&i?formatHostPort(i.address,i.port):formatHostPort(a,u);t?.info(`[Mempool] Server listening at http://${p}`),e(y)});y.once(`error`,e=>{t?.error(`[Mempool] Failed to bind HTTP server on ${formatHostPort(a,u)}: ${e.message}`),i(e),(e.code===`EADDRINUSE`||e.code===`EACCES`)&&process.exit(1)})});return y.setTimeout(2e4),y}__name(getServer$1,`getServer`);var MempoolActor=class extends ChainActor{_evidenceStoreRunner;_evidenceViewer;_mempoolRunner;_mempoolViewer;_pairCounter;_pairsSeen=/* @__PURE__ */ new Set;server;get blockPruneInterval(){return this.params.config.blockPruneInterval}get evidencePruneInterval(){return this.params.config.evidencePruneInterval}get mempoolRunner(){return this._mempoolRunner}get serveRpc(){return this.params.config.serveRpc}get transactionPruneInterval(){return this.params.config.transactionPruneInterval}async createHandler(){await super.createHandler(),this._mempoolRunner=await this.locator.getInstance(fz),this._evidenceStoreRunner=await this.locator.tryGetInstance(cz),this._evidenceViewer=await this.locator.tryGetInstance(Zz),this._pairCounter=this.counter(`mempool_actor_candidate_pairs_detected`,`Distinct same-height candidate pairs recorded in the evidence index`),this.serveRpc&&(this._mempoolViewer=assertEx$1(await this.locator.tryGetInstance(iB),()=>`[MempoolActor] serveRpc requires a MempoolViewer provider — bind MempoolViewer to the mempool store connection`))}async startHandler(){await super.startHandler(),this.serveRpc&&(this.stopServer(),await this.startServer()),this.registerTimer(`mempoolBlockPrune`,async()=>{await this.prunePendingBlocks()},2e3,this.blockPruneInterval),this.registerTimer(`mempoolTransactionPrune`,async()=>{await this.prunePendingTransactions()},2e3,this.transactionPruneInterval),this.registerTimer(`mempoolEvidencePrune`,async()=>{await this.pruneEvidence()},2e3,this.evidencePruneInterval)}async stopHandler(){await super.stopHandler(),this.stopServer()}async readyHandler(){await this.prunePendingBlocks(),await this.prunePendingTransactions()}async pruneEvidence(){await this.recordCandidatePairs(),this._evidenceStoreRunner!==void 0&&await this.spanAsync(`mempool:pruneEvidence`,async()=>{try{await this._evidenceStoreRunner?.pruneEvidence({batchSize:100,maxCheck:1e4,maxPrune:5e3})}catch(e){this.logger?.error(`[MempoolActor] Error pruning evidence: ${e.message}`)}},{...this.context,timeBudgetLimit:5e3})}async prunePendingBlocks(){await this.spanAsync(`mempool:prunePendingBlocks`,async()=>{try{await this.mempoolRunner.prunePendingBlocks({batchSize:100,maxCheck:1e4,maxPrune:5e3})}catch(e){throw this.logger?.error(`[MempoolActor] Error pruning pending blocks: ${e.message}`),e}},{...this.context,timeBudgetLimit:1e3})}async prunePendingTransactions(){await this.spanAsync(`mempool:prunePendingTransactions`,async()=>{try{await this.mempoolRunner.prunePendingTransactions({batchSize:100,maxCheck:1e4,maxPrune:5e3})}catch(e){throw this.logger?.error(`[MempoolActor] Error pruning pending transactions: ${e.message}`),e}},{...this.context,timeBudgetLimit:1e3})}async recordCandidatePairs(){let e=this._evidenceViewer;if(e!==void 0)try{let t=(await e.candidatePairs()).filter(e=>eL(e));for(let e of t){let t=e._hash;this._pairsSeen.has(t)||(this._pairsSeen.size>=1e4&&this._pairsSeen.clear(),this._pairsSeen.add(t),this._pairCounter?.add(1,{producer:e.producer}),this.logger?.warn(`[MempoolActor] candidate pair recorded at ${e.height} by ${e.producer}`))}}catch(e){this.logger?.debug(`[MempoolActor] could not read the candidate-pair index: ${e.message}`)}}async startServer(){this.server=await getServer$1({config:this.params.config,logger:this.logger,mempoolRunner:this._mempoolRunner,mempoolViewer:assertEx$1(this._mempoolViewer,()=>`[MempoolActor] MempoolViewer was not resolved`),telemetry:httpTelemetryConfig(this.params.process)})}stopServer(){this.server?.close(),this.server=void 0}};B8(MempoolActor,`dependencies`,[fz]),B8(MempoolActor,`optionalDependencies`,[iB,cz,Zz]),MempoolActor=pfe([creatable()],MempoolActor);var Tfe={configParser:V8,create:async e=>await MempoolActor.create({account:e.wallet,config:_fe(e.actor),locator:e.locator,process:e.process}),defaultAccountPath:`4`,dependencies:[`MempoolRunner`],name:`mempool`,optionalProviderRoots:[`EvidenceProtectionViewer`,`EvidenceStoreRunner`,`EvidenceViewer`,`MempoolViewer`]};Uo(),vG(),VN(),cH(),DB(),Ha(),hM(),pZ();var H8=Object.defineProperty,Efe=Object.getOwnPropertyDescriptor,Dfe=/* @__PURE__ */ __name((e,t,i)=>t in e?H8(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,`__defNormalProp`),U8=/* @__PURE__ */ __name((e,t,i,a)=>{for(var u=a>1?void 0:a?Efe(t,i):t,p=e.length-1,y;p>=0;p--)(y=e[p])&&(u=(a?y(t,i,u):y(u))||u);return a&&u&&H8(t,i,u),u},`__decorateClass`),W8=/* @__PURE__ */ __name((e,t,i)=>Dfe(e,typeof t==`symbol`?t:t+``,i),`__publicField`);function encodeBody(e,t){switch(t){case`br`:return{body:Ge.brotliCompressSync(e),contentEncoding:`br`};case`gzip`:return{body:Ge.gzipSync(e),contentEncoding:`gzip`};case`none`:return{body:new TextEncoder().encode(e)}}}function decodeBody(e,t){switch(t){case`br`:return Ge.brotliDecompressSync(e).toString(`utf8`);case`gzip`:return Ge.gunzipSync(e).toString(`utf8`);default:return new TextDecoder().decode(e)}}var Ofe=object$3({contentEncoding:_enum([`br`,`gzip`,`none`]).default(`br`)});function r2EndpointFor(e){return`https://${e}.r2.cloudflarestorage.com`}function httpsAgentForCaFile(e){return new rt.Agent({ca:et.readFileSync(e)})}var kfe=5e3,Afe=3e4;function s3ClientForConnection(e,t={}){let i=e.endpoint??r2EndpointFor(assertEx$1(e.accountId,()=>`s3 connection requires an endpoint or an accountId`)),a=i.includes(`r2.cloudflarestorage`),{caFile:u}=e,{connectionTimeoutMs:p=kfe,maxAttempts:y=5,socketTimeoutMs:x=Afe}=t;return new $e({region:a?`auto`:`us-east-1`,endpoint:i,forcePathStyle:!a,maxAttempts:y,credentials:{accessKeyId:assertEx$1(e.accessKeyId,()=>`s3 connection requires accessKeyId`),secretAccessKey:assertEx$1(e.secretAccessKey,()=>`s3 connection requires secretAccessKey`)},requestHandler:{connectionTimeout:p,socketTimeout:x,...isDefined$1(u)&&{httpsAgent:httpsAgentForCaFile(u)}}})}var G8=`public, max-age=31536000, immutable`,K8=`public, max-age=1`,q8=`public, max-age=300`,AbstractS3Provider=class extends AbstractCreatableProvider{_resolvedClient;_s3Connection;_s3Options;get bucket(){return assertEx$1(this._s3Connection?.config.bucket,()=>`No bucket specified`)}get client(){return assertEx$1(this._resolvedClient,()=>`No client specified`)}get contentEncoding(){return this.s3Options.contentEncoding}get prefix(){return this._s3Connection?.config.prefix??``}get readUrl(){return this._s3Connection?.config.readUrl}get s3Options(){return this._s3Options??=Ofe.parse(this.config.options),this._s3Options}async createHandler(){await super.createHandler();let e=this.s3Binding();this._s3Connection=e,this._resolvedClient=await this.connectionHandles.getOrOpen(`s3:${e.name}`,()=>s3ClientForConnection(e.config))}async getJson(e){try{let t=await this.client.send(new Xe({Bucket:this.bucket,Key:`${this.prefix}${e}`})),i=await t.Body?.transformToByteArray();return i===void 0?void 0:JSON.parse(decodeBody(i,t.ContentEncoding))}catch(e){if(J8(e))return;throw e}}async hasJson(e){try{return await this.client.send(new Ze({Bucket:this.bucket,Key:`${this.prefix}${e}`})),!0}catch(e){if(J8(e))return!1;throw e}}async putJson(e,t,i){let{body:a,contentEncoding:u}=encodeBody(t,this.contentEncoding);await this.client.send(new Qe({Bucket:this.bucket,Key:`${this.prefix}${e}`,Body:a,CacheControl:i,ContentEncoding:u,ContentType:`application/json`}))}s3Binding(){let e=this.constructor.requireBoundConnection(this.config),t=e.config;if(t.type!==`s3`)throw Error(`Provider [${this.moniker}] is bound to connection "${e.name}" of type "${t.type}" \u2014 expected "s3"`);return{config:t,name:e.name}}},J8=/* @__PURE__ */ __name(e=>{if(typeof e!=`object`||!e)return!1;let{name:t,$metadata:i}=e;return t===`NoSuchKey`||t===`NotFound`||i?.httpStatusCode===404},`isNotFoundError`),jfe=object$3({concurrency:number$1().default(8),progressInterval:number$1().default(100)}),S3BlockPublishRunner=class extends AbstractS3Provider{moniker=S3BlockPublishRunner.defaultMoniker;onProgress;_source;_options;get concurrency(){return this.options.concurrency}get progressInterval(){return this.options.progressInterval}get source(){return assertEx$1(this._source,()=>`No source specified`)}get options(){return this._options??=jfe.parse(this.config.options),this._options}async createHandler(){await super.createHandler(),this._source=await this.locator.getInstance(Hz)}async findCatchUpStart(e=rP(0,!0)){let t=(await this.source.currentBlock())[0].block;if(e>t||e===0&&!await this.hasBlock(rP(0,!0)))return e;for(let i=t;i>=e;i-=this.concurrency){let t=Math.max(e,i-this.concurrency+1),a=await Promise.all(Array.from({length:i-t+1},(e,i)=>this.hasBlock(rP(t+i,!0))));for(let e=i;e>=t;e--){let i=e-t;if(a.at(i)===!0)return rP(e+1,!0)}}return e}async hasBlock(e){return await this.hasJson(blockNumberPath(e))}async publishBlock(e){let t=await this.source.blockByNumber(e);if(isNull(t))return null;let i=JSON.stringify(t);await this.putJson(blockNumberPath(t[0].block),i,G8),await this.putJson(blockHashPath(t[0]._hash),i,G8);let a=t[1];for(let e of a)await this.putJson(payloadPath(e._hash),JSON.stringify(e),G8);return t}async publishManifest(){let e=createChainManifest(this.contentEncoding);await this.putJson(manifestPath(),JSON.stringify(e),q8)}async sync(e=rP(0,!0)){let t=(await this.source.currentBlock())[0].block;if(e>t)return null;await this.publishManifest();let i=new Semaphore(this.concurrency),a=Array.from({length:t-e+1},(t,i)=>rP(e+i,!0)),u=a.length,p=0;return await Promise.all(a.map(e=>i.runExclusive(async()=>{assertEx$1(await this.publishBlock(e),()=>`Block not found in source [${e}]`),p+=1,(p===u||p%this.progressInterval===0)&&this.report({blockNumber:e,published:p,total:u})}))),[e,t]}report(e){let t=this.onProgress;t?t(e):this.logger?.info(`S3BlockPublishRunner: published block ${e.blockNumber} (${e.published}/${e.total})`)}};W8(S3BlockPublishRunner,`connectionTypes`,[`s3`]),W8(S3BlockPublishRunner,`defaultMoniker`,iz),W8(S3BlockPublishRunner,`dependencies`,[Hz]),W8(S3BlockPublishRunner,`monikers`,[iz]),W8(S3BlockPublishRunner,`providerId`,`S3BlockPublishRunner`),W8(S3BlockPublishRunner,`surface`,`node`),S3BlockPublishRunner=U8([creatableProvider()],S3BlockPublishRunner);var Y8=`ChainParamsPublishRunner`,S3ChainParamsPublishRunner=class extends AbstractS3Provider{moniker=S3ChainParamsPublishRunner.defaultMoniker;_blockViewer;get blockViewer(){return assertEx$1(this._blockViewer,()=>`No BlockViewer specified`)}async createHandler(){await super.createHandler(),this._blockViewer=await this.locator.getInstance(Hz)}async currentPublished(e){let t=await this.tryGetJson(chainParamsHeadPath(e));if(t===void 0)return;let i=t.version;if(i===void 0)return;let a=await this.tryGetJson(chainParamsVersionPath(e,i));return a===void 0?void 0:oV(a,!0)}async publishParams(e){let t=e.chainId,i=[...chainParamsSuccessionErrors(await this.currentPublished(t),e,(await this.blockViewer.currentBlock())[0].block),...chainParamsInvariantErrors(e)];assertEx$1(i.length===0,()=>`Refusing to publish register version: ${i.join(`; `)}`);let a=chainParamsVersionPath(t,e.version);assertEx$1(!await this.hasJson(a),()=>`Register version ${e.version} is already published and versions are immutable`);let u=await al.dataHash(e);return await this.putJson(a,JSON.stringify(e),G8),await this.putJson(chainParamsHeadPath(t),JSON.stringify(createChainParamsHead(e.version,u)),K8),u}async tryGetJson(e){try{return await this.getJson(e)}catch{return}}};W8(S3ChainParamsPublishRunner,`connectionTypes`,[`s3`]),W8(S3ChainParamsPublishRunner,`defaultMoniker`,Y8),W8(S3ChainParamsPublishRunner,`dependencies`,[Hz]),W8(S3ChainParamsPublishRunner,`monikers`,[Y8]),W8(S3ChainParamsPublishRunner,`providerId`,`S3ChainParamsPublishRunner`),S3ChainParamsPublishRunner=U8([creatableProvider()],S3ChainParamsPublishRunner);var S3ChainStatePublishRunner=class extends AbstractS3Provider{moniker=S3ChainStatePublishRunner.defaultMoniker;_blockViewer;_chainContractViewer;get blockViewer(){return assertEx$1(this._blockViewer,()=>`No BlockViewer specified`)}get chainContractViewer(){return assertEx$1(this._chainContractViewer,()=>`No ChainContractViewer specified`)}async createHandler(){await super.createHandler(),this._blockViewer=await this.locator.getInstance(Hz),this._chainContractViewer=await this.locator.getInstance(qz)}async publishChainContract(){let e=this.chainContractViewer;for(;e!==null;)await this.ensureChainContractPublished(e),e=await e.forkedChainContractViewer()}async publishHead(){let e=await this.blockViewer.currentBlock();return await this.putJson(headPath(),JSON.stringify(e),K8),this.logger?.info(`S3ChainStatePublishRunner: published head ${e[0].block}`),e}async startHandler(){await super.startHandler(),await this.publishChainContract()}async buildChainContractManifest(e,t){let[i,a,u,p,y,x]=await Promise.all([e.minWithdrawalBlocks(),e.rewardsContract(),e.stakingTokenAddress(),e.forkedAtBlockNumber(),e.forkedAtHash(),e.forkedChainId()]);return createChainContractManifest({chainId:t,forkedAtBlockNumber:p,forkedAtHash:y,forkedChainId:x,minWithdrawalBlocks:i,rewardsContract:a,stakingTokenAddress:u})}async ensureChainContractPublished(e){let t=await e.chainId(),i=chainContractByIdPath(t);if(await this.hasJson(i))return;let a=await this.buildChainContractManifest(e,t);await this.putJson(i,JSON.stringify(a),G8),this.logger?.info(`S3ChainStatePublishRunner: published chain contract [${t}]`)}};W8(S3ChainStatePublishRunner,`connectionTypes`,[`s3`]),W8(S3ChainStatePublishRunner,`defaultMoniker`,az),W8(S3ChainStatePublishRunner,`dependencies`,[Hz,qz]),W8(S3ChainStatePublishRunner,`monikers`,[az]),W8(S3ChainStatePublishRunner,`providerId`,`S3ChainStatePublishRunner`),S3ChainStatePublishRunner=U8([creatableProvider()],S3ChainStatePublishRunner);var S3ChainStateViewer=class extends AbstractS3Provider{moniker=S3ChainStateViewer.defaultMoniker;async currentBlock(){return await this.spanAsync(`currentBlock`,async()=>{let e=assertEx$1(await this.getJson(headPath()),()=>`Head not found`);return JI(e,!0)},this.context)}async currentBlockHash(){return(await this.currentBlock())[0]._hash}async currentBlockNumber(){return(await this.currentBlock())[0].block}async tryCurrentBlock(){let e=await this.getJson(headPath());return e===void 0?void 0:JI(e,!0)}};W8(S3ChainStateViewer,`connectionTypes`,[`s3`]),W8(S3ChainStateViewer,`defaultMoniker`,Yz),W8(S3ChainStateViewer,`dependencies`,[]),W8(S3ChainStateViewer,`monikers`,[Yz]),W8(S3ChainStateViewer,`providerId`,`S3ChainStateViewer`),S3ChainStateViewer=U8([creatableProvider()],S3ChainStateViewer);var Mfe=object$3({allowedSchemas:array$1(string$1()).optional(),concurrency:number$1().default(8),disallowedSchemas:array$1(string$1()).optional()}),S3DataLakePublishRunner=class extends AbstractS3Provider{moniker=S3DataLakePublishRunner.defaultMoniker;_options;get allowedSchemas(){return this.options.allowedSchemas?.map(e=>Cs(e,!0))}get concurrency(){return this.options.concurrency}get disallowedSchemas(){return this.options.disallowedSchemas?.map(e=>Cs(e,!0))}get options(){return this._options??=Mfe.parse(this.config.options),this._options}async insert(e){let t=e.filter(e=>Gs(e)&&isSchemaAllowed(e.schema,this.allowedSchemas,this.disallowedSchemas));if(t.length===0)return[];let i=await al.addHashMeta(t),a=new Semaphore(this.concurrency);return await Promise.all(i.map(e=>a.runExclusive(async()=>{await this.putJson(payloadPath(e._hash),JSON.stringify(e),G8)}))),i}};W8(S3DataLakePublishRunner,`connectionTypes`,[`s3`]),W8(S3DataLakePublishRunner,`defaultMoniker`,oz),W8(S3DataLakePublishRunner,`dependencies`,[]),W8(S3DataLakePublishRunner,`monikers`,[oz]),W8(S3DataLakePublishRunner,`providerId`,`S3DataLakePublishRunner`),W8(S3DataLakePublishRunner,`surface`,`node`),S3DataLakePublishRunner=U8([creatableProvider()],S3DataLakePublishRunner);var Nfe=object$3({eventQueryBlockChunkSize:number$1().optional(),eventQueryInitialDelayMs:number$1().default(WX),eventQueryMaxAttempts:number$1().default(8),frameSize:number$1().default(1e5)}),S3EvmEventIndexPublishRunner=class extends AbstractS3Provider{moniker=S3EvmEventIndexPublishRunner.defaultMoniker;_options;adaptiveChunkSize;source;get address(){return toEthAddress(assertEx$1(this.config.chain.id,()=>`EVM event index requires config.chain.id`))}get configuredDeploymentBlock(){return this.config.chain.deploymentBlock}get eventQueryBlockChunkSize(){return this.fixedEventQueryBlockChunkSize??this.adaptiveChunkSize??1e5}get eventQueryInitialDelayMs(){return this.options.eventQueryInitialDelayMs}get eventQueryMaxAttempts(){return this.options.eventQueryMaxAttempts}get fixedEventQueryBlockChunkSize(){return this.options.eventQueryBlockChunkSize}get frameSize(){return this.options.frameSize}get options(){return this._options??=Nfe.parse(this.config.options),this._options}async createHandler(){await super.createHandler(),this.source=await this.locator.getInstance($z)}async publishFinalizedEvents(){let e=await assertEx$1(this.source,()=>`EVM event source is not initialized`).provider(),t=(await e.getNetwork()).chainId.toString(),i=await this.readManifest(),a=await this.resolveDeploymentBlock(e,i),u=this.createManifest(t,a);this.assertManifestCompatible(i,u);let p=assertEx$1(await e.getBlock(`finalized`),()=>`EVM provider did not return a finalized block`),y=assertEx$1(p.hash,()=>`Finalized EVM block is missing its hash`);if(p.number<a)return null;let x=await this.readHead();if(x!==void 0){if(this.assertHeadCompatible(x,u),assertEx$1(x.block<=p.number,()=>`EVM event index head is ahead of the provider finalized head`),x.block===p.number)return assertEx$1(y===x.hash,()=>`Finalized EVM index reorg detected at block ${x.block}`),x;assertEx$1(assertEx$1(await e.getBlock(x.block),()=>`Indexed EVM block ${x.block} is no longer available`).hash===x.hash,()=>`Finalized EVM index reorg detected at block ${x.block}`)}await this.publishFrames(e,u,x?.block??a-1,p.number),i===void 0&&await this.putJson(evmEventIndexManifestPath(this.address),JSON.stringify(u),q8);let w={address:this.address,block:p.number,chainId:t,hash:y};return await this.putJson(evmEventIndexHeadPath(this.address),JSON.stringify(w),K8),this.logger?.info(`S3EvmEventIndexPublishRunner: index complete through finalized EVM block ${w.block}`),w}assertHeadCompatible(e,t){assertEx$1(e.address.toLowerCase()===t.address.toLowerCase(),()=>`EVM event index head address mismatch`),assertEx$1(e.chainId===t.chainId,()=>`EVM event index head chain mismatch`)}assertManifestCompatible(e,t){e!==void 0&&(assertEx$1(e.address.toLowerCase()===t.address.toLowerCase(),()=>`EVM event index manifest address mismatch`),assertEx$1(e.chainId===t.chainId,()=>`EVM event index manifest chain mismatch`),assertEx$1(e.deploymentBlock===t.deploymentBlock,()=>`EVM event index deployment block cannot change`),assertEx$1(e.frameSize===t.frameSize,()=>`EVM event index frame size cannot change`),assertEx$1(e.layout===t.layout,()=>`Unsupported EVM event index layout`))}createManifest(e,t){return assertEx$1(Number.isSafeInteger(this.frameSize)&&this.frameSize>0,()=>`EVM event index frameSize must be a positive integer`),{address:this.address,chainId:e,deploymentBlock:t,frameSize:this.frameSize,layout:`evm-contract-events-v1`}}parseFrame(e){return _V(e,!0)}async publishFrames(e,t,i,a){let u=i+1,p;for(i>=t.deploymentBlock&&(i-t.deploymentBlock+1)%t.frameSize!==0&&(p=await this.readFrameThroughHead(t,i));u<=a;){let i=Math.floor((u-t.deploymentBlock)/t.frameSize),y=t.deploymentBlock+i*t.frameSize,x=y+t.frameSize-1,w=Math.min(x,a),E={fromBlock:y,logs:[...p?.fromBlock===y?p.logs:[],...await this.queryLogs(e,u,w)],toBlock:w};w===x?await this.putJson(evmEventIndexFramePath(this.address,i),JSON.stringify(E),G8):await this.putJson(evmEventIndexTailPath(this.address),JSON.stringify(E),K8),p=void 0,u=w+1}}async queryLogs(e,t,i){let a=[],u=t;for(;u<=i;){let t=this.eventQueryBlockChunkSize,p=Math.min(u+t-1,i),y;try{y=await withRpcRateLimitBackoff(()=>e.getLogs({address:this.address,fromBlock:u,toBlock:p}),{initialDelayMs:this.eventQueryInitialDelayMs,maxAttempts:this.eventQueryMaxAttempts})}catch(e){if(!isDefined$1(this.fixedEventQueryBlockChunkSize)&&isRpcRangeLimitError(e)&&t>1e3){let i=rpcRangeLimitFromError(e);this.adaptiveChunkSize=Math.max(UX,Math.min(i??2**53-1,Math.floor(t/2)));continue}throw e}a.push(...y.filter(e=>!e.removed).map(e=>this.toIndexedLog(e))),u=p+1}return a}async readFrameThroughHead(e,t){let i=Math.floor((t-e.deploymentBlock)/e.frameSize),a=e.deploymentBlock+i*e.frameSize,u=await this.getJson(evmEventIndexTailPath(this.address)),p=u===void 0?void 0:this.parseFrame(u);if(p?.fromBlock===a&&p.toBlock>=t)return this.trimFrameThrough(p,t);let y=await this.getJson(evmEventIndexFramePath(this.address,i)),x=y===void 0?void 0:this.parseFrame(y),w=a+e.frameSize-1,E=assertEx$1(x?.fromBlock===a&&x.toBlock===w?x:void 0,()=>`EVM event index has no published frame covering its head`);return this.trimFrameThrough(E,t)}async readHead(){let e=await this.getJson(evmEventIndexHeadPath(this.address));return e===void 0?void 0:vV(e,!0)}async readManifest(){let e=await this.getJson(evmEventIndexManifestPath(this.address));return e===void 0?void 0:yV(e,!0)}async resolveDeploymentBlock(e,t){let i=this.configuredDeploymentBlock;return t===void 0?i??await resolveContractDeploymentBlock(e,this.address,this.logger):(isDefined$1(i)&&assertEx$1(i===t.deploymentBlock,()=>`Configured EVM deployment block does not match the index manifest`),t.deploymentBlock)}toIndexedLog(e){return{address:asEthAddress(e.address,!0),blockHash:e.blockHash,blockNumber:e.blockNumber,data:e.data,index:e.index,topics:[...e.topics],transactionHash:e.transactionHash,transactionIndex:e.transactionIndex}}trimFrameThrough(e,t){return{...e,logs:e.logs.filter(e=>e.blockNumber<=t),toBlock:t}}};W8(S3EvmEventIndexPublishRunner,`connectionTypes`,[`s3`]),W8(S3EvmEventIndexPublishRunner,`defaultMoniker`,lz),W8(S3EvmEventIndexPublishRunner,`dependencies`,[$z]),W8(S3EvmEventIndexPublishRunner,`monikers`,[lz]),W8(S3EvmEventIndexPublishRunner,`providerId`,`S3EvmEventIndexPublishRunner`),W8(S3EvmEventIndexPublishRunner,`surface`,`node`),S3EvmEventIndexPublishRunner=U8([creatableProvider()],S3EvmEventIndexPublishRunner);var Pfe=5,S3IndexSummaryMap=class{family;read;window;write;constructor(e,t,i,a){this.family=e,this.window=t,this.read=i,this.write=a}clear(){}delete(e){return!1}async get(e){let[t,i]=e.split(`|`,2),{path:a}=this.locateFrame(t,Number(i)),u=await this.read(a);if(u===void 0)return;let p=u;return assertEx$1(p.hash===t,()=>`Published ${this.family} frame ${a} has head ${p.hash}, not canonical ${t}`),p}async getMany(e){return(await Promise.all(e.map(e=>this.get(e)))).flatMap(e=>e===void 0?[]:[e])}async has(e){return await this.get(e)!==void 0}async set(e,t){let{path:i,start:a}=this.locateFrame(t.hash,t.stepSize);xz(t)&&assertLinkedBlocksStepSummary(t,this.window.hashAt(a-1)),await this.write(i,JSON.stringify(t))}async setMany(e){await Promise.all(e.map(([e,t])=>this.set(e,t)))}locateFrame(e,t){let i=assertEx$1(this.window.numberOf(e),()=>`${this.family} frame head ${e} is not a block of the verified canonical window [${this.window.from}, ${this.window.to}]`),a=assertEx$1(stepPlacementForBlockNumber(i,t),()=>`Block ${i} does not end a ${t}-block ${this.family} frame`);return{path:indexSummaryPath(this.family,a.stepLevel,a.stepIndex),start:i-t+1}}},S3IndexPublishRunner=class extends AbstractS3Provider{moniker=S3IndexPublishRunner.defaultMoniker;_source;_summaryContext;get source(){return assertEx$1(this._source,()=>`No source specified`)}get fetchFn(){return this.context.fetchFn??fetch.bind(globalThis)}get summaryContext(){return this._summaryContext??={...this.context,caches:{}},this._summaryContext}async createHandler(){await super.createHandler(),this._source=await this.locator.getInstance(Hz)}async publishCompletedFramesUpTo(e){let t=await this.source.currentBlockNumber();assertEx$1(e<=t,()=>`Ceiling ${e} exceeds source head ${t}`);let i=await this.readWatermark(),a=i?.block??-1;assertEx$1(e>=a,()=>`Ceiling ${e} is behind index head ${a}`);let u=await this.readTransactionHead(),p=u?.block??-1;assertEx$1(e>=p,()=>`Ceiling ${e} is behind transaction-inclusion head ${p}`);let y=[];i&&y.push({block:i.block,hash:i.hash,name:`Index watermark`}),u&&y.push({block:u.block,hash:u.blockHash,name:`Transaction-inclusion head`});let x=await loadCanonicalBlockWindow(this.source,{anchors:y,from:Math.min(completedFramesReadStart(a,e,Pfe),p+1),to:e}),w=x.top;u&&assertEx$1(u.chain===w[0].chain,()=>`Transaction-inclusion chain ${u.chain} does not match source chain ${w[0].chain}`);let E={balances:await this.publishFamily(`balances`,5,balancesStepSummaryFromRange,x,a,e),blocks:await this.publishFamily(`blocks`,3,blocksStepSummaryFromRange,x,a,e),schemas:await this.publishFamily(`schemas`,5,schemasStepSummaryFromRange,x,a,e),transfers:await this.publishFamily(`transfers`,4,transfersStepSummaryFromRange,x,a,e)},D=await this.publishTransactionInclusions(x,p,e),A={block:e,hash:w[0]._hash,families:E};return await this.writeManifest(),await this.writeTransactionManifest(w[0].chain),await this.writeTransactionHead(createTransactionInclusionHead({block:e,blockHash:w[0]._hash,chain:w[0].chain,entries:(u?.entries??0)+D})),await this.writeHead(A),this.logger?.info(`S3IndexPublishRunner: index complete through block ${e}`),A}async publishFrame(e,t,i){let a=dI[t],u=(i+1)*a-1,p=await this.source.currentBlockNumber();assertEx$1(u<=p,()=>`Frame ${e} ${t}/${i} is not complete (head ${p})`);let y=yL([i*a,u],!0),x=await loadCanonicalBlockWindow(this.source,{from:y[0],to:y[1]});await this.buildFamilyFrame(e,y,x),this.logger?.info(`S3IndexPublishRunner: published frame ${e} ${t}/${i}`)}async buildFamilyFrame(e,t,i){let a=dI.map(()=>new Semaphore(20));switch(e){case`balances`:await balancesStepSummaryFromRange(this.summaryContext,a,i,this.summaryMap(`balances`,i),t);break;case`blocks`:await blocksStepSummaryFromRange(this.summaryContext,a,i,this.summaryMap(`blocks`,i),t);break;case`schemas`:await schemasStepSummaryFromRange(this.summaryContext,a,i,this.summaryMap(`schemas`,i),t);break;case`transfers`:await transfersStepSummaryFromRange(this.summaryContext,a,i,this.summaryMap(`transfers`,i),t)}}async publishFamily(e,t,i,a,u,p){let y=this.summaryMap(e,a),x=dI.map(()=>new Semaphore(20)),w=0;for(let e=0;e<=t;e++){let t=dI[e],E=Math.floor((u+1)/t),D=Math.floor((p+1)/t);w+=D;for(let e=E;e<D;e++){let u=e*t;await i(this.summaryContext,x,a,y,yL([u,u+t-1],!0))}}return w}async publishTransactionInclusion(e){let t=transactionInclusionPath(e.transactionHash),i=await this.readFrame(t);if(i!==void 0){let t=NR(i,!0);assertEx$1(t.transactionHash===e.transactionHash&&t.blockHash===e.blockHash&&t.blockNumber===e.blockNumber&&t.transactionIndex===e.transactionIndex,()=>`Conflicting transaction inclusion for ${e.transactionHash}`)}else await this.putJson(t,JSON.stringify(e),G8)}async publishTransactionInclusions(e,t,i){let a=new Semaphore(20),u=0,p=i;for(;p>t;){let i=Math.min(50,p-t),y=(await e.blocksByNumber(rP(p,!0),i)).flatMap(e=>transactionInclusionsFromHydratedBlock(e));await Promise.all(y.map(e=>a.runExclusive(async()=>{await this.publishTransactionInclusion(e)}))),u+=y.length,p-=i}return u}async readFrame(e){let t=this.readUrl;if(t===void 0)return await this.getJson(e);try{let i=await this.fetchFn(`${t}/${e}`);return i.status===404?void 0:i.ok?await i.json():await this.getJson(e)}catch{return await this.getJson(e)}}async readTransactionHead(){let e=await this.getJson(transactionInclusionHeadPath());return e===void 0?void 0:oH(e,!0)}async readWatermark(){let e=await this.getJson(indexHeadPath());return e===void 0?void 0:OV(e,!0)}summaryMap(e,t){return new S3IndexSummaryMap(e,t,e=>this.readFrame(e),(e,t)=>this.putJson(e,t,G8))}async writeHead(e){let t=createIndexHead(e);await this.putJson(indexHeadPath(),JSON.stringify(t),K8)}async writeManifest(){let e=createIndexManifest({balances:5,blocks:3,schemas:5,transfers:4});await this.putJson(indexManifestPath(),JSON.stringify(e),q8)}async writeTransactionHead(e){await this.putJson(transactionInclusionHeadPath(),JSON.stringify(e),K8)}async writeTransactionManifest(e){let t=createTransactionInclusionManifest(e),i=await this.getJson(transactionInclusionManifestPath());if(i!==void 0){let a=aH(i,!0);assertEx$1(a.chain===t.chain&&a.layout===t.layout&&a.path===t.path,()=>`Transaction-inclusion manifest does not match source chain ${e}`)}await this.putJson(transactionInclusionManifestPath(),JSON.stringify(t),q8)}};W8(S3IndexPublishRunner,`connectionTypes`,[`s3`]),W8(S3IndexPublishRunner,`defaultMoniker`,dz),W8(S3IndexPublishRunner,`dependencies`,[Hz]),W8(S3IndexPublishRunner,`monikers`,[dz]),W8(S3IndexPublishRunner,`providerId`,`S3IndexPublishRunner`),S3IndexPublishRunner=U8([creatableProvider()],S3IndexPublishRunner);var X8=[3,4,5,6,7],Z8=32,Ffe=object$3({policyId:NV.default(AV),stepConcurrency:number$1().int().min(1).max(8).default(4),timeAnchor:qX.optional()}),S3NetworkStakeRewardsIndexPublishRunner=class extends AbstractS3Provider{moniker=S3NetworkStakeRewardsIndexPublishRunner.defaultMoniker;_blockViewer;_stakeViewer;_options;get options(){return this._options??=Ffe.parse(this.config.options),this._options}get policyId(){return this.options.policyId}get timeAnchor(){return this.options.timeAnchor}async createHandler(){await super.createHandler(),this._blockViewer=await this.locator.getInstance(Hz),this._stakeViewer=await this.locator.getInstance(pB)}async publishRewardsIndex(e,t){let i=await this.readManifest(),a=this.createManifest(t);this.assertManifestCompatible(i,a);let u=await this.readHead();if(await this.assertHeadCompatible(u,e,t),await this.publishManifestIfMissing(i,a),u!==void 0&&this.isCurrent(u,e,t))return u;let p=await this.resolvePublishableSteps(rP(u?.processedThroughBlock??0,!0),e.block,t.block),y=this.processedThroughBlock(p,e.block),x=await this._stakeViewer.stakeEvents.positionCount([0,t.block]),w=await this.advanceRewards(u,p.publishable,t.block,x),E=u!==void 0&&p.publishable.length===0?u.snapshotHash:await this.publishSnapshot(w.stepCount,w.positionTotals,w.totalReward),D=WV({layout:kV,policyId:this.policyId,positionCount:x,processedThroughBlock:y,snapshotHash:E,source:{evm:{block:t.block,hash:t.hash},xl1:{block:e.block,hash:e.hash}},stepCount:w.stepCount},!0);return await this.putJson(networkStakeRewardsIndexHeadPath(this.policyId),JSON.stringify(D),K8),this.logger?.info(`S3NetworkStakeRewardsIndexPublishRunner: ${w.stepCount} reward steps complete through XL1 block ${y} (XL1 source ${e.block}, EVM source ${t.block})`),D}async advanceRewards(e,t,i,a){let u=e===void 0?void 0:await this.readSnapshot(e.snapshotHash);u!==void 0&&assertEx$1(u.stepCount===e?.stepCount,()=>`Rewards snapshot step count mismatch`);let p={positionTotals:this.positionTotals(u),stepCount:e?.stepCount??0,totalReward:BigInt(u?.totalReward??`0`)};if(t.length===0)return p;let y=await this.loadPositions(a),x=indexStakeEventsByPosition(await this._stakeViewer.stakeEvents.stakeEvents([0,i]));for(let e=0;e<t.length;e+=this.options.stepConcurrency){this.signal.throwIfAborted();let i=t.slice(e,e+this.options.stepConcurrency),a=await Promise.all(i.map(async e=>await this.resolveStepRecord(e,y,x)));for(let e of a){p.stepCount++,p.totalReward+=BigInt(e.totalReward);for(let[t,i]of Object.entries(e.positionRewards)){let e=Number(t);p.positionTotals.set(e,(p.positionTotals.get(e)??0n)+BigInt(i))}}}return p}async assertHeadCompatible(e,t,i){assertEx$1((await this._blockViewer.blockByNumber(t.block))?.[0]._hash===t.hash,()=>`Rewards index XL1 watermark hash mismatch`),e!==void 0&&(assertEx$1(e.policyId===this.policyId,()=>`Rewards index head policy mismatch`),assertEx$1(e.source.xl1.block<=t.block,()=>`Rewards index XL1 source moved backwards`),assertEx$1(e.source.evm.block<=i.block,()=>`Rewards index EVM source moved backwards`),e.source.evm.block===i.block&&assertEx$1(e.source.evm.hash===i.hash,()=>`Rewards index EVM source hash changed`),assertEx$1((await this._blockViewer.blockByNumber(rP(e.source.xl1.block,!0)))?.[0]._hash===e.source.xl1.hash,()=>`Rewards index XL1 source reorg detected`))}assertManifestCompatible(e,t){e!==void 0&&(assertEx$1(e.layout===t.layout,()=>`Unsupported rewards index layout`),assertEx$1(e.policyId===t.policyId,()=>`Rewards index manifest policy mismatch`),assertEx$1(e.evmAddress.toLowerCase()===t.evmAddress.toLowerCase(),()=>`Rewards index EVM address mismatch`),assertEx$1(e.evmChainId===t.evmChainId,()=>`Rewards index EVM chain mismatch`),assertEx$1(JSON.stringify(e.stepLevels)===JSON.stringify(t.stepLevels),()=>`Rewards index step levels changed`),assertEx$1(JSON.stringify(e.timeAnchor)===JSON.stringify(t.timeAnchor),()=>`Rewards index time anchor changed`))}createManifest(e){return VV({evmAddress:e.address,evmChainId:e.chainId,layout:kV,policyId:this.policyId,stepLevels:[...X8],timeAnchor:this.timeAnchor},!0)}isCurrent(e,t,i){return e.source.xl1.block===t.block&&e.source.xl1.hash===t.hash&&e.source.evm.block===i.block&&e.source.evm.hash===i.hash}async loadPositions(e){let t=[];for(let i=0;i<e;i+=Z8){this.signal.throwIfAborted();let a=Array.from({length:Math.min(Z8,e-i)},(e,t)=>i+t);t.push(...await Promise.all(a.map(async e=>await this._stakeViewer.stakeById(e))))}return t}positionTotals(e){return new Map(Object.entries(e?.positionRewards??{}).map(([e,t])=>[Number(e),BigInt(t)]))}processedThroughBlock(e,t){return e.firstBlockedStep===void 0?t:rP(e.firstBlockedStep.block-1,!0)}async publishManifestIfMissing(e,t){e===void 0&&await this.putJson(networkStakeRewardsIndexManifestPath(this.policyId),JSON.stringify(t),q8)}async publishSnapshot(e,t,i){let a=t.entries().filter(([,e])=>e>0n).toArray(),u=Object.fromEntries(a.toSorted(([e],[t])=>e-t).map(([e,t])=>[String(e),t.toString()])),p=new al({schema:jV}),y=UV(p.fields({layout:kV,policyId:this.policyId,positionRewards:u,stepCount:e,totalReward:i.toString()}).build(),!0),x=await al.hash(y),w=networkStakeRewardsIndexSnapshotPath(this.policyId,x);return await this.putJson(w,JSON.stringify(y),G8),x}async readHead(){let e=await this.getJson(networkStakeRewardsIndexHeadPath(this.policyId));return e===void 0?void 0:WV(e,!0)}async readManifest(){let e=await this.getJson(networkStakeRewardsIndexManifestPath(this.policyId));return e===void 0?void 0:VV(e,!0)}async readSnapshot(e){let t=networkStakeRewardsIndexSnapshotPath(this.policyId,e),i=UV(assertEx$1(await this.getJson(t),()=>`Rewards index snapshot is missing: ${t}`),!0);return assertEx$1(await al.hash(i)===e,()=>`Rewards index snapshot hash mismatch: ${t}`),assertEx$1(i.policyId===this.policyId,()=>`Rewards snapshot policy mismatch`),i}async resolvePublishableSteps(e,t,i){let a=blockRangeSteps(yL([e,t],{name:`S3NetworkStakeRewardsIndexPublishRunner`}),[...X8]).toSorted((e,t)=>e.block-t.block||e.step-t.step),u=[];for(let e of a){let t=await externalBlockRangeFromStep(this.context,this._blockViewer,e,this.timeAnchor);if(t[1]>i)return{firstBlockedStep:e,publishable:u};u.push({externalRange:t,step:e})}return{publishable:u}}async resolveStepRecord(e,t,i){let a=networkStakeRewardsIndexStepPath(this.policyId,e.step),u=await this.getJson(a);if(isDefined$1(u)){let t=HV(u,!0);return assertEx$1(t.policyId===this.policyId,()=>`Rewards step policy mismatch`),assertEx$1(t.step.block===e.step.block&&t.step.step===e.step.step,()=>`Rewards step identity mismatch`),assertEx$1(t.externalRange[0]===e.externalRange[0]&&t.externalRange[1]===e.externalRange[1],()=>`Rewards step external range mismatch`),t}let p=await networkStakeStepRewardsForPositions(this.context,this._blockViewer,e.step,t,i,{},this.timeAnchor,e.externalRange),y=Object.fromEntries(p.positionRewards.entries().filter(([,e])=>e>0n).map(([e,t])=>[String(e),t.toString()])),x=assertEx$1(dI[e.step.step],()=>`Unknown step level ${e.step.step}`),w=HV({denominator:p.denominator.toString(),externalRange:e.externalRange,layout:kV,policyId:this.policyId,positionRewards:y,step:e.step,totalReward:p.totalReward.toString(),xl1Range:[e.step.block-x,e.step.block-1]},!0);return await this.putJson(a,JSON.stringify(w),G8),w}};W8(S3NetworkStakeRewardsIndexPublishRunner,`connectionTypes`,[`s3`]),W8(S3NetworkStakeRewardsIndexPublishRunner,`defaultMoniker`,mz),W8(S3NetworkStakeRewardsIndexPublishRunner,`dependencies`,[Hz,pB]),W8(S3NetworkStakeRewardsIndexPublishRunner,`monikers`,[mz]),W8(S3NetworkStakeRewardsIndexPublishRunner,`providerId`,`S3NetworkStakeRewardsIndexPublishRunner`),W8(S3NetworkStakeRewardsIndexPublishRunner,`surface`,`node`),S3NetworkStakeRewardsIndexPublishRunner=U8([creatableProvider()],S3NetworkStakeRewardsIndexPublishRunner);var Q8=3,$8=dI[Q8],e5=dI[0],Ife=object$3({concurrency:int().positive().default(32),limits:Tz.default({...Ez}),maxBlocksPerPass:int().positive().default(8*$8)}),PublishedBlocksSource=class{blocks=/* @__PURE__ */ new Map;loaded=[];maxCachedBlocks;numbers=/* @__PURE__ */ new Map;pending=/* @__PURE__ */ new Map;published;read;constructor(e,t,i=3*$8){this.read=e,this.published=t,this.maxCachedBlocks=i}async blockByNumber(e){let t=this.blocks.get(e);return t===void 0?(await this.load(e,`smallest`),assertEx$1(this.blocks.get(e),()=>`Block ${e} is not in its published blocks frame`).block):t.block}numberOf(e){return this.numbers.get(e)}async prefetch(e,t){let i=e;for(;i<=t;)this.blocks.has(i)?i+=1:i=(await this.load(i,`largest`)).to+1}evict(){let e=this.blocks.size;for(;e>this.maxCachedBlocks&&this.loaded.length>1;){let t=this.loaded.shift();for(let e=t.from;e<=t.to;e++){let t=this.blocks.get(e);t!==void 0&&(--t.refs,t.refs===0&&this.blocks.delete(e))}e=this.blocks.size}}frameFor(e,t){let i=t===`largest`?[3,2,1,0]:[0,1,2,3];for(let t of i){let i=dI[t],a=Math.floor(e/i);if((a+1)*i-1<=this.published)return{stepIndex:a,stepLevel:t}}throw Error(`Block ${e} is in no complete blocks frame (index head ${this.published})`)}async load(e,t){let{stepIndex:i,stepLevel:a}=this.frameFor(e,t),u=indexSummaryPath(`blocks`,a,i),p=this.pending.get(u);if(p!==void 0)return await p;let y=this.loadFrame(u,a,i);this.pending.set(u,y);try{return await y}finally{this.pending.delete(u)}}async loadFrame(e,t,i){let a=assertEx$1(await this.read(e),()=>`Blocks frame ${e} is not published`),u=Sz(a,{required:!0});await verifyBlocksFrame(u);let p=dI[t],y=i*p,x=y+p-1,[w]=u.blocks[0],[E]=u.blocks.at(-1);assertEx$1(w.block===y&&E.block===x,()=>`Blocks frame ${e} holds [${w.block}, ${E.block}], not [${y}, ${x}]`);let D=this.blocks.get(y-1);assertEx$1(D===void 0||w.previous===D.block[0]._hash,()=>`Blocks frame ${e} does not link to block ${y-1}`);let A=this.blocks.get(x+1);assertEx$1(A===void 0||A.block[0].previous===E._hash,()=>`Block ${x+1} does not link to blocks frame ${e}`);for(let t of u.blocks){let i=this.blocks.get(t[0].block);i===void 0?this.blocks.set(t[0].block,{block:t,refs:1}):(assertEx$1(i.block[0]._hash===t[0]._hash,()=>`Blocks frame ${e} disagrees with a loaded frame at block ${t[0].block}`),i.refs+=1),this.numbers.set(t[0]._hash,t[0].block)}return this.loaded.push({from:y,to:x}),this.evict(),{from:y,to:x}}};async function verifyBlocksFrame(e){assertLinkedBlocksStepSummary(e);for(let[t,i]of e.blocks){assertEx$1(await al.hash(t)===t._hash,()=>`Block ${t.block} does not rehash to ${t._hash}`);let e=/* @__PURE__ */ new Set;for(let a of i)TP(a)&&(assertEx$1(await al.hash(a)===a._hash,()=>`Transaction ${a._hash} in block ${t.block} does not rehash`),assertEx$1(t.payload_hashes.includes(a._hash),()=>`Block ${t.block} hydrates transaction ${a._hash} it does not list`),e.add(a._hash));for(let[a,u]of t.payload_schemas.entries()){if(u!==sw)continue;let p=t.payload_hashes[a];assertEx$1(e.has(p)||i.some(e=>e._hash===p),()=>`Block ${t.block} lists bound witness ${p} but does not hydrate it`)}}}async function verifyDataHash(e,t,i){let a=await al.dataHash(e),u=e._dataHash;return assertEx$1(u===a,()=>`${i} claims data hash ${String(u)} but rehashes to ${a}`),assertEx$1(t===void 0||a===t,()=>`${i} rehashes to ${a}, not ${t}`),a}var S3PayloadIndexPublishRunner=class extends AbstractS3Provider{moniker=S3PayloadIndexPublishRunner.defaultMoniker;_options;get limits(){return this.options.limits}get maxBlocksPerPass(){return this.options.maxBlocksPerPass}get fetchFn(){return this.context.fetchFn??fetch.bind(globalThis)}get options(){return this._options??=Ife.parse(this.config.options??{}),this._options}async publishCompletedFrames(){let e=await this.getJson(indexHeadPath());if(e===void 0)return null;let t=OV(e,!0),i=await this.readManifest(),a=await this.readHead(),u=a?.block??-1,p=Math.floor((t.block+1)/e5)*e5-1,y=Math.min(p,u+this.maxBlocksPerPass),x=Math.floor((y+1)/e5)*e5-1;if(x<=u)return a===void 0?null:toWatermark(a);let w=new PublishedBlocksSource(e=>this.readFrame(e),t.block);if(a!==void 0){let e=await w.blockByNumber(rP(a.block,!0));assertEx$1(e[0]._hash===a.hash,()=>`Payloads head ${a.block} (${a.hash}) is not the indexed block ${e[0]._hash}`)}await this.buildFrames(w,u,x);let[E]=await w.blockByNumber(rP(x,!0));x===t.block&&assertEx$1(E._hash===t.hash,()=>`Indexed block ${x} is ${E._hash}, but the index head names ${t.hash}`),await this.writeManifest(i,E.chain);let D={block:rP(x,!0),frames:dI.slice(0,6).map(e=>Math.floor((x+1)/e)),hash:E._hash};return await this.putJson(payloadsHeadPath(),JSON.stringify(createPayloadIndexHead(D)),K8),this.logger?.info(`S3PayloadIndexPublishRunner: payloads index complete through block ${x}`),D}async buildFrames(e,t,i){let a=new PassCache,u=this.summaryMap(e,t,a),p=this.pageStore(a),y=dI.map(()=>new Semaphore(20)),build=async(t,i)=>{let a=dI[t];await payloadsStepSummaryFromRange({...this.context,caches:{}},y,e,u,p,yL([i*a,i*a+a-1],!0),this.limits)};for(let a=Math.floor((t+1)/$8)*$8;a<=i;a+=$8){let u=Math.max(a,t+1),p=Math.min(a+$8-1,i);await e.prefetch(u,p);for(let e=0;e<=Math.min(Q8,5);e++)await runPool(framesEndingIn(e,u,p),this.options.concurrency,t=>build(e,t))}for(let e=Q8+1;e<=5;e++)await runPool(framesEndingIn(e,t+1,i),this.options.concurrency,t=>build(e,t))}pageStore(e){return{get:async t=>{let i=e.pages.get(t);if(i!==void 0)return i;let a=await this.readFrame(payloadsPagePath(t));if(a!==void 0)return assertEx$1(Rz(a),()=>`Payloads page ${t} is not a locator page`),await verifyDataHash(a,t,`Payloads page ${t}`),e.pages.set(t,a),a},set:async t=>{await this.putJson(payloadsPagePath(t._dataHash),JSON.stringify(t),G8),e.pages.set(t._dataHash,t)}}}async readFrame(e){let t=this.readUrl;if(t===void 0)return await this.getJson(e);try{let i=await this.fetchFn(`${t}/${e}`);return i.status===404?void 0:i.ok?await i.json():await this.getJson(e)}catch{return await this.getJson(e)}}async readHead(){let e=await this.getJson(payloadsHeadPath());if(e===void 0)return;let t=XV(e,!0);return assertEx$1(t.version===1,()=>`Payloads head is layout version ${t.version}, not 1`),t}async readManifest(){let e=await this.getJson(payloadsManifestPath());if(e===void 0)return;let t=JV(e,!0),i=this.limits;return assertEx$1(t.version===1&&t.maxStep===5&&t.limits.delegateAbove===i.delegateAbove&&t.limits.inlinePerSchema===i.inlinePerSchema&&t.limits.inlinePerSummary===i.inlinePerSummary&&t.limits.pageLocators===i.pageLocators,()=>`The published payloads manifest describes a different layout; a new layout needs a new family root`),t}summaryMap(e,t,i){let locate=(t,i)=>{let a=assertEx$1(e.numberOf(t),()=>`Payloads frame head ${t} is not a loaded indexed block`);return assertEx$1(stepPlacementForBlockNumber(a,i),()=>`Block ${a} does not end a ${i}-block frame`)},get=async e=>{let[a,u]=e.split(`|`,2),p=Number(u),{stepIndex:y,stepLevel:x}=locate(a,p),w=payloadsSummaryPath(x,y),E=i.summaries.get(w);if(E!==void 0)return E;if((y+1)*p-1>t)return;let D=await this.readFrame(w);if(D===void 0)return;assertEx$1(Fz(D),()=>`Published ${w} is not a payloads summary`);let A=D;return assertEx$1(A.hash===a,()=>`Published ${w} has head ${A.hash}, not ${a}`),await verifyDataHash(A,void 0,`Published ${w}`),i.summaries.set(w,A),A},set=async(e,t)=>{let{stepIndex:a,stepLevel:u}=locate(t.hash,t.stepSize),p=indexSummaryPath(`schemas`,u,a);assertPayloadsSchemasParity(t,assertEx$1(await this.readFrame(p),()=>`Schemas frame ${p} is not published`));let y=payloadsSummaryPath(u,a);await this.putJson(y,JSON.stringify(t),G8),i.summaries.set(y,t)};return{clear:()=>{},delete:()=>!1,get,getMany:async e=>(await Promise.all(e.map(e=>get(e)))).filter(e=>e!==void 0),has:async e=>await get(e)!==void 0,set,setMany:async e=>{for(let[t,i]of e)await set(t,i)}}}async writeManifest(e,t){if(e!==void 0){assertEx$1(e.chain===t,()=>`The payloads manifest names chain ${e.chain}, not ${t}`);return}let i=createPayloadIndexManifest({chain:t,limits:this.limits,maxStep:5});await this.putJson(payloadsManifestPath(),JSON.stringify(i),q8)}};W8(S3PayloadIndexPublishRunner,`connectionTypes`,[`s3`]),W8(S3PayloadIndexPublishRunner,`defaultMoniker`,hz),W8(S3PayloadIndexPublishRunner,`dependencies`,[]),W8(S3PayloadIndexPublishRunner,`monikers`,[hz]),W8(S3PayloadIndexPublishRunner,`providerId`,`S3PayloadIndexPublishRunner`),S3PayloadIndexPublishRunner=U8([creatableProvider()],S3PayloadIndexPublishRunner);var BoundedMap=class{max;values=/* @__PURE__ */ new Map;constructor(e){this.max=e}get(e){return this.values.get(e)}set(e,t){for(this.values.delete(e),this.values.set(e,t);this.values.size>this.max;)this.values.delete(this.values.keys().next().value)}},PassCache=class{pages=new BoundedMap(512);summaries=new BoundedMap(4096)};async function runPool(e,t,i){let a=0,u,worker=async()=>{for(;u===void 0&&a<e.length;){let t=e[a];a+=1;try{await i(t)}catch(e){u??={error:e}}}};if(await Promise.all(Array.from({length:Math.min(t,e.length)},()=>worker())),u!==void 0)throw u.error}function framesEndingIn(e,t,i){let a=dI[e],u=Math.ceil((t+1)/a)-1,p=Math.floor((i+1)/a)-1,y=[];for(let e=Math.max(u,0);e<=p;e++)y.push(e);return y}function toWatermark(e){return{block:rP(e.block,!0),frames:e.frames,hash:e.hash}}_Z(),za(),hM(),Uo();var t5=Object.defineProperty,Lfe=Object.getOwnPropertyDescriptor,Rfe=/* @__PURE__ */ __name((e,t,i)=>t in e?t5(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,`__defNormalProp`),n5=/* @__PURE__ */ __name((e,t,i,a)=>{for(var u=a>1?void 0:a?Lfe(t,i):t,p=e.length-1,y;p>=0;p--)(y=e[p])&&(u=(a?y(t,i,u):y(u))||u);return a&&u&&t5(t,i,u),u},`__decorateClass`),r5=/* @__PURE__ */ __name((e,t,i)=>Rfe(e,typeof t==`symbol`?t:t+``,i),`__publicField`),MirrorVerificationError=class extends Error{block;constructor(e,t){super(`Mirror verification failed at block ${e}: ${t}`),this.name=`MirrorVerificationError`,this.block=e}};async function isPayloadHashVerified(e,t,i){let a=await al.hash(t);return a===t._hash||findPayloadHashVariance(e,t,a,i)!==void 0}async function verifyHydratedBlock(e,t,i=RB){if(!qI(e))throw new MirrorVerificationError(t.block,`the source is not a signed hydrated block with hash metadata`);let[a,u]=e,p=a.block;if(p!==t.block)throw new MirrorVerificationError(t.block,`the source returned block ${p} instead`);if(t.hash!==void 0&&a._hash!==t.hash)throw new MirrorVerificationError(p,`the block does not match the pinned head hash`);let y=a.previous??null;if(t.previous!==void 0&&y!==t.previous)throw new MirrorVerificationError(p,`previous is ${y}, expected ${t.previous}`);if(await al.hash(a)!==a._hash)throw new MirrorVerificationError(p,`the block hash does not match its contents`);if(await al.dataHash(a)!==a._dataHash)throw new MirrorVerificationError(p,`the block data hash does not match its contents`);if(a.payload_hashes.length!==a.payload_schemas.length)throw new MirrorVerificationError(p,`the hydrated payloads do not cover the block references`);let x=/* @__PURE__ */ new Set;for(let[e,t]of a.payload_hashes.entries()){let i=JSON.stringify([t,a.payload_schemas[e]]);x.add(i)}if(u.length<x.size)throw new MirrorVerificationError(p,`the hydrated payloads do not cover the block references`);let w=/* @__PURE__ */ new Set;for(let t of u){if(!await isPayloadHashVerified(e,t,i))throw new MirrorVerificationError(p,`payload ${t._hash} does not match its contents`);let a=JSON.stringify([t._hash,t.schema]);if(!x.has(a))throw new MirrorVerificationError(p,`the hydrated payloads do not match the block references`);w.add(a)}if(w.size!==x.size)throw new MirrorVerificationError(p,`the hydrated payloads do not match the block references`)}function sha256(e){return ot(`sha256`).update(e).digest(`hex`)}async function verifyBlockRollup(e,t){let i=dI[t.level];if(!Number.isSafeInteger(t.level)||t.level<0||t.level>3||!Number.isSafeInteger(t.index)||t.index<0||i===void 0)throw RangeError(`Block rollups require a published level 0–3 and a nonnegative safe index`);let a=t.index*i,u=a+i-1;if(!Number.isSafeInteger(u))throw RangeError(`The rollup range exceeds safe block numbers`);if(typeof e!=`object`||!e)throw new MirrorVerificationError(u,`the step is not an object`);let p=e;if(p.schema!==bz||p.stepSize!==i||!Array.isArray(p.blocks)||p.blocks.length!==i||p.hash!==t.hash)throw new MirrorVerificationError(u,`the rollup schema, size, count, or pinned last hash is wrong`);if(!p.blocks.every(qI))throw new MirrorVerificationError(u,`the rollup contains a malformed hydrated block`);let y=await verifyDescendingBlocks(p.blocks.toSorted((e,t)=>t[0].block-e[0].block),u,t.hash);if(a===0&&y!==null)throw new MirrorVerificationError(0,`genesis must not have a previous block`);let x=JSON.stringify(e);return{bytes:Buffer.byteLength(x),firstPreviousHash:y,from:a,index:t.index,json:x,lastBlockHash:t.hash,level:t.level,sha256:sha256(x),to:u}}async function verifyDescendingBlocks(e,t,i){let a=i;for(let[i,u]of e.entries()){let e=t-i;if(a===null)throw new MirrorVerificationError(e,`the chain ended before genesis`);await verifyHydratedBlock(u,{block:e,hash:a,previous:e===0?null:void 0}),a=u[0].previous??null}return a}var ArchiveOutcomeUnknownError=class extends Error{constructor(e){super(`Archive upload outcome remains unknown at ${e}; reconcile the prior attempt before retrying`),this.name=`ArchiveOutcomeUnknownError`}};function isNotFound(e){return e?.$metadata?.httpStatusCode===404}function journaledAttempts(e){let t=`attempts`in e?e:{};return{attemptedAt:t.attemptedAt===void 0?-1/0:Date.parse(t.attemptedAt),attempts:t.attempts??1}}function assertMatchingIntent(e,t){for(let i of[`key`,`sha256`,`storedSha256`,`bytes`,`storedBytes`,`contentEncoding`])if(e[i]!==t[i])throw Error(`Archive journal conflicts at ${t.key}`)}function decodePublishedBody(e,t,i){let a=new TextDecoder(`utf-8`,{fatal:!0});if(t!==`none`)try{let u=t===`br`?qe(e,{maxOutputLength:i}):Ye(e,{maxOutputLength:i}),p=a.decode(u);return JSON.parse(p),{json:p,stored:e}}catch{}if(e.byteLength>i)throw Error(`Published archive object exceeds its read bound`);let u=a.decode(e);return JSON.parse(u),{json:u,stored:encodeArchiveBody(u,t).body}}function isArchiveCid(e){return typeof e==`string`&&/^[a-zA-Z0-9]{10,256}$/.test(e)}function encodeArchiveBody(e,t){return t===`br`?{body:Ke(e,{params:{[Je.BROTLI_PARAM_QUALITY]:6}}),contentEncoding:`br`}:encodeBody(e,t)}function decodeArchivedBody(e,t){let i=sha256(e),a;if(i===t.storedSha256&&e.byteLength===t.storedBytes)switch(t.contentEncoding){case`br`:a=qe(e,{maxOutputLength:t.bytes});break;case`gzip`:a=Ye(e,{maxOutputLength:t.bytes});break;default:a=e}else a=e;if(a.byteLength!==t.bytes||sha256(a)!==t.sha256)throw Error(`Archive content checksum fails at ${t.key}`);return new TextDecoder(`utf-8`,{fatal:!0}).decode(a)}var S3ArchiveObjectStore=class{bucket;client;encoding;journal;now;retry;signal;constructor(e){this.bucket=e.bucket,this.client=e.client,this.encoding=e.contentEncoding,this.journal=e.journal,this.now=e.now??Date.now,this.retry=e.retry,this.signal=e.signal}async exists(e){try{return await this.client.send(new Ze({Bucket:this.bucket,Key:e}),{abortSignal:this.signal?.()}),!0}catch(e){if(isNotFound(e))return!1;throw e}}async readPublishedJson(e,t){let i=await this.readMapped(e,t);if(i===void 0)return;let{json:a,stored:u}=decodePublishedBody(i.body,this.encoding,t),p=/* @__PURE__ */ new Date;return{json:a,receipt:{bytes:Buffer.byteLength(a),cid:i.cid,contentEncoding:this.encoding,key:e,readBackAt:p.toISOString(),sha256:sha256(a),storedBytes:u.byteLength,storedSha256:sha256(u)}}}async writeJson(e,t){let{body:i,contentEncoding:a}=encodeArchiveBody(t,this.encoding),u={bytes:Buffer.byteLength(t),contentEncoding:this.encoding,key:e,sha256:sha256(t),storedBytes:i.byteLength,storedSha256:sha256(i)},p=await this.journal.read(e);if(p!==void 0&&(assertMatchingIntent(p,u),`cid`in p&&isArchiveCid(p.cid)))return p;let y=await this.readReceipt(u);if(y!==void 0)return await this.journal.finish(y),y;if(p!==void 0&&!this.mayRetry(p))throw new ArchiveOutcomeUnknownError(e);let x=new Date(this.now());await this.journal.begin({...u,attemptedAt:x.toISOString(),attempts:p===void 0?1:journaledAttempts(p).attempts+1}),await this.client.send(new Qe({Body:i,Bucket:this.bucket,CacheControl:G8,ContentEncoding:a,ContentType:`application/json`,IfNoneMatch:`*`,Key:e,Metadata:{sha256:u.sha256,"stored-sha256":u.storedSha256}}),{abortSignal:this.signal?.()});let w=await this.readReceipt(u);if(w===void 0)throw new ArchiveOutcomeUnknownError(e);return await this.journal.finish(w),w}mayRetry(e){if(this.retry===void 0)return!1;let{attemptedAt:t,attempts:i}=journaledAttempts(e);return i<this.retry.maxAttempts&&this.now()-t>=this.retry.retryAfterMs}async readMapped(e,t){let i;try{i=await this.client.send(new Ze({Bucket:this.bucket,Key:e}),{abortSignal:this.signal?.()})}catch(e){if(isNotFound(e))return;throw e}let a=i.Metadata?.cid;if(!isArchiveCid(a))throw Error(`Archive object has no CID at ${e}`);if(t!==void 0&&(i.ContentLength??0)>t)throw Error(`Published archive object exceeds its read bound`);let u=await this.client.send(new Xe({Bucket:this.bucket,Key:e,VersionId:i.VersionId}),{abortSignal:this.signal?.()}),p=await u.Body?.transformToByteArray();if(p===void 0||u.Metadata?.cid!==a)throw Error(`Archive readback CID changed at ${e}`);return{body:p,cid:a}}async readReceipt(e){let t=await this.readMapped(e.key);if(t===void 0)return;decodeArchivedBody(t.body,e);let i=/* @__PURE__ */ new Date;return{...e,cid:t.cid,readBackAt:i.toISOString()}}},i5=dI[3],zfe={fromIndex:0,previousHash:null};async function prepareRollupArchive(e,t,i=zfe,a){let u={block:t[0].block,hash:t[0]._hash},p=Math.floor((u.block+1)/i5);if(!Number.isSafeInteger(i.fromIndex)||i.fromIndex<0||i.fromIndex>p||i.fromIndex===0&&i.previousHash!==null)throw RangeError(`Invalid verified archive checkpoint`);let y=(u.block+1)%i5,x=y===0?[]:await e.reader.blocksByNumber(rP(u.block,!0),y);if(x.length!==y)throw new MirrorVerificationError(u.block,`the open tail has missing blocks`);let w=await verifyDescendingBlocks(x,u.block,u.hash);await e.staging.stageTail(x);let E=p===0||w===null?void 0:{block:p*i5-1,hash:w},D=0;for(let t=p-1;t>=i.fromIndex;t--){if(w===null)throw new MirrorVerificationError(t*i5,`the chain ended before genesis`);let i={hash:w,index:t,level:3},u=await verifyBlockRollup(e.index.canonicalStep===void 0?await e.index.stepSummary(`blocks`,3,t):await e.index.canonicalStep(i),i);await e.staging.stageRollup(u),D+=u.bytes,w=u.firstPreviousHash,a?.(t,u.bytes)}if(w!==i.previousHash)throw new MirrorVerificationError(i.fromIndex*i5,`the archive does not connect to its verified checkpoint`);return{archiveHead:E,completedSteps:p,fromIndex:i.fromIndex,pinnedHead:u,tailBlocks:y,verifiedBytes:D}}var a5=(/* @__PURE__ */ string$3()).check(/* @__PURE__ */ _regex(/^[0-9a-f]{64}$/)),o5=(/* @__PURE__ */ string$3()).check(/* @__PURE__ */ _regex(/^[a-zA-Z0-9]{10,256}$/)),s5=(/* @__PURE__ */ number$5()).check(int$1(),/* @__PURE__ */ _nonnegative()),c5=/* @__PURE__ */ object$5({block:s5,hash:a5}),l5={archiveHead:c5,level:/* @__PURE__ */ literal$2(3),previousManifestCid:/* @__PURE__ */ optional$2(o5),schema:/* @__PURE__ */ literal$2(`network.xyo.archive.manifest`),sourceHead:c5,steps:/* @__PURE__ */ array$2(/* @__PURE__ */ object$5({bytes:s5,cid:o5,contentEncoding:/* @__PURE__ */ _enum$1([`br`,`gzip`,`none`]),firstPreviousHash:/* @__PURE__ */ nullable$2(a5),index:s5,key:/* @__PURE__ */ string$3(),lastBlockHash:a5,readBackAt:/* @__PURE__ */ string$3(),sha256:a5,storedBytes:s5,storedSha256:a5,version:(/* @__PURE__ */ number$5()).check(int$1(),/* @__PURE__ */ _positive())})),version:(/* @__PURE__ */ number$5()).check(int$1(),/* @__PURE__ */ _positive())},Bfe=/* @__PURE__ */ union$3([/* @__PURE__ */ object$5({...l5,formatVersion:/* @__PURE__ */ literal$2(1)}),/* @__PURE__ */ object$5({...l5,formatVersion:/* @__PURE__ */ literal$2(2),genesisHash:a5,network:/* @__PURE__ */ _enum$1([`mainnet`,`sequence`])})]);function validNetwork(e){if(e!==`mainnet`&&e!==`sequence`)throw RangeError(`Invalid archive network`)}function namedArchiveStepKey(e,t,i=1){validNetwork(e),archiveStepKey(t,i);let a=t*i5,u=a+i5-1;if(!Number.isSafeInteger(a)||!Number.isSafeInteger(u))throw RangeError(`Invalid archive block range`);return`blocks/3/xl1-${e}-blocks-${a}-${u}-v${i}.json.br`}function namedArchiveManifestKey(e,t){return validNetwork(e),archiveManifestKey(t),`xl1-${e}-manifest-v${t}.json.br`}function archiveRollupGenesisHash(e){let t=JSON.parse(e);if(typeof t!=`object`||!t||!(`blocks`in t)||!Array.isArray(t.blocks))throw Error(`A verified genesis rollup is required`);let i=t.blocks.find(e=>qI(e)&&e[0].block===0);if(!qI(i)||i[0].previous!==null)throw Error(`Archive genesis is missing`);return i[0]._hash}function archiveStepKey(e,t=1){if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t)||t<1)throw RangeError(`Invalid archive step index/version`);return`blocks/3/${e}${t===1?``:`_${t}`}.json`}function archiveManifestKey(e){if(!Number.isSafeInteger(e)||e<1)throw RangeError(`Invalid archive manifest version`);return`manifest${e===1?``:`_${e}`}.json`}function parseArchiveManifest(e){let t=Bfe.parse(e);if(t.steps.length===0)throw Error(`An archive manifest cannot claim empty coverage`);let i=null;for(let[e,a]of t.steps.entries()){let u=t.formatVersion===2?namedArchiveStepKey(t.network,e,a.version):archiveStepKey(e,a.version);if(a.index!==e||a.key!==u||a.firstPreviousHash!==i||t.formatVersion===2&&a.contentEncoding!==`br`)throw Error(`Archive manifest has a gap, wrong key, or conflicting link at step ${e}`);i=a.lastBlockHash}if(t.archiveHead.block!==t.steps.length*i5-1||t.archiveHead.hash!==i||t.sourceHead.block<t.archiveHead.block)throw Error(`Archive manifest head does not match its coverage`);return t}function createArchiveManifest(e,t,i,a,u){if(e.archiveHead===void 0||t.length!==e.completedSteps)throw Error(`A manifest requires a readback receipt for every completed step`);let p=t.map(({receipt:e,rollup:t,version:i})=>{if(t.level!==3||e.sha256!==t.sha256||e.bytes!==t.bytes)throw Error(`Archive receipt does not match verified rollup ${t.index}`);return{...e,firstPreviousHash:t.firstPreviousHash,index:t.index,lastBlockHash:t.lastBlockHash,version:i}});return parseArchiveManifest({archiveHead:e.archiveHead,...u===void 0?{formatVersion:1}:{formatVersion:2,...u},level:3,previousManifestCid:a,schema:`network.xyo.archive.manifest`,sourceHead:e.pinnedHead,steps:p,version:i})}var u5=`https://s3.auto-drive.autonomys.xyz`,Vfe=`https://mainnet.auto-drive.autonomys.xyz/api`,d5=int$1(),Hfe=/* @__PURE__ */ object$5({downloadLimit:d5,id:(/* @__PURE__ */ string$3()).check(/* @__PURE__ */ _minLength(1)),model:/* @__PURE__ */ _enum$1([`monthly`,`one_off`]),organizationId:(/* @__PURE__ */ string$3()).check(/* @__PURE__ */ _minLength(1)),pendingDownloadCredits:d5,pendingUploadCredits:d5,uploadLimit:d5});function createAutoDriveS3Client(e){if(e.trim().length===0)throw Error(`An Auto Drive API key is required`);return new $e({credentials:{accessKeyId:e,secretAccessKey:`unused`},endpoint:u5,forcePathStyle:!0,maxAttempts:1,region:`us-east-1`,requestHandler:{connectionTimeout:1e4,requestTimeout:12e4}})}function parseAutoDriveAccount(e){return Hfe.parse(e)}async function readAutoDriveAccount(e,t=fetch){if(e.trim().length===0)throw Error(`An Auto Drive API key is required`);let i=await t(`${Vfe}/accounts/@me`,{headers:{Authorization:`Bearer ${e}`,"X-Auth-Provider":`apikey`},redirect:`error`,signal:AbortSignal.timeout(3e4)});if(!i.ok)throw Error(`Auto Drive account lookup failed with HTTP ${i.status}`);return parseAutoDriveAccount(await i.json())}function assertAutoDriveUploadBudget(e,t,i){if(!Number.isSafeInteger(i)||i<0)throw RangeError(`Invalid Auto Drive upload size`);if(e.id!==t)throw Error(`Auto Drive account does not match the selected archive account`);if(i>0&&e.pendingUploadCredits<i)throw Error(`Auto Drive available upload bytes do not cover the archive plan`)}function publishedBlockMap(e){let t=/* @__PURE__ */ new Map;if(typeof e!=`object`||!e||!(`blocks`in e)||!Array.isArray(e.blocks))return t;let i=e.blocks;for(let e of i)qI(e)&&t.set(e[0]._hash,e);return t}async function reconstructBlockRollup(e,t,i){let a=dI[t.level];if(!Number.isSafeInteger(t.level)||t.level<0||t.level>3||!Number.isSafeInteger(t.index)||t.index<0||a===void 0)throw RangeError(`Invalid rollup reconstruction range`);let u=(t.index+1)*a-1;if(!Number.isSafeInteger(u))throw RangeError(`The rollup range exceeds safe block numbers`);let p=publishedBlockMap(e),y=[],x=t.hash;for(let e=0;e<a;e++){let t=u-e;if(x===null)throw new MirrorVerificationError(t,`reconstruction reached genesis too early`);let a=p.get(x)??await i(x);if(a===null)throw new MirrorVerificationError(t,`canonical block ${x} is unavailable`);await verifyHydratedBlock(a,{block:t,hash:x,previous:t===0?null:void 0}),y.push(a),x=a[0].previous??null}return await verifyBlockRollup({blocks:y.toReversed(),hash:t.hash,schema:bz,stepSize:a},t)}var BackupSourceConflictError=class extends Error{constructor(e){super(e),this.name=`BackupSourceConflictError`}},f5=/* @__PURE__ */ Symbol(`backupPassStage`);async function atBackupPassStage(e,t){try{return await t()}catch(t){throw typeof t==`object`&&t&&!Object.hasOwn(t,f5)&&Object.defineProperty(t,f5,{value:e}),t}}function backupPassStage(e){return typeof e==`object`&&e?e[f5]:void 0}var BackupArchiveAdvancedError=class extends Error{constructor(e){super(`Archive manifest ${e} was published by another writer; adopt it before continuing`),this.name=`BackupArchiveAdvancedError`}},BackupIndexPendingError=class extends Error{index;constructor(e){super(`Index step ${e} is not published yet`),this.name=`BackupIndexPendingError`,this.index=e}};function checkBudget(e){for(let t of[e.maxPassBytes,e.maxStepsPerPass,e.manifestReserveBytes])ct.ok(Number.isSafeInteger(t)&&t>0,`Backup pass limits must be positive safe integers`);ct.ok(Number.isSafeInteger(e.maxTotalUploadBytes)&&e.maxTotalUploadBytes>=0),ct.ok(e.deadline===void 0||Number.isFinite(e.deadline)),e.dryRun||ct.ok(e.maxTotalUploadBytes>0,`Paid backup requires an explicit positive upload ceiling`)}function stripJson(e){let{json:t,...i}=e;return i}async function latestPublishedManifestVersion(e,t,i,a){async function published(i){return a(),await atBackupPassStage(`archive-provider`,()=>e.exists(namedArchiveManifestKey(t,i)))}if(!await published(i+1))return i;let u=i+1,p=i+2;for(;await published(p);)u=p,p=i+2*(p-i);for(;p-u>1;){let e=Math.floor((u+p)/2);await published(e)?u=e:p=e}return u}async function adoptPublishedArchive(e,t,i,a){let{store:u}=e;if(t.dryRun||u===void 0)return!1;let p=await latestPublishedManifestVersion(u,t.network,i.manifestVersion,a);if(p===i.manifestVersion)return!1;let y=await atBackupPassStage(`archive-provider`,()=>u.readPublishedJson(namedArchiveManifestKey(t.network,p),t.maxPassBytes));if(a(),y===void 0)throw new BackupSourceConflictError(`A published archive manifest disappeared during adoption`);let x=parseArchiveManifest(JSON.parse(y.json));if(x.version!==p)throw new BackupSourceConflictError(`A published archive manifest is stored under another version`);let w=await atBackupPassStage(`source-read`,async()=>await e.reader.blocksByNumber(rP(x.archiveHead.block,!0),1));a(),ct.equal(w.length,1,`Source is missing the published archive head`);let E=w[0];if(await verifyHydratedBlock(E,{block:x.archiveHead.block,hash:E[0]._hash}),E[0].chain!==t.expectedChainId||E[0]._hash!==x.archiveHead.hash)throw new BackupSourceConflictError(`A published archive head differs from the source chain`);return a(),await e.state.adopt(x,y.receipt),!0}async function selectWindow(e,t,i,a){let u=await atBackupPassStage(`source-read`,async()=>await e.source.tryCurrentBlock());if(a(),u===void 0)return{status:`idle`};if(ct.ok(qI(u),`Source head is not a signed hydrated block`),u[0].chain!==t.expectedChainId)throw new BackupSourceConflictError(`Current source chain differs from the selected network identity`);if(await verifyHydratedBlock(u,{block:u[0].block,hash:u[0]._hash}),a(),i.archiveHead!==void 0&&(u[0].block<i.archiveHead.block||u[0].block===i.archiveHead.block&&u[0]._hash!==i.archiveHead.hash))throw new BackupSourceConflictError(`Source conflicts with the durable archive head`);let p={block:u[0].block,hash:u[0]._hash},y=Math.floor((u[0].block+1)/i5);if(y<=i.nextIndex&&i.pendingWindow===void 0)return{sourceHead:p,status:`idle`};let x=i.pendingWindow?.toIndex??Math.min(i.nextIndex+t.maxStepsPerPass,y)-1;if(x>=y||x-i.nextIndex+1>t.maxStepsPerPass)throw new BackupSourceConflictError(`Unfinished window no longer fits the source or selected pass bound`);let w=(x+1)*i5-1;ct.ok(Number.isSafeInteger(w));let E=await atBackupPassStage(`source-read`,async()=>await e.reader.blocksByNumber(rP(w,!0),1));a(),ct.equal(E.length,1,`Source is missing the selected sealed tip`);let D=E[0];if(await verifyHydratedBlock(D,{block:w,hash:D[0]._hash}),w===p.block&&D[0]._hash!==p.hash)throw new BackupSourceConflictError(`Selected tip conflicts with the pinned source head`);if(i.pendingWindow!==void 0&&D[0]._hash!==i.pendingWindow.pinnedHead.hash)throw new BackupSourceConflictError(`Source changed an unfinished paid window`);return a(),{sourceHead:p,status:`window`,tip:D,toIndex:x}}async function prepareWindow(e,t,i,a,u){let p={fromIndex:i.nextIndex,pinnedHead:{block:a.tip[0].block,hash:a.tip[0]._hash},toIndex:a.toIndex},y=[],x=[],w=0;async function stepSummary(t,i,a){u();let p=await atBackupPassStage(`source-read`,async()=>await e.index.stepSummary(t,i,a));return u(),p}let{blockByHash:E}=e,D=await prepareRollupArchive({index:{canonicalStep:E===void 0?void 0:async e=>{let t=await stepSummary(`blocks`,e.level,e.index);if(t==null)throw new BackupIndexPendingError(e.index);try{return await verifyBlockRollup(t,e),t}catch(i){if(!(i instanceof MirrorVerificationError))throw i;let a=await reconstructBlockRollup(t,e,async e=>(u(),await atBackupPassStage(`source-read`,async()=>await E(e))));return u(),x.push({index:e.index,rejectedBlock:i.block}),JSON.parse(a.json)}},stepSummary},reader:{blocksByNumber:async(t,i)=>await atBackupPassStage(`source-read`,async()=>await e.reader.blocksByNumber(t,i))},staging:{stageRollup:e=>(u(),w+=e.bytes,ct.ok(w<=t.maxPassBytes,`Backup pass source bytes exceed the finite window budget`),y.push(e),Promise.resolve()),stageTail:e=>(ct.equal(e.length,0,`Backup may only publish sealed steps`),Promise.resolve())}},a.tip,{fromIndex:i.nextIndex,previousHash:i.archiveHead?.hash??null});u(),y.sort((e,t)=>e.index-t.index),ct.equal(y.length,a.toIndex-i.nextIndex+1);let A=y.find(e=>e.index===0),N=i.genesisHash??(A===void 0?void 0:archiveRollupGenesisHash(A.json));if(ct.ok(N!==void 0,`A backup needs its verified genesis identity`),t.expectedGenesisHash!==void 0&&N!==t.expectedGenesisHash)throw new BackupSourceConflictError(`Source genesis differs from the selected archive identity`);let P=new Set(x.map(e=>e.index)),F=y.map(e=>{let i=encodeArchiveBody(e.json,`br`).body,a=P.has(e.index)?2:1;return{bytes:i.byteLength,index:e.index,key:namedArchiveStepKey(t.network,e.index,a),sha256:sha256(i),version:a}}),I=i.manifestVersion+1,L=namedArchiveManifestKey(t.network,I),B=F.reduce((e,t)=>e+t.bytes,t.manifestReserveBytes);return ct.ok(Number.isSafeInteger(B)&&B<=t.maxPassBytes,`Backup pass upload reservation exceeds its finite byte budget`),{genesisHash:N,manifestKey:L,manifestVersion:I,plannedUploadBytes:B,prepared:D,reconstructedSteps:x,rollups:y,sourceHead:a.sourceHead,stepIntents:F,window:p}}async function prepareWindowOrWait(e,t,i,a,u){try{return await prepareWindow(e,t,i,a,u)}catch(e){if(e instanceof BackupIndexPendingError)return;throw e}}async function publishWindow(e,t,i,a,u){ct.ok(e.store!==void 0&&e.checkAccount!==void 0,`Paid backup requires a selected object writer and live account preflight`),u(),await atBackupPassStage(`account`,()=>e.checkAccount(0)),u(),await e.state.reserveWindow(a.window,[...a.stepIntents,{bytes:t.manifestReserveBytes,key:a.manifestKey}],t.maxTotalUploadBytes);let p=e.state.createJournal(t.maxTotalUploadBytes),y=[...i.steps];for(let t of a.rollups){u();let i=a.stepIntents.find(e=>e.index===t.index);ct.ok(i!==void 0,`Every prepared step requires an upload intent`);let x=await p.read(i.key);await atBackupPassStage(`account`,()=>e.checkAccount(x!==void 0&&`cid`in x?0:i.bytes)),u();let w=await atBackupPassStage(`archive-provider`,()=>e.store.writeJson(i.key,t.json));u(),ct.ok(w.key===i.key&&w.contentEncoding===`br`&&w.sha256===t.sha256&&w.bytes===t.bytes&&w.storedBytes===i.bytes&&w.storedSha256===i.sha256,`Backup readback receipt differs from the verified prepared step`),y.push({receipt:w,rollup:stripJson(t),version:i.version})}let x=createArchiveManifest({...a.prepared,verifiedBytes:y.reduce((e,t)=>e+t.rollup.bytes,0)},y,a.manifestVersion,i.manifestReceipt?.cid,{genesisHash:a.genesisHash,network:t.network}),w=JSON.stringify(x);ct.ok(encodeArchiveBody(w,`br`).body.byteLength<=t.manifestReserveBytes,`Manifest exceeds the reserved upload bytes`),u();let E=await p.read(a.manifestKey);if(E===void 0&&await atBackupPassStage(`archive-provider`,()=>e.store.exists(a.manifestKey)))throw new BackupArchiveAdvancedError(a.manifestKey);await atBackupPassStage(`account`,()=>e.checkAccount(E!==void 0&&`cid`in E?0:encodeArchiveBody(w,`br`).body.byteLength)),u();let D=await atBackupPassStage(`archive-provider`,()=>e.store.writeJson(a.manifestKey,w));u(),await e.state.commit(x,D,y);let A=e.state.read();return{archiveHead:A.archiveHead,chargedBytes:e.state.chargedBytes(),fromIndex:i.nextIndex,manifestCid:A.manifestReceipt?.cid,nextIndex:A.nextIndex,plannedUploadBytes:a.plannedUploadBytes,preparedSteps:a.rollups.length,reconstructedSteps:a.reconstructedSteps,sourceHead:a.sourceHead,status:`published`}}async function backupPass(e,t){checkBudget(t);let i=t.now??Date.now;function check(){if(t.signal?.throwIfAborted(),t.deadline!==void 0&&i()>=t.deadline)throw Error(`Backup pass deadline reached`)}return await e.state.withPass(async()=>{check();let i=e.state.read();ct.equal(i.scope.network,t.network),ct.equal(i.scope.chainId,t.expectedChainId),ct.equal(i.scope.expectedGenesisHash,t.expectedGenesisHash);let a=await adoptPublishedArchive(e,t,i,check),u=e.state.read(),p={archiveHead:u.archiveHead,chargedBytes:e.state.chargedBytes(),fromIndex:u.nextIndex,manifestCid:u.manifestReceipt?.cid,nextIndex:u.nextIndex,plannedUploadBytes:0,preparedSteps:0,status:`idle`};if(a)return{...p,fromIndex:i.nextIndex,status:`adopted`};let y=await selectWindow(e,t,u,check);if(y.status===`idle`)return{...p,sourceHead:y.sourceHead};let x=await prepareWindowOrWait(e,t,u,y,check);return x===void 0?{...p,sourceHead:y.sourceHead,status:`waiting-for-index`}:t.dryRun?{...p,plannedUploadBytes:x.plannedUploadBytes,preparedSteps:x.rollups.length,reconstructedSteps:x.reconstructedSteps,sourceHead:x.sourceHead,status:`dry-run`}:await publishWindow(e,t,u,x,check)})}async function writeDurableJson(e,t){let i=D.dirname(e);await We.mkdir(i,{mode:448,recursive:!0});let a=`${e}.${st()}.tmp`,u=await We.open(a,`wx`,384);try{await u.writeFile(JSON.stringify(t)),await u.sync()}finally{await u.close()}await We.rename(a,e);let p=await We.open(i,`r`);try{await p.sync()}finally{await p.close()}}var FileArchiveWriteJournal=class{directory;constructor(e){this.directory=e}async begin(e){await writeDurableJson(this.path(e.key),e)}async finish(e){await writeDurableJson(this.path(e.key),e)}async read(e){try{return JSON.parse(await We.readFile(this.path(e),`utf8`))}catch(e){if(e.code===`ENOENT`)return;throw e}}path(e){return D.join(this.directory,`${sha256(e)}.json`)}},BackupPassOverlapError=class extends Error{constructor(){super(`A backup pass is already active for this state store`),this.name=`BackupPassOverlapError`}};function serviceUid(){let e=process.getuid;return ct.ok(e!==void 0,`Backup state requires POSIX user identity`),e()}function safeInteger(e){ct.ok(typeof e==`number`&&Number.isSafeInteger(e)&&e>=0,`Invalid backup state integer`)}function hash(e){ct.ok(typeof e==`string`&&/^[0-9a-f]{64}$/.test(e),`Invalid backup state hash`)}function checkIntent(e,t){e.attempts!==void 0&&(safeInteger(e.attempts),ct.ok(e.attempts>0,`Invalid backup upload attempt count`)),e.attemptedAt!==void 0&&ct.ok(Number.isFinite(Date.parse(e.attemptedAt)),`Invalid backup upload attempt time`),safeInteger(e.bytes),safeInteger(e.storedBytes),ct.ok(e.bytes>0&&e.storedBytes>0&&e.contentEncoding===`br`,`Invalid backup object encoding or length`),hash(e.sha256),hash(e.storedSha256);let i=/^blocks\/3\/xl1-(mainnet|sequence)-blocks-(\d+)-(\d+)-v(\d+)\.json\.br$/.exec(e.key),a=/^xl1-(mainnet|sequence)-manifest-v(\d+)\.json\.br$/.exec(e.key);if(i===null)ct.ok(a!==null,`Unexpected backup journal key`),ct.equal(e.key,namedArchiveManifestKey(t.network,Number(a[2])));else{let a=Number(i[2]);ct.equal(e.key,namedArchiveStepKey(t.network,a/i5,Number(i[4])))}}function checkReceipt(e,t){checkIntent(e,t),ct.ok(isArchiveCid(e.cid),`Invalid backup receipt CID`),ct.ok(typeof e.readBackAt==`string`&&Number.isFinite(Date.parse(e.readBackAt)),`Invalid backup receipt time`)}function chargedBytes(e){let t=Object.values(e.reservations).reduce((e,t)=>e+t.bytes*(t.attempts??1),0);return safeInteger(t),t}function checkCommittedSteps(e,t,i){let a=null;for(let[u,p]of e.steps.entries())i(p.receipt),ct.ok(p.version===1||p.version===2,`Invalid backup step version`),ct.equal(p.rollup.index,u),ct.equal(p.rollup.level,3),ct.equal(p.rollup.from,u*i5),ct.equal(p.rollup.to,(u+1)*i5-1),ct.equal(p.rollup.firstPreviousHash,a),hash(p.rollup.lastBlockHash),ct.equal(p.receipt.key,namedArchiveStepKey(t.network,u,p.version)),ct.equal(p.receipt.sha256,p.rollup.sha256),ct.equal(p.receipt.bytes,p.rollup.bytes),a=p.rollup.lastBlockHash;return a}function isSameStoredStep(e,t){let{receipt:i,rollup:a}=e;return t?.key===i.key&&t.cid===i.cid&&t.contentEncoding===i.contentEncoding&&t.bytes===i.bytes&&t.sha256===i.sha256&&t.storedBytes===i.storedBytes&&t.storedSha256===i.storedSha256&&t.firstPreviousHash===a.firstPreviousHash&&t.lastBlockHash===a.lastBlockHash&&t.version===e.version}function committedStepFromManifest(e){return{receipt:{bytes:e.bytes,cid:e.cid,contentEncoding:e.contentEncoding,key:e.key,readBackAt:e.readBackAt,sha256:e.sha256,storedBytes:e.storedBytes,storedSha256:e.storedSha256},rollup:{bytes:e.bytes,firstPreviousHash:e.firstPreviousHash,from:e.index*i5,index:e.index,lastBlockHash:e.lastBlockHash,level:3,sha256:e.sha256,to:(e.index+1)*i5-1},version:e.version}}function checkCommittedState(e,t,i){if(e.nextIndex===0)ct.equal(e.archiveHead,void 0),ct.equal(e.manifestReceipt,void 0),ct.equal(e.genesisHash,void 0),ct.equal(e.manifestVersion,0);else{ct.ok(e.archiveHead!==void 0&&e.manifestReceipt!==void 0&&e.genesisHash!==void 0),hash(e.genesisHash),t.expectedGenesisHash!==void 0&&ct.equal(e.genesisHash,t.expectedGenesisHash),i(e.manifestReceipt),ct.deepEqual(e.manifestReceipt,e.manifestReceipts.at(-1)),ct.equal(e.manifestReceipt.key,namedArchiveManifestKey(t.network,e.manifestVersion));let a=checkCommittedSteps(e,t,i);ct.equal(e.archiveHead.block,e.nextIndex*i5-1),ct.equal(e.archiveHead.hash,a)}}function checkPendingWindow(e){if(e.pendingWindow===void 0)return;let t=e.pendingWindow;safeInteger(t.fromIndex),safeInteger(t.toIndex),ct.equal(t.fromIndex,e.nextIndex),ct.ok(t.toIndex>=t.fromIndex),ct.equal(t.pinnedHead.block,(t.toIndex+1)*i5-1),hash(t.pinnedHead.hash)}function validateState(e,t){ct.ok(typeof e==`object`&&!!e&&!Array.isArray(e),`Invalid backup checkpoint`);let i=e;ct.equal(i.schema,`network.xyo.backup.state/1`),ct.deepEqual(i.scope,t,`Backup state scope differs from selected network/account/bucket/endpoint`),safeInteger(i.nextIndex),safeInteger(i.manifestVersion);let a=i.manifestReceiptsFrom??1;safeInteger(a),ct.ok(a>=1&&(i.manifestVersion===0?a===1:a<=i.manifestVersion),`Invalid backup manifest receipt history start`),ct.ok(Array.isArray(i.manifestReceipts)&&i.manifestReceipts.length===(i.manifestVersion===0?0:i.manifestVersion-a+1),`Backup manifest receipt history is incomplete`),ct.ok(Array.isArray(i.steps)&&i.steps.length===i.nextIndex,`Backup coverage is incomplete`),ct.ok(typeof i.reservations==`object`&&i.reservations!==null&&!Array.isArray(i.reservations));for(let[e,a]of Object.entries(i.reservations))ct.ok(typeof a==`object`&&!!a),safeInteger(a.bytes),ct.ok(a.bytes>0&&typeof a.confirmed==`boolean`),a.attempts!==void 0&&(safeInteger(a.attempts),ct.ok(a.attempts>0,`Invalid backup reservation attempt count`)),a.sha256!==void 0&&hash(a.sha256),ct.ok(e.startsWith(`xl1-${t.network}-manifest-v`)||e.startsWith(`blocks/3/xl1-${t.network}-blocks-`));chargedBytes(i);function confirmedReceipt(e){checkReceipt(e,t);let a=i.reservations[e.key];ct.ok(a?.confirmed,`Committed receipt lacks its paid reservation`),ct.equal(a.bytes,e.storedBytes,`Committed byte accounting differs from its receipt`),ct.equal(a.sha256,e.storedSha256,`Committed accounting hash differs from its receipt`)}for(let[e,u]of i.manifestReceipts.entries())confirmedReceipt(u),ct.equal(u.key,namedArchiveManifestKey(t.network,a+e));return checkCommittedState(i,t,confirmedReceipt),checkPendingWindow(i),i}async function assertFreshJournal(e){let t=D.join(e,`journal`),i;try{i=await We.lstat(t)}catch(e){if(e.code===`ENOENT`)return;throw e}ct.ok(i.isDirectory()&&i.uid===serviceUid(),`Backup journal must be a service-owned directory`);let a=await We.opendir(t);try{ct.equal(await a.read(),null,`Missing backup checkpoint with a nonempty durable journal; refusing budget reset`)}finally{await a.close()}}async function verifyBackupWriterLock(e,t){ct.equal(process.platform,`linux`,`Backup state requires a Linux inherited advisory flock`),ct.ok(Number.isSafeInteger(t)&&t>=3,`Invalid backup lock descriptor`);let i=et.fstatSync(t,{bigint:!0}),a=await We.lstat(D.join(e,`.writer.lock`),{bigint:!0});ct.ok(i.isFile()&&a.isFile()&&i.nlink===1n&&a.nlink===1n,`Backup lock must be a regular single-link file`),ct.equal(i.dev,a.dev),ct.equal(i.ino,a.ino),ct.equal(Number(a.uid),serviceUid(),`Backup lock must belong to the service user`);let u=i.dev>>8n&4095n|i.dev>>32n&-4096n,p=i.dev&255n|i.dev>>12n&-256n,y=await We.readFile(`/proc/locks`,`utf8`);ct.ok(y.split(`
|
|
34578
34578
|
`).some(e=>{let t=e.trim().split(/\s+/);if(t[1]!==`FLOCK`||t[2]!==`ADVISORY`||t[3]!==`WRITE`||Number(t[4])!==process.pid)return!1;let a=t[5]?.split(`:`);return a?.length===3&&BigInt(`0x${a[0]}`)===u&&BigInt(`0x${a[1]}`)===p&&BigInt(a[2])===i.ino&&t[6]===`0`&&t[7]===`EOF`}),`Current process does not own the exact backup FLOCK WRITE lock`)}var BackupStateStore=class{directory;scope;active=!1;lockFd;lockVerifier;state;constructor(e,t,i=9,a){ct.ok(D.isAbsolute(e),`Backup state directory must be absolute`),this.directory=D.resolve(e),this.scope=structuredClone(t),this.scope.expectedGenesisHash===void 0&&delete this.scope.expectedGenesisHash,this.lockFd=i,this.lockVerifier=a??(()=>verifyBackupWriterLock(this.directory,this.lockFd))}async adopt(e,t){this.assertActive();let i=this.read(),a=parseArchiveManifest(e);ct.ok(a.formatVersion===2&&a.network===this.scope.network,`Published manifest belongs to another archive`),this.scope.expectedGenesisHash!==void 0&&ct.equal(a.genesisHash,this.scope.expectedGenesisHash,`Published manifest genesis differs from the selected archive identity`),i.genesisHash!==void 0&&ct.equal(a.genesisHash,i.genesisHash,`Published manifest genesis differs from the checkpoint`),ct.ok(a.version>i.manifestVersion&&a.steps.length>=i.nextIndex,`Published manifest does not extend the checkpoint`);for(let[e,t]of i.steps.entries())ct.ok(isSameStoredStep(t,a.steps[e]),`Published archive diverges from the checkpoint`);checkReceipt(t,this.scope),ct.equal(t.key,namedArchiveManifestKey(this.scope.network,a.version));let u=[...i.steps,...a.steps.slice(i.steps.length).map(committedStepFromManifest)],p={...i.reservations};for(let{receipt:e}of[...u.slice(i.steps.length),{receipt:t}])p[e.key]={attempts:p[e.key]?.attempts,bytes:e.storedBytes,confirmed:!0,sha256:e.storedSha256};await this.save({...i,archiveHead:{block:a.archiveHead.block,hash:a.archiveHead.hash},genesisHash:a.genesisHash,manifestReceipt:t,manifestReceipts:[t],manifestReceiptsFrom:a.version,manifestVersion:a.version,nextIndex:u.length,pendingWindow:void 0,reservations:p,steps:u})}chargedBytes(){return chargedBytes(this.read())}async commit(e,t,i){this.assertActive();let a=this.read(),u=parseArchiveManifest(e);ct.ok(u.formatVersion===2&&u.network===this.scope.network),ct.equal(u.version,a.manifestVersion+1),ct.equal(u.previousManifestCid,a.manifestReceipt?.cid),ct.deepEqual(i.slice(0,a.steps.length),a.steps,`Committed archive history cannot change`),ct.ok(a.pendingWindow!==void 0&&i.length===a.pendingWindow.toIndex+1),ct.deepEqual(u.archiveHead,a.pendingWindow.pinnedHead),ct.deepEqual(u.steps,i.map(e=>({...e.receipt,firstPreviousHash:e.rollup.firstPreviousHash,index:e.rollup.index,lastBlockHash:e.rollup.lastBlockHash,version:e.version})),`Manifest entries differ from the confirmed step receipts`),checkReceipt(t,this.scope),ct.equal(t.key,namedArchiveManifestKey(this.scope.network,u.version)),ct.equal(t.sha256,sha256(JSON.stringify(u))),ct.equal(t.bytes,Buffer.byteLength(JSON.stringify(u))),ct.ok(a.reservations[t.key]?.confirmed,`Manifest must have a durable readback receipt before checkpoint advance`);for(let e of i)ct.ok(a.reservations[e.receipt.key]?.confirmed,`Every committed step requires a confirmed receipt`);await this.save({...a,archiveHead:u.archiveHead,genesisHash:u.genesisHash,manifestReceipt:t,manifestReceipts:[...a.manifestReceipts,t],manifestVersion:u.version,nextIndex:i.length,pendingWindow:void 0,steps:i})}createJournal(e){let t=new FileArchiveWriteJournal(D.join(this.directory,`journal`));return{begin:async i=>{this.assertActive(),checkIntent(i,this.scope);let a=this.read(),u=a.reservations[i.key];ct.ok(u!==void 0&&i.storedBytes<=u.bytes,`Paid intent must have a durable reservation`),u.sha256!==void 0&&ct.equal(u.sha256,i.storedSha256,`Paid intent differs from its reservation`),u.sha256=i.storedSha256,u.attempts=Math.max(u.attempts??1,i.attempts??1),ct.ok(chargedBytes(a)<=e,`Backup total upload ceiling exceeded`),await this.save(a),await t.begin(i)},finish:async e=>{this.assertActive(),checkReceipt(e,this.scope);let i=this.read(),a=i.reservations[e.key];ct.ok(a!==void 0&&e.storedBytes<=a.bytes,`Receipt exceeds its reservation`),a.sha256!==void 0&&ct.equal(a.sha256,e.storedSha256),await t.finish(e),i.reservations[e.key]={attempts:a.attempts,bytes:e.storedBytes,confirmed:!0,sha256:e.storedSha256},await this.save(i)},read:async e=>{this.assertActive();let i=await t.read(e);if(i!==void 0&&(checkIntent(i,this.scope),`cid`in i)){checkReceipt(i,this.scope);let t=this.read(),a=t.reservations[e];ct.ok(a!==void 0&&i.storedBytes<=a.bytes,`Stored receipt lacks its reservation`),a.sha256!==void 0&&ct.equal(a.sha256,i.storedSha256),a.confirmed&&a.bytes===i.storedBytes||(t.reservations[e]={attempts:a.attempts,bytes:i.storedBytes,confirmed:!0,sha256:i.storedSha256},await this.save(t))}return i}}}async initialize(){await this.withPass(()=>Promise.resolve())}read(){return ct.ok(this.state!==void 0,`Backup state has not been initialized`),structuredClone(this.state)}async reserveWindow(e,t,i){this.assertActive();let a=this.read();a.pendingWindow!==void 0&&ct.deepEqual(e,a.pendingWindow,`An unfinished backup window must be reconciled unchanged`),a.pendingWindow=e;for(let e of t){safeInteger(e.bytes),ct.ok(e.bytes>0);let t=a.reservations[e.key];t===void 0?a.reservations[e.key]={bytes:e.bytes,confirmed:!1,sha256:e.sha256}:(ct.ok(t.bytes<=e.bytes,`Backup reservation cannot be silently exceeded`),t.sha256!==void 0&&e.sha256!==void 0&&ct.equal(t.sha256,e.sha256,`Backup source differs from a paid reservation`))}ct.ok(chargedBytes(a)<=i,`Backup total upload ceiling does not cover the reserved window`),await this.save(a)}async withPass(e){if(this.active)throw new BackupPassOverlapError;this.active=!0;try{await this.lockVerifier();let t=await We.lstat(this.directory);return ct.ok(t.isDirectory()&&t.uid===serviceUid()&&!(t.mode&63),`Backup state must be a private service-owned directory`),await this.load(),await e()}finally{this.active=!1}}assertActive(){ct.ok(this.active,`Backup mutations require the active externally locked pass`)}async load(){let e=D.join(this.directory,`checkpoint.json`),t;try{t=await We.open(e,et.constants.O_RDONLY|et.constants.O_NOFOLLOW)}catch(e){if(e.code!==`ENOENT`)throw e;await assertFreshJournal(this.directory),this.state={manifestReceipts:[],manifestVersion:0,nextIndex:0,reservations:{},schema:`network.xyo.backup.state/1`,scope:this.scope,steps:[]},await this.save(this.state);return}try{let e=await t.stat();ct.ok(e.isFile()&&e.nlink===1&&e.uid===serviceUid()&&e.size<=67108864,`Invalid backup checkpoint file`);let i=await t.readFile(`utf8`),a=await t.stat();ct.equal(e.size,a.size),ct.equal(e.mtimeMs,a.mtimeMs),this.state=validateState(JSON.parse(i),this.scope)}finally{await t.close()}}async save(e){this.assertActive();let t=validateState(e,this.scope);await this.lockVerifier(),await writeDurableJson(D.join(this.directory,`checkpoint.json`),t),this.state=structuredClone(t)}},Ufe=[[`Backup pass source bytes exceed`,`source-bytes-limit`],[`Backup pass upload reservation exceeds`,`pass-upload-limit`],[`Backup total upload ceiling`,`upload-ceiling`],[`Backup pass deadline reached`,`deadline`],[`Auto Drive available upload bytes`,`account-credits`],[`Auto Drive account does not match`,`account-mismatch`],[`Auto Drive account lookup failed`,`account-lookup`],[`Archive content checksum fails`,`archive-readback`],[`Archive readback CID changed`,`archive-readback`],[`Archive object has no CID`,`archive-readback`],[`Archive manifest`,`archive-conflict`],[`Published archive`,`archive-conflict`],[`Published manifest`,`archive-conflict`]],Wfe=/* @__PURE__ */ new Set([`AssertError`,`AssertionError`,`Error`,`TypeError`]);function safeDetail(e){if(typeof e!=`object`||!e)return``;let{$metadata:t,cause:i,code:a,message:u,name:p}=e;if(typeof t?.httpStatusCode==`number`)return` HTTP ${t.httpStatusCode}`;let y=typeof u==`string`?/^Head request failed \[(\d{3})\]$/.exec(u)?.[1]:void 0;if(y!==void 0)return` HTTP ${y}`;let x=i?.code??a;return typeof x==`string`&&/^[A-Z][A-Z0-9_]{1,40}$/.test(x)?` ${x}`:typeof p==`string`&&/^[A-Za-z][A-Za-z0-9]{1,40}$/.test(p)&&!Wfe.has(p)?` ${p}`:``}function backupStopReason(e){if(e instanceof ArchiveOutcomeUnknownError)return`unknown-upload`;if(e instanceof BackupArchiveAdvancedError)return`archive-advanced`;if(e instanceof BackupSourceConflictError)return`source-conflict`;if(e instanceof BackupPassOverlapError)return`overlap`;if(e instanceof MirrorVerificationError)return`source-verification block ${e.block}`;if(e instanceof Error){if(e.name===`AbortError`||e.name===`TimeoutError`)return`aborted`;let t=Ufe.find(([t])=>e.message.startsWith(t));if(t!==void 0){let i=/ with HTTP (\d{3})$/.exec(e.message)?.[1];return i===void 0?t[1]:`${t[1]} HTTP ${i}`}}return`${backupPassStage(e)??`unexpected`}${safeDetail(e)}`}async function readBackupCredential(e){let t=await We.open(e,et.constants.O_RDONLY|et.constants.O_NOFOLLOW);try{let i=await t.stat();if(!i.isFile()||i.nlink!==1||i.mode&63||i.uid!==(typeof process.getuid==`function`?process.getuid():-1)||i.size<1||i.size>4096)throw Error(`Backup credential must be a small owner-only regular file`);let a=Buffer.alloc(4097),{bytesRead:u}=await t.read(a,0,a.length,0),p=await t.stat(),y=await We.lstat(e);if(u!==i.size||p.size!==i.size||p.mtimeMs!==i.mtimeMs||p.mode!==i.mode||p.nlink!==1||y.dev!==i.dev||y.ino!==i.ino)throw Error(`Backup credential changed during its bounded read`);let x=a.subarray(0,u).toString(`utf8`).trim();if(!/^[\u{21}-\u{7E}]+$/u.test(x))throw Error(`Backup credential must contain one raw API key`);return x}finally{await t.close()}}var Gfe={maxAttempts:3,retryAfterMs:3e5},BackupActor=class extends ChainActor{_activePass;_apiKey;_blockViewer;_chainStateViewer;_client;_indexViewer;_passAbort;_state;_store;async createHandler(){await super.createHandler(),this._blockViewer=await this.locator.getInstance(Hz),this._chainStateViewer=await this.locator.getInstance(Yz),this._indexViewer=await this.locator.getInstance(tB);let{config:e}=this.params;this._state=new BackupStateStore(e.stateDirectory,{accountId:e.expectedAccountId??`dry-run`,bucket:e.bucket??`dry-run`,chainId:e.expectedChainId,endpoint:u5,expectedGenesisHash:e.expectedGenesisHash,network:e.network},e.lockFd),await this._state.initialize(),e.dryRun||(this._apiKey=await readBackupCredential(e.credentialFile),this._client=createAutoDriveS3Client(this._apiKey),this._store=new S3ArchiveObjectStore({bucket:e.bucket,client:this._client,contentEncoding:`br`,journal:this._state.createJournal(e.maxTotalUploadBytes),retry:Gfe,signal:()=>this._passAbort?.signal}))}async startHandler(){await super.startHandler(),this.registerTimer(`BackupActor`,async()=>{this._activePass=this.runBackupPass();try{await this._activePass}finally{this._activePass=void 0}},2e3,this.params.config.syncInterval)}async stopHandler(){this.requestCancellation(),this._passAbort?.abort();try{await this._activePass,await super.stopHandler()}finally{this._client?.destroy(),this._client=void 0,this._store=void 0,this._apiKey=void 0}}async runBackupPass(){let{config:e}=this.params;this._passAbort=new AbortController;let t=AbortSignal.any([this.signal,this._passAbort.signal,AbortSignal.timeout(e.passBudgetMs)]),timerAbort=()=>this._passAbort?.abort();t.addEventListener(`abort`,timerAbort,{once:!0});try{let i=await backupPass({blockByHash:async e=>await this._blockViewer.blockByHash(e),checkAccount:this._apiKey===void 0?void 0:async i=>{assertAutoDriveUploadBudget(await readAutoDriveAccount(this._apiKey,async(e,i)=>await fetch(e,{...i,signal:AbortSignal.any([t,i?.signal??t])})),e.expectedAccountId,i)},index:this._indexViewer,reader:this._blockViewer,source:this._chainStateViewer,state:this._state,store:this._store},{...e,deadline:Date.now()+e.passBudgetMs,signal:t});for(let t of i.reconstructedSteps??[])this.logger.warn(`BackupActor: ${e.network} step ${t.index} rebuilt from canonical blocks; its published index rollup fails verification at block ${t.rejectedBlock}`);this.logger.info(`BackupActor: ${e.network} ${i.status}; steps ${i.preparedSteps}; next ${i.nextIndex}; reserved bytes ${i.chargedBytes}; manifest CID ${i.manifestCid??`none`}`)}catch(e){this.signal.aborted||this.logger.warn(`BackupActor: pass stopped (${backupStopReason(e)}); inspect the private durable state before changing limits or retrying an unknown upload`)}finally{t.removeEventListener(`abort`,timerAbort),this._passAbort=void 0}}};r5(BackupActor,`dependencies`,[Hz,Yz,tB]),BackupActor=n5([creatable()],BackupActor);var p5=(/* @__PURE__ */ number$4()).check(int$1(),/* @__PURE__ */ _positive(),/* @__PURE__ */ _lte(2**53-1)),Kfe=(/* @__PURE__ */ number$4()).check(int$1(),/* @__PURE__ */ _nonnegative(),/* @__PURE__ */ _lte(2**53-1)),m5=(/* @__PURE__ */ string$3()).check(/* @__PURE__ */ _regex(/^\//),/* @__PURE__ */ _minLength(2)),h5=(/* @__PURE__ */ extend(SZ,{bucket:/* @__PURE__ */ optional$2((/* @__PURE__ */ string$3()).check(/* @__PURE__ */ _minLength(1))),credentialFile:/* @__PURE__ */ optional$2(m5),dryRun:/* @__PURE__ */ _default$1(/* @__PURE__ */ boolean$2(),!0),expectedAccountId:/* @__PURE__ */ optional$2((/* @__PURE__ */ string$3()).check(/* @__PURE__ */ _minLength(1))),expectedChainId:(/* @__PURE__ */ string$3()).check(/* @__PURE__ */ _regex(/^[0-9a-f]{40}$/)),expectedGenesisHash:/* @__PURE__ */ optional$2((/* @__PURE__ */ string$3()).check(/* @__PURE__ */ _regex(/^[0-9a-f]{64}$/))),lockFd:/* @__PURE__ */ _default$1(p5,9),manifestReserveBytes:/* @__PURE__ */ _default$1(p5,2097152),maxPassBytes:/* @__PURE__ */ _default$1(p5,67108864),maxStepsPerPass:/* @__PURE__ */ _default$1(p5,1),maxTotalUploadBytes:/* @__PURE__ */ _default$1(Kfe,0),network:/* @__PURE__ */ _enum$1([`mainnet`,`sequence`]),passBudgetMs:/* @__PURE__ */ _default$1(p5,3e4),stateDirectory:m5,syncInterval:/* @__PURE__ */ _default$1(p5,6e4)})).check(/* @__PURE__ */ refine$2(e=>e.dryRun||e.maxTotalUploadBytes>0&&e.bucket!==void 0&&e.expectedAccountId!==void 0&&e.credentialFile!==void 0,{message:`Paid backup requires an explicit account, bucket, credential file, and positive total upload ceiling`})),qfe=zodToFactory(h5,`toBackupConfig`),g5={mainnet:{chainId:`319e667ced10452a117472811130444ded357f26`,genesisHash:`f72abf65c6c8acbf5a83b4bb998096fa912c21ced056421eda0dbeafb6f5d764`},sequence:{chainId:`4b43a753c8024c0e5000e8ac948ac0063ac624bc`,genesisHash:`d248370d5ec3054d07221b5d128a842a27f15e2cb7cdb123de4cf5b8a12df74a`}};function validateBackupSourceBindings(e,t){let i=g5[e.network];if(e.expectedChainId!==i.chainId||e.expectedGenesisHash!==void 0&&e.expectedGenesisHash!==i.genesisHash)throw Error(`Backup network, current contract, and genesis identity disagree`);for(let[i,a]of Object.entries({BlockViewer:`blocks`,ChainStateViewer:`state`,IndexViewer:`indexes`})){let u=t.providerBindings?.[i],p=u?.connection===void 0?void 0:t.connections?.[u.connection];if(p?.type!==`rest`||p.baseUrl.replace(/\/$/,``)!==`https://${a}.${e.network}.xyo.space`)throw Error(`Backup ${i} must bind to the selected network's canonical public REST endpoint`)}}var Jfe={configParser:h5,create:async({actor:e,locator:t,process:i,wallet:a})=>{let u=qfe({...e,...process.env.XL1_BACKUP_CREDENTIAL_FILE===void 0?{}:{credentialFile:process.env.XL1_BACKUP_CREDENTIAL_FILE}},!0);return validateBackupSourceBindings(u,i),await BackupActor.create({account:a,config:{...u,expectedGenesisHash:g5[u.network].genesisHash},locator:t})},defaultAccountPath:`9`,dependencies:[`BlockViewer`,`ChainStateViewer`,`IndexViewer`],name:`backup`},_5=(/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _multipleOf(1),/* @__PURE__ */ _positive()),v5=/* @__PURE__ */ extend(SZ,{concurrency:/* @__PURE__ */ _default$1(_5,16),contentEncoding:/* @__PURE__ */ _default$1(/* @__PURE__ */ _enum$1([`br`,`gzip`,`none`]),`br`),syncInterval:/* @__PURE__ */ _default$1(_5,5e3),targetChainStateConnection:/* @__PURE__ */ _default$1(/* @__PURE__ */ string$3(),`s3-mirror-chain-state`),targetFinalizedConnection:/* @__PURE__ */ _default$1(/* @__PURE__ */ string$3(),`s3-mirror-finalized`),windowSize:/* @__PURE__ */ _default$1(_5,211)}),Yfe=zodToFactory(v5,`toMirrorConfig`),RestChainStateSource=class{baseUrl;constructor(e){this.baseUrl=e.replace(/\/+$/,``)}async readObject(e){let t=await fetch(`${this.baseUrl}/${e}`,{signal:AbortSignal.timeout(6e4)});if(t.status!==404){if(!t.ok)throw Error(`GET ${this.baseUrl}/${e} failed with HTTP ${t.status}`);return await t.json()}}};async function copyChainContracts(e,t,i){let a=[],u=i;for(;u!=null&&!a.includes(u);){let i=chainContractByIdPath(u),p=await e.readObject(i);if(!GB(p))break;await t.hasObject(i)||await t.writeObject(i,JSON.stringify(p),G8),a.push(u),u=p.forkedChainId}return a}async function copyChainParams(e,t,i){let a=chainParamsHeadPath(i),u=await e.readObject(a);if(!lV(u))return;let p=await t.readObject(a);if(lV(p)&&p.version===u.version&&p.hash===u.hash)return u.version;let y=chainParamsVersionPath(i,u.version);if(!await t.hasObject(y)){let a=await e.readObject(y);if(!Gs(a))return;let p=await al.dataHash(a);if(p!==u.hash)throw Error(`Register v${u.version} for ${i} hashes to ${p}, but its head names ${u.hash}`);await t.writeObject(y,JSON.stringify(a),G8)}return await t.writeObject(a,JSON.stringify(u),K8),u.version}var MirrorSourceError=class extends Error{constructor(e){super(e),this.name=`MirrorSourceError`}};function assertHeadAgreement(e,t){if(e!==void 0&&t!==void 0&&t.block===e[0].block&&t.hash!==e[0]._hash)throw new MirrorVerificationError(t.block,`the mirror head conflicts with the pinned source head`)}async function readMirrorHead(e){let t=await e.readObject(headPath());if(t===void 0)return;let i=Array.isArray(t)?t[0]:void 0;if(typeof i?.block!=`number`||typeof i._hash!=`string`)throw TypeError(`The mirror's ${headPath()} is not a hydrated block; refusing to guess where to resume`);return{block:i.block,hash:i._hash}}function windowEnd(e,t){return(Math.floor(e/t)+1)*t-1}async function forEachConcurrently(e,t,i){let a=0,worker=async()=>{for(;a<e.length;){let t=a;a+=1,await i(e[t])}};await Promise.all(Array.from({length:Math.min(t,e.length)},worker))}async function readWindow(e,t,i){let a=i-t+1,u=await e.blocksByNumber(rP(i,!0),a);if(u.length!==a)throw new MirrorSourceError(`The source returned ${u.length} of the ${a} blocks in [${t}..${i}]`);return u.toSorted((e,t)=>e[0].block-t[0].block)}function withoutStorageCursor(e){let t={...e};return delete t._sequence,t}async function writeBlock(e,t){let i=[withoutStorageCursor(t[0]),t[1].map(withoutStorageCursor)];await Promise.all(i[1].map(async t=>await e.writeObject(payloadPath(t._hash),JSON.stringify(t),G8)));let a=JSON.stringify(i);await e.writeObject(blockHashPath(i[0]._hash),a,G8),await e.writeObject(blockNumberPath(i[0].block),a,G8)}async function copyWindow(e,t,i){let{chainState:a,finalized:u,reader:p}=e,{from:y,to:x}=t,w=await readWindow(p,y,x),E=t.previous;for(let[e,i]of w.entries())await verifyHydratedBlock(i,{block:y+e,hash:y+e===x?t.hash:void 0,previous:E}),E=i[0]._hash;await forEachConcurrently(w,i,async e=>await writeBlock(u,e));let D=assertEx$1(w.at(-1),()=>`Window [${y}..${x}] is empty`);return await a.writeObject(headPath(),JSON.stringify(D),K8),D[0]._hash}async function mirrorPass(e,t){let{concurrency:i,contentEncoding:a,deadline:u,onWindow:p,signal:y,windowSize:x}=t,[w,E]=await Promise.all([e.source.tryCurrentBlock(),readMirrorHead(e.chainState)]),D=w?.[0].chain,A=E?.block,N=w?.[0].block;if(assertHeadAgreement(w,E),N===void 0||A!==void 0&&A>=N)return{chainId:D,localHead:A,mirrored:0,sourceHead:N};await e.finalized.writeObject(manifestPath(),JSON.stringify(createChainManifest(a)),q8);let P=E===void 0?0:E.block+1,F=E===void 0?null:E.hash,I=0,L=0;for(;P<=N&&!(y?.aborted===!0||I>0&&u!==void 0&&Date.now()+L>=u);){let t=Date.now(),a=Math.min(N,windowEnd(P,x));F=await copyWindow(e,{from:P,hash:a===N?w?.[0]._hash:void 0,previous:F,to:a},i),I+=a-P+1,A=a,p?.([rP(P,!0),rP(a,!0)]),P=a+1,L=Date.now()-t}return{chainId:D,localHead:A,mirrored:I,sourceHead:N}}var Xfe=6e5,Zfe=.9,MirrorActor=class extends ChainActor{_blockViewer;_chainStateViewer;_blocksMirroredCounter;_chainStateCopiedAt;_lagGauge;_localHeadGauge;_sourceHeadGauge;_verificationFailureCounter;async createHandler(){await super.createHandler(),this._blockViewer=await this.locator.getInstance(Hz),this._chainStateViewer=await this.locator.getInstance(Yz),this._blocksMirroredCounter=this.counter(`mirror_actor_blocks_mirrored`,`Blocks verified and written to the mirror`),this._verificationFailureCounter=this.counter(`mirror_actor_verification_failures`,`Passes stopped because a source block failed verification`),this._localHeadGauge=this.gauge(`mirror_actor_local_head`,`Height of the mirror's head`),this._sourceHeadGauge=this.gauge(`mirror_actor_source_head`,`Height of the source head the mirror follows`),this._lagGauge=this.gauge(`mirror_actor_lag_blocks`,`Blocks the mirror is behind the source head`)}async startHandler(){await super.startHandler(),this.registerTimer(`MirrorActor`,async()=>{let e=await this.runMirrorPass();await this.copyChainStateIfDue(e.chainId)},2e3,this.params.config.syncInterval)}async copyChainStateIfDue(e){let t=this.params.chainStateSource;if(t!==void 0&&e!==void 0&&!(this._chainStateCopiedAt!==void 0&&Date.now()-this._chainStateCopiedAt<Xfe))try{let i=this.params.targets.chainState,a=await copyChainContracts(t,i,e),u=await copyChainParams(t,i,e);this._chainStateCopiedAt=Date.now(),this.logger.info(`MirrorActor: chain state copied (contracts: ${a.join(`, `)||`none`}; register: ${u===void 0?`none`:`v${u}`})`)}catch(e){this.logger.warn(`MirrorActor: chain state copy failed; will retry next pass: ${e.message}`)}}recordHeads(e){let{localHead:t,sourceHead:i}=e;t!==void 0&&this._localHeadGauge?.record(t),i!==void 0&&this._sourceHeadGauge?.record(i),i!==void 0&&this._lagGauge?.record(Math.max(0,i-(t??-1)))}async runMirrorPass(){let{config:e,targets:t}=this.params;return await this.spanAsync(`mirrorPass`,async()=>{try{let i=await mirrorPass({chainState:t.chainState,finalized:t.finalized,reader:this._blockViewer,source:this._chainStateViewer},{concurrency:e.concurrency,contentEncoding:e.contentEncoding,deadline:Date.now()+e.syncInterval*Zfe,onWindow:([e,t])=>this._blocksMirroredCounter?.add(t-e+1),signal:this.signal,windowSize:e.windowSize});return this.recordHeads(i),i.mirrored>0&&this.logger.info(`MirrorActor: mirrored ${i.mirrored} blocks; head ${i.localHead} of ${i.sourceHead}`),i}catch(e){throw e instanceof MirrorVerificationError&&this._verificationFailureCounter?.add(1),e}},this.context)}};r5(MirrorActor,`dependencies`,[Hz,Yz]),MirrorActor=n5([creatable()],MirrorActor);function isNotFoundError(e){if(typeof e!=`object`||!e)return!1;let{name:t,$metadata:i}=e;return t===`NoSuchKey`||t===`NotFound`||i?.httpStatusCode===404}var MirrorObjectConflictError=class extends Error{constructor(e){super(`Immutable mirror object conflicts at ${e}`),this.name=`MirrorObjectConflictError`}};function isPreconditionFailed(e){if(typeof e!=`object`||!e)return!1;let{name:t,$metadata:i}=e;return t===`PreconditionFailed`||i?.httpStatusCode===412}var y5=class _S3MirrorObjectStore{bucket;client;contentEncoding;prefix;constructor(e){this.bucket=e.bucket,this.client=e.client,this.contentEncoding=e.contentEncoding,this.prefix=e.prefix??``}static fromConnection(e,t){return new _S3MirrorObjectStore({bucket:assertEx$1(e.bucket,()=>`The mirror's s3 connections need a bucket`),client:s3ClientForConnection(e),contentEncoding:t,prefix:e.prefix})}async hasObject(e){try{return await this.client.send(new Ze({Bucket:this.bucket,Key:this.key(e)})),!0}catch(e){if(isNotFoundError(e))return!1;throw e}}async readObject(e){let t=await this.readJson(e);return t===void 0?void 0:JSON.parse(t)}async writeObject(e,t,i){let{body:a,contentEncoding:u}=encodeBody(t,this.contentEncoding),p=i===G8;try{await this.client.send(new Qe({Body:a,Bucket:this.bucket,CacheControl:i,ContentEncoding:u,ContentType:`application/json`,IfNoneMatch:p?`*`:void 0,Key:this.key(e)}))}catch(i){if(!p||!isPreconditionFailed(i))throw i;if(await this.readJson(e)!==t)throw new MirrorObjectConflictError(e)}}key(e){return`${this.prefix}${e}`}async readJson(e){try{let t=await this.client.send(new Xe({Bucket:this.bucket,Key:this.key(e)})),i=await t.Body?.transformToByteArray();return i===void 0?void 0:decodeBody(i,t.ContentEncoding)}catch(e){if(isNotFoundError(e))return;throw e}}};function requireS3Connection(e,t){let i=e.connections?.[t];if(i?.type!==`s3`){let e=i===void 0?`no such connection`:`a "${i.type}" connection`;throw Error(`The mirror target "${t}" must be an "s3" connection, but found ${e}`)}return i}function restChainStateSource(e){let t=e.providerBindings?.ChainStateViewer?.connection,i=t===void 0?void 0:e.connections?.[t];return i?.type===`rest`?new RestChainStateSource(i.baseUrl):void 0}var Qfe={configParser:v5,create:async({actor:e,locator:t,process:i,wallet:a})=>{let u=Yfe(e,!0);return await MirrorActor.create({account:a,chainStateSource:restChainStateSource(i),config:u,locator:t,targets:{chainState:y5.fromConnection(requireS3Connection(i,u.targetChainStateConnection),u.contentEncoding),finalized:y5.fromConnection(requireS3Connection(i,u.targetFinalizedConnection),u.contentEncoding)}})},defaultAccountPath:`8`,dependencies:[`BlockViewer`,`ChainStateViewer`],name:`mirror`};_Z(),Uo(),za(),Ha();var b5=Object.defineProperty,$fe=Object.getOwnPropertyDescriptor,epe=/* @__PURE__ */ __name((e,t,i)=>t in e?b5(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,`__defNormalProp`),tpe=/* @__PURE__ */ __name((e,t,i,a)=>{for(var u=a>1?void 0:a?$fe(t,i):t,p=e.length-1,y;p>=0;p--)(y=e[p])&&(u=(a?y(t,i,u):y(u))||u);return a&&u&&b5(t,i,u),u},`__decorateClass`),x5=/* @__PURE__ */ __name((e,t,i)=>epe(e,typeof t==`symbol`?t:t+``,i),`__publicField`);function producerBlockRunnerDescriptor(){return providerCandidateFromClass(SimpleBlockRunner,`SimpleBlockRunner`)}var S5=1e4,C5=/* @__PURE__ */ extend(SZ,{allowlist:(/* @__PURE__ */ optional$2(/* @__PURE__ */ array$2(ao))).register(Ji,{description:`List of allowed producer addresses, if undefined anyone can participate`,title:`allowlist`,type:`array`}),blockProductionCheckInterval:(/* @__PURE__ */ _default$1(/* @__PURE__ */ number$4(),S5)).register(Ji,{description:`The interval time (in milliseconds) between block production attempts`,title:`producer.blockProductionCheckInterval`,type:`number`}),disableIntentRedeclaration:(/* @__PURE__ */ optional$2(/* @__PURE__ */ boolean$2())).register(Ji,{description:`Should the producer skip redeclaring their intent to continue producing blocks`,title:`producer.disableIntentRedeclaration`,type:`boolean`}),heartbeatInterval:(/* @__PURE__ */ _default$1(/* @__PURE__ */ number$4(),o8)).register(Ji,{description:`The number of milliseconds between heartbeats if no blocks are produced`,title:`producer.heartbeatInterval`,type:`number`}),minStake:(/* @__PURE__ */ _default$1(/* @__PURE__ */ number$4(),1)).register(Ji,{description:`Minimum stake required to be a Producer`,title:`producer.minStake`,type:`number`}),rewardAddress:(/* @__PURE__ */ optional$2(/* @__PURE__ */ string$3())).register(Ji,{description:`Address to receive block rewards`,title:`producer.rewardAddress`,type:`string`})}),npe=zodToFactory(C5,`toProducerConfig`),w5=`xl1ProducerStats`,rpe=[`blockProduction`,`blockRewardTransfers`,`headFetch`,`mempoolPendingBlocksFetch`,`mempoolPendingTransactionsFetch`,`mempoolSubmitBlock`,`productionCycle`,`timePayloadGeneration`],ipe=256;function emptyCounts(){return{actorStarts:0,blockProductionAttempts:0,blockProductionChecks:0,blocksProduced:0,blocksPublished:0,candidateRecoveries:0,concurrentChecksSkipped:0,failedChecks:0,idleAttempts:0,rejectedPublishes:0}}function emptyTiming(){return{count:0,recentSamples:[],totalMs:0}}function emptyTimings(){return{blockProduction:emptyTiming(),blockRewardTransfers:emptyTiming(),headFetch:emptyTiming(),mempoolPendingBlocksFetch:emptyTiming(),mempoolPendingTransactionsFetch:emptyTiming(),mempoolSubmitBlock:emptyTiming(),productionCycle:emptyTiming(),timePayloadGeneration:emptyTiming()}}function percentile(e,t){return e.length===0?null:e[Math.ceil(e.length*t)-1]??null}function durationSnapshot(e){let t=e.recentSamples.toSorted((e,t)=>e-t);return{count:e.count,lastMs:e.lastMs??null,maxMs:e.maxMs??null,meanMs:e.count===0?null:e.totalMs/e.count,minMs:e.minMs??null,p50Ms:percentile(t,.5),p95Ms:percentile(t,.95),recentSampleCount:t.length,totalMs:e.totalMs}}var ProducerStats=class{actorStartedAt;collectedSince=Date.now();counts=emptyCounts();lastPublishedBlock;timings=emptyTimings();increment(e){this.counts[e]++}markActorStarted(e=Date.now()){this.actorStartedAt=e,this.increment(`actorStarts`)}recordPublishedBlock(e,t,i,a=Date.now()){let u=new Date(a);this.lastPublishedBlock={block:e,hash:t,payloadCount:i,publishedAt:u.toISOString()}}recordTiming(e,t){if(!Number.isFinite(t)||t<0)return;let i=this.timings[e];i.count++,i.lastMs=t,i.maxMs=Math.max(i.maxMs??t,t),i.minMs=Math.min(i.minMs??t,t),i.totalMs+=t,i.recentSamples.push(t),i.recentSamples.length>ipe&&i.recentSamples.shift()}snapshot(e=Date.now()){let t=Object.fromEntries(rpe.map(e=>[e,durationSnapshot(this.timings[e])])),i=this.actorStartedAt===void 0?void 0:new Date(this.actorStartedAt),a=new Date(this.collectedSince),u=new Date(e);return{actor:`producer`,actorStartedAt:i?.toISOString()??null,actorUptimeMs:this.actorStartedAt===void 0?null:Math.max(0,e-this.actorStartedAt),collectedSince:a.toISOString(),counts:{...this.counts},generatedAt:u.toISOString(),lastPublishedBlock:this.lastPublishedBlock??null,timings:t}}async time(e,t){let i=Date.now();try{return await t()}finally{this.recordTiming(e,Date.now()-i)}}};function getOrCreateProducerStats(e){let t=e.singletons[w5];if(t instanceof ProducerStats)return registerSimpleBlockRunnerInstrumentation(e,t),t;let i=new ProducerStats;return e.singletons[w5]=i,registerSimpleBlockRunnerInstrumentation(e,i),i}var ape=!0,T5=6e5,toFormattedBlockReference=e=>`${e.block} [${toHex(e._hash,{prefix:!0})}]`,ProducerActor=class extends ChainActor{_lastProducedBlock;_lastRedeclarationIntent;_metricAttributes;_producerActorBlockProductionAttempts;_producerActorBlockProductionChecks;_producerActorBlocksProduced;_producerActorBlocksPublished;_accountBalanceViewer;_blockRunner;_blockViewer;_chainContractViewer;_chainId;_fastCandidateRecoveriesForHead=0;_lastCandidateGoneCheckTime=0;_lastHeadChangeTime;_lastHeadHash;_mempoolRunner;_mempoolViewer;_produceBlockMutex=new Mutex;_stakeTotalsViewer;_stats;get logger(){return assertEx$1(super.logger,()=>`Logger is required for ProducerActor`)}get accountBalanceViewer(){return this._accountBalanceViewer}get blockProductionCheckInterval(){return this.config.blockProductionCheckInterval??ProducerActor.DefaultBlockProductionCheckInterval}get blockRunner(){return this._blockRunner}get blockViewer(){return this._blockViewer}get chainContractViewer(){return this._chainContractViewer}get chainId(){return this._chainId}get config(){return this.params.config}get headResubmissionThreshold(){return ProducerActor.HeadResubmissionThresholdMs}get mempoolRunner(){return this._mempoolRunner}get mempoolViewer(){return this._mempoolViewer}get stakeTotalsViewer(){return this._stakeTotalsViewer}get stats(){return this._stats??=getOrCreateProducerStats(this.context)}async createHandler(){await super.createHandler(),this._metricAttributes={address:this.account.address},this._producerActorBlockProductionChecks=this.counter(`producer_actor_block_production_checks`,`Number of block production checks`),this._producerActorBlockProductionAttempts=this.counter(`producer_actor_block_production_attempts`,`Number of block production attempts`),this._producerActorBlocksProduced=this.counter(`producer_actor_blocks_produced`,`Number of blocks produced`),this._producerActorBlocksPublished=this.counter(`producer_actor_blocks_published`,`Number of blocks published`),await(await this.locator?.getInstance(eB)).start(),this._accountBalanceViewer=assertEx$1(await this.locator?.getInstance(DL),()=>`Unable to locate AccountBalanceViewer`),this._blockRunner=assertEx$1(await this.locator?.getInstance(rz),()=>`Unable to locate BlockRunner`),this._blockViewer=assertEx$1(await this.locator?.getInstance(Hz),()=>`Unable to locate BlockViewer`),this._chainContractViewer=assertEx$1(await this.locator?.getInstance(qz),()=>`Unable to locate ChainContractViewer`),this._mempoolRunner=assertEx$1(await this.locator?.getInstance(fz),()=>`Unable to locate MempoolRunner`),this._mempoolViewer=assertEx$1(await this.locator?.getInstance(iB),()=>`Unable to locate MempoolViewer`),this._stakeTotalsViewer=assertEx$1(await this.locator?.getInstance(_B),()=>`Unable to locate StakeTotalsViewer`),this._chainId=await this.chainContractViewer.chainId()}async startHandler(){await super.startHandler(),this.stats.markActorStarted(),this._produceBlockMutex=new Mutex,this._lastProducedBlock=void 0,this._lastHeadHash=void 0,this._lastHeadChangeTime=void 0,this._fastCandidateRecoveriesForHead=0,this._lastCandidateGoneCheckTime=0,this.registerTimer(`BlockProductionTimer`,async()=>{await this.produceBlock()},2e3,this.blockProductionCheckInterval),ape&&this.registerTimer(`ProducerRedeclarationTimer`,async()=>{await this.redeclareIntent()},T5,T5)}calculateBlocksUntilProducerDeclarationExpiration(e){return(this._lastRedeclarationIntent?.exp??e)-e}async lastCandidateDropped(e){let t=this._lastProducedBlock;if(isUndefined$1(t)||this._fastCandidateRecoveriesForHead>=ProducerActor.MaxFastCandidateRecoveriesPerHead||e-this._lastCandidateGoneCheckTime<ProducerActor.CandidateGoneCheckIntervalMs)return!1;this._lastCandidateGoneCheckTime=e;let i=await this.stats.time(`mempoolPendingBlocksFetch`,async()=>await this.mempoolViewer.pendingBlocks());return i.every(e=>e[0]._hash!==t[0]._hash)&&i.length<ProducerActor.CandidateGoneScanLimit}async produceBlock(){this._producerActorBlockProductionChecks.add(1,this._metricAttributes),this.stats.increment(`blockProductionChecks`);try{await this.spanAsync(`produceBlock`,async()=>{this._produceBlockMutex.isLocked()?(this.stats.increment(`concurrentChecksSkipped`),this.logger?.debug(`Skipping block production, previous production still in progress`)):await this.stats.time(`productionCycle`,async()=>await this._produceBlockMutex.runExclusive(()=>this.produceBlockExclusive()))},{...this.context,timeBudgetLimit:1e3})}catch(e){throw this.stats.increment(`failedChecks`),e}}async readyHandler(){await this.produceBlock()}async redeclareIntent(){await this.spanAsync(`redeclareIntent`,async()=>{if(this.config.disableIntentRedeclaration===!0)return;let[e]=await this.blockViewer.currentBlock();if(isUndefined$1(e))return;let t=e.block;if(this.calculateBlocksUntilProducerDeclarationExpiration(t)>ProducerActor.RedeclarationWindow*.1){this._lastRedeclarationIntent=void 0;return}if(this._lastRedeclarationIntent){if(this._lastRedeclarationIntent.exp>t)return;this._lastRedeclarationIntent=void 0}if(!await this.validateCurrentBalance()){this.logger?.error(`Add balance to address ${this.account.address} for the producer to declare it's intent.`);return}if(!await this.validateCurrentStake()){this.logger?.error(`Add stake to contract address ${this.chainId} for the producer to declare it's intent.`);return}this.logger?.log(`Creating redeclaration intent for producer:`,this.account.address);let i=createDeclarationIntent(toAddress(this.account.address),`producer`,t,t+SimpleBlockRunner.RedeclarationDuration);await this.submitRedeclarationIntent(t,i),this._lastRedeclarationIntent=i},{...this.context,timeBudgetLimit:1e3})}async submitRedeclarationIntent(e,t){this.logger?.log(`Submitting redeclaration intent for producer:`,this.account.address);let i=await buildTransaction(this.chainId,[t],[],this.account,e,rP(e+1e3,!0));await this.mempoolRunner.submitTransactions([i]),this.logger?.log(`Submitted redeclaration intent for producer:`,this.account.address)}async validateCurrentBalance(){let e=(await this.blockViewer.currentBlock())?.[0]?._hash;if(isDefined$1(e)){let t=toAddress(this.account.address);return((await this.accountBalanceViewer.accountBalances([t],{head:e}))[t]??0n)<=0n?(this.logger?.error(`Producer ${this.account.address} has no balance.`),!1):!0}return!0}async validateCurrentStake(){return await this.stakeTotalsViewer.activeByStaked(toAddress(this.account.address))<1n?(this.logger?.error(`Producer ${this.account.address} has insufficient stake.`),!1):!0}async produceBlockExclusive(){let[e]=await this.stats.time(`headFetch`,async()=>await this.blockViewer.currentBlock()),t=e._hash,i=Date.now();this.recordHeadChange(t,i);let a=isDefined$1(this._lastHeadChangeTime)?i-this._lastHeadChangeTime:0,u=this._lastProducedBlock?.[0].previous!==t,p=a>this.headResubmissionThreshold,y=!u&&!p&&await this.lastCandidateDropped(i);u||p||y?(p&&(this.logger?.log(`Resubmitting block due to stale head. Head ${toFormattedBlockReference(e)} unchanged for ${a}ms`),this._lastHeadChangeTime=i),y&&this.recoverDroppedCandidate(),await this.publishNextBlock(e,i)):this.logger?.debug(`No block submission required at this time.`)}async publishNextBlock(e,t){this._producerActorBlockProductionAttempts.add(1,this._metricAttributes),this.stats.increment(`blockProductionAttempts`);let i=await this.stats.time(`blockProduction`,async()=>await this.blockRunner.produceNextBlock(e));if(!i){this.stats.increment(`idleAttempts`),this.logger?.log(`No block produced for submission.`);return}let a=toFormattedBlockReference(i[0]);this.logger?.log(`Produced block:`,a),this._producerActorBlocksProduced.add(1,this._metricAttributes),this.stats.increment(`blocksProduced`),(await this.stats.time(`mempoolSubmitBlock`,async()=>await this.mempoolRunner.submitBlocks([i]))).length===0?(this.stats.increment(`rejectedPublishes`),this.logger?.error(`Submit dropped block ${a} silently \u2014 archivist accepted 0 of 1 (hash ${i[0]._hash})`)):(this.logger?.log(`Published block:`,a),this._producerActorBlocksPublished.add(1,this._metricAttributes),this.stats.increment(`blocksPublished`),this.stats.recordPublishedBlock(i[0].block,i[0]._hash,i[1].length),this._lastProducedBlock=i,this._lastCandidateGoneCheckTime=t)}recordHeadChange(e,t){if(this._lastHeadHash===e)return;let i=isDefined$1(this._lastHeadHash)?`0x${this._lastHeadHash}`:`undefined`;this.logger?.log(`Found updated head ${i} -> 0x${e}`),this._lastHeadHash=e,this._lastHeadChangeTime=t,this._fastCandidateRecoveriesForHead=0}recoverDroppedCandidate(){let e=this._lastProducedBlock;isUndefined$1(e)||(this._fastCandidateRecoveriesForHead+=1,this.stats.increment(`candidateRecoveries`),this.logger?.warn(`Last produced candidate ${toFormattedBlockReference(e[0])} is no longer pending (pruned or rejected); resuming production (recovery ${this._fastCandidateRecoveriesForHead}/${ProducerActor.MaxFastCandidateRecoveriesPerHead} for this head)`),this._lastProducedBlock=void 0)}};x5(ProducerActor,`CandidateGoneCheckIntervalMs`,1e3),x5(ProducerActor,`CandidateGoneScanLimit`,100),x5(ProducerActor,`DefaultBlockProductionCheckInterval`,S5),x5(ProducerActor,`HeadResubmissionThresholdMs`,3e4),x5(ProducerActor,`MaxFastCandidateRecoveriesPerHead`,3),x5(ProducerActor,`RedeclarationWindow`,1e3),x5(ProducerActor,`dependencies`,[DL,rz,Hz,qz,eB,fz,iB,_B]),ProducerActor=tpe([creatable()],ProducerActor);var ope={bootExtras:({configuration:e,signingWallets:t})=>t.producer===void 0?[]:(C5.parse(getActorSliceFromRun(e,`producer`)),[producerBlockRunnerDescriptor()]),configParser:C5,create:async e=>await ProducerActor.create({account:e.wallet,config:npe(e.actor),locator:e.locator,name:`xl1-producer`}),defaultAccountPath:`0`,dependencies:[`AccountBalanceViewer`,`BlockRunner`,`BlockViewer`,`ChainContractViewer`,`FinalizationViewer`,`MempoolRunner`,`MempoolViewer`,`StakeTotalsViewer`],name:`producer`,optionalProviderRoots:[`DeadLetterQueueRunner`,`EvmChainViewer`],signerMoniker:rz};Uo(),WD(),za(),nD(),Cs(`network.xyo.module.mongodb.config`,!0);var E5={"network.xyo.storage.class":`mongodb`};Uo();var D5=Object.defineProperty,spe=Object.getOwnPropertyDescriptor,cpe=/* @__PURE__ */ __name((e,t,i)=>t in e?D5(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,`__defNormalProp`),O5=/* @__PURE__ */ __name((e,t,i,a)=>{for(var u=a>1?void 0:a?spe(t,i):t,p=e.length-1,y;p>=0;p--)(y=e[p])&&(u=(a?y(t,i,u):y(u))||u);return a&&u&&D5(t,i,u),u},`__decorateClass`),k5=/* @__PURE__ */ __name((e,t,i)=>cpe(e,typeof t==`symbol`?t:t+``,i),`__publicField`),A5={AddressInfo:`address_info`,ArchivistStats:`archivist_stats`,BoundWitnesses:`bound_witnesses`,Payloads:`payloads`,Thumbnails:`thumbnails`,Users:`users`},getMongoDBConfig=()=>{let e={},t=process.env.MONGO_CONNECTION_STRING;t!==void 0&&t!==``&&(e.MONGO_CONNECTION_STRING=t);let i=process.env.MONGO_DOMAIN;return i!==void 0&&i!==``&&(e.MONGO_DATABASE=process.env.MONGO_DATABASE,e.MONGO_DOMAIN=i,e.MONGO_PASSWORD=process.env.MONGO_PASSWORD,e.MONGO_USERNAME=process.env.MONGO_USERNAME),e},getBaseMongoSdkPrivateConfig=()=>{let e=getMongoDBConfig();return{dbConnectionString:e.MONGO_CONNECTION_STRING,dbDomain:assertEx$1(e.MONGO_DOMAIN,()=>`Missing Mongo Domain`),dbName:assertEx$1(e.MONGO_DATABASE,()=>`Missing Mongo Database`),dbPassword:assertEx$1(e.MONGO_PASSWORD,()=>`Missing Mongo Password`),dbUserName:assertEx$1(e.MONGO_USERNAME,()=>`Missing Mongo Username`)}};function isObject(e){return typeof e==`object`&&!!e}function merge(e,...t){if(!isObject(e))throw TypeError(`Target must be an object`);for(let i of t)if(isObject(i))for(let[t,a]of Object.entries(i)){let i=e[t];Array.isArray(a)?e[t]=[...a]:isObject(a)?(isObject(i)||(e[t]={}),merge(e[t],a)):e[t]=a}return e}var j5=[{name:`IX__hash`,key:{_hash:1},unique:!1},{name:`IX__dataHash`,key:{_dataHash:1},unique:!1},{name:`IX__sequence`,key:{_sequence:1},unique:!1}],MongoDBModuleMixin=e=>{let MongoModuleBase=class extends e{_boundWitnessSdk;_payloadSdk;get boundWitnessSdkConfig(){return merge({collection:A5.BoundWitnesses,...getBaseMongoSdkPrivateConfig()},this.params.boundWitnessSdkConfig,this.config.boundWitnessSdkConfig,{collection:this.config.boundWitnessSdkConfig?.collection??this.params.boundWitnessSdkConfig?.collection??A5.BoundWitnesses})}get boundWitnesses(){return this._boundWitnessSdk??=new BaseMongoSdk(this.boundWitnessSdkConfig),assertEx$1(this._boundWitnessSdk)}get jobQueue(){return assertEx$1(this.params.jobQueue,()=>`MongoDBModule Error: jobQueue required for this module but is not defined`)}get payloadSdkConfig(){return merge({collection:A5.Payloads,...getBaseMongoSdkPrivateConfig()},this.params.payloadSdkConfig,this.config.payloadSdkConfig,{collection:this.config.payloadSdkConfig?.collection??this.params.payloadSdkConfig?.collection??A5.Payloads})}get payloads(){return this._payloadSdk??=new BaseMongoSdk(this.payloadSdkConfig),assertEx$1(this._payloadSdk)}async ensureIndexes(){let e=this.config?.storage?.indexes??[],t=this.boundWitnessSdkConfig.collection,i=this.payloadSdkConfig.collection,a=j5.map(e=>({...e,name:`${t}.${e.name}`}));await ensureIndexesExistOnCollection(this.boundWitnesses,[...a,...e]);let u=j5.map(e=>({...e,name:`${i}.${e.name}`}));await ensureIndexesExistOnCollection(this.payloads,[...u,...e])}};return k5(MongoModuleBase,`labels`,E5),MongoModuleBase=O5([staticImplements()],MongoModuleBase),MongoModuleBase},ensureIndexesExistOnCollection=async(e,t)=>{await e.useCollection(async e=>{let i=e.collectionName.toLowerCase(),a=t.filter(e=>e?.name?.toLowerCase().startsWith(i)??!1);if(a.length!==0)for(let t of a)try{await e.createIndexes([t])}catch(e){let{codeName:a}=e;if(a===`IndexKeySpecsConflict`||a===`IndexOptionsConflict`)continue;throw console.error(`Error creating index ${t.name} for collection ${i}: ${String(e)}`),e}})},lpe=[{name:`UX__hash`,key:{_hash:1},unique:!0},{name:`IX__dataHash`,key:{_dataHash:1},unique:!1},{name:`UX__sequence`,key:{_sequence:1},unique:!0}],MongoDBModuleMixinV2=e=>{let MongoModuleBase=class extends e{_payloadSdk;get jobQueue(){return assertEx$1(this.params.jobQueue,()=>`MongoDBModule Error: jobQueue required for this module but is not defined`)}get payloadSdkConfig(){let e={collection:A5.Payloads},t=this.params.payloadSdkConfig,i=this.config.payloadSdkConfig;return isDefined$1(t)||isDefined$1(i)?merge(e,i??{},t??{}):merge(e,getBaseMongoSdkPrivateConfig())}get payloads(){return this._payloadSdk??=new BaseMongoSdk(this.payloadSdkConfig),assertEx$1(this._payloadSdk)}async ensureCollection(){let{max:e}=this.config,t=this.payloadSdkConfig.collection,i=lpe.map(e=>({...e,name:`${t}.${e.name}`}));isDefined$1(e)&&await ensureCappedCollection(this.payloads,e),await ensureIndexesExistOnCollection2(this.payloads,[...i])}};return k5(MongoModuleBase,`labels`,E5),MongoModuleBase=O5([staticImplements()],MongoModuleBase),MongoModuleBase},collectionExists=async(e,t)=>(await e.listCollections({name:t}).toArray()).length>0,ensureIndexesExistOnCollection2=async(e,t)=>{await e.useCollection(async e=>{let i=e.collectionName.toLowerCase(),a=t.filter(e=>e?.name?.toLowerCase().startsWith(i)??!1);if(a.length!==0)for(let t of a)try{await e.createIndexes([t])}catch(e){let{codeName:a=``}=e;if([`IndexKeySpecsConflict`,`IndexOptionsConflict`,`Unauthorized`].includes(a))continue;throw console.error(`Error creating index ${t.name} for collection ${i}: ${String(e)}`),e}})},ensureCappedCollection=async(e,t,i=1024)=>{await e.useCollection(async a=>{let u=a.collectionName.toLowerCase();await e.useMongo(async p=>{let y=p.db(a.dbName),x=await collectionExists(y,u),w=i*t;return x?await ensureExistingCollectionIsCapped(e,t,w):await y.createCollection(u,{capped:!0,size:w,max:t})})})},ensureExistingCollectionIsCapped=async(e,t,i=1024)=>{await e.useCollection(async a=>{let u=a.collectionName.toLowerCase();await e.useMongo(async e=>{let p=e.db(a.dbName);if(!await collectionExists(p,u))throw Error(`Collection '${u}' does not exist`);let y=i*t,x=await p.command({collStats:u});if(x.capped===!0&&x.max===t&&x.maxSize===y)return;let w=`${u}_tmp_capped`;await p.createCollection(w,{capped:!0,size:y,max:t});let E=await a.find().sort({$natural:-1}).limit(t).toArray();E.length>0&&await p.collection(w).insertMany(E.toReversed()),await a.drop(),await p.collection(w).rename(u)})})};nD();function payloadFromDbRepresentation(e){let t=structuredClone(e),i={};for(let[e,a]of Object.entries(t))e.startsWith(`_$`)?i[e.slice(1)]=a:e!==`_id`&&(i[e]=a);return Hs(al.omitPrivateStorageMeta(i),!0)}function boundWitnessFromDbRepresentation(e){return payloadFromDbRepresentation(e)}function fromDbRepresentation(e){return vw(e)?boundWitnessFromDbRepresentation(e):payloadFromDbRepresentation(e)}var payloadToDbRepresentation=e=>{let t=structuredClone(e),i={};for(let[e,a]of Object.entries(t))e.startsWith(`$`)?i[`_${e}`]=a:i[e]=a;return i},boundWitnessToDbRepresentation=e=>payloadToDbRepresentation(e),toDbRepresentation=e=>vw(e)?boundWitnessToDbRepresentation(e):payloadToDbRepresentation(e);Uo(),qO(),sO(),nD(),HO();var validByType=async(e=[])=>{let t=[[],[]];return await Promise.all(e.map(async e=>{if(vw(e)){let i=(Ew(e)?Pw:Nw).parse(e);if(await i.getValid())t[0].push(e);else{let e=await i.getErrors();console.log(`validByType.Error: ${JSON.stringify(e,null,2)}`)}}else await PayloadWrapper.wrap(e).getValid()&&t[1].push(e)})),t},M5=Cs(`network.xyo.archivist.mongodb.config`,!0),upe=MongoDBModuleMixin(KO),MongoDBArchivist=class extends upe{static configSchemas=[...super.configSchemas,M5];static defaultConfigSchema=M5;queries=[QD,$D,...super.queries];aggregateTimeoutMs=1e4;async findOneByHash(e){return await this.payloads.findOne({_$hash:e})||await this.boundWitnesses.findOne({_$hash:e})||await this.payloads.findOne({_hash:e})||(await this.boundWitnesses.findOne({_hash:e})??void 0)}async findOneBySequence(e){return await this.payloads.findOne({_sequence:e})||await this.boundWitnesses.findOne({_sequence:e})}async getHandler(e){let t=[...e],i=(await Promise.all(t.map(e=>this.payloads.findOne({_dataHash:e})))).filter(eo),a=new Set(i.map(e=>e._dataHash)),u=t.filter(e=>!a.has(e)),p=(await Promise.all(u.map(e=>this.boundWitnesses.findOne({_dataHash:e})))).filter(eo),y=new Set(p.map(e=>e._dataHash)),x=u.filter(e=>!y.has(e)),w=(await Promise.all(x.map(e=>this.payloads.findOne({_hash:e})))).filter(eo),E=new Set(w.map(e=>e._hash)),D=x.filter(e=>!E.has(e)),A=(await Promise.all(D.map(e=>this.boundWitnesses.findOne({_hash:e})))).filter(eo);return[...i,...p,...w,...A].map(fromDbRepresentation)}async insertHandler(e){let[t,i]=await validByType(e),a=i.map(e=>toDbRepresentation(e));if(a.length>0){let e=await this.payloads.insertMany(a);if(!e.acknowledged||e.insertedCount!==a.length)throw Error(`MongoDBArchivist: Error inserting Payloads`)}let u=t.map(e=>toDbRepresentation(e));if(u.length>0){let e=await this.boundWitnesses.insertMany(u);if(!e.acknowledged||e.insertedCount!==u.length)throw Error(`MongoDBArchivist: Error inserting BoundWitnesses`)}return[...u,...a].map(fromDbRepresentation)}async nextHandler(e){let{limit:t,order:i}=e??{limit:10,order:`desc`},{cursor:a,open:u}=e??{limit:10,order:`desc`};t??=10,t>100&&(t=100),i!=`asc`&&(i=`desc`);let p;if(a){let e=await this.findOneBySequence(a);e&&(p=e._id)}else p=Re.createFromTime(i===`asc`?0:(Date.now()+1e4)/1e3);if(!p)return[];let y=i===`asc`?1:-1,x=i===`asc`?{_id:u===!0?{$gte:p}:{$gt:p}}:{_id:u===!0?{$lte:p}:{$lt:p}};return(await this.payloads.useCollection(e=>e.aggregate([{$match:x},{$sort:{_id:y}},{$limit:t},{$unionWith:{coll:this.boundWitnessSdkConfig.collection,pipeline:[{$match:x},{$sort:{_id:y}},{$limit:t}]}},{$sort:{_id:y}},{$limit:t}]).maxTimeMS(this.aggregateTimeoutMs).toArray())).map(fromDbRepresentation)}async startHandler(){await super.startHandler(),await this.ensureIndexes()}},dpe=MongoDBModuleMixinV2(KO),fpe=11e3,MongoDBArchivistV2=class extends dpe{static configSchemas=[...super.configSchemas,M5];static defaultConfigSchema=M5;queries=[QD,$D,...super.queries];aggregateTimeoutMs=1e4;async deleteHandler(e){let t=await this.getHandler(e),i=t.map(e=>e._hash);return await this.payloads.deleteMany({_hash:{$in:i}}),t}async findOneByHash(e){let t=await this.payloads.findOne({_$hash:e});if(t)return t;let i=await this.payloads.findOne({_hash:e});if(i)return i}async findOneBySequence(e){let t=await this.payloads.findOne({_sequence:e});if(t)return t}async getHandler(e){let t=[...e],i=(await Promise.all(t.map(e=>this.payloads.findOne({_dataHash:e})))).filter(eo),a=new Set(i.map(e=>e._dataHash)),u=t.filter(e=>!a.has(e)),p=(await Promise.all(u.map(e=>this.payloads.findOne({_hash:e})))).filter(eo);return[...i,...p].map(fromDbRepresentation)}async insertHandler(e){let t=e.map(e=>toDbRepresentation(e));if(t.length>0)try{if(!(await this.payloads.insertMany(t,{ordered:!1})).acknowledged)throw Error(`MongoDBArchivist: Error inserting Payloads`)}catch(e){if(e?.code!=fpe)throw e}return[...t].map(fromDbRepresentation)}async nextHandler(e){let{limit:t,order:i}=e??{limit:10,order:`desc`},{cursor:a,open:u=!0}=e??{limit:10,order:`desc`};t??=10,t>100&&(t=100),i!=`asc`&&(i=`desc`);let p;if(a){let e=await this.findOneBySequence(a);e&&(p=e._sequence)}else p=i===`asc`?ks.minLocalSequence:ks.maxLocalSequence;if(!p)return[];let y=i===`asc`?1:-1,x=i===`asc`?{_sequence:u?{$gt:p}:{$gte:p}}:{_sequence:u?{$lt:p}:{$lte:p}};return(await this.payloads.useCollection(e=>e.aggregate([{$match:x},{$sort:{_sequence:y}},{$limit:t}]).maxTimeMS(this.aggregateTimeoutMs).toArray())).map(fromDbRepresentation)}async startHandler(){await super.startHandler(),await this.ensureCollection()}},MongoDBArchivistV2Deletable=class extends MongoDBArchivistV2{queries=[XD,ZD,QD,$D,...zO]};Uo(),_Z(),za(),hM(),pk(),Ha();var N5=Object.defineProperty,ppe=Object.getOwnPropertyDescriptor,mpe=/* @__PURE__ */ __name((e,t,i)=>t in e?N5(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,`__defNormalProp`),hpe=/* @__PURE__ */ __name((e,t,i,a)=>{for(var u=a>1?void 0:a?ppe(t,i):t,p=e.length-1,y;p>=0;p--)(y=e[p])&&(u=(a?y(t,i,u):y(u))||u);return a&&u&&N5(t,i,u),u},`__decorateClass`),gpe=/* @__PURE__ */ __name((e,t,i)=>mpe(e,typeof t==`symbol`?t:t+``,i),`__publicField`),P5=/* @__PURE__ */ extend(CZ,{}),_pe=zodToFactory(P5,`toRewardRedemptionConfig`),vpe=N2.ReasonPhrases.OK,handler=(e,t)=>{setRawResponseFormat(t),t.status(200).send({message:vpe})},ype=handler,bpe=N2.ReasonPhrases.OK,handler2=(e,t)=>{setRawResponseFormat(t),t.status(200).send({message:bpe})},xpe=handler2,Spe=N2.ReasonPhrases.OK,handler3=(e,t)=>{setRawResponseFormat(t),t.status(200).send({message:Spe})},Cpe=handler3,addProbeRoutes=e=>{e.get(`/livez`,ype),e.get(`/readyz`,xpe),e.get(`/startupz`,Cpe)},resolveArchivist=async(e,t)=>{let i=await e.resolve(t);return rO(i,{required:!0})},F5,getArchivist=async(e,t)=>(isDefined$1(F5)||(F5=await resolveArchivist(e,t)),F5),archivistMiddleware=e=>{let{node:t,archivistModuleIdentifier:i}=e,a=M2.Router({mergeParams:!0});return a.post(`/insert`,async(e,a)=>{await spanAsync(`reward-redemption:data-lake:insert`,async()=>{setRawResponseFormat(a);let u=(Array.isArray(e.body)?e.body:[e.body]).filter(e=>Gs(e)),p=(await al.hashPairs(u)).map(([e])=>e),y=await(await getArchivist(t,i)).insert(p);a.status(200).json(y)},{timeBudgetLimit:2e3})}),a.get(`/next`,async(e,a)=>{await spanAsync(`reward-redemption:data-lake:next-get`,async()=>{setRawResponseFormat(a);let u=isSequence(e.query.cursor)?e.query.cursor:void 0,p={limit:isDefined$1(e.query.limit)?Number(e.query.limit):void 0,open:isDefined$1(e.query.open)?!!e.query.open:void 0,order:e.query.order===`asc`?`asc`:`desc`,cursor:u},y=await(await getArchivist(t,i)).next(p);a.status(200).json(y)},{timeBudgetLimit:2e3})}),a.post(`/next`,async(e,a)=>{await spanAsync(`reward-redemption:data-lake:next-post`,async()=>{setRawResponseFormat(a);let u=e.body,p=await getArchivist(t,i),y=await(isDefined$1(u)?p.next(u):p.next());a.status(200).json(y)},{timeBudgetLimit:2e3})}),a.get(`/get/:hash`,async(e,a)=>{await spanAsync(`reward-redemption:data-lake:get`,async()=>{setRawResponseFormat(a);let{hash:u}=e.params,p=asHash(u);if(isDefined$1(p)){let[e]=await(await getArchivist(t,i)).get([p]);if(Gs(e)){a.json(e);return}a.status(404).send()}else a.status(400).send()},{timeBudgetLimit:2e3})}),a},addDataLakeRoutes=e=>{let{node:t}=e;e.use(`/data`,archivistMiddleware({node:t,archivistModuleIdentifier:`Data`}))},I5=[3,4,5,6,7,8],wpe=Math.min(...I5),Tpe=Math.max(...I5),Epe=/* @__PURE__ */ object$5({fromBlock:/* @__PURE__ */ optional$2((/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _multipleOf(1),/* @__PURE__ */ _nonnegative())),toBlock:/* @__PURE__ */ optional$2((/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _multipleOf(1),/* @__PURE__ */ _nonnegative())),step:/* @__PURE__ */ _default$1((/* @__PURE__ */ number$4()).check(/* @__PURE__ */ _multipleOf(1),/* @__PURE__ */ _nonnegative(),/* @__PURE__ */ _gte(wpe),/* @__PURE__ */ _lte(Tpe)),3)}),Dpe=requestHandlerValidator({response:/* @__PURE__ */ array$2(Js)}),getChainStepRewardsClaimSentinel=async e=>{let t=await e.resolve(`XYORewardRedemptionNode:ChainStepRewardsClaimSentinel`);return assertEx$1(iA(t),()=>`ChainStepRewardsClaimSentinel not found on node`)},Ope={method:`post`,path:`/rewards/claimRange`,handlers:Dpe(async(e,t)=>{await spanAsync(`reward-redemption:claim-range`,async()=>{let{locator:i,node:a}=e.app,{fromBlock:u,toBlock:p,step:y}=hn(Epe,e.query),x=await i.getInstance(EB),w=isDefined$1(u)?u:0,E=await x.currentBlockNumber(),D=isDefined$1(p)?Math.min(p,E):E;if(D<=w){t.status(400),t.json([]);return}let A=blockRangeSteps(yL([w,D],{name:`claimRange`}),[y]),N=[];for(let e of A){let t=await getChainStepRewardsClaimSentinel(a),i=new al({schema:mI}).fields(e).build(),u=await t.report([i]);N.push(...u)}t.status(200),t.json(N)},{timeBudgetLimit:5e3})})},kpe=requestHandlerValidator({body:/* @__PURE__ */ tuple$1([/* @__PURE__ */ extend(PayloadZodStrictOfSchema(_W),gW.shape),/* @__PURE__ */ extend(PayloadZodStrictOfSchema(xW),bW.shape)]),response:/* @__PURE__ */ array$2(Js)}),getDerivedAddressWalletTransferSentinel=async e=>{let t=await e.resolve(`XYORewardRedemptionNode:DerivedAddressWalletTransferSentinel`);return assertEx$1(iA(t),()=>`DerivedAddressWalletTransferSentinel not found on node`)},Ape={method:`post`,path:`/rewards/redeem`,handlers:kpe(async(e,t)=>{await spanAsync(`reward-redemption:redeem`,async()=>{let{node:i}=e.app,{body:a}=e,u=await(await getDerivedAddressWalletTransferSentinel(i)).report(a);t.status(200),t.json(u)},{timeBudgetLimit:2e3})})},getRouteDefinitions=()=>[Ope,Ape],addRewardRedemptionRoutes=e=>{addRouteDefinitions(e,getRouteDefinitions())},addRoutes=e=>{addProbeRoutes(e),addDataLakeRoutes(e),addRewardRedemptionRoutes(e)},getApp=(e,t,i)=>{let a=(0,M2.default)();return sharedMiddleware(a,{telemetry:httpTelemetryConfig(t)}),a.config=t,a.node=e,a.locator=i,addRoutes(a),a.use(standardErrors),a},L5=Cs(`network.xyo.sentinel.chain.step.rewards.claim.config`,!0),jpe=15e3,Mpe=100,Npe=36e5,Ppe=`reward-escrow`,Fpe=[3,4,5,6,7,8],StepClaimSubmissionError=class extends Error{exp;constructor(e,t){super(`Rewards claim submission was inconclusive through expiration block ${e}`,{cause:t}),this.name=`StepClaimSubmissionError`,this.exp=e}};function stepIdentityKey(e){return`${e.step}|${e.block}`}function sortStepIdentities(e){return[...e].toSorted((e,t)=>e.block===t.block?e.step-t.step:e.block-t.block)}function chunks(e,t){return Array.from({length:Math.ceil(e.length/t)},(i,a)=>e.slice(a*t,(a+1)*t))}var ChainStepRewardsClaimSentinel=class extends AbstractSentinel{static configSchemas=[L5];static defaultConfigSchema=L5;_claimAttemptsCounter;_claimCheckCounter;_claimErrorCounter;_claimSuccessCounter;_connection;_gateway;_inFlightClaims=/* @__PURE__ */ new Map;_lastFullReconciliationEpoch;_lastScannedBoundaryByStep=/* @__PURE__ */ new Map;_pendingClaims=/* @__PURE__ */ new Map;_reportMutex=new Mutex;_viewer;get balanceBatchSize(){return Math.max(1,Math.floor(this.config.balanceBatchSize??Mpe))}get connection(){return assertEx$1(this._connection,()=>`Connection is not defined`)}get fullReconciliationIntervalMs(){return Math.max(0,this.config.fullReconciliationIntervalMs??Npe)}get gateway(){return assertEx$1(this._gateway,()=>`Gateway is not defined`)}get rewardableSteps(){return isDefined$1(this.config.rewardableSteps)?this.config.rewardableSteps:Fpe}get stepClaimIntervalMs(){return Math.max(0,this.config.stepClaimIntervalMs??jpe)}get viewer(){return assertEx$1(this._viewer,()=>`Viewer is not defined`)}async createHandler(){await super.createHandler(),this._claimAttemptsCounter=this.meter?.createCounter(`chain_step_rewards_claim_sentinel_attempts_total`,{description:`Number of claim attempts`}),this._claimCheckCounter=this.meter?.createCounter(`chain_step_rewards_claim_sentinel_check_total`,{description:`Number of claim checks`}),this._claimSuccessCounter=this.meter?.createCounter(`chain_step_rewards_claim_sentinel_success_total`,{description:`Number of claim successes`}),this._claimErrorCounter=this.meter?.createCounter(`chain_step_rewards_claim_sentinel_errors_total`,{description:`Number of claim errors`});let e=assertEx$1(this.params.gateway,()=>`Gateway parameter is required`),t=assertEx$1(e.connection,()=>`Gateway connection is required`),i=assertEx$1(t.viewer,()=>`Viewer is not defined in gateway connection`);this._gateway=e,this._connection=t,this._viewer=i}async reportHandler(e){return this._reportMutex.isLocked()?(this.logger?.debug(`ChainRewardsClaimSentinel [${this.id}] is already running, skipping report [${Date.now()}]`),[]):await this._reportMutex.runExclusive(async()=>{let t=[];if(isUndefined$1(e)||e.length===0)await this.claimAllSteps();else{let i=e.filter(gI).map(e=>{let{step:t,block:i}=e;return{step:t,block:rP(i,{name:`reportHandler`})}}).filter(e=>this.rewardableSteps.includes(e.step));for(let e of i)this.queuePendingClaim(e);let a=await this.processPendingClaims(new Set(i.map(stepIdentityKey)));t.push(...flattenHydratedTransactions(a))}return t})}calculateAddressDistributions(e,t){let i={},a=Object.values(e).reduce((e,t)=>e+t,0n);for(let[u,p]of Object.entries(e)){if(p<=0n)continue;let e=t*p/a;if(e<=0n)continue;let y=derivedReceiveAddress(toAddress(u),Ppe);i[y]=e}let u=Object.values(i).reduce((e,t)=>e+t,0n);assertEx$1(u<=t,()=>`Total claimed exceeds claimable balance`);let p=t-u;return p>0n&&(i[AL]=p),i}async claimAllSteps(){let e=await this.viewer.finalization.headNumber();await this.reconcileInFlightClaims(e);let t=this.shouldRunFullReconciliation();return await this.refreshPendingClaims(e,t),flattenHydratedTransactions(await this.processPendingClaims())}async claimStepIdentity(e){this.logger?.info(`Checking rewards to claim for step ${e.step} at block ${e.block}`);let t={step:e.step.toString(),block:e.block.toString()};this._claimCheckCounter?.add(1,t);let i=rewardAddressFromStepIdentity(e),a=await this.viewer.account.balance.accountBalance(i);if(this.logger?.info(`Found balance of ${a} to claim for step ${e.step} at block ${e.block} in step reward address ${i}`),!(a>0n))return;this._claimAttemptsCounter?.add(1,t);let u=await this.viewer.networkStakeStepRewardPoolRewards(e),p=Object.keys(u).length;this.logger?.info(`Found ${p} reward recipients for step ${e.step} at block ${e.block}`),this.config.claimEmptySteps!==!0&&assertEx$1(p>0,()=>`No reward recipients for step`);let y=this.calculateAddressDistributions(u,a);this.logger?.info(`Calculated address distributions for step ${e.step} at block ${e.block} with ${Object.keys(y).length} addresses`);let x=await this.submitRewardDistributionTransaction(i,y,e,this.gateway);return this.logger?.info(`Submitted rewards claim for step ${e.step} at block ${e.block}`),this._claimSuccessCounter?.add(1,t),x}completedStepIdentities(e,t){let i=[];for(let a of this.rewardableSteps){let u=t?0:this._lastScannedBoundaryByStep.get(a)??0,p=yL([u,e],{name:`completedStepIdentities`});i.push(...blockRangeSteps(p,[a]).filter(e=>e.block>u))}return sortStepIdentities(i)}async processPendingClaims(e){let t=sortStepIdentities(this._pendingClaims.values()).filter(t=>{let i=stepIdentityKey(t);return!this._inFlightClaims.has(i)&&(e===void 0||e.has(i))}),i=[];for(let[e,a]of t.entries()){let u=stepIdentityKey(a),p={step:a.step.toString(),block:a.block.toString()};try{let e=await this.claimStepIdentity(a);isDefined$1(e)?(this._inFlightClaims.set(u,{exp:e.exp,stepIdentity:a,transactionHash:e.transactionHash}),i.push(e.transaction)):this._pendingClaims.delete(u)}catch(e){e instanceof StepClaimSubmissionError&&this._inFlightClaims.set(u,{exp:e.exp,stepIdentity:a}),this._claimErrorCounter?.add(1,p),this.logger?.error(`Error claiming rewards for step ${a.step} at block ${a.block}:`,e)}e<t.length-1&&this.stepClaimIntervalMs>0&&await Oo(this.stepClaimIntervalMs)}return i}queuePendingClaim(e){this._pendingClaims.set(stepIdentityKey(e),e)}async reconcileInFlightClaims(e){for(let[t,i]of this._inFlightClaims){let a=!1;if(isDefined$1(i.transactionHash))try{isDefinedNotNull(await this.viewer.transaction.byHash(i.transactionHash))&&(a=!0)}catch(e){this.logger?.error(`Error resolving in-flight rewards transaction for step ${i.stepIdentity.step} at block ${i.stepIdentity.block}:`,e)}if(a&&this.logger?.info(`Found submitted rewards claim for step ${i.stepIdentity.step} at block ${i.stepIdentity.block} on chain`),!(e<i.exp))try{let a=rewardAddressFromStepIdentity(i.stepIdentity),u=await this.viewer.account.balance.accountBalance(a,{range:yL([0,e],{name:`reconcileInFlightClaims`})});this._inFlightClaims.delete(t),u===0n?(this._pendingClaims.delete(t),this.logger?.info(`Rewards claim settled for step ${i.stepIdentity.step} at block ${i.stepIdentity.block} even though its submitted transaction was not resolved by hash`)):this.logger?.warn(`Rewards claim expired with balance ${u} still funded for step ${i.stepIdentity.step} at block ${i.stepIdentity.block}; retaining it for retry`)}catch(e){this.logger?.error(`Error resolving finalized reward balance for in-flight step ${i.stepIdentity.step} at block ${i.stepIdentity.block}:`,e)}}}async refreshPendingClaims(e,t){let i=this.completedStepIdentities(e,t),a={};for(let t of chunks(i,this.balanceBatchSize)){let i=t.map(rewardAddressFromStepIdentity);Object.assign(a,await this.viewer.account.balance.accountBalances(i,{range:yL([0,e],{name:`refreshPendingClaims`})}))}let u=0;for(let e of i){let t=stepIdentityKey(e),i=a[rewardAddressFromStepIdentity(e)]??0n;this._claimCheckCounter?.add(1,{step:e.step.toString(),block:e.block.toString()}),i>0n?(u+=1,this.queuePendingClaim(e)):this._inFlightClaims.has(t)||this._pendingClaims.delete(t);let p=this._lastScannedBoundaryByStep.get(e.step)??0;e.block>p&&this._lastScannedBoundaryByStep.set(e.step,e.block)}t&&(this._lastFullReconciliationEpoch=Date.now()),this.logger?.info(`${t?`Full`:`Incremental`} finalized reward scan checked ${i.length} step identities through block ${e} and found ${u} funded`)}shouldRunFullReconciliation(){return this._lastFullReconciliationEpoch===void 0||Date.now()-this._lastFullReconciliationEpoch>=this.fullReconciliationIntervalMs}async submitRewardDistributionTransaction(e,t,i,a){let u=createTransferPayload(e,t);u.context={step:i};let p=await this.viewer.currentBlockNumber(),y=rP(p+10,!0),x;try{x=assertEx$1(await a.addPayloadsToChain?.([u],[],{nbf:p,exp:y}),()=>`Gateway did not return a submitted rewards transaction`)}catch(e){throw new StepClaimSubmissionError(y,e)}return{exp:y,transaction:x[1],transactionHash:x[0]}}},R5=Cs(`network.xyo.sentinel.chain.derived.address.wallet.transfer.config`,!0),z5=`reward-escrow`,Ipe=/* @__PURE__ */ object$5({From:uo,"To XL1 Address":ao,"XL1 Amount":/* @__PURE__ */ string$3(),"XL1 Amount (Hex)":so,"XL1 Not after block":tP,"XL1 Not before block":tP}),parseConfirmedClaimValues=e=>({amount:e[`XL1 Amount (Hex)`],exp:e[`XL1 Not after block`],from:toAddress(e.From),nbf:e[`XL1 Not before block`],to:toAddress(e[`To XL1 Address`])}),DerivedAddressWalletTransferSentinel=class extends AbstractSentinel{static configSchemas=[R5];static defaultConfigSchema=R5;_transferAttemptsCounter;_transferErrorCounter;_transferSuccessCounter;get gateway(){return this.params.gateway}async createHandler(){await super.createHandler(),this._transferAttemptsCounter=this.meter?.createCounter(`derived_address_wallet_transfer_sentinel_attempts_total`,{description:`Number of transfer attempts`}),this._transferSuccessCounter=this.meter?.createCounter(`derived_address_wallet_transfer_sentinel_success_total`,{description:`Number of transfer successes`}),this._transferErrorCounter=this.meter?.createCounter(`derived_address_wallet_transfer_sentinel_errors_total`,{description:`Number of transfer errors`})}async reportHandler(e){let t=e?.find(e=>yW(e)),i=e?.find(e=>CW(e));if(isUndefined$1(t)||isUndefined$1(i))return[];if(this._transferAttemptsCounter?.add(1),!await verifyEIP712Message(t,i))throw this._transferErrorCounter?.add(1),Error(`Invalid EIP712 signature`);let a=parseConfirmedClaimValues(Ipe.parse(t.values));if(toAddress(i.address)===toAddress(a.from)){let e=await this.submitRewardDistributionTransaction(a);if(isDefined$1(e))return this._transferSuccessCounter?.add(1),flattenHydratedTransaction(e)}return this._transferErrorCounter?.add(1),[]}submitRewardDistributionTransaction=async e=>{let{amount:t,from:i,to:a,nbf:u,exp:p}=e,y=await assertEx$1(this.gateway.signer,()=>`Signer is not defined in gateway`).address(),x=assertEx$1(this.gateway.connection.viewer,()=>`Viewer is not defined in gateway connection`),w=await x.currentBlockNumber();if(w<u||w>p)throw Error(`Transaction is not within a valid block range`);let E=derivedReceiveAddress(i,z5);assertEx$1(await x.account.balance.accountBalance(E)===hexToBigInt(toHex(t)),()=>`Insufficient balance in escrow account`),assertEx$1(await x.account.balance.accountBalance(y)>1000n,()=>`Insufficient allowance to transfer from escrow account`);let D=createTransferPayload(E,{[a]:hexToBigInt(toHex(t))});D.context={address:i,scope:z5};let A=await x.chainId(),N=await this.gateway.addPayloadsToChain?.([D],[],{chain:A,nbf:u,exp:p});if(isDefined$1(N))return N[1]}},getLocator=async(e,t)=>{let{config:i,logger:a}=e,{otlpEndpoint:u}=i.telemetry?.otel??{},{path:p=`/metrics`,port:y=9467}=i.telemetry?.metrics?.scrape??{},{traceProvider:x,meterProvider:w}=initTelemetry({attributes:{serviceName:`xl1-reward-redemption`,serviceVersion:`1.0.0`},otlpEndpoint:u,metricsConfig:{endpoint:p,port:y}});isDefined$1(a)&&(BO.defaultLogger=a);let E=a?new LoggerModuleStatusReporter(a):void 0,D=new sM,A=resolveMongoConnection(i);if(isDefined$1(A)){let{connectionString:e,database:t,domain:i,password:a,username:u}=A,p={meterProvider:w,payloadSdkConfig:{dbConnectionString:e,dbDomain:i,dbName:t,dbPassword:a,dbUserName:u},statusReporter:E,traceProvider:x};D.register(MongoDBArchivistV2.factory(p),void 0,!0)}D.register(MemoryArchivist.factory({traceProvider:x,meterProvider:w,statusReporter:E})),D.register(MemorySentinel.factory({traceProvider:x,meterProvider:w,statusReporter:E})),D.register(ViewArchivist.factory({traceProvider:x,meterProvider:w,statusReporter:E}));let N={gateway:t,traceProvider:x,meterProvider:w,statusReporter:E};D.register(ChainStepRewardsClaimSentinel.factory(N));let P={gateway:t,traceProvider:x,meterProvider:w,statusReporter:E};return D.register(DerivedAddressWalletTransferSentinel.factory(P)),D},Lpe={$schema:`https://raw.githubusercontent.com/XYOracleNetwork/sdk-xyo-client-js/main/packages/manifest/src/schema.json`,nodes:[{config:{accountPath:`44'/60'/1`,name:`XYORewardRedemptionNode`,schema:`network.xyo.node.config`},modules:{private:[{config:{accountPath:`1/1'/1'`,name:`DataPrivate`,getCache:{enabled:!0,maxEntries:5e3},payloadSdkConfig:{collection:`reward_redemption_api_datalake`},schema:`network.xyo.archivist.config`}},{config:{accountPath:`1/1'/2'`,name:`ChainStepRewardsClaimSentinel`,schema:`network.xyo.sentinel.chain.step.rewards.claim.config`}},{config:{accountPath:`1/1'/3'`,automations:[{frequency:6e4,frequencyUnits:`millis`,schema:`network.xyo.automation.interval`,type:`interval`}],name:`ChainRewardsClaimIntervalSentinel`,schema:`network.xyo.sentinel.config`,synchronous:!0,tasks:[{mod:`ChainStepRewardsClaimSentinel`,endPoint:`report`}]}},{config:{accountPath:`1/1'/4'`,name:`DerivedAddressWalletTransferSentinel`,schema:`network.xyo.sentinel.chain.derived.address.wallet.transfer.config`}}],public:[{config:{accountPath:`1/1/1`,name:`Data`,allowedQueries:[`network.xyo.query.archivist.get`,`network.xyo.query.archivist.next`],getCache:{enabled:!0,maxEntries:5e3},originArchivist:`DataPrivate`,schema:`network.xyo.archivist.view.config`}}]}}],schema:`network.xyo.manifest`},Rpe=[],zpe=[],getNode=async(e,t,i)=>{let a=await getLocator(e,t),[u,...p]=await new ManifestWrapper(Lpe,i,a,zpe,Rpe).loadNodes();return p?.length>0&&(await Promise.all(p.map(e=>u.register(e))),await Promise.all(p.map(e=>u.attach(e.address,!0)))),u},B5=`::`,getServer=async(e,t,i,a)=>{let{logger:u,config:p}=e,{port:y}=p,x=await initActorSeedPhrase(e),w=await HDWallet.fromPhrase(x),E=getApp(a??await getNode(e,t,w),p,i),D=await new Promise((e,t)=>{let i=E.listen(y,B5,()=>{u?.info(`[RewardsRedemption] Server listening at http://${B5}:${y}`),e(i)});i.once(`error`,e=>{u?.error(`[RewardsRedemption] Failed to bind HTTP server on ${B5}:${y}: ${e.message}`),t(e),(e.code===`EADDRINUSE`||e.code===`EACCES`)&&process.exit(1)})});return D.setTimeout(12e4),D},RewardRedemptionActor=class extends ChainActor{_gatewayRunner;server;get gatewayRunner(){return this._gatewayRunner}async createHandler(){await super.createHandler(),this._gatewayRunner=await this.locator.getInstance(tz)}async startHandler(){await super.startHandler(),this.stopServer(),await this.startServer()}async stopHandler(){await super.stopHandler(),this.stopServer()}async startServer(){this.server=await getServer(cae({...this.locator.context,config:hostConfigView(this.params.process,this.params.config)},!0),this._gatewayRunner,this.locator)}stopServer(){this.server?.close(),this.server=void 0}};gpe(RewardRedemptionActor,`dependencies`,[tz,EB]),RewardRedemptionActor=hpe([creatable()],RewardRedemptionActor);var Bpe={bootExtras:({signingWallets:e})=>e.rewardRedemption===void 0?[]:[gatewaySignerDescriptor()],compileExtras:({process:e})=>[xyoConnectionActorDescriptor(e,!0)],configParser:P5,create:async e=>await RewardRedemptionActor.create({account:e.wallet,config:_pe(e.actor),locator:e.locator,process:e.process}),defaultAccountPath:`2`,dependencies:[`XyoGatewayRunner`,`XyoViewer`],name:`rewardRedemption`,signerMoniker:QR};Uo(),_Z(),za(),Ha(),hM();var V5=Object.defineProperty,Vpe=Object.getOwnPropertyDescriptor,Hpe=/* @__PURE__ */ __name((e,t,i)=>t in e?V5(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,`__defNormalProp`),Upe=/* @__PURE__ */ __name((e,t,i,a)=>{for(var u=a>1?void 0:a?Vpe(t,i):t,p=e.length-1,y;p>=0;p--)(y=e[p])&&(u=(a?y(t,i,u):y(u))||u);return a&&u&&V5(t,i,u),u},`__decorateClass`),H5=/* @__PURE__ */ __name((e,t,i)=>Hpe(e,typeof t==`symbol`?t:t+``,i),`__publicField`),U5=1e4,Wpe=1e4,W5=/* @__PURE__ */ extend(SZ,{step:(/* @__PURE__ */ _default$1(/* @__PURE__ */ number$4(),2)).register(Ji,{description:`The step level to witness (index into StepSizes)`,title:`validator.step`,type:`number`}),stepCheckInterval:(/* @__PURE__ */ _default$1(/* @__PURE__ */ number$4(),U5)).register(Ji,{description:`The interval time (in milliseconds) between step rollover checks`,title:`validator.stepCheckInterval`,type:`number`}),offenses:(/* @__PURE__ */ _default$1(/* @__PURE__ */ array$2(aI),[...iI])).register(Ji,{description:`Offense classes to watch for; further narrowed at runtime by the parameter register`,title:`validator.offenses`,type:`array`}),maxOpenReports:(/* @__PURE__ */ _default$1(/* @__PURE__ */ number$4(),4)).register(Ji,{description:`Ceiling on reports this validator will hold open at once`,title:`validator.maxOpenReports`,type:`number`}),report:(/* @__PURE__ */ _default$1(stringbool(),!1)).register(Ji,{description:`Submit verified detections to the chain as slash reports; requires a parameter register`,title:`validator.report`,type:`boolean`}),watch:(/* @__PURE__ */ _default$1(stringbool(),!0)).register(Ji,{description:`Watch the chain for reportable offenses and record what was found as telemetry`,title:`validator.watch`,type:`boolean`}),watchInterval:(/* @__PURE__ */ _default$1(/* @__PURE__ */ number$4(),Wpe)).register(Ji,{description:`The interval time (in milliseconds) between offense watch passes`,title:`validator.watchInterval`,type:`number`})}),Gpe=zodToFactory(W5,`toValidatorConfig`);function anchorOf(e){return e[1].find(e=>RF(e))?.ethereum}function canonicalChainReader(e,t=64){let at=async t=>{try{return(await e.blocksByNumber(t,1))[0]}catch{return}};return{blockAtHeight:at,blockByHash:async t=>{try{return(await e.blocksByHash(t,1))[0]}catch{return}},finalizedHead:async()=>{try{return await e.currentBlock()}catch{return}},validatedAnchorAt:async e=>{for(let i=0;i<=t&&e>=i;i++){let t=await at(e-i);if(t===void 0)continue;let a=anchorOf(t);if(a!==void 0)return a}}}}var Kpe=512,qpe=2048,G5=25,sightingOf=e=>{let t=e.addresses[0];return t===void 0?void 0:{block:e.block,dataHash:e._dataHash,previous:e.previous,producer:t,supersedes:e.supersedes}},OffenseWatcher=class{_emitted=/* @__PURE__ */ new Set;_scannedTo;_seen=/* @__PURE__ */ new Map;params;constructor(e){this.params=e}async tick(){let e=await this.params.params();if(e===void 0)return this.params.logger?.debug(`[OffenseWatcher] no parameter register resolved; nothing is watchable`),[];let[t,i,a]=await Promise.all([this.watchEquivocation(e),this.watchInvalidBlocks(e),this.watchFinalized(e)]);return[...t,...i,...a].filter(e=>this.emitOnce(e))}async collectSightings(){let e=await this.params.mempool?.pendingBlocks()??[];for(let[t]of e){let e=sightingOf(t);e!==void 0&&(this._seen.delete(e.dataHash),this._seen.set(e.dataHash,{block:t,sighting:e}))}let t=this.params.sightingLimit??Kpe;for(;this._seen.size>t;){let e=this._seen.keys().next().value;if(e===void 0)break;this._seen.delete(e)}}emitOnce(e){let t=offenseKeyString(e.key);return!this._emitted.has(t)&&(this._emitted.size>=qpe&&this._emitted.clear(),this._emitted.add(t),!0)}async recordedPairs(){return(await this.params.evidence?.candidatePairs()??[]).filter(e=>eL(e))}async verifiedArtifacts(e){let t=new Map(await Promise.all(e.map(async e=>[await al.dataHash(e),e]))),i=await verifyArtifacts(t,Array.from(t.keys()));if(!i.ok)this.params.logger?.debug(`[OffenseWatcher] feed artifacts failed the preamble: ${i.reason}`);else return i.byHash}async verifyFinalizedAnchor(e,t){let[i,a]=t,u=i.addresses[0],p=i.previous;if(u===void 0||p===null)return;let y=await this.params.chain.blockByHash(p);if(y===void 0)return;let x=a.find(e=>RF(e))?.ethereum;if(x===void 0)return;let w={accused:u,block:i.block,chain:i.chain,offense:`false-anchor`};if(this._emitted.has(offenseKeyString(w))||await suppressionFor(this.params.history,w)!==void 0)return;let E=[i,...a.filter(e=>RF(e)),y[0],...y[1].filter(e=>RF(e))],D=await this.verifiedArtifacts(E);if(D===void 0)return;let A=await verifyFalseAnchor({catalogVersion:e.catalogVersion,chain:this.params.chain,params:e},{accused:u,block:i.block,evm:x,offense:`false-anchor`},D);return A.outcome===`verified`?{artifacts:E,key:w,offense:`false-anchor`,verdict:A}:void 0}async verifyFinalizedOvermint(e,t){let[i,a]=t,u=i.addresses[0];if(u===void 0)return;let p={accused:u,block:i.block,chain:i.chain,offense:`reward-overmint`};if(this._emitted.has(offenseKeyString(p))||await suppressionFor(this.params.history,p)!==void 0)return;let y=[i,...a],x=await this.verifiedArtifacts(y);if(x===void 0)return;let w=await verifyRewardOvermint({catalogVersion:e.catalogVersion,chain:this.params.chain,params:e},{accused:u,block:i.block,offense:`reward-overmint`},x);return w.outcome===`verified`?{artifacts:y,key:p,offense:`reward-overmint`,verdict:w}:void 0}async verifyPair(e,t,i,a){let u={accused:t,block:i,chain:a[0]?.chain,offense:`equivocation`};if(this._emitted.has(offenseKeyString(u)))return;let p=await suppressionFor(this.params.history,u);if(p!==void 0){this.params.logger?.debug(`[OffenseWatcher] skipping ${offenseKeyString(u)}: ${p}`);return}let y=await this.verifiedArtifacts(a);if(y===void 0)return;let x={accused:t,block:i,catalog:e.catalogVersion,chain:u.chain,evidence:Array.from(y.keys()),offense:`equivocation`},w=await verifyEquivocation({params:e},x,y);return w.outcome===`verified`?{artifacts:a,key:u,offense:`equivocation`,verdict:w}:void 0}async watchEquivocation(e){await this.collectSightings();let t=findCandidatePairs(Array.from(this._seen.values(),e=>e.sighting)),i=[];for(let a of t){if(!this.watchable(e,a.block).includes(`equivocation`))continue;let t=this._seen.get(a.first.dataHash),u=this._seen.get(a.second.dataHash);if(t===void 0||u===void 0)continue;let p=await this.verifyPair(e,a.producer,a.block,[t.block,u.block]);p!==void 0&&i.push(p)}for(let t of await this.recordedPairs()){if(!this.watchable(e,t.height).includes(`equivocation`))continue;let[a,u]=t.subjects,p=this._seen.get(a),y=this._seen.get(u);if(p===void 0||y===void 0){this.params.logger?.debug(`[OffenseWatcher] recorded pair at ${t.height} by ${t.producer} has no retrievable bodies`);continue}let x=await this.verifyPair(e,t.producer,t.height,[p.block,y.block]);x!==void 0&&i.push(x)}return i}async watchFinalized(e){let t=await this.params.chain.finalizedHead();if(t===void 0)return[];let i=t[0].block,a=Math.max(this._scannedTo??i-G5,0)+1,u=Math.min(i,a+G5-1),p=[];for(let y=a;y<=u;y++){let a=y===i?t:await this.params.chain.blockAtHeight(y);if(a===void 0)break;this._scannedTo=y;let u=this.watchable(e,y);if(u.includes(`reward-overmint`)){let t=await this.verifyFinalizedOvermint(e,a);t!==void 0&&p.push(t)}if(u.includes(`false-anchor`)){let t=await this.verifyFinalizedAnchor(e,a);t!==void 0&&p.push(t)}}return p}async watchInvalidBlocks(e){let t=await this.params.deadLetterQueue?.rejectedBlocks()??[],i=[];for(let a of t){let[t,u]=a.block??[],p=NI(t);if(p===void 0||!this.watchable(e,p.block).includes(`invalid-block`))continue;let y=p.addresses[0];if(y===void 0)continue;let x={accused:y,block:p.block,chain:p.chain,offense:`invalid-block`};if(this._emitted.has(offenseKeyString(x))||await suppressionFor(this.params.history,x)!==void 0)continue;let w=[t,...u??[]].filter(e=>e!==void 0),E=await this.verifiedArtifacts(w);if(E===void 0)continue;let D=await verifyInvalidBlock({catalogVersion:e.catalogVersion,chain:this.params.chain,params:e},{accused:y,block:p.block,offense:`invalid-block`},E);D.outcome===`verified`&&i.push({artifacts:w,key:x,offense:`invalid-block`,verdict:D})}return i}watchable(e,t){return this.params.offenses.filter(i=>isOffenseWatchable(e,i,t))}},Jpe=5e3,K5=100,emptyIndex=e=>({adjudications:/* @__PURE__ */ new Map,challenges:/* @__PURE__ */ new Map,commits:/* @__PURE__ */ new Map,head:e,requests:/* @__PURE__ */ new Map});function push(e,t,i){let a=e.get(t)??[];a.push(i),e.set(t,a)}function isSlashTraffic(e){return lI(e)||GF(e)||YF(e)||$F(e)}function byLanding(e,t){return e.carryingHeight-t.carryingHeight||e.index-t.index}function foldBlock(e,t,i){for(let[a,u]of i.entries()){let i={carryingHeight:t,hash:u._dataHash,index:a};lI(u)?push(e.requests,offenseKeyString(offenseKeyOf(u)),{...i,payload:u}):GF(u)?e.adjudications.has(u.request)||e.adjudications.set(u.request,{...i,payload:u}):YF(u)?push(e.challenges,u.request,{...i,payload:u}):$F(u)&&push(e.commits,u.commitment,{...i,payload:u})}}function chainWalkSlashHistoryReader(e,t=Jpe){let i,index=async()=>{let a=(await e.currentBlock())[0].block;if(i?.head===a)return i;let u=emptyIndex(a),p=Math.max(0,a-t),y=[];for(let t=a;t>=p;t-=K5){let i=Math.min(K5,t-p+1),a=await e.blocksByNumber(t,i);if(y.push(...a.filter(([,e])=>e.some(e=>isSlashTraffic(e)))),a.length===0)break}for(let[e,t]of y.toSorted((e,t)=>e[0].block-t[0].block))foldBlock(u,e.block,t);return i=u,u};return{adjudicationByKey:async e=>{let t=await index();return(t.requests.get(offenseKeyString(e))??[]).map(e=>t.adjudications.get(e.hash)).filter(e=>e!==void 0).toSorted(byLanding).at(0)},challengesForRequest:async e=>(await index()).challenges.get(e)??[],commitsMatching:async e=>(await index()).commits.get(e)??[],requestsByKey:async e=>(await index()).requests.get(offenseKeyString(e))??[]}}var SlashReporter=class{_open=/* @__PURE__ */ new Map;params;constructor(e){this.params=e}get openReports(){return this._open.size}settle(e){this._open.delete(e)}async settleThrough(e,t){let i=0;for(let[a,u]of this._open){if(await e.adjudicationByKey(u)!==void 0){this.settle(a),i+=1;continue}let p=(await e.requestsByKey(u))[0]?.carryingHeight;p!==void 0&&t!==void 0&&(!isRuleObservedAt(t,`eligibility-admission`,p)||isRuleObservedAt(t,adjudicableRuleId(`invalid-slash-request`),p))&&(this.settle(a),i+=1)}return i>0&&this.params.logger?.log(`[report] settled ${i} report slot(s)`),i}async submit(e,t){let i=offenseKeyString(e.key);if(this._open.has(i))return;if(this._open.size>=this.params.maxOpenReports){this.params.logger?.warn(`[report] holding ${i}: ${this._open.size} reports already open`);return}let a={artifacts:e.artifacts,from:this.params.reporter,schema:eI},u={accused:e.key.accused,block:e.key.block,catalog:t.catalogVersion,chain:e.key.chain,evidence:await Promise.all(e.artifacts.map(async e=>await al.dataHash(e))),from:this.params.reporter,offense:e.offense,schema:oI};try{let[t]=await this.params.gateway.addPayloadsToChain([a,u],[]);return this._open.set(i,e.key),this.params.logger?.warn(`[report] filed ${i} in transaction ${t}`),t}catch(e){this.params.logger?.warn(`[report] could not file ${i}: ${e.message}`);return}}},ValidatorActor=class extends ChainActor{_lastWitnessedStepIndex;_metricAttributes;_validatorActorOffensesDetected;_validatorActorRequestsSubmitted;_validatorActorStepChecks;_validatorActorStepsWitnessed;_validatorActorWatchPasses;_chainParams;_checkStepMutex=new Mutex;_gatewayRunner;_offenseWatcher;_slashHistory;_slashReporter;_watchMutex=new Mutex;get logger(){return assertEx$1(super.logger,()=>`Logger is required for ValidatorActor`)}get config(){return this.params.config}get gatewayRunner(){return this._gatewayRunner}get step(){return this.config.step??ValidatorActor.DefaultWitnessedStep}get stepCheckInterval(){return this.config.stepCheckInterval??ValidatorActor.DefaultStepCheckInterval}get watchInterval(){return this.config.watchInterval??1e4}async createHandler(){await super.createHandler(),this._metricAttributes={address:this.account.address},this._validatorActorStepChecks=this.counter(`validator_actor_step_checks`,`Number of step rollover checks`),this._validatorActorStepsWitnessed=this.counter(`validator_actor_steps_witnessed`,`Number of steps witnessed`),this._validatorActorOffensesDetected=this.counter(`validator_actor_offenses_detected`,`Number of offenses detected and verified by the watch duty`),this._validatorActorWatchPasses=this.counter(`validator_actor_watch_passes`,`Number of offense watch passes`),this._validatorActorRequestsSubmitted=this.counter(`validator_actor_requests_submitted`,`Number of slash reports submitted to the chain`),this._gatewayRunner=assertEx$1(await this.locator?.getInstance(tz),()=>`Unable to locate XyoGatewayRunner`),this.config.watch&&await this.createOffenseWatcher()}async startHandler(){await super.startHandler(),this._checkStepMutex=new Mutex,this._lastWitnessedStepIndex=void 0,this._watchMutex=new Mutex,this.registerTimer(`StepWitnessTimer`,async()=>{await this.checkStepRollover()},2e3,this.stepCheckInterval),this._offenseWatcher!==void 0&&this.registerTimer(`SlashWatchTimer`,async()=>{await this.runOffenseWatch()},5e3,this.watchInterval)}async checkStepRollover(){this._validatorActorStepChecks.add(1,this._metricAttributes),await this.spanAsync(`checkStepRollover`,async()=>{this._checkStepMutex.isLocked()?this.logger?.debug(`Skipping step rollover check, previous check still in progress`):await this._checkStepMutex.runExclusive(async()=>{let[e]=await assertEx$1(this.gatewayRunner.connection.viewer,()=>`ValidatorActor: gateway has no connection.viewer — cannot read blocks`).currentBlock(),t=Math.floor(e.block/stepSize(this.step));if(this._lastWitnessedStepIndex===void 0){this.logger?.log(`Watching step ${this.step} from block ${e.block} (step index ${t})`),this._lastWitnessedStepIndex=t;return}if(t<=this._lastWitnessedStepIndex)return;let{txHash:i,witness:a}=await witnessPreviousStep(this.gatewayRunner,{addToChain:!0,step:this.step});i&&await this.gatewayRunner.confirmSubmittedTransaction(i),this.logger?.log(`Witnessed step ${this.step} [${toHex(a.stepHash,{prefix:!0})}] at block ${a.blockNumber} [tx ${i===void 0?`none`:toHex(i,{prefix:!0})}]`),this._validatorActorStepsWitnessed.add(1,this._metricAttributes),this._lastWitnessedStepIndex=t})},{...this.context,timeBudgetLimit:1e3})}async createOffenseWatcher(){let e=this.gatewayRunner.connection.viewer;if(e===void 0){this.logger?.warn(`ValidatorActor: gateway has no connection.viewer — offense watch disabled`);return}let t=await this.locator?.tryGetInstance(Jz);if(this._chainParams=t,this.config.report){if(t===void 0)throw Error(`ValidatorActor: validator.report is enabled but no ChainParamsViewer is configured — reporting requires the parameter register that says which offenses are reportable.`);this._slashReporter=new SlashReporter({gateway:this.gatewayRunner,logger:this.logger,maxOpenReports:this.config.maxOpenReports,reporter:toAddress(this.account.address)})}this._slashHistory=chainWalkSlashHistoryReader(e),this._offenseWatcher=new OffenseWatcher({chain:canonicalChainReader(e),deadLetterQueue:await this.locator?.tryGetInstance(Xz),evidence:await this.locator?.tryGetInstance(Zz),history:this._slashHistory,logger:this.logger,mempool:await this.locator?.tryGetInstance(iB),offenses:this.config.offenses,params:async()=>await t?.tryCurrentParams()})}async readyHandler(){await this.checkStepRollover()}async runOffenseWatch(){let e=this._offenseWatcher;e===void 0||this._watchMutex.isLocked()||await this._watchMutex.runExclusive(async()=>{this._validatorActorWatchPasses.add(1,this._metricAttributes);try{let t=await this._chainParams?.tryCurrentParams();for(let i of await e.tick())this._validatorActorOffensesDetected.add(1,{...this._metricAttributes,offense:i.offense}),this.logger?.warn(`[watch] ${i.offense} detected against ${i.key.accused} at block ${i.key.block}: ${i.verdict.reason}`+(this._slashReporter===void 0?` (reporting is off)`:``)),this._slashReporter!==void 0&&t!==void 0&&await this._slashReporter.submit(i,t)!==void 0&&this._validatorActorRequestsSubmitted.add(1,{...this._metricAttributes,offense:i.offense});this._slashReporter!==void 0&&this._slashHistory!==void 0&&await this._slashReporter.settleThrough(this._slashHistory,t)}catch(e){this.logger?.warn(`[watch] offense watch pass failed: ${e.message}`)}})}};H5(ValidatorActor,`DefaultStepCheckInterval`,U5),H5(ValidatorActor,`DefaultWitnessedStep`,2),H5(ValidatorActor,`dependencies`,[tz]),ValidatorActor=Upe([creatable()],ValidatorActor);var Ype={bootExtras:({signingWallets:e})=>e.validator===void 0?[]:[gatewaySignerDescriptor()],compileExtras:({process:e})=>[xyoConnectionActorDescriptor(e,!0)],configParser:W5,create:async e=>await ValidatorActor.create({account:e.wallet,config:Gpe(e.actor),locator:e.locator,name:`xl1-validator`}),defaultAccountPath:`7`,dependencies:[`XyoGatewayRunner`],name:`validator`,optionalProviderRoots:[`BlockValidationViewer`,`ChainParamsViewer`,`DeadLetterQueueViewer`,`EvidenceViewer`,`MempoolViewer`,`StakeIntentViewer`,`StakeSnapshotViewer`],signerMoniker:QR};function createActorBuilderCatalog(e){let t=/* @__PURE__ */ new Map,i=[];for(let a of e){if(t.has(a.name))throw Error(`Actor builder "${a.name}" is already registered`);t.set(a.name,a),i.push(a.name)}return{names:Object.freeze(i),async build(e,i){let a=t.get(e);if(a===void 0)throw Error(`Unknown actor: ${e}`);return await a.build(i)}}}var Xpe=1e4;function logInterruptError(e,...t){try{e.error(...t)}catch{}}function logInterruptInfo(e,...t){try{e.info(...t)}catch{}}function hostInterruptLogger(e){return{error:(...t)=>e.io.error(...t),info:(...t)=>e.io.log(...t)}}function isUnrefableTimer(e){return typeof e==`object`&&!!e&&`unref`in e&&typeof e.unref==`function`}function installRuntimeInterruptController({host:e,startupTimeoutMs:t=Xpe}){let i=hostInterruptLogger(e),a=new AbortController,u=0,p=!1,y;function forceExit(){clearTimeout(y),y=void 0;try{e.exit(130)}catch(e){logInterruptError(i,`Error requesting immediate exit:`,e)}}function armStartupTimer(){y!==void 0||t<=0||(y=setTimeout(()=>{y=void 0,logInterruptError(i,`Startup did not stop within ${t}ms of the interrupt; exiting now.`),forceExit()},t),isUnrefableTimer(y)&&y.unref())}function handleInterrupt(){u+=1,u===1?(a.abort(/* @__PURE__ */ Error(`Runtime interrupt requested`)),p||(logInterruptInfo(i,`
|
|
34579
34579
|
Shutdown requested during startup. Cancelling...`),armStartupTimer())):(logInterruptInfo(i,`
|
|
34580
34580
|
Second interrupt received. Exiting immediately.`),forceExit())}let x=e.onInterrupt(handleInterrupt);return{get isInterrupted(){return u>0},get isSessionAdopted(){return p},get signal(){return a.signal},adoptSession(){p=!0,u>0||(clearTimeout(y),y=void 0)},dispose(){clearTimeout(y),y=void 0,x()}}}var Zpe=15e3;function resolveShutdownTimeoutMs(e,t={}){let{defaultMs:i=Zpe,environmentVariable:a,override:u}=t;if(u!==void 0)return u;let p=a===void 0?void 0:e.environment?.[a];if(p===void 0||p===``)return i;let y=Number(p);return Number.isFinite(y)&&y>=0?y:i}async function stopWithinTimeout(e,t,i,a){let u,p=!1,y=t<=0?void 0:new Promise(e=>{u=setTimeout(()=>{p=!0,e({kind:`timeout`})},t)}),x=(async()=>{if(a!==void 0)try{await a()}catch(e){logInterruptError(i,`Error cancelling in-flight work during shutdown:`,e)}if(p)return{kind:`timeout`};try{return await e.stop(),{kind:`stopped`}}catch(e){return{error:e,kind:`failed`}}})();try{return y===void 0?await x:await Promise.race([x,y])}finally{clearTimeout(u)}}async function handleRuntimeInterrupt$1(e,t,i,a={}){let u=resolveShutdownTimeoutMs(e,{environmentVariable:a.shutdownTimeoutEnvironmentVariable,...a.shutdownTimeoutMs!==void 0&&{override:a.shutdownTimeoutMs}});logInterruptInfo(t,`
|
|
@@ -34700,7 +34700,7 @@ https://yargs.js.org/docs/#api-reference-version`,void 0,`versionWarning`),__cla
|
|
|
34700
34700
|
`),i=i.replace(/\\r/g,`\r`)),t[e]=i}return t}function g(e){return e<=32?e===32||e>=9&&e<=13:e>=160&&(e===160||e===5760||e>=8192&&e<=8202||e===8232||e===8233||e===8239||e===8287||e===12288||e===65279)}function O(e){return e===10||e===8232||e===8233}function V(e){let t={},i=typeof e==`string`?e:e.toString();i.indexOf(`\r`)!==-1&&(i=i.replace(/\r\n?/g,`
|
|
34701
34701
|
`));let a=i.length,u=0;for(;u<a;){let e=i.charCodeAt(u);for(;u<a&&g(e);)u++,e=i.charCodeAt(u);if(u>=a)break;if(e===35){for(;u<a&&!O(i.charCodeAt(u));)u++;continue}let p=-1;if(e===101&&u+6<a&&i.charCodeAt(u+1)===120&&i.charCodeAt(u+2)===112&&i.charCodeAt(u+3)===111&&i.charCodeAt(u+4)===114&&i.charCodeAt(u+5)===116){if(g(i.charCodeAt(u+6))){let e=u+7;for(;e<a&&g(i.charCodeAt(e));)e++;A[i.charCodeAt(e)]&&(p=u+6,u=e)}else e=i.charCodeAt(u)}let y=u,x=0;for(;u<a&&(x=i.charCodeAt(u),A[x]);)u++;if(u===y){for(;u<a&&!O(i.charCodeAt(u));)u++;continue}let w=i.slice(y,u),E=u;if(u>=a&&(x=0),g(x))do u++,x=u<a?i.charCodeAt(u):0;while(g(x));if(x===61)u++;else if(x===58&&u===E&&u+1<a&&g(i.charCodeAt(u+1)))u+=2;else{for(u=p===-1?E:p;u<a&&!O(i.charCodeAt(u));)u++;continue}let D=u,N=u;for(;N<a&&g(i.charCodeAt(N));)N++;let P=i.charCodeAt(N),F,I=!1;if(P===39||P===34||P===96){let e=i[N],t=i.indexOf(e,N+1),p=-1,y=-1;for(;t!==-1;){let u=i.charCodeAt(t-1)===92,x=t+1;for(;x<a&&!O(i.charCodeAt(x))&&g(i.charCodeAt(x));)x++;if((x===a||O(i.charCodeAt(x))||i.charCodeAt(x)===35)&&(p=t,y=x),!u)break;t=i.indexOf(e,t+1)}if(p!==-1){if(F=i.slice(N+1,p),u=y,i.charCodeAt(u)===35)for(;u<a&&!O(i.charCodeAt(u));)u++;I=!0}}if(!I){let e=i.indexOf(`
|
|
34702
34702
|
`,D);e===-1&&(e=a);let t;if(a<4096)t=i.indexOf(`#`,D),(t===-1||t>e)&&(t=e);else for(t=D;t<e&&i.charCodeAt(t)!==35;)t++;let p=D,y=t;for(;p<y&&g(i.charCodeAt(p));)p++;for(;y>p&&g(i.charCodeAt(y-1));)y--;let x=i.charCodeAt(p);if(F=i.slice(p,y),F.includes(`\u2028`)||F.includes(`\u2029`)?F=F.replace(/^(['"`])([\s\S]*)\1$/gm,`$2`):y-p>=2&&(x===39||x===34||x===96)&&i.charCodeAt(y-1)===x&&(F=i.slice(p+1,y-1)),u=t,t<e)for(;u<a&&!O(i.charCodeAt(u));)u++}P===34&&(I||N<u)&&F.indexOf(`\\`)!==-1&&(F=F.replace(/\\n/g,`
|
|
34703
|
-
`).replace(/\\r/g,`\r`)),t[w]=F}return t}function J(e,t){return t&&w(t.fast)?V(e):H(e)}function v(e){console.log(`\u2506 ${e}`)}function W(e){console.error(`\u25C7 ${e}`)}function S(e){return e[0]===`~`?u.join(p.homedir(),e.slice(1)):e}function K(e={}){let t={...e};for(let e of Object.keys(t))t[e]===void 0&&delete t[e];return{...E(),...t}}function M(e){e=K(e);let t=u.resolve(process.cwd(),`.env`),i=`utf8`,p=process.env;e&&e.processEnv!=null&&(p=e.processEnv);let D=w(e&&e.debug);e&&e.encoding?i=e.encoding:D&&v(`no encoding is specified (UTF-8 is used by default)`);let A=[t];if(e&&e.path){if(!Array.isArray(e.path))A=[S(e.path)];else{A=[];for(let t of e.path)A.push(S(t))}}let P,F={},I={fast:e.fast};for(let t of A)try{let u=N.parse(a.readFileSync(t,{encoding:i}),I);N.populate(F,u,e)}catch(e){D&&v(`failed to load ${t} ${e.message}`),P=e}let L=N.populate(p,F,e),B=w(Object.prototype.hasOwnProperty.call(e,`quiet`)?e.quiet:E(p).quiet);if(D||!B){let e=Object.keys(L).length,t=[];for(let e of A)try{let i=u.relative(process.cwd(),e instanceof y?x(e):e);t.push(i)}catch(t){D&&v(`failed to load ${e} ${t.message}`),P=t}W(`injected env (${e}) from ${t.join(`,`)}`)}return P?{parsed:F,error:P}:{parsed:F}}function Y(e){return N.configDotenv(e)}function z(e,t,i={}){let a=w(i&&i.debug),u=w(i&&i.override),p={};if(typeof e!=`object`||!e||typeof t!=`object`||!t){let e=/* @__PURE__ */ Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let i of Object.keys(t))Object.prototype.hasOwnProperty.call(e,i)?(u===!0&&(e[i]=t[i],p[i]=t[i]),a&&v(u===!0?`"${i}" is already defined and WAS overwritten`:`"${i}" is already defined and was NOT overwritten`)):(e[i]=t[i],p[i]=t[i]);return p}var N={configDotenv:M,config:Y,parse:J,populate:z};t.exports.configDotenv=N.configDotenv,t.exports.config=N.config,t.exports.parse=N.parse,t.exports.populate=N.populate,t.exports=N})();t.exports=a,t.exports.config=a.config,t.exports.configDotenv=a.configDotenv,t.exports.parse=a.parse,t.exports.populate=a.populate}));Uo(),_Z(),za();var nhe=the();function registerDefaultInstalledActors(e){e.registerMany([$2,Jfe,lde,$de,ife,lfe,ufe,cfe,Tfe,Qfe,ope,Bpe,Ype])}function createDefaultInstalledActorRegistry(){let e=createInstalledActorRegistry();return registerDefaultInstalledActors(e),e}function ensureDefaultInstalledActors(){let e=getDefaultInstalledActorRegistry();return e.all().length===0&®isterDefaultInstalledActors(e),e}async function cleanupConstructedActors(e){return(await Promise.allSettled(e.map(async e=>{await e.shutdown?.()}))).flatMap(e=>e.status===`rejected`?[e.reason]:[])}function throwWithActorCleanupFailures(e,t){throw t.length>0?AggregateError([e,...t],`${t.length} constructed actor(s) failed to clean up`,{cause:e}):e}async function buildCatalogActors(e,t,i){let a=Array.from({length:t.length}),u=!1,p=t.map(async(t,p)=>{try{let y=await e.build(t,i);u?await y.shutdown?.():a[p]=y}catch(e){throw u=!0,e}});try{await Promise.all(p)}catch(e){u=!0,throwWithActorCleanupFailures(e,await cleanupConstructedActors(a.filter(e=>e!==void 0)))}return a.filter(e=>e!==void 0)}async function startActorsOnOrchestrator(e,t,i){try{for(let i of e)await t.registerActor(i)}catch(t){throwWithActorCleanupFailures(t,await cleanupConstructedActors(e))}if(!await t.start())throw Error(`Orchestrator failed to start one or more actors`);await t.whenReady(i)}var J9=createDefaultInstalledActorRegistry(),rhe=createActorBuilderCatalog(J9.all().flatMap(e=>e.create===void 0?[]:{name:e.name,build:async({configuration:t,locator:i})=>await buildInstalledActor(e.name,t,i,J9)})),ihe=6e4;function getActorsFromConfig(e){let t=e.actors.filter(e=>e.enabled!==!1).map(e=>e.name);return t.length>0?t:void 0}function getDefaultActors(){return[`api`,`producer`,`finalizer`]}async function bootActors(e,t,i,a,u){let p=Date.now();await startActorsOnOrchestrator(await buildCatalogActors(u,e,{configuration:a,locator:t}),i,ihe);let y=Date.now()-p;initDefaultLogger(a.log).info(`[xl1] system ready (${e.join(`/`)} in ${y}ms)`)}function startCommand(e,t,i=rhe){return{command:[`start [actors..]`,`$0`],describe:`Run a full XL1 Node`,builder:e=>e.positional(`actors`,{type:`string`,array:!0,description:`Actors to start (e.g. xl1 start api producer or xl1 start api,producer)`,coerce:e=>Array.isArray(e)?e.flatMap(e=>typeof e==`string`?e.split(`,`):[]):e}).option(`actors`,{type:`array`,string:!0,description:`List of actors to start (e.g. --actors api producer finalizer). Defaults to api, producer, and finalizer.`}).check(e=>{let t=(Array.isArray(e.actors)?e.actors.filter(e=>typeof e==`string`):[]).filter(e=>!i.names.includes(e));if(t.length>0)throw Error(`Unknown actor(s): ${t.join(`, `)}. Choices: ${i.names.join(`, `)}`);return!0}),handler:async a=>{let u=e(),p=Array.isArray(a.actors)&&a.actors.length>0?a.actors:getActorsFromConfig(u)??getDefaultActors(),{locator:y,orchestrator:x}=await t(p,u);await bootActors(p,y,x,u,i)}}}function withDeprecationWarning(e,t=X5){return withDeprecationWarning$1(e,t)}var ahe=[{actors:[`api`,`mempool`,`finalizer`],command:`api`,describe:`Run a XL1 API Node`},{actors:[`bridge`],command:`bridge`,describe:`Run a XL1 Bridge Node`},{actors:[`finalizer`],command:`finalizer`,describe:`Run a XL1 Finalizer Node`},{actors:[`indexer`],command:`indexer`,describe:`Run a XL1 chain index Indexer Node`},{actors:[`mempool`],command:`mempool`,describe:`Run a XL1 Mempool Node`},{actors:[`producer`],command:`producer`,describe:`Run a XL1 Producer Node`},{actors:[`rewardRedemption`],command:`reward-redemption-api`,describe:`Run a XL1 Rewards Redemption API Node`},{actors:[`validator`],command:`validator`,describe:`Run a XL1 Validator Node`}];function legacyActorCommand(e,t){return{command:e.command,deprecated:`Use "start ${e.actors.join(` `)}" instead`,describe:e.describe,handler:async()=>{let i=t.getConfiguration(),{locator:a,orchestrator:u}=await t.getLocatorFromConfig([...e.actors],i);await startActorsOnOrchestrator(await Promise.all(e.actors.map(e=>buildInstalledActor(e,i,a))),u)}}}var ohe=createCommandCatalog([...ahe.map(e=>({id:e.command,create:t=>withDeprecationWarning(legacyActorCommand(e,t),t.host)})),{id:`backup`,create:e=>({command:`backup`,describe:`Run bounded, resumable Auto Drive backup passes (dry-run by default)`,handler:async()=>{let t=e.getConfiguration(),{locator:i,orchestrator:a}=await e.getLocatorFromConfig([`backup`],t);await startActorsOnOrchestrator([await buildInstalledActor(`backup`,t,i)],a,6e4)}})},{id:`start`,create:e=>startCommand(e.getConfiguration,e.getLocatorFromConfig)}]),she=createDeepMerge({arrayStrategy:`concat`}),che={chainMongo:`chain-mongo`,defaultEvmRpc:`default-evm-rpc`,defaultRpc:`default-rpc`,localStore:`local-store`,restChainState:`rest-chain-state`,restFinalized:`rest-finalized`,restIndex:`rest-index`,s3ChainState:`s3-chain-state`,s3Finalized:`s3-finalized`,s3Index:`s3-index`},Y9=/* @__PURE__ */ new Set([`$0`,`_`,`config`,`dump-config`,`dumpConfig`,`dump-providers`,`dumpProviders`,`help`,`selected-actors`,`selectedActors`,`skip-insecure-confirm`,`skipInsecureConfirm`,`version`,`with-secrets`,`withSecrets`]);function isRecord(e){return typeof e==`object`&&!!e}function canonicalConnectionName(e){return che[e]??e}function normalizeConnectionNames(e){let t={...e},i=t.connections;if(isRecord(i)){let e={};for(let[t,a]of Object.entries(i))e[canonicalConnectionName(t)]=a;t.connections=e}let a=t.providerBindings;if(isRecord(a)){let e={};for(let[t,i]of Object.entries(a))e[t]=isRecord(i)?{...i,...typeof i.connection==`string`&&{connection:canonicalConnectionName(i.connection)},...typeof i.transport==`string`&&{transport:canonicalConnectionName(i.transport)}}:i;t.providerBindings=e}return t}function selectActorSlices(e,t){let i=Array.isArray(e)?e.filter(isRecord):[];return[...new Set(t)].map(e=>i.find(t=>t.name===e)??{name:e})}function resolveXl1Configuration({argv:e,fileConfiguration:t}){let i=normalizeConnectionNames(t),a=typeof i.mnemonic==`string`?i.mnemonic:void 0,u=normalizeConnectionNames(coerceIndexedArrayOption(e,`actors`)),p=omitArgvKeys(u,Y9),y=stripOrchestrationOnlyConnections(p),x=y.actors===void 0&&y.connections===void 0&&y.providerBindings===void 0?{}:y,w=typeof u.mnemonic==`string`?u.mnemonic:void 0,E=i,D=p.actors;if(Array.isArray(D)&&D.length>0){let{actors:e,...t}=i;E=t;let a=D.filter(e=>typeof e==`string`);a.length===D.length&&(x={...x,actors:selectActorSlices(e,a)})}let A=stripOrchestrationOnlyConnections(she(E,x)),N=w??a;return finalizeConfig({...A,...isDefined$1(N)&&{mnemonic:N}})}async function configMiddleware(e,t,i=X5){let a=!1;try{let u=resolveXl1Configuration({argv:e,fileConfiguration:await tryParseConfig({configPath:e.config,finalize:!1})});if(assertNoActorMnemonics(u),t(u),e[`dump-config`]===!0){let t=e[`with-secrets`]?u:redactConfig(u);i.io.log(JSON.stringify(t,null,2)),a=!0}}catch(e){throw e instanceof ConfigFileNotFoundError?i.io.error(`${e.message}. Check the path passed to --config/-c and try again.`):e instanceof ActorMnemonicNotAllowedError?i.io.error(e.message):isZodError(e)?i.io.error(`Zod error: ${e.message}`):i.io.error(`Error parsing configuration: ${String(e)}`),!(e instanceof ConfigFileNotFoundError)&&!(e instanceof ActorMnemonicNotAllowedError)&&i.io.error(`Stack: ${e instanceof Error?e.stack:`N/A`}`),new CliConfigError(`Invalid configuration`,{cause:e})}a&&exitProcess(i,0)}var X9=[`producer`,`finalizer`,`api`,`mempool`,`bridge`,`rewardRedemption`];function enumerateLocator(e){let t=/* @__PURE__ */ new Map,i=e.registry;for(let[e,a]of Object.entries(i))if(a)for(let i of a){let a=i,u=a.providerName??`<unknown>`,p=a.scope??`<unknown>`,y=a.dependencies??[],x=`${e}|${u}|${p}|${y.join(`,`)}`,w=t.get(x);w?w.count+=1:t.set(x,{count:1,dependencies:y,moniker:e,providerName:u,scope:p})}return t.values().toArray().toSorted((e,t)=>e.moniker.localeCompare(t.moniker)||e.providerName.localeCompare(t.providerName))}function buildOwnerIndex(e){let t=/* @__PURE__ */ new Map;for(let[i,a]of e)for(let e of a){let a=t.get(e.moniker);a||(a=/* @__PURE__ */ new Set,t.set(e.moniker,a)),a.add(i)}return t}function renderDuplicatesSummary(e){let t=[...e].filter(([,e])=>e.size>1).map(([e,t])=>({moniker:e,owners:[...t].toSorted((e,t)=>e.localeCompare(t)).map(formatGroupForDisplay)})).toSorted((e,t)=>e.moniker.localeCompare(t.moniker));if(t.length===0)return[];let i=[`Duplicate monikers (registered by more than one locator):`];for(let{moniker:e,owners:a}of t)i.push(` - ${e}: ${a.join(`, `)}`);return i.push(``),i}function groupActorsBySharedRegistry(e){let t=[];for(let[i,a]of Object.entries(e)){let e=t.find(e=>e.registry===a.registry);e?e.actorNames.push(i):t.push({actorNames:[i],locator:a,registry:a.registry})}return t}function groupId(e){return e.toSorted((e,t)=>e.localeCompare(t)).join(`,`)}function formatGroupForDisplay(e){let t=e.split(`,`);return t.length===1?t[0]:`(${t.join(`, `)})`}function renderGroupSection(e,t,i){let a=e.toSorted((e,t)=>e.localeCompare(t)),u=groupId(a),p=[a.length===1?`Providers for actor: ${a[0]} (${t.length} registered)`:`Providers shared by actors: ${a.join(`, `)} (${t.length} registered)`];if(t.length===0)return p.push(` (none)`,``),p;for(let e=0;e<t.length;e++){let a=t[e],y=e===t.length-1?`└──`:`├──`,x=[...i.get(a.moniker)??/* @__PURE__ */ new Set].filter(e=>e!==u).toSorted((e,t)=>e.localeCompare(t)).map(formatGroupForDisplay),w=x.length>0?` \u26A0 also in: ${x.join(`, `)}`:``,E=a.dependencies.length>0?`, deps: [${a.dependencies.join(`, `)}]`:``,D=a.count>1?` (\xD7${a.count})`:``;p.push(` ${y} ${a.moniker}${D} [impl: ${a.providerName}, scope: ${a.scope}${E}]${w}`)}return p.push(``),p}function formatProviderTree(e){let t=groupActorsBySharedRegistry(e).map(e=>({...e,key:groupId(e.actorNames)})),i=/* @__PURE__ */ new Map;for(let e of t)i.set(e.key,enumerateLocator(e.locator));let a=buildOwnerIndex(i),u=[...t].toSorted((e,t)=>{let i=e.actorNames.includes(`_root`);if(i!==t.actorNames.includes(`_root`))return i?-1:1;let a=X9.indexOf(e.actorNames[0]),u=X9.indexOf(t.actorNames[0]);return a===u?e.key.localeCompare(t.key):(a===-1?2**53-1:a)-(u===-1?2**53-1:u)}),p=[`XL1 Provider Dump`,`=================`,``];for(let e of u)p.push(...renderGroupSection(e.actorNames.toSorted((e,t)=>e.localeCompare(t)),i.get(e.key)??[],a));return p.push(...renderDuplicatesSummary(a)),p.join(`
|
|
34703
|
+
`).replace(/\\r/g,`\r`)),t[w]=F}return t}function J(e,t){return t&&w(t.fast)?V(e):H(e)}function v(e){console.log(`\u2506 ${e}`)}function W(e){console.error(`\u25C7 ${e}`)}function S(e){return e[0]===`~`?u.join(p.homedir(),e.slice(1)):e}function K(e={}){let t={...e};for(let e of Object.keys(t))t[e]===void 0&&delete t[e];return{...E(),...t}}function M(e){e=K(e);let t=u.resolve(process.cwd(),`.env`),i=`utf8`,p=process.env;e&&e.processEnv!=null&&(p=e.processEnv);let D=w(e&&e.debug);e&&e.encoding?i=e.encoding:D&&v(`no encoding is specified (UTF-8 is used by default)`);let A=[t];if(e&&e.path){if(!Array.isArray(e.path))A=[S(e.path)];else{A=[];for(let t of e.path)A.push(S(t))}}let P,F={},I={fast:e.fast};for(let t of A)try{let u=N.parse(a.readFileSync(t,{encoding:i}),I);N.populate(F,u,e)}catch(e){D&&v(`failed to load ${t} ${e.message}`),P=e}let L=N.populate(p,F,e),B=w(Object.prototype.hasOwnProperty.call(e,`quiet`)?e.quiet:E(p).quiet);if(D||!B){let e=Object.keys(L).length,t=[];for(let e of A)try{let i=u.relative(process.cwd(),e instanceof y?x(e):e);t.push(i)}catch(t){D&&v(`failed to load ${e} ${t.message}`),P=t}W(`injected env (${e}) from ${t.join(`,`)}`)}return P?{parsed:F,error:P}:{parsed:F}}function Y(e){return N.configDotenv(e)}function z(e,t,i={}){let a=w(i&&i.debug),u=w(i&&i.override),p={};if(typeof e!=`object`||!e||typeof t!=`object`||!t){let e=/* @__PURE__ */ Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let i of Object.keys(t))Object.prototype.hasOwnProperty.call(e,i)?(u===!0&&(e[i]=t[i],p[i]=t[i]),a&&v(u===!0?`"${i}" is already defined and WAS overwritten`:`"${i}" is already defined and was NOT overwritten`)):(e[i]=t[i],p[i]=t[i]);return p}var N={configDotenv:M,config:Y,parse:J,populate:z};t.exports.configDotenv=N.configDotenv,t.exports.config=N.config,t.exports.parse=N.parse,t.exports.populate=N.populate,t.exports=N})();t.exports=a,t.exports.config=a.config,t.exports.configDotenv=a.configDotenv,t.exports.parse=a.parse,t.exports.populate=a.populate}));Uo(),_Z(),za();var nhe=the();function registerDefaultInstalledActors(e){e.registerMany([$2,Jfe,lde,$de,rfe,lfe,ufe,cfe,Tfe,Qfe,ope,Bpe,Ype])}function createDefaultInstalledActorRegistry(){let e=createInstalledActorRegistry();return registerDefaultInstalledActors(e),e}function ensureDefaultInstalledActors(){let e=getDefaultInstalledActorRegistry();return e.all().length===0&®isterDefaultInstalledActors(e),e}async function cleanupConstructedActors(e){return(await Promise.allSettled(e.map(async e=>{await e.shutdown?.()}))).flatMap(e=>e.status===`rejected`?[e.reason]:[])}function throwWithActorCleanupFailures(e,t){throw t.length>0?AggregateError([e,...t],`${t.length} constructed actor(s) failed to clean up`,{cause:e}):e}async function buildCatalogActors(e,t,i){let a=Array.from({length:t.length}),u=!1,p=t.map(async(t,p)=>{try{let y=await e.build(t,i);u?await y.shutdown?.():a[p]=y}catch(e){throw u=!0,e}});try{await Promise.all(p)}catch(e){u=!0,throwWithActorCleanupFailures(e,await cleanupConstructedActors(a.filter(e=>e!==void 0)))}return a.filter(e=>e!==void 0)}async function startActorsOnOrchestrator(e,t,i){try{for(let i of e)await t.registerActor(i)}catch(t){throwWithActorCleanupFailures(t,await cleanupConstructedActors(e))}if(!await t.start())throw Error(`Orchestrator failed to start one or more actors`);await t.whenReady(i)}var J9=createDefaultInstalledActorRegistry(),rhe=createActorBuilderCatalog(J9.all().flatMap(e=>e.create===void 0?[]:{name:e.name,build:async({configuration:t,locator:i})=>await buildInstalledActor(e.name,t,i,J9)})),ihe=6e4;function getActorsFromConfig(e){let t=e.actors.filter(e=>e.enabled!==!1).map(e=>e.name);return t.length>0?t:void 0}function getDefaultActors(){return[`api`,`producer`,`finalizer`]}async function bootActors(e,t,i,a,u){let p=Date.now();await startActorsOnOrchestrator(await buildCatalogActors(u,e,{configuration:a,locator:t}),i,ihe);let y=Date.now()-p;initDefaultLogger(a.log).info(`[xl1] system ready (${e.join(`/`)} in ${y}ms)`)}function startCommand(e,t,i=rhe){return{command:[`start [actors..]`,`$0`],describe:`Run a full XL1 Node`,builder:e=>e.positional(`actors`,{type:`string`,array:!0,description:`Actors to start (e.g. xl1 start api producer or xl1 start api,producer)`,coerce:e=>Array.isArray(e)?e.flatMap(e=>typeof e==`string`?e.split(`,`):[]):e}).option(`actors`,{type:`array`,string:!0,description:`List of actors to start (e.g. --actors api producer finalizer). Defaults to api, producer, and finalizer.`}).check(e=>{let t=(Array.isArray(e.actors)?e.actors.filter(e=>typeof e==`string`):[]).filter(e=>!i.names.includes(e));if(t.length>0)throw Error(`Unknown actor(s): ${t.join(`, `)}. Choices: ${i.names.join(`, `)}`);return!0}),handler:async a=>{let u=e(),p=Array.isArray(a.actors)&&a.actors.length>0?a.actors:getActorsFromConfig(u)??getDefaultActors(),{locator:y,orchestrator:x}=await t(p,u);await bootActors(p,y,x,u,i)}}}function withDeprecationWarning(e,t=X5){return withDeprecationWarning$1(e,t)}var ahe=[{actors:[`api`,`mempool`,`finalizer`],command:`api`,describe:`Run a XL1 API Node`},{actors:[`bridge`],command:`bridge`,describe:`Run a XL1 Bridge Node`},{actors:[`finalizer`],command:`finalizer`,describe:`Run a XL1 Finalizer Node`},{actors:[`indexer`],command:`indexer`,describe:`Run a XL1 chain index Indexer Node`},{actors:[`mempool`],command:`mempool`,describe:`Run a XL1 Mempool Node`},{actors:[`producer`],command:`producer`,describe:`Run a XL1 Producer Node`},{actors:[`rewardRedemption`],command:`reward-redemption-api`,describe:`Run a XL1 Rewards Redemption API Node`},{actors:[`validator`],command:`validator`,describe:`Run a XL1 Validator Node`}];function legacyActorCommand(e,t){return{command:e.command,deprecated:`Use "start ${e.actors.join(` `)}" instead`,describe:e.describe,handler:async()=>{let i=t.getConfiguration(),{locator:a,orchestrator:u}=await t.getLocatorFromConfig([...e.actors],i);await startActorsOnOrchestrator(await Promise.all(e.actors.map(e=>buildInstalledActor(e,i,a))),u)}}}var ohe=createCommandCatalog([...ahe.map(e=>({id:e.command,create:t=>withDeprecationWarning(legacyActorCommand(e,t),t.host)})),{id:`backup`,create:e=>({command:`backup`,describe:`Run bounded, resumable Auto Drive backup passes (dry-run by default)`,handler:async()=>{let t=e.getConfiguration(),{locator:i,orchestrator:a}=await e.getLocatorFromConfig([`backup`],t);await startActorsOnOrchestrator([await buildInstalledActor(`backup`,t,i)],a,6e4)}})},{id:`start`,create:e=>startCommand(e.getConfiguration,e.getLocatorFromConfig)}]),she=createDeepMerge({arrayStrategy:`concat`}),che={chainMongo:`chain-mongo`,defaultEvmRpc:`default-evm-rpc`,defaultRpc:`default-rpc`,localStore:`local-store`,restChainState:`rest-chain-state`,restFinalized:`rest-finalized`,restIndex:`rest-index`,s3ChainState:`s3-chain-state`,s3Finalized:`s3-finalized`,s3Index:`s3-index`},Y9=/* @__PURE__ */ new Set([`$0`,`_`,`config`,`dump-config`,`dumpConfig`,`dump-providers`,`dumpProviders`,`help`,`selected-actors`,`selectedActors`,`skip-insecure-confirm`,`skipInsecureConfirm`,`version`,`with-secrets`,`withSecrets`]);function isRecord(e){return typeof e==`object`&&!!e}function canonicalConnectionName(e){return che[e]??e}function normalizeConnectionNames(e){let t={...e},i=t.connections;if(isRecord(i)){let e={};for(let[t,a]of Object.entries(i))e[canonicalConnectionName(t)]=a;t.connections=e}let a=t.providerBindings;if(isRecord(a)){let e={};for(let[t,i]of Object.entries(a))e[t]=isRecord(i)?{...i,...typeof i.connection==`string`&&{connection:canonicalConnectionName(i.connection)},...typeof i.transport==`string`&&{transport:canonicalConnectionName(i.transport)}}:i;t.providerBindings=e}return t}function selectActorSlices(e,t){let i=Array.isArray(e)?e.filter(isRecord):[];return[...new Set(t)].map(e=>i.find(t=>t.name===e)??{name:e})}function resolveXl1Configuration({argv:e,fileConfiguration:t}){let i=normalizeConnectionNames(t),a=typeof i.mnemonic==`string`?i.mnemonic:void 0,u=normalizeConnectionNames(coerceIndexedArrayOption(e,`actors`)),p=omitArgvKeys(u,Y9),y=stripOrchestrationOnlyConnections(p),x=y.actors===void 0&&y.connections===void 0&&y.providerBindings===void 0?{}:y,w=typeof u.mnemonic==`string`?u.mnemonic:void 0,E=i,D=p.actors;if(Array.isArray(D)&&D.length>0){let{actors:e,...t}=i;E=t;let a=D.filter(e=>typeof e==`string`);a.length===D.length&&(x={...x,actors:selectActorSlices(e,a)})}let A=stripOrchestrationOnlyConnections(she(E,x)),N=w??a;return finalizeConfig({...A,...isDefined$1(N)&&{mnemonic:N}})}async function configMiddleware(e,t,i=X5){let a=!1;try{let u=resolveXl1Configuration({argv:e,fileConfiguration:await tryParseConfig({configPath:e.config,finalize:!1})});if(assertNoActorMnemonics(u),t(u),e[`dump-config`]===!0){let t=e[`with-secrets`]?u:redactConfig(u);i.io.log(JSON.stringify(t,null,2)),a=!0}}catch(e){throw e instanceof ConfigFileNotFoundError?i.io.error(`${e.message}. Check the path passed to --config/-c and try again.`):e instanceof ActorMnemonicNotAllowedError?i.io.error(e.message):isZodError(e)?i.io.error(`Zod error: ${e.message}`):i.io.error(`Error parsing configuration: ${String(e)}`),!(e instanceof ConfigFileNotFoundError)&&!(e instanceof ActorMnemonicNotAllowedError)&&i.io.error(`Stack: ${e instanceof Error?e.stack:`N/A`}`),new CliConfigError(`Invalid configuration`,{cause:e})}a&&exitProcess(i,0)}var X9=[`producer`,`finalizer`,`api`,`mempool`,`bridge`,`rewardRedemption`];function enumerateLocator(e){let t=/* @__PURE__ */ new Map,i=e.registry;for(let[e,a]of Object.entries(i))if(a)for(let i of a){let a=i,u=a.providerName??`<unknown>`,p=a.scope??`<unknown>`,y=a.dependencies??[],x=`${e}|${u}|${p}|${y.join(`,`)}`,w=t.get(x);w?w.count+=1:t.set(x,{count:1,dependencies:y,moniker:e,providerName:u,scope:p})}return t.values().toArray().toSorted((e,t)=>e.moniker.localeCompare(t.moniker)||e.providerName.localeCompare(t.providerName))}function buildOwnerIndex(e){let t=/* @__PURE__ */ new Map;for(let[i,a]of e)for(let e of a){let a=t.get(e.moniker);a||(a=/* @__PURE__ */ new Set,t.set(e.moniker,a)),a.add(i)}return t}function renderDuplicatesSummary(e){let t=[...e].filter(([,e])=>e.size>1).map(([e,t])=>({moniker:e,owners:[...t].toSorted((e,t)=>e.localeCompare(t)).map(formatGroupForDisplay)})).toSorted((e,t)=>e.moniker.localeCompare(t.moniker));if(t.length===0)return[];let i=[`Duplicate monikers (registered by more than one locator):`];for(let{moniker:e,owners:a}of t)i.push(` - ${e}: ${a.join(`, `)}`);return i.push(``),i}function groupActorsBySharedRegistry(e){let t=[];for(let[i,a]of Object.entries(e)){let e=t.find(e=>e.registry===a.registry);e?e.actorNames.push(i):t.push({actorNames:[i],locator:a,registry:a.registry})}return t}function groupId(e){return e.toSorted((e,t)=>e.localeCompare(t)).join(`,`)}function formatGroupForDisplay(e){let t=e.split(`,`);return t.length===1?t[0]:`(${t.join(`, `)})`}function renderGroupSection(e,t,i){let a=e.toSorted((e,t)=>e.localeCompare(t)),u=groupId(a),p=[a.length===1?`Providers for actor: ${a[0]} (${t.length} registered)`:`Providers shared by actors: ${a.join(`, `)} (${t.length} registered)`];if(t.length===0)return p.push(` (none)`,``),p;for(let e=0;e<t.length;e++){let a=t[e],y=e===t.length-1?`└──`:`├──`,x=[...i.get(a.moniker)??/* @__PURE__ */ new Set].filter(e=>e!==u).toSorted((e,t)=>e.localeCompare(t)).map(formatGroupForDisplay),w=x.length>0?` \u26A0 also in: ${x.join(`, `)}`:``,E=a.dependencies.length>0?`, deps: [${a.dependencies.join(`, `)}]`:``,D=a.count>1?` (\xD7${a.count})`:``;p.push(` ${y} ${a.moniker}${D} [impl: ${a.providerName}, scope: ${a.scope}${E}]${w}`)}return p.push(``),p}function formatProviderTree(e){let t=groupActorsBySharedRegistry(e).map(e=>({...e,key:groupId(e.actorNames)})),i=/* @__PURE__ */ new Map;for(let e of t)i.set(e.key,enumerateLocator(e.locator));let a=buildOwnerIndex(i),u=[...t].toSorted((e,t)=>{let i=e.actorNames.includes(`_root`);if(i!==t.actorNames.includes(`_root`))return i?-1:1;let a=X9.indexOf(e.actorNames[0]),u=X9.indexOf(t.actorNames[0]);return a===u?e.key.localeCompare(t.key):(a===-1?2**53-1:a)-(u===-1?2**53-1:u)}),p=[`XL1 Provider Dump`,`=================`,``];for(let e of u)p.push(...renderGroupSection(e.actorNames.toSorted((e,t)=>e.localeCompare(t)),i.get(e.key)??[],a));return p.push(...renderDuplicatesSummary(a)),p.join(`
|
|
34704
34704
|
`)}function formatStartupBanner(e,t){return formatStartupBanner$1({actors:t,title:`🚀 XL1 Node CLI`,version:e})}var lhe=`XL1_SHUTDOWN_TIMEOUT_MS`;function isCancellableProvider(e){return typeof e==`object`&&!!e&&`requestCancel`in e&&typeof e.requestCancel==`function`}function requestRuntimeProviderCancel(e,t){let i=e.locator?.context?.singletons;if(typeof i!=`object`||!i)return;let a=/* @__PURE__ */ Error(`XL1 runtime shutdown requested`);for(let e of Object.values(i))isCancellableProvider(e)?cancelProvider(e,a,t):Promise.resolve(e).then(e=>{isCancellableProvider(e)&&cancelProvider(e,a,t)},()=>{})}function cancelProvider(e,t,i){try{e.requestCancel(t)}catch(e){logInterruptError(i,`Error cancelling provider work during shutdown:`,e)}}async function handleRuntimeInterrupt(e,t,i,a={}){await handleRuntimeInterrupt$1(e,t,i,{onBeforeStop:()=>requestRuntimeProviderCancel(i,t),shutdownTimeoutEnvironmentVariable:lhe,...a.shutdownTimeoutMs!==void 0&&{shutdownTimeoutMs:a.shutdownTimeoutMs}})}function resolveRuntimeStatusRequest(e,t,i){if(t!==`/statz`)return resolveStatusProbe(e,t);if(i===void 0)return{body:{status:`not found`},statusCode:404};try{return{body:i(),statusCode:200}}catch{return{body:{status:`error`},statusCode:500}}}function sendJson(e,{body:t,statusCode:i}){e.writeHead(i,{"Content-Type":`application/json`}),e.end(JSON.stringify(t))}var HttpXl1RuntimeStatusPublisher=class{isStarted=!1;options;server;status;constructor(e,t){this.status=e,this.options=t}get listeningPort(){let e=this.server?.address();return typeof e==`object`&&e?e.port:void 0}async start(){this.isStarted=!0;let{getStats:e,host:t,logger:i,port:a}=this.options;this.status.onGlobalTransition({},(e,t)=>{this.isStarted&&i?.log(`System status: ${e} -> ${t}`)});let u=kt.createServer((t,i)=>{sendJson(i,resolveRuntimeStatusRequest(this.status,t.url??``,e))});await new Promise((e,i)=>{u.once(`error`,i),u.listen(a,t,()=>e())}),this.server=u,i?.log(`System status HTTP server running on http://${t??`localhost`}:${this.listeningPort??a}`);for(let t of[`/healthz`,`/livez`,`/readyz`,`/status`,...e===void 0?[]:[`/statz`]])i?.log(` - ${t}`)}async stop(){this.isStarted=!1;let e=this.server;this.server=void 0,e!==void 0&&await new Promise(t=>{e.close(()=>t())})}};async function stopOrchestrator(e){let t,i=!1;try{let t=await e.stop();if(t!==!1)return t}catch(e){t=e,i=!0}let a=e.shutdown?.bind(e);if(a===void 0){if(i)throw t;return!1}let u,p=!1;try{await a()}catch(e){u=e,p=!0}if(p)throw i?AggregateError([t,u],`Orchestrator stop and status-independent shutdown both failed`,{cause:t}):u;if(i)throw t}var Xl1RuntimeSession=class{locator;orchestrator;statusHttpPublisher;statusReporter;globalErrorEscalation;runtimeCleanup;runtimeSession;constructor(e){this.locator=e.locator,this.orchestrator=e.orchestrator,this.runtimeCleanup=e.runtimeCleanup,this.statusHttpPublisher=e.statusHttpPublisher,this.statusReporter=e.statusReporter,this.runtimeSession=new RuntimeSession(async()=>{let e,t=!1,attempt=async(i,a)=>{try{if(await a()===!1)throw Error(`${i} reported failure`)}catch(i){t||(e=i),t=!0}};if(await attempt(`Status reporter shutdown`,()=>this.statusReporter?.setShuttingDown(!0)),await attempt(`Status HTTP publisher shutdown`,()=>this.statusHttpPublisher?.stop()),await attempt(`Orchestrator shutdown`,async()=>await stopOrchestrator(this.orchestrator)),await attempt(`Runtime context cleanup`,()=>this.runtimeCleanup?.()),t)throw e}),this.globalErrorEscalation=new GlobalErrorEscalation({isShutdownInProgress:()=>this.statusReporter?.isShuttingDown?.()===!0,session:this,...e.globalErrorExitTimeoutMs!==void 0&&{exitTimeoutMs:e.globalErrorExitTimeoutMs}}),this.statusReporter?.onGlobalTransition?.({to:`error`},()=>{this.globalErrorEscalation.notify()}),this.statusReporter?.getGlobalStatus?.()===`error`&&this.globalErrorEscalation.notify()}get state(){return this.runtimeSession.state}get stopError(){return this.runtimeSession.stopError}activateGlobalErrorHandling(e){return this.globalErrorEscalation.activate(e)}armGlobalErrorHandling(e){this.globalErrorEscalation.arm(e)}bindInterrupt(e,t){this.runtimeSession.bindInterrupt(e,t)}requestExit(e,t){return this.runtimeSession.requestExit(e,t)}stop(){let e=this.runtimeSession.stop();return e.then(()=>this.globalErrorEscalation.clearExitTimer(),()=>this.globalErrorEscalation.clearExitTimer()),e}},uhe=9099,Xl1RuntimeExitRequest=class extends Error{exitCode;constructor(e){super(`XL1 runtime requested exit with code ${e}`),this.exitCode=e}};async function stopXl1RuntimeContext(e){let t,i=!1,attempt=async e=>{try{await e()}catch(e){i||(t=e),i=!0}},a=/* @__PURE__ */ new Set,u=[e.meterProvider,e.traceProvider];for(let e of u)isShutdownResource(e)&&a.add(e);for(let t of Object.values(e.singletons).toReversed())await attempt(async()=>await stopUniqueResource(t,a));let p=e.runtimeResourceOwner;if(p===void 0){let t=e.connectionHandles;for(let i of Object.keys(e.config.connections??{}))await attempt(async()=>await stopUniqueResource(t?.get(i),a)),await attempt(async()=>await stopUniqueResource(t?.get(`evm-rpc:${i}`),a));let i=/* @__PURE__ */ new Set;for(let e of u)isShutdownResource(e)&&!i.has(e)&&(i.add(e),await attempt(async()=>{await e.shutdown()}))}else await attempt(async()=>{await p.cleanup()});if(i)throw t}var dhe={assembleRunConfig,buildRunLocator,contextFromConfigWithoutLocator,createOrchestrator:async e=>await Orchestrator.create({logger:e}),createStatusHttpPublisher:(e,t,i,a)=>new HttpXl1RuntimeStatusPublisher(e,{...a!==void 0&&{getStats:a},logger:t,port:i}),detectDerivationPathCollisions,formatProviderTree,formatStartupBanner,formatWalletReport,getActorSliceFromRun,handleRuntimeInterrupt,initLogger:e=>initDefaultLogger(e.log),initializeResolvedWalletReport,installRuntimeInterruptController,splitRunConfig,stopRuntimeContext:stopXl1RuntimeContext};function defaultScrapePortForActors(e){let t=e[0];return pU[t===`rewardRedemption`?`rewardRedemptionApi`:t]??pU.producer}function isAbortError(e){return e instanceof Error&&`code`in e&&e.code===`ABORT_ERR`}async function promptForInsecureGenesisConfirmation(e,t){if(!e.io.isInteractive)t.warn(`Insecure genesis reward wallet is active. Interactive confirmation skipped because this session is not a TTY.`);else try{await e.io.question(`Insecure genesis reward wallet is active. Hit RETURN to continue.`)}catch(e){throw isAbortError(e)?(t.info(`
|
|
34705
34705
|
Shutdown requested. Exiting.`),new Xl1RuntimeExitRequest(0)):e}}async function prepareXl1Runtime(e,t){let{actors:i,configuration:a,fullVersion:u,version:p}=e,y=[...i],x=y.map(e=>t.getActorSliceFromRun(a,e)),{process:w}=t.splitRunConfig(a),E=t.assembleRunConfig(w,x,a.mnemonic),D=t.initLogger(a);D.info(t.formatStartupBanner(u,y));let A=t.detectDerivationPathCollisions(y,E);if(A)throw A;let N=await t.initializeResolvedWalletReport(y,E);D.info(t.formatWalletReport(N));let P=y.length===1?`xl1-${y[0]}`:`xl1-cli`;return{context:await t.contextFromConfigWithoutLocator(E,D,P,p,defaultScrapePortForActors(y)),fullConfig:E,logger:D,requestedActors:y}}function logFailedRuntimeCleanup(e,t){try{e.error(`Error cleaning up failed XL1 runtime acquisition:`,t)}catch{}}async function cleanupFailedRuntimeAcquisition({context:e,dependencies:t,logger:i,orchestrator:a,session:u,statusHttpPublisher:p}){let y=u===void 0?[()=>p?.stop(),()=>a?.shutdown?.()??a?.stop(),async()=>await t.stopRuntimeContext(e)]:[u.stop.bind(u)];for(let e of y)try{await e()}catch(e){logFailedRuntimeCleanup(i,e)}}async function createXl1RuntimeSession({actors:e,configuration:t,fullVersion:i,host:a,isDumpingProviders:u,isSkippingInsecureConfirm:p,version:y},x={}){let w={...dhe,...x},E=w.installRuntimeInterruptController({host:a});try{return await acquireXl1RuntimeSession({actors:e,configuration:t,dependencies:w,fullVersion:i,host:a,interruptController:E,isDumpingProviders:u,isSkippingInsecureConfirm:p,version:y})}finally{E.isSessionAdopted||E.dispose()}}async function acquireXl1RuntimeSession({actors:e,configuration:t,dependencies:i,fullVersion:a,host:u,interruptController:p,isDumpingProviders:y,isSkippingInsecureConfirm:x,version:w}){let throwIfInterrupted=()=>{if(p.isInterrupted)throw new Xl1RuntimeExitRequest(130)};ensureDefaultInstalledActors();let{context:E,fullConfig:D,logger:A,requestedActors:N}=await prepareXl1Runtime({actors:e,configuration:t,fullVersion:a,version:w},i),P,F,I;try{throwIfInterrupted(),x&&A.warn(`Insecure genesis reward wallet is active. Interactive confirmation skipped via --skip-insecure-confirm.`);let e=x?void 0:async()=>await promptForInsecureGenesisConfirmation(u,A),a=await i.buildRunLocator(E,D,{installedActors:ensureDefaultInstalledActors(),onInsecureGenesisConfirm:e});if(throwIfInterrupted(),y)throw u.io.log(i.formatProviderTree(Object.fromEntries(N.map(e=>[e,a])))),new Xl1RuntimeExitRequest(0);P=await i.createOrchestrator(A),throwIfInterrupted();let w=t.healthCheckPort??uhe,L=E.statusReporter,B=N.includes(`producer`)?getOrCreateProducerStats(a.context):void 0;I=w>0&&L!==void 0?i.createStatusHttpPublisher(L,A,w,B===void 0?void 0:()=>B.snapshot()):void 0;let ee=new Xl1RuntimeSession({locator:a,orchestrator:P,runtimeCleanup:async()=>await i.stopRuntimeContext(a.context),statusHttpPublisher:I,statusReporter:L});return F=ee,ee.armGlobalErrorHandling(u),await I?.start(),throwIfInterrupted(),ee.bindInterrupt(u,async()=>{await i.handleRuntimeInterrupt(u,A,ee)}),p.adoptSession(),ee}catch(e){throw await cleanupFailedRuntimeAcquisition({context:E,dependencies:i,logger:A,orchestrator:P,session:F,statusHttpPublisher:I}),e instanceof Xl1RuntimeExitRequest&&exitProcess(u,e.exitCode),e}}var fhe=`\x1B[38;2;128;128;128m\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\x1B[0m\x1B[38;2;118;111;144m_\x1B[0m
|
|
34706
34706
|
\x1B[38;2;128;128;128m\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\x1B[0m\x1B[38;2;72;32;223m╠\x1B[0m\x1B[38;2;66;21;234m╠\x1B[0m
|
|
@@ -34725,4 +34725,4 @@ ${fhe}
|
|
|
34725
34725
|
Run various components of the XL1 ecosystem.
|
|
34726
34726
|
|
|
34727
34727
|
Usage:
|
|
34728
|
-
$0 <command> [options]`).parserConfiguration({"dot-notation":!0,"parse-numbers":!1,"populate--":!0,"strip-aliased":!0}).config(p).scriptName(`xl1`).middleware(async e=>{await configMiddleware(e,e=>{u.configuration=e},a),u.isSkippingInsecureConfirm=!!e[`skip-insecure-confirm`],u.isDumpingProviders=!!e[`dump-providers`]}).options(optionsFromGlobalZodRegistry()).wrap(a.io.columns??null);y&&(w=w.default(`extends`,x));for(let e of t)w=w.command(e);return w=rejectUnknownCommands(w,t),w.options({config:{type:`string`,description:`Path to a config file to use instead of the default search.`,alias:`c`},mnemonic:{type:`string`,description:`Shared root mnemonic used by actors that do not define their own mnemonic.`},"dump-config":{type:`boolean`,description:`Just process the configuration and print the resolved config to stdout, then exit. Secrets are redacted unless --with-secrets is also passed.`,default:!1},"with-secrets":{type:`boolean`,description:`When used with --dump-config, print raw secret values (mnemonic, private keys, passwords) instead of "[REDACTED]". Use only on a developer machine.`,default:!1},"dump-providers":{type:`boolean`,description:`Run the normal command flow up to provider locator construction, print the per-actor provider tree (with duplicate detection), then exit.`,default:!1},"skip-insecure-confirm":{type:`boolean`,description:`Skip the interactive RETURN confirmation when the built-in dev mnemonic / insecure genesis reward wallet is active.`,default:!1}}).help().alias(`help`,`h`).version(i)}var Z9=isDefined$1(`5.7.
|
|
34728
|
+
$0 <command> [options]`).parserConfiguration({"dot-notation":!0,"parse-numbers":!1,"populate--":!0,"strip-aliased":!0}).config(p).scriptName(`xl1`).middleware(async e=>{await configMiddleware(e,e=>{u.configuration=e},a),u.isSkippingInsecureConfirm=!!e[`skip-insecure-confirm`],u.isDumpingProviders=!!e[`dump-providers`]}).options(optionsFromGlobalZodRegistry()).wrap(a.io.columns??null);y&&(w=w.default(`extends`,x));for(let e of t)w=w.command(e);return w=rejectUnknownCommands(w,t),w.options({config:{type:`string`,description:`Path to a config file to use instead of the default search.`,alias:`c`},mnemonic:{type:`string`,description:`Shared root mnemonic used by actors that do not define their own mnemonic.`},"dump-config":{type:`boolean`,description:`Just process the configuration and print the resolved config to stdout, then exit. Secrets are redacted unless --with-secrets is also passed.`,default:!1},"with-secrets":{type:`boolean`,description:`When used with --dump-config, print raw secret values (mnemonic, private keys, passwords) instead of "[REDACTED]". Use only on a developer machine.`,default:!1},"dump-providers":{type:`boolean`,description:`Run the normal command flow up to provider locator construction, print the per-actor provider tree (with duplicate detection), then exit.`,default:!1},"skip-insecure-confirm":{type:`boolean`,description:`Skip the interactive RETURN confirmation when the built-in dev mnemonic / insecure genesis reward wallet is active.`,default:!1}}).help().alias(`help`,`h`).version(i)}var Z9=isDefined$1(`5.7.3`)?`5.7.3`:`unknown`,Q9=isDefined$1(`fc527ea8c`)?`fc527ea8c`:``,$9=Q9.length>0?`${Z9} (${Q9})`:Z9,phe=createSysExitFailureMapper(),mhe={configureYargs:configureXl1Yargs,createCommands:e=>ohe.createCommands(e),createRuntimeSession:createXl1RuntimeSession,runYargsApplication};async function runCLI(e=X5,t={}){ensureDefaultInstalledActors();let i={...mhe,...t},a={isDumpingProviders:!1,isSkippingInsecureConfirm:!1},u,p={get argv(){return e.argv},get environment(){return e.environment},exit(t){let i=u;i===void 0?e.exit(t):i.requestExit(e,t)},get io(){return e.io},get isDevelopment(){return e.isDevelopment},onInterrupt:t=>e.onInterrupt(t)};function getConfiguration(){if(a.configuration===void 0)throw Error(`CLI configuration is unavailable before middleware runs.`);return a.configuration}async function getLocatorFromRuntimeConfig(t,p){let y=await i.createRuntimeSession({actors:t,configuration:p,fullVersion:$9,host:e,isDumpingProviders:a.isDumpingProviders,isSkippingInsecureConfirm:a.isSkippingInsecureConfirm,version:Z9});return u=y,y.armGlobalErrorHandling(e),{locator:y.locator,orchestrator:y.orchestrator}}let y={getConfiguration,getLocatorFromConfig:getLocatorFromRuntimeConfig,host:p},x=i.createCommands(y);await i.runYargsApplication({configure:e=>i.configureYargs(e,{commands:x,fullVersion:$9,host:p,state:a}),host:p,mapFailureToExitCode:phe,onFailure:async()=>await u?.stop()}),await u?.activateGlobalErrorHandling(e)}async function start(e=X5){(0,nhe.config)({quiet:!0}),await runCLI(e)}async function runCliMain(e=X5){await runProcessApplication({application:start,host:e})}function installGlobalHttpCache(){let e=new At({allowH2:!1}).compose(Mt.cache({store:new jt.MemoryCacheStore({maxCount:1e3,maxEntrySize:5242880,maxSize:0x6400000}),type:`shared`}));return Nt(e),e}installGlobalHttpCache(),await runCliMain();export{};
|