@visa/cli 5.0.0-rc.406 → 5.0.0-rc.408

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.
@@ -0,0 +1,125 @@
1
+ "use strict";var Fse=Object.create;var I3=Object.defineProperty;var $se=Object.getOwnPropertyDescriptor;var Jse=Object.getOwnPropertyNames;var Vse=Object.getPrototypeOf,Gse=Object.prototype.hasOwnProperty;var g=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Kse=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Jse(t))!Gse.call(e,i)&&i!==r&&I3(e,i,{get:()=>t[i],enumerable:!(n=$se(t,i))||n.enumerable});return e};var se=(e,t,r)=>(r=e!=null?Fse(Vse(e)):{},Kse(t||!e||!e.__esModule?I3(r,"default",{value:e,enumerable:!0}):r,e));var T3=g(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.PAYMENT_APPROVAL_PATH_PREFIX=void 0;Jc.paymentApprovalPath=P3;Jc.paymentApprovalUrl=Wse;Jc.PAYMENT_APPROVAL_PATH_PREFIX="/agent/enroll/approvals/";function P3(e){let t=e.rail==="wallet"?e.approvalId:e.rail==="hosted"?e.draftId:e.attemptId,r=new URLSearchParams({rail:e.rail});return e.rail==="card"&&(r.set("agent",e.agentId),r.set("purchase",e.purchaseId),r.set("runtime",e.runtimeId)),`${Jc.PAYMENT_APPROVAL_PATH_PREFIX}${encodeURIComponent(t)}?${r.toString()}`}function Wse(e,t){return new URL(P3(t),e).toString()}});var fB=g((oQe,kae)=>{kae.exports={name:"@visa/cli",version:"5.0.0-rc.408",description:"Visa CLI runtime for stable agent identity and separately authorized payment capabilities",bin:{"visa-cli":"./bin/visa-cli.js",visa:"./bin/visa-cli.js","visa-runtime-converge":"./dist/managed-runtime/resolve-and-update.mjs"},scripts:{"sync:server-json":"node scripts/sync-server-json.mjs","check:server-json":"node scripts/sync-server-json.mjs --check",prebuild:"node scripts/sync-server-json.mjs",build:"tsc --noEmit && node esbuild.config.js",prepack:"node scripts/sync-server-json.mjs --check",dev:"tsc --watch",pretest:"pnpm build",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:packed":"node scripts/packed-cli-smoke.mjs","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","coinbase:onramp":"pnpm exec tsx tests/e2e/coinbase-onramp-harness/run.ts","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/ext-apps":"1.7.5","@modelcontextprotocol/server":"2.0.0","@ucp-js/sdk":"0.4.4",commander:"^12.1.0",punycode:"^2.3.1",zod:"^3.25.76"},devDependencies:{"@types/express":"^5.0.0","@types/jest":"^30.0.0","@types/node":"^26.1.0","@typescript-eslint/eslint-plugin":"^8.68.0","@typescript-eslint/parser":"^8.68.0","@visa-cli/tools":"workspace:*","@visa/crypto":"workspace:*","@visa/financial-core":"workspace:*","@visa/identity":"workspace:*","@visa/money":"workspace:*","@visa/observability":"workspace:*","@visa/shared":"workspace:*","@visa/wallet":"workspace:*","@visa/wallet-tools":"workspace:*",esbuild:"^0.28.1",eslint:"^10.0.2",express:"^4.21.0",jest:"^30.3.0",prettier:"^3.9.6","ts-jest":"^29.4.12",typescript:"^5.7.0",viem:"^2.56.0"},engines:{node:">=20.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","server.json","README.md"]}});var D0=g((lQe,HU)=>{"use strict";var zae=Object.create,x0=Object.defineProperty,Yae=Object.getOwnPropertyDescriptor,UB=Object.getOwnPropertyNames,Xae=Object.getPrototypeOf,Zae=Object.prototype.hasOwnProperty,Qae=(e,t)=>function(){try{return t||(0,e[UB(e)[0]])((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},ece=(e,t)=>{for(var r in t)x0(e,r,{get:t[r],enumerable:!0})},HB=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of UB(t))!Zae.call(e,i)&&i!==r&&x0(e,i,{get:()=>t[i],enumerable:!(n=Yae(t,i))||n.enumerable});return e},FB=(e,t,r)=>(r=e!=null?zae(Xae(e)):{},HB(t||!e||!e.__esModule?x0(r,"default",{value:e,enumerable:!0}):r,e)),tce=e=>HB(x0({},"__esModule",{value:!0}),e),rce=Qae({"../shared/dist/canonical-contract.js"(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.CanonicalJsonError=e.CANONICAL_OPAQUE_ID_MAX_BYTES=e.CANONICAL_OPAQUE_ID_RE=e.CANONICAL_OPAQUE_ID_PATTERN=void 0,e.utf8ByteLength=n,e.isCanonicalText=i,e.compareCanonicalKeys=o,e.isCanonicalOpaqueId=s,e.assertCanonicalOpaqueId=a,e.canonicalJsonExact=d,e.CANONICAL_OPAQUE_ID_PATTERN="^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$",e.CANONICAL_OPAQUE_ID_RE=new RegExp(e.CANONICAL_OPAQUE_ID_PATTERN),e.CANONICAL_OPAQUE_ID_MAX_BYTES=128;var t=/[\u0000-\u001f\u007f\u2028\u2029]/,r=new TextEncoder;function n(l){return r.encode(l).length}function i(l,m){return typeof l=="string"&&l.length>0&&n(l)<=m&&l.trim()===l&&l.normalize("NFC")===l&&!t.test(l)}function o(l,m){let p=r.encode(l),h=r.encode(m),y=Math.min(p.length,h.length);for(let b=0;b<y;b+=1)if(p[b]!==h[b])return p[b]-h[b];return p.length-h.length}function s(l){return typeof l=="string"&&n(l)<=e.CANONICAL_OPAQUE_ID_MAX_BYTES&&e.CANONICAL_OPAQUE_ID_RE.test(l)}function a(l,m="value"){if(!s(l))throw new Error(`${m} must be a canonical opaque id (max 128 ASCII bytes)`)}var c=/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,u=class extends Error{constructor(l){super(l),this.name="CanonicalJsonError"}};e.CanonicalJsonError=u;function d(l,m=0){if(m>16)throw new u("nesting is deeper than 16");if(l===null||typeof l=="boolean")return JSON.stringify(l);if(typeof l=="string"){if(c.test(l))throw new u("text is not valid Unicode");return JSON.stringify(l)}if(typeof l=="number"){if(!Number.isSafeInteger(l)||Object.is(l,-0))throw new u("numbers must be whole and at most 2^53 - 1; put amounts and decimals in strings");return JSON.stringify(l)}if(Array.isArray(l)){if(l.length>1024)throw new u("an array has more than 1024 items");return`[${l.map(h=>d(h,m+1)).join(",")}]`}if(typeof l!="object"||Object.getPrototypeOf(l)!==Object.prototype)throw new u("only JSON objects, arrays, strings, whole numbers and booleans");let p=Object.keys(l);if(p.length>512)throw new u("an object has more than 512 keys");for(let h of p)if(!i(h,128))throw new u("keys must be non-empty trimmed NFC text of at most 128 bytes");return`{${p.sort(o).map(h=>`${JSON.stringify(h)}:${d(l[h],m+1)}`).join(",")}}`}}}),$B={};ece($B,{AGENT_AUTHORITY_VALUATION_POLICY:()=>v0,AGENT_AUTHORITY_VERSION:()=>zo,AGENT_AUTHORIZATION_SCOPES:()=>tu,AGENT_BUDGET_EPOCH_MODES:()=>bU,AGENT_CAPABILITY_ATTACH_CAPABILITIES:()=>RU,AGENT_CHANNEL_ASSURANCES:()=>SU,AGENT_CHANNEL_KINDS:()=>wU,AGENT_CHANNEL_STATUSES:()=>vU,AGENT_EXECUTION_READINESS_REASONS:()=>lue,AGENT_HANDOFF_AUTHORITIES:()=>Oue,AGENT_HANDOFF_COMPOUND_AUTHORITY:()=>qI,AGENT_KEY_CUSTODIES:()=>fue,AGENT_KEY_STATUSES:()=>pue,AGENT_PAIRING_CODE_ALPHABET:()=>ml,AGENT_PAIRING_CODE_LENGTH:()=>um,AGENT_PAIRING_PROTOCOL_VERSION:()=>Cue,AGENT_PAIRING_PROTOCOL_VERSION_V2:()=>P0,AGENT_PAYMENT_MODE_NAMES:()=>uue,AGENT_PAYMENT_RAILS:()=>bI,AGENT_PAYMENT_SURFACES:()=>_I,DOMAINS:()=>zce,USD_MICROS_PER_CENT:()=>CI,VIC_PROCESSOR_ACTIONS:()=>cue,WALLET_GRANT_SCOPE:()=>EU,agentAuthorityGrantHash:()=>Tue,agentMailCredentialClaimMessageV2:()=>ode,authorizationScopeFacts:()=>Aue,base64ToBytes:()=>pU,base64UrlToBytes:()=>N0,bytesToBase64:()=>fU,bytesToBase64Url:()=>Yo,bytesToHex:()=>lU,canonicalAgentAuthorityGrant:()=>jI,canonicalAgentChannelDescriptor:()=>Pue,canonicalFormAgent:()=>Yce,canonicalPairingDeliveryArtifactV2:()=>UU,canonicalPairingTerms:()=>qU,canonicalPairingTermsV2:()=>UI,canonicalPayWithinBudget:()=>xU,canonicalSpendAuthorizationIntent:()=>MI,centsToUsdMicros:()=>vue,computeJkt:()=>yU,concatBytes:()=>RI,defaultPayWithinBudget:()=>due,extractEd25519Seed:()=>aue,formatPairingCode:()=>q0,generateKeyPair:()=>$ce,generateSeed:()=>uU,getPublicKey:()=>C0,grantPaymentRails:()=>NI,handoffAuthorityCapabilities:()=>Rue,hexToBytes:()=>OI,isCanonicalBase64Url32:()=>On,isValidPairingCode:()=>jU,jwkToKeyPair:()=>eue,jwkToPublicKey:()=>Qce,jwkToSeed:()=>hU,keyPairFromSeed:()=>dU,keyRotationClaimHashV2:()=>ide,keyRotationClaimMessageV2:()=>BU,normalizePairingCode:()=>M0,pairingActivationMessage:()=>tde,pairingActivationMessageV2:()=>nde,pairingArtifactHash:()=>ade,pairingClaimHashV2:()=>rde,pairingClaimMessage:()=>ede,pairingClaimMessageV2:()=>LU,pairingClaimTokenHash:()=>MU,pairingCodeFromClaimToken:()=>Xue,pairingCodeHash:()=>zue,pairingConfirmationCode:()=>Zue,pairingDeliveryArtifactV2Hash:()=>sde,pairingInstrumentCommitment:()=>Jue,pairingSha256:()=>to,pairingTermsHash:()=>Que,pairingTermsV2Hash:()=>DU,pairingVerifierChallenge:()=>Kue,pkcs8ToSeed:()=>oue,publicKeyToJwk:()=>Zce,publicKeyToSpki:()=>iue,randomPairingClaimToken:()=>Yue,randomPairingCode:()=>Wue,randomPairingId:()=>Vue,randomPairingVerifier:()=>Gue,seedToJwk:()=>Xce,seedToPkcs8:()=>nue,sign:()=>Jce,signAsync:()=>Gce,spendAuthorizationIntentHash:()=>OU,spkiToPublicKey:()=>sue,subwayAgentMsgV1:()=>mU,usdcAtomicToUsdMicros:()=>Sue,verify:()=>Vce,verifyAsync:()=>Kce,walletAuthorizationRequestHash:()=>xue});HU.exports=tce($B);var O0=Object.freeze,pl=0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,S0=0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,E0=0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,gI=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,hI=0x6666666666666666666666666666666666666666666666666666666666666658n,w0=pl-1n,nce=O0({p:pl,n:S0,h:8n,a:w0,d:E0,Gx:gI,Gy:hI}),fa=32,vB=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&e.BYTES_PER_ELEMENT===1,xn=(e,t,r="")=>{if(vB(e)&&(t===void 0||e.length===t))return e;let n=vB(e),i=t!==void 0?` of length ${t}`:"",o=n?`length=${e.length}`:`type=${typeof e}`,s=(r?`"${r}" `:"")+"expected Uint8Array"+i+", got "+o;throw n?new RangeError(s):new TypeError(s)},R0=(e,t="",r)=>Uint8Array.from(xn(e,r,t)),JB=(e,t)=>e.toString(16).padStart(t,"0"),vI=e=>{let t="";for(let r of xn(e))t+=JB(r,2);return t},SI=e=>{let t="hex invalid";if(typeof e!="string")throw new TypeError(t);if(e.length%2||!/^[\da-f]*$/i.test(e))throw new RangeError(t);let r=new Uint8Array(e.length/2);for(let n=0,i=0;n<r.length;n++,i+=2){let o=e.charCodeAt(i),s=e.charCodeAt(i+1);r[n]=((o&15)+(o>>6)*9)*16+(s&15)+(s>>6)*9}return r},iu=(...e)=>{let t=0;for(let i of e)t+=xn(i).length;let r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return r},VB=(e=fa)=>{let t=globalThis?.crypto;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined, consider polyfill");return t.getRandomValues(new Uint8Array(e))},Xc=(e,t,r,n="bad number: out of range")=>{if(typeof e!="bigint")throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},it=(e,t=pl)=>(e%=t)>=0n?e:t+e,SB=(1n<<255n)-1n,z=e=>{if(e<0n)throw new RangeError("negative coordinate");let t=(e>>255n)*19n+(e&SB);return t=(t>>255n)*19n+(t&SB),t%pl},GB=e=>it(e,S0),KB=(e,t)=>{if(e===0n)throw new Error("invert: expected non-zero number");if(t<=1n)throw new Error("invert: expected modulus > 1, got "+t);let r=it(e,t),n=t,i=0n,o=1n;for(;r!==0n;){let a=n/r,c=n-r*a,u=i-o*a;n=r,r=c,i=o,o=u}if(n!==1n)throw new Error("invert: does not exist");return it(i,t)},WB=e=>{let t=nU[e];if(typeof t!="function")throw new Error("hashes."+e+" not set");return t},AI=(e,...t)=>xn(WB(e)(iu(...t)),64,"digest"),II=async(e,...t)=>xn(await WB(e)(iu(...t)),64,"digest"),pI=e=>{if(e instanceof ou)return e;throw new TypeError("Point expected")},zB=2n**256n,ou=class Zc{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=zB;this.X=Xc(t,0n,o),this.Y=Xc(r,0n,o),this.Z=Xc(n,1n,o),this.T=Xc(i,0n,o),O0(this)}static CURVE(){return nce}static fromAffine(t){return new Zc(t.x,t.y,1n,z(t.x*t.y))}static fromBytes(t,r=!1){let n=R0(t,"point",fa),i=n[31];n[31]=i&-129;let o=PI(n);r||Xc(o,0n,pl);let s=z(o*o),a=it(s-1n),c=z(E0*s+1n),{isValid:u,value:d}=oce(a,c);if(!u)throw new Error("bad point: y not sqrt");let l=!!(i&128);if(!r&&d===0n&&l)throw new Error("bad point: x==0, isLastByteOdd");return l!==!!(d&1n)&&(d=it(-d)),new Zc(d,o,1n,z(d*o))}static fromHex(t,r){return Zc.fromBytes(SI(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=w0,r=E0,n=this;if(n.is0())throw new Error("bad point: ZERO");let{X:i,Y:o,Z:s,T:a}=n,c=z(i*i),u=z(o*o),d=z(s*s),l=z(d*d),m=z(c*t),p=z(d*(m+u)),h=it(l+z(r*z(c*u)));if(p!==h)throw new Error("bad point: equation left != right (1)");let y=z(i*o),b=z(s*a);if(y!==b)throw new Error("bad point: equation left != right (2)");return this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=pI(t);return z(r*a)===z(o*i)&&z(n*a)===z(s*i)}is0(){return this.equals(Qc)}negate(){return new Zc(it(-this.X),this.Y,this.Z,it(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=w0,o=z(t*t),s=z(r*r),a=z(2n*n*n),c=z(i*o),u=it(t+r),d=it(z(u*u)-o-s),l=it(c+s),m=it(l-a),p=it(c-s),h=z(d*m),y=z(l*p),b=z(d*p),v=z(m*l);return new Zc(h,y,v,b)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=pI(t),d=w0,l=E0,m=z(r*s),p=z(n*a),h=z(z(o*l)*u),y=z(i*c),b=it(z(it(r+n)*it(s+a))-m-p),v=it(y-h),A=it(y+h),E=it(p-z(d*m)),S=z(b*v),I=z(A*E),T=z(b*E),x=z(v*A);return new Zc(S,I,x,T)}subtract(t){return this.add(pI(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(Xc(t,1n,S0),!r&&this.is0()))return Qc;if(t===1n)return this;if(this.equals(pa))return gce(t).p;let n=Qc,i=pa,o=this;for(let s=0;r?s<256:t>0n;s++)t&1n?n=n.add(o):r&&(i=i.add(o)),o=o.double(),t>>=1n;return n}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:r,Z:n}=this;if(this.equals(Qc))return{x:0n,y:1n};let i=KB(n,pl);if(z(n*i)!==1n)throw new Error("invalid inverse");return{x:z(t*i),y:z(r*i)}}toBytes(){let{x:t,y:r}=this.toAffine(),n=YB(r);return n[31]|=t&1n?128:0,n}toHex(){return vI(this.toBytes())}clearCofactor(){return this.multiply(8n,!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return this.multiply(S0/2n,!1).double().add(this).is0()}},pa=new ou(gI,hI,1n,it(gI*hI)),Qc=new ou(0n,1n,1n,0n);ou.BASE=pa;ou.ZERO=Qc;var YB=e=>SI(JB(Xc(e,0n,zB),64)).reverse(),PI=e=>BigInt("0x"+vI(Uint8Array.from(xn(e)).reverse())),Xi=(e,t)=>{let r=e;for(;t-- >0;)r=z(r*r);return r},ice=e=>{let t=z(e*e),r=z(t*e),n=z(Xi(r,2)*r),i=z(Xi(n,1)*e),o=z(Xi(i,5)*i),s=z(Xi(o,10)*o),a=z(Xi(s,20)*s),c=z(Xi(a,40)*a),u=z(Xi(c,80)*c),d=z(Xi(u,80)*c),l=z(Xi(d,10)*o);return z(Xi(l,2)*e)},AB=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,oce=(e,t)=>{let r=z(t*z(t*t)),n=z(z(r*r)*t),i=ice(z(e*n)),o=z(e*z(r*i)),s=z(t*z(o*o)),a=o,c=z(o*AB),u=s===e,d=s===it(-e),l=s===it(-e*AB);return u&&(o=a),(d||l)&&(o=c),(it(o)&1n)===1n&&(o=it(-o)),{isValid:u||d,value:o}},A0=e=>GB(PI(e)),XB=e=>{let t=R0(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32),i=A0(r),o=pa.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},ZB=e=>II("sha512Async",xn(e,fa,"secretKey")).then(XB),TI=e=>XB(AI("sha512",xn(e,fa,"secretKey"))),sce=e=>TI(e).pointBytes,QB=async e=>e[1](await II("sha512Async",e[0])),eU=e=>e[1](AI("sha512",e[0])),tU=(e,t,r)=>{let{pointBytes:n,scalar:i}=e,o=A0(t),s=pa.multiply(o).toBytes();return[iu(s,n,r),u=>{let d=GB(o+A0(u)*i);return xn(iu(s,YB(d)),64)}]},ace=async(e,t)=>{let r=R0(e,"message"),n=await ZB(t);return QB(tU(n,await II("sha512Async",n.prefix,r),r))},cce=(e,t)=>{let r=R0(e,"message"),n=TI(t);return eU(tU(n,AI("sha512",n.prefix,r),r))},uce=e=>{if(e===null||typeof e!="object")throw new TypeError("expected valid options object");return e.zip215??!0},rU=(e,t,r,n)=>{e=xn(e,64,"signature"),t=xn(t,void 0,"message"),r=xn(r,fa,"publicKey");let i=uce(n),o=e.subarray(0,fa),s=PI(e.subarray(fa,64)),a,c,u,d=Uint8Array.of(),l=!1;try{a=ou.fromBytes(r,i),c=ou.fromBytes(o,i),u=pa.multiply(s,!1),d=iu(o,r,t),l=!0}catch{}return[d,p=>{if(!l||!i&&a.isSmallOrder())return!1;let h=A0(p);return c.add(a.multiply(h,!1)).subtract(u).clearCofactor().is0()}]},dce=async(e,t,r,n={})=>QB(rU(e,t,r,n)),lce=(e,t,r,n={})=>eU(rU(e,t,r,n)),xI=O0({bytesToHex:vI,hexToBytes:SI,concatBytes:iu,mod:it,invert:KB,randomBytes:VB}),nU={sha512Async:async e=>{let t=globalThis?.crypto?.subtle;if(!t)throw new Error("crypto.subtle must be defined, consider polyfill");return new Uint8Array(await t.digest("SHA-512",iu(e)))},sha512:void 0},fce=e=>xn(e===void 0?VB():e,fa,"seed"),pce=O0({getExtendedPublicKeyAsync:ZB,getExtendedPublicKey:TI,randomSecretKey:fce}),mce=()=>{let e=[],t=pa,r;for(let n=0;n<33;n++){r=t,e.push(r);for(let i=1;i<128;i++)r=r.add(t),e.push(r);t=r.double()}return e},IB=void 0,PB=(e,t)=>{let r=t.negate();return e?r:t},gce=e=>{let t=IB||(IB=mce()),r=Qc,n=pa;for(let i=0;i<33;i++){let o=Number(e&255n);e>>=8n,o>128&&(o-=256,e+=1n);let s=i*128,a=s+Math.abs(o)-1,c=i%2!==0,u=o<0;o===0?n=n.add(PB(c,t[s])):r=r.add(PB(u,t[a]))}if(e!==0n)throw new Error("invalid wnaf");return{p:r,f:n}},y0=BigInt(2**32-1),TB=BigInt(32);function hce(e,t=!1){return t?{h:Number(e&y0),l:Number(e>>TB&y0)}:{h:Number(e>>TB&y0)|0,l:Number(e&y0)|0}}function yce(e,t=!1){let r=e.length,n=new Uint32Array(r),i=new Uint32Array(r);for(let o=0;o<r;o++){let{h:s,l:a}=hce(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}var _ce=e=>e/2**32|0,bce=e=>e>>>0;function Ece(e,t,r,n){let i=_ce(r),o=bce(r);e.setUint32(t,n?o:i,n),e.setUint32(t+4,n?i:o,n)}var xB=(e,t,r)=>e>>>r,OB=(e,t,r)=>e<<32-r|t>>>r,dl=(e,t,r)=>e>>>r|t<<32-r,ll=(e,t,r)=>e<<32-r|t>>>r,_0=(e,t,r)=>e<<64-r|t>>>r-32,b0=(e,t,r)=>e>>>r-32|t<<64-r;function Wo(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}var wce=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),vce=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,Sce=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Ace=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,Ice=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),Pce=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0;function RB(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var yI=e=>e?`"${e}" `:"";function Tce(e,t=""){if(typeof e!="number")throw new TypeError(yI(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(yI(t)+"expected integer >= 0, got "+e);return e}function iU(e,t,r=""){if(RB(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Tce(t,"length");let n=RB(e),i=t!==void 0?` of length ${t}`:"",o=n?`length=${e.length}`:`type=${typeof e}`,s=yI(r)+"expected Uint8Array"+i+", got "+o;throw n?new RangeError(s):new TypeError(s)}var xce=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},CB=(e,t)=>{xce(e,t);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function NB(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function Oce(e,t){iU(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw new RangeError('"output" expected length >= '+r)}function I0(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function mI(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Zi(e,t){return e<<32-t|e>>>t}function Rce(e,t,r="opts"){return CB(e,"defaults"),t!==void 0&&CB(t,r),Object.assign(Object.create(null),e,t)}function oU(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=Rce({},t,"info");let r=(i,o)=>e(o).update(i).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=i=>e(i),Object.assign(r,t),Object.freeze(r)}var sU=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Cce(e,t,r){return e&t^~e&r}function Nce(e,t,r){return e&t^e&r^t&r}var aU=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=mI(this.buffer)}update(e){NB(this),iU(e);let{view:t,buffer:r,blockLen:n}=this,i=e.length,o=!1;for(let s=0;s<i;){let a=Math.min(n-this.pos,i-s);if(a===n){let c=mI(e);for(;n<=i-s;s+=n)this.process(c,s);o=!0;continue}r.set(s===0&&a===i?e:e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===n&&(this.process(t,0),this.pos=0,o=!0)}return this.length+=e.length,o&&this.roundClean(),this}digestInto(e){NB(this),Oce(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,t.fill(0,o),this.padOffset>n-o&&(this.process(r,0),t.fill(0)),Ece(r,n-8,this.length*8,i),this.process(r,0),this.roundClean();let s=e===t?r:mI(e),a=this.outputLen,c=a/4,u=this.get();if(a%4||c>u.length)throw new Error("invalid outputLen");for(let d=0;d<c;d++)s.setUint32(4*d,u[d],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:n,destroyed:i,pos:o}=this;return e.destroyed=i,e.finished=n,e.length=r,e.pos=o,o&&e.buffer.set(t),e}clone(){return this._cloneInto()}},kce=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),jce=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Mce=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ua=new Uint32Array(64),qce=class extends aU{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:r,D:n,E:i,F:o,G:s,H:a}=this;return[e,t,r,n,i,o,s,a]}set(e,t,r,n,i,o,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=s|0,this.H=a|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let d=0;d<16;d++,t+=4)ua[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let l=ua[d-15],m=ua[d-2],p=Zi(l,7)^Zi(l,18)^l>>>3,h=Zi(m,17)^Zi(m,19)^m>>>10;ua[d]=h+ua[d-7]+p+ua[d-16]|0}let{A:r,B:n,C:i,D:o,E:s,F:a,G:c,H:u}=this;for(let d=0;d<64;d++){let l=Zi(s,6)^Zi(s,11)^Zi(s,25),m=u+l+Cce(s,a,c)+Mce[d]+ua[d]|0,h=(Zi(r,2)^Zi(r,13)^Zi(r,22))+Nce(r,n,i)|0;u=c,c=a,a=s,s=o+m|0,o=i,i=n,n=r,r=m+h|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,i,o,s,a,c,u)}roundClean(){I0(ua)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),I0(this.buffer)}},Dce=class extends qce{constructor(){super(32,kce)}},cU=yce(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),Lce=cU[0],Bce=cU[1],da=new Uint32Array(80),la=new Uint32Array(80),Uce=class extends aU{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:o,Dh:s,Dl:a,Eh:c,El:u,Fh:d,Fl:l,Gh:m,Gl:p,Hh:h,Hl:y}=this;return[e,t,r,n,i,o,s,a,c,u,d,l,m,p,h,y]}set(e,t,r,n,i,o,s,a,c,u,d,l,m,p,h,y){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=n|0,this.Ch=i|0,this.Cl=o|0,this.Dh=s|0,this.Dl=a|0,this.Eh=c|0,this.El=u|0,this.Fh=d|0,this.Fl=l|0,this.Gh=m|0,this.Gl=p|0,this.Hh=h|0,this.Hl=y|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let A=0;A<16;A++,t+=4)da[A]=e.getUint32(t),la[A]=e.getUint32(t+=4);for(let A=16;A<80;A++){let E=da[A-15]|0,S=la[A-15]|0,I=dl(E,S,1)^dl(E,S,8)^xB(E,S,7),T=ll(E,S,1)^ll(E,S,8)^OB(E,S,7),x=da[A-2]|0,C=la[A-2]|0,k=dl(x,C,19)^_0(x,C,61)^xB(x,C,6),N=ll(x,C,19)^b0(x,C,61)^OB(x,C,6),M=Sce(T,N,la[A-7],la[A-16]),j=Ace(M,I,k,da[A-7],da[A-16]);da[A]=j|0,la[A]=M|0}let{Ah:r,Al:n,Bh:i,Bl:o,Ch:s,Cl:a,Dh:c,Dl:u,Eh:d,El:l,Fh:m,Fl:p,Gh:h,Gl:y,Hh:b,Hl:v}=this;for(let A=0;A<80;A++){let E=dl(d,l,14)^dl(d,l,18)^_0(d,l,41),S=ll(d,l,14)^ll(d,l,18)^b0(d,l,41),I=d&m^~d&h,T=l&p^~l&y,x=Ice(v,S,T,Bce[A],la[A]),C=Pce(x,b,E,I,Lce[A],da[A]),k=x|0,N=dl(r,n,28)^_0(r,n,34)^_0(r,n,39),M=ll(r,n,28)^b0(r,n,34)^b0(r,n,39),j=r&i^r&s^i&s,D=n&o^n&a^o&a;b=h|0,v=y|0,h=m|0,y=p|0,m=d|0,p=l|0,{h:d,l}=Wo(c|0,u|0,C|0,k|0),c=s|0,u=a|0,s=i|0,a=o|0,i=r|0,o=n|0;let U=wce(k,M,D);r=vce(U,C,N,j),n=U|0}({h:r,l:n}=Wo(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=Wo(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=Wo(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=Wo(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=Wo(this.Eh|0,this.El|0,d|0,l|0),{h:m,l:p}=Wo(this.Fh|0,this.Fl|0,m|0,p|0),{h,l:y}=Wo(this.Gh|0,this.Gl|0,h|0,y|0),{h:b,l:v}=Wo(this.Hh|0,this.Hl|0,b|0,v|0),this.set(r,n,i,o,s,a,c,u,d,l,m,p,h,y,b,v)}roundClean(){I0(da,la)}destroy(){this.destroyed=!0,I0(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Hce=class extends Uce{constructor(){super(64,jce)}},dm=oU(()=>new Dce,sU(1)),Fce=oU(()=>new Hce,sU(3)),kB=nU;kB.sha512||(kB.sha512=e=>Fce(e));var jB=32;function uU(){return pce.randomSecretKey()}function C0(e){return sce(e)}function $ce(){let e=uU();return{secretKey:e,publicKey:C0(e)}}function dU(e){if(e.length!==jB)throw new Error(`Ed25519 seed must be ${jB} bytes, got ${e.length}`);return{secretKey:e,publicKey:C0(e)}}function Jce(e,t){return cce(t,e)}function Vce(e,t,r){return lce(t,r,e)}function Gce(e,t){return ace(t,e)}function Kce(e,t,r){return dce(t,r,e)}var lU=xI.bytesToHex,OI=xI.hexToBytes,RI=xI.concatBytes;function fU(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function pU(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function Yo(e){return fU(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function N0(e){let t=e.length%4===0?0:4-e.length%4,r=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return pU(r)}var Wce=new TextEncoder,zce={subwayAgentMsgV1:"message_id;sender_peer_id;sender_name;timestamp_ms;message_type;payload_hash;nonce"};function mU(e){let t=lU(dm(e.payload)),r=`${e.messageId}
2
+ ${e.senderPeerId}
3
+ ${e.senderName}
4
+ ${e.timestampMs}
5
+ ${e.messageType}
6
+ ${t}
7
+ ${e.nonce}`;return Wce.encode(r)}function Yce(e,t,r,n,i,o,s){return mU({messageId:e,senderPeerId:t,senderName:r,timestampMs:n,messageType:i,payload:o,nonce:s})}function gU(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function Xce(e){let t=C0(e);return{kty:"OKP",crv:"Ed25519",x:Yo(t),d:Yo(e)}}function Zce(e){return{kty:"OKP",crv:"Ed25519",x:Yo(e)}}function hU(e){if(gU(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return N0(e.d)}function Qce(e){return gU(e),N0(e.x)}function eue(e){return dU(hU(e))}function yU(e){if(e.kty!=="OKP")throw new Error(`computeJkt expects an OKP JWK; got kty="${e.kty}"`);let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return Yo(dm(new TextEncoder().encode(t)))}var tue=OI("302e020100300506032b657004220420"),rue=OI("302a300506032b6570032100"),ma=32;function nue(e){if(e.length!==ma)throw new Error(`seed must be ${ma} bytes, got ${e.length}`);return RI(tue,e)}function iue(e){if(e.length!==ma)throw new Error(`public key must be ${ma} bytes, got ${e.length}`);return RI(rue,e)}function oue(e){if(e.length<ma)throw new Error("PKCS8 DER too short for an Ed25519 key");return e.slice(e.length-ma)}function sue(e){if(e.length<ma)throw new Error("SPKI DER too short for an Ed25519 key");return e.slice(e.length-ma)}function aue(e){let t=0;for(;t<e.length;){let r=e[t],n=r>>3,i=r&7;if(t++,i===0){for(;t<e.length&&e[t]&128;)t++;t++}else if(i===2){let o=0,s=0;for(;t<e.length&&e[t]&128;)o|=(e[t]&127)<<s,s+=7,t++;if(o|=(e[t]&127)<<s,t++,n===2&&o>=64)return e.slice(t,t+32);t+=o}else return null}return null}var ga=FB(require("node:crypto")),_U=FB(rce()),zo=2,bU=["new","continue"],cue=["charge_and_capture","authorize_only"],CI=10000n,v0="nominal_usd_usdc_parity",tu=["card:vic","wallet:x402"],EU="wallet:x402",_I=["connector","laptop"],bI=["card:vic","wallet:tempo","wallet:x402"];function NI(e){let t=new Set(e);return e.includes(EU)&&t.add("wallet:tempo"),[...t].sort((r,n)=>cm(r,n))}var uue={ask:"Ask me each time",budget:"Pay within my budget"};function due(e,t){return e!=="laptop"?[]:NI(t).map(r=>({surface:"laptop",scope:r}))}var lue=["hosted_identity_key_migration_required","identity_key_expired","identity_key_rotated","identity_key_lost","identity_key_inactive","agent_inactive","current_grant_missing","current_grant_replaced","current_grant_expired","current_grant_inactive","required_scope_missing","managed_wallet_authority_unverified","authority_projection_unknown","authorization_version_unsupported","identity_key_custody_unsupported","owner_eligibility_required"],fue=["runtime","turnkey","server_encrypted","server_kms","external"],pue=["pending","active","retired","revoked","lost"],wU=["dotvisa","tap","email","messaging"],vU=["provisioning","active","needs_attention","suspended","disabled"],SU=["routing_only","provider_verified","agent_key_bound"],mue=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,gue=/^[A-Za-z0-9_-]{43}$/,hue=/^(?:0|[1-9][0-9]*)$/,yue=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})$/,AU=/[\u0000-\u001f\u007f]/,_ue=2147483647,IU=9223372036854775807n,MB=100,bue=512,qB=32,Eue=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.visa$/,PU=/^0x[0-9a-f]{40}$/,kI=new TextEncoder;function cm(e,t){return(0,_U.compareCanonicalKeys)(e,t)}function ru(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function On(e){if(typeof e!="string"||!gue.test(e))return!1;try{let t=N0(e);return t.byteLength===32&&Yo(t)===e}catch{return!1}}function nu(e,t,r){let n=Object.keys(t).filter(i=>!r.has(i));if(n.length>0)throw new Error(`${e} contains unknown field(s): ${n.sort().join(", ")}`)}function wue(e,t){if(typeof t!="string"||!mue.test(t))throw new Error(`${e} must be a UUID`)}function rn(e,t){return wue(e,t),t.toLowerCase()}function EI(e,t){if(!(0,_U.isCanonicalOpaqueId)(t))throw new Error(`${e} must be a non-empty opaque id (max 128 chars)`)}function fl(e,t){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let r=yue.exec(t);if(!r)throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let[,n,i,o,s,a,c]=r,u=Number(n),d=Number(i),l=Number(o),m=Number(s),p=Number(a),h=Number(c),y=new Date(0);if(y.setUTCFullYear(u,d-1,l),y.setUTCHours(m,p,h,0),u===0||y.getUTCFullYear()!==u||y.getUTCMonth()!==d-1||y.getUTCDate()!==l||y.getUTCHours()!==m||y.getUTCMinutes()!==p||y.getUTCSeconds()!==h)throw new Error(`${e} must be a valid calendar timestamp`);let b=Date.parse(t);if(!Number.isFinite(b))throw new Error(`${e} must be a valid ISO timestamp`);return new Date(b).toISOString()}function eu(e,t,r=!1){if(typeof t!="string"||!hue.test(t))throw new Error(`${e} must be a canonical non-negative integer micros string`);if(!r&&t==="0")throw new Error(`${e} must be positive`);if(BigInt(t)>IU)throw new Error(`${e} exceeds the PostgreSQL BIGINT range`);return t}function TU(e,t){if(typeof t!="number"||!Number.isInteger(t)||t<=0||t>_ue)throw new Error(`${e} must be a positive PostgreSQL INTEGER`);return t}function wI(e,t){if(typeof t!="string")throw new Error(`${e} must be a string`);if(AU.test(t))throw new Error(`${e} must be a bounded non-empty payee without control characters`);let r=t.normalize("NFC").trim();if(r.length===0||r.length>bue)throw new Error(`${e} must be a bounded non-empty payee without control characters`);return r}function am(e,t,r){if(typeof t!="string")throw new Error(`${e} must be a string`);if(AU.test(t))throw new Error(`${e} must be bounded, non-empty text without control characters`);let n=t.normalize("NFC").trim();if(n.length===0||n.length>r)throw new Error(`${e} must be bounded, non-empty text without control characters`);return n}function Qi(e,t){return typeof e=="string"&&t.includes(e)}function vue(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("cents must be a non-negative safe integer");let t=BigInt(e)*CI;if(t>IU)throw new Error("cents exceed the PostgreSQL BIGINT micros range");return t.toString()}function Sue(e){return eu("amountAtomic",e,!0)}function Aue(e){if(e==="card:vic")return{scope:e,paymentRail:"card",protocol:null,instrumentKind:"vic_card"};if(e==="wallet:x402")return{scope:e,paymentRail:"stablecoin",protocol:"x402",instrumentKind:"turnkey_wallet"};throw new Error(`unknown authorization scope: ${String(e)}`)}function Iue(e,t,r){if(!ru(e))throw new Error("keyLink must be an object");nu("channel keyLink",e,new Set(["keyId","agentId","purpose","fingerprint"]));let n=rn("keyLink.keyId",e.keyId),i=rn("keyLink.agentId",e.agentId);if(i!==t)throw new Error("keyLink.agentId must match the channel agentId");if(!Qi(e.purpose,["identity","email_signing"]))throw new Error("channel keyLink cannot use a wallet-signing key");if(r==="email"&&e.purpose!=="email_signing")throw new Error("an agent-key-bound email channel requires an email_signing key");if((r==="tap"||r==="dotvisa")&&e.purpose!=="identity")throw new Error(`${r} requires an identity key`);let o=am("keyLink.fingerprint",e.fingerprint,255);if(!On(o))throw new Error(`an ${e.purpose} key link fingerprint must be a 43-char RFC 7638 JKT`);return{keyId:n,agentId:i,purpose:e.purpose,fingerprint:o}}function Pue(e){if(!ru(e))throw new Error("agent channel descriptor must be an object");nu("agent channel descriptor",e,new Set(["channelId","agentId","kind","status","assurance","address","providerRef","keyLink","capabilities","createdAt","verifiedAt","disabledAt"])),EI("channelId",e.channelId);let t=rn("agentId",e.agentId);if(!Qi(e.kind,wU))throw new Error("invalid channel kind");if(!Qi(e.status,vU))throw new Error("invalid channel status");if(!Qi(e.assurance,SU))throw new Error("invalid channel assurance");let r=e.address===void 0?void 0:am("address",e.address,320),n=e.kind==="dotvisa"?r?.toLowerCase():r;if((e.kind==="email"||e.kind==="dotvisa")&&n===void 0)throw new Error(`${e.kind} channels require an address`);if(e.kind==="dotvisa"&&n!==void 0&&!Eue.test(n))throw new Error("dotvisa channel address must be a canonical lowercase .visa address");if(e.kind==="tap"&&n!==void 0)throw new Error("tap channels use providerRef and cannot claim a public address");let i=e.providerRef===void 0?void 0:am("providerRef",e.providerRef,255);if(!Array.isArray(e.capabilities)||e.capabilities.length===0||e.capabilities.length>qB)throw new Error(`capabilities must contain between 1 and ${qB} entries`);let o=e.capabilities.map(l=>am("capability",l,64));if(new Set(o).size!==o.length)throw new Error("capabilities must not repeat");let s=fl("createdAt",e.createdAt),a=e.verifiedAt===void 0?void 0:fl("verifiedAt",e.verifiedAt),c=e.disabledAt===void 0?void 0:fl("disabledAt",e.disabledAt);if(a!==void 0&&Date.parse(a)<Date.parse(s))throw new Error("verifiedAt cannot be before createdAt");if(c!==void 0&&Date.parse(c)<Date.parse(s))throw new Error("disabledAt cannot be before createdAt");if(c!==void 0&&a!==void 0&&Date.parse(c)<Date.parse(a))throw new Error("disabledAt cannot be before verifiedAt");if(e.status==="disabled"!=(c!==void 0))throw new Error("status='disabled' and disabledAt must be set together");let u={channelId:e.channelId,agentId:t,kind:e.kind,status:e.status,...n!==void 0?{address:n}:{},...i!==void 0?{providerRef:i}:{},capabilities:[...o].sort(cm),createdAt:s,...c!==void 0?{disabledAt:c}:{}};if(e.assurance==="routing_only"){if(a!==void 0||e.keyLink!==void 0)throw new Error("routing_only channels cannot claim verification or an agent key link");return{...u,assurance:"routing_only"}}if(i===void 0||a===void 0)throw new Error(`${e.assurance} channels require providerRef and verifiedAt`);if(e.assurance==="provider_verified"){if(e.keyLink!==void 0)throw new Error("provider_verified channels cannot claim an agent key link");return{...u,assurance:"provider_verified",providerRef:i,verifiedAt:a}}let d=Iue(e.keyLink,t,e.kind);return{...u,assurance:"agent_key_bound",providerRef:i,verifiedAt:a,keyLink:d}}function xU(e,t){if(!Array.isArray(e)||e.length>_I.length*bI.length)throw new Error("payWithinBudget must be an array of surface/scope entries");let r=e.map(i=>{if(!ru(i))throw new Error("payWithinBudget entry must be an object");if(nu("payWithinBudget entry",i,new Set(["surface","scope"])),!Qi(i.surface,_I))throw new Error("payWithinBudget surface must be laptop or connector");if(!Qi(i.scope,bI))throw new Error("payWithinBudget scope is not a payment rail");if(!NI(t).includes(i.scope))throw new Error(i.scope==="wallet:tempo"?"payWithinBudget wallet:tempo needs the wallet:x402 grant scope":"payWithinBudget scope must be present in grant scopes");return{surface:i.surface,scope:i.scope}}),n=r.map(({surface:i,scope:o})=>`${i}:${o}`);if(new Set(n).size!==n.length)throw new Error("payWithinBudget must not repeat");return[...r].sort((i,o)=>cm(`${i.surface}:${i.scope}`,`${o.surface}:${o.scope}`))}function jI(e){if(!ru(e))throw new Error("agent authority grant must be an object");if(nu("agent authority grant",e,new Set(["v","grantId","agentId","version","budgetEpochId","budgetEpochMode","status","currency","valuationPolicy","totalMicros","perTransactionMicros","dailyMicros","scopes","payWithinBudget","payeeConstraints","effectiveAt","expiresAt","supersedesGrantId"])),e.v!==zo)throw new Error("grant.v must be 2");let t=rn("grantId",e.grantId),r=rn("agentId",e.agentId),n=TU("version",e.version),i=rn("budgetEpochId",e.budgetEpochId);if(!Qi(e.budgetEpochMode,bU))throw new Error("budgetEpochMode must be new or continue");if(!Qi(e.status,["active","superseded","revoked"]))throw new Error("invalid grant status");if(e.currency!=="USD")throw new Error("currency must be 'USD'");if(e.valuationPolicy!==v0)throw new Error(`valuationPolicy must be '${v0}'`);let o=eu("totalMicros",e.totalMicros),s=eu("perTransactionMicros",e.perTransactionMicros);if(BigInt(s)>BigInt(o))throw new Error("perTransactionMicros cannot exceed totalMicros");let a=e.dailyMicros===void 0?void 0:eu("dailyMicros",e.dailyMicros);if(a!==void 0){if(BigInt(a)>BigInt(o))throw new Error("dailyMicros cannot exceed totalMicros");if(BigInt(s)>BigInt(a))throw new Error("perTransactionMicros cannot exceed dailyMicros")}if(!Array.isArray(e.scopes)||e.scopes.length===0)throw new Error("scopes must be a non-empty array");let c=e.scopes.map(p=>{if(!ru(p))throw new Error("grant scope must be an object");if(nu("grant scope",p,new Set(["scope","totalMicros","perTransactionMicros","instrumentRef"])),!Qi(p.scope,tu))throw new Error("invalid authorization scope");let h=p.totalMicros===void 0?void 0:eu("scope.totalMicros",p.totalMicros),y=p.perTransactionMicros===void 0?void 0:eu("scope.perTransactionMicros",p.perTransactionMicros);if(h!==void 0&&BigInt(h)>BigInt(o))throw new Error("scope.totalMicros cannot exceed the aggregate totalMicros");if(y!==void 0&&BigInt(y)>BigInt(s))throw new Error("scope.perTransactionMicros cannot exceed the aggregate perTransactionMicros");if(h!==void 0&&y!==void 0&&BigInt(y)>BigInt(h))throw new Error("scope.perTransactionMicros cannot exceed scope.totalMicros");let b=am("scope.instrumentRef",p.instrumentRef,255);return{scope:p.scope,...h!==void 0?{totalMicros:h}:{},...y!==void 0?{perTransactionMicros:y}:{},instrumentRef:b}});if(new Set(c.map(({scope:p})=>p)).size!==c.length)throw new Error("scopes must not repeat");let u=e.payWithinBudget===void 0?void 0:xU(e.payWithinBudget,c.map(({scope:p})=>p)),d;if(e.payeeConstraints!==void 0){if(!Array.isArray(e.payeeConstraints)||e.payeeConstraints.length===0||e.payeeConstraints.length>MB)throw new Error(`payeeConstraints must contain between 1 and ${MB} entries`);if(d=e.payeeConstraints.map(h=>{if(!ru(h))throw new Error("payee constraint must be an object");if(nu("payee constraint",h,new Set(["scope","kind","canonicalId"])),h.scope==="card:vic"&&h.kind==="processor_merchant_id")return{scope:h.scope,kind:h.kind,canonicalId:wI("payee constraint canonicalId",h.canonicalId)};if(h.scope==="wallet:x402"&&h.kind==="evm_address"){let y=wI("payee constraint canonicalId",h.canonicalId).toLowerCase();if(!PU.test(y))throw new Error("wallet payee constraint canonicalId must be an EVM address");return{scope:h.scope,kind:h.kind,canonicalId:y}}throw new Error("payee constraint scope/kind combination is invalid")}),d.some(h=>!c.some(({scope:y})=>y===h.scope)))throw new Error("payee constraint scope must be present in grant scopes");let p=d.map(({scope:h,kind:y,canonicalId:b})=>`${h}:${y}:${b}`);if(new Set(p).size!==p.length)throw new Error("payeeConstraints must not repeat after normalization")}let l=fl("effectiveAt",e.effectiveAt),m=fl("expiresAt",e.expiresAt);if(Date.parse(m)<=Date.parse(l))throw new Error("expiresAt must be after effectiveAt");if(e.supersedesGrantId!==void 0&&rn("supersedesGrantId",e.supersedesGrantId)===t)throw new Error("a grant cannot supersede itself");return{v:zo,grantId:t,agentId:r,version:n,budgetEpochId:i,budgetEpochMode:e.budgetEpochMode,status:e.status,currency:"USD",valuationPolicy:v0,totalMicros:o,perTransactionMicros:s,...a!==void 0?{dailyMicros:a}:{},scopes:[...c].sort((p,h)=>cm(p.scope,h.scope)),...u!==void 0?{payWithinBudget:u}:{},...d!==void 0?{payeeConstraints:[...d].sort((p,h)=>cm(`${p.scope}:${p.kind}:${p.canonicalId}`,`${h.scope}:${h.kind}:${h.canonicalId}`))}:{},effectiveAt:l,expiresAt:m,...e.supersedesGrantId!==void 0?{supersedesGrantId:rn("supersedesGrantId",e.supersedesGrantId)}:{}}}function Tue(e){let t=jI(e),{status:r,...n}=t;return Yo(dm(kI.encode(`visa-agent-authority-grant:v2:${JSON.stringify(n)}`)))}function MI(e){if(!ru(e))throw new Error("spend authorization intent must be an object");if(nu("spend authorization intent",e,new Set(["v","authorizationId","agentId","keyJkt","grantId","grantVersion","budgetEpochId","scope","amountMicros","currency","payee","intentId","economicIntentId","settlementHash","settlementExpiresAt"])),e.v!==zo)throw new Error("intent.v must be 2");let t=rn("authorizationId",e.authorizationId),r=rn("agentId",e.agentId);if(!On(e.keyJkt))throw new Error("keyJkt must be a 43-char RFC 7638 thumbprint");let n=rn("grantId",e.grantId),i=TU("grantVersion",e.grantVersion),o=rn("budgetEpochId",e.budgetEpochId);if(!Qi(e.scope,tu))throw new Error("invalid authorization scope");let s=eu("amountMicros",e.amountMicros);if(e.scope==="card:vic"&&BigInt(s)%CI!==0n)throw new Error("card:vic amountMicros must represent a whole number of card cents");if(e.currency!=="USD")throw new Error("currency must be 'USD'");let a=wI("payee",e.payee),c=e.scope==="wallet:x402"?a.toLowerCase():a;if(e.scope==="wallet:x402"&&!PU.test(c))throw new Error("wallet:x402 payee must be an EVM address");if(EI("intentId",e.intentId),EI("economicIntentId",e.economicIntentId),!On(e.settlementHash))throw new Error("settlementHash is required and must be a 32-byte base64url commitment");let u=fl("settlementExpiresAt",e.settlementExpiresAt);return{v:zo,authorizationId:t,agentId:r,keyJkt:e.keyJkt,grantId:n,grantVersion:i,budgetEpochId:o,scope:e.scope,amountMicros:s,currency:"USD",payee:c,intentId:e.intentId,economicIntentId:e.economicIntentId,settlementHash:e.settlementHash,settlementExpiresAt:u}}function OU(e){let t=MI(e),r=JSON.stringify({v:t.v,authorizationId:t.authorizationId,agentId:t.agentId,keyJkt:t.keyJkt,grantId:t.grantId,grantVersion:t.grantVersion,budgetEpochId:t.budgetEpochId,scope:t.scope,amountMicros:t.amountMicros,currency:t.currency,payee:t.payee,intentId:t.intentId,economicIntentId:t.economicIntentId,settlementHash:t.settlementHash,settlementExpiresAt:t.settlementExpiresAt});return Yo(dm(kI.encode(`visa-agent-spend-authorization:v2:${r}`)))}function xue(e){let t=MI(e.intent),r=rn("walletApiKeyId",e.walletApiKeyId),n=rn("runtimeSessionId",e.runtimeSessionId);if(e.executionChannel!=="cli"&&e.executionChannel!=="mcp")throw new Error("executionChannel must be cli or mcp");if(!On(e.resourceCommitment))throw new Error("resourceCommitment must be a 32-byte base64url commitment");let i=JSON.stringify({v:1,intentHash:OU(t),walletApiKeyId:r,runtimeSessionId:n,executionChannel:e.executionChannel,resourceCommitment:e.resourceCommitment});return Yo(dm(kI.encode(`visa-wallet-authorization-request:v1:${i}`)))}var RU=["card","wallet"],qI="both",Oue=[...RU,qI];function Rue(e){return e===qI?["card","wallet"]:[e]}var Cue=1,P0=2,ml="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",um=8,DI=ml.length-1,LI="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",Nue=8,CU=LI.length-1;if((ml.length&DI)!==0)throw new Error("agent pairing code alphabet must contain a power-of-two number of symbols");if((LI.length&CU)!==0)throw new Error("pairing confirmation alphabet must contain a power-of-two number of symbols");var k0=/^ap_[A-Za-z0-9_-]{24}$/,DB=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,lm=/[\p{Cc}\p{Cf}]/u,kue=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.visa$/,jue=255,Mue=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,que=100,Due=200,Lue=64,Bue=100,Uue=100,LB=2048,NU=/[\u0080-\u009f\u2028\u2029]/;function kU(e,t){return e<t?-1:e>t?1:0}function Tn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Vn(e,t,r){let n=new Set(r),i=Object.keys(t).filter(o=>!n.has(o));if(i.length>0)throw new Error(`${e} contains unknown field(s): ${i.sort().join(", ")}`)}function Hue(e){if(typeof e!="string")throw new Error("displayName must be a string");if(lm.test(e))throw new Error("displayName must be bounded, non-empty text without control characters");let t=e.normalize("NFC").trim().replace(/ {2,}/g," ");if(t.length===0||t.length>jue)throw new Error("displayName must be bounded, non-empty text without control characters");return t}function Fue(e){if(typeof e!="string")throw new Error("dotVisaAddress must be a string");if(lm.test(e))throw new Error("dotVisaAddress must be a valid .visa address");let t=e.trim().toLowerCase();if(!kue.test(t))throw new Error("dotVisaAddress must be a valid .visa address");return t}function sm(e,t,r){if(typeof t!="string")throw new Error(`${e} must be a string`);if(lm.test(t)||NU.test(t))throw new Error(`${e} must be bounded, non-empty text without control characters`);let n=t.normalize("NFC").trim();if(n.length===0||n.length>r)throw new Error(`${e} must be bounded, non-empty text without control characters`);return n}function $ue(e){if(!Tn(e))throw new Error("runtime context v2 must be an object");Vn("runtime context v2",e,["runtime","contextLabel","cliVersion","platform","deviceLabel"]);let t=sm("runtime",e.runtime,que),r=sm("contextLabel",e.contextLabel,Due),n=e.cliVersion===void 0?void 0:sm("cliVersion",e.cliVersion,Lue),i=e.platform===void 0?void 0:sm("platform",e.platform,Bue),o=e.deviceLabel===void 0?void 0:sm("deviceLabel",e.deviceLabel,Uue);return{runtime:t,contextLabel:r,...n!==void 0?{cliVersion:n}:{},...i!==void 0?{platform:i}:{},...o!==void 0?{deviceLabel:o}:{}}}function BI(e){if(typeof e!="string"||!k0.test(e))throw new Error("pairingId must be a server-generated pairing id")}function j0(e){if(e!==P0)throw new Error("protocolVersion must be 2")}function eo(e,t){if(typeof t!="string"||!Mue.test(t))throw new Error(`${e} must be a canonical lowercase UUID`)}function nn(e,t){if(!On(t))throw new Error(`${e} must be 32 canonical unpadded base64url bytes`)}function BB(e,t){if(typeof t!="string"||t.length===0||t.length>LB||lm.test(t)||NU.test(t))throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);let r;try{r=new URL(t)}catch{throw new Error(`${e} must be a bounded absolute HTTP(S) URL`)}if(r.protocol!=="https:"&&r.protocol!=="http:"||r.hostname.length===0||r.username.length>0||r.password.length>0||r.hash.length>0)throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);let n=r.toString();if(n.length>LB)throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);return n}function Jue(e){if(!Tn(e))throw new Error("instrument commitment input must be an object");if(Vn("instrument commitment input",e,["pairingId","scope","instrumentRef","serverSecret"]),typeof e.pairingId!="string"||!k0.test(e.pairingId))throw new Error("pairingId must be a server-generated pairing id");if(!tu.includes(e.scope))throw new Error("invalid authorization scope");if(!(e.serverSecret instanceof Uint8Array)||e.serverSecret.byteLength<32)throw new Error("instrument commitment requires at least 32 bytes of server secret");if(typeof e.instrumentRef!="string")throw new Error("instrumentRef must be a string");if(lm.test(e.instrumentRef))throw new Error("instrumentRef must be bounded and contain no control characters");let t=e.instrumentRef.normalize("NFC").trim();if(t.length===0||t.length>255)throw new Error("instrumentRef must be bounded and contain no control characters");return ga.default.createHmac("sha256",e.serverSecret).update(`visa-agent-pairing-instrument:v2:${JSON.stringify({instrumentRef:t,pairingId:e.pairingId,scope:e.scope})}`,"utf8").digest("base64url")}function Vue(){return`ap_${ga.default.randomBytes(18).toString("base64url")}`}function Gue(){return ga.default.randomBytes(32).toString("base64url")}function Kue(e){if(!On(e))throw new Error("pairing verifier must be 32 unpadded base64url bytes");return to(e)}function Wue(e=ga.default.randomBytes){let t=e(um),r="";for(let n=0;n<um;n+=1)r+=ml[t[n]&DI];return q0(r)}function M0(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function q0(e){let t=M0(e);return`${t.slice(0,4)}-${t.slice(4)}`}function jU(e){let t=M0(e);return t.length===um&&[...t].every(r=>ml.includes(r))}function zue(e,t){if(!jU(t))throw new Error("invalid pairing verification code");return to(`visa-agent-pairing-code:v1:${e}:${M0(t)}`)}function Yue(){return ga.default.randomBytes(32).toString("base64url")}function MU(e){if(!On(e))throw new Error("claim token must be 32 unpadded base64url bytes");return to(`visa-agent-pairing-claim-token:v1:${e}`)}function Xue(e,t){MU(t);let r=ga.default.createHash("sha256").update(`visa-agent-pairing-derived-code:v1:${e}:${t}`,"utf8").digest(),n="";for(let i=0;i<um;i+=1)n+=ml[r[i]&DI];return q0(n)}function Zue(e,t){if(!k0.test(e))throw new Error("pairingId must use the canonical ap_ + 24 base64url form");if(!On(t))throw new Error("identityKeyJkt must be a canonical RFC 7638 thumbprint");let r=ga.default.createHash("sha256").update(`visa-agent-pairing-confirmation-code:v1:${e}:${t}`,"utf8").digest(),n="";for(let i=0;i<Nue;i+=1)n+=LI[r[i]&CU];return q0(n)}function qU(e){let t=e.name.trim().toLowerCase();if(!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.visa$/.test(t))throw new Error("agent name must be a valid .visa name");if(e.mode!=="wallet"&&e.mode!=="card"&&e.mode!=="both"&&e.mode!=="identity_only")throw new Error("mode must be one of wallet, card, both, identity_only");if(!Number.isSafeInteger(e.dailyLimitCents)||e.dailyLimitCents<0)throw new Error("dailyLimitCents must be a non-negative safe integer");if(!Number.isSafeInteger(e.perTransactionLimitCents)||e.perTransactionLimitCents<0)throw new Error("perTransactionLimitCents must be a non-negative safe integer");if(e.perTransactionLimitCents>e.dailyLimitCents)throw new Error("per-transaction limit cannot exceed daily limit");if(e.mode==="identity_only"&&(e.dailyLimitCents!==0||e.perTransactionLimitCents!==0))throw new Error("identity-only agents cannot receive spend limits");return JSON.stringify({dailyLimitCents:e.dailyLimitCents,mode:e.mode,name:t,perTransactionLimitCents:e.perTransactionLimitCents})}function Que(e){return to(`visa-agent-pairing-terms:v1:${qU(e)}`)}function UI(e){if(!Tn(e))throw new Error("pairing terms v2 must be an object");if(Vn("pairing terms v2",e,["v","pairingId","agentId","agentSelection","identityKeyJkt","ownerPublicId","displayName","dotVisaAddress","authority"]),e.v!==zo)throw new Error("pairing terms v2 must carry v=2");if(typeof e.pairingId!="string"||!k0.test(e.pairingId))throw new Error("pairingId must be a server-issued pairing id");if(typeof e.agentId!="string"||!DB.test(e.agentId))throw new Error("agentId must be a UUID");if(e.agentSelection!=="new"&&e.agentSelection!=="existing")throw new Error("agentSelection must be new or existing");if(!On(e.identityKeyJkt))throw new Error("identityKeyJkt must be a canonical 32-byte base64url thumbprint");if(typeof e.ownerPublicId!="string"||!DB.test(e.ownerPublicId))throw new Error("ownerPublicId must be a UUID");let t=e.agentId.toLowerCase(),r=e.ownerPublicId.toLowerCase(),n=Hue(e.displayName),i=e.dotVisaAddress===void 0?void 0:Fue(e.dotVisaAddress);if(e.authority===null){if(e.agentSelection==="existing")throw new Error("an existing-agent pairing must bind its exact current authority; identity-only attachment requires a future explicit no-spend key policy");return JSON.stringify({agentId:t,agentSelection:e.agentSelection,authority:null,displayName:n,identityKeyJkt:e.identityKeyJkt,...i!==void 0?{dotVisaAddress:i}:{},ownerPublicId:r,pairingId:e.pairingId,v:zo})}if(!Tn(e.authority))throw new Error("pairing authority must be an object or null");if(Vn("pairing authority",e.authority,["grantId","grantVersion","supersedesGrantId","budgetEpochId","budgetEpochMode","currency","valuationPolicy","totalMicros","perTransactionMicros","dailyMicros","payWithinBudget","scopes","payeeConstraints","effectiveAt","expiresAt"]),!Array.isArray(e.authority.scopes)||e.authority.scopes.length===0||e.authority.scopes.length>tu.length)throw new Error(`pairing authority scopes must contain between 1 and ${tu.length} entries`);let o=new Map,s=e.authority.scopes.map(c=>{if(!Tn(c))throw new Error("pairing authority scope must be an object");if(Object.prototype.hasOwnProperty.call(c,"instrumentRef"))throw new Error("pairing authority scopes may not supply instrumentRef; auth resolves it");if(Vn("pairing authority scope",c,["scope","totalMicros","perTransactionMicros","instrumentCommitment"]),!tu.includes(c.scope))throw new Error("invalid authorization scope");let u=c.scope;if(!On(c.instrumentCommitment))throw new Error("every approved scope requires a 32-byte instrumentCommitment");return o.set(u,c.instrumentCommitment),{scope:u,instrumentRef:c.instrumentCommitment,...c.totalMicros!==void 0?{totalMicros:c.totalMicros}:{},...c.perTransactionMicros!==void 0?{perTransactionMicros:c.perTransactionMicros}:{}}}),a=jI({v:zo,grantId:e.authority.grantId,agentId:t,version:e.authority.grantVersion,budgetEpochId:e.authority.budgetEpochId,budgetEpochMode:e.authority.budgetEpochMode,status:"active",currency:e.authority.currency,valuationPolicy:e.authority.valuationPolicy,totalMicros:e.authority.totalMicros,perTransactionMicros:e.authority.perTransactionMicros,...e.authority.dailyMicros!==void 0?{dailyMicros:e.authority.dailyMicros}:{},scopes:s,...e.authority.payWithinBudget!==void 0?{payWithinBudget:e.authority.payWithinBudget}:{},...e.authority.payeeConstraints!==void 0?{payeeConstraints:e.authority.payeeConstraints}:{},effectiveAt:e.authority.effectiveAt,expiresAt:e.authority.expiresAt,...e.authority.supersedesGrantId!==void 0?{supersedesGrantId:e.authority.supersedesGrantId}:{}});if(e.agentSelection==="new"&&(a.version>1||a.supersedesGrantId!==void 0))throw new Error("a new-agent pairing cannot replace or supersede an existing grant; replacement authority belongs to an existing agent");if(a.version===1&&(a.budgetEpochMode!=="new"||a.supersedesGrantId!==void 0))throw new Error("an initial pairing grant must start a new budget epoch and supersede nothing");if(a.version>1&&a.supersedesGrantId===void 0)throw new Error("a replacement pairing grant must name its direct predecessor");return JSON.stringify({agentId:t,agentSelection:e.agentSelection,authority:{...a.payeeConstraints!==void 0?{payeeConstraints:a.payeeConstraints}:{},currency:a.currency,effectiveAt:a.effectiveAt,expiresAt:a.expiresAt,grantId:a.grantId,grantVersion:a.version,budgetEpochId:a.budgetEpochId,budgetEpochMode:a.budgetEpochMode,...a.supersedesGrantId!==void 0?{supersedesGrantId:a.supersedesGrantId}:{},perTransactionMicros:a.perTransactionMicros,...a.dailyMicros!==void 0?{dailyMicros:a.dailyMicros}:{},...a.payWithinBudget!==void 0?{payWithinBudget:a.payWithinBudget}:{},scopes:a.scopes.map(({scope:c,totalMicros:u,perTransactionMicros:d})=>{let l=o.get(c);if(l===void 0)throw new Error("canonical scope lost its approved instrument commitment");return{instrumentCommitment:l,...d!==void 0?{perTransactionMicros:d}:{},scope:c,...u!==void 0?{totalMicros:u}:{}}}),totalMicros:a.totalMicros,valuationPolicy:a.valuationPolicy},displayName:n,identityKeyJkt:e.identityKeyJkt,...i!==void 0?{dotVisaAddress:i}:{},ownerPublicId:r,pairingId:e.pairingId,v:zo})}function DU(e){return to(`visa-agent-pairing-terms:v2:${UI(e)}`)}function ede(e){for(let[t,r]of[["serverNonce",e.serverNonce],["claimTokenHash",e.claimTokenHash],["agentJkt",e.agentJkt]])if(!On(r))throw new Error(`${t} must be 32 canonical unpadded base64url bytes`);return gl("visa-agent-pairing-claim:v1",{agentJkt:e.agentJkt,claimTokenHash:e.claimTokenHash,contextLabel:e.runtime.contextLabel,pairingId:e.pairingId,platform:e.runtime.platform??"",runtime:e.runtime.runtime,serverNonce:e.serverNonce,walletPublicKey:e.walletPublicKey})}function tde(e){for(let[t,r]of[["agentJkt",e.agentJkt],["termsHash",e.termsHash],["artifactHash",e.artifactHash]])if(!On(r))throw new Error(`${t} must be 32 canonical unpadded base64url bytes`);return gl("visa-agent-pairing-activation:v1",{agentJkt:e.agentJkt,artifactHash:e.artifactHash,pairingId:e.pairingId,termsHash:e.termsHash})}function LU(e){if(!Tn(e))throw new Error("pairing claim v2 must be an object");Vn("pairing claim v2",e,["protocolVersion","pairingId","agentId","serverNonce","claimTokenHash","identityKeyJkt","runtime"]),j0(e.protocolVersion),BI(e.pairingId),eo("agentId",e.agentId),nn("serverNonce",e.serverNonce),nn("claimTokenHash",e.claimTokenHash),nn("identityKeyJkt",e.identityKeyJkt);let t=$ue(e.runtime);return gl("visa-agent-pairing-claim:v2",{agentId:e.agentId,claimTokenHash:e.claimTokenHash,cliVersion:t.cliVersion??"",contextLabel:t.contextLabel,...t.deviceLabel!==void 0?{deviceLabel:t.deviceLabel}:{},identityKeyJkt:e.identityKeyJkt,pairingId:e.pairingId,platform:t.platform??"",protocolVersion:String(e.protocolVersion),runtime:t.runtime,serverNonce:e.serverNonce})}function rde(e){return to(LU(e))}function nde(e){if(!Tn(e))throw new Error("pairing activation v2 must be an object");return Vn("pairing activation v2",e,["protocolVersion","pairingId","agentId","ownerPublicId","claimTokenHash","identityKeyJkt","ceremonyHash","deliveryArtifactHash"]),j0(e.protocolVersion),BI(e.pairingId),eo("agentId",e.agentId),eo("ownerPublicId",e.ownerPublicId),nn("claimTokenHash",e.claimTokenHash),nn("identityKeyJkt",e.identityKeyJkt),nn("ceremonyHash",e.ceremonyHash),nn("deliveryArtifactHash",e.deliveryArtifactHash),gl("visa-agent-pairing-activation:v2",{agentId:e.agentId,ceremonyHash:e.ceremonyHash,claimTokenHash:e.claimTokenHash,deliveryArtifactHash:e.deliveryArtifactHash,identityKeyJkt:e.identityKeyJkt,ownerPublicId:e.ownerPublicId,pairingId:e.pairingId,protocolVersion:String(e.protocolVersion)})}function BU(e){if(!Tn(e))throw new Error("key rotation claim v2 must be an object");return Vn("key rotation claim v2",e,["protocolVersion","rotationId","agentId","serverNonce","identityKeyJkt"]),j0(e.protocolVersion),eo("rotationId",e.rotationId),eo("agentId",e.agentId),nn("serverNonce",e.serverNonce),nn("identityKeyJkt",e.identityKeyJkt),gl("visa-agent-key-rotation-claim:v2",{agentId:e.agentId,identityKeyJkt:e.identityKeyJkt,protocolVersion:String(e.protocolVersion),rotationId:e.rotationId,serverNonce:e.serverNonce})}function ide(e){return to(BU(e))}function ode(e){if(!Tn(e))throw new Error("agent mail credential claim v2 must be an object");return Vn("agent mail credential claim v2",e,["protocolVersion","credentialId","agentId","channelId","serverNonce","identityKeyJkt"]),j0(e.protocolVersion),eo("credentialId",e.credentialId),eo("agentId",e.agentId),eo("channelId",e.channelId),nn("serverNonce",e.serverNonce),nn("identityKeyJkt",e.identityKeyJkt),gl("visa-agent-mail-credential-claim:v2",{agentId:e.agentId,channelId:e.channelId,credentialId:e.credentialId,identityKeyJkt:e.identityKeyJkt,protocolVersion:String(e.protocolVersion),serverNonce:e.serverNonce})}function UU(e){if(!Tn(e))throw new Error("pairing delivery artifact v2 must be an object");if(Vn("pairing delivery artifact v2",e,["v","kind","pairingId","agentId","ownerPublicId","identityKey","terms","ceremonyHash","issuer","activationAudience"]),e.v!==P0)throw new Error("pairing delivery artifact v2 must carry v=2");if(e.kind!=="agent-pairing-delivery")throw new Error("pairing delivery artifact kind must be agent-pairing-delivery");if(BI(e.pairingId),eo("agentId",e.agentId),eo("ownerPublicId",e.ownerPublicId),nn("ceremonyHash",e.ceremonyHash),!Tn(e.identityKey))throw new Error("pairing delivery identityKey must be an object");if(Vn("pairing delivery identityKey",e.identityKey,["jkt","publicJwk"]),nn("identityKey.jkt",e.identityKey.jkt),!Tn(e.identityKey.publicJwk))throw new Error("pairing delivery identityKey.publicJwk must be an object");let t=e.identityKey.publicJwk;if(Vn("pairing delivery identityKey.publicJwk",t,["kty","crv","x"]),t.kty!=="OKP"||t.crv!=="Ed25519")throw new Error("pairing delivery identity key must be a public Ed25519 OKP JWK");nn("identityKey.publicJwk.x",t.x);let r=yU({kty:"OKP",crv:"Ed25519",x:t.x});if(e.identityKey.jkt!==r)throw new Error("identityKey.jkt must equal the RFC 7638 thumbprint of publicJwk");if(!Tn(e.terms))throw new Error("pairing delivery terms must be PairingTermsV2");if(e.terms.agentSelection!=="new"||e.terms.authority!==null)throw new Error("pairing delivery terms must be a new identity-only pairing");if(e.terms.pairingId!==e.pairingId||e.terms.agentId!==e.agentId||e.terms.ownerPublicId!==e.ownerPublicId||e.terms.identityKeyJkt!==e.identityKey.jkt)throw new Error("pairing delivery terms must match the exact ceremony principals and key");let n=UI(e.terms);if(DU(e.terms)!==e.ceremonyHash)throw new Error("ceremonyHash must equal the hash of the exact canonical v2 terms");let i=BB("issuer",e.issuer),o=BB("activationAudience",e.activationAudience);return T0({activationAudience:o,agentId:e.agentId,ceremonyHash:e.ceremonyHash,identityKey:{jkt:e.identityKey.jkt,publicJwk:{crv:"Ed25519",kty:"OKP",x:t.x}},issuer:i,kind:"agent-pairing-delivery",ownerPublicId:e.ownerPublicId,pairingId:e.pairingId,terms:JSON.parse(n),v:P0})}function sde(e){return to(`visa-agent-pairing-delivery-artifact:v2:${UU(e)}`)}function ade(e){return to(`visa-agent-pairing-artifacts:v1:${T0(e)}`)}function to(e){return ga.default.createHash("sha256").update(e,"utf8").digest("base64url")}function gl(e,t){return`${e}
8
+ ${Object.entries(t).sort(([r],[n])=>kU(r,n)).map(([r,n])=>`${r}=${n}`).join(`
9
+ `)}`}function T0(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(T0).join(",")}]`;let t=e;return`{${Object.keys(t).sort(kU).map(r=>`${JSON.stringify(r)}:${T0(t[r])}`).join(",")}}`}});var fm=g((wQe,bH)=>{"use strict";var GI=Object.defineProperty,cde=Object.getOwnPropertyDescriptor,ude=Object.getOwnPropertyNames,dde=Object.prototype.hasOwnProperty,lde=(e,t)=>{for(var r in t)GI(e,r,{get:t[r],enumerable:!0})},fde=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ude(t))!dde.call(e,i)&&i!==r&&GI(e,i,{get:()=>t[i],enumerable:!(n=cde(t,i))||n.enumerable});return e},pde=e=>fde(GI({},"__esModule",{value:!0}),e),eH={};lde(eH,{computeJkt:()=>sle,sha256:()=>_H,sign:()=>ele,signAsync:()=>rle,verify:()=>tle,verifyAsync:()=>nle});bH.exports=pde(eH);var KI=Object.freeze,_l=0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,$0=0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,H0=0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,$I=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,JI=0x6666666666666666666666666666666666666666666666666666666666666658n,F0=_l-1n,mde=KI({p:_l,n:$0,h:8n,a:F0,d:H0,Gx:$I,Gy:JI}),uu=32,FU=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&e.BYTES_PER_ELEMENT===1,Gn=(e,t,r="")=>{if(FU(e)&&(t===void 0||e.length===t))return e;let n=FU(e),i=t!==void 0?` of length ${t}`:"",o=n?`length=${e.length}`:`type=${typeof e}`,s=(r?`"${r}" `:"")+"expected Uint8Array"+i+", got "+o;throw n?new RangeError(s):new TypeError(s)},G0=(e,t="",r)=>Uint8Array.from(Gn(e,r,t)),tH=(e,t)=>e.toString(16).padStart(t,"0"),WI=e=>{let t="";for(let r of Gn(e))t+=tH(r,2);return t},zI=e=>{let t="hex invalid";if(typeof e!="string")throw new TypeError(t);if(e.length%2||!/^[\da-f]*$/i.test(e))throw new RangeError(t);let r=new Uint8Array(e.length/2);for(let n=0,i=0;n<r.length;n++,i+=2){let o=e.charCodeAt(i),s=e.charCodeAt(i+1);r[n]=((o&15)+(o>>6)*9)*16+(s&15)+(s>>6)*9}return r},du=(...e)=>{let t=0;for(let i of e)t+=Gn(i).length;let r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return r},gde=(e=uu)=>{let t=globalThis?.crypto;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined, consider polyfill");return t.getRandomValues(new Uint8Array(e))},su=(e,t,r,n="bad number: out of range")=>{if(typeof e!="bigint")throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},ot=(e,t=_l)=>(e%=t)>=0n?e:t+e,$U=(1n<<255n)-1n,Y=e=>{if(e<0n)throw new RangeError("negative coordinate");let t=(e>>255n)*19n+(e&$U);return t=(t>>255n)*19n+(t&$U),t%_l},rH=e=>ot(e,$0),nH=(e,t)=>{if(e===0n)throw new Error("invert: expected non-zero number");if(t<=1n)throw new Error("invert: expected modulus > 1, got "+t);let r=ot(e,t),n=t,i=0n,o=1n;for(;r!==0n;){let a=n/r,c=n-r*a,u=i-o*a;n=r,r=c,i=o,o=u}if(n!==1n)throw new Error("invert: does not exist");return ot(i,t)},iH=e=>{let t=fH[e];if(typeof t!="function")throw new Error("hashes."+e+" not set");return t},YI=(e,...t)=>Gn(iH(e)(du(...t)),64,"digest"),XI=async(e,...t)=>Gn(await iH(e)(du(...t)),64,"digest"),HI=e=>{if(e instanceof lu)return e;throw new TypeError("Point expected")},oH=2n**256n,lu=class au{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=oH;this.X=su(t,0n,o),this.Y=su(r,0n,o),this.Z=su(n,1n,o),this.T=su(i,0n,o),KI(this)}static CURVE(){return mde}static fromAffine(t){return new au(t.x,t.y,1n,Y(t.x*t.y))}static fromBytes(t,r=!1){let n=G0(t,"point",uu),i=n[31];n[31]=i&-129;let o=ZI(n);r||su(o,0n,_l);let s=Y(o*o),a=ot(s-1n),c=Y(H0*s+1n),{isValid:u,value:d}=yde(a,c);if(!u)throw new Error("bad point: y not sqrt");let l=!!(i&128);if(!r&&d===0n&&l)throw new Error("bad point: x==0, isLastByteOdd");return l!==!!(d&1n)&&(d=ot(-d)),new au(d,o,1n,Y(d*o))}static fromHex(t,r){return au.fromBytes(zI(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=F0,r=H0,n=this;if(n.is0())throw new Error("bad point: ZERO");let{X:i,Y:o,Z:s,T:a}=n,c=Y(i*i),u=Y(o*o),d=Y(s*s),l=Y(d*d),m=Y(c*t),p=Y(d*(m+u)),h=ot(l+Y(r*Y(c*u)));if(p!==h)throw new Error("bad point: equation left != right (1)");let y=Y(i*o),b=Y(s*a);if(y!==b)throw new Error("bad point: equation left != right (2)");return this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=HI(t);return Y(r*a)===Y(o*i)&&Y(n*a)===Y(s*i)}is0(){return this.equals(cu)}negate(){return new au(ot(-this.X),this.Y,this.Z,ot(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=F0,o=Y(t*t),s=Y(r*r),a=Y(2n*n*n),c=Y(i*o),u=ot(t+r),d=ot(Y(u*u)-o-s),l=ot(c+s),m=ot(l-a),p=ot(c-s),h=Y(d*m),y=Y(l*p),b=Y(d*p),v=Y(m*l);return new au(h,y,v,b)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=HI(t),d=F0,l=H0,m=Y(r*s),p=Y(n*a),h=Y(Y(o*l)*u),y=Y(i*c),b=ot(Y(ot(r+n)*ot(s+a))-m-p),v=ot(y-h),A=ot(y+h),E=ot(p-Y(d*m)),S=Y(b*v),I=Y(A*E),T=Y(b*E),x=Y(v*A);return new au(S,I,x,T)}subtract(t){return this.add(HI(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(su(t,1n,$0),!r&&this.is0()))return cu;if(t===1n)return this;if(this.equals(ba))return Pde(t).p;let n=cu,i=ba,o=this;for(let s=0;r?s<256:t>0n;s++)t&1n?n=n.add(o):r&&(i=i.add(o)),o=o.double(),t>>=1n;return n}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:r,Z:n}=this;if(this.equals(cu))return{x:0n,y:1n};let i=nH(n,_l);if(Y(n*i)!==1n)throw new Error("invalid inverse");return{x:Y(t*i),y:Y(r*i)}}toBytes(){let{x:t,y:r}=this.toAffine(),n=sH(r);return n[31]|=t&1n?128:0,n}toHex(){return WI(this.toBytes())}clearCofactor(){return this.multiply(8n,!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return this.multiply($0/2n,!1).double().add(this).is0()}},ba=new lu($I,JI,1n,ot($I*JI)),cu=new lu(0n,1n,1n,0n);lu.BASE=ba;lu.ZERO=cu;var sH=e=>zI(tH(su(e,0n,oH),64)).reverse(),ZI=e=>BigInt("0x"+WI(Uint8Array.from(Gn(e)).reverse())),ro=(e,t)=>{let r=e;for(;t-- >0;)r=Y(r*r);return r},hde=e=>{let t=Y(e*e),r=Y(t*e),n=Y(ro(r,2)*r),i=Y(ro(n,1)*e),o=Y(ro(i,5)*i),s=Y(ro(o,10)*o),a=Y(ro(s,20)*s),c=Y(ro(a,40)*a),u=Y(ro(c,80)*c),d=Y(ro(u,80)*c),l=Y(ro(d,10)*o);return Y(ro(l,2)*e)},JU=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,yde=(e,t)=>{let r=Y(t*Y(t*t)),n=Y(Y(r*r)*t),i=hde(Y(e*n)),o=Y(e*Y(r*i)),s=Y(t*Y(o*o)),a=o,c=Y(o*JU),u=s===e,d=s===ot(-e),l=s===ot(-e*JU);return u&&(o=a),(d||l)&&(o=c),(ot(o)&1n)===1n&&(o=ot(-o)),{isValid:u||d,value:o}},J0=e=>rH(ZI(e)),aH=e=>{let t=G0(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32),i=J0(r),o=ba.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},_de=e=>XI("sha512Async",Gn(e,uu,"secretKey")).then(aH),bde=e=>aH(YI("sha512",Gn(e,uu,"secretKey"))),cH=async e=>e[1](await XI("sha512Async",e[0])),uH=e=>e[1](YI("sha512",e[0])),dH=(e,t,r)=>{let{pointBytes:n,scalar:i}=e,o=J0(t),s=ba.multiply(o).toBytes();return[du(s,n,r),u=>{let d=rH(o+J0(u)*i);return Gn(du(s,sH(d)),64)}]},Ede=async(e,t)=>{let r=G0(e,"message"),n=await _de(t);return cH(dH(n,await XI("sha512Async",n.prefix,r),r))},wde=(e,t)=>{let r=G0(e,"message"),n=bde(t);return uH(dH(n,YI("sha512",n.prefix,r),r))},vde=e=>{if(e===null||typeof e!="object")throw new TypeError("expected valid options object");return e.zip215??!0},lH=(e,t,r,n)=>{e=Gn(e,64,"signature"),t=Gn(t,void 0,"message"),r=Gn(r,uu,"publicKey");let i=vde(n),o=e.subarray(0,uu),s=ZI(e.subarray(uu,64)),a,c,u,d=Uint8Array.of(),l=!1;try{a=lu.fromBytes(r,i),c=lu.fromBytes(o,i),u=ba.multiply(s,!1),d=du(o,r,t),l=!0}catch{}return[d,p=>{if(!l||!i&&a.isSmallOrder())return!1;let h=J0(p);return c.add(a.multiply(h,!1)).subtract(u).clearCofactor().is0()}]},Sde=async(e,t,r,n={})=>cH(lH(e,t,r,n)),Ade=(e,t,r,n={})=>uH(lH(e,t,r,n)),QI=KI({bytesToHex:WI,hexToBytes:zI,concatBytes:du,mod:ot,invert:nH,randomBytes:gde}),fH={sha512Async:async e=>{let t=globalThis?.crypto?.subtle;if(!t)throw new Error("crypto.subtle must be defined, consider polyfill");return new Uint8Array(await t.digest("SHA-512",du(e)))},sha512:void 0},Ide=()=>{let e=[],t=ba,r;for(let n=0;n<33;n++){r=t,e.push(r);for(let i=1;i<128;i++)r=r.add(t),e.push(r);t=r.double()}return e},VU=void 0,GU=(e,t)=>{let r=t.negate();return e?r:t},Pde=e=>{let t=VU||(VU=Ide()),r=cu,n=ba;for(let i=0;i<33;i++){let o=Number(e&255n);e>>=8n,o>128&&(o-=256,e+=1n);let s=i*128,a=s+Math.abs(o)-1,c=i%2!==0,u=o<0;o===0?n=n.add(GU(c,t[s])):r=r.add(GU(u,t[a]))}if(e!==0n)throw new Error("invalid wnaf");return{p:r,f:n}},L0=BigInt(2**32-1),KU=BigInt(32);function Tde(e,t=!1){return t?{h:Number(e&L0),l:Number(e>>KU&L0)}:{h:Number(e>>KU&L0)|0,l:Number(e&L0)|0}}function xde(e,t=!1){let r=e.length,n=new Uint32Array(r),i=new Uint32Array(r);for(let o=0;o<r;o++){let{h:s,l:a}=Tde(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}var Ode=e=>e/2**32|0,Rde=e=>e>>>0;function Cde(e,t,r,n){let i=Ode(r),o=Rde(r);e.setUint32(t,n?o:i,n),e.setUint32(t+4,n?i:o,n)}var WU=(e,t,r)=>e>>>r,zU=(e,t,r)=>e<<32-r|t>>>r,hl=(e,t,r)=>e>>>r|t<<32-r,yl=(e,t,r)=>e<<32-r|t>>>r,B0=(e,t,r)=>e<<64-r|t>>>r-32,U0=(e,t,r)=>e>>>r-32|t<<64-r;function Xo(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}var Nde=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),kde=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,jde=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Mde=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,qde=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),Dde=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0;function YU(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var VI=e=>e?`"${e}" `:"";function Lde(e,t=""){if(typeof e!="number")throw new TypeError(VI(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(VI(t)+"expected integer >= 0, got "+e);return e}function pH(e,t,r=""){if(YU(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Lde(t,"length");let n=YU(e),i=t!==void 0?` of length ${t}`:"",o=n?`length=${e.length}`:`type=${typeof e}`,s=VI(r)+"expected Uint8Array"+i+", got "+o;throw n?new RangeError(s):new TypeError(s)}var Bde=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},XU=(e,t)=>{Bde(e,t);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function ZU(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function Ude(e,t){pH(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw new RangeError('"output" expected length >= '+r)}function V0(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function FI(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function no(e,t){return e<<32-t|e>>>t}function Hde(e,t,r="opts"){return XU(e,"defaults"),t!==void 0&&XU(t,r),Object.assign(Object.create(null),e,t)}function mH(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=Hde({},t,"info");let r=(i,o)=>e(o).update(i).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=i=>e(i),Object.assign(r,t),Object.freeze(r)}var gH=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Fde(e,t,r){return e&t^~e&r}function $de(e,t,r){return e&t^e&r^t&r}var hH=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=FI(this.buffer)}update(e){ZU(this),pH(e);let{view:t,buffer:r,blockLen:n}=this,i=e.length,o=!1;for(let s=0;s<i;){let a=Math.min(n-this.pos,i-s);if(a===n){let c=FI(e);for(;n<=i-s;s+=n)this.process(c,s);o=!0;continue}r.set(s===0&&a===i?e:e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===n&&(this.process(t,0),this.pos=0,o=!0)}return this.length+=e.length,o&&this.roundClean(),this}digestInto(e){ZU(this),Ude(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,t.fill(0,o),this.padOffset>n-o&&(this.process(r,0),t.fill(0)),Cde(r,n-8,this.length*8,i),this.process(r,0),this.roundClean();let s=e===t?r:FI(e),a=this.outputLen,c=a/4,u=this.get();if(a%4||c>u.length)throw new Error("invalid outputLen");for(let d=0;d<c;d++)s.setUint32(4*d,u[d],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:n,destroyed:i,pos:o}=this;return e.destroyed=i,e.finished=n,e.length=r,e.pos=o,o&&e.buffer.set(t),e}clone(){return this._cloneInto()}},Jde=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Vde=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Gde=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ha=new Uint32Array(64),Kde=class extends hH{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:r,D:n,E:i,F:o,G:s,H:a}=this;return[e,t,r,n,i,o,s,a]}set(e,t,r,n,i,o,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=s|0,this.H=a|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let d=0;d<16;d++,t+=4)ha[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let l=ha[d-15],m=ha[d-2],p=no(l,7)^no(l,18)^l>>>3,h=no(m,17)^no(m,19)^m>>>10;ha[d]=h+ha[d-7]+p+ha[d-16]|0}let{A:r,B:n,C:i,D:o,E:s,F:a,G:c,H:u}=this;for(let d=0;d<64;d++){let l=no(s,6)^no(s,11)^no(s,25),m=u+l+Fde(s,a,c)+Gde[d]+ha[d]|0,h=(no(r,2)^no(r,13)^no(r,22))+$de(r,n,i)|0;u=c,c=a,a=s,s=o+m|0,o=i,i=n,n=r,r=m+h|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,i,o,s,a,c,u)}roundClean(){V0(ha)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),V0(this.buffer)}},Wde=class extends Kde{constructor(){super(32,Jde)}},yH=xde(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),zde=yH[0],Yde=yH[1],ya=new Uint32Array(80),_a=new Uint32Array(80),Xde=class extends hH{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:o,Dh:s,Dl:a,Eh:c,El:u,Fh:d,Fl:l,Gh:m,Gl:p,Hh:h,Hl:y}=this;return[e,t,r,n,i,o,s,a,c,u,d,l,m,p,h,y]}set(e,t,r,n,i,o,s,a,c,u,d,l,m,p,h,y){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=n|0,this.Ch=i|0,this.Cl=o|0,this.Dh=s|0,this.Dl=a|0,this.Eh=c|0,this.El=u|0,this.Fh=d|0,this.Fl=l|0,this.Gh=m|0,this.Gl=p|0,this.Hh=h|0,this.Hl=y|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let A=0;A<16;A++,t+=4)ya[A]=e.getUint32(t),_a[A]=e.getUint32(t+=4);for(let A=16;A<80;A++){let E=ya[A-15]|0,S=_a[A-15]|0,I=hl(E,S,1)^hl(E,S,8)^WU(E,S,7),T=yl(E,S,1)^yl(E,S,8)^zU(E,S,7),x=ya[A-2]|0,C=_a[A-2]|0,k=hl(x,C,19)^B0(x,C,61)^WU(x,C,6),N=yl(x,C,19)^U0(x,C,61)^zU(x,C,6),M=jde(T,N,_a[A-7],_a[A-16]),j=Mde(M,I,k,ya[A-7],ya[A-16]);ya[A]=j|0,_a[A]=M|0}let{Ah:r,Al:n,Bh:i,Bl:o,Ch:s,Cl:a,Dh:c,Dl:u,Eh:d,El:l,Fh:m,Fl:p,Gh:h,Gl:y,Hh:b,Hl:v}=this;for(let A=0;A<80;A++){let E=hl(d,l,14)^hl(d,l,18)^B0(d,l,41),S=yl(d,l,14)^yl(d,l,18)^U0(d,l,41),I=d&m^~d&h,T=l&p^~l&y,x=qde(v,S,T,Yde[A],_a[A]),C=Dde(x,b,E,I,zde[A],ya[A]),k=x|0,N=hl(r,n,28)^B0(r,n,34)^B0(r,n,39),M=yl(r,n,28)^U0(r,n,34)^U0(r,n,39),j=r&i^r&s^i&s,D=n&o^n&a^o&a;b=h|0,v=y|0,h=m|0,y=p|0,m=d|0,p=l|0,{h:d,l}=Xo(c|0,u|0,C|0,k|0),c=s|0,u=a|0,s=i|0,a=o|0,i=r|0,o=n|0;let U=Nde(k,M,D);r=kde(U,C,N,j),n=U|0}({h:r,l:n}=Xo(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=Xo(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=Xo(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=Xo(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=Xo(this.Eh|0,this.El|0,d|0,l|0),{h:m,l:p}=Xo(this.Fh|0,this.Fl|0,m|0,p|0),{h,l:y}=Xo(this.Gh|0,this.Gl|0,h|0,y|0),{h:b,l:v}=Xo(this.Hh|0,this.Hl|0,b|0,v|0),this.set(r,n,i,o,s,a,c,u,d,l,m,p,h,y,b,v)}roundClean(){V0(ya,_a)}destroy(){this.destroyed=!0,V0(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Zde=class extends Xde{constructor(){super(64,Vde)}},_H=mH(()=>new Wde,gH(1)),Qde=mH(()=>new Zde,gH(3)),QU=fH;QU.sha512||(QU.sha512=e=>Qde(e));function ele(e,t){return wde(t,e)}function tle(e,t,r){return Ade(t,r,e)}function rle(e,t){return Ede(t,e)}function nle(e,t,r){return Sde(t,r,e)}var _Qe=QI.bytesToHex,bQe=QI.hexToBytes,EQe=QI.concatBytes;function ile(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function ole(e){return ile(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function sle(e){if(e.kty!=="OKP")throw new Error(`computeJkt expects an OKP JWK; got kty="${e.kty}"`);let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return ole(_H(new TextEncoder().encode(t)))}});var W0=g(K0=>{"use strict";Object.defineProperty(K0,"__esModule",{value:!0});K0.computeJkt=void 0;var ale=fm();Object.defineProperty(K0,"computeJkt",{enumerable:!0,get:function(){return ale.computeJkt}})});var Br=g(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.computeJkt=void 0;Qo.generateAgentKey=ule;Qo.agentKeyFromSeed=dle;Qo.generateAnchorKey=lle;Qo.anchorKeyFromSeed=fle;Qo.buildJwks=ple;var Zo=D0(),cle=W0();Object.defineProperty(Qo,"computeJkt",{enumerable:!0,get:function(){return cle.computeJkt}});var EH=W0();function ule(){let{secretKey:e,publicKey:t}=(0,Zo.generateKeyPair)(),r=(0,Zo.seedToJwk)(e),n=(0,Zo.publicKeyToJwk)(t);return{privateJwk:r,publicJwk:n,jkt:(0,EH.computeJkt)(n)}}function dle(e){let{secretKey:t,publicKey:r}=(0,Zo.keyPairFromSeed)(e),n=(0,Zo.seedToJwk)(t),i=(0,Zo.publicKeyToJwk)(r);return{privateJwk:n,publicJwk:i,jkt:(0,EH.computeJkt)(i)}}function wH(e,t,r){let n={...(0,Zo.seedToJwk)(e),kid:t,use:"sig",alg:"EdDSA",...r?{role:r}:{}},{d:i,...o}=n;return{kid:t,privateJwk:n,publicJwk:o,...r?{role:r}:{}}}function lle(e,t){return wH((0,Zo.generateKeyPair)().secretKey,e,t)}function fle(e,t,r){return wH((0,Zo.keyPairFromSeed)(e).secretKey,t,r)}function ple(e){let t=new Set;for(let r of e){if(t.has(r.kid))throw new Error(`buildJwks: duplicate kid ${JSON.stringify(r.kid)} \u2014 every key in a JWKS must have a unique kid`);t.add(r.kid)}return{keys:e.map(r=>({kty:r.publicJwk.kty,crv:r.publicJwk.crv,x:r.publicJwk.x,kid:r.kid,use:"sig",alg:"EdDSA",...r.role??r.publicJwk.role?{role:r.role??r.publicJwk.role}:{}}))}}});var vH=g(z0=>{"use strict";Object.defineProperty(z0,"__esModule",{value:!0});z0.version=void 0;z0.version="1.2.3"});var fu=g(Y0=>{"use strict";Object.defineProperty(Y0,"__esModule",{value:!0});Y0.BaseError=void 0;var mle=vH(),eP=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,i=r.cause instanceof e&&r.cause.docsPath||r.docsPath,o=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: https://abitype.dev${i}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${mle.version}`].join(`
10
+ `);super(o),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.shortMessage=t}};Y0.BaseError=eP});var SH=g(tP=>{"use strict";Object.defineProperty(tP,"__esModule",{value:!0});tP.narrow=gle;function gle(e){return e}});var pm=g(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});es.isTupleRegex=es.integerRegex=es.bytesRegex=void 0;es.execTyped=hle;function hle(e,t){return e.exec(t)?.groups}es.bytesRegex=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/;es.integerRegex=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;es.isTupleRegex=/^\(.+?\).*?$/});var iP=g(nP=>{"use strict";Object.defineProperty(nP,"__esModule",{value:!0});nP.formatAbiParameter=rP;var yle=pm(),AH=/^tuple(?<array>(\[(\d*)\])*)$/;function rP(e){let t=e.type;if(AH.test(e.type)&&"components"in e){t="(";let r=e.components.length;for(let i=0;i<r;i++){let o=e.components[i];t+=rP(o),i<r-1&&(t+=", ")}let n=(0,yle.execTyped)(AH,e.type);return t+=`)${n?.array||""}`,rP({...e,type:t})}return"indexed"in e&&e.indexed&&(t=`${t} indexed`),e.name?`${t} ${e.name}`:t}});var sP=g(oP=>{"use strict";Object.defineProperty(oP,"__esModule",{value:!0});oP.formatAbiParameters=ble;var _le=iP();function ble(e){let t="",r=e.length;for(let n=0;n<r;n++){let i=e[n];t+=(0,_le.formatAbiParameter)(i),n!==r-1&&(t+=", ")}return t}});var cP=g(aP=>{"use strict";Object.defineProperty(aP,"__esModule",{value:!0});aP.formatAbiItem=Ele;var mm=sP();function Ele(e){return e.type==="function"?`function ${e.name}(${(0,mm.formatAbiParameters)(e.inputs)})${e.stateMutability&&e.stateMutability!=="nonpayable"?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${(0,mm.formatAbiParameters)(e.outputs)})`:""}`:e.type==="event"?`event ${e.name}(${(0,mm.formatAbiParameters)(e.inputs)})`:e.type==="error"?`error ${e.name}(${(0,mm.formatAbiParameters)(e.inputs)})`:e.type==="constructor"?`constructor(${(0,mm.formatAbiParameters)(e.inputs)})${e.stateMutability==="payable"?" payable":""}`:e.type==="fallback"?`fallback() external${e.stateMutability==="payable"?" payable":""}`:"receive() external payable"}});var IH=g(uP=>{"use strict";Object.defineProperty(uP,"__esModule",{value:!0});uP.formatAbi=vle;var wle=cP();function vle(e){let t=[],r=e.length;for(let n=0;n<r;n++){let i=e[n],o=(0,wle.formatAbiItem)(i);t.push(o)}return t}});var pu=g(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.functionModifiers=Ct.eventModifiers=Ct.modifiers=void 0;Ct.isErrorSignature=Sle;Ct.execErrorSignature=Ale;Ct.isEventSignature=Ile;Ct.execEventSignature=Ple;Ct.isFunctionSignature=Tle;Ct.execFunctionSignature=xle;Ct.isStructSignature=Ole;Ct.execStructSignature=Rle;Ct.isConstructorSignature=Cle;Ct.execConstructorSignature=Nle;Ct.isFallbackSignature=kle;Ct.execFallbackSignature=jle;Ct.isReceiveSignature=qle;var bl=pm(),PH=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function Sle(e){return PH.test(e)}function Ale(e){return(0,bl.execTyped)(PH,e)}var TH=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function Ile(e){return TH.test(e)}function Ple(e){return(0,bl.execTyped)(TH,e)}var xH=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function Tle(e){return xH.test(e)}function xle(e){return(0,bl.execTyped)(xH,e)}var OH=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function Ole(e){return OH.test(e)}function Rle(e){return(0,bl.execTyped)(OH,e)}var RH=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function Cle(e){return RH.test(e)}function Nle(e){return(0,bl.execTyped)(RH,e)}var CH=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function kle(e){return CH.test(e)}function jle(e){return(0,bl.execTyped)(CH,e)}var Mle=/^receive\(\) external payable$/;function qle(e){return Mle.test(e)}Ct.modifiers=new Set(["memory","indexed","storage","calldata"]);Ct.eventModifiers=new Set(["indexed"]);Ct.functionModifiers=new Set(["calldata","memory","storage"])});var gm=g(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.UnknownSolidityTypeError=Ea.UnknownTypeError=Ea.InvalidAbiItemError=void 0;var pP=fu(),dP=class extends pP.BaseError{constructor({signature:t}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}};Ea.InvalidAbiItemError=dP;var lP=class extends pP.BaseError{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}};Ea.UnknownTypeError=lP;var fP=class extends pP.BaseError{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}};Ea.UnknownSolidityTypeError=fP});var El=g(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.InvalidAbiTypeParameterError=vr.InvalidFunctionModifierError=vr.InvalidModifierError=vr.SolidityProtectedKeywordError=vr.InvalidParameterError=vr.InvalidAbiParametersError=vr.InvalidAbiParameterError=void 0;var mu=fu(),mP=class extends mu.BaseError{constructor({param:t}){super("Failed to parse ABI parameter.",{details:`parseAbiParameter(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameter-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParameterError"})}};vr.InvalidAbiParameterError=mP;var gP=class extends mu.BaseError{constructor({params:t}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"})}};vr.InvalidAbiParametersError=gP;var hP=class extends mu.BaseError{constructor({param:t}){super("Invalid ABI parameter.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}};vr.InvalidParameterError=hP;var yP=class extends mu.BaseError{constructor({param:t,name:r}){super("Invalid ABI parameter.",{details:t,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}};vr.SolidityProtectedKeywordError=yP;var _P=class extends mu.BaseError{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}};vr.InvalidModifierError=_P;var bP=class extends mu.BaseError{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}};vr.InvalidFunctionModifierError=bP;var EP=class extends mu.BaseError{constructor({abiParameter:t}){super("Invalid ABI parameter.",{details:JSON.stringify(t,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}};vr.InvalidAbiTypeParameterError=EP});var X0=g(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.InvalidStructSignatureError=wa.UnknownSignatureError=wa.InvalidSignatureError=void 0;var AP=fu(),wP=class extends AP.BaseError{constructor({signature:t,type:r}){super(`Invalid ${r} signature.`,{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}};wa.InvalidSignatureError=wP;var vP=class extends AP.BaseError{constructor({signature:t}){super("Unknown signature.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}};wa.UnknownSignatureError=vP;var SP=class extends AP.BaseError{constructor({signature:t}){super("Invalid struct signature.",{details:t,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}};wa.InvalidStructSignatureError=SP});var PP=g(Z0=>{"use strict";Object.defineProperty(Z0,"__esModule",{value:!0});Z0.CircularReferenceError=void 0;var Dle=fu(),IP=class extends Dle.BaseError{constructor({type:t}){super("Circular reference detected.",{metaMessages:[`Struct "${t}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}};Z0.CircularReferenceError=IP});var xP=g(Q0=>{"use strict";Object.defineProperty(Q0,"__esModule",{value:!0});Q0.InvalidParenthesisError=void 0;var Lle=fu(),TP=class extends Lle.BaseError{constructor({current:t,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${t.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}};Q0.InvalidParenthesisError=TP});var NH=g(hm=>{"use strict";Object.defineProperty(hm,"__esModule",{value:!0});hm.parameterCache=void 0;hm.getParameterCacheKey=Ble;function Ble(e,t,r){let n="";if(r)for(let i of Object.entries(r)){if(!i)continue;let o="";for(let s of i[1])o+=`[${s.type}${s.name?`:${s.name}`:""}]`;n+=`(${i[0]}{${o}})`}return t?`${t}:${e}${n}`:`${e}${n}`}hm.parameterCache=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]])});var hu=g(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.parseSignature=Fle;Rn.parseFunctionSignature=kH;Rn.parseEventSignature=jH;Rn.parseErrorSignature=MH;Rn.parseConstructorSignature=qH;Rn.parseFallbackSignature=DH;Rn.parseAbiParameter=gu;Rn.splitParameters=Kn;Rn.isSolidityType=LH;Rn.isSolidityKeyword=BH;Rn.isValidDataLocation=UH;var wl=pm(),Ule=gm(),e_=El(),vl=X0(),Hle=xP(),t_=NH(),Ur=pu();function Fle(e,t={}){if((0,Ur.isFunctionSignature)(e))return kH(e,t);if((0,Ur.isEventSignature)(e))return jH(e,t);if((0,Ur.isErrorSignature)(e))return MH(e,t);if((0,Ur.isConstructorSignature)(e))return qH(e,t);if((0,Ur.isFallbackSignature)(e))return DH(e);if((0,Ur.isReceiveSignature)(e))return{type:"receive",stateMutability:"payable"};throw new vl.UnknownSignatureError({signature:e})}function kH(e,t={}){let r=(0,Ur.execFunctionSignature)(e);if(!r)throw new vl.InvalidSignatureError({signature:e,type:"function"});let n=Kn(r.parameters),i=[],o=n.length;for(let a=0;a<o;a++)i.push(gu(n[a],{modifiers:Ur.functionModifiers,structs:t,type:"function"}));let s=[];if(r.returns){let a=Kn(r.returns),c=a.length;for(let u=0;u<c;u++)s.push(gu(a[u],{modifiers:Ur.functionModifiers,structs:t,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:i,outputs:s}}function jH(e,t={}){let r=(0,Ur.execEventSignature)(e);if(!r)throw new vl.InvalidSignatureError({signature:e,type:"event"});let n=Kn(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(gu(n[s],{modifiers:Ur.eventModifiers,structs:t,type:"event"}));return{name:r.name,type:"event",inputs:i}}function MH(e,t={}){let r=(0,Ur.execErrorSignature)(e);if(!r)throw new vl.InvalidSignatureError({signature:e,type:"error"});let n=Kn(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(gu(n[s],{structs:t,type:"error"}));return{name:r.name,type:"error",inputs:i}}function qH(e,t={}){let r=(0,Ur.execConstructorSignature)(e);if(!r)throw new vl.InvalidSignatureError({signature:e,type:"constructor"});let n=Kn(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(gu(n[s],{structs:t,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:i}}function DH(e){let t=(0,Ur.execFallbackSignature)(e);if(!t)throw new vl.InvalidSignatureError({signature:e,type:"fallback"});return{type:"fallback",stateMutability:t.stateMutability??"nonpayable"}}var $le=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,Jle=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,Vle=/^u?int$/;function gu(e,t){let r=(0,t_.getParameterCacheKey)(e,t?.type,t?.structs);if(t_.parameterCache.has(r))return t_.parameterCache.get(r);let n=wl.isTupleRegex.test(e),i=(0,wl.execTyped)(n?Jle:$le,e);if(!i)throw new e_.InvalidParameterError({param:e});if(i.name&&BH(i.name))throw new e_.SolidityProtectedKeywordError({param:e,name:i.name});let o=i.name?{name:i.name}:{},s=i.modifier==="indexed"?{indexed:!0}:{},a=t?.structs??{},c,u={};if(n){c="tuple";let l=Kn(i.type),m=[],p=l.length;for(let h=0;h<p;h++)m.push(gu(l[h],{structs:a}));u={components:m}}else if(i.type in a)c="tuple",u={components:a[i.type]};else if(Vle.test(i.type))c=`${i.type}256`;else if(i.type==="address payable")c="address";else if(c=i.type,t?.type!=="struct"&&!LH(c))throw new Ule.UnknownSolidityTypeError({type:c});if(i.modifier){if(!t?.modifiers?.has?.(i.modifier))throw new e_.InvalidModifierError({param:e,type:t?.type,modifier:i.modifier});if(Ur.functionModifiers.has(i.modifier)&&!UH(c,!!i.array))throw new e_.InvalidFunctionModifierError({param:e,type:t?.type,modifier:i.modifier})}let d={type:`${c}${i.array??""}`,...o,...s,...u};return t_.parameterCache.set(r,d),d}function Kn(e,t=[],r="",n=0){let i=e.trim().length;for(let o=0;o<i;o++){let s=e[o],a=e.slice(o+1);switch(s){case",":return n===0?Kn(a,[...t,r.trim()]):Kn(a,t,`${r}${s}`,n);case"(":return Kn(a,t,`${r}${s}`,n+1);case")":return Kn(a,t,`${r}${s}`,n-1);default:return Kn(a,t,`${r}${s}`,n)}}if(r==="")return t;if(n!==0)throw new Hle.InvalidParenthesisError({current:r,depth:n});return t.push(r.trim()),t}function LH(e){return e==="address"||e==="bool"||e==="function"||e==="string"||wl.bytesRegex.test(e)||wl.integerRegex.test(e)}var Gle=/^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/;function BH(e){return e==="address"||e==="bool"||e==="function"||e==="string"||e==="tuple"||wl.bytesRegex.test(e)||wl.integerRegex.test(e)||Gle.test(e)}function UH(e,t){return t||e==="bytes"||e==="string"||e==="tuple"}});var ym=g(OP=>{"use strict";Object.defineProperty(OP,"__esModule",{value:!0});OP.parseStructs=Yle;var HH=pm(),Kle=gm(),Wle=El(),FH=X0(),zle=PP(),$H=pu(),JH=hu();function Yle(e){let t={},r=e.length;for(let s=0;s<r;s++){let a=e[s];if(!(0,$H.isStructSignature)(a))continue;let c=(0,$H.execStructSignature)(a);if(!c)throw new FH.InvalidSignatureError({signature:a,type:"struct"});let u=c.properties.split(";"),d=[],l=u.length;for(let m=0;m<l;m++){let h=u[m].trim();if(!h)continue;let y=(0,JH.parseAbiParameter)(h,{type:"struct"});d.push(y)}if(!d.length)throw new FH.InvalidStructSignatureError({signature:a});t[c.name]=d}let n={},i=Object.entries(t),o=i.length;for(let s=0;s<o;s++){let[a,c]=i[s];n[a]=VH(c,t)}return n}var Xle=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function VH(e=[],t={},r=new Set){let n=[],i=e.length;for(let o=0;o<i;o++){let s=e[o];if(HH.isTupleRegex.test(s.type))n.push(s);else{let c=(0,HH.execTyped)(Xle,s.type);if(!c?.type)throw new Wle.InvalidAbiTypeParameterError({abiParameter:s});let{array:u,type:d}=c;if(d in t){if(r.has(d))throw new zle.CircularReferenceError({type:d});n.push({...s,type:`tuple${u??""}`,components:VH(t[d],t,new Set([...r,d]))})}else if((0,JH.isSolidityType)(d))n.push(s);else throw new Kle.UnknownTypeError({type:d})}}return n}});var GH=g(RP=>{"use strict";Object.defineProperty(RP,"__esModule",{value:!0});RP.parseAbi=tfe;var Zle=pu(),Qle=ym(),efe=hu();function tfe(e){let t=(0,Qle.parseStructs)(e),r=[],n=e.length;for(let i=0;i<n;i++){let o=e[i];(0,Zle.isStructSignature)(o)||r.push((0,efe.parseSignature)(o,t))}return r}});var WH=g(CP=>{"use strict";Object.defineProperty(CP,"__esModule",{value:!0});CP.parseAbiItem=ofe;var rfe=gm(),nfe=pu(),ife=ym(),KH=hu();function ofe(e){let t;if(typeof e=="string")t=(0,KH.parseSignature)(e);else{let r=(0,ife.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if(!(0,nfe.isStructSignature)(o)){t=(0,KH.parseSignature)(o,r);break}}}if(!t)throw new rfe.InvalidAbiItemError({signature:e});return t}});var YH=g(kP=>{"use strict";Object.defineProperty(kP,"__esModule",{value:!0});kP.parseAbiParameter=cfe;var sfe=El(),NP=pu(),afe=ym(),zH=hu();function cfe(e){let t;if(typeof e=="string")t=(0,zH.parseAbiParameter)(e,{modifiers:NP.modifiers});else{let r=(0,afe.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if(!(0,NP.isStructSignature)(o)){t=(0,zH.parseAbiParameter)(o,{modifiers:NP.modifiers,structs:r});break}}}if(!t)throw new sfe.InvalidAbiParameterError({param:e});return t}});var QH=g(MP=>{"use strict";Object.defineProperty(MP,"__esModule",{value:!0});MP.parseAbiParameters=lfe;var ufe=El(),jP=pu(),dfe=ym(),XH=hu(),ZH=hu();function lfe(e){let t=[];if(typeof e=="string"){let r=(0,XH.splitParameters)(e),n=r.length;for(let i=0;i<n;i++)t.push((0,ZH.parseAbiParameter)(r[i],{modifiers:jP.modifiers}))}else{let r=(0,dfe.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if((0,jP.isStructSignature)(o))continue;let s=(0,XH.splitParameters)(o),a=s.length;for(let c=0;c<a;c++)t.push((0,ZH.parseAbiParameter)(s[c],{modifiers:jP.modifiers,structs:r}))}}if(t.length===0)throw new ufe.InvalidAbiParametersError({params:e});return t}});var _m=g(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.CircularReferenceError=le.InvalidParenthesisError=le.UnknownSignatureError=le.InvalidSignatureError=le.InvalidStructSignatureError=le.InvalidAbiParameterError=le.InvalidAbiParametersError=le.InvalidParameterError=le.SolidityProtectedKeywordError=le.InvalidModifierError=le.InvalidFunctionModifierError=le.InvalidAbiTypeParameterError=le.UnknownSolidityTypeError=le.InvalidAbiItemError=le.UnknownTypeError=le.parseAbiParameters=le.parseAbiParameter=le.parseAbiItem=le.parseAbi=le.formatAbiParameters=le.formatAbiParameter=le.formatAbiItem=le.formatAbi=le.narrow=le.BaseError=void 0;var ffe=fu();Object.defineProperty(le,"BaseError",{enumerable:!0,get:function(){return ffe.BaseError}});var pfe=SH();Object.defineProperty(le,"narrow",{enumerable:!0,get:function(){return pfe.narrow}});var mfe=IH();Object.defineProperty(le,"formatAbi",{enumerable:!0,get:function(){return mfe.formatAbi}});var gfe=cP();Object.defineProperty(le,"formatAbiItem",{enumerable:!0,get:function(){return gfe.formatAbiItem}});var hfe=iP();Object.defineProperty(le,"formatAbiParameter",{enumerable:!0,get:function(){return hfe.formatAbiParameter}});var yfe=sP();Object.defineProperty(le,"formatAbiParameters",{enumerable:!0,get:function(){return yfe.formatAbiParameters}});var _fe=GH();Object.defineProperty(le,"parseAbi",{enumerable:!0,get:function(){return _fe.parseAbi}});var bfe=WH();Object.defineProperty(le,"parseAbiItem",{enumerable:!0,get:function(){return bfe.parseAbiItem}});var Efe=YH();Object.defineProperty(le,"parseAbiParameter",{enumerable:!0,get:function(){return Efe.parseAbiParameter}});var wfe=QH();Object.defineProperty(le,"parseAbiParameters",{enumerable:!0,get:function(){return wfe.parseAbiParameters}});var qP=gm();Object.defineProperty(le,"UnknownTypeError",{enumerable:!0,get:function(){return qP.UnknownTypeError}});Object.defineProperty(le,"InvalidAbiItemError",{enumerable:!0,get:function(){return qP.InvalidAbiItemError}});Object.defineProperty(le,"UnknownSolidityTypeError",{enumerable:!0,get:function(){return qP.UnknownSolidityTypeError}});var yu=El();Object.defineProperty(le,"InvalidAbiTypeParameterError",{enumerable:!0,get:function(){return yu.InvalidAbiTypeParameterError}});Object.defineProperty(le,"InvalidFunctionModifierError",{enumerable:!0,get:function(){return yu.InvalidFunctionModifierError}});Object.defineProperty(le,"InvalidModifierError",{enumerable:!0,get:function(){return yu.InvalidModifierError}});Object.defineProperty(le,"SolidityProtectedKeywordError",{enumerable:!0,get:function(){return yu.SolidityProtectedKeywordError}});Object.defineProperty(le,"InvalidParameterError",{enumerable:!0,get:function(){return yu.InvalidParameterError}});Object.defineProperty(le,"InvalidAbiParametersError",{enumerable:!0,get:function(){return yu.InvalidAbiParametersError}});Object.defineProperty(le,"InvalidAbiParameterError",{enumerable:!0,get:function(){return yu.InvalidAbiParameterError}});var DP=X0();Object.defineProperty(le,"InvalidStructSignatureError",{enumerable:!0,get:function(){return DP.InvalidStructSignatureError}});Object.defineProperty(le,"InvalidSignatureError",{enumerable:!0,get:function(){return DP.InvalidSignatureError}});Object.defineProperty(le,"UnknownSignatureError",{enumerable:!0,get:function(){return DP.UnknownSignatureError}});var vfe=xP();Object.defineProperty(le,"InvalidParenthesisError",{enumerable:!0,get:function(){return vfe.InvalidParenthesisError}});var Sfe=PP();Object.defineProperty(le,"CircularReferenceError",{enumerable:!0,get:function(){return Sfe.CircularReferenceError}})});var Te=g(LP=>{"use strict";Object.defineProperty(LP,"__esModule",{value:!0});LP.getAction=Afe;function Afe(e,t,r){let n=e[t.name];if(typeof n=="function")return n;let i=e[r];return typeof i=="function"?i:o=>t(e,o)}});var io=g(r_=>{"use strict";Object.defineProperty(r_,"__esModule",{value:!0});r_.formatAbiItem=Pfe;r_.formatAbiParams=BP;var Ife=ft();function Pfe(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new Ife.InvalidDefinitionTypeError(e.type);return`${e.name}(${BP(e.inputs,{includeName:t})})`}function BP(e,{includeName:t=!1}={}){return e?e.map(r=>Tfe(r,{includeName:t})).join(t?", ":","):""}function Tfe(e,{includeName:t}){return e.type.startsWith("tuple")?`(${BP(e.components,{includeName:t})})${e.type.slice(5)}`:e.type+(t&&e.name?` ${e.name}`:"")}});var Sr=g(UP=>{"use strict";Object.defineProperty(UP,"__esModule",{value:!0});UP.isHex=xfe;function xfe(e,{strict:t=!0}={}){return!e||typeof e!="string"?!1:t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}});var ur=g(HP=>{"use strict";Object.defineProperty(HP,"__esModule",{value:!0});HP.size=Rfe;var Ofe=Sr();function Rfe(e){return(0,Ofe.isHex)(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}});var e9=g(n_=>{"use strict";Object.defineProperty(n_,"__esModule",{value:!0});n_.version=void 0;n_.version="2.56.1"});var ye=g(bm=>{"use strict";Object.defineProperty(bm,"__esModule",{value:!0});bm.BaseError=void 0;bm.setErrorConfig=Cfe;var t9=e9(),i_={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${t9.version}`};function Cfe(e){i_=e}var FP=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,i=r.cause instanceof e&&r.cause.docsPath||r.docsPath,o=i_.getDocsUrl?.({...r,docsPath:i}),s=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...o?[`Docs: ${o}`]:[],...n?[`Details: ${n}`]:[],...i_.version?[`Version: ${i_.version}`]:[]].join(`
11
+ `);super(s,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=t,this.version=t9.version}walk(t){return r9(this,t)}};bm.BaseError=FP;function r9(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause!==void 0?r9(e.cause,t):t?null:e}});var ft=g(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.UnsupportedPackedAbiType=ae.InvalidDefinitionTypeError=ae.InvalidArrayError=ae.InvalidAbiDecodingTypeError=ae.InvalidAbiEncodingTypeError=ae.DecodeLogTopicsMismatch=ae.DecodeLogDataMismatch=ae.BytesSizeMismatchError=ae.AbiItemAmbiguityError=ae.AbiFunctionSignatureNotFoundError=ae.AbiFunctionOutputsNotFoundError=ae.AbiFunctionNotFoundError=ae.AbiEventNotFoundError=ae.AbiEventSignatureNotFoundError=ae.AbiEventSignatureEmptyTopicsError=ae.AbiErrorSignatureNotFoundError=ae.AbiErrorNotFoundError=ae.AbiErrorInputsNotFoundError=ae.AbiEncodingLengthMismatchError=ae.AbiEncodingBytesSizeMismatchError=ae.AbiEncodingArrayLengthMismatchError=ae.AbiDecodingZeroDataError=ae.AbiDecodingDataSizeTooSmallError=ae.AbiDecodingDataSizeInvalidError=ae.AbiConstructorParamsNotFoundError=ae.AbiConstructorNotFoundError=void 0;var Em=io(),Nfe=ur(),Ze=ye(),$P=class extends Ze.BaseError{constructor({docsPath:t}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(`
12
+ `),{docsPath:t,name:"AbiConstructorNotFoundError"})}};ae.AbiConstructorNotFoundError=$P;var JP=class extends Ze.BaseError{constructor({docsPath:t}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join(`
13
+ `),{docsPath:t,name:"AbiConstructorParamsNotFoundError"})}};ae.AbiConstructorParamsNotFoundError=JP;var VP=class extends Ze.BaseError{constructor({data:t,size:r}){super([`Data size of ${r} bytes is invalid.`,"Size must be in increments of 32 bytes (size % 32 === 0)."].join(`
14
+ `),{metaMessages:[`Data: ${t} (${r} bytes)`],name:"AbiDecodingDataSizeInvalidError"})}};ae.AbiDecodingDataSizeInvalidError=VP;var GP=class extends Ze.BaseError{constructor({data:t,params:r,size:n}){super([`Data size of ${n} bytes is too small for given parameters.`].join(`
15
+ `),{metaMessages:[`Params: (${(0,Em.formatAbiParams)(r,{includeName:!0})})`,`Data: ${t} (${n} bytes)`],name:"AbiDecodingDataSizeTooSmallError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t,this.params=r,this.size=n}};ae.AbiDecodingDataSizeTooSmallError=GP;var KP=class extends Ze.BaseError{constructor({cause:t}={}){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError",cause:t})}};ae.AbiDecodingZeroDataError=KP;var WP=class extends Ze.BaseError{constructor({expectedLength:t,givenLength:r,type:n}){super([`ABI encoding array length mismatch for type ${n}.`,`Expected length: ${t}`,`Given length: ${r}`].join(`
16
+ `),{name:"AbiEncodingArrayLengthMismatchError"})}};ae.AbiEncodingArrayLengthMismatchError=WP;var zP=class extends Ze.BaseError{constructor({expectedSize:t,value:r}){super(`Size of bytes "${r}" (bytes${(0,Nfe.size)(r)}) does not match expected size (bytes${t}).`,{name:"AbiEncodingBytesSizeMismatchError"})}};ae.AbiEncodingBytesSizeMismatchError=zP;var YP=class extends Ze.BaseError{constructor({expectedLength:t,givenLength:r}){super(["ABI encoding params/values length mismatch.",`Expected length (params): ${t}`,`Given length (values): ${r}`].join(`
17
+ `),{name:"AbiEncodingLengthMismatchError"})}};ae.AbiEncodingLengthMismatchError=YP;var XP=class extends Ze.BaseError{constructor(t,{docsPath:r}){super([`Arguments (\`args\`) were provided to "${t}", but "${t}" on the ABI does not contain any parameters (\`inputs\`).`,"Cannot encode error result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the inputs exist on it."].join(`
18
+ `),{docsPath:r,name:"AbiErrorInputsNotFoundError"})}};ae.AbiErrorInputsNotFoundError=XP;var ZP=class extends Ze.BaseError{constructor(t,{docsPath:r}={}){super([`Error ${t?`"${t}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it."].join(`
19
+ `),{docsPath:r,name:"AbiErrorNotFoundError"})}};ae.AbiErrorNotFoundError=ZP;var QP=class extends Ze.BaseError{constructor(t,{docsPath:r,cause:n}){super([`Encoded error signature "${t}" not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://4byte.sourcify.dev/?q=${t}.`].join(`
20
+ `),{docsPath:r,name:"AbiErrorSignatureNotFoundError",cause:n}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.signature=t}};ae.AbiErrorSignatureNotFoundError=QP;var eT=class extends Ze.BaseError{constructor({docsPath:t}){super("Cannot extract event signature from empty topics.",{docsPath:t,name:"AbiEventSignatureEmptyTopicsError"})}};ae.AbiEventSignatureEmptyTopicsError=eT;var tT=class extends Ze.BaseError{constructor(t,{docsPath:r}){super([`Encoded event signature "${t}" not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it.",`You can look up the signature here: https://4byte.sourcify.dev/?q=${t}.`].join(`
21
+ `),{docsPath:r,name:"AbiEventSignatureNotFoundError"})}};ae.AbiEventSignatureNotFoundError=tT;var rT=class extends Ze.BaseError{constructor(t,{docsPath:r}={}){super([`Event ${t?`"${t}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it."].join(`
22
+ `),{docsPath:r,name:"AbiEventNotFoundError"})}};ae.AbiEventNotFoundError=rT;var nT=class extends Ze.BaseError{constructor(t,{docsPath:r}={}){super([`Function ${t?`"${t}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it."].join(`
23
+ `),{docsPath:r,name:"AbiFunctionNotFoundError"})}};ae.AbiFunctionNotFoundError=nT;var iT=class extends Ze.BaseError{constructor(t,{docsPath:r}){super([`Function "${t}" does not contain any \`outputs\` on ABI.`,"Cannot decode function result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the function exists on it."].join(`
24
+ `),{docsPath:r,name:"AbiFunctionOutputsNotFoundError"})}};ae.AbiFunctionOutputsNotFoundError=iT;var oT=class extends Ze.BaseError{constructor(t,{docsPath:r}){super([`Encoded function signature "${t}" not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it.",`You can look up the signature here: https://4byte.sourcify.dev/?q=${t}.`].join(`
25
+ `),{docsPath:r,name:"AbiFunctionSignatureNotFoundError"})}};ae.AbiFunctionSignatureNotFoundError=oT;var sT=class extends Ze.BaseError{constructor(t,r){super("Found ambiguous types in overloaded ABI items.",{metaMessages:[`\`${t.type}\` in \`${(0,Em.formatAbiItem)(t.abiItem)}\`, and`,`\`${r.type}\` in \`${(0,Em.formatAbiItem)(r.abiItem)}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."],name:"AbiItemAmbiguityError"})}};ae.AbiItemAmbiguityError=sT;var aT=class extends Ze.BaseError{constructor({expectedSize:t,givenSize:r}){super(`Expected bytes${t}, got bytes${r}.`,{name:"BytesSizeMismatchError"})}};ae.BytesSizeMismatchError=aT;var cT=class extends Ze.BaseError{constructor({abiItem:t,data:r,params:n,size:i}){super([`Data size of ${i} bytes is too small for non-indexed event parameters.`].join(`
26
+ `),{metaMessages:[`Params: (${(0,Em.formatAbiParams)(n,{includeName:!0})})`,`Data: ${r} (${i} bytes)`],name:"DecodeLogDataMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=t,this.data=r,this.params=n,this.size=i}};ae.DecodeLogDataMismatch=cT;var uT=class extends Ze.BaseError{constructor({abiItem:t,param:r}){super([`Expected a topic for indexed event parameter${r.name?` "${r.name}"`:""} on event "${(0,Em.formatAbiItem)(t,{includeName:!0})}".`].join(`
27
+ `),{name:"DecodeLogTopicsMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=t}};ae.DecodeLogTopicsMismatch=uT;var dT=class extends Ze.BaseError{constructor(t,{docsPath:r}){super([`Type "${t}" is not a valid encoding type.`,"Please provide a valid ABI type."].join(`
28
+ `),{docsPath:r,name:"InvalidAbiEncodingType"})}};ae.InvalidAbiEncodingTypeError=dT;var lT=class extends Ze.BaseError{constructor(t,{docsPath:r}){super([`Type "${t}" is not a valid decoding type.`,"Please provide a valid ABI type."].join(`
29
+ `),{docsPath:r,name:"InvalidAbiDecodingType"})}};ae.InvalidAbiDecodingTypeError=lT;var fT=class extends Ze.BaseError{constructor(t){super([`Value "${t}" is not a valid array.`].join(`
30
+ `),{name:"InvalidArrayError"})}};ae.InvalidArrayError=fT;var pT=class extends Ze.BaseError{constructor(t){super([`"${t}" is not a valid definition type.`,'Valid types: "function", "event", "error"'].join(`
31
+ `),{name:"InvalidDefinitionTypeError"})}};ae.InvalidDefinitionTypeError=pT;var mT=class extends Ze.BaseError{constructor(t){super(`Type "${t}" is not supported for packed encoding.`,{name:"UnsupportedPackedAbiType"})}};ae.UnsupportedPackedAbiType=mT});var hT=g(o_=>{"use strict";Object.defineProperty(o_,"__esModule",{value:!0});o_.FilterTypeNotSupportedError=void 0;var kfe=ye(),gT=class extends kfe.BaseError{constructor(t){super(`Filter type "${t}" is not supported.`,{name:"FilterTypeNotSupportedError"})}};o_.FilterTypeNotSupportedError=gT});var wm=g(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.InvalidBytesLengthError=va.SizeExceedsPaddingSizeError=va.SliceOffsetOutOfBoundsError=void 0;var ET=ye(),yT=class extends ET.BaseError{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${t}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}};va.SliceOffsetOutOfBoundsError=yT;var _T=class extends ET.BaseError{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${t}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}};va.SizeExceedsPaddingSizeError=_T;var bT=class extends ET.BaseError{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} is expected to be ${r} ${n} long, but is ${t} ${n} long.`,{name:"InvalidBytesLengthError"})}};va.InvalidBytesLengthError=bT});var oo=g(vm=>{"use strict";Object.defineProperty(vm,"__esModule",{value:!0});vm.pad=jfe;vm.padHex=i9;vm.padBytes=o9;var n9=wm();function jfe(e,{dir:t,size:r=32}={}){return typeof e=="string"?i9(e,{dir:t,size:r}):o9(e,{dir:t,size:r})}function i9(e,{dir:t,size:r=32}={}){if(r===null)return e;let n=e.replace("0x","");if(n.length>r*2)throw new n9.SizeExceedsPaddingSizeError({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[t==="right"?"padEnd":"padStart"](r*2,"0")}`}function o9(e,{dir:t,size:r=32}={}){if(r===null)return e;if(e.length>r)throw new n9.SizeExceedsPaddingSizeError({size:e.length,targetSize:r,type:"bytes"});let n=new Uint8Array(r);for(let i=0;i<r;i++){let o=t==="right";n[o?i:r-i-1]=e[o?i:e.length-i-1]}return n}});var _u=g(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.SizeOverflowError=Yt.RlpTrailingBytesError=Yt.RlpListBoundaryExceededError=Yt.RlpDepthLimitExceededError=Yt.InvalidHexValueError=Yt.InvalidHexBooleanError=Yt.InvalidBytesBooleanError=Yt.IntegerOutOfRangeError=void 0;var Sa=ye(),wT=class extends Sa.BaseError{constructor({max:t,min:r,signed:n,size:i,value:o}){super(`Number "${o}" is not in safe ${i?`${i*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${t?`(${r} to ${t})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}};Yt.IntegerOutOfRangeError=wT;var vT=class extends Sa.BaseError{constructor(t){super(`Bytes value "${t}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}};Yt.InvalidBytesBooleanError=vT;var ST=class extends Sa.BaseError{constructor(t){super(`Hex value "${t}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`,{name:"InvalidHexBooleanError"})}};Yt.InvalidHexBooleanError=ST;var AT=class extends Sa.BaseError{constructor(t){super(`Hex value "${t}" is an odd length (${t.length}). It must be an even length.`,{name:"InvalidHexValueError"})}};Yt.InvalidHexValueError=AT;var IT=class extends Sa.BaseError{constructor({limit:t}){super(`RLP depth limit of \`${t}\` exceeded.`,{name:"RlpDepthLimitExceededError"})}};Yt.RlpDepthLimitExceededError=IT;var PT=class extends Sa.BaseError{constructor({consumed:t,declared:r}){super(`RLP list items consumed \`${t}\` bytes but the list declared a length of \`${r}\`.`,{name:"RlpListBoundaryExceededError"})}};Yt.RlpListBoundaryExceededError=PT;var TT=class extends Sa.BaseError{constructor({count:t}){super(`RLP payload encodes a single item, but \`${t}\` trailing ${t===1?"byte remains":"bytes remain"}.`,{name:"RlpTrailingBytesError"})}};Yt.RlpTrailingBytesError=TT;var xT=class extends Sa.BaseError{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${t} bytes.`,{name:"SizeOverflowError"})}};Yt.SizeOverflowError=xT});var ts=g(OT=>{"use strict";Object.defineProperty(OT,"__esModule",{value:!0});OT.trim=Mfe;function Mfe(e,{dir:t="left"}={}){let r=typeof e=="string"?e.replace("0x",""):e,n=0;for(let i=0;i<r.length-1&&r[t==="left"?i:r.length-i-1].toString()==="0";i++)n++;return r=t==="left"?r.slice(n):r.slice(0,r.length-n),typeof e=="string"?(r.length===1&&t==="right"&&(r=`${r}0`),`0x${r.length%2===1?`0${r}`:r}`):r}});var pt=g(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.assertSize=a_;Aa.fromHex=qfe;Aa.hexToBigInt=CT;Aa.hexToBool=c9;Aa.hexToNumber=u9;Aa.hexToString=d9;var RT=_u(),s9=ur(),s_=ts(),a9=Je();function a_(e,{size:t}){if((0,s9.size)(e)>t)throw new RT.SizeOverflowError({givenSize:(0,s9.size)(e),maxSize:t})}function qfe(e,t){let r=typeof t=="string"?{to:t}:t,n=r.to;return n==="number"?u9(e,r):n==="bigint"?CT(e,r):n==="string"?d9(e,r):n==="boolean"?c9(e,r):(0,a9.hexToBytes)(e,r)}function CT(e,t={}){let{signed:r}=t;t.size&&a_(e,{size:t.size});let n=BigInt(e);if(!r)return n;let i=(e.length-2)/2,o=(1n<<BigInt(i)*8n-1n)-1n;return n<=o?n:n-BigInt(`0x${"f".padStart(i*2,"f")}`)-1n}function c9(e,t={}){let r=e;if(t.size&&(a_(r,{size:t.size}),r=(0,s_.trim)(r)),(0,s_.trim)(r)==="0x00")return!1;if((0,s_.trim)(r)==="0x01")return!0;throw new RT.InvalidHexBooleanError(r)}function u9(e,t={}){let r=CT(e,t),n=Number(r);if(!Number.isSafeInteger(n))throw new RT.IntegerOutOfRangeError({max:`${Number.MAX_SAFE_INTEGER}`,min:`${Number.MIN_SAFE_INTEGER}`,signed:t.signed,size:t.size,value:`${r}n`});return n}function d9(e,t={}){let r=(0,a9.hexToBytes)(e);return t.size&&(a_(r,{size:t.size}),r=(0,s_.trim)(r,{dir:"right"})),new TextDecoder().decode(r)}});var W=g(bu=>{"use strict";Object.defineProperty(bu,"__esModule",{value:!0});bu.toHex=Bfe;bu.boolToHex=f9;bu.bytesToHex=kT;bu.numberToHex=p9;bu.stringToHex=m9;var Dfe=_u(),NT=oo(),l9=pt(),Lfe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Bfe(e,t={}){return typeof e=="number"||typeof e=="bigint"?p9(e,t):typeof e=="string"?m9(e,t):typeof e=="boolean"?f9(e,t):kT(e,t)}function f9(e,t={}){let r=`0x${Number(e)}`;return typeof t.size=="number"?((0,l9.assertSize)(r,{size:t.size}),(0,NT.pad)(r,{size:t.size})):r}function kT(e,t={}){let r="";for(let i=0;i<e.length;i++)r+=Lfe[e[i]];let n=`0x${r}`;return typeof t.size=="number"?((0,l9.assertSize)(n,{size:t.size}),(0,NT.pad)(n,{dir:"right",size:t.size})):n}function p9(e,t={}){let{signed:r,size:n}=t,i=BigInt(e),o;n?r?o=(1n<<BigInt(n)*8n-1n)-1n:o=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(o=BigInt(Number.MAX_SAFE_INTEGER));let s=typeof o=="bigint"&&r?-o-1n:0;if(o&&i>o||i<s){let c=typeof e=="bigint"?"n":"";throw new Dfe.IntegerOutOfRangeError({max:o?`${o}${c}`:void 0,min:`${s}${c}`,signed:r,size:n,value:`${e}${c}`})}let a=`0x${(r&&i<0?(1n<<BigInt(n*8))+BigInt(i):i).toString(16)}`;return n?(0,NT.pad)(a,{size:n}):a}var Ufe=new TextEncoder;function m9(e,t={}){let r=Ufe.encode(e);return kT(r,t)}});var Je=g(Eu=>{"use strict";Object.defineProperty(Eu,"__esModule",{value:!0});Eu.toBytes=Vfe;Eu.boolToBytes=h9;Eu.hexToBytes=qT;Eu.numberToBytes=y9;Eu.stringToBytes=_9;var Hfe=ye(),Ffe=Sr(),jT=oo(),MT=pt(),$fe=W(),Jfe=new TextEncoder;function Vfe(e,t={}){return typeof e=="number"||typeof e=="bigint"?y9(e,t):typeof e=="boolean"?h9(e,t):(0,Ffe.isHex)(e)?qT(e,t):_9(e,t)}function h9(e,t={}){let r=new Uint8Array(1);return r[0]=Number(e),typeof t.size=="number"?((0,MT.assertSize)(r,{size:t.size}),(0,jT.pad)(r,{size:t.size})):r}var rs={zero:48,nine:57,A:65,F:70,a:97,f:102};function g9(e){if(e>=rs.zero&&e<=rs.nine)return e-rs.zero;if(e>=rs.A&&e<=rs.F)return e-(rs.A-10);if(e>=rs.a&&e<=rs.f)return e-(rs.a-10)}function qT(e,t={}){let r=e;t.size&&((0,MT.assertSize)(r,{size:t.size}),r=(0,jT.pad)(r,{dir:"right",size:t.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);let i=n.length/2,o=new Uint8Array(i);for(let s=0,a=0;s<i;s++){let c=g9(n.charCodeAt(a++)),u=g9(n.charCodeAt(a++));if(c===void 0||u===void 0)throw new Hfe.BaseError(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);o[s]=c*16+u}return o}function y9(e,t){let r=(0,$fe.numberToHex)(e,t);return qT(r)}function _9(e,t={}){let r=Jfe.encode(e);return typeof t.size=="number"?((0,MT.assertSize)(r,{size:t.size}),(0,jT.pad)(r,{dir:"right",size:t.size})):r}});var BT=g(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.toBig=be.shrSL=be.shrSH=be.rotrSL=be.rotrSH=be.rotrBL=be.rotrBH=be.rotr32L=be.rotr32H=be.rotlSL=be.rotlSH=be.rotlBL=be.rotlBH=be.add5L=be.add5H=be.add4L=be.add4H=be.add3L=be.add3H=void 0;be.add=k9;be.fromBig=LT;be.split=b9;var c_=BigInt(2**32-1),DT=BigInt(32);function LT(e,t=!1){return t?{h:Number(e&c_),l:Number(e>>DT&c_)}:{h:Number(e>>DT&c_)|0,l:Number(e&c_)|0}}function b9(e,t=!1){let r=e.length,n=new Uint32Array(r),i=new Uint32Array(r);for(let o=0;o<r;o++){let{h:s,l:a}=LT(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}var E9=(e,t)=>BigInt(e>>>0)<<DT|BigInt(t>>>0);be.toBig=E9;var w9=(e,t,r)=>e>>>r;be.shrSH=w9;var v9=(e,t,r)=>e<<32-r|t>>>r;be.shrSL=v9;var S9=(e,t,r)=>e>>>r|t<<32-r;be.rotrSH=S9;var A9=(e,t,r)=>e<<32-r|t>>>r;be.rotrSL=A9;var I9=(e,t,r)=>e<<64-r|t>>>r-32;be.rotrBH=I9;var P9=(e,t,r)=>e>>>r-32|t<<64-r;be.rotrBL=P9;var T9=(e,t)=>t;be.rotr32H=T9;var x9=(e,t)=>e;be.rotr32L=x9;var O9=(e,t,r)=>e<<r|t>>>32-r;be.rotlSH=O9;var R9=(e,t,r)=>t<<r|e>>>32-r;be.rotlSL=R9;var C9=(e,t,r)=>t<<r-32|e>>>64-r;be.rotlBH=C9;var N9=(e,t,r)=>e<<r-32|t>>>64-r;be.rotlBL=N9;function k9(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}var j9=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0);be.add3L=j9;var M9=(e,t,r,n)=>t+r+n+(e/2**32|0)|0;be.add3H=M9;var q9=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0);be.add4L=q9;var D9=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0;be.add4H=D9;var L9=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0);be.add5L=L9;var B9=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0;be.add5H=B9;var Gfe={fromBig:LT,split:b9,toBig:E9,shrSH:w9,shrSL:v9,rotrSH:S9,rotrSL:A9,rotrBH:I9,rotrBL:P9,rotr32H:T9,rotr32L:x9,rotlSH:O9,rotlSL:R9,rotlBH:C9,rotlBL:N9,add:k9,add3L:j9,add3H:M9,add4L:q9,add4H:D9,add5H:B9,add5L:L9};be.default=Gfe});var U9=g(u_=>{"use strict";Object.defineProperty(u_,"__esModule",{value:!0});u_.crypto=void 0;var Ia=require("node:crypto");u_.crypto=Ia&&typeof Ia=="object"&&"webcrypto"in Ia?Ia.webcrypto:Ia&&typeof Ia=="object"&&"randomBytes"in Ia?Ia:void 0});var is=g(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.wrapXOFConstructorWithOpts=ge.wrapConstructorWithOpts=ge.wrapConstructor=ge.Hash=ge.nextTick=ge.swap32IfBE=ge.byteSwapIfBE=ge.swap8IfBE=ge.isLE=void 0;ge.isBytes=F9;ge.anumber=UT;ge.abytes=Al;ge.ahash=Kfe;ge.aexists=Wfe;ge.aoutput=zfe;ge.u8=Yfe;ge.u32=Xfe;ge.clean=Zfe;ge.createView=Qfe;ge.rotr=epe;ge.rotl=tpe;ge.byteSwap=FT;ge.byteSwap32=$9;ge.bytesToHex=npe;ge.hexToBytes=ipe;ge.asyncLoop=spe;ge.utf8ToBytes=$T;ge.bytesToUtf8=ape;ge.toBytes=d_;ge.kdfInputToBytes=cpe;ge.concatBytes=upe;ge.checkOpts=dpe;ge.createHasher=V9;ge.createOptHasher=G9;ge.createXOFer=K9;ge.randomBytes=lpe;var Sl=U9();function F9(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function UT(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Al(e,...t){if(!F9(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Kfe(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");UT(e.outputLen),UT(e.blockLen)}function Wfe(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function zfe(e,t){Al(e);let r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Yfe(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function Xfe(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Zfe(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Qfe(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function epe(e,t){return e<<32-t|e>>>t}function tpe(e,t){return e<<t|e>>>32-t>>>0}ge.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function FT(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}ge.swap8IfBE=ge.isLE?e=>e:e=>FT(e);ge.byteSwapIfBE=ge.swap8IfBE;function $9(e){for(let t=0;t<e.length;t++)e[t]=FT(e[t]);return e}ge.swap32IfBE=ge.isLE?e=>e:$9;var J9=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",rpe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function npe(e){if(Al(e),J9)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=rpe[e[r]];return t}var ns={_0:48,_9:57,A:65,F:70,a:97,f:102};function H9(e){if(e>=ns._0&&e<=ns._9)return e-ns._0;if(e>=ns.A&&e<=ns.F)return e-(ns.A-10);if(e>=ns.a&&e<=ns.f)return e-(ns.a-10)}function ipe(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(J9)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){let s=H9(e.charCodeAt(o)),a=H9(e.charCodeAt(o+1));if(s===void 0||a===void 0){let c=e[o]+e[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}n[i]=s*16+a}return n}var ope=async()=>{};ge.nextTick=ope;async function spe(e,t,r){let n=Date.now();for(let i=0;i<e;i++){r(i);let o=Date.now()-n;o>=0&&o<t||(await(0,ge.nextTick)(),n+=o)}}function $T(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function ape(e){return new TextDecoder().decode(e)}function d_(e){return typeof e=="string"&&(e=$T(e)),Al(e),e}function cpe(e){return typeof e=="string"&&(e=$T(e)),Al(e),e}function upe(...e){let t=0;for(let n=0;n<e.length;n++){let i=e[n];Al(i),t+=i.length}let r=new Uint8Array(t);for(let n=0,i=0;n<e.length;n++){let o=e[n];r.set(o,i),i+=o.length}return r}function dpe(e,t){if(t!==void 0&&{}.toString.call(t)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(e,t)}var HT=class{};ge.Hash=HT;function V9(e){let t=n=>e().update(d_(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function G9(e){let t=(n,i)=>e(i).update(d_(n)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}function K9(e){let t=(n,i)=>e(i).update(d_(n)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}ge.wrapConstructor=V9;ge.wrapConstructorWithOpts=G9;ge.wrapXOFConstructorWithOpts=K9;function lpe(e=32){if(Sl.crypto&&typeof Sl.crypto.getRandomValues=="function")return Sl.crypto.getRandomValues(new Uint8Array(e));if(Sl.crypto&&typeof Sl.crypto.randomBytes=="function")return Uint8Array.from(Sl.crypto.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}});var JT=g(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.shake256=st.shake128=st.keccak_512=st.keccak_384=st.keccak_256=st.keccak_224=st.sha3_512=st.sha3_384=st.sha3_256=st.sha3_224=st.Keccak=void 0;st.keccakP=eF;var Am=BT(),Ar=is(),fpe=BigInt(0),Sm=BigInt(1),ppe=BigInt(2),mpe=BigInt(7),gpe=BigInt(256),hpe=BigInt(113),Y9=[],X9=[],Z9=[];for(let e=0,t=Sm,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],Y9.push(2*(5*n+r)),X9.push((e+1)*(e+2)/2%64);let i=fpe;for(let o=0;o<7;o++)t=(t<<Sm^(t>>mpe)*hpe)%gpe,t&ppe&&(i^=Sm<<(Sm<<BigInt(o))-Sm);Z9.push(i)}var Q9=(0,Am.split)(Z9,!0),ype=Q9[0],_pe=Q9[1],W9=(e,t,r)=>r>32?(0,Am.rotlBH)(e,t,r):(0,Am.rotlSH)(e,t,r),z9=(e,t,r)=>r>32?(0,Am.rotlBL)(e,t,r):(0,Am.rotlSL)(e,t,r);function eF(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let s=0;s<10;s++)r[s]=e[s]^e[s+10]^e[s+20]^e[s+30]^e[s+40];for(let s=0;s<10;s+=2){let a=(s+8)%10,c=(s+2)%10,u=r[c],d=r[c+1],l=W9(u,d,1)^r[a],m=z9(u,d,1)^r[a+1];for(let p=0;p<50;p+=10)e[s+p]^=l,e[s+p+1]^=m}let i=e[2],o=e[3];for(let s=0;s<24;s++){let a=X9[s],c=W9(i,o,a),u=z9(i,o,a),d=Y9[s];i=e[d],o=e[d+1],e[d]=c,e[d+1]=u}for(let s=0;s<50;s+=10){for(let a=0;a<10;a++)r[a]=e[s+a];for(let a=0;a<10;a++)e[s+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=ype[n],e[1]^=_pe[n]}(0,Ar.clean)(r)}var Im=class e extends Ar.Hash{constructor(t,r,n,i=!1,o=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=o,(0,Ar.anumber)(n),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=(0,Ar.u32)(this.state)}clone(){return this._cloneInto()}keccak(){(0,Ar.swap32IfBE)(this.state32),eF(this.state32,this.rounds),(0,Ar.swap32IfBE)(this.state32),this.posOut=0,this.pos=0}update(t){(0,Ar.aexists)(this),t=(0,Ar.toBytes)(t),(0,Ar.abytes)(t);let{blockLen:r,state:n}=this,i=t.length;for(let o=0;o<i;){let s=Math.min(r-this.pos,i-o);for(let a=0;a<s;a++)n[this.pos++]^=t[o++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:t,suffix:r,pos:n,blockLen:i}=this;t[n]^=r,(r&128)!==0&&n===i-1&&this.keccak(),t[i-1]^=128,this.keccak()}writeInto(t){(0,Ar.aexists)(this,!1),(0,Ar.abytes)(t),this.finish();let r=this.state,{blockLen:n}=this;for(let i=0,o=t.length;i<o;){this.posOut>=n&&this.keccak();let s=Math.min(n-this.posOut,o-i);t.set(r.subarray(this.posOut,this.posOut+s),i),this.posOut+=s,i+=s}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return(0,Ar.anumber)(t),this.xofInto(new Uint8Array(t))}digestInto(t){if((0,Ar.aoutput)(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,(0,Ar.clean)(this.state)}_cloneInto(t){let{blockLen:r,suffix:n,outputLen:i,rounds:o,enableXOF:s}=this;return t||(t=new e(r,n,i,s,o)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=o,t.suffix=n,t.outputLen=i,t.enableXOF=s,t.destroyed=this.destroyed,t}};st.Keccak=Im;var Pa=(e,t,r)=>(0,Ar.createHasher)(()=>new Im(t,e,r));st.sha3_224=Pa(6,144,224/8);st.sha3_256=Pa(6,136,256/8);st.sha3_384=Pa(6,104,384/8);st.sha3_512=Pa(6,72,512/8);st.keccak_224=Pa(1,144,224/8);st.keccak_256=Pa(1,136,256/8);st.keccak_384=Pa(1,104,384/8);st.keccak_512=Pa(1,72,512/8);var tF=(e,t,r)=>(0,Ar.createXOFer)((n={})=>new Im(t,e,n.dkLen===void 0?r:n.dkLen,!0));st.shake128=tF(31,168,128/8);st.shake256=tF(31,136,256/8)});var Hr=g(VT=>{"use strict";Object.defineProperty(VT,"__esModule",{value:!0});VT.keccak256=Spe;var bpe=JT(),Epe=Sr(),wpe=Je(),vpe=W();function Spe(e,t){let r=t||"hex",n=(0,bpe.keccak_256)((0,Epe.isHex)(e,{strict:!1})?(0,wpe.toBytes)(e):e);return r==="bytes"?n:(0,vpe.toHex)(n)}});var rF=g(GT=>{"use strict";Object.defineProperty(GT,"__esModule",{value:!0});GT.hashSignature=Tpe;var Ape=Je(),Ipe=Hr(),Ppe=e=>(0,Ipe.keccak256)((0,Ape.toBytes)(e));function Tpe(e){return Ppe(e)}});var nF=g(KT=>{"use strict";Object.defineProperty(KT,"__esModule",{value:!0});KT.normalizeSignature=Ope;var xpe=ye();function Ope(e){let t=!0,r="",n=0,i="",o=!1;for(let s=0;s<e.length;s++){let a=e[s];if(["(",")",","].includes(a)&&(t=!0),a==="("&&n++,a===")"&&n--,!!t){if(n===0){if(a===" "&&["event","function",""].includes(i))i="";else if(i+=a,a===")"){o=!0;break}continue}if(a===" "){e[s-1]!==","&&r!==","&&r!==",("&&(r="",t=!1);continue}i+=a,r+=a}}if(!o)throw new xpe.BaseError("Unable to normalize signature.");return i}});var f_=g(l_=>{"use strict";Object.defineProperty(l_,"__esModule",{value:!0});l_.toSignature=void 0;var Rpe=_m(),Cpe=nF(),Npe=e=>{let t=typeof e=="string"?e:(0,Rpe.formatAbiItem)(e);return(0,Cpe.normalizeSignature)(t)};l_.toSignature=Npe});var Pm=g(WT=>{"use strict";Object.defineProperty(WT,"__esModule",{value:!0});WT.toSignatureHash=Mpe;var kpe=rF(),jpe=f_();function Mpe(e){return(0,kpe.hashSignature)((0,jpe.toSignature)(e))}});var wu=g(p_=>{"use strict";Object.defineProperty(p_,"__esModule",{value:!0});p_.toEventSelector=void 0;var qpe=Pm();p_.toEventSelector=qpe.toSignatureHash});var Wn=g(m_=>{"use strict";Object.defineProperty(m_,"__esModule",{value:!0});m_.InvalidAddressError=void 0;var Dpe=ye(),zT=class extends Dpe.BaseError{constructor({address:t}){super(`Address "${t}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}};m_.InvalidAddressError=zT});var Ta=g(g_=>{"use strict";Object.defineProperty(g_,"__esModule",{value:!0});g_.LruMap=void 0;var YT=class extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){let r=super.get(t);return super.has(t)&&(super.delete(t),super.set(t,r)),r}set(t,r){if(super.has(t)&&super.delete(t),super.set(t,r),this.maxSize&&this.size>this.maxSize){let n=super.keys().next().value;n!==void 0&&super.delete(n)}return this}};g_.LruMap=YT});var Ir=g(h_=>{"use strict";Object.defineProperty(h_,"__esModule",{value:!0});h_.checksumAddress=iF;h_.getAddress=$pe;var Lpe=Wn(),Bpe=Je(),Upe=Hr(),Hpe=Ta(),Fpe=Pr(),XT=new Hpe.LruMap(8192);function iF(e,t){if(XT.has(`${e}.${t}`))return XT.get(`${e}.${t}`);let r=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),n=(0,Upe.keccak256)((0,Bpe.stringToBytes)(r),"bytes"),i=(t?r.substring(`${t}0x`.length):r).split("");for(let s=0;s<40;s+=2)n[s>>1]>>4>=8&&i[s]&&(i[s]=i[s].toUpperCase()),(n[s>>1]&15)>=8&&i[s+1]&&(i[s+1]=i[s+1].toUpperCase());let o=`0x${i.join("")}`;return XT.set(`${e}.${t}`,o),o}function $pe(e,t){if(!(0,Fpe.isAddress)(e,{strict:!1}))throw new Lpe.InvalidAddressError({address:e});return iF(e,t)}});var Pr=g(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.isAddressCache=void 0;xa.isAddress=Kpe;var Jpe=Ta(),Vpe=Ir(),Gpe=/^0x[a-fA-F0-9]{40}$/;xa.isAddressCache=new Jpe.LruMap(8192);function Kpe(e,t){let{strict:r=!0}=t??{},n=`${e}.${r}`;if(xa.isAddressCache.has(n))return xa.isAddressCache.get(n);let i=Gpe.test(e)?e.toLowerCase()===e?!0:r?(0,Vpe.checksumAddress)(e)===e:!0:!1;return xa.isAddressCache.set(n,i),i}});var Nt=g(Tm=>{"use strict";Object.defineProperty(Tm,"__esModule",{value:!0});Tm.concat=Wpe;Tm.concatBytes=oF;Tm.concatHex=sF;function Wpe(e){return typeof e[0]=="string"?sF(e):oF(e)}function oF(e){let t=0;for(let i of e)t+=i.length;let r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return r}function sF(e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}});var on=g(xm=>{"use strict";Object.defineProperty(xm,"__esModule",{value:!0});xm.slice=Ype;xm.sliceBytes=dF;xm.sliceHex=lF;var aF=wm(),zpe=Sr(),y_=ur();function Ype(e,t,r,{strict:n}={}){return(0,zpe.isHex)(e,{strict:!1})?lF(e,t,r,{strict:n}):dF(e,t,r,{strict:n})}function cF(e,t){if(typeof t=="number"&&t>0&&t>(0,y_.size)(e)-1)throw new aF.SliceOffsetOutOfBoundsError({offset:t,position:"start",size:(0,y_.size)(e)})}function uF(e,t,r){if(typeof t=="number"&&typeof r=="number"&&(0,y_.size)(e)!==r-t)throw new aF.SliceOffsetOutOfBoundsError({offset:r,position:"end",size:(0,y_.size)(e)})}function dF(e,t,r,{strict:n}={}){cF(e,t);let i=e.slice(t,r);return n&&uF(i,t,r),i}function lF(e,t,r,{strict:n}={}){cF(e,t);let i=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;return n&&uF(i,t,r),i}});var Om=g(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.integerRegex=Oa.bytesRegex=Oa.arrayRegex=void 0;Oa.arrayRegex=/^(.*)\[([0-9]*)\]$/;Oa.bytesRegex=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/;Oa.integerRegex=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/});var zn=g(__=>{"use strict";Object.defineProperty(__,"__esModule",{value:!0});__.encodeAbiParameters=nme;__.getArrayComponents=tx;var Rm=ft(),Xpe=Wn(),Zpe=ye(),Qpe=_u(),eme=Pr(),Il=Nt(),vu=oo(),Cm=ur(),tme=on(),Su=W(),rme=Om();function nme(e,t){if(e.length!==t.length)throw new Rm.AbiEncodingLengthMismatchError({expectedLength:e.length,givenLength:t.length});let r=ime({params:e,values:t});return ex(r)}function ime({params:e,values:t}){let r=[];for(let n=0;n<e.length;n++)r.push(QT({param:e[n],value:t[n]}));return r}function QT({param:e,value:t}){let r=tx(e.type);if(r){let[n,i]=r;return sme(t,{length:n,param:{...e,type:i}})}if(e.type==="tuple")return lme(t,{param:e});if(e.type==="address")return ome(t);if(e.type==="bool")return cme(t);if(e.type.startsWith("uint")||e.type.startsWith("int")){let n=e.type.startsWith("int"),[,,i="256"]=rme.integerRegex.exec(e.type)??[];return ume(t,{signed:n,size:Number(i)})}if(e.type.startsWith("bytes"))return ame(t,{param:e});if(e.type==="string")return dme(t);throw new Rm.InvalidAbiEncodingTypeError(e.type,{docsPath:"/docs/contract/encodeAbiParameters"})}function ex(e){let t=0;for(let o=0;o<e.length;o++){let{dynamic:s,encoded:a}=e[o];s?t+=32:t+=(0,Cm.size)(a)}let r=[],n=[],i=0;for(let o=0;o<e.length;o++){let{dynamic:s,encoded:a}=e[o];s?(r.push((0,Su.numberToHex)(t+i,{size:32})),n.push(a),i+=(0,Cm.size)(a)):r.push(a)}return(0,Il.concatHex)([...r,...n])}function ome(e){if(!(0,eme.isAddress)(e))throw new Xpe.InvalidAddressError({address:e});return{dynamic:!1,encoded:(0,vu.padHex)(e.toLowerCase())}}function sme(e,{length:t,param:r}){let n=t===null;if(!Array.isArray(e))throw new Rm.InvalidArrayError(e);if(!n&&e.length!==t)throw new Rm.AbiEncodingArrayLengthMismatchError({expectedLength:t,givenLength:e.length,type:`${r.type}[${t}]`});let i=e.length===0&&ZT(r),o=[];for(let s=0;s<e.length;s++){let a=QT({param:r,value:e[s]});a.dynamic&&(i=!0),o.push(a)}if(n||i){let s=ex(o);if(n){let a=(0,Su.numberToHex)(o.length,{size:32});return{dynamic:!0,encoded:(0,Il.concatHex)([a,s])}}if(i)return{dynamic:!0,encoded:s}}return{dynamic:!1,encoded:(0,Il.concatHex)(o.map(({encoded:s})=>s))}}function ame(e,{param:t}){let[,r]=t.type.split("bytes"),n=(0,Cm.size)(e);if(!r){let i=e;return n%32!==0&&(i=(0,vu.padHex)(i,{dir:"right",size:Math.ceil((e.length-2)/2/32)*32})),{dynamic:!0,encoded:(0,Il.concatHex)([(0,vu.padHex)((0,Su.numberToHex)(n,{size:32})),i])}}if(n!==Number.parseInt(r,10))throw new Rm.AbiEncodingBytesSizeMismatchError({expectedSize:Number.parseInt(r,10),value:e});return{dynamic:!1,encoded:(0,vu.padHex)(e,{dir:"right"})}}function cme(e){if(typeof e!="boolean")throw new Zpe.BaseError(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:(0,vu.padHex)((0,Su.boolToHex)(e))}}function ume(e,{signed:t,size:r=256}){if(typeof r=="number"){let n=2n**(BigInt(r)-(t?1n:0n))-1n,i=t?-n-1n:0n;if(e>n||e<i)throw new Qpe.IntegerOutOfRangeError({max:n.toString(),min:i.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:(0,Su.numberToHex)(e,{size:32,signed:t})}}function dme(e){let t=(0,Su.stringToHex)(e),r=Math.ceil((0,Cm.size)(t)/32),n=[];for(let i=0;i<r;i++)n.push((0,vu.padHex)((0,tme.slice)(t,i*32,(i+1)*32),{dir:"right"}));return{dynamic:!0,encoded:(0,Il.concatHex)([(0,vu.padHex)((0,Su.numberToHex)((0,Cm.size)(t),{size:32})),...n])}}function lme(e,{param:t}){let r=!1,n=[];for(let i=0;i<t.components.length;i++){let o=t.components[i],s=Array.isArray(e)?i:o.name,a=QT({param:o,value:e[s]});n.push(a),a.dynamic&&(r=!0)}return{dynamic:r,encoded:r?ex(n):(0,Il.concatHex)(n.map(({encoded:i})=>i))}}function tx(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function ZT(e){let{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return e.components.some(ZT);let r=tx(t);return r?ZT({...e,type:r[1]}):!1}});var Ra=g(b_=>{"use strict";Object.defineProperty(b_,"__esModule",{value:!0});b_.toFunctionSelector=void 0;var fme=on(),pme=Pm(),mme=e=>(0,fme.slice)((0,pme.toSignatureHash)(e),0,4);b_.toFunctionSelector=mme});var so=g(Nm=>{"use strict";Object.defineProperty(Nm,"__esModule",{value:!0});Nm.getAbiItem=bme;Nm.isArgOfType=E_;Nm.getAmbiguousTypes=nx;var gme=ft(),hme=Sr(),rx=Pr(),yme=wu(),_me=Ra();function bme(e){let{abi:t,args:r=[],name:n}=e,i=(0,hme.isHex)(n,{strict:!1}),o=t.filter(a=>i?a.type==="function"?(0,_me.toFunctionSelector)(a)===n:a.type==="event"?(0,yme.toEventSelector)(a)===n:!1:"name"in a&&a.name===n);if(o.length===0)return;if(o.length===1)return o[0];let s;for(let a of o){if(!("inputs"in a))continue;if(!r||r.length===0){if(!a.inputs||a.inputs.length===0)return a;continue}if(!a.inputs||a.inputs.length===0||a.inputs.length!==r.length)continue;if(r.every((u,d)=>{let l="inputs"in a&&a.inputs[d];return l?E_(u,l):!1})){if(s&&"inputs"in s&&s.inputs){let u=nx(a.inputs,s.inputs,r);if(u)throw new gme.AbiItemAmbiguityError({abiItem:a,type:u[0]},{abiItem:s,type:u[1]})}s=a}}return s||o[0]}function E_(e,t){let r=typeof e,n=t.type;switch(n){case"address":return(0,rx.isAddress)(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in t?Object.values(t.components).every((i,o)=>r==="object"&&E_(Object.values(e)[o],i)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?r==="number"||r==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?r==="string"||e instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(e)&&e.every(i=>E_(i,{...t,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function nx(e,t,r){for(let n in e){let i=e[n],o=t[n];if(i.type==="tuple"&&o.type==="tuple"&&"components"in i&&"components"in o)return nx(i.components,o.components,r[n]);let s=[i.type,o.type];if(s.includes("address")&&s.includes("bytes20")?!0:s.includes("address")&&s.includes("string")?(0,rx.isAddress)(r[n],{strict:!1}):s.includes("address")&&s.includes("bytes")?(0,rx.isAddress)(r[n],{strict:!1}):!1)return s}}});var Ca=g(ix=>{"use strict";Object.defineProperty(ix,"__esModule",{value:!0});ix.encodeEventTopics=Tme;var fF=ft(),Eme=hT(),wme=Je(),vme=Hr(),Sme=wu(),Ame=zn(),Ime=io(),Pme=so(),pF="/docs/contract/encodeEventTopics";function Tme(e){let{abi:t,eventName:r,args:n}=e,i=t[0];if(r){let c=(0,Pme.getAbiItem)({abi:t,name:r});if(!c)throw new fF.AbiEventNotFoundError(r,{docsPath:pF});i=c}if(i.type!=="event")throw new fF.AbiEventNotFoundError(void 0,{docsPath:pF});let o=[];if(n&&"inputs"in i){let c=i.inputs?.filter(d=>"indexed"in d&&d.indexed),u=Array.isArray(n)?n:Object.values(n).length>0?c?.map(d=>n[d.name])??[]:[];u.length>0&&(o=c?.map((d,l)=>Array.isArray(u[l])?u[l].map((m,p)=>mF({param:d,value:u[l][p]})):typeof u[l]<"u"&&u[l]!==null?mF({param:d,value:u[l]}):null)??[])}if(i.anonymous)return o;let s=(0,Ime.formatAbiItem)(i);return[(0,Sme.toEventSelector)(s),...o]}function mF({param:e,value:t}){if(e.type==="string"||e.type==="bytes")return(0,vme.keccak256)((0,wme.toBytes)(t));if(e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))throw new Eme.FilterTypeNotSupportedError(e.type);return(0,Ame.encodeAbiParameters)([e],[t])}});var km=g(ox=>{"use strict";Object.defineProperty(ox,"__esModule",{value:!0});ox.createFilterRequestScope=xme;function xme(e,{method:t}){let r={};return e.transport.type==="fallback"&&e.transport.onResponse?.(({method:n,response:i,status:o,transport:s})=>{o==="success"&&t===n&&(r[i]=s.request)}),(n=>r[n]||e.request)}});var w_=g(sx=>{"use strict";Object.defineProperty(sx,"__esModule",{value:!0});sx.createContractEventFilter=Cme;var Ome=Ca(),gF=W(),Rme=km();async function Cme(e,t){let{address:r,abi:n,args:i,eventName:o,fromBlock:s,strict:a,toBlock:c}=t,u=(0,Rme.createFilterRequestScope)(e,{method:"eth_newFilter"}),d=o?(0,Ome.encodeEventTopics)({abi:n,args:i,eventName:o}):void 0,l=await e.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof s=="bigint"?(0,gF.numberToHex)(s):s,toBlock:typeof c=="bigint"?(0,gF.numberToHex)(c):c,topics:d}]});return{abi:n,args:i,eventName:o,id:l,request:u(l),strict:!!a,type:"event"}}});var at=g(ax=>{"use strict";Object.defineProperty(ax,"__esModule",{value:!0});ax.parseAccount=Nme;function Nme(e){return typeof e=="string"?{address:e,type:"json-rpc"}:e}});var ux=g(cx=>{"use strict";Object.defineProperty(cx,"__esModule",{value:!0});cx.prepareEncodeFunctionData=qme;var hF=ft(),kme=Ra(),jme=io(),Mme=so(),yF="/docs/contract/encodeFunctionData";function qme(e){let{abi:t,args:r,functionName:n}=e,i=t[0];if(n){let o=(0,Mme.getAbiItem)({abi:t,args:r,name:n});if(!o)throw new hF.AbiFunctionNotFoundError(n,{docsPath:yF});i=o}if(i.type!=="function")throw new hF.AbiFunctionNotFoundError(void 0,{docsPath:yF});return{abi:[i],functionName:(0,kme.toFunctionSelector)((0,jme.formatAbiItem)(i))}}});var Tr=g(dx=>{"use strict";Object.defineProperty(dx,"__esModule",{value:!0});dx.encodeFunctionData=Ume;var Dme=Nt(),Lme=zn(),Bme=ux();function Ume(e){let{args:t}=e,{abi:r,functionName:n}=e.abi.length===1&&e.functionName?.startsWith("0x")?e:(0,Bme.prepareEncodeFunctionData)(e),i=r[0],o=n,s="inputs"in i&&i.inputs?(0,Lme.encodeAbiParameters)(i.inputs,t??[]):void 0;return(0,Dme.concatHex)([o,s??"0x"])}});var jm=g(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.solidityPanic=Na.solidityError=Na.panicReasons=void 0;Na.panicReasons={1:"An `assert` condition failed.",17:"Arithmetic operation resulted in underflow or overflow.",18:"Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).",33:"Attempted to convert to an invalid type.",34:"Attempted to access a storage byte array that is incorrectly encoded.",49:"Performed `.pop()` on an empty array",50:"Array index is out of bounds.",65:"Allocated too much memory or created an array which is too large.",81:"Attempted to call a zero-initialized variable of internal function type."};Na.solidityError={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"};Na.solidityPanic={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"}});var gx=g(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.RecursiveReadLimitExceededError=ka.PositionOutOfBoundsError=ka.NegativeOffsetError=void 0;var mx=ye(),lx=class extends mx.BaseError{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`,{name:"NegativeOffsetError"})}};ka.NegativeOffsetError=lx;var fx=class extends mx.BaseError{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`,{name:"PositionOutOfBoundsError"})}};ka.PositionOutOfBoundsError=fx;var px=class extends mx.BaseError{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`,{name:"RecursiveReadLimitExceededError"})}};ka.RecursiveReadLimitExceededError=px});var Pl=g(hx=>{"use strict";Object.defineProperty(hx,"__esModule",{value:!0});hx.createCursor=Fme;var v_=gx(),Hme={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new v_.RecursiveReadLimitExceededError({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new v_.PositionOutOfBoundsError({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new v_.NegativeOffsetError({offset:e});let t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new v_.NegativeOffsetError({offset:e});let t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){let r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){let t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){let t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){let t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();let r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();let e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();let e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();let e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();let e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){let t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;let e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};function Fme(e,{recursiveReadLimit:t=8192}={}){let r=Object.create(Hme);return r.bytes=e,r.dataView=new DataView(e.buffer??e,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}});var S_=g(Au=>{"use strict";Object.defineProperty(Au,"__esModule",{value:!0});Au.fromBytes=Jme;Au.bytesToBigInt=bF;Au.bytesToBool=EF;Au.bytesToNumber=wF;Au.bytesToString=vF;var $me=_u(),_F=ts(),Tl=pt(),yx=W();function Jme(e,t){let r=typeof t=="string"?{to:t}:t,n=r.to;return n==="number"?wF(e,r):n==="bigint"?bF(e,r):n==="boolean"?EF(e,r):n==="string"?vF(e,r):(0,yx.bytesToHex)(e,r)}function bF(e,t={}){typeof t.size<"u"&&(0,Tl.assertSize)(e,{size:t.size});let r=(0,yx.bytesToHex)(e);return(0,Tl.hexToBigInt)(r,t)}function EF(e,t={}){let r=e;if(typeof t.size<"u"&&((0,Tl.assertSize)(r,{size:t.size}),r=(0,_F.trim)(r)),r.length>1||r[0]>1)throw new $me.InvalidBytesBooleanError(r);return!!r[0]}function wF(e,t={}){typeof t.size<"u"&&(0,Tl.assertSize)(e,{size:t.size});let r=(0,yx.bytesToHex)(e);return(0,Tl.hexToNumber)(r,t)}function vF(e,t={}){let r=e;return typeof t.size<"u"&&((0,Tl.assertSize)(r,{size:t.size}),r=(0,_F.trim)(r,{dir:"right"})),new TextDecoder().decode(r)}});var os=g(Ex=>{"use strict";Object.defineProperty(Ex,"__esModule",{value:!0});Ex.decodeAbiParameters=zme;var _x=ft(),Vme=Ir(),Gme=Pl(),A_=ur(),Kme=on(),Yn=S_(),Wme=Je(),I_=W(),AF=zn();function zme(e,t){let r=typeof t=="string"?(0,Wme.hexToBytes)(t):t,n=(0,Gme.createCursor)(r);if((0,A_.size)(r)===0&&e.length>0)throw new _x.AbiDecodingZeroDataError;if((0,A_.size)(t)&&(0,A_.size)(t)<32)throw new _x.AbiDecodingDataSizeTooSmallError({data:typeof t=="string"?t:(0,I_.bytesToHex)(t),params:e,size:(0,A_.size)(t)});let i=0,o=[];for(let s=0;s<e.length;++s){let a=e[s];i<r.length&&n.setPosition(i);let[c,u]=xl(n,a,{staticPosition:0});i+=u,o.push(c)}return o}function xl(e,t,{staticPosition:r}){let n=(0,AF.getArrayComponents)(t.type);if(n){let[i,o]=n;return Xme(e,{...t,type:o},{length:i,staticPosition:r})}if(t.type==="tuple")return tge(e,t,{staticPosition:r});if(t.type==="address")return Yme(e);if(t.type==="bool")return Zme(e);if(t.type.startsWith("bytes"))return Qme(e,t,{staticPosition:r});if(t.type.startsWith("uint")||t.type.startsWith("int"))return ege(e,t);if(t.type==="string")return rge(e,{staticPosition:r});throw new _x.InvalidAbiDecodingTypeError(t.type,{docsPath:"/docs/contract/decodeAbiParameters"})}var SF=32,bx=32;function Yme(e){let t=e.readBytes(32);return[(0,Vme.checksumAddress)((0,I_.bytesToHex)((0,Kme.sliceBytes)(t,-20))),32]}function Xme(e,t,{length:r,staticPosition:n}){if(r===null){let s=(0,Yn.bytesToNumber)(e.readBytes(bx)),a=n+s,c=a+SF;e.setPosition(a);let u=(0,Yn.bytesToNumber)(e.readBytes(SF)),d=Mm(t),l=0,m=[];for(let p=0;p<u;++p){e.setPosition(c+(d?p*32:l));let[h,y]=xl(e,t,{staticPosition:c});l+=y,m.push(h),y===0&&(e.assertReadLimit(),e._touch())}return e.setPosition(n+32),[m,32]}if(Mm(t)){let s=(0,Yn.bytesToNumber)(e.readBytes(bx)),a=n+s,c=[];for(let u=0;u<r;++u){e.setPosition(a+u*32);let[d]=xl(e,t,{staticPosition:a});c.push(d)}return e.setPosition(n+32),[c,32]}let i=0,o=[];for(let s=0;s<r;++s){let[a,c]=xl(e,t,{staticPosition:n+i});i+=c,o.push(a),c===0&&(e.assertReadLimit(),e._touch())}return[o,i]}function Zme(e){return[(0,Yn.bytesToBool)(e.readBytes(32),{size:32}),32]}function Qme(e,t,{staticPosition:r}){let[n,i]=t.type.split("bytes");if(!i){let s=(0,Yn.bytesToNumber)(e.readBytes(32));e.setPosition(r+s);let a=(0,Yn.bytesToNumber)(e.readBytes(32));if(a===0)return e.setPosition(r+32),["0x",32];let c=e.readBytes(a);return e.setPosition(r+32),[(0,I_.bytesToHex)(c),32]}return[(0,I_.bytesToHex)(e.readBytes(Number.parseInt(i,10),32)),32]}function ege(e,t){let r=t.type.startsWith("int"),n=Number.parseInt(t.type.split("int")[1]||"256",10),i=e.readBytes(32);return[n>48?(0,Yn.bytesToBigInt)(i,{signed:r}):(0,Yn.bytesToNumber)(i,{signed:r}),32]}function tge(e,t,{staticPosition:r}){let n=t.components.length===0||t.components.some(({name:s})=>!s),i=n?[]:{},o=0;if(Mm(t)){let s=(0,Yn.bytesToNumber)(e.readBytes(bx)),a=r+s;for(let c=0;c<t.components.length;++c){let u=t.components[c];e.setPosition(a+o);let[d,l]=xl(e,u,{staticPosition:a});o+=l,i[n?c:u?.name]=d}return e.setPosition(r+32),[i,32]}for(let s=0;s<t.components.length;++s){let a=t.components[s],[c,u]=xl(e,a,{staticPosition:r});i[n?s:a?.name]=c,o+=u}return[i,o]}function rge(e,{staticPosition:t}){let r=(0,Yn.bytesToNumber)(e.readBytes(32)),n=t+r;e.setPosition(n);let i=(0,Yn.bytesToNumber)(e.readBytes(32));if(i===0)return e.setPosition(t+32),["",32];let o=e.readBytes(i,32),s=(0,Yn.bytesToString)(o);return e.setPosition(t+32),[s,32]}function Mm(e){let{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return e.components?.some(Mm);let r=(0,AF.getArrayComponents)(e.type);return!!(r&&Mm({...e,type:r[1]}))}});var Ol=g(wx=>{"use strict";Object.defineProperty(wx,"__esModule",{value:!0});wx.decodeErrorResult=sge;var IF=jm(),PF=ft(),TF=on(),nge=Ra(),ige=os(),oge=io();function sge(e){let{abi:t,data:r,cause:n}=e,i=(0,TF.slice)(r,0,4);if(i==="0x")throw new PF.AbiDecodingZeroDataError({cause:n});let s=[...t||[],IF.solidityError,IF.solidityPanic].find(a=>a.type==="error"&&i===(0,nge.toFunctionSelector)((0,oge.formatAbiItem)(a)));if(!s)throw new PF.AbiErrorSignatureNotFoundError(i,{docsPath:"/docs/contract/decodeErrorResult",cause:n});return{abiItem:s,args:"inputs"in s&&s.inputs&&s.inputs.length>0?(0,ige.decodeAbiParameters)(s.inputs,(0,TF.slice)(r,4)):void 0,errorName:s.name}}});var Mt=g(P_=>{"use strict";Object.defineProperty(P_,"__esModule",{value:!0});P_.stringify=void 0;var age=(e,t,r)=>JSON.stringify(e,(n,i)=>{let o=typeof i=="bigint"?i.toString():i;return typeof t=="function"?t(n,o):o},r);P_.stringify=age});var Sx=g(vx=>{"use strict";Object.defineProperty(vx,"__esModule",{value:!0});vx.formatAbiItemWithArgs=uge;var cge=Mt();function uge({abiItem:e,args:t,includeFunctionName:r=!0,includeName:n=!1}){if("name"in e&&"inputs"in e&&e.inputs)return`${r?e.name:""}(${e.inputs.map((i,o)=>`${n&&i.name?`${i.name}: `:""}${typeof t[o]=="object"?(0,cge.stringify)(t[o]):t[o]}`).join(", ")})`}});var Iu=g(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.format=Ix;Ma.formatEther=dge;Ma.formatGwei=lge;Ma.from=Px;Ma.fromEther=pge;Ma.fromGwei=mge;var ja={wei:0,gwei:9,szabo:12,finney:15,ether:18};function Ix(e,t=0){if(!Number.isInteger(t)||t<0)throw new T_({decimals:t});let r=e.toString(),n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(t,"0");let[i,o]=[r.slice(0,r.length-t),r.slice(r.length-t)];return o=o.replace(/(0+)$/,""),`${n?"-":""}${i||"0"}${o?`.${o}`:""}`}function dge(e,t="wei"){return Ix(e,ja.ether-ja[t])}function lge(e,t="wei"){return Ix(e,ja.gwei-ja[t])}function Px(e,t=0){if(!Number.isInteger(t)||t<0)throw new T_({decimals:t});if(!/^-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/.test(e))throw new Ax({value:e});let[r="",n="0"]=e.split("."),i=r.startsWith("-");if(i&&(r=r.slice(1)),r===""&&(r="0"),n=n.replace(/(0+)$/,""),t===0)n.length>0&&Number.parseInt(n[0],10)>=5&&(r=`${BigInt(r)+1n}`),n="";else if(n.length>t){let o=n.slice(0,t);if(Number.parseInt(n.slice(t,t+1),10)>=5){let a=fge(o);a.length>t?(n=a.slice(1),r=`${BigInt(r)+1n}`):n=a}else n=o}else n=n.padEnd(t,"0");return BigInt(`${i?"-":""}${r}${n}`)}function fge(e){let t=e.split(""),r=t.length-1;for(;r>=0;){let n=Number.parseInt(t[r],10)+1;if(n<10)return t[r]=String(n),t.join("");t[r]="0",r--}return`1${t.join("")}`}function pge(e,t="wei"){return Px(e,ja.ether-ja[t])}function mge(e,t="wei"){return Px(e,ja.gwei-ja[t])}var Ax=class extends Error{constructor({value:t}){super(`Value \`${t}\` is not a valid decimal number.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Value.InvalidDecimalNumberError"})}},T_=class extends Error{constructor({decimals:t}){super(`\`decimals\` must be a non-negative integer. Got \`${t}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Value.InvalidDecimalsError"})}}});var Rl=g(Tx=>{"use strict";Object.defineProperty(Tx,"__esModule",{value:!0});Tx.formatEther=hge;var gge=Iu();function hge(e,t="wei"){return gge.formatEther(e,t)}});var qa=g(xx=>{"use strict";Object.defineProperty(xx,"__esModule",{value:!0});xx.formatGwei=_ge;var yge=Iu();function _ge(e,t="wei"){return yge.formatGwei(e,t)}});var x_=g(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.StateAssignmentConflictError=Da.AccountStateConflictError=void 0;Da.prettyStateMapping=Cx;Da.prettyStateOverride=bge;var xF=ye(),Ox=class extends xF.BaseError{constructor({address:t}){super(`State for account "${t}" is set multiple times.`,{name:"AccountStateConflictError"})}};Da.AccountStateConflictError=Ox;var Rx=class extends xF.BaseError{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}};Da.StateAssignmentConflictError=Rx;function Cx(e){return e.reduce((t,{slot:r,value:n})=>`${t} ${r}: ${n}
32
+ `,"")}function bge(e){return e.reduce((t,{address:r,...n})=>{let i=`${t} ${r}:
33
+ `;return n.nonce&&(i+=` nonce: ${n.nonce}
34
+ `),n.balance&&(i+=` balance: ${n.balance}
35
+ `),n.code&&(i+=` code: ${n.code}
36
+ `),n.state&&(i+=` state:
37
+ `,i+=Cx(n.state)),n.stateDiff&&(i+=` stateDiff:
38
+ `,i+=Cx(n.stateDiff)),i},` State Override:
39
+ `).slice(0,-1)}});var Xt=g(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.WaitForTransactionReceiptTimeoutError=He.TransactionReceiptRevertedError=He.TransactionReceiptNotFoundError=He.TransactionNotFoundError=He.TransactionExecutionError=He.InvalidStorageKeySizeError=He.InvalidSerializedTransactionError=He.InvalidSerializedTransactionTypeError=He.InvalidSerializableTransactionError=He.InvalidYParityError=He.InvalidLegacyVError=He.FeePayerNonceMismatchError=He.FeeConflictError=void 0;He.prettyPrint=Gx;var Ege=Rl(),Nx=qa(),Cn=ye();function Gx(e){let t=Object.entries(e).map(([n,i])=>i===void 0||i===!1?null:[n,i]).filter(Boolean),r=t.reduce((n,[i])=>Math.max(n,i.length),0);return t.map(([n,i])=>` ${`${n}:`.padEnd(r+1)} ${i}`).join(`
40
+ `)}var kx=class extends Cn.BaseError{constructor(){super(["Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.","Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others."].join(`
41
+ `),{name:"FeeConflictError"})}};He.FeeConflictError=kx;var jx=class extends Cn.BaseError{constructor({filledNonce:t,requestedNonce:r}){super("The filled transaction nonce does not match the requested nonce.",{metaMessages:[`Requested Nonce: ${r}`,`Filled Nonce: ${t}`],name:"FeePayerNonceMismatchError"})}};He.FeePayerNonceMismatchError=jx;var Mx=class extends Cn.BaseError{constructor({v:t}){super(`Invalid \`v\` value "${t}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}};He.InvalidLegacyVError=Mx;var qx=class extends Cn.BaseError{constructor({yParity:t}){super(`Invalid \`yParity\` value "${t}". Expected 0 or 1.`,{name:"InvalidYParityError"})}};He.InvalidYParityError=qx;var Dx=class extends Cn.BaseError{constructor({transaction:t}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",Gx(t),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}};He.InvalidSerializableTransactionError=Dx;var Lx=class extends Cn.BaseError{constructor({serializedType:t}){super(`Serialized transaction type "${t}" is invalid.`,{name:"InvalidSerializedTransactionType"}),Object.defineProperty(this,"serializedType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.serializedType=t}};He.InvalidSerializedTransactionTypeError=Lx;var Bx=class extends Cn.BaseError{constructor({attributes:t,serializedTransaction:r,type:n}){let i=Object.entries(t).map(([o,s])=>typeof s>"u"?o:void 0).filter(Boolean);super(`Invalid serialized transaction of type "${n}" was provided.`,{metaMessages:[`Serialized Transaction: "${r}"`,i.length>0?`Missing Attributes: ${i.join(", ")}`:""].filter(Boolean),name:"InvalidSerializedTransactionError"}),Object.defineProperty(this,"serializedTransaction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.serializedTransaction=r,this.type=n}};He.InvalidSerializedTransactionError=Bx;var Ux=class extends Cn.BaseError{constructor({storageKey:t}){super(`Size for storage key "${t}" is invalid. Expected 32 bytes. Got ${Math.floor((t.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}};He.InvalidStorageKeySizeError=Ux;var Hx=class extends Cn.BaseError{constructor(t,{account:r,docsPath:n,chain:i,data:o,gas:s,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:d,to:l,value:m}){let p=Gx({chain:i&&`${i?.name} (id: ${i?.id})`,from:r?.address,to:l,value:typeof m<"u"&&`${(0,Ege.formatEther)(m)} ${i?.nativeCurrency?.symbol||"ETH"}`,data:o,gas:s,gasPrice:typeof a<"u"&&`${(0,Nx.formatGwei)(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${(0,Nx.formatGwei)(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${(0,Nx.formatGwei)(u)} gwei`,nonce:d});super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Request Arguments:",p].filter(Boolean),name:"TransactionExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}};He.TransactionExecutionError=Hx;var Fx=class extends Cn.BaseError{constructor({blockHash:t,blockNumber:r,blockTag:n,hash:i,index:o}){let s="Transaction";n&&o!==void 0&&(s=`Transaction at block time "${n}" at index "${o}"`),t&&o!==void 0&&(s=`Transaction at block hash "${t}" at index "${o}"`),r&&o!==void 0&&(s=`Transaction at block number "${r}" at index "${o}"`),i&&(s=`Transaction with hash "${i}"`),super(`${s} could not be found.`,{name:"TransactionNotFoundError"})}};He.TransactionNotFoundError=Fx;var $x=class extends Cn.BaseError{constructor({hash:t}){super(`Transaction receipt with hash "${t}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}};He.TransactionReceiptNotFoundError=$x;var Jx=class extends Cn.BaseError{constructor({receipt:t}){super(`Transaction with hash "${t.transactionHash}" reverted.`,{metaMessages:['The receipt marked the transaction as "reverted". This could mean that the function on the contract you are trying to call threw an error.'," ","You can attempt to extract the revert reason by:","- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract","- using the `call` Action with raw `data`"],name:"TransactionReceiptRevertedError"}),Object.defineProperty(this,"receipt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.receipt=t}};He.TransactionReceiptRevertedError=Jx;var Vx=class extends Cn.BaseError{constructor({hash:t}){super(`Timed out while waiting for transaction with hash "${t}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}};He.WaitForTransactionReceiptTimeoutError=Vx});var Ii=g(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.getUrl=La.getContractAddress=void 0;La.getAbortError=vge;La.isAbortError=Sge;var wge=e=>e;La.getContractAddress=wge;function vge(e){if(e?.reason)return e.reason;if(typeof DOMException=="function")return new DOMException("This operation was aborted","AbortError");let t=new Error("This operation was aborted");return t.name="AbortError",t}function Sge(e){return typeof e=="object"&&e!==null&&"name"in e&&e.name==="AbortError"}var Age=e=>{try{let t=new URL(e);return!t.username&&!t.password?e:(t.username="",t.password="",t.toString())}catch{return e}};La.getUrl=Age});var ao=g(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.RawContractError=sn.CounterfactualDeploymentFailedError=sn.ContractFunctionZeroDataError=sn.ContractFunctionRevertedError=sn.ContractFunctionExecutionError=sn.CallExecutionError=void 0;var Ige=at(),Pge=jm(),Tge=Ol(),OF=io(),RF=Sx(),xge=so(),Oge=Rl(),Kx=qa(),Rge=ft(),Cl=ye(),Cge=x_(),CF=Xt(),Nge=Ii(),Wx=class extends Cl.BaseError{constructor(t,{account:r,docsPath:n,chain:i,data:o,gas:s,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:d,to:l,value:m,stateOverride:p}){let h=r?(0,Ige.parseAccount)(r):void 0,y=(0,CF.prettyPrint)({from:h?.address,to:l,value:typeof m<"u"&&`${(0,Oge.formatEther)(m)} ${i?.nativeCurrency?.symbol||"ETH"}`,data:o,gas:s,gasPrice:typeof a<"u"&&`${(0,Kx.formatGwei)(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${(0,Kx.formatGwei)(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${(0,Kx.formatGwei)(u)} gwei`,nonce:d});p&&(y+=`
42
+ ${(0,Cge.prettyStateOverride)(p)}`),super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Raw Call Arguments:",y].filter(Boolean),name:"CallExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}};sn.CallExecutionError=Wx;var zx=class extends Cl.BaseError{constructor(t,{abi:r,args:n,contractAddress:i,docsPath:o,functionName:s,sender:a}){let c=(0,xge.getAbiItem)({abi:r,args:n,name:s}),u=c?(0,RF.formatAbiItemWithArgs)({abiItem:c,args:n,includeFunctionName:!1,includeName:!1}):void 0,d=c?(0,OF.formatAbiItem)(c,{includeName:!0}):void 0,l=(0,CF.prettyPrint)({address:i&&(0,Nge.getContractAddress)(i),function:d,args:u&&u!=="()"&&`${[...Array(s?.length??0).keys()].map(()=>" ").join("")}${u}`,sender:a});super(t.shortMessage||`An unknown error occurred while executing the contract function "${s}".`,{cause:t,docsPath:o,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],l&&"Contract Call:",l].filter(Boolean),name:"ContractFunctionExecutionError"}),Object.defineProperty(this,"abi",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"contractAddress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"formattedArgs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abi=r,this.args=n,this.cause=t,this.contractAddress=i,this.functionName=s,this.sender=a}};sn.ContractFunctionExecutionError=zx;var Yx=class extends Cl.BaseError{constructor({abi:t,data:r,functionName:n,message:i,cause:o}){let s,a,c,u;if(r&&r!=="0x")try{a=(0,Tge.decodeErrorResult)({abi:t,data:r,cause:o});let{abiItem:l,errorName:m,args:p}=a;if(m==="Error")u=p[0];else if(m==="Panic"){let[h]=p;u=Pge.panicReasons[h]}else{let h=l?(0,OF.formatAbiItem)(l,{includeName:!0}):void 0,y=l&&p?(0,RF.formatAbiItemWithArgs)({abiItem:l,args:p,includeFunctionName:!1,includeName:!1}):void 0;c=[h?`Error: ${h}`:"",y&&y!=="()"?` ${[...Array(m?.length??0).keys()].map(()=>" ").join("")}${y}`:""]}}catch(l){s=l}else i&&(u=i);let d;s instanceof Rge.AbiErrorSignatureNotFoundError&&(d=s.signature,c=[`Unable to decode signature "${d}" as it was not found on the provided ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://4byte.sourcify.dev/?q=${d}.`]),super(u&&u!=="execution reverted"||d?[`The contract function "${n}" reverted with the following ${d?"signature":"reason"}:`,u||d].join(`
43
+ `):`The contract function "${n}" reverted.`,{cause:s??o,metaMessages:c,name:"ContractFunctionRevertedError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"raw",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=a,this.raw=r,this.reason=u,this.signature=d}};sn.ContractFunctionRevertedError=Yx;var Xx=class extends Cl.BaseError{constructor({functionName:t,cause:r}){super(`The contract function "${t}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${t}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError",cause:r})}};sn.ContractFunctionZeroDataError=Xx;var Zx=class extends Cl.BaseError{constructor({factory:t}){super(`Deployment for counterfactual contract call failed${t?` for factory "${t}".`:""}`,{metaMessages:["Please ensure:","- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).","- The `factoryData` is a valid encoded function call for contract deployment function on the factory."],name:"CounterfactualDeploymentFailedError"})}};sn.CounterfactualDeploymentFailedError=Zx;var Qx=class extends Cl.BaseError{constructor({data:t,message:r}){super(r||"",{name:"RawContractError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t}};sn.RawContractError=Qx});var Nn=g(an=>{"use strict";Object.defineProperty(an,"__esModule",{value:!0});an.TimeoutError=an.SocketClosedError=an.RpcRequestError=an.WebSocketRequestError=an.ResponseBodyTooLargeError=an.HttpRequestError=void 0;var O_=Mt(),Nl=ye(),qm=Ii(),e2=class extends Nl.BaseError{constructor({body:t,cause:r,details:n,headers:i,status:o,url:s}){super("HTTP request failed.",{cause:r,details:n,metaMessages:[o&&`Status: ${o}`,`URL: ${(0,qm.getUrl)(s)}`,t&&`Request body: ${(0,O_.stringify)(t)}`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=t,this.headers=i,this.status=o,this.url=s}};an.HttpRequestError=e2;var t2=class extends Nl.BaseError{constructor({maxSize:t,size:r}){super("HTTP response body exceeded the size limit.",{metaMessages:[`Max: ${t} bytes`,`Received: ${r} bytes`],name:"ResponseBodyTooLargeError"}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t,this.size=r}};an.ResponseBodyTooLargeError=t2;var r2=class extends Nl.BaseError{constructor({body:t,cause:r,details:n,url:i}){super("WebSocket request failed.",{cause:r,details:n,metaMessages:[`URL: ${(0,qm.getUrl)(i)}`,t&&`Request body: ${(0,O_.stringify)(t)}`].filter(Boolean),name:"WebSocketRequestError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=i}};an.WebSocketRequestError=r2;var n2=class extends Nl.BaseError{constructor({body:t,error:r,url:n}){super("RPC Request failed.",{cause:r,details:r.message,metaMessages:[`URL: ${(0,qm.getUrl)(n)}`,`Request body: ${(0,O_.stringify)(t)}`],name:"RpcRequestError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=r.code,this.data=r.data,this.url=n}};an.RpcRequestError=n2;var i2=class extends Nl.BaseError{constructor({url:t}={}){super("The socket has been closed.",{metaMessages:[t&&`URL: ${(0,qm.getUrl)(t)}`].filter(Boolean),name:"SocketClosedError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=t}};an.SocketClosedError=i2;var o2=class extends Nl.BaseError{constructor({body:t,url:r}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${(0,qm.getUrl)(r)}`,`Request body: ${(0,O_.stringify)(t)}`],name:"TimeoutError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=r}};an.TimeoutError=o2});var ss=g(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.UnknownRpcError=ee.WalletConnectSessionSettlementError=ee.AtomicityNotSupportedError=ee.AtomicReadyWalletRejectedUpgradeError=ee.BundleTooLargeError=ee.UnknownBundleIdError=ee.DuplicateIdError=ee.UnsupportedChainIdError=ee.UnsupportedNonOptionalCapabilityError=ee.SwitchChainError=ee.ChainDisconnectedError=ee.ProviderDisconnectedError=ee.UnsupportedProviderMethodError=ee.UnauthorizedProviderError=ee.UserRejectedRequestError=ee.JsonRpcVersionUnsupportedError=ee.LimitExceededRpcError=ee.MethodNotSupportedRpcError=ee.TransactionRejectedRpcError=ee.ResourceUnavailableRpcError=ee.ResourceNotFoundRpcError=ee.InvalidInputRpcError=ee.InternalRpcError=ee.InvalidParamsRpcError=ee.MethodNotFoundRpcError=ee.InvalidRequestRpcError=ee.ParseRpcError=ee.ProviderRpcError=ee.RpcError=void 0;var kge=ye(),jge=Nn(),Mge=-1,dr=class extends kge.BaseError{constructor(t,{code:r,docsPath:n,metaMessages:i,name:o,shortMessage:s}){super(s,{cause:t,docsPath:n,metaMessages:i||t?.metaMessages,name:o||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=o||t.name,this.code=t instanceof jge.RpcRequestError?t.code:r??Mge}};ee.RpcError=dr;var lr=class extends dr{constructor(t,r){super(t,r),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=r.data}};ee.ProviderRpcError=lr;var R_=class e extends dr{constructor(t){super(t,{code:e.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}};ee.ParseRpcError=R_;Object.defineProperty(R_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});var C_=class e extends dr{constructor(t){super(t,{code:e.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}};ee.InvalidRequestRpcError=C_;Object.defineProperty(C_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});var N_=class e extends dr{constructor(t,{method:r}={}){super(t,{code:e.code,name:"MethodNotFoundRpcError",shortMessage:`The method${r?` "${r}"`:""} does not exist / is not available.`})}};ee.MethodNotFoundRpcError=N_;Object.defineProperty(N_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});var k_=class e extends dr{constructor(t){super(t,{code:e.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
44
+ `)})}};ee.InvalidParamsRpcError=k_;Object.defineProperty(k_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});var j_=class e extends dr{constructor(t){super(t,{code:e.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}};ee.InternalRpcError=j_;Object.defineProperty(j_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});var M_=class e extends dr{constructor(t){super(t,{code:e.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
45
+ `)})}};ee.InvalidInputRpcError=M_;Object.defineProperty(M_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});var q_=class e extends dr{constructor(t){super(t,{code:e.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}};ee.ResourceNotFoundRpcError=q_;Object.defineProperty(q_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});var D_=class e extends dr{constructor(t){super(t,{code:e.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}};ee.ResourceUnavailableRpcError=D_;Object.defineProperty(D_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});var L_=class e extends dr{constructor(t){super(t,{code:e.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}};ee.TransactionRejectedRpcError=L_;Object.defineProperty(L_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});var B_=class e extends dr{constructor(t,{method:r}={}){super(t,{code:e.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${r?` "${r}"`:""} is not supported.`})}};ee.MethodNotSupportedRpcError=B_;Object.defineProperty(B_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});var U_=class e extends dr{constructor(t){super(t,{code:e.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}};ee.LimitExceededRpcError=U_;Object.defineProperty(U_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});var H_=class e extends dr{constructor(t){super(t,{code:e.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}};ee.JsonRpcVersionUnsupportedError=H_;Object.defineProperty(H_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});var F_=class e extends lr{constructor(t){super(t,{code:e.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}};ee.UserRejectedRequestError=F_;Object.defineProperty(F_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});var $_=class e extends lr{constructor(t){super(t,{code:e.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}};ee.UnauthorizedProviderError=$_;Object.defineProperty($_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});var J_=class e extends lr{constructor(t,{method:r}={}){super(t,{code:e.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${r?` " ${r}"`:""}.`})}};ee.UnsupportedProviderMethodError=J_;Object.defineProperty(J_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});var V_=class e extends lr{constructor(t){super(t,{code:e.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}};ee.ProviderDisconnectedError=V_;Object.defineProperty(V_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});var G_=class e extends lr{constructor(t){super(t,{code:e.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}};ee.ChainDisconnectedError=G_;Object.defineProperty(G_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});var K_=class e extends lr{constructor(t){super(t,{code:e.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}};ee.SwitchChainError=K_;Object.defineProperty(K_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});var W_=class e extends lr{constructor(t){super(t,{code:e.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}};ee.UnsupportedNonOptionalCapabilityError=W_;Object.defineProperty(W_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});var z_=class e extends lr{constructor(t){super(t,{code:e.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}};ee.UnsupportedChainIdError=z_;Object.defineProperty(z_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});var Y_=class e extends lr{constructor(t){super(t,{code:e.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}};ee.DuplicateIdError=Y_;Object.defineProperty(Y_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});var X_=class e extends lr{constructor(t){super(t,{code:e.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}};ee.UnknownBundleIdError=X_;Object.defineProperty(X_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});var Z_=class e extends lr{constructor(t){super(t,{code:e.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}};ee.BundleTooLargeError=Z_;Object.defineProperty(Z_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});var Q_=class e extends lr{constructor(t){super(t,{code:e.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}};ee.AtomicReadyWalletRejectedUpgradeError=Q_;Object.defineProperty(Q_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});var eb=class e extends lr{constructor(t){super(t,{code:e.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}};ee.AtomicityNotSupportedError=eb;Object.defineProperty(eb,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});var tb=class e extends lr{constructor(t){super(t,{code:e.code,name:"WalletConnectSessionSettlementError",shortMessage:"WalletConnect session settlement failed."})}};ee.WalletConnectSessionSettlementError=tb;Object.defineProperty(tb,"code",{enumerable:!0,configurable:!0,writable:!0,value:7e3});var s2=class extends dr{constructor(t){super(t,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}};ee.UnknownRpcError=s2});var as=g(a2=>{"use strict";Object.defineProperty(a2,"__esModule",{value:!0});a2.getContractError=Uge;var qge=ft(),Dge=ye(),rb=ao(),Lge=Nn(),NF=ss(),Bge=3;function Uge(e,{abi:t,address:r,args:n,docsPath:i,functionName:o,sender:s}){let a=e instanceof rb.RawContractError?e:e instanceof Dge.BaseError?e.walk(h=>"data"in h)||e.walk():{},{code:c,data:u,details:d,message:l,shortMessage:m}=a,p=e instanceof qge.AbiDecodingZeroDataError?new rb.ContractFunctionZeroDataError({functionName:o,cause:e}):[Bge,NF.InternalRpcError.code].includes(c)&&(u||d||l||m)||c===NF.InvalidInputRpcError.code&&d==="execution reverted"&&u?new rb.ContractFunctionRevertedError({abi:t,data:typeof u=="object"?u.data:u,functionName:o,message:a instanceof Lge.RpcRequestError?d:m??l,cause:e}):e;return new rb.ContractFunctionExecutionError(p,{abi:t,args:n,contractAddress:r,docsPath:i,functionName:o,sender:s})}});var u2=g(c2=>{"use strict";Object.defineProperty(c2,"__esModule",{value:!0});c2.publicKeyToAddress=$ge;var Hge=Ir(),Fge=Hr();function $ge(e){let t=(0,Fge.keccak256)(`0x${e.substring(4)}`).substring(26);return(0,Hge.checksumAddress)(`0x${t}`)}});var l2=g(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.SHA512_IV=Fr.SHA384_IV=Fr.SHA224_IV=Fr.SHA256_IV=Fr.HashMD=void 0;Fr.setBigUint64=kF;Fr.Chi=Jge;Fr.Maj=Vge;var co=is();function kF(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),a=Number(r&o),c=n?4:0,u=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+u,a,n)}function Jge(e,t,r){return e&t^~e&r}function Vge(e,t,r){return e&t^e&r^t&r}var d2=class extends co.Hash{constructor(t,r,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(t),this.view=(0,co.createView)(this.buffer)}update(t){(0,co.aexists)(this),t=(0,co.toBytes)(t),(0,co.abytes)(t);let{view:r,buffer:n,blockLen:i}=this,o=t.length;for(let s=0;s<o;){let a=Math.min(i-this.pos,o-s);if(a===i){let c=(0,co.createView)(t);for(;i<=o-s;s+=i)this.process(c,s);continue}n.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){(0,co.aexists)(this),(0,co.aoutput)(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,(0,co.clean)(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let l=s;l<i;l++)r[l]=0;kF(n,i-8,BigInt(this.length*8),o),this.process(n,0);let a=(0,co.createView)(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,d[l],o)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:a}=this;return t.destroyed=s,t.finished=o,t.length=i,t.pos=a,i%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}};Fr.HashMD=d2;Fr.SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);Fr.SHA224_IV=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);Fr.SHA384_IV=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]);Fr.SHA512_IV=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});var f2=g(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.sha512_224=Qe.sha512_256=Qe.sha384=Qe.sha512=Qe.sha224=Qe.sha256=Qe.SHA512_256=Qe.SHA512_224=Qe.SHA384=Qe.SHA512=Qe.SHA224=Qe.SHA256=void 0;var fe=l2(),ve=BT(),qt=is(),Gge=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ba=new Uint32Array(64),Dm=class extends fe.HashMD{constructor(t=32){super(64,t,8,!1),this.A=fe.SHA256_IV[0]|0,this.B=fe.SHA256_IV[1]|0,this.C=fe.SHA256_IV[2]|0,this.D=fe.SHA256_IV[3]|0,this.E=fe.SHA256_IV[4]|0,this.F=fe.SHA256_IV[5]|0,this.G=fe.SHA256_IV[6]|0,this.H=fe.SHA256_IV[7]|0}get(){let{A:t,B:r,C:n,D:i,E:o,F:s,G:a,H:c}=this;return[t,r,n,i,o,s,a,c]}set(t,r,n,i,o,s,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,r){for(let l=0;l<16;l++,r+=4)Ba[l]=t.getUint32(r,!1);for(let l=16;l<64;l++){let m=Ba[l-15],p=Ba[l-2],h=(0,qt.rotr)(m,7)^(0,qt.rotr)(m,18)^m>>>3,y=(0,qt.rotr)(p,17)^(0,qt.rotr)(p,19)^p>>>10;Ba[l]=y+Ba[l-7]+h+Ba[l-16]|0}let{A:n,B:i,C:o,D:s,E:a,F:c,G:u,H:d}=this;for(let l=0;l<64;l++){let m=(0,qt.rotr)(a,6)^(0,qt.rotr)(a,11)^(0,qt.rotr)(a,25),p=d+m+(0,fe.Chi)(a,c,u)+Gge[l]+Ba[l]|0,y=((0,qt.rotr)(n,2)^(0,qt.rotr)(n,13)^(0,qt.rotr)(n,22))+(0,fe.Maj)(n,i,o)|0;d=u,u=c,c=a,a=s+p|0,s=o,o=i,i=n,n=p+y|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,i,o,s,a,c,u,d)}roundClean(){(0,qt.clean)(Ba)}destroy(){this.set(0,0,0,0,0,0,0,0),(0,qt.clean)(this.buffer)}};Qe.SHA256=Dm;var nb=class extends Dm{constructor(){super(28),this.A=fe.SHA224_IV[0]|0,this.B=fe.SHA224_IV[1]|0,this.C=fe.SHA224_IV[2]|0,this.D=fe.SHA224_IV[3]|0,this.E=fe.SHA224_IV[4]|0,this.F=fe.SHA224_IV[5]|0,this.G=fe.SHA224_IV[6]|0,this.H=fe.SHA224_IV[7]|0}};Qe.SHA224=nb;var jF=ve.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),Kge=jF[0],Wge=jF[1],Ua=new Uint32Array(80),Ha=new Uint32Array(80),Pu=class extends fe.HashMD{constructor(t=64){super(128,t,16,!1),this.Ah=fe.SHA512_IV[0]|0,this.Al=fe.SHA512_IV[1]|0,this.Bh=fe.SHA512_IV[2]|0,this.Bl=fe.SHA512_IV[3]|0,this.Ch=fe.SHA512_IV[4]|0,this.Cl=fe.SHA512_IV[5]|0,this.Dh=fe.SHA512_IV[6]|0,this.Dl=fe.SHA512_IV[7]|0,this.Eh=fe.SHA512_IV[8]|0,this.El=fe.SHA512_IV[9]|0,this.Fh=fe.SHA512_IV[10]|0,this.Fl=fe.SHA512_IV[11]|0,this.Gh=fe.SHA512_IV[12]|0,this.Gl=fe.SHA512_IV[13]|0,this.Hh=fe.SHA512_IV[14]|0,this.Hl=fe.SHA512_IV[15]|0}get(){let{Ah:t,Al:r,Bh:n,Bl:i,Ch:o,Cl:s,Dh:a,Dl:c,Eh:u,El:d,Fh:l,Fl:m,Gh:p,Gl:h,Hh:y,Hl:b}=this;return[t,r,n,i,o,s,a,c,u,d,l,m,p,h,y,b]}set(t,r,n,i,o,s,a,c,u,d,l,m,p,h,y,b){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=i|0,this.Ch=o|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=d|0,this.Fh=l|0,this.Fl=m|0,this.Gh=p|0,this.Gl=h|0,this.Hh=y|0,this.Hl=b|0}process(t,r){for(let E=0;E<16;E++,r+=4)Ua[E]=t.getUint32(r),Ha[E]=t.getUint32(r+=4);for(let E=16;E<80;E++){let S=Ua[E-15]|0,I=Ha[E-15]|0,T=ve.rotrSH(S,I,1)^ve.rotrSH(S,I,8)^ve.shrSH(S,I,7),x=ve.rotrSL(S,I,1)^ve.rotrSL(S,I,8)^ve.shrSL(S,I,7),C=Ua[E-2]|0,k=Ha[E-2]|0,N=ve.rotrSH(C,k,19)^ve.rotrBH(C,k,61)^ve.shrSH(C,k,6),M=ve.rotrSL(C,k,19)^ve.rotrBL(C,k,61)^ve.shrSL(C,k,6),j=ve.add4L(x,M,Ha[E-7],Ha[E-16]),D=ve.add4H(j,T,N,Ua[E-7],Ua[E-16]);Ua[E]=D|0,Ha[E]=j|0}let{Ah:n,Al:i,Bh:o,Bl:s,Ch:a,Cl:c,Dh:u,Dl:d,Eh:l,El:m,Fh:p,Fl:h,Gh:y,Gl:b,Hh:v,Hl:A}=this;for(let E=0;E<80;E++){let S=ve.rotrSH(l,m,14)^ve.rotrSH(l,m,18)^ve.rotrBH(l,m,41),I=ve.rotrSL(l,m,14)^ve.rotrSL(l,m,18)^ve.rotrBL(l,m,41),T=l&p^~l&y,x=m&h^~m&b,C=ve.add5L(A,I,x,Wge[E],Ha[E]),k=ve.add5H(C,v,S,T,Kge[E],Ua[E]),N=C|0,M=ve.rotrSH(n,i,28)^ve.rotrBH(n,i,34)^ve.rotrBH(n,i,39),j=ve.rotrSL(n,i,28)^ve.rotrBL(n,i,34)^ve.rotrBL(n,i,39),D=n&o^n&a^o&a,U=i&s^i&c^s&c;v=y|0,A=b|0,y=p|0,b=h|0,p=l|0,h=m|0,{h:l,l:m}=ve.add(u|0,d|0,k|0,N|0),u=a|0,d=c|0,a=o|0,c=s|0,o=n|0,s=i|0;let q=ve.add3L(N,j,U);n=ve.add3H(q,k,M,D),i=q|0}({h:n,l:i}=ve.add(this.Ah|0,this.Al|0,n|0,i|0)),{h:o,l:s}=ve.add(this.Bh|0,this.Bl|0,o|0,s|0),{h:a,l:c}=ve.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:d}=ve.add(this.Dh|0,this.Dl|0,u|0,d|0),{h:l,l:m}=ve.add(this.Eh|0,this.El|0,l|0,m|0),{h:p,l:h}=ve.add(this.Fh|0,this.Fl|0,p|0,h|0),{h:y,l:b}=ve.add(this.Gh|0,this.Gl|0,y|0,b|0),{h:v,l:A}=ve.add(this.Hh|0,this.Hl|0,v|0,A|0),this.set(n,i,o,s,a,c,u,d,l,m,p,h,y,b,v,A)}roundClean(){(0,qt.clean)(Ua,Ha)}destroy(){(0,qt.clean)(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};Qe.SHA512=Pu;var ib=class extends Pu{constructor(){super(48),this.Ah=fe.SHA384_IV[0]|0,this.Al=fe.SHA384_IV[1]|0,this.Bh=fe.SHA384_IV[2]|0,this.Bl=fe.SHA384_IV[3]|0,this.Ch=fe.SHA384_IV[4]|0,this.Cl=fe.SHA384_IV[5]|0,this.Dh=fe.SHA384_IV[6]|0,this.Dl=fe.SHA384_IV[7]|0,this.Eh=fe.SHA384_IV[8]|0,this.El=fe.SHA384_IV[9]|0,this.Fh=fe.SHA384_IV[10]|0,this.Fl=fe.SHA384_IV[11]|0,this.Gh=fe.SHA384_IV[12]|0,this.Gl=fe.SHA384_IV[13]|0,this.Hh=fe.SHA384_IV[14]|0,this.Hl=fe.SHA384_IV[15]|0}};Qe.SHA384=ib;var xr=Uint32Array.from([2352822216,424955298,1944164710,2312950998,502970286,855612546,1738396948,1479516111,258812777,2077511080,2011393907,79989058,1067287976,1780299464,286451373,2446758561]),Or=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]),ob=class extends Pu{constructor(){super(28),this.Ah=xr[0]|0,this.Al=xr[1]|0,this.Bh=xr[2]|0,this.Bl=xr[3]|0,this.Ch=xr[4]|0,this.Cl=xr[5]|0,this.Dh=xr[6]|0,this.Dl=xr[7]|0,this.Eh=xr[8]|0,this.El=xr[9]|0,this.Fh=xr[10]|0,this.Fl=xr[11]|0,this.Gh=xr[12]|0,this.Gl=xr[13]|0,this.Hh=xr[14]|0,this.Hl=xr[15]|0}};Qe.SHA512_224=ob;var sb=class extends Pu{constructor(){super(32),this.Ah=Or[0]|0,this.Al=Or[1]|0,this.Bh=Or[2]|0,this.Bl=Or[3]|0,this.Ch=Or[4]|0,this.Cl=Or[5]|0,this.Dh=Or[6]|0,this.Dl=Or[7]|0,this.Eh=Or[8]|0,this.El=Or[9]|0,this.Fh=Or[10]|0,this.Fl=Or[11]|0,this.Gh=Or[12]|0,this.Gl=Or[13]|0,this.Hh=Or[14]|0,this.Hl=Or[15]|0}};Qe.SHA512_256=sb;Qe.sha256=(0,qt.createHasher)(()=>new Dm);Qe.sha224=(0,qt.createHasher)(()=>new nb);Qe.sha512=(0,qt.createHasher)(()=>new Pu);Qe.sha384=(0,qt.createHasher)(()=>new ib);Qe.sha512_256=(0,qt.createHasher)(()=>new sb);Qe.sha512_224=(0,qt.createHasher)(()=>new ob)});var p2=g(xu=>{"use strict";Object.defineProperty(xu,"__esModule",{value:!0});xu.hmac=xu.HMAC=void 0;var Tu=is(),Lm=class extends Tu.Hash{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,(0,Tu.ahash)(t);let n=(0,Tu.toBytes)(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(n.length>i?t.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),(0,Tu.clean)(o)}update(t){return(0,Tu.aexists)(this),this.iHash.update(t),this}digestInto(t){(0,Tu.aexists)(this),(0,Tu.abytes)(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:n,finished:i,destroyed:o,blockLen:s,outputLen:a}=this;return t=t,t.finished=i,t.destroyed=o,t.blockLen=s,t.outputLen=a,t.oHash=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};xu.HMAC=Lm;var zge=(e,t,r)=>new Lm(e,t).update(r).digest();xu.hmac=zge;xu.hmac.create=(e,t)=>new Lm(e,t)});var Fa=g(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.notImplemented=Le.bitMask=void 0;Le.isBytes=cb;Le.abytes=ub;Le.abool=Yge;Le.numberToHexUnpadded=DF;Le.hexToNumber=h2;Le.bytesToHex=y2;Le.hexToBytes=db;Le.bytesToNumberBE=Zge;Le.bytesToNumberLE=Qge;Le.numberToBytesBE=BF;Le.numberToBytesLE=ehe;Le.numberToVarBytesBE=the;Le.ensureBytes=rhe;Le.concatBytes=UF;Le.equalBytes=nhe;Le.utf8ToBytes=ihe;Le.inRange=HF;Le.aInRange=ohe;Le.bitLen=she;Le.bitGet=ahe;Le.bitSet=che;Le.createHmacDrbg=dhe;Le.validateObject=fhe;Le.memoized=mhe;var ab=BigInt(0),Bm=BigInt(1);function cb(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function ub(e){if(!cb(e))throw new Error("Uint8Array expected")}function Yge(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function DF(e){let t=e.toString(16);return t.length&1?"0"+t:t}function h2(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?ab:BigInt("0x"+e)}var LF=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Xge=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function y2(e){if(ub(e),LF)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Xge[e[r]];return t}var cs={_0:48,_9:57,A:65,F:70,a:97,f:102};function MF(e){if(e>=cs._0&&e<=cs._9)return e-cs._0;if(e>=cs.A&&e<=cs.F)return e-(cs.A-10);if(e>=cs.a&&e<=cs.f)return e-(cs.a-10)}function db(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(LF)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){let s=MF(e.charCodeAt(o)),a=MF(e.charCodeAt(o+1));if(s===void 0||a===void 0){let c=e[o]+e[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}n[i]=s*16+a}return n}function Zge(e){return h2(y2(e))}function Qge(e){return ub(e),h2(y2(Uint8Array.from(e).reverse()))}function BF(e,t){return db(e.toString(16).padStart(t*2,"0"))}function ehe(e,t){return BF(e,t).reverse()}function the(e){return db(DF(e))}function rhe(e,t,r){let n;if(typeof t=="string")try{n=db(t)}catch(o){throw new Error(e+" must be hex string or Uint8Array, cause: "+o)}else if(cb(t))n=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");let i=n.length;if(typeof r=="number"&&i!==r)throw new Error(e+" of length "+r+" expected, got "+i);return n}function UF(...e){let t=0;for(let n=0;n<e.length;n++){let i=e[n];ub(i),t+=i.length}let r=new Uint8Array(t);for(let n=0,i=0;n<e.length;n++){let o=e[n];r.set(o,i),i+=o.length}return r}function nhe(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}function ihe(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}var m2=e=>typeof e=="bigint"&&ab<=e;function HF(e,t,r){return m2(e)&&m2(t)&&m2(r)&&t<=e&&e<r}function ohe(e,t,r,n){if(!HF(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function she(e){let t;for(t=0;e>ab;e>>=Bm,t+=1);return t}function ahe(e,t){return e>>BigInt(t)&Bm}function che(e,t,r){return e|(r?Bm:ab)<<BigInt(t)}var uhe=e=>(Bm<<BigInt(e))-Bm;Le.bitMask=uhe;var g2=e=>new Uint8Array(e),qF=e=>Uint8Array.from(e);function dhe(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=g2(e),i=g2(e),o=0,s=()=>{n.fill(1),i.fill(0),o=0},a=(...l)=>r(i,n,...l),c=(l=g2(0))=>{i=a(qF([0]),l),n=a(),l.length!==0&&(i=a(qF([1]),l),n=a())},u=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let l=0,m=[];for(;l<t;){n=a();let p=n.slice();m.push(p),l+=n.length}return UF(...m)};return(l,m)=>{s(),c(l);let p;for(;!(p=m(u()));)c();return s(),p}}var lhe={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||cb(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function fhe(e,t,r={}){let n=(i,o,s)=>{let a=lhe[o];if(typeof a!="function")throw new Error("invalid validator function");let c=e[i];if(!(s&&c===void 0)&&!a(c,e))throw new Error("param "+String(i)+" is invalid. Expected "+o+", got "+c)};for(let[i,o]of Object.entries(t))n(i,o,!1);for(let[i,o]of Object.entries(r))n(i,o,!0);return e}var phe=()=>{throw new Error("not implemented")};Le.notImplemented=phe;function mhe(e){let t=new WeakMap;return(r,...n)=>{let i=t.get(r);if(i!==void 0)return i;let o=e(r,...n);return t.set(r,o),o}}});var Um=g(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.isNegativeLE=void 0;mt.mod=kn;mt.pow=yhe;mt.pow2=_he;mt.invert=lb;mt.tonelliShanks=GF;mt.FpSqrt=KF;mt.validateField=vhe;mt.FpPow=_2;mt.FpInvertBatch=WF;mt.FpDiv=She;mt.FpLegendre=fb;mt.FpIsSquare=Ahe;mt.nLength=b2;mt.Field=E2;mt.FpSqrtOdd=Ihe;mt.FpSqrtEven=Phe;mt.hashToPrivateScalar=The;mt.getFieldBytesLength=w2;mt.getMinHashLength=zF;mt.mapHashToField=xhe;var ghe=is(),jn=Fa(),$r=BigInt(0),Dt=BigInt(1),Ou=BigInt(2),hhe=BigInt(3),FF=BigInt(4),$F=BigInt(5),JF=BigInt(8);function kn(e,t){let r=e%t;return r>=$r?r:t+r}function yhe(e,t,r){return _2(E2(r),e,t)}function _he(e,t,r){let n=e;for(;t-- >$r;)n*=n,n%=r;return n}function lb(e,t){if(e===$r)throw new Error("invert: expected non-zero number");if(t<=$r)throw new Error("invert: expected positive modulus, got "+t);let r=kn(e,t),n=t,i=$r,o=Dt,s=Dt,a=$r;for(;r!==$r;){let u=n/r,d=n%r,l=i-s*u,m=o-a*u;n=r,r=d,i=s,o=a,s=l,a=m}if(n!==Dt)throw new Error("invert: does not exist");return kn(i,t)}function VF(e,t){let r=(e.ORDER+Dt)/FF,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function bhe(e,t){let r=(e.ORDER-$F)/JF,n=e.mul(t,Ou),i=e.pow(n,r),o=e.mul(t,i),s=e.mul(e.mul(o,Ou),i),a=e.mul(o,e.sub(s,e.ONE));if(!e.eql(e.sqr(a),t))throw new Error("Cannot find square root");return a}function GF(e){if(e<BigInt(3))throw new Error("sqrt is not defined for small field");let t=e-Dt,r=0;for(;t%Ou===$r;)t/=Ou,r++;let n=Ou,i=E2(e);for(;fb(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return VF;let o=i.pow(n,t),s=(t+Dt)/Ou;return function(c,u){if(c.is0(u))return u;if(fb(c,u)!==1)throw new Error("Cannot find square root");let d=r,l=c.mul(c.ONE,o),m=c.pow(u,t),p=c.pow(u,s);for(;!c.eql(m,c.ONE);){if(c.is0(m))return c.ZERO;let h=1,y=c.sqr(m);for(;!c.eql(y,c.ONE);)if(h++,y=c.sqr(y),h===d)throw new Error("Cannot find square root");let b=Dt<<BigInt(d-h-1),v=c.pow(l,b);d=h,l=c.sqr(v),m=c.mul(m,l),p=c.mul(p,v)}return p}}function KF(e){return e%FF===hhe?VF:e%JF===$F?bhe:GF(e)}var Ehe=(e,t)=>(kn(e,t)&Dt)===Dt;mt.isNegativeLE=Ehe;var whe=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function vhe(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=whe.reduce((n,i)=>(n[i]="function",n),t);return(0,jn.validateObject)(e,r)}function _2(e,t,r){if(r<$r)throw new Error("invalid exponent, negatives unsupported");if(r===$r)return e.ONE;if(r===Dt)return t;let n=e.ONE,i=t;for(;r>$r;)r&Dt&&(n=e.mul(n,i)),i=e.sqr(i),r>>=Dt;return n}function WF(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),i=t.reduce((s,a,c)=>e.is0(a)?s:(n[c]=s,e.mul(s,a)),e.ONE),o=e.inv(i);return t.reduceRight((s,a,c)=>e.is0(a)?s:(n[c]=e.mul(s,n[c]),e.mul(s,a)),o),n}function She(e,t,r){return e.mul(t,typeof r=="bigint"?lb(r,e.ORDER):e.inv(r))}function fb(e,t){let r=(e.ORDER-Dt)/Ou,n=e.pow(t,r),i=e.eql(n,e.ONE),o=e.eql(n,e.ZERO),s=e.eql(n,e.neg(e.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function Ahe(e,t){return fb(e,t)===1}function b2(e,t){t!==void 0&&(0,ghe.anumber)(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function E2(e,t,r=!1,n={}){if(e<=$r)throw new Error("invalid field: expected ORDER > 0, got "+e);let{nBitLength:i,nByteLength:o}=b2(e,t);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let s,a=Object.freeze({ORDER:e,isLE:r,BITS:i,BYTES:o,MASK:(0,jn.bitMask)(i),ZERO:$r,ONE:Dt,create:c=>kn(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return $r<=c&&c<e},is0:c=>c===$r,isOdd:c=>(c&Dt)===Dt,neg:c=>kn(-c,e),eql:(c,u)=>c===u,sqr:c=>kn(c*c,e),add:(c,u)=>kn(c+u,e),sub:(c,u)=>kn(c-u,e),mul:(c,u)=>kn(c*u,e),pow:(c,u)=>_2(a,c,u),div:(c,u)=>kn(c*lb(u,e),e),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>lb(c,e),sqrt:n.sqrt||(c=>(s||(s=KF(e)),s(a,c))),toBytes:c=>r?(0,jn.numberToBytesLE)(c,o):(0,jn.numberToBytesBE)(c,o),fromBytes:c=>{if(c.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+c.length);return r?(0,jn.bytesToNumberLE)(c):(0,jn.bytesToNumberBE)(c)},invertBatch:c=>WF(a,c),cmov:(c,u,d)=>d?u:c});return Object.freeze(a)}function Ihe(e,t){if(!e.isOdd)throw new Error("Field doesn't have isOdd");let r=e.sqrt(t);return e.isOdd(r)?r:e.neg(r)}function Phe(e,t){if(!e.isOdd)throw new Error("Field doesn't have isOdd");let r=e.sqrt(t);return e.isOdd(r)?e.neg(r):r}function The(e,t,r=!1){e=(0,jn.ensureBytes)("privateHash",e);let n=e.length,i=b2(t).nByteLength+8;if(i<24||n<i||n>1024)throw new Error("hashToPrivateScalar: expected "+i+"-1024 bytes of input, got "+n);let o=r?(0,jn.bytesToNumberLE)(e):(0,jn.bytesToNumberBE)(e);return kn(o,t-Dt)+Dt}function w2(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function zF(e){let t=w2(e);return t+Math.ceil(t/2)}function xhe(e,t,r=!1){let n=e.length,i=w2(t),o=zF(t);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let s=r?(0,jn.bytesToNumberLE)(e):(0,jn.bytesToNumberBE)(e),a=kn(s,t-Dt)+Dt;return r?(0,jn.numberToBytesLE)(a,i):(0,jn.numberToBytesBE)(a,i)}});var r$=g(kl=>{"use strict";Object.defineProperty(kl,"__esModule",{value:!0});kl.wNAF=Ohe;kl.pippenger=Rhe;kl.precomputeMSMUnsafe=Che;kl.validateBasic=Nhe;var YF=Um(),Hm=Fa(),XF=BigInt(0),P2=BigInt(1);function v2(e,t){let r=t.negate();return e?r:t}function T2(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function S2(e,t){T2(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),i=2**e,o=(0,Hm.bitMask)(e),s=BigInt(e);return{windows:r,windowSize:n,mask:o,maxNumber:i,shiftBy:s}}function ZF(e,t,r){let{windowSize:n,mask:i,maxNumber:o,shiftBy:s}=r,a=Number(e&i),c=e>>s;a>n&&(a-=o,c+=P2);let u=t*n,d=u+Math.abs(a)-1,l=a===0,m=a<0,p=t%2!==0;return{nextN:c,offset:d,isZero:l,isNeg:m,isNegF:p,offsetF:u}}function QF(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function e$(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}var A2=new WeakMap,t$=new WeakMap;function I2(e){return t$.get(e)||1}function Ohe(e,t){return{constTimeNegate:v2,hasPrecomputes(r){return I2(r)!==1},unsafeLadder(r,n,i=e.ZERO){let o=r;for(;n>XF;)n&P2&&(i=i.add(o)),o=o.double(),n>>=P2;return i},precomputeWindow(r,n){let{windows:i,windowSize:o}=S2(n,t),s=[],a=r,c=a;for(let u=0;u<i;u++){c=a,s.push(c);for(let d=1;d<o;d++)c=c.add(a),s.push(c);a=c.double()}return s},wNAF(r,n,i){let o=e.ZERO,s=e.BASE,a=S2(r,t);for(let c=0;c<a.windows;c++){let{nextN:u,offset:d,isZero:l,isNeg:m,isNegF:p,offsetF:h}=ZF(i,c,a);i=u,l?s=s.add(v2(p,n[h])):o=o.add(v2(m,n[d]))}return{p:o,f:s}},wNAFUnsafe(r,n,i,o=e.ZERO){let s=S2(r,t);for(let a=0;a<s.windows&&i!==XF;a++){let{nextN:c,offset:u,isZero:d,isNeg:l}=ZF(i,a,s);if(i=c,!d){let m=n[u];o=o.add(l?m.negate():m)}}return o},getPrecomputes(r,n,i){let o=A2.get(n);return o||(o=this.precomputeWindow(n,r),r!==1&&A2.set(n,i(o))),o},wNAFCached(r,n,i){let o=I2(r);return this.wNAF(o,this.getPrecomputes(o,r,i),n)},wNAFCachedUnsafe(r,n,i,o){let s=I2(r);return s===1?this.unsafeLadder(r,n,o):this.wNAFUnsafe(s,this.getPrecomputes(s,r,i),n,o)},setWindowSize(r,n){T2(n,t),t$.set(r,n),A2.delete(r)}}}function Rhe(e,t,r,n){QF(r,e),e$(n,t);let i=r.length,o=n.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");let s=e.ZERO,a=(0,Hm.bitLen)(BigInt(i)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=(0,Hm.bitMask)(c),d=new Array(Number(u)+1).fill(s),l=Math.floor((t.BITS-1)/c)*c,m=s;for(let p=l;p>=0;p-=c){d.fill(s);for(let y=0;y<o;y++){let b=n[y],v=Number(b>>BigInt(p)&u);d[v]=d[v].add(r[y])}let h=s;for(let y=d.length-1,b=s;y>0;y--)b=b.add(d[y]),h=h.add(b);if(m=m.add(h),p!==0)for(let y=0;y<c;y++)m=m.double()}return m}function Che(e,t,r,n){T2(n,t.BITS),QF(r,e);let i=e.ZERO,o=2**n-1,s=Math.ceil(t.BITS/n),a=(0,Hm.bitMask)(n),c=r.map(u=>{let d=[];for(let l=0,m=u;l<o;l++)d.push(m),m=m.add(u);return d});return u=>{if(e$(u,t),u.length>r.length)throw new Error("array of scalars must be smaller than array of points");let d=i;for(let l=0;l<s;l++){if(d!==i)for(let p=0;p<n;p++)d=d.double();let m=BigInt(s*n-(l+1)*n);for(let p=0;p<u.length;p++){let h=u[p],y=Number(h>>m&a);y&&(d=d.add(c[p][y-1]))}}return d}}function Nhe(e){return(0,YF.validateField)(e.Fp),(0,Hm.validateObject)(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...(0,YF.nLength)(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}});var R2=g(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.DER=Ft.DERErr=void 0;Ft.weierstrassPoints=i$;Ft.weierstrass=Mhe;Ft.SWUFpSqrtRatio=o$;Ft.mapToCurveSimpleSWU=qhe;var pb=r$(),us=Um(),pe=Fa();function n$(e){e.lowS!==void 0&&(0,pe.abool)("lowS",e.lowS),e.prehash!==void 0&&(0,pe.abool)("prehash",e.prehash)}function khe(e){let t=(0,pb.validateBasic)(e);(0,pe.validateObject)(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:r,Fp:n,a:i}=t;if(r){if(!n.eql(i,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}var mb=class extends Error{constructor(t=""){super(t)}};Ft.DERErr=mb;Ft.DER={Err:mb,_tlv:{encode:(e,t)=>{let{Err:r}=Ft.DER;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,i=(0,pe.numberToHexUnpadded)(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?(0,pe.numberToHexUnpadded)(i.length/2|128):"";return(0,pe.numberToHexUnpadded)(e)+o+i+t},decode(e,t){let{Err:r}=Ft.DER,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let i=t[n++],o=!!(i&128),s=0;if(!o)s=i;else{let c=i&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(n+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(e){let{Err:t}=Ft.DER;if(e<Pi)throw new t("integer: negative integers are not allowed");let r=(0,pe.numberToHexUnpadded)(e);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=Ft.DER;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return(0,pe.bytesToNumberBE)(e)}},toSig(e){let{Err:t,_int:r,_tlv:n}=Ft.DER,i=(0,pe.ensureBytes)("signature",e),{v:o,l:s}=n.decode(48,i);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:u,l:d}=n.decode(2,c);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(e){let{_tlv:t,_int:r}=Ft.DER,n=t.encode(2,r.encode(e.r)),i=t.encode(2,r.encode(e.s)),o=n+i;return t.encode(48,o)}};function x2(e,t){return(0,pe.bytesToHex)((0,pe.numberToBytesBE)(e,t))}var Pi=BigInt(0),Ve=BigInt(1),$a=BigInt(2),Fm=BigInt(3),O2=BigInt(4);function i$(e){let t=khe(e),{Fp:r}=t,n=(0,us.Field)(t.n,t.nBitLength),i=t.toBytes||((E,S,I)=>{let T=S.toAffine();return(0,pe.concatBytes)(Uint8Array.from([4]),r.toBytes(T.x),r.toBytes(T.y))}),o=t.fromBytes||(E=>{let S=E.subarray(1),I=r.fromBytes(S.subarray(0,r.BYTES)),T=r.fromBytes(S.subarray(r.BYTES,2*r.BYTES));return{x:I,y:T}});function s(E){let{a:S,b:I}=t,T=r.sqr(E),x=r.mul(T,E);return r.add(r.add(x,r.mul(E,S)),I)}function a(E,S){let I=r.sqr(S),T=s(E);return r.eql(I,T)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let c=r.mul(r.pow(t.a,Fm),O2),u=r.mul(r.sqr(t.b),BigInt(27));if(r.is0(r.add(c,u)))throw new Error("bad curve params: a or b");function d(E){return(0,pe.inRange)(E,Ve,t.n)}function l(E){let{allowedPrivateKeyLengths:S,nByteLength:I,wrapPrivateKey:T,n:x}=t;if(S&&typeof E!="bigint"){if((0,pe.isBytes)(E)&&(E=(0,pe.bytesToHex)(E)),typeof E!="string"||!S.includes(E.length))throw new Error("invalid private key");E=E.padStart(I*2,"0")}let C;try{C=typeof E=="bigint"?E:(0,pe.bytesToNumberBE)((0,pe.ensureBytes)("private key",E,I))}catch{throw new Error("invalid private key, expected hex or "+I+" bytes, got "+typeof E)}return T&&(C=(0,us.mod)(C,x)),(0,pe.aInRange)("private key",C,Ve,x),C}function m(E){if(!(E instanceof y))throw new Error("ProjectivePoint expected")}let p=(0,pe.memoized)((E,S)=>{let{px:I,py:T,pz:x}=E;if(r.eql(x,r.ONE))return{x:I,y:T};let C=E.is0();S==null&&(S=C?r.ONE:r.inv(x));let k=r.mul(I,S),N=r.mul(T,S),M=r.mul(x,S);if(C)return{x:r.ZERO,y:r.ZERO};if(!r.eql(M,r.ONE))throw new Error("invZ was invalid");return{x:k,y:N}}),h=(0,pe.memoized)(E=>{if(E.is0()){if(t.allowInfinityPoint&&!r.is0(E.py))return;throw new Error("bad point: ZERO")}let{x:S,y:I}=E.toAffine();if(!r.isValid(S)||!r.isValid(I))throw new Error("bad point: x or y not FE");if(!a(S,I))throw new Error("bad point: equation left != right");if(!E.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class y{constructor(S,I,T){if(S==null||!r.isValid(S))throw new Error("x required");if(I==null||!r.isValid(I)||r.is0(I))throw new Error("y required");if(T==null||!r.isValid(T))throw new Error("z required");this.px=S,this.py=I,this.pz=T,Object.freeze(this)}static fromAffine(S){let{x:I,y:T}=S||{};if(!S||!r.isValid(I)||!r.isValid(T))throw new Error("invalid affine point");if(S instanceof y)throw new Error("projective point not allowed");let x=C=>r.eql(C,r.ZERO);return x(I)&&x(T)?y.ZERO:new y(I,T,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(S){let I=(0,us.FpInvertBatch)(r,S.map(T=>T.pz));return S.map((T,x)=>T.toAffine(I[x])).map(y.fromAffine)}static fromHex(S){let I=y.fromAffine(o((0,pe.ensureBytes)("pointHex",S)));return I.assertValidity(),I}static fromPrivateKey(S){return y.BASE.multiply(l(S))}static msm(S,I){return(0,pb.pippenger)(y,n,S,I)}_setWindowSize(S){A.setWindowSize(this,S)}assertValidity(){h(this)}hasEvenY(){let{y:S}=this.toAffine();if(r.isOdd)return!r.isOdd(S);throw new Error("Field doesn't support isOdd")}equals(S){m(S);let{px:I,py:T,pz:x}=this,{px:C,py:k,pz:N}=S,M=r.eql(r.mul(I,N),r.mul(C,x)),j=r.eql(r.mul(T,N),r.mul(k,x));return M&&j}negate(){return new y(this.px,r.neg(this.py),this.pz)}double(){let{a:S,b:I}=t,T=r.mul(I,Fm),{px:x,py:C,pz:k}=this,N=r.ZERO,M=r.ZERO,j=r.ZERO,D=r.mul(x,x),U=r.mul(C,C),q=r.mul(k,k),L=r.mul(x,C);return L=r.add(L,L),j=r.mul(x,k),j=r.add(j,j),N=r.mul(S,j),M=r.mul(T,q),M=r.add(N,M),N=r.sub(U,M),M=r.add(U,M),M=r.mul(N,M),N=r.mul(L,N),j=r.mul(T,j),q=r.mul(S,q),L=r.sub(D,q),L=r.mul(S,L),L=r.add(L,j),j=r.add(D,D),D=r.add(j,D),D=r.add(D,q),D=r.mul(D,L),M=r.add(M,D),q=r.mul(C,k),q=r.add(q,q),D=r.mul(q,L),N=r.sub(N,D),j=r.mul(q,U),j=r.add(j,j),j=r.add(j,j),new y(N,M,j)}add(S){m(S);let{px:I,py:T,pz:x}=this,{px:C,py:k,pz:N}=S,M=r.ZERO,j=r.ZERO,D=r.ZERO,U=t.a,q=r.mul(t.b,Fm),L=r.mul(I,C),V=r.mul(T,k),Q=r.mul(x,N),re=r.add(I,T),_e=r.add(C,k);re=r.mul(re,_e),_e=r.add(L,V),re=r.sub(re,_e),_e=r.add(I,x);let je=r.add(C,N);return _e=r.mul(_e,je),je=r.add(L,Q),_e=r.sub(_e,je),je=r.add(T,x),M=r.add(k,N),je=r.mul(je,M),M=r.add(V,Q),je=r.sub(je,M),D=r.mul(U,_e),M=r.mul(q,Q),D=r.add(M,D),M=r.sub(V,D),D=r.add(V,D),j=r.mul(M,D),V=r.add(L,L),V=r.add(V,L),Q=r.mul(U,Q),_e=r.mul(q,_e),V=r.add(V,Q),Q=r.sub(L,Q),Q=r.mul(U,Q),_e=r.add(_e,Q),L=r.mul(V,_e),j=r.add(j,L),L=r.mul(je,_e),M=r.mul(re,M),M=r.sub(M,L),L=r.mul(re,V),D=r.mul(je,D),D=r.add(D,L),new y(M,j,D)}subtract(S){return this.add(S.negate())}is0(){return this.equals(y.ZERO)}wNAF(S){return A.wNAFCached(this,S,y.normalizeZ)}multiplyUnsafe(S){let{endo:I,n:T}=t;(0,pe.aInRange)("scalar",S,Pi,T);let x=y.ZERO;if(S===Pi)return x;if(this.is0()||S===Ve)return this;if(!I||A.hasPrecomputes(this))return A.wNAFCachedUnsafe(this,S,y.normalizeZ);let{k1neg:C,k1:k,k2neg:N,k2:M}=I.splitScalar(S),j=x,D=x,U=this;for(;k>Pi||M>Pi;)k&Ve&&(j=j.add(U)),M&Ve&&(D=D.add(U)),U=U.double(),k>>=Ve,M>>=Ve;return C&&(j=j.negate()),N&&(D=D.negate()),D=new y(r.mul(D.px,I.beta),D.py,D.pz),j.add(D)}multiply(S){let{endo:I,n:T}=t;(0,pe.aInRange)("scalar",S,Ve,T);let x,C;if(I){let{k1neg:k,k1:N,k2neg:M,k2:j}=I.splitScalar(S),{p:D,f:U}=this.wNAF(N),{p:q,f:L}=this.wNAF(j);D=A.constTimeNegate(k,D),q=A.constTimeNegate(M,q),q=new y(r.mul(q.px,I.beta),q.py,q.pz),x=D.add(q),C=U.add(L)}else{let{p:k,f:N}=this.wNAF(S);x=k,C=N}return y.normalizeZ([x,C])[0]}multiplyAndAddUnsafe(S,I,T){let x=y.BASE,C=(N,M)=>M===Pi||M===Ve||!N.equals(x)?N.multiplyUnsafe(M):N.multiply(M),k=C(this,I).add(C(S,T));return k.is0()?void 0:k}toAffine(S){return p(this,S)}isTorsionFree(){let{h:S,isTorsionFree:I}=t;if(S===Ve)return!0;if(I)return I(y,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:S,clearCofactor:I}=t;return S===Ve?this:I?I(y,this):this.multiplyUnsafe(t.h)}toRawBytes(S=!0){return(0,pe.abool)("isCompressed",S),this.assertValidity(),i(y,this,S)}toHex(S=!0){return(0,pe.abool)("isCompressed",S),(0,pe.bytesToHex)(this.toRawBytes(S))}}y.BASE=new y(t.Gx,t.Gy,r.ONE),y.ZERO=new y(r.ZERO,r.ONE,r.ZERO);let{endo:b,nBitLength:v}=t,A=(0,pb.wNAF)(y,b?Math.ceil(v/2):v);return{CURVE:t,ProjectivePoint:y,normPrivateKeyToScalar:l,weierstrassEquation:s,isWithinCurveOrder:d}}function jhe(e){let t=(0,pb.validateBasic)(e);return(0,pe.validateObject)(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Mhe(e){let t=jhe(e),{Fp:r,n,nByteLength:i,nBitLength:o}=t,s=r.BYTES+1,a=2*r.BYTES+1;function c(q){return(0,us.mod)(q,n)}function u(q){return(0,us.invert)(q,n)}let{ProjectivePoint:d,normPrivateKeyToScalar:l,weierstrassEquation:m,isWithinCurveOrder:p}=i$({...t,toBytes(q,L,V){let Q=L.toAffine(),re=r.toBytes(Q.x),_e=pe.concatBytes;return(0,pe.abool)("isCompressed",V),V?_e(Uint8Array.from([L.hasEvenY()?2:3]),re):_e(Uint8Array.from([4]),re,r.toBytes(Q.y))},fromBytes(q){let L=q.length,V=q[0],Q=q.subarray(1);if(L===s&&(V===2||V===3)){let re=(0,pe.bytesToNumberBE)(Q);if(!(0,pe.inRange)(re,Ve,r.ORDER))throw new Error("Point is not on curve");let _e=m(re),je;try{je=r.sqrt(_e)}catch(nt){let Ot=nt instanceof Error?": "+nt.message:"";throw new Error("Point is not on curve"+Ot)}let K=(je&Ve)===Ve;return(V&1)===1!==K&&(je=r.neg(je)),{x:re,y:je}}else if(L===a&&V===4){let re=r.fromBytes(Q.subarray(0,r.BYTES)),_e=r.fromBytes(Q.subarray(r.BYTES,2*r.BYTES));return{x:re,y:_e}}else{let re=s,_e=a;throw new Error("invalid Point, expected length of "+re+", or uncompressed "+_e+", got "+L)}}});function h(q){let L=n>>Ve;return q>L}function y(q){return h(q)?c(-q):q}let b=(q,L,V)=>(0,pe.bytesToNumberBE)(q.slice(L,V));class v{constructor(L,V,Q){(0,pe.aInRange)("r",L,Ve,n),(0,pe.aInRange)("s",V,Ve,n),this.r=L,this.s=V,Q!=null&&(this.recovery=Q),Object.freeze(this)}static fromCompact(L){let V=i;return L=(0,pe.ensureBytes)("compactSignature",L,V*2),new v(b(L,0,V),b(L,V,2*V))}static fromDER(L){let{r:V,s:Q}=Ft.DER.toSig((0,pe.ensureBytes)("DER",L));return new v(V,Q)}assertValidity(){}addRecoveryBit(L){return new v(this.r,this.s,L)}recoverPublicKey(L){let{r:V,s:Q,recovery:re}=this,_e=x((0,pe.ensureBytes)("msgHash",L));if(re==null||![0,1,2,3].includes(re))throw new Error("recovery id invalid");let je=re===2||re===3?V+t.n:V;if(je>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let K=(re&1)===0?"02":"03",wr=d.fromHex(K+x2(je,r.BYTES)),nt=u(je),Ot=c(-_e*nt),Ki=c(Q*nt),vi=d.BASE.multiplyAndAddUnsafe(wr,Ot,Ki);if(!vi)throw new Error("point at infinify");return vi.assertValidity(),vi}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return(0,pe.hexToBytes)(this.toDERHex())}toDERHex(){return Ft.DER.hexFromSig(this)}toCompactRawBytes(){return(0,pe.hexToBytes)(this.toCompactHex())}toCompactHex(){let L=i;return x2(this.r,L)+x2(this.s,L)}}let A={isValidPrivateKey(q){try{return l(q),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let q=(0,us.getMinHashLength)(t.n);return(0,us.mapHashToField)(t.randomBytes(q),t.n)},precompute(q=8,L=d.BASE){return L._setWindowSize(q),L.multiply(BigInt(3)),L}};function E(q,L=!0){return d.fromPrivateKey(q).toRawBytes(L)}function S(q){if(typeof q=="bigint")return!1;if(q instanceof d)return!0;let V=(0,pe.ensureBytes)("key",q).length,Q=r.BYTES,re=Q+1,_e=2*Q+1;if(!(t.allowedPrivateKeyLengths||i===re))return V===re||V===_e}function I(q,L,V=!0){if(S(q)===!0)throw new Error("first arg must be private key");if(S(L)===!1)throw new Error("second arg must be public key");return d.fromHex(L).multiply(l(q)).toRawBytes(V)}let T=t.bits2int||function(q){if(q.length>8192)throw new Error("input is too large");let L=(0,pe.bytesToNumberBE)(q),V=q.length*8-o;return V>0?L>>BigInt(V):L},x=t.bits2int_modN||function(q){return c(T(q))},C=(0,pe.bitMask)(o);function k(q){return(0,pe.aInRange)("num < 2^"+o,q,Pi,C),(0,pe.numberToBytesBE)(q,i)}function N(q,L,V=M){if(["recovered","canonical"].some($o=>$o in V))throw new Error("sign() legacy options not supported");let{hash:Q,randomBytes:re}=t,{lowS:_e,prehash:je,extraEntropy:K}=V;_e==null&&(_e=!0),q=(0,pe.ensureBytes)("msgHash",q),n$(V),je&&(q=(0,pe.ensureBytes)("prehashed msgHash",Q(q)));let wr=x(q),nt=l(L),Ot=[k(nt),k(wr)];if(K!=null&&K!==!1){let $o=K===!0?re(r.BYTES):K;Ot.push((0,pe.ensureBytes)("extraEntropy",$o))}let Ki=(0,pe.concatBytes)(...Ot),vi=wr;function Kp($o){let ia=T($o);if(!p(ia))return;let KA=u(ia),Wp=d.BASE.multiply(ia).toAffine(),$c=c(Wp.x);if($c===Pi)return;let zp=c(KA*c(vi+$c*nt));if(zp===Pi)return;let el=(Wp.x===$c?0:2)|Number(Wp.y&Ve),A3=zp;return _e&&h(zp)&&(A3=y(zp),el^=1),new v($c,A3,el)}return{seed:Ki,k2sig:Kp}}let M={lowS:t.lowS,prehash:!1},j={lowS:t.lowS,prehash:!1};function D(q,L,V=M){let{seed:Q,k2sig:re}=N(q,L,V),_e=t;return(0,pe.createHmacDrbg)(_e.hash.outputLen,_e.nByteLength,_e.hmac)(Q,re)}d.BASE._setWindowSize(8);function U(q,L,V,Q=j){let re=q;L=(0,pe.ensureBytes)("msgHash",L),V=(0,pe.ensureBytes)("publicKey",V);let{lowS:_e,prehash:je,format:K}=Q;if(n$(Q),"strict"in Q)throw new Error("options.strict was renamed to lowS");if(K!==void 0&&K!=="compact"&&K!=="der")throw new Error("format must be compact or der");let wr=typeof re=="string"||(0,pe.isBytes)(re),nt=!wr&&!K&&typeof re=="object"&&re!==null&&typeof re.r=="bigint"&&typeof re.s=="bigint";if(!wr&&!nt)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let Ot,Ki;try{if(nt&&(Ot=new v(re.r,re.s)),wr){try{K!=="compact"&&(Ot=v.fromDER(re))}catch(el){if(!(el instanceof Ft.DER.Err))throw el}!Ot&&K!=="der"&&(Ot=v.fromCompact(re))}Ki=d.fromHex(V)}catch{return!1}if(!Ot||_e&&Ot.hasHighS())return!1;je&&(L=t.hash(L));let{r:vi,s:Kp}=Ot,$o=x(L),ia=u(Kp),KA=c($o*ia),Wp=c(vi*ia),$c=d.BASE.multiplyAndAddUnsafe(Ki,KA,Wp)?.toAffine();return $c?c($c.x)===vi:!1}return{CURVE:t,getPublicKey:E,getSharedSecret:I,sign:D,verify:U,ProjectivePoint:d,Signature:v,utils:A}}function o$(e,t){let r=e.ORDER,n=Pi;for(let h=r-Ve;h%$a===Pi;h/=$a)n+=Ve;let i=n,o=$a<<i-Ve-Ve,s=o*$a,a=(r-Ve)/s,c=(a-Ve)/$a,u=s-Ve,d=o,l=e.pow(t,a),m=e.pow(t,(a+Ve)/$a),p=(h,y)=>{let b=l,v=e.pow(y,u),A=e.sqr(v);A=e.mul(A,y);let E=e.mul(h,A);E=e.pow(E,c),E=e.mul(E,v),v=e.mul(E,y),A=e.mul(E,h);let S=e.mul(A,v);E=e.pow(S,d);let I=e.eql(E,e.ONE);v=e.mul(A,m),E=e.mul(S,b),A=e.cmov(v,A,I),S=e.cmov(E,S,I);for(let T=i;T>Ve;T--){let x=T-$a;x=$a<<x-Ve;let C=e.pow(S,x),k=e.eql(C,e.ONE);v=e.mul(A,b),b=e.mul(b,b),C=e.mul(S,b),A=e.cmov(v,A,k),S=e.cmov(C,S,k)}return{isValid:I,value:A}};if(e.ORDER%O2===Fm){let h=(e.ORDER-Fm)/O2,y=e.sqrt(e.neg(t));p=(b,v)=>{let A=e.sqr(v),E=e.mul(b,v);A=e.mul(A,E);let S=e.pow(A,h);S=e.mul(S,E);let I=e.mul(S,y),T=e.mul(e.sqr(S),v),x=e.eql(T,b),C=e.cmov(I,S,x);return{isValid:x,value:C}}}return p}function qhe(e,t){if((0,us.validateField)(e),!e.isValid(t.A)||!e.isValid(t.B)||!e.isValid(t.Z))throw new Error("mapToCurveSimpleSWU: invalid opts");let r=o$(e,t.Z);if(!e.isOdd)throw new Error("Fp.isOdd is not implemented!");return n=>{let i,o,s,a,c,u,d,l;i=e.sqr(n),i=e.mul(i,t.Z),o=e.sqr(i),o=e.add(o,i),s=e.add(o,e.ONE),s=e.mul(s,t.B),a=e.cmov(t.Z,e.neg(o),!e.eql(o,e.ZERO)),a=e.mul(a,t.A),o=e.sqr(s),u=e.sqr(a),c=e.mul(u,t.A),o=e.add(o,c),o=e.mul(o,s),u=e.mul(u,a),c=e.mul(u,t.B),o=e.add(o,c),d=e.mul(i,s);let{isValid:m,value:p}=r(o,u);l=e.mul(i,n),l=e.mul(l,p),d=e.cmov(d,s,m),l=e.cmov(l,p,m);let h=e.isOdd(n)===e.isOdd(l);l=e.cmov(e.neg(l),l,h);let y=(0,us.FpInvertBatch)(e,[a],!0)[0];return d=e.mul(d,y),{x:d,y:l}}}});var c$=g(gb=>{"use strict";Object.defineProperty(gb,"__esModule",{value:!0});gb.getHash=a$;gb.createCurve=Bhe;var Dhe=p2(),s$=is(),Lhe=R2();function a$(e){return{hash:e,hmac:(t,...r)=>(0,Dhe.hmac)(e,t,(0,s$.concatBytes)(...r)),randomBytes:s$.randomBytes}}function Bhe(e,t){let r=n=>(0,Lhe.weierstrass)({...e,...a$(n)});return{...r(t),create:r}}});var f$=g(Ru=>{"use strict";Object.defineProperty(Ru,"__esModule",{value:!0});Ru.expand_message_xmd=d$;Ru.expand_message_xof=l$;Ru.hash_to_field=C2;Ru.isogenyMap=Fhe;Ru.createHasher=$he;var u$=Um(),Rr=Fa(),Uhe=Rr.bytesToNumberBE;function Ja(e,t){if($m(e),$m(t),e<0||e>=1<<8*t)throw new Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let n=t-1;n>=0;n--)r[n]=e&255,e>>>=8;return new Uint8Array(r)}function Hhe(e,t){let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e[n]^t[n];return r}function $m(e){if(!Number.isSafeInteger(e))throw new Error("number expected")}function d$(e,t,r,n){(0,Rr.abytes)(e),(0,Rr.abytes)(t),$m(r),t.length>255&&(t=n((0,Rr.concatBytes)((0,Rr.utf8ToBytes)("H2C-OVERSIZE-DST-"),t)));let{outputLen:i,blockLen:o}=n,s=Math.ceil(r/i);if(r>65535||s>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=(0,Rr.concatBytes)(t,Ja(t.length,1)),c=Ja(0,o),u=Ja(r,2),d=new Array(s),l=n((0,Rr.concatBytes)(c,e,u,Ja(0,1),a));d[0]=n((0,Rr.concatBytes)(l,Ja(1,1),a));for(let p=1;p<=s;p++){let h=[Hhe(l,d[p-1]),Ja(p+1,1),a];d[p]=n((0,Rr.concatBytes)(...h))}return(0,Rr.concatBytes)(...d).slice(0,r)}function l$(e,t,r,n,i){if((0,Rr.abytes)(e),(0,Rr.abytes)(t),$m(r),t.length>255){let o=Math.ceil(2*n/8);t=i.create({dkLen:o}).update((0,Rr.utf8ToBytes)("H2C-OVERSIZE-DST-")).update(t).digest()}if(r>65535||t.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return i.create({dkLen:r}).update(e).update(Ja(r,2)).update(t).update(Ja(t.length,1)).digest()}function C2(e,t,r){(0,Rr.validateObject)(r,{DST:"stringOrUint8Array",p:"bigint",m:"isSafeInteger",k:"isSafeInteger",hash:"hash"});let{p:n,k:i,m:o,hash:s,expand:a,DST:c}=r;(0,Rr.abytes)(e),$m(t);let u=typeof c=="string"?(0,Rr.utf8ToBytes)(c):c,d=n.toString(2).length,l=Math.ceil((d+i)/8),m=t*o*l,p;if(a==="xmd")p=d$(e,u,m,s);else if(a==="xof")p=l$(e,u,m,i,s);else if(a==="_internal_pass")p=e;else throw new Error('expand must be "xmd" or "xof"');let h=new Array(t);for(let y=0;y<t;y++){let b=new Array(o);for(let v=0;v<o;v++){let A=l*(v+y*o),E=p.subarray(A,A+l);b[v]=(0,u$.mod)(Uhe(E),n)}h[y]=b}return h}function Fhe(e,t){let r=t.map(n=>Array.from(n).reverse());return(n,i)=>{let[o,s,a,c]=r.map(l=>l.reduce((m,p)=>e.add(e.mul(m,n),p))),[u,d]=(0,u$.FpInvertBatch)(e,[s,c],!0);return n=e.mul(o,u),i=e.mul(i,e.mul(a,d)),{x:n,y:i}}}function $he(e,t,r){if(typeof t!="function")throw new Error("mapToCurve() must be defined");function n(o){return e.fromAffine(t(o))}function i(o){let s=o.clearCofactor();return s.equals(e.ZERO)?e.ZERO:(s.assertValidity(),s)}return{defaults:r,hashToCurve(o,s){let a=C2(o,2,{...r,DST:r.DST,...s}),c=n(a[0]),u=n(a[1]);return i(c.add(u))},encodeToCurve(o,s){let a=C2(o,1,{...r,DST:r.encodeDST,...s});return i(n(a[0]))},mapToCurve(o){if(!Array.isArray(o))throw new Error("expected array of bigints");for(let s of o)if(typeof s!="bigint")throw new Error("expected array of bigints");return i(n(o))}}}});var Ga=g(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.encodeToCurve=Qt.hashToCurve=Qt.secp256k1_hasher=Qt.schnorr=Qt.secp256k1=void 0;var hb=f2(),Jhe=is(),Vhe=c$(),g$=f$(),Zt=Um(),cn=Fa(),Ghe=R2(),Gm=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),yb=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),M2=BigInt(0),Jm=BigInt(1),_b=BigInt(2),p$=(e,t)=>(e+t/_b)/t;function h$(e){let t=Gm,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,d=u*u*e%t,l=(0,Zt.pow2)(d,r,t)*d%t,m=(0,Zt.pow2)(l,r,t)*d%t,p=(0,Zt.pow2)(m,_b,t)*u%t,h=(0,Zt.pow2)(p,i,t)*p%t,y=(0,Zt.pow2)(h,o,t)*h%t,b=(0,Zt.pow2)(y,a,t)*y%t,v=(0,Zt.pow2)(b,c,t)*b%t,A=(0,Zt.pow2)(v,a,t)*y%t,E=(0,Zt.pow2)(A,r,t)*d%t,S=(0,Zt.pow2)(E,s,t)*h%t,I=(0,Zt.pow2)(S,n,t)*u%t,T=(0,Zt.pow2)(I,_b,t);if(!Va.eql(Va.sqr(T),e))throw new Error("Cannot find square root");return T}var Va=(0,Zt.Field)(Gm,void 0,void 0,{sqrt:h$});Qt.secp256k1=(0,Vhe.createCurve)({a:M2,b:BigInt(7),Fp:Va,n:yb,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=yb,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Jm*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,s=BigInt("0x100000000000000000000000000000000"),a=p$(o*e,t),c=p$(-n*e,t),u=(0,Zt.mod)(e-a*r-c*i,t),d=(0,Zt.mod)(-a*n-c*o,t),l=u>s,m=d>s;if(l&&(u=t-u),m&&(d=t-d),u>s||d>s)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:l,k1:u,k2neg:m,k2:d}}}},hb.sha256);var m$={};function bb(e,...t){let r=m$[e];if(r===void 0){let n=(0,hb.sha256)(Uint8Array.from(e,i=>i.charCodeAt(0)));r=(0,cn.concatBytes)(n,n),m$[e]=r}return(0,hb.sha256)((0,cn.concatBytes)(r,...t))}var q2=e=>e.toRawBytes(!0).slice(1),k2=e=>(0,cn.numberToBytesBE)(e,32),N2=e=>(0,Zt.mod)(e,Gm),Vm=e=>(0,Zt.mod)(e,yb),D2=Qt.secp256k1.ProjectivePoint,Khe=(e,t,r)=>D2.BASE.multiplyAndAddUnsafe(e,t,r);function j2(e){let t=Qt.secp256k1.utils.normPrivateKeyToScalar(e),r=D2.fromPrivateKey(t);return{scalar:r.hasEvenY()?t:Vm(-t),bytes:q2(r)}}function y$(e){(0,cn.aInRange)("x",e,Jm,Gm);let t=N2(e*e),r=N2(t*e+BigInt(7)),n=h$(r);n%_b!==M2&&(n=N2(-n));let i=new D2(e,n,Jm);return i.assertValidity(),i}var jl=cn.bytesToNumberBE;function _$(...e){return Vm(jl(bb("BIP0340/challenge",...e)))}function Whe(e){return j2(e).bytes}function zhe(e,t,r=(0,Jhe.randomBytes)(32)){let n=(0,cn.ensureBytes)("message",e),{bytes:i,scalar:o}=j2(t),s=(0,cn.ensureBytes)("auxRand",r,32),a=k2(o^jl(bb("BIP0340/aux",s))),c=bb("BIP0340/nonce",a,i,n),u=Vm(jl(c));if(u===M2)throw new Error("sign failed: k is zero");let{bytes:d,scalar:l}=j2(u),m=_$(d,i,n),p=new Uint8Array(64);if(p.set(d,0),p.set(k2(Vm(l+m*o)),32),!b$(p,n,i))throw new Error("sign: Invalid signature produced");return p}function b$(e,t,r){let n=(0,cn.ensureBytes)("signature",e,64),i=(0,cn.ensureBytes)("message",t),o=(0,cn.ensureBytes)("publicKey",r,32);try{let s=y$(jl(o)),a=jl(n.subarray(0,32));if(!(0,cn.inRange)(a,Jm,Gm))return!1;let c=jl(n.subarray(32,64));if(!(0,cn.inRange)(c,Jm,yb))return!1;let u=_$(k2(a),q2(s),i),d=Khe(s,c,Vm(-u));return!(!d||!d.hasEvenY()||d.toAffine().x!==a)}catch{return!1}}Qt.schnorr={getPublicKey:Whe,sign:zhe,verify:b$,utils:{randomPrivateKey:Qt.secp256k1.utils.randomPrivateKey,lift_x:y$,pointToBytes:q2,numberToBytesBE:cn.numberToBytesBE,bytesToNumberBE:cn.bytesToNumberBE,taggedHash:bb,mod:Zt.mod}};var Yhe=(0,g$.isogenyMap)(Va,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),Xhe=(0,Ghe.mapToCurveSimpleSWU)(Va,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:Va.create(BigInt("-11"))});Qt.secp256k1_hasher=(0,g$.createHasher)(Qt.secp256k1.ProjectivePoint,e=>{let{x:t,y:r}=Xhe(Va.create(e[0]));return Yhe(t,r)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:Va.ORDER,m:1,k:128,expand:"xmd",hash:hb.sha256});Qt.hashToCurve=Qt.secp256k1_hasher.hashToCurve;Qt.encodeToCurve=Qt.secp256k1_hasher.encodeToCurve});var Eb=g(B2=>{"use strict";Object.defineProperty(B2,"__esModule",{value:!0});B2.recoverPublicKey=Qhe;var E$=Sr(),Zhe=ur(),L2=pt(),w$=W();async function Qhe({hash:e,signature:t}){let r=(0,E$.isHex)(e)?e:(0,w$.toHex)(e),{secp256k1:n}=await Promise.resolve().then(()=>Ga());return`0x${(()=>{if(typeof t=="object"&&"r"in t&&"s"in t){let{r:u,s:d,v:l,yParity:m}=t,p=Number(m??l),h=v$(p);return new n.Signature((0,L2.hexToBigInt)(u),(0,L2.hexToBigInt)(d)).addRecoveryBit(h)}let s=(0,E$.isHex)(t)?t:(0,w$.toHex)(t);if((0,Zhe.size)(s)!==65)throw new Error("invalid signature length");let a=(0,L2.hexToNumber)(`0x${s.slice(130)}`),c=v$(a);return n.Signature.fromCompact(s.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function v$(e){if(e===0||e===1)return e;if(e===27)return 0;if(e===28)return 1;throw new Error("Invalid yParityOrV value")}});var ds=g(U2=>{"use strict";Object.defineProperty(U2,"__esModule",{value:!0});U2.recoverAddress=rye;var eye=u2(),tye=Eb();async function rye({hash:e,signature:t}){return(0,eye.publicKeyToAddress)(await(0,tye.recoverPublicKey)({hash:e,signature:t}))}});var Ml=g(Km=>{"use strict";Object.defineProperty(Km,"__esModule",{value:!0});Km.toRlp=H2;Km.bytesToRlp=aye;Km.hexToRlp=cye;var nye=ye(),iye=Pl(),oye=Je(),sye=W();function H2(e,t="hex"){let r=S$(e),n=(0,iye.createCursor)(new Uint8Array(r.length));return r.encode(n),t==="hex"?(0,sye.bytesToHex)(n.bytes):n.bytes}function aye(e,t="bytes"){return H2(e,t)}function cye(e,t="hex"){return H2(e,t)}function S$(e){return Array.isArray(e)?uye(e.map(t=>S$(t))):dye(e)}function uye(e){let t=e.reduce((i,o)=>i+o.length,0),r=A$(t);return{length:t<=55?1+t:1+r+t,encode(i){t<=55?i.pushByte(192+t):(i.pushByte(247+r),r===1?i.pushUint8(t):r===2?i.pushUint16(t):r===3?i.pushUint24(t):i.pushUint32(t));for(let{encode:o}of e)o(i)}}}function dye(e){let t=typeof e=="string"?(0,oye.hexToBytes)(e):e,r=A$(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length,encode(i){t.length===1&&t[0]<128?i.pushBytes(t):t.length<=55?(i.pushByte(128+t.length),i.pushBytes(t)):(i.pushByte(183+r),r===1?i.pushUint8(t.length):r===2?i.pushUint16(t.length):r===3?i.pushUint24(t.length):i.pushUint32(t.length),i.pushBytes(t))}}}function A$(e){if(e<2**8)return 1;if(e<2**16)return 2;if(e<2**24)return 3;if(e<2**32)return 4;throw new nye.BaseError("Length is too large.")}});var $2=g(F2=>{"use strict";Object.defineProperty(F2,"__esModule",{value:!0});F2.hashAuthorization=gye;var lye=Nt(),fye=Je(),I$=W(),pye=Ml(),mye=Hr();function gye(e){let{chainId:t,nonce:r,to:n}=e,i=e.contractAddress??e.address,o=(0,mye.keccak256)((0,lye.concatHex)(["0x05",(0,pye.toRlp)([t?(0,I$.numberToHex)(t):"0x",i,r?(0,I$.numberToHex)(r):"0x"])]));return n==="bytes"?(0,fye.hexToBytes)(o):o}});var ql=g(J2=>{"use strict";Object.defineProperty(J2,"__esModule",{value:!0});J2.recoverAuthorizationAddress=_ye;var hye=ds(),yye=$2();async function _ye(e){let{authorization:t,signature:r}=e;return(0,hye.recoverAddress)({hash:(0,yye.hashAuthorization)(t),signature:r??t})}});var K2=g(wb=>{"use strict";Object.defineProperty(wb,"__esModule",{value:!0});wb.EstimateGasExecutionError=void 0;var bye=Rl(),V2=qa(),Eye=ye(),wye=Xt(),G2=class extends Eye.BaseError{constructor(t,{account:r,docsPath:n,chain:i,data:o,gas:s,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:d,to:l,value:m}){let p=(0,wye.prettyPrint)({from:r?.address,to:l,value:typeof m<"u"&&`${(0,bye.formatEther)(m)} ${i?.nativeCurrency?.symbol||"ETH"}`,data:o,gas:s,gasPrice:typeof a<"u"&&`${(0,V2.formatGwei)(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${(0,V2.formatGwei)(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${(0,V2.formatGwei)(u)} gwei`,nonce:d});super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Estimate Gas Arguments:",p].filter(Boolean),name:"EstimateGasExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}};wb.EstimateGasExecutionError=G2});var Ti=g(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.UnknownNodeError=et.TipAboveFeeCapError=et.TransactionTypeNotSupportedError=et.IntrinsicGasTooLowError=et.IntrinsicGasTooHighError=et.InsufficientFundsError=et.NonceMaxValueError=et.NonceTooLowError=et.NonceTooHighError=et.FeeCapTooLowError=et.FeeCapTooHighError=et.ExecutionRevertedError=void 0;var vb=qa(),Xn=ye(),Wm=class extends Xn.BaseError{constructor({cause:t,message:r}={}){let n=r?.replace("execution reverted: ","")?.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:t,name:"ExecutionRevertedError"})}};et.ExecutionRevertedError=Wm;Object.defineProperty(Wm,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(Wm,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});var Sb=class extends Xn.BaseError{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${(0,vb.formatGwei)(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:t,name:"FeeCapTooHighError"})}};et.FeeCapTooHighError=Sb;Object.defineProperty(Sb,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});var Ab=class extends Xn.BaseError{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${(0,vb.formatGwei)(r)}`:""} gwei) cannot be lower than the block base fee.`,{cause:t,name:"FeeCapTooLowError"})}};et.FeeCapTooLowError=Ab;Object.defineProperty(Ab,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});var Ib=class extends Xn.BaseError{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}is higher than the next one expected.`,{cause:t,name:"NonceTooHighError"})}};et.NonceTooHighError=Ib;Object.defineProperty(Ib,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});var Pb=class extends Xn.BaseError{constructor({cause:t,nonce:r}={}){super([`Nonce provided for the transaction ${r?`(${r}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(`
46
+ `),{cause:t,name:"NonceTooLowError"})}};et.NonceTooLowError=Pb;Object.defineProperty(Pb,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});var Tb=class extends Xn.BaseError{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}exceeds the maximum allowed nonce.`,{cause:t,name:"NonceMaxValueError"})}};et.NonceMaxValueError=Tb;Object.defineProperty(Tb,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});var xb=class extends Xn.BaseError{constructor({cause:t}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
47
+ `),{cause:t,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}};et.InsufficientFundsError=xb;Object.defineProperty(xb,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});var Ob=class extends Xn.BaseError{constructor({cause:t,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:t,name:"IntrinsicGasTooHighError"})}};et.IntrinsicGasTooHighError=Ob;Object.defineProperty(Ob,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});var Rb=class extends Xn.BaseError{constructor({cause:t,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction is too low.`,{cause:t,name:"IntrinsicGasTooLowError"})}};et.IntrinsicGasTooLowError=Rb;Object.defineProperty(Rb,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});var Cb=class extends Xn.BaseError{constructor({cause:t}){super("The transaction type is not supported for this chain.",{cause:t,name:"TransactionTypeNotSupportedError"})}};et.TransactionTypeNotSupportedError=Cb;Object.defineProperty(Cb,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});var Nb=class extends Xn.BaseError{constructor({cause:t,maxPriorityFeePerGas:r,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${r?` = ${(0,vb.formatGwei)(r)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${(0,vb.formatGwei)(n)} gwei`:""}).`].join(`
48
+ `),{cause:t,name:"TipAboveFeeCapError"})}};et.TipAboveFeeCapError=Nb;Object.defineProperty(Nb,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});var W2=class extends Xn.BaseError{constructor({cause:t}){super(`An error occurred while executing: ${t?.shortMessage}`,{cause:t,name:"UnknownNodeError"})}};et.UnknownNodeError=W2});var Dl=g(kb=>{"use strict";Object.defineProperty(kb,"__esModule",{value:!0});kb.containsNodeError=Sye;kb.getNodeError=Aye;var P$=ye(),tt=Ti(),vye=Nn(),T$=ss();function Sye(e){return e instanceof T$.TransactionRejectedRpcError||e instanceof T$.InvalidInputRpcError||e instanceof vye.RpcRequestError&&e.code===tt.ExecutionRevertedError.code}function Aye(e,t){let r=(e.details||"").toLowerCase(),n=e instanceof P$.BaseError?e.walk(i=>i?.code===tt.ExecutionRevertedError.code):e;return n instanceof P$.BaseError?new tt.ExecutionRevertedError({cause:e,message:n.details}):tt.ExecutionRevertedError.nodeMessage.test(r)?new tt.ExecutionRevertedError({cause:e,message:e.details}):tt.FeeCapTooHighError.nodeMessage.test(r)?new tt.FeeCapTooHighError({cause:e,maxFeePerGas:t?.maxFeePerGas}):tt.FeeCapTooLowError.nodeMessage.test(r)?new tt.FeeCapTooLowError({cause:e,maxFeePerGas:t?.maxFeePerGas}):tt.NonceTooHighError.nodeMessage.test(r)?new tt.NonceTooHighError({cause:e,nonce:t?.nonce}):tt.NonceTooLowError.nodeMessage.test(r)?new tt.NonceTooLowError({cause:e,nonce:t?.nonce}):tt.NonceMaxValueError.nodeMessage.test(r)?new tt.NonceMaxValueError({cause:e,nonce:t?.nonce}):tt.InsufficientFundsError.nodeMessage.test(r)?new tt.InsufficientFundsError({cause:e}):tt.IntrinsicGasTooHighError.nodeMessage.test(r)?new tt.IntrinsicGasTooHighError({cause:e,gas:t?.gas}):tt.IntrinsicGasTooLowError.nodeMessage.test(r)?new tt.IntrinsicGasTooLowError({cause:e,gas:t?.gas}):tt.TransactionTypeNotSupportedError.nodeMessage.test(r)?new tt.TransactionTypeNotSupportedError({cause:e}):tt.TipAboveFeeCapError.nodeMessage.test(r)?new tt.TipAboveFeeCapError({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas}):new tt.UnknownNodeError({cause:e})}});var Y2=g(z2=>{"use strict";Object.defineProperty(z2,"__esModule",{value:!0});z2.getEstimateGasError=xye;var Iye=K2(),Pye=Ti(),Tye=Dl();function xye(e,{docsPath:t,...r}){let n=(()=>{let i=(0,Tye.getNodeError)(e,r);return i instanceof Pye.UnknownNodeError?e:i})();return new Iye.EstimateGasExecutionError(n,{docsPath:t,...r})}});var ls=g(X2=>{"use strict";Object.defineProperty(X2,"__esModule",{value:!0});X2.extract=Oye;function Oye(e,{format:t}){if(!t)return{};let r={};function n(o){let s=Object.keys(o);for(let a of s)a in e&&(r[a]=e[a]),o[a]&&typeof o[a]=="object"&&!Array.isArray(o[a])&&n(o[a])}let i=t(e||{});return n(i),r}});var Ll=g(Z2=>{"use strict";Object.defineProperty(Z2,"__esModule",{value:!0});Z2.defineFormatter=Rye;function Rye(e,t){return({exclude:r,format:n})=>({exclude:r,format:(i,o)=>{let s=t(i,o);if(r)for(let a of r)delete s[a];return{...s,...n(i,o)}},type:e})}});var Zn=g(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.defineTransactionRequest=Ka.rpcTransactionType=void 0;Ka.formatTransactionRequest=x$;var un=W(),Cye=Ll();Ka.rpcTransactionType={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function x$(e,t){let r={};return typeof e.authorizationList<"u"&&(r.authorizationList=Nye(e.authorizationList)),typeof e.accessList<"u"&&(r.accessList=e.accessList),typeof e.blobVersionedHashes<"u"&&(r.blobVersionedHashes=e.blobVersionedHashes),typeof e.blobs<"u"&&(typeof e.blobs[0]!="string"?r.blobs=e.blobs.map(n=>(0,un.bytesToHex)(n)):r.blobs=e.blobs),typeof e.data<"u"&&(r.data=e.data),e.account&&(r.from=e.account.address),typeof e.from<"u"&&(r.from=e.from),typeof e.gas<"u"&&(r.gas=(0,un.numberToHex)(e.gas)),typeof e.gasPrice<"u"&&(r.gasPrice=(0,un.numberToHex)(e.gasPrice)),typeof e.maxFeePerBlobGas<"u"&&(r.maxFeePerBlobGas=(0,un.numberToHex)(e.maxFeePerBlobGas)),typeof e.maxFeePerGas<"u"&&(r.maxFeePerGas=(0,un.numberToHex)(e.maxFeePerGas)),typeof e.maxPriorityFeePerGas<"u"&&(r.maxPriorityFeePerGas=(0,un.numberToHex)(e.maxPriorityFeePerGas)),typeof e.nonce<"u"&&(r.nonce=(0,un.numberToHex)(e.nonce)),typeof e.to<"u"&&(r.to=e.to),typeof e.type<"u"&&(r.type=Ka.rpcTransactionType[e.type]),typeof e.value<"u"&&(r.value=(0,un.numberToHex)(e.value)),r}Ka.defineTransactionRequest=(0,Cye.defineFormatter)("transactionRequest",x$);function Nye(e){return e.map(t=>({address:t.address,r:t.r?(0,un.numberToHex)(BigInt(t.r)):t.r,s:t.s?(0,un.numberToHex)(BigInt(t.s)):t.s,chainId:(0,un.numberToHex)(t.chainId),nonce:(0,un.numberToHex)(t.nonce),...typeof t.yParity<"u"?{yParity:(0,un.numberToHex)(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:(0,un.numberToHex)(t.v)}:{}}))}});var jb=g(zm=>{"use strict";Object.defineProperty(zm,"__esModule",{value:!0});zm.serializeStateMapping=Q2;zm.serializeAccountStateOverride=N$;zm.serializeStateOverride=Mye;var kye=Wn(),O$=wm(),C$=x_(),jye=Pr(),R$=W();function Q2(e){if(!(!e||e.length===0))return e.reduce((t,{slot:r,value:n})=>{if(r.length!==66)throw new O$.InvalidBytesLengthError({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new O$.InvalidBytesLengthError({size:n.length,targetSize:66,type:"hex"});return t[r]=n,t},{})}function N$(e){let{balance:t,nonce:r,state:n,stateDiff:i,code:o}=e,s={};if(o!==void 0&&(s.code=o),t!==void 0&&(s.balance=(0,R$.numberToHex)(t)),r!==void 0&&(s.nonce=(0,R$.numberToHex)(r)),n!==void 0&&(s.state=Q2(n)),i!==void 0){if(s.state)throw new C$.StateAssignmentConflictError;s.stateDiff=Q2(i)}return s}function Mye(e){if(!e)return;let t={};for(let{address:r,...n}of e){if(!(0,jye.isAddress)(r,{strict:!1}))throw new kye.InvalidAddressError({address:r});if(t[r])throw new C$.AccountStateConflictError({address:r});t[r]=N$(n)}return t}});var Mb=g(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.minInt144=R.minInt136=R.minInt128=R.minInt120=R.minInt112=R.minInt104=R.minInt96=R.minInt88=R.minInt80=R.minInt72=R.minInt64=R.minInt56=R.minInt48=R.minInt40=R.minInt32=R.minInt24=R.minInt16=R.minInt8=R.maxInt256=R.maxInt248=R.maxInt240=R.maxInt232=R.maxInt224=R.maxInt216=R.maxInt208=R.maxInt200=R.maxInt192=R.maxInt184=R.maxInt176=R.maxInt168=R.maxInt160=R.maxInt152=R.maxInt144=R.maxInt136=R.maxInt128=R.maxInt120=R.maxInt112=R.maxInt104=R.maxInt96=R.maxInt88=R.maxInt80=R.maxInt72=R.maxInt64=R.maxInt56=R.maxInt48=R.maxInt40=R.maxInt32=R.maxInt24=R.maxInt16=R.maxInt8=void 0;R.maxUint256=R.maxUint248=R.maxUint240=R.maxUint232=R.maxUint224=R.maxUint216=R.maxUint208=R.maxUint200=R.maxUint192=R.maxUint184=R.maxUint176=R.maxUint168=R.maxUint160=R.maxUint152=R.maxUint144=R.maxUint136=R.maxUint128=R.maxUint120=R.maxUint112=R.maxUint104=R.maxUint96=R.maxUint88=R.maxUint80=R.maxUint72=R.maxUint64=R.maxUint56=R.maxUint48=R.maxUint40=R.maxUint32=R.maxUint24=R.maxUint16=R.maxUint8=R.minInt256=R.minInt248=R.minInt240=R.minInt232=R.minInt224=R.minInt216=R.minInt208=R.minInt200=R.minInt192=R.minInt184=R.minInt176=R.minInt168=R.minInt160=R.minInt152=void 0;R.maxInt8=2n**(8n-1n)-1n;R.maxInt16=2n**(16n-1n)-1n;R.maxInt24=2n**(24n-1n)-1n;R.maxInt32=2n**(32n-1n)-1n;R.maxInt40=2n**(40n-1n)-1n;R.maxInt48=2n**(48n-1n)-1n;R.maxInt56=2n**(56n-1n)-1n;R.maxInt64=2n**(64n-1n)-1n;R.maxInt72=2n**(72n-1n)-1n;R.maxInt80=2n**(80n-1n)-1n;R.maxInt88=2n**(88n-1n)-1n;R.maxInt96=2n**(96n-1n)-1n;R.maxInt104=2n**(104n-1n)-1n;R.maxInt112=2n**(112n-1n)-1n;R.maxInt120=2n**(120n-1n)-1n;R.maxInt128=2n**(128n-1n)-1n;R.maxInt136=2n**(136n-1n)-1n;R.maxInt144=2n**(144n-1n)-1n;R.maxInt152=2n**(152n-1n)-1n;R.maxInt160=2n**(160n-1n)-1n;R.maxInt168=2n**(168n-1n)-1n;R.maxInt176=2n**(176n-1n)-1n;R.maxInt184=2n**(184n-1n)-1n;R.maxInt192=2n**(192n-1n)-1n;R.maxInt200=2n**(200n-1n)-1n;R.maxInt208=2n**(208n-1n)-1n;R.maxInt216=2n**(216n-1n)-1n;R.maxInt224=2n**(224n-1n)-1n;R.maxInt232=2n**(232n-1n)-1n;R.maxInt240=2n**(240n-1n)-1n;R.maxInt248=2n**(248n-1n)-1n;R.maxInt256=2n**(256n-1n)-1n;R.minInt8=-(2n**(8n-1n));R.minInt16=-(2n**(16n-1n));R.minInt24=-(2n**(24n-1n));R.minInt32=-(2n**(32n-1n));R.minInt40=-(2n**(40n-1n));R.minInt48=-(2n**(48n-1n));R.minInt56=-(2n**(56n-1n));R.minInt64=-(2n**(64n-1n));R.minInt72=-(2n**(72n-1n));R.minInt80=-(2n**(80n-1n));R.minInt88=-(2n**(88n-1n));R.minInt96=-(2n**(96n-1n));R.minInt104=-(2n**(104n-1n));R.minInt112=-(2n**(112n-1n));R.minInt120=-(2n**(120n-1n));R.minInt128=-(2n**(128n-1n));R.minInt136=-(2n**(136n-1n));R.minInt144=-(2n**(144n-1n));R.minInt152=-(2n**(152n-1n));R.minInt160=-(2n**(160n-1n));R.minInt168=-(2n**(168n-1n));R.minInt176=-(2n**(176n-1n));R.minInt184=-(2n**(184n-1n));R.minInt192=-(2n**(192n-1n));R.minInt200=-(2n**(200n-1n));R.minInt208=-(2n**(208n-1n));R.minInt216=-(2n**(216n-1n));R.minInt224=-(2n**(224n-1n));R.minInt232=-(2n**(232n-1n));R.minInt240=-(2n**(240n-1n));R.minInt248=-(2n**(248n-1n));R.minInt256=-(2n**(256n-1n));R.maxUint8=2n**8n-1n;R.maxUint16=2n**16n-1n;R.maxUint24=2n**24n-1n;R.maxUint32=2n**32n-1n;R.maxUint40=2n**40n-1n;R.maxUint48=2n**48n-1n;R.maxUint56=2n**56n-1n;R.maxUint64=2n**64n-1n;R.maxUint72=2n**72n-1n;R.maxUint80=2n**80n-1n;R.maxUint88=2n**88n-1n;R.maxUint96=2n**96n-1n;R.maxUint104=2n**104n-1n;R.maxUint112=2n**112n-1n;R.maxUint120=2n**120n-1n;R.maxUint128=2n**128n-1n;R.maxUint136=2n**136n-1n;R.maxUint144=2n**144n-1n;R.maxUint152=2n**152n-1n;R.maxUint160=2n**160n-1n;R.maxUint168=2n**168n-1n;R.maxUint176=2n**176n-1n;R.maxUint184=2n**184n-1n;R.maxUint192=2n**192n-1n;R.maxUint200=2n**200n-1n;R.maxUint208=2n**208n-1n;R.maxUint216=2n**216n-1n;R.maxUint224=2n**224n-1n;R.maxUint232=2n**232n-1n;R.maxUint240=2n**240n-1n;R.maxUint248=2n**248n-1n;R.maxUint256=2n**256n-1n});var Qn=g(eO=>{"use strict";Object.defineProperty(eO,"__esModule",{value:!0});eO.assertRequest=Lye;var qye=at(),Dye=Mb(),k$=Wn(),j$=Ti(),M$=Pr();function Lye(e){let{account:t,maxFeePerGas:r,maxPriorityFeePerGas:n,to:i}=e,o=t?(0,qye.parseAccount)(t):void 0;if(o&&!(0,M$.isAddress)(o.address))throw new k$.InvalidAddressError({address:o.address});if(i&&!(0,M$.isAddress)(i))throw new k$.InvalidAddressError({address:i});if(r&&r>Dye.maxUint256)throw new j$.FeeCapTooHighError({maxFeePerGas:r});if(n&&r&&n>r)throw new j$.TipAboveFeeCapError({maxFeePerGas:r,maxPriorityFeePerGas:n})}});var Bl=g(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.MaxFeePerGasTooLowError=Wa.Eip1559FeesNotSupportedError=Wa.BaseFeeScalarError=void 0;var Bye=qa(),iO=ye(),tO=class extends iO.BaseError{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}};Wa.BaseFeeScalarError=tO;var rO=class extends iO.BaseError{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}};Wa.Eip1559FeesNotSupportedError=rO;var nO=class extends iO.BaseError{constructor({maxPriorityFeePerGas:t}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${(0,Bye.formatGwei)(t)} gwei).`,{name:"MaxFeePerGasTooLowError"})}};Wa.MaxFeePerGasTooLowError=nO});var Ym=g(qb=>{"use strict";Object.defineProperty(qb,"__esModule",{value:!0});qb.BlockNotFoundError=void 0;var Uye=ye(),oO=class extends Uye.BaseError{constructor({blockHash:t,blockNumber:r}){let n="Block";t&&(n=`Block at hash "${t}"`),r&&(n=`Block at number "${r}"`),super(`${n} could not be found.`,{name:"BlockNotFoundError"})}};qb.BlockNotFoundError=oO});var Cu=g(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.defineTransaction=za.transactionType=void 0;za.formatTransaction=D$;var q$=pt(),Hye=Ll();za.transactionType={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function D$(e,t){let r={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,...e.blockTimestamp!=null&&{blockTimestamp:BigInt(e.blockTimestamp)},chainId:e.chainId?(0,q$.hexToNumber)(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?(0,q$.hexToNumber)(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?za.transactionType[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};return e.authorizationList&&(r.authorizationList=Fye(e.authorizationList)),r.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof r.v=="bigint"){if(r.v===0n||r.v===27n)return 0;if(r.v===1n||r.v===28n)return 1;if(r.v>=35n)return r.v%2n===0n?1:0}})(),r.type==="legacy"&&(delete r.accessList,delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas,delete r.yParity),r.type==="eip2930"&&(delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas),r.type==="eip1559"&&delete r.maxFeePerBlobGas,r}za.defineTransaction=(0,Hye.defineFormatter)("transaction",D$);function Fye(e){return e.map(t=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}});var Ul=g(Xm=>{"use strict";Object.defineProperty(Xm,"__esModule",{value:!0});Xm.defineBlock=void 0;Xm.formatBlock=L$;var $ye=Ll(),Jye=Cu();function L$(e,t){let r=(e.transactions??[]).map(n=>typeof n=="string"?n:(0,Jye.formatTransaction)(n));return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:r,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}Xm.defineBlock=(0,$ye.defineFormatter)("block",L$)});var fs=g(sO=>{"use strict";Object.defineProperty(sO,"__esModule",{value:!0});sO.getBlock=Wye;var Vye=Ym(),Gye=W(),Kye=Ul();async function Wye(e,{blockHash:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",includeTransactions:i}={}){let o=i??!1,s=r!==void 0?(0,Gye.numberToHex)(r):void 0,a=null;if(t?a=await e.request({method:"eth_getBlockByHash",params:[t,o]},{dedupe:!0}):a=await e.request({method:"eth_getBlockByNumber",params:[s||n,o]},{dedupe:!!s}),!a)throw new Vye.BlockNotFoundError({blockHash:t,blockNumber:r});return(e.chain?.formatters?.block?.format||Kye.formatBlock)(a,"getBlock")}});var Db=g(aO=>{"use strict";Object.defineProperty(aO,"__esModule",{value:!0});aO.getGasPrice=zye;async function zye(e){let t=await e.request({method:"eth_gasPrice"});return BigInt(t)}});var uO=g(Lb=>{"use strict";Object.defineProperty(Lb,"__esModule",{value:!0});Lb.estimateMaxPriorityFeePerGas=Qye;Lb.internal_estimateMaxPriorityFeePerGas=U$;var Yye=Bl(),Xye=pt(),cO=Te(),B$=fs(),Zye=Db();async function Qye(e,t){return U$(e,t)}async function U$(e,t){let{block:r,chain:n=e.chain,request:i}=t||{};try{let o=n?.fees?.maxPriorityFeePerGas??n?.fees?.defaultPriorityFee;if(typeof o=="function"){let a=r||await(0,cO.getAction)(e,B$.getBlock,"getBlock")({}),c=await o({block:a,client:e,request:i});if(c===null)throw new Error;return c}if(typeof o<"u")return o;let s=await e.request({method:"eth_maxPriorityFeePerGas"});return(0,Xye.hexToBigInt)(s)}catch{let[o,s]=await Promise.all([r?Promise.resolve(r):(0,cO.getAction)(e,B$.getBlock,"getBlock")({}),(0,cO.getAction)(e,Zye.getGasPrice,"getGasPrice")({})]);if(typeof o.baseFeePerGas!="bigint")throw new Yye.Eip1559FeesNotSupportedError;let a=s-o.baseFeePerGas;return a<0n?0n:a}}});var dO=g(Bb=>{"use strict";Object.defineProperty(Bb,"__esModule",{value:!0});Bb.estimateFeesPerGas=n0e;Bb.internal_estimateFeesPerGas=$$;var H$=Bl(),F$=Te(),e0e=uO(),t0e=fs(),r0e=Db();async function n0e(e,t){return $$(e,t)}async function $$(e,t){let{block:r,chain:n=e.chain,request:i,type:o="eip1559"}=t||{},s=await(async()=>typeof n?.fees?.baseFeeMultiplier=="function"?n.fees.baseFeeMultiplier({block:r,client:e,request:i}):n?.fees?.baseFeeMultiplier??1.2)();if(s<1)throw new H$.BaseFeeScalarError;let c=10**(s.toString().split(".")[1]?.length??0),u=m=>m*BigInt(Math.round(s*c))/BigInt(c),d=r||await(0,F$.getAction)(e,t0e.getBlock,"getBlock")({});if(typeof n?.fees?.estimateFeesPerGas=="function"){let m=await n.fees.estimateFeesPerGas({block:r,client:e,multiply:u,request:i,type:o});if(m!==null)return m}if(o==="eip1559"){if(typeof d.baseFeePerGas!="bigint")throw new H$.Eip1559FeesNotSupportedError;let m=typeof i?.maxPriorityFeePerGas=="bigint"?i.maxPriorityFeePerGas:await(0,e0e.internal_estimateMaxPriorityFeePerGas)(e,{block:d,chain:n,request:i}),p=u(d.baseFeePerGas);return{maxFeePerGas:i?.maxFeePerGas??p+m,maxPriorityFeePerGas:m}}return{gasPrice:i?.gasPrice??u(await(0,F$.getAction)(e,r0e.getGasPrice,"getGasPrice")({}))}}});var Nu=g(lO=>{"use strict";Object.defineProperty(lO,"__esModule",{value:!0});lO.formatBlockParameter=s0e;var i0e=ye(),o0e=W();function s0e(e){let{blockHash:t,blockNumber:r,blockTag:n,requireCanonical:i}=e;if(i!==void 0&&!t)throw new i0e.BaseError("`requireCanonical` can only be provided when `blockHash` is set.");return t?i?{blockHash:t,requireCanonical:i}:{blockHash:t}:typeof r=="bigint"?(0,o0e.numberToHex)(r):n??"latest"}});var Zm=g(fO=>{"use strict";Object.defineProperty(fO,"__esModule",{value:!0});fO.getTransactionCount=u0e;var a0e=Nu(),c0e=pt();async function u0e(e,{address:t,blockHash:r,blockNumber:n,blockTag:i="latest",requireCanonical:o}){let s=(0,a0e.formatBlockParameter)({blockHash:r,blockNumber:n,blockTag:i,requireCanonical:o}),a=await e.request({method:"eth_getTransactionCount",params:[t,s]},{dedupe:typeof n=="bigint"||r!==void 0});return(0,c0e.hexToNumber)(a)}});var Qm=g(pO=>{"use strict";Object.defineProperty(pO,"__esModule",{value:!0});pO.blobsToCommitments=f0e;var d0e=Je(),l0e=W();function f0e(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(o=>(0,d0e.hexToBytes)(o)):e.blobs,i=[];for(let o of n)i.push(Uint8Array.from(t.blobToKzgCommitment(o)));return r==="bytes"?i:i.map(o=>(0,l0e.bytesToHex)(o))}});var eg=g(mO=>{"use strict";Object.defineProperty(mO,"__esModule",{value:!0});mO.blobsToProofs=m0e;var J$=Je(),p0e=W();function m0e(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(s=>(0,J$.hexToBytes)(s)):e.blobs,i=typeof e.commitments[0]=="string"?e.commitments.map(s=>(0,J$.hexToBytes)(s)):e.commitments,o=[];for(let s=0;s<n.length;s++){let a=n[s],c=i[s];o.push(Uint8Array.from(t.computeBlobKzgProof(a,c)))}return r==="bytes"?o:o.map(s=>(0,p0e.bytesToHex)(s))}});var gO=g(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.sha224=uo.SHA224=uo.sha256=uo.SHA256=void 0;var Ub=f2();uo.SHA256=Ub.SHA256;uo.sha256=Ub.sha256;uo.SHA224=Ub.SHA224;uo.sha224=Ub.sha224});var Hb=g(hO=>{"use strict";Object.defineProperty(hO,"__esModule",{value:!0});hO.sha256=b0e;var g0e=gO(),h0e=Sr(),y0e=Je(),_0e=W();function b0e(e,t){let r=t||"hex",n=(0,g0e.sha256)((0,h0e.isHex)(e,{strict:!1})?(0,y0e.toBytes)(e):e);return r==="bytes"?n:(0,_0e.toHex)(n)}});var Fb=g(yO=>{"use strict";Object.defineProperty(yO,"__esModule",{value:!0});yO.commitmentToVersionedHash=v0e;var E0e=W(),w0e=Hb();function v0e(e){let{commitment:t,version:r=1}=e,n=e.to??(typeof t=="string"?"hex":"bytes"),i=(0,w0e.sha256)(t,"bytes");return i.set([r],0),n==="bytes"?i:(0,E0e.bytesToHex)(i)}});var $b=g(_O=>{"use strict";Object.defineProperty(_O,"__esModule",{value:!0});_O.commitmentsToVersionedHashes=A0e;var S0e=Fb();function A0e(e){let{commitments:t,version:r}=e,n=e.to??(typeof t[0]=="string"?"hex":"bytes"),i=[];for(let o of t)i.push((0,S0e.commitmentToVersionedHash)({commitment:o,to:n,version:r}));return i}});var G$=g(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.maxBytesPerTransaction=dn.bytesPerBlob=dn.fieldElementsPerBlob=dn.bytesPerFieldElement=void 0;var V$=6;dn.bytesPerFieldElement=32;dn.fieldElementsPerBlob=4096;dn.bytesPerBlob=dn.bytesPerFieldElement*dn.fieldElementsPerBlob;dn.maxBytesPerTransaction=dn.bytesPerBlob*V$-1-1*dn.fieldElementsPerBlob*V$});var bO=g(Jb=>{"use strict";Object.defineProperty(Jb,"__esModule",{value:!0});Jb.versionedHashVersionKzg=void 0;Jb.versionedHashVersionKzg=1});var AO=g(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.InvalidVersionedHashVersionError=lo.InvalidVersionedHashSizeError=lo.EmptyBlobError=lo.BlobSizeTooLargeError=void 0;var I0e=bO(),Vb=ye(),EO=class extends Vb.BaseError{constructor({maxSize:t,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${t} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}};lo.BlobSizeTooLargeError=EO;var wO=class extends Vb.BaseError{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}};lo.EmptyBlobError=wO;var vO=class extends Vb.BaseError{constructor({hash:t,size:r}){super(`Versioned hash "${t}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}};lo.InvalidVersionedHashSizeError=vO;var SO=class extends Vb.BaseError{constructor({hash:t,version:r}){super(`Versioned hash "${t}" version is invalid.`,{metaMessages:[`Expected: ${I0e.versionedHashVersionKzg}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}};lo.InvalidVersionedHashVersionError=SO});var PO=g(IO=>{"use strict";Object.defineProperty(IO,"__esModule",{value:!0});IO.toBlobs=R0e;var tg=G$(),K$=AO(),P0e=Pl(),T0e=ur(),x0e=Je(),O0e=W();function R0e(e){let t=e.to??(typeof e.data=="string"?"hex":"bytes"),r=typeof e.data=="string"?(0,x0e.hexToBytes)(e.data):e.data,n=(0,T0e.size)(r);if(!n)throw new K$.EmptyBlobError;if(n>tg.maxBytesPerTransaction)throw new K$.BlobSizeTooLargeError({maxSize:tg.maxBytesPerTransaction,size:n});let i=[],o=!0,s=0;for(;o;){let a=(0,P0e.createCursor)(new Uint8Array(tg.bytesPerBlob)),c=0;for(;c<tg.fieldElementsPerBlob;){let u=r.slice(s,s+(tg.bytesPerFieldElement-1));if(a.pushByte(0),a.pushBytes(u),u.length<31){a.pushByte(128),o=!1;break}c++,s+=31}i.push(a)}return t==="bytes"?i.map(a=>a.bytes):i.map(a=>(0,O0e.bytesToHex)(a.bytes))}});var rg=g(TO=>{"use strict";Object.defineProperty(TO,"__esModule",{value:!0});TO.toBlobSidecars=j0e;var C0e=Qm(),N0e=eg(),k0e=PO();function j0e(e){let{data:t,kzg:r,to:n}=e,i=e.blobs??(0,k0e.toBlobs)({data:t,to:n}),o=e.commitments??(0,C0e.blobsToCommitments)({blobs:i,kzg:r,to:n}),s=e.proofs??(0,N0e.blobsToProofs)({blobs:i,commitments:o,kzg:r,to:n}),a=[];for(let c=0;c<i.length;c++)a.push({blob:i[c],commitment:o[c],proof:s[c]});return a}});var ng=g(xO=>{"use strict";Object.defineProperty(xO,"__esModule",{value:!0});xO.getTransactionType=q0e;var M0e=Xt();function q0e(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u")return typeof e.accessList<"u"?"eip2930":"legacy";throw new M0e.InvalidSerializableTransactionError({transaction:e})}});var Hl=g(OO=>{"use strict";Object.defineProperty(OO,"__esModule",{value:!0});OO.getTransactionError=U0e;var D0e=Ti(),L0e=Xt(),B0e=Dl();function U0e(e,{docsPath:t,...r}){let n=(()=>{let i=(0,B0e.getNodeError)(e,r);return i instanceof D0e.UnknownNodeError?e:i})();return new L0e.TransactionExecutionError(n,{docsPath:t,...r})}});var ps=g(RO=>{"use strict";Object.defineProperty(RO,"__esModule",{value:!0});RO.getChainId=F0e;var H0e=pt();async function F0e(e){let t=await e.request({method:"eth_chainId"},{dedupe:!0});return(0,H0e.hexToNumber)(t)}});var Gb=g(CO=>{"use strict";Object.defineProperty(CO,"__esModule",{value:!0});CO.fillTransaction=Z0e;var W$=at(),$0e=Bl(),J0e=Xt(),V0e=Hl(),G0e=ls(),K0e=Cu(),W0e=Zn(),z$=Te(),z0e=Qn(),Y0e=fs(),X0e=ps();async function Z0e(e,t){let{account:r=e.account,accessList:n,authorizationList:i,chain:o=e.chain,blobVersionedHashes:s,blobs:a,data:c,gas:u,gasPrice:d,maxFeePerBlobGas:l,maxFeePerGas:m,maxPriorityFeePerGas:p,nonce:h,nonceManager:y,to:b,type:v,value:A,...E}=t,S=await(async()=>{if(!r||!y||typeof h<"u")return h;let C=(0,W$.parseAccount)(r),k=o?o.id:await(0,z$.getAction)(e,X0e.getChainId,"getChainId")({});return await y.consume({address:C.address,chainId:k,client:e})})();(0,z0e.assertRequest)(t);let I=o?.formatters?.transactionRequest?.format,x=(I||W0e.formatTransactionRequest)({...(0,G0e.extract)(E,{format:I}),account:r?(0,W$.parseAccount)(r):void 0,accessList:n,authorizationList:i,blobs:a,blobVersionedHashes:s,data:c,gas:u,gasPrice:d,maxFeePerBlobGas:l,maxFeePerGas:m,maxPriorityFeePerGas:p,nonce:S,to:b,type:v,value:A},"fillTransaction");try{let C=await e.request({method:"eth_fillTransaction",params:[x]}),N=(o?.formatters?.transaction?.format||K0e.formatTransaction)(C.tx);delete N.blockHash,delete N.blockNumber,delete N.r,delete N.s,delete N.transactionIndex,delete N.v,delete N.yParity,N.data=N.input;let M=typeof N.feePayerSignature<"u"&&N.feePayerSignature!==null;if(M&&typeof S<"u"&&N.nonce!==S)throw new J0e.FeePayerNonceMismatchError({filledNonce:N.nonce,requestedNonce:S});if(!M){N.gas&&(N.gas=t.gas??N.gas),N.gasPrice&&(N.gasPrice=t.gasPrice??N.gasPrice),N.maxFeePerBlobGas&&(N.maxFeePerBlobGas=t.maxFeePerBlobGas??N.maxFeePerBlobGas),N.maxFeePerGas&&(N.maxFeePerGas=t.maxFeePerGas??N.maxFeePerGas),N.maxPriorityFeePerGas&&(N.maxPriorityFeePerGas=t.maxPriorityFeePerGas??N.maxPriorityFeePerGas),typeof N.nonce<"u"&&(N.nonce=t.nonce??N.nonce);let j=await(async()=>{if(typeof o?.fees?.baseFeeMultiplier=="function"){let L=await(0,z$.getAction)(e,Y0e.getBlock,"getBlock")({});return o.fees.baseFeeMultiplier({block:L,client:e,request:t})}return o?.fees?.baseFeeMultiplier??1.2})();if(j<1)throw new $0e.BaseFeeScalarError;let U=10**(j.toString().split(".")[1]?.length??0),q=L=>L*BigInt(Math.round(j*U))/BigInt(U);N.maxFeePerGas&&!t.maxFeePerGas&&(N.maxFeePerGas=q(N.maxFeePerGas)),N.gasPrice&&!t.gasPrice&&(N.gasPrice=q(N.gasPrice))}return{raw:C.raw,transaction:{from:x.from,...N},...C.capabilities?{capabilities:C.capabilities}:{}}}catch(C){throw(0,V0e.getTransactionError)(C,{...t,chain:e.chain})}}});var Fl=g(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.supportsFillTransaction=Jr.eip1559NetworkCache=Jr.defaultParameters=void 0;Jr.prepareTransactionRequest=f_e;var Y$=at(),X$=dO(),Q0e=Kb(),e_e=fs(),t_e=Zm(),Z$=Bl(),r_e=Xt(),n_e=Qm(),i_e=eg(),o_e=$b(),s_e=rg(),ig=Te(),a_e=Ta(),c_e=Qn(),u_e=ng(),d_e=Gb(),l_e=ps();Jr.defaultParameters=["blobVersionedHashes","chainId","fees","gas","nonce","type"];Jr.eip1559NetworkCache=new Map;Jr.supportsFillTransaction=new a_e.LruMap(128);async function f_e(e,t){let r=t;r.account??=e.account,r.parameters??=Jr.defaultParameters;let{account:n,chain:i=e.chain,nonceManager:o,parameters:s}=r,a=(()=>{if(typeof i?.prepareTransactionRequest=="function")return{fn:i.prepareTransactionRequest,runAt:["beforeFillTransaction"]};if(Array.isArray(i?.prepareTransactionRequest))return{fn:i.prepareTransactionRequest[0],runAt:i.prepareTransactionRequest[1].runAt}})(),c;async function u(){return c||(typeof r.chainId<"u"?r.chainId:i?i.id:(c=await(0,ig.getAction)(e,l_e.getChainId,"getChainId")({}),c))}let d=n&&(0,Y$.parseAccount)(n),l=r.nonce;if(a?.fn&&a.runAt?.includes("beforeFillTransaction")){r=await a.fn({...r,chain:i},{client:e,phase:"beforeFillTransaction"}),l??=r.nonce;let S=r.account??r.from;d=S?(0,Y$.parseAccount)(S):void 0}if(s.includes("nonce")&&typeof l>"u"&&d&&o){let S=await u();l=await o.consume({address:d.address,chainId:S,client:e})}let p=((s.includes("blobVersionedHashes")||s.includes("sidecars"))&&r.kzg&&r.blobs?!1:s.length>0&&"feePayer"in r&&r.feePayer&&!("feePayerSignature"in r&&r.feePayerSignature)?!0:Jr.supportsFillTransaction.get(e.uid)===!1||!["fees","gas"].some(I=>s.includes(I))?!1:!!(s.includes("chainId")&&typeof r.chainId!="number"||s.includes("nonce")&&typeof l!="number"||s.includes("fees")&&typeof r.gasPrice!="bigint"&&(typeof r.maxFeePerGas!="bigint"||typeof r.maxPriorityFeePerGas!="bigint")||s.includes("gas")&&typeof r.gas!="bigint"))?await(0,ig.getAction)(e,d_e.fillTransaction,"fillTransaction")({...r,nonce:l}).then(S=>{let{chainId:I,from:T,gas:x,gasPrice:C,nonce:k,maxFeePerBlobGas:N,maxFeePerGas:M,maxPriorityFeePerGas:j,type:D,...U}=S.transaction,q="feeToken"in U?U.feeToken:void 0,L="feePayerSignature"in U&&U.feePayerSignature!==null&&typeof U.feePayerSignature<"u",V=typeof q<"u"&&q!==null&&(!("feeToken"in r)||L);return Jr.supportsFillTransaction.set(e.uid,!0),{...r,...T?{from:T}:{},...D&&!r.type?{type:D}:{},...typeof I<"u"?{chainId:I}:{},...typeof x<"u"?{gas:x}:{},...typeof C<"u"?{gasPrice:C}:{},...typeof k<"u"?{nonce:k}:{},...typeof N<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerBlobGas:N}:{},...typeof M<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerGas:M}:{},...typeof j<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxPriorityFeePerGas:j}:{},..."nonceKey"in U&&typeof U.nonceKey<"u"?{nonceKey:U.nonceKey}:{},..."keyAuthorization"in U&&typeof U.keyAuthorization<"u"&&U.keyAuthorization!==null&&!("keyAuthorization"in r)?{keyAuthorization:U.keyAuthorization}:{},..."feePayerSignature"in U&&typeof U.feePayerSignature<"u"&&U.feePayerSignature!==null?{feePayerSignature:U.feePayerSignature}:{},...V?{feeToken:q}:{},...S.capabilities?{_capabilities:S.capabilities}:{}}}).catch(S=>{let I=S;if(I.name!=="TransactionExecutionError")return r;if(I.walk?.(k=>k instanceof r_e.FeePayerNonceMismatchError)||I.walk?.(k=>k.name==="ExecutionRevertedError"))throw S;return I.walk?.(k=>{let N=k;return N.name==="MethodNotFoundRpcError"||N.name==="MethodNotSupportedRpcError"||N.message?.includes("eth_fillTransaction is not available")})&&Jr.supportsFillTransaction.set(e.uid,!1),r}):r;l??=p.nonce,r={...p,...d?{from:d?.address}:{},...typeof l<"u"?{nonce:l}:{}};let{blobs:h,gas:y,kzg:b,type:v}=r;a?.fn&&a.runAt?.includes("beforeFillParameters")&&(r=await a.fn({...r,chain:i},{client:e,phase:"beforeFillParameters"}));let A;async function E(){return A||(A=await(0,ig.getAction)(e,e_e.getBlock,"getBlock")({blockTag:"latest"}),A)}if(s.includes("nonce")&&typeof l>"u"&&d&&!o&&(r.nonce=await(0,ig.getAction)(e,t_e.getTransactionCount,"getTransactionCount")({address:d.address,blockTag:"pending"})),(s.includes("blobVersionedHashes")||s.includes("sidecars"))&&h&&b){let S=(0,n_e.blobsToCommitments)({blobs:h,kzg:b});if(s.includes("blobVersionedHashes")){let I=(0,o_e.commitmentsToVersionedHashes)({commitments:S,to:"hex"});r.blobVersionedHashes=I}if(s.includes("sidecars")){let I=(0,i_e.blobsToProofs)({blobs:h,commitments:S,kzg:b}),T=(0,s_e.toBlobSidecars)({blobs:h,commitments:S,proofs:I,to:"hex"});r.sidecars=T}}if(s.includes("chainId")&&(r.chainId=await u()),(s.includes("fees")||s.includes("type"))&&typeof v>"u")try{r.type=(0,u_e.getTransactionType)(r)}catch{let S=Jr.eip1559NetworkCache.get(e.uid);typeof S>"u"&&(S=typeof(await E())?.baseFeePerGas=="bigint",Jr.eip1559NetworkCache.set(e.uid,S)),r.type=S?"eip1559":"legacy"}if(s.includes("fees"))if(r.type!=="legacy"&&r.type!=="eip2930"){if(typeof r.maxFeePerGas>"u"||typeof r.maxPriorityFeePerGas>"u"){let S=await E(),{maxFeePerGas:I,maxPriorityFeePerGas:T}=await(0,X$.internal_estimateFeesPerGas)(e,{block:S,chain:i,request:r});if(typeof r.maxPriorityFeePerGas>"u"&&r.maxFeePerGas&&r.maxFeePerGas<T)throw new Z$.MaxFeePerGasTooLowError({maxPriorityFeePerGas:T});r.maxPriorityFeePerGas=T,r.maxFeePerGas=I}}else{if(typeof r.maxFeePerGas<"u"||typeof r.maxPriorityFeePerGas<"u")throw new Z$.Eip1559FeesNotSupportedError;if(typeof r.gasPrice>"u"){let S=await E(),{gasPrice:I}=await(0,X$.internal_estimateFeesPerGas)(e,{block:S,chain:i,request:r,type:"legacy"});r.gasPrice=I}}return s.includes("gas")&&typeof y>"u"&&(r.gas=await(0,ig.getAction)(e,Q0e.estimateGas,"estimateGas")({...r,account:d,prepare:d?.type==="local"?[]:["blobVersionedHashes"]})),a?.fn&&a.runAt?.includes("afterFillParameters")&&(r=await a.fn({...r,chain:i},{client:e,phase:"afterFillParameters"})),(0,c_e.assertRequest)(r),delete r.parameters,r}});var Kb=g(NO=>{"use strict";Object.defineProperty(NO,"__esModule",{value:!0});NO.estimateGas=S_e;var p_e=at(),m_e=ye(),g_e=ql(),h_e=W(),y_e=Y2(),__e=ls(),b_e=Zn(),E_e=jb(),w_e=Qn(),v_e=Fl();async function S_e(e,t){let{account:r=e.account,prepare:n=!0}=t,i=r?(0,p_e.parseAccount)(r):void 0,o=(()=>{if(Array.isArray(n))return n;if(i?.type!=="local")return["blobVersionedHashes"]})();try{let s=await(async()=>{if(t.to)return t.to;if(t.authorizationList&&t.authorizationList.length>0)return await(0,g_e.recoverAuthorizationAddress)({authorization:t.authorizationList[0]}).catch(()=>{throw new m_e.BaseError("`to` is required. Could not infer from `authorizationList`")})})(),{accessList:a,authorizationList:c,blobs:u,blobVersionedHashes:d,blockNumber:l,blockTag:m,data:p,gas:h,gasPrice:y,maxFeePerBlobGas:b,maxFeePerGas:v,maxPriorityFeePerGas:A,nonce:E,value:S,stateOverride:I,...T}=n?await(0,v_e.prepareTransactionRequest)(e,{...t,parameters:o,to:s}):t;if(h&&t.gas!==h)return h;let C=(typeof l=="bigint"?(0,h_e.numberToHex)(l):void 0)||m,k=(0,E_e.serializeStateOverride)(I);(0,w_e.assertRequest)(t);let N=e.chain?.formatters?.transactionRequest?.format,j=(N||b_e.formatTransactionRequest)({...(0,__e.extract)(T,{format:N}),account:i,accessList:a,authorizationList:c,blobs:u,blobVersionedHashes:d,data:p,gasPrice:y,maxFeePerBlobGas:b,maxFeePerGas:v,maxPriorityFeePerGas:A,nonce:E,to:s,value:S},"estimateGas");return BigInt(await e.request({method:"eth_estimateGas",params:k?[j,C??e.experimental_blockTag??"latest",k]:C?[j,C]:[j]}))}catch(s){throw(0,y_e.getEstimateGasError)(s,{...t,account:i,chain:e.chain})}}});var og=g(kO=>{"use strict";Object.defineProperty(kO,"__esModule",{value:!0});kO.estimateContractGas=O_e;var A_e=at(),I_e=Tr(),P_e=as(),T_e=Te(),x_e=Kb();async function O_e(e,t){let{abi:r,address:n,args:i,functionName:o,dataSuffix:s=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=(0,I_e.encodeFunctionData)({abi:r,args:i,functionName:o});try{return await(0,T_e.getAction)(e,x_e.estimateGas,"estimateGas")({data:`${c}${s?s.replace("0x",""):""}`,to:n,...a})}catch(u){let d=a.account?(0,A_e.parseAccount)(a.account):void 0;throw(0,P_e.getContractError)(u,{abi:r,address:n,args:i,docsPath:"/docs/contract/estimateContractGas",functionName:o,sender:d?.address})}}});var ln=g(jO=>{"use strict";Object.defineProperty(jO,"__esModule",{value:!0});jO.isAddressEqual=R_e;var Q$=Wn(),eJ=Pr();function R_e(e,t){if(!(0,eJ.isAddress)(e,{strict:!1}))throw new Q$.InvalidAddressError({address:e});if(!(0,eJ.isAddress)(t,{strict:!1}))throw new Q$.InvalidAddressError({address:t});return e.toLowerCase()===t.toLowerCase()}});var xi=g(MO=>{"use strict";Object.defineProperty(MO,"__esModule",{value:!0});MO.formatLog=C_e;function C_e(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,blockTimestamp:e.blockTimestamp?BigInt(e.blockTimestamp):e.blockTimestamp===null?null:void 0,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}});var Jl=g(qO=>{"use strict";Object.defineProperty(qO,"__esModule",{value:!0});qO.decodeEventLog=q_e;var $l=ft(),N_e=gx(),k_e=ur(),j_e=wu(),rJ=os(),M_e=io(),tJ="/docs/contract/decodeEventLog";function q_e(e){let{abi:t,data:r,strict:n,topics:i}=e,o=n??!0,[s,...a]=i;if(!s)throw new $l.AbiEventSignatureEmptyTopicsError({docsPath:tJ});let c=t.find(v=>v.type==="event"&&s===(0,j_e.toEventSelector)((0,M_e.formatAbiItem)(v)));if(!(c&&"name"in c)||c.type!=="event")throw new $l.AbiEventSignatureNotFoundError(s,{docsPath:tJ});let{name:u,inputs:d}=c,l=d?.some(v=>!("name"in v&&v.name)),m=l?[]:{},p=d.map((v,A)=>[v,A]).filter(([v])=>"indexed"in v&&v.indexed),h=[];for(let v=0;v<p.length;v++){let[A,E]=p[v],S=a[v];if(!S){if(o)throw new $l.DecodeLogTopicsMismatch({abiItem:c,param:A});h.push([A,E]);continue}m[l?E:A.name||E]=D_e({param:A,value:S})}let y=d.filter(v=>!("indexed"in v&&v.indexed)),b=o?y:[...h.map(([v])=>v),...y];if(b.length>0){if(r&&r!=="0x")try{let v=(0,rJ.decodeAbiParameters)(b,r);if(v){let A=0;if(!o)for(let[E,S]of h)m[l?S:E.name||S]=v[A++];if(l)for(let E=0;E<d.length;E++)m[E]===void 0&&A<v.length&&(m[E]=v[A++]);else for(let E=0;E<y.length;E++)m[y[E].name]=v[A++]}}catch(v){if(o)throw v instanceof $l.AbiDecodingDataSizeTooSmallError||v instanceof N_e.PositionOutOfBoundsError?new $l.DecodeLogDataMismatch({abiItem:c,data:r,params:b,size:(0,k_e.size)(r)}):v}else if(o)throw new $l.DecodeLogDataMismatch({abiItem:c,data:"0x",params:b,size:0})}return{eventName:u,args:Object.values(m).length>0?m:void 0}}function D_e({param:e,value:t}){return e.type==="string"||e.type==="bytes"||e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/)?t:((0,rJ.decodeAbiParameters)([e],t)||[])[0]}});var Ya=g(DO=>{"use strict";Object.defineProperty(DO,"__esModule",{value:!0});DO.parseEventLogs=$_e;var L_e=ln(),B_e=Je(),U_e=xi(),H_e=Hr(),F_e=wu(),nJ=Jl();function $_e(e){let{abi:t,args:r,logs:n,strict:i=!0}=e,o=(()=>{if(e.eventName)return Array.isArray(e.eventName)?e.eventName:[e.eventName]})(),s=t.filter(a=>a.type==="event").map(a=>({abi:a,selector:(0,F_e.toEventSelector)(a)}));return n.map(a=>{let c=typeof a.blockNumber=="string"?(0,U_e.formatLog)(a):a,u=s.filter(m=>c.topics[0]===m.selector);if(u.length===0)return null;let d,l;for(let m of u)try{d=(0,nJ.decodeEventLog)({...c,abi:[m.abi],strict:!0}),l=m;break}catch{}if(!d&&!i){l=u[0];try{d=(0,nJ.decodeEventLog)({data:c.data,topics:c.topics,abi:[l.abi],strict:!1})}catch{let m=l.abi.inputs?.some(p=>!("name"in p&&p.name));return{...c,args:m?[]:{},eventName:l.abi.name}}}return!d||!l||o&&!o.includes(d.eventName)||!J_e({args:d.args,inputs:l.abi.inputs,matchArgs:r})?null:{...d,...c}}).filter(Boolean)}function J_e(e){let{args:t,inputs:r,matchArgs:n}=e;if(!n)return!0;if(!t)return!1;function i(o,s,a){try{return o.type==="address"?(0,L_e.isAddressEqual)(s,a):o.type==="string"||o.type==="bytes"?(0,H_e.keccak256)((0,B_e.toBytes)(s))===a:s===a}catch{return!1}}return Array.isArray(t)&&Array.isArray(n)?n.every((o,s)=>{if(o==null)return!0;let a=r[s];return a?(Array.isArray(o)?o:[o]).some(u=>i(a,u,t[s])):!1}):typeof t=="object"&&!Array.isArray(t)&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).every(([o,s])=>{if(s==null)return!0;let a=r.find(u=>u.name===o);return a?(Array.isArray(s)?s:[s]).some(u=>i(a,u,t[o])):!1}):!1}});var Wb=g(LO=>{"use strict";Object.defineProperty(LO,"__esModule",{value:!0});LO.getLogs=W_e;var V_e=Ca(),G_e=Ya(),iJ=W(),K_e=xi();async function W_e(e,{address:t,blockHash:r,fromBlock:n,toBlock:i,event:o,events:s,args:a,strict:c}={}){let u=c??!1,d=s??(o?[o]:void 0),l=[];d&&(l=[d.flatMap(y=>(0,V_e.encodeEventTopics)({abi:[y],eventName:y.name,args:s?void 0:a}))],o&&(l=l[0]));let m;r?m=await e.request({method:"eth_getLogs",params:[{address:t,topics:l,blockHash:r}]}):m=await e.request({method:"eth_getLogs",params:[{address:t,topics:l,fromBlock:typeof n=="bigint"?(0,iJ.numberToHex)(n):n,toBlock:typeof i=="bigint"?(0,iJ.numberToHex)(i):i}]});let p=m.map(h=>(0,K_e.formatLog)(h));return d?(0,G_e.parseEventLogs)({abi:d,args:a,logs:p,strict:u}):p}});var zb=g(BO=>{"use strict";Object.defineProperty(BO,"__esModule",{value:!0});BO.getContractEvents=Z_e;var z_e=so(),Y_e=Te(),X_e=Wb();async function Z_e(e,t){let{abi:r,address:n,args:i,blockHash:o,eventName:s,fromBlock:a,toBlock:c,strict:u}=t,d=s?(0,z_e.getAbiItem)({abi:r,name:s}):void 0,l=d?void 0:r.filter(m=>m.type==="event");return(0,Y_e.getAction)(e,X_e.getLogs,"getLogs")({address:n,args:i,blockHash:o,event:d,events:l,fromBlock:a,toBlock:c,strict:u})}});var ei=g(FO=>{"use strict";Object.defineProperty(FO,"__esModule",{value:!0});FO.decodeFunctionResult=tbe;var UO=ft(),Q_e=os(),ebe=so(),HO="/docs/contract/decodeFunctionResult";function tbe(e){let{abi:t,args:r,functionName:n,data:i}=e,o=t[0];if(n){let a=(0,ebe.getAbiItem)({abi:t,args:r,name:n});if(!a)throw new UO.AbiFunctionNotFoundError(n,{docsPath:HO});o=a}if(o.type!=="function")throw new UO.AbiFunctionNotFoundError(void 0,{docsPath:HO});if(!o.outputs)throw new UO.AbiFunctionOutputsNotFoundError(o.name,{docsPath:HO});let s=(0,Q_e.decodeAbiParameters)(o.outputs,i);if(s&&s.length>1)return s;if(s&&s.length===1)return s[0]}});var oJ=g(Yb=>{"use strict";Object.defineProperty(Yb,"__esModule",{value:!0});Yb.version=void 0;Yb.version="0.1.1"});var $O=g(sg=>{"use strict";Object.defineProperty(sg,"__esModule",{value:!0});sg.getUrl=nbe;sg.getVersion=ibe;sg.prettyPrint=obe;var rbe=oJ();function nbe(e){return e}function ibe(){return rbe.version}function obe(e){if(!e)return"";let t=Object.entries(e).map(([n,i])=>i===void 0||i===!1?null:[n,i]).filter(Boolean),r=t.reduce((n,[i])=>Math.max(n,i.length),0);return t.map(([n,i])=>` ${`${n}:`.padEnd(r+1)} ${i}`).join(`
49
+ `)}});var Vr=g(Xb=>{"use strict";Object.defineProperty(Xb,"__esModule",{value:!0});Xb.BaseError=void 0;var sbe=$O(),Vl=class e extends Error{static setStaticOptions(t){e.prototype.docsOrigin=t.docsOrigin,e.prototype.showVersion=t.showVersion,e.prototype.version=t.version}constructor(t,r={}){let n=(()=>{if(r.cause instanceof e){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:r.cause?.message?r.cause.message:r.details})(),i=r.cause instanceof e&&r.cause.docsPath||r.docsPath,o=r.docsOrigin??e.prototype.docsOrigin,s=`${o}${i??""}`,a=!!(r.version??e.prototype.showVersion),c=r.version??e.prototype.version,u=[t||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||i||a?["",n?`Details: ${n}`:void 0,i?`See: ${s}`:void 0,a?`Version: ${c}`:void 0]:[]].filter(d=>typeof d=="string").join(`
50
+ `);super(u,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsOrigin",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"showVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.cause=r.cause,this.details=n,this.docs=s,this.docsOrigin=o,this.docsPath=i,this.shortMessage=t,this.showVersion=a,this.version=c}walk(t){return sJ(this,t)}};Xb.BaseError=Vl;Object.defineProperty(Vl,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:"https://oxlib.sh",showVersion:!1,version:`ox@${(0,sbe.getVersion)()}`}});Vl.setStaticOptions(Vl.defaultStaticOptions);function sJ(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?sJ(e.cause,t):t?null:e}});var JO=g($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.charCodeMap=void 0;$t.assertSize=abe;$t.assertStartOffset=cbe;$t.assertEndOffset=ube;$t.charCodeToBase16=dbe;$t.pad=lbe;$t.trim=fbe;var fo=ti();function abe(e,t){if(fo.size(e)>t)throw new fo.SizeOverflowError({givenSize:fo.size(e),maxSize:t})}function cbe(e,t){if(typeof t=="number"&&t>0&&t>fo.size(e)-1)throw new fo.SliceOffsetOutOfBoundsError({offset:t,position:"start",size:fo.size(e)})}function ube(e,t,r){if(typeof t=="number"&&typeof r=="number"&&fo.size(e)!==r-t)throw new fo.SliceOffsetOutOfBoundsError({offset:r,position:"end",size:fo.size(e)})}$t.charCodeMap={zero:48,nine:57,A:65,F:70,a:97,f:102};function dbe(e){if(e>=$t.charCodeMap.zero&&e<=$t.charCodeMap.nine)return e-$t.charCodeMap.zero;if(e>=$t.charCodeMap.A&&e<=$t.charCodeMap.F)return e-($t.charCodeMap.A-10);if(e>=$t.charCodeMap.a&&e<=$t.charCodeMap.f)return e-($t.charCodeMap.a-10)}function lbe(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;if(e.length>n)throw new fo.SizeExceedsPaddingSizeError({size:e.length,targetSize:n,type:"Bytes"});let i=new Uint8Array(n);for(let o=0;o<n;o++){let s=r==="right";i[s?o:n-o-1]=e[s?o:e.length-o-1]}return i}function fbe(e,t={}){let{dir:r="left"}=t,n=e,i=0;for(let o=0;o<n.length-1&&n[r==="left"?o:n.length-o-1].toString()==="0";o++)i++;return n=r==="left"?n.slice(i):n.slice(0,n.length-i),n}});var VO=g(ku=>{"use strict";Object.defineProperty(ku,"__esModule",{value:!0});ku.assertSize=pbe;ku.assertStartOffset=mbe;ku.assertEndOffset=gbe;ku.pad=hbe;ku.trim=ybe;var po=Jt();function pbe(e,t){if(po.size(e)>t)throw new po.SizeOverflowError({givenSize:po.size(e),maxSize:t})}function mbe(e,t){if(typeof t=="number"&&t>0&&t>po.size(e)-1)throw new po.SliceOffsetOutOfBoundsError({offset:t,position:"start",size:po.size(e)})}function gbe(e,t,r){if(typeof t=="number"&&typeof r=="number"&&po.size(e)!==r-t)throw new po.SliceOffsetOutOfBoundsError({offset:r,position:"end",size:po.size(e)})}function hbe(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;let i=e.replace("0x","");if(i.length>n*2)throw new po.SizeExceedsPaddingSizeError({size:Math.ceil(i.length/2),targetSize:n,type:"Hex"});return`0x${i[r==="right"?"padEnd":"padStart"](n*2,"0")}`}function ybe(e,t={}){let{dir:r="left"}=t,n=e.replace("0x",""),i=0;for(let o=0;o<n.length-1&&n[r==="left"?o:n.length-o-1].toString()==="0";o++)i++;return n=r==="left"?n.slice(i):n.slice(0,n.length-i),n==="0"?"0x":r==="right"&&n.length%2===1?`0x${n}0`:`0x${n}`}});var cg=g(ag=>{"use strict";Object.defineProperty(ag,"__esModule",{value:!0});ag.canonicalize=KO;ag.parse=_be;ag.stringify=bbe;var GO="#__bigint";function KO(e){if(e===null||typeof e=="boolean"||typeof e=="string")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError("Cannot canonicalize non-finite number");return Object.is(e,-0)?"0":JSON.stringify(e)}if(typeof e=="bigint")throw new TypeError("Cannot canonicalize bigint");if(Array.isArray(e))return`[${e.map(t=>KO(t)).join(",")}]`;if(typeof e=="object")return`{${Object.keys(e).sort().reduce((r,n)=>{let i=e[n];return i!==void 0&&r.push(`${JSON.stringify(n)}:${KO(i)}`),r},[]).join(",")}}`}function _be(e,t){return JSON.parse(e,(r,n)=>{let i=n;return typeof i=="string"&&i.endsWith(GO)?BigInt(i.slice(0,-GO.length)):typeof t=="function"?t(r,i):i})}function bbe(e,t,r){return JSON.stringify(e,(n,i)=>typeof t=="function"?t(n,i):typeof i=="bigint"?i.toString()+GO:i,r)}});var ti=g(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.SizeExceedsPaddingSizeError=Oe.SliceOffsetOutOfBoundsError=Oe.SizeOverflowError=Oe.InvalidBytesTypeError=Oe.InvalidBytesBooleanError=void 0;Oe.assert=aJ;Oe.concat=Ibe;Oe.from=Pbe;Oe.fromArray=cJ;Oe.fromBoolean=Tbe;Oe.fromHex=XO;Oe.fromNumber=xbe;Oe.fromString=Obe;Oe.isEqual=Rbe;Oe.padLeft=uJ;Oe.padRight=dJ;Oe.random=Cbe;Oe.size=Nbe;Oe.slice=kbe;Oe.toBigInt=jbe;Oe.toBoolean=Mbe;Oe.toHex=qbe;Oe.toNumber=Dbe;Oe.toString=Lbe;Oe.trimLeft=lJ;Oe.trimRight=fJ;Oe.validate=Bbe;var Ebe=Fa(),Gl=Vr(),Mu=Jt(),fn=JO(),wbe=VO(),vbe=cg(),Sbe=new TextDecoder,Abe=new TextEncoder;function aJ(e){if(!(e instanceof Uint8Array)){if(!e)throw new ju(e);if(typeof e!="object")throw new ju(e);if(!("BYTES_PER_ELEMENT"in e))throw new ju(e);if(e.BYTES_PER_ELEMENT!==1||e.constructor.name!=="Uint8Array")throw new ju(e)}}function Ibe(...e){let t=0;for(let n of e)t+=n.length;let r=new Uint8Array(t);for(let n=0,i=0;n<e.length;n++){let o=e[n];r.set(o,i),i+=o.length}return r}function Pbe(e){return e instanceof Uint8Array?e:typeof e=="string"?XO(e):cJ(e)}function cJ(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function Tbe(e,t={}){let{size:r}=t,n=new Uint8Array(1);return n[0]=Number(e),typeof r=="number"?(fn.assertSize(n,r),uJ(n,r)):n}function XO(e,t={}){let{size:r}=t,n=e;r&&(wbe.assertSize(e,r),n=Mu.padRight(e,r));let i=n.slice(2);i.length%2&&(i=`0${i}`);let o=i.length/2,s=new Uint8Array(o);for(let a=0,c=0;a<o;a++){let u=fn.charCodeToBase16(i.charCodeAt(c++)),d=fn.charCodeToBase16(i.charCodeAt(c++));if(u===void 0||d===void 0)throw new Gl.BaseError(`Invalid byte sequence ("${i[c-2]}${i[c-1]}" in "${i}").`);s[a]=u<<4|d}return s}function xbe(e,t){let r=Mu.fromNumber(e,t);return XO(r)}function Obe(e,t={}){let{size:r}=t,n=Abe.encode(e);return typeof r=="number"?(fn.assertSize(n,r),dJ(n,r)):n}function Rbe(e,t){return(0,Ebe.equalBytes)(e,t)}function uJ(e,t){return fn.pad(e,{dir:"left",size:t})}function dJ(e,t){return fn.pad(e,{dir:"right",size:t})}function Cbe(e){return crypto.getRandomValues(new Uint8Array(e))}function Nbe(e){return e.length}function kbe(e,t,r,n={}){let{strict:i}=n;fn.assertStartOffset(e,t);let o=e.slice(t,r);return i&&fn.assertEndOffset(o,t,r),o}function jbe(e,t={}){let{size:r}=t;typeof r<"u"&&fn.assertSize(e,r);let n=Mu.fromBytes(e,t);return Mu.toBigInt(n,t)}function Mbe(e,t={}){let{size:r}=t,n=e;if(typeof r<"u"&&(fn.assertSize(n,r),n=lJ(n)),n.length>1||n[0]>1)throw new Zb(n);return!!n[0]}function qbe(e,t={}){return Mu.fromBytes(e,t)}function Dbe(e,t={}){let{size:r}=t;typeof r<"u"&&fn.assertSize(e,r);let n=Mu.fromBytes(e,t);return Mu.toNumber(n,t)}function Lbe(e,t={}){let{size:r}=t,n=e;return typeof r<"u"&&(fn.assertSize(n,r),n=fJ(n)),Sbe.decode(n)}function lJ(e){return fn.trim(e,{dir:"left"})}function fJ(e){return fn.trim(e,{dir:"right"})}function Bbe(e){try{return aJ(e),!0}catch{return!1}}var Zb=class extends Gl.BaseError{constructor(t){super(`Bytes value \`${t}\` is not a valid boolean.`,{metaMessages:["The bytes array must contain a single byte of either a `0` or `1` value."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesBooleanError"})}};Oe.InvalidBytesBooleanError=Zb;var ju=class extends Gl.BaseError{constructor(t){super(`Value \`${typeof t=="object"?vbe.stringify(t):t}\` of type \`${typeof t}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}};Oe.InvalidBytesTypeError=ju;var WO=class extends Gl.BaseError{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}};Oe.SizeOverflowError=WO;var zO=class extends Gl.BaseError{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${t}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SliceOffsetOutOfBoundsError"})}};Oe.SliceOffsetOutOfBoundsError=zO;var YO=class extends Gl.BaseError{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}};Oe.SizeExceedsPaddingSizeError=YO});var Jt=g(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.SizeExceedsPaddingSizeError=Se.SliceOffsetOutOfBoundsError=Se.SizeOverflowError=Se.InvalidLengthError=Se.InvalidHexValueError=Se.InvalidHexTypeError=Se.InvalidHexBooleanError=Se.IntegerOutOfRangeError=void 0;Se.assert=pJ;Se.concat=Vbe;Se.from=Gbe;Se.fromBoolean=Kbe;Se.fromBytes=ug;Se.fromNumber=Wbe;Se.fromString=zbe;Se.isEqual=Ybe;Se.padLeft=r6;Se.padRight=mJ;Se.random=Xbe;Se.slice=Zbe;Se.size=Qbe;Se.trimLeft=gJ;Se.trimRight=eEe;Se.toBigInt=hJ;Se.toBoolean=tEe;Se.toBytes=rEe;Se.toNumber=nEe;Se.toString=iEe;Se.validate=oEe;var Ube=Fa(),Kl=ti(),Xa=Vr(),Hbe=JO(),mo=VO(),Fbe=cg(),$be=new TextEncoder,Jbe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function pJ(e,t={}){let{strict:r=!1}=t;if(!e)throw new dg(e);if(typeof e!="string")throw new dg(e);if(r&&!/^0x[0-9a-fA-F]*$/.test(e))throw new lg(e);if(!e.startsWith("0x"))throw new lg(e)}function Vbe(...e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function Gbe(e){return e instanceof Uint8Array?ug(e):Array.isArray(e)?ug(new Uint8Array(e)):e}function Kbe(e,t={}){let r=`0x${Number(e)}`;return typeof t.size=="number"?(mo.assertSize(r,t.size),r6(r,t.size)):r}function ug(e,t={}){let r="";for(let i=0;i<e.length;i++)r+=Jbe[e[i]];let n=`0x${r}`;return typeof t.size=="number"?(mo.assertSize(n,t.size),mJ(n,t.size)):n}function Wbe(e,t={}){let{signed:r,size:n}=t,i=BigInt(e),o;n?r?o=(1n<<BigInt(n)*8n-1n)-1n:o=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(o=BigInt(Number.MAX_SAFE_INTEGER));let s=typeof o=="bigint"&&r?-o-1n:0;if(o&&i>o||i<s){let u=typeof e=="bigint"?"n":"";throw new Qb({max:o?`${o}${u}`:void 0,min:`${s}${u}`,signed:r,size:n,value:`${e}${u}`})}let c=`0x${(r&&i<0?BigInt.asUintN(n*8,BigInt(i)):i).toString(16)}`;return n?r6(c,n):c}function zbe(e,t={}){return ug($be.encode(e),t)}function Ybe(e,t){return(0,Ube.equalBytes)(Kl.fromHex(e),Kl.fromHex(t))}function r6(e,t){return mo.pad(e,{dir:"left",size:t})}function mJ(e,t){return mo.pad(e,{dir:"right",size:t})}function Xbe(e){return ug(Kl.random(e))}function Zbe(e,t,r,n={}){let{strict:i}=n;mo.assertStartOffset(e,t);let o=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;return i&&mo.assertEndOffset(o,t,r),o}function Qbe(e){return Math.ceil((e.length-2)/2)}function gJ(e){return mo.trim(e,{dir:"left"})}function eEe(e){return mo.trim(e,{dir:"right"})}function hJ(e,t={}){let{signed:r}=t;t.size&&mo.assertSize(e,t.size);let n=BigInt(e);if(!r)return n;let i=(e.length-2)/2,o=(1n<<BigInt(i)*8n)-1n,s=o>>1n;return n<=s?n:n-o-1n}function tEe(e,t={}){t.size&&mo.assertSize(e,t.size);let r=gJ(e);if(r==="0x")return!1;if(r==="0x1")return!0;throw new eE(e)}function rEe(e,t={}){return Kl.fromHex(e,t)}function nEe(e,t={}){let{signed:r,size:n}=t;return Number(!r&&!n?e:hJ(e,t))}function iEe(e,t={}){let{size:r}=t,n=Kl.fromHex(e);return r&&(Hbe.assertSize(n,r),n=Kl.trimRight(n)),new TextDecoder().decode(n)}function oEe(e,t={}){let{strict:r=!1}=t;try{return pJ(e,{strict:r}),!0}catch{return!1}}var Qb=class extends Xa.BaseError{constructor({max:t,min:r,signed:n,size:i,value:o}){super(`Number \`${o}\` is not in safe${i?` ${i*8}-bit`:""}${n?" signed":" unsigned"} integer range ${t?`(\`${r}\` to \`${t}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}};Se.IntegerOutOfRangeError=Qb;var eE=class extends Xa.BaseError{constructor(t){super(`Hex value \`"${t}"\` is not a valid boolean.`,{metaMessages:['The hex value must be `"0x0"` (false) or `"0x1"` (true).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexBooleanError"})}};Se.InvalidHexBooleanError=eE;var dg=class extends Xa.BaseError{constructor(t){super(`Value \`${typeof t=="object"?Fbe.stringify(t):t}\` of type \`${typeof t}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}};Se.InvalidHexTypeError=dg;var lg=class extends Xa.BaseError{constructor(t){super(`Value \`${t}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}};Se.InvalidHexValueError=lg;var ZO=class extends Xa.BaseError{constructor(t){super(`Hex value \`"${t}"\` is an odd length (${t.length-2} nibbles).`,{metaMessages:["It must be an even length."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidLengthError"})}};Se.InvalidLengthError=ZO;var QO=class extends Xa.BaseError{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}};Se.SizeOverflowError=QO;var e6=class extends Xa.BaseError{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${t}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}};Se.SliceOffsetOutOfBoundsError=e6;var t6=class extends Xa.BaseError{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}};Se.SizeExceedsPaddingSizeError=t6});var yJ=g(tE=>{"use strict";Object.defineProperty(tE,"__esModule",{value:!0});tE.fromRpc=sEe;tE.toRpc=aEe;var n6=Jt();function sEe(e){return{...e,amount:BigInt(e.amount),index:Number(e.index),validatorIndex:Number(e.validatorIndex)}}function aEe(e){return{address:e.address,amount:n6.fromNumber(e.amount),index:n6.fromNumber(e.index),validatorIndex:n6.fromNumber(e.validatorIndex)}}});var i6=g(rE=>{"use strict";Object.defineProperty(rE,"__esModule",{value:!0});rE.fromRpc=cEe;rE.toRpc=uEe;var Wl=Jt(),_J=yJ();function cEe(e){return{...e.baseFeePerGas&&{baseFeePerGas:BigInt(e.baseFeePerGas)},...e.blobBaseFee&&{blobBaseFee:BigInt(e.blobBaseFee)},...e.feeRecipient&&{feeRecipient:e.feeRecipient},...e.gasLimit&&{gasLimit:BigInt(e.gasLimit)},...e.number&&{number:BigInt(e.number)},...e.prevRandao&&{prevRandao:BigInt(e.prevRandao)},...e.time&&{time:BigInt(e.time)},...e.withdrawals&&{withdrawals:e.withdrawals.map(_J.fromRpc)}}}function uEe(e){return{...typeof e.baseFeePerGas=="bigint"&&{baseFeePerGas:Wl.fromNumber(e.baseFeePerGas)},...typeof e.blobBaseFee=="bigint"&&{blobBaseFee:Wl.fromNumber(e.blobBaseFee)},...typeof e.feeRecipient=="string"&&{feeRecipient:e.feeRecipient},...typeof e.gasLimit=="bigint"&&{gasLimit:Wl.fromNumber(e.gasLimit)},...typeof e.number=="bigint"&&{number:Wl.fromNumber(e.number)},...typeof e.prevRandao=="bigint"&&{prevRandao:Wl.fromNumber(e.prevRandao)},...typeof e.time=="bigint"&&{time:Wl.fromNumber(e.time)},...e.withdrawals&&{withdrawals:e.withdrawals.map(_J.toRpc)}}}});var er=g(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.erc4626Abi=Ge.erc721Abi=Ge.erc1155Abi=Ge.erc20Abi_bytes32=Ge.erc20Abi=Ge.erc6492SignatureValidatorAbi=Ge.erc1271Abi=Ge.addressResolverAbi=Ge.textResolverAbi=Ge.universalResolverReverseAbi=Ge.universalResolverResolveAbi=Ge.batchGatewayAbi=Ge.multicall3Abi=void 0;Ge.multicall3Abi=[{inputs:[{components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}],name:"calls",type:"tuple[]"}],name:"aggregate3",outputs:[{components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}],name:"returnData",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{name:"addr",type:"address"}],name:"getEthBalance",outputs:[{name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"}];Ge.batchGatewayAbi=[{name:"query",type:"function",stateMutability:"view",inputs:[{type:"tuple[]",name:"queries",components:[{type:"address",name:"sender"},{type:"string[]",name:"urls"},{type:"bytes",name:"data"}]}],outputs:[{type:"bool[]",name:"failures"},{type:"bytes[]",name:"responses"}]},{name:"HttpError",type:"error",inputs:[{type:"uint16",name:"status"},{type:"string",name:"message"}]}];var bJ=[{inputs:[{name:"dns",type:"bytes"}],name:"DNSDecodingFailed",type:"error"},{inputs:[{name:"ens",type:"string"}],name:"DNSEncodingFailed",type:"error"},{inputs:[],name:"EmptyAddress",type:"error"},{inputs:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"HttpError",type:"error"},{inputs:[],name:"InvalidBatchGatewayResponse",type:"error"},{inputs:[{name:"errorData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{name:"name",type:"bytes"},{name:"resolver",type:"address"}],name:"ResolverNotContract",type:"error"},{inputs:[{name:"name",type:"bytes"}],name:"ResolverNotFound",type:"error"},{inputs:[{name:"primary",type:"string"},{name:"primaryAddress",type:"bytes"}],name:"ReverseAddressMismatch",type:"error"},{inputs:[{internalType:"bytes4",name:"selector",type:"bytes4"}],name:"UnsupportedResolverProfile",type:"error"}];Ge.universalResolverResolveAbi=[...bJ,{name:"resolveWithGateways",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"},{name:"gateways",type:"string[]"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]}];Ge.universalResolverReverseAbi=[...bJ,{name:"reverseWithGateways",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"uint256",name:"coinType"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolver"},{type:"address",name:"reverseResolver"}]}];Ge.textResolverAbi=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}];Ge.addressResolverAbi=[{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"}],outputs:[{name:"",type:"address"}]},{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"coinType",type:"uint256"}],outputs:[{name:"",type:"bytes"}]}];Ge.erc1271Abi=[{name:"isValidSignature",type:"function",stateMutability:"view",inputs:[{name:"hash",type:"bytes32"},{name:"signature",type:"bytes"}],outputs:[{name:"",type:"bytes4"}]}];Ge.erc6492SignatureValidatorAbi=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}];Ge.erc20Abi=[{type:"event",name:"Approval",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"event",name:"Transfer",inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{type:"uint8"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}];Ge.erc20Abi_bytes32=[{type:"event",name:"Approval",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"event",name:"Transfer",inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{type:"uint8"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"bytes32"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:"bytes32"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}];Ge.erc1155Abi=[{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"ERC1155InsufficientBalance",type:"error"},{inputs:[{internalType:"address",name:"approver",type:"address"}],name:"ERC1155InvalidApprover",type:"error"},{inputs:[{internalType:"uint256",name:"idsLength",type:"uint256"},{internalType:"uint256",name:"valuesLength",type:"uint256"}],name:"ERC1155InvalidArrayLength",type:"error"},{inputs:[{internalType:"address",name:"operator",type:"address"}],name:"ERC1155InvalidOperator",type:"error"},{inputs:[{internalType:"address",name:"receiver",type:"address"}],name:"ERC1155InvalidReceiver",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"}],name:"ERC1155InvalidSender",type:"error"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"address",name:"owner",type:"address"}],name:"ERC1155MissingApprovalForAll",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!1,internalType:"bool",name:"approved",type:"bool"}],name:"ApprovalForAll",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256[]",name:"ids",type:"uint256[]"},{indexed:!1,internalType:"uint256[]",name:"values",type:"uint256[]"}],name:"TransferBatch",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"id",type:"uint256"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"TransferSingle",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"string",name:"value",type:"string"},{indexed:!0,internalType:"uint256",name:"id",type:"uint256"}],name:"URI",type:"event"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"uint256",name:"id",type:"uint256"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address[]",name:"accounts",type:"address[]"},{internalType:"uint256[]",name:"ids",type:"uint256[]"}],name:"balanceOfBatch",outputs:[{internalType:"uint256[]",name:"",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"address",name:"operator",type:"address"}],name:"isApprovedForAll",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256[]",name:"ids",type:"uint256[]"},{internalType:"uint256[]",name:"values",type:"uint256[]"},{internalType:"bytes",name:"data",type:"bytes"}],name:"safeBatchTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],name:"safeTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"bool",name:"approved",type:"bool"}],name:"setApprovalForAll",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"uri",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"}];Ge.erc721Abi=[{type:"event",name:"Approval",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!0,name:"tokenId",type:"uint256"}]},{type:"event",name:"ApprovalForAll",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"operator",type:"address"},{indexed:!1,name:"approved",type:"bool"}]},{type:"event",name:"Transfer",inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!0,name:"tokenId",type:"uint256"}]},{type:"function",name:"approve",stateMutability:"payable",inputs:[{name:"spender",type:"address"},{name:"tokenId",type:"uint256"}],outputs:[]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"getApproved",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{type:"address"}]},{type:"function",name:"isApprovedForAll",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"operator",type:"address"}],outputs:[{type:"bool"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"ownerOf",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"owner",type:"address"}]},{type:"function",name:"safeTransferFrom",stateMutability:"payable",inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"tokenId",type:"uint256"}],outputs:[]},{type:"function",name:"safeTransferFrom",stateMutability:"nonpayable",inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"id",type:"uint256"},{name:"data",type:"bytes"}],outputs:[]},{type:"function",name:"setApprovalForAll",stateMutability:"nonpayable",inputs:[{name:"operator",type:"address"},{name:"approved",type:"bool"}],outputs:[]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"tokenByIndex",stateMutability:"view",inputs:[{name:"index",type:"uint256"}],outputs:[{type:"uint256"}]},{type:"function",name:"tokenByIndex",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"index",type:"uint256"}],outputs:[{name:"tokenId",type:"uint256"}]},{type:"function",name:"tokenURI",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{type:"string"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"transferFrom",stateMutability:"payable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"tokenId",type:"uint256"}],outputs:[]}];Ge.erc4626Abi=[{anonymous:!1,inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"sender",type:"address"},{indexed:!0,name:"receiver",type:"address"},{indexed:!1,name:"assets",type:"uint256"},{indexed:!1,name:"shares",type:"uint256"}],name:"Deposit",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Transfer",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"sender",type:"address"},{indexed:!0,name:"receiver",type:"address"},{indexed:!0,name:"owner",type:"address"},{indexed:!1,name:"assets",type:"uint256"},{indexed:!1,name:"shares",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],name:"allowance",outputs:[{type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],name:"approve",outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"asset",outputs:[{name:"assetTokenAddress",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{name:"account",type:"address"}],name:"balanceOf",outputs:[{type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"}],name:"convertToAssets",outputs:[{name:"assets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"assets",type:"uint256"}],name:"convertToShares",outputs:[{name:"shares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"assets",type:"uint256"},{name:"receiver",type:"address"}],name:"deposit",outputs:[{name:"shares",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"caller",type:"address"}],name:"maxDeposit",outputs:[{name:"maxAssets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"caller",type:"address"}],name:"maxMint",outputs:[{name:"maxShares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"owner",type:"address"}],name:"maxRedeem",outputs:[{name:"maxShares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"owner",type:"address"}],name:"maxWithdraw",outputs:[{name:"maxAssets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"},{name:"receiver",type:"address"}],name:"mint",outputs:[{name:"assets",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"assets",type:"uint256"}],name:"previewDeposit",outputs:[{name:"shares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"}],name:"previewMint",outputs:[{name:"assets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"}],name:"previewRedeem",outputs:[{name:"assets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"assets",type:"uint256"}],name:"previewWithdraw",outputs:[{name:"shares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"},{name:"receiver",type:"address"},{name:"owner",type:"address"}],name:"redeem",outputs:[{name:"assets",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"totalAssets",outputs:[{name:"totalManagedAssets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"to",type:"address"},{name:"amount",type:"uint256"}],name:"transfer",outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"amount",type:"uint256"}],name:"transferFrom",outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"assets",type:"uint256"},{name:"receiver",type:"address"},{name:"owner",type:"address"}],name:"withdraw",outputs:[{name:"shares",type:"uint256"}],stateMutability:"nonpayable",type:"function"}]});var EJ=g(nE=>{"use strict";Object.defineProperty(nE,"__esModule",{value:!0});nE.aggregate3Signature=void 0;nE.aggregate3Signature="0x82ad56cb"});var zl=g(go=>{"use strict";Object.defineProperty(go,"__esModule",{value:!0});go.multicall3Bytecode=go.erc6492SignatureValidatorByteCode=go.deploylessCallViaFactoryBytecode=go.deploylessCallViaBytecodeBytecode=void 0;go.deploylessCallViaBytecodeBytecode="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe";go.deploylessCallViaFactoryBytecode="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe";go.erc6492SignatureValidatorByteCode="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572";go.multicall3Bytecode="0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033"});var Yl=g(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});ri.InvalidChainIdError=ri.ClientChainNotConfiguredError=ri.ChainNotFoundError=ri.ChainMismatchError=ri.ChainDoesNotSupportContract=void 0;var fg=ye(),o6=class extends fg.BaseError{constructor({blockNumber:t,chain:r,contract:n}){super(`Chain "${r.name}" does not support contract "${n.name}".`,{metaMessages:["This could be due to any of the following:",...t&&n.blockCreated&&n.blockCreated>t?[`- The contract "${n.name}" was not deployed until block ${n.blockCreated} (current block ${t}).`]:[`- The chain does not have the contract "${n.name}" configured.`]],name:"ChainDoesNotSupportContract"})}};ri.ChainDoesNotSupportContract=o6;var s6=class extends fg.BaseError{constructor({chain:t,currentChainId:r}){super(`The current chain of the wallet (id: ${r}) does not match the target chain for the transaction (id: ${t.id} \u2013 ${t.name}).`,{metaMessages:[`Current Chain ID: ${r}`,`Expected Chain ID: ${t.id} \u2013 ${t.name}`],name:"ChainMismatchError"})}};ri.ChainMismatchError=s6;var a6=class extends fg.BaseError{constructor(){super(["No chain was provided to the request.","Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient."].join(`
51
+ `),{name:"ChainNotFoundError"})}};ri.ChainNotFoundError=a6;var c6=class extends fg.BaseError{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}};ri.ClientChainNotConfiguredError=c6;var u6=class extends fg.BaseError{constructor({chainId:t}){super(typeof t=="number"?`Chain ID "${t}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}};ri.InvalidChainIdError=u6});var Xl=g(f6=>{"use strict";Object.defineProperty(f6,"__esModule",{value:!0});f6.encodeDeployData=fEe;var d6=ft(),dEe=Nt(),lEe=zn(),l6="/docs/contract/encodeDeployData";function fEe(e){let{abi:t,args:r,bytecode:n}=e;if(!r||r.length===0)return n;let i=t.find(s=>"type"in s&&s.type==="constructor");if(!i)throw new d6.AbiConstructorNotFoundError({docsPath:l6});if(!("inputs"in i))throw new d6.AbiConstructorParamsNotFoundError({docsPath:l6});if(!i.inputs||i.inputs.length===0)throw new d6.AbiConstructorParamsNotFoundError({docsPath:l6});let o=(0,lEe.encodeAbiParameters)(i.inputs,r);return(0,dEe.concatHex)([n,o])}});var ms=g(p6=>{"use strict";Object.defineProperty(p6,"__esModule",{value:!0});p6.getChainContractAddress=pEe;var wJ=Yl();function pEe({blockNumber:e,chain:t,contract:r}){let n=t?.contracts?.[r];if(!n)throw new wJ.ChainDoesNotSupportContract({chain:t,contract:{name:r}});if(e&&n.blockCreated&&n.blockCreated>e)throw new wJ.ChainDoesNotSupportContract({blockNumber:e,chain:t,contract:{name:r,blockCreated:n.blockCreated}});return n.address}});var iE=g(m6=>{"use strict";Object.defineProperty(m6,"__esModule",{value:!0});m6.getCallError=yEe;var mEe=ao(),gEe=Ti(),hEe=Dl();function yEe(e,{docsPath:t,...r}){let n=(()=>{let i=(0,hEe.getNodeError)(e,r);return i instanceof gEe.UnknownNodeError?e:i})();return new mEe.CallExecutionError(n,{docsPath:t,...r})}});var oE=g(g6=>{"use strict";Object.defineProperty(g6,"__esModule",{value:!0});g6.withResolvers=_Ee;function _Ee(){let e=()=>{},t=()=>{};return{promise:new Promise((n,i)=>{e=n,t=i}),resolve:e,reject:t}}});var pg=g(y6=>{"use strict";Object.defineProperty(y6,"__esModule",{value:!0});y6.createBatchScheduler=EEe;var bEe=oE(),h6=new Map;function EEe({fn:e,id:t,shouldSplitBatch:r,wait:n=0,sort:i}){let o=async()=>{let d=c();s();let l=d.map(({args:m})=>m);l.length!==0&&e(l).then(m=>{i&&Array.isArray(m)&&m.sort(i);for(let p=0;p<d.length;p++){let{resolve:h}=d[p];h?.([m[p],m])}}).catch(m=>{for(let p=0;p<d.length;p++){let{reject:h}=d[p];h?.(m)}})},s=()=>h6.delete(t),a=()=>c().map(({args:d})=>d),c=()=>h6.get(t)||[],u=d=>h6.set(t,[...c(),d]);return{flush:s,async schedule(d){let{promise:l,resolve:m,reject:p}=(0,bEe.withResolvers)();return r?.([...a(),d])&&o(),c().length>0?(u({args:d,resolve:m,reject:p}),l):(u({args:d,resolve:m,reject:p}),setTimeout(o,n),l)}}}});var SJ=g(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.OffchainLookupSenderMismatchError=Za.OffchainLookupResponseMalformedError=Za.OffchainLookupError=void 0;var wEe=Mt(),w6=ye(),vJ=Ii(),_6=class extends w6.BaseError{constructor({callbackSelector:t,cause:r,data:n,extraData:i,sender:o,urls:s}){super(r.shortMessage||"An error occurred while fetching for an offchain result.",{cause:r,metaMessages:[...r.metaMessages||[],r.metaMessages?.length?"":[],"Offchain Gateway Call:",s&&[" Gateway URL(s):",...s.map(a=>` ${(0,vJ.getUrl)(a)}`)],` Sender: ${o}`,` Data: ${n}`,` Callback selector: ${t}`,` Extra data: ${i}`].flat(),name:"OffchainLookupError"})}};Za.OffchainLookupError=_6;var b6=class extends w6.BaseError{constructor({result:t,url:r}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${(0,vJ.getUrl)(r)}`,`Response: ${(0,wEe.stringify)(t)}`],name:"OffchainLookupResponseMalformedError"})}};Za.OffchainLookupResponseMalformedError=b6;var E6=class extends w6.BaseError{constructor({sender:t,to:r}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${r}`,`OffchainLookup sender address: ${t}`],name:"OffchainLookupSenderMismatchError"})}};Za.OffchainLookupSenderMismatchError=E6});var sE=g(v6=>{"use strict";Object.defineProperty(v6,"__esModule",{value:!0});v6.decodeFunctionData=PEe;var vEe=ft(),AJ=on(),SEe=Ra(),AEe=os(),IEe=io();function PEe(e){let{abi:t,data:r}=e,n=(0,AJ.slice)(r,0,4),i=t.find(o=>o.type==="function"&&n===(0,SEe.toFunctionSelector)((0,IEe.formatAbiItem)(o)));if(!i)throw new vEe.AbiFunctionSignatureNotFoundError(n,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:i.name,args:"inputs"in i&&i.inputs&&i.inputs.length>0?(0,AEe.decodeAbiParameters)(i.inputs,(0,AJ.slice)(r,4)):void 0}}});var aE=g(I6=>{"use strict";Object.defineProperty(I6,"__esModule",{value:!0});I6.encodeErrorResult=NEe;var S6=ft(),TEe=Nt(),xEe=Ra(),OEe=zn(),REe=io(),CEe=so(),A6="/docs/contract/encodeErrorResult";function NEe(e){let{abi:t,errorName:r,args:n}=e,i=t[0];if(r){let c=(0,CEe.getAbiItem)({abi:t,args:n,name:r});if(!c)throw new S6.AbiErrorNotFoundError(r,{docsPath:A6});i=c}if(i.type!=="error")throw new S6.AbiErrorNotFoundError(void 0,{docsPath:A6});let o=(0,REe.formatAbiItem)(i),s=(0,xEe.toFunctionSelector)(o),a="0x";if(n&&n.length>0){if(!i.inputs)throw new S6.AbiErrorInputsNotFoundError(i.name,{docsPath:A6});a=(0,OEe.encodeAbiParameters)(i.inputs,n)}return(0,TEe.concatHex)([s,a])}});var uE=g(T6=>{"use strict";Object.defineProperty(T6,"__esModule",{value:!0});T6.encodeFunctionResult=MEe;var cE=ft(),kEe=zn(),jEe=so(),P6="/docs/contract/encodeFunctionResult";function MEe(e){let{abi:t,functionName:r,result:n}=e,i=t[0];if(r){let s=(0,jEe.getAbiItem)({abi:t,name:r});if(!s)throw new cE.AbiFunctionNotFoundError(r,{docsPath:P6});i=s}if(i.type!=="function")throw new cE.AbiFunctionNotFoundError(void 0,{docsPath:P6});if(!i.outputs)throw new cE.AbiFunctionOutputsNotFoundError(i.name,{docsPath:P6});let o=(()=>{if(i.outputs.length===0)return[];if(i.outputs.length===1)return[n];if(Array.isArray(n))return n;throw new cE.InvalidArrayError(n)})();return(0,kEe.encodeAbiParameters)(i.outputs,o)}});var Ql=g(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});Zl.localBatchGatewayUrl=void 0;Zl.localBatchGatewayRequest=PJ;var x6=er(),qEe=jm(),DEe=sE(),IJ=aE(),LEe=uE();Zl.localBatchGatewayUrl="x-batch-gateway:true";async function PJ(e){let{data:t,ccipRequest:r}=e,{args:[n]}=(0,DEe.decodeFunctionData)({abi:x6.batchGatewayAbi,data:t}),i=[],o=[];return await Promise.all(n.map(async(s,a)=>{try{o[a]=s.urls.includes(Zl.localBatchGatewayUrl)?await PJ({data:s.data,ccipRequest:r}):await r(s),i[a]=!1}catch(c){i[a]=!0,o[a]=BEe(c)}})),(0,LEe.encodeFunctionResult)({abi:x6.batchGatewayAbi,functionName:"query",result:[i,o]})}function BEe(e){return e.name==="HttpRequestError"&&e.status?(0,IJ.encodeErrorResult)({abi:x6.batchGatewayAbi,errorName:"HttpError",args:[e.status,e.shortMessage]}):(0,IJ.encodeErrorResult)({abi:[qEe.solidityError],errorName:"Error",args:["shortMessage"in e?e.shortMessage:e.message]})}});var gg=g(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});gs.offchainLookupAbiItem=gs.offchainLookupSignature=void 0;gs.offchainLookup=KEe;gs.ccipRequest=OJ;var UEe=Qa(),O6=SJ(),TJ=Nn(),mg=Ii(),HEe=Ol(),FEe=zn(),$Ee=ln(),JEe=Nt(),VEe=Sr(),xJ=Ql(),GEe=Mt();gs.offchainLookupSignature="0x556f1830";gs.offchainLookupAbiItem={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]};async function KEe(e,{blockNumber:t,blockTag:r,data:n,requestOptions:i,to:o}){let{args:s}=(0,HEe.decodeErrorResult)({data:n,abi:[gs.offchainLookupAbiItem]}),[a,c,u,d,l]=s,{ccipRead:m}=e,p=m&&typeof m?.request=="function"?m.request:OJ;try{if(!(0,$Ee.isAddressEqual)(o,a))throw new O6.OffchainLookupSenderMismatchError({sender:a,to:o});let h=c.includes(xJ.localBatchGatewayUrl)?await(0,xJ.localBatchGatewayRequest)({data:u,ccipRequest:b=>p({...b,requestOptions:i})}):await p({data:u,requestOptions:i,sender:a,urls:c}),{data:y}=await(0,UEe.call)(e,{blockNumber:t,blockTag:r,data:(0,JEe.concat)([d,(0,FEe.encodeAbiParameters)([{type:"bytes"},{type:"bytes"}],[h,l])]),requestOptions:i,to:o});return y}catch(h){throw i?.signal?.aborted?(0,mg.getAbortError)(i.signal):(0,mg.isAbortError)(h)?h:new O6.OffchainLookupError({callbackSelector:d,cause:h,data:n,extraData:l,sender:a,urls:c})}}async function OJ({data:e,requestOptions:t,sender:r,urls:n}){let i=new Error("An unknown error occurred.");for(let o=0;o<n.length;o++){if(t?.signal?.aborted)throw(0,mg.getAbortError)(t.signal);let s=n[o],a=s.includes("{data}")?"GET":"POST",c=a==="POST"?{data:e,sender:r}:void 0,u=a==="POST"?{"Content-Type":"application/json"}:{};try{let d=await fetch(s.replace("{sender}",r.toLowerCase()).replace("{data}",e),{body:JSON.stringify(c),headers:u,method:a,...t?.signal?{signal:t.signal}:{}}),l;if(d.headers.get("Content-Type")?.startsWith("application/json")?l=(await d.json()).data:l=await d.text(),!d.ok){i=new TJ.HttpRequestError({body:c,details:l?.error?(0,GEe.stringify)(l.error):d.statusText,headers:d.headers,status:d.status,url:s});continue}if(!(0,VEe.isHex)(l)){i=new O6.OffchainLookupResponseMalformedError({result:l,url:s});continue}return l}catch(d){if(t?.signal?.aborted)throw(0,mg.getAbortError)(t.signal);if((0,mg.isAbortError)(d))throw d;i=new TJ.HttpRequestError({body:c,details:d.message,url:s})}}throw i}});var Qa=g(dE=>{"use strict";Object.defineProperty(dE,"__esModule",{value:!0});dE.call=awe;dE.getRevertErrorData=BJ;var kJ=_m(),WEe=i6(),zEe=at(),RJ=er(),YEe=EJ(),N6=zl(),R6=ye(),C6=Yl(),jJ=ao(),CJ=Ii(),XEe=ei(),MJ=Xl(),ZEe=Tr(),QEe=ln(),qJ=Nu(),ewe=ms(),twe=iE(),rwe=ls(),nwe=Zn(),iwe=pg(),owe=jb(),swe=Qn();async function awe(e,t){let{account:r=e.account,authorizationList:n,batch:i=!!e.batch?.multicall,blockHash:o,blockNumber:s,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,accessList:u,blobs:d,blockOverrides:l,code:m,data:p,factory:h,factoryData:y,gas:b,gasPrice:v,maxFeePerBlobGas:A,maxFeePerGas:E,maxPriorityFeePerGas:S,nonce:I,requestOptions:T,to:x,value:C,stateOverride:k,...N}=t,M=r?(0,zEe.parseAccount)(r):void 0;if(m&&(h||y))throw new R6.BaseError("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(m&&x)throw new R6.BaseError("Cannot provide both `code` & `to` as parameters.");let j=m&&p,D=h&&y&&x&&p,U=j||D,q=j?LJ({code:m,data:p}):D?pwe({data:p,factory:h,factoryData:y,to:x}):p;try{(0,swe.assertRequest)(t);let L=(0,qJ.formatBlockParameter)({blockHash:o,blockNumber:s,blockTag:a,requireCanonical:c}),V=l?WEe.toRpc(l):void 0,Q=(0,owe.serializeStateOverride)(k),re=e.chain?.formatters?.transactionRequest?.format,je=(re||nwe.formatTransactionRequest)({...(0,rwe.extract)(N,{format:re}),accessList:u,account:M,authorizationList:n,blobs:d,data:q,gas:b,gasPrice:v,maxFeePerBlobGas:A,maxFeePerGas:E,maxPriorityFeePerGas:S,nonce:I,to:U?void 0:x,value:C},"call");if(i&&cwe({request:je})&&!V&&o===void 0)try{let{deployless:nt=!1}=typeof e.batch?.multicall=="object"?e.batch.multicall:{},Ot=DJ(e,{blockNumber:s,deployless:nt});if(!Ot||!fwe(Q,Ot))return await lwe(e,{...je,blockHash:o,blockNumber:s,blockTag:a,multicallAddress:Ot,requestOptions:T,requireCanonical:c,rpcStateOverride:Q})}catch(nt){if(!(nt instanceof C6.ClientChainNotConfiguredError)&&!(nt instanceof C6.ChainDoesNotSupportContract))throw nt}let K=(()=>{let nt=[je,L];return Q&&V?[...nt,Q,V]:Q?[...nt,Q]:V?[...nt,{},V]:nt})(),wr=await e.request({method:"eth_call",params:K},T);return wr==="0x"?{data:void 0}:{data:wr}}catch(L){if(T?.signal?.aborted)throw(0,CJ.getAbortError)(T.signal);if((0,CJ.isAbortError)(L))throw L;let V=BJ(L),{offchainLookup:Q,offchainLookupSignature:re}=await Promise.resolve().then(()=>gg());if(e.ccipRead!==!1&&V?.slice(0,10)===re&&x)return{data:await Q(e,{data:V,requestOptions:T,to:x})};throw U&&V?.slice(0,10)==="0x101bb98d"?new jJ.CounterfactualDeploymentFailedError({factory:h}):(0,twe.getCallError)(L,{...t,account:M,chain:e.chain})}}function cwe({request:e}){let{data:t,to:r,...n}=e;return!(!t||t.startsWith(YEe.aggregate3Signature)||!r||Object.values(n).filter(i=>typeof i<"u").length>0)}var uwe=0,NJ=new WeakMap;function dwe(e){if(!e)return"default";let t=NJ.get(e);if(t!==void 0)return t;let r=uwe++;return NJ.set(e,r),r}async function lwe(e,t){let{batchSize:r=1024,deployless:n=!1,wait:i=0}=typeof e.batch?.multicall=="object"?e.batch.multicall:{},{blockHash:o,blockNumber:s,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,data:u,multicallAddress:d,requestOptions:l,rpcStateOverride:m,to:p}=t,h=d!==void 0?d:DJ(e,{blockNumber:s,deployless:n}),y=(0,qJ.formatBlockParameter)({blockHash:o,blockNumber:s,blockTag:a,requireCanonical:c}),b=typeof y=="string"?y:JSON.stringify(y),v=m?`.${JSON.stringify(m)}`:"",{schedule:A}=(0,iwe.createBatchScheduler)({id:`${e.uid}.${b}.${dwe(l)}${v}`,wait:i,shouldSplitBatch(I){return I.reduce((x,{data:C})=>x+(C.length-2),0)>r*2},fn:async I=>{let T=I.map(N=>({allowFailure:!0,callData:N.data,target:N.to})),x=(0,ZEe.encodeFunctionData)({abi:RJ.multicall3Abi,args:[T],functionName:"aggregate3"}),C={...h===null?{data:LJ({code:N6.multicall3Bytecode,data:x})}:{to:h,data:x}},k=await e.request({method:"eth_call",params:m?[C,y,m]:[C,y]},l);return(0,XEe.decodeFunctionResult)({abi:RJ.multicall3Abi,args:[T],functionName:"aggregate3",data:k||"0x"})}}),[{returnData:E,success:S}]=await A({data:u,to:p});if(!S)throw new jJ.RawContractError({data:E});return E==="0x"?{data:void 0}:{data:E}}function DJ(e,t){let{blockNumber:r,deployless:n}=t;if(n)return null;if(e.chain)return(0,ewe.getChainContractAddress)({blockNumber:r,chain:e.chain,contract:"multicall3"});throw new C6.ClientChainNotConfiguredError}function fwe(e,t){return e?Object.keys(e).some(r=>(0,QEe.isAddressEqual)(r,t)):!1}function LJ(e){let{code:t,data:r}=e;return(0,MJ.encodeDeployData)({abi:(0,kJ.parseAbi)(["constructor(bytes, bytes)"]),bytecode:N6.deploylessCallViaBytecodeBytecode,args:[t,r]})}function pwe(e){let{data:t,factory:r,factoryData:n,to:i}=e;return(0,MJ.encodeDeployData)({abi:(0,kJ.parseAbi)(["constructor(address, bytes, address, bytes)"]),bytecode:N6.deploylessCallViaFactoryBytecode,args:[i,t,r,n]})}function BJ(e){if(!(e instanceof R6.BaseError))return;let t=e.walk();return typeof t?.data=="object"?t.data?.data:t.data}});var Cr=g(k6=>{"use strict";Object.defineProperty(k6,"__esModule",{value:!0});k6.readContract=bwe;var mwe=ei(),gwe=Tr(),hwe=as(),ywe=Te(),_we=Qa();async function bwe(e,t){let{abi:r,address:n,args:i,functionName:o,...s}=t,a=(0,gwe.encodeFunctionData)({abi:r,args:i,functionName:o});try{let{data:c}=await(0,ywe.getAction)(e,_we.call,"call")({...s,data:a,to:n});return(0,mwe.decodeFunctionResult)({abi:r,args:i,functionName:o,data:c||"0x"})}catch(c){throw(0,hwe.getContractError)(c,{abi:r,address:n,args:i,docsPath:"/docs/contract/readContract",functionName:o})}}});var hg=g(j6=>{"use strict";Object.defineProperty(j6,"__esModule",{value:!0});j6.simulateContract=Pwe;var Ewe=at(),wwe=ei(),vwe=Tr(),Swe=as(),Awe=Te(),Iwe=Qa();async function Pwe(e,t){let{abi:r,address:n,args:i,functionName:o,dataSuffix:s=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=a.account?(0,Ewe.parseAccount)(a.account):e.account,u=(0,vwe.encodeFunctionData)({abi:r,args:i,functionName:o});try{let{data:d}=await(0,Awe.getAction)(e,Iwe.call,"call")({batch:!1,data:`${u}${s?s.replace("0x",""):""}`,to:n,...a,account:c}),l=(0,wwe.decodeFunctionResult)({abi:r,args:i,functionName:o,data:d||"0x"}),m=r.filter(p=>"name"in p&&p.name===t.functionName);return{result:l,request:{abi:m,address:n,args:i,dataSuffix:s,functionName:o,...a,account:c}}}catch(d){throw(0,Swe.getContractError)(d,{abi:r,address:n,args:i,docsPath:"/docs/contract/simulateContract",functionName:o,sender:c?.address})}}});var hs=g(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.cleanupCache=pn.listenersCache=void 0;pn.observe=xwe;pn.listenersCache=new Map;pn.cleanupCache=new Map;var Twe=0;function xwe(e,t,r){let n=++Twe,i=()=>pn.listenersCache.get(e)||[],o=()=>{let l=i().filter(m=>m.id!==n);if(l.length===0){pn.listenersCache.delete(e),pn.cleanupCache.delete(e);return}pn.listenersCache.set(e,l)},s=()=>{let d=i();if(!d.some(m=>m.id===n))return;let l=pn.cleanupCache.get(e);if(d.length===1&&l){let m=l();m instanceof Promise&&m.catch(()=>{})}o()},a=i();if(pn.listenersCache.set(e,[...a,{id:n,fns:t}]),a&&a.length>0)return s;let c={};for(let d in t)c[d]=((...l)=>{let m=i();if(m.length!==0)for(let p of m)p.fns[d]?.(...l)});let u=r(c);return typeof u=="function"&&pn.cleanupCache.set(e,u),s}});var lE=g(M6=>{"use strict";Object.defineProperty(M6,"__esModule",{value:!0});M6.wait=Owe;var UJ=Ii();async function Owe(e,{signal:t}={}){return new Promise((r,n)=>{if(t?.aborted){n((0,UJ.getAbortError)(t));return}let i=()=>t?.removeEventListener("abort",s),o=setTimeout(()=>{i(),r()},e),s=()=>{clearTimeout(o),i(),n((0,UJ.getAbortError)(t))};t?.addEventListener("abort",s,{once:!0})})}});var qu=g(q6=>{"use strict";Object.defineProperty(q6,"__esModule",{value:!0});q6.poll=Rwe;var HJ=lE();function Rwe(e,{emitOnBegin:t,initialWaitTime:r,interval:n}){let i=!0,o=()=>i=!1;return(async()=>{let a;t&&(a=await e({unpoll:o}));let c=await r?.(a)??n;await(0,HJ.wait)(c);let u=async()=>{i&&(await e({unpoll:o}),await(0,HJ.wait)(n),u())};u()})(),o}});var D6=g(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.responseCache=ho.promiseCache=void 0;ho.getCache=FJ;ho.withCache=Cwe;ho.promiseCache=new Map;ho.responseCache=new Map;function FJ(e){let t=(i,o)=>({clear:()=>o.delete(i),get:()=>o.get(i),set:s=>o.set(i,s)}),r=t(e,ho.promiseCache),n=t(e,ho.responseCache);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function Cwe(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){let n=FJ(t),i=n.response.get();if(i&&r>0&&Date.now()-i.created.getTime()<r)return i.data;let o=n.promise.get();o||(o=e(),n.promise.set(o));try{let s=await o;return n.response.set({created:new Date,data:s}),s}finally{n.promise.clear()}}});var Du=g(fE=>{"use strict";Object.defineProperty(fE,"__esModule",{value:!0});fE.getBlockNumberCache=Nwe;fE.getBlockNumber=kwe;var $J=D6(),JJ=e=>`blockNumber.${e}`;function Nwe(e){return(0,$J.getCache)(JJ(e))}async function kwe(e,{cacheTime:t=e.cacheTime}={}){let r=await(0,$J.withCache)(()=>e.request({method:"eth_blockNumber"}),{cacheKey:JJ(e.uid),cacheTime:t});return BigInt(r)}});var yg=g(L6=>{"use strict";Object.defineProperty(L6,"__esModule",{value:!0});L6.getFilterChanges=qwe;var jwe=Ya(),Mwe=xi();async function qwe(e,{filter:t}){let r="strict"in t&&t.strict,n=await t.request({method:"eth_getFilterChanges",params:[t.id]});if(typeof n[0]=="string")return n;let i=n.map(o=>(0,Mwe.formatLog)(o));return!("abi"in t)||!t.abi?i:(0,jwe.parseEventLogs)({abi:t.abi,logs:i,strict:r})}});var _g=g(B6=>{"use strict";Object.defineProperty(B6,"__esModule",{value:!0});B6.uninstallFilter=Dwe;async function Dwe(e,{filter:t}){return t.request({method:"eth_uninstallFilter",params:[t.id]})}});var H6=g(U6=>{"use strict";Object.defineProperty(U6,"__esModule",{value:!0});U6.watchContractEvent=Kwe;var VJ=ft(),Lwe=ss(),Bwe=Jl(),Uwe=Ca(),GJ=xi(),bg=Te(),KJ=hs(),Hwe=qu(),WJ=Mt(),Fwe=w_(),$we=Du(),Jwe=zb(),Vwe=yg(),Gwe=_g();function Kwe(e,t){let{abi:r,address:n,args:i,batch:o=!0,eventName:s,fromBlock:a,onError:c,onLogs:u,poll:d,pollingInterval:l=e.pollingInterval,strict:m}=t;return(typeof d<"u"?d:typeof a=="bigint"?!0:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")))?(()=>{let b=m??!1,v=(0,WJ.stringify)(["watchContractEvent",n,i,o,e.uid,s,l,b,a]);return(0,KJ.observe)(v,{onLogs:u,onError:c},A=>{let E;a!==void 0&&(E=a-1n);let S,I=!1,T=(0,Hwe.poll)(async()=>{if(!I){try{S=await(0,bg.getAction)(e,Fwe.createContractEventFilter,"createContractEventFilter")({abi:r,address:n,args:i,eventName:s,strict:b,fromBlock:a})}catch{}I=!0;return}try{let x;if(S)x=await(0,bg.getAction)(e,Vwe.getFilterChanges,"getFilterChanges")({filter:S});else{let C=await(0,bg.getAction)(e,$we.getBlockNumber,"getBlockNumber")({});E&&E<C?x=await(0,bg.getAction)(e,Jwe.getContractEvents,"getContractEvents")({abi:r,address:n,args:i,eventName:s,fromBlock:E+1n,toBlock:C,strict:b}):x=[],E=C}if(x.length===0)return;if(o)A.onLogs(x);else for(let C of x)A.onLogs([C])}catch(x){S&&x instanceof Lwe.InvalidInputRpcError&&(I=!1),A.onError?.(x)}},{emitOnBegin:!0,interval:l});return async()=>{S&&await(0,bg.getAction)(e,Gwe.uninstallFilter,"uninstallFilter")({filter:S}),T()}})})():(()=>{let b=m??!1,v=(0,WJ.stringify)(["watchContractEvent",n,i,o,e.uid,s,l,b]),A=!0,E=()=>A=!1;return(0,KJ.observe)(v,{onLogs:u,onError:c},S=>((async()=>{try{let I=(()=>{if(e.transport.type==="fallback"){let C=e.transport.transports.find(k=>k.config.type==="webSocket"||k.config.type==="ipc");return C?C.value:e.transport}return e.transport})(),T=s?(0,Uwe.encodeEventTopics)({abi:r,eventName:s,args:i}):[],{unsubscribe:x}=await I.subscribe({params:["logs",{address:n,topics:T}],onData(C){if(!A)return;let k=C.result;try{let{eventName:N,args:M}=(0,Bwe.decodeEventLog)({abi:r,data:k.data,topics:k.topics,strict:m}),j=(0,GJ.formatLog)(k,{args:M,eventName:N});S.onLogs([j])}catch(N){let M,j;if(N instanceof VJ.DecodeLogDataMismatch||N instanceof VJ.DecodeLogTopicsMismatch){if(m)return;M=N.abiItem.name,j=N.abiItem.inputs?.some(U=>!("name"in U&&U.name))}let D=(0,GJ.formatLog)(k,{args:j?[]:{},eventName:M});S.onLogs([D])}},onError(C){S.onError?.(C)}});E=x,A||E()}catch(I){c?.(I)}})(),()=>E()))})()}});var yo=g(ef=>{"use strict";Object.defineProperty(ef,"__esModule",{value:!0});ef.AccountTypeNotSupportedError=ef.AccountNotFoundError=void 0;var zJ=ye(),F6=class extends zJ.BaseError{constructor({docsPath:t}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(`
52
+ `),{docsPath:t,docsSlug:"account",name:"AccountNotFoundError"})}};ef.AccountNotFoundError=F6;var $6=class extends zJ.BaseError{constructor({docsPath:t,metaMessages:r,type:n}){super(`Account type "${n}" is not supported.`,{docsPath:t,metaMessages:r,name:"AccountTypeNotSupportedError"})}};ef.AccountTypeNotSupportedError=$6});var tf=g(J6=>{"use strict";Object.defineProperty(J6,"__esModule",{value:!0});J6.assertCurrentChain=Wwe;var YJ=Yl();function Wwe({chain:e,currentChainId:t}){if(!e)throw new YJ.ChainNotFoundError;if(t!==e.id)throw new YJ.ChainMismatchError({chain:e,currentChainId:t})}});var pE=g(V6=>{"use strict";Object.defineProperty(V6,"__esModule",{value:!0});V6.sendRawTransaction=zwe;async function zwe(e,{serializedTransaction:t}){return e.request({method:"eth_sendRawTransaction",params:[t]},{retryCount:0})}});var Eg=g(W6=>{"use strict";Object.defineProperty(W6,"__esModule",{value:!0});W6.sendTransaction=a1e;var Ywe=at(),mE=yo(),Xwe=ye(),Zwe=ql(),Qwe=tf(),XJ=Nt(),e1e=Hl(),t1e=ls(),r1e=Zn(),G6=Te(),n1e=Ta(),i1e=Qn(),o1e=ps(),ZJ=Fl(),s1e=pE(),K6=new n1e.LruMap(128);async function a1e(e,t){let{account:r=e.account,assertChainId:n=!0,chain:i=e.chain,accessList:o,authorizationList:s,blobs:a,data:c,dataSuffix:u=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,gas:d,gasPrice:l,maxFeePerBlobGas:m,maxFeePerGas:p,maxPriorityFeePerGas:h,nonce:y,type:b,value:v,...A}=t;if(typeof r>"u")throw new mE.AccountNotFoundError({docsPath:"/docs/actions/wallet/sendTransaction"});let E=r?(0,Ywe.parseAccount)(r):null,S;try{(0,i1e.assertRequest)(t);let I=await(async()=>{if(t.to)return t.to;if(t.to!==null&&s&&s.length>0)return await(0,Zwe.recoverAuthorizationAddress)({authorization:s[0]}).catch(()=>{throw new Xwe.BaseError("`to` is required. Could not infer from `authorizationList`.")})})();if(E?.type==="json-rpc"||E===null){let T;i!==null&&(T=await(0,G6.getAction)(e,o1e.getChainId,"getChainId")({}),n&&(0,Qwe.assertCurrentChain)({currentChainId:T,chain:i}));let x=e.chain?.formatters?.transactionRequest?.format,k=(x||r1e.formatTransactionRequest)({...(0,t1e.extract)(A,{format:x}),accessList:o,account:E,authorizationList:s,blobs:a,chainId:T,data:u?(0,XJ.concat)([c??"0x",u]):c,gas:d,gasPrice:l,maxFeePerBlobGas:m,maxFeePerGas:p,maxPriorityFeePerGas:h,nonce:y,to:I,type:b,value:v},"sendTransaction"),N=K6.get(e.uid),M=N?"wallet_sendTransaction":"eth_sendTransaction";try{return await e.request({method:M,params:[k]},{retryCount:0})}catch(j){if(N===!1)throw j;let D=j;if(D.name==="InvalidInputRpcError"||D.name==="InvalidParamsRpcError"||D.name==="MethodNotFoundRpcError"||D.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[k]},{retryCount:0}).then(U=>(K6.set(e.uid,!0),U)).catch(U=>{let q=U;throw q.name==="MethodNotFoundRpcError"||q.name==="MethodNotSupportedRpcError"?(K6.set(e.uid,!1),D):q});throw D}}if(E?.type==="local"){let T=(()=>{if(!E.nonceManager||typeof y<"u")return E.nonceManager;let N=E.nonceManager;return{consume(M){return S={address:M.address,chainId:M.chainId},N.consume(M)},get(M){return N.get(M)},increment(M){return N.increment(M)},reset(M){return N.reset(M)}}})(),x=await(0,G6.getAction)(e,ZJ.prepareTransactionRequest,"prepareTransactionRequest")({account:E,accessList:o,authorizationList:s,blobs:a,chain:i,data:u?(0,XJ.concat)([c??"0x",u]):c,gas:d,gasPrice:l,maxFeePerBlobGas:m,maxFeePerGas:p,maxPriorityFeePerGas:h,nonce:y,nonceManager:T,parameters:[...ZJ.defaultParameters,"sidecars"],type:b,value:v,...A,to:I}),C=i?.serializers?.transaction,k=await E.signTransaction(x,{serializer:C});return await(0,G6.getAction)(e,s1e.sendRawTransaction,"sendRawTransaction")({serializedTransaction:k})}throw E?.type==="smart"?new mE.AccountTypeNotSupportedError({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new mE.AccountTypeNotSupportedError({docsPath:"/docs/actions/wallet/sendTransaction",type:E?.type})}catch(I){throw I instanceof mE.AccountTypeNotSupportedError?I:(S&&E?.nonceManager?.reset(S),(0,e1e.getTransactionError)(I,{...t,account:E,chain:t.chain||void 0}))}}});var rf=g(hE=>{"use strict";Object.defineProperty(hE,"__esModule",{value:!0});hE.writeContract=gE;var c1e=at(),u1e=yo(),d1e=Tr(),l1e=as(),f1e=Te(),p1e=Eg();async function gE(e,t){return gE.internal(e,p1e.sendTransaction,"sendTransaction",t)}(function(e){async function t(r,n,i,o){let{abi:s,account:a=r.account,address:c,args:u,functionName:d,...l}=o;if(typeof a>"u")throw new u1e.AccountNotFoundError({docsPath:"/docs/contract/writeContract"});let m=a?(0,c1e.parseAccount)(a):null,p=(0,d1e.encodeFunctionData)({abi:s,args:u,functionName:d});try{return await(0,f1e.getAction)(r,n,i)({data:p,to:c,account:m,...l})}catch(h){throw(0,l1e.getContractError)(h,{abi:s,address:c,args:u,docsPath:"/docs/contract/writeContract",functionName:d,sender:m?.address})}}e.internal=t})(gE||(hE.writeContract=gE={}))});var QJ=g(vg=>{"use strict";Object.defineProperty(vg,"__esModule",{value:!0});vg.getContract=w1e;vg.getFunctionParameters=wg;vg.getEventParameters=yE;var Lu=Te(),m1e=w_(),g1e=og(),h1e=zb(),y1e=Cr(),_1e=hg(),b1e=H6(),E1e=rf();function w1e({abi:e,address:t,client:r}){let n=r,[i,o]=n?"public"in n&&"wallet"in n?[n.public,n.wallet]:"public"in n?[n.public,void 0]:"wallet"in n?[void 0,n.wallet]:[n,n]:[void 0,void 0],s=i!=null,a=o!=null,c={},u=!1,d=!1,l=!1;for(let m of e)if(m.type==="function"?m.stateMutability==="view"||m.stateMutability==="pure"?u=!0:d=!0:m.type==="event"&&(l=!0),u&&d&&l)break;return s&&(u&&(c.read=new Proxy({},{get(m,p){return(...h)=>{let{args:y,options:b}=wg(h);return(0,Lu.getAction)(i,y1e.readContract,"readContract")({abi:e,address:t,functionName:p,args:y,...b})}}})),d&&(c.simulate=new Proxy({},{get(m,p){return(...h)=>{let{args:y,options:b}=wg(h);return(0,Lu.getAction)(i,_1e.simulateContract,"simulateContract")({abi:e,address:t,functionName:p,args:y,...b})}}})),l&&(c.createEventFilter=new Proxy({},{get(m,p){return(...h)=>{let y=e.find(A=>A.type==="event"&&A.name===p),{args:b,options:v}=yE(h,y);return(0,Lu.getAction)(i,m1e.createContractEventFilter,"createContractEventFilter")({abi:e,address:t,eventName:p,args:b,...v})}}}),c.getEvents=new Proxy({},{get(m,p){return(...h)=>{let y=e.find(A=>A.type==="event"&&A.name===p),{args:b,options:v}=yE(h,y);return(0,Lu.getAction)(i,h1e.getContractEvents,"getContractEvents")({abi:e,address:t,eventName:p,args:b,...v})}}}),c.watchEvent=new Proxy({},{get(m,p){return(...h)=>{let y=e.find(A=>A.type==="event"&&A.name===p),{args:b,options:v}=yE(h,y);return(0,Lu.getAction)(i,b1e.watchContractEvent,"watchContractEvent")({abi:e,address:t,eventName:p,args:b,...v})}}}))),a&&d&&(c.write=new Proxy({},{get(m,p){return(...h)=>{let{args:y,options:b}=wg(h);return(0,Lu.getAction)(o,E1e.writeContract,"writeContract")({abi:e,address:t,functionName:p,args:y,...b})}}})),(s||a)&&d&&(c.estimateGas=new Proxy({},{get(m,p){return(...h)=>{let{args:y,options:b}=wg(h),v=i??o;return(0,Lu.getAction)(v,g1e.estimateContractGas,"estimateContractGas")({abi:e,address:t,functionName:p,args:y,...b,account:b.account??o.account})}}})),c.address=t,c.abi=e,c}function wg(e){let t=e.length&&Array.isArray(e[0]),r=t?e[0]:[],n=(t?e[1]:e[0])??{};return{args:r,options:n}}function yE(e,t){let r=!1;Array.isArray(e[0])?r=!0:e.length===1?r=t.inputs.some(o=>o.indexed):e.length===2&&(r=!0);let n=r?e[0]:void 0,i=(r?e[1]:e[0])??{};return{args:n,options:i}}});var Y6=g(_E=>{"use strict";Object.defineProperty(_E,"__esModule",{value:!0});_E.BundleFailedError=void 0;var v1e=ye(),z6=class extends v1e.BaseError{constructor(t){super(`Call bundle failed with status: ${t.statusCode}`,{name:"BundleFailedError"}),Object.defineProperty(this,"result",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.result=t}};_E.BundleFailedError=z6});var Sg=g(Z6=>{"use strict";Object.defineProperty(Z6,"__esModule",{value:!0});Z6.withRetry=A1e;var X6=Ii(),S1e=lE();function A1e(e,{delay:t=100,retryCount:r=2,shouldRetry:n=()=>!0,signal:i}={}){return new Promise((o,s)=>{let a=async({count:c=0}={})=>{if(i?.aborted){s((0,X6.getAbortError)(i));return}let u=async({error:d})=>{let l=typeof t=="function"?t({count:c,error:d}):t;if(l)try{await(0,S1e.wait)(l,{signal:i})}catch(m){s(m);return}return a({count:c+1})};try{let d=await e();o(d)}catch(d){if(i?.aborted){s((0,X6.getAbortError)(i));return}if((0,X6.isAbortError)(d)){s(d);return}if(c<r&&await n({count:c,error:d}))return u({error:d});s(d)}};a().catch(s)})}});var Bu=g(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.defineTransactionReceipt=ec.receiptStatuses=void 0;ec.formatTransactionReceipt=e7;var I1e=pt(),P1e=Ll(),T1e=xi(),x1e=Cu();ec.receiptStatuses={"0x0":"reverted","0x1":"success"};function e7(e,t){let r={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map(n=>(0,T1e.formatLog)(n)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?(0,I1e.hexToNumber)(e.transactionIndex):null,status:e.status?ec.receiptStatuses[e.status]:null,type:e.type?x1e.transactionType[e.type]||e.type:null};return e.blobGasPrice&&(r.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(r.blobGasUsed=BigInt(e.blobGasUsed)),r}ec.defineTransactionReceipt=(0,P1e.defineFormatter)("transactionReceipt",e7)});var EE=g(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});ys.fallbackTransactionErrorMagicIdentifier=ys.fallbackMagicIdentifier=void 0;ys.sendCalls=j1e;var O1e=at(),t7=ye(),r7=ss(),R1e=Tr(),n7=Nt(),C1e=pt(),bE=W(),N1e=Hl(),k1e=Eg();ys.fallbackMagicIdentifier="0x5792579257925792579257925792579257925792579257925792579257925792";ys.fallbackTransactionErrorMagicIdentifier=(0,bE.numberToHex)(0,{size:32});async function j1e(e,t){let{account:r=e.account,chain:n=e.chain,experimental_fallback:i,experimental_fallbackDelay:o=32,forceAtomic:s=!1,id:a,version:c="2.0.0"}=t,u=r?(0,O1e.parseAccount)(r):null,d=t.capabilities;e.dataSuffix&&!t.capabilities?.dataSuffix&&(typeof e.dataSuffix=="string"?d={...t.capabilities,dataSuffix:{value:e.dataSuffix,optional:!0}}:d={...t.capabilities,dataSuffix:{value:e.dataSuffix.value,...e.dataSuffix.required?{}:{optional:!0}}});let l=t.calls.map(m=>{let p=m,h=p.abi?(0,R1e.encodeFunctionData)({abi:p.abi,functionName:p.functionName,args:p.args}):p.data;return{data:p.dataSuffix&&h?(0,n7.concat)([h,p.dataSuffix]):h,to:p.to,value:p.value?(0,bE.numberToHex)(p.value):void 0}});try{let m=await e.request({method:"wallet_sendCalls",params:[{atomicRequired:s,calls:l,capabilities:d,chainId:(0,bE.numberToHex)(n.id),from:u?.address,id:a,version:c}]},{retryCount:0});return typeof m=="string"?{id:m}:m}catch(m){let p=m;if(i&&(p.name==="MethodNotFoundRpcError"||p.name==="MethodNotSupportedRpcError"||p.name==="UnknownRpcError"||p.details.toLowerCase().includes("does not exist / is not available")||p.details.toLowerCase().includes("missing or invalid. request()")||p.details.toLowerCase().includes("did not match any variant of untagged enum")||p.details.toLowerCase().includes("account upgraded to unsupported contract")||p.details.toLowerCase().includes("eip-7702 not supported")||p.details.toLowerCase().includes("unsupported wc_ method")||p.details.toLowerCase().includes("feature toggled misconfigured")||p.details.toLowerCase().includes("jsonrpcengine: response has no error or result for request"))){if(d&&Object.values(d).some(v=>!v.optional)){let v="non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";throw new r7.UnsupportedNonOptionalCapabilityError(new t7.BaseError(v,{details:v}))}if(s&&l.length>1){let b="`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";throw new r7.AtomicityNotSupportedError(new t7.BaseError(b,{details:b}))}let h=[];for(let b of l){try{let v=await(0,k1e.sendTransaction)(e,{account:u,chain:n,data:b.data,to:b.to,value:b.value?(0,C1e.hexToBigInt)(b.value):void 0});h.push({status:"fulfilled",value:v})}catch(v){h.push({reason:v,status:"rejected"})}o>0&&await new Promise(v=>setTimeout(v,o))}if(h.every(b=>b.status==="rejected"))throw h[0].reason;let y=h.map(b=>b.status==="fulfilled"?b.value:ys.fallbackTransactionErrorMagicIdentifier);return{id:(0,n7.concat)([...y,(0,bE.numberToHex)(n.id,{size:32}),ys.fallbackMagicIdentifier])}}throw(0,N1e.getTransactionError)(m,{...t,account:u,chain:t.chain})}}});var eR=g(Q6=>{"use strict";Object.defineProperty(Q6,"__esModule",{value:!0});Q6.getCallsStatus=D1e;var i7=on(),M1e=ts(),wE=pt(),q1e=Bu(),o7=EE();async function D1e(e,t){async function r(d){if(d.endsWith(o7.fallbackMagicIdentifier.slice(2))){let m=(0,M1e.trim)((0,i7.sliceHex)(d,-64,-32)),p=(0,i7.sliceHex)(d,0,-64).slice(2).match(/.{1,64}/g),h=await Promise.all(p.map(b=>o7.fallbackTransactionErrorMagicIdentifier.slice(2)!==b?e.request({method:"eth_getTransactionReceipt",params:[`0x${b}`]},{dedupe:!0}):void 0)),y=h.some(b=>b===null)?100:h.every(b=>b?.status==="0x1")?200:h.every(b=>b?.status==="0x0")?500:600;return{atomic:!1,chainId:(0,wE.hexToNumber)(m),receipts:h.filter(Boolean),status:y,version:"2.0.0"}}return e.request({method:"wallet_getCallsStatus",params:[d]})}let{atomic:n=!1,chainId:i,receipts:o,version:s="2.0.0",...a}=await r(t.id),[c,u]=(()=>{let d=a.status;return d>=100&&d<200?["pending",d]:d>=200&&d<300?["success",d]:d>=300&&d<700?["failure",d]:d==="CONFIRMED"?["success",200]:d==="PENDING"?["pending",100]:[void 0,d]})();return{...a,atomic:n,chainId:i?(0,wE.hexToNumber)(i):void 0,receipts:o?.map(d=>({...d,blockNumber:(0,wE.hexToBigInt)(d.blockNumber),gasUsed:(0,wE.hexToBigInt)(d.gasUsed),status:q1e.receiptStatuses[d.status]}))??[],statusCode:u,status:c,version:s}}});var SE=g(Ag=>{"use strict";Object.defineProperty(Ag,"__esModule",{value:!0});Ag.WaitForCallsStatusTimeoutError=void 0;Ag.waitForCallsStatus=K1e;var L1e=ye(),B1e=Y6(),U1e=Te(),H1e=hs(),F1e=qu(),$1e=oE(),J1e=Sg(),V1e=Mt(),G1e=eR();async function K1e(e,t){let{id:r,pollingInterval:n=e.pollingInterval,status:i=({statusCode:y})=>y===200||y>=300,retryCount:o=4,retryDelay:s=({count:y})=>~~(1<<y)*200,timeout:a=6e4,throwOnFailure:c=!1}=t,u=(0,V1e.stringify)(["waitForCallsStatus",e.uid,r]),{promise:d,resolve:l,reject:m}=(0,$1e.withResolvers)(),p,h=(0,H1e.observe)(u,{resolve:l,reject:m},y=>{let b=(0,F1e.poll)(async()=>{let v=A=>{clearTimeout(p),b(),A(),h()};try{let A=await(0,J1e.withRetry)(async()=>{let E=await(0,U1e.getAction)(e,G1e.getCallsStatus,"getCallsStatus")({id:r});if(c&&E.status==="failure")throw new B1e.BundleFailedError(E);return E},{retryCount:o,delay:s});if(!i(A))return;v(()=>y.resolve(A))}catch(A){v(()=>y.reject(A))}},{interval:n,emitOnBegin:!0});return b});return p=a?setTimeout(()=>{h(),clearTimeout(p),m(new vE({id:r}))},a):void 0,await d}var vE=class extends L1e.BaseError{constructor({id:t}){super(`Timed out while waiting for call bundle with id "${t}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}};Ag.WaitForCallsStatusTimeoutError=vE});var nR=g(rR=>{"use strict";Object.defineProperty(rR,"__esModule",{value:!0});rR.uid=W1e;var tR=256,AE=tR,IE;function W1e(e=11){if(!IE||AE+e>tR*2){IE="",AE=0;for(let t=0;t<tR;t++)IE+=(256+Math.random()*256|0).toString(16).substring(1)}return IE.substring(AE,AE+++e)}});var Uu=g(Ig=>{"use strict";Object.defineProperty(Ig,"__esModule",{value:!0});Ig.createClient=X1e;Ig.bindActionDecorators=Z1e;Ig.rpcSchema=Q1e;var z1e=at(),Y1e=nR();function X1e(e){let{batch:t,chain:r,ccipRead:n,dataSuffix:i,key:o="base",name:s="Base Client",tokens:a,type:c="base"}=e,u=e.experimental_blockTag??(typeof r?.experimental_preconfirmationTime=="number"?"pending":void 0),d=r?.blockTime??12e3,l=Math.min(Math.max(Math.floor(d/2),500),4e3),m=e.pollingInterval??l,p=e.cacheTime??m,h=e.account?(0,z1e.parseAccount)(e.account):void 0,{config:y,request:b,value:v}=e.transport({account:h,chain:r,pollingInterval:m}),A={...y,...v},E={account:h,batch:t,cacheTime:p,ccipRead:n,chain:r,dataSuffix:i,key:o,name:s,pollingInterval:m,request:b,tokens:a,transport:A,type:c,uid:(0,Y1e.uid)(),...u?{experimental_blockTag:u}:{}};function S(I){return T=>{let x=T(I);for(let k in E)delete x[k];let C={...I,...x};for(let k in x){let N=I[k],M=x[k];s7(N)&&s7(M)&&(C[k]={...N,...M})}return Object.assign(C,{extend:S(C)})}}return Object.assign(E,{extend:S(E)})}function s7(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Z1e(e,t){let r=(n={})=>t(e,n);for(let n of["call","calls","callWithPeriod","estimateGas","prepare","prepareRecipient","predict","simulate"])if(Object.hasOwn(t,n)){let i=t[n];r[n]=(o={})=>i.length===1?i(o):i(e,o)}for(let n of["extractEvent","extractEvents"])Object.hasOwn(t,n)&&(r[n]=t[n]);return r}function Q1e(){return null}});var PE=g(iR=>{"use strict";Object.defineProperty(iR,"__esModule",{value:!0});iR.isNullUniversalResolverError=tve;var eve=ye(),a7=ao();function tve(e){if(!(e instanceof eve.BaseError))return!1;let t=e.walk(r=>r instanceof a7.ContractFunctionRevertedError);return t instanceof a7.ContractFunctionRevertedError?t.data?.errorName==="HttpError"||t.data?.errorName==="ResolverError"||t.data?.errorName==="ResolverNotContract"||t.data?.errorName==="ResolverNotFound"||t.data?.errorName==="ReverseAddressMismatch"||t.data?.errorName==="UnsupportedResolverProfile":!1}});var sR=g(oR=>{"use strict";Object.defineProperty(oR,"__esModule",{value:!0});oR.encodedLabelToLabelhash=nve;var rve=Sr();function nve(e){if(e.length!==66||e.indexOf("[")!==0||e.indexOf("]")!==65)return null;let t=`0x${e.slice(1,65)}`;return(0,rve.isHex)(t)?t:null}});var TE=g(aR=>{"use strict";Object.defineProperty(aR,"__esModule",{value:!0});aR.namehash=sve;var ive=Nt(),c7=Je(),u7=W(),d7=Hr(),ove=sR();function sve(e){let t=new Uint8Array(32).fill(0);if(!e)return(0,u7.bytesToHex)(t);let r=e.split(".");for(let n=r.length-1;n>=0;n-=1){let i=(0,ove.encodedLabelToLabelhash)(r[n]),o=i?(0,c7.toBytes)(i):(0,d7.keccak256)((0,c7.stringToBytes)(r[n]),"bytes");t=(0,d7.keccak256)((0,ive.concat)([t,o]),"bytes")}return(0,u7.bytesToHex)(t)}});var l7=g(cR=>{"use strict";Object.defineProperty(cR,"__esModule",{value:!0});cR.encodeLabelhash=ave;function ave(e){return`[${e.slice(2)}]`}});var dR=g(uR=>{"use strict";Object.defineProperty(uR,"__esModule",{value:!0});uR.labelhash=fve;var cve=Je(),uve=W(),dve=Hr(),lve=sR();function fve(e){let t=new Uint8Array(32).fill(0);return e?(0,lve.encodedLabelToLabelhash)(e)||(0,dve.keccak256)((0,cve.stringToBytes)(e)):(0,uve.bytesToHex)(t)}});var xE=g(fR=>{"use strict";Object.defineProperty(fR,"__esModule",{value:!0});fR.packetToBytes=gve;var lR=Je(),pve=l7(),mve=dR();function gve(e){let t=e.replace(/^\.|\.$/gm,"");if(t.length===0)return new Uint8Array(1);let r=new Uint8Array((0,lR.stringToBytes)(t).byteLength+2),n=0,i=t.split(".");for(let o=0;o<i.length;o++){let s=(0,lR.stringToBytes)(i[o]);s.byteLength>255&&(s=(0,lR.stringToBytes)((0,pve.encodeLabelhash)((0,mve.labelhash)(i[o])))),r[n]=s.length,r.set(s,n+1),n+=s.length+1}return r.byteLength!==n+1?r.slice(0,n+1):r}});var m7=g(mR=>{"use strict";Object.defineProperty(mR,"__esModule",{value:!0});mR.getEnsAddress=Tve;var pR=er(),hve=ei(),yve=Tr(),_ve=Ir(),bve=ms(),Eve=ur(),p7=ts(),wve=W(),vve=PE(),Sve=Ql(),f7=TE(),Ave=xE(),Ive=Te(),Pve=Cr();async function Tve(e,t){let{blockNumber:r,blockTag:n,coinType:i,name:o,gatewayUrls:s,strict:a}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return(0,bve.getChainContractAddress)({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),d=c?.ensTlds;if(d&&!d.some(m=>o.endsWith(m)))return null;let l=i!=null?[(0,f7.namehash)(o),BigInt(i)]:[(0,f7.namehash)(o)];try{let m=(0,yve.encodeFunctionData)({abi:pR.addressResolverAbi,functionName:"addr",args:l}),p={address:u,abi:pR.universalResolverResolveAbi,functionName:"resolveWithGateways",args:[(0,wve.toHex)((0,Ave.packetToBytes)(o)),m,s??[Sve.localBatchGatewayUrl]],blockNumber:r,blockTag:n},y=await(0,Ive.getAction)(e,Pve.readContract,"readContract")(p);if(y[0]==="0x")return null;let b=xve({coinType:i,data:y[0],args:l});return b==="0x"||(0,p7.trim)(b)==="0x00"?null:b}catch(m){if(a)throw m;if((0,vve.isNullUniversalResolverError)(m))return null;throw m}}function xve({coinType:e,data:t,args:r}){try{return(0,hve.decodeFunctionResult)({abi:pR.addressResolverAbi,args:r,functionName:"addr",data:t})}catch(n){if(e==null)throw n;let i=(0,p7.trim)(t);if((0,Eve.size)(i)===20)return(0,_ve.getAddress)(i);throw n}}});var OE=g(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.EnsInvalidChainIdError=ni.EnsAvatarUnsupportedNamespaceError=ni.EnsAvatarUriResolutionError=ni.EnsAvatarInvalidNftUriError=ni.EnsAvatarInvalidMetadataError=void 0;var Pg=ye(),gR=class extends Pg.BaseError{constructor({data:t}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(t)}`],name:"EnsAvatarInvalidMetadataError"})}};ni.EnsAvatarInvalidMetadataError=gR;var hR=class extends Pg.BaseError{constructor({reason:t}){super(`ENS NFT avatar URI is invalid. ${t}`,{name:"EnsAvatarInvalidNftUriError"})}};ni.EnsAvatarInvalidNftUriError=hR;var yR=class extends Pg.BaseError{constructor({uri:t}){super(`Unable to resolve ENS avatar URI "${t}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}};ni.EnsAvatarUriResolutionError=yR;var _R=class extends Pg.BaseError{constructor({namespace:t}){super(`ENS NFT avatar namespace "${t}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}};ni.EnsAvatarUnsupportedNamespaceError=_R;var bR=class extends Pg.BaseError{constructor({chainId:t}){super(`Invalid ENSIP-11 chainId: ${t}. Must be between 0 and 0x7fffffff, or 1.`,{name:"EnsInvalidChainIdError"})}};ni.EnsInvalidChainIdError=bR});var E7=g(bo=>{"use strict";Object.defineProperty(bo,"__esModule",{value:!0});bo.isImageUri=h7;bo.getGateway=ER;bo.resolveAvatarUri=y7;bo.getJsonImage=_7;bo.getMetadataAvatarUri=kve;bo.parseAvatarUri=b7;bo.parseNftUri=jve;bo.getNftTokenUri=Mve;var g7=Cr(),_o=OE(),Ove=/(?<protocol>https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,Rve=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?<target>[\w\-.]+))?(?<subtarget>\/.*)?$/,Cve=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,Nve=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function h7(e){try{let t=await fetch(e,{method:"HEAD"});return t.status===200?t.headers.get("content-type")?.startsWith("image/"):!1}catch(t){return typeof t=="object"&&typeof t.response<"u"||!Object.hasOwn(globalThis,"Image")?!1:new Promise(r=>{let n=new Image;n.onload=()=>{r(!0)},n.onerror=()=>{r(!1)},n.src=e})}}function ER(e,t){return e?e.endsWith("/")?e.slice(0,-1):e:t}function y7({uri:e,gatewayUrls:t}){let r=Cve.test(e);if(r)return{uri:e,isOnChain:!0,isEncoded:r};let n=ER(t?.ipfs,"https://ipfs.io"),i=ER(t?.arweave,"https://arweave.net"),o=e.match(Ove),{protocol:s,subpath:a,target:c,subtarget:u=""}=o?.groups||{},d=s==="ipns:/"||a==="ipns/",l=s==="ipfs:/"||a==="ipfs/"||Rve.test(e);if(e.startsWith("http")&&!d&&!l){let p=e;return t?.arweave&&(p=e.replace(/https:\/\/arweave.net/g,t?.arweave)),{uri:p,isOnChain:!1,isEncoded:!1}}if((d||l)&&c)return{uri:`${n}/${d?"ipns":"ipfs"}/${c}${u}`,isOnChain:!1,isEncoded:!1};if(s==="ar:/"&&c)return{uri:`${i}/${c}${u||""}`,isOnChain:!1,isEncoded:!1};let m=e.replace(Nve,"");if(m.startsWith("<svg")&&(m=`data:image/svg+xml;base64,${btoa(m)}`),m.startsWith("data:")||m.startsWith("{"))return{uri:m,isOnChain:!0,isEncoded:!1};throw new _o.EnsAvatarUriResolutionError({uri:e})}function _7(e){if(typeof e!="object"||!("image"in e)&&!("image_url"in e)&&!("image_data"in e))throw new _o.EnsAvatarInvalidMetadataError({data:e});return e.image||e.image_url||e.image_data}async function kve({gatewayUrls:e,uri:t}){try{let r=await fetch(t).then(i=>i.json());return await b7({gatewayUrls:e,uri:_7(r)})}catch{throw new _o.EnsAvatarUriResolutionError({uri:t})}}async function b7({gatewayUrls:e,uri:t}){let{uri:r,isOnChain:n}=y7({uri:t,gatewayUrls:e});if(n||await h7(r))return r;throw new _o.EnsAvatarUriResolutionError({uri:t})}function jve(e){let t=e;t.startsWith("did:nft:")&&(t=t.replace("did:nft:","").replace(/_/g,"/"));let[r,n,i]=t.split("/"),[o,s]=r.split(":"),[a,c]=n.split(":");if(!o||o.toLowerCase()!=="eip155")throw new _o.EnsAvatarInvalidNftUriError({reason:"Only EIP-155 supported"});if(!s)throw new _o.EnsAvatarInvalidNftUriError({reason:"Chain ID not found"});if(!c)throw new _o.EnsAvatarInvalidNftUriError({reason:"Contract address not found"});if(!i)throw new _o.EnsAvatarInvalidNftUriError({reason:"Token ID not found"});if(!a)throw new _o.EnsAvatarInvalidNftUriError({reason:"ERC namespace not found"});return{chainID:Number.parseInt(s,10),namespace:a.toLowerCase(),contractAddress:c,tokenID:i}}async function Mve(e,{nft:t}){if(t.namespace==="erc721")return(0,g7.readContract)(e,{address:t.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(t.tokenID)]});if(t.namespace==="erc1155")return(0,g7.readContract)(e,{address:t.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(t.tokenID)]});throw new _o.EnsAvatarUnsupportedNamespaceError({namespace:t.namespace})}});var w7=g(wR=>{"use strict";Object.defineProperty(wR,"__esModule",{value:!0});wR.parseAvatarRecord=qve;var Hu=E7();async function qve(e,{gatewayUrls:t,record:r}){return/eip155:/i.test(r)?Dve(e,{gatewayUrls:t,record:r}):(0,Hu.parseAvatarUri)({uri:r,gatewayUrls:t})}async function Dve(e,{gatewayUrls:t,record:r}){let n=(0,Hu.parseNftUri)(r),i=await(0,Hu.getNftTokenUri)(e,{nft:n}),{uri:o,isOnChain:s,isEncoded:a}=(0,Hu.resolveAvatarUri)({uri:i,gatewayUrls:t});if(s&&(o.includes("data:application/json;base64,")||o.startsWith("{"))){let u=a?atob(o.replace("data:application/json;base64,","")):o,d=JSON.parse(u);return(0,Hu.parseAvatarUri)({uri:(0,Hu.getJsonImage)(d),gatewayUrls:t})}let c=n.tokenID;return n.namespace==="erc1155"&&(c=c.replace("0x","").padStart(64,"0")),(0,Hu.getMetadataAvatarUri)({gatewayUrls:t,uri:o.replace(/(?:0x)?{id}/,c)})}});var AR=g(SR=>{"use strict";Object.defineProperty(SR,"__esModule",{value:!0});SR.getEnsText=Wve;var vR=er(),Lve=ei(),Bve=Tr(),Uve=ms(),Hve=W(),Fve=PE(),$ve=Ql(),Jve=TE(),Vve=xE(),Gve=Te(),Kve=Cr();async function Wve(e,t){let{blockNumber:r,blockTag:n,key:i,name:o,gatewayUrls:s,strict:a}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return(0,Uve.getChainContractAddress)({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),d=c?.ensTlds;if(d&&!d.some(l=>o.endsWith(l)))return null;try{let l={address:u,abi:vR.universalResolverResolveAbi,args:[(0,Hve.toHex)((0,Vve.packetToBytes)(o)),(0,Bve.encodeFunctionData)({abi:vR.textResolverAbi,functionName:"text",args:[(0,Jve.namehash)(o),i]}),s??[$ve.localBatchGatewayUrl]],functionName:"resolveWithGateways",blockNumber:r,blockTag:n},p=await(0,Gve.getAction)(e,Kve.readContract,"readContract")(l);if(p[0]==="0x")return null;let h=(0,Lve.decodeFunctionResult)({abi:vR.textResolverAbi,functionName:"text",data:p[0]});return h===""?null:h}catch(l){if(a)throw l;if((0,Fve.isNullUniversalResolverError)(l))return null;throw l}}});var v7=g(IR=>{"use strict";Object.defineProperty(IR,"__esModule",{value:!0});IR.getEnsAvatar=Zve;var zve=w7(),Yve=Te(),Xve=AR();async function Zve(e,{blockNumber:t,blockTag:r,assetGatewayUrls:n,name:i,gatewayUrls:o,strict:s,universalResolverAddress:a}){let c=await(0,Yve.getAction)(e,Xve.getEnsText,"getEnsText")({blockNumber:t,blockTag:r,key:"avatar",name:i,universalResolverAddress:a,gatewayUrls:o,strict:s});if(!c)return null;try{return await(0,zve.parseAvatarRecord)(e,{record:c,gatewayUrls:n})}catch{return null}}});var S7=g(PR=>{"use strict";Object.defineProperty(PR,"__esModule",{value:!0});PR.getEnsName=oSe;var Qve=er(),eSe=ms(),tSe=PE(),rSe=Ql(),nSe=Te(),iSe=Cr();async function oSe(e,t){let{address:r,blockNumber:n,blockTag:i,coinType:o=60n,gatewayUrls:s,strict:a}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return(0,eSe.getChainContractAddress)({blockNumber:n,chain:c,contract:"ensUniversalResolver"})})();try{let d={address:u,abi:Qve.universalResolverReverseAbi,args:[r,o,s??[rSe.localBatchGatewayUrl]],functionName:"reverseWithGateways",blockNumber:n,blockTag:i},l=(0,nSe.getAction)(e,iSe.readContract,"readContract"),[m]=await l(d);return m||null}catch(d){if(a)throw d;if((0,tSe.isNullUniversalResolverError)(d))return null;throw d}}});var A7=g(TR=>{"use strict";Object.defineProperty(TR,"__esModule",{value:!0});TR.getEnsResolver=lSe;var sSe=ms(),aSe=W(),cSe=xE(),uSe=Te(),dSe=Cr();async function lSe(e,t){let{blockNumber:r,blockTag:n,name:i}=t,{chain:o}=e,s=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!o)throw new Error("client chain not configured. universalResolverAddress is required.");return(0,sSe.getChainContractAddress)({blockNumber:r,chain:o,contract:"ensUniversalResolver"})})(),a=o?.ensTlds;if(a&&!a.some(u=>i.endsWith(u)))throw new Error(`${i} is not a valid ENS TLD (${a?.join(", ")}) for chain "${o.name}" (id: ${o.id}).`);let[c]=await(0,uSe.getAction)(e,dSe.readContract,"readContract")({address:s,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[(0,aSe.toHex)((0,cSe.packetToBytes)(i))],blockNumber:r,blockTag:n});return c}});var I7=g(xR=>{"use strict";Object.defineProperty(xR,"__esModule",{value:!0});xR.createAccessList=bSe;var fSe=at(),pSe=ye(),mSe=W(),gSe=iE(),hSe=ls(),ySe=Zn(),_Se=Qn();async function bSe(e,t){let{account:r=e.account,blockNumber:n,blockTag:i="latest",blobs:o,data:s,gas:a,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:l,to:m,value:p,...h}=t,y=r?(0,fSe.parseAccount)(r):void 0;try{(0,_Se.assertRequest)(t);let v=(typeof n=="bigint"?(0,mSe.numberToHex)(n):void 0)||i,A=e.chain?.formatters?.transactionRequest?.format,S=(A||ySe.formatTransactionRequest)({...(0,hSe.extract)(h,{format:A}),account:y,blobs:o,data:s,gas:a,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:l,to:m,value:p},"createAccessList"),I=await e.request({method:"eth_createAccessList",params:[S,v]});if(I.error)throw new pSe.BaseError(I.error,{details:I.error});return{accessList:I.accessList,gasUsed:BigInt(I.gasUsed)}}catch(b){throw(0,gSe.getCallError)(b,{...t,account:y,chain:e.chain})}}});var P7=g(OR=>{"use strict";Object.defineProperty(OR,"__esModule",{value:!0});OR.createBlockFilter=wSe;var ESe=km();async function wSe(e){let t=(0,ESe.createFilterRequestScope)(e,{method:"eth_newBlockFilter"}),r=await e.request({method:"eth_newBlockFilter"});return{id:r,request:t(r),type:"block"}}});var CR=g(RR=>{"use strict";Object.defineProperty(RR,"__esModule",{value:!0});RR.createEventFilter=ASe;var vSe=Ca(),T7=W(),SSe=km();async function ASe(e,{address:t,args:r,event:n,events:i,fromBlock:o,strict:s,toBlock:a}={}){let c=i??(n?[n]:void 0),u=(0,SSe.createFilterRequestScope)(e,{method:"eth_newFilter"}),d=[];c&&(d=[c.flatMap(p=>(0,vSe.encodeEventTopics)({abi:[p],eventName:p.name,args:r}))],n&&(d=d[0]));let l=await e.request({method:"eth_newFilter",params:[{address:t,fromBlock:typeof o=="bigint"?(0,T7.numberToHex)(o):o,toBlock:typeof a=="bigint"?(0,T7.numberToHex)(a):a,...d.length?{topics:d}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:o,id:l,request:u(l),strict:!!s,toBlock:a,type:"event"}}});var kR=g(NR=>{"use strict";Object.defineProperty(NR,"__esModule",{value:!0});NR.createPendingTransactionFilter=PSe;var ISe=km();async function PSe(e){let t=(0,ISe.createFilterRequestScope)(e,{method:"eth_newPendingTransactionFilter"}),r=await e.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:t(r),type:"transaction"}}});var O7=g(jR=>{"use strict";Object.defineProperty(jR,"__esModule",{value:!0});jR.getBalance=NSe;var x7=er(),TSe=ei(),xSe=Tr(),OSe=Nu(),RSe=Te(),CSe=Qa();async function NSe(e,{address:t,blockHash:r,blockNumber:n,blockTag:i=e.experimental_blockTag??"latest",requireCanonical:o}){let s=(0,OSe.formatBlockParameter)({blockHash:r,blockNumber:n,blockTag:i,requireCanonical:o});if(e.batch?.multicall&&e.chain?.contracts?.multicall3){let c=e.chain.contracts.multicall3.address,u=(0,xSe.encodeFunctionData)({abi:x7.multicall3Abi,functionName:"getEthBalance",args:[t]}),{data:d}=await(0,RSe.getAction)(e,CSe.call,"call")({to:c,data:u,blockHash:r,blockNumber:n,blockTag:i,requireCanonical:o});return(0,TSe.decodeFunctionResult)({abi:x7.multicall3Abi,functionName:"getEthBalance",args:[t],data:d||"0x"})}let a=await e.request({method:"eth_getBalance",params:[t,s]});return BigInt(a)}});var R7=g(MR=>{"use strict";Object.defineProperty(MR,"__esModule",{value:!0});MR.getBlobBaseFee=kSe;async function kSe(e){let t=await e.request({method:"eth_blobBaseFee"});return BigInt(t)}});var C7=g(qR=>{"use strict";Object.defineProperty(qR,"__esModule",{value:!0});qR.getBlockReceipts=DSe;var jSe=Ym(),MSe=W(),qSe=Bu();async function DSe(e,{blockHash:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest"}={}){let i=r!==void 0?(0,MSe.numberToHex)(r):void 0,o=await e.request({method:"eth_getBlockReceipts",params:[t||i||n]},{dedupe:!!(t||i)});if(!o)throw new jSe.BlockNotFoundError({blockHash:t,blockNumber:r});let s=e.chain?.formatters?.transactionReceipt?.format||qSe.formatTransactionReceipt;return o.map(a=>s(a,"getBlockReceipts"))}});var N7=g(DR=>{"use strict";Object.defineProperty(DR,"__esModule",{value:!0});DR.getBlockTransactionCount=USe;var LSe=pt(),BSe=W();async function USe(e,{blockHash:t,blockNumber:r,blockTag:n="latest"}={}){let i=r!==void 0?(0,BSe.numberToHex)(r):void 0,o;return t?o=await e.request({method:"eth_getBlockTransactionCountByHash",params:[t]},{dedupe:!0}):o=await e.request({method:"eth_getBlockTransactionCountByNumber",params:[i||n]},{dedupe:!!i}),(0,LSe.hexToNumber)(o)}});var RE=g(LR=>{"use strict";Object.defineProperty(LR,"__esModule",{value:!0});LR.getCode=FSe;var HSe=Nu();async function FSe(e,{address:t,blockHash:r,blockNumber:n,blockTag:i="latest",requireCanonical:o}){let s=(0,HSe.formatBlockParameter)({blockHash:r,blockNumber:n,blockTag:i,requireCanonical:o}),a=await e.request({method:"eth_getCode",params:[t,s]},{dedupe:typeof n=="bigint"||r!==void 0});if(a!=="0x")return a}});var k7=g(BR=>{"use strict";Object.defineProperty(BR,"__esModule",{value:!0});BR.getDelegation=KSe;var $Se=Ir(),JSe=ur(),VSe=on(),GSe=RE();async function KSe(e,{address:t,blockNumber:r,blockTag:n="latest"}){let i=await(0,GSe.getCode)(e,{address:t,...r!==void 0?{blockNumber:r}:{blockTag:n}});if(i&&(0,JSe.size)(i)===23&&i.startsWith("0xef0100"))return(0,$Se.getAddress)((0,VSe.slice)(i,3,23))}});var j7=g(CE=>{"use strict";Object.defineProperty(CE,"__esModule",{value:!0});CE.Eip712DomainNotFoundError=void 0;var WSe=ye(),UR=class extends WSe.BaseError{constructor({address:t}){super(`No EIP-712 domain found on contract "${t}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${t}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}};CE.Eip712DomainNotFoundError=UR});var M7=g(HR=>{"use strict";Object.defineProperty(HR,"__esModule",{value:!0});HR.getEip712Domain=ZSe;var zSe=j7(),YSe=Te(),XSe=Cr();async function ZSe(e,t){let{address:r,factory:n,factoryData:i}=t;try{let[o,s,a,c,u,d,l]=await(0,YSe.getAction)(e,XSe.readContract,"readContract")({abi:QSe,address:r,functionName:"eip712Domain",factory:n,factoryData:i});return{domain:{name:s,version:a,chainId:Number(c),verifyingContract:u,salt:d},extensions:l,fields:o}}catch(o){let s=o;throw s.name==="ContractFunctionExecutionError"&&s.cause.name==="ContractFunctionZeroDataError"?new zSe.Eip712DomainNotFoundError({address:r}):s}}var QSe=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}]});var q7=g(FR=>{"use strict";Object.defineProperty(FR,"__esModule",{value:!0});FR.formatFeeHistory=eAe;function eAe(e){return{baseFeePerGas:e.baseFeePerGas.map(t=>BigInt(t)),gasUsedRatio:e.gasUsedRatio,oldestBlock:BigInt(e.oldestBlock),reward:e.reward?.map(t=>t.map(r=>BigInt(r)))}}});var L7=g($R=>{"use strict";Object.defineProperty($R,"__esModule",{value:!0});$R.getFeeHistory=rAe;var D7=W(),tAe=q7();async function rAe(e,{blockCount:t,blockNumber:r,blockTag:n="latest",rewardPercentiles:i}){let o=typeof r=="bigint"?(0,D7.numberToHex)(r):void 0,s=await e.request({method:"eth_feeHistory",params:[(0,D7.numberToHex)(t),o||n,i]},{dedupe:!!o});return(0,tAe.formatFeeHistory)(s)}});var B7=g(JR=>{"use strict";Object.defineProperty(JR,"__esModule",{value:!0});JR.getFilterLogs=oAe;var nAe=Ya(),iAe=xi();async function oAe(e,{filter:t}){let r=t.strict??!1,i=(await t.request({method:"eth_getFilterLogs",params:[t.id]})).map(o=>(0,iAe.formatLog)(o));return t.abi?(0,nAe.parseEventLogs)({abi:t.abi,logs:i,strict:r}):i}});var YR=g(zR=>{"use strict";Object.defineProperty(zR,"__esModule",{value:!0});zR.encodePacked=cAe;var WR=ft(),sAe=Wn(),aAe=Pr(),U7=Nt(),VR=oo(),GR=W(),KR=Om();function cAe(e,t){if(e.length!==t.length)throw new WR.AbiEncodingLengthMismatchError({expectedLength:e.length,givenLength:t.length});let r=[];for(let n=0;n<e.length;n++){let i=e[n],o=t[n];r.push(H7(i,o))}return(0,U7.concatHex)(r)}function H7(e,t,r=!1){if(e==="address"){let s=t;if(!(0,aAe.isAddress)(s))throw new sAe.InvalidAddressError({address:s});return(0,VR.pad)(s.toLowerCase(),{size:r?32:null})}if(e==="string")return(0,GR.stringToHex)(t);if(e==="bytes")return t;if(e==="bool")return(0,VR.pad)((0,GR.boolToHex)(t),{size:r?32:1});let n=e.match(KR.integerRegex);if(n){let[s,a,c="256"]=n,u=Number.parseInt(c,10)/8;return(0,GR.numberToHex)(t,{size:r?32:u,signed:a==="int"})}let i=e.match(KR.bytesRegex);if(i){let[s,a]=i;if(Number.parseInt(a,10)!==(t.length-2)/2)throw new WR.BytesSizeMismatchError({expectedSize:Number.parseInt(a,10),givenSize:(t.length-2)/2});return(0,VR.pad)(t,{dir:"right",size:r?32:null})}let o=e.match(KR.arrayRegex);if(o&&Array.isArray(t)){let[s,a]=o,c=[];for(let u=0;u<t.length;u++)c.push(H7(a,t[u],!0));return c.length===0?"0x":(0,U7.concatHex)(c)}throw new WR.UnsupportedPackedAbiType(e)}});var NE=g(XR=>{"use strict";Object.defineProperty(XR,"__esModule",{value:!0});XR.isBytes=uAe;function uAe(e){return!e||typeof e!="object"||!("BYTES_PER_ELEMENT"in e)?!1:e.BYTES_PER_ELEMENT===1&&e.constructor.name==="Uint8Array"}});var QR=g(Tg=>{"use strict";Object.defineProperty(Tg,"__esModule",{value:!0});Tg.getContractAddress=mAe;Tg.getCreateAddress=$7;Tg.getCreate2Address=J7;var dAe=Nt(),F7=NE(),lAe=oo(),fAe=on(),nf=Je(),pAe=Ml(),ZR=Hr(),kE=Ir();function mAe(e){return e.opcode==="CREATE2"?J7(e):$7(e)}function $7(e){let t=(0,nf.toBytes)((0,kE.getAddress)(e.from)),r=(0,nf.toBytes)(e.nonce);return r[0]===0&&(r=new Uint8Array([])),(0,kE.getAddress)(`0x${(0,ZR.keccak256)((0,pAe.toRlp)([t,r],"bytes")).slice(26)}`)}function J7(e){let t=(0,nf.toBytes)((0,kE.getAddress)(e.from)),r=(0,lAe.pad)((0,F7.isBytes)(e.salt)?e.salt:(0,nf.toBytes)(e.salt),{size:32}),n="bytecodeHash"in e?(0,F7.isBytes)(e.bytecodeHash)?e.bytecodeHash:(0,nf.toBytes)(e.bytecodeHash):(0,ZR.keccak256)(e.bytecode,"bytes");return(0,kE.getAddress)((0,fAe.slice)((0,ZR.keccak256)((0,dAe.concat)([(0,nf.toBytes)("0xff"),t,r,n])),12))}});var xg=g(Fu=>{"use strict";Object.defineProperty(Fu,"__esModule",{value:!0});Fu.assertTransactionEIP7702=bAe;Fu.assertTransactionEIP4844=EAe;Fu.assertTransactionEIP1559=rC;Fu.assertTransactionEIP2930=wAe;Fu.assertTransactionLegacy=vAe;var gAe=bO(),tC=Mb(),ME=Wn(),V7=ye(),eC=AO(),qE=Yl(),jE=Ti(),DE=Pr(),hAe=ur(),yAe=on(),_Ae=pt();function bAe(e){let{authorizationList:t}=e;if(t)for(let r of t){let{chainId:n}=r,i=r.address;if(!(0,DE.isAddress)(i))throw new ME.InvalidAddressError({address:i});if(n<0)throw new qE.InvalidChainIdError({chainId:n})}rC(e)}function EAe(e){let{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new eC.EmptyBlobError;for(let r of t){let n=(0,hAe.size)(r),i=(0,_Ae.hexToNumber)((0,yAe.slice)(r,0,1));if(n!==32)throw new eC.InvalidVersionedHashSizeError({hash:r,size:n});if(i!==gAe.versionedHashVersionKzg)throw new eC.InvalidVersionedHashVersionError({hash:r,version:i})}}rC(e)}function rC(e){let{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:i}=e;if(t<=0)throw new qE.InvalidChainIdError({chainId:t});if(i&&!(0,DE.isAddress)(i))throw new ME.InvalidAddressError({address:i});if(n&&n>tC.maxUint256)throw new jE.FeeCapTooHighError({maxFeePerGas:n});if(r&&n&&r>n)throw new jE.TipAboveFeeCapError({maxFeePerGas:n,maxPriorityFeePerGas:r})}function wAe(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:o}=e;if(t<=0)throw new qE.InvalidChainIdError({chainId:t});if(o&&!(0,DE.isAddress)(o))throw new ME.InvalidAddressError({address:o});if(r||i)throw new V7.BaseError("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>tC.maxUint256)throw new jE.FeeCapTooHighError({maxFeePerGas:n})}function vAe(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:o}=e;if(o&&!(0,DE.isAddress)(o))throw new ME.InvalidAddressError({address:o});if(typeof t<"u"&&t<=0)throw new qE.InvalidChainIdError({chainId:t});if(r||i)throw new V7.BaseError("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>tC.maxUint256)throw new jE.FeeCapTooHighError({maxFeePerGas:n})}});var LE=g(nC=>{"use strict";Object.defineProperty(nC,"__esModule",{value:!0});nC.serializeAccessList=PAe;var SAe=Wn(),AAe=Xt(),IAe=Pr();function PAe(e){if(!e||e.length===0)return[];let t=[];for(let r=0;r<e.length;r++){let{address:n,storageKeys:i}=e[r];for(let o=0;o<i.length;o++)if(i[o].length-2!==64)throw new AAe.InvalidStorageKeySizeError({storageKey:i[o]});if(!(0,IAe.isAddress)(n,{strict:!1}))throw new SAe.InvalidAddressError({address:n});t.push([n,i])}return t}});var Cg=g(FE=>{"use strict";Object.defineProperty(FE,"__esModule",{value:!0});FE.serializeTransaction=jAe;FE.toYParitySignatureArray=Rg;var TAe=Xt(),xAe=iC(),OAe=Qm(),RAe=eg(),CAe=$b(),NAe=rg(),UE=Nt(),BE=ts(),Re=W(),of=Ml(),Og=xg(),kAe=ng(),HE=LE();function jAe(e,t){let r=(0,kAe.getTransactionType)(e);return r==="eip1559"?DAe(e,t):r==="eip2930"?LAe(e,t):r==="eip4844"?qAe(e,t):r==="eip7702"?MAe(e,t):BAe(e,t)}function MAe(e,t){let{authorizationList:r,chainId:n,gas:i,nonce:o,to:s,value:a,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:d,data:l}=e;(0,Og.assertTransactionEIP7702)(e);let m=(0,HE.serializeAccessList)(d),p=(0,xAe.serializeAuthorizationList)(r);return(0,UE.concatHex)(["0x04",(0,of.toRlp)([(0,Re.numberToHex)(n),o?(0,Re.numberToHex)(o):"0x",u?(0,Re.numberToHex)(u):"0x",c?(0,Re.numberToHex)(c):"0x",i?(0,Re.numberToHex)(i):"0x",s??"0x",a?(0,Re.numberToHex)(a):"0x",l??"0x",m,p,...Rg(e,t)])])}function qAe(e,t){let{chainId:r,gas:n,nonce:i,to:o,value:s,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:d,data:l}=e;(0,Og.assertTransactionEIP4844)(e);let m=e.blobVersionedHashes,p=e.sidecars;if(e.blobs&&(typeof m>"u"||typeof p>"u")){let E=typeof e.blobs[0]=="string"?e.blobs:e.blobs.map(T=>(0,Re.bytesToHex)(T)),S=e.kzg,I=(0,OAe.blobsToCommitments)({blobs:E,kzg:S});if(typeof m>"u"&&(m=(0,CAe.commitmentsToVersionedHashes)({commitments:I})),typeof p>"u"){let T=(0,RAe.blobsToProofs)({blobs:E,commitments:I,kzg:S});p=(0,NAe.toBlobSidecars)({blobs:E,commitments:I,proofs:T})}}let h=(0,HE.serializeAccessList)(d),y=[(0,Re.numberToHex)(r),i?(0,Re.numberToHex)(i):"0x",u?(0,Re.numberToHex)(u):"0x",c?(0,Re.numberToHex)(c):"0x",n?(0,Re.numberToHex)(n):"0x",o??"0x",s?(0,Re.numberToHex)(s):"0x",l??"0x",h,a?(0,Re.numberToHex)(a):"0x",m??[],...Rg(e,t)],b=[],v=[],A=[];if(p)for(let E=0;E<p.length;E++){let{blob:S,commitment:I,proof:T}=p[E];b.push(S),v.push(I),A.push(T)}return(0,UE.concatHex)(["0x03",p?(0,of.toRlp)([y,b,v,A]):(0,of.toRlp)(y)])}function DAe(e,t){let{chainId:r,gas:n,nonce:i,to:o,value:s,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:u,data:d}=e;(0,Og.assertTransactionEIP1559)(e);let l=(0,HE.serializeAccessList)(u),m=[(0,Re.numberToHex)(r),i?(0,Re.numberToHex)(i):"0x",c?(0,Re.numberToHex)(c):"0x",a?(0,Re.numberToHex)(a):"0x",n?(0,Re.numberToHex)(n):"0x",o??"0x",s?(0,Re.numberToHex)(s):"0x",d??"0x",l,...Rg(e,t)];return(0,UE.concatHex)(["0x02",(0,of.toRlp)(m)])}function LAe(e,t){let{chainId:r,gas:n,data:i,nonce:o,to:s,value:a,accessList:c,gasPrice:u}=e;(0,Og.assertTransactionEIP2930)(e);let d=(0,HE.serializeAccessList)(c),l=[(0,Re.numberToHex)(r),o?(0,Re.numberToHex)(o):"0x",u?(0,Re.numberToHex)(u):"0x",n?(0,Re.numberToHex)(n):"0x",s??"0x",a?(0,Re.numberToHex)(a):"0x",i??"0x",d,...Rg(e,t)];return(0,UE.concatHex)(["0x01",(0,of.toRlp)(l)])}function BAe(e,t){let{chainId:r=0,gas:n,data:i,nonce:o,to:s,value:a,gasPrice:c}=e;(0,Og.assertTransactionLegacy)(e);let u=[o?(0,Re.numberToHex)(o):"0x",c?(0,Re.numberToHex)(c):"0x",n?(0,Re.numberToHex)(n):"0x",s??"0x",a?(0,Re.numberToHex)(a):"0x",i??"0x"];if(t){let d=(()=>{if(t.v>=35n)return(t.v-35n)/2n>0?t.v:27n+(t.v===35n?0n:1n);if(r>0)return BigInt(r*2)+BigInt(35n+t.v-27n);let p=27n+(t.v===27n?0n:1n);if(t.v!==p)throw new TAe.InvalidLegacyVError({v:t.v});return p})(),l=(0,BE.trim)(t.r),m=(0,BE.trim)(t.s);u=[...u,(0,Re.numberToHex)(d),l==="0x00"?"0x":l,m==="0x00"?"0x":m]}else r>0&&(u=[...u,(0,Re.numberToHex)(r),"0x","0x"]);return(0,of.toRlp)(u)}function Rg(e,t){let r=t??e,{v:n,yParity:i}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof i>"u")return[];let o=(0,BE.trim)(r.r),s=(0,BE.trim)(r.s);return[typeof i=="number"?i?(0,Re.numberToHex)(1):"0x":n===0n?"0x":n===1n?(0,Re.numberToHex)(1):n===27n?"0x":(0,Re.numberToHex)(1),o==="0x00"?"0x":o,s==="0x00"?"0x":s]}});var iC=g(oC=>{"use strict";Object.defineProperty(oC,"__esModule",{value:!0});oC.serializeAuthorizationList=HAe;var G7=W(),UAe=Cg();function HAe(e){if(!e||e.length===0)return[];let t=[];for(let r of e){let{chainId:n,nonce:i,...o}=r,s=r.address;t.push([n?(0,G7.toHex)(n):"0x",s,i?(0,G7.toHex)(i):"0x",...(0,UAe.toYParitySignatureArray)({},o)])}return t}});var aC=g(sC=>{"use strict";Object.defineProperty(sC,"__esModule",{value:!0});sC.verifyAuthorization=VAe;var FAe=Ir(),$Ae=ln(),JAe=ql();async function VAe({address:e,authorization:t,signature:r}){return(0,$Ae.isAddressEqual)((0,FAe.getAddress)(e),await(0,JAe.recoverAuthorizationAddress)({authorization:t,signature:r}))}});var K7=g(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});_s.promiseCache=void 0;_s.withDedupe=KAe;var GAe=Ta();_s.promiseCache=new GAe.LruMap(8192);function KAe(e,{enabled:t=!0,id:r}){if(!t||!r)return e();if(_s.promiseCache.get(r))return _s.promiseCache.get(r);let n=e().finally(()=>_s.promiseCache.delete(r));return _s.promiseCache.set(r,n),n}});var cC=g(JE=>{"use strict";Object.defineProperty(JE,"__esModule",{value:!0});JE.buildRequest=ZAe;JE.shouldRetry=z7;var WAe=ye(),W7=Nn(),te=ss(),$E=Ii(),zAe=K7(),YAe=Sg(),XAe=Mt();function ZAe(e,t={}){return async(r,n={})=>{let{dedupe:i=!1,methods:o,retryDelay:s=150,retryCount:a=3,signal:c,uid:u}={...t,...n},{method:d}=r;if(o?.exclude?.includes(d))throw new te.MethodNotSupportedRpcError(new Error("method not supported"),{method:d});if(o?.include&&!o.include.includes(d))throw new te.MethodNotSupportedRpcError(new Error("method not supported"),{method:d});if(c?.aborted)throw(0,$E.getAbortError)(c);let l=i?QAe(`${u}.${(0,XAe.stringify)(r)}`):void 0;return(0,zAe.withDedupe)(()=>(0,YAe.withRetry)(async()=>{try{return await e(r,c?{signal:c}:void 0)}catch(m){if(c?.aborted)throw(0,$E.getAbortError)(c);if((0,$E.isAbortError)(m))throw m;let p=m;switch(p.code){case te.ParseRpcError.code:throw new te.ParseRpcError(p);case te.InvalidRequestRpcError.code:throw new te.InvalidRequestRpcError(p);case te.MethodNotFoundRpcError.code:throw new te.MethodNotFoundRpcError(p,{method:r.method});case te.InvalidParamsRpcError.code:throw new te.InvalidParamsRpcError(p);case te.InternalRpcError.code:throw new te.InternalRpcError(p);case te.InvalidInputRpcError.code:throw new te.InvalidInputRpcError(p);case te.ResourceNotFoundRpcError.code:throw new te.ResourceNotFoundRpcError(p);case te.ResourceUnavailableRpcError.code:throw new te.ResourceUnavailableRpcError(p);case te.TransactionRejectedRpcError.code:throw new te.TransactionRejectedRpcError(p);case te.MethodNotSupportedRpcError.code:throw new te.MethodNotSupportedRpcError(p,{method:r.method});case te.LimitExceededRpcError.code:throw new te.LimitExceededRpcError(p);case te.JsonRpcVersionUnsupportedError.code:throw new te.JsonRpcVersionUnsupportedError(p);case te.UserRejectedRequestError.code:throw new te.UserRejectedRequestError(p);case te.UnauthorizedProviderError.code:throw new te.UnauthorizedProviderError(p);case te.UnsupportedProviderMethodError.code:throw new te.UnsupportedProviderMethodError(p);case te.ProviderDisconnectedError.code:throw new te.ProviderDisconnectedError(p);case te.ChainDisconnectedError.code:throw new te.ChainDisconnectedError(p);case te.SwitchChainError.code:throw new te.SwitchChainError(p);case te.UnsupportedNonOptionalCapabilityError.code:throw new te.UnsupportedNonOptionalCapabilityError(p);case te.UnsupportedChainIdError.code:throw new te.UnsupportedChainIdError(p);case te.DuplicateIdError.code:throw new te.DuplicateIdError(p);case te.UnknownBundleIdError.code:throw new te.UnknownBundleIdError(p);case te.BundleTooLargeError.code:throw new te.BundleTooLargeError(p);case te.AtomicReadyWalletRejectedUpgradeError.code:throw new te.AtomicReadyWalletRejectedUpgradeError(p);case te.AtomicityNotSupportedError.code:throw new te.AtomicityNotSupportedError(p);case 5e3:throw new te.UserRejectedRequestError(p);case te.WalletConnectSessionSettlementError.code:throw new te.WalletConnectSessionSettlementError(p);default:throw m instanceof WAe.BaseError?m:new te.UnknownRpcError(p)}}},{delay:({count:m,error:p})=>{if(p&&p instanceof W7.HttpRequestError){let h=p?.headers?.get("Retry-After");if(h?.match(/\d/))return Number.parseInt(h,10)*1e3}return~~(1<<m)*s},retryCount:a,signal:c,shouldRetry:({error:m})=>z7(m)}),{enabled:i,id:l})}}function z7(e){return(0,$E.isAbortError)(e)?!1:"code"in e&&typeof e.code=="number"?e.code===-1||e.code===te.LimitExceededRpcError.code||e.code===te.InternalRpcError.code||e.code===429:e instanceof W7.HttpRequestError&&e.status?e.status===403||e.status===408||e.status===413||e.status===429||e.status===500||e.status===502||e.status===503||e.status===504:!0}function QAe(e,t=0){let r=3735928559^t,n=1103547991^t;for(let i=0;i<e.length;i++){let o=e.charCodeAt(i);r=Math.imul(r^o,2654435761),n=Math.imul(n^o,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>16,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>16,3266489909),(4294967296*(2097151&n)+(r>>>0)).toString(36)}});var lC=g(dC=>{"use strict";Object.defineProperty(dC,"__esModule",{value:!0});dC.ccipReadTunnel=aIe;var uC=er(),eIe=jm(),tIe=Nn(),rIe=Ol(),nIe=ei(),iIe=Tr(),oIe=gg(),sIe=Ql();function aIe({batchGateways:e,ccipRequest:t=oIe.ccipRequest}){return{async request({data:r,sender:n,urls:i}){if(i.includes(sIe.localBatchGatewayUrl))return t({data:r,sender:n,urls:e});{let[o,s]=(0,nIe.decodeFunctionResult)({abi:uC.batchGatewayAbi,functionName:"query",data:await t({data:(0,iIe.encodeFunctionData)({abi:uC.batchGatewayAbi,functionName:"query",args:[[{sender:n,data:r,urls:i}]]}),sender:n,urls:e})});if(o[0]){let a;try{let c=(0,rIe.decodeErrorResult)({abi:[...uC.batchGatewayAbi,eIe.solidityError],data:s[0]});if(c.errorName==="HttpError")a=new tIe.HttpRequestError({body:{message:c.args[1]},status:c.args[0],url:i.join(" | ")});else{let u=c.args[0];u&&(a=new Error(u))}}catch{}throw a??new Error("An unknown error occurred.")}return s[0]}}}}});var fC=g(VE=>{"use strict";Object.defineProperty(VE,"__esModule",{value:!0});VE.defineChain=cIe;VE.extendSchema=uIe;function cIe(e){let t={formatters:void 0,fees:void 0,serializers:void 0,...e};function r(n){return i=>{let o=typeof i=="function"?i(n):i,s={...n,...o};return Object.assign(s,{extend:r(s)})}}return Object.assign(t,{extend:r(t)})}function uIe(){return{}}});var mC=g(pC=>{"use strict";Object.defineProperty(pC,"__esModule",{value:!0});pC.extractChain=dIe;function dIe({chains:e,id:t}){return e.find(r=>r.id===t)}});var Y7=g(gC=>{"use strict";Object.defineProperty(gC,"__esModule",{value:!0});gC.filterChains=lIe;function lIe(e){let{chains:t,sort:r,testnet:n,token:i}=e,o=Array.isArray(t)?t:Object.values(t),s=[];for(let a of o)fIe(a)&&(i&&!(a.id in i.addresses)||n===!0&&a.testnet!==!0||n===!1&&a.testnet===!0||s.push(a));return r==="id"&&s.sort((a,c)=>a.id-c.id),r==="name"&&s.sort((a,c)=>a.name.localeCompare(c.name)),s}function fIe(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="number"&&"name"in e&&typeof e.name=="string"&&"nativeCurrency"in e&&"rpcUrls"in e}});var KE=g(hC=>{"use strict";Object.defineProperty(hC,"__esModule",{value:!0});hC.fromRlp=hIe;var pIe=ye(),GE=_u(),mIe=Pl(),gIe=Je(),X7=W(),Z7=1024;function hIe(e,t="hex"){let r=(()=>{if(typeof e=="string"){if(e.length>3&&e.length%2!==0)throw new GE.InvalidHexValueError(e);return(0,gIe.hexToBytes)(e)}return e})(),n=(0,mIe.createCursor)(r,{recursiveReadLimit:Number.POSITIVE_INFINITY}),i=eV(n,t);if(n.position<n.bytes.length)throw new GE.RlpTrailingBytesError({count:n.bytes.length-n.position});return i}function eV(e,t="hex",r=0){if(r>=Z7)throw new GE.RlpDepthLimitExceededError({limit:Z7});if(e.bytes.length===0)return t==="hex"?(0,X7.bytesToHex)(e.bytes):e.bytes;let n=e.readByte();if(n<128&&e.decrementPosition(1),n<192){let o=Q7(e,n,128),s=e.readBytes(o);return t==="hex"?(0,X7.bytesToHex)(s):s}let i=Q7(e,n,192);return yIe(e,i,t,r+1)}function Q7(e,t,r){if(r===128&&t<128)return 1;if(t<=r+55)return t-r;if(t===r+55+1)return e.readUint8();if(t===r+55+2)return e.readUint16();if(t===r+55+3)return e.readUint24();if(t===r+55+4)return e.readUint32();throw new pIe.BaseError("Invalid RLP prefix")}function yIe(e,t,r,n){let i=e.position,o=[];for(;e.position-i<t;)o.push(eV(e,r,n));if(e.position-i!==t)throw new GE.RlpListBoundaryExceededError({consumed:e.position-i,declared:t});return o}});var WE=g(yC=>{"use strict";Object.defineProperty(yC,"__esModule",{value:!0});yC.isHash=EIe;var _Ie=Sr(),bIe=ur();function EIe(e){return(0,_Ie.isHex)(e)&&(0,bIe.size)(e)===32}});var aV=g(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.ripemd160=mn.RIPEMD160=mn.md5=mn.MD5=mn.sha1=mn.SHA1=void 0;var $u=l2(),fr=is(),sf=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),tc=new Uint32Array(80),XE=class extends $u.HashMD{constructor(){super(64,20,8,!1),this.A=sf[0]|0,this.B=sf[1]|0,this.C=sf[2]|0,this.D=sf[3]|0,this.E=sf[4]|0}get(){let{A:t,B:r,C:n,D:i,E:o}=this;return[t,r,n,i,o]}set(t,r,n,i,o){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0}process(t,r){for(let c=0;c<16;c++,r+=4)tc[c]=t.getUint32(r,!1);for(let c=16;c<80;c++)tc[c]=(0,fr.rotl)(tc[c-3]^tc[c-8]^tc[c-14]^tc[c-16],1);let{A:n,B:i,C:o,D:s,E:a}=this;for(let c=0;c<80;c++){let u,d;c<20?(u=(0,$u.Chi)(i,o,s),d=1518500249):c<40?(u=i^o^s,d=1859775393):c<60?(u=(0,$u.Maj)(i,o,s),d=2400959708):(u=i^o^s,d=3395469782);let l=(0,fr.rotl)(n,5)+u+a+d+tc[c]|0;a=s,s=o,o=(0,fr.rotl)(i,30),i=n,n=l}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,this.set(n,i,o,s,a)}roundClean(){(0,fr.clean)(tc)}destroy(){this.set(0,0,0,0,0),(0,fr.clean)(this.buffer)}};mn.SHA1=XE;mn.sha1=(0,fr.createHasher)(()=>new XE);var wIe=Math.pow(2,32),vIe=Array.from({length:64},(e,t)=>Math.floor(wIe*Math.abs(Math.sin(t+1)))),zE=sf.slice(0,4),_C=new Uint32Array(16),ZE=class extends $u.HashMD{constructor(){super(64,16,8,!0),this.A=zE[0]|0,this.B=zE[1]|0,this.C=zE[2]|0,this.D=zE[3]|0}get(){let{A:t,B:r,C:n,D:i}=this;return[t,r,n,i]}set(t,r,n,i){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0}process(t,r){for(let a=0;a<16;a++,r+=4)_C[a]=t.getUint32(r,!0);let{A:n,B:i,C:o,D:s}=this;for(let a=0;a<64;a++){let c,u,d;a<16?(c=(0,$u.Chi)(i,o,s),u=a,d=[7,12,17,22]):a<32?(c=(0,$u.Chi)(s,i,o),u=(5*a+1)%16,d=[5,9,14,20]):a<48?(c=i^o^s,u=(3*a+5)%16,d=[4,11,16,23]):(c=o^(i|~s),u=7*a%16,d=[6,10,15,21]),c=c+n+vIe[a]+_C[u],n=s,s=o,o=i,i=i+(0,fr.rotl)(c,d[a%4])}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,this.set(n,i,o,s)}roundClean(){(0,fr.clean)(_C)}destroy(){this.set(0,0,0,0),(0,fr.clean)(this.buffer)}};mn.MD5=ZE;mn.md5=(0,fr.createHasher)(()=>new ZE);var SIe=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),rV=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),AIe=rV.map(e=>(9*e+5)%16),nV=(()=>{let r=[[rV],[AIe]];for(let n=0;n<4;n++)for(let i of r)i.push(i[n].map(o=>SIe[o]));return r})(),iV=nV[0],oV=nV[1],sV=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(e=>Uint8Array.from(e)),IIe=iV.map((e,t)=>e.map(r=>sV[t][r])),PIe=oV.map((e,t)=>e.map(r=>sV[t][r])),TIe=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),xIe=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function tV(e,t,r,n){return e===0?t^r^n:e===1?t&r|~t&n:e===2?(t|~r)^n:e===3?t&n|r&~n:t^(r|~n)}var YE=new Uint32Array(16),QE=class extends $u.HashMD{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){let{h0:t,h1:r,h2:n,h3:i,h4:o}=this;return[t,r,n,i,o]}set(t,r,n,i,o){this.h0=t|0,this.h1=r|0,this.h2=n|0,this.h3=i|0,this.h4=o|0}process(t,r){for(let p=0;p<16;p++,r+=4)YE[p]=t.getUint32(r,!0);let n=this.h0|0,i=n,o=this.h1|0,s=o,a=this.h2|0,c=a,u=this.h3|0,d=u,l=this.h4|0,m=l;for(let p=0;p<5;p++){let h=4-p,y=TIe[p],b=xIe[p],v=iV[p],A=oV[p],E=IIe[p],S=PIe[p];for(let I=0;I<16;I++){let T=(0,fr.rotl)(n+tV(p,o,a,u)+YE[v[I]]+y,E[I])+l|0;n=l,l=u,u=(0,fr.rotl)(a,10)|0,a=o,o=T}for(let I=0;I<16;I++){let T=(0,fr.rotl)(i+tV(h,s,c,d)+YE[A[I]]+b,S[I])+m|0;i=m,m=d,d=(0,fr.rotl)(c,10)|0,c=s,s=T}}this.set(this.h1+a+d|0,this.h2+u+m|0,this.h3+l+i|0,this.h4+n+s|0,this.h0+o+c|0)}roundClean(){(0,fr.clean)(YE)}destroy(){this.destroyed=!0,(0,fr.clean)(this.buffer),this.set(0,0,0,0,0)}};mn.RIPEMD160=QE;mn.ripemd160=(0,fr.createHasher)(()=>new QE)});var bC=g(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});af.ripemd160=af.RIPEMD160=void 0;var cV=aV();af.RIPEMD160=cV.RIPEMD160;af.ripemd160=cV.ripemd160});var wC=g(EC=>{"use strict";Object.defineProperty(EC,"__esModule",{value:!0});EC.ripemd160=kIe;var OIe=bC(),RIe=Sr(),CIe=Je(),NIe=W();function kIe(e,t){let r=t||"hex",n=(0,OIe.ripemd160)((0,RIe.isHex)(e,{strict:!1})?(0,CIe.toBytes)(e):e);return r==="bytes"?n:(0,NIe.toHex)(n)}});var vC=g(ew=>{"use strict";Object.defineProperty(ew,"__esModule",{value:!0});ew.toEventHash=void 0;var jIe=Pm();Object.defineProperty(ew,"toEventHash",{enumerable:!0,get:function(){return jIe.toSignatureHash}})});var SC=g(tw=>{"use strict";Object.defineProperty(tw,"__esModule",{value:!0});tw.toEventSignature=void 0;var MIe=f_();Object.defineProperty(tw,"toEventSignature",{enumerable:!0,get:function(){return MIe.toSignature}})});var AC=g(rw=>{"use strict";Object.defineProperty(rw,"__esModule",{value:!0});rw.toFunctionHash=void 0;var qIe=Pm();Object.defineProperty(rw,"toFunctionHash",{enumerable:!0,get:function(){return qIe.toSignatureHash}})});var IC=g(nw=>{"use strict";Object.defineProperty(nw,"__esModule",{value:!0});nw.toFunctionSignature=void 0;var DIe=f_();Object.defineProperty(nw,"toFunctionSignature",{enumerable:!0,get:function(){return DIe.toSignature}})});var PC=g(cf=>{"use strict";Object.defineProperty(cf,"__esModule",{value:!0});cf.nonceManager=void 0;cf.createNonceManager=uV;cf.jsonRpc=dV;var LIe=Zm(),BIe=Ta();function uV(e){let{source:t}=e,r=new Map,n=new BIe.LruMap(8192),i=new Map,o=({address:a,chainId:c})=>`${a}.${c}`,s=a=>{r.delete(a),i.delete(a)};return{async consume({address:a,chainId:c,client:u}){let d=o({address:a,chainId:c}),l=this.get({address:a,chainId:c,client:u});this.increment({address:a,chainId:c});let m=await l;return await t.set({address:a,chainId:c},m),n.set(d,m),m},async increment({address:a,chainId:c}){let u=o({address:a,chainId:c}),d=r.get(u)??0;r.set(u,d+1)},async get({address:a,chainId:c,client:u}){let d=o({address:a,chainId:c}),l=i.get(d);return l||(l=(async()=>{try{let p=await t.get({address:a,chainId:c,client:u}),h=n.get(d)??0;return h>0&&p<=h?h+1:(n.delete(d),p)}finally{s(d)}})(),i.set(d,l)),(r.get(d)??0)+await l},reset({address:a,chainId:c}){let u=o({address:a,chainId:c});n.delete(u),s(u)}}}function dV(){return{async get(e){let{address:t,client:r}=e;return(0,LIe.getTransactionCount)(r,{address:t,blockTag:"pending"})},set(){}}}cf.nonceManager=uV({source:dV()})});var iw=g(TC=>{"use strict";Object.defineProperty(TC,"__esModule",{value:!0});TC.withTimeout=HIe;var UIe=Ii();function HIe(e,{errorInstance:t=new Error("timed out"),timeout:r,signal:n}){return new Promise((i,o)=>{(async()=>{let s,a=new AbortController;try{r>0&&(s=setTimeout(()=>{n?a.abort():o(t)},r)),i(await e({signal:a?.signal||null}))}catch(c){if(a?.signal.aborted&&(0,UIe.isAbortError)(c)){o(t);return}o(c)}finally{clearTimeout(s)}})()})}});var xC=g(ow=>{"use strict";Object.defineProperty(ow,"__esModule",{value:!0});ow.idCache=void 0;function FIe(){return{current:0,take(){return this.current++},reset(){this.current=0}}}ow.idCache=FIe()});var aw=g(sw=>{"use strict";Object.defineProperty(sw,"__esModule",{value:!0});sw.getHttpRpcClient=VIe;sw.parseUrl=pV;var bs=Nn(),lV=Ii(),$Ie=iw(),OC=Mt(),fV=xC(),JIe=10485760;function VIe(e,t={}){let{url:r,headers:n}=pV(e);return{async request(i){let{body:o,fetchFn:s=t.fetchFn??fetch,maxResponseBodySize:a=t.maxResponseBodySize??JIe,onRequest:c=t.onRequest,onResponse:u=t.onResponse,timeout:d=t.timeout??1e4}=i,l={...t.fetchOptions??{},...i.fetchOptions??{}},{headers:m,method:p,signal:h}=l;try{let y=await(0,$Ie.withTimeout)(async({signal:A})=>{let E={...l,body:Array.isArray(o)?(0,OC.stringify)(o.map(x=>({jsonrpc:"2.0",id:x.id??fV.idCache.take(),...x}))):(0,OC.stringify)({jsonrpc:"2.0",id:o.id??fV.idCache.take(),...o}),headers:{...n,"Content-Type":"application/json",...m},method:p||"POST",signal:h||(d>0?A:null)},S=new Request(r,E),I=await c?.(S,E)??{...E,url:r};return await s(I.url??r,I)},{errorInstance:new bs.TimeoutError({body:o,url:r}),timeout:d,signal:!0});u&&await u(y);let b,v=await GIe(y,{maxResponseBodySize:a});if(y.headers.get("Content-Type")?.startsWith("application/json"))b=JSON.parse(v);else{b=v;try{b=JSON.parse(b||"{}")}catch(A){if(y.ok)throw A;b={error:b}}}if(!y.ok){if(typeof b.error?.code=="number"&&typeof b.error?.message=="string")return b;throw new bs.HttpRequestError({body:o,details:(0,OC.stringify)(b.error)||y.statusText,headers:y.headers,status:y.status,url:r})}return b}catch(y){throw h?.aborted?(0,lV.getAbortError)(h):(0,lV.isAbortError)(y)||y instanceof bs.HttpRequestError||y instanceof bs.ResponseBodyTooLargeError||y instanceof bs.TimeoutError?y:new bs.HttpRequestError({body:o,cause:y,url:r})}}}}async function GIe(e,{maxResponseBodySize:t}){if(t===!1)return e.text();let r=e.headers.get("Content-Length");if(r){let a=Number(r);if(a>t)throw new bs.ResponseBodyTooLargeError({maxSize:t,size:a})}if(!e.body){let a=await e.text(),c=new TextEncoder().encode(a).length;if(c>t)throw new bs.ResponseBodyTooLargeError({maxSize:t,size:c});return a}let n=e.body.getReader(),i=new TextDecoder,o="",s=0;try{for(;;){let{done:a,value:c}=await n.read();if(a)break;if(s+=c.byteLength,s>t)throw await n.cancel(),new bs.ResponseBodyTooLargeError({maxSize:t,size:s});o+=i.decode(c,{stream:!0})}return o+=i.decode(),o}finally{n.releaseLock()}}function pV(e){try{let t=new URL(e),r=(()=>{if(t.username){let n=`${decodeURIComponent(t.username)}:${decodeURIComponent(t.password)}`;return t.username="",t.password="",{url:t.toString(),headers:{Authorization:`Basic ${btoa(n)}`}}}})();return{url:t.toString(),...r}}catch{return{url:e}}}});var CC=g(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.socketClientCache=void 0;rc.getSocketRpcClient=YIe;var RC=Nn(),KIe=pg(),WIe=iw(),zIe=xC();rc.socketClientCache=new Map;async function YIe(e){let{getSocket:t,keepAlive:r=!0,key:n="socket",reconnect:i=!0,url:o}=e,{interval:s=3e4}=typeof r=="object"?r:{},{attempts:a=5,delay:c=2e3}=typeof i=="object"?i:{},u=JSON.stringify({keepAlive:r,key:n,url:o,reconnect:i}),d=rc.socketClientCache.get(u);if(d)return d;let l=0,{schedule:m}=(0,KIe.createBatchScheduler)({id:u,fn:async()=>{let y=new Map,b=new Map,v,A,E,S,I=!1,T=!1;function x(){if(i&&!T&&l<a){if(I)return;I=!0,l++,A?.close(),S=setTimeout(async()=>{if(S=void 0,T){I=!1;return}await C().catch(console.error),I=!1},c)}else y.clear(),b.clear()}async function C(){let k=await t({onClose(){for(let N of y.values())N.onError?.(new RC.SocketClosedError({url:o}));for(let N of b.values())N.onError?.(new RC.SocketClosedError({url:o}));x()},onError(N){v=N;for(let M of y.values())M.onError?.(v);for(let M of b.values())M.onError?.(v);x()},onOpen(){v=void 0,l=0},onResponse(N){let M=N.method==="eth_subscription",j=M?N.params.subscription:N.id,D=M?b:y,U=D.get(j);U&&U.onResponse(N),M||D.delete(j)}});if(T)return k.close(),k;if(A=k,r&&(E&&clearInterval(E),E=setInterval(()=>A.ping?.(),s)),i&&b.size>0){let N=b.entries();for(let[M,{onResponse:j,body:D,onError:U}]of N)D&&(b.delete(M),d?.request({body:D,onResponse:j,onError:U}))}return k}return await C(),v=void 0,d={close(){T=!0,E&&clearInterval(E),S&&(clearTimeout(S),S=void 0,I=!1),A.close(),rc.socketClientCache.delete(u)},get socket(){return A},request({body:k,onError:N,onResponse:M}){v&&N&&N(v);let j=k.id??zIe.idCache.take(),D=U=>{typeof U.id=="number"&&j!==U.id||(k.method==="eth_subscribe"&&typeof U.result=="string"&&b.set(U.result,{onResponse:D,onError:N,body:k}),M(U))};k.method==="eth_unsubscribe"&&b.delete(k.params?.[0]),y.set(j,{onResponse:D,onError:N});try{A.request({body:{jsonrpc:"2.0",id:j,...k}})}catch(U){N?.(U)}},requestAsync({body:k,timeout:N=1e4}){return(0,WIe.withTimeout)(()=>new Promise((M,j)=>this.request({body:k,onError:j,onResponse:M})),{errorInstance:new RC.TimeoutError({body:k,url:o}),timeout:N})},requests:y,subscriptions:b,url:o},rc.socketClientCache.set(u,d),[d]}}),[p,[h]]=await m();return h}});var Es=g((dit,hV)=>{"use strict";var mV=["nodebuffer","arraybuffer","fragments"],gV=typeof Blob<"u";gV&&mV.push("blob");hV.exports={BINARY_TYPES:mV,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:gV,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ng=g((lit,cw)=>{"use strict";var{EMPTY_BUFFER:XIe}=Es(),NC=Buffer[Symbol.species];function ZIe(e,t){if(e.length===0)return XIe;if(e.length===1)return e[0];let r=Buffer.allocUnsafe(t),n=0;for(let i=0;i<e.length;i++){let o=e[i];r.set(o,n),n+=o.length}return n<t?new NC(r.buffer,r.byteOffset,n):r}function yV(e,t,r,n,i){for(let o=0;o<i;o++)r[n+o]=e[o]^t[o&3]}function _V(e,t){for(let r=0;r<e.length;r++)e[r]^=t[r&3]}function QIe(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function kC(e){if(kC.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new NC(e):ArrayBuffer.isView(e)?t=new NC(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),kC.readOnly=!1),t}cw.exports={concat:ZIe,mask:yV,toArrayBuffer:QIe,toBuffer:kC,unmask:_V};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=require("bufferutil");cw.exports.mask=function(t,r,n,i,o){o<48?yV(t,r,n,i,o):e.mask(t,r,n,i,o)},cw.exports.unmask=function(t,r){t.length<32?_V(t,r):e.unmask(t,r)}}catch{}});var wV=g((fit,EV)=>{"use strict";var bV=Symbol("kDone"),jC=Symbol("kRun"),MC=class{constructor(t){this[bV]=()=>{this.pending--,this[jC]()},this.concurrency=t||1/0,this.jobs=[],this.pending=0}add(t){this.jobs.push(t),this[jC]()}[jC](){if(this.pending!==this.concurrency&&this.jobs.length){let t=this.jobs.shift();this.pending++,t(this[bV])}}};EV.exports=MC});var lf=g((pit,IV)=>{"use strict";var kg=require("zlib"),vV=Ng(),ePe=wV(),{kStatusCode:SV}=Es(),tPe=Buffer[Symbol.species],rPe=Buffer.from([0,0,255,255]),dw=Symbol("permessage-deflate"),ws=Symbol("total-length"),uf=Symbol("callback"),nc=Symbol("buffers"),df=Symbol("error"),uw,qC=class{constructor(t){if(this._options=t||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!uw){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;uw=new ePe(r)}}static get extensionName(){return"permessage-deflate"}offer(){let t={};return this._options.serverNoContextTakeover&&(t.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(t.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(t.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?t.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(t.client_max_window_bits=!0),t}accept(t){return t=this.normalizeParams(t),this.params=this._isServer?this.acceptAsServer(t):this.acceptAsClient(t),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let t=this._deflate[uf];this._deflate.close(),this._deflate=null,t&&t(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(t){let r=this._options,n=t.find(i=>!(r.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>i.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(n.server_no_context_takeover=!0),r.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(n.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?n.client_max_window_bits=r.clientMaxWindowBits:(n.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(t){let r=t[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(t){return t.forEach(r=>{Object.keys(r).forEach(n=>{let i=r[n];if(i.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(i=i[0],n==="client_max_window_bits"){if(i!==!0){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else if(n==="server_max_window_bits"){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=o}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else throw new Error(`Unknown parameter "${n}"`);r[n]=i})}),t}decompress(t,r,n){uw.add(i=>{this._decompress(t,r,(o,s)=>{i(),n(o,s)})})}compress(t,r,n){uw.add(i=>{this._compress(t,r,(o,s)=>{i(),n(o,s)})})}_decompress(t,r,n){let i=this._isServer?"client":"server";if(!this._inflate){let o=`${i}_max_window_bits`,s=typeof this.params[o]!="number"?kg.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=kg.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[dw]=this,this._inflate[ws]=0,this._inflate[nc]=[],this._inflate.on("error",iPe),this._inflate.on("data",AV)}this._inflate[uf]=n,this._inflate.write(t),r&&this._inflate.write(rPe),this._inflate.flush(()=>{let o=this._inflate[df];if(o){this._inflate.close(),this._inflate=null,n(o);return}let s=vV.concat(this._inflate[nc],this._inflate[ws]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ws]=0,this._inflate[nc]=[],r&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),n(null,s)})}_compress(t,r,n){let i=this._isServer?"server":"client";if(!this._deflate){let o=`${i}_max_window_bits`,s=typeof this.params[o]!="number"?kg.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=kg.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[ws]=0,this._deflate[nc]=[],this._deflate.on("data",nPe)}this._deflate[uf]=n,this._deflate.write(t),this._deflate.flush(kg.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=vV.concat(this._deflate[nc],this._deflate[ws]);r&&(o=new tPe(o.buffer,o.byteOffset,o.length-4)),this._deflate[uf]=null,this._deflate[ws]=0,this._deflate[nc]=[],r&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),n(null,o)})}};IV.exports=qC;function nPe(e){this[nc].push(e),this[ws]+=e.length}function AV(e){if(this[ws]+=e.length,this[dw]._maxPayload<1||this[ws]<=this[dw]._maxPayload){this[nc].push(e);return}this[df]=new RangeError("Max payload size exceeded"),this[df].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[df][SV]=1009,this.removeListener("data",AV),this.reset()}function iPe(e){if(this[dw]._inflate=null,this[df]){this[uf](this[df]);return}e[SV]=1007,this[uf](e)}});var ff=g((mit,lw)=>{"use strict";var{isUtf8:PV}=require("buffer"),{hasBlob:oPe}=Es(),sPe=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function aPe(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function DC(e){let t=e.length,r=0;for(;r<t;)if((e[r]&128)===0)r++;else if((e[r]&224)===192){if(r+1===t||(e[r+1]&192)!==128||(e[r]&254)===192)return!1;r+=2}else if((e[r]&240)===224){if(r+2>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||e[r]===224&&(e[r+1]&224)===128||e[r]===237&&(e[r+1]&224)===160)return!1;r+=3}else if((e[r]&248)===240){if(r+3>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||(e[r+3]&192)!==128||e[r]===240&&(e[r+1]&240)===128||e[r]===244&&e[r+1]>143||e[r]>244)return!1;r+=4}else return!1;return!0}function cPe(e){return oPe&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}lw.exports={isBlob:cPe,isValidStatusCode:aPe,isValidUTF8:DC,tokenChars:sPe};if(PV)lw.exports.isValidUTF8=function(e){return e.length<24?DC(e):PV(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=require("utf-8-validate");lw.exports.isValidUTF8=function(t){return t.length<32?DC(t):e(t)}}catch{}});var FC=g((git,kV)=>{"use strict";var{Writable:uPe}=require("stream"),TV=lf(),{BINARY_TYPES:dPe,EMPTY_BUFFER:xV,kStatusCode:lPe,kWebSocket:fPe}=Es(),{concat:LC,toArrayBuffer:pPe,unmask:mPe}=Ng(),{isValidStatusCode:gPe,isValidUTF8:OV}=ff(),fw=Buffer[Symbol.species],ii=0,RV=1,CV=2,NV=3,BC=4,UC=5,pw=6,HC=class extends uPe{constructor(t={}){super(),this._allowSynchronousEvents=t.allowSynchronousEvents!==void 0?t.allowSynchronousEvents:!0,this._binaryType=t.binaryType||dPe[0],this._extensions=t.extensions||{},this._isServer=!!t.isServer,this._maxBufferedChunks=t.maxBufferedChunks|0,this._maxFragments=t.maxFragments|0,this._maxPayload=t.maxPayload|0,this._skipUTF8Validation=!!t.skipUTF8Validation,this[fPe]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=ii}_write(t,r,n){if(this._opcode===8&&this._state==ii)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=t.length,this._buffers.push(t),this.startLoop(n)}consume(t){if(this._bufferedBytes-=t,t===this._buffers[0].length)return this._buffers.shift();if(t<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new fw(n.buffer,n.byteOffset+t,n.length-t),new fw(n.buffer,n.byteOffset,t)}let r=Buffer.allocUnsafe(t);do{let n=this._buffers[0],i=r.length-t;t>=n.length?r.set(this._buffers.shift(),i):(r.set(new Uint8Array(n.buffer,n.byteOffset,t),i),this._buffers[0]=new fw(n.buffer,n.byteOffset+t,n.length-t)),t-=n.length}while(t>0);return r}startLoop(t){this._loop=!0;do switch(this._state){case ii:this.getInfo(t);break;case RV:this.getPayloadLength16(t);break;case CV:this.getPayloadLength64(t);break;case NV:this.getMask();break;case BC:this.getData(t);break;case UC:case pw:this._loop=!1;return}while(this._loop);this._errored||t()}getInfo(t){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");t(i);return}let n=(r[0]&64)===64;if(n&&!this._extensions[TV.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(i);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");t(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(i);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");t(i);return}if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");t(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");t(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");t(i);return}this._payloadLength===126?this._state=RV:this._payloadLength===127?this._state=CV:this.haveLength(t)}getPayloadLength16(t){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(t)}getPayloadLength64(t){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),n=r.readUInt32BE(0);if(n>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");t(i);return}this._payloadLength=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(t)}haveLength(t){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(r);return}this._masked?this._state=NV:this._state=BC}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=BC}getData(t){let r=xV;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&mPe(r,this._mask)}if(this._opcode>7){this.controlMessage(r,t);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");t(n);return}if(this._compressed){this._state=UC,this.decompress(r,t);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(t)}decompress(t,r){this._extensions[TV.extensionName].decompress(t,this._fin,(i,o)=>{if(i)return r(i);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(s);return}this._fragments.push(o)}this.dataMessage(r),this._state===ii&&this.startLoop(r)})}dataMessage(t){if(!this._fin){this._state=ii;return}let r=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=LC(n,r):this._binaryType==="arraybuffer"?i=pPe(LC(n,r)):this._binaryType==="blob"?i=new Blob(n):i=n,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=ii):(this._state=pw,setImmediate(()=>{this.emit("message",i,!0),this._state=ii,this.startLoop(t)}))}else{let i=LC(n,r);if(!this._skipUTF8Validation&&!OV(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(o);return}this._state===UC||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=ii):(this._state=pw,setImmediate(()=>{this.emit("message",i,!1),this._state=ii,this.startLoop(t)}))}}controlMessage(t,r){if(this._opcode===8){if(t.length===0)this._loop=!1,this.emit("conclude",1005,xV),this.end();else{let n=t.readUInt16BE(0);if(!gPe(n)){let o=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(o);return}let i=new fw(t.buffer,t.byteOffset+2,t.length-2);if(!this._skipUTF8Validation&&!OV(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(o);return}this._loop=!1,this.emit("conclude",n,i),this.end()}this._state=ii;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",t),this._state=ii):(this._state=pw,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",t),this._state=ii,this.startLoop(r)}))}createError(t,r,n,i,o){this._loop=!1,this._errored=!0;let s=new t(n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(s,this.createError),s.code=o,s[lPe]=i,s}};kV.exports=HC});var VC=g((yit,qV)=>{"use strict";var{Duplex:hit}=require("stream"),{randomFillSync:hPe}=require("crypto"),{types:{isUint8Array:yPe}}=require("util"),jV=lf(),{EMPTY_BUFFER:_Pe,kWebSocket:bPe,NOOP:EPe}=Es(),{isBlob:pf,isValidStatusCode:wPe}=ff(),{mask:MV,toBuffer:Ju}=Ng(),oi=Symbol("kByteLength"),vPe=Buffer.alloc(4),mw=8*1024,Vu,mf=mw,Oi=0,SPe=1,APe=2,$C=class e{constructor(t,r,n){this._extensions=r||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=t,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Oi,this.onerror=EPe,this[bPe]=void 0}static frame(t,r){let n,i=!1,o=2,s=!1;r.mask&&(n=r.maskBuffer||vPe,r.generateMask?r.generateMask(n):(mf===mw&&(Vu===void 0&&(Vu=Buffer.alloc(mw)),hPe(Vu,0,mw),mf=0),n[0]=Vu[mf++],n[1]=Vu[mf++],n[2]=Vu[mf++],n[3]=Vu[mf++]),s=(n[0]|n[1]|n[2]|n[3])===0,o=6);let a;typeof t=="string"?(!r.mask||s)&&r[oi]!==void 0?a=r[oi]:(t=Buffer.from(t),a=t.length):(a=t.length,i=r.mask&&r.readOnly&&!s);let c=a;a>=65536?(o+=8,c=127):a>125&&(o+=2,c=126);let u=Buffer.allocUnsafe(i?a+o:o);return u[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(u[0]|=64),u[1]=c,c===126?u.writeUInt16BE(a,2):c===127&&(u[2]=u[3]=0,u.writeUIntBE(a,4,6)),r.mask?(u[1]|=128,u[o-4]=n[0],u[o-3]=n[1],u[o-2]=n[2],u[o-1]=n[3],s?[u,t]:i?(MV(t,n,u,o,a),[u]):(MV(t,n,t,0,a),[u,t])):[u,t]}close(t,r,n,i){let o;if(t===void 0)o=_Pe;else{if(typeof t!="number"||!wPe(t))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(o=Buffer.allocUnsafe(2+a),o.writeUInt16BE(t,0),typeof r=="string")o.write(r,2);else if(yPe(r))o.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[oi]:o.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Oi?this.enqueue([this.dispatch,o,!1,s,i]):this.sendFrame(e.frame(o,s),i)}ping(t,r,n){let i,o;if(typeof t=="string"?(i=Buffer.byteLength(t),o=!1):pf(t)?(i=t.size,o=!1):(t=Ju(t),i=t.length,o=Ju.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[oi]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};pf(t)?this._state!==Oi?this.enqueue([this.getBlobData,t,!1,s,n]):this.getBlobData(t,!1,s,n):this._state!==Oi?this.enqueue([this.dispatch,t,!1,s,n]):this.sendFrame(e.frame(t,s),n)}pong(t,r,n){let i,o;if(typeof t=="string"?(i=Buffer.byteLength(t),o=!1):pf(t)?(i=t.size,o=!1):(t=Ju(t),i=t.length,o=Ju.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[oi]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};pf(t)?this._state!==Oi?this.enqueue([this.getBlobData,t,!1,s,n]):this.getBlobData(t,!1,s,n):this._state!==Oi?this.enqueue([this.dispatch,t,!1,s,n]):this.sendFrame(e.frame(t,s),n)}send(t,r,n){let i=this._extensions[jV.extensionName],o=r.binary?2:1,s=r.compress,a,c;typeof t=="string"?(a=Buffer.byteLength(t),c=!1):pf(t)?(a=t.size,c=!1):(t=Ju(t),a=t.length,c=Ju.readOnly),this._firstFragment?(this._firstFragment=!1,s&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=i._threshold),this._compress=s):(s=!1,o=0),r.fin&&(this._firstFragment=!0);let u={[oi]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:s};pf(t)?this._state!==Oi?this.enqueue([this.getBlobData,t,this._compress,u,n]):this.getBlobData(t,this._compress,u,n):this._state!==Oi?this.enqueue([this.dispatch,t,this._compress,u,n]):this.dispatch(t,this._compress,u,n)}getBlobData(t,r,n,i){this._bufferedBytes+=n[oi],this._state=APe,t.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(JC,this,a,i);return}this._bufferedBytes-=n[oi];let s=Ju(o);r?this.dispatch(s,r,n,i):(this._state=Oi,this.sendFrame(e.frame(s,n),i),this.dequeue())}).catch(o=>{process.nextTick(IPe,this,o,i)})}dispatch(t,r,n,i){if(!r){this.sendFrame(e.frame(t,n),i);return}let o=this._extensions[jV.extensionName];this._bufferedBytes+=n[oi],this._state=SPe,o.compress(t,n.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");JC(this,c,i);return}this._bufferedBytes-=n[oi],this._state=Oi,n.readOnly=!1,this.sendFrame(e.frame(a,n),i),this.dequeue()})}dequeue(){for(;this._state===Oi&&this._queue.length;){let t=this._queue.shift();this._bufferedBytes-=t[3][oi],Reflect.apply(t[0],this,t.slice(1))}}enqueue(t){this._bufferedBytes+=t[3][oi],this._queue.push(t)}sendFrame(t,r){t.length===2?(this._socket.cork(),this._socket.write(t[0]),this._socket.write(t[1],r),this._socket.uncork()):this._socket.write(t[0],r)}};qV.exports=$C;function JC(e,t,r){typeof r=="function"&&r(t);for(let n=0;n<e._queue.length;n++){let i=e._queue[n],o=i[i.length-1];typeof o=="function"&&o(t)}}function IPe(e,t,r){JC(e,t,r),e.onerror(t)}});var VV=g((_it,JV)=>{"use strict";var{kForOnEventAttribute:jg,kListener:GC}=Es(),DV=Symbol("kCode"),LV=Symbol("kData"),BV=Symbol("kError"),UV=Symbol("kMessage"),HV=Symbol("kReason"),gf=Symbol("kTarget"),FV=Symbol("kType"),$V=Symbol("kWasClean"),vs=class{constructor(t){this[gf]=null,this[FV]=t}get target(){return this[gf]}get type(){return this[FV]}};Object.defineProperty(vs.prototype,"target",{enumerable:!0});Object.defineProperty(vs.prototype,"type",{enumerable:!0});var Gu=class extends vs{constructor(t,r={}){super(t),this[DV]=r.code===void 0?0:r.code,this[HV]=r.reason===void 0?"":r.reason,this[$V]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[DV]}get reason(){return this[HV]}get wasClean(){return this[$V]}};Object.defineProperty(Gu.prototype,"code",{enumerable:!0});Object.defineProperty(Gu.prototype,"reason",{enumerable:!0});Object.defineProperty(Gu.prototype,"wasClean",{enumerable:!0});var hf=class extends vs{constructor(t,r={}){super(t),this[BV]=r.error===void 0?null:r.error,this[UV]=r.message===void 0?"":r.message}get error(){return this[BV]}get message(){return this[UV]}};Object.defineProperty(hf.prototype,"error",{enumerable:!0});Object.defineProperty(hf.prototype,"message",{enumerable:!0});var Mg=class extends vs{constructor(t,r={}){super(t),this[LV]=r.data===void 0?null:r.data}get data(){return this[LV]}};Object.defineProperty(Mg.prototype,"data",{enumerable:!0});var PPe={addEventListener(e,t,r={}){for(let i of this.listeners(e))if(!r[jg]&&i[GC]===t&&!i[jg])return;let n;if(e==="message")n=function(o,s){let a=new Mg("message",{data:s?o:o.toString()});a[gf]=this,gw(t,this,a)};else if(e==="close")n=function(o,s){let a=new Gu("close",{code:o,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[gf]=this,gw(t,this,a)};else if(e==="error")n=function(o){let s=new hf("error",{error:o,message:o.message});s[gf]=this,gw(t,this,s)};else if(e==="open")n=function(){let o=new vs("open");o[gf]=this,gw(t,this,o)};else return;n[jg]=!!r[jg],n[GC]=t,r.once?this.once(e,n):this.on(e,n)},removeEventListener(e,t){for(let r of this.listeners(e))if(r[GC]===t&&!r[jg]){this.removeListener(e,r);break}}};JV.exports={CloseEvent:Gu,ErrorEvent:hf,Event:vs,EventTarget:PPe,MessageEvent:Mg};function gw(e,t,r){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}});var hw=g((bit,GV)=>{"use strict";var{tokenChars:qg}=ff();function Eo(e,t,r){e[t]===void 0?e[t]=[r]:e[t].push(r)}function TPe(e){let t=Object.create(null),r=Object.create(null),n=!1,i=!1,o=!1,s,a,c=-1,u=-1,d=-1,l=0;for(;l<e.length;l++)if(u=e.charCodeAt(l),s===void 0)if(d===-1&&qg[u]===1)c===-1&&(c=l);else if(l!==0&&(u===32||u===9))d===-1&&c!==-1&&(d=l);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${l}`);d===-1&&(d=l);let p=e.slice(c,d);u===44?(Eo(t,p,r),r=Object.create(null)):s=p,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${l}`);else if(a===void 0)if(d===-1&&qg[u]===1)c===-1&&(c=l);else if(u===32||u===9)d===-1&&c!==-1&&(d=l);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${l}`);d===-1&&(d=l),Eo(r,e.slice(c,d),!0),u===44&&(Eo(t,s,r),r=Object.create(null),s=void 0),c=d=-1}else if(u===61&&c!==-1&&d===-1)a=e.slice(c,l),c=d=-1;else throw new SyntaxError(`Unexpected character at index ${l}`);else if(i){if(qg[u]!==1)throw new SyntaxError(`Unexpected character at index ${l}`);c===-1?c=l:n||(n=!0),i=!1}else if(o)if(qg[u]===1)c===-1&&(c=l);else if(u===34&&c!==-1)o=!1,d=l;else if(u===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${l}`);else if(u===34&&e.charCodeAt(l-1)===61)o=!0;else if(d===-1&&qg[u]===1)c===-1&&(c=l);else if(c!==-1&&(u===32||u===9))d===-1&&(d=l);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${l}`);d===-1&&(d=l);let p=e.slice(c,d);n&&(p=p.replace(/\\/g,""),n=!1),Eo(r,a,p),u===44&&(Eo(t,s,r),r=Object.create(null),s=void 0),a=void 0,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${l}`);if(c===-1||o||u===32||u===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=l);let m=e.slice(c,d);return s===void 0?Eo(t,m,r):(a===void 0?Eo(r,m,!0):n?Eo(r,a,m.replace(/\\/g,"")):Eo(r,a,m),Eo(t,s,r)),t}function xPe(e){return Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(n=>[t].concat(Object.keys(n).map(i=>{let o=n[i];return Array.isArray(o)||(o=[o]),o.map(s=>s===!0?i:`${i}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}GV.exports={format:xPe,parse:TPe}});var Ew=g((vit,iG)=>{"use strict";var OPe=require("events"),RPe=require("https"),CPe=require("http"),zV=require("net"),NPe=require("tls"),{randomBytes:kPe,createHash:jPe}=require("crypto"),{Duplex:Eit,Readable:wit}=require("stream"),{URL:KC}=require("url"),ic=lf(),MPe=FC(),qPe=VC(),{isBlob:DPe}=ff(),{BINARY_TYPES:KV,CLOSE_TIMEOUT:LPe,EMPTY_BUFFER:yw,GUID:BPe,kForOnEventAttribute:WC,kListener:UPe,kStatusCode:HPe,kWebSocket:tr,NOOP:YV}=Es(),{EventTarget:{addEventListener:FPe,removeEventListener:$Pe}}=VV(),{format:JPe,parse:VPe}=hw(),{toBuffer:GPe}=Ng(),XV=Symbol("kAborted"),zC=[8,13],Ss=["CONNECTING","OPEN","CLOSING","CLOSED"],KPe=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,gt=class e extends OPe{constructor(t,r,n){super(),this._binaryType=KV[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=yw,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,r=[]):r=[r]),ZV(this,t,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(t){KV.includes(t)&&(this._binaryType=t,this._receiver&&(this._receiver._binaryType=t))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,r,n){let i=new MPe({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),o=new qPe(t,this._extensions,n.generateMask);this._receiver=i,this._sender=o,this._socket=t,i[tr]=this,o[tr]=this,t[tr]=this,i.on("conclude",YPe),i.on("drain",XPe),i.on("error",ZPe),i.on("message",QPe),i.on("ping",eTe),i.on("pong",tTe),o.onerror=rTe,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),r.length>0&&t.unshift(r),t.on("close",tG),t.on("data",bw),t.on("end",rG),t.on("error",nG),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[ic.extensionName]&&this._extensions[ic.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,r){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){Mn(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,r,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),eG(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(n=t,t=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){YC(this,t,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(t||yw,r,n)}pong(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(n=t,t=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){YC(this,t,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(t||yw,r,n)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){YC(this,t,n);return}let i={binary:typeof t!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[ic.extensionName]||(i.compress=!1),this._sender.send(t||yw,i,n)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){Mn(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(gt,"CONNECTING",{enumerable:!0,value:Ss.indexOf("CONNECTING")});Object.defineProperty(gt.prototype,"CONNECTING",{enumerable:!0,value:Ss.indexOf("CONNECTING")});Object.defineProperty(gt,"OPEN",{enumerable:!0,value:Ss.indexOf("OPEN")});Object.defineProperty(gt.prototype,"OPEN",{enumerable:!0,value:Ss.indexOf("OPEN")});Object.defineProperty(gt,"CLOSING",{enumerable:!0,value:Ss.indexOf("CLOSING")});Object.defineProperty(gt.prototype,"CLOSING",{enumerable:!0,value:Ss.indexOf("CLOSING")});Object.defineProperty(gt,"CLOSED",{enumerable:!0,value:Ss.indexOf("CLOSED")});Object.defineProperty(gt.prototype,"CLOSED",{enumerable:!0,value:Ss.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(gt.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach(e=>{Object.defineProperty(gt.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[WC])return t[UPe];return null},set(t){for(let r of this.listeners(e))if(r[WC]){this.removeListener(e,r);break}typeof t=="function"&&this.addEventListener(e,t,{[WC]:!0})}})});gt.prototype.addEventListener=FPe;gt.prototype.removeEventListener=$Pe;iG.exports=gt;function ZV(e,t,r,n){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:LPe,protocolVersion:zC[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=i.autoPong,e._closeTimeout=i.closeTimeout,!zC.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${zC.join(", ")})`);let o;if(t instanceof KC)o=t;else try{o=new KC(t)}catch{throw new SyntaxError(`Invalid URL: ${t}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),e._url=o.href;let s=o.protocol==="wss:",a=o.protocol==="ws+unix:",c;if(o.protocol!=="ws:"&&!s&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!o.pathname?c="The URL's pathname is empty":o.hash&&(c="The URL contains a fragment identifier"),c){let y=new SyntaxError(c);if(e._redirects===0)throw y;_w(e,y);return}let u=s?443:80,d=kPe(16).toString("base64"),l=s?RPe.request:CPe.request,m=new Set,p;if(i.createConnection=i.createConnection||(s?zPe:WPe),i.defaultPort=i.defaultPort||u,i.port=o.port||u,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(p=new ic({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=JPe({[ic.extensionName]:p.offer()})),r.length){for(let y of r){if(typeof y!="string"||!KPe.test(y)||m.has(y))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(y)}i.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(o.username||o.password)&&(i.auth=`${o.username}:${o.password}`),a){let y=i.path.split(":");i.socketPath=y[0],i.path=y[1]}let h;if(i.followRedirects){if(e._redirects===0){e._originalIpc=a,e._originalSecure=s,e._originalHostOrSocketPath=a?i.socketPath:o.host;let y=n&&n.headers;if(n={...n,headers:{}},y)for(let[b,v]of Object.entries(y))n.headers[b.toLowerCase()]=v}else if(e.listenerCount("redirect")===0){let y=a?e._originalIpc?i.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:o.host===e._originalHostOrSocketPath;(!y||e._originalSecure&&!s)&&(delete i.headers.authorization,delete i.headers.cookie,y||delete i.headers.host,i.auth=void 0)}i.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),h=e._req=l(i),e._redirects&&e.emit("redirect",e.url,h)}else h=e._req=l(i);i.timeout&&h.on("timeout",()=>{Mn(e,h,"Opening handshake has timed out")}),h.on("error",y=>{h===null||h[XV]||(h=e._req=null,_w(e,y))}),h.on("response",y=>{let b=y.headers.location,v=y.statusCode;if(b&&i.followRedirects&&v>=300&&v<400){if(++e._redirects>i.maxRedirects){Mn(e,h,"Maximum redirects exceeded");return}h.abort();let A;try{A=new KC(b,t)}catch{let S=new SyntaxError(`Invalid URL: ${b}`);_w(e,S);return}ZV(e,A,r,n)}else e.emit("unexpected-response",h,y)||Mn(e,h,`Unexpected server response: ${y.statusCode}`)}),h.on("upgrade",(y,b,v)=>{if(e.emit("upgrade",y),e.readyState!==gt.CONNECTING)return;h=e._req=null;let A=y.headers.upgrade;if(A===void 0||A.toLowerCase()!=="websocket"){Mn(e,b,"Invalid Upgrade header");return}let E=jPe("sha1").update(d+BPe).digest("base64");if(y.headers["sec-websocket-accept"]!==E){Mn(e,b,"Invalid Sec-WebSocket-Accept header");return}let S=y.headers["sec-websocket-protocol"],I;if(S!==void 0?m.size?m.has(S)||(I="Server sent an invalid subprotocol"):I="Server sent a subprotocol but none was requested":m.size&&(I="Server sent no subprotocol"),I){Mn(e,b,I);return}S&&(e._protocol=S);let T=y.headers["sec-websocket-extensions"];if(T!==void 0){if(!p){Mn(e,b,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let x;try{x=VPe(T)}catch{Mn(e,b,"Invalid Sec-WebSocket-Extensions header");return}let C=Object.keys(x);if(C.length!==1||C[0]!==ic.extensionName){Mn(e,b,"Server indicated an extension that was not requested");return}try{p.accept(x[ic.extensionName])}catch{Mn(e,b,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[ic.extensionName]=p}e.setSocket(b,v,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(h,e):h.end()}function _w(e,t){e._readyState=gt.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function WPe(e){return e.path=e.socketPath,zV.connect(e)}function zPe(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=zV.isIP(e.host)?"":e.host),NPe.connect(e)}function Mn(e,t,r){e._readyState=gt.CLOSING;let n=new Error(r);Error.captureStackTrace(n,Mn),t.setHeader?(t[XV]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(_w,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function YC(e,t,r){if(t){let n=DPe(t)?t.size:GPe(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${e.readyState} (${Ss[e.readyState]})`);process.nextTick(r,n)}}function YPe(e,t){let r=this[tr];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,r._socket[tr]!==void 0&&(r._socket.removeListener("data",bw),process.nextTick(QV,r._socket),e===1005?r.close():r.close(e,t))}function XPe(){let e=this[tr];e.isPaused||e._socket.resume()}function ZPe(e){let t=this[tr];t._socket[tr]!==void 0&&(t._socket.removeListener("data",bw),process.nextTick(QV,t._socket),t.close(e[HPe])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function WV(){this[tr].emitClose()}function QPe(e,t){this[tr].emit("message",e,t)}function eTe(e){let t=this[tr];t._autoPong&&t.pong(e,!this._isServer,YV),t.emit("ping",e)}function tTe(e){this[tr].emit("pong",e)}function QV(e){e.resume()}function rTe(e){let t=this[tr];t.readyState!==gt.CLOSED&&(t.readyState===gt.OPEN&&(t._readyState=gt.CLOSING,eG(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function eG(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function tG(){let e=this[tr];if(this.removeListener("close",tG),this.removeListener("data",bw),this.removeListener("end",rG),e._readyState=gt.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[tr]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",WV),e._receiver.on("finish",WV))}function bw(e){this[tr]._receiver.write(e)||this.pause()}function rG(){let e=this[tr];e._readyState=gt.CLOSING,e._receiver.end(),this.end()}function nG(){let e=this[tr];this.removeListener("error",nG),this.on("error",YV),e&&(e._readyState=gt.CLOSING,this.destroy())}});var cG=g((Ait,aG)=>{"use strict";var Sit=Ew(),{Duplex:nTe}=require("stream");function oG(e){e.emit("close")}function iTe(){!this.destroyed&&this._writableState.finished&&this.destroy()}function sG(e){this.removeListener("error",sG),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}function oTe(e,t){let r=!0,n=new nTe({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(o,s){let a=!s&&n._readableState.objectMode?o.toString():o;n.push(a)||e.pause()}),e.once("error",function(o){n.destroyed||(r=!1,n.destroy(o))}),e.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(i,o){if(e.readyState===e.CLOSED){o(i),process.nextTick(oG,n);return}let s=!1;e.once("error",function(c){s=!0,o(c)}),e.once("close",function(){s||o(i),process.nextTick(oG,n)}),r&&e.terminate()},n._final=function(i){if(e.readyState===e.CONNECTING){e.once("open",function(){n._final(i)});return}e._socket!==null&&(e._socket._writableState.finished?(i(),n._readableState.endEmitted&&n.destroy()):(e._socket.once("finish",function(){i()}),e.close()))},n._read=function(){e.isPaused&&e.resume()},n._write=function(i,o,s){if(e.readyState===e.CONNECTING){e.once("open",function(){n._write(i,o,s)});return}e.send(i,s)},n.on("end",iTe),n.on("error",sG),n}aG.exports=oTe});var XC=g((Iit,uG)=>{"use strict";var{tokenChars:sTe}=ff();function aTe(e){let t=new Set,r=-1,n=-1,i=0;for(i;i<e.length;i++){let s=e.charCodeAt(i);if(n===-1&&sTe[s]===1)r===-1&&(r=i);else if(i!==0&&(s===32||s===9))n===-1&&r!==-1&&(n=i);else if(s===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${i}`);n===-1&&(n=i);let a=e.slice(r,n);if(t.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);t.add(a),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let o=e.slice(r,i);if(t.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}uG.exports={parse:aTe}});var hG=g((Tit,gG)=>{"use strict";var cTe=require("events"),ww=require("http"),{Duplex:Pit}=require("stream"),{createHash:uTe}=require("crypto"),dG=hw(),Ku=lf(),dTe=XC(),lTe=Ew(),{CLOSE_TIMEOUT:fTe,GUID:pTe,kWebSocket:mTe}=Es(),gTe=/^[+/0-9A-Za-z]{22}==$/,lG=0,fG=1,mG=2,ZC=class extends cTe{constructor(t,r){if(super(),t={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:fTe,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:lTe,...t},t.port==null&&!t.server&&!t.noServer||t.port!=null&&(t.server||t.noServer)||t.server&&t.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(t.port!=null?(this._server=ww.createServer((n,i)=>{let o=ww.STATUS_CODES[426];i.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),i.end(o)}),this._server.listen(t.port,t.host,t.backlog,r)):t.server&&(this._server=t.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=hTe(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,o,s)=>{this.handleUpgrade(i,o,s,n)}})}t.perMessageDeflate===!0&&(t.perMessageDeflate={}),t.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=t,this._state=lG}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(t){if(this._state===mG){t&&this.once("close",()=>{t(new Error("The server is not running"))}),process.nextTick(Dg,this);return}if(t&&this.once("close",t),this._state!==fG)if(this._state=fG,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Dg,this):process.nextTick(Dg,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Dg(this)})}}shouldHandle(t){if(this.options.path){let r=t.url.indexOf("?");if((r!==-1?t.url.slice(0,r):t.url)!==this.options.path)return!1}return!0}handleUpgrade(t,r,n,i){r.on("error",pG);let o=t.headers["sec-websocket-key"],s=t.headers.upgrade,a=+t.headers["sec-websocket-version"];if(t.method!=="GET"){Wu(this,t,r,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){Wu(this,t,r,400,"Invalid Upgrade header");return}if(o===void 0||!gTe.test(o)){Wu(this,t,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Wu(this,t,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(t)){Lg(r,400);return}let c=t.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=dTe.parse(c)}catch{Wu(this,t,r,400,"Invalid Sec-WebSocket-Protocol header");return}let d=t.headers["sec-websocket-extensions"],l={};if(this.options.perMessageDeflate&&d!==void 0){let m=new Ku({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=dG.parse(d);p[Ku.extensionName]&&(m.accept(p[Ku.extensionName]),l[Ku.extensionName]=m)}catch{Wu(this,t,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:t.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(t.socket.authorized||t.socket.encrypted),req:t};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(p,h,y,b)=>{if(!p)return Lg(r,h||401,y,b);this.completeUpgrade(l,o,u,t,r,n,i)});return}if(!this.options.verifyClient(m))return Lg(r,401)}this.completeUpgrade(l,o,u,t,r,n,i)}completeUpgrade(t,r,n,i,o,s,a){if(!o.readable||!o.writable)return o.destroy();if(o[mTe])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>lG)return Lg(o,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${uTe("sha1").update(r+pTe).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let l=this.options.handleProtocols?this.options.handleProtocols(n,i):n.values().next().value;l&&(u.push(`Sec-WebSocket-Protocol: ${l}`),d._protocol=l)}if(t[Ku.extensionName]){let l=t[Ku.extensionName].params,m=dG.format({[Ku.extensionName]:[l]});u.push(`Sec-WebSocket-Extensions: ${m}`),d._extensions=t}this.emit("headers",u,i),o.write(u.concat(`\r
53
+ `).join(`\r
54
+ `)),o.removeListener("error",pG),d.setSocket(o,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Dg,this)})),a(d,i)}};gG.exports=ZC;function hTe(e,t){for(let r of Object.keys(t))e.on(r,t[r]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function Dg(e){e._state=mG,e.emit("close")}function pG(){this.destroy()}function Lg(e,t,r,n){r=r||ww.STATUS_CODES[t],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${ww.STATUS_CODES[t]}\r
55
+ `+Object.keys(n).map(i=>`${i}: ${n[i]}`).join(`\r
56
+ `)+`\r
57
+ \r
58
+ `+r)}function Wu(e,t,r,n,i,o){if(e.listenerCount("wsClientError")){let s=new Error(i);Error.captureStackTrace(s,Wu),e.emit("wsClientError",s,r,t)}else Lg(r,n,i,o)}});var bG=g((xit,_G)=>{"use strict";var yTe=cG(),_Te=hw(),bTe=lf(),ETe=FC(),wTe=VC(),vTe=XC(),Ri=Ew(),yG=hG();Ri.createWebSocketStream=yTe;Ri.extension=_Te;Ri.PerMessageDeflate=bTe;Ri.Receiver=ETe;Ri.Sender=wTe;Ri.Server=yG;Ri.subprotocol=vTe;Ri.WebSocket=Ri;Ri.WebSocketServer=yG;_G.exports=Ri});var EG=g(vw=>{"use strict";Object.defineProperty(vw,"__esModule",{value:!0});vw.getNativeWebSocket=void 0;function STe(){if(typeof WebSocket<"u")return WebSocket;if(typeof global.WebSocket<"u")return global.WebSocket;if(typeof window.WebSocket<"u")return window.WebSocket;if(typeof self.WebSocket<"u")return self.WebSocket;throw new Error("`WebSocket` is not supported in this environment")}vw.getNativeWebSocket=STe});var wG=g(Sw=>{"use strict";Object.defineProperty(Sw,"__esModule",{value:!0});Sw.WebSocket=void 0;var QC=bG(),ATe=EG();Sw.WebSocket=(()=>{try{return(0,ATe.getNativeWebSocket)()}catch{return QC.WebSocket?QC.WebSocket:QC}})()});var Iw=g(eN=>{"use strict";Object.defineProperty(eN,"__esModule",{value:!0});eN.getWebSocketRpcClient=PTe;var Aw=Nn(),ITe=CC();async function PTe(e,t={}){let{keepAlive:r,reconnect:n}=t;return(0,ITe.getSocketRpcClient)({async getSocket({onClose:i,onError:o,onOpen:s,onResponse:a}){let c=await Promise.resolve().then(()=>wG()).then(p=>p.WebSocket),u=new c(e);function d(){u.removeEventListener("close",d),u.removeEventListener("message",l),u.removeEventListener("error",o),u.removeEventListener("open",s),i()}function l({data:p}){if(!(typeof p=="string"&&p.trim().length===0))try{let h=JSON.parse(p);a(h)}catch(h){o(h)}}u.addEventListener("close",d),u.addEventListener("message",l),u.addEventListener("error",o),u.addEventListener("open",s),u.readyState===c.CONNECTING&&await new Promise((p,h)=>{u&&(u.onopen=p,u.onerror=h)});let{close:m}=u;return Object.assign(u,{close(){m.bind(u)(),d()},ping(){try{if(u.readyState===u.CLOSED||u.readyState===u.CLOSING)throw new Aw.WebSocketRequestError({url:u.url,cause:new Aw.SocketClosedError({url:u.url})});let p={jsonrpc:"2.0",id:null,method:"net_version",params:[]};u.send(JSON.stringify(p))}catch(p){o(p)}},request({body:p}){if(u.readyState===u.CLOSED||u.readyState===u.CLOSING)throw new Aw.WebSocketRequestError({body:p,url:u.url,cause:new Aw.SocketClosedError({url:u.url})});return u.send(JSON.stringify(p))}})},keepAlive:r,reconnect:n,url:e})}});var tN=g(Bg=>{"use strict";Object.defineProperty(Bg,"__esModule",{value:!0});Bg.rpc=void 0;Bg.getSocket=CTe;var TTe=aw(),xTe=Iw();function OTe(e,{body:t,onError:r,onResponse:n}){return e.request({body:t,onError:r,onResponse:n}),e}async function RTe(e,{body:t,timeout:r=1e4}){return e.requestAsync({body:t,timeout:r})}async function CTe(e){let t=await(0,xTe.getWebSocketRpcClient)(e);return Object.assign(t.socket,{requests:t.requests,subscriptions:t.subscriptions})}Bg.rpc={http(e,t){return(0,TTe.getHttpRpcClient)(e).request(t)},webSocket:OTe,webSocketAsync:RTe}});var rN=g(Pw=>{"use strict";Object.defineProperty(Pw,"__esModule",{value:!0});Pw.presignMessagePrefix=void 0;Pw.presignMessagePrefix=`Ethereum Signed Message:
59
+ `});var oN=g(iN=>{"use strict";Object.defineProperty(iN,"__esModule",{value:!0});iN.toPrefixedMessage=MTe;var NTe=rN(),kTe=Nt(),jTe=ur(),nN=W();function MTe(e){let t=typeof e=="string"?(0,nN.stringToHex)(e):typeof e.raw=="string"?e.raw:(0,nN.bytesToHex)(e.raw),r=(0,nN.stringToHex)(`${NTe.presignMessagePrefix}${(0,jTe.size)(t)}`);return(0,kTe.concat)([r,t])}});var yf=g(sN=>{"use strict";Object.defineProperty(sN,"__esModule",{value:!0});sN.hashMessage=LTe;var qTe=Hr(),DTe=oN();function LTe(e,t){return(0,qTe.keccak256)((0,DTe.toPrefixedMessage)(e),t)}});var lN=g(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});wo.InvalidTypedDataTypeError=wo.InvalidStructTypeError=wo.InvalidPrimaryTypeError=wo.InvalidDomainError=void 0;var BTe=Mt(),Tw=ye(),aN=class extends Tw.BaseError{constructor({domain:t}){super(`Invalid domain "${(0,BTe.stringify)(t)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}};wo.InvalidDomainError=aN;var cN=class extends Tw.BaseError{constructor({primaryType:t,types:r}){super(`Invalid primary type \`${t}\` must be one of \`${JSON.stringify(Object.keys(r))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."]})}};wo.InvalidPrimaryTypeError=cN;var uN=class extends Tw.BaseError{constructor({type:t}){super(`Struct type "${t}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}};wo.InvalidStructTypeError=uN;var dN=class extends Tw.BaseError{constructor({type:t}){let r=t.replace(/^(u?int)/,"$&256");super(`Type "${t}" is not a valid EIP-712 type.`,{metaMessages:[`Use "${r}" instead.`],name:"InvalidTypedDataTypeError"})}};wo.InvalidTypedDataTypeError=dN});var Ug=g(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});_f.serializeTypedData=GTe;_f.validateTypedData=KTe;_f.getTypesForEIP712Domain=AG;_f.domainSeparator=WTe;var UTe=ft(),HTe=Wn(),xw=lN(),FTe=Pr(),vG=ur(),$Te=W(),SG=Om(),JTe=bf(),VTe=Mt();function GTe(e){let{domain:t,message:r,primaryType:n,types:i}=e,o=(c,u)=>{let d={...u};for(let l of c){let{name:m,type:p}=l;p==="address"&&(d[m]=d[m].toLowerCase())}return d},s=i.EIP712Domain?t?o(i.EIP712Domain,t):{}:{},a=(()=>{if(n!=="EIP712Domain")return o(i[n],r)})();return(0,VTe.stringify)({domain:s,message:a,primaryType:n,types:i})}function KTe(e){let{domain:t,message:r,primaryType:n,types:i}=e,o=(s,a)=>{for(let c of s){let{name:u,type:d}=c,l=a[u],m=d.replace(/(\[[0-9]*\])+$/,"");if(m==="int"||m==="uint")throw new xw.InvalidTypedDataTypeError({type:d});let p=d.match(SG.integerRegex);if(p&&(typeof l=="number"||typeof l=="bigint")){let[b,v,A]=p;(0,$Te.numberToHex)(l,{signed:v==="int",size:Number.parseInt(A,10)/8})}if(d==="address"&&typeof l=="string"&&!(0,FTe.isAddress)(l))throw new HTe.InvalidAddressError({address:l});let h=d.match(SG.bytesRegex);if(h){let[b,v]=h;if(v&&(0,vG.size)(l)!==Number.parseInt(v,10))throw new UTe.BytesSizeMismatchError({expectedSize:Number.parseInt(v,10),givenSize:(0,vG.size)(l)})}let y=i[d];y&&(zTe(d),o(y,l))}};if(i.EIP712Domain&&t){if(typeof t!="object")throw new xw.InvalidDomainError({domain:t});o(i.EIP712Domain,t)}if(n!=="EIP712Domain")if(i[n])o(i[n],r);else throw new xw.InvalidPrimaryTypeError({primaryType:n,types:i})}function AG({domain:e}){return[typeof e?.name=="string"&&{name:"name",type:"string"},e?.version&&{name:"version",type:"string"},(typeof e?.chainId=="number"||typeof e?.chainId=="bigint")&&{name:"chainId",type:"uint256"},e?.verifyingContract&&{name:"verifyingContract",type:"address"},e?.salt&&{name:"salt",type:"bytes32"}].filter(Boolean)}function WTe({domain:e}){return(0,JTe.hashDomain)({domain:e,types:{EIP712Domain:AG({domain:e})}})}function zTe(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new xw.InvalidStructTypeError({type:e})}});var bf=g(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});Ef.hashTypedData=XTe;Ef.hashDomain=xG;Ef.hashStruct=fN;Ef.encodeType=RG;var PG=zn(),YTe=Nt(),TG=W(),zu=Hr(),IG=Ug();function XTe(e){let{domain:t={},message:r,primaryType:n}=e,i={EIP712Domain:(0,IG.getTypesForEIP712Domain)({domain:t}),...e.types};(0,IG.validateTypedData)({domain:t,message:r,primaryType:n,types:i});let o=["0x1901"];return t&&o.push(xG({domain:t,types:i})),n!=="EIP712Domain"&&o.push(fN({data:r,primaryType:n,types:i})),(0,zu.keccak256)((0,YTe.concat)(o))}function xG({domain:e,types:t}){return fN({data:e,primaryType:"EIP712Domain",types:t})}function fN({data:e,primaryType:t,types:r}){let n=OG({data:e,primaryType:t,types:r});return(0,zu.keccak256)(n)}function OG({data:e,primaryType:t,types:r}){let n=[{type:"bytes32"}],i=[ZTe({primaryType:t,types:r})];for(let o of r[t]){let[s,a]=NG({types:r,name:o.name,type:o.type,value:e[o.name]});n.push(s),i.push(a)}return(0,PG.encodeAbiParameters)(n,i)}function ZTe({primaryType:e,types:t}){let r=(0,TG.toHex)(RG({primaryType:e,types:t}));return(0,zu.keccak256)(r)}function RG({primaryType:e,types:t}){let r="",n=CG({primaryType:e,types:t});n.delete(e);let i=[e,...Array.from(n).sort()];for(let o of i)r+=`${o}(${t[o].map(({name:s,type:a})=>`${a} ${s}`).join(",")})`;return r}function CG({primaryType:e,types:t},r=new Set){let i=e.match(/^\w*/u)?.[0];if(r.has(i)||t[i]===void 0)return r;r.add(i);for(let o of t[i])CG({primaryType:o.type,types:t},r);return r}function NG({types:e,name:t,type:r,value:n}){if(e[r]!==void 0)return[{type:"bytes32"},(0,zu.keccak256)(OG({data:n,primaryType:r,types:e}))];if(r==="bytes")return[{type:"bytes32"},(0,zu.keccak256)(n)];if(r==="string")return[{type:"bytes32"},(0,zu.keccak256)((0,TG.toHex)(n))];if(r.lastIndexOf("]")===r.length-1){let i=r.slice(0,r.lastIndexOf("[")),o=n.map(s=>NG({name:t,type:i,types:e,value:s}));return[{type:"bytes32"},(0,zu.keccak256)((0,PG.encodeAbiParameters)(o.map(([s])=>s),o.map(([,s])=>s)))]}return[{type:r},n]}});var Ow=g(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});wf.zeroHash=wf.erc6492MagicBytes=void 0;wf.erc6492MagicBytes="0x6492649264926492649264926492649264926492649264926492649264926492";wf.zeroHash="0x0000000000000000000000000000000000000000000000000000000000000000"});var Rw=g(pN=>{"use strict";Object.defineProperty(pN,"__esModule",{value:!0});pN.isErc6492Signature=txe;var QTe=Ow(),exe=on();function txe(e){return(0,exe.sliceHex)(e,-32)===QTe.erc6492MagicBytes}});var kG=g(Cw=>{"use strict";Object.defineProperty(Cw,"__esModule",{value:!0});Cw.version=void 0;Cw.version="1.3.0"});var Yu=g(Nw=>{"use strict";Object.defineProperty(Nw,"__esModule",{value:!0});Nw.BaseError=void 0;var rxe=kG(),mN=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,i=r.cause instanceof e&&r.cause.docsPath||r.docsPath,o=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: https://abitype.dev${i}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${rxe.version}`].join(`
60
+ `);super(o),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.shortMessage=t}};Nw.BaseError=mN});var jG=g(gN=>{"use strict";Object.defineProperty(gN,"__esModule",{value:!0});gN.narrow=nxe;function nxe(e){return e}});var Hg=g(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});As.isTupleRegex=As.integerRegex=As.bytesRegex=void 0;As.execTyped=ixe;function ixe(e,t){return e.exec(t)?.groups}As.bytesRegex=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/;As.integerRegex=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;As.isTupleRegex=/^\(.+?\).*?$/});var _N=g(yN=>{"use strict";Object.defineProperty(yN,"__esModule",{value:!0});yN.formatAbiParameter=hN;var oxe=Hg(),MG=/^tuple(?<array>(\[(\d*)\])*)$/;function hN(e){let t=e.type;if(MG.test(e.type)&&"components"in e){t="(";let r=e.components.length;for(let i=0;i<r;i++){let o=e.components[i];t+=hN(o),i<r-1&&(t+=", ")}let n=(0,oxe.execTyped)(MG,e.type);return t+=`)${n?.array||""}`,hN({...e,type:t})}return"indexed"in e&&e.indexed&&(t=`${t} indexed`),e.name?`${t} ${e.name}`:t}});var EN=g(bN=>{"use strict";Object.defineProperty(bN,"__esModule",{value:!0});bN.formatAbiParameters=axe;var sxe=_N();function axe(e){let t="",r=e.length;for(let n=0;n<r;n++){let i=e[n];t+=(0,sxe.formatAbiParameter)(i),n!==r-1&&(t+=", ")}return t}});var vN=g(wN=>{"use strict";Object.defineProperty(wN,"__esModule",{value:!0});wN.formatAbiItem=cxe;var Fg=EN();function cxe(e){return e.type==="function"?`function ${e.name}(${(0,Fg.formatAbiParameters)(e.inputs)})${e.stateMutability&&e.stateMutability!=="nonpayable"?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${(0,Fg.formatAbiParameters)(e.outputs)})`:""}`:e.type==="event"?`event ${e.name}(${(0,Fg.formatAbiParameters)(e.inputs)})`:e.type==="error"?`error ${e.name}(${(0,Fg.formatAbiParameters)(e.inputs)})`:e.type==="constructor"?`constructor(${(0,Fg.formatAbiParameters)(e.inputs)})${e.stateMutability==="payable"?" payable":""}`:e.type==="fallback"?`fallback() external${e.stateMutability==="payable"?" payable":""}`:"receive() external payable"}});var qG=g(SN=>{"use strict";Object.defineProperty(SN,"__esModule",{value:!0});SN.formatAbi=dxe;var uxe=vN();function dxe(e){let t=[],r=e.length;for(let n=0;n<r;n++){let i=e[n],o=(0,uxe.formatAbiItem)(i);t.push(o)}return t}});var Xu=g(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.functionModifiers=kt.eventModifiers=kt.modifiers=void 0;kt.isErrorSignature=lxe;kt.execErrorSignature=fxe;kt.isEventSignature=pxe;kt.execEventSignature=mxe;kt.isFunctionSignature=gxe;kt.execFunctionSignature=hxe;kt.isStructSignature=yxe;kt.execStructSignature=_xe;kt.isConstructorSignature=bxe;kt.execConstructorSignature=Exe;kt.isFallbackSignature=wxe;kt.execFallbackSignature=vxe;kt.isReceiveSignature=Axe;var vf=Hg(),DG=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function lxe(e){return DG.test(e)}function fxe(e){return(0,vf.execTyped)(DG,e)}var LG=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function pxe(e){return LG.test(e)}function mxe(e){return(0,vf.execTyped)(LG,e)}var BG=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function gxe(e){return BG.test(e)}function hxe(e){return(0,vf.execTyped)(BG,e)}var UG=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function yxe(e){return UG.test(e)}function _xe(e){return(0,vf.execTyped)(UG,e)}var HG=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function bxe(e){return HG.test(e)}function Exe(e){return(0,vf.execTyped)(HG,e)}var FG=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function wxe(e){return FG.test(e)}function vxe(e){return(0,vf.execTyped)(FG,e)}var Sxe=/^receive\(\) external payable$/;function Axe(e){return Sxe.test(e)}kt.modifiers=new Set(["memory","indexed","storage","calldata"]);kt.eventModifiers=new Set(["indexed"]);kt.functionModifiers=new Set(["calldata","memory","storage"])});var $g=g(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.UnknownSolidityTypeError=oc.UnknownTypeError=oc.InvalidAbiItemError=void 0;var TN=Yu(),AN=class extends TN.BaseError{constructor({signature:t}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}};oc.InvalidAbiItemError=AN;var IN=class extends TN.BaseError{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}};oc.UnknownTypeError=IN;var PN=class extends TN.BaseError{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}};oc.UnknownSolidityTypeError=PN});var Sf=g(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.InvalidAbiTypeParameterError=Nr.InvalidFunctionModifierError=Nr.InvalidModifierError=Nr.SolidityProtectedKeywordError=Nr.InvalidParameterError=Nr.InvalidAbiParametersError=Nr.InvalidAbiParameterError=void 0;var Zu=Yu(),xN=class extends Zu.BaseError{constructor({param:t}){super("Failed to parse ABI parameter.",{details:`parseAbiParameter(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameter-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParameterError"})}};Nr.InvalidAbiParameterError=xN;var ON=class extends Zu.BaseError{constructor({params:t}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"})}};Nr.InvalidAbiParametersError=ON;var RN=class extends Zu.BaseError{constructor({param:t}){super("Invalid ABI parameter.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}};Nr.InvalidParameterError=RN;var CN=class extends Zu.BaseError{constructor({param:t,name:r}){super("Invalid ABI parameter.",{details:t,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}};Nr.SolidityProtectedKeywordError=CN;var NN=class extends Zu.BaseError{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}};Nr.InvalidModifierError=NN;var kN=class extends Zu.BaseError{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}};Nr.InvalidFunctionModifierError=kN;var jN=class extends Zu.BaseError{constructor({abiParameter:t}){super("Invalid ABI parameter.",{details:JSON.stringify(t,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}};Nr.InvalidAbiTypeParameterError=jN});var kw=g(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});sc.InvalidStructSignatureError=sc.UnknownSignatureError=sc.InvalidSignatureError=void 0;var LN=Yu(),MN=class extends LN.BaseError{constructor({signature:t,type:r}){super(`Invalid ${r} signature.`,{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}};sc.InvalidSignatureError=MN;var qN=class extends LN.BaseError{constructor({signature:t}){super("Unknown signature.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}};sc.UnknownSignatureError=qN;var DN=class extends LN.BaseError{constructor({signature:t}){super("Invalid struct signature.",{details:t,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}};sc.InvalidStructSignatureError=DN});var UN=g(jw=>{"use strict";Object.defineProperty(jw,"__esModule",{value:!0});jw.CircularReferenceError=void 0;var Ixe=Yu(),BN=class extends Ixe.BaseError{constructor({type:t}){super("Circular reference detected.",{metaMessages:[`Struct "${t}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}};jw.CircularReferenceError=BN});var FN=g(Mw=>{"use strict";Object.defineProperty(Mw,"__esModule",{value:!0});Mw.InvalidParenthesisError=void 0;var Pxe=Yu(),HN=class extends Pxe.BaseError{constructor({current:t,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${t.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}};Mw.InvalidParenthesisError=HN});var $G=g(Jg=>{"use strict";Object.defineProperty(Jg,"__esModule",{value:!0});Jg.parameterCache=void 0;Jg.getParameterCacheKey=Txe;function Txe(e,t,r){let n="";if(r)for(let i of Object.entries(r)){if(!i)continue;let o="";for(let s of i[1])o+=`[${s.type}${s.name?`:${s.name}`:""}]`;n+=`(${i[0]}{${o}})`}return t?`${t}:${e}${n}`:`${e}${n}`}Jg.parameterCache=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]])});var ed=g(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.parseSignature=Rxe;qn.parseFunctionSignature=JG;qn.parseEventSignature=VG;qn.parseErrorSignature=GG;qn.parseConstructorSignature=KG;qn.parseFallbackSignature=WG;qn.parseAbiParameter=Qu;qn.splitParameters=si;qn.isSolidityType=zG;qn.isSolidityKeyword=YG;qn.isValidDataLocation=XG;var Af=Hg(),xxe=$g(),qw=Sf(),If=kw(),Oxe=FN(),Dw=$G(),Gr=Xu();function Rxe(e,t={}){if((0,Gr.isFunctionSignature)(e))return JG(e,t);if((0,Gr.isEventSignature)(e))return VG(e,t);if((0,Gr.isErrorSignature)(e))return GG(e,t);if((0,Gr.isConstructorSignature)(e))return KG(e,t);if((0,Gr.isFallbackSignature)(e))return WG(e);if((0,Gr.isReceiveSignature)(e))return{type:"receive",stateMutability:"payable"};throw new If.UnknownSignatureError({signature:e})}function JG(e,t={}){let r=(0,Gr.execFunctionSignature)(e);if(!r)throw new If.InvalidSignatureError({signature:e,type:"function"});let n=si(r.parameters),i=[],o=n.length;for(let a=0;a<o;a++)i.push(Qu(n[a],{modifiers:Gr.functionModifiers,structs:t,type:"function"}));let s=[];if(r.returns){let a=si(r.returns),c=a.length;for(let u=0;u<c;u++)s.push(Qu(a[u],{modifiers:Gr.functionModifiers,structs:t,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:i,outputs:s}}function VG(e,t={}){let r=(0,Gr.execEventSignature)(e);if(!r)throw new If.InvalidSignatureError({signature:e,type:"event"});let n=si(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(Qu(n[s],{modifiers:Gr.eventModifiers,structs:t,type:"event"}));return{name:r.name,type:"event",inputs:i}}function GG(e,t={}){let r=(0,Gr.execErrorSignature)(e);if(!r)throw new If.InvalidSignatureError({signature:e,type:"error"});let n=si(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(Qu(n[s],{structs:t,type:"error"}));return{name:r.name,type:"error",inputs:i}}function KG(e,t={}){let r=(0,Gr.execConstructorSignature)(e);if(!r)throw new If.InvalidSignatureError({signature:e,type:"constructor"});let n=si(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(Qu(n[s],{structs:t,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:i}}function WG(e){let t=(0,Gr.execFallbackSignature)(e);if(!t)throw new If.InvalidSignatureError({signature:e,type:"fallback"});return{type:"fallback",stateMutability:t.stateMutability??"nonpayable"}}var Cxe=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,Nxe=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,kxe=/^u?int$/;function Qu(e,t){let r=(0,Dw.getParameterCacheKey)(e,t?.type,t?.structs);if(Dw.parameterCache.has(r))return Dw.parameterCache.get(r);let n=Af.isTupleRegex.test(e),i=(0,Af.execTyped)(n?Nxe:Cxe,e);if(!i)throw new qw.InvalidParameterError({param:e});if(i.name&&YG(i.name))throw new qw.SolidityProtectedKeywordError({param:e,name:i.name});let o=i.name?{name:i.name}:{},s=i.modifier==="indexed"?{indexed:!0}:{},a=t?.structs??{},c,u={};if(n){c="tuple";let l=si(i.type),m=[],p=l.length;for(let h=0;h<p;h++)m.push(Qu(l[h],{structs:a}));u={components:m}}else if(i.type in a)c="tuple",u={components:a[i.type]};else if(kxe.test(i.type))c=`${i.type}256`;else if(i.type==="address payable")c="address";else if(c=i.type,t?.type!=="struct"&&!zG(c))throw new xxe.UnknownSolidityTypeError({type:c});if(i.modifier){if(!t?.modifiers?.has?.(i.modifier))throw new qw.InvalidModifierError({param:e,type:t?.type,modifier:i.modifier});if(Gr.functionModifiers.has(i.modifier)&&!XG(c,!!i.array))throw new qw.InvalidFunctionModifierError({param:e,type:t?.type,modifier:i.modifier})}let d={type:`${c}${i.array??""}`,...o,...s,...u};return Dw.parameterCache.set(r,d),d}function si(e,t=[],r="",n=0){let i=e.trim().length;for(let o=0;o<i;o++){let s=e[o],a=e.slice(o+1);switch(s){case",":return n===0?si(a,[...t,r.trim()]):si(a,t,`${r}${s}`,n);case"(":return si(a,t,`${r}${s}`,n+1);case")":return si(a,t,`${r}${s}`,n-1);default:return si(a,t,`${r}${s}`,n)}}if(r==="")return t;if(n!==0)throw new Oxe.InvalidParenthesisError({current:r,depth:n});return t.push(r.trim()),t}function zG(e){return e==="address"||e==="bool"||e==="function"||e==="string"||Af.bytesRegex.test(e)||Af.integerRegex.test(e)}var jxe=/^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/;function YG(e){return e==="address"||e==="bool"||e==="function"||e==="string"||e==="tuple"||Af.bytesRegex.test(e)||Af.integerRegex.test(e)||jxe.test(e)}function XG(e,t){return t||e==="bytes"||e==="string"||e==="tuple"}});var Vg=g($N=>{"use strict";Object.defineProperty($N,"__esModule",{value:!0});$N.parseStructs=Lxe;var ZG=Hg(),Mxe=$g(),qxe=Sf(),QG=kw(),Dxe=UN(),eK=Xu(),tK=ed();function Lxe(e){let t={},r=e.length;for(let s=0;s<r;s++){let a=e[s];if(!(0,eK.isStructSignature)(a))continue;let c=(0,eK.execStructSignature)(a);if(!c)throw new QG.InvalidSignatureError({signature:a,type:"struct"});let u=c.properties.split(";"),d=[],l=u.length;for(let m=0;m<l;m++){let h=u[m].trim();if(!h)continue;let y=(0,tK.parseAbiParameter)(h,{type:"struct"});d.push(y)}if(!d.length)throw new QG.InvalidStructSignatureError({signature:a});t[c.name]=d}let n={},i=Object.entries(t),o=i.length;for(let s=0;s<o;s++){let[a,c]=i[s];n[a]=rK(c,t)}return n}var Bxe=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function rK(e=[],t={},r=new Set){let n=[],i=e.length;for(let o=0;o<i;o++){let s=e[o];if(ZG.isTupleRegex.test(s.type))n.push(s);else{let c=(0,ZG.execTyped)(Bxe,s.type);if(!c?.type)throw new qxe.InvalidAbiTypeParameterError({abiParameter:s});let{array:u,type:d}=c;if(d in t){if(r.has(d))throw new Dxe.CircularReferenceError({type:d});n.push({...s,type:`tuple${u??""}`,components:rK(t[d],t,new Set([...r,d]))})}else if((0,tK.isSolidityType)(d))n.push(s);else throw new Mxe.UnknownTypeError({type:d})}}return n}});var nK=g(JN=>{"use strict";Object.defineProperty(JN,"__esModule",{value:!0});JN.parseAbi=$xe;var Uxe=Xu(),Hxe=Vg(),Fxe=ed();function $xe(e){let t=(0,Hxe.parseStructs)(e),r=[],n=e.length;for(let i=0;i<n;i++){let o=e[i];(0,Uxe.isStructSignature)(o)||r.push((0,Fxe.parseSignature)(o,t))}return r}});var oK=g(VN=>{"use strict";Object.defineProperty(VN,"__esModule",{value:!0});VN.parseAbiItem=Kxe;var Jxe=$g(),Vxe=Xu(),Gxe=Vg(),iK=ed();function Kxe(e){let t;if(typeof e=="string")t=(0,iK.parseSignature)(e);else{let r=(0,Gxe.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if(!(0,Vxe.isStructSignature)(o)){t=(0,iK.parseSignature)(o,r);break}}}if(!t)throw new Jxe.InvalidAbiItemError({signature:e});return t}});var aK=g(KN=>{"use strict";Object.defineProperty(KN,"__esModule",{value:!0});KN.parseAbiParameter=Yxe;var Wxe=Sf(),GN=Xu(),zxe=Vg(),sK=ed();function Yxe(e){let t;if(typeof e=="string")t=(0,sK.parseAbiParameter)(e,{modifiers:GN.modifiers});else{let r=(0,zxe.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if(!(0,GN.isStructSignature)(o)){t=(0,sK.parseAbiParameter)(o,{modifiers:GN.modifiers,structs:r});break}}}if(!t)throw new Wxe.InvalidAbiParameterError({param:e});return t}});var dK=g(zN=>{"use strict";Object.defineProperty(zN,"__esModule",{value:!0});zN.parseAbiParameters=Qxe;var Xxe=Sf(),WN=Xu(),Zxe=Vg(),cK=ed(),uK=ed();function Qxe(e){let t=[];if(typeof e=="string"){let r=(0,cK.splitParameters)(e),n=r.length;for(let i=0;i<n;i++)t.push((0,uK.parseAbiParameter)(r[i],{modifiers:WN.modifiers}))}else{let r=(0,Zxe.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if((0,WN.isStructSignature)(o))continue;let s=(0,cK.splitParameters)(o),a=s.length;for(let c=0;c<a;c++)t.push((0,uK.parseAbiParameter)(s[c],{modifiers:WN.modifiers,structs:r}))}}if(t.length===0)throw new Xxe.InvalidAbiParametersError({params:e});return t}});var Pf=g(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.CircularReferenceError=me.InvalidParenthesisError=me.UnknownSignatureError=me.InvalidSignatureError=me.InvalidStructSignatureError=me.InvalidAbiParameterError=me.InvalidAbiParametersError=me.InvalidParameterError=me.SolidityProtectedKeywordError=me.InvalidModifierError=me.InvalidFunctionModifierError=me.InvalidAbiTypeParameterError=me.UnknownSolidityTypeError=me.InvalidAbiItemError=me.UnknownTypeError=me.parseAbiParameters=me.parseAbiParameter=me.parseAbiItem=me.parseAbi=me.formatAbiParameters=me.formatAbiParameter=me.formatAbiItem=me.formatAbi=me.narrow=me.BaseError=void 0;var e2e=Yu();Object.defineProperty(me,"BaseError",{enumerable:!0,get:function(){return e2e.BaseError}});var t2e=jG();Object.defineProperty(me,"narrow",{enumerable:!0,get:function(){return t2e.narrow}});var r2e=qG();Object.defineProperty(me,"formatAbi",{enumerable:!0,get:function(){return r2e.formatAbi}});var n2e=vN();Object.defineProperty(me,"formatAbiItem",{enumerable:!0,get:function(){return n2e.formatAbiItem}});var i2e=_N();Object.defineProperty(me,"formatAbiParameter",{enumerable:!0,get:function(){return i2e.formatAbiParameter}});var o2e=EN();Object.defineProperty(me,"formatAbiParameters",{enumerable:!0,get:function(){return o2e.formatAbiParameters}});var s2e=nK();Object.defineProperty(me,"parseAbi",{enumerable:!0,get:function(){return s2e.parseAbi}});var a2e=oK();Object.defineProperty(me,"parseAbiItem",{enumerable:!0,get:function(){return a2e.parseAbiItem}});var c2e=aK();Object.defineProperty(me,"parseAbiParameter",{enumerable:!0,get:function(){return c2e.parseAbiParameter}});var u2e=dK();Object.defineProperty(me,"parseAbiParameters",{enumerable:!0,get:function(){return u2e.parseAbiParameters}});var YN=$g();Object.defineProperty(me,"UnknownTypeError",{enumerable:!0,get:function(){return YN.UnknownTypeError}});Object.defineProperty(me,"InvalidAbiItemError",{enumerable:!0,get:function(){return YN.InvalidAbiItemError}});Object.defineProperty(me,"UnknownSolidityTypeError",{enumerable:!0,get:function(){return YN.UnknownSolidityTypeError}});var td=Sf();Object.defineProperty(me,"InvalidAbiTypeParameterError",{enumerable:!0,get:function(){return td.InvalidAbiTypeParameterError}});Object.defineProperty(me,"InvalidFunctionModifierError",{enumerable:!0,get:function(){return td.InvalidFunctionModifierError}});Object.defineProperty(me,"InvalidModifierError",{enumerable:!0,get:function(){return td.InvalidModifierError}});Object.defineProperty(me,"SolidityProtectedKeywordError",{enumerable:!0,get:function(){return td.SolidityProtectedKeywordError}});Object.defineProperty(me,"InvalidParameterError",{enumerable:!0,get:function(){return td.InvalidParameterError}});Object.defineProperty(me,"InvalidAbiParametersError",{enumerable:!0,get:function(){return td.InvalidAbiParametersError}});Object.defineProperty(me,"InvalidAbiParameterError",{enumerable:!0,get:function(){return td.InvalidAbiParameterError}});var XN=kw();Object.defineProperty(me,"InvalidStructSignatureError",{enumerable:!0,get:function(){return XN.InvalidStructSignatureError}});Object.defineProperty(me,"InvalidSignatureError",{enumerable:!0,get:function(){return XN.InvalidSignatureError}});Object.defineProperty(me,"UnknownSignatureError",{enumerable:!0,get:function(){return XN.UnknownSignatureError}});var d2e=FN();Object.defineProperty(me,"InvalidParenthesisError",{enumerable:!0,get:function(){return d2e.InvalidParenthesisError}});var l2e=UN();Object.defineProperty(me,"CircularReferenceError",{enumerable:!0,get:function(){return l2e.CircularReferenceError}})});var lK=g(Lw=>{"use strict";Object.defineProperty(Lw,"__esModule",{value:!0});Lw.LruMap=void 0;var ZN=class extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){let r=super.get(t);return super.has(t)&&r!==void 0&&(this.delete(t),super.set(t,r)),r}set(t,r){if(super.set(t,r),this.maxSize&&this.size>this.maxSize){let n=this.keys().next().value;n&&this.delete(n)}return this}};Lw.LruMap=ZN});var pK=g(Gg=>{"use strict";Object.defineProperty(Gg,"__esModule",{value:!0});Gg.checksum=void 0;Gg.clear=p2e;var f2e=lK(),fK={checksum:new f2e.LruMap(8192)};Gg.checksum=fK.checksum;function p2e(){for(let e of Object.values(fK))e.clear()}});var Wg=g(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});rd.keccak256=y2e;rd.hmac256=_2e;rd.ripemd160=b2e;rd.sha256=E2e;rd.validate=w2e;var m2e=p2(),g2e=bC(),h2e=JT(),mK=gO(),Kg=ti(),Tf=Jt();function y2e(e,t={}){let{as:r=typeof e=="string"?"Hex":"Bytes"}=t,n=(0,h2e.keccak_256)(Kg.from(e));return r==="Bytes"?n:Tf.fromBytes(n)}function _2e(e,t,r={}){let{as:n=typeof t=="string"?"Hex":"Bytes"}=r,i=(0,m2e.hmac)(mK.sha256,Kg.from(e),Kg.from(t));return n==="Bytes"?i:Tf.fromBytes(i)}function b2e(e,t={}){let{as:r=typeof e=="string"?"Hex":"Bytes"}=t,n=(0,g2e.ripemd160)(Kg.from(e));return r==="Bytes"?n:Tf.fromBytes(n)}function E2e(e,t={}){let{as:r=typeof e=="string"?"Hex":"Bytes"}=t,n=(0,mK.sha256)(Kg.from(e));return r==="Bytes"?n:Tf.fromBytes(n)}function w2e(e){return Tf.validate(e)&&Tf.size(e)===32}});var e5=g(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.InvalidSerializedSizeError=Lt.InvalidUncompressedPrefixError=Lt.InvalidCompressedPrefixError=Lt.InvalidPrefixError=Lt.InvalidError=void 0;Lt.assert=$w;Lt.compress=S2e;Lt.from=A2e;Lt.fromBytes=hK;Lt.fromHex=QN;Lt.toBytes=I2e;Lt.toHex=yK;Lt.validate=P2e;var gK=ti(),Yg=Vr(),Kr=Jt(),v2e=cg();function $w(e,t={}){let{compressed:r}=t,{prefix:n,x:i,y:o}=e;if(r===!1||typeof i=="bigint"&&typeof o=="bigint"){if(n!==4)throw new zg({prefix:n,cause:new Hw});return}if(r===!0||typeof i=="bigint"&&typeof o>"u"){if(n!==3&&n!==2)throw new zg({prefix:n,cause:new Uw});return}throw new Bw({publicKey:e})}function S2e(e){let{x:t,y:r}=e;return{prefix:r%2n===0n?2:3,x:t}}function A2e(e){let t=(()=>{if(Kr.validate(e))return QN(e);if(gK.validate(e))return hK(e);let{prefix:r,x:n,y:i}=e;return typeof n=="bigint"&&typeof i=="bigint"?{prefix:r??4,x:n,y:i}:{prefix:r,x:n}})();return $w(t),t}function hK(e){return QN(Kr.fromBytes(e))}function QN(e){if(e.length!==132&&e.length!==130&&e.length!==68)throw new Fw({publicKey:e});if(e.length===130){let n=BigInt(Kr.slice(e,0,32)),i=BigInt(Kr.slice(e,32,64));return{prefix:4,x:n,y:i}}if(e.length===132){let n=Number(Kr.slice(e,0,1)),i=BigInt(Kr.slice(e,1,33)),o=BigInt(Kr.slice(e,33,65));return{prefix:n,x:i,y:o}}let t=Number(Kr.slice(e,0,1)),r=BigInt(Kr.slice(e,1,33));return{prefix:t,x:r}}function I2e(e,t={}){return gK.fromHex(yK(e,t))}function yK(e,t={}){$w(e);let{prefix:r,x:n,y:i}=e,{includePrefix:o=!0}=t;return Kr.concat(o?Kr.fromNumber(r,{size:1}):"0x",Kr.fromNumber(n,{size:32}),typeof i=="bigint"?Kr.fromNumber(i,{size:32}):"0x")}function P2e(e,t={}){try{return $w(e,t),!0}catch{return!1}}var Bw=class extends Yg.BaseError{constructor({publicKey:t}){super(`Value \`${v2e.stringify(t)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}};Lt.InvalidError=Bw;var zg=class extends Yg.BaseError{constructor({prefix:t,cause:r}){super(`Prefix "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}};Lt.InvalidPrefixError=zg;var Uw=class extends Yg.BaseError{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}};Lt.InvalidCompressedPrefixError=Uw;var Hw=class extends Yg.BaseError{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}};Lt.InvalidUncompressedPrefixError=Hw;var Fw=class extends Yg.BaseError{constructor({publicKey:t}){super(`Value \`${t}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${Kr.size(Kr.from(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}};Lt.InvalidSerializedSizeError=Fw});var Of=g(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.InvalidChecksumError=gn.InvalidInputError=gn.InvalidAddressError=void 0;gn.assert=xf;gn.checksum=n5;gn.from=bK;gn.fromPublicKey=R2e;gn.isEqual=C2e;gn.validate=N2e;var T2e=ti(),t5=pK(),r5=Vr(),_K=Wg(),x2e=e5(),O2e=/^0x[a-fA-F0-9]{40}$/;function xf(e,t={}){let{strict:r=!0}=t;if(!O2e.test(e))throw new Xg({address:e,cause:new Jw});if(r){if(e.toLowerCase()===e)return;if(n5(e)!==e)throw new Xg({address:e,cause:new Vw})}}function n5(e){if(t5.checksum.has(e))return t5.checksum.get(e);xf(e,{strict:!1});let t=e.substring(2).toLowerCase(),r=_K.keccak256(T2e.fromString(t),{as:"Bytes"}),n=t.split("");for(let o=0;o<40;o+=2)r[o>>1]>>4>=8&&n[o]&&(n[o]=n[o].toUpperCase()),(r[o>>1]&15)>=8&&n[o+1]&&(n[o+1]=n[o+1].toUpperCase());let i=`0x${n.join("")}`;return t5.checksum.set(e,i),i}function bK(e,t={}){let{checksum:r=!1}=t;return xf(e),r?n5(e):e}function R2e(e,t={}){let r=_K.keccak256(`0x${x2e.toHex(e).slice(4)}`).substring(26);return bK(`0x${r}`,t)}function C2e(e,t){return xf(e,{strict:!1}),xf(t,{strict:!1}),e.toLowerCase()===t.toLowerCase()}function N2e(e,t={}){let{strict:r=!0}=t??{};try{return xf(e,{strict:r}),!0}catch{return!1}}var Xg=class extends r5.BaseError{constructor({address:t,cause:r}){super(`Address "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}};gn.InvalidAddressError=Xg;var Jw=class extends r5.BaseError{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}};gn.InvalidInputError=Jw;var Vw=class extends r5.BaseError{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}};gn.InvalidChecksumError=Vw});var Gw=g(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.minInt120=O.minInt112=O.minInt104=O.minInt96=O.minInt88=O.minInt80=O.minInt72=O.minInt64=O.minInt56=O.minInt48=O.minInt40=O.minInt32=O.minInt24=O.minInt16=O.minInt8=O.maxInt256=O.maxInt248=O.maxInt240=O.maxInt232=O.maxInt224=O.maxInt216=O.maxInt208=O.maxInt200=O.maxInt192=O.maxInt184=O.maxInt176=O.maxInt168=O.maxInt160=O.maxInt152=O.maxInt144=O.maxInt136=O.maxInt128=O.maxInt120=O.maxInt112=O.maxInt104=O.maxInt96=O.maxInt88=O.maxInt80=O.maxInt72=O.maxInt64=O.maxInt56=O.maxInt48=O.maxInt40=O.maxInt32=O.maxInt24=O.maxInt16=O.maxInt8=O.integerRegex=O.bytesRegex=O.arrayRegex=void 0;O.maxUint256=O.maxUint248=O.maxUint240=O.maxUint232=O.maxUint224=O.maxUint216=O.maxUint208=O.maxUint200=O.maxUint192=O.maxUint184=O.maxUint176=O.maxUint168=O.maxUint160=O.maxUint152=O.maxUint144=O.maxUint136=O.maxUint128=O.maxUint120=O.maxUint112=O.maxUint104=O.maxUint96=O.maxUint88=O.maxUint80=O.maxUint72=O.maxUint64=O.maxUint56=O.maxUint48=O.maxUint40=O.maxUint32=O.maxUint24=O.maxUint16=O.maxUint8=O.minInt256=O.minInt248=O.minInt240=O.minInt232=O.minInt224=O.minInt216=O.minInt208=O.minInt200=O.minInt192=O.minInt184=O.minInt176=O.minInt168=O.minInt160=O.minInt152=O.minInt144=O.minInt136=O.minInt128=void 0;O.arrayRegex=/^(.*)\[([0-9]*)\]$/;O.bytesRegex=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/;O.integerRegex=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;O.maxInt8=2n**(8n-1n)-1n;O.maxInt16=2n**(16n-1n)-1n;O.maxInt24=2n**(24n-1n)-1n;O.maxInt32=2n**(32n-1n)-1n;O.maxInt40=2n**(40n-1n)-1n;O.maxInt48=2n**(48n-1n)-1n;O.maxInt56=2n**(56n-1n)-1n;O.maxInt64=2n**(64n-1n)-1n;O.maxInt72=2n**(72n-1n)-1n;O.maxInt80=2n**(80n-1n)-1n;O.maxInt88=2n**(88n-1n)-1n;O.maxInt96=2n**(96n-1n)-1n;O.maxInt104=2n**(104n-1n)-1n;O.maxInt112=2n**(112n-1n)-1n;O.maxInt120=2n**(120n-1n)-1n;O.maxInt128=2n**(128n-1n)-1n;O.maxInt136=2n**(136n-1n)-1n;O.maxInt144=2n**(144n-1n)-1n;O.maxInt152=2n**(152n-1n)-1n;O.maxInt160=2n**(160n-1n)-1n;O.maxInt168=2n**(168n-1n)-1n;O.maxInt176=2n**(176n-1n)-1n;O.maxInt184=2n**(184n-1n)-1n;O.maxInt192=2n**(192n-1n)-1n;O.maxInt200=2n**(200n-1n)-1n;O.maxInt208=2n**(208n-1n)-1n;O.maxInt216=2n**(216n-1n)-1n;O.maxInt224=2n**(224n-1n)-1n;O.maxInt232=2n**(232n-1n)-1n;O.maxInt240=2n**(240n-1n)-1n;O.maxInt248=2n**(248n-1n)-1n;O.maxInt256=2n**(256n-1n)-1n;O.minInt8=-(2n**(8n-1n));O.minInt16=-(2n**(16n-1n));O.minInt24=-(2n**(24n-1n));O.minInt32=-(2n**(32n-1n));O.minInt40=-(2n**(40n-1n));O.minInt48=-(2n**(48n-1n));O.minInt56=-(2n**(56n-1n));O.minInt64=-(2n**(64n-1n));O.minInt72=-(2n**(72n-1n));O.minInt80=-(2n**(80n-1n));O.minInt88=-(2n**(88n-1n));O.minInt96=-(2n**(96n-1n));O.minInt104=-(2n**(104n-1n));O.minInt112=-(2n**(112n-1n));O.minInt120=-(2n**(120n-1n));O.minInt128=-(2n**(128n-1n));O.minInt136=-(2n**(136n-1n));O.minInt144=-(2n**(144n-1n));O.minInt152=-(2n**(152n-1n));O.minInt160=-(2n**(160n-1n));O.minInt168=-(2n**(168n-1n));O.minInt176=-(2n**(176n-1n));O.minInt184=-(2n**(184n-1n));O.minInt192=-(2n**(192n-1n));O.minInt200=-(2n**(200n-1n));O.minInt208=-(2n**(208n-1n));O.minInt216=-(2n**(216n-1n));O.minInt224=-(2n**(224n-1n));O.minInt232=-(2n**(232n-1n));O.minInt240=-(2n**(240n-1n));O.minInt248=-(2n**(248n-1n));O.minInt256=-(2n**(256n-1n));O.maxUint8=2n**8n-1n;O.maxUint16=2n**16n-1n;O.maxUint24=2n**24n-1n;O.maxUint32=2n**32n-1n;O.maxUint40=2n**40n-1n;O.maxUint48=2n**48n-1n;O.maxUint56=2n**56n-1n;O.maxUint64=2n**64n-1n;O.maxUint72=2n**72n-1n;O.maxUint80=2n**80n-1n;O.maxUint88=2n**88n-1n;O.maxUint96=2n**96n-1n;O.maxUint104=2n**104n-1n;O.maxUint112=2n**112n-1n;O.maxUint120=2n**120n-1n;O.maxUint128=2n**128n-1n;O.maxUint136=2n**136n-1n;O.maxUint144=2n**144n-1n;O.maxUint152=2n**152n-1n;O.maxUint160=2n**160n-1n;O.maxUint168=2n**168n-1n;O.maxUint176=2n**176n-1n;O.maxUint184=2n**184n-1n;O.maxUint192=2n**192n-1n;O.maxUint200=2n**200n-1n;O.maxUint208=2n**208n-1n;O.maxUint216=2n**216n-1n;O.maxUint224=2n**224n-1n;O.maxUint232=2n**232n-1n;O.maxUint240=2n**240n-1n;O.maxUint248=2n**248n-1n;O.maxUint256=2n**256n-1n});var qK=g(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.decodeParameter=Rf;vt.decodeAddress=vK;vt.decodeArray=SK;vt.decodeBool=AK;vt.decodeBytes=IK;vt.decodeNumber=PK;vt.decodeTuple=TK;vt.decodeString=xK;vt.prepareParameters=M2e;vt.prepareParameter=Kw;vt.encode=o5;vt.encodeAddress=OK;vt.encodeArray=RK;vt.encodeBytes=CK;vt.encodeBoolean=NK;vt.encodeNumber=kK;vt.encodeString=jK;vt.encodeTuple=MK;vt.getArrayComponents=Ww;vt.hasDynamicChild=nd;var Zg=id(),wK=Of(),hn=ti(),k2e=Vr(),Be=Jt(),j2e=Gw();function Rf(e,t,r){let{checksumAddress:n,staticPosition:i}=r,o=Ww(t.type);if(o){let[s,a]=o;return SK(e,{...t,type:a},{checksumAddress:n,length:s,staticPosition:i})}if(t.type==="tuple")return TK(e,t,{checksumAddress:n,staticPosition:i});if(t.type==="address")return vK(e,{checksum:n});if(t.type==="bool")return AK(e);if(t.type.startsWith("bytes"))return IK(e,t,{staticPosition:i});if(t.type.startsWith("uint")||t.type.startsWith("int"))return PK(e,t);if(t.type==="string")return xK(e,{staticPosition:i});throw new Zg.InvalidTypeError(t.type)}var EK=32,i5=32;function vK(e,t={}){let{checksum:r=!1}=t,n=e.readBytes(32);return[(o=>r?wK.checksum(o):o)(Be.fromBytes(hn.slice(n,-20))),32]}function SK(e,t,r){let{checksumAddress:n,length:i,staticPosition:o}=r;if(i===null){let c=hn.toNumber(e.readBytes(i5)),u=o+c,d=u+EK;e.setPosition(u);let l=hn.toNumber(e.readBytes(EK)),m=nd(t),p=0,h=[];for(let y=0;y<l;++y){e.setPosition(d+(m?y*32:p));let[b,v]=Rf(e,t,{checksumAddress:n,staticPosition:d});p+=v,h.push(b),v===0&&(e.assertReadLimit(),e._touch())}return e.setPosition(o+32),[h,32]}if(nd(t)){let c=hn.toNumber(e.readBytes(i5)),u=o+c,d=[];for(let l=0;l<i;++l){e.setPosition(u+l*32);let[m]=Rf(e,t,{checksumAddress:n,staticPosition:u});d.push(m)}return e.setPosition(o+32),[d,32]}let s=0,a=[];for(let c=0;c<i;++c){let[u,d]=Rf(e,t,{checksumAddress:n,staticPosition:o+s});s+=d,a.push(u),d===0&&(e.assertReadLimit(),e._touch())}return[a,s]}function AK(e){return[hn.toBoolean(e.readBytes(32),{size:32}),32]}function IK(e,t,{staticPosition:r}){let[n,i]=t.type.split("bytes");if(!i){let s=hn.toNumber(e.readBytes(32));e.setPosition(r+s);let a=hn.toNumber(e.readBytes(32));if(a===0)return e.setPosition(r+32),["0x",32];let c=e.readBytes(a);return e.setPosition(r+32),[Be.fromBytes(c),32]}return[Be.fromBytes(e.readBytes(Number.parseInt(i,10),32)),32]}function PK(e,t){let r=t.type.startsWith("int"),n=Number.parseInt(t.type.split("int")[1]||"256",10),i=e.readBytes(32);return[n>48?hn.toBigInt(i,{signed:r}):hn.toNumber(i,{signed:r}),32]}function TK(e,t,r){let{checksumAddress:n,staticPosition:i}=r,o=t.components.length===0||t.components.some(({name:c})=>!c),s=o?[]:{},a=0;if(nd(t)){let c=hn.toNumber(e.readBytes(i5)),u=i+c;for(let d=0;d<t.components.length;++d){let l=t.components[d];e.setPosition(u+a);let[m,p]=Rf(e,l,{checksumAddress:n,staticPosition:u});a+=p,s[o?d:l?.name]=m}return e.setPosition(i+32),[s,32]}for(let c=0;c<t.components.length;++c){let u=t.components[c],[d,l]=Rf(e,u,{checksumAddress:n,staticPosition:i});s[o?c:u?.name]=d,a+=l}return[s,a]}function xK(e,{staticPosition:t}){let r=hn.toNumber(e.readBytes(32)),n=t+r;e.setPosition(n);let i=hn.toNumber(e.readBytes(32));if(i===0)return e.setPosition(t+32),["",32];let o=e.readBytes(i,32),s=hn.toString(hn.trimLeft(o));return e.setPosition(t+32),[s,32]}function M2e({checksumAddress:e,parameters:t,values:r}){let n=[];for(let i=0;i<t.length;i++)n.push(Kw({checksumAddress:e,parameter:t[i],value:r[i]}));return n}function Kw({checksumAddress:e=!1,parameter:t,value:r}){let n=t,i=Ww(n.type);if(i){let[o,s]=i;return RK(r,{checksumAddress:e,length:o,parameter:{...n,type:s}})}if(n.type==="tuple")return MK(r,{checksumAddress:e,parameter:n});if(n.type==="address")return OK(r,{checksum:e});if(n.type==="bool")return NK(r);if(n.type.startsWith("uint")||n.type.startsWith("int")){let o=n.type.startsWith("int"),[,,s="256"]=j2e.integerRegex.exec(n.type)??[];return kK(r,{signed:o,size:Number(s)})}if(n.type.startsWith("bytes"))return CK(r,{type:n.type});if(n.type==="string")return jK(r);throw new Zg.InvalidTypeError(n.type)}function o5(e){let t=0;for(let o=0;o<e.length;o++){let{dynamic:s,encoded:a}=e[o];s?t+=32:t+=Be.size(a)}let r=[],n=[],i=0;for(let o=0;o<e.length;o++){let{dynamic:s,encoded:a}=e[o];s?(r.push(Be.fromNumber(t+i,{size:32})),n.push(a),i+=Be.size(a)):r.push(a)}return Be.concat(...r,...n)}function OK(e,t){let{checksum:r=!1}=t;return wK.assert(e,{strict:r}),{dynamic:!1,encoded:Be.padLeft(e.toLowerCase())}}function RK(e,t){let{checksumAddress:r,length:n,parameter:i}=t,o=n===null;if(!Array.isArray(e))throw new Zg.InvalidArrayError(e);if(!o&&e.length!==n)throw new Zg.ArrayLengthMismatchError({expectedLength:n,givenLength:e.length,type:`${i.type}[${n}]`});let s=e.length===0&&nd(i),a=[];for(let c=0;c<e.length;c++){let u=Kw({checksumAddress:r,parameter:i,value:e[c]});u.dynamic&&(s=!0),a.push(u)}if(o||s){let c=o5(a);if(o){let u=Be.fromNumber(a.length,{size:32});return{dynamic:!0,encoded:a.length>0?Be.concat(u,c):u}}if(s)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:Be.concat(...a.map(({encoded:c})=>c))}}function CK(e,{type:t}){let[,r]=t.split("bytes"),n=Be.size(e);if(!r){let i=e;return n%32!==0&&(i=Be.padRight(i,Math.ceil((e.length-2)/2/32)*32)),{dynamic:!0,encoded:Be.concat(Be.padLeft(Be.fromNumber(n,{size:32})),i)}}if(n!==Number.parseInt(r,10))throw new Zg.BytesSizeMismatchError({expectedSize:Number.parseInt(r,10),value:e});return{dynamic:!1,encoded:Be.padRight(e)}}function NK(e){if(typeof e!="boolean")throw new k2e.BaseError(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Be.padLeft(Be.fromBoolean(e))}}function kK(e,{signed:t,size:r}){if(typeof r=="number"){let n=2n**(BigInt(r)-(t?1n:0n))-1n,i=t?-n-1n:0n;if(e>n||e<i)throw new Be.IntegerOutOfRangeError({max:n.toString(),min:i.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:Be.fromNumber(e,{size:32,signed:t})}}function jK(e){let t=Be.fromString(e),r=Math.ceil(Be.size(t)/32),n=[];for(let i=0;i<r;i++)n.push(Be.padRight(Be.slice(t,i*32,(i+1)*32)));return{dynamic:!0,encoded:Be.concat(Be.padRight(Be.fromNumber(Be.size(t),{size:32})),...n)}}function MK(e,t){let{checksumAddress:r,parameter:n}=t,i=!1,o=[];for(let s=0;s<n.components.length;s++){let a=n.components[s],c=Array.isArray(e)?s:a.name,u=Kw({checksumAddress:r,parameter:a,value:e[c]});o.push(u),u.dynamic&&(i=!0)}return{dynamic:i,encoded:i?o5(o):Be.concat(...o.map(({encoded:s})=>s))}}function Ww(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function nd(e){let{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return e.components?.some(nd);let r=Ww(e.type);return!!(r&&nd({...e,type:r[1]}))}});var Xw=g(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});Is.RecursiveReadLimitExceededError=Is.PositionOutOfBoundsError=Is.NegativeOffsetError=void 0;Is.create=D2e;var s5=Vr(),q2e={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new Yw({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new zw({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new Qg({offset:e});let t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new Qg({offset:e});let t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){let r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){let t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){let t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){let t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();let r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();let e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();let e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();let e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();let e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){let t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;let e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};function D2e(e,{recursiveReadLimit:t=8192}={}){let r=Object.create(q2e);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}var Qg=class extends s5.BaseError{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}};Is.NegativeOffsetError=Qg;var zw=class extends s5.BaseError{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"})}};Is.PositionOutOfBoundsError=zw;var Yw=class extends s5.BaseError{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"})}};Is.RecursiveReadLimitExceededError=Yw});var id=g(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.InvalidTypeError=St.InvalidArrayError=St.LengthMismatchError=St.BytesSizeMismatchError=St.ArrayLengthMismatchError=St.ZeroDataError=St.DataSizeTooSmallError=void 0;St.decode=U2e;St.encode=H2e;St.encodePacked=Qw;St.format=F2e;St.from=$2e;var Zw=Pf(),L2e=Of(),eh=ti(),od=Vr(),vo=Jt(),c5=qK(),B2e=Xw(),a5=Gw();function U2e(e,t,r={}){let{as:n="Array",checksumAddress:i=!1}=r,o=typeof t=="string"?eh.fromHex(t):t,s=B2e.create(o);if(eh.size(o)===0&&e.length>0)throw new t1;if(eh.size(o)&&eh.size(o)<32)throw new e1({data:typeof t=="string"?t:vo.fromBytes(t),parameters:e,size:eh.size(o)});let a=0,c=n==="Array"?[]:{};for(let u=0;u<e.length;++u){let d=e[u];a<o.length&&s.setPosition(a);let[l,m]=c5.decodeParameter(s,d,{checksumAddress:i,staticPosition:0});a+=m,n==="Array"?c.push(l):c[d.name??u]=l}return c}function H2e(e,t,r){let{checksumAddress:n=!1}=r??{};if(e.length!==t.length)throw new th({expectedLength:e.length,givenLength:t.length});let i=c5.prepareParameters({checksumAddress:n,parameters:e,values:t}),o=c5.encode(i);return o.length===0?"0x":o}function Qw(e,t){if(e.length!==t.length)throw new th({expectedLength:e.length,givenLength:t.length});let r=[];for(let n=0;n<e.length;n++){let i=e[n],o=t[n];r.push(Qw.encode(i,o))}return vo.concat(...r)}(function(e){function t(r,n,i=!1){if(r==="address"){let c=n;return L2e.assert(c),vo.padLeft(c.toLowerCase(),i?32:0)}if(r==="string")return vo.fromString(n);if(r==="bytes")return n;if(r==="bool")return vo.padLeft(vo.fromBoolean(n),i?32:1);let o=r.match(a5.integerRegex);if(o){let[c,u,d="256"]=o,l=Number.parseInt(d,10)/8;return vo.fromNumber(n,{size:i?32:l,signed:u==="int"})}let s=r.match(a5.bytesRegex);if(s){let[c,u]=s;if(Number.parseInt(u,10)!==(n.length-2)/2)throw new r1({expectedSize:Number.parseInt(u,10),value:n});return vo.padRight(n,i?32:0)}let a=r.match(a5.arrayRegex);if(a&&Array.isArray(n)){let[c,u]=a,d=[];for(let l=0;l<n.length;l++)d.push(t(u,n[l],!0));return d.length===0?"0x":vo.concat(...d)}throw new n1(r)}e.encode=t})(Qw||(St.encodePacked=Qw={}));function F2e(e){return Zw.formatAbiParameters(e)}function $2e(e){return Array.isArray(e)&&typeof e[0]=="string"||typeof e=="string"?Zw.parseAbiParameters(e):e}var e1=class extends od.BaseError{constructor({data:t,parameters:r,size:n}){super(`Data size of ${n} bytes is too small for given parameters.`,{metaMessages:[`Params: (${Zw.formatAbiParameters(r)})`,`Data: ${t} (${n} bytes)`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"})}};St.DataSizeTooSmallError=e1;var t1=class extends od.BaseError{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.'),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ZeroDataError"})}};St.ZeroDataError=t1;var u5=class extends od.BaseError{constructor({expectedLength:t,givenLength:r,type:n}){super(`Array length mismatch for type \`${n}\`. Expected: \`${t}\`. Given: \`${r}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}};St.ArrayLengthMismatchError=u5;var r1=class extends od.BaseError{constructor({expectedSize:t,value:r}){super(`Size of bytes "${r}" (bytes${vo.size(r)}) does not match expected size (bytes${t}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}};St.BytesSizeMismatchError=r1;var th=class extends od.BaseError{constructor({expectedLength:t,givenLength:r}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${t}`,`Given length (values): ${r}`].join(`
61
+ `)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}};St.LengthMismatchError=th;var d5=class extends od.BaseError{constructor(t){super(`Value \`${t}\` is not a valid array.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}};St.InvalidArrayError=d5;var n1=class extends od.BaseError{constructor(t){super(`Type \`${t}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}};St.InvalidTypeError=n1});var $K=g(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});Ci.toBytes=J2e;Ci.toHex=V2e;Ci.to=f5;Ci.decodeRlpCursor=p5;Ci.readLength=l5;Ci.readList=UK;Ci.from=m5;Ci.fromBytes=G2e;Ci.fromHex=K2e;var DK=ti(),LK=Vr(),i1=Jt(),BK=Xw();function J2e(e){return f5(e,"Bytes")}function V2e(e){return f5(e,"Hex")}function f5(e,t){let r=t??(typeof e=="string"?"Hex":"Bytes"),n=(()=>{if(typeof e=="string"){if(e.length>3&&e.length%2!==0)throw new i1.InvalidLengthError(e);return DK.fromHex(e)}return e})(),i=BK.create(n,{recursiveReadLimit:Number.POSITIVE_INFINITY});return p5(i,r)}function p5(e,t="Hex"){if(e.bytes.length===0)return t==="Hex"?i1.fromBytes(e.bytes):e.bytes;let r=e.readByte();if(r<128&&e.decrementPosition(1),r<192){let i=l5(e,r,128),o=e.readBytes(i);return t==="Hex"?i1.fromBytes(o):o}let n=l5(e,r,192);return UK(e,n,t)}function l5(e,t,r){if(r===128&&t<128)return 1;if(t<=r+55)return t-r;if(t===r+55+1)return e.readUint8();if(t===r+55+2)return e.readUint16();if(t===r+55+3)return e.readUint24();if(t===r+55+4)return e.readUint32();throw new LK.BaseError("Invalid RLP prefix")}function UK(e,t,r){let n=e.position,i=[];for(;e.position-n<t;)i.push(p5(e,r));return i}function m5(e,t){let{as:r}=t,n=HK(e),i=BK.create(new Uint8Array(n.length));return n.encode(i),r==="Hex"?i1.fromBytes(i.bytes):i.bytes}function G2e(e,t={}){let{as:r="Bytes"}=t;return m5(e,{as:r})}function K2e(e,t={}){let{as:r="Hex"}=t;return m5(e,{as:r})}function HK(e){return Array.isArray(e)?W2e(e.map(t=>HK(t))):z2e(e)}function W2e(e){let t=e.reduce((i,o)=>i+o.length,0),r=FK(t);return{length:t<=55?1+t:1+r+t,encode(i){t<=55?i.pushByte(192+t):(i.pushByte(247+r),r===1?i.pushUint8(t):r===2?i.pushUint16(t):r===3?i.pushUint24(t):i.pushUint32(t));for(let{encode:o}of e)o(i)}}}function z2e(e){let t=typeof e=="string"?DK.fromHex(e):e,r=FK(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length,encode(i){t.length===1&&t[0]<128?i.pushBytes(t):t.length<=55?(i.pushByte(128+t.length),i.pushBytes(t)):(i.pushByte(183+r),r===1?i.pushUint8(t.length):r===2?i.pushUint16(t.length):r===3?i.pushUint24(t.length):i.pushUint32(t.length),i.pushBytes(t))}}}function FK(e){if(e<=255)return 1;if(e<=65535)return 2;if(e<=16777215)return 3;if(e<=4294967295)return 4;throw new LK.BaseError("Length is too large.")}});var b5=g(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.InvalidVError=Ce.InvalidYParityError=Ce.InvalidSError=Ce.InvalidRError=Ce.MissingPropertiesError=Ce.InvalidSerializedSizeError=void 0;Ce.assert=u1;Ce.fromBytes=VK;Ce.fromHex=h5;Ce.extract=Z2e;Ce.from=y5;Ce.fromDerBytes=Q2e;Ce.fromDerHex=GK;Ce.fromLegacy=KK;Ce.fromRpc=WK;Ce.fromTuple=eOe;Ce.toBytes=tOe;Ce.toHex=zK;Ce.toDerBytes=rOe;Ce.toDerHex=nOe;Ce.toLegacy=iOe;Ce.toRpc=oOe;Ce.toTuple=sOe;Ce.validate=aOe;Ce.vToYParity=d1;Ce.yParityToV=_5;var g5=Ga(),Y2e=ti(),Nf=Vr(),pr=Jt(),X2e=cg(),JK=Gw();function u1(e,t={}){let{recovered:r}=t;if(typeof e.r>"u")throw new Cf({signature:e});if(typeof e.s>"u")throw new Cf({signature:e});if(r&&typeof e.yParity>"u")throw new Cf({signature:e});if(e.r<0n||e.r>JK.maxUint256)throw new s1({value:e.r});if(e.s<0n||e.s>JK.maxUint256)throw new a1({value:e.s});if(typeof e.yParity=="number"&&e.yParity!==0&&e.yParity!==1)throw new sd({value:e.yParity})}function VK(e){return h5(pr.fromBytes(e))}function h5(e){if(e.length!==130&&e.length!==132)throw new o1({signature:e});let t=BigInt(pr.slice(e,0,32)),r=BigInt(pr.slice(e,32,64)),n=(()=>{let i=+`0x${e.slice(130)}`;if(!Number.isNaN(i))try{return d1(i)}catch{throw new sd({value:i})}})();return typeof n>"u"?{r:t,s:r}:{r:t,s:r,yParity:n}}function Z2e(e){if(!(typeof e.r>"u")&&!(typeof e.s>"u"))return y5(e)}function y5(e){let t=typeof e=="string"?h5(e):e instanceof Uint8Array?VK(e):typeof e.r=="string"?WK(e):e.v?KK(e):{r:e.r,s:e.s,...typeof e.yParity<"u"?{yParity:e.yParity}:{}};return u1(t),t}function Q2e(e){return GK(pr.fromBytes(e))}function GK(e){let{r:t,s:r}=g5.secp256k1.Signature.fromDER(pr.from(e).slice(2));return{r:t,s:r}}function KK(e){return{r:e.r,s:e.s,yParity:d1(e.v)}}function WK(e){let t=(()=>{let r=e.v?Number(e.v):void 0,n=e.yParity?Number(e.yParity):void 0;if(typeof r=="number"&&typeof n!="number"&&(n=d1(r)),typeof n!="number")throw new sd({value:e.yParity});return n})();return{r:BigInt(e.r),s:BigInt(e.s),yParity:t}}function eOe(e){let[t,r,n]=e;return y5({r:r==="0x"?0n:BigInt(r),s:n==="0x"?0n:BigInt(n),yParity:t==="0x"?0:Number(t)})}function tOe(e){return Y2e.fromHex(zK(e))}function zK(e){u1(e);let t=e.r,r=e.s;return pr.concat(pr.fromNumber(t,{size:32}),pr.fromNumber(r,{size:32}),typeof e.yParity=="number"?pr.fromNumber(_5(e.yParity),{size:1}):"0x")}function rOe(e){return new g5.secp256k1.Signature(e.r,e.s).toDERRawBytes()}function nOe(e){return`0x${new g5.secp256k1.Signature(e.r,e.s).toDERHex()}`}function iOe(e){return{r:e.r,s:e.s,v:_5(e.yParity)}}function oOe(e){let{r:t,s:r,yParity:n}=e;return{r:pr.fromNumber(t,{size:32}),s:pr.fromNumber(r,{size:32}),yParity:n===0?"0x0":"0x1"}}function sOe(e){let{r:t,s:r,yParity:n}=e;return[n?"0x01":"0x",t===0n?"0x":pr.trimLeft(pr.fromNumber(t)),r===0n?"0x":pr.trimLeft(pr.fromNumber(r))]}function aOe(e,t={}){try{return u1(e,t),!0}catch{return!1}}function d1(e){if(e===0||e===27)return 0;if(e===1||e===28)return 1;if(e>=35)return e%2===0?1:0;throw new c1({value:e})}function _5(e){if(e===0)return 27;if(e===1)return 28;throw new sd({value:e})}var o1=class extends Nf.BaseError{constructor({signature:t}){super(`Value \`${t}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${pr.size(pr.from(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}};Ce.InvalidSerializedSizeError=o1;var Cf=class extends Nf.BaseError{constructor({signature:t}){super(`Signature \`${X2e.stringify(t)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}};Ce.MissingPropertiesError=Cf;var s1=class extends Nf.BaseError{constructor({value:t}){super(`Value \`${t}\` is an invalid r value. r must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}};Ce.InvalidRError=s1;var a1=class extends Nf.BaseError{constructor({value:t}){super(`Value \`${t}\` is an invalid s value. s must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}};Ce.InvalidSError=a1;var sd=class extends Nf.BaseError{constructor({value:t}){super(`Value \`${t}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}};Ce.InvalidYParityError=sd;var c1=class extends Nf.BaseError{constructor({value:t}){super(`Value \`${t}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}};Ce.InvalidVError=c1});var eW=g(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.from=YK;Dn.fromRpc=E5;Dn.fromRpcList=dOe;Dn.fromTuple=XK;Dn.fromTupleList=lOe;Dn.getSignPayload=fOe;Dn.hash=ZK;Dn.toRpc=QK;Dn.toRpcList=pOe;Dn.toTuple=w5;Dn.toTupleList=mOe;var cOe=Wg(),rh=Jt(),uOe=$K(),nh=b5();function YK(e,t={}){return typeof e.chainId=="string"?E5(e):{...e,...t.signature}}function E5(e){let{address:t,chainId:r,nonce:n}=e,i=nh.extract(e);return{address:t,chainId:Number(r),nonce:BigInt(n),...i}}function dOe(e){return e.map(E5)}function XK(e){let[t,r,n,i,o,s]=e,a={address:r,chainId:t==="0x"?0:Number(t),nonce:n==="0x"?0n:BigInt(n)};return i&&o&&s&&(a={...a,...nh.fromTuple([i,o,s])}),YK(a)}function lOe(e){let t=[];for(let r of e)t.push(XK(r));return t}function fOe(e){return ZK(e,{presign:!0})}function ZK(e,t={}){let{presign:r}=t;return cOe.keccak256(rh.concat("0x05",uOe.fromHex(w5(r?{address:e.address,chainId:e.chainId,nonce:e.nonce}:e))))}function QK(e){let{address:t,chainId:r,nonce:n,...i}=e;return{address:t,chainId:rh.fromNumber(r),nonce:rh.fromNumber(n),...nh.toRpc(i)}}function pOe(e){return e.map(QK)}function w5(e){let{address:t,chainId:r,nonce:n}=e,i=nh.extract(e);return[r?rh.fromNumber(r):"0x",t,n?rh.fromNumber(n):"0x",...i?nh.toTuple(i):[]]}function mOe(e){if(!e||e.length===0)return[];let t=[];for(let r of e)t.push(w5(r));return t}});var tW=g(kf=>{"use strict";Object.defineProperty(kf,"__esModule",{value:!0});kf.extraEntropy=void 0;kf.setExtraEntropy=gOe;kf.extraEntropy=!1;function gOe(e){kf.extraEntropy=e}});var aW=g(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});ai.noble=void 0;ai.createKeyPair=yOe;ai.getPublicKey=nW;ai.getSharedSecret=_Oe;ai.randomPrivateKey=iW;ai.recoverAddress=oW;ai.recoverPublicKey=sW;ai.sign=bOe;ai.verify=EOe;var ac=Ga(),rW=Of(),v5=ti(),jf=Jt(),hOe=tW(),l1=e5();ai.noble=ac.secp256k1;function yOe(e={}){let{as:t="Hex"}=e,r=iW({as:t}),n=nW({privateKey:r});return{privateKey:r,publicKey:n}}function nW(e){let{privateKey:t}=e,r=ac.secp256k1.ProjectivePoint.fromPrivateKey(jf.from(t).slice(2));return l1.from(r)}function _Oe(e){let{as:t="Hex",privateKey:r,publicKey:n}=e,s=ac.secp256k1.ProjectivePoint.fromHex(l1.toHex(n).slice(2)).multiply(ac.secp256k1.utils.normPrivateKeyToScalar(jf.from(r).slice(2))).toRawBytes(!0);return t==="Hex"?jf.fromBytes(s):s}function iW(e={}){let{as:t="Hex"}=e,r=ac.secp256k1.utils.randomPrivateKey();return t==="Hex"?jf.fromBytes(r):r}function oW(e){return rW.fromPublicKey(sW(e))}function sW(e){let{payload:t,signature:r}=e,{r:n,s:i,yParity:o}=r,a=new ac.secp256k1.Signature(BigInt(n),BigInt(i)).addRecoveryBit(o).recoverPublicKey(jf.from(t).substring(2));return l1.from(a)}function bOe(e){let{extraEntropy:t=hOe.extraEntropy,hash:r,payload:n,privateKey:i}=e,{r:o,s,recovery:a}=ac.secp256k1.sign(v5.from(n),v5.from(i),{extraEntropy:typeof t=="boolean"?t:jf.from(t).slice(2),lowS:!0,...r?{prehash:!0}:{}});return{r:o,s,yParity:a}}function EOe(e){let{hash:t,payload:r}=e;return e.address?rW.isEqual(e.address,oW({payload:r,signature:e.signature})):ac.secp256k1.verify(e.signature,v5.from(r),l1.toBytes(e.publicKey),...t?[{prehash:!0,lowS:!0}]:[])}});var lW=g(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.InvalidWrappedSignatureError=mr.suffixParameters=mr.magicBytes=void 0;mr.assert=p1;mr.from=SOe;mr.unwrap=dW;mr.wrap=AOe;mr.validate=IOe;var S5=id(),cW=eW(),wOe=Vr(),cc=Jt(),vOe=aW(),uW=b5();mr.magicBytes="0x8010801080108010801080108010801080108010801080108010801080108010";mr.suffixParameters=S5.from("(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data");function p1(e){if(typeof e=="string"){if(cc.slice(e,-32)!==mr.magicBytes)throw new f1(e)}else uW.assert(e.authorization)}function SOe(e){return typeof e=="string"?dW(e):e}function dW(e){p1(e);let t=cc.toNumber(cc.slice(e,-64,-32)),r=cc.slice(e,-t-64,-64),n=cc.slice(e,0,-t-64),[i,o,s]=S5.decode(mr.suffixParameters,r);return{authorization:cW.from({address:i.delegation,chainId:Number(i.chainId),nonce:i.nonce,yParity:i.yParity,r:i.r,s:i.s}),signature:n,...s&&s!=="0x"?{data:s,to:o}:{}}}function AOe(e){let{data:t,signature:r}=e;p1(e);let n=vOe.recoverAddress({payload:cW.getSignPayload(e.authorization),signature:uW.from(e.authorization)}),i=S5.encode(mr.suffixParameters,[{...e.authorization,delegation:e.authorization.address,chainId:BigInt(e.authorization.chainId)},e.to??n,t??"0x"]),o=cc.fromNumber(cc.size(i),{size:32});return cc.concat(r,i,o,mr.magicBytes)}function IOe(e){try{return p1(e),!0}catch{return!1}}var f1=class extends wOe.BaseError{constructor(t){super(`Value \`${t}\` is an invalid ERC-8010 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc8010.InvalidWrappedSignatureError"})}};mr.InvalidWrappedSignatureError=f1});var ih=g(m1=>{"use strict";Object.defineProperty(m1,"__esModule",{value:!0});m1.SignatureErc8010=void 0;m1.SignatureErc8010=lW()});var g1=g(A5=>{"use strict";Object.defineProperty(A5,"__esModule",{value:!0});A5.isErc8010Signature=TOe;var POe=ih();function TOe(e){return POe.SignatureErc8010.validate(e)}});var P5=g(I5=>{"use strict";Object.defineProperty(I5,"__esModule",{value:!0});I5.parseErc6492Signature=ROe;var xOe=os(),OOe=Rw();function ROe(e){if(!(0,OOe.isErc6492Signature)(e))return{signature:e};let[t,r,n]=(0,xOe.decodeAbiParameters)([{type:"address"},{type:"bytes"},{type:"bytes"}],e);return{address:t,data:r,signature:n}}});var x5=g(T5=>{"use strict";Object.defineProperty(T5,"__esModule",{value:!0});T5.parseErc8010Signature=kOe;var COe=ih(),fW=W(),NOe=g1();function kOe(e){if(!(0,NOe.isErc8010Signature)(e))return{signature:e};let{authorization:t,to:r,...n}=COe.SignatureErc8010.unwrap(e);return{authorization:{address:t.address,chainId:t.chainId,nonce:Number(t.nonce),r:(0,fW.numberToHex)(t.r,{size:32}),s:(0,fW.numberToHex)(t.s,{size:32}),yParity:t.yParity},...r?{address:r}:{},...n}}});var h1=g(O5=>{"use strict";Object.defineProperty(O5,"__esModule",{value:!0});O5.recoverMessageAddress=qOe;var jOe=yf(),MOe=ds();async function qOe({message:e,signature:t}){return(0,MOe.recoverAddress)({hash:(0,jOe.hashMessage)(e),signature:t})}});var y1=g(R5=>{"use strict";Object.defineProperty(R5,"__esModule",{value:!0});R5.recoverTypedDataAddress=BOe;var DOe=bf(),LOe=ds();async function BOe(e){let{domain:t,message:r,primaryType:n,signature:i,types:o}=e;return(0,LOe.recoverAddress)({hash:(0,DOe.hashTypedData)({domain:t,message:r,primaryType:n,types:o}),signature:i})}});var N5=g(C5=>{"use strict";Object.defineProperty(C5,"__esModule",{value:!0});C5.serializeErc6492Signature=JOe;var UOe=Ow(),HOe=zn(),FOe=Nt(),$Oe=Je();function JOe(e){let{address:t,data:r,signature:n,to:i="hex"}=e,o=(0,FOe.concatHex)([(0,HOe.encodeAbiParameters)([{type:"address"},{type:"bytes"},{type:"bytes"}],[t,r,n]),UOe.erc6492MagicBytes]);return i==="hex"?o:(0,$Oe.hexToBytes)(o)}});var j5=g(k5=>{"use strict";Object.defineProperty(k5,"__esModule",{value:!0});k5.serializeErc8010Signature=KOe;var VOe=ih(),GOe=Je();function KOe(e){let{address:t,data:r,signature:n,to:i="hex"}=e,o=VOe.SignatureErc8010.wrap({authorization:{address:e.authorization.address,chainId:e.authorization.chainId,nonce:BigInt(e.authorization.nonce),r:BigInt(e.authorization.r),s:BigInt(e.authorization.s),yParity:e.authorization.yParity},data:r,signature:n,to:t});return i==="hex"?o:(0,GOe.hexToBytes)(o)}});var q5=g(M5=>{"use strict";Object.defineProperty(M5,"__esModule",{value:!0});M5.verifyHash=XOe;var WOe=Ir(),zOe=ln(),YOe=ds();async function XOe({address:e,hash:t,signature:r}){return(0,zOe.isAddressEqual)((0,WOe.getAddress)(e),await(0,YOe.recoverAddress)({hash:t,signature:r}))}});var L5=g(D5=>{"use strict";Object.defineProperty(D5,"__esModule",{value:!0});D5.verifyMessage=t6e;var ZOe=Ir(),QOe=ln(),e6e=h1();async function t6e({address:e,message:t,signature:r}){return(0,QOe.isAddressEqual)((0,ZOe.getAddress)(e),await(0,e6e.recoverMessageAddress)({message:t,signature:r}))}});var U5=g(B5=>{"use strict";Object.defineProperty(B5,"__esModule",{value:!0});B5.verifyTypedData=o6e;var r6e=Ir(),n6e=ln(),i6e=y1();async function o6e(e){let{address:t,domain:r,message:n,primaryType:i,signature:o,types:s}=e;return(0,n6e.isAddressEqual)((0,r6e.getAddress)(t),await(0,i6e.recoverTypedDataAddress)({domain:r,message:n,primaryType:i,signature:o,types:s}))}});var _1=g(H5=>{"use strict";Object.defineProperty(H5,"__esModule",{value:!0});H5.getSerializedTransactionType=u6e;var s6e=Xt(),a6e=on(),c6e=pt();function u6e(e){let t=(0,a6e.sliceHex)(e,0,1);if(t==="0x04")return"eip7702";if(t==="0x03")return"eip4844";if(t==="0x02")return"eip1559";if(t==="0x01")return"eip2930";if(t!=="0x"&&(0,c6e.hexToNumber)(t)>=192)return"legacy";throw new s6e.InvalidSerializedTransactionTypeError({serializedType:t})}});var b1=g(uh=>{"use strict";Object.defineProperty(uh,"__esModule",{value:!0});uh.parseTransaction=h6e;uh.toTransactionArray=sh;uh.parseAccessList=ah;var d6e=Wn(),ad=Xt(),l6e=Pr(),f6e=rg(),Ne=Sr(),pW=oo(),p6e=ts(),Me=pt(),mW=KE(),m6e=WE(),oh=xg(),g6e=_1();function h6e(e){let t=(0,g6e.getSerializedTransactionType)(e);return t==="eip1559"?b6e(e):t==="eip2930"?E6e(e):t==="eip4844"?_6e(e):t==="eip7702"?y6e(e):w6e(e)}function y6e(e){let t=sh(e),[r,n,i,o,s,a,c,u,d,l,m,p,h]=t;if(t.length!==10&&t.length!==13)throw new ad.InvalidSerializedTransactionError({attributes:{chainId:r,nonce:n,maxPriorityFeePerGas:i,maxFeePerGas:o,gas:s,to:a,value:c,data:u,accessList:d,authorizationList:l,...t.length>9?{v:m,r:p,s:h}:{}},serializedTransaction:e,type:"eip7702"});let y={chainId:(0,Me.hexToNumber)(r),type:"eip7702"};return(0,Ne.isHex)(a)&&a!=="0x"&&(y.to=a),(0,Ne.isHex)(s)&&s!=="0x"&&(y.gas=(0,Me.hexToBigInt)(s)),(0,Ne.isHex)(u)&&u!=="0x"&&(y.data=u),(0,Ne.isHex)(n)&&(y.nonce=n==="0x"?0:(0,Me.hexToNumber)(n)),(0,Ne.isHex)(c)&&c!=="0x"&&(y.value=(0,Me.hexToBigInt)(c)),(0,Ne.isHex)(o)&&o!=="0x"&&(y.maxFeePerGas=(0,Me.hexToBigInt)(o)),(0,Ne.isHex)(i)&&i!=="0x"&&(y.maxPriorityFeePerGas=(0,Me.hexToBigInt)(i)),d.length!==0&&d!=="0x"&&(y.accessList=ah(d)),l.length!==0&&l!=="0x"&&(y.authorizationList=v6e(l)),(0,oh.assertTransactionEIP7702)(y),{...t.length===13?ch(t):void 0,...y}}function _6e(e){let t=sh(e),r=t.length===4,n=r?t[0]:t,i=r?t.slice(1):[],[o,s,a,c,u,d,l,m,p,h,y,b,v,A]=n,[E,S,I]=i;if(!(n.length===11||n.length===14))throw new ad.InvalidSerializedTransactionError({attributes:{chainId:o,nonce:s,maxPriorityFeePerGas:a,maxFeePerGas:c,gas:u,to:d,value:l,data:m,accessList:p,...n.length>9?{v:b,r:v,s:A}:{}},serializedTransaction:e,type:"eip4844"});let T={blobVersionedHashes:y,chainId:(0,Me.hexToNumber)(o),to:d,type:"eip4844"};return(0,Ne.isHex)(u)&&u!=="0x"&&(T.gas=(0,Me.hexToBigInt)(u)),(0,Ne.isHex)(m)&&m!=="0x"&&(T.data=m),(0,Ne.isHex)(s)&&(T.nonce=s==="0x"?0:(0,Me.hexToNumber)(s)),(0,Ne.isHex)(l)&&l!=="0x"&&(T.value=(0,Me.hexToBigInt)(l)),(0,Ne.isHex)(h)&&h!=="0x"&&(T.maxFeePerBlobGas=(0,Me.hexToBigInt)(h)),(0,Ne.isHex)(c)&&c!=="0x"&&(T.maxFeePerGas=(0,Me.hexToBigInt)(c)),(0,Ne.isHex)(a)&&a!=="0x"&&(T.maxPriorityFeePerGas=(0,Me.hexToBigInt)(a)),p.length!==0&&p!=="0x"&&(T.accessList=ah(p)),E&&S&&I&&(T.sidecars=(0,f6e.toBlobSidecars)({blobs:E,commitments:S,proofs:I})),(0,oh.assertTransactionEIP4844)(T),{...n.length===14?ch(n):void 0,...T}}function b6e(e){let t=sh(e),[r,n,i,o,s,a,c,u,d,l,m,p]=t;if(!(t.length===9||t.length===12))throw new ad.InvalidSerializedTransactionError({attributes:{chainId:r,nonce:n,maxPriorityFeePerGas:i,maxFeePerGas:o,gas:s,to:a,value:c,data:u,accessList:d,...t.length>9?{v:l,r:m,s:p}:{}},serializedTransaction:e,type:"eip1559"});let h={chainId:(0,Me.hexToNumber)(r),type:"eip1559"};return(0,Ne.isHex)(a)&&a!=="0x"&&(h.to=a),(0,Ne.isHex)(s)&&s!=="0x"&&(h.gas=(0,Me.hexToBigInt)(s)),(0,Ne.isHex)(u)&&u!=="0x"&&(h.data=u),(0,Ne.isHex)(n)&&(h.nonce=n==="0x"?0:(0,Me.hexToNumber)(n)),(0,Ne.isHex)(c)&&c!=="0x"&&(h.value=(0,Me.hexToBigInt)(c)),(0,Ne.isHex)(o)&&o!=="0x"&&(h.maxFeePerGas=(0,Me.hexToBigInt)(o)),(0,Ne.isHex)(i)&&i!=="0x"&&(h.maxPriorityFeePerGas=(0,Me.hexToBigInt)(i)),d.length!==0&&d!=="0x"&&(h.accessList=ah(d)),(0,oh.assertTransactionEIP1559)(h),{...t.length===12?ch(t):void 0,...h}}function E6e(e){let t=sh(e),[r,n,i,o,s,a,c,u,d,l,m]=t;if(!(t.length===8||t.length===11))throw new ad.InvalidSerializedTransactionError({attributes:{chainId:r,nonce:n,gasPrice:i,gas:o,to:s,value:a,data:c,accessList:u,...t.length>8?{v:d,r:l,s:m}:{}},serializedTransaction:e,type:"eip2930"});let p={chainId:(0,Me.hexToNumber)(r),type:"eip2930"};return(0,Ne.isHex)(s)&&s!=="0x"&&(p.to=s),(0,Ne.isHex)(o)&&o!=="0x"&&(p.gas=(0,Me.hexToBigInt)(o)),(0,Ne.isHex)(c)&&c!=="0x"&&(p.data=c),(0,Ne.isHex)(n)&&(p.nonce=n==="0x"?0:(0,Me.hexToNumber)(n)),(0,Ne.isHex)(a)&&a!=="0x"&&(p.value=(0,Me.hexToBigInt)(a)),(0,Ne.isHex)(i)&&i!=="0x"&&(p.gasPrice=(0,Me.hexToBigInt)(i)),u.length!==0&&u!=="0x"&&(p.accessList=ah(u)),(0,oh.assertTransactionEIP2930)(p),{...t.length===11?ch(t):void 0,...p}}function w6e(e){let t=(0,mW.fromRlp)(e,"hex"),[r,n,i,o,s,a,c,u,d]=t;if(!(t.length===6||t.length===9))throw new ad.InvalidSerializedTransactionError({attributes:{nonce:r,gasPrice:n,gas:i,to:o,value:s,data:a,...t.length>6?{v:c,r:u,s:d}:{}},serializedTransaction:e,type:"legacy"});let l={type:"legacy"};if((0,Ne.isHex)(o)&&o!=="0x"&&(l.to=o),(0,Ne.isHex)(i)&&i!=="0x"&&(l.gas=(0,Me.hexToBigInt)(i)),(0,Ne.isHex)(a)&&a!=="0x"&&(l.data=a),(0,Ne.isHex)(r)&&(l.nonce=r==="0x"?0:(0,Me.hexToNumber)(r)),(0,Ne.isHex)(s)&&s!=="0x"&&(l.value=(0,Me.hexToBigInt)(s)),(0,Ne.isHex)(n)&&n!=="0x"&&(l.gasPrice=(0,Me.hexToBigInt)(n)),(0,oh.assertTransactionLegacy)(l),t.length===6)return l;let m=(0,Ne.isHex)(c)&&c!=="0x"?(0,Me.hexToBigInt)(c):0n;if(d==="0x"&&u==="0x")return m>0&&(l.chainId=Number(m)),l;let p=m,h=Number((p-35n)/2n);if(h>0)l.chainId=h;else if(p!==27n&&p!==28n)throw new ad.InvalidLegacyVError({v:p});return l.v=p,l.s=d,l.r=u,l.yParity=p%2n===0n?1:0,l}function sh(e){return(0,mW.fromRlp)(`0x${e.slice(4)}`,"hex")}function ah(e){let t=[];for(let r=0;r<e.length;r++){let[n,i]=e[r];if(!(0,l6e.isAddress)(n,{strict:!1}))throw new d6e.InvalidAddressError({address:n});t.push({address:n,storageKeys:i.map(o=>(0,m6e.isHash)(o)?o:(0,p6e.trim)(o))})}return t}function v6e(e){let t=[];for(let r=0;r<e.length;r++){let[n,i,o,s,a,c]=e[r];t.push({address:i,chainId:n==="0x"?0:(0,Me.hexToNumber)(n),nonce:o==="0x"?0:(0,Me.hexToNumber)(o),...ch([s,a,c])})}return t}function ch(e){let t=e.slice(-3),r=t[0]==="0x"?0n:(0,Me.hexToBigInt)(t[0]);if(r!==0n&&r!==1n)throw new ad.InvalidYParityError({yParity:r});let n=r===0n?27n:28n;return{r:(0,pW.padHex)(t[1],{size:32}),s:(0,pW.padHex)(t[2],{size:32}),v:n,yParity:n===27n?0:1}}});var Mf=g(F5=>{"use strict";Object.defineProperty(F5,"__esModule",{value:!0});F5.formatUnits=A6e;var S6e=Iu();function A6e(e,t){return S6e.format(e,t)}});var J5=g($5=>{"use strict";Object.defineProperty($5,"__esModule",{value:!0});$5.parseEther=P6e;var I6e=Iu();function P6e(e,t="wei"){return I6e.fromEther(e,t)}});var G5=g(V5=>{"use strict";Object.defineProperty(V5,"__esModule",{value:!0});V5.parseGwei=x6e;var T6e=Iu();function x6e(e,t="wei"){return T6e.fromGwei(e,t)}});var E1=g(K5=>{"use strict";Object.defineProperty(K5,"__esModule",{value:!0});K5.parseUnits=R6e;var O6e=Iu();function R6e(e,t){return O6e.from(e,t)}});var tk=g(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});w.isHex=w.isBytes=w.concatHex=w.concatBytes=w.concat=w.getChainContractAddress=w.filterChains=w.extractChain=w.defineChain=w.assertCurrentChain=w.ccipReadTunnel=w.offchainLookupSignature=w.offchainLookupAbiItem=w.offchainLookup=w.ccipFetch=w.ccipRequest=w.buildRequest=w.verifyAuthorization=w.serializeAuthorizationList=w.recoverAuthorizationAddress=w.hashAuthorization=w.isAddressEqual=w.isAddress=w.getCreateAddress=w.getCreate2Address=w.getContractAddress=w.getAddress=w.parseEventLogs=w.getAbiItem=w.formatAbiItemWithArgs=w.formatAbiParams=w.formatAbiItem=w.encodePacked=w.encodeFunctionResult=w.encodeFunctionData=w.encodeEventTopics=w.encodeErrorResult=w.encodeDeployData=w.encodeAbiParameters=w.decodeFunctionResult=w.decodeFunctionData=w.decodeEventLog=w.decodeErrorResult=w.decodeAbiParameters=w.publicKeyToAddress=w.parseAccount=w.parseAbiParameters=w.parseAbiParameter=w.parseAbiItem=w.parseAbi=void 0;w.isHash=w.getAction=w.formatTransactionRequest=w.defineTransactionRequest=w.defineTransactionReceipt=w.transactionType=w.formatTransaction=w.defineTransaction=w.formatLog=w.defineFormatter=w.extract=w.formatBlock=w.defineBlock=w.getTransactionError=w.getNodeError=w.containsNodeError=w.getEstimateGasError=w.getContractError=w.getCallError=w.toRlp=w.toHex=w.stringToHex=w.numberToHex=w.bytesToHex=w.boolToHex=w.toBytes=w.stringToBytes=w.numberToBytes=w.hexToBytes=w.boolToBytes=w.fromRlp=w.hexToString=w.hexToNumber=w.hexToBool=w.hexToBigInt=w.fromHex=w.fromBytes=w.bytesToString=w.bytesToNumber=w.bytesToBool=w.bytesToBigint=w.bytesToBigInt=w.trim=w.sliceHex=w.sliceBytes=w.slice=w.size=w.padHex=w.padBytes=w.pad=void 0;w.serializeTransaction=w.serializeAccessList=w.parseTransaction=w.getTransactionType=w.getSerializedTransactionType=w.assertTransactionLegacy=w.assertTransactionEIP2930=w.assertTransactionEIP1559=w.assertRequest=w.stringify=w.verifyTypedData=w.verifyMessage=w.verifyHash=w.serializeErc8010Signature=w.serializeErc6492Signature=w.recoverTypedDataAddress=w.recoverPublicKey=w.recoverMessageAddress=w.recoverAddress=w.parseErc8010Signature=w.parseErc6492Signature=w.isErc8010Signature=w.isErc6492Signature=w.hashTypedData=w.hashStruct=w.hashMessage=w.getWebSocketRpcClient=w.socketClientCache=w.getSocketRpcClient=w.getHttpRpcClient=w.rpc=w.getSocket=w.integerRegex=w.bytesRegex=w.arrayRegex=w.nonceManager=w.createNonceManager=w.getFunctionSignature=w.toFunctionSignature=w.getFunctionSelector=w.toFunctionSelector=w.toFunctionHash=w.getEventSignature=w.toEventSignature=w.getEventSelector=w.toEventSelector=w.toEventHash=w.sha256=w.ripemd160=w.keccak256=void 0;w.parseUnits=w.parseGwei=w.parseEther=w.formatUnits=w.formatGwei=w.formatEther=w.validateTypedData=w.serializeTypedData=void 0;var w1=_m();Object.defineProperty(w,"parseAbi",{enumerable:!0,get:function(){return w1.parseAbi}});Object.defineProperty(w,"parseAbiItem",{enumerable:!0,get:function(){return w1.parseAbiItem}});Object.defineProperty(w,"parseAbiParameter",{enumerable:!0,get:function(){return w1.parseAbiParameter}});Object.defineProperty(w,"parseAbiParameters",{enumerable:!0,get:function(){return w1.parseAbiParameters}});var C6e=at();Object.defineProperty(w,"parseAccount",{enumerable:!0,get:function(){return C6e.parseAccount}});var N6e=u2();Object.defineProperty(w,"publicKeyToAddress",{enumerable:!0,get:function(){return N6e.publicKeyToAddress}});var k6e=os();Object.defineProperty(w,"decodeAbiParameters",{enumerable:!0,get:function(){return k6e.decodeAbiParameters}});var j6e=Ol();Object.defineProperty(w,"decodeErrorResult",{enumerable:!0,get:function(){return j6e.decodeErrorResult}});var M6e=Jl();Object.defineProperty(w,"decodeEventLog",{enumerable:!0,get:function(){return M6e.decodeEventLog}});var q6e=sE();Object.defineProperty(w,"decodeFunctionData",{enumerable:!0,get:function(){return q6e.decodeFunctionData}});var D6e=ei();Object.defineProperty(w,"decodeFunctionResult",{enumerable:!0,get:function(){return D6e.decodeFunctionResult}});var L6e=zn();Object.defineProperty(w,"encodeAbiParameters",{enumerable:!0,get:function(){return L6e.encodeAbiParameters}});var B6e=Xl();Object.defineProperty(w,"encodeDeployData",{enumerable:!0,get:function(){return B6e.encodeDeployData}});var U6e=aE();Object.defineProperty(w,"encodeErrorResult",{enumerable:!0,get:function(){return U6e.encodeErrorResult}});var H6e=Ca();Object.defineProperty(w,"encodeEventTopics",{enumerable:!0,get:function(){return H6e.encodeEventTopics}});var F6e=Tr();Object.defineProperty(w,"encodeFunctionData",{enumerable:!0,get:function(){return F6e.encodeFunctionData}});var $6e=uE();Object.defineProperty(w,"encodeFunctionResult",{enumerable:!0,get:function(){return $6e.encodeFunctionResult}});var J6e=YR();Object.defineProperty(w,"encodePacked",{enumerable:!0,get:function(){return J6e.encodePacked}});var gW=io();Object.defineProperty(w,"formatAbiItem",{enumerable:!0,get:function(){return gW.formatAbiItem}});Object.defineProperty(w,"formatAbiParams",{enumerable:!0,get:function(){return gW.formatAbiParams}});var V6e=Sx();Object.defineProperty(w,"formatAbiItemWithArgs",{enumerable:!0,get:function(){return V6e.formatAbiItemWithArgs}});var G6e=so();Object.defineProperty(w,"getAbiItem",{enumerable:!0,get:function(){return G6e.getAbiItem}});var K6e=Ya();Object.defineProperty(w,"parseEventLogs",{enumerable:!0,get:function(){return K6e.parseEventLogs}});var W6e=Ir();Object.defineProperty(w,"getAddress",{enumerable:!0,get:function(){return W6e.getAddress}});var W5=QR();Object.defineProperty(w,"getContractAddress",{enumerable:!0,get:function(){return W5.getContractAddress}});Object.defineProperty(w,"getCreate2Address",{enumerable:!0,get:function(){return W5.getCreate2Address}});Object.defineProperty(w,"getCreateAddress",{enumerable:!0,get:function(){return W5.getCreateAddress}});var z6e=Pr();Object.defineProperty(w,"isAddress",{enumerable:!0,get:function(){return z6e.isAddress}});var Y6e=ln();Object.defineProperty(w,"isAddressEqual",{enumerable:!0,get:function(){return Y6e.isAddressEqual}});var X6e=$2();Object.defineProperty(w,"hashAuthorization",{enumerable:!0,get:function(){return X6e.hashAuthorization}});var Z6e=ql();Object.defineProperty(w,"recoverAuthorizationAddress",{enumerable:!0,get:function(){return Z6e.recoverAuthorizationAddress}});var Q6e=iC();Object.defineProperty(w,"serializeAuthorizationList",{enumerable:!0,get:function(){return Q6e.serializeAuthorizationList}});var eRe=aC();Object.defineProperty(w,"verifyAuthorization",{enumerable:!0,get:function(){return eRe.verifyAuthorization}});var tRe=cC();Object.defineProperty(w,"buildRequest",{enumerable:!0,get:function(){return tRe.buildRequest}});var dh=gg();Object.defineProperty(w,"ccipRequest",{enumerable:!0,get:function(){return dh.ccipRequest}});Object.defineProperty(w,"ccipFetch",{enumerable:!0,get:function(){return dh.ccipRequest}});Object.defineProperty(w,"offchainLookup",{enumerable:!0,get:function(){return dh.offchainLookup}});Object.defineProperty(w,"offchainLookupAbiItem",{enumerable:!0,get:function(){return dh.offchainLookupAbiItem}});Object.defineProperty(w,"offchainLookupSignature",{enumerable:!0,get:function(){return dh.offchainLookupSignature}});var rRe=lC();Object.defineProperty(w,"ccipReadTunnel",{enumerable:!0,get:function(){return rRe.ccipReadTunnel}});var nRe=tf();Object.defineProperty(w,"assertCurrentChain",{enumerable:!0,get:function(){return nRe.assertCurrentChain}});var iRe=fC();Object.defineProperty(w,"defineChain",{enumerable:!0,get:function(){return iRe.defineChain}});var oRe=mC();Object.defineProperty(w,"extractChain",{enumerable:!0,get:function(){return oRe.extractChain}});var sRe=Y7();Object.defineProperty(w,"filterChains",{enumerable:!0,get:function(){return sRe.filterChains}});var aRe=ms();Object.defineProperty(w,"getChainContractAddress",{enumerable:!0,get:function(){return aRe.getChainContractAddress}});var z5=Nt();Object.defineProperty(w,"concat",{enumerable:!0,get:function(){return z5.concat}});Object.defineProperty(w,"concatBytes",{enumerable:!0,get:function(){return z5.concatBytes}});Object.defineProperty(w,"concatHex",{enumerable:!0,get:function(){return z5.concatHex}});var cRe=NE();Object.defineProperty(w,"isBytes",{enumerable:!0,get:function(){return cRe.isBytes}});var uRe=Sr();Object.defineProperty(w,"isHex",{enumerable:!0,get:function(){return uRe.isHex}});var Y5=oo();Object.defineProperty(w,"pad",{enumerable:!0,get:function(){return Y5.pad}});Object.defineProperty(w,"padBytes",{enumerable:!0,get:function(){return Y5.padBytes}});Object.defineProperty(w,"padHex",{enumerable:!0,get:function(){return Y5.padHex}});var dRe=ur();Object.defineProperty(w,"size",{enumerable:!0,get:function(){return dRe.size}});var X5=on();Object.defineProperty(w,"slice",{enumerable:!0,get:function(){return X5.slice}});Object.defineProperty(w,"sliceBytes",{enumerable:!0,get:function(){return X5.sliceBytes}});Object.defineProperty(w,"sliceHex",{enumerable:!0,get:function(){return X5.sliceHex}});var lRe=ts();Object.defineProperty(w,"trim",{enumerable:!0,get:function(){return lRe.trim}});var qf=S_();Object.defineProperty(w,"bytesToBigInt",{enumerable:!0,get:function(){return qf.bytesToBigInt}});Object.defineProperty(w,"bytesToBigint",{enumerable:!0,get:function(){return qf.bytesToBigInt}});Object.defineProperty(w,"bytesToBool",{enumerable:!0,get:function(){return qf.bytesToBool}});Object.defineProperty(w,"bytesToNumber",{enumerable:!0,get:function(){return qf.bytesToNumber}});Object.defineProperty(w,"bytesToString",{enumerable:!0,get:function(){return qf.bytesToString}});Object.defineProperty(w,"fromBytes",{enumerable:!0,get:function(){return qf.fromBytes}});var lh=pt();Object.defineProperty(w,"fromHex",{enumerable:!0,get:function(){return lh.fromHex}});Object.defineProperty(w,"hexToBigInt",{enumerable:!0,get:function(){return lh.hexToBigInt}});Object.defineProperty(w,"hexToBool",{enumerable:!0,get:function(){return lh.hexToBool}});Object.defineProperty(w,"hexToNumber",{enumerable:!0,get:function(){return lh.hexToNumber}});Object.defineProperty(w,"hexToString",{enumerable:!0,get:function(){return lh.hexToString}});var fRe=KE();Object.defineProperty(w,"fromRlp",{enumerable:!0,get:function(){return fRe.fromRlp}});var fh=Je();Object.defineProperty(w,"boolToBytes",{enumerable:!0,get:function(){return fh.boolToBytes}});Object.defineProperty(w,"hexToBytes",{enumerable:!0,get:function(){return fh.hexToBytes}});Object.defineProperty(w,"numberToBytes",{enumerable:!0,get:function(){return fh.numberToBytes}});Object.defineProperty(w,"stringToBytes",{enumerable:!0,get:function(){return fh.stringToBytes}});Object.defineProperty(w,"toBytes",{enumerable:!0,get:function(){return fh.toBytes}});var ph=W();Object.defineProperty(w,"boolToHex",{enumerable:!0,get:function(){return ph.boolToHex}});Object.defineProperty(w,"bytesToHex",{enumerable:!0,get:function(){return ph.bytesToHex}});Object.defineProperty(w,"numberToHex",{enumerable:!0,get:function(){return ph.numberToHex}});Object.defineProperty(w,"stringToHex",{enumerable:!0,get:function(){return ph.stringToHex}});Object.defineProperty(w,"toHex",{enumerable:!0,get:function(){return ph.toHex}});var pRe=Ml();Object.defineProperty(w,"toRlp",{enumerable:!0,get:function(){return pRe.toRlp}});var mRe=iE();Object.defineProperty(w,"getCallError",{enumerable:!0,get:function(){return mRe.getCallError}});var gRe=as();Object.defineProperty(w,"getContractError",{enumerable:!0,get:function(){return gRe.getContractError}});var hRe=Y2();Object.defineProperty(w,"getEstimateGasError",{enumerable:!0,get:function(){return hRe.getEstimateGasError}});var hW=Dl();Object.defineProperty(w,"containsNodeError",{enumerable:!0,get:function(){return hW.containsNodeError}});Object.defineProperty(w,"getNodeError",{enumerable:!0,get:function(){return hW.getNodeError}});var yRe=Hl();Object.defineProperty(w,"getTransactionError",{enumerable:!0,get:function(){return yRe.getTransactionError}});var yW=Ul();Object.defineProperty(w,"defineBlock",{enumerable:!0,get:function(){return yW.defineBlock}});Object.defineProperty(w,"formatBlock",{enumerable:!0,get:function(){return yW.formatBlock}});var _Re=ls();Object.defineProperty(w,"extract",{enumerable:!0,get:function(){return _Re.extract}});var bRe=Ll();Object.defineProperty(w,"defineFormatter",{enumerable:!0,get:function(){return bRe.defineFormatter}});var ERe=xi();Object.defineProperty(w,"formatLog",{enumerable:!0,get:function(){return ERe.formatLog}});var Z5=Cu();Object.defineProperty(w,"defineTransaction",{enumerable:!0,get:function(){return Z5.defineTransaction}});Object.defineProperty(w,"formatTransaction",{enumerable:!0,get:function(){return Z5.formatTransaction}});Object.defineProperty(w,"transactionType",{enumerable:!0,get:function(){return Z5.transactionType}});var wRe=Bu();Object.defineProperty(w,"defineTransactionReceipt",{enumerable:!0,get:function(){return wRe.defineTransactionReceipt}});var _W=Zn();Object.defineProperty(w,"defineTransactionRequest",{enumerable:!0,get:function(){return _W.defineTransactionRequest}});Object.defineProperty(w,"formatTransactionRequest",{enumerable:!0,get:function(){return _W.formatTransactionRequest}});var vRe=Te();Object.defineProperty(w,"getAction",{enumerable:!0,get:function(){return vRe.getAction}});var SRe=WE();Object.defineProperty(w,"isHash",{enumerable:!0,get:function(){return SRe.isHash}});var ARe=Hr();Object.defineProperty(w,"keccak256",{enumerable:!0,get:function(){return ARe.keccak256}});var IRe=wC();Object.defineProperty(w,"ripemd160",{enumerable:!0,get:function(){return IRe.ripemd160}});var PRe=Hb();Object.defineProperty(w,"sha256",{enumerable:!0,get:function(){return PRe.sha256}});var TRe=vC();Object.defineProperty(w,"toEventHash",{enumerable:!0,get:function(){return TRe.toEventHash}});var bW=wu();Object.defineProperty(w,"toEventSelector",{enumerable:!0,get:function(){return bW.toEventSelector}});Object.defineProperty(w,"getEventSelector",{enumerable:!0,get:function(){return bW.toEventSelector}});var EW=SC();Object.defineProperty(w,"toEventSignature",{enumerable:!0,get:function(){return EW.toEventSignature}});Object.defineProperty(w,"getEventSignature",{enumerable:!0,get:function(){return EW.toEventSignature}});var xRe=AC();Object.defineProperty(w,"toFunctionHash",{enumerable:!0,get:function(){return xRe.toFunctionHash}});var wW=Ra();Object.defineProperty(w,"toFunctionSelector",{enumerable:!0,get:function(){return wW.toFunctionSelector}});Object.defineProperty(w,"getFunctionSelector",{enumerable:!0,get:function(){return wW.toFunctionSelector}});var vW=IC();Object.defineProperty(w,"toFunctionSignature",{enumerable:!0,get:function(){return vW.toFunctionSignature}});Object.defineProperty(w,"getFunctionSignature",{enumerable:!0,get:function(){return vW.toFunctionSignature}});var SW=PC();Object.defineProperty(w,"createNonceManager",{enumerable:!0,get:function(){return SW.createNonceManager}});Object.defineProperty(w,"nonceManager",{enumerable:!0,get:function(){return SW.nonceManager}});var Q5=Om();Object.defineProperty(w,"arrayRegex",{enumerable:!0,get:function(){return Q5.arrayRegex}});Object.defineProperty(w,"bytesRegex",{enumerable:!0,get:function(){return Q5.bytesRegex}});Object.defineProperty(w,"integerRegex",{enumerable:!0,get:function(){return Q5.integerRegex}});var AW=tN();Object.defineProperty(w,"getSocket",{enumerable:!0,get:function(){return AW.getSocket}});Object.defineProperty(w,"rpc",{enumerable:!0,get:function(){return AW.rpc}});var ORe=aw();Object.defineProperty(w,"getHttpRpcClient",{enumerable:!0,get:function(){return ORe.getHttpRpcClient}});var IW=CC();Object.defineProperty(w,"getSocketRpcClient",{enumerable:!0,get:function(){return IW.getSocketRpcClient}});Object.defineProperty(w,"socketClientCache",{enumerable:!0,get:function(){return IW.socketClientCache}});var RRe=Iw();Object.defineProperty(w,"getWebSocketRpcClient",{enumerable:!0,get:function(){return RRe.getWebSocketRpcClient}});var CRe=yf();Object.defineProperty(w,"hashMessage",{enumerable:!0,get:function(){return CRe.hashMessage}});var PW=bf();Object.defineProperty(w,"hashStruct",{enumerable:!0,get:function(){return PW.hashStruct}});Object.defineProperty(w,"hashTypedData",{enumerable:!0,get:function(){return PW.hashTypedData}});var NRe=Rw();Object.defineProperty(w,"isErc6492Signature",{enumerable:!0,get:function(){return NRe.isErc6492Signature}});var kRe=g1();Object.defineProperty(w,"isErc8010Signature",{enumerable:!0,get:function(){return kRe.isErc8010Signature}});var jRe=P5();Object.defineProperty(w,"parseErc6492Signature",{enumerable:!0,get:function(){return jRe.parseErc6492Signature}});var MRe=x5();Object.defineProperty(w,"parseErc8010Signature",{enumerable:!0,get:function(){return MRe.parseErc8010Signature}});var qRe=ds();Object.defineProperty(w,"recoverAddress",{enumerable:!0,get:function(){return qRe.recoverAddress}});var DRe=h1();Object.defineProperty(w,"recoverMessageAddress",{enumerable:!0,get:function(){return DRe.recoverMessageAddress}});var LRe=Eb();Object.defineProperty(w,"recoverPublicKey",{enumerable:!0,get:function(){return LRe.recoverPublicKey}});var BRe=y1();Object.defineProperty(w,"recoverTypedDataAddress",{enumerable:!0,get:function(){return BRe.recoverTypedDataAddress}});var URe=N5();Object.defineProperty(w,"serializeErc6492Signature",{enumerable:!0,get:function(){return URe.serializeErc6492Signature}});var HRe=j5();Object.defineProperty(w,"serializeErc8010Signature",{enumerable:!0,get:function(){return HRe.serializeErc8010Signature}});var FRe=q5();Object.defineProperty(w,"verifyHash",{enumerable:!0,get:function(){return FRe.verifyHash}});var $Re=L5();Object.defineProperty(w,"verifyMessage",{enumerable:!0,get:function(){return $Re.verifyMessage}});var JRe=U5();Object.defineProperty(w,"verifyTypedData",{enumerable:!0,get:function(){return JRe.verifyTypedData}});var VRe=Mt();Object.defineProperty(w,"stringify",{enumerable:!0,get:function(){return VRe.stringify}});var GRe=Qn();Object.defineProperty(w,"assertRequest",{enumerable:!0,get:function(){return GRe.assertRequest}});var ek=xg();Object.defineProperty(w,"assertTransactionEIP1559",{enumerable:!0,get:function(){return ek.assertTransactionEIP1559}});Object.defineProperty(w,"assertTransactionEIP2930",{enumerable:!0,get:function(){return ek.assertTransactionEIP2930}});Object.defineProperty(w,"assertTransactionLegacy",{enumerable:!0,get:function(){return ek.assertTransactionLegacy}});var KRe=_1();Object.defineProperty(w,"getSerializedTransactionType",{enumerable:!0,get:function(){return KRe.getSerializedTransactionType}});var WRe=ng();Object.defineProperty(w,"getTransactionType",{enumerable:!0,get:function(){return WRe.getTransactionType}});var zRe=b1();Object.defineProperty(w,"parseTransaction",{enumerable:!0,get:function(){return zRe.parseTransaction}});var YRe=LE();Object.defineProperty(w,"serializeAccessList",{enumerable:!0,get:function(){return YRe.serializeAccessList}});var XRe=Cg();Object.defineProperty(w,"serializeTransaction",{enumerable:!0,get:function(){return XRe.serializeTransaction}});var TW=Ug();Object.defineProperty(w,"serializeTypedData",{enumerable:!0,get:function(){return TW.serializeTypedData}});Object.defineProperty(w,"validateTypedData",{enumerable:!0,get:function(){return TW.validateTypedData}});var ZRe=Rl();Object.defineProperty(w,"formatEther",{enumerable:!0,get:function(){return ZRe.formatEther}});var QRe=qa();Object.defineProperty(w,"formatGwei",{enumerable:!0,get:function(){return QRe.formatGwei}});var eCe=Mf();Object.defineProperty(w,"formatUnits",{enumerable:!0,get:function(){return eCe.formatUnits}});var tCe=J5();Object.defineProperty(w,"parseEther",{enumerable:!0,get:function(){return tCe.parseEther}});var rCe=G5();Object.defineProperty(w,"parseGwei",{enumerable:!0,get:function(){return rCe.parseGwei}});var nCe=E1();Object.defineProperty(w,"parseUnits",{enumerable:!0,get:function(){return nCe.parseUnits}})});var xW=g(rk=>{"use strict";Object.defineProperty(rk,"__esModule",{value:!0});rk.formatProof=sCe;var iCe=tk();function oCe(e){return e.map(t=>({...t,value:BigInt(t.value)}))}function sCe(e){return{...e,balance:e.balance?BigInt(e.balance):void 0,nonce:e.nonce?(0,iCe.hexToNumber)(e.nonce):void 0,storageProof:e.storageProof?oCe(e.storageProof):void 0}}});var OW=g(nk=>{"use strict";Object.defineProperty(nk,"__esModule",{value:!0});nk.getProof=uCe;var aCe=Nu(),cCe=xW();async function uCe(e,{address:t,blockHash:r,blockNumber:n,blockTag:i="latest",requireCanonical:o,storageKeys:s}){let a=(0,aCe.formatBlockParameter)({blockHash:r,blockNumber:n,blockTag:i,requireCanonical:o}),c=await e.request({method:"eth_getProof",params:[t,s,a]});return(0,cCe.formatProof)(c)}});var RW=g(ik=>{"use strict";Object.defineProperty(ik,"__esModule",{value:!0});ik.getRawTransaction=lCe;var dCe=Xt();async function lCe(e,{hash:t}){let r=await e.request({method:"eth_getRawTransactionByHash",params:[t]},{dedupe:!0});if(!r)throw new dCe.TransactionNotFoundError({hash:t});return r}});var CW=g(ok=>{"use strict";Object.defineProperty(ok,"__esModule",{value:!0});ok.getStorageAt=pCe;var fCe=Nu();async function pCe(e,{address:t,blockHash:r,blockNumber:n,blockTag:i="latest",requireCanonical:o,slot:s}){let a=(0,fCe.formatBlockParameter)({blockHash:r,blockNumber:n,blockTag:i,requireCanonical:o});return await e.request({method:"eth_getStorageAt",params:[t,s,a]})}});var S1=g(sk=>{"use strict";Object.defineProperty(sk,"__esModule",{value:!0});sk.getTransaction=hCe;var mCe=Xt(),v1=W(),gCe=Cu();async function hCe(e,{blockHash:t,blockNumber:r,blockTag:n,hash:i,index:o,sender:s,nonce:a}){let c=n||"latest",u=r!==void 0?(0,v1.numberToHex)(r):void 0,d=null;if(i?d=await e.request({method:"eth_getTransactionByHash",params:[i]},{dedupe:!0}):t?d=await e.request({method:"eth_getTransactionByBlockHashAndIndex",params:[t,(0,v1.numberToHex)(o)]},{dedupe:!0}):(u||c)&&typeof o=="number"?d=await e.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[u||c,(0,v1.numberToHex)(o)]},{dedupe:!!u}):s&&typeof a=="number"&&(d=await e.request({method:"eth_getTransactionBySenderAndNonce",params:[s,(0,v1.numberToHex)(a)]},{dedupe:!0})),!d)throw new mCe.TransactionNotFoundError({blockHash:t,blockNumber:r,blockTag:c,hash:i,index:o});return(e.chain?.formatters?.transaction?.format||gCe.formatTransaction)(d,"getTransaction")}});var kW=g(ak=>{"use strict";Object.defineProperty(ak,"__esModule",{value:!0});ak.getTransactionConfirmations=bCe;var NW=Te(),yCe=Du(),_Ce=S1();async function bCe(e,{hash:t,transactionReceipt:r}){let[n,i]=await Promise.all([(0,NW.getAction)(e,yCe.getBlockNumber,"getBlockNumber")({}),t?(0,NW.getAction)(e,_Ce.getTransaction,"getTransaction")({hash:t}):void 0]),o=r?.blockNumber||i?.blockNumber;return o?n-o+1n:0n}});var uk=g(ck=>{"use strict";Object.defineProperty(ck,"__esModule",{value:!0});ck.getTransactionReceipt=vCe;var ECe=Xt(),wCe=Bu();async function vCe(e,{hash:t}){let r=await e.request({method:"eth_getTransactionReceipt",params:[t]},{dedupe:!0});if(!r)throw new ECe.TransactionReceiptNotFoundError({hash:t});return(e.chain?.formatters?.transactionReceipt?.format||wCe.formatTransactionReceipt)(r,"getTransactionReceipt")}});var BW=g(dk=>{"use strict";Object.defineProperty(dk,"__esModule",{value:!0});dk.multicall=CCe;var MW=er(),qW=zl(),SCe=ft(),ACe=ye(),ICe=ao(),PCe=ei(),TCe=Tr(),xCe=ms(),jW=as(),DW=Te(),OCe=pg(),RCe=Mt(),LW=Cr();async function CCe(e,t){let{account:r,authorizationList:n,allowFailure:i=!0,blockHash:o,blockNumber:s,blockOverrides:a,blockTag:c,requireCanonical:u,stateOverride:d}=t,l=t.contracts,m=typeof e.batch?.multicall=="object"?e.batch.multicall:{},p=t.batchSize??m.batchSize??1024,h=t.deployless??m.deployless??!1,y=(()=>{if(t.multicallAddress)return t.multicallAddress;if(h)return null;if(e.chain)return(0,xCe.getChainContractAddress)({blockNumber:s,chain:e.chain,contract:"multicall3"});throw new Error("client chain not configured. multicallAddress is required.")})(),b=[[]],v=0,A=0;for(let x=0;x<l.length;x++){let{abi:C,address:k,args:N,functionName:M}=l[x];try{let j=(0,TCe.encodeFunctionData)({abi:C,args:N,functionName:M});A+=(j.length-2)/2,p>0&&A>p&&b[v].length>0&&(v++,A=(j.length-2)/2,b[v]=[]),b[v]=[...b[v],{allowFailure:!0,callData:j,target:k}]}catch(j){let D=(0,jW.getContractError)(j,{abi:C,address:k,args:N,docsPath:"/docs/contract/multicall",functionName:M,sender:r});if(!i)throw D;b[v]=[...b[v],{allowFailure:!0,callData:"0x",target:k}]}}let E=!!e.batch?.multicall,S=E?b.flatMap(x=>x.map(C=>[C])):b,I=await Promise.allSettled(S.map(x=>E?NCe(e,{account:r,authorizationList:n,batchSize:p,blockHash:o,blockNumber:s,blockOverrides:a,blockTag:c,call:x[0],multicallAddress:y,requireCanonical:u,stateOverride:d}).then(C=>[C]):(0,DW.getAction)(e,LW.readContract,"readContract")({...y===null?{code:qW.multicall3Bytecode}:{address:y},abi:MW.multicall3Abi,account:r,args:[x],authorizationList:n,blockHash:o,blockNumber:s,blockOverrides:a,blockTag:c,functionName:"aggregate3",requireCanonical:u,stateOverride:d}))),T=[];for(let x=0;x<I.length;x++){let C=I[x];if(C.status==="rejected"){if(!i)throw C.reason;for(let N=0;N<S[x].length;N++)T.push({status:"failure",error:C.reason,result:void 0});continue}let k=C.value;for(let N=0;N<k.length;N++){let{returnData:M,success:j}=k[N],{callData:D}=S[x][N],{abi:U,address:q,functionName:L,args:V}=l[T.length];try{if(D==="0x")throw new SCe.AbiDecodingZeroDataError;if(!j)throw new ICe.RawContractError({data:M});let Q=(0,PCe.decodeFunctionResult)({abi:U,args:V,data:M,functionName:L});T.push(i?{result:Q,status:"success"}:Q)}catch(Q){let re=(0,jW.getContractError)(Q,{abi:U,address:q,args:V,docsPath:"/docs/contract/multicall",functionName:L});if(!i)throw re;T.push({error:re,result:void 0,status:"failure"})}}}if(T.length!==l.length)throw new ACe.BaseError("multicall results mismatch");return T}async function NCe(e,t){let{batchSize:r,call:n,multicallAddress:i,...o}=t,{wait:s=0}=typeof e.batch?.multicall=="object"?e.batch.multicall:{},{schedule:a}=(0,OCe.createBatchScheduler)({id:(0,RCe.stringify)(["multicall",e.uid,r,i,o]),wait:s,shouldSplitBatch(u){return r===0?!1:u.reduce((l,{callData:m})=>l+(m.length-2)/2,0)>r},fn:u=>(0,DW.getAction)(e,LW.readContract,"readContract")({...i===null?{code:qW.multicall3Bytecode}:{address:i},...o,abi:MW.multicall3Abi,args:[u],functionName:"aggregate3"})}),[c]=await a(n);return c}});var fk=g(lk=>{"use strict";Object.defineProperty(lk,"__esModule",{value:!0});lk.simulateBlocks=zCe;var kCe=i6(),jCe=at(),MCe=ft(),qCe=ao(),DCe=Ti(),LCe=ei(),BCe=Tr(),UCe=Nt(),HCe=W(),FCe=as(),$Ce=Dl(),JCe=Ul(),VCe=xi(),GCe=Zn(),KCe=jb(),WCe=Qn();async function zCe(e,t){let{blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",blocks:i,returnFullTransactions:o,traceTransfers:s,validation:a}=t;try{let c=[];for(let m of i){let p=m.blockOverrides?kCe.toRpc(m.blockOverrides):void 0,h=m.calls.map(b=>{let v=b,A=v.account?(0,jCe.parseAccount)(v.account):void 0,E=v.abi?(0,BCe.encodeFunctionData)(v):v.data,S={...v,account:A,data:v.dataSuffix?(0,UCe.concat)([E||"0x",v.dataSuffix]):E,from:v.from??A?.address};return(0,WCe.assertRequest)(S),(0,GCe.formatTransactionRequest)(S)}),y=m.stateOverrides?(0,KCe.serializeStateOverride)(m.stateOverrides):void 0;c.push({blockOverrides:p,calls:h,stateOverrides:y})}let d=(typeof r=="bigint"?(0,HCe.numberToHex)(r):void 0)||n;return(await e.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:o,traceTransfers:s,validation:a},d]})).map((m,p)=>({...(0,JCe.formatBlock)(m),calls:m.calls.map((h,y)=>{let{abi:b,args:v,functionName:A,to:E}=i[p].calls[y],S=h.error?.data??h.returnData,I=BigInt(h.gasUsed),T=h.logs?.map(N=>(0,VCe.formatLog)(N)),x=h.status==="0x1"?"success":"failure",C=b&&x==="success"&&S!=="0x"?(0,LCe.decodeFunctionResult)({abi:b,data:S,functionName:A}):null,k=(()=>{if(x==="success")return;let N;if(S==="0x"?N=new MCe.AbiDecodingZeroDataError:S&&(N=new qCe.RawContractError({data:S})),!!N)return(0,FCe.getContractError)(N,{abi:b??[],address:E??"0x",args:v,functionName:A??"<unknown>"})})();return{data:S,gasUsed:I,logs:T,status:x,...x==="success"?{result:C}:{error:k}}})}))}catch(c){let u=c,d=(0,$Ce.getNodeError)(u,{});throw d instanceof DCe.UnknownNodeError?u:d}}});var HW=g(mh=>{"use strict";Object.defineProperty(mh,"__esModule",{value:!0});mh.normalizeSignature=XCe;mh.isArgOfType=mk;mh.getAmbiguousTypes=UW;var pk=Of(),YCe=Vr();function XCe(e){let t=!0,r="",n=0,i="",o=!1;for(let s=0;s<e.length;s++){let a=e[s];if(["(",")",","].includes(a)&&(t=!0),a==="("&&n++,a===")"&&n--,!!t){if(n===0){if(a===" "&&["event","function","error",""].includes(i))i="";else if(i+=a,a===")"){o=!0;break}continue}if(a===" "){e[s-1]!==","&&r!==","&&r!==",("&&(r="",t=!1);continue}i+=a,r+=a}}if(!o)throw new YCe.BaseError("Unable to normalize signature.");return i}function mk(e,t){let r=typeof e,n=t.type;switch(n){case"address":return pk.validate(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in t?Object.values(t.components).every((i,o)=>mk(Object.values(e)[o],i)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?r==="number"||r==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?r==="string"||e instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(e)&&e.every(i=>mk(i,{...t,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function UW(e,t,r){for(let n in e){let i=e[n],o=t[n];if(i.type==="tuple"&&o.type==="tuple"&&"components"in i&&"components"in o)return UW(i.components,o.components,r[n]);let s=[i.type,o.type];if(s.includes("address")&&s.includes("bytes20")?!0:s.includes("address")&&s.includes("string")?pk.validate(r[n],{strict:!1}):s.includes("address")&&s.includes("bytes")?pk.validate(r[n],{strict:!1}):!1)return s}}});var P1=g(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.InvalidSelectorSizeError=yn.NotFoundError=yn.AmbiguityError=void 0;yn.format=QCe;yn.from=eNe;yn.fromAbi=I1;yn.getSelector=FW;yn.getSignature=$W;yn.getSignatureHash=cd;var Df=Pf(),hk=Vr(),ZCe=Wg(),gh=Jt(),hh=HW();function QCe(e){return Df.formatAbiItem(e)}function eNe(e,t={}){let{prepare:r=!0}=t,n=Array.isArray(e)||typeof e=="string"?Df.parseAbiItem(e):e;return{...n,...r?{hash:cd(n)}:{}}}function I1(e,t,r){let{args:n=[],prepare:i=!0}=r??{},o=gh.validate(t,{strict:!1}),s=e.filter(u=>o?u.type==="function"||u.type==="error"?FW(u)===gh.slice(t,0,4):u.type==="event"?cd(u)===t:!1:"name"in u&&u.name===t);if(s.length===0)throw new yh({name:t});if(s.length===1)return{...s[0],...i?{hash:cd(s[0])}:{}};let a;for(let u of s){if(!("inputs"in u))continue;if(!n||n.length===0){if(!u.inputs||u.inputs.length===0)return{...u,...i?{hash:cd(u)}:{}};continue}if(!u.inputs||u.inputs.length===0||u.inputs.length!==n.length)continue;if(n.every((l,m)=>{let p="inputs"in u&&u.inputs[m];return p?hh.isArgOfType(l,p):!1})){if(a&&"inputs"in a&&a.inputs){let l=hh.getAmbiguousTypes(u.inputs,a.inputs,n);if(l)throw new A1({abiItem:u,type:l[0]},{abiItem:a,type:l[1]})}a=u}}let c=(()=>{if(a)return a;let[u,...d]=s;return{...u,overloads:d}})();if(!c)throw new yh({name:t});return{...c,...i?{hash:cd(c)}:{}}}function FW(...e){let t=(()=>{if(Array.isArray(e[0])){let[r,n]=e;return I1(r,n)}return e[0]})();return gh.slice(cd(t),0,4)}function $W(...e){let t=(()=>{if(Array.isArray(e[0])){let[n,i]=e;return I1(n,i)}return e[0]})(),r=typeof t=="string"?t:Df.formatAbiItem(t);return hh.normalizeSignature(r)}function cd(...e){let t=(()=>{if(Array.isArray(e[0])){let[r,n]=e;return I1(r,n)}return e[0]})();return typeof t!="string"&&"hash"in t&&t.hash?t.hash:ZCe.keccak256(gh.fromString($W(t)))}var A1=class extends hk.BaseError{constructor(t,r){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${t.type}\` in \`${hh.normalizeSignature(Df.formatAbiItem(t.abiItem))}\`, and`,`\`${r.type}\` in \`${hh.normalizeSignature(Df.formatAbiItem(r.abiItem))}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.AmbiguityError"})}};yn.AmbiguityError=A1;var yh=class extends hk.BaseError{constructor({name:t,data:r,type:n="item"}){let i=t?` with name "${t}"`:r?` with data "${r}"`:"";super(`ABI ${n}${i} not found.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}};yn.NotFoundError=yh;var gk=class extends hk.BaseError{constructor({data:t}){super(`Selector size is invalid. Expected 4 bytes. Received ${gh.size(t)} bytes ("${t}").`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.InvalidSelectorSizeError"})}};yn.InvalidSelectorSizeError=gk});var GW=g(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});ud.decode=nNe;ud.encode=iNe;ud.format=oNe;ud.from=sNe;ud.fromAbi=yk;var tNe=Pf(),JW=P1(),VW=id(),rNe=Jt();function nNe(...e){let[t,r]=(()=>{if(Array.isArray(e[0])){let[o,s]=e;return[yk(o),s]}return e})(),{bytecode:n}=r;if(t.inputs?.length===0)return;let i=r.data.replace(n,"0x");return VW.decode(t.inputs,i)}function iNe(...e){let[t,r]=(()=>{if(Array.isArray(e[0])){let[o,s]=e;return[yk(o),s]}return e})(),{bytecode:n,args:i}=r;return rNe.concat(n,t.inputs?.length&&i?.length?VW.encode(t.inputs,i):"0x")}function oNe(e){return tNe.formatAbiItem(e)}function sNe(e){return JW.from(e)}function yk(e){let t=e.find(r=>r.type==="constructor");if(!t)throw new JW.NotFoundError({name:"constructor"});return t}});var zW=g(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.FilterTypeNotSupportedError=jt.SelectorTopicMismatchError=jt.TopicsMismatchError=jt.DataMismatchError=jt.InputNotFoundError=jt.ArgsMismatchError=void 0;jt.assertArgs=lNe;jt.decode=fNe;jt.encode=pNe;jt.format=wh;jt.from=mNe;jt.fromAbi=_k;jt.getSelector=bk;var aNe=Pf(),T1=P1(),_h=id(),cNe=Of(),uNe=ti(),Bf=Vr(),x1=Wg(),WW=Jt(),dNe=Xw(),KW=$O();function lNe(e,t,r){if(!t||!r)throw new Lf({abiEvent:e,expected:t,given:r});function n(i,o,s){return i.type==="address"?cNe.isEqual(o,s):i.type==="string"?x1.keccak256(uNe.fromString(o))===s:i.type==="bytes"?x1.keccak256(o)===s:o===s}if(Array.isArray(t)&&Array.isArray(r))for(let[i,o]of r.entries()){if(o==null)continue;let s=e.inputs[i];if(!s)throw new bh({abiEvent:e,name:`${i}`});let a=Array.isArray(o)?o:[o],c=!1;for(let u of a)n(s,u,t[i])&&(c=!0);if(!c)throw new Lf({abiEvent:e,expected:t,given:r})}if(typeof t=="object"&&!Array.isArray(t)&&typeof r=="object"&&!Array.isArray(r))for(let[i,o]of Object.entries(r)){if(o==null)continue;let s=e.inputs.find(u=>u.name===i);if(!s)throw new bh({abiEvent:e,name:i});let a=Array.isArray(o)?o:[o],c=!1;for(let u of a)n(s,u,t[i])&&(c=!0);if(!c)throw new Lf({abiEvent:e,expected:t,given:r})}}function fNe(...e){let[t,r]=(()=>{if(Array.isArray(e[0])){let[p,h,y]=e;return[_k(p,h),y]}return e})(),{data:n,topics:i}=r,[o,...s]=i,a=bk(t);if(o!==a)throw new R1({abiEvent:t,actual:o,expected:a});let{inputs:c}=t,u=c?.every(p=>!("name"in p&&p.name)),d=u?[]:{},l=c.filter(p=>"indexed"in p&&p.indexed);for(let p=0;p<l.length;p++){let h=l[p],y=s[p];if(!y)throw new O1({abiEvent:t,param:h});d[u?p:h.name||p]=h.type==="string"||h.type==="bytes"||h.type==="tuple"||h.type.match(/^(.*)\[(\d+)?\]$/)?y:(_h.decode([h],y)||[])[0]}let m=c.filter(p=>!("indexed"in p&&p.indexed));if(m.length>0)if(n&&n!=="0x")try{let p=_h.decode(m,n);if(p)if(u)d=[...d,...p];else for(let h=0;h<m.length;h++){let y=c.indexOf(m[h]);d[m[h].name||y]=p[h]}}catch(p){throw p instanceof _h.DataSizeTooSmallError||p instanceof dNe.PositionOutOfBoundsError?new Eh({abiEvent:t,data:n,parameters:m,size:WW.size(n)}):p}else throw new Eh({abiEvent:t,data:"0x",parameters:m,size:0});return Object.values(d).length>0?d:void 0}function pNe(...e){let[t,r]=(()=>{if(Array.isArray(e[0])){let[a,c,u]=e;return[_k(a,c),u]}let[o,s]=e;return[o,s]})(),n=[];if(r&&t.inputs){let o=t.inputs.filter(a=>"indexed"in a&&a.indexed),s=Array.isArray(r)?r:Object.values(r).length>0?o?.map((a,c)=>r[a.name??c])??[]:[];if(s.length>0){let a=(c,u)=>{if(c.type==="string")return x1.keccak256(WW.fromString(u));if(c.type==="bytes")return x1.keccak256(u);if(c.type==="tuple"||c.type.match(/^(.*)\[(\d+)?\]$/))throw new C1(c.type);return _h.encode([c],[u])};n=o?.map((c,u)=>Array.isArray(s[u])?s[u].map((d,l)=>a(c,s[u][l])):typeof s[u]<"u"&&s[u]!==null?a(c,s[u]):null)??[]}}return{topics:[t.hash?t.hash:bk(t),...n]}}function wh(e){return aNe.formatAbiItem(e)}function mNe(e,t={}){return T1.from(e,t)}function _k(e,t,r){let n=T1.fromAbi(e,t,r);if(n.type!=="event")throw new T1.NotFoundError({name:t,type:"event"});return n}function bk(e){return T1.getSignatureHash(e)}var Lf=class extends Bf.BaseError{constructor({abiEvent:t,expected:r,given:n}){super("Given arguments do not match the expected arguments.",{metaMessages:[`Event: ${wh(t)}`,`Expected Arguments: ${r?"":"None"}`,r?(0,KW.prettyPrint)(r):void 0,`Given Arguments: ${n?"":"None"}`,n?(0,KW.prettyPrint)(n):void 0]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiEvent.ArgsMismatchError"})}};jt.ArgsMismatchError=Lf;var bh=class extends Bf.BaseError{constructor({abiEvent:t,name:r}){super(`Parameter "${r}" not found on \`${wh(t)}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiEvent.InputNotFoundError"})}};jt.InputNotFoundError=bh;var Eh=class extends Bf.BaseError{constructor({abiEvent:t,data:r,parameters:n,size:i}){super([`Data size of ${i} bytes is too small for non-indexed event parameters.`].join(`
62
+ `),{metaMessages:[`Non-indexed Parameters: (${_h.format(n)})`,`Data: ${r} (${i} bytes)`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiEvent.DataMismatchError"}),Object.defineProperty(this,"abiEvent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parameters",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiEvent=t,this.data=r,this.parameters=n,this.size=i}};jt.DataMismatchError=Eh;var O1=class extends Bf.BaseError{constructor({abiEvent:t,param:r}){super([`Expected a topic for indexed event parameter${r.name?` "${r.name}"`:""} for "${wh(t)}".`].join(`
63
+ `)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiEvent.TopicsMismatchError"}),Object.defineProperty(this,"abiEvent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiEvent=t}};jt.TopicsMismatchError=O1;var R1=class extends Bf.BaseError{constructor({abiEvent:t,actual:r,expected:n}){super(`topics[0]="${r}" does not match the expected topics[0]="${n}".`,{metaMessages:[`Event: ${wh(t)}`,`Selector: ${n}`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiEvent.SelectorTopicMismatchError"})}};jt.SelectorTopicMismatchError=R1;var C1=class extends Bf.BaseError{constructor(t){super(`Filter type "${t}" is not supported.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiEvent.FilterTypeNotSupportedError"})}};jt.FilterTypeNotSupportedError=C1});var XW=g(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.decodeData=hNe;So.decodeResult=yNe;So.encodeData=_Ne;So.encodeResult=bNe;So.format=ENe;So.from=wNe;So.fromAbi=dd;So.getSelector=YW;var gNe=Pf(),vh=P1(),k1=id(),N1=Jt();function hNe(...e){let[t,r]=(()=>{if(Array.isArray(e[0])){let[o,s,a]=e;return[dd(o,s),a]}return e})(),{overloads:n}=t;if(N1.size(r)<4)throw new vh.InvalidSelectorSizeError({data:r});if(t.inputs?.length===0)return;let i=n?dd([t,...n],r):t;if(!(N1.size(r)<=4))return k1.decode(i.inputs,N1.slice(r,4))}function yNe(...e){let[t,r,n={}]=(()=>{if(Array.isArray(e[0])){let[o,s,a,c]=e;return[dd(o,s),a,c]}return e})(),i=k1.decode(t.outputs,r,n);if(!(i&&Object.keys(i).length===0))return i&&Object.keys(i).length===1?Array.isArray(i)?i[0]:Object.values(i)[0]:i}function _Ne(...e){let[t,r=[]]=(()=>{if(Array.isArray(e[0])){let[u,d,l]=e;return[dd(u,d,{args:l}),l]}let[a,c]=e;return[a,c]})(),{overloads:n}=t,i=n?dd([t,...n],t.name,{args:r}):t,o=YW(i),s=r.length>0?k1.encode(i.inputs,r):void 0;return s?N1.concat(o,s):o}function bNe(...e){let[t,r,n={}]=(()=>{if(Array.isArray(e[0])){let[s,a,c,u]=e;return[dd(s,a),c,u]}return e})(),{as:i="Array"}=n,o=t.outputs.length===1?[r]:Array.isArray(r)?r:i==="Object"?Object.values(r):[r];return k1.encode(t.outputs,o)}function ENe(e){return gNe.formatAbiItem(e)}function wNe(e,t={}){return vh.from(e,t)}function dd(e,t,r){let n=vh.fromAbi(e,t,r);if(n.type!=="function")throw new vh.NotFoundError({name:t,type:"function"});return n}function YW(e){return vh.getSelector(e)}});var Ek=g(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});Uf.zeroAddress=Uf.ethAddress=void 0;Uf.ethAddress="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";Uf.zeroAddress="0x0000000000000000000000000000000000000000"});var dz=g(vk=>{"use strict";Object.defineProperty(vk,"__esModule",{value:!0});vk.simulateCalls=jNe;var ZW=GW(),QW=zW(),_n=XW(),vNe=at(),Hf=Ek(),SNe=zl(),ez=ye(),ANe=ao(),INe=Ti(),PNe=oo(),tz=pt(),TNe=Qa(),xNe=fs(),ONe=Du(),rz=fk(),RNe="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033",uz="0x608060405234801561000f575f5ffd5b5060043610610029575f3560e01c8063fd00430c1461002d575b5f5ffd5b6100476004803603810190610042919061012b565b610049565b005b80825f375f5f825f865afa610060573d5f5f3e3d5ffd5b3d5f5f3e3d5ff35b5f5ffd5b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f61009982610070565b9050919050565b6100a98161008f565b81146100b3575f5ffd5b50565b5f813590506100c4816100a0565b92915050565b5f5ffd5b5f5ffd5b5f5ffd5b5f5f83601f8401126100eb576100ea6100ca565b5b8235905067ffffffffffffffff811115610108576101076100ce565b5b602083019150836001820283011115610124576101236100d2565b5b9250929050565b5f5f5f6040848603121561014257610141610068565b5b5f61014f868287016100b6565b935050602084013567ffffffffffffffff8111156101705761016f61006c565b5b61017c868287016100d6565b9250925050925092509256fea2646970667358221220635ed99185cacf3f2acba6921f23687c969cec2bbaf5f9ad599f507e6e105e6964736f6c63430008230033",CNe=0x00000000000000000000000000000000deadbeefn,NNe=QW.getSelector(QW.from("event Transfer(address indexed from, address indexed to, uint256 value)")),nz=_n.from("function balanceOf(address) returns (uint256)"),iz=_n.from("function decimals() returns (uint256)"),oz=_n.from("function tokenURI(uint256) returns (string)"),sz=_n.from("function symbol() returns (string)"),kNe=_n.from("function query(address target, bytes data)");async function jNe(e,t){let{blockNumber:r,blockTag:n,calls:i,stateOverrides:o,traceAssetChanges:s,traceTransfers:a,validation:c}=t,u=t.account?(0,vNe.parseAccount)(t.account):void 0;if(s&&!u)throw new ez.BaseError("`account` is required when `traceAssetChanges` is true");let d=u?ZW.encode(ZW.from("constructor(bytes, bytes)"),{bytecode:SNe.deploylessCallViaBytecodeBytecode,args:[RNe,_n.encodeData(_n.from("function getBalance(address)"),[u.address])]}):void 0,l=n??e.experimental_blockTag??"latest",m=r;if(s&&typeof m!="bigint"&&l!=="earliest"&&l!=="pending")if(l==="latest")m=await(0,ONe.getBlockNumber)(e,{cacheTime:0});else{let K=await(0,xNe.getBlock)(e,{blockTag:l});if(typeof K.number!="bigint")throw new ez.BaseError(`Block tag \`${l}\` did not resolve to a number.`);m=K.number}let p=typeof m=="bigint"?{blockNumber:m}:{blockTag:l},h=s?await(0,rz.simulateBlocks)(e,{...p,blocks:[{calls:i.map(K=>({...K,from:u.address})),stateOverrides:o}],traceTransfers:a,validation:c}):void 0,y=h?[...new Set([...MNe(h[0].calls.flatMap(K=>K.logs??[]),u.address),...t.calls.map(K=>K.to?.toLowerCase())])].filter(K=>!!K&&K!==Hf.ethAddress&&K!==Hf.zeroAddress):[],b=qNe([...u?[u.address]:[],...y,...o?.map(({address:K})=>K)??[]]),v=[{address:b,code:uz}],[A,E]=await Promise.all([s?Promise.all([cz(e,{account:u.address,...p,data:d,stateOverride:o}),...y.map(K=>cz(e,{account:u.address,address:K,...p,data:_n.encodeData(nz,[u.address]),staticCallAddress:b,stateOverride:o}))]):[],(0,rz.simulateBlocks)(e,{...p,blocks:[{calls:[...i,{to:Hf.zeroAddress}].map(K=>({...K,from:u?.address})),stateOverrides:o},...s?[{calls:[{data:d}]},{calls:y.map(K=>({to:b,data:Sh(K,_n.encodeData(nz,[u.address]))})),stateOverrides:v},{calls:y.map(K=>({to:b,data:Sh(K,_n.encodeData(iz))})),stateOverrides:v},{calls:y.map(K=>({to:b,data:Sh(K,_n.encodeData(oz,[0n]))})),stateOverrides:v},{calls:y.map(K=>({to:b,data:Sh(K,_n.encodeData(sz))})),stateOverrides:v}]:[]],traceTransfers:a,validation:c})]),S=E[0],[I,T,x,C,k]=s?E.slice(1):[],{calls:N,...M}=S,j=N.slice(0,-1),D=A.map(K=>az(K)?(0,tz.hexToBigInt)(K.data):null),U=I?.calls??[],q=T?.calls??[],V=[...U,...q].map(K=>az(K)?(0,tz.hexToBigInt)(K.data):null),Q=(x?.calls??[]).map(K=>wk(K,iz)),re=(k?.calls??[]).map(K=>wk(K,sz)),_e=(C?.calls??[]).map(K=>wk(K,oz)),je=[];for(let[K,wr]of V.entries()){let nt=D[K],Ot=A[K],Ki=typeof nt=="bigint"?nt:K>0&&Ot?.status==="success"&&Ot.data==="0x"?0n:null;if(typeof wr!="bigint"||typeof Ki!="bigint")continue;let vi=Q[K-1],Kp=re[K-1],$o=_e[K-1],ia=K===0?{address:Hf.ethAddress,decimals:18,symbol:"ETH"}:{address:y[K-1],decimals:$o||vi?Number(vi??1):void 0,symbol:Kp??void 0};je.push({token:ia,value:{pre:Ki,post:wr,diff:wr-Ki}})}return{assetChanges:je,block:M,results:j}}function Sh(e,t){return _n.encodeData(kNe,[e,t])}function MNe(e,t){let r=(0,PNe.pad)(t.toLowerCase(),{size:32});return e.filter(n=>n.topics[0]?.toLowerCase()!==NNe||n.address.toLowerCase()===Hf.ethAddress?!1:n.topics[1]?.toLowerCase()===r||n.topics[2]?.toLowerCase()===r).map(n=>n.address.toLowerCase())}function az(e){return e.status==="success"&&/^0x[\da-f]{64}$/i.test(e.data)}function wk(e,t){if(e.status==="failure"||e.data==="0x")return null;try{return _n.decodeResult(t,e.data)}catch{return null}}async function cz(e,t){let{account:r,address:n,blockNumber:i,blockTag:o,data:s,staticCallAddress:a,stateOverride:c}=t;try{return{data:(await(0,TNe.call)({...e,ccipRead:!1},{account:n?Hf.zeroAddress:r,data:n?Sh(n,s):s,stateOverride:n&&a?[...c??[],{address:a,code:uz}]:c,...n?{to:a}:{},...typeof i=="bigint"?{blockNumber:i}:{blockTag:o}})).data??"0x",status:"success"}}catch(u){if(!(u instanceof ANe.CallExecutionError)||!(u.cause instanceof INe.ExecutionRevertedError))throw u;return{data:"0x",status:"failure"}}}function qNe(e){let t=new Set(e.map(n=>n.toLowerCase())),r=CNe;for(;t.has(`0x${r.toString(16).padStart(40,"0")}`);)r++;return`0x${r.toString(16).padStart(40,"0")}`}});var pz=g(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.InvalidWrappedSignatureError=gr.universalSignatureValidatorAbi=gr.universalSignatureValidatorBytecode=gr.magicBytes=void 0;gr.assert=Sk;gr.from=LNe;gr.unwrap=fz;gr.wrap=BNe;gr.validate=UNe;var j1=id(),DNe=Vr(),lz=Jt();gr.magicBytes="0x6492649264926492649264926492649264926492649264926492649264926492";gr.universalSignatureValidatorBytecode="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572";gr.universalSignatureValidatorAbi=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}];function Sk(e){if(lz.slice(e,-32)!==gr.magicBytes)throw new M1(e)}function LNe(e){return typeof e=="string"?fz(e):e}function fz(e){Sk(e);let[t,r,n]=j1.decode(j1.from("address, bytes, bytes"),e);return{data:r,signature:n,to:t}}function BNe(e){let{data:t,signature:r,to:n}=e;return lz.concat(j1.encode(j1.from("address, bytes, bytes"),[n,t,r]),gr.magicBytes)}function UNe(e){try{return Sk(e),!0}catch{return!1}}var M1=class extends DNe.BaseError{constructor(t){super(`Value \`${t}\` is an invalid ERC-6492 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc6492.InvalidWrappedSignatureError"})}};gr.InvalidWrappedSignatureError=M1});var mz=g(q1=>{"use strict";Object.defineProperty(q1,"__esModule",{value:!0});q1.SignatureErc6492=void 0;q1.SignatureErc6492=pz()});var Ik=g(Ak=>{"use strict";Object.defineProperty(Ak,"__esModule",{value:!0});Ak.serializeSignature=$Ne;var HNe=Ga(),gz=pt(),FNe=Je();function $Ne({r:e,s:t,to:r="hex",v:n,yParity:i}){let o=(()=>{if(i===0||i===1)return i;if(n&&(n===27n||n===28n||n>=35n))return n%2n===0n?1:0;throw new Error("Invalid `v` or `yParity` value")})(),s=`0x${new HNe.secp256k1.Signature((0,gz.hexToBigInt)(e),(0,gz.hexToBigInt)(t)).toCompactHex()}${o===0?"1b":"1c"}`;return r==="hex"?s:(0,FNe.hexToBytes)(s)}});var Ph=g(Ih=>{"use strict";Object.defineProperty(Ih,"__esModule",{value:!0});Ih.verifyHash=ZNe;Ih.verifyErc8010=Iz;Ih.verifyErc1271=Pz;var hz=mz(),Ez=ih(),Ah=er(),wz=zl(),vz=ao(),JNe=Xl(),Sz=Tr(),yz=Ir(),_z=ln(),VNe=aC(),GNe=Nt(),KNe=Sr(),WNe=pt(),Pk=W(),Tk=Te(),bz=ds(),zNe=Ik(),YNe=Qa(),XNe=RE(),Az=Cr();async function ZNe(e,t){let{address:r,chain:n=e.chain,hash:i,erc6492VerifierAddress:o=t.universalSignatureVerifierAddress??n?.contracts?.erc6492Verifier?.address,multicallAddress:s=t.multicallAddress??n?.contracts?.multicall3?.address,mode:a="auto"}=t;if(n?.verifyHash)return await n.verifyHash(e,t);let c=(()=>{let u=t.signature;return(0,KNe.isHex)(u)?u:typeof u=="object"&&"r"in u&&"s"in u?(0,zNe.serializeSignature)(u):(0,Pk.bytesToHex)(u)})();try{if(a==="eoa")try{if((0,_z.isAddressEqual)((0,yz.getAddress)(r),await(0,bz.recoverAddress)({hash:i,signature:c})))return!0}catch{}return Ez.SignatureErc8010.validate(c)?await Iz(e,{...t,multicallAddress:s,signature:c}):await QNe(e,{...t,verifierAddress:o,signature:c})}catch(u){if(a!=="eoa")try{if((0,_z.isAddressEqual)((0,yz.getAddress)(r),await(0,bz.recoverAddress)({hash:i,signature:c})))return!0}catch{}if(u instanceof Ps)return!1;throw u}}async function Iz(e,t){let{address:r,blockHash:n,blockNumber:i,blockTag:o,hash:s,multicallAddress:a,requireCanonical:c}=t,{authorization:u,data:d,signature:l,to:m}=Ez.SignatureErc8010.unwrap(t.signature);if(await(0,XNe.getCode)(e,{address:r,blockHash:n,blockNumber:i,blockTag:o,requireCanonical:c})===(0,GNe.concatHex)(["0xef0100",u.address]))return await Pz(e,{...t,signature:l});let h={address:u.address,chainId:Number(u.chainId),nonce:Number(u.nonce),r:(0,Pk.numberToHex)(u.r,{size:32}),s:(0,Pk.numberToHex)(u.s,{size:32}),yParity:u.yParity};if(!await(0,VNe.verifyAuthorization)({address:r,authorization:h}))throw new Ps;let b=await(0,Tk.getAction)(e,Az.readContract,"readContract")({...a?{address:a}:{code:wz.multicall3Bytecode},authorizationList:[h],abi:Ah.multicall3Abi,blockHash:n,blockNumber:i,blockTag:"pending",functionName:"aggregate3",requireCanonical:c,args:[[...d?[{allowFailure:!0,target:m??r,callData:d}]:[],{allowFailure:!0,target:r,callData:(0,Sz.encodeFunctionData)({abi:Ah.erc1271Abi,functionName:"isValidSignature",args:[s,l]})}]]});if(b[b.length-1]?.returnData?.startsWith("0x1626ba7e"))return!0;throw new Ps}async function QNe(e,t){let{address:r,factory:n,factoryData:i,hash:o,signature:s,verifierAddress:a,...c}=t,u=await(async()=>!n&&!i||hz.SignatureErc6492.validate(s)?s:hz.SignatureErc6492.wrap({data:i,signature:s,to:n}))(),d=a?{to:a,data:(0,Sz.encodeFunctionData)({abi:Ah.erc6492SignatureValidatorAbi,functionName:"isValidSig",args:[r,o,u]}),...c}:{data:(0,JNe.encodeDeployData)({abi:Ah.erc6492SignatureValidatorAbi,args:[r,o,u],bytecode:wz.erc6492SignatureValidatorByteCode}),...c},{data:l}=await(0,Tk.getAction)(e,YNe.call,"call")(d).catch(m=>{throw m instanceof vz.CallExecutionError?new Ps:m});if((0,WNe.hexToBool)(l??"0x0"))return!0;throw new Ps}async function Pz(e,t){let{address:r,blockHash:n,blockNumber:i,blockTag:o,hash:s,requireCanonical:a,signature:c}=t;if((await(0,Tk.getAction)(e,Az.readContract,"readContract")({address:r,abi:Ah.erc1271Abi,args:[s,c],blockHash:n,blockNumber:i,blockTag:o,functionName:"isValidSignature",requireCanonical:a}).catch(d=>{throw d instanceof vz.ContractFunctionExecutionError?new Ps:d})).startsWith("0x1626ba7e"))return!0;throw new Ps}var Ps=class extends Error{}});var Tz=g(xk=>{"use strict";Object.defineProperty(xk,"__esModule",{value:!0});xk.verifyMessage=n5e;var e5e=Te(),t5e=yf(),r5e=Ph();async function n5e(e,{address:t,message:r,factory:n,factoryData:i,signature:o,...s}){let a=(0,t5e.hashMessage)(r);return(0,e5e.getAction)(e,r5e.verifyHash,"verifyHash")({address:t,factory:n,factoryData:i,hash:a,signature:o,...s})}});var xz=g(Ok=>{"use strict";Object.defineProperty(Ok,"__esModule",{value:!0});Ok.verifyTypedData=a5e;var i5e=Te(),o5e=bf(),s5e=Ph();async function a5e(e,t){let{address:r,factory:n,factoryData:i,signature:o,message:s,primaryType:a,types:c,domain:u,...d}=t,l=(0,o5e.hashTypedData)({message:s,primaryType:a,types:c,domain:u});return(0,i5e.getAction)(e,s5e.verifyHash,"verifyHash")({address:r,factory:n,factoryData:i,hash:l,signature:o,...d})}});var Ck=g(Rk=>{"use strict";Object.defineProperty(Rk,"__esModule",{value:!0});Rk.watchBlockNumber=f5e;var c5e=pt(),u5e=Te(),Oz=hs(),d5e=qu(),Rz=Mt(),l5e=Du();function f5e(e,{emitOnBegin:t=!1,emitMissed:r=!1,onBlockNumber:n,onError:i,poll:o,pollingInterval:s=e.pollingInterval}){let a=typeof o<"u"?o:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")),c;return a?(()=>{let l=(0,Rz.stringify)(["watchBlockNumber",e.uid,t,r,s]);return(0,Oz.observe)(l,{onBlockNumber:n,onError:i},m=>(0,d5e.poll)(async()=>{try{let p=await(0,u5e.getAction)(e,l5e.getBlockNumber,"getBlockNumber")({cacheTime:0});if(c!==void 0){if(p===c)return;if(p-c>1&&r)for(let h=c+1n;h<p;h++)m.onBlockNumber(h,c),c=h}(c===void 0||p>c)&&(m.onBlockNumber(p,c),c=p)}catch(p){m.onError?.(p)}},{emitOnBegin:t,interval:s}))})():(()=>{let l=(0,Rz.stringify)(["watchBlockNumber",e.uid,t,r]);return(0,Oz.observe)(l,{onBlockNumber:n,onError:i},m=>{let p=!0,h=()=>p=!1;return(async()=>{try{let y=(()=>{if(e.transport.type==="fallback"){let v=e.transport.transports.find(A=>A.config.type==="webSocket"||A.config.type==="ipc");return v?v.value:e.transport}return e.transport})(),{unsubscribe:b}=await y.subscribe({params:["newHeads"],onData(v){if(!p)return;let A=(0,c5e.hexToBigInt)(v.result?.number);m.onBlockNumber(A,c),c=A},onError(v){m.onError?.(v)}});h=b,p||h()}catch(y){i?.(y)}})(),()=>h()})})()}});var Mk=g(jk=>{"use strict";Object.defineProperty(jk,"__esModule",{value:!0});jk.waitForTransactionReceipt=E5e;var p5e=Ym(),Nk=Xt(),Ff=Te(),m5e=hs(),g5e=oE(),Cz=Sg(),h5e=Mt(),y5e=fs(),_5e=S1(),kk=uk(),b5e=Ck();async function E5e(e,t){let{checkReplacement:r=e.chain?.supportsTransactionReplacementDetection??!0,confirmations:n=1,hash:i,onReplaced:o,retryCount:s=6,retryDelay:a=({count:I})=>~~(1<<I)*200,timeout:c=18e4}=t,u=(0,h5e.stringify)(["waitForTransactionReceipt",e.uid,i]),d=t.pollingInterval?t.pollingInterval:e.chain?.experimental_preconfirmationTime?e.chain.experimental_preconfirmationTime:e.pollingInterval,l,m,p,h=!1,y,b,{promise:v,resolve:A,reject:E}=(0,g5e.withResolvers)(),S=c?setTimeout(()=>{b?.(),y?.(),E(new Nk.WaitForTransactionReceiptTimeoutError({hash:i}))},c):void 0;return y=(0,m5e.observe)(u,{onReplaced:o,resolve:A,reject:E},async I=>{if(p=await(0,Ff.getAction)(e,kk.getTransactionReceipt,"getTransactionReceipt")({hash:i}).catch(()=>{}),p&&n<=1){clearTimeout(S),I.resolve(p),y?.();return}b=(0,Ff.getAction)(e,b5e.watchBlockNumber,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:d,async onBlockNumber(T){let x=k=>{clearTimeout(S),b?.(),k(),y?.()},C=T;if(!h)try{if(p){if(n>1&&(!p.blockNumber||C-p.blockNumber+1n<n))return;x(()=>I.resolve(p));return}if(r&&!l&&(h=!0,await(0,Cz.withRetry)(async()=>{l=await(0,Ff.getAction)(e,_5e.getTransaction,"getTransaction")({hash:i}),l.blockNumber&&(C=l.blockNumber)},{delay:a,retryCount:s}),h=!1),p=await(0,Ff.getAction)(e,kk.getTransactionReceipt,"getTransactionReceipt")({hash:i}),n>1&&(!p.blockNumber||C-p.blockNumber+1n<n))return;x(()=>I.resolve(p))}catch(k){if(k instanceof Nk.TransactionNotFoundError||k instanceof Nk.TransactionReceiptNotFoundError){if(!l){h=!1;return}try{m=l,h=!0;let N=await(0,Cz.withRetry)(()=>(0,Ff.getAction)(e,y5e.getBlock,"getBlock")({blockNumber:C,includeTransactions:!0}),{delay:a,retryCount:s,shouldRetry:({error:D})=>D instanceof p5e.BlockNotFoundError});h=!1;let M=N.transactions.find(({from:D,nonce:U})=>D===m.from&&U===m.nonce);if(!M||(p=await(0,Ff.getAction)(e,kk.getTransactionReceipt,"getTransactionReceipt")({hash:M.hash}),n>1&&(!p.blockNumber||C-p.blockNumber+1n<n)))return;let j="replaced";M.to===m.to&&M.value===m.value&&M.input===m.input?j="repriced":M.from===M.to&&M.value===0n&&(j="cancelled"),x(()=>{I.onReplaced?.({reason:j,replacedTransaction:m,transaction:M,transactionReceipt:p}),I.resolve(p)})}catch(N){x(()=>I.reject(N))}}else x(()=>I.reject(k))}}})}),v}});var Nz=g(qk=>{"use strict";Object.defineProperty(qk,"__esModule",{value:!0});qk.watchBlockHeaders=I5e;var w5e=Ul(),v5e=hs(),S5e=Mt(),A5e=["size","totalDifficulty","transactions","uncles","withdrawals"];function I5e(e,{onBlockHeader:t,onError:r}){let n,i=(0,S5e.stringify)(["watchBlockHeaders",e.uid]);return(0,v5e.observe)(i,{onBlockHeader:t,onError:r},o=>{let s=!0,a=!1,c=()=>s=!1;return(async()=>{try{let u=(()=>{if(e.transport.type==="fallback"){let l=e.transport.transports.find(m=>m.config.type==="webSocket"||m.config.type==="ipc");return l?l.value:e.transport}return e.transport})(),{unsubscribe:d}=await u.subscribe({params:["newHeads"],onData(l){if(!s)return;let m=(e.chain?.formatters?.block?.format||w5e.formatBlock)(l.result,"watchBlockHeaders");for(let p of A5e)delete m[p];o.onBlockHeader(m,n),n=m},onError(l){a&&o.onError?.(l)}});a=!0,c=d,s||c()}catch(u){o.onError?.(u)}})(),()=>c()})}});var kz=g(Dk=>{"use strict";Object.defineProperty(Dk,"__esModule",{value:!0});Dk.watchBlocks=O5e;var D1=Te(),P5e=hs(),T5e=qu(),x5e=Mt(),L1=fs();function O5e(e,{blockTag:t=e.experimental_blockTag??"latest",emitMissed:r=!1,emitOnBegin:n=!1,onBlock:i,onError:o,includeTransactions:s,poll:a,pollingInterval:c=e.pollingInterval}){let u=typeof a<"u"?a:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")),d=s??!1,l;return u?(()=>{let h=(0,x5e.stringify)(["watchBlocks",e.uid,t,r,n,d,c]);return(0,P5e.observe)(h,{onBlock:i,onError:o},y=>(0,T5e.poll)(async()=>{try{let b=await(0,D1.getAction)(e,L1.getBlock,"getBlock")({blockTag:t,includeTransactions:d});if(b.number!==null&&l?.number!=null){if(b.number===l.number)return;if(b.number-l.number>1&&r)for(let v=l?.number+1n;v<b.number;v++){let A=await(0,D1.getAction)(e,L1.getBlock,"getBlock")({blockNumber:v,includeTransactions:d});y.onBlock(A,l),l=A}}(l?.number==null||t==="pending"&&b?.number==null||b.number!==null&&b.number>l.number)&&(y.onBlock(b,l),l=b)}catch(b){y.onError?.(b)}},{emitOnBegin:n,interval:c}))})():(()=>{let h=!0,y=!0,b=()=>h=!1;return(async()=>{try{n&&(0,D1.getAction)(e,L1.getBlock,"getBlock")({blockTag:t,includeTransactions:d}).then(E=>{h&&y&&(i(E,void 0),y=!1)}).catch(o);let v=(()=>{if(e.transport.type==="fallback"){let E=e.transport.transports.find(S=>S.config.type==="webSocket"||S.config.type==="ipc");return E?E.value:e.transport}return e.transport})(),{unsubscribe:A}=await v.subscribe({params:["newHeads"],async onData(E){if(!h)return;let S=await(0,D1.getAction)(e,L1.getBlock,"getBlock")({blockNumber:E.result?.number,includeTransactions:d}).catch(()=>{});h&&(i(S,l),y=!1,l=S)},onError(E){o?.(E)}});b=A,h||b()}catch(v){o?.(v)}})(),()=>b()})()}});var qz=g(Lk=>{"use strict";Object.defineProperty(Lk,"__esModule",{value:!0});Lk.watchEvent=H5e;var jz=ft(),R5e=ss(),C5e=Jl(),N5e=Ca(),Mz=xi(),Th=Te(),k5e=hs(),j5e=qu(),M5e=Mt(),q5e=CR(),D5e=Du(),L5e=yg(),B5e=Wb(),U5e=_g();function H5e(e,{address:t,args:r,batch:n=!0,event:i,events:o,fromBlock:s,onError:a,onLogs:c,poll:u,pollingInterval:d=e.pollingInterval,strict:l}){let m=typeof u<"u"?u:typeof s=="bigint"?!0:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")),p=l??!1;return m?(()=>{let b=(0,M5e.stringify)(["watchEvent",t,r,n,e.uid,i,d,s]);return(0,k5e.observe)(b,{onLogs:c,onError:a},v=>{let A;s!==void 0&&(A=s-1n);let E,S=!1,I=(0,j5e.poll)(async()=>{if(!S){try{E=await(0,Th.getAction)(e,q5e.createEventFilter,"createEventFilter")({address:t,args:r,event:i,events:o,strict:p,fromBlock:s})}catch{}S=!0;return}try{let T;if(E)T=await(0,Th.getAction)(e,L5e.getFilterChanges,"getFilterChanges")({filter:E});else{let x=await(0,Th.getAction)(e,D5e.getBlockNumber,"getBlockNumber")({});A&&A!==x?T=await(0,Th.getAction)(e,B5e.getLogs,"getLogs")({address:t,args:r,event:i,events:o,fromBlock:A+1n,toBlock:x}):T=[],A=x}if(T.length===0)return;if(n)v.onLogs(T);else for(let x of T)v.onLogs([x])}catch(T){E&&T instanceof R5e.InvalidInputRpcError&&(S=!1),v.onError?.(T)}},{emitOnBegin:!0,interval:d});return async()=>{E&&await(0,Th.getAction)(e,U5e.uninstallFilter,"uninstallFilter")({filter:E}),I()}})})():(()=>{let b=!0,v=()=>b=!1;return(async()=>{try{let A=(()=>{if(e.transport.type==="fallback"){let T=e.transport.transports.find(x=>x.config.type==="webSocket"||x.config.type==="ipc");return T?T.value:e.transport}return e.transport})(),E=o??(i?[i]:void 0),S=[];E&&(S=[E.flatMap(x=>(0,N5e.encodeEventTopics)({abi:[x],eventName:x.name,args:r}))],i&&(S=S[0]));let{unsubscribe:I}=await A.subscribe({params:["logs",{address:t,topics:S}],onData(T){if(!b)return;let x=T.result;try{let{eventName:C,args:k}=(0,C5e.decodeEventLog)({abi:E??[],data:x.data,topics:x.topics,strict:p}),N=(0,Mz.formatLog)(x,{args:k,eventName:C});c([N])}catch(C){let k,N;if(C instanceof jz.DecodeLogDataMismatch||C instanceof jz.DecodeLogTopicsMismatch){if(l)return;k=C.abiItem.name,N=C.abiItem.inputs?.some(j=>!("name"in j&&j.name))}let M=(0,Mz.formatLog)(x,{args:N?[]:{},eventName:k});c([M])}},onError(T){a?.(T)}});v=I,b||v()}catch(A){a?.(A)}})(),()=>v()})()}});var Dz=g(Uk=>{"use strict";Object.defineProperty(Uk,"__esModule",{value:!0});Uk.watchPendingTransactions=W5e;var Bk=Te(),F5e=hs(),$5e=qu(),J5e=Mt(),V5e=kR(),G5e=yg(),K5e=_g();function W5e(e,{batch:t=!0,onError:r,onTransactions:n,poll:i,pollingInterval:o=e.pollingInterval}){return(typeof i<"u"?i:e.transport.type!=="webSocket"&&e.transport.type!=="ipc")?(()=>{let u=(0,J5e.stringify)(["watchPendingTransactions",e.uid,t,o]);return(0,F5e.observe)(u,{onTransactions:n,onError:r},d=>{let l,m=(0,$5e.poll)(async()=>{try{if(!l)try{l=await(0,Bk.getAction)(e,V5e.createPendingTransactionFilter,"createPendingTransactionFilter")({});return}catch(h){throw m(),h}let p=await(0,Bk.getAction)(e,G5e.getFilterChanges,"getFilterChanges")({filter:l});if(p.length===0)return;if(t)d.onTransactions(p);else for(let h of p)d.onTransactions([h])}catch(p){d.onError?.(p)}},{emitOnBegin:!0,interval:o});return async()=>{l&&await(0,Bk.getAction)(e,K5e.uninstallFilter,"uninstallFilter")({filter:l}),m()}})})():(()=>{let u=!0,d=()=>u=!1;return(async()=>{try{let{unsubscribe:l}=await e.transport.subscribe({params:["newPendingTransactions"],onData(m){if(!u)return;let p=m.result;n([p])},onError(m){r?.(m)}});d=l,u||d()}catch(l){r?.(l)}})(),()=>d()})()}});var Lz=g(Fk=>{"use strict";Object.defineProperty(Fk,"__esModule",{value:!0});Fk.parseSiweMessage=X5e;var z5e=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function Y5e(e){return z5e.test(e)?!Number.isNaN(new Date(e).getTime()):!1}function Hk(e){return Y5e(e)?new Date(e):new Date(Number.NaN)}function X5e(e){let{scheme:t,statement:r,...n}=e.match(Z5e)?.groups??{},{chainId:i,expirationTime:o,issuedAt:s,notBefore:a,requestId:c,...u}=e.match(Q5e)?.groups??{},d=e.split("Resources:")[1]?.split(`
64
+ - `).slice(1);return{...n,...u,...i?{chainId:Number(i)}:{},...o?{expirationTime:Hk(o)}:{},...s?{issuedAt:Hk(s)}:{},...a?{notBefore:Hk(a)}:{},...c?{requestId:c}:{},...d?{resources:d}:{},...t?{scheme:t}:{},...r?{statement:r}:{}}}var Z5e=/^(?:(?<scheme>[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?<domain>[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?<address>0x[a-fA-F0-9]{40})\n\n(?:(?<statement>.*)\n\n)?/,Q5e=/(?:URI: (?<uri>.+))\n(?:Version: (?<version>.+))\n(?:Chain ID: (?<chainId>\d+))\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\n(?:Issued At: (?<issuedAt>.+))(?:\nExpiration Time: (?<expirationTime>.+))?(?:\nNot Before: (?<notBefore>.+))?(?:\nRequest ID: (?<requestId>.+))?/});var Bz=g($k=>{"use strict";Object.defineProperty($k,"__esModule",{value:!0});$k.validateSiweMessage=rke;var eke=Pr(),tke=ln();function rke(e){let{address:t,domain:r,message:n,nonce:i,scheme:o,time:s=new Date}=e;if(r&&n.domain!==r||i&&n.nonce!==i||o&&n.scheme!==o||Number.isNaN(s.getTime())||n.expirationTime&&(Number.isNaN(n.expirationTime.getTime())||s>=n.expirationTime)||n.notBefore&&(Number.isNaN(n.notBefore.getTime())||s<n.notBefore))return!1;try{if(!n.address||!(0,eke.isAddress)(n.address,{strict:!1})||t&&!(0,tke.isAddressEqual)(n.address,t))return!1}catch{return!1}return!0}});var Uz=g(Jk=>{"use strict";Object.defineProperty(Jk,"__esModule",{value:!0});Jk.verifySiweMessage=ake;var nke=yf(),ike=Lz(),oke=Bz(),ske=Ph();async function ake(e,t){let{address:r,domain:n,message:i,nonce:o,scheme:s,signature:a,time:c=new Date,...u}=t,d=(0,ike.parseSiweMessage)(i);if(!d.address||!(0,oke.validateSiweMessage)({address:r,domain:n,message:d,nonce:o,scheme:s,time:c}))return!1;let m=(0,nke.hashMessage)(i);return(0,ske.verifyHash)(e,{address:d.address,hash:m,signature:a,...u})}});var Ts=g(Ni=>{"use strict";Object.defineProperty(Ni,"__esModule",{value:!0});Ni.toAmount=pke;Ni.toBaseUnits=mke;Ni.requireTokenDecimals=$z;Ni.resolveAmountDecimals=gke;Ni.resolveToken=Jz;Ni.findDeclaredToken=Vz;Ni.resolveTokenWithDecimals=_ke;Ni.pickWriteParameters=bke;Ni.defineCall=Eke;var cke=er(),Hz=Pr(),Fz=ln(),uke=tk(),dke=Mf(),lke=E1(),fke=Cr();function pke(e,t){return{amount:e,decimals:t,formatted:(0,dke.formatUnits)(e,t)}}function mke(e,t){if(typeof e=="bigint")return e;let r=e.decimals??t;return(0,lke.parseUnits)(e.formatted,$z(r))}function $z(e){if(e===void 0)throw new Error("Token decimals are required. Pass `amount.decimals` or select a declared token.");return e}function gke(e,t){return typeof e=="bigint"?t:e.decimals??t}function Jz(e,t){let{decimals:r,token:n}=t,i=Vz(e,n);if(i)return{address:i.address,decimals:r??i.decimals};if((0,Hz.isAddress)(n,{strict:!1}))return{address:n,decimals:r??yke(e,n)};throw new Error(`Token "${n}" is not a declared ERC-20 token on the client's \`tokens\` array (with an address for the client's chain), and is not a valid address.`)}function Vz(e,t){let r=e.tokens,n=e.chain?.id;if(!r||n===void 0)return;let i=hke(r,t);if(i)return Vk(i,n);if((0,Hz.isAddress)(t,{strict:!1}))for(let o of r){let s=Vk(o,n);if(s&&(0,Fz.isAddressEqual)(s.address,t))return s}}function Vk(e,t){let r=e.addresses[t];if(r)return{address:r,currency:e.currency,decimals:e.decimals,name:e.name,popular:e.popular,symbol:e.symbol}}function hke(e,t){let r=t.toLowerCase();for(let n of e)if(n.symbol?.toLowerCase()===r)return n}function yke(e,t){let r=e.tokens,n=e.chain?.id;if(r&&n!==void 0)for(let i of r){let o=Vk(i,n);if(o&&(0,Fz.isAddressEqual)(o.address,t))return o.decimals}}async function _ke(e,t){let{address:r,decimals:n}=Jz(e,t);return n!==void 0?{address:r,decimals:n}:{address:r,decimals:await(0,fke.readContract)(e,{abi:cke.erc20Abi,address:r,functionName:"decimals"})}}function bke(e){let{account:t,chain:r,gas:n,maxFeePerGas:i,maxPriorityFeePerGas:o,nonce:s}=e;return{account:t,chain:r,gas:n,maxFeePerGas:i,maxPriorityFeePerGas:o,nonce:s}}function Eke(e){return{...e,data:(0,uke.encodeFunctionData)(e),to:e.address}}});var Gk=g(U1=>{"use strict";Object.defineProperty(U1,"__esModule",{value:!0});U1.approve=B1;var Gz=er(),wke=Ya(),vke=og(),Ske=hg(),Ake=rf(),xh=Ts();async function B1(e,t){return B1.inner(Ake.writeContract,e,t)}(function(e){async function t(s,a,c){return await s(a,{...c,...e.call(a,c)})}e.inner=t;function r(s,a){return(0,xh.defineCall)(Ike(s,a))}e.call=r;async function n(s,a){return(0,vke.estimateContractGas)(s,{...(0,xh.pickWriteParameters)(a),...e.call(s,a)})}e.estimateGas=n;async function i(s,a){return(0,Ske.simulateContract)(s,{...(0,xh.pickWriteParameters)(a),...e.call(s,a)})}e.simulate=i;function o(s){let[a]=(0,wke.parseEventLogs)({abi:Gz.erc20Abi,logs:s,eventName:"Approval",strict:!0});if(!a)throw new Error("`Approval` event not found.");return a}e.extractEvent=o})(B1||(U1.approve=B1={}));function Ike(e,t){let{amount:r,spender:n,token:i}=t,{address:o,decimals:s}=(0,xh.resolveToken)(e,{token:i});return{abi:Gz.erc20Abi,address:o,args:[n,(0,xh.toBaseUnits)(r,s)],functionName:"approve"}}});var H1=g(Kk=>{"use strict";Object.defineProperty(Kk,"__esModule",{value:!0});Kk.sendRawTransactionSync=xke;var Pke=Xt(),Tke=Bu();async function xke(e,{serializedTransaction:t,throwOnReceiptRevert:r,timeout:n}){let i=await e.request({method:"eth_sendRawTransactionSync",params:n?[t,n]:[t]},{retryCount:0}),s=(e.chain?.formatters?.transactionReceipt?.format||Tke.formatTransactionReceipt)(i);if(s.status==="reverted"&&r)throw new Pke.TransactionReceiptRevertedError({receipt:s});return s}});var Yk=g(zk=>{"use strict";Object.defineProperty(zk,"__esModule",{value:!0});zk.sendTransactionSync=Hke;var Oke=at(),F1=yo(),Rke=ye(),Kz=Xt(),Cke=ql(),Nke=tf(),Wz=Nt(),kke=Hl(),jke=ls(),Mke=Zn(),$1=Te(),qke=Ta(),Dke=Qn(),Lke=ps(),Bke=Mk(),zz=Fl(),Uke=H1(),Wk=new qke.LruMap(128);async function Hke(e,t){let{account:r=e.account,assertChainId:n=!0,chain:i=e.chain,accessList:o,authorizationList:s,blobs:a,data:c,dataSuffix:u=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,gas:d,gasPrice:l,maxFeePerBlobGas:m,maxFeePerGas:p,maxPriorityFeePerGas:h,nonce:y,pollingInterval:b,throwOnReceiptRevert:v,type:A,value:E,...S}=t,I=t.timeout??Math.max((i?.blockTime??0)*3,5e3);if(typeof r>"u")throw new F1.AccountNotFoundError({docsPath:"/docs/actions/wallet/sendTransactionSync"});let T=r?(0,Oke.parseAccount)(r):null,x;try{(0,Dke.assertRequest)(t);let C=await(async()=>{if(t.to)return t.to;if(t.to!==null&&s&&s.length>0)return await(0,Cke.recoverAuthorizationAddress)({authorization:s[0]}).catch(()=>{throw new Rke.BaseError("`to` is required. Could not infer from `authorizationList`.")})})();if(T?.type==="json-rpc"||T===null){let k;i!==null&&(k=await(0,$1.getAction)(e,Lke.getChainId,"getChainId")({}),n&&(0,Nke.assertCurrentChain)({currentChainId:k,chain:i}));let N=e.chain?.formatters?.transactionRequest?.format,j=(N||Mke.formatTransactionRequest)({...(0,jke.extract)(S,{format:N}),accessList:o,account:T,authorizationList:s,blobs:a,chainId:k,data:u?(0,Wz.concat)([c??"0x",u]):c,gas:d,gasPrice:l,maxFeePerBlobGas:m,maxFeePerGas:p,maxPriorityFeePerGas:h,nonce:y,to:C,type:A,value:E},"sendTransaction"),D=Wk.get(e.uid),U=D?"wallet_sendTransaction":"eth_sendTransaction",q=await(async()=>{try{return await e.request({method:U,params:[j]},{retryCount:0})}catch(V){if(D===!1)throw V;let Q=V;if(Q.name==="InvalidInputRpcError"||Q.name==="InvalidParamsRpcError"||Q.name==="MethodNotFoundRpcError"||Q.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[j]},{retryCount:0}).then(re=>(Wk.set(e.uid,!0),re)).catch(re=>{let _e=re;throw _e.name==="MethodNotFoundRpcError"||_e.name==="MethodNotSupportedRpcError"?(Wk.set(e.uid,!1),Q):_e});throw Q}})(),L=await(0,$1.getAction)(e,Bke.waitForTransactionReceipt,"waitForTransactionReceipt")({checkReplacement:!1,hash:q,pollingInterval:b,timeout:I});if(v&&L.status==="reverted")throw new Kz.TransactionReceiptRevertedError({receipt:L});return L}if(T?.type==="local"){let k=(()=>{if(!T.nonceManager||typeof y<"u")return T.nonceManager;let D=T.nonceManager;return{consume(U){return x={address:U.address,chainId:U.chainId},D.consume(U)},get(U){return D.get(U)},increment(U){return D.increment(U)},reset(U){return D.reset(U)}}})(),N=await(0,$1.getAction)(e,zz.prepareTransactionRequest,"prepareTransactionRequest")({account:T,accessList:o,authorizationList:s,blobs:a,chain:i,data:u?(0,Wz.concat)([c??"0x",u]):c,gas:d,gasPrice:l,maxFeePerBlobGas:m,maxFeePerGas:p,maxPriorityFeePerGas:h,nonce:y,nonceManager:k,parameters:[...zz.defaultParameters,"sidecars"],type:A,value:E,...S,to:C}),M=i?.serializers?.transaction,j=await T.signTransaction(N,{serializer:M});return await(0,$1.getAction)(e,Uke.sendRawTransactionSync,"sendRawTransactionSync")({serializedTransaction:j,throwOnReceiptRevert:v,timeout:t.timeout})}throw T?.type==="smart"?new F1.AccountTypeNotSupportedError({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new F1.AccountTypeNotSupportedError({docsPath:"/docs/actions/wallet/sendTransactionSync",type:T?.type})}catch(C){throw C instanceof F1.AccountTypeNotSupportedError?C:(x&&!(C instanceof Kz.TransactionReceiptRevertedError)&&T?.nonceManager?.reset(x),(0,kke.getTransactionError)(C,{...t,account:T,chain:t.chain||void 0}))}}});var J1=g(Xk=>{"use strict";Object.defineProperty(Xk,"__esModule",{value:!0});Xk.writeContractSync=Jke;var Fke=Yk(),$ke=rf();async function Jke(e,t){return $ke.writeContract.internal(e,Fke.sendTransactionSync,"sendTransactionSync",t)}});var Zz=g(Zk=>{"use strict";Object.defineProperty(Zk,"__esModule",{value:!0});Zk.approveSync=Kke;var Vke=Mf(),Gke=J1(),Yz=Gk(),Xz=Ts();async function Kke(e,t){let{amount:r,token:n,throwOnReceiptRevert:i=!0}=t,{decimals:o}=(0,Xz.resolveToken)(e,{token:n}),s=(0,Xz.resolveAmountDecimals)(r,o),a=await Yz.approve.inner(Gke.writeContractSync,e,{...t,throwOnReceiptRevert:i}),{args:c}=Yz.approve.extractEvent(a.logs);return{...c,...s===void 0?{}:{decimals:s,formatted:(0,Vke.formatUnits)(c.value,s)},receipt:a}}});var Qz=g(K1=>{"use strict";Object.defineProperty(K1,"__esModule",{value:!0});K1.getAllowance=G1;var Wke=er(),zke=Cr(),V1=Ts();async function G1(e,t){let{account:r,decimals:n,spender:i,token:o,...s}=t,[a,{decimals:c}]=await Promise.all([(0,zke.readContract)(e,{...s,...G1.call(e,{account:r,spender:i,token:o})}),(0,V1.resolveTokenWithDecimals)(e,{decimals:n,token:o})]);return(0,V1.toAmount)(a,c)}(function(e){function t(r,n){return(0,V1.defineCall)({address:(0,V1.resolveToken)(r,n).address,abi:Wke.erc20Abi,functionName:"allowance",args:[n.account,n.spender]})}e.call=t})(G1||(K1.getAllowance=G1={}))});var rY=g(Y1=>{"use strict";Object.defineProperty(Y1,"__esModule",{value:!0});Y1.getBalance=z1;var eY=at(),Yke=er(),tY=yo(),Xke=Cr(),W1=Ts();async function z1(e,t){let{account:r=e.account,decimals:n,token:i,...o}=t;if(!r)throw new tY.AccountNotFoundError;let s=(0,eY.parseAccount)(r).address,[a,{decimals:c}]=await Promise.all([(0,Xke.readContract)(e,{...o,...z1.call(e,{account:s,token:i})}),(0,W1.resolveTokenWithDecimals)(e,{decimals:n,token:i})]);return(0,W1.toAmount)(a,c)}(function(e){function t(r,n){let i=n.account??r.account;if(!i)throw new tY.AccountNotFoundError;let o=(0,eY.parseAccount)(i).address;return(0,W1.defineCall)({address:(0,W1.resolveToken)(r,n).address,abi:Yke.erc20Abi,functionName:"balanceOf",args:[o]})}e.call=t})(z1||(Y1.getBalance=z1={}))});var iY=g(tj=>{"use strict";Object.defineProperty(tj,"__esModule",{value:!0});tj.getMetadata=Zke;var Qk=er(),ej=Cr(),nY=Ts();async function Zke(e,t){let{token:r,...n}=t,{address:i}=(0,nY.resolveToken)(e,{token:r}),o=(0,nY.findDeclaredToken)(e,r),[s,a,c]=await Promise.all([o?.decimals??(0,ej.readContract)(e,{...n,abi:Qk.erc20Abi,address:i,functionName:"decimals"}),o?.name??(0,ej.readContract)(e,{...n,abi:Qk.erc20Abi,address:i,functionName:"name"}),o?.symbol??(0,ej.readContract)(e,{...n,abi:Qk.erc20Abi,address:i,functionName:"symbol"})]);return{decimals:s,name:a,symbol:c}}});var oY=g(Q1=>{"use strict";Object.defineProperty(Q1,"__esModule",{value:!0});Q1.getTotalSupply=Z1;var Qke=er(),eje=Cr(),X1=Ts();async function Z1(e,t){let{decimals:r,token:n,...i}=t,[o,{decimals:s}]=await Promise.all([(0,eje.readContract)(e,{...i,...Z1.call(e,{token:n})}),(0,X1.resolveTokenWithDecimals)(e,{decimals:r,token:n})]);return(0,X1.toAmount)(o,s)}(function(e){function t(r,n){return(0,X1.defineCall)({address:(0,X1.resolveToken)(r,n).address,abi:Qke.erc20Abi,args:[],functionName:"totalSupply"})}e.call=t})(Z1||(Q1.getTotalSupply=Z1={}))});var nj=g(tv=>{"use strict";Object.defineProperty(tv,"__esModule",{value:!0});tv.transfer=ev;var rj=er(),tje=Ya(),rje=og(),nje=hg(),ije=rf(),Oh=Ts();async function ev(e,t){return ev.inner(ije.writeContract,e,t)}(function(e){async function t(s,a,c){return await s(a,{...c,...e.call(a,c)})}e.inner=t;function r(s,a){return(0,Oh.defineCall)(oje(s,a))}e.call=r;async function n(s,a){return(0,rje.estimateContractGas)(s,{...(0,Oh.pickWriteParameters)(a),...e.call(s,a)})}e.estimateGas=n;async function i(s,a){return(0,nje.simulateContract)(s,{...(0,Oh.pickWriteParameters)(a),...e.call(s,a)})}e.simulate=i;function o(s){let[a]=(0,tje.parseEventLogs)({abi:rj.erc20Abi,logs:s,eventName:"Transfer",strict:!0});if(!a)throw new Error("`Transfer` event not found.");return a}e.extractEvent=o})(ev||(tv.transfer=ev={}));function oje(e,t){let{amount:r,from:n,to:i,token:o}=t,{address:s,decimals:a}=(0,Oh.resolveToken)(e,{token:o}),c=(0,Oh.toBaseUnits)(r,a);return n?{abi:rj.erc20Abi,address:s,args:[n,i,c],functionName:"transferFrom"}:{abi:rj.erc20Abi,address:s,args:[i,c],functionName:"transfer"}}});var cY=g(ij=>{"use strict";Object.defineProperty(ij,"__esModule",{value:!0});ij.transferSync=cje;var sje=Mf(),aje=J1(),sY=Ts(),aY=nj();async function cje(e,t){let{amount:r,token:n,throwOnReceiptRevert:i=!0}=t,{decimals:o}=(0,sY.resolveToken)(e,{token:n}),s=(0,sY.resolveAmountDecimals)(r,o),a=await aY.transfer.inner(aje.writeContractSync,e,{...t,throwOnReceiptRevert:i}),{args:c}=aY.transfer.extractEvent(a.logs);return{...c,...s===void 0?{}:{decimals:s,formatted:(0,sje.formatUnits)(c.value,s)},receipt:a}}});var oj=g(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.transferSync=rr.transfer=rr.getTotalSupply=rr.getMetadata=rr.getBalance=rr.getAllowance=rr.approveSync=rr.approve=void 0;var uje=Gk();Object.defineProperty(rr,"approve",{enumerable:!0,get:function(){return uje.approve}});var dje=Zz();Object.defineProperty(rr,"approveSync",{enumerable:!0,get:function(){return dje.approveSync}});var lje=Qz();Object.defineProperty(rr,"getAllowance",{enumerable:!0,get:function(){return lje.getAllowance}});var fje=rY();Object.defineProperty(rr,"getBalance",{enumerable:!0,get:function(){return fje.getBalance}});var pje=iY();Object.defineProperty(rr,"getMetadata",{enumerable:!0,get:function(){return pje.getMetadata}});var mje=oY();Object.defineProperty(rr,"getTotalSupply",{enumerable:!0,get:function(){return mje.getTotalSupply}});var gje=nj();Object.defineProperty(rr,"transfer",{enumerable:!0,get:function(){return gje.transfer}});var hje=cY();Object.defineProperty(rr,"transferSync",{enumerable:!0,get:function(){return hje.transferSync}})});var aj=g(sj=>{"use strict";Object.defineProperty(sj,"__esModule",{value:!0});sj.publicActions=EMe;var yje=m7(),_je=v7(),bje=S7(),Eje=A7(),wje=AR(),vje=Qa(),Sje=I7(),Aje=P7(),Ije=w_(),Pje=CR(),Tje=kR(),xje=og(),Oje=dO(),Rje=Kb(),Cje=uO(),Nje=Gb(),kje=O7(),jje=R7(),Mje=fs(),qje=Du(),Dje=C7(),Lje=N7(),Bje=ps(),uY=RE(),Uje=zb(),Hje=k7(),Fje=M7(),$je=L7(),Jje=yg(),Vje=B7(),Gje=Db(),Kje=Wb(),Wje=OW(),zje=RW(),Yje=CW(),Xje=S1(),Zje=kW(),Qje=Zm(),eMe=uk(),tMe=BW(),rMe=Cr(),dY=fk(),nMe=dz(),iMe=hg(),oMe=_g(),sMe=Ph(),aMe=Tz(),cMe=xz(),uMe=Mk(),dMe=Nz(),lMe=Ck(),fMe=kz(),pMe=H6(),mMe=qz(),gMe=Dz(),hMe=Uz(),rv=oj(),yMe=Fl(),_Me=pE(),bMe=H1(),nv=Uu();function EMe(e){return{call:t=>(0,vje.call)(e,t),createAccessList:t=>(0,Sje.createAccessList)(e,t),createBlockFilter:()=>(0,Aje.createBlockFilter)(e),createContractEventFilter:t=>(0,Ije.createContractEventFilter)(e,t),createEventFilter:t=>(0,Pje.createEventFilter)(e,t),createPendingTransactionFilter:()=>(0,Tje.createPendingTransactionFilter)(e),estimateContractGas:t=>(0,xje.estimateContractGas)(e,t),estimateGas:t=>(0,Rje.estimateGas)(e,t),getBalance:t=>(0,kje.getBalance)(e,t),getBlobBaseFee:()=>(0,jje.getBlobBaseFee)(e),getBlock:t=>(0,Mje.getBlock)(e,t),getBlockNumber:t=>(0,qje.getBlockNumber)(e,t),getBlockReceipts:t=>(0,Dje.getBlockReceipts)(e,t),getBlockTransactionCount:t=>(0,Lje.getBlockTransactionCount)(e,t),getBytecode:t=>(0,uY.getCode)(e,t),getChainId:()=>(0,Bje.getChainId)(e),getCode:t=>(0,uY.getCode)(e,t),getContractEvents:t=>(0,Uje.getContractEvents)(e,t),getDelegation:t=>(0,Hje.getDelegation)(e,t),getEip712Domain:t=>(0,Fje.getEip712Domain)(e,t),getEnsAddress:t=>(0,yje.getEnsAddress)(e,t),getEnsAvatar:t=>(0,_je.getEnsAvatar)(e,t),getEnsName:t=>(0,bje.getEnsName)(e,t),getEnsResolver:t=>(0,Eje.getEnsResolver)(e,t),getEnsText:t=>(0,wje.getEnsText)(e,t),getFeeHistory:t=>(0,$je.getFeeHistory)(e,t),estimateFeesPerGas:t=>(0,Oje.estimateFeesPerGas)(e,t),getFilterChanges:t=>(0,Jje.getFilterChanges)(e,t),getFilterLogs:t=>(0,Vje.getFilterLogs)(e,t),getGasPrice:()=>(0,Gje.getGasPrice)(e),getLogs:t=>(0,Kje.getLogs)(e,t),getProof:t=>(0,Wje.getProof)(e,t),estimateMaxPriorityFeePerGas:t=>(0,Cje.estimateMaxPriorityFeePerGas)(e,t),fillTransaction:t=>(0,Nje.fillTransaction)(e,t),getRawTransaction:t=>(0,zje.getRawTransaction)(e,t),getStorageAt:t=>(0,Yje.getStorageAt)(e,t),getTransaction:t=>(0,Xje.getTransaction)(e,t),getTransactionConfirmations:t=>(0,Zje.getTransactionConfirmations)(e,t),getTransactionCount:t=>(0,Qje.getTransactionCount)(e,t),getTransactionReceipt:t=>(0,eMe.getTransactionReceipt)(e,t),multicall:t=>(0,tMe.multicall)(e,t),prepareTransactionRequest:t=>(0,yMe.prepareTransactionRequest)(e,t),readContract:t=>(0,rMe.readContract)(e,t),sendRawTransaction:t=>(0,_Me.sendRawTransaction)(e,t),sendRawTransactionSync:t=>(0,bMe.sendRawTransactionSync)(e,t),simulate:t=>(0,dY.simulateBlocks)(e,t),simulateBlocks:t=>(0,dY.simulateBlocks)(e,t),simulateCalls:t=>(0,nMe.simulateCalls)(e,t),simulateContract:t=>(0,iMe.simulateContract)(e,t),verifyHash:t=>(0,sMe.verifyHash)(e,t),verifyMessage:t=>(0,aMe.verifyMessage)(e,t),verifySiweMessage:t=>(0,hMe.verifySiweMessage)(e,t),verifyTypedData:t=>(0,cMe.verifyTypedData)(e,t),uninstallFilter:t=>(0,oMe.uninstallFilter)(e,t),waitForTransactionReceipt:t=>(0,uMe.waitForTransactionReceipt)(e,t),watchBlockHeaders:t=>(0,dMe.watchBlockHeaders)(e,t),watchBlocks:t=>(0,fMe.watchBlocks)(e,t),watchBlockNumber:t=>(0,lMe.watchBlockNumber)(e,t),watchContractEvent:t=>(0,pMe.watchContractEvent)(e,t),watchEvent:t=>(0,mMe.watchEvent)(e,t),watchPendingTransactions:t=>(0,gMe.watchPendingTransactions)(e,t),token:wMe(e)}}function wMe(e){return{getAllowance:(0,nv.bindActionDecorators)(e,rv.getAllowance),getBalance:(0,nv.bindActionDecorators)(e,rv.getBalance),getMetadata:(0,nv.bindActionDecorators)(e,rv.getMetadata),getTotalSupply:(0,nv.bindActionDecorators)(e,rv.getTotalSupply)}}});var lY=g(cj=>{"use strict";Object.defineProperty(cj,"__esModule",{value:!0});cj.createPublicClient=AMe;var vMe=Uu(),SMe=aj();function AMe(e){let{key:t="public",name:r="Public Client"}=e;return(0,vMe.createClient)({...e,key:t,name:r,type:"publicClient"}).extend(SMe.publicActions)}});var fY=g(uj=>{"use strict";Object.defineProperty(uj,"__esModule",{value:!0});uj.dropTransaction=IMe;async function IMe(e,{hash:t}){await e.request({method:`${e.mode}_dropTransaction`,params:[t]})}});var pY=g(dj=>{"use strict";Object.defineProperty(dj,"__esModule",{value:!0});dj.dumpState=PMe;async function PMe(e){return e.request({method:`${e.mode}_dumpState`})}});var mY=g(lj=>{"use strict";Object.defineProperty(lj,"__esModule",{value:!0});lj.getAutomine=TMe;async function TMe(e){return e.mode==="ganache"?await e.request({method:"eth_mining"}):await e.request({method:`${e.mode}_getAutomine`})}});var gY=g(fj=>{"use strict";Object.defineProperty(fj,"__esModule",{value:!0});fj.getTxpoolContent=xMe;async function xMe(e){return await e.request({method:"txpool_content"})}});var yY=g(pj=>{"use strict";Object.defineProperty(pj,"__esModule",{value:!0});pj.getTxpoolStatus=OMe;var hY=pt();async function OMe(e){let{pending:t,queued:r}=await e.request({method:"txpool_status"});return{pending:(0,hY.hexToNumber)(t),queued:(0,hY.hexToNumber)(r)}}});var _Y=g(mj=>{"use strict";Object.defineProperty(mj,"__esModule",{value:!0});mj.impersonateAccount=RMe;async function RMe(e,{address:t}){await e.request({method:`${e.mode}_impersonateAccount`,params:[t]})}});var bY=g(gj=>{"use strict";Object.defineProperty(gj,"__esModule",{value:!0});gj.increaseTime=NMe;var CMe=W();async function NMe(e,{seconds:t}){return await e.request({method:"evm_increaseTime",params:[(0,CMe.numberToHex)(t)]})}});var EY=g(hj=>{"use strict";Object.defineProperty(hj,"__esModule",{value:!0});hj.inspectTxpool=kMe;async function kMe(e){return await e.request({method:"txpool_inspect"})}});var wY=g(yj=>{"use strict";Object.defineProperty(yj,"__esModule",{value:!0});yj.loadState=jMe;async function jMe(e,{state:t}){await e.request({method:`${e.mode}_loadState`,params:[t]})}});var vY=g(bj=>{"use strict";Object.defineProperty(bj,"__esModule",{value:!0});bj.mine=MMe;var _j=W();async function MMe(e,{blocks:t,interval:r}){e.mode==="ganache"?await e.request({method:"evm_mine",params:[{blocks:(0,_j.numberToHex)(t)}]}):await e.request({method:`${e.mode}_mine`,params:[(0,_j.numberToHex)(t),(0,_j.numberToHex)(r||0)]})}});var SY=g(Ej=>{"use strict";Object.defineProperty(Ej,"__esModule",{value:!0});Ej.removeBlockTimestampInterval=qMe;async function qMe(e){await e.request({method:`${e.mode}_removeBlockTimestampInterval`})}});var AY=g(wj=>{"use strict";Object.defineProperty(wj,"__esModule",{value:!0});wj.reset=DMe;async function DMe(e,{blockNumber:t,jsonRpcUrl:r}={}){await e.request({method:`${e.mode}_reset`,params:[{forking:{blockNumber:Number(t),jsonRpcUrl:r}}]})}});var IY=g(vj=>{"use strict";Object.defineProperty(vj,"__esModule",{value:!0});vj.revert=LMe;async function LMe(e,{id:t}){await e.request({method:"evm_revert",params:[t]})}});var PY=g(Sj=>{"use strict";Object.defineProperty(Sj,"__esModule",{value:!0});Sj.sendUnsignedTransaction=HMe;var BMe=ls(),UMe=Zn();async function HMe(e,t){let{accessList:r,data:n,from:i,gas:o,gasPrice:s,maxFeePerGas:a,maxPriorityFeePerGas:c,nonce:u,to:d,value:l,...m}=t,p=e.chain?.formatters?.transactionRequest?.format,y=(p||UMe.formatTransactionRequest)({...(0,BMe.extract)(m,{format:p}),accessList:r,data:n,from:i,gas:o,gasPrice:s,maxFeePerGas:a,maxPriorityFeePerGas:c,nonce:u,to:d,value:l},"sendUnsignedTransaction");return await e.request({method:"eth_sendUnsignedTransaction",params:[y]})}});var TY=g(Aj=>{"use strict";Object.defineProperty(Aj,"__esModule",{value:!0});Aj.setAutomine=FMe;async function FMe(e,t){e.mode==="ganache"?t?await e.request({method:"miner_start"}):await e.request({method:"miner_stop"}):await e.request({method:"evm_setAutomine",params:[t]})}});var OY=g(Ij=>{"use strict";Object.defineProperty(Ij,"__esModule",{value:!0});Ij.setBalance=$Me;var xY=W();async function $Me(e,{address:t,value:r}){e.mode==="ganache"?await e.request({method:"evm_setAccountBalance",params:[t,(0,xY.numberToHex)(r)]}):await e.request({method:`${e.mode}_setBalance`,params:[t,(0,xY.numberToHex)(r)]})}});var RY=g(Pj=>{"use strict";Object.defineProperty(Pj,"__esModule",{value:!0});Pj.setBlockGasLimit=VMe;var JMe=W();async function VMe(e,{gasLimit:t}){await e.request({method:"evm_setBlockGasLimit",params:[(0,JMe.numberToHex)(t)]})}});var CY=g(Tj=>{"use strict";Object.defineProperty(Tj,"__esModule",{value:!0});Tj.setBlockTimestampInterval=GMe;async function GMe(e,{interval:t}){let r=e.mode==="hardhat"?t*1e3:t;await e.request({method:`${e.mode}_setBlockTimestampInterval`,params:[r]})}});var NY=g(xj=>{"use strict";Object.defineProperty(xj,"__esModule",{value:!0});xj.setCode=KMe;async function KMe(e,{address:t,bytecode:r}){e.mode==="ganache"?await e.request({method:"evm_setAccountCode",params:[t,r]}):await e.request({method:`${e.mode}_setCode`,params:[t,r]})}});var kY=g(Oj=>{"use strict";Object.defineProperty(Oj,"__esModule",{value:!0});Oj.setCoinbase=WMe;async function WMe(e,{address:t}){await e.request({method:`${e.mode}_setCoinbase`,params:[t]})}});var jY=g(Rj=>{"use strict";Object.defineProperty(Rj,"__esModule",{value:!0});Rj.setIntervalMining=zMe;async function zMe(e,{interval:t}){let r=e.mode==="hardhat"?t*1e3:t;await e.request({method:"evm_setIntervalMining",params:[r]})}});var MY=g(Cj=>{"use strict";Object.defineProperty(Cj,"__esModule",{value:!0});Cj.setLoggingEnabled=YMe;async function YMe(e,t){await e.request({method:`${e.mode}_setLoggingEnabled`,params:[t]})}});var qY=g(Nj=>{"use strict";Object.defineProperty(Nj,"__esModule",{value:!0});Nj.setMinGasPrice=ZMe;var XMe=W();async function ZMe(e,{gasPrice:t}){await e.request({method:`${e.mode}_setMinGasPrice`,params:[(0,XMe.numberToHex)(t)]})}});var DY=g(kj=>{"use strict";Object.defineProperty(kj,"__esModule",{value:!0});kj.setNextBlockBaseFeePerGas=e8e;var QMe=W();async function e8e(e,{baseFeePerGas:t}){await e.request({method:`${e.mode}_setNextBlockBaseFeePerGas`,params:[(0,QMe.numberToHex)(t)]})}});var LY=g(jj=>{"use strict";Object.defineProperty(jj,"__esModule",{value:!0});jj.setNextBlockTimestamp=r8e;var t8e=W();async function r8e(e,{timestamp:t}){await e.request({method:"evm_setNextBlockTimestamp",params:[(0,t8e.numberToHex)(t)]})}});var BY=g(Mj=>{"use strict";Object.defineProperty(Mj,"__esModule",{value:!0});Mj.setNonce=i8e;var n8e=W();async function i8e(e,{address:t,nonce:r}){await e.request({method:`${e.mode}_setNonce`,params:[t,(0,n8e.numberToHex)(r)]})}});var UY=g(qj=>{"use strict";Object.defineProperty(qj,"__esModule",{value:!0});qj.setRpcUrl=o8e;async function o8e(e,t){await e.request({method:`${e.mode}_setRpcUrl`,params:[t]})}});var HY=g(Dj=>{"use strict";Object.defineProperty(Dj,"__esModule",{value:!0});Dj.setStorageAt=a8e;var s8e=W();async function a8e(e,{address:t,index:r,value:n}){await e.request({method:`${e.mode}_setStorageAt`,params:[t,typeof r=="number"?(0,s8e.numberToHex)(r):r,n]})}});var FY=g(Lj=>{"use strict";Object.defineProperty(Lj,"__esModule",{value:!0});Lj.snapshot=c8e;async function c8e(e){return await e.request({method:"evm_snapshot"})}});var $Y=g(Bj=>{"use strict";Object.defineProperty(Bj,"__esModule",{value:!0});Bj.stopImpersonatingAccount=u8e;async function u8e(e,{address:t}){await e.request({method:`${e.mode}_stopImpersonatingAccount`,params:[t]})}});var Hj=g(Uj=>{"use strict";Object.defineProperty(Uj,"__esModule",{value:!0});Uj.testActions=U8e;var d8e=fY(),l8e=pY(),f8e=mY(),p8e=gY(),m8e=yY(),g8e=_Y(),h8e=bY(),y8e=EY(),_8e=wY(),b8e=vY(),E8e=SY(),w8e=AY(),v8e=IY(),S8e=PY(),A8e=TY(),I8e=OY(),P8e=RY(),T8e=CY(),x8e=NY(),O8e=kY(),R8e=jY(),C8e=MY(),N8e=qY(),k8e=DY(),j8e=LY(),M8e=BY(),q8e=UY(),D8e=HY(),L8e=FY(),B8e=$Y();function U8e({mode:e}){return t=>{let r=t.extend(()=>({mode:e}));return{dropTransaction:n=>(0,d8e.dropTransaction)(r,n),dumpState:()=>(0,l8e.dumpState)(r),getAutomine:()=>(0,f8e.getAutomine)(r),getTxpoolContent:()=>(0,p8e.getTxpoolContent)(r),getTxpoolStatus:()=>(0,m8e.getTxpoolStatus)(r),impersonateAccount:n=>(0,g8e.impersonateAccount)(r,n),increaseTime:n=>(0,h8e.increaseTime)(r,n),inspectTxpool:()=>(0,y8e.inspectTxpool)(r),loadState:n=>(0,_8e.loadState)(r,n),mine:n=>(0,b8e.mine)(r,n),removeBlockTimestampInterval:()=>(0,E8e.removeBlockTimestampInterval)(r),reset:n=>(0,w8e.reset)(r,n),revert:n=>(0,v8e.revert)(r,n),sendUnsignedTransaction:n=>(0,S8e.sendUnsignedTransaction)(r,n),setAutomine:n=>(0,A8e.setAutomine)(r,n),setBalance:n=>(0,I8e.setBalance)(r,n),setBlockGasLimit:n=>(0,P8e.setBlockGasLimit)(r,n),setBlockTimestampInterval:n=>(0,T8e.setBlockTimestampInterval)(r,n),setCode:n=>(0,x8e.setCode)(r,n),setCoinbase:n=>(0,O8e.setCoinbase)(r,n),setIntervalMining:n=>(0,R8e.setIntervalMining)(r,n),setLoggingEnabled:n=>(0,C8e.setLoggingEnabled)(r,n),setMinGasPrice:n=>(0,N8e.setMinGasPrice)(r,n),setNextBlockBaseFeePerGas:n=>(0,k8e.setNextBlockBaseFeePerGas)(r,n),setNextBlockTimestamp:n=>(0,j8e.setNextBlockTimestamp)(r,n),setNonce:n=>(0,M8e.setNonce)(r,n),setRpcUrl:n=>(0,q8e.setRpcUrl)(r,n),setStorageAt:n=>(0,D8e.setStorageAt)(r,n),snapshot:()=>(0,L8e.snapshot)(r),stopImpersonatingAccount:n=>(0,B8e.stopImpersonatingAccount)(r,n)}}}});var JY=g(Fj=>{"use strict";Object.defineProperty(Fj,"__esModule",{value:!0});Fj.createTestClient=$8e;var H8e=Uu(),F8e=Hj();function $8e(e){let{key:t="test",name:r="Test Client",mode:n}=e;return(0,H8e.createClient)({...e,key:t,name:r,type:"testClient"}).extend(o=>({mode:n,...(0,F8e.testActions)({mode:n})(o)}))}});var VY=g($j=>{"use strict";Object.defineProperty($j,"__esModule",{value:!0});$j.addChain=V8e;var J8e=W();async function V8e(e,{chain:t}){let{id:r,name:n,nativeCurrency:i,rpcUrls:o,blockExplorers:s}=t;await e.request({method:"wallet_addEthereumChain",params:[{chainId:(0,J8e.numberToHex)(r),chainName:n,nativeCurrency:i,rpcUrls:o.default.http,blockExplorerUrls:s?Object.values(s).map(({url:a})=>a):void 0}]},{dedupe:!0,retryCount:0})}});var GY=g(Jj=>{"use strict";Object.defineProperty(Jj,"__esModule",{value:!0});Jj.deployContract=W8e;var G8e=Xl(),K8e=Eg();function W8e(e,t){let{abi:r,args:n,bytecode:i,...o}=t,s=(0,G8e.encodeDeployData)({abi:r,args:n,bytecode:i});return(0,K8e.sendTransaction)(e,{...o,...o.authorizationList?{to:null}:{},data:s})}});var KY=g(Vj=>{"use strict";Object.defineProperty(Vj,"__esModule",{value:!0});Vj.getAddresses=Y8e;var z8e=Ir();async function Y8e(e){return e.account?.type==="local"?[e.account.address]:(await e.request({method:"eth_accounts"},{dedupe:!0})).map(r=>(0,z8e.checksumAddress)(r))}});var WY=g(Gj=>{"use strict";Object.defineProperty(Gj,"__esModule",{value:!0});Gj.getCapabilities=Q8e;var X8e=at(),Z8e=W();async function Q8e(e,t={}){let{account:r=e.account,chainId:n}=t,i=r?(0,X8e.parseAccount)(r):void 0,o=n?[i?.address,[(0,Z8e.numberToHex)(n)]]:[i?.address],s=await e.request({method:"wallet_getCapabilities",params:o}),a={};for(let[c,u]of Object.entries(s)){a[Number(c)]={};for(let[d,l]of Object.entries(u))d==="addSubAccount"&&(d="unstable_addSubAccount"),a[Number(c)][d]=l}return typeof n=="number"?a[n]:a}});var zY=g(Kj=>{"use strict";Object.defineProperty(Kj,"__esModule",{value:!0});Kj.getPermissions=eqe;async function eqe(e){return await e.request({method:"wallet_getPermissions"},{dedupe:!0})}});var zj=g(Wj=>{"use strict";Object.defineProperty(Wj,"__esModule",{value:!0});Wj.prepareAuthorization=oqe;var YY=at(),tqe=yo(),rqe=ln(),XY=Te(),nqe=ps(),iqe=Zm();async function oqe(e,t){let{account:r=e.account,chainId:n,nonce:i}=t;if(!r)throw new tqe.AccountNotFoundError({docsPath:"/docs/eip7702/prepareAuthorization"});let o=(0,YY.parseAccount)(r),s=(()=>{if(t.executor)return t.executor==="self"?t.executor:(0,YY.parseAccount)(t.executor)})(),a={address:t.contractAddress??t.address,chainId:n,nonce:i};return typeof a.chainId>"u"&&(a.chainId=e.chain?.id??await(0,XY.getAction)(e,nqe.getChainId,"getChainId")({})),typeof a.nonce>"u"&&(a.nonce=await(0,XY.getAction)(e,iqe.getTransactionCount,"getTransactionCount")({address:o.address,blockTag:"pending"}),(s==="self"||s?.address&&(0,rqe.isAddressEqual)(s.address,o.address))&&(a.nonce+=1)),a}});var ZY=g(Yj=>{"use strict";Object.defineProperty(Yj,"__esModule",{value:!0});Yj.requestAddresses=aqe;var sqe=Ir();async function aqe(e){return(await e.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(r=>(0,sqe.getAddress)(r))}});var QY=g(Xj=>{"use strict";Object.defineProperty(Xj,"__esModule",{value:!0});Xj.requestPermissions=cqe;async function cqe(e,t){return e.request({method:"wallet_requestPermissions",params:[t]},{retryCount:0})}});var tX=g(Zj=>{"use strict";Object.defineProperty(Zj,"__esModule",{value:!0});Zj.sendCallsSync=lqe;var eX=Te(),uqe=EE(),dqe=SE();async function lqe(e,t){let{chain:r=e.chain}=t,n=t.timeout??Math.max((r?.blockTime??0)*3,5e3),i=await(0,eX.getAction)(e,uqe.sendCalls,"sendCalls")(t);return await(0,eX.getAction)(e,dqe.waitForCallsStatus,"waitForCallsStatus")({...t,id:i.id,timeout:n})}});var rX=g(Qj=>{"use strict";Object.defineProperty(Qj,"__esModule",{value:!0});Qj.showCallsStatus=fqe;async function fqe(e,t){let{id:r}=t;await e.request({method:"wallet_showCallsStatus",params:[r]})}});var iX=g(eM=>{"use strict";Object.defineProperty(eM,"__esModule",{value:!0});eM.signAuthorization=gqe;var pqe=at(),nX=yo(),mqe=zj();async function gqe(e,t){let{account:r=e.account}=t;if(!r)throw new nX.AccountNotFoundError({docsPath:"/docs/eip7702/signAuthorization"});let n=(0,pqe.parseAccount)(r);if(!n.signAuthorization)throw new nX.AccountTypeNotSupportedError({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});let i=await(0,mqe.prepareAuthorization)(e,t);return n.signAuthorization(i)}});var sX=g(tM=>{"use strict";Object.defineProperty(tM,"__esModule",{value:!0});tM.signMessage=_qe;var hqe=at(),yqe=yo(),oX=W();async function _qe(e,{account:t=e.account,message:r}){if(!t)throw new yqe.AccountNotFoundError({docsPath:"/docs/actions/wallet/signMessage"});let n=(0,hqe.parseAccount)(t);if(n.signMessage)return n.signMessage({message:r});let i=typeof r=="string"?(0,oX.stringToHex)(r):r.raw instanceof Uint8Array?(0,oX.toHex)(r.raw):r.raw;return e.request({method:"personal_sign",params:[i,n.address]},{retryCount:0})}});var aX=g(rM=>{"use strict";Object.defineProperty(rM,"__esModule",{value:!0});rM.signTransaction=Tqe;var bqe=at(),Eqe=yo(),wqe=tf(),vqe=W(),Sqe=Zn(),Aqe=Te(),Iqe=Qn(),Pqe=ps();async function Tqe(e,t){let{account:r=e.account,chain:n=e.chain,...i}=t;if(!r)throw new Eqe.AccountNotFoundError({docsPath:"/docs/actions/wallet/signTransaction"});let o=(0,bqe.parseAccount)(r);(0,Iqe.assertRequest)({account:o,...t});let s=await(0,Aqe.getAction)(e,Pqe.getChainId,"getChainId")({});n!==null&&(0,wqe.assertCurrentChain)({currentChainId:s,chain:n});let c=(n?.formatters||e.chain?.formatters)?.transactionRequest?.format||Sqe.formatTransactionRequest;return o.signTransaction?o.signTransaction({...i,account:o,chainId:s},{serializer:e.chain?.serializers?.transaction}):await e.request({method:"eth_signTransaction",params:[{...c({...i,account:o},"signTransaction"),chainId:(0,vqe.numberToHex)(s),from:o.address}]},{retryCount:0})}});var cX=g(iM=>{"use strict";Object.defineProperty(iM,"__esModule",{value:!0});iM.signTypedData=Rqe;var xqe=at(),Oqe=yo(),nM=Ug();async function Rqe(e,t){let{account:r=e.account,domain:n,message:i,primaryType:o}=t;if(!r)throw new Oqe.AccountNotFoundError({docsPath:"/docs/actions/wallet/signTypedData"});let s=(0,xqe.parseAccount)(r),a={EIP712Domain:(0,nM.getTypesForEIP712Domain)({domain:n}),...t.types};if((0,nM.validateTypedData)({domain:n,message:i,primaryType:o,types:a}),s.signTypedData)return s.signTypedData({domain:n,message:i,primaryType:o,types:a});let c=(0,nM.serializeTypedData)({domain:n,message:i,primaryType:o,types:a});return e.request({method:"eth_signTypedData_v4",params:[s.address,c]},{retryCount:0})}});var uX=g(oM=>{"use strict";Object.defineProperty(oM,"__esModule",{value:!0});oM.switchChain=Nqe;var Cqe=W();async function Nqe(e,{id:t}){await e.request({method:"wallet_switchEthereumChain",params:[{chainId:(0,Cqe.numberToHex)(t)}]},{retryCount:0})}});var dX=g(sM=>{"use strict";Object.defineProperty(sM,"__esModule",{value:!0});sM.watchAsset=kqe;async function kqe(e,t){return await e.request({method:"wallet_watchAsset",params:t},{retryCount:0})}});var cM=g(aM=>{"use strict";Object.defineProperty(aM,"__esModule",{value:!0});aM.walletActions=cDe;var jqe=Gb(),Mqe=ps(),iv=oj(),qqe=VY(),Dqe=GY(),Lqe=KY(),Bqe=eR(),Uqe=WY(),Hqe=zY(),Fqe=zj(),$qe=Fl(),Jqe=ZY(),Vqe=QY(),Gqe=EE(),Kqe=tX(),Wqe=pE(),zqe=H1(),Yqe=Eg(),Xqe=Yk(),Zqe=rX(),Qqe=iX(),eDe=sX(),tDe=aX(),rDe=cX(),nDe=uX(),iDe=SE(),oDe=dX(),sDe=rf(),aDe=J1(),ov=Uu();function cDe(e){return{addChain:t=>(0,qqe.addChain)(e,t),deployContract:t=>(0,Dqe.deployContract)(e,t),fillTransaction:t=>(0,jqe.fillTransaction)(e,t),getAddresses:()=>(0,Lqe.getAddresses)(e),getCallsStatus:t=>(0,Bqe.getCallsStatus)(e,t),getCapabilities:t=>(0,Uqe.getCapabilities)(e,t),getChainId:()=>(0,Mqe.getChainId)(e),getPermissions:()=>(0,Hqe.getPermissions)(e),prepareAuthorization:t=>(0,Fqe.prepareAuthorization)(e,t),prepareTransactionRequest:t=>(0,$qe.prepareTransactionRequest)(e,t),requestAddresses:()=>(0,Jqe.requestAddresses)(e),requestPermissions:t=>(0,Vqe.requestPermissions)(e,t),sendCalls:t=>(0,Gqe.sendCalls)(e,t),sendCallsSync:t=>(0,Kqe.sendCallsSync)(e,t),sendRawTransaction:t=>(0,Wqe.sendRawTransaction)(e,t),sendRawTransactionSync:t=>(0,zqe.sendRawTransactionSync)(e,t),sendTransaction:t=>(0,Yqe.sendTransaction)(e,t),sendTransactionSync:t=>(0,Xqe.sendTransactionSync)(e,t),showCallsStatus:t=>(0,Zqe.showCallsStatus)(e,t),signAuthorization:t=>(0,Qqe.signAuthorization)(e,t),signMessage:t=>(0,eDe.signMessage)(e,t),signTransaction:t=>(0,tDe.signTransaction)(e,t),signTypedData:t=>(0,rDe.signTypedData)(e,t),switchChain:t=>(0,nDe.switchChain)(e,t),waitForCallsStatus:t=>(0,iDe.waitForCallsStatus)(e,t),watchAsset:t=>(0,oDe.watchAsset)(e,t),writeContract:t=>(0,sDe.writeContract)(e,t),writeContractSync:t=>(0,aDe.writeContractSync)(e,t),token:{approve:(0,ov.bindActionDecorators)(e,iv.approve),approveSync:(0,ov.bindActionDecorators)(e,iv.approveSync),transfer:(0,ov.bindActionDecorators)(e,iv.transfer),transferSync:(0,ov.bindActionDecorators)(e,iv.transferSync)}}}});var lX=g(uM=>{"use strict";Object.defineProperty(uM,"__esModule",{value:!0});uM.createWalletClient=lDe;var uDe=Uu(),dDe=cM();function lDe(e){let{key:t="wallet",name:r="Wallet Client",transport:n}=e;return(0,uDe.createClient)({...e,key:t,name:r,transport:n,type:"walletClient"}).extend(dDe.walletActions)}});var $f=g(dM=>{"use strict";Object.defineProperty(dM,"__esModule",{value:!0});dM.createTransport=mDe;var fDe=cC(),pDe=nR();function mDe({key:e,methods:t,name:r,request:n,retryCount:i=3,retryDelay:o=150,timeout:s,type:a},c){let u=(0,pDe.uid)();return{config:{key:e,methods:t,name:r,request:n,retryCount:i,retryDelay:o,timeout:s,type:a},request:(0,fDe.buildRequest)(n,{methods:t,retryCount:i,retryDelay:o,uid:u}),value:c}}});var fX=g(lM=>{"use strict";Object.defineProperty(lM,"__esModule",{value:!0});lM.custom=hDe;var gDe=$f();function hDe(e,t={}){let{key:r="custom",methods:n,name:i="Custom Provider",retryDelay:o}=t;return({retryCount:s})=>(0,gDe.createTransport)({key:r,methods:n,name:i,request:e.request.bind(e),retryCount:t.retryCount??s,retryDelay:o,type:"custom"})}});var gX=g(Rh=>{"use strict";Object.defineProperty(Rh,"__esModule",{value:!0});Rh.fallback=EDe;Rh.shouldThrow=pX;Rh.rankTransports=mX;var yDe=Ti(),fM=ss(),_De=lE(),bDe=$f();function EDe(e,t={}){let{key:r="fallback",name:n="Fallback",rank:i=!1,shouldThrow:o=pX,retryCount:s,retryDelay:a}=t;return(({chain:c,pollingInterval:u=4e3,timeout:d,...l})=>{let m=e,p=()=>{},h=(0,bDe.createTransport)({key:r,name:n,async request({method:y,params:b}){let v,A=async(E=0)=>{let S=m[E]({...l,chain:c,retryCount:0,timeout:d});try{let I=await S.request({method:y,params:b});return p({method:y,params:b,response:I,transport:S,status:"success"}),I}catch(I){if(p({error:I,method:y,params:b,transport:S,status:"error"}),o(I)||E===m.length-1||(v??=m.slice(E+1).some(T=>{let{include:x,exclude:C}=T({chain:c}).config.methods||{};return x?x.includes(y):C?!C.includes(y):!0}),!v))throw I;return A(E+1)}};return A()},retryCount:s,retryDelay:a,type:"fallback"},{onResponse:y=>p=y,transports:m.map(y=>y({chain:c,retryCount:0}))});if(i){let y=typeof i=="object"?i:{};mX({chain:c,interval:y.interval??u,onTransports:b=>m=b,ping:y.ping,sampleCount:y.sampleCount,timeout:y.timeout,transports:m,weights:y.weights})}return h})}function pX(e){return!!("code"in e&&typeof e.code=="number"&&(e.code===fM.TransactionRejectedRpcError.code||e.code===fM.UserRejectedRequestError.code||e.code===fM.WalletConnectSessionSettlementError.code||yDe.ExecutionRevertedError.nodeMessage.test(e.message)||e.code===5e3))}function mX({chain:e,interval:t=4e3,onTransports:r,ping:n,sampleCount:i=10,timeout:o=1e3,transports:s,weights:a={}}){let{stability:c=.7,latency:u=.3}=a,d=[],l=async()=>{let m=await Promise.all(s.map(async y=>{let b=y({chain:e,retryCount:0,timeout:o}),v=Date.now(),A,E;try{await(n?n({transport:b}):b.request({method:"net_listening"})),E=1}catch{E=0}finally{A=Date.now()}return{latency:A-v,success:E}}));d.push(m),d.length>i&&d.shift();let p=Math.max(...d.map(y=>Math.max(...y.map(({latency:b})=>b)))),h=s.map((y,b)=>{let v=d.map(T=>T[b].latency),E=1-v.reduce((T,x)=>T+x,0)/v.length/p,S=d.map(T=>T[b].success),I=S.reduce((T,x)=>T+x,0)/S.length;return I===0?[0,b]:[u*E+c*I,b]}).sort((y,b)=>b[0]-y[0]);r(h.map(([,y])=>s[y])),await(0,_De.wait)(t),l()};l()}});var av=g(sv=>{"use strict";Object.defineProperty(sv,"__esModule",{value:!0});sv.UrlRequiredError=void 0;var wDe=ye(),pM=class extends wDe.BaseError{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}};sv.UrlRequiredError=pM});var yX=g(mM=>{"use strict";Object.defineProperty(mM,"__esModule",{value:!0});mM.http=ODe;var vDe=Nn(),SDe=av(),ADe=pg(),IDe=aw(),PDe=$f(),TDe=0,hX=new WeakMap;function xDe(e){if(!e)return"default";let t=hX.get(e);if(t!==void 0)return t;let r=TDe++;return hX.set(e,r),r}function ODe(e,t={}){let{batch:r,fetchFn:n,fetchOptions:i,key:o="http",maxResponseBodySize:s,methods:a,name:c="HTTP JSON-RPC",onFetchRequest:u,onFetchResponse:d,retryDelay:l,raw:m}=t;return({chain:p,retryCount:h,timeout:y})=>{let{batchSize:b=1e3,wait:v=0}=typeof r=="object"?r:{},A=t.retryCount??h,E=y??t.timeout??1e4,S=e||p?.rpcUrls.default.http[0];if(!S)throw new SDe.UrlRequiredError;let I=(0,IDe.getHttpRpcClient)(S,{fetchFn:n,fetchOptions:i,maxResponseBodySize:s,onRequest:u,onResponse:d,timeout:E});return(0,PDe.createTransport)({key:o,methods:a,name:c,async request({method:T,params:x},C){let k={method:T,params:x},N=C?.signal?{signal:C.signal}:void 0,{schedule:M}=(0,ADe.createBatchScheduler)({id:`${S}.${xDe(C?.signal)}`,wait:v,shouldSplitBatch(q){return q.length>b},fn:q=>I.request({body:q,fetchOptions:N}),sort:(q,L)=>q.id-L.id}),j=async q=>r?M(q):[await I.request({body:q,fetchOptions:N})],[{error:D,result:U}]=await j(k);if(m)return{error:D,result:U};if(D)throw new vDe.RpcRequestError({body:k,error:D,url:S});return U},retryCount:A,retryDelay:l,timeout:E,type:"http"},{fetchOptions:i,url:S})}}});var _X=g(hM=>{"use strict";Object.defineProperty(hM,"__esModule",{value:!0});hM.webSocket=jDe;var RDe=Nn(),CDe=av(),NDe=tN(),gM=Iw(),kDe=$f();function jDe(e,t={}){let{keepAlive:r,key:n="webSocket",methods:i,name:o="WebSocket JSON-RPC",reconnect:s,retryDelay:a}=t;return({chain:c,retryCount:u,timeout:d})=>{let l=t.retryCount??u,m=d??t.timeout??1e4,p=e||c?.rpcUrls.default.webSocket?.[0],h={keepAlive:r,reconnect:s};if(!p)throw new CDe.UrlRequiredError;return(0,kDe.createTransport)({key:n,methods:i,name:o,async request({method:y,params:b}){let v={method:y,params:b},A=await(0,gM.getWebSocketRpcClient)(p,h),{error:E,result:S}=await A.requestAsync({body:v,timeout:m});if(E)throw new RDe.RpcRequestError({body:v,error:E,url:p});return S},retryCount:l,retryDelay:a,timeout:m,type:"webSocket"},{getSocket(){return(0,NDe.getSocket)(p)},getRpcClient(){return(0,gM.getWebSocketRpcClient)(p,h)},async subscribe({params:y,onData:b,onError:v}){let A=await(0,gM.getWebSocketRpcClient)(p,h),{result:E}=await new Promise((S,I)=>A.request({body:{method:"eth_subscribe",params:y},onError(T){I(T),v?.(T)},onResponse(T){if(T.error){I(T.error),v?.(T.error);return}if(typeof T.id=="number"){S(T);return}T.method==="eth_subscription"&&b(T.params)}}));return{subscriptionId:E,async unsubscribe(){return new Promise(S=>A.request({body:{method:"eth_unsubscribe",params:[E]},onResponse:S}))}}}})}}});var bX=g(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.weiUnits=uc.gweiUnits=uc.etherUnits=void 0;uc.etherUnits={gwei:9,wei:18};uc.gweiUnits={ether:-9,wei:9};uc.weiUnits={ether:-18,gwei:-9}});var EX=g(cv=>{"use strict";Object.defineProperty(cv,"__esModule",{value:!0});cv.InvalidDecimalNumberError=void 0;var MDe=ye(),yM=class extends MDe.BaseError{constructor({value:t}){super(`Number \`${t}\` is not a valid decimal number.`,{name:"InvalidDecimalNumberError"})}};cv.InvalidDecimalNumberError=yM});var wX=g(uv=>{"use strict";Object.defineProperty(uv,"__esModule",{value:!0});uv.ProviderRpcError=void 0;var _M=class extends Error{constructor(t,r){super(r),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=t,this.details=r}};uv.ProviderRpcError=_M});var vX=g(wM=>{"use strict";Object.defineProperty(wM,"__esModule",{value:!0});wM.decodeDeployData=DDe;var bM=ft(),qDe=os(),EM="/docs/contract/decodeDeployData";function DDe(e){let{abi:t,bytecode:r,data:n}=e;if(n===r)return{bytecode:r};let i=t.find(s=>"type"in s&&s.type==="constructor");if(!i)throw new bM.AbiConstructorNotFoundError({docsPath:EM});if(!("inputs"in i))throw new bM.AbiConstructorParamsNotFoundError({docsPath:EM});if(!i.inputs||i.inputs.length===0)throw new bM.AbiConstructorParamsNotFoundError({docsPath:EM});return{args:(0,qDe.decodeAbiParameters)(i.inputs,`0x${n.replace(r,"")}`),bytecode:r}}});var AX=g(vM=>{"use strict";Object.defineProperty(vM,"__esModule",{value:!0});vM.fromBlobs=UDe;var SX=Pl(),LDe=Je(),BDe=W();function UDe(e){let t=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),r=typeof e.blobs[0]=="string"?e.blobs.map(a=>(0,LDe.hexToBytes)(a)):e.blobs,n=r.reduce((a,c)=>a+c.length,0),i=(0,SX.createCursor)(new Uint8Array(n)),o=!0;for(let[a,c]of r.entries()){let u=(0,SX.createCursor)(c),d=a===r.length-1;for(;o&&u.position<c.length;){u.incrementPosition(1);let l=31;c.length-u.position<31&&(l=c.length-u.position);for(let m in Array.from({length:l})){let p=u.readByte();if(d&&p===128&&!u.inspectBytes(u.remaining).includes(128)){o=!1;break}i.pushByte(p)}}}let s=i.bytes.slice(0,i.position);return t==="hex"?(0,BDe.bytesToHex)(s):s}});var IX=g(SM=>{"use strict";Object.defineProperty(SM,"__esModule",{value:!0});SM.sidecarsToVersionedHashes=FDe;var HDe=Fb();function FDe(e){let{sidecars:t,version:r}=e,n=e.to??(typeof t[0].blob=="string"?"hex":"bytes"),i=[];for(let{commitment:o}of t)i.push((0,HDe.commitmentToVersionedHash)({commitment:o,to:n,version:r}));return i}});var PX=g(AM=>{"use strict";Object.defineProperty(AM,"__esModule",{value:!0});AM.toCoinType=VDe;var $De=OE(),JDe=2147483648;function VDe(e){if(e===1)return 60n;if(e>=JDe||e<0)throw new $De.EnsInvalidChainIdError({chainId:e});return BigInt((2147483648|e)>>>0)}});var PM=g(IM=>{"use strict";Object.defineProperty(IM,"__esModule",{value:!0});IM.defineKzg=GDe;function GDe({blobToKzgCommitment:e,computeBlobKzgProof:t}){return{blobToKzgCommitment:e,computeBlobKzgProof:t}}});var TX=g(TM=>{"use strict";Object.defineProperty(TM,"__esModule",{value:!0});TM.setupKzg=WDe;var KDe=PM();function WDe(e,t){try{e.loadTrustedSetup(t)}catch(r){let n=r;if(!n.message.includes("trusted setup is already loaded"))throw n}return(0,KDe.defineKzg)(e)}});var xX=g(xM=>{"use strict";Object.defineProperty(xM,"__esModule",{value:!0});xM.compactSignatureToSignature=XDe;var zDe=Je(),YDe=W();function XDe({r:e,yParityAndS:t}){let r=(0,zDe.hexToBytes)(t),n=r[0]&128?1:0,i=r;return n===1&&(i[0]&=127),{r:e,s:(0,YDe.bytesToHex)(i),yParity:n}}});var RX=g(OM=>{"use strict";Object.defineProperty(OM,"__esModule",{value:!0});OM.parseCompactSignature=QDe;var ZDe=Ga(),OX=W();function QDe(e){let{r:t,s:r}=ZDe.secp256k1.Signature.fromCompact(e.slice(2,130));return{r:(0,OX.numberToHex)(t,{size:32}),yParityAndS:(0,OX.numberToHex)(r,{size:32})}}});var CX=g(RM=>{"use strict";Object.defineProperty(RM,"__esModule",{value:!0});RM.parseSignature=t4e;var e4e=Ga(),dv=W();function t4e(e){let{r:t,s:r}=e4e.secp256k1.Signature.fromCompact(e.slice(2,130)),n=+`0x${e.slice(130)}`,[i,o]=(()=>{if(n===0||n===1)return[void 0,n];if(n===27)return[BigInt(n),0];if(n===28)return[BigInt(n),1];throw new Error("Invalid yParityOrV value")})();return typeof i<"u"?{r:(0,dv.numberToHex)(t,{size:32}),s:(0,dv.numberToHex)(r,{size:32}),v:i,yParity:o}:{r:(0,dv.numberToHex)(t,{size:32}),s:(0,dv.numberToHex)(r,{size:32}),yParity:o}}});var NX=g(CM=>{"use strict";Object.defineProperty(CM,"__esModule",{value:!0});CM.recoverTransactionAddress=s4e;var r4e=Hr(),n4e=b1(),i4e=Cg(),o4e=ds();async function s4e(e){let{serializedTransaction:t,signature:r}=e,n=(0,n4e.parseTransaction)(t),i=r??{r:n.r,s:n.s,v:n.v,yParity:n.yParity},o=(0,i4e.serializeTransaction)({...n,r:void 0,s:void 0,v:void 0,yParity:void 0,sidecars:void 0});return await(0,o4e.recoverAddress)({hash:(0,r4e.keccak256)(o),signature:i})}});var jX=g(NM=>{"use strict";Object.defineProperty(NM,"__esModule",{value:!0});NM.serializeCompactSignature=c4e;var a4e=Ga(),kX=pt();function c4e({r:e,yParityAndS:t}){return`0x${new a4e.secp256k1.Signature((0,kX.hexToBigInt)(e),(0,kX.hexToBigInt)(t)).toCompactHex()}`}});var MX=g(kM=>{"use strict";Object.defineProperty(kM,"__esModule",{value:!0});kM.signatureToCompactSignature=l4e;var u4e=Je(),d4e=W();function l4e(e){let{r:t,s:r,v:n,yParity:i}=e,o=Number(i??n-27n),s=r;if(o===1){let a=(0,u4e.hexToBytes)(r);a[0]|=128,s=(0,d4e.bytesToHex)(a)}return{r:t,yParityAndS:s}}});var gv=g(f=>{"use strict";Object.defineProperty(f,"__esModule",{value:!0});f.maxInt8=f.universalSignatureValidatorByteCode=f.erc6492SignatureValidatorByteCode=f.deploylessCallViaFactoryBytecode=f.deploylessCallViaBytecodeBytecode=f.zeroHash=f.zeroAddress=f.ethAddress=f.multicall3Abi=f.universalSignatureValidatorAbi=f.erc6492SignatureValidatorAbi=f.erc4626Abi=f.erc1155Abi=f.erc721Abi=f.erc20Abi_bytes32=f.erc20Abi=f.webSocket=f.http=f.shouldThrow=f.fallback=f.custom=f.createTransport=f.walletActions=f.testActions=f.publicActions=f.createWalletClient=f.createTestClient=f.createPublicClient=f.rpcSchema=f.createClient=f.WaitForCallsStatusTimeoutError=f.getContract=f.UnknownTypeError=f.UnknownSignatureError=f.SolidityProtectedKeywordError=f.parseAbiParameters=f.parseAbiParameter=f.parseAbiItem=f.parseAbi=f.InvalidStructSignatureError=f.InvalidSignatureError=f.InvalidParenthesisError=f.InvalidParameterError=f.InvalidModifierError=f.InvalidFunctionModifierError=f.InvalidAbiTypeParameterError=f.InvalidAbiParametersError=f.InvalidAbiParameterError=f.InvalidAbiItemError=f.CircularReferenceError=void 0;f.maxUint152=f.maxUint144=f.maxUint136=f.maxUint128=f.maxUint120=f.maxUint112=f.maxUint104=f.maxUint96=f.maxUint88=f.maxUint80=f.maxUint72=f.maxUint64=f.maxUint56=f.maxUint48=f.maxUint40=f.maxUint32=f.maxUint24=f.maxUint16=f.maxUint8=f.maxInt256=f.maxInt248=f.maxInt240=f.maxInt232=f.maxInt224=f.maxInt216=f.maxInt208=f.maxInt200=f.maxInt192=f.maxInt184=f.maxInt176=f.maxInt168=f.maxInt160=f.maxInt152=f.maxInt144=f.maxInt136=f.maxInt128=f.maxInt120=f.maxInt112=f.maxInt104=f.maxInt96=f.maxInt88=f.maxInt80=f.maxInt72=f.maxInt64=f.maxInt56=f.maxInt48=f.maxInt40=f.maxInt32=f.maxInt24=f.maxInt16=void 0;f.AbiConstructorNotFoundError=f.weiUnits=f.gweiUnits=f.etherUnits=f.presignMessagePrefix=f.minInt256=f.minInt248=f.minInt240=f.minInt232=f.minInt224=f.minInt216=f.minInt208=f.minInt200=f.minInt192=f.minInt184=f.minInt176=f.minInt168=f.minInt160=f.minInt152=f.minInt144=f.minInt136=f.minInt128=f.minInt120=f.minInt112=f.minInt104=f.minInt96=f.minInt88=f.minInt80=f.minInt72=f.minInt64=f.minInt56=f.minInt48=f.minInt40=f.minInt32=f.minInt24=f.minInt16=f.minInt8=f.maxUint256=f.maxUint248=f.maxUint240=f.maxUint232=f.maxUint224=f.maxUint216=f.maxUint208=f.maxUint200=f.maxUint192=f.maxUint184=f.maxUint176=f.maxUint168=f.maxUint160=void 0;f.SizeOverflowError=f.RlpTrailingBytesError=f.RlpListBoundaryExceededError=f.RlpDepthLimitExceededError=f.InvalidHexValueError=f.InvalidHexBooleanError=f.InvalidBytesBooleanError=f.IntegerOutOfRangeError=f.SliceOffsetOutOfBoundsError=f.SizeExceedsPaddingSizeError=f.RawContractError=f.CounterfactualDeploymentFailedError=f.ContractFunctionZeroDataError=f.ContractFunctionRevertedError=f.ContractFunctionExecutionError=f.CallExecutionError=f.InvalidChainIdError=f.ClientChainNotConfiguredError=f.ChainNotFoundError=f.ChainMismatchError=f.ChainDoesNotSupportContract=f.BundleFailedError=f.BlockNotFoundError=f.setErrorConfig=f.BaseError=f.InvalidAddressError=f.UnsupportedPackedAbiType=f.InvalidDefinitionTypeError=f.InvalidArrayError=f.InvalidAbiEncodingTypeError=f.InvalidAbiDecodingTypeError=f.DecodeLogTopicsMismatch=f.DecodeLogDataMismatch=f.BytesSizeMismatchError=f.AbiFunctionSignatureNotFoundError=f.AbiFunctionOutputsNotFoundError=f.AbiFunctionNotFoundError=f.AbiEventSignatureNotFoundError=f.AbiEventSignatureEmptyTopicsError=f.AbiEventNotFoundError=f.AbiErrorSignatureNotFoundError=f.AbiErrorNotFoundError=f.AbiErrorInputsNotFoundError=f.AbiEncodingLengthMismatchError=f.AbiEncodingBytesSizeMismatchError=f.AbiEncodingArrayLengthMismatchError=f.AbiDecodingZeroDataError=f.AbiDecodingDataSizeTooSmallError=f.AbiDecodingDataSizeInvalidError=f.AbiConstructorParamsNotFoundError=void 0;f.UnknownBundleIdError=f.UnauthorizedProviderError=f.TransactionRejectedRpcError=f.SwitchChainError=f.RpcError=f.ResourceUnavailableRpcError=f.ResourceNotFoundRpcError=f.ProviderRpcError=f.ProviderDisconnectedError=f.ParseRpcError=f.MethodNotSupportedRpcError=f.MethodNotFoundRpcError=f.LimitExceededRpcError=f.JsonRpcVersionUnsupportedError=f.InvalidRequestRpcError=f.InvalidParamsRpcError=f.InvalidInputRpcError=f.InternalRpcError=f.DuplicateIdError=f.ChainDisconnectedError=f.BundleTooLargeError=f.AtomicReadyWalletRejectedUpgradeError=f.AtomicityNotSupportedError=f.WebSocketRequestError=f.TimeoutError=f.SocketClosedError=f.RpcRequestError=f.ResponseBodyTooLargeError=f.HttpRequestError=f.UnknownNodeError=f.TransactionTypeNotSupportedError=f.TipAboveFeeCapError=f.NonceTooLowError=f.NonceTooHighError=f.NonceMaxValueError=f.IntrinsicGasTooLowError=f.IntrinsicGasTooHighError=f.InsufficientFundsError=f.FeeCapTooLowError=f.FeeCapTooHighError=f.ExecutionRevertedError=f.FilterTypeNotSupportedError=f.MaxFeePerGasTooLowError=f.Eip1559FeesNotSupportedError=f.BaseFeeScalarError=f.EstimateGasExecutionError=f.EnsInvalidChainIdError=f.EnsAvatarUriResolutionError=f.EnsAvatarUnsupportedNamespaceError=f.EnsAvatarInvalidNftUriError=void 0;f.blobsToCommitments=f.isAddressEqual=f.isAddress=f.getCreateAddress=f.getCreate2Address=f.getContractAddress=f.getAddress=f.checksumAddress=f.prepareEncodeFunctionData=f.parseEventLogs=f.getAbiItem=f.encodePacked=f.encodeFunctionResult=f.encodeFunctionData=f.encodeEventTopics=f.encodeErrorResult=f.encodeDeployData=f.encodeAbiParameters=f.decodeFunctionResult=f.decodeFunctionData=f.decodeEventLog=f.decodeErrorResult=f.decodeDeployData=f.decodeAbiParameters=f.EIP1193ProviderRpcError=f.InvalidDecimalNumberError=f.InvalidTypedDataTypeError=f.InvalidStructTypeError=f.InvalidPrimaryTypeError=f.InvalidDomainError=f.UrlRequiredError=f.WaitForTransactionReceiptTimeoutError=f.TransactionReceiptNotFoundError=f.TransactionNotFoundError=f.TransactionExecutionError=f.InvalidYParityError=f.InvalidStorageKeySizeError=f.InvalidSerializedTransactionTypeError=f.InvalidSerializedTransactionError=f.InvalidSerializableTransactionError=f.InvalidLegacyVError=f.FeePayerNonceMismatchError=f.FeeConflictError=f.StateAssignmentConflictError=f.AccountStateConflictError=f.UserRejectedRequestError=f.UnsupportedProviderMethodError=f.UnsupportedNonOptionalCapabilityError=f.UnsupportedChainIdError=f.UnknownRpcError=void 0;f.numberToHex=f.bytesToHex=f.boolToHex=f.toBytes=f.stringToBytes=f.numberToBytes=f.hexToBytes=f.boolToBytes=f.fromRlp=f.hexToString=f.hexToNumber=f.hexToBool=f.hexToBigInt=f.fromHex=f.fromBytes=f.bytesToString=f.bytesToNumber=f.bytesToBool=f.bytesToBigInt=f.trim=f.sliceHex=f.sliceBytes=f.slice=f.size=f.padHex=f.padBytes=f.pad=f.isHex=f.isBytes=f.concatHex=f.concatBytes=f.concat=f.getChainContractAddress=f.extractChain=f.extendSchema=f.defineChain=f.assertCurrentChain=f.ccipReadTunnel=f.offchainLookupSignature=f.offchainLookupAbiItem=f.offchainLookup=f.ccipFetch=f.ccipRequest=f.toBlobs=f.toBlobSidecars=f.sidecarsToVersionedHashes=f.fromBlobs=f.commitmentToVersionedHash=f.commitmentsToVersionedHashes=f.blobsToProofs=void 0;f.parseCompactSignature=f.hexToCompactSignature=f.isErc8010Signature=f.isErc6492Signature=f.hashTypedData=f.hashStruct=f.hashDomain=f.hashMessage=f.compactSignatureToSignature=f.withTimeout=f.withRetry=f.withCache=f.nonceManager=f.createNonceManager=f.setupKzg=f.defineKzg=f.getFunctionSignature=f.toFunctionSignature=f.getFunctionSelector=f.toFunctionSelector=f.toFunctionHash=f.getEventSignature=f.toEventSignature=f.getEventSelector=f.toEventSelector=f.toEventHash=f.sha256=f.ripemd160=f.keccak256=f.isHash=f.rpcTransactionType=f.formatTransactionRequest=f.defineTransactionRequest=f.formatTransactionReceipt=f.defineTransactionReceipt=f.transactionType=f.formatTransaction=f.defineTransaction=f.formatLog=f.formatBlock=f.defineBlock=f.getContractError=f.toCoinType=f.namehash=f.labelhash=f.toRlp=f.hexToRlp=f.bytesToRlp=f.toHex=f.stringToHex=void 0;f.parseUnits=f.parseGwei=f.parseEther=f.formatUnits=f.formatGwei=f.formatEther=f.validateTypedData=f.serializeTypedData=f.getTypesForEIP712Domain=f.domainSeparator=f.serializeTransaction=f.serializeAccessList=f.parseTransaction=f.getTransactionType=f.getSerializedTransactionType=f.assertTransactionLegacy=f.assertTransactionEIP2930=f.assertTransactionEIP1559=f.assertRequest=f.stringify=f.verifyTypedData=f.verifyMessage=f.verifyHash=f.toPrefixedMessage=f.signatureToCompactSignature=f.serializeSignature=f.signatureToHex=f.serializeErc8010Signature=f.serializeErc6492Signature=f.serializeCompactSignature=f.compactSignatureToHex=f.recoverTypedDataAddress=f.recoverTransactionAddress=f.recoverPublicKey=f.recoverMessageAddress=f.recoverAddress=f.parseSignature=f.hexToSignature=f.parseErc8010Signature=f.parseErc6492Signature=void 0;var nr=_m();Object.defineProperty(f,"CircularReferenceError",{enumerable:!0,get:function(){return nr.CircularReferenceError}});Object.defineProperty(f,"InvalidAbiItemError",{enumerable:!0,get:function(){return nr.InvalidAbiItemError}});Object.defineProperty(f,"InvalidAbiParameterError",{enumerable:!0,get:function(){return nr.InvalidAbiParameterError}});Object.defineProperty(f,"InvalidAbiParametersError",{enumerable:!0,get:function(){return nr.InvalidAbiParametersError}});Object.defineProperty(f,"InvalidAbiTypeParameterError",{enumerable:!0,get:function(){return nr.InvalidAbiTypeParameterError}});Object.defineProperty(f,"InvalidFunctionModifierError",{enumerable:!0,get:function(){return nr.InvalidFunctionModifierError}});Object.defineProperty(f,"InvalidModifierError",{enumerable:!0,get:function(){return nr.InvalidModifierError}});Object.defineProperty(f,"InvalidParameterError",{enumerable:!0,get:function(){return nr.InvalidParameterError}});Object.defineProperty(f,"InvalidParenthesisError",{enumerable:!0,get:function(){return nr.InvalidParenthesisError}});Object.defineProperty(f,"InvalidSignatureError",{enumerable:!0,get:function(){return nr.InvalidSignatureError}});Object.defineProperty(f,"InvalidStructSignatureError",{enumerable:!0,get:function(){return nr.InvalidStructSignatureError}});Object.defineProperty(f,"parseAbi",{enumerable:!0,get:function(){return nr.parseAbi}});Object.defineProperty(f,"parseAbiItem",{enumerable:!0,get:function(){return nr.parseAbiItem}});Object.defineProperty(f,"parseAbiParameter",{enumerable:!0,get:function(){return nr.parseAbiParameter}});Object.defineProperty(f,"parseAbiParameters",{enumerable:!0,get:function(){return nr.parseAbiParameters}});Object.defineProperty(f,"SolidityProtectedKeywordError",{enumerable:!0,get:function(){return nr.SolidityProtectedKeywordError}});Object.defineProperty(f,"UnknownSignatureError",{enumerable:!0,get:function(){return nr.UnknownSignatureError}});Object.defineProperty(f,"UnknownTypeError",{enumerable:!0,get:function(){return nr.UnknownTypeError}});var f4e=QJ();Object.defineProperty(f,"getContract",{enumerable:!0,get:function(){return f4e.getContract}});var p4e=SE();Object.defineProperty(f,"WaitForCallsStatusTimeoutError",{enumerable:!0,get:function(){return p4e.WaitForCallsStatusTimeoutError}});var qX=Uu();Object.defineProperty(f,"createClient",{enumerable:!0,get:function(){return qX.createClient}});Object.defineProperty(f,"rpcSchema",{enumerable:!0,get:function(){return qX.rpcSchema}});var m4e=lY();Object.defineProperty(f,"createPublicClient",{enumerable:!0,get:function(){return m4e.createPublicClient}});var g4e=JY();Object.defineProperty(f,"createTestClient",{enumerable:!0,get:function(){return g4e.createTestClient}});var h4e=lX();Object.defineProperty(f,"createWalletClient",{enumerable:!0,get:function(){return h4e.createWalletClient}});var y4e=aj();Object.defineProperty(f,"publicActions",{enumerable:!0,get:function(){return y4e.publicActions}});var _4e=Hj();Object.defineProperty(f,"testActions",{enumerable:!0,get:function(){return _4e.testActions}});var b4e=cM();Object.defineProperty(f,"walletActions",{enumerable:!0,get:function(){return b4e.walletActions}});var E4e=$f();Object.defineProperty(f,"createTransport",{enumerable:!0,get:function(){return E4e.createTransport}});var w4e=fX();Object.defineProperty(f,"custom",{enumerable:!0,get:function(){return w4e.custom}});var DX=gX();Object.defineProperty(f,"fallback",{enumerable:!0,get:function(){return DX.fallback}});Object.defineProperty(f,"shouldThrow",{enumerable:!0,get:function(){return DX.shouldThrow}});var v4e=yX();Object.defineProperty(f,"http",{enumerable:!0,get:function(){return v4e.http}});var S4e=_X();Object.defineProperty(f,"webSocket",{enumerable:!0,get:function(){return S4e.webSocket}});var dc=er();Object.defineProperty(f,"erc20Abi",{enumerable:!0,get:function(){return dc.erc20Abi}});Object.defineProperty(f,"erc20Abi_bytes32",{enumerable:!0,get:function(){return dc.erc20Abi_bytes32}});Object.defineProperty(f,"erc721Abi",{enumerable:!0,get:function(){return dc.erc721Abi}});Object.defineProperty(f,"erc1155Abi",{enumerable:!0,get:function(){return dc.erc1155Abi}});Object.defineProperty(f,"erc4626Abi",{enumerable:!0,get:function(){return dc.erc4626Abi}});Object.defineProperty(f,"erc6492SignatureValidatorAbi",{enumerable:!0,get:function(){return dc.erc6492SignatureValidatorAbi}});Object.defineProperty(f,"universalSignatureValidatorAbi",{enumerable:!0,get:function(){return dc.erc6492SignatureValidatorAbi}});Object.defineProperty(f,"multicall3Abi",{enumerable:!0,get:function(){return dc.multicall3Abi}});var LX=Ek();Object.defineProperty(f,"ethAddress",{enumerable:!0,get:function(){return LX.ethAddress}});Object.defineProperty(f,"zeroAddress",{enumerable:!0,get:function(){return LX.zeroAddress}});var A4e=Ow();Object.defineProperty(f,"zeroHash",{enumerable:!0,get:function(){return A4e.zeroHash}});var lv=zl();Object.defineProperty(f,"deploylessCallViaBytecodeBytecode",{enumerable:!0,get:function(){return lv.deploylessCallViaBytecodeBytecode}});Object.defineProperty(f,"deploylessCallViaFactoryBytecode",{enumerable:!0,get:function(){return lv.deploylessCallViaFactoryBytecode}});Object.defineProperty(f,"erc6492SignatureValidatorByteCode",{enumerable:!0,get:function(){return lv.erc6492SignatureValidatorByteCode}});Object.defineProperty(f,"universalSignatureValidatorByteCode",{enumerable:!0,get:function(){return lv.erc6492SignatureValidatorByteCode}});var B=Mb();Object.defineProperty(f,"maxInt8",{enumerable:!0,get:function(){return B.maxInt8}});Object.defineProperty(f,"maxInt16",{enumerable:!0,get:function(){return B.maxInt16}});Object.defineProperty(f,"maxInt24",{enumerable:!0,get:function(){return B.maxInt24}});Object.defineProperty(f,"maxInt32",{enumerable:!0,get:function(){return B.maxInt32}});Object.defineProperty(f,"maxInt40",{enumerable:!0,get:function(){return B.maxInt40}});Object.defineProperty(f,"maxInt48",{enumerable:!0,get:function(){return B.maxInt48}});Object.defineProperty(f,"maxInt56",{enumerable:!0,get:function(){return B.maxInt56}});Object.defineProperty(f,"maxInt64",{enumerable:!0,get:function(){return B.maxInt64}});Object.defineProperty(f,"maxInt72",{enumerable:!0,get:function(){return B.maxInt72}});Object.defineProperty(f,"maxInt80",{enumerable:!0,get:function(){return B.maxInt80}});Object.defineProperty(f,"maxInt88",{enumerable:!0,get:function(){return B.maxInt88}});Object.defineProperty(f,"maxInt96",{enumerable:!0,get:function(){return B.maxInt96}});Object.defineProperty(f,"maxInt104",{enumerable:!0,get:function(){return B.maxInt104}});Object.defineProperty(f,"maxInt112",{enumerable:!0,get:function(){return B.maxInt112}});Object.defineProperty(f,"maxInt120",{enumerable:!0,get:function(){return B.maxInt120}});Object.defineProperty(f,"maxInt128",{enumerable:!0,get:function(){return B.maxInt128}});Object.defineProperty(f,"maxInt136",{enumerable:!0,get:function(){return B.maxInt136}});Object.defineProperty(f,"maxInt144",{enumerable:!0,get:function(){return B.maxInt144}});Object.defineProperty(f,"maxInt152",{enumerable:!0,get:function(){return B.maxInt152}});Object.defineProperty(f,"maxInt160",{enumerable:!0,get:function(){return B.maxInt160}});Object.defineProperty(f,"maxInt168",{enumerable:!0,get:function(){return B.maxInt168}});Object.defineProperty(f,"maxInt176",{enumerable:!0,get:function(){return B.maxInt176}});Object.defineProperty(f,"maxInt184",{enumerable:!0,get:function(){return B.maxInt184}});Object.defineProperty(f,"maxInt192",{enumerable:!0,get:function(){return B.maxInt192}});Object.defineProperty(f,"maxInt200",{enumerable:!0,get:function(){return B.maxInt200}});Object.defineProperty(f,"maxInt208",{enumerable:!0,get:function(){return B.maxInt208}});Object.defineProperty(f,"maxInt216",{enumerable:!0,get:function(){return B.maxInt216}});Object.defineProperty(f,"maxInt224",{enumerable:!0,get:function(){return B.maxInt224}});Object.defineProperty(f,"maxInt232",{enumerable:!0,get:function(){return B.maxInt232}});Object.defineProperty(f,"maxInt240",{enumerable:!0,get:function(){return B.maxInt240}});Object.defineProperty(f,"maxInt248",{enumerable:!0,get:function(){return B.maxInt248}});Object.defineProperty(f,"maxInt256",{enumerable:!0,get:function(){return B.maxInt256}});Object.defineProperty(f,"maxUint8",{enumerable:!0,get:function(){return B.maxUint8}});Object.defineProperty(f,"maxUint16",{enumerable:!0,get:function(){return B.maxUint16}});Object.defineProperty(f,"maxUint24",{enumerable:!0,get:function(){return B.maxUint24}});Object.defineProperty(f,"maxUint32",{enumerable:!0,get:function(){return B.maxUint32}});Object.defineProperty(f,"maxUint40",{enumerable:!0,get:function(){return B.maxUint40}});Object.defineProperty(f,"maxUint48",{enumerable:!0,get:function(){return B.maxUint48}});Object.defineProperty(f,"maxUint56",{enumerable:!0,get:function(){return B.maxUint56}});Object.defineProperty(f,"maxUint64",{enumerable:!0,get:function(){return B.maxUint64}});Object.defineProperty(f,"maxUint72",{enumerable:!0,get:function(){return B.maxUint72}});Object.defineProperty(f,"maxUint80",{enumerable:!0,get:function(){return B.maxUint80}});Object.defineProperty(f,"maxUint88",{enumerable:!0,get:function(){return B.maxUint88}});Object.defineProperty(f,"maxUint96",{enumerable:!0,get:function(){return B.maxUint96}});Object.defineProperty(f,"maxUint104",{enumerable:!0,get:function(){return B.maxUint104}});Object.defineProperty(f,"maxUint112",{enumerable:!0,get:function(){return B.maxUint112}});Object.defineProperty(f,"maxUint120",{enumerable:!0,get:function(){return B.maxUint120}});Object.defineProperty(f,"maxUint128",{enumerable:!0,get:function(){return B.maxUint128}});Object.defineProperty(f,"maxUint136",{enumerable:!0,get:function(){return B.maxUint136}});Object.defineProperty(f,"maxUint144",{enumerable:!0,get:function(){return B.maxUint144}});Object.defineProperty(f,"maxUint152",{enumerable:!0,get:function(){return B.maxUint152}});Object.defineProperty(f,"maxUint160",{enumerable:!0,get:function(){return B.maxUint160}});Object.defineProperty(f,"maxUint168",{enumerable:!0,get:function(){return B.maxUint168}});Object.defineProperty(f,"maxUint176",{enumerable:!0,get:function(){return B.maxUint176}});Object.defineProperty(f,"maxUint184",{enumerable:!0,get:function(){return B.maxUint184}});Object.defineProperty(f,"maxUint192",{enumerable:!0,get:function(){return B.maxUint192}});Object.defineProperty(f,"maxUint200",{enumerable:!0,get:function(){return B.maxUint200}});Object.defineProperty(f,"maxUint208",{enumerable:!0,get:function(){return B.maxUint208}});Object.defineProperty(f,"maxUint216",{enumerable:!0,get:function(){return B.maxUint216}});Object.defineProperty(f,"maxUint224",{enumerable:!0,get:function(){return B.maxUint224}});Object.defineProperty(f,"maxUint232",{enumerable:!0,get:function(){return B.maxUint232}});Object.defineProperty(f,"maxUint240",{enumerable:!0,get:function(){return B.maxUint240}});Object.defineProperty(f,"maxUint248",{enumerable:!0,get:function(){return B.maxUint248}});Object.defineProperty(f,"maxUint256",{enumerable:!0,get:function(){return B.maxUint256}});Object.defineProperty(f,"minInt8",{enumerable:!0,get:function(){return B.minInt8}});Object.defineProperty(f,"minInt16",{enumerable:!0,get:function(){return B.minInt16}});Object.defineProperty(f,"minInt24",{enumerable:!0,get:function(){return B.minInt24}});Object.defineProperty(f,"minInt32",{enumerable:!0,get:function(){return B.minInt32}});Object.defineProperty(f,"minInt40",{enumerable:!0,get:function(){return B.minInt40}});Object.defineProperty(f,"minInt48",{enumerable:!0,get:function(){return B.minInt48}});Object.defineProperty(f,"minInt56",{enumerable:!0,get:function(){return B.minInt56}});Object.defineProperty(f,"minInt64",{enumerable:!0,get:function(){return B.minInt64}});Object.defineProperty(f,"minInt72",{enumerable:!0,get:function(){return B.minInt72}});Object.defineProperty(f,"minInt80",{enumerable:!0,get:function(){return B.minInt80}});Object.defineProperty(f,"minInt88",{enumerable:!0,get:function(){return B.minInt88}});Object.defineProperty(f,"minInt96",{enumerable:!0,get:function(){return B.minInt96}});Object.defineProperty(f,"minInt104",{enumerable:!0,get:function(){return B.minInt104}});Object.defineProperty(f,"minInt112",{enumerable:!0,get:function(){return B.minInt112}});Object.defineProperty(f,"minInt120",{enumerable:!0,get:function(){return B.minInt120}});Object.defineProperty(f,"minInt128",{enumerable:!0,get:function(){return B.minInt128}});Object.defineProperty(f,"minInt136",{enumerable:!0,get:function(){return B.minInt136}});Object.defineProperty(f,"minInt144",{enumerable:!0,get:function(){return B.minInt144}});Object.defineProperty(f,"minInt152",{enumerable:!0,get:function(){return B.minInt152}});Object.defineProperty(f,"minInt160",{enumerable:!0,get:function(){return B.minInt160}});Object.defineProperty(f,"minInt168",{enumerable:!0,get:function(){return B.minInt168}});Object.defineProperty(f,"minInt176",{enumerable:!0,get:function(){return B.minInt176}});Object.defineProperty(f,"minInt184",{enumerable:!0,get:function(){return B.minInt184}});Object.defineProperty(f,"minInt192",{enumerable:!0,get:function(){return B.minInt192}});Object.defineProperty(f,"minInt200",{enumerable:!0,get:function(){return B.minInt200}});Object.defineProperty(f,"minInt208",{enumerable:!0,get:function(){return B.minInt208}});Object.defineProperty(f,"minInt216",{enumerable:!0,get:function(){return B.minInt216}});Object.defineProperty(f,"minInt224",{enumerable:!0,get:function(){return B.minInt224}});Object.defineProperty(f,"minInt232",{enumerable:!0,get:function(){return B.minInt232}});Object.defineProperty(f,"minInt240",{enumerable:!0,get:function(){return B.minInt240}});Object.defineProperty(f,"minInt248",{enumerable:!0,get:function(){return B.minInt248}});Object.defineProperty(f,"minInt256",{enumerable:!0,get:function(){return B.minInt256}});var I4e=rN();Object.defineProperty(f,"presignMessagePrefix",{enumerable:!0,get:function(){return I4e.presignMessagePrefix}});var jM=bX();Object.defineProperty(f,"etherUnits",{enumerable:!0,get:function(){return jM.etherUnits}});Object.defineProperty(f,"gweiUnits",{enumerable:!0,get:function(){return jM.gweiUnits}});Object.defineProperty(f,"weiUnits",{enumerable:!0,get:function(){return jM.weiUnits}});var ct=ft();Object.defineProperty(f,"AbiConstructorNotFoundError",{enumerable:!0,get:function(){return ct.AbiConstructorNotFoundError}});Object.defineProperty(f,"AbiConstructorParamsNotFoundError",{enumerable:!0,get:function(){return ct.AbiConstructorParamsNotFoundError}});Object.defineProperty(f,"AbiDecodingDataSizeInvalidError",{enumerable:!0,get:function(){return ct.AbiDecodingDataSizeInvalidError}});Object.defineProperty(f,"AbiDecodingDataSizeTooSmallError",{enumerable:!0,get:function(){return ct.AbiDecodingDataSizeTooSmallError}});Object.defineProperty(f,"AbiDecodingZeroDataError",{enumerable:!0,get:function(){return ct.AbiDecodingZeroDataError}});Object.defineProperty(f,"AbiEncodingArrayLengthMismatchError",{enumerable:!0,get:function(){return ct.AbiEncodingArrayLengthMismatchError}});Object.defineProperty(f,"AbiEncodingBytesSizeMismatchError",{enumerable:!0,get:function(){return ct.AbiEncodingBytesSizeMismatchError}});Object.defineProperty(f,"AbiEncodingLengthMismatchError",{enumerable:!0,get:function(){return ct.AbiEncodingLengthMismatchError}});Object.defineProperty(f,"AbiErrorInputsNotFoundError",{enumerable:!0,get:function(){return ct.AbiErrorInputsNotFoundError}});Object.defineProperty(f,"AbiErrorNotFoundError",{enumerable:!0,get:function(){return ct.AbiErrorNotFoundError}});Object.defineProperty(f,"AbiErrorSignatureNotFoundError",{enumerable:!0,get:function(){return ct.AbiErrorSignatureNotFoundError}});Object.defineProperty(f,"AbiEventNotFoundError",{enumerable:!0,get:function(){return ct.AbiEventNotFoundError}});Object.defineProperty(f,"AbiEventSignatureEmptyTopicsError",{enumerable:!0,get:function(){return ct.AbiEventSignatureEmptyTopicsError}});Object.defineProperty(f,"AbiEventSignatureNotFoundError",{enumerable:!0,get:function(){return ct.AbiEventSignatureNotFoundError}});Object.defineProperty(f,"AbiFunctionNotFoundError",{enumerable:!0,get:function(){return ct.AbiFunctionNotFoundError}});Object.defineProperty(f,"AbiFunctionOutputsNotFoundError",{enumerable:!0,get:function(){return ct.AbiFunctionOutputsNotFoundError}});Object.defineProperty(f,"AbiFunctionSignatureNotFoundError",{enumerable:!0,get:function(){return ct.AbiFunctionSignatureNotFoundError}});Object.defineProperty(f,"BytesSizeMismatchError",{enumerable:!0,get:function(){return ct.BytesSizeMismatchError}});Object.defineProperty(f,"DecodeLogDataMismatch",{enumerable:!0,get:function(){return ct.DecodeLogDataMismatch}});Object.defineProperty(f,"DecodeLogTopicsMismatch",{enumerable:!0,get:function(){return ct.DecodeLogTopicsMismatch}});Object.defineProperty(f,"InvalidAbiDecodingTypeError",{enumerable:!0,get:function(){return ct.InvalidAbiDecodingTypeError}});Object.defineProperty(f,"InvalidAbiEncodingTypeError",{enumerable:!0,get:function(){return ct.InvalidAbiEncodingTypeError}});Object.defineProperty(f,"InvalidArrayError",{enumerable:!0,get:function(){return ct.InvalidArrayError}});Object.defineProperty(f,"InvalidDefinitionTypeError",{enumerable:!0,get:function(){return ct.InvalidDefinitionTypeError}});Object.defineProperty(f,"UnsupportedPackedAbiType",{enumerable:!0,get:function(){return ct.UnsupportedPackedAbiType}});var P4e=Wn();Object.defineProperty(f,"InvalidAddressError",{enumerable:!0,get:function(){return P4e.InvalidAddressError}});var BX=ye();Object.defineProperty(f,"BaseError",{enumerable:!0,get:function(){return BX.BaseError}});Object.defineProperty(f,"setErrorConfig",{enumerable:!0,get:function(){return BX.setErrorConfig}});var T4e=Ym();Object.defineProperty(f,"BlockNotFoundError",{enumerable:!0,get:function(){return T4e.BlockNotFoundError}});var x4e=Y6();Object.defineProperty(f,"BundleFailedError",{enumerable:!0,get:function(){return x4e.BundleFailedError}});var Ch=Yl();Object.defineProperty(f,"ChainDoesNotSupportContract",{enumerable:!0,get:function(){return Ch.ChainDoesNotSupportContract}});Object.defineProperty(f,"ChainMismatchError",{enumerable:!0,get:function(){return Ch.ChainMismatchError}});Object.defineProperty(f,"ChainNotFoundError",{enumerable:!0,get:function(){return Ch.ChainNotFoundError}});Object.defineProperty(f,"ClientChainNotConfiguredError",{enumerable:!0,get:function(){return Ch.ClientChainNotConfiguredError}});Object.defineProperty(f,"InvalidChainIdError",{enumerable:!0,get:function(){return Ch.InvalidChainIdError}});var Jf=ao();Object.defineProperty(f,"CallExecutionError",{enumerable:!0,get:function(){return Jf.CallExecutionError}});Object.defineProperty(f,"ContractFunctionExecutionError",{enumerable:!0,get:function(){return Jf.ContractFunctionExecutionError}});Object.defineProperty(f,"ContractFunctionRevertedError",{enumerable:!0,get:function(){return Jf.ContractFunctionRevertedError}});Object.defineProperty(f,"ContractFunctionZeroDataError",{enumerable:!0,get:function(){return Jf.ContractFunctionZeroDataError}});Object.defineProperty(f,"CounterfactualDeploymentFailedError",{enumerable:!0,get:function(){return Jf.CounterfactualDeploymentFailedError}});Object.defineProperty(f,"RawContractError",{enumerable:!0,get:function(){return Jf.RawContractError}});var UX=wm();Object.defineProperty(f,"SizeExceedsPaddingSizeError",{enumerable:!0,get:function(){return UX.SizeExceedsPaddingSizeError}});Object.defineProperty(f,"SliceOffsetOutOfBoundsError",{enumerable:!0,get:function(){return UX.SliceOffsetOutOfBoundsError}});var lc=_u();Object.defineProperty(f,"IntegerOutOfRangeError",{enumerable:!0,get:function(){return lc.IntegerOutOfRangeError}});Object.defineProperty(f,"InvalidBytesBooleanError",{enumerable:!0,get:function(){return lc.InvalidBytesBooleanError}});Object.defineProperty(f,"InvalidHexBooleanError",{enumerable:!0,get:function(){return lc.InvalidHexBooleanError}});Object.defineProperty(f,"InvalidHexValueError",{enumerable:!0,get:function(){return lc.InvalidHexValueError}});Object.defineProperty(f,"RlpDepthLimitExceededError",{enumerable:!0,get:function(){return lc.RlpDepthLimitExceededError}});Object.defineProperty(f,"RlpListBoundaryExceededError",{enumerable:!0,get:function(){return lc.RlpListBoundaryExceededError}});Object.defineProperty(f,"RlpTrailingBytesError",{enumerable:!0,get:function(){return lc.RlpTrailingBytesError}});Object.defineProperty(f,"SizeOverflowError",{enumerable:!0,get:function(){return lc.SizeOverflowError}});var fv=OE();Object.defineProperty(f,"EnsAvatarInvalidNftUriError",{enumerable:!0,get:function(){return fv.EnsAvatarInvalidNftUriError}});Object.defineProperty(f,"EnsAvatarUnsupportedNamespaceError",{enumerable:!0,get:function(){return fv.EnsAvatarUnsupportedNamespaceError}});Object.defineProperty(f,"EnsAvatarUriResolutionError",{enumerable:!0,get:function(){return fv.EnsAvatarUriResolutionError}});Object.defineProperty(f,"EnsInvalidChainIdError",{enumerable:!0,get:function(){return fv.EnsInvalidChainIdError}});var O4e=K2();Object.defineProperty(f,"EstimateGasExecutionError",{enumerable:!0,get:function(){return O4e.EstimateGasExecutionError}});var MM=Bl();Object.defineProperty(f,"BaseFeeScalarError",{enumerable:!0,get:function(){return MM.BaseFeeScalarError}});Object.defineProperty(f,"Eip1559FeesNotSupportedError",{enumerable:!0,get:function(){return MM.Eip1559FeesNotSupportedError}});Object.defineProperty(f,"MaxFeePerGasTooLowError",{enumerable:!0,get:function(){return MM.MaxFeePerGasTooLowError}});var R4e=hT();Object.defineProperty(f,"FilterTypeNotSupportedError",{enumerable:!0,get:function(){return R4e.FilterTypeNotSupportedError}});var ci=Ti();Object.defineProperty(f,"ExecutionRevertedError",{enumerable:!0,get:function(){return ci.ExecutionRevertedError}});Object.defineProperty(f,"FeeCapTooHighError",{enumerable:!0,get:function(){return ci.FeeCapTooHighError}});Object.defineProperty(f,"FeeCapTooLowError",{enumerable:!0,get:function(){return ci.FeeCapTooLowError}});Object.defineProperty(f,"InsufficientFundsError",{enumerable:!0,get:function(){return ci.InsufficientFundsError}});Object.defineProperty(f,"IntrinsicGasTooHighError",{enumerable:!0,get:function(){return ci.IntrinsicGasTooHighError}});Object.defineProperty(f,"IntrinsicGasTooLowError",{enumerable:!0,get:function(){return ci.IntrinsicGasTooLowError}});Object.defineProperty(f,"NonceMaxValueError",{enumerable:!0,get:function(){return ci.NonceMaxValueError}});Object.defineProperty(f,"NonceTooHighError",{enumerable:!0,get:function(){return ci.NonceTooHighError}});Object.defineProperty(f,"NonceTooLowError",{enumerable:!0,get:function(){return ci.NonceTooLowError}});Object.defineProperty(f,"TipAboveFeeCapError",{enumerable:!0,get:function(){return ci.TipAboveFeeCapError}});Object.defineProperty(f,"TransactionTypeNotSupportedError",{enumerable:!0,get:function(){return ci.TransactionTypeNotSupportedError}});Object.defineProperty(f,"UnknownNodeError",{enumerable:!0,get:function(){return ci.UnknownNodeError}});var Vf=Nn();Object.defineProperty(f,"HttpRequestError",{enumerable:!0,get:function(){return Vf.HttpRequestError}});Object.defineProperty(f,"ResponseBodyTooLargeError",{enumerable:!0,get:function(){return Vf.ResponseBodyTooLargeError}});Object.defineProperty(f,"RpcRequestError",{enumerable:!0,get:function(){return Vf.RpcRequestError}});Object.defineProperty(f,"SocketClosedError",{enumerable:!0,get:function(){return Vf.SocketClosedError}});Object.defineProperty(f,"TimeoutError",{enumerable:!0,get:function(){return Vf.TimeoutError}});Object.defineProperty(f,"WebSocketRequestError",{enumerable:!0,get:function(){return Vf.WebSocketRequestError}});var Ke=ss();Object.defineProperty(f,"AtomicityNotSupportedError",{enumerable:!0,get:function(){return Ke.AtomicityNotSupportedError}});Object.defineProperty(f,"AtomicReadyWalletRejectedUpgradeError",{enumerable:!0,get:function(){return Ke.AtomicReadyWalletRejectedUpgradeError}});Object.defineProperty(f,"BundleTooLargeError",{enumerable:!0,get:function(){return Ke.BundleTooLargeError}});Object.defineProperty(f,"ChainDisconnectedError",{enumerable:!0,get:function(){return Ke.ChainDisconnectedError}});Object.defineProperty(f,"DuplicateIdError",{enumerable:!0,get:function(){return Ke.DuplicateIdError}});Object.defineProperty(f,"InternalRpcError",{enumerable:!0,get:function(){return Ke.InternalRpcError}});Object.defineProperty(f,"InvalidInputRpcError",{enumerable:!0,get:function(){return Ke.InvalidInputRpcError}});Object.defineProperty(f,"InvalidParamsRpcError",{enumerable:!0,get:function(){return Ke.InvalidParamsRpcError}});Object.defineProperty(f,"InvalidRequestRpcError",{enumerable:!0,get:function(){return Ke.InvalidRequestRpcError}});Object.defineProperty(f,"JsonRpcVersionUnsupportedError",{enumerable:!0,get:function(){return Ke.JsonRpcVersionUnsupportedError}});Object.defineProperty(f,"LimitExceededRpcError",{enumerable:!0,get:function(){return Ke.LimitExceededRpcError}});Object.defineProperty(f,"MethodNotFoundRpcError",{enumerable:!0,get:function(){return Ke.MethodNotFoundRpcError}});Object.defineProperty(f,"MethodNotSupportedRpcError",{enumerable:!0,get:function(){return Ke.MethodNotSupportedRpcError}});Object.defineProperty(f,"ParseRpcError",{enumerable:!0,get:function(){return Ke.ParseRpcError}});Object.defineProperty(f,"ProviderDisconnectedError",{enumerable:!0,get:function(){return Ke.ProviderDisconnectedError}});Object.defineProperty(f,"ProviderRpcError",{enumerable:!0,get:function(){return Ke.ProviderRpcError}});Object.defineProperty(f,"ResourceNotFoundRpcError",{enumerable:!0,get:function(){return Ke.ResourceNotFoundRpcError}});Object.defineProperty(f,"ResourceUnavailableRpcError",{enumerable:!0,get:function(){return Ke.ResourceUnavailableRpcError}});Object.defineProperty(f,"RpcError",{enumerable:!0,get:function(){return Ke.RpcError}});Object.defineProperty(f,"SwitchChainError",{enumerable:!0,get:function(){return Ke.SwitchChainError}});Object.defineProperty(f,"TransactionRejectedRpcError",{enumerable:!0,get:function(){return Ke.TransactionRejectedRpcError}});Object.defineProperty(f,"UnauthorizedProviderError",{enumerable:!0,get:function(){return Ke.UnauthorizedProviderError}});Object.defineProperty(f,"UnknownBundleIdError",{enumerable:!0,get:function(){return Ke.UnknownBundleIdError}});Object.defineProperty(f,"UnknownRpcError",{enumerable:!0,get:function(){return Ke.UnknownRpcError}});Object.defineProperty(f,"UnsupportedChainIdError",{enumerable:!0,get:function(){return Ke.UnsupportedChainIdError}});Object.defineProperty(f,"UnsupportedNonOptionalCapabilityError",{enumerable:!0,get:function(){return Ke.UnsupportedNonOptionalCapabilityError}});Object.defineProperty(f,"UnsupportedProviderMethodError",{enumerable:!0,get:function(){return Ke.UnsupportedProviderMethodError}});Object.defineProperty(f,"UserRejectedRequestError",{enumerable:!0,get:function(){return Ke.UserRejectedRequestError}});var HX=x_();Object.defineProperty(f,"AccountStateConflictError",{enumerable:!0,get:function(){return HX.AccountStateConflictError}});Object.defineProperty(f,"StateAssignmentConflictError",{enumerable:!0,get:function(){return HX.StateAssignmentConflictError}});var ui=Xt();Object.defineProperty(f,"FeeConflictError",{enumerable:!0,get:function(){return ui.FeeConflictError}});Object.defineProperty(f,"FeePayerNonceMismatchError",{enumerable:!0,get:function(){return ui.FeePayerNonceMismatchError}});Object.defineProperty(f,"InvalidLegacyVError",{enumerable:!0,get:function(){return ui.InvalidLegacyVError}});Object.defineProperty(f,"InvalidSerializableTransactionError",{enumerable:!0,get:function(){return ui.InvalidSerializableTransactionError}});Object.defineProperty(f,"InvalidSerializedTransactionError",{enumerable:!0,get:function(){return ui.InvalidSerializedTransactionError}});Object.defineProperty(f,"InvalidSerializedTransactionTypeError",{enumerable:!0,get:function(){return ui.InvalidSerializedTransactionTypeError}});Object.defineProperty(f,"InvalidStorageKeySizeError",{enumerable:!0,get:function(){return ui.InvalidStorageKeySizeError}});Object.defineProperty(f,"InvalidYParityError",{enumerable:!0,get:function(){return ui.InvalidYParityError}});Object.defineProperty(f,"TransactionExecutionError",{enumerable:!0,get:function(){return ui.TransactionExecutionError}});Object.defineProperty(f,"TransactionNotFoundError",{enumerable:!0,get:function(){return ui.TransactionNotFoundError}});Object.defineProperty(f,"TransactionReceiptNotFoundError",{enumerable:!0,get:function(){return ui.TransactionReceiptNotFoundError}});Object.defineProperty(f,"WaitForTransactionReceiptTimeoutError",{enumerable:!0,get:function(){return ui.WaitForTransactionReceiptTimeoutError}});var C4e=av();Object.defineProperty(f,"UrlRequiredError",{enumerable:!0,get:function(){return C4e.UrlRequiredError}});var pv=lN();Object.defineProperty(f,"InvalidDomainError",{enumerable:!0,get:function(){return pv.InvalidDomainError}});Object.defineProperty(f,"InvalidPrimaryTypeError",{enumerable:!0,get:function(){return pv.InvalidPrimaryTypeError}});Object.defineProperty(f,"InvalidStructTypeError",{enumerable:!0,get:function(){return pv.InvalidStructTypeError}});Object.defineProperty(f,"InvalidTypedDataTypeError",{enumerable:!0,get:function(){return pv.InvalidTypedDataTypeError}});var N4e=EX();Object.defineProperty(f,"InvalidDecimalNumberError",{enumerable:!0,get:function(){return N4e.InvalidDecimalNumberError}});var k4e=wX();Object.defineProperty(f,"EIP1193ProviderRpcError",{enumerable:!0,get:function(){return k4e.ProviderRpcError}});var j4e=os();Object.defineProperty(f,"decodeAbiParameters",{enumerable:!0,get:function(){return j4e.decodeAbiParameters}});var M4e=vX();Object.defineProperty(f,"decodeDeployData",{enumerable:!0,get:function(){return M4e.decodeDeployData}});var q4e=Ol();Object.defineProperty(f,"decodeErrorResult",{enumerable:!0,get:function(){return q4e.decodeErrorResult}});var D4e=Jl();Object.defineProperty(f,"decodeEventLog",{enumerable:!0,get:function(){return D4e.decodeEventLog}});var L4e=sE();Object.defineProperty(f,"decodeFunctionData",{enumerable:!0,get:function(){return L4e.decodeFunctionData}});var B4e=ei();Object.defineProperty(f,"decodeFunctionResult",{enumerable:!0,get:function(){return B4e.decodeFunctionResult}});var U4e=zn();Object.defineProperty(f,"encodeAbiParameters",{enumerable:!0,get:function(){return U4e.encodeAbiParameters}});var H4e=Xl();Object.defineProperty(f,"encodeDeployData",{enumerable:!0,get:function(){return H4e.encodeDeployData}});var F4e=aE();Object.defineProperty(f,"encodeErrorResult",{enumerable:!0,get:function(){return F4e.encodeErrorResult}});var $4e=Ca();Object.defineProperty(f,"encodeEventTopics",{enumerable:!0,get:function(){return $4e.encodeEventTopics}});var J4e=Tr();Object.defineProperty(f,"encodeFunctionData",{enumerable:!0,get:function(){return J4e.encodeFunctionData}});var V4e=uE();Object.defineProperty(f,"encodeFunctionResult",{enumerable:!0,get:function(){return V4e.encodeFunctionResult}});var G4e=YR();Object.defineProperty(f,"encodePacked",{enumerable:!0,get:function(){return G4e.encodePacked}});var K4e=so();Object.defineProperty(f,"getAbiItem",{enumerable:!0,get:function(){return K4e.getAbiItem}});var W4e=Ya();Object.defineProperty(f,"parseEventLogs",{enumerable:!0,get:function(){return W4e.parseEventLogs}});var z4e=ux();Object.defineProperty(f,"prepareEncodeFunctionData",{enumerable:!0,get:function(){return z4e.prepareEncodeFunctionData}});var FX=Ir();Object.defineProperty(f,"checksumAddress",{enumerable:!0,get:function(){return FX.checksumAddress}});Object.defineProperty(f,"getAddress",{enumerable:!0,get:function(){return FX.getAddress}});var qM=QR();Object.defineProperty(f,"getContractAddress",{enumerable:!0,get:function(){return qM.getContractAddress}});Object.defineProperty(f,"getCreate2Address",{enumerable:!0,get:function(){return qM.getCreate2Address}});Object.defineProperty(f,"getCreateAddress",{enumerable:!0,get:function(){return qM.getCreateAddress}});var Y4e=Pr();Object.defineProperty(f,"isAddress",{enumerable:!0,get:function(){return Y4e.isAddress}});var X4e=ln();Object.defineProperty(f,"isAddressEqual",{enumerable:!0,get:function(){return X4e.isAddressEqual}});var Z4e=Qm();Object.defineProperty(f,"blobsToCommitments",{enumerable:!0,get:function(){return Z4e.blobsToCommitments}});var Q4e=eg();Object.defineProperty(f,"blobsToProofs",{enumerable:!0,get:function(){return Q4e.blobsToProofs}});var eLe=$b();Object.defineProperty(f,"commitmentsToVersionedHashes",{enumerable:!0,get:function(){return eLe.commitmentsToVersionedHashes}});var tLe=Fb();Object.defineProperty(f,"commitmentToVersionedHash",{enumerable:!0,get:function(){return tLe.commitmentToVersionedHash}});var rLe=AX();Object.defineProperty(f,"fromBlobs",{enumerable:!0,get:function(){return rLe.fromBlobs}});var nLe=IX();Object.defineProperty(f,"sidecarsToVersionedHashes",{enumerable:!0,get:function(){return nLe.sidecarsToVersionedHashes}});var iLe=rg();Object.defineProperty(f,"toBlobSidecars",{enumerable:!0,get:function(){return iLe.toBlobSidecars}});var oLe=PO();Object.defineProperty(f,"toBlobs",{enumerable:!0,get:function(){return oLe.toBlobs}});var Nh=gg();Object.defineProperty(f,"ccipRequest",{enumerable:!0,get:function(){return Nh.ccipRequest}});Object.defineProperty(f,"ccipFetch",{enumerable:!0,get:function(){return Nh.ccipRequest}});Object.defineProperty(f,"offchainLookup",{enumerable:!0,get:function(){return Nh.offchainLookup}});Object.defineProperty(f,"offchainLookupAbiItem",{enumerable:!0,get:function(){return Nh.offchainLookupAbiItem}});Object.defineProperty(f,"offchainLookupSignature",{enumerable:!0,get:function(){return Nh.offchainLookupSignature}});var sLe=lC();Object.defineProperty(f,"ccipReadTunnel",{enumerable:!0,get:function(){return sLe.ccipReadTunnel}});var aLe=tf();Object.defineProperty(f,"assertCurrentChain",{enumerable:!0,get:function(){return aLe.assertCurrentChain}});var $X=fC();Object.defineProperty(f,"defineChain",{enumerable:!0,get:function(){return $X.defineChain}});Object.defineProperty(f,"extendSchema",{enumerable:!0,get:function(){return $X.extendSchema}});var cLe=mC();Object.defineProperty(f,"extractChain",{enumerable:!0,get:function(){return cLe.extractChain}});var uLe=ms();Object.defineProperty(f,"getChainContractAddress",{enumerable:!0,get:function(){return uLe.getChainContractAddress}});var DM=Nt();Object.defineProperty(f,"concat",{enumerable:!0,get:function(){return DM.concat}});Object.defineProperty(f,"concatBytes",{enumerable:!0,get:function(){return DM.concatBytes}});Object.defineProperty(f,"concatHex",{enumerable:!0,get:function(){return DM.concatHex}});var dLe=NE();Object.defineProperty(f,"isBytes",{enumerable:!0,get:function(){return dLe.isBytes}});var lLe=Sr();Object.defineProperty(f,"isHex",{enumerable:!0,get:function(){return lLe.isHex}});var LM=oo();Object.defineProperty(f,"pad",{enumerable:!0,get:function(){return LM.pad}});Object.defineProperty(f,"padBytes",{enumerable:!0,get:function(){return LM.padBytes}});Object.defineProperty(f,"padHex",{enumerable:!0,get:function(){return LM.padHex}});var fLe=ur();Object.defineProperty(f,"size",{enumerable:!0,get:function(){return fLe.size}});var BM=on();Object.defineProperty(f,"slice",{enumerable:!0,get:function(){return BM.slice}});Object.defineProperty(f,"sliceBytes",{enumerable:!0,get:function(){return BM.sliceBytes}});Object.defineProperty(f,"sliceHex",{enumerable:!0,get:function(){return BM.sliceHex}});var pLe=ts();Object.defineProperty(f,"trim",{enumerable:!0,get:function(){return pLe.trim}});var kh=S_();Object.defineProperty(f,"bytesToBigInt",{enumerable:!0,get:function(){return kh.bytesToBigInt}});Object.defineProperty(f,"bytesToBool",{enumerable:!0,get:function(){return kh.bytesToBool}});Object.defineProperty(f,"bytesToNumber",{enumerable:!0,get:function(){return kh.bytesToNumber}});Object.defineProperty(f,"bytesToString",{enumerable:!0,get:function(){return kh.bytesToString}});Object.defineProperty(f,"fromBytes",{enumerable:!0,get:function(){return kh.fromBytes}});var jh=pt();Object.defineProperty(f,"fromHex",{enumerable:!0,get:function(){return jh.fromHex}});Object.defineProperty(f,"hexToBigInt",{enumerable:!0,get:function(){return jh.hexToBigInt}});Object.defineProperty(f,"hexToBool",{enumerable:!0,get:function(){return jh.hexToBool}});Object.defineProperty(f,"hexToNumber",{enumerable:!0,get:function(){return jh.hexToNumber}});Object.defineProperty(f,"hexToString",{enumerable:!0,get:function(){return jh.hexToString}});var mLe=KE();Object.defineProperty(f,"fromRlp",{enumerable:!0,get:function(){return mLe.fromRlp}});var Mh=Je();Object.defineProperty(f,"boolToBytes",{enumerable:!0,get:function(){return Mh.boolToBytes}});Object.defineProperty(f,"hexToBytes",{enumerable:!0,get:function(){return Mh.hexToBytes}});Object.defineProperty(f,"numberToBytes",{enumerable:!0,get:function(){return Mh.numberToBytes}});Object.defineProperty(f,"stringToBytes",{enumerable:!0,get:function(){return Mh.stringToBytes}});Object.defineProperty(f,"toBytes",{enumerable:!0,get:function(){return Mh.toBytes}});var qh=W();Object.defineProperty(f,"boolToHex",{enumerable:!0,get:function(){return qh.boolToHex}});Object.defineProperty(f,"bytesToHex",{enumerable:!0,get:function(){return qh.bytesToHex}});Object.defineProperty(f,"numberToHex",{enumerable:!0,get:function(){return qh.numberToHex}});Object.defineProperty(f,"stringToHex",{enumerable:!0,get:function(){return qh.stringToHex}});Object.defineProperty(f,"toHex",{enumerable:!0,get:function(){return qh.toHex}});var UM=Ml();Object.defineProperty(f,"bytesToRlp",{enumerable:!0,get:function(){return UM.bytesToRlp}});Object.defineProperty(f,"hexToRlp",{enumerable:!0,get:function(){return UM.hexToRlp}});Object.defineProperty(f,"toRlp",{enumerable:!0,get:function(){return UM.toRlp}});var gLe=dR();Object.defineProperty(f,"labelhash",{enumerable:!0,get:function(){return gLe.labelhash}});var hLe=TE();Object.defineProperty(f,"namehash",{enumerable:!0,get:function(){return hLe.namehash}});var yLe=PX();Object.defineProperty(f,"toCoinType",{enumerable:!0,get:function(){return yLe.toCoinType}});var _Le=as();Object.defineProperty(f,"getContractError",{enumerable:!0,get:function(){return _Le.getContractError}});var JX=Ul();Object.defineProperty(f,"defineBlock",{enumerable:!0,get:function(){return JX.defineBlock}});Object.defineProperty(f,"formatBlock",{enumerable:!0,get:function(){return JX.formatBlock}});var bLe=xi();Object.defineProperty(f,"formatLog",{enumerable:!0,get:function(){return bLe.formatLog}});var HM=Cu();Object.defineProperty(f,"defineTransaction",{enumerable:!0,get:function(){return HM.defineTransaction}});Object.defineProperty(f,"formatTransaction",{enumerable:!0,get:function(){return HM.formatTransaction}});Object.defineProperty(f,"transactionType",{enumerable:!0,get:function(){return HM.transactionType}});var VX=Bu();Object.defineProperty(f,"defineTransactionReceipt",{enumerable:!0,get:function(){return VX.defineTransactionReceipt}});Object.defineProperty(f,"formatTransactionReceipt",{enumerable:!0,get:function(){return VX.formatTransactionReceipt}});var FM=Zn();Object.defineProperty(f,"defineTransactionRequest",{enumerable:!0,get:function(){return FM.defineTransactionRequest}});Object.defineProperty(f,"formatTransactionRequest",{enumerable:!0,get:function(){return FM.formatTransactionRequest}});Object.defineProperty(f,"rpcTransactionType",{enumerable:!0,get:function(){return FM.rpcTransactionType}});var ELe=WE();Object.defineProperty(f,"isHash",{enumerable:!0,get:function(){return ELe.isHash}});var wLe=Hr();Object.defineProperty(f,"keccak256",{enumerable:!0,get:function(){return wLe.keccak256}});var vLe=wC();Object.defineProperty(f,"ripemd160",{enumerable:!0,get:function(){return vLe.ripemd160}});var SLe=Hb();Object.defineProperty(f,"sha256",{enumerable:!0,get:function(){return SLe.sha256}});var ALe=vC();Object.defineProperty(f,"toEventHash",{enumerable:!0,get:function(){return ALe.toEventHash}});var GX=wu();Object.defineProperty(f,"toEventSelector",{enumerable:!0,get:function(){return GX.toEventSelector}});Object.defineProperty(f,"getEventSelector",{enumerable:!0,get:function(){return GX.toEventSelector}});var KX=SC();Object.defineProperty(f,"toEventSignature",{enumerable:!0,get:function(){return KX.toEventSignature}});Object.defineProperty(f,"getEventSignature",{enumerable:!0,get:function(){return KX.toEventSignature}});var ILe=AC();Object.defineProperty(f,"toFunctionHash",{enumerable:!0,get:function(){return ILe.toFunctionHash}});var WX=Ra();Object.defineProperty(f,"toFunctionSelector",{enumerable:!0,get:function(){return WX.toFunctionSelector}});Object.defineProperty(f,"getFunctionSelector",{enumerable:!0,get:function(){return WX.toFunctionSelector}});var zX=IC();Object.defineProperty(f,"toFunctionSignature",{enumerable:!0,get:function(){return zX.toFunctionSignature}});Object.defineProperty(f,"getFunctionSignature",{enumerable:!0,get:function(){return zX.toFunctionSignature}});var PLe=PM();Object.defineProperty(f,"defineKzg",{enumerable:!0,get:function(){return PLe.defineKzg}});var TLe=TX();Object.defineProperty(f,"setupKzg",{enumerable:!0,get:function(){return TLe.setupKzg}});var YX=PC();Object.defineProperty(f,"createNonceManager",{enumerable:!0,get:function(){return YX.createNonceManager}});Object.defineProperty(f,"nonceManager",{enumerable:!0,get:function(){return YX.nonceManager}});var xLe=D6();Object.defineProperty(f,"withCache",{enumerable:!0,get:function(){return xLe.withCache}});var OLe=Sg();Object.defineProperty(f,"withRetry",{enumerable:!0,get:function(){return OLe.withRetry}});var RLe=iw();Object.defineProperty(f,"withTimeout",{enumerable:!0,get:function(){return RLe.withTimeout}});var CLe=xX();Object.defineProperty(f,"compactSignatureToSignature",{enumerable:!0,get:function(){return CLe.compactSignatureToSignature}});var NLe=yf();Object.defineProperty(f,"hashMessage",{enumerable:!0,get:function(){return NLe.hashMessage}});var $M=bf();Object.defineProperty(f,"hashDomain",{enumerable:!0,get:function(){return $M.hashDomain}});Object.defineProperty(f,"hashStruct",{enumerable:!0,get:function(){return $M.hashStruct}});Object.defineProperty(f,"hashTypedData",{enumerable:!0,get:function(){return $M.hashTypedData}});var kLe=Rw();Object.defineProperty(f,"isErc6492Signature",{enumerable:!0,get:function(){return kLe.isErc6492Signature}});var jLe=g1();Object.defineProperty(f,"isErc8010Signature",{enumerable:!0,get:function(){return jLe.isErc8010Signature}});var XX=RX();Object.defineProperty(f,"hexToCompactSignature",{enumerable:!0,get:function(){return XX.parseCompactSignature}});Object.defineProperty(f,"parseCompactSignature",{enumerable:!0,get:function(){return XX.parseCompactSignature}});var MLe=P5();Object.defineProperty(f,"parseErc6492Signature",{enumerable:!0,get:function(){return MLe.parseErc6492Signature}});var qLe=x5();Object.defineProperty(f,"parseErc8010Signature",{enumerable:!0,get:function(){return qLe.parseErc8010Signature}});var ZX=CX();Object.defineProperty(f,"hexToSignature",{enumerable:!0,get:function(){return ZX.parseSignature}});Object.defineProperty(f,"parseSignature",{enumerable:!0,get:function(){return ZX.parseSignature}});var DLe=ds();Object.defineProperty(f,"recoverAddress",{enumerable:!0,get:function(){return DLe.recoverAddress}});var LLe=h1();Object.defineProperty(f,"recoverMessageAddress",{enumerable:!0,get:function(){return LLe.recoverMessageAddress}});var BLe=Eb();Object.defineProperty(f,"recoverPublicKey",{enumerable:!0,get:function(){return BLe.recoverPublicKey}});var ULe=NX();Object.defineProperty(f,"recoverTransactionAddress",{enumerable:!0,get:function(){return ULe.recoverTransactionAddress}});var HLe=y1();Object.defineProperty(f,"recoverTypedDataAddress",{enumerable:!0,get:function(){return HLe.recoverTypedDataAddress}});var QX=jX();Object.defineProperty(f,"compactSignatureToHex",{enumerable:!0,get:function(){return QX.serializeCompactSignature}});Object.defineProperty(f,"serializeCompactSignature",{enumerable:!0,get:function(){return QX.serializeCompactSignature}});var FLe=N5();Object.defineProperty(f,"serializeErc6492Signature",{enumerable:!0,get:function(){return FLe.serializeErc6492Signature}});var $Le=j5();Object.defineProperty(f,"serializeErc8010Signature",{enumerable:!0,get:function(){return $Le.serializeErc8010Signature}});var eZ=Ik();Object.defineProperty(f,"signatureToHex",{enumerable:!0,get:function(){return eZ.serializeSignature}});Object.defineProperty(f,"serializeSignature",{enumerable:!0,get:function(){return eZ.serializeSignature}});var JLe=MX();Object.defineProperty(f,"signatureToCompactSignature",{enumerable:!0,get:function(){return JLe.signatureToCompactSignature}});var VLe=oN();Object.defineProperty(f,"toPrefixedMessage",{enumerable:!0,get:function(){return VLe.toPrefixedMessage}});var GLe=q5();Object.defineProperty(f,"verifyHash",{enumerable:!0,get:function(){return GLe.verifyHash}});var KLe=L5();Object.defineProperty(f,"verifyMessage",{enumerable:!0,get:function(){return KLe.verifyMessage}});var WLe=U5();Object.defineProperty(f,"verifyTypedData",{enumerable:!0,get:function(){return WLe.verifyTypedData}});var zLe=Mt();Object.defineProperty(f,"stringify",{enumerable:!0,get:function(){return zLe.stringify}});var YLe=Qn();Object.defineProperty(f,"assertRequest",{enumerable:!0,get:function(){return YLe.assertRequest}});var JM=xg();Object.defineProperty(f,"assertTransactionEIP1559",{enumerable:!0,get:function(){return JM.assertTransactionEIP1559}});Object.defineProperty(f,"assertTransactionEIP2930",{enumerable:!0,get:function(){return JM.assertTransactionEIP2930}});Object.defineProperty(f,"assertTransactionLegacy",{enumerable:!0,get:function(){return JM.assertTransactionLegacy}});var XLe=_1();Object.defineProperty(f,"getSerializedTransactionType",{enumerable:!0,get:function(){return XLe.getSerializedTransactionType}});var ZLe=ng();Object.defineProperty(f,"getTransactionType",{enumerable:!0,get:function(){return ZLe.getTransactionType}});var QLe=b1();Object.defineProperty(f,"parseTransaction",{enumerable:!0,get:function(){return QLe.parseTransaction}});var e3e=LE();Object.defineProperty(f,"serializeAccessList",{enumerable:!0,get:function(){return e3e.serializeAccessList}});var t3e=Cg();Object.defineProperty(f,"serializeTransaction",{enumerable:!0,get:function(){return t3e.serializeTransaction}});var mv=Ug();Object.defineProperty(f,"domainSeparator",{enumerable:!0,get:function(){return mv.domainSeparator}});Object.defineProperty(f,"getTypesForEIP712Domain",{enumerable:!0,get:function(){return mv.getTypesForEIP712Domain}});Object.defineProperty(f,"serializeTypedData",{enumerable:!0,get:function(){return mv.serializeTypedData}});Object.defineProperty(f,"validateTypedData",{enumerable:!0,get:function(){return mv.validateTypedData}});var r3e=Rl();Object.defineProperty(f,"formatEther",{enumerable:!0,get:function(){return r3e.formatEther}});var n3e=qa();Object.defineProperty(f,"formatGwei",{enumerable:!0,get:function(){return n3e.formatGwei}});var i3e=Mf();Object.defineProperty(f,"formatUnits",{enumerable:!0,get:function(){return i3e.formatUnits}});var o3e=J5();Object.defineProperty(f,"parseEther",{enumerable:!0,get:function(){return o3e.parseEther}});var s3e=G5();Object.defineProperty(f,"parseGwei",{enumerable:!0,get:function(){return s3e.parseGwei}});var a3e=E1();Object.defineProperty(f,"parseUnits",{enumerable:!0,get:function(){return a3e.parseUnits}})});var rZ=g(hv=>{"use strict";Object.defineProperty(hv,"__esModule",{value:!0});hv.eip712DigestBase64Url=c3e;hv.verifyEip712TypedDataSignature=u3e;var tZ=gv();function c3e(e){let t;try{t=(0,tZ.hashTypedData)(e)}catch{throw new Error("typed data is not a valid EIP-712 payload")}let r=Buffer.from(t.slice(2),"hex");if(r.length!==32)throw new Error("EIP-712 digest is not 32 bytes");return r.toString("base64url")}async function u3e(e){if(!/^0x[0-9a-f]{130}$/i.test(e.signature)||!/^0x[0-9a-f]{40}$/i.test(e.expectedAddress))return!1;try{return await(0,tZ.verifyTypedData)({...e.typedData,address:e.expectedAddress,signature:e.signature})}catch{return!1}}});var iZ=g(VM=>{"use strict";Object.defineProperty(VM,"__esModule",{value:!0});VM.turnkeyOwnerIdentityKey=l3e;var d3e=require("node:crypto"),nZ=/^[A-Za-z0-9_-]{1,128}$/;function l3e(e,t){if(!nZ.test(e)||!nZ.test(t))throw new Error("turnkey owner coordinates invalid");return"owner:v1:"+(0,d3e.createHash)("sha256").update(JSON.stringify([e,t])).digest("hex")}});var sZ=g(yv=>{"use strict";Object.defineProperty(yv,"__esModule",{value:!0});yv.canonicalEvmProviderAddress=oZ;yv.isCanonicalEvmProviderAddress=p3e;var f3e=gv();function oZ(e){let t=(0,f3e.getAddress)(e),r=e.slice(2),n=/[a-f]/.test(r),i=/[A-F]/.test(r);if(n&&i&&t!==e)throw new Error("EVM address has an invalid mixed-case checksum");return t}function p3e(e){try{return oZ(e)===e}catch{return!1}}});var KM=g(GM=>{"use strict";Object.defineProperty(GM,"__esModule",{value:!0});var m3e=require("node:crypto"),g3e=(e,t)=>(0,m3e.createHash)(e).update(t).digest();GM.default=g3e});var At=g(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.decoder=Ln.encoder=void 0;Ln.concat=zM;Ln.p2s=y3e;Ln.uint64be=_3e;Ln.uint32be=YM;Ln.lengthAndInput=b3e;Ln.concatKdf=E3e;var h3e=KM();Ln.encoder=new TextEncoder;Ln.decoder=new TextDecoder;var _v=2**32;function zM(...e){let t=e.reduce((i,{length:o})=>i+o,0),r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return r}function y3e(e,t){return zM(Ln.encoder.encode(e),new Uint8Array([0]),t)}function WM(e,t,r){if(t<0||t>=_v)throw new RangeError(`value must be >= 0 and <= ${_v-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r)}function _3e(e){let t=Math.floor(e/_v),r=e%_v,n=new Uint8Array(8);return WM(n,t,0),WM(n,r,4),n}function YM(e){let t=new Uint8Array(4);return WM(t,e),t}function b3e(e){return zM(YM(e.length),e)}async function E3e(e,t,r){let n=Math.ceil((t>>3)/32),i=new Uint8Array(n*32);for(let o=0;o<n;o++){let s=new Uint8Array(4+e.length+r.length);s.set(YM(o+1)),s.set(e,4),s.set(r,4+e.length),i.set(await(0,h3e.default)("sha256",s),o*32)}return i.slice(0,t>>3)}});var Wr=g(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});Ao.decode=Ao.encode=Ao.encodeBase64=Ao.decodeBase64=void 0;var bv=require("node:buffer"),w3e=At();function v3e(e){let t=e;return t instanceof Uint8Array&&(t=w3e.decoder.decode(t)),t}var S3e=e=>bv.Buffer.from(e).toString("base64url");Ao.encode=S3e;var A3e=e=>new Uint8Array(bv.Buffer.from(e,"base64"));Ao.decodeBase64=A3e;var I3e=e=>bv.Buffer.from(e).toString("base64");Ao.encodeBase64=I3e;var P3e=e=>new Uint8Array(bv.Buffer.from(v3e(e),"base64url"));Ao.decode=P3e});var we=g(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.JWSSignatureVerificationFailed=qe.JWKSTimeout=qe.JWKSMultipleMatchingKeys=qe.JWKSNoMatchingKey=qe.JWKSInvalid=qe.JWKInvalid=qe.JWTInvalid=qe.JWSInvalid=qe.JWEInvalid=qe.JWEDecryptionFailed=qe.JOSENotSupported=qe.JOSEAlgNotAllowed=qe.JWTExpired=qe.JWTClaimValidationFailed=qe.JOSEError=void 0;var hr=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,r){super(t,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};qe.JOSEError=hr;var XM=class extends hr{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(t,r,n="unspecified",i="unspecified"){super(t,{cause:{claim:n,reason:i,payload:r}}),this.claim=n,this.reason=i,this.payload=r}};qe.JWTClaimValidationFailed=XM;var ZM=class extends hr{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(t,r,n="unspecified",i="unspecified"){super(t,{cause:{claim:n,reason:i,payload:r}}),this.claim=n,this.reason=i,this.payload=r}};qe.JWTExpired=ZM;var QM=class extends hr{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"};qe.JOSEAlgNotAllowed=QM;var e8=class extends hr{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"};qe.JOSENotSupported=e8;var t8=class extends hr{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(t="decryption operation failed",r){super(t,r)}};qe.JWEDecryptionFailed=t8;var r8=class extends hr{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"};qe.JWEInvalid=r8;var n8=class extends hr{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};qe.JWSInvalid=n8;var i8=class extends hr{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"};qe.JWTInvalid=i8;var o8=class extends hr{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};qe.JWKInvalid=o8;var s8=class extends hr{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"};qe.JWKSInvalid=s8;var a8=class extends hr{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r)}};qe.JWKSNoMatchingKey=a8;var c8=class extends hr{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r)}};qe.JWKSMultipleMatchingKeys=c8;var u8=class extends hr{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(t="request timed out",r){super(t,r)}};qe.JWKSTimeout=u8;var d8=class extends hr{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(t="signature verification failed",r){super(t,r)}};qe.JWSSignatureVerificationFailed=d8});var Dh=g(Ev=>{"use strict";Object.defineProperty(Ev,"__esModule",{value:!0});Ev.default=void 0;var T3e=require("node:crypto");Object.defineProperty(Ev,"default",{enumerable:!0,get:function(){return T3e.randomFillSync}})});var l8=g(wv=>{"use strict";Object.defineProperty(wv,"__esModule",{value:!0});wv.bitLength=aZ;var x3e=we(),O3e=Dh();function aZ(e){switch(e){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new x3e.JOSENotSupported(`Unsupported JWE Algorithm: ${e}`)}}wv.default=e=>(0,O3e.default)(new Uint8Array(aZ(e)>>3))});var p8=g(f8=>{"use strict";Object.defineProperty(f8,"__esModule",{value:!0});var R3e=we(),C3e=l8(),N3e=(e,t)=>{if(t.length<<3!==(0,C3e.bitLength)(e))throw new R3e.JWEInvalid("Invalid Initialization Vector length")};f8.default=N3e});var di=g(m8=>{"use strict";Object.defineProperty(m8,"__esModule",{value:!0});var k3e=require("node:util");m8.default=e=>k3e.types.isKeyObject(e)});var y8=g(h8=>{"use strict";Object.defineProperty(h8,"__esModule",{value:!0});var g8=we(),j3e=di(),M3e=(e,t)=>{let r;switch(e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":r=parseInt(e.slice(-3),10);break;case"A128GCM":case"A192GCM":case"A256GCM":r=parseInt(e.slice(1,4),10);break;default:throw new g8.JOSENotSupported(`Content Encryption Algorithm ${e} is not supported either by JOSE or your javascript runtime`)}if(t instanceof Uint8Array){let n=t.byteLength<<3;if(n!==r)throw new g8.JWEInvalid(`Invalid Content Encryption Key length. Expected ${r} bits, got ${n} bits`);return}if((0,j3e.default)(t)&&t.type==="secret"){let n=t.symmetricKeySize<<3;if(n!==r)throw new g8.JWEInvalid(`Invalid Content Encryption Key length. Expected ${r} bits, got ${n} bits`);return}throw new TypeError("Invalid Content Encryption Key type")};h8.default=M3e});var cZ=g(_8=>{"use strict";Object.defineProperty(_8,"__esModule",{value:!0});var q3e=require("node:crypto"),D3e=q3e.timingSafeEqual;_8.default=D3e});var E8=g(b8=>{"use strict";Object.defineProperty(b8,"__esModule",{value:!0});b8.default=B3e;var L3e=require("node:crypto"),uZ=At();function B3e(e,t,r,n,i,o){let s=(0,uZ.concat)(e,t,r,(0,uZ.uint64be)(e.length<<3)),a=(0,L3e.createHmac)(`sha${n}`,i);return a.update(s),a.digest().slice(0,o>>3)}});var li=g(Lh=>{"use strict";Object.defineProperty(Lh,"__esModule",{value:!0});Lh.isCryptoKey=void 0;var U3e=require("node:crypto"),H3e=require("node:util"),F3e=U3e.webcrypto;Lh.default=F3e;var $3e=e=>H3e.types.isCryptoKey(e);Lh.isCryptoKey=$3e});var fc=g(Sv=>{"use strict";Object.defineProperty(Sv,"__esModule",{value:!0});Sv.checkSigCryptoKey=V3e;Sv.checkEncCryptoKey=G3e;function ir(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function xs(e,t){return e.name===t}function vv(e){return parseInt(e.name.slice(4),10)}function J3e(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function dZ(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function V3e(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!xs(e.algorithm,"HMAC"))throw ir("HMAC");let n=parseInt(t.slice(2),10);if(vv(e.algorithm.hash)!==n)throw ir(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!xs(e.algorithm,"RSASSA-PKCS1-v1_5"))throw ir("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(vv(e.algorithm.hash)!==n)throw ir(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!xs(e.algorithm,"RSA-PSS"))throw ir("RSA-PSS");let n=parseInt(t.slice(2),10);if(vv(e.algorithm.hash)!==n)throw ir(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw ir("Ed25519 or Ed448");break}case"Ed25519":{if(!xs(e.algorithm,"Ed25519"))throw ir("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!xs(e.algorithm,"ECDSA"))throw ir("ECDSA");let n=J3e(t);if(e.algorithm.namedCurve!==n)throw ir(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}dZ(e,r)}function G3e(e,t,...r){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!xs(e.algorithm,"AES-GCM"))throw ir("AES-GCM");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw ir(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!xs(e.algorithm,"AES-KW"))throw ir("AES-KW");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw ir(n,"algorithm.length");break}case"ECDH":{switch(e.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw ir("ECDH, X25519, or X448")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!xs(e.algorithm,"PBKDF2"))throw ir("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!xs(e.algorithm,"RSA-OAEP"))throw ir("RSA-OAEP");let n=parseInt(t.slice(9),10)||1;if(vv(e.algorithm.hash)!==n)throw ir(`SHA-${n}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}dZ(e,r)}});var fi=g(Av=>{"use strict";Object.defineProperty(Av,"__esModule",{value:!0});Av.withAlg=K3e;function lZ(e,t,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}Av.default=(e,...t)=>lZ("Key must be ",e,...t);function K3e(e,t,...r){return lZ(`Key for the ${e} algorithm must be `,t,...r)}});var Iv=g(w8=>{"use strict";Object.defineProperty(w8,"__esModule",{value:!0});var W3e=require("node:crypto"),fZ;w8.default=e=>(fZ||=new Set((0,W3e.getCiphers)()),fZ.has(e))});var pi=g(Bh=>{"use strict";Object.defineProperty(Bh,"__esModule",{value:!0});Bh.types=void 0;var pZ=li(),z3e=di();Bh.default=e=>(0,z3e.default)(e)||(0,pZ.isCryptoKey)(e);var mZ=["KeyObject"];Bh.types=mZ;(globalThis.CryptoKey||pZ.default?.CryptoKey)&&mZ.push("CryptoKey")});var A8=g(S8=>{"use strict";Object.defineProperty(S8,"__esModule",{value:!0});var v8=require("node:crypto"),Y3e=p8(),X3e=y8(),Z3e=At(),pc=we(),Q3e=cZ(),eBe=E8(),tBe=li(),rBe=fc(),gZ=di(),nBe=fi(),hZ=Iv(),iBe=pi();function oBe(e,t,r,n,i,o){let s=parseInt(e.slice(1,4),10);(0,gZ.default)(t)&&(t=t.export());let a=t.subarray(s>>3),c=t.subarray(0,s>>3),u=parseInt(e.slice(-3),10),d=`aes-${s}-cbc`;if(!(0,hZ.default)(d))throw new pc.JOSENotSupported(`alg ${e} is not supported by your javascript runtime`);let l=(0,eBe.default)(o,n,r,u,c,s),m;try{m=(0,Q3e.default)(i,l)}catch{}if(!m)throw new pc.JWEDecryptionFailed;let p;try{let h=(0,v8.createDecipheriv)(d,a,n);p=(0,Z3e.concat)(h.update(r),h.final())}catch{}if(!p)throw new pc.JWEDecryptionFailed;return p}function sBe(e,t,r,n,i,o){let a=`aes-${parseInt(e.slice(1,4),10)}-gcm`;if(!(0,hZ.default)(a))throw new pc.JOSENotSupported(`alg ${e} is not supported by your javascript runtime`);try{let c=(0,v8.createDecipheriv)(a,t,n,{authTagLength:16});c.setAuthTag(i),o.byteLength&&c.setAAD(o,{plaintextLength:r.length});let u=c.update(r);return c.final(),u}catch{throw new pc.JWEDecryptionFailed}}var aBe=(e,t,r,n,i,o)=>{let s;if((0,tBe.isCryptoKey)(t))(0,rBe.checkEncCryptoKey)(t,e,"decrypt"),s=v8.KeyObject.from(t);else if(t instanceof Uint8Array||(0,gZ.default)(t))s=t;else throw new TypeError((0,nBe.default)(t,...iBe.types,"Uint8Array"));if(!n)throw new pc.JWEInvalid("JWE Initialization Vector missing");if(!i)throw new pc.JWEInvalid("JWE Authentication Tag missing");switch((0,X3e.default)(e,s),(0,Y3e.default)(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return oBe(e,s,r,n,i,o);case"A128GCM":case"A192GCM":case"A256GCM":return sBe(e,s,r,n,i,o);default:throw new pc.JOSENotSupported("Unsupported JWE Content Encryption Algorithm")}};S8.default=aBe});var Gf=g(I8=>{"use strict";Object.defineProperty(I8,"__esModule",{value:!0});var cBe=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let i=Object.keys(n);if(!r||r.size===0){r=new Set(i);continue}for(let o of i){if(r.has(o))return!1;r.add(o)}}return!0};I8.default=cBe});var kr=g(P8=>{"use strict";Object.defineProperty(P8,"__esModule",{value:!0});P8.default=dBe;function uBe(e){return typeof e=="object"&&e!==null}function dBe(e){if(!uBe(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}});var Tv=g(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});Kf.unwrap=Kf.wrap=void 0;var yZ=require("node:buffer"),Pv=require("node:crypto"),_Z=we(),bZ=At(),lBe=li(),fBe=fc(),pBe=di(),mBe=fi(),EZ=Iv(),gBe=pi();function wZ(e,t){if(e.symmetricKeySize<<3!==parseInt(t.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${t}`)}function vZ(e,t,r){if((0,pBe.default)(e))return e;if(e instanceof Uint8Array)return(0,Pv.createSecretKey)(e);if((0,lBe.isCryptoKey)(e))return(0,fBe.checkEncCryptoKey)(e,t,r),Pv.KeyObject.from(e);throw new TypeError((0,mBe.default)(e,...gBe.types,"Uint8Array"))}var hBe=(e,t,r)=>{let i=`aes${parseInt(e.slice(1,4),10)}-wrap`;if(!(0,EZ.default)(i))throw new _Z.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`);let o=vZ(t,e,"wrapKey");wZ(o,e);let s=(0,Pv.createCipheriv)(i,o,yZ.Buffer.alloc(8,166));return(0,bZ.concat)(s.update(r),s.final())};Kf.wrap=hBe;var yBe=(e,t,r)=>{let i=`aes${parseInt(e.slice(1,4),10)}-wrap`;if(!(0,EZ.default)(i))throw new _Z.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`);let o=vZ(t,e,"unwrapKey");wZ(o,e);let s=(0,Pv.createDecipheriv)(i,o,yZ.Buffer.alloc(8,166));return(0,bZ.concat)(s.update(r),s.final())};Kf.unwrap=yBe});var Uh=g(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});Wf.isJWK=SZ;Wf.isPrivateJWK=bBe;Wf.isPublicJWK=EBe;Wf.isSecretJWK=wBe;var _Be=kr();function SZ(e){return(0,_Be.default)(e)&&typeof e.kty=="string"}function bBe(e){return e.kty!=="oct"&&typeof e.d=="string"}function EBe(e){return e.kty!=="oct"&&typeof e.d>"u"}function wBe(e){return SZ(e)&&e.kty==="oct"&&typeof e.k=="string"}});var T8=g(Hh=>{"use strict";Object.defineProperty(Hh,"__esModule",{value:!0});Hh.weakMap=void 0;var vBe=require("node:crypto"),SBe=we(),ABe=li(),IBe=di(),PBe=fi(),TBe=pi(),xBe=Uh();Hh.weakMap=new WeakMap;var OBe=e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new SBe.JOSENotSupported("Unsupported key curve for this operation")}},RBe=(e,t)=>{let r;if((0,ABe.isCryptoKey)(e))r=vBe.KeyObject.from(e);else if((0,IBe.default)(e))r=e;else{if((0,xBe.isJWK)(e))return e.crv;throw new TypeError((0,PBe.default)(e,...TBe.types))}if(r.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{let n=r.asymmetricKeyDetails.namedCurve;return t?n:OBe(n)}default:throw new TypeError("Invalid asymmetric key type for this operation")}};Hh.default=RBe});var k8=g(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});zf.ecdhAllowed=void 0;zf.deriveKey=kBe;zf.generateEpk=jBe;var Fh=require("node:crypto"),CBe=require("node:util"),IZ=T8(),ld=At(),NBe=we(),O8=li(),AZ=fc(),R8=di(),C8=fi(),N8=pi(),x8=(0,CBe.promisify)(Fh.generateKeyPair);async function kBe(e,t,r,n,i=new Uint8Array(0),o=new Uint8Array(0)){let s;if((0,O8.isCryptoKey)(e))(0,AZ.checkEncCryptoKey)(e,"ECDH"),s=Fh.KeyObject.from(e);else if((0,R8.default)(e))s=e;else throw new TypeError((0,C8.default)(e,...N8.types));let a;if((0,O8.isCryptoKey)(t))(0,AZ.checkEncCryptoKey)(t,"ECDH","deriveBits"),a=Fh.KeyObject.from(t);else if((0,R8.default)(t))a=t;else throw new TypeError((0,C8.default)(t,...N8.types));let c=(0,ld.concat)((0,ld.lengthAndInput)(ld.encoder.encode(r)),(0,ld.lengthAndInput)(i),(0,ld.lengthAndInput)(o),(0,ld.uint32be)(n)),u=(0,Fh.diffieHellman)({privateKey:a,publicKey:s});return(0,ld.concatKdf)(u,n,c)}async function jBe(e){let t;if((0,O8.isCryptoKey)(e))t=Fh.KeyObject.from(e);else if((0,R8.default)(e))t=e;else throw new TypeError((0,C8.default)(e,...N8.types));switch(t.asymmetricKeyType){case"x25519":return x8("x25519");case"x448":return x8("x448");case"ec":{let r=(0,IZ.default)(t);return x8("ec",{namedCurve:r})}default:throw new NBe.JOSENotSupported("Invalid or unsupported EPK")}}var MBe=e=>["P-256","P-384","P-521","X25519","X448"].includes((0,IZ.default)(e));zf.ecdhAllowed=MBe});var PZ=g(j8=>{"use strict";Object.defineProperty(j8,"__esModule",{value:!0});j8.default=DBe;var qBe=we();function DBe(e){if(!(e instanceof Uint8Array)||e.length<8)throw new qBe.JWEInvalid("PBES2 Salt Input must be 8 or more octets")}});var M8=g(Yf=>{"use strict";Object.defineProperty(Yf,"__esModule",{value:!0});Yf.decrypt=Yf.encrypt=void 0;var LBe=require("node:util"),TZ=require("node:crypto"),BBe=Dh(),xZ=At(),UBe=Wr(),OZ=Tv(),RZ=PZ(),HBe=li(),FBe=fc(),$Be=di(),JBe=fi(),VBe=pi(),CZ=(0,LBe.promisify)(TZ.pbkdf2);function NZ(e,t){if((0,$Be.default)(e))return e.export();if(e instanceof Uint8Array)return e;if((0,HBe.isCryptoKey)(e))return(0,FBe.checkEncCryptoKey)(e,t,"deriveBits","deriveKey"),TZ.KeyObject.from(e).export();throw new TypeError((0,JBe.default)(e,...VBe.types,"Uint8Array"))}var GBe=async(e,t,r,n=2048,i=(0,BBe.default)(new Uint8Array(16)))=>{(0,RZ.default)(i);let o=(0,xZ.p2s)(e,i),s=parseInt(e.slice(13,16),10)>>3,a=NZ(t,e),c=await CZ(a,o,n,s,`sha${e.slice(8,11)}`);return{encryptedKey:await(0,OZ.wrap)(e.slice(-6),c,r),p2c:n,p2s:(0,UBe.encode)(i)}};Yf.encrypt=GBe;var KBe=async(e,t,r,n,i)=>{(0,RZ.default)(i);let o=(0,xZ.p2s)(e,i),s=parseInt(e.slice(13,16),10)>>3,a=NZ(t,e),c=await CZ(a,o,n,s,`sha${e.slice(8,11)}`);return(0,OZ.unwrap)(e.slice(-6),c,r)};Yf.decrypt=KBe});var D8=g(q8=>{"use strict";Object.defineProperty(q8,"__esModule",{value:!0});var WBe=require("node:crypto");q8.default=(e,t)=>{let r;try{e instanceof WBe.KeyObject?r=e.asymmetricKeyDetails?.modulusLength:r=Buffer.from(e.n,"base64url").byteLength<<3}catch{}if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}});var L8=g(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});Xf.decrypt=Xf.encrypt=void 0;var $h=require("node:crypto"),zBe=require("node:util"),YBe=D8(),XBe=li(),ZBe=fc(),QBe=di(),eUe=fi(),tUe=pi(),kZ=(e,t)=>{if(e.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");(0,YBe.default)(e,t)},rUe=(0,zBe.deprecate)(()=>$h.constants.RSA_PKCS1_PADDING,'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.'),jZ=e=>{switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return $h.constants.RSA_PKCS1_OAEP_PADDING;case"RSA1_5":return rUe();default:return}},MZ=e=>{switch(e){case"RSA-OAEP":return"sha1";case"RSA-OAEP-256":return"sha256";case"RSA-OAEP-384":return"sha384";case"RSA-OAEP-512":return"sha512";default:return}};function qZ(e,t,...r){if((0,QBe.default)(e))return e;if((0,XBe.isCryptoKey)(e))return(0,ZBe.checkEncCryptoKey)(e,t,...r),$h.KeyObject.from(e);throw new TypeError((0,eUe.default)(e,...tUe.types))}var nUe=(e,t,r)=>{let n=jZ(e),i=MZ(e),o=qZ(t,e,"wrapKey","encrypt");return kZ(o,e),(0,$h.publicEncrypt)({key:o,oaepHash:i,padding:n},r)};Xf.encrypt=nUe;var iUe=(e,t,r)=>{let n=jZ(e),i=MZ(e),o=qZ(t,e,"unwrapKey","decrypt");return kZ(o,e),(0,$h.privateDecrypt)({key:o,oaepHash:i,padding:n},r)};Xf.decrypt=iUe});var U8=g(B8=>{"use strict";Object.defineProperty(B8,"__esModule",{value:!0});B8.default={}});var Jh=g(xv=>{"use strict";Object.defineProperty(xv,"__esModule",{value:!0});xv.bitLength=DZ;var oUe=we(),sUe=Dh();function DZ(e){switch(e){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new oUe.JOSENotSupported(`Unsupported JWE Algorithm: ${e}`)}}xv.default=e=>(0,sUe.default)(new Uint8Array(DZ(e)>>3))});var Rv=g(mi=>{"use strict";Object.defineProperty(mi,"__esModule",{value:!0});mi.fromX509=mi.fromSPKI=mi.fromPKCS8=mi.toPKCS8=mi.toSPKI=void 0;var Ov=require("node:crypto"),LZ=require("node:buffer"),aUe=li(),cUe=di(),uUe=fi(),dUe=pi(),BZ=(e,t,r)=>{let n;if((0,aUe.isCryptoKey)(r)){if(!r.extractable)throw new TypeError("CryptoKey is not extractable");n=Ov.KeyObject.from(r)}else if((0,cUe.default)(r))n=r;else throw new TypeError((0,uUe.default)(r,...dUe.types));if(n.type!==e)throw new TypeError(`key is not a ${e} key`);return n.export({format:"pem",type:t})},lUe=e=>BZ("public","spki",e);mi.toSPKI=lUe;var fUe=e=>BZ("private","pkcs8",e);mi.toPKCS8=fUe;var pUe=e=>(0,Ov.createPrivateKey)({key:LZ.Buffer.from(e.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,""),"base64"),type:"pkcs8",format:"der"});mi.fromPKCS8=pUe;var mUe=e=>(0,Ov.createPublicKey)({key:LZ.Buffer.from(e.replace(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,""),"base64"),type:"spki",format:"der"});mi.fromSPKI=mUe;var gUe=e=>(0,Ov.createPublicKey)({key:e,type:"spki",format:"pem"});mi.fromX509=gUe});var HZ=g(H8=>{"use strict";Object.defineProperty(H8,"__esModule",{value:!0});var UZ=require("node:crypto"),hUe=e=>e.d?(0,UZ.createPrivateKey)({format:"jwk",key:e}):(0,UZ.createPublicKey)({format:"jwk",key:e});H8.default=hUe});var Qf=g(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});Zf.importSPKI=EUe;Zf.importX509=wUe;Zf.importPKCS8=vUe;Zf.importJWK=SUe;var yUe=Wr(),F8=Rv(),_Ue=HZ(),FZ=we(),bUe=kr();async function EUe(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return(0,F8.fromSPKI)(e,t,r)}async function wUe(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return(0,F8.fromX509)(e,t,r)}async function vUe(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return(0,F8.fromPKCS8)(e,t,r)}async function SUe(e,t){if(!(0,bUe.default)(e))throw new TypeError("JWK must be an object");switch(t||=e.alg,e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return(0,yUe.decode)(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new FZ.JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return(0,_Ue.default)({...e,alg:t});default:throw new FZ.JOSENotSupported('Unsupported "kty" (Key Type) Parameter value')}}});var Kh=g(Gh=>{"use strict";Object.defineProperty(Gh,"__esModule",{value:!0});Gh.checkKeyTypeWithJwk=void 0;var $Z=fi(),Cv=pi(),Vh=Uh(),ep=e=>e?.[Symbol.toStringTag],$8=(e,t,r)=>{if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&t.key_ops.includes?.(r)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},AUe=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&Vh.isJWK(t)){if(Vh.isSecretJWK(t)&&$8(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!(0,Cv.default)(t))throw new TypeError((0,$Z.withAlg)(e,t,...Cv.types,"Uint8Array",n?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${ep(t)} instances for symmetric algorithms must be of type "secret"`)}},IUe=(e,t,r,n)=>{if(n&&Vh.isJWK(t))switch(r){case"sign":if(Vh.isPrivateJWK(t)&&$8(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Vh.isPublicJWK(t)&&$8(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!(0,Cv.default)(t))throw new TypeError((0,$Z.withAlg)(e,t,...Cv.types,n?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${ep(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${ep(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${ep(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${ep(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${ep(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function JZ(e,t,r,n){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?AUe(t,r,n,e):IUe(t,r,n,e)}Gh.default=JZ.bind(void 0,!1);Gh.checkKeyTypeWithJwk=JZ.bind(void 0,!0)});var K8=g(G8=>{"use strict";Object.defineProperty(G8,"__esModule",{value:!0});var J8=require("node:crypto"),PUe=p8(),TUe=y8(),xUe=At(),OUe=E8(),RUe=li(),CUe=fc(),VZ=di(),NUe=fi(),kUe=l8(),V8=we(),GZ=Iv(),jUe=pi();function MUe(e,t,r,n,i){let o=parseInt(e.slice(1,4),10);(0,VZ.default)(r)&&(r=r.export());let s=r.subarray(o>>3),a=r.subarray(0,o>>3),c=`aes-${o}-cbc`;if(!(0,GZ.default)(c))throw new V8.JOSENotSupported(`alg ${e} is not supported by your javascript runtime`);let u=(0,J8.createCipheriv)(c,s,n),d=(0,xUe.concat)(u.update(t),u.final()),l=parseInt(e.slice(-3),10),m=(0,OUe.default)(i,n,d,l,a,o);return{ciphertext:d,tag:m,iv:n}}function qUe(e,t,r,n,i){let s=`aes-${parseInt(e.slice(1,4),10)}-gcm`;if(!(0,GZ.default)(s))throw new V8.JOSENotSupported(`alg ${e} is not supported by your javascript runtime`);let a=(0,J8.createCipheriv)(s,r,n,{authTagLength:16});i.byteLength&&a.setAAD(i,{plaintextLength:t.length});let c=a.update(t);a.final();let u=a.getAuthTag();return{ciphertext:c,tag:u,iv:n}}var DUe=(e,t,r,n,i)=>{let o;if((0,RUe.isCryptoKey)(r))(0,CUe.checkEncCryptoKey)(r,e,"encrypt"),o=J8.KeyObject.from(r);else if(r instanceof Uint8Array||(0,VZ.default)(r))o=r;else throw new TypeError((0,NUe.default)(r,...jUe.types,"Uint8Array"));switch((0,TUe.default)(e,o),n?(0,PUe.default)(e,n):n=(0,kUe.default)(e),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return MUe(e,t,o,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return qUe(e,t,o,n,i);default:throw new V8.JOSENotSupported("Unsupported JWE Content Encryption Algorithm")}};G8.default=DUe});var W8=g(Nv=>{"use strict";Object.defineProperty(Nv,"__esModule",{value:!0});Nv.wrap=UUe;Nv.unwrap=HUe;var LUe=K8(),BUe=A8(),KZ=Wr();async function UUe(e,t,r,n){let i=e.slice(0,7),o=await(0,LUe.default)(i,r,t,n,new Uint8Array(0));return{encryptedKey:o.ciphertext,iv:(0,KZ.encode)(o.iv),tag:(0,KZ.encode)(o.tag)}}async function HUe(e,t,r,n,i){let o=e.slice(0,7);return(0,BUe.default)(o,t,r,n,i,new Uint8Array(0))}});var YZ=g(z8=>{"use strict";Object.defineProperty(z8,"__esModule",{value:!0});var WZ=Tv(),zZ=k8(),FUe=M8(),$Ue=L8(),Wh=Wr(),JUe=U8(),It=we(),VUe=Jh(),GUe=Qf(),KUe=Kh(),WUe=kr(),zUe=W8();async function YUe(e,t,r,n,i){switch((0,KUe.default)(e,t,"decrypt"),t=await JUe.default.normalizePrivateKey?.(t,e)||t,e){case"dir":{if(r!==void 0)throw new It.JWEInvalid("Encountered unexpected JWE Encrypted Key");return t}case"ECDH-ES":if(r!==void 0)throw new It.JWEInvalid("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!(0,WUe.default)(n.epk))throw new It.JWEInvalid('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!zZ.ecdhAllowed(t))throw new It.JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");let o=await(0,GUe.importJWK)(n.epk,e),s,a;if(n.apu!==void 0){if(typeof n.apu!="string")throw new It.JWEInvalid('JOSE Header "apu" (Agreement PartyUInfo) invalid');try{s=(0,Wh.decode)(n.apu)}catch{throw new It.JWEInvalid("Failed to base64url decode the apu")}}if(n.apv!==void 0){if(typeof n.apv!="string")throw new It.JWEInvalid('JOSE Header "apv" (Agreement PartyVInfo) invalid');try{a=(0,Wh.decode)(n.apv)}catch{throw new It.JWEInvalid("Failed to base64url decode the apv")}}let c=await zZ.deriveKey(o,t,e==="ECDH-ES"?n.enc:e,e==="ECDH-ES"?(0,VUe.bitLength)(n.enc):parseInt(e.slice(-5,-2),10),s,a);if(e==="ECDH-ES")return c;if(r===void 0)throw new It.JWEInvalid("JWE Encrypted Key missing");return(0,WZ.unwrap)(e.slice(-6),c,r)}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(r===void 0)throw new It.JWEInvalid("JWE Encrypted Key missing");return(0,$Ue.decrypt)(e,t,r)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(r===void 0)throw new It.JWEInvalid("JWE Encrypted Key missing");if(typeof n.p2c!="number")throw new It.JWEInvalid('JOSE Header "p2c" (PBES2 Count) missing or invalid');let o=i?.maxPBES2Count||1e4;if(n.p2c>o)throw new It.JWEInvalid('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new It.JWEInvalid('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let s;try{s=(0,Wh.decode)(n.p2s)}catch{throw new It.JWEInvalid("Failed to base64url decode the p2s")}return(0,FUe.decrypt)(e,t,r,n.p2c,s)}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new It.JWEInvalid("JWE Encrypted Key missing");return(0,WZ.unwrap)(e,t,r)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(r===void 0)throw new It.JWEInvalid("JWE Encrypted Key missing");if(typeof n.iv!="string")throw new It.JWEInvalid('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new It.JWEInvalid('JOSE Header "tag" (Authentication Tag) missing or invalid');let o;try{o=(0,Wh.decode)(n.iv)}catch{throw new It.JWEInvalid("Failed to base64url decode the iv")}let s;try{s=(0,Wh.decode)(n.tag)}catch{throw new It.JWEInvalid("Failed to base64url decode the tag")}return(0,zUe.unwrap)(e,t,r,o,s)}default:throw new It.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value')}}z8.default=YUe});var tp=g(Y8=>{"use strict";Object.defineProperty(Y8,"__esModule",{value:!0});var XUe=we();function ZUe(e,t,r,n,i){if(i.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;r!==void 0?o=new Map([...Object.entries(r),...t.entries()]):o=t;for(let s of n.crit){if(!o.has(s))throw new XUe.JOSENotSupported(`Extension Header Parameter "${s}" is not recognized`);if(i[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(o.get(s)&&n[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(n.crit)}Y8.default=ZUe});var Z8=g(X8=>{"use strict";Object.defineProperty(X8,"__esModule",{value:!0});var QUe=(e,t)=>{if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)};X8.default=QUe});var kv=g(eq=>{"use strict";Object.defineProperty(eq,"__esModule",{value:!0});eq.flattenedDecrypt=oHe;var rp=Wr(),eHe=A8(),ut=we(),tHe=Gf(),Q8=kr(),rHe=YZ(),zh=At(),nHe=Jh(),iHe=tp(),XZ=Z8();async function oHe(e,t,r){if(!(0,Q8.default)(e))throw new ut.JWEInvalid("Flattened JWE must be an object");if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new ut.JWEInvalid("JOSE Header missing");if(e.iv!==void 0&&typeof e.iv!="string")throw new ut.JWEInvalid("JWE Initialization Vector incorrect type");if(typeof e.ciphertext!="string")throw new ut.JWEInvalid("JWE Ciphertext missing or incorrect type");if(e.tag!==void 0&&typeof e.tag!="string")throw new ut.JWEInvalid("JWE Authentication Tag incorrect type");if(e.protected!==void 0&&typeof e.protected!="string")throw new ut.JWEInvalid("JWE Protected Header incorrect type");if(e.encrypted_key!==void 0&&typeof e.encrypted_key!="string")throw new ut.JWEInvalid("JWE Encrypted Key incorrect type");if(e.aad!==void 0&&typeof e.aad!="string")throw new ut.JWEInvalid("JWE AAD incorrect type");if(e.header!==void 0&&!(0,Q8.default)(e.header))throw new ut.JWEInvalid("JWE Shared Unprotected Header incorrect type");if(e.unprotected!==void 0&&!(0,Q8.default)(e.unprotected))throw new ut.JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type");let n;if(e.protected)try{let E=(0,rp.decode)(e.protected);n=JSON.parse(zh.decoder.decode(E))}catch{throw new ut.JWEInvalid("JWE Protected Header is invalid")}if(!(0,tHe.default)(n,e.header,e.unprotected))throw new ut.JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let i={...n,...e.header,...e.unprotected};if((0,iHe.default)(ut.JWEInvalid,new Map,r?.crit,n,i),i.zip!==void 0)throw new ut.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');let{alg:o,enc:s}=i;if(typeof o!="string"||!o)throw new ut.JWEInvalid("missing JWE Algorithm (alg) in JWE Header");if(typeof s!="string"||!s)throw new ut.JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header");let a=r&&(0,XZ.default)("keyManagementAlgorithms",r.keyManagementAlgorithms),c=r&&(0,XZ.default)("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(a&&!a.has(o)||!a&&o.startsWith("PBES2"))throw new ut.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');if(c&&!c.has(s))throw new ut.JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed');let u;if(e.encrypted_key!==void 0)try{u=(0,rp.decode)(e.encrypted_key)}catch{throw new ut.JWEInvalid("Failed to base64url decode the encrypted_key")}let d=!1;typeof t=="function"&&(t=await t(n,e),d=!0);let l;try{l=await(0,rHe.default)(o,t,u,i,r)}catch(E){if(E instanceof TypeError||E instanceof ut.JWEInvalid||E instanceof ut.JOSENotSupported)throw E;l=(0,nHe.default)(s)}let m,p;if(e.iv!==void 0)try{m=(0,rp.decode)(e.iv)}catch{throw new ut.JWEInvalid("Failed to base64url decode the iv")}if(e.tag!==void 0)try{p=(0,rp.decode)(e.tag)}catch{throw new ut.JWEInvalid("Failed to base64url decode the tag")}let h=zh.encoder.encode(e.protected??""),y;e.aad!==void 0?y=(0,zh.concat)(h,zh.encoder.encode("."),zh.encoder.encode(e.aad)):y=h;let b;try{b=(0,rp.decode)(e.ciphertext)}catch{throw new ut.JWEInvalid("Failed to base64url decode the ciphertext")}let A={plaintext:await(0,eHe.default)(s,l,b,m,p,y)};if(e.protected!==void 0&&(A.protectedHeader=n),e.aad!==void 0)try{A.additionalAuthenticatedData=(0,rp.decode)(e.aad)}catch{throw new ut.JWEInvalid("Failed to base64url decode the aad")}return e.unprotected!==void 0&&(A.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(A.unprotectedHeader=e.header),d?{...A,key:t}:A}});var rq=g(tq=>{"use strict";Object.defineProperty(tq,"__esModule",{value:!0});tq.compactDecrypt=cHe;var sHe=kv(),ZZ=we(),aHe=At();async function cHe(e,t,r){if(e instanceof Uint8Array&&(e=aHe.decoder.decode(e)),typeof e!="string")throw new ZZ.JWEInvalid("Compact JWE must be a string or Uint8Array");let{0:n,1:i,2:o,3:s,4:a,length:c}=e.split(".");if(c!==5)throw new ZZ.JWEInvalid("Invalid Compact JWE");let u=await(0,sHe.flattenedDecrypt)({ciphertext:s,iv:o||void 0,protected:n,tag:a||void 0,encrypted_key:i||void 0},t,r),d={plaintext:u.plaintext,protectedHeader:u.protectedHeader};return typeof t=="function"?{...d,key:u.key}:d}});var eQ=g(nq=>{"use strict";Object.defineProperty(nq,"__esModule",{value:!0});nq.generalDecrypt=dHe;var uHe=kv(),jv=we(),QZ=kr();async function dHe(e,t,r){if(!(0,QZ.default)(e))throw new jv.JWEInvalid("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(QZ.default))throw new jv.JWEInvalid("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new jv.JWEInvalid("JWE Recipients has no members");for(let n of e.recipients)try{return await(0,uHe.flattenedDecrypt)({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,r)}catch{}throw new jv.JWEDecryptionFailed}});var iq=g(Mv=>{"use strict";Object.defineProperty(Mv,"__esModule",{value:!0});Mv.unprotected=void 0;Mv.unprotected=Symbol()});var tQ=g(oq=>{"use strict";Object.defineProperty(oq,"__esModule",{value:!0});var lHe=require("node:crypto"),fHe=Wr(),pHe=we(),mHe=li(),gHe=di(),hHe=fi(),yHe=pi(),_He=e=>{let t;if((0,mHe.isCryptoKey)(e)){if(!e.extractable)throw new TypeError("CryptoKey is not extractable");t=lHe.KeyObject.from(e)}else if((0,gHe.default)(e))t=e;else{if(e instanceof Uint8Array)return{kty:"oct",k:(0,fHe.encode)(e)};throw new TypeError((0,hHe.default)(e,...yHe.types,"Uint8Array"))}if(t.type!=="secret"&&!["rsa","ec","ed25519","x25519","ed448","x448"].includes(t.asymmetricKeyType))throw new pHe.JOSENotSupported("Unsupported key asymmetricKeyType");return t.export({format:"jwk"})};oq.default=_He});var sq=g(Yh=>{"use strict";Object.defineProperty(Yh,"__esModule",{value:!0});Yh.exportSPKI=vHe;Yh.exportPKCS8=SHe;Yh.exportJWK=AHe;var bHe=Rv(),EHe=Rv(),wHe=tQ();async function vHe(e){return(0,bHe.toSPKI)(e)}async function SHe(e){return(0,EHe.toPKCS8)(e)}async function AHe(e){return(0,wHe.default)(e)}});var uq=g(cq=>{"use strict";Object.defineProperty(cq,"__esModule",{value:!0});var rQ=Tv(),aq=k8(),IHe=M8(),PHe=L8(),nQ=Wr(),THe=U8(),np=Jh(),iQ=we(),xHe=sq(),OHe=Kh(),RHe=W8();async function CHe(e,t,r,n,i={}){let o,s,a;switch((0,OHe.default)(e,r,"encrypt"),r=await THe.default.normalizePublicKey?.(r,e)||r,e){case"dir":{a=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!aq.ecdhAllowed(r))throw new iQ.JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:c,apv:u}=i,{epk:d}=i;d||=(await aq.generateEpk(r)).privateKey;let{x:l,y:m,crv:p,kty:h}=await(0,xHe.exportJWK)(d),y=await aq.deriveKey(r,d,e==="ECDH-ES"?t:e,e==="ECDH-ES"?(0,np.bitLength)(t):parseInt(e.slice(-5,-2),10),c,u);if(s={epk:{x:l,crv:p,kty:h}},h==="EC"&&(s.epk.y=m),c&&(s.apu=(0,nQ.encode)(c)),u&&(s.apv=(0,nQ.encode)(u)),e==="ECDH-ES"){a=y;break}a=n||(0,np.default)(t);let b=e.slice(-6);o=await(0,rQ.wrap)(b,y,a);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{a=n||(0,np.default)(t),o=await(0,PHe.encrypt)(e,r,a);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{a=n||(0,np.default)(t);let{p2c:c,p2s:u}=i;({encryptedKey:o,...s}=await(0,IHe.encrypt)(e,r,a,c,u));break}case"A128KW":case"A192KW":case"A256KW":{a=n||(0,np.default)(t),o=await(0,rQ.wrap)(e,r,a);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{a=n||(0,np.default)(t);let{iv:c}=i;({encryptedKey:o,...s}=await(0,RHe.wrap)(e,r,a,c));break}default:throw new iQ.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:a,encryptedKey:o,parameters:s}}cq.default=CHe});var Dv=g(qv=>{"use strict";Object.defineProperty(qv,"__esModule",{value:!0});qv.FlattenedEncrypt=void 0;var ip=Wr(),NHe=iq(),kHe=K8(),jHe=uq(),op=we(),MHe=Gf(),sp=At(),qHe=tp(),dq=class{_plaintext;_protectedHeader;_sharedUnprotectedHeader;_unprotectedHeader;_aad;_cek;_iv;_keyManagementParameters;constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=t}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}async encrypt(t,r){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new op.JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!(0,MHe.default)(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new op.JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if((0,qHe.default)(op.JWEInvalid,new Map,r?.crit,this._protectedHeader,n),n.zip!==void 0)throw new op.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');let{alg:i,enc:o}=n;if(typeof i!="string"||!i)throw new op.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof o!="string"||!o)throw new op.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let s;if(this._cek&&(i==="dir"||i==="ECDH-ES"))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${i}`);let a;{let y;({cek:a,encryptedKey:s,parameters:y}=await(0,jHe.default)(i,o,t,this._cek,this._keyManagementParameters)),y&&(r&&NHe.unprotected in r?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...y}:this.setUnprotectedHeader(y):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...y}:this.setProtectedHeader(y))}let c,u,d;this._protectedHeader?u=sp.encoder.encode((0,ip.encode)(JSON.stringify(this._protectedHeader))):u=sp.encoder.encode(""),this._aad?(d=(0,ip.encode)(this._aad),c=(0,sp.concat)(u,sp.encoder.encode("."),sp.encoder.encode(d))):c=u;let{ciphertext:l,tag:m,iv:p}=await(0,kHe.default)(o,this._plaintext,a,this._iv,c),h={ciphertext:(0,ip.encode)(l)};return p&&(h.iv=(0,ip.encode)(p)),m&&(h.tag=(0,ip.encode)(m)),s&&(h.encrypted_key=(0,ip.encode)(s)),d&&(h.aad=d),this._protectedHeader&&(h.protected=sp.decoder.decode(u)),this._sharedUnprotectedHeader&&(h.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(h.header=this._unprotectedHeader),h}};qv.FlattenedEncrypt=dq});var sQ=g(Lv=>{"use strict";Object.defineProperty(Lv,"__esModule",{value:!0});Lv.GeneralEncrypt=void 0;var oQ=Dv(),DHe=iq(),mc=we(),LHe=Jh(),BHe=Gf(),UHe=uq(),HHe=Wr(),FHe=tp(),lq=class{parent;unprotectedHeader;key;options;constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addRecipient(...t){return this.parent.addRecipient(...t)}encrypt(...t){return this.parent.encrypt(...t)}done(){return this.parent}},fq=class{_plaintext;_recipients=[];_protectedHeader;_unprotectedHeader;_aad;constructor(t){this._plaintext=t}addRecipient(t,r){let n=new lq(this,t,{crit:r?.crit});return this._recipients.push(n),n}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}async encrypt(){if(!this._recipients.length)throw new mc.JWEInvalid("at least one recipient must be added");if(this._recipients.length===1){let[i]=this._recipients,o=await new oQ.FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(i.unprotectedHeader).encrypt(i.key,{...i.options}),s={ciphertext:o.ciphertext,iv:o.iv,recipients:[{}],tag:o.tag};return o.aad&&(s.aad=o.aad),o.protected&&(s.protected=o.protected),o.unprotected&&(s.unprotected=o.unprotected),o.encrypted_key&&(s.recipients[0].encrypted_key=o.encrypted_key),o.header&&(s.recipients[0].header=o.header),s}let t;for(let i=0;i<this._recipients.length;i++){let o=this._recipients[i];if(!(0,BHe.default)(this._protectedHeader,this._unprotectedHeader,o.unprotectedHeader))throw new mc.JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let s={...this._protectedHeader,...this._unprotectedHeader,...o.unprotectedHeader},{alg:a}=s;if(typeof a!="string"||!a)throw new mc.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(a==="dir"||a==="ECDH-ES")throw new mc.JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient');if(typeof s.enc!="string"||!s.enc)throw new mc.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(!t)t=s.enc;else if(t!==s.enc)throw new mc.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');if((0,FHe.default)(mc.JWEInvalid,new Map,o.options.crit,this._protectedHeader,s),s.zip!==void 0)throw new mc.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.')}let r=(0,LHe.default)(t),n={ciphertext:"",iv:"",recipients:[],tag:""};for(let i=0;i<this._recipients.length;i++){let o=this._recipients[i],s={};n.recipients.push(s);let c={...this._protectedHeader,...this._unprotectedHeader,...o.unprotectedHeader}.alg.startsWith("PBES2")?2048+i:void 0;if(i===0){let l=await new oQ.FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(r).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(o.unprotectedHeader).setKeyManagementParameters({p2c:c}).encrypt(o.key,{...o.options,[DHe.unprotected]:!0});n.ciphertext=l.ciphertext,n.iv=l.iv,n.tag=l.tag,l.aad&&(n.aad=l.aad),l.protected&&(n.protected=l.protected),l.unprotected&&(n.unprotected=l.unprotected),s.encrypted_key=l.encrypted_key,l.header&&(s.header=l.header);continue}let{encryptedKey:u,parameters:d}=await(0,UHe.default)(o.unprotectedHeader?.alg||this._protectedHeader?.alg||this._unprotectedHeader?.alg,t,o.key,r,{p2c:c});s.encrypted_key=(0,HHe.encode)(u),(o.unprotectedHeader||d)&&(s.header={...o.unprotectedHeader,...d})}return n}};Lv.GeneralEncrypt=fq});var mq=g(pq=>{"use strict";Object.defineProperty(pq,"__esModule",{value:!0});pq.default=JHe;var $He=we();function JHe(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"Ed25519":case"EdDSA":return;default:throw new $He.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}});var yq=g(hq=>{"use strict";Object.defineProperty(hq,"__esModule",{value:!0});hq.default=WHe;var gq=require("node:crypto"),VHe=T8(),GHe=we(),aQ=D8(),KHe=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function WHe(e,t){let r,n,i;if(t instanceof gq.KeyObject)r=t.asymmetricKeyType,n=t.asymmetricKeyDetails;else switch(i=!0,t.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":{if(t.crv==="Ed25519"){r="ed25519";break}if(t.crv==="Ed448"){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448")}default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}let o;switch(e){case"Ed25519":if(r!=="ed25519")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");(0,aQ.default)(t,e);break;case"PS256":case"PS384":case"PS512":if(r==="rsa-pss"){let{hashAlgorithm:s,mgf1HashAlgorithm:a,saltLength:c}=n,u=parseInt(e.slice(-3),10);if(s!==void 0&&(s!==`sha${u}`||a!==s))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(c!==void 0&&c>u>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(r!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");(0,aQ.default)(t,e),o={padding:gq.constants.RSA_PKCS1_PSS_PADDING,saltLength:gq.constants.RSA_PSS_SALTLEN_DIGEST};break;case"ES256":case"ES256K":case"ES384":case"ES512":{if(r!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let s=(0,VHe.default)(t),a=KHe.get(e);if(s!==a)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${a}, got ${s}`);o={dsaEncoding:"ieee-p1363"};break}default:throw new GHe.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return i?{format:"jwk",key:t,...o}:o?{...o,key:t}:t}});var cQ=g(_q=>{"use strict";Object.defineProperty(_q,"__esModule",{value:!0});_q.default=YHe;var zHe=we();function YHe(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new zHe.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}});var Eq=g(bq=>{"use strict";Object.defineProperty(bq,"__esModule",{value:!0});bq.default=e9e;var Bv=require("node:crypto"),XHe=li(),ZHe=fc(),uQ=fi(),dQ=pi(),QHe=Uh();function e9e(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError((0,uQ.default)(t,...dQ.types));return(0,Bv.createSecretKey)(t)}if(t instanceof Bv.KeyObject)return t;if((0,XHe.isCryptoKey)(t))return(0,ZHe.checkSigCryptoKey)(t,e,r),Bv.KeyObject.from(t);if(QHe.isJWK(t))return e.startsWith("HS")?(0,Bv.createSecretKey)(Buffer.from(t.k,"base64url")):t;throw new TypeError((0,uQ.default)(t,...dQ.types,"Uint8Array","JSON Web Key"))}});var vq=g(wq=>{"use strict";Object.defineProperty(wq,"__esModule",{value:!0});var lQ=require("node:crypto"),t9e=require("node:util"),r9e=mq(),n9e=cQ(),i9e=yq(),o9e=Eq(),s9e=(0,t9e.promisify)(lQ.sign),a9e=async(e,t,r)=>{let n=(0,o9e.default)(e,t,"sign");if(e.startsWith("HS")){let i=lQ.createHmac((0,n9e.default)(e),n);return i.update(r),i.digest()}return s9e((0,r9e.default)(e),r,(0,i9e.default)(e,n))};wq.default=a9e});var pQ=g(Sq=>{"use strict";Object.defineProperty(Sq,"__esModule",{value:!0});var fQ=require("node:crypto"),c9e=require("node:util"),u9e=mq(),d9e=yq(),l9e=vq(),f9e=Eq(),p9e=(0,c9e.promisify)(fQ.verify),m9e=async(e,t,r,n)=>{let i=(0,f9e.default)(e,t,"verify");if(e.startsWith("HS")){let a=await(0,l9e.default)(e,i,n),c=r;try{return fQ.timingSafeEqual(c,a)}catch{return!1}}let o=(0,u9e.default)(e),s=(0,d9e.default)(e,i);try{return await p9e(o,n,s,r)}catch{return!1}};Sq.default=m9e});var Uv=g(Iq=>{"use strict";Object.defineProperty(Iq,"__esModule",{value:!0});Iq.flattenedVerify=w9e;var Aq=Wr(),g9e=pQ(),yr=we(),ap=At(),h9e=Gf(),mQ=kr(),gQ=Kh(),y9e=tp(),_9e=Z8(),b9e=Uh(),E9e=Qf();async function w9e(e,t,r){if(!(0,mQ.default)(e))throw new yr.JWSInvalid("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new yr.JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new yr.JWSInvalid("JWS Protected Header incorrect type");if(e.payload===void 0)throw new yr.JWSInvalid("JWS Payload missing");if(typeof e.signature!="string")throw new yr.JWSInvalid("JWS Signature missing or incorrect type");if(e.header!==void 0&&!(0,mQ.default)(e.header))throw new yr.JWSInvalid("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{let y=(0,Aq.decode)(e.protected);n=JSON.parse(ap.decoder.decode(y))}catch{throw new yr.JWSInvalid("JWS Protected Header is invalid")}if(!(0,h9e.default)(n,e.header))throw new yr.JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let i={...n,...e.header},o=(0,y9e.default)(yr.JWSInvalid,new Map([["b64",!0]]),r?.crit,n,i),s=!0;if(o.has("b64")&&(s=n.b64,typeof s!="boolean"))throw new yr.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=i;if(typeof a!="string"||!a)throw new yr.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');let c=r&&(0,_9e.default)("algorithms",r.algorithms);if(c&&!c.has(a))throw new yr.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');if(s){if(typeof e.payload!="string")throw new yr.JWSInvalid("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new yr.JWSInvalid("JWS Payload must be a string or an Uint8Array instance");let u=!1;typeof t=="function"?(t=await t(n,e),u=!0,(0,gQ.checkKeyTypeWithJwk)(a,t,"verify"),(0,b9e.isJWK)(t)&&(t=await(0,E9e.importJWK)(t,a))):(0,gQ.checkKeyTypeWithJwk)(a,t,"verify");let d=(0,ap.concat)(ap.encoder.encode(e.protected??""),ap.encoder.encode("."),typeof e.payload=="string"?ap.encoder.encode(e.payload):e.payload),l;try{l=(0,Aq.decode)(e.signature)}catch{throw new yr.JWSInvalid("Failed to base64url decode the signature")}if(!await(0,g9e.default)(a,t,l,d))throw new yr.JWSSignatureVerificationFailed;let p;if(s)try{p=(0,Aq.decode)(e.payload)}catch{throw new yr.JWSInvalid("Failed to base64url decode the payload")}else typeof e.payload=="string"?p=ap.encoder.encode(e.payload):p=e.payload;let h={payload:p};return e.protected!==void 0&&(h.protectedHeader=n),e.header!==void 0&&(h.unprotectedHeader=e.header),u?{...h,key:t}:h}});var Tq=g(Pq=>{"use strict";Object.defineProperty(Pq,"__esModule",{value:!0});Pq.compactVerify=A9e;var v9e=Uv(),hQ=we(),S9e=At();async function A9e(e,t,r){if(e instanceof Uint8Array&&(e=S9e.decoder.decode(e)),typeof e!="string")throw new hQ.JWSInvalid("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:o,length:s}=e.split(".");if(s!==3)throw new hQ.JWSInvalid("Invalid Compact JWS");let a=await(0,v9e.flattenedVerify)({payload:i,protected:n,signature:o},t,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof t=="function"?{...c,key:a.key}:c}});var _Q=g(Oq=>{"use strict";Object.defineProperty(Oq,"__esModule",{value:!0});Oq.generalVerify=P9e;var I9e=Uv(),xq=we(),yQ=kr();async function P9e(e,t,r){if(!(0,yQ.default)(e))throw new xq.JWSInvalid("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(yQ.default))throw new xq.JWSInvalid("JWS Signatures missing or incorrect type");for(let n of e.signatures)try{return await(0,I9e.flattenedVerify)({header:n.header,payload:e.payload,protected:n.protected,signature:n.signature},t,r)}catch{}throw new xq.JWSSignatureVerificationFailed}});var Cq=g(Rq=>{"use strict";Object.defineProperty(Rq,"__esModule",{value:!0});Rq.default=e=>Math.floor(e.getTime()/1e3)});var jq=g(kq=>{"use strict";Object.defineProperty(kq,"__esModule",{value:!0});var bQ=60,EQ=bQ*60,Nq=EQ*24,T9e=Nq*7,x9e=Nq*365.25,O9e=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;kq.default=e=>{let t=O9e.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),i;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":i=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":i=Math.round(r*bQ);break;case"hour":case"hours":case"hr":case"hrs":case"h":i=Math.round(r*EQ);break;case"day":case"days":case"d":i=Math.round(r*Nq);break;case"week":case"weeks":case"w":i=Math.round(r*T9e);break;default:i=Math.round(r*x9e);break}return t[1]==="-"||t[4]==="ago"?-i:i}});var Hv=g(Mq=>{"use strict";Object.defineProperty(Mq,"__esModule",{value:!0});var Bn=we(),R9e=At(),C9e=Cq(),wQ=jq(),N9e=kr(),vQ=e=>e.toLowerCase().replace(/^application\//,""),k9e=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;Mq.default=(e,t,r={})=>{let n;try{n=JSON.parse(R9e.decoder.decode(t))}catch{}if(!(0,N9e.default)(n))throw new Bn.JWTInvalid("JWT Claims Set must be a top-level JSON object");let{typ:i}=r;if(i&&(typeof e.typ!="string"||vQ(e.typ)!==vQ(i)))throw new Bn.JWTClaimValidationFailed('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:o=[],issuer:s,subject:a,audience:c,maxTokenAge:u}=r,d=[...o];u!==void 0&&d.push("iat"),c!==void 0&&d.push("aud"),a!==void 0&&d.push("sub"),s!==void 0&&d.push("iss");for(let h of new Set(d.reverse()))if(!(h in n))throw new Bn.JWTClaimValidationFailed(`missing required "${h}" claim`,n,h,"missing");if(s&&!(Array.isArray(s)?s:[s]).includes(n.iss))throw new Bn.JWTClaimValidationFailed('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new Bn.JWTClaimValidationFailed('unexpected "sub" claim value',n,"sub","check_failed");if(c&&!k9e(n.aud,typeof c=="string"?[c]:c))throw new Bn.JWTClaimValidationFailed('unexpected "aud" claim value',n,"aud","check_failed");let l;switch(typeof r.clockTolerance){case"string":l=(0,wQ.default)(r.clockTolerance);break;case"number":l=r.clockTolerance;break;case"undefined":l=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:m}=r,p=(0,C9e.default)(m||new Date);if((n.iat!==void 0||u)&&typeof n.iat!="number")throw new Bn.JWTClaimValidationFailed('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new Bn.JWTClaimValidationFailed('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>p+l)throw new Bn.JWTClaimValidationFailed('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new Bn.JWTClaimValidationFailed('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=p-l)throw new Bn.JWTExpired('"exp" claim timestamp check failed',n,"exp","check_failed")}if(u){let h=p-n.iat,y=typeof u=="number"?u:(0,wQ.default)(u);if(h-l>y)throw new Bn.JWTExpired('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(h<0-l)throw new Bn.JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}});var SQ=g(qq=>{"use strict";Object.defineProperty(qq,"__esModule",{value:!0});qq.jwtVerify=D9e;var j9e=Tq(),M9e=Hv(),q9e=we();async function D9e(e,t,r){let n=await(0,j9e.compactVerify)(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new q9e.JWTInvalid("JWTs MUST NOT use unencoded payload");let o={payload:(0,M9e.default)(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...o,key:n.key}:o}});var AQ=g(Lq=>{"use strict";Object.defineProperty(Lq,"__esModule",{value:!0});Lq.jwtDecrypt=U9e;var L9e=rq(),B9e=Hv(),Dq=we();async function U9e(e,t,r){let n=await(0,L9e.compactDecrypt)(e,t,r),i=(0,B9e.default)(n.protectedHeader,n.plaintext,r),{protectedHeader:o}=n;if(o.iss!==void 0&&o.iss!==i.iss)throw new Dq.JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch',i,"iss","mismatch");if(o.sub!==void 0&&o.sub!==i.sub)throw new Dq.JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch',i,"sub","mismatch");if(o.aud!==void 0&&JSON.stringify(o.aud)!==JSON.stringify(i.aud))throw new Dq.JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch',i,"aud","mismatch");let s={payload:i,protectedHeader:o};return typeof t=="function"?{...s,key:n.key}:s}});var Uq=g(Fv=>{"use strict";Object.defineProperty(Fv,"__esModule",{value:!0});Fv.CompactEncrypt=void 0;var H9e=Dv(),Bq=class{_flattened;constructor(t){this._flattened=new H9e.FlattenedEncrypt(t)}setContentEncryptionKey(t){return this._flattened.setContentEncryptionKey(t),this}setInitializationVector(t){return this._flattened.setInitializationVector(t),this}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}setKeyManagementParameters(t){return this._flattened.setKeyManagementParameters(t),this}async encrypt(t,r){let n=await this._flattened.encrypt(t,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}};Fv.CompactEncrypt=Bq});var Jv=g($v=>{"use strict";Object.defineProperty($v,"__esModule",{value:!0});$v.FlattenedSign=void 0;var Hq=Wr(),F9e=vq(),$9e=Gf(),Xh=we(),fd=At(),J9e=Kh(),V9e=tp(),Fq=class{_payload;_protectedHeader;_unprotectedHeader;constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new Xh.JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!(0,$9e.default)(this._protectedHeader,this._unprotectedHeader))throw new Xh.JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},i=(0,V9e.default)(Xh.JWSInvalid,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),o=!0;if(i.has("b64")&&(o=this._protectedHeader.b64,typeof o!="boolean"))throw new Xh.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=n;if(typeof s!="string"||!s)throw new Xh.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');(0,J9e.checkKeyTypeWithJwk)(s,t,"sign");let a=this._payload;o&&(a=fd.encoder.encode((0,Hq.encode)(a)));let c;this._protectedHeader?c=fd.encoder.encode((0,Hq.encode)(JSON.stringify(this._protectedHeader))):c=fd.encoder.encode("");let u=(0,fd.concat)(c,fd.encoder.encode("."),a),d=await(0,F9e.default)(s,t,u),l={signature:(0,Hq.encode)(d),payload:""};return o&&(l.payload=fd.decoder.decode(a)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=fd.decoder.decode(c)),l}};$v.FlattenedSign=Fq});var Jq=g(Vv=>{"use strict";Object.defineProperty(Vv,"__esModule",{value:!0});Vv.CompactSign=void 0;var G9e=Jv(),$q=class{_flattened;constructor(t){this._flattened=new G9e.FlattenedSign(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}};Vv.CompactSign=$q});var PQ=g(Gv=>{"use strict";Object.defineProperty(Gv,"__esModule",{value:!0});Gv.GeneralSign=void 0;var K9e=Jv(),IQ=we(),Vq=class{parent;protectedHeader;unprotectedHeader;options;key;constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setProtectedHeader(t){if(this.protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this.protectedHeader=t,this}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addSignature(...t){return this.parent.addSignature(...t)}sign(...t){return this.parent.sign(...t)}done(){return this.parent}},Gq=class{_payload;_signatures=[];constructor(t){this._payload=t}addSignature(t,r){let n=new Vq(this,t,r);return this._signatures.push(n),n}async sign(){if(!this._signatures.length)throw new IQ.JWSInvalid("at least one signature must be added");let t={signatures:[],payload:""};for(let r=0;r<this._signatures.length;r++){let n=this._signatures[r],i=new K9e.FlattenedSign(this._payload);i.setProtectedHeader(n.protectedHeader),i.setUnprotectedHeader(n.unprotectedHeader);let{payload:o,...s}=await i.sign(n.key,n.options);if(r===0)t.payload=o;else if(t.payload!==o)throw new IQ.JWSInvalid("inconsistent use of JWS Unencoded Payload (RFC7797)");t.signatures.push(s)}return t}};Gv.GeneralSign=Gq});var Wv=g(Kv=>{"use strict";Object.defineProperty(Kv,"__esModule",{value:!0});Kv.ProduceJWT=void 0;var pd=Cq(),W9e=kr(),Kq=jq();function md(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var Wq=class{_payload;constructor(t={}){if(!(0,W9e.default)(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:md("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:md("setNotBefore",(0,pd.default)(t))}:this._payload={...this._payload,nbf:(0,pd.default)(new Date)+(0,Kq.default)(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:md("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:md("setExpirationTime",(0,pd.default)(t))}:this._payload={...this._payload,exp:(0,pd.default)(new Date)+(0,Kq.default)(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:(0,pd.default)(new Date)}:t instanceof Date?this._payload={...this._payload,iat:md("setIssuedAt",(0,pd.default)(t))}:typeof t=="string"?this._payload={...this._payload,iat:md("setIssuedAt",(0,pd.default)(new Date)+(0,Kq.default)(t))}:this._payload={...this._payload,iat:md("setIssuedAt",t)},this}};Kv.ProduceJWT=Wq});var TQ=g(zv=>{"use strict";Object.defineProperty(zv,"__esModule",{value:!0});zv.SignJWT=void 0;var z9e=Jq(),Y9e=we(),X9e=At(),Z9e=Wv(),zq=class extends Z9e.ProduceJWT{_protectedHeader;setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){let n=new z9e.CompactSign(X9e.encoder.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new Y9e.JWTInvalid("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};zv.SignJWT=zq});var xQ=g(Yv=>{"use strict";Object.defineProperty(Yv,"__esModule",{value:!0});Yv.EncryptJWT=void 0;var Q9e=Uq(),eFe=At(),tFe=Wv(),Yq=class extends tFe.ProduceJWT{_cek;_iv;_keyManagementParameters;_protectedHeader;_replicateIssuerAsHeader;_replicateSubjectAsHeader;_replicateAudienceAsHeader;setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}replicateIssuerAsHeader(){return this._replicateIssuerAsHeader=!0,this}replicateSubjectAsHeader(){return this._replicateSubjectAsHeader=!0,this}replicateAudienceAsHeader(){return this._replicateAudienceAsHeader=!0,this}async encrypt(t,r){let n=new Q9e.CompactEncrypt(eFe.encoder.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),n.setProtectedHeader(this._protectedHeader),this._iv&&n.setInitializationVector(this._iv),this._cek&&n.setContentEncryptionKey(this._cek),this._keyManagementParameters&&n.setKeyManagementParameters(this._keyManagementParameters),n.encrypt(t,r)}};Yv.EncryptJWT=Yq});var CQ=g(Xv=>{"use strict";Object.defineProperty(Xv,"__esModule",{value:!0});Xv.calculateJwkThumbprint=RQ;Xv.calculateJwkThumbprintUri=sFe;var rFe=KM(),nFe=Wr(),OQ=we(),iFe=At(),oFe=kr(),gc=(e,t)=>{if(typeof e!="string"||!e)throw new OQ.JWKInvalid(`${t} missing or invalid`)};async function RQ(e,t){if(!(0,oFe.default)(e))throw new TypeError("JWK must be an object");if(t??="sha256",t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(e.kty){case"EC":gc(e.crv,'"crv" (Curve) Parameter'),gc(e.x,'"x" (X Coordinate) Parameter'),gc(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":gc(e.crv,'"crv" (Subtype of Key Pair) Parameter'),gc(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":gc(e.e,'"e" (Exponent) Parameter'),gc(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":gc(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new OQ.JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported')}let n=iFe.encoder.encode(JSON.stringify(r));return(0,nFe.encode)(await(0,rFe.default)(t,n))}async function sFe(e,t){t??="sha256";let r=await RQ(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}});var kQ=g(Xq=>{"use strict";Object.defineProperty(Xq,"__esModule",{value:!0});Xq.EmbeddedJWK=uFe;var aFe=Qf(),cFe=kr(),NQ=we();async function uFe(e,t){let r={...e,...t?.header};if(!(0,cFe.default)(r.jwk))throw new NQ.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await(0,aFe.importJWK)({...r.jwk,ext:!0},r.alg);if(n instanceof Uint8Array||n.type!=="public")throw new NQ.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}});var eD=g(Qq=>{"use strict";Object.defineProperty(Qq,"__esModule",{value:!0});Qq.createLocalJWKSet=gFe;var dFe=Qf(),Zh=we(),lFe=kr();function fFe(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new Zh.JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set')}}function pFe(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(mFe)}function mFe(e){return(0,lFe.default)(e)}function MQ(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}var Zq=class{_jwks;_cached=new WeakMap;constructor(t){if(!pFe(t))throw new Zh.JWKSInvalid("JSON Web Key Set malformed");this._jwks=MQ(t)}async getKey(t,r){let{alg:n,kid:i}={...t,...r?.header},o=fFe(n),s=this._jwks.keys.filter(u=>{let d=o===u.kty;if(d&&typeof i=="string"&&(d=i===u.kid),d&&typeof u.alg=="string"&&(d=n===u.alg),d&&typeof u.use=="string"&&(d=u.use==="sig"),d&&Array.isArray(u.key_ops)&&(d=u.key_ops.includes("verify")),d)switch(n){case"ES256":d=u.crv==="P-256";break;case"ES256K":d=u.crv==="secp256k1";break;case"ES384":d=u.crv==="P-384";break;case"ES512":d=u.crv==="P-521";break;case"Ed25519":d=u.crv==="Ed25519";break;case"EdDSA":d=u.crv==="Ed25519"||u.crv==="Ed448";break}return d}),{0:a,length:c}=s;if(c===0)throw new Zh.JWKSNoMatchingKey;if(c!==1){let u=new Zh.JWKSMultipleMatchingKeys,{_cached:d}=this;throw u[Symbol.asyncIterator]=async function*(){for(let l of s)try{yield await jQ(d,l,n)}catch{}},u}return jQ(this._cached,a,n)}};async function jQ(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let i=await(0,dFe.importJWK)({...t,ext:!0},r);if(i instanceof Uint8Array||i.type!=="public")throw new Zh.JWKSInvalid("JSON Web Key Set members must be public keys");n[r]=i}return n[r]}function gFe(e){let t=new Zq(e),r=async(n,i)=>t.getKey(n,i);return Object.defineProperties(r,{jwks:{value:()=>MQ(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}});var LQ=g(rD=>{"use strict";Object.defineProperty(rD,"__esModule",{value:!0});var hFe=require("node:http"),yFe=require("node:https"),qQ=require("node:events"),tD=we(),DQ=At(),_Fe=async(e,t,r)=>{let n;switch(e.protocol){case"https:":n=yFe.get;break;case"http:":n=hFe.get;break;default:throw new TypeError("Unsupported URL protocol.")}let{agent:i,headers:o}=r,s=n(e.href,{agent:i,timeout:t,headers:o}),[a]=await Promise.race([(0,qQ.once)(s,"response"),(0,qQ.once)(s,"timeout")]);if(!a)throw s.destroy(),new tD.JWKSTimeout;if(a.statusCode!==200)throw new tD.JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");let c=[];for await(let u of a)c.push(u);try{return JSON.parse(DQ.decoder.decode((0,DQ.concat)(...c)))}catch{throw new tD.JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON")}};rD.default=_Fe});var HQ=g(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});ki.experimental_jwksCache=ki.jwksCache=void 0;ki.createRemoteJWKSet=SFe;var bFe=LQ(),EFe=we(),BQ=eD(),UQ=kr();function wFe(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var nD;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(nD="jose/v5.10.0");ki.jwksCache=Symbol();function vFe(e,t){return!(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||Date.now()-e.uat>=t||!("jwks"in e)||!(0,UQ.default)(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,UQ.default))}var iD=class{_url;_timeoutDuration;_cooldownDuration;_cacheMaxAge;_jwksTimestamp;_pendingFetch;_options;_local;_cache;constructor(t,r){if(!(t instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(t.href),this._options={agent:r?.agent,headers:r?.headers},this._timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this._cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this._cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5,r?.[ki.jwksCache]!==void 0&&(this._cache=r?.[ki.jwksCache],vFe(r?.[ki.jwksCache],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=(0,BQ.createLocalJWKSet)(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(t,r){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(t,r)}catch(n){if(n instanceof EFe.JWKSNoMatchingKey&&this.coolingDown()===!1)return await this.reload(),this._local(t,r);throw n}}async reload(){this._pendingFetch&&wFe()&&(this._pendingFetch=void 0);let t=new Headers(this._options.headers);nD&&!t.has("User-Agent")&&(t.set("User-Agent",nD),this._options.headers=Object.fromEntries(t.entries())),this._pendingFetch||=(0,bFe.default)(this._url,this._timeoutDuration,this._options).then(r=>{this._local=(0,BQ.createLocalJWKSet)(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(r=>{throw this._pendingFetch=void 0,r}),await this._pendingFetch}};function SFe(e,t){let r=new iD(e,t),n=async(i,o)=>r.getKey(i,o);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>r._local?.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}ki.experimental_jwksCache=ki.jwksCache});var FQ=g(Qv=>{"use strict";Object.defineProperty(Qv,"__esModule",{value:!0});Qv.UnsecuredJWT=void 0;var Zv=Wr(),AFe=At(),oD=we(),IFe=Hv(),PFe=Wv(),sD=class extends PFe.ProduceJWT{encode(){let t=Zv.encode(JSON.stringify({alg:"none"})),r=Zv.encode(JSON.stringify(this._payload));return`${t}.${r}.`}static decode(t,r){if(typeof t!="string")throw new oD.JWTInvalid("Unsecured JWT must be a string");let{0:n,1:i,2:o,length:s}=t.split(".");if(s!==3||o!=="")throw new oD.JWTInvalid("Invalid Unsecured JWT");let a;try{if(a=JSON.parse(AFe.decoder.decode(Zv.decode(n))),a.alg!=="none")throw new Error}catch{throw new oD.JWTInvalid("Invalid Unsecured JWT")}return{payload:(0,IFe.default)(a,Zv.decode(i),r),header:a}}};Qv.UnsecuredJWT=sD});var eS=g(cp=>{"use strict";Object.defineProperty(cp,"__esModule",{value:!0});cp.decode=cp.encode=void 0;var $Q=Wr();cp.encode=$Q.encode;cp.decode=$Q.decode});var JQ=g(aD=>{"use strict";Object.defineProperty(aD,"__esModule",{value:!0});aD.decodeProtectedHeader=RFe;var TFe=eS(),xFe=At(),OFe=kr();function RFe(e){let t;if(typeof e=="string"){let r=e.split(".");(r.length===3||r.length===5)&&([t]=r)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;let r=JSON.parse(xFe.decoder.decode((0,TFe.decode)(t)));if(!(0,OFe.default)(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}});var VQ=g(cD=>{"use strict";Object.defineProperty(cD,"__esModule",{value:!0});cD.decodeJwt=jFe;var CFe=eS(),NFe=At(),kFe=kr(),gd=we();function jFe(e){if(typeof e!="string")throw new gd.JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.split(".");if(r===5)throw new gd.JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new gd.JWTInvalid("Invalid JWT");if(!t)throw new gd.JWTInvalid("JWTs must contain a payload");let n;try{n=(0,CFe.decode)(t)}catch{throw new gd.JWTInvalid("Failed to base64url decode the payload")}let i;try{i=JSON.parse(NFe.decoder.decode(n))}catch{throw new gd.JWTInvalid("Failed to parse the decoded payload as JSON")}if(!(0,kFe.default)(i))throw new gd.JWTInvalid("Invalid JWT Claims Set");return i}});var uD=g(tS=>{"use strict";Object.defineProperty(tS,"__esModule",{value:!0});tS.generateSecret=DFe;tS.generateKeyPair=LFe;var GQ=require("node:crypto"),MFe=require("node:util"),qFe=Dh(),Qh=we(),ji=(0,MFe.promisify)(GQ.generateKeyPair);async function DFe(e,t){let r;switch(e){case"HS256":case"HS384":case"HS512":case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":r=parseInt(e.slice(-3),10);break;case"A128KW":case"A192KW":case"A256KW":case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":r=parseInt(e.slice(1,4),10);break;default:throw new Qh.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return(0,GQ.createSecretKey)((0,qFe.default)(new Uint8Array(r>>3)))}async function LFe(e,t){switch(e){case"RS256":case"RS384":case"RS512":case"PS256":case"PS384":case"PS512":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":case"RSA1_5":{let r=t?.modulusLength??2048;if(typeof r!="number"||r<2048)throw new Qh.JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return await ji("rsa",{modulusLength:r,publicExponent:65537})}case"ES256":return ji("ec",{namedCurve:"P-256"});case"ES256K":return ji("ec",{namedCurve:"secp256k1"});case"ES384":return ji("ec",{namedCurve:"P-384"});case"ES512":return ji("ec",{namedCurve:"P-521"});case"Ed25519":return ji("ed25519");case"EdDSA":switch(t?.crv){case void 0:case"Ed25519":return ji("ed25519");case"Ed448":return ji("ed448");default:throw new Qh.JOSENotSupported("Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448")}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let r=t?.crv??"P-256";switch(r){case void 0:case"P-256":case"P-384":case"P-521":return ji("ec",{namedCurve:r});case"X25519":return ji("x25519");case"X448":return ji("x448");default:throw new Qh.JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}}default:throw new Qh.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}}});var KQ=g(dD=>{"use strict";Object.defineProperty(dD,"__esModule",{value:!0});dD.generateKeyPair=UFe;var BFe=uD();async function UFe(e,t){return(0,BFe.generateKeyPair)(e,t)}});var WQ=g(lD=>{"use strict";Object.defineProperty(lD,"__esModule",{value:!0});lD.generateSecret=FFe;var HFe=uD();async function FFe(e,t){return(0,HFe.generateSecret)(e,t)}});var zQ=g(fD=>{"use strict";Object.defineProperty(fD,"__esModule",{value:!0});fD.default="node:crypto"});var YQ=g(pD=>{"use strict";Object.defineProperty(pD,"__esModule",{value:!0});var $Fe=zQ();pD.default=$Fe.default});var hD=g($=>{"use strict";Object.defineProperty($,"__esModule",{value:!0});$.cryptoRuntime=$.base64url=$.generateSecret=$.generateKeyPair=$.errors=$.decodeJwt=$.decodeProtectedHeader=$.importJWK=$.importX509=$.importPKCS8=$.importSPKI=$.exportJWK=$.exportSPKI=$.exportPKCS8=$.UnsecuredJWT=$.experimental_jwksCache=$.jwksCache=$.createRemoteJWKSet=$.createLocalJWKSet=$.EmbeddedJWK=$.calculateJwkThumbprintUri=$.calculateJwkThumbprint=$.EncryptJWT=$.SignJWT=$.GeneralSign=$.FlattenedSign=$.CompactSign=$.FlattenedEncrypt=$.CompactEncrypt=$.jwtDecrypt=$.jwtVerify=$.generalVerify=$.flattenedVerify=$.compactVerify=$.GeneralEncrypt=$.generalDecrypt=$.flattenedDecrypt=$.compactDecrypt=void 0;var JFe=rq();Object.defineProperty($,"compactDecrypt",{enumerable:!0,get:function(){return JFe.compactDecrypt}});var VFe=kv();Object.defineProperty($,"flattenedDecrypt",{enumerable:!0,get:function(){return VFe.flattenedDecrypt}});var GFe=eQ();Object.defineProperty($,"generalDecrypt",{enumerable:!0,get:function(){return GFe.generalDecrypt}});var KFe=sQ();Object.defineProperty($,"GeneralEncrypt",{enumerable:!0,get:function(){return KFe.GeneralEncrypt}});var WFe=Tq();Object.defineProperty($,"compactVerify",{enumerable:!0,get:function(){return WFe.compactVerify}});var zFe=Uv();Object.defineProperty($,"flattenedVerify",{enumerable:!0,get:function(){return zFe.flattenedVerify}});var YFe=_Q();Object.defineProperty($,"generalVerify",{enumerable:!0,get:function(){return YFe.generalVerify}});var XFe=SQ();Object.defineProperty($,"jwtVerify",{enumerable:!0,get:function(){return XFe.jwtVerify}});var ZFe=AQ();Object.defineProperty($,"jwtDecrypt",{enumerable:!0,get:function(){return ZFe.jwtDecrypt}});var QFe=Uq();Object.defineProperty($,"CompactEncrypt",{enumerable:!0,get:function(){return QFe.CompactEncrypt}});var e$e=Dv();Object.defineProperty($,"FlattenedEncrypt",{enumerable:!0,get:function(){return e$e.FlattenedEncrypt}});var t$e=Jq();Object.defineProperty($,"CompactSign",{enumerable:!0,get:function(){return t$e.CompactSign}});var r$e=Jv();Object.defineProperty($,"FlattenedSign",{enumerable:!0,get:function(){return r$e.FlattenedSign}});var n$e=PQ();Object.defineProperty($,"GeneralSign",{enumerable:!0,get:function(){return n$e.GeneralSign}});var i$e=TQ();Object.defineProperty($,"SignJWT",{enumerable:!0,get:function(){return i$e.SignJWT}});var o$e=xQ();Object.defineProperty($,"EncryptJWT",{enumerable:!0,get:function(){return o$e.EncryptJWT}});var XQ=CQ();Object.defineProperty($,"calculateJwkThumbprint",{enumerable:!0,get:function(){return XQ.calculateJwkThumbprint}});Object.defineProperty($,"calculateJwkThumbprintUri",{enumerable:!0,get:function(){return XQ.calculateJwkThumbprintUri}});var s$e=kQ();Object.defineProperty($,"EmbeddedJWK",{enumerable:!0,get:function(){return s$e.EmbeddedJWK}});var a$e=eD();Object.defineProperty($,"createLocalJWKSet",{enumerable:!0,get:function(){return a$e.createLocalJWKSet}});var mD=HQ();Object.defineProperty($,"createRemoteJWKSet",{enumerable:!0,get:function(){return mD.createRemoteJWKSet}});Object.defineProperty($,"jwksCache",{enumerable:!0,get:function(){return mD.jwksCache}});Object.defineProperty($,"experimental_jwksCache",{enumerable:!0,get:function(){return mD.experimental_jwksCache}});var c$e=FQ();Object.defineProperty($,"UnsecuredJWT",{enumerable:!0,get:function(){return c$e.UnsecuredJWT}});var gD=sq();Object.defineProperty($,"exportPKCS8",{enumerable:!0,get:function(){return gD.exportPKCS8}});Object.defineProperty($,"exportSPKI",{enumerable:!0,get:function(){return gD.exportSPKI}});Object.defineProperty($,"exportJWK",{enumerable:!0,get:function(){return gD.exportJWK}});var rS=Qf();Object.defineProperty($,"importSPKI",{enumerable:!0,get:function(){return rS.importSPKI}});Object.defineProperty($,"importPKCS8",{enumerable:!0,get:function(){return rS.importPKCS8}});Object.defineProperty($,"importX509",{enumerable:!0,get:function(){return rS.importX509}});Object.defineProperty($,"importJWK",{enumerable:!0,get:function(){return rS.importJWK}});var u$e=JQ();Object.defineProperty($,"decodeProtectedHeader",{enumerable:!0,get:function(){return u$e.decodeProtectedHeader}});var d$e=VQ();Object.defineProperty($,"decodeJwt",{enumerable:!0,get:function(){return d$e.decodeJwt}});$.errors=we();var l$e=KQ();Object.defineProperty($,"generateKeyPair",{enumerable:!0,get:function(){return l$e.generateKeyPair}});var f$e=WQ();Object.defineProperty($,"generateSecret",{enumerable:!0,get:function(){return f$e.generateSecret}});$.base64url=eS();var p$e=YQ();Object.defineProperty($,"cryptoRuntime",{enumerable:!0,get:function(){return p$e.default}})});var Un=g(up=>{"use strict";Object.defineProperty(up,"__esModule",{value:!0});up.signJwt=m$e;up.decodeJwt=QQ;up.verifyJwtSignature=g$e;up.temporalReason=h$e;var nS=hD();async function m$e(e,t,r){let n=await(0,nS.importJWK)({...e},"EdDSA");return new nS.SignJWT(r).setProtectedHeader({alg:"EdDSA",kid:t.kid,typ:t.typ}).sign(n)}function ZQ(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function QQ(e){let t=e.split(".");if(t.length!==3)return null;try{let r=JSON.parse(Buffer.from(t[0],"base64url").toString("utf8")),n=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return!ZQ(r)||!ZQ(n)?null:{header:r,claims:n}}catch{return null}}async function g$e(e,t,r,n=!1){let i=QQ(e);if(!i)return{ok:!1,reason:"malformed"};if(i.header.alg!=="EdDSA")return{ok:!1,reason:"bad_alg"};let o=t.keys.find(s=>s.kid===i.header.kid);if(!o)return{ok:!1,reason:"unknown_kid"};if(r!==void 0){if(o.role===void 0){if(n)return{ok:!1,reason:"role_required"}}else if(o.role!==r)return{ok:!1,reason:"role_mismatch"}}try{let s=await(0,nS.importJWK)({...o},"EdDSA");await(0,nS.compactVerify)(e,s)}catch{return{ok:!1,reason:"bad_signature"}}return{ok:!0,header:i.header,claims:i.claims}}function h$e(e,t){return Number.isFinite(t)?typeof e.iat!="number"||typeof e.exp!="number"?"bad_temporal_claims":e.iat>t?"not_yet_valid":t>=e.exp?"expired":null:"bad_verification_time"}});var ey=g(jr=>{"use strict";Object.defineProperty(jr,"__esModule",{value:!0});jr.REGISTRATION_JWT_TYP=jr.TTL_REG_DAYS=void 0;jr.isPairwiseRef=_D;jr.derivePairwiseRef=b$e;jr.registrationHash=E$e;jr.issueRegistration=w$e;jr.verifyRegistration=v$e;var eee=require("node:crypto"),yD=Un();jr.TTL_REG_DAYS=90;var y$e=86400;jr.REGISTRATION_JWT_TYP="agent-registration+jwt";var tee="prn_",_$e=/^prn_[A-Za-z0-9_-]{43}$/;function _D(e){return _$e.test(e)}function b$e(e,t){let r=(0,eee.createHmac)("sha256",t).update(e,"utf8").digest();return tee+Buffer.from(r).toString("base64url")}function E$e(e){return(0,eee.createHash)("sha256").update(e,"utf8").digest().toString("base64url")}async function w$e(e){let{anchorKey:t,kid:r=t.kid,issuer:n,agentJkt:i,name:o,pairwisePrincipalRef:s,verificationPolicyId:a,ttlDays:c=jr.TTL_REG_DAYS,nowSec:u=Math.floor(Date.now()/1e3)}=e;if(!_D(s))throw new Error(`pairwisePrincipalRef must be a pairwise ref ("${tee}\u2026" via derivePairwiseRef), never a raw principal id`);if(!Number.isFinite(c)||c<=0||c>jr.TTL_REG_DAYS)throw new Error(`ttlDays must be in (0, ${jr.TTL_REG_DAYS}] (spec \xA78.1 T_reg); got ${c}`);let d={iss:n,sub:i,prn:s,name:o,pol:a,iat:u,exp:u+c*y$e,cnf:{jkt:i}};return(0,yD.signJwt)(t.privateJwk,{kid:r,typ:jr.REGISTRATION_JWT_TYP},{...d})}async function v$e(e,t){let r=await(0,yD.verifyJwtSignature)(e,t.jwks,"anchor-reg",!0);if(!r.ok)return{valid:!1,reason:r.reason};if(r.header.typ!==jr.REGISTRATION_JWT_TYP)return{valid:!1,reason:"typ_mismatch"};let n=r.claims;if(typeof n.iss!="string"||typeof n.sub!="string"||typeof n.prn!="string"||typeof n.name!="string"||typeof n.pol!="string"||typeof n.cnf?.jkt!="string")return{valid:!1,reason:"bad_claim_shape"};if(n.cnf.jkt!==n.sub)return{valid:!1,reason:"cnf_jkt_mismatch"};if(!_D(n.prn))return{valid:!1,reason:"raw_principal_ref"};if(!t.acceptedIssuers.includes(n.iss))return{valid:!1,reason:"issuer_not_accepted"};let i=(0,yD.temporalReason)(n,t.nowSec);return i?{valid:!1,reason:i}:{valid:!0,claims:n}}});var ED=g(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.FreshnessService=Bt.InMemoryFreshnessStore=Bt.FRESHNESS_JWT_TYP=Bt.MAX_TTL_FRESH_HOURS=Bt.TTL_FRESH_HOURS=void 0;Bt.issueFreshness=nee;Bt.verifyFreshness=A$e;var dp=Un(),ree=ey();Bt.TTL_FRESH_HOURS=4;Bt.MAX_TTL_FRESH_HOURS=24;var S$e=3600;Bt.FRESHNESS_JWT_TYP="agent-freshness+jwt";async function nee(e){let{anchorFreshnessKey:t,kid:r=t.kid,issuer:n,registrationJwt:i,status:o="good",ttlHours:s=Bt.TTL_FRESH_HOURS,nowSec:a=Math.floor(Date.now()/1e3)}=e;if(!Number.isFinite(s)||s<=0||s>Bt.MAX_TTL_FRESH_HOURS)throw new Error(`ttlHours must be in (0, ${Bt.MAX_TTL_FRESH_HOURS}] (spec \xA78.3 max staleness); got ${s}`);let c=(0,dp.decodeJwt)(i);if(!c||typeof c.claims.sub!="string")throw new Error("registrationJwt is not a decodable registration");let u={iss:n,sub:c.claims.sub,reg:(0,ree.registrationHash)(i),status:o,iat:a,exp:a+s*S$e};return(0,dp.signJwt)(t.privateJwk,{kid:r,typ:Bt.FRESHNESS_JWT_TYP},{...u})}async function A$e(e,t){let r=await(0,dp.verifyJwtSignature)(e,t.jwks,"anchor-fresh",!0);if(!r.ok)return{valid:!1,reason:r.reason};if(r.header.typ!==Bt.FRESHNESS_JWT_TYP)return{valid:!1,reason:"typ_mismatch"};let n=r.claims;if(typeof n.iss!="string"||typeof n.sub!="string"||typeof n.reg!="string")return{valid:!1,reason:"bad_claim_shape"};if(n.status!=="good")return{valid:!1,reason:"status_not_good"};if(!t.acceptedIssuers.includes(n.iss))return{valid:!1,reason:"issuer_not_accepted"};if(n.reg!==(0,ree.registrationHash)(t.registrationJwt))return{valid:!1,reason:"registration_hash_mismatch"};let i=(0,dp.decodeJwt)(t.registrationJwt);if(!i||n.sub!==i.claims.sub)return{valid:!1,reason:"subject_mismatch"};let o=(0,dp.temporalReason)(n,t.nowSec);return o?{valid:!1,reason:o}:{valid:!0,claims:n}}var iS=class{records=new Map;get(t){return this.records.get(t)}set(t,r){this.records.set(t,r)}};Bt.InMemoryFreshnessStore=iS;var bD=class{key;issuer;ttlHours;store;constructor(t){this.key=t.anchorFreshnessKey,this.issuer=t.issuer,this.ttlHours=t.ttlHours??Bt.TTL_FRESH_HOURS,this.store=t.store??new iS}startRenewal(t,r){let n=(0,dp.decodeJwt)(r);if(!n||n.claims.sub!==t)throw new Error("registrationJwt does not belong to agentJkt");let i=this.store.get(t);if(i?.status==="halted")throw new Error(`agent is halted (${i.haltedReason??"no reason recorded"}); refuse re-enrolment`);this.store.set(t,{status:"good",registrationJwt:r})}halt(t,r,n=Math.floor(Date.now()/1e3)){let i=this.store.get(t);this.store.set(t,{status:"halted",registrationJwt:i?.registrationJwt??"",haltedReason:r,haltedAtSec:n})}isInGoodStanding(t){return this.store.get(t)?.status==="good"}async renew(t,r=Math.floor(Date.now()/1e3)){let n=this.store.get(t);return n?n.status!=="good"?{ok:!1,reason:`halted:${n.haltedReason??"unspecified"}`}:{ok:!0,freshnessJwt:await nee({anchorFreshnessKey:this.key,issuer:this.issuer,registrationJwt:n.registrationJwt,ttlHours:this.ttlHours,nowSec:r})}:{ok:!1,reason:"unknown_agent"}}};Bt.FreshnessService=bD});var wD=g(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});hd.DEFAULT_MAX_STALENESS_SECONDS=void 0;hd.verifyBindingChain=x$e;var I$e=ED(),P$e=ey();hd.DEFAULT_MAX_STALENESS_SECONDS={trusted_messaging:24*3600,spend_low:4*3600,spend_high:300};var T$e=["spend_high","spend_low","trusted_messaging"];async function x$e(e){let{registrationJwt:t,freshnessJwt:r,anchorPolicy:n,nowSec:i}=e,o=[],s=await(0,P$e.verifyRegistration)(t,{jwks:n.registration.jwks,nowSec:i,acceptedIssuers:n.registration.acceptedIssuers});s.valid||o.push(`registration:${s.reason}`);let a=await(0,I$e.verifyFreshness)(r,{registrationJwt:t,jwks:n.freshness.jwks,nowSec:i,acceptedIssuers:n.freshness.acceptedIssuers});if(a.valid||o.push(`freshness:${a.reason}`),e.maxStalenessSeconds!==void 0&&!Number.isFinite(e.maxStalenessSeconds))throw new Error(`maxStalenessSeconds must be finite (spec \xA78.3); got ${e.maxStalenessSeconds}`);let c=e.maxStalenessSeconds??hd.DEFAULT_MAX_STALENESS_SECONDS.spend_high,u=null;if(a.valid){let m=i-a.claims.iat;m>c&&o.push("freshness:staleness_exceeded"),u=T$e.find(p=>m<=hd.DEFAULT_MAX_STALENESS_SECONDS[p])??null}let d=s.valid?s.claims.sub:null;d&&e.killRecords&&e.killRecords.find(p=>p.jkt===d&&p.iat<=i)&&o.push("killed:principal_kill_switch");let l=o.length===0;return{valid:l,tier:l?u:null,agentJkt:d,name:s.valid?s.claims.name:null,reasons:o}}});var iee=g(vD=>{"use strict";Object.defineProperty(vD,"__esModule",{value:!0});vD.deriveCapabilities=O$e;function O$e(e){let t=e.anchorAccepted??!1,r=e.key&&e.relay,n=r&&e.wallet,i=e.trust==="anchor_binding"&&e.bindingFresh&&t,o=r&&(i||e.trust==="admin_grant"),s=i&&n&&e.walletVerified&&e.policy&&e.facilitator;return{reachable:r,wallet_ready:n,anchored:i,trusted:o,economic:s}}});var Ed=g((qut,gee)=>{"use strict";var TD=Object.defineProperty,R$e=Object.getOwnPropertyDescriptor,C$e=Object.getOwnPropertyNames,N$e=Object.prototype.hasOwnProperty,k$e=(e,t)=>{for(var r in t)TD(e,r,{get:t[r],enumerable:!0})},j$e=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of C$e(t))!N$e.call(e,i)&&i!==r&&TD(e,i,{get:()=>t[i],enumerable:!(n=R$e(t,i))||n.enumerable});return e},M$e=e=>j$e(TD({},"__esModule",{value:!0}),e),dee={};k$e(dee,{base64UrlToBytes:()=>X$e,bytesToBase64Url:()=>Y$e,bytesToHex:()=>G$e,hexToBytes:()=>K$e});gee.exports=M$e(dee);var xD=Object.freeze,lp=0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,AD=0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,oS=0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,ID=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,PD=0x6666666666666666666666666666666666666666666666666666666666666658n,sS=lp-1n,q$e=xD({p:lp,n:AD,h:8n,a:sS,d:oS,Gx:ID,Gy:PD}),lee=32,oee=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&e.BYTES_PER_ELEMENT===1,aS=(e,t,r="")=>{if(oee(e)&&(t===void 0||e.length===t))return e;let n=oee(e),i=t!==void 0?` of length ${t}`:"",o=n?`length=${e.length}`:`type=${typeof e}`,s=(r?`"${r}" `:"")+"expected Uint8Array"+i+", got "+o;throw n?new RangeError(s):new TypeError(s)},D$e=(e,t="",r)=>Uint8Array.from(aS(e,r,t)),fee=(e,t)=>e.toString(16).padStart(t,"0"),OD=e=>{let t="";for(let r of aS(e))t+=fee(r,2);return t},RD=e=>{let t="hex invalid";if(typeof e!="string")throw new TypeError(t);if(e.length%2||!/^[\da-f]*$/i.test(e))throw new RangeError(t);let r=new Uint8Array(e.length/2);for(let n=0,i=0;n<r.length;n++,i+=2){let o=e.charCodeAt(i),s=e.charCodeAt(i+1);r[n]=((o&15)+(o>>6)*9)*16+(s&15)+(s>>6)*9}return r},L$e=(...e)=>{let t=0;for(let i of e)t+=aS(i).length;let r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return r},B$e=(e=lee)=>{let t=globalThis?.crypto;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined, consider polyfill");return t.getRandomValues(new Uint8Array(e))},yd=(e,t,r,n="bad number: out of range")=>{if(typeof e!="bigint")throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},ht=(e,t=lp)=>(e%=t)>=0n?e:t+e,see=(1n<<255n)-1n,X=e=>{if(e<0n)throw new RangeError("negative coordinate");let t=(e>>255n)*19n+(e&see);return t=(t>>255n)*19n+(t&see),t%lp},pee=(e,t)=>{if(e===0n)throw new Error("invert: expected non-zero number");if(t<=1n)throw new Error("invert: expected modulus > 1, got "+t);let r=ht(e,t),n=t,i=0n,o=1n;for(;r!==0n;){let a=n/r,c=n-r*a,u=i-o*a;n=r,r=c,i=o,o=u}if(n!==1n)throw new Error("invert: does not exist");return ht(i,t)},SD=e=>{if(e instanceof ry)return e;throw new TypeError("Point expected")},mee=2n**256n,ry=class _d{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=mee;this.X=yd(t,0n,o),this.Y=yd(r,0n,o),this.Z=yd(n,1n,o),this.T=yd(i,0n,o),xD(this)}static CURVE(){return q$e}static fromAffine(t){return new _d(t.x,t.y,1n,X(t.x*t.y))}static fromBytes(t,r=!1){let n=D$e(t,"point",lee),i=n[31];n[31]=i&-129;let o=H$e(n);r||yd(o,0n,lp);let s=X(o*o),a=ht(s-1n),c=X(oS*s+1n),{isValid:u,value:d}=$$e(a,c);if(!u)throw new Error("bad point: y not sqrt");let l=!!(i&128);if(!r&&d===0n&&l)throw new Error("bad point: x==0, isLastByteOdd");return l!==!!(d&1n)&&(d=ht(-d)),new _d(d,o,1n,X(d*o))}static fromHex(t,r){return _d.fromBytes(RD(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=sS,r=oS,n=this;if(n.is0())throw new Error("bad point: ZERO");let{X:i,Y:o,Z:s,T:a}=n,c=X(i*i),u=X(o*o),d=X(s*s),l=X(d*d),m=X(c*t),p=X(d*(m+u)),h=ht(l+X(r*X(c*u)));if(p!==h)throw new Error("bad point: equation left != right (1)");let y=X(i*o),b=X(s*a);if(y!==b)throw new Error("bad point: equation left != right (2)");return this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=SD(t);return X(r*a)===X(o*i)&&X(n*a)===X(s*i)}is0(){return this.equals(bd)}negate(){return new _d(ht(-this.X),this.Y,this.Z,ht(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=sS,o=X(t*t),s=X(r*r),a=X(2n*n*n),c=X(i*o),u=ht(t+r),d=ht(X(u*u)-o-s),l=ht(c+s),m=ht(l-a),p=ht(c-s),h=X(d*m),y=X(l*p),b=X(d*p),v=X(m*l);return new _d(h,y,v,b)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=SD(t),d=sS,l=oS,m=X(r*s),p=X(n*a),h=X(X(o*l)*u),y=X(i*c),b=ht(X(ht(r+n)*ht(s+a))-m-p),v=ht(y-h),A=ht(y+h),E=ht(p-X(d*m)),S=X(b*v),I=X(A*E),T=X(b*E),x=X(v*A);return new _d(S,I,x,T)}subtract(t){return this.add(SD(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(yd(t,1n,AD),!r&&this.is0()))return bd;if(t===1n)return this;if(this.equals(ty))return V$e(t).p;let n=bd,i=ty,o=this;for(let s=0;r?s<256:t>0n;s++)t&1n?n=n.add(o):r&&(i=i.add(o)),o=o.double(),t>>=1n;return n}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:r,Z:n}=this;if(this.equals(bd))return{x:0n,y:1n};let i=pee(n,lp);if(X(n*i)!==1n)throw new Error("invalid inverse");return{x:X(t*i),y:X(r*i)}}toBytes(){let{x:t,y:r}=this.toAffine(),n=U$e(r);return n[31]|=t&1n?128:0,n}toHex(){return OD(this.toBytes())}clearCofactor(){return this.multiply(8n,!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return this.multiply(AD/2n,!1).double().add(this).is0()}},ty=new ry(ID,PD,1n,ht(ID*PD)),bd=new ry(0n,1n,1n,0n);ry.BASE=ty;ry.ZERO=bd;var U$e=e=>RD(fee(yd(e,0n,mee),64)).reverse(),H$e=e=>BigInt("0x"+OD(Uint8Array.from(aS(e)).reverse())),Io=(e,t)=>{let r=e;for(;t-- >0;)r=X(r*r);return r},F$e=e=>{let t=X(e*e),r=X(t*e),n=X(Io(r,2)*r),i=X(Io(n,1)*e),o=X(Io(i,5)*i),s=X(Io(o,10)*o),a=X(Io(s,20)*s),c=X(Io(a,40)*a),u=X(Io(c,80)*c),d=X(Io(u,80)*c),l=X(Io(d,10)*o);return X(Io(l,2)*e)},aee=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,$$e=(e,t)=>{let r=X(t*X(t*t)),n=X(X(r*r)*t),i=F$e(X(e*n)),o=X(e*X(r*i)),s=X(t*X(o*o)),a=o,c=X(o*aee),u=s===e,d=s===ht(-e),l=s===ht(-e*aee);return u&&(o=a),(d||l)&&(o=c),(ht(o)&1n)===1n&&(o=ht(-o)),{isValid:u||d,value:o}},CD=xD({bytesToHex:OD,hexToBytes:RD,concatBytes:L$e,mod:ht,invert:pee,randomBytes:B$e}),J$e=()=>{let e=[],t=ty,r;for(let n=0;n<33;n++){r=t,e.push(r);for(let i=1;i<128;i++)r=r.add(t),e.push(r);t=r.double()}return e},cee=void 0,uee=(e,t)=>{let r=t.negate();return e?r:t},V$e=e=>{let t=cee||(cee=J$e()),r=bd,n=ty;for(let i=0;i<33;i++){let o=Number(e&255n);e>>=8n,o>128&&(o-=256,e+=1n);let s=i*128,a=s+Math.abs(o)-1,c=i%2!==0,u=o<0;o===0?n=n.add(uee(c,t[s])):r=r.add(uee(u,t[a]))}if(e!==0n)throw new Error("invalid wnaf");return{p:r,f:n}},G$e=CD.bytesToHex,K$e=CD.hexToBytes,Mut=CD.concatBytes;function W$e(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function z$e(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function Y$e(e){return W$e(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function X$e(e){let t=e.length%4===0?0:4-e.length%4,r=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return z$e(r)}});var cS=g(ND=>{"use strict";Object.defineProperty(ND,"__esModule",{value:!0});ND.signJwtWithSigner=Z$e;var yee=Ed(),hee=e=>(0,yee.bytesToBase64Url)(new TextEncoder().encode(JSON.stringify(e)));async function Z$e(e,t,r){let n=hee({alg:"EdDSA",kid:e.kid,typ:t.typ}),i=hee(r),o=`${n}.${i}`,s=await e.sign(new TextEncoder().encode(o));if(!(s instanceof Uint8Array)||s.length!==64)throw new Error(`signer.sign must return a raw 64-byte Ed25519 signature; got ${s instanceof Uint8Array?`${s.length} bytes`:typeof s} (check the vault adapter is not DER-wrapping or re-encoding)`);return`${o}.${(0,yee.bytesToBase64Url)(s)}`}});var fp=g(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});Os.LocalSigner=Os.signJwtWithSigner=void 0;Os.signerFromAnchorKey=rJe;Os.signerFromSignFn=nJe;Os.issueRegistrationWithSigner=sJe;var _ee=require("node:crypto"),ny=ey();function bee(e,t){let r={kty:"OKP",crv:"Ed25519",x:e.x,kid:t};return e.use!==void 0&&(r.use=e.use),e.alg!==void 0&&(r.alg=e.alg),e.role!==void 0&&(r.role=e.role),r}var Q$e=cS();Object.defineProperty(Os,"signJwtWithSigner",{enumerable:!0,get:function(){return Q$e.signJwtWithSigner}});var eJe=cS();function tJe(e){return{kty:"OKP",crv:"Ed25519",x:e.x,d:e.d}}var uS=class{kid;publicJwk;#e;constructor(t,r,n){this.kid=n,this.publicJwk=bee(r,n),this.#e=(0,_ee.createPrivateKey)({key:tJe(t),format:"jwk"})}async sign(t){return new Uint8Array((0,_ee.sign)(null,Buffer.from(t),this.#e))}};Os.LocalSigner=uS;function rJe(e){return new uS(e.privateJwk,e.publicJwk,e.kid)}function nJe(e,t,r){return{kid:e,publicJwk:bee(t,e),sign:r}}var iJe=86400,oJe="prn_";async function sJe(e){let{signer:t,issuer:r,agentJkt:n,name:i,pairwisePrincipalRef:o,verificationPolicyId:s,ttlDays:a=ny.TTL_REG_DAYS,nowSec:c=Math.floor(Date.now()/1e3)}=e;if(!(0,ny.isPairwiseRef)(o))throw new Error(`pairwisePrincipalRef must be a pairwise ref ("${oJe}\u2026" via derivePairwiseRef), never a raw principal id`);if(!Number.isFinite(a)||a<=0||a>ny.TTL_REG_DAYS)throw new Error(`ttlDays must be in (0, ${ny.TTL_REG_DAYS}] (spec \xA78.1 T_reg); got ${a}`);if(!Number.isFinite(c))throw new Error(`nowSec must be a finite unix-seconds value; got ${c}`);let u={iss:r,sub:n,prn:o,name:i,pol:s,iat:c,exp:c+a*iJe,cnf:{jkt:n}};return(0,eJe.signJwtWithSigner)(t,{typ:ny.REGISTRATION_JWT_TYP},{...u})}});var dS=g(pp=>{"use strict";Object.defineProperty(pp,"__esModule",{value:!0});pp.POP_JWT_TYP=void 0;pp.createPopProofWithSigner=cJe;var aJe=cS();pp.POP_JWT_TYP="visa-agent-pop+jwt";async function cJe(e,t){let n={cnf:{jwk:{kty:e.publicJwk.kty,crv:e.publicJwk.crv,x:e.publicJwk.x}},nonce:t.nonce,aud:t.audience,iat:t.nowSec};return t.intentHash!==void 0&&(n.int=t.intentHash),t.runtimeCertificate!==void 0&&(n.rkc=t.runtimeCertificate),(0,aJe.signJwtWithSigner)(e,{typ:pp.POP_JWT_TYP},n)}});var wd=g(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.DEFAULT_POP_MAX_AGE_SEC=Mr.UNIVERSAL_AGENT_OPERATION_AUDIENCE=Mr.POP_JWT_TYP=Mr.createPopProofWithSigner=void 0;Mr.randomPopNonce=fJe;Mr.createPopProof=Aee;Mr.createAgentOperationPopProof=pJe;Mr.verifyAgentOperationPopProof=mJe;Mr.verifyPopProof=Iee;var uJe=require("node:crypto"),Eee=hD(),dJe=Br(),wee=Un(),vee=dS();Object.defineProperty(Mr,"createPopProofWithSigner",{enumerable:!0,get:function(){return vee.createPopProofWithSigner}});Object.defineProperty(Mr,"POP_JWT_TYP",{enumerable:!0,get:function(){return vee.POP_JWT_TYP}});var See=dS();Mr.UNIVERSAL_AGENT_OPERATION_AUDIENCE="visa-agent-operations:v1";Mr.DEFAULT_POP_MAX_AGE_SEC=120;var lJe=30;function fJe(){return(0,uJe.randomBytes)(32).toString("base64url")}async function Aee(e,t){if("createProof"in e)return e.createProof(t);let n={cnf:{jwk:{kty:e.publicJwk.kty,crv:e.publicJwk.crv,x:e.publicJwk.x}},nonce:t.nonce,aud:t.audience,iat:t.nowSec};return t.intentHash!==void 0&&(n.int=t.intentHash),t.runtimeCertificate!==void 0&&(n.rkc=t.runtimeCertificate),(0,wee.signJwt)(e.privateJwk,{kid:e.jkt,typ:See.POP_JWT_TYP},n)}function pJe(e,t){return Aee(e,{nonce:t.operationId,audience:t.audience,nowSec:t.nowSec,intentHash:t.intentHash,...t.runtimeCertificate===void 0?{}:{runtimeCertificate:t.runtimeCertificate}})}function mJe(e,t){return Iee(e,{expectedNonce:t.operationId,audience:t.audience,nowSec:t.nowSec,expectedIntentHash:t.expectedIntentHash,...t.maxAgeSec===void 0?{}:{maxAgeSec:t.maxAgeSec}})}function gJe(e){return typeof e=="object"&&e!==null&&typeof e.kty=="string"&&typeof e.crv=="string"&&typeof e.x=="string"}async function Iee(e,t){let r=(0,wee.decodeJwt)(e);if(!r)return{ok:!1,reason:"malformed"};if(r.header.alg!=="EdDSA")return{ok:!1,reason:"bad_alg"};if(r.header.typ!==See.POP_JWT_TYP)return{ok:!1,reason:"typ_mismatch"};let n=r.claims.cnf?.jwk;if(!gJe(n)||n.kty!=="OKP"||n.crv!=="Ed25519")return{ok:!1,reason:"bad_cnf_key"};try{let a=await(0,Eee.importJWK)({kty:n.kty,crv:n.crv,x:n.x},"EdDSA");await(0,Eee.compactVerify)(e,a)}catch{return{ok:!1,reason:"bad_signature"}}let i=(0,dJe.computeJkt)(n);if(r.claims.nonce!==t.expectedNonce)return{ok:!1,reason:"nonce_mismatch"};if(r.claims.aud!==t.audience)return{ok:!1,reason:"aud_mismatch"};if(t.expectedIntentHash!==void 0&&r.claims.int!==t.expectedIntentHash)return{ok:!1,reason:"intent_mismatch"};let o=r.claims.iat;if(typeof o!="number"||!Number.isFinite(o))return{ok:!1,reason:"bad_iat"};if(o>t.nowSec+lJe)return{ok:!1,reason:"not_yet_valid"};let s=t.maxAgeSec??Mr.DEFAULT_POP_MAX_AGE_SEC;return t.nowSec-o>s?{ok:!1,reason:"stale"}:r.claims.rkc!==void 0&&typeof r.claims.rkc!="string"?{ok:!1,reason:"bad_runtime_certificate"}:{ok:!0,jkt:i,...typeof r.claims.rkc=="string"?{runtimeCertificate:r.claims.rkc}:{}}}});var vd=g(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.DELEGATION_RENEW_SOON_MS=ie.TAP_RENEW_WINDOW_SECONDS=ie.TAP_KEY_TTL_DAYS=ie.APP_CONNECT_TTL_SECONDS=ie.APP_TOKEN_TTL_SECONDS=ie.CLI_CEREMONY_GRACE_MS=ie.CLI_HANDOFF_TTL_MS=ie.OWNER_ENROLLMENT_CLAIM_WINDOW_SECONDS=ie.OWNER_PAYMENT_APPROVAL_SECONDS=ie.RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS=ie.OWNERSHIP_CHALLENGE_MAX_AGE_SECONDS=ie.ENROLLMENT_CHALLENGE_MAX_AGE_MS=ie.AGENT_PAIRING_TTL_SECONDS=ie.HOSTED_CONNECTOR_PROOF_TTL_SECONDS=ie.RUNTIME_LEASE_MAX_TTL_SECONDS=ie.RUNTIME_DELEGATION_MAX_TTL_SECONDS=ie.WALLET_GRANT_DEFAULT_DAYS=ie.CARD_MANDATE_MAX_SECONDS=ie.CARD_GRANT_DEFAULT_TERM_SECONDS=ie.CARD_GRANT_MAX_TERM_SECONDS=ie.DAY_SECONDS=void 0;ie.defaultGrantExpiry=hJe;ie.DAY_SECONDS=86400;ie.CARD_GRANT_MAX_TERM_SECONDS=7*ie.DAY_SECONDS;ie.CARD_GRANT_DEFAULT_TERM_SECONDS=ie.CARD_GRANT_MAX_TERM_SECONDS-3600;ie.CARD_MANDATE_MAX_SECONDS=ie.CARD_GRANT_DEFAULT_TERM_SECONDS;ie.WALLET_GRANT_DEFAULT_DAYS=30;function hJe(e,t){return t.card?new Date(e.getTime()+ie.CARD_GRANT_DEFAULT_TERM_SECONDS*1e3):new Date(e.getTime()+ie.WALLET_GRANT_DEFAULT_DAYS*ie.DAY_SECONDS*1e3)}ie.RUNTIME_DELEGATION_MAX_TTL_SECONDS=366*ie.DAY_SECONDS;ie.RUNTIME_LEASE_MAX_TTL_SECONDS=300;ie.HOSTED_CONNECTOR_PROOF_TTL_SECONDS=300;ie.AGENT_PAIRING_TTL_SECONDS=3600;ie.ENROLLMENT_CHALLENGE_MAX_AGE_MS=6e4;ie.OWNERSHIP_CHALLENGE_MAX_AGE_SECONDS=300;ie.RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS=60;ie.OWNER_PAYMENT_APPROVAL_SECONDS=240;ie.OWNER_ENROLLMENT_CLAIM_WINDOW_SECONDS=600;ie.CLI_HANDOFF_TTL_MS=15*6e4;ie.CLI_CEREMONY_GRACE_MS=45*6e4;ie.APP_TOKEN_TTL_SECONDS=90*ie.DAY_SECONDS;ie.APP_CONNECT_TTL_SECONDS=900;ie.TAP_KEY_TTL_DAYS=365;ie.TAP_RENEW_WINDOW_SECONDS=30*ie.DAY_SECONDS;ie.DELEGATION_RENEW_SOON_MS=335*ie.DAY_SECONDS*1e3});var jD=g(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.CHALLENGE_MAX_AGE_SEC=ze.MAX_TTL_OWNERSHIP_HOURS=ze.TTL_OWNERSHIP_HOURS=ze.OWNERSHIP_PROOF_JWT_TYP=ze.OWNERSHIP_CHALLENGE_DOMAIN_V1=void 0;ze.buildOwnershipChallenge=Tee;ze.verifyOwnershipSignature=xee;ze.issueOwnershipProof=Ree;ze.issueOwnershipProofWithSigner=SJe;ze.attestWalletOwnership=AJe;ze.verifyOwnershipProof=Cee;ze.walletVerifiedFromProof=IJe;var yJe=require("node:crypto"),_Je=gv(),kD=Un(),bJe=fp(),EJe=wd(),Pee=vd();Object.defineProperty(ze,"CHALLENGE_MAX_AGE_SEC",{enumerable:!0,get:function(){return Pee.OWNERSHIP_CHALLENGE_MAX_AGE_SECONDS}});ze.OWNERSHIP_CHALLENGE_DOMAIN_V1="visa-wallet-ownership:v1";ze.OWNERSHIP_PROOF_JWT_TYP="wallet-ownership+jwt";ze.TTL_OWNERSHIP_HOURS=4;ze.MAX_TTL_OWNERSHIP_HOURS=24;var wJe=60,vJe=3600,fS=/^0x[0-9a-fA-F]{40}$/;function lS(e){return e.toLowerCase()}function Tee(e){let{agentJkt:t,walletAddress:r,nowSec:n=Math.floor(Date.now()/1e3)}=e;if(!t)throw new Error("buildOwnershipChallenge requires agentJkt");if(!fS.test(r))throw new Error("walletAddress must be a 0x-prefixed 20-byte EVM address");let i=lS(r),o=e.nonce??(0,yJe.randomBytes)(16).toString("base64url");return{message:[ze.OWNERSHIP_CHALLENGE_DOMAIN_V1,`agent=${t}`,`wallet=${i}`,`nonce=${o}`,`ts=${n}`].join(`
65
+ `),nonce:o,issuedAtSec:n}}async function xee(e){let{message:t,signature:r,address:n}=e;if(!t||!r||!n)return{ok:!1,reason:"missing_inputs"};if(!fS.test(n))return{ok:!1,reason:"bad_address"};try{return await(0,_Je.verifyMessage)({address:n,message:t,signature:r})?{ok:!0}:{ok:!1,reason:"signature_mismatch"}}catch{return{ok:!1,reason:"verify_error"}}}function Oee(e){if(!fS.test(e.walletAddress))throw new Error("walletAddress must be a 0x-prefixed 20-byte EVM address");if(!Number.isFinite(e.nowSec))throw new Error("nowSec must be a finite unix-seconds value");if(!Number.isFinite(e.ttlHours)||e.ttlHours<=0)throw new Error(`ttlHours must be in (0, ${ze.MAX_TTL_OWNERSHIP_HOURS}]`);let t=Math.min(e.ttlHours,ze.MAX_TTL_OWNERSHIP_HOURS);return{iss:e.issuer,sub:e.agentJkt,wallet:lS(e.walletAddress),mth:"eip191",nonce:e.nonce,...e.chain?{chain:e.chain}:{},iat:e.nowSec,exp:e.nowSec+t*vJe,cnf:{jkt:e.agentJkt},...e.twoSided?{tsc:!0}:{}}}async function Ree(e){let{ownershipKey:t,kid:r=t.kid,ttlHours:n=ze.TTL_OWNERSHIP_HOURS,nowSec:i=Math.floor(Date.now()/1e3)}=e,o=Oee({...e,ttlHours:n,nowSec:i});return(0,kD.signJwt)(t.privateJwk,{kid:r,typ:ze.OWNERSHIP_PROOF_JWT_TYP},{...o})}async function SJe(e){let{signer:t,ttlHours:r=ze.TTL_OWNERSHIP_HOURS,nowSec:n=Math.floor(Date.now()/1e3)}=e,i=Oee({...e,ttlHours:r,nowSec:n});return(0,bJe.signJwtWithSigner)(t,{typ:ze.OWNERSHIP_PROOF_JWT_TYP},{...i})}async function AJe(e){let t=e.nowSec??Math.floor(Date.now()/1e3),r=e.maxChallengeAgeSec??Pee.OWNERSHIP_CHALLENGE_MAX_AGE_SECONDS,n=e.challenge.issuedAtSec;if(!Number.isFinite(t))return{ok:!1,reason:"bad_verification_time"};if(!Number.isFinite(r)||r<0)return{ok:!1,reason:"bad_challenge_window"};if(!Number.isFinite(n))return{ok:!1,reason:"challenge_bad_timestamp"};if(n>t+wJe)return{ok:!1,reason:"challenge_not_yet_valid"};if(t-n>r)return{ok:!1,reason:"challenge_stale"};let i=Tee({agentJkt:e.agentJkt,walletAddress:e.walletAddress,nonce:e.challenge.nonce,nowSec:e.challenge.issuedAtSec});if(i.message!==e.challenge.message)return{ok:!1,reason:"challenge_mismatch"};let o=await xee({message:i.message,signature:e.signature,address:e.walletAddress});if(!o.ok)return{ok:!1,reason:o.reason};if(e.agentPop!==void 0){let a=await(0,EJe.verifyPopProof)(e.agentPop.jwt,{expectedNonce:e.challenge.nonce,audience:e.issuer,nowSec:t});if(!a.ok)return{ok:!1,reason:`agent_pop_${a.reason}`};if(a.jkt!==e.agentJkt)return{ok:!1,reason:"agent_pop_jkt_mismatch"}}return{ok:!0,proof:await Ree({ownershipKey:e.ownershipKey,kid:e.kid,issuer:e.issuer,agentJkt:e.agentJkt,walletAddress:e.walletAddress,nonce:e.challenge.nonce,chain:e.chain,ttlHours:e.ttlHours,nowSec:e.nowSec,twoSided:e.agentPop!==void 0})}}async function Cee(e,t){let r=await(0,kD.verifyJwtSignature)(e,t.jwks,"ownership",!0);if(!r.ok)return{valid:!1,reason:r.reason};if(r.header.typ!==ze.OWNERSHIP_PROOF_JWT_TYP)return{valid:!1,reason:"typ_mismatch"};let n=r.claims;if(typeof n.iss!="string"||typeof n.sub!="string"||typeof n.wallet!="string"||n.mth!=="eip191"||typeof n.nonce!="string"||typeof n.cnf?.jkt!="string"||n.tsc!==void 0&&n.tsc!==!0)return{valid:!1,reason:"bad_claim_shape"};if(n.cnf.jkt!==n.sub)return{valid:!1,reason:"cnf_jkt_mismatch"};if(t.requireTwoSided===!0&&n.tsc!==!0)return{valid:!1,reason:"not_two_sided"};if(!fS.test(n.wallet)||n.wallet!==lS(n.wallet))return{valid:!1,reason:"bad_wallet"};if(!t.acceptedIssuers.includes(n.iss))return{valid:!1,reason:"issuer_not_accepted"};if(t.expectedAgentJkt!==void 0&&n.sub!==t.expectedAgentJkt)return{valid:!1,reason:"agent_mismatch"};if(t.expectedWalletAddress!==void 0&&n.wallet!==lS(t.expectedWalletAddress))return{valid:!1,reason:"wallet_mismatch"};let i=(0,kD.temporalReason)(n,t.nowSec);return i?{valid:!1,reason:i}:{valid:!0,claims:n}}async function IJe(e,t){return(await Cee(e,t)).valid}});var Nee=g(MD=>{"use strict";Object.defineProperty(MD,"__esModule",{value:!0});MD.evaluateEconomic=OJe;var PJe=iee(),TJe=wD(),xJe=jD();async function OJe(e){let{registrationJwt:t,freshnessJwt:r,ownershipProofJwt:n,settlingWalletAddress:i,anchorPolicy:o,ownershipTrust:s,nowSec:a,maxStalenessSeconds:c,killRecords:u,runtime:d}=e,l;try{l=await(0,TJe.verifyBindingChain)({registrationJwt:t,freshnessJwt:r,anchorPolicy:o,nowSec:a,...c!==void 0?{maxStalenessSeconds:c}:{},...u!==void 0?{killRecords:u}:{}})}catch(E){l={valid:!1,tier:null,agentJkt:null,name:null,reasons:[`chain: ${E instanceof Error?E.message:String(E)}`]}}let m=l.agentJkt!==null,p=!1,h=null;if(l.agentJkt!==null)try{p=await(0,xJe.walletVerifiedFromProof)(n,{jwks:s.jwks,acceptedIssuers:s.acceptedIssuers,nowSec:a,expectedWalletAddress:i,expectedAgentJkt:l.agentJkt})}catch(E){h=E instanceof Error?E.message:String(E)}else h="no verified agent binding to attribute wallet ownership to";let y={key:m,relay:d.relay,wallet:d.wallet,walletVerified:p,trust:l.valid?"anchor_binding":"none",bindingFresh:l.valid,anchorAccepted:l.valid,policy:d.policy,facilitator:d.facilitator},b=(0,PJe.deriveCapabilities)(y),v={anchored:b.anchored,wallet_ready:b.wallet_ready,walletVerified:p,policy:d.policy,facilitator:d.facilitator},A=[];if(!b.economic){if(b.anchored||A.push(`anchored: ${l.reasons.join("; ")||"binding chain did not verify"}`),!b.wallet_ready){let E=[!m&&"agent key",!d.relay&&".relay name",!d.wallet&&"wallet record"].filter(Boolean);A.push(`wallet_ready: missing ${E.join(", ")}`)}p||A.push(`walletVerified: ${h??`ownership proof invalid or not bound to the settling wallet ${i}`}`),d.policy||A.push("policy: no active spend policy"),d.facilitator||A.push("facilitator: no valid session credential")}return{economic:b.economic,capabilities:b,conjuncts:v,agentJkt:l.agentJkt,reasons:A}}});var kee=g(iy=>{"use strict";Object.defineProperty(iy,"__esModule",{value:!0});iy.AGENT_OUTCOME_LABELS=void 0;iy.projectAgentOutcome=RJe;iy.AGENT_OUTCOME_LABELS=["Connecting","Waiting for your approval","Finishing setup","Retrying","Ready","Needs attention","Disconnected"];function RJe(e){switch(e){case"awaiting_agent":case"agent_claimed":case"code_verified":case"attach_initiated":return"Connecting";case"awaiting_human":case"awaiting_human_approval":case"attach_claimed":return"Waiting for your approval";case"authorized":case"delivered":case"human_authorized":return"Finishing setup";case"retryable_http_429":case"retryable_http_502":case"retryable_http_503":case"retryable_http_504":case"retryable_transport":return"Retrying";case"activated":case"grant_activated":case"active":return"Ready";case"cancelled":case"revoked":return"Disconnected";default:return"Needs attention"}}});var Mee=g(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.TVC_PROVIDER_WARN_THRESHOLD=qr.TURNKEY_SUBORG_RESOURCE_LIMITS=void 0;qr.tvcProviderCapacityEvidence=jee;qr.parseTvcProviderCapacityEvidence=CJe;qr.TURNKEY_SUBORG_RESOURCE_LIMITS=Object.freeze({users:100,policies:100,source:"https://docs.turnkey.com/reference/resource-limits",verifiedOn:"2026-08-29"});qr.TVC_PROVIDER_WARN_THRESHOLD=70;function jee(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error("user count is invalid");if(!Number.isSafeInteger(t)||t<0)throw new Error("policy count is invalid");let r=qr.TURNKEY_SUBORG_RESOURCE_LIMITS.users-e,n=qr.TURNKEY_SUBORG_RESOURCE_LIMITS.policies-t;return{userCount:e,policyCount:t,userLimit:qr.TURNKEY_SUBORG_RESOURCE_LIMITS.users,policyLimit:qr.TURNKEY_SUBORG_RESOURCE_LIMITS.policies,remainingUsers:r,remainingPolicies:n,pressure:e>qr.TVC_PROVIDER_WARN_THRESHOLD||t>qr.TVC_PROVIDER_WARN_THRESHOLD,limitsSource:qr.TURNKEY_SUBORG_RESOURCE_LIMITS.source,limitsVerifiedOn:qr.TURNKEY_SUBORG_RESOURCE_LIMITS.verifiedOn}}function CJe(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("TVC provider capacity evidence is invalid");let t=e,r=jee(t.userCount??-1,t.policyCount??-1);for(let n of Object.keys(r))if(t[n]!==r[n])throw new Error("TVC provider capacity evidence is invalid");if(Object.keys(t).length!==Object.keys(r).length)throw new Error("TVC provider capacity evidence is invalid");return r}});var Bee=g(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.TVC_CREDENTIAL_CONTRACT_SOURCES=Hn.TVC_CREDENTIAL_REBIND_LEAD_SECONDS=void 0;Hn.tvcCredentialLifecycleEvidence=Dee;Hn.parseTvcCredentialLifecycleEvidence=Lee;Hn.assertTvcCredentialRebindWindow=MJe;var NJe=/^(0|[1-9][0-9]*)$/;Hn.TVC_CREDENTIAL_REBIND_LEAD_SECONDS=720*60*60;Hn.TVC_CREDENTIAL_CONTRACT_SOURCES=Object.freeze({create:"https://docs.turnkey.com/api-reference/activities/create-users",read:"https://docs.turnkey.com/api-reference/queries/list-users",verifiedOn:"2026-08-29"});function qee(e,t){if(typeof e!="string"||e.length===0||e.length>256)throw new Error(`${t} is invalid`);return e}function kJe(e,t){let r=new Date(e);if(!Number.isFinite(r.getTime())||r.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function jJe(e,t){if(!NJe.test(t)||t==="0"||t.length>13)throw new Error("TVC API key expirationSeconds is invalid");let n=BigInt(new Date(e).getTime())+BigInt(t)*1000n,i=n-BigInt(Hn.TVC_CREDENTIAL_REBIND_LEAD_SECONDS)*1000n,o=8640000000000000n;if(n>o||n<-o||i>o||i<-o)throw new Error("TVC API key expiry is outside the supported date range");return{expiresAt:new Date(Number(n)).toISOString(),rebindBy:new Date(Number(i)).toISOString()}}function Dee(e){let t=qee(e.apiKeyId,"TVC API key id"),r=qee(e.apiKeyName,"TVC API key name"),n=kJe(e.createdAt,"TVC API key creation time"),i=e.expirationSeconds??null,o=i===null?null:jJe(n,i);return{schemaVersion:1,apiKeyId:t,apiKeyName:r,createdAt:n,expirationSeconds:i,expiresAt:o?.expiresAt??null,rebindBy:o?.rebindBy??null,minimumRebindLeadSeconds:Hn.TVC_CREDENTIAL_REBIND_LEAD_SECONDS,currentImageContract:"tvc_signer_v1",finalContractRebindRequired:!0,cohortEligible:!1,contractSources:Hn.TVC_CREDENTIAL_CONTRACT_SOURCES}}function Lee(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("TVC credential lifecycle evidence is invalid");let t=e,r=Dee({apiKeyId:t.apiKeyId??"",apiKeyName:t.apiKeyName??"",createdAt:t.createdAt??"",expirationSeconds:t.expirationSeconds});for(let n of Object.keys(r))if(n==="contractSources"){let i=t.contractSources;if(!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).sort().join(",")!=="create,read,verifiedOn"||i.create!==r.contractSources.create||i.read!==r.contractSources.read||i.verifiedOn!==r.contractSources.verifiedOn)throw new Error("TVC credential lifecycle evidence is invalid")}else if(t[n]!==r[n])throw new Error("TVC credential lifecycle evidence is invalid");if(Object.keys(t).length!==Object.keys(r).length)throw new Error("TVC credential lifecycle evidence is invalid");return r}function MJe(e,t=new Date){let r=Lee(e);if(!Number.isFinite(t.getTime()))throw new Error("TVC credential observation time is invalid");if(r.expiresAt!==null&&new Date(r.expiresAt).getTime()<=t.getTime()+Hn.TVC_CREDENTIAL_REBIND_LEAD_SECONDS*1e3)throw new Error("TVC credential expires inside the required rebind lead")}});var Uee=g(pS=>{"use strict";Object.defineProperty(pS,"__esModule",{value:!0});pS.TVC_SIGNER_POLICY_CONTRACT_VERSION=void 0;pS.TVC_SIGNER_POLICY_CONTRACT_VERSION=1});var Fee=g(qD=>{"use strict";Object.defineProperty(qD,"__esModule",{value:!0});qD.checkTvcPinParity=HJe;var mS=/^[0-9a-f]{64}$/,Hee=16*1024,qJe=4096,DJe="tvc-proof-verifier.railway.internal",gS=class extends Error{};function LJe(e,t){return Object.keys(e).sort().join(",")===[...t].sort().join(",")}function BJe(e){try{let t=new URL(e),r=t.protocol==="http:"&&t.hostname===DJe&&t.port!=="";return t.protocol!=="https:"&&!r||t.username!==""||t.password!==""||t.search!==""||t.hash!==""?null:(t.pathname="/effective-pins",t)}catch{return null}}async function UJe(e){let t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>Hee)throw await e.body?.cancel().catch(()=>{}),new Error("response too large");let r=e.body?.getReader();if(!r)throw new Error("response body missing");let n=[],i=0,o=async()=>{try{return await r.read()}catch{throw new gS}};try{for(;;){let c=await o();if(c.done)break;if(i+=c.value.byteLength,i>Hee)throw await r.cancel().catch(()=>{}),new Error("response too large");n.push(c.value)}}finally{r.releaseLock()}let s=new Uint8Array(i),a=0;for(let c of n)s.set(c,a),a+=c.byteLength;return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s))}async function HJe(e){let t=e.verifierUrl?.trim()??"",r=e.bearerToken?.trim()??"",n=e.approvedManifestDigest?.trim()??"",i=e.approvedPivotDigest?.trim()??"",o=[t,r,n,i].filter(Boolean).length;if(o===0)return{status:"dark"};let s=t?BJe(t):null;if(o!==4||!s||r.length>qJe||!mS.test(n)||!mS.test(i))return{status:"invalid_configuration"};let a;try{a=await(e.fetchImpl??fetch)(s,{method:"GET",redirect:"error",headers:{accept:"application/json",authorization:`Bearer ${r}`},signal:AbortSignal.timeout(Math.min(Math.max(e.timeoutMs??5e3,100),1e4))})}catch{return{status:"verifier_unavailable"}}if(!a.ok)return await a.body?.cancel().catch(()=>{}),a.status===401||a.status===403?{status:"verifier_auth_failed"}:a.status===408||a.status===425||a.status===429||a.status>=500?{status:"verifier_unavailable"}:{status:"verifier_invalid_response"};let c;try{c=await UJe(a)}catch(d){return{status:d instanceof gS?"verifier_unavailable":"verifier_invalid_response"}}if(typeof c!="object"||c===null||Array.isArray(c)||!LJe(c,["approvedManifestDigest","approvedPivotDigest"]))return{status:"verifier_invalid_response"};let u=c;return typeof u.approvedManifestDigest!="string"||!mS.test(u.approvedManifestDigest)||typeof u.approvedPivotDigest!="string"||!mS.test(u.approvedPivotDigest)?{status:"verifier_invalid_response"}:u.approvedManifestDigest!==n?{status:"manifest_mismatch"}:u.approvedPivotDigest!==i?{status:"pivot_mismatch"}:{status:"ready"}}});var DD=g(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.ACCOUNT_OPERATION_EVIDENCE_TYPES=_r.ACCOUNT_OPERATION_PROOF_LEVELS=_r.ACCOUNT_OPERATION_OUTCOMES=_r.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION=void 0;_r.cardProofLevel=FJe;_r.cardStatusClaimsProcessorTruth=$Je;_r.parseAccountOperationReceipt=GJe;_r.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION=1;_r.ACCOUNT_OPERATION_OUTCOMES=["pending","completed","failed","uncertain","released","reversed","disputed"];_r.ACCOUNT_OPERATION_PROOF_LEVELS=["none","platform_observed","merchant_reported","owner_attested","processor_confirmed","network_verified","settled"];var $ee={sale_accepted:"merchant_reported",auth_held:"merchant_reported",capture_pending:"merchant_reported",captured:"processor_confirmed",voided:"processor_confirmed",refunded:"processor_confirmed",partially_refunded:"processor_confirmed",refund_pending:"processor_confirmed",chargeback_open:"processor_confirmed",chargeback_lost:"processor_confirmed",chargeback_won:"processor_confirmed",pending:"platform_observed",needs_reconciliation:"platform_observed"};function FJe(e,t){let r=$ee[e]??"platform_observed";return r==="processor_confirmed"&&!t?"merchant_reported":r}function $Je(e){return $ee[e]==="processor_confirmed"}_r.ACCOUNT_OPERATION_EVIDENCE_TYPES=["platform_activity","merchant_confirmation","card_lifecycle","onchain_transaction"];function hc(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Rs(e){return e===null||typeof e=="string"}function oy(e){return typeof e=="string"&&e.length>0&&!Number.isNaN(Date.parse(e))}function yc(e,t){let r=Object.keys(e).sort(),n=[...t].sort();return r.length===n.length&&r.every((i,o)=>i===n[o])}function JJe(e){return hc(e)?yc(e,["type","source","observedAt","reference","url"])&&typeof e.type=="string"&&_r.ACCOUNT_OPERATION_EVIDENCE_TYPES.includes(e.type)&&typeof e.source=="string"&&oy(e.observedAt)&&Rs(e.reference)&&Rs(e.url):!1}function VJe(e){return hc(e)?yc(e,["type","at"])&&typeof e.type=="string"&&e.type.length>0&&oy(e.at):!1}function GJe(e){if(!hc(e)||!yc(e,["schemaVersion","operationId","activityId","payment","route","party","authority","outcome","evidence","timeline","dataCompleteness"])||e.schemaVersion!==_r.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION||typeof e.operationId!="string"||typeof e.activityId!="string"||e.dataCompleteness!=="complete"&&e.dataCompleteness!=="partial"||!Array.isArray(e.evidence)||!e.evidence.every(JJe)||!Array.isArray(e.timeline)||!e.timeline.every(VJe))return null;let t=e.payment,r=e.route,n=e.party,i=e.authority,o=e.outcome;return!hc(t)||!yc(t,["amountAtomic","decimals","currency","merchant","description","createdAt"])||typeof t.amountAtomic!="string"||!/^\d+$/.test(t.amountAtomic)||typeof t.decimals!="number"||!Number.isInteger(t.decimals)||t.decimals<0||t.decimals>18||typeof t.currency!="string"||typeof t.merchant!="string"||typeof t.description!="string"||!oy(t.createdAt)||!hc(r)||!yc(r,["rail","protocol","network","cardLast4"])||r.rail!=="wallet"&&r.rail!=="card"||!(r.protocol===null||r.protocol==="x402"||r.protocol==="mpp"||r.protocol==="vic"||r.protocol==="virtual_card")||!Rs(r.network)||!Rs(r.cardLast4)||!hc(n)||!yc(n,["agentId","agentName"])||!Rs(n.agentId)||!Rs(n.agentName)||!hc(i)||!yc(i,["grantId","mandateId","drawId"])||!Rs(i.grantId)||!Rs(i.mandateId)||!Rs(i.drawId)||!hc(o)||!yc(o,["status","proofLevel","final","updatedAt","finalizesBy"])||typeof o.status!="string"||!_r.ACCOUNT_OPERATION_OUTCOMES.includes(o.status)||typeof o.proofLevel!="string"||!_r.ACCOUNT_OPERATION_PROOF_LEVELS.includes(o.proofLevel)||typeof o.final!="boolean"||!oy(o.updatedAt)||!(o.finalizesBy===null||oy(o.finalizesBy))?null:e}});var LD=g(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.CARD_PAYMENT_ATTEMPT_STATUSES=Ie.CARD_PAYMENT_EVENT_REQUIRED_PROVENANCE=Ie.CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES=Ie.CARD_PAYMENT_SOURCE_PROVENANCE=Ie.CARD_PAYMENT_PROVENANCES=Ie.CARD_PAYMENT_UNMATCHED_EVENT_TYPES=Ie.OWNER_ATTESTATION_VERDICTS=Ie.CARD_PAYMENT_EVENT_TYPES=Ie.CARD_PAYMENT_INTENTS=Ie.CARD_PAYMENT_UNMATCHED_SOURCES=Ie.CARD_PAYMENT_SOURCES=Ie.CARD_PAYMENT_UNMATCHED_PROCESSORS=Ie.CARD_PAYMENT_PROCESSORS=void 0;Ie.isOwnerAttestationVerdict=Gee;Ie.provenanceOfSource=Kee;Ie.requiresProviderProvenance=KJe;Ie.requiredProvenanceFor=Wee;Ie.reduceCardPaymentEvents=r7e;Ie.CARD_PAYMENT_PROCESSORS=["cybersource","vgs"];Ie.CARD_PAYMENT_UNMATCHED_PROCESSORS=["cybersource"];Ie.CARD_PAYMENT_SOURCES=["auth_request","mpp_gateway","cybersource_tss","cybersource_report","cybersource_webhook","web_vgs","admin","owner_attestation"];Ie.CARD_PAYMENT_UNMATCHED_SOURCES=["cybersource_report","cybersource_tss","cybersource_webhook","admin"];Ie.CARD_PAYMENT_INTENTS=["sale","auth","capture","refund","void","unknown"];Ie.CARD_PAYMENT_EVENT_TYPES=["charge_requested","charge_ambiguous","sale_accepted","auth_held","capture_pending","captured","voided","refund_pending","refund_succeeded","refund_failed","chargeback_opened","chargeback_lost","chargeback_won","processor_unknown","reconciliation_gap","owner_attested"];Ie.OWNER_ATTESTATION_VERDICTS=["found_charge","merchant_completed","no_charge_visible"];function Gee(e){return typeof e=="string"&&Ie.OWNER_ATTESTATION_VERDICTS.includes(e)}Ie.CARD_PAYMENT_UNMATCHED_EVENT_TYPES=["refund_succeeded","chargeback_opened","chargeback_lost","chargeback_won","processor_unknown","reconciliation_gap"];Ie.CARD_PAYMENT_PROVENANCES=["provider","platform_caller","owner","operator"];Ie.CARD_PAYMENT_SOURCE_PROVENANCE={auth_request:"platform_caller",mpp_gateway:"platform_caller",web_vgs:"platform_caller",cybersource_tss:"provider",cybersource_report:"provider",cybersource_webhook:"provider",admin:"operator",owner_attestation:"owner"};function Kee(e){return Ie.CARD_PAYMENT_SOURCE_PROVENANCE[e]??"platform_caller"}Ie.CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES=new Set(["auth_held","capture_pending","captured","voided","refund_pending","refund_succeeded","refund_failed","chargeback_opened","chargeback_lost","chargeback_won"]);function KJe(e){return Ie.CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES.has(e)}Ie.CARD_PAYMENT_EVENT_REQUIRED_PROVENANCE={...Object.fromEntries([...Ie.CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES].map(e=>[e,"provider"])),owner_attested:"owner"};function Wee(e){return Ie.CARD_PAYMENT_EVENT_REQUIRED_PROVENANCE[e]??null}Ie.CARD_PAYMENT_ATTEMPT_STATUSES=["pending","needs_reconciliation","auth_held","capture_pending","sale_accepted","captured","voided","refund_pending","partially_refunded","refunded","chargeback_open","chargeback_lost","chargeback_won"];var WJe=-9223372036854775808n,zJe=9223372036854775807n;function Jee(e){if(!e)return null;let r=(e instanceof Date?e:new Date(e)).getTime();return Number.isFinite(r)?r:null}function zee(e){if(!/^-?\d+$/.test(e))return null;try{let t=BigInt(e);return t>=WJe&&t<=zJe?t:null}catch{return null}}function YJe(e){return e==null?0n:typeof e=="number"?Number.isSafeInteger(e)?BigInt(e):0n:zee(e)??0n}function XJe(e){let t=Jee(e.observedAt)??0;return{event:e,primaryAt:Jee(e.occurredAt)??t,observedAt:t,id:YJe(e.id)}}function ZJe(e,t){let r=e.primaryAt-t.primaryAt;if(r!==0)return r;let n=e.observedAt-t.observedAt;if(n!==0)return n;let i=e.id-t.id;return i<0n?-1:i>0n?1:0}function Vee(e){return e==null?null:typeof e=="bigint"?e:typeof e=="number"?Number.isFinite(e)&&Number.isSafeInteger(e)?BigInt(e):null:zee(e)}function QJe(e,t){return e>0n&&t<e?"partially_refunded":"refunded"}function e7e(e){return e==="charge_requested"||e==="auth_held"||e==="capture_pending"||e==="sale_accepted"||e==="captured"}function t7e(e,t){return e===t||t==="needs_reconciliation"?!0:e==="captured"?t==="refund_pending"||t==="partially_refunded"||t==="refunded":e==="sale_accepted"?t==="captured"||t==="refund_pending"||t==="partially_refunded"||t==="refunded"||t==="voided":e==="refund_pending"?t==="partially_refunded"||t==="refunded"||t==="refund_pending":e==="partially_refunded"?t==="partially_refunded"||t==="refunded":e==="refunded"?t==="refunded":e==="voided"?t==="voided":!0}function Cs(e,t,r,n){return t7e(e,t)?{status:t,reason:n}:{status:e,reason:r}}function r7e(e,t={}){let r="needs_reconciliation",n="no_processor_events",i=[],o=!1,s=null,a=0n,c=Vee(t.attemptAmountMicros),u=c!==null&&c>0n?c:0n,d=null,l=null,m=!1,p=t.attemptAmountMicros!==null&&t.attemptAmountMicros!==void 0&&(c===null||c<0n)?"invalid_amount":null,h=e.map(XJe).sort(ZJe).map(({event:y})=>y);for(let y of h){let b=Kee(y.source),v=Wee(y.eventType);if(v!==null&&b!==v){i.push({eventType:y.eventType,source:y.source,provenance:b,requiredProvenance:v});continue}if(y.eventType==="owner_attested"){o=!0,Gee(y.ownerVerdict)&&(s=y.ownerVerdict);continue}let A=Vee(y.amountMicros);if(y.amountMicros!==null&&y.amountMicros!==void 0&&(A===null||A<0n)){p="invalid_amount",r="needs_reconciliation",n="invalid_amount";continue}if((y.amountMicros===null||y.amountMicros===void 0)&&e7e(y.eventType)&&u<=0n){p="missing_amount",r="needs_reconciliation",n="missing_amount";continue}let E=A??u;if(y.eventType==="chargeback_opened"||y.eventType==="chargeback_lost"){d=y.eventType==="chargeback_opened"?"chargeback_open":"chargeback_lost",l=y.eventType,m=!0;continue}if(y.eventType==="chargeback_won"){d=null,l=null,m=!1,r==="needs_reconciliation"&&(r="chargeback_won",n="chargeback_won");continue}switch(y.eventType){case"charge_requested":E>u&&(u=E),{status:r,reason:n}=Cs(r,"pending",n,"charge_requested");break;case"charge_ambiguous":case"processor_unknown":case"reconciliation_gap":({status:r,reason:n}=Cs(r,"needs_reconciliation",n,y.eventType));break;case"auth_held":E>u&&(u=E),{status:r,reason:n}=Cs(r,"auth_held",n,"auth_held");break;case"capture_pending":E>u&&(u=E),{status:r,reason:n}=Cs(r,"capture_pending",n,"capture_pending");break;case"sale_accepted":E>u&&(u=E),{status:r,reason:n}=Cs(r,"sale_accepted",n,"sale_accepted");break;case"captured":E>u&&(u=E),{status:r,reason:n}=Cs(r,"captured",n,"captured");break;case"voided":({status:r,reason:n}=Cs(r,"voided",n,"voided"));break;case"refund_pending":({status:r,reason:n}=Cs(r,"refund_pending",n,"refund_pending"));break;case"refund_succeeded":if(A===null){p="missing_amount",r="needs_reconciliation",n="missing_amount";continue}a+=E,u>0n&&a>u&&(a=u),{status:r,reason:n}=Cs(r,QJe(u,a),n,"refund_succeeded");break;case"refund_failed":n="refund_failed";break}}return d?{status:d,statusReason:l??d,refundMicros:a,hasChargeback:m,rejectedProcessorClaims:i,ownerAttested:o,ownerVerdict:s}:p?{status:"needs_reconciliation",statusReason:p,refundMicros:a,hasChargeback:m,rejectedProcessorClaims:i,ownerAttested:o,ownerVerdict:s}:{status:r,statusReason:n,refundMicros:a,hasChargeback:m,rejectedProcessorClaims:i,ownerAttested:o,ownerVerdict:s}}});var ste=g(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});Mi.CardPaymentDbValidationError=void 0;Mi.validateCardPaymentEventInsertRow=tte;Mi.validateCardPaymentUnmatchedEventInsertRow=rte;Mi.assertValidCardPaymentAttemptStatus=nte;Mi.insertCardPaymentLifecycleEvent=p7e;Mi.insertCardPaymentLifecycleEventWithId=ote;Mi.refreshCardPaymentAttemptProjection=m7e;Mi.insertCardPaymentUnmatchedEvent=g7e;var bc=LD(),Sd=class extends Error{table;offendingKeys;constructor(t,r,n){super(`[pg:${r}] ${t}`),this.table=r,this.offendingKeys=n,this.name="CardPaymentDbValidationError"}};Mi.CardPaymentDbValidationError=Sd;function Dr(e,t,r){throw new Sd(t,e,Object.keys(r))}function Xee(e,t){if(!t||typeof t!="object"||Array.isArray(t))throw new Sd("row must be a non-array object",e,[]);return t}function Zee(e,t,r){for(let n of Object.keys(t))r.has(n)||Dr(e,`unknown column "${n}"`,t)}function Qee(e,t,r){for(let n of r)(t[n]===void 0||t[n]===null)&&Dr(e,`required column "${n}" is missing`,t)}function _c(e,t,r,n={}){let i=t[r];if(i==null){if(n.nullable)return;Dr(e,`${r} must be a string`,t)}typeof i!="string"&&Dr(e,`${r} must be a string`,t),n.nonEmpty&&i.length===0&&Dr(e,`${r} must be non-empty`,t),n.maxLen&&i.length>n.maxLen&&Dr(e,`${r} exceeds ${n.maxLen} chars`,t)}function mp(e,t,r,n){let i=t[r];(typeof i!="string"||!n.has(i))&&Dr(e,`${r} must be one of ${[...n].join("|")}`,t)}function ete(e,t,r){let n=t[r],i=9223372036854775807n,o=typeof n=="bigint"?n:typeof n=="string"&&/^\d+$/.test(n)&&n.length<=19?BigInt(n):null;o===null&&Dr(e,`${r} must be a numeric integer string`,t),o<=0n&&Dr(e,`${r} must be positive`,t),o>i&&Dr(e,`${r} must fit signed 64-bit integer`,t)}var n7e=new Set(["attempt_id","transaction_id","user_login","processor","source","event_type","processor_event_id","processor_transaction_id","amount_micros","currency","processor_status","occurred_at","payload"]),i7e=new Set(["processor","source","event_type","processor_event_id","processor_transaction_id","amount_micros","currency","payload"]),o7e=["user_login","processor","source","event_type","payload"],s7e=["processor","source","event_type","payload"],a7e=new Set(bc.CARD_PAYMENT_PROCESSORS),c7e=new Set(bc.CARD_PAYMENT_UNMATCHED_PROCESSORS),u7e=new Set(bc.CARD_PAYMENT_SOURCES),d7e=new Set(bc.CARD_PAYMENT_UNMATCHED_SOURCES),l7e=new Set(bc.CARD_PAYMENT_EVENT_TYPES),f7e=new Set(bc.CARD_PAYMENT_UNMATCHED_EVENT_TYPES),Yee=new Set(bc.CARD_PAYMENT_ATTEMPT_STATUSES);function tte(e){let t=Xee("card_payment_events",e);Zee("card_payment_events",t,n7e),Qee("card_payment_events",t,o7e);for(let r of["attempt_id","transaction_id"]){let n=t[r];if(n!=null){let i=typeof n=="string"&&/^\d+$/.test(n)?Number(n):n;(typeof i!="number"||!Number.isInteger(i)||i<=0)&&Dr("card_payment_events",`${r} must be a positive integer or null`,t)}}_c("card_payment_events",t,"user_login",{nonEmpty:!0,maxLen:255}),mp("card_payment_events",t,"processor",a7e),mp("card_payment_events",t,"source",u7e),mp("card_payment_events",t,"event_type",l7e),t.processor_event_id!==null&&t.processor_event_id!==void 0&&_c("card_payment_events",t,"processor_event_id",{nonEmpty:!0,maxLen:255,nullable:!0}),t.processor_transaction_id!==null&&t.processor_transaction_id!==void 0&&_c("card_payment_events",t,"processor_transaction_id",{nonEmpty:!0,maxLen:255,nullable:!0}),t.amount_micros!==null&&t.amount_micros!==void 0&&ete("card_payment_events",t,"amount_micros"),t.currency!==null&&t.currency!==void 0&&_c("card_payment_events",t,"currency",{nonEmpty:!0,maxLen:3,nullable:!0}),t.processor_status!==null&&t.processor_status!==void 0&&_c("card_payment_events",t,"processor_status",{nonEmpty:!0,maxLen:128,nullable:!0}),t.occurred_at!==null&&t.occurred_at!==void 0&&!(t.occurred_at instanceof Date)&&typeof t.occurred_at!="string"&&Dr("card_payment_events","occurred_at must be a Date, ISO string, or null",t),typeof t.payload!="string"&&Dr("card_payment_events","payload must be a JSON string",t);try{JSON.parse(t.payload)}catch{Dr("card_payment_events","payload must be valid JSON",t)}}function rte(e){let t=Xee("card_payment_unmatched_events",e);Zee("card_payment_unmatched_events",t,i7e),Qee("card_payment_unmatched_events",t,s7e),mp("card_payment_unmatched_events",t,"processor",c7e),mp("card_payment_unmatched_events",t,"source",d7e),mp("card_payment_unmatched_events",t,"event_type",f7e),t.processor_event_id!==null&&t.processor_event_id!==void 0&&_c("card_payment_unmatched_events",t,"processor_event_id",{nonEmpty:!0,maxLen:255,nullable:!0}),t.processor_transaction_id!==null&&t.processor_transaction_id!==void 0&&_c("card_payment_unmatched_events",t,"processor_transaction_id",{nonEmpty:!0,maxLen:255,nullable:!0}),t.amount_micros!==null&&t.amount_micros!==void 0&&ete("card_payment_unmatched_events",t,"amount_micros"),t.currency!==null&&t.currency!==void 0&&_c("card_payment_unmatched_events",t,"currency",{nonEmpty:!0,maxLen:3,nullable:!0}),typeof t.payload!="string"&&Dr("card_payment_unmatched_events","payload must be a JSON string",t);try{JSON.parse(t.payload)}catch{Dr("card_payment_unmatched_events","payload must be valid JSON",t)}}function nte(e){if(!Yee.has(e))throw new Sd(`current_status must be one of ${[...Yee].join("|")}`,"card_payment_attempts",["current_status"])}function ite(e){return e===null?null:typeof e=="number"?e:Number(e)}async function p7e(e,t){return(await ote(e,t)).inserted}async function ote(e,t){let r={attempt_id:ite(t.attemptId),transaction_id:t.transactionId,user_login:t.userLogin,processor:t.processor??"cybersource",source:t.source,event_type:t.eventType,processor_event_id:t.processorEventId,processor_transaction_id:t.processorTransactionId,amount_micros:t.amountMicros,currency:t.currency,processor_status:t.processorStatus,occurred_at:t.occurredAt??null,payload:JSON.stringify(t.payload)};tte(r);let i=(await e.query(`INSERT INTO card_payment_events (
66
+ attempt_id, transaction_id, user_login, processor, source, event_type,
67
+ processor_event_id, processor_transaction_id, amount_micros, currency,
68
+ processor_status, occurred_at, payload
69
+ ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9::bigint,$10,$11,$12::timestamptz,$13::jsonb)
70
+ ON CONFLICT (processor, processor_event_id)
71
+ WHERE processor_event_id IS NOT NULL
72
+ DO NOTHING
73
+ RETURNING id::text`,[r.attempt_id,r.transaction_id,r.user_login,r.processor,r.source,r.event_type,r.processor_event_id,r.processor_transaction_id,r.amount_micros,r.currency,r.processor_status,r.occurred_at,r.payload])).rows[0]?.id,o=i===void 0?null:Number(i);return{inserted:o!==null,eventId:o}}async function m7e(e,t){let r=ite(t);if(r===null)throw new Sd("attempt_id is required","card_payment_attempts",["attempt_id"]);let i=(await e.query(`SELECT amount_micros::text AS amount_micros
74
+ FROM card_payment_attempts
75
+ WHERE id = $1
76
+ FOR UPDATE`,[r])).rows[0]?.amount_micros;if(!i)return null;let o=await e.query(`SELECT id::text AS id, event_type, source, amount_micros::text AS amount_micros,
77
+ processor_status, payload->>'verdict' AS owner_verdict, occurred_at, observed_at
78
+ FROM card_payment_events
79
+ WHERE attempt_id = $1
80
+ ORDER BY COALESCE(occurred_at, observed_at) ASC, observed_at ASC, id ASC`,[r]),s=o.rows[o.rows.length-1]?.id??null,a=(0,bc.reduceCardPaymentEvents)(o.rows.map(c=>({id:c.id,eventType:c.event_type,source:c.source,amountMicros:c.amount_micros,processorStatus:c.processor_status,ownerVerdict:c.owner_verdict,occurredAt:c.occurred_at,observedAt:c.observed_at})),{attemptAmountMicros:i});return nte(a.status),await e.query(`UPDATE card_payment_attempts
81
+ SET current_status = $2,
82
+ status_reason = $3,
83
+ last_event_id = $4,
84
+ last_observed_at = NOW(),
85
+ updated_at = NOW()
86
+ WHERE id = $1`,[r,a.status,a.statusReason,s]),{status:a.status,statusReason:a.statusReason,rejectedProcessorClaims:a.rejectedProcessorClaims,ownerAttested:a.ownerAttested,ownerVerdict:a.ownerVerdict}}async function g7e(e,t){let r={processor:"cybersource",source:"cybersource_report",event_type:t.eventType,processor_event_id:t.processorEventId,processor_transaction_id:t.processorTransactionId,amount_micros:t.amountMicros,currency:t.currency,payload:JSON.stringify(t.payload)};return rte(r),((await e.query(`INSERT INTO card_payment_unmatched_events (
87
+ processor, source, event_type, processor_event_id, processor_transaction_id,
88
+ amount_micros, currency, payload
89
+ ) VALUES ('cybersource', 'cybersource_report', $1, $2, $3, $4::bigint, $5, $6::jsonb)
90
+ ON CONFLICT (processor, source, processor_event_id)
91
+ WHERE processor_event_id IS NOT NULL
92
+ DO NOTHING`,[r.event_type,r.processor_event_id,r.processor_transaction_id,r.amount_micros,r.currency,r.payload])).rowCount??0)>0}});var lte=g(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});qi.normalizeRailEnvironmentValue=ate;qi.isLiveVgsEnvironment=_7e;qi.isExplicitProductionRailEnvironment=hS;qi.isPublicPreviewRailEnvironment=FD;qi.clickhouseDatabaseHasStagingMarker=ute;qi.resolveClickhouseEnvBinding=w7e;qi.resolveDeploymentEnvClass=dte;qi.detectDeploymentEnvNodeEnvMismatch=v7e;qi.isExplicitPreviewPaymentRailOptIn=S7e;var h7e=new Set(["visacli.sh","app.visacli.sh","auth.visacli.sh","mpp.visacli.sh","api.visacli.sh"]),BD="visa-code-preview",y7e=new Set(["mpp-visa-code-preview.up.railway.app"]);function Po(e){return(e||"").trim().toLowerCase()}function HD(e){let t=Po(e),r=t;(t.startsWith("http://")||t.startsWith("https://"))&&(r=t.slice(t.indexOf("://")+3));let n=r.indexOf("/");n!==-1&&(r=r.slice(0,n));let i=r.indexOf(":");return i!==-1&&(r=r.slice(0,i)),r.startsWith("www.")?r.slice(4):r}function UD(e,t){let r="";for(let n of Po(e)){if(n>="a"&&n<="z"||n>="0"&&n<="9"){r+=n;continue}if(r&&t.has(r))return!0;r=""}return r?t.has(r):!1}function ate(e){return Po(e)}function cte(e){return(e||"").trim()}function _7e(e){return new Set(["live","prod","production"]).has(ate(e))}function b7e(e){return typeof e=="boolean"?e:cte(e)==="true"}function hS(e){let t=HD(e.railwayPublicDomain),r=Po(e.railwayEnvironment),n=Po(e.railwayEnvironmentName),i=Po(e.railwayGitBranch);return h7e.has(t)||r==="production"||n==="production"||i==="main"||i==="production"}function FD(e){if(hS(e))return!1;let t=HD(e.railwayPublicDomain),r=new Set(["preview","staging","stage"]),n=new Set(["preview"]),i=Po(e.railwayGitBranch);return UD(t,n)||UD(e.railwayEnvironment,r)||UD(e.railwayEnvironmentName,r)||i==="staging"||i==="preview"||t.endsWith(".up.railway.app")||t.endsWith(".railway.app")}var E7e=new Set(["staging","stage","preview"]);function ute(e){let t=Po(e);if(!t)return!1;for(let r of t.split(/[^a-z0-9]+/))if(E7e.has(r))return!0;return!1}function w7e(e){let t=(e.clickhouseDatabase||"").trim(),r=ute(t);return hS(e)?r?{status:"mismatch",environment:"production",database:t,message:`production deploy is pointed at a non-production ClickHouse database (${t||"<empty>"}); production must use an unmarked database such as visa_mcp`}:{status:"ok",environment:"production",database:t}:FD(e)?r?{status:"ok",environment:"preview",database:t}:{status:"mismatch",environment:"preview",database:t,message:`staging/preview deploy is pointed at the production ClickHouse database (${t||"<empty>"}); staging must use a marked database such as visa_mcp_staging`}:{status:"indeterminate"}}function dte(e){return hS(e)?"production":FD(e)?"preview":"unknown"}function v7e(e,t){let r=dte(e),n=(t||"").trim().toLowerCase();return r==="unknown"?{status:"indeterminate",deploymentEnv:r,nodeEnv:n,message:null}:r==="production"?n===""||n==="production"?{status:"ok",deploymentEnv:r,nodeEnv:n,message:null}:{status:"mismatch",deploymentEnv:r,nodeEnv:n,message:`Railway signals classify this deploy as production, but NODE_ENV=${n||"<empty>"}. Dev-only guards keyed on NODE_ENV!=='production' would silently activate. Set NODE_ENV=production on this Railway service.`}:new Set(["","development","test","preview","staging","production"]).has(n)?{status:"ok",deploymentEnv:r,nodeEnv:n,message:null}:{status:"mismatch",deploymentEnv:r,nodeEnv:n,message:`Railway signals classify this deploy as preview/staging, but NODE_ENV=${n||"<empty>"}. Set NODE_ENV=production on deployed Railway preview services.`}}function S7e(e){if(!b7e(e.allowPreviewLivePaymentRails)||cte(e.previewPaymentRailProfile)!==BD)return!1;let t=Po(e.railwayEnvironment),r=Po(e.railwayEnvironmentName);if(t!==BD||r!==BD)return!1;let n=HD(e.railwayPublicDomain);return y7e.has(n)}});var pte=g(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});Ad.PREVIEW_LEGACY_BALANCE_DRIFT_BASELINE=void 0;Ad.matchesPreviewLegacyBalanceDrift=A7e;var $D=[{ownerIdentityDigest:"7b9d6737bc901bb6dcf5048c314c3b0702605228346c6c470583df69bf8de9f5",balanceMicros:"4910228",ledgerSumMicros:"4850228",driftMicros:"60000"},{ownerIdentityDigest:"e057a8228dbc8a550e70c98d79ada53df841020b68f59f6a448ba585b38dd126",balanceMicros:"5608536",ledgerSumMicros:"5528536",driftMicros:"80000"},{ownerIdentityDigest:"05410c30d7fe5ee48859106ee484aa6e5b35637a986545a743497455decc3925",balanceMicros:"6242951",ledgerSumMicros:"-10959519",driftMicros:"17202470"},{ownerIdentityDigest:"c1999d183182d21b750b9b45f82dddc93beeb6aa930a3299bcf54c3d7a36963f",balanceMicros:"4",ledgerSumMicros:"-19999996",driftMicros:"20000000"},{ownerIdentityDigest:"41bc90e14117747ab05a516c582e1956d8dd11571875f86af5e2a128b35346e4",balanceMicros:"20000000",ledgerSumMicros:"0",driftMicros:"20000000"}];Ad.PREVIEW_LEGACY_BALANCE_DRIFT_BASELINE=Object.freeze({issue:8009,count:$D.length,absoluteMicros:"57342470"});function yS(e){try{return BigInt(e).toString()}catch{return null}}function fte(e,t){let r=BigInt(e),n=BigInt(t);return r<n?-1:r>n?1:0}function A7e(e){if(e.deploymentEnvironment!=="preview"||e.totalCount!==Ad.PREVIEW_LEGACY_BALANCE_DRIFT_BASELINE.count||yS(e.totalAbsoluteMicros)!==Ad.PREVIEW_LEGACY_BALANCE_DRIFT_BASELINE.absoluteMicros||e.rows.length!==$D.length)return!1;let t=e.rows.map(r=>({ownerIdentityDigest:r.ownerIdentityDigest?.toLowerCase()??null,balanceMicros:yS(r.balanceMicros),ledgerSumMicros:yS(r.ledgerSumMicros),driftMicros:yS(r.driftMicros)}));return t.some(r=>r.ownerIdentityDigest===null||!/^[a-f0-9]{64}$/.test(r.ownerIdentityDigest)||r.balanceMicros===null||r.ledgerSumMicros===null||r.driftMicros===null)?!1:(t.sort((r,n)=>{let i=fte(r.driftMicros,n.driftMicros);return i!==0?i:fte(r.balanceMicros,n.balanceMicros)}),t.every((r,n)=>{let i=$D[n];return r.ownerIdentityDigest===i?.ownerIdentityDigest&&r.balanceMicros===i?.balanceMicros&&r.ledgerSumMicros===i.ledgerSumMicros&&r.driftMicros===i.driftMicros}))}});var mte=g(gp=>{"use strict";Object.defineProperty(gp,"__esModule",{value:!0});gp.DEFAULT_FETCH_TIMEOUT_MS=void 0;gp.fetchWithTimeout=I7e;gp.DEFAULT_FETCH_TIMEOUT_MS=15e3;function I7e(e,t={},r=gp.DEFAULT_FETCH_TIMEOUT_MS){return fetch(e,{...t,signal:t.signal??AbortSignal.timeout(r)})}});var hte=g(sy=>{"use strict";Object.defineProperty(sy,"__esModule",{value:!0});sy.normalizeAgentName=VD;sy.parseAgentSelector=gte;sy.computeAgentSelection=P7e;function VD(e){return e.replace(/\.visa$/i,"").toLowerCase()}function gte(e){if(e!==void 0){if(typeof e!="string"||e.trim().length===0)throw new Error("Invalid agent selector. Pass a non-empty agent name or stable id.");return e.trim()}}function JD(e,t){return t?` Available: ${e.map(t).join(", ")}.`:""}function P7e(e){let t=gte(e.requested);if(t){let r=VD(t),n=e.candidates.filter(i=>i.exactSelectors.includes(t)||i.names?.some(o=>VD(o)===r));return n.length>1?{kind:"ambiguous",message:`more than one ${e.duplicateAuthorityLabel??e.authorityLabel} is named "${t}".${JD(n,e.describeCandidate)} Select the exact ${e.exactSelectorLabel??"stable id"}. `+e.selectorGuidance,matches:n.map(i=>i.value)}:n.length===1?{kind:"selected",value:n[0].value}:{kind:"not_found",requested:t,message:`no ${e.authorityLabel} matched ${JSON.stringify(t)}.`+JD(e.candidates,e.describeCandidate)+` ${e.selectorGuidance}`}}return e.candidates.length>1?{kind:"ambiguous",message:`more than one ${e.authorityLabel} is available.${JD(e.candidates,e.describeCandidate)} ${e.selectorGuidance}`,matches:e.candidates.map(r=>r.value)}:e.candidates.length===1?{kind:"selected",value:e.candidates[0].value}:{kind:"none"}}});var _S=g(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.CanonicalJsonError=Vt.CANONICAL_OPAQUE_ID_MAX_BYTES=Vt.CANONICAL_OPAQUE_ID_RE=Vt.CANONICAL_OPAQUE_ID_PATTERN=void 0;Vt.utf8ByteLength=WD;Vt.isCanonicalText=yte;Vt.compareCanonicalKeys=_te;Vt.isCanonicalOpaqueId=bte;Vt.assertCanonicalOpaqueId=x7e;Vt.canonicalJsonExact=KD;Vt.CANONICAL_OPAQUE_ID_PATTERN="^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$";Vt.CANONICAL_OPAQUE_ID_RE=new RegExp(Vt.CANONICAL_OPAQUE_ID_PATTERN);Vt.CANONICAL_OPAQUE_ID_MAX_BYTES=128;var T7e=/[\u0000-\u001f\u007f\u2028\u2029]/,GD=new TextEncoder;function WD(e){return GD.encode(e).length}function yte(e,t){return typeof e=="string"&&e.length>0&&WD(e)<=t&&e.trim()===e&&e.normalize("NFC")===e&&!T7e.test(e)}function _te(e,t){let r=GD.encode(e),n=GD.encode(t),i=Math.min(r.length,n.length);for(let o=0;o<i;o+=1)if(r[o]!==n[o])return r[o]-n[o];return r.length-n.length}function bte(e){return typeof e=="string"&&WD(e)<=Vt.CANONICAL_OPAQUE_ID_MAX_BYTES&&Vt.CANONICAL_OPAQUE_ID_RE.test(e)}function x7e(e,t="value"){if(!bte(e))throw new Error(`${t} must be a canonical opaque id (max 128 ASCII bytes)`)}var O7e=/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,To=class extends Error{constructor(t){super(t),this.name="CanonicalJsonError"}};Vt.CanonicalJsonError=To;function KD(e,t=0){if(t>16)throw new To("nesting is deeper than 16");if(e===null||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="string"){if(O7e.test(e))throw new To("text is not valid Unicode");return JSON.stringify(e)}if(typeof e=="number"){if(!Number.isSafeInteger(e)||Object.is(e,-0))throw new To("numbers must be whole and at most 2^53 - 1; put amounts and decimals in strings");return JSON.stringify(e)}if(Array.isArray(e)){if(e.length>1024)throw new To("an array has more than 1024 items");return`[${e.map(n=>KD(n,t+1)).join(",")}]`}if(typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype)throw new To("only JSON objects, arrays, strings, whole numbers and booleans");let r=Object.keys(e);if(r.length>512)throw new To("an object has more than 512 keys");for(let n of r)if(!yte(n,128))throw new To("keys must be non-empty trimmed NFC text of at most 128 bytes");return`{${r.sort(_te).map(n=>`${JSON.stringify(n)}:${KD(e[n],t+1)}`).join(",")}}`}});var Ec=g(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.AgentOperationContractError=Di.AGENT_OPERATION_CONTRACT_ERROR_CODES=void 0;Di.record=wte;Di.bounded=vte;Di.canonicalJsonValue=Ste;Di.canonicalJson=R7e;Di.canonicalEnvelopeJson=C7e;var Ete=_S();Di.AGENT_OPERATION_CONTRACT_ERROR_CODES=["commitment_mismatch","intent_mismatch","invalid_amount","invalid_contract","invalid_currency","invalid_effect","invalid_evidence","invalid_principal","invalid_window","settlement_amount_invalid","unsupported_version"];var Ns=class extends Error{code;constructor(t,r){super(r),this.code=t,this.name="AgentOperationContractError"}};Di.AgentOperationContractError=Ns;function wte(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new Ns("invalid_contract",`${t} must be an object`);return e}function vte(e,t,r=4096){if(!(0,Ete.isCanonicalText)(e,r))throw new Ns("invalid_contract",`${t} is not bounded canonical text`);return e}function Ste(e,t=0){return bS(e,t,16)}function bS(e,t,r){if(t>r)throw new Ns("invalid_contract","payload nesting is too deep");if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isSafeInteger(e)&&!Object.is(e,-0))return e;if(typeof e=="number")throw new Ns("invalid_contract","JSON numbers must be safe canonical integers; use strings for larger or decimal values");if(Array.isArray(e)){if(e.length>1024)throw new Ns("invalid_contract","payload array is too large");return e.map(o=>bS(o,t+1,r))}let n=wte(e,"payload"),i=Object.entries(n);if(i.length>512)throw new Ns("invalid_contract","payload object is too large");return Object.fromEntries(i.sort(([o],[s])=>(0,Ete.compareCanonicalKeys)(o,s)).map(([o,s])=>[vte(o,"payload key",128),bS(s,t+1,r)]))}function R7e(e){return JSON.stringify(Ste(e))}function C7e(e){return JSON.stringify(bS(e,0,64))}});var Pte=g(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.PgDecryptionFailedError=rt.PgEncryptionWireFormatError=rt.PgEncryptionKeyMissingError=rt.PgEncryptionError=rt.PG_ENCRYPTION_WIRE_VERSIONS=rt.ENCRYPTION_KEY_MIN_BYTES=void 0;rt.isPgcryptoIntegrityError=j7e;rt.validateEncryptionKey=q7e;rt.encodeWireFormat=Ate;rt.decodeWireFormat=Ite;rt.encrypt=D7e;rt.decrypt=L7e;rt.encryptSqlFragment=B7e;rt.decryptSqlFragment=U7e;rt.ENCRYPTION_KEY_MIN_BYTES=32;rt.PG_ENCRYPTION_WIRE_VERSIONS=["v1"];var N7e=/^(v[0-9]+):([A-Za-z0-9+/]+={0,2})$/,gi=class extends Error{constructor(t){super(`[pg-encryption] ${t}`),this.name="PgEncryptionError"}};rt.PgEncryptionError=gi;var hp=class extends gi{constructor(t){super(`${t} is missing or shorter than ${rt.ENCRYPTION_KEY_MIN_BYTES} bytes; merchant credential encryption is disabled`),this.name="PgEncryptionKeyMissingError"}};rt.PgEncryptionKeyMissingError=hp;var wc=class extends gi{constructor(t){super(`malformed ciphertext: ${t}`),this.name="PgEncryptionWireFormatError"}};rt.PgEncryptionWireFormatError=wc;var ay=class extends gi{constructor(t){super(`decryption failed: ${t}`),this.name="PgDecryptionFailedError"}};rt.PgDecryptionFailedError=ay;var k7e=new Set(["39000","22023","22P02"]);function j7e(e){return typeof e!="object"||e===null||!("code"in e)?!1:typeof e.code=="string"&&k7e.has(e.code)}var M7e=/^[A-Za-z0-9+/]+={0,2}$/;function q7e(e,t){if(!e||e.trim()==="")throw new hp(t);let r=e.trim();if(!M7e.test(r))throw new hp(t);if(Buffer.from(r,"base64").length<rt.ENCRYPTION_KEY_MIN_BYTES)throw new hp(t);return r}function Ate(e,t){if(!rt.PG_ENCRYPTION_WIRE_VERSIONS.includes(e))throw new wc(`unsupported version "${e}"`);if(!/^[A-Za-z0-9+/]+={0,2}$/.test(t)||t.length===0)throw new wc("cipher payload is not base64");return`${e}:${t}`}function Ite(e){if(typeof e!="string"||e.length===0)throw new wc("value is empty");let t=N7e.exec(e);if(!t)throw new wc("does not match v<N>:<base64>");let r=t[1];if(!rt.PG_ENCRYPTION_WIRE_VERSIONS.includes(r))throw new wc(`unsupported version "${r}"`);return{version:r,cipherBase64:t[2]}}async function D7e(e,t,r){if(typeof t!="string"||t.length===0)throw new gi("plaintext must be a non-empty string");if(typeof r!="string"||r.length===0)throw new gi("key must be a non-empty string");let i=(await e.query("SELECT encode(pgp_sym_encrypt($1, $2, 'cipher-algo=aes256, compress-algo=2'), 'base64') AS ct",[t,r])).rows[0]?.ct;if(typeof i!="string"||i.length===0)throw new gi("pgp_sym_encrypt returned no ciphertext");return Ate("v1",i.replace(/\s+/g,""))}async function L7e(e,t,r){if(typeof r!="string"||r.length===0)throw new gi("key must be a non-empty string");let n=Ite(t),i;try{i=await e.query("SELECT pgp_sym_decrypt(decode($1, 'base64'), $2) AS pt",[n.cipherBase64,r])}catch(s){let a=s instanceof Error?s.message:String(s);throw new ay(a)}let o=i.rows[0]?.pt;if(typeof o!="string")throw new ay("decrypt returned no plaintext");return o}function B7e(e,t){return zD(e,"plaintext"),zD(t,"key"),`('v1:' || translate(encode(pgp_sym_encrypt(${e}, ${t}, 'cipher-algo=aes256, compress-algo=2'), 'base64'), E'\\n\\r', ''))`}function U7e(e,t){return H7e(e),zD(t,"key"),`CASE WHEN ${e} IS NULL THEN NULL
93
+ WHEN SUBSTRING(${e} FROM 1 FOR 3) = 'v1:'
94
+ THEN pgp_sym_decrypt(decode(translate(SUBSTRING(${e} FROM 4), E'\\n\\r ', ''), 'base64'), ${t})
95
+ ELSE NULL END`}function zD(e,t){if(!/^\$[1-9][0-9]*$/.test(e))throw new gi(`${t} param ref must look like "$N", got "${e}"`)}function H7e(e){if(!/^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*){0,2}$/.test(e))throw new gi(`column ref must be a simple identifier, got "${e}"`)}});var Cte=g(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.UNBOUND_AWAITING_RUNTIME_LABEL=ue.TARGETED_AWAITING_RUNTIME_LABEL=ue.SETUP_POLL_MS=ue.SETUP_STEP_STATUSES=ue.SETUP_IDENTITY_STEPS=ue.SETUP_RAIL_STEPS=ue.SETUP_STEPS=ue.SETUP_TERMINAL_STATES=ue.SETUP_STATES=ue.SETUP_RAILS=ue.PROTECTED_CARD_MAX_DRAWS=ue.SETUP_DEFAULT_DAILY_CENTS=ue.SETUP_DEFAULT_PER_PURCHASE_CENTS=ue.SETUP_DEFAULT_AGGREGATE_CENTS=ue.SETUP_CONTRACT_VERSION=void 0;ue.setupPlanSteps=Tte;ue.computeSetupReadiness=YD;ue.computeSetupNextAction=xte;ue.isTerminal=Ote;ue.computeSetupStatus=W7e;ue.computeSetupStepTargets=z7e;ue.isSetupPlanSettled=Z7e;ue.progressLadder=Rte;ue.setupProgressSteps=tVe;ue.SETUP_CONTRACT_VERSION=4;ue.SETUP_DEFAULT_AGGREGATE_CENTS=1e4;ue.SETUP_DEFAULT_PER_PURCHASE_CENTS=2500;ue.SETUP_DEFAULT_DAILY_CENTS=2500;ue.PROTECTED_CARD_MAX_DRAWS=1e3;ue.SETUP_RAILS=["card","wallet"];ue.SETUP_STATES=["awaiting_runtime","awaiting_owner","approved","completed","failed","denied","cancelled","expired","merged"];ue.SETUP_TERMINAL_STATES=["completed","failed","denied","cancelled","expired","merged"];ue.SETUP_STEPS=["identity.authorize","identity.activate","card.attach","card.mandate","wallet.provision_owner","wallet.attach","wallet.signer"];ue.SETUP_RAIL_STEPS={card:["card.attach","card.mandate"],wallet:["wallet.provision_owner","wallet.attach","wallet.signer"]};ue.SETUP_IDENTITY_STEPS=["identity.authorize","identity.activate"];function Tte(e){let t=new Set,r=[];for(let n of[...ue.SETUP_IDENTITY_STEPS,...e.flatMap(i=>ue.SETUP_RAIL_STEPS[i]??[])])t.has(n)||(t.add(n),r.push(n));return r}ue.SETUP_STEP_STATUSES=["pending","running","awaiting_human","awaiting_runtime","succeeded","failed","skipped","abandoned"];ue.SETUP_POLL_MS={afterHumanAction:1e3,provisioning:3e3,idle:5e3,completedNeedsHuman:3e4,slowDown:1e4};function F7e(e,t){return!t||!t.grantActivated&&!t.ownerPrerequisiteMissing?{rail:e,ready:!1,blocker:"not_provisioned"}:t.ownerPrerequisiteMissing?{rail:e,ready:!1,blocker:"blocked"}:t.instrumentResolves?e==="wallet"&&t.fundedForOnePurchase===!1?{rail:e,ready:!1,blocker:"unfunded"}:e==="card"?{rail:e,ready:!0,tapFree:t.liveMandateWithDrawsLeft===!0}:{rail:e,ready:!0}:{rail:e,ready:!1,blocker:"not_provisioned"}}function YD(e){let t=e.identity.activated,r=e.operation.requestedRails.map(n=>{let i=F7e(n,e.rails[n]);return n==="wallet"&&i.ready&&e.identity.runtimeDelegation?{rail:n,ready:!1,blocker:"runtime_approval"}:i});return{kind:t&&r.every(n=>n.ready)?"ready":"needs_action",identityReady:t,rails:r}}function xo(e,t){return t===void 0?{}:{[e]:t}}var $7e={completed:"Setup finished.",failed:"Setup could not finish.",denied:"You said this was not your agent.",cancelled:"Setup was cancelled.",expired:"This setup request expired.",merged:"This agent joined the setup you started in the Console."},J7e=["enroll_card","card_verification","provision_wallet","wallet_signature"],V7e={enroll_card:"Add a card to pay with.",card_verification:"Verify your card with your bank.",provision_wallet:"Create your wallet.",wallet_signature:"Approve the wallet signer in your browser."};ue.TARGETED_AWAITING_RUNTIME_LABEL="Waiting for your agent to pick this up. If it doesn't, tell it: connect Visa.";ue.UNBOUND_AWAITING_RUNTIME_LABEL="This request is not picked up automatically. On the runtime you want, say: connect Visa. You review that runtime\u2019s fingerprint before it holds any authority.";function G7e(e){return e.claimBindingMode?e.claimBindingMode==="unbound":e.source==="console"}function xte(e){let{operation:t,identity:r,viewer:n,steps:i}=e,o=YD(e);if(n.kind==="owner"&&n.signedInAs&&t.ownerUserLogin&&n.signedInAs!==t.ownerUserLogin)return{actor:"human",kind:"switch_account",label:"Sign out, then sign back in as the account that started this.",safeToRetry:!0,afterAction:"stop",expectedLogin:t.ownerUserLogin,signedInAs:n.signedInAs};if(Ote(t.state)&&!(t.state==="completed"&&o.kind==="ready")&&t.state!=="completed")return{actor:"none",kind:"terminal",label:$7e[t.state],safeToRetry:!1,afterAction:"stop",outcome:t.state,...t.failureReason?{reason:t.failureReason}:{},canRestart:t.state==="expired"||t.state==="cancelled",...t.successorOperationId?{successorOperationId:t.successorOperationId}:{}};if(t.state==="awaiting_runtime"&&r.shortCode&&r.deepLink)return{actor:"human",kind:"give_code",label:"Tell your agent to connect, and give it this code if it asks.",safeToRetry:!0,afterAction:"poll",shortCode:r.shortCode,deepLink:r.deepLink,...xo("expiresAt",r.credentialExpiresAt??t.expiresAt)};if(t.state==="awaiting_owner"&&r.reviewUrl)return{actor:"human",kind:"open_url",label:"Review and connect this agent.",safeToRetry:!0,afterAction:"open_url_again",channel:"browser",url:r.reviewUrl,...r.openedFromThisDevice===!0?{provenance:"same_device"}:xo("code",r.compareCode),...xo("expiresAt",t.expiresAt)};if(r.pendingRuntimeAction)return{actor:"agent",kind:"activate",label:"Finishing setup.",safeToRetry:!0,afterAction:"poll",endpoint:r.pendingRuntimeAction.endpoint};for(let c of J7e)for(let u of t.requestedRails){let d=e.rails[u]?.humanAction;if(d?.kind!==c)continue;let l={actor:"human",label:V7e[c],safeToRetry:!0,afterAction:"open_url_again",url:d.url};return c==="wallet_signature"?{...l,kind:c,...xo("expiresAt",d.expiresAt),...xo("attachId",d.attachId),...xo("agentId",d.agentId)}:c==="card_verification"?{...l,kind:c,...xo("expiresAt",d.expiresAt)}:{...l,kind:c}}let s=i.find(c=>c.status==="failed");if(s)return s.retryable?{actor:"agent",kind:"retry",label:"Retrying a step that did not finish.",safeToRetry:!0,afterAction:"poll",step:s.step,endpoint:e.endpoints.retry(t.operationId,s.step),...xo("notBefore",s.nextAttemptAt)}:{actor:"human",kind:"contact_support",label:"This needs a hand from support.",safeToRetry:!1,afterAction:"stop",supportRef:t.operationId,stepFailed:s.step};if(t.state==="completed"&&r.runtimeDelegation?.state==="pending")return{actor:"human",kind:"runtime_delegation",label:"Approve secure wallet access for this runtime.",safeToRetry:!0,afterAction:"poll",url:r.runtimeDelegation.url,agentId:r.runtimeDelegation.agentId,runtimeId:r.runtimeDelegation.runtimeId};if(o.rails.find(c=>c.blocker==="unfunded")){let c=e.rails.wallet;return{actor:"human",kind:"fund_wallet",label:"Add USDC so your agent has something to spend.",safeToRetry:!0,afterAction:"poll",...xo("address",c?.depositAddress),network:"base",...xo("minimumMicros",c?.minimumMicros)}}return n.keyMismatchOnLiveAgent&&t.agentId?{actor:"agent",kind:"rotate_key",label:"Rotating this agent to a new key.",safeToRetry:!0,afterAction:"poll",agentId:t.agentId,endpoint:e.endpoints.rotateKey(t.agentId)}:n.throttled?{actor:"agent",kind:"slow_down",label:"Checking less often.",safeToRetry:!0,afterAction:"poll",pollAfterMs:ue.SETUP_POLL_MS.slowDown}:t.state==="completed"&&o.kind==="ready"?{actor:"none",kind:"done",label:"Your agent is ready to pay.",safeToRetry:!1,afterAction:"stop"}:{actor:"agent",kind:"poll",label:t.state==="awaiting_runtime"?G7e(t)?ue.UNBOUND_AWAITING_RUNTIME_LABEL:ue.TARGETED_AWAITING_RUNTIME_LABEL:"Setting up.",safeToRetry:!0,afterAction:"poll",pollAfterMs:K7e(t.state,o)}}function Ote(e){return ue.SETUP_TERMINAL_STATES.includes(e)}function K7e(e,t){return e==="approved"?ue.SETUP_POLL_MS.provisioning:e==="completed"&&t.kind==="needs_action"?ue.SETUP_POLL_MS.completedNeedsHuman:ue.SETUP_POLL_MS.idle}function W7e(e){let t=YD(e),r=xte(e);return{contractVersion:ue.SETUP_CONTRACT_VERSION,operationId:e.operation.operationId,state:e.operation.state,readiness:t,nextAction:r,pollAfterMs:"pollAfterMs"in r?r.pollAfterMs:r.afterAction==="stop"?0:r.afterAction==="open_url_again"?ue.SETUP_POLL_MS.idle:ue.SETUP_POLL_MS.afterHumanAction}}function z7e(e){let{identity:t,rails:r}=e;return Tte(e.requestedRails).map(n=>({step:n,status:Y7e(n,t.activated,r)}))}function Y7e(e,t,r){switch(e){case"identity.authorize":return"succeeded";case"identity.activate":return t?"succeeded":"awaiting_runtime";default:return X7e(e,t,r)}}function X7e(e,t,r){if(!t)return"pending";let n=r.card,i=r.wallet;switch(e){case"card.attach":return n?.ownerPrerequisiteMissing?"awaiting_human":n?.grantActivated&&n.instrumentResolves?"succeeded":"pending";case"card.mandate":return n?.liveMandateWithDrawsLeft===!0?"succeeded":n?.grantActivated&&n.instrumentResolves?"skipped":"pending";case"wallet.provision_owner":return i===void 0?"pending":i.ownerPrerequisiteMissing?"awaiting_human":"succeeded";case"wallet.attach":return i?.grantActivated?"succeeded":"pending";case"wallet.signer":return i?.grantActivated&&i.instrumentResolves?"succeeded":"pending";default:return"pending"}}function Z7e(e){return e.every(t=>t.status==="succeeded"||t.status==="skipped")}var Q7e={card:"Card ready to pay",wallet:"USDC wallet ready to pay"},eVe=new Set(["failed","denied","cancelled","expired"]);function Rte(e,t){let r=!0;return e.map(({key:n,label:i,done:o})=>o?{key:n,label:i,state:"done"}:r?(r=!1,{key:n,label:i,state:t?"stopped":"active"}):{key:n,label:i,state:"pending"})}function tVe(e){let t=String(e.state),r=Array.isArray(e.readiness?.rails)?e.readiness.rails:[],n=!!(e.agent?.runtime||e.agent?.device)||e.readiness?.identityReady===!0||t==="awaiting_owner"||t==="approved"||t==="completed",i=[{key:"created",label:"Request created",done:!0},{key:"picked-up",label:"Agent picked it up",done:n},{key:"approved",label:"Limits approved",done:t==="approved"||t==="completed"},{key:"identity",label:"Agent identity verified",done:e.readiness?.identityReady===!0},...r.map(o=>({key:`rail-${o.rail}`,label:Q7e[o.rail]??`${o.rail} ready to pay`,done:o.ready===!0}))];return Rte(i,eVe.has(t))}});var Nte=g(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});Id.runtimeLabel=nVe;Id.canonicalRuntimeId=ES;Id.runtimeMatchAliases=iVe;Id.runtimesMatch=oVe;Id.claimBindingMode=sVe;var rVe={"claude-code":"Claude Code",claude:"Claude Code",codex:"Codex",openclaw:"OpenClaw",hermes:"Hermes",cursor:"Cursor","custom-mcp":"Custom (MCP)",mcp:"Custom (MCP)",custom:"Custom (MCP)"};function nVe(e){let t=e.trim();return rVe[t.toLowerCase()]??t}function ES(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();if(t.length!==0)return t==="claude"||t==="claude-code"?"claude-code":t==="codex"?"codex":t==="openclaw"?"openclaw":t==="hermes"?"hermes":t==="cursor"?"cursor":t==="custom-mcp"||t==="mcp"||t==="custom"?"custom-mcp":t}function iVe(e){let t=ES(e);return t?t==="claude-code"?["claude","claude-code"]:t==="custom-mcp"?["custom","custom-mcp","mcp"]:[t]:[]}function oVe(e,t){return!e||e.trim().length===0?!0:!t||t.trim().length===0?!1:ES(e)===ES(t)}function sVe(e){return e&&e.trim().length>0?"targeted":"unbound"}});var kte=g(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.ReleaseManifestValidationError=zr.PROVIDER_CONFIGURATION_VARIABLE_KEYS=zr.ACTIVE_RAILWAY_SERVICES=zr.RELEASE_MANIFEST_SCHEMA_VERSION=void 0;zr.validateReleaseManifest=cVe;var aVe=Ec();zr.RELEASE_MANIFEST_SCHEMA_VERSION="1.0.0";zr.ACTIVE_RAILWAY_SERVICES=["auth","web","mpp","admin","worker"];zr.PROVIDER_CONFIGURATION_VARIABLE_KEYS=["name","sensitivity","owners","consumer"];var oe=class extends Error{field;constructor(t,r){super(`ReleaseManifest validation error: ${t}${r?` (field: ${r})`:""}`),this.field=r,this.name="ReleaseManifestValidationError"}};zr.ReleaseManifestValidationError=oe;function cVe(e){if(!e||typeof e!="object"||Array.isArray(e))throw new oe("Manifest must be a non-null object");let t=e;if(t.schemaVersion!==zr.RELEASE_MANIFEST_SCHEMA_VERSION)throw new oe(`Unsupported schemaVersion "${t.schemaVersion}"; expected "${zr.RELEASE_MANIFEST_SCHEMA_VERSION}"`,"schemaVersion");if(typeof t.candidateId!="string"||!t.candidateId.trim())throw new oe("candidateId must be a non-empty string","candidateId");if(typeof t.sourceCommit!="string"||!/^[0-9a-f]{7,40}$/i.test(t.sourceCommit))throw new oe("sourceCommit must be a valid git commit SHA","sourceCommit");if(typeof t.generatedAt!="string"||!t.generatedAt.trim())throw new oe("generatedAt must be a valid timestamp","generatedAt");if(t.environment!=="staging"&&t.environment!=="production")throw new oe('environment must be "staging" or "production"',"environment");if(!t.services||typeof t.services!="object"||Array.isArray(t.services))throw new oe("services must be an object","services");let r=t.services;for(let h of zr.ACTIVE_RAILWAY_SERVICES){if(!r[h]||typeof r[h]!="object")throw new oe(`Missing required active Railway service "${h}"`,`services.${h}`);let y=r[h];if(y.serviceId!==h)throw new oe(`Service ID mismatch for "${h}"`,`services.${h}.serviceId`);if(typeof y.rootPath!="string"||!y.rootPath.trim())throw new oe(`Invalid rootPath for service "${h}"`,`services.${h}.rootPath`);if(!Array.isArray(y.watchPaths)||y.watchPaths.length===0)throw new oe(`watchPaths must be a non-empty array for service "${h}"`,`services.${h}.watchPaths`);if(!Array.isArray(y.healthEndpoints)||y.healthEndpoints.length===0)throw new oe(`healthEndpoints must be a non-empty array for service "${h}"`,`services.${h}.healthEndpoints`)}if(!t.cli||typeof t.cli!="object"||Array.isArray(t.cli))throw new oe("cli must be an object","cli");let n=t.cli;if(n.packageName!=="@visa/cli")throw new oe('cli.packageName must be "@visa/cli"',"cli.packageName");if(typeof n.version!="string"||!n.version.trim())throw new oe("cli.version must be a valid string","cli.version");if(n.channel!=="rc"&&n.channel!=="latest")throw new oe('cli.channel must be "rc" or "latest"',"cli.channel");if(typeof n.tarballIntegrity!="string"||!n.tarballIntegrity.trim())throw new oe("cli.tarballIntegrity must be a non-empty string","cli.tarballIntegrity");if(typeof n.minimumCompatibleVersion!="string"||!n.minimumCompatibleVersion.trim())throw new oe("cli.minimumCompatibleVersion must be a non-empty string","cli.minimumCompatibleVersion");if(!n.capabilityFloors||typeof n.capabilityFloors!="object")throw new oe("cli.capabilityFloors must be an object","cli.capabilityFloors");if(!t.database||typeof t.database!="object")throw new oe("database must be an object","database");let i=t.database;if(!i.postgres||typeof i.postgres!="object")throw new oe("database.postgres must be an object","database.postgres");let o=i.postgres;if(typeof o.schemaChecksum!="string"||!o.schemaChecksum.trim())throw new oe("database.postgres.schemaChecksum must be a non-empty string","database.postgres.schemaChecksum");if(!Array.isArray(o.tables)||o.tables.length===0)throw new oe("database.postgres.tables must be a non-empty array","database.postgres.tables");if(!i.clickhouse||typeof i.clickhouse!="object")throw new oe("database.clickhouse must be an object","database.clickhouse");let s=i.clickhouse;if(typeof s.schemaChecksum!="string"||!s.schemaChecksum.trim())throw new oe("database.clickhouse.schemaChecksum must be a non-empty string","database.clickhouse.schemaChecksum");if(!Array.isArray(s.tables)||s.tables.length===0)throw new oe("database.clickhouse.tables must be a non-empty array","database.clickhouse.tables");if(!t.capabilities||typeof t.capabilities!="object")throw new oe("capabilities must be an object","capabilities");let a=t.capabilities;if(!Array.isArray(a.publicTools)||a.publicTools.length===0)throw new oe("capabilities.publicTools must be a non-empty array","capabilities.publicTools");if(!Array.isArray(a.paymentRails)||a.paymentRails.length===0)throw new oe("capabilities.paymentRails must be a non-empty array","capabilities.paymentRails");if(!Array.isArray(a.protocols)||a.protocols.length===0)throw new oe("capabilities.protocols must be a non-empty array","capabilities.protocols");if(!Array.isArray(a.rolloutFlags)||a.rolloutFlags.length===0)throw new oe("capabilities.rolloutFlags must be a non-empty array","capabilities.rolloutFlags");if(!t.providers||typeof t.providers!="object"||Array.isArray(t.providers))throw new oe("providers must be an object","providers");let c=t.providers,u=["turnkey","postgres","clickhouse","redis","sentry"];for(let h of u)if(!c[h]||typeof c[h]!="object")throw new oe(`Missing required provider assertion "${h}"`,`providers.${h}`);for(let[h,y]of Object.entries(c)){let b=y;if(b.configuration!==void 0){if(!Array.isArray(b.configuration))throw new oe(`providers.${h}.configuration must be an array`,`providers.${h}.configuration`);b.configuration.forEach((v,A)=>{let E=`providers.${h}.configuration[${A}]`;if(!v||typeof v!="object"||Array.isArray(v))throw new oe(`${E} must be an object`,E);let S=v;for(let I of Object.keys(S))if(!zr.PROVIDER_CONFIGURATION_VARIABLE_KEYS.includes(I))throw new oe(`${E} carries unexpected key "${I}"; only variable names and registry metadata belong in the manifest`,E);if(typeof S.name!="string"||!/^[A-Z][A-Z0-9_]*$/.test(S.name))throw new oe(`${E}.name must be an environment variable name`,`${E}.name`);if(typeof S.sensitivity!="string"||!S.sensitivity.trim())throw new oe(`${E}.sensitivity must be a non-empty string`,`${E}.sensitivity`);if(!Array.isArray(S.owners)||S.owners.some(I=>typeof I!="string"))throw new oe(`${E}.owners must be an array of service names`,`${E}.owners`);if(typeof S.consumer!="string"||!S.consumer.trim())throw new oe(`${E}.consumer must be a non-empty string`,`${E}.consumer`)})}}if(!t.canaries||typeof t.canaries!="object"||Array.isArray(t.canaries))throw new oe("canaries must be an object","canaries");let d=t.canaries;if(!d.ceremonyCanary7590||typeof d.ceremonyCanary7590!="object")throw new oe('Missing required canary "ceremonyCanary7590"',"canaries.ceremonyCanary7590");if(!d.serviceHealthProbes||typeof d.serviceHealthProbes!="object")throw new oe('Missing required canary "serviceHealthProbes"',"canaries.serviceHealthProbes");if(!t.docs||typeof t.docs!="object")throw new oe("docs must be an object","docs");let l=t.docs;if(typeof l.canonicalDocsVersion!="string"||!l.canonicalDocsVersion.trim())throw new oe("docs.canonicalDocsVersion must be a non-empty string","docs.canonicalDocsVersion");if(!Array.isArray(t.rollbackClassification)||t.rollbackClassification.length===0)throw new oe("rollbackClassification must be a non-empty array","rollbackClassification");let m=new Set(["schema","credentials","provider_effects","money_state"]),p=new Set;for(let h of t.rollbackClassification){if(!h||typeof h!="object")throw new oe("rollbackClassification item must be an object","rollbackClassification");let y=h;if(y.classification!=="safe_rollback"&&y.classification!=="forward_fix_required")throw new oe(`Invalid classification "${y.classification}" for step "${y.step}"`,"rollbackClassification");typeof y.category=="string"&&p.add(y.category)}for(let h of m)if(!p.has(h))throw new oe(`rollbackClassification must cover category "${h}"`,"rollbackClassification");return XD(t),(0,aVe.canonicalJsonValue)(e)}function XD(e,t=""){if(e!=null){if(typeof e=="string"){if(/Bearer\s+[A-Za-z0-9_-]{20,}/i.test(e))throw new oe(`Bearer token detected in manifest at ${t}`);if(/-----BEGIN\s+(?:RSA|EC|PRIVATE)\s+KEY-----/i.test(e))throw new oe(`Private key detected in manifest at ${t}`);if(/^(?:postgres|postgresql|redis|mongodb):\/\/[^:]+:[^@]+@/i.test(e))throw new oe(`Credential-bearing connection URL detected in manifest at ${t}`);return}if(Array.isArray(e)){for(let r=0;r<e.length;r++)XD(e[r],`${t}[${r}]`);return}if(typeof e=="object")for(let[r,n]of Object.entries(e))XD(n,t?`${t}.${r}`:r)}}});var Fn=g(P=>{"use strict";Object.defineProperty(P,"__esModule",{value:!0});P.isExplicitProductionRailEnvironment=P.isExplicitPreviewPaymentRailOptIn=P.detectDeploymentEnvNodeEnvMismatch=P.clickhouseDatabaseHasStagingMarker=P.validateCardPaymentUnmatchedEventInsertRow=P.validateCardPaymentEventInsertRow=P.refreshCardPaymentAttemptProjection=P.insertCardPaymentUnmatchedEvent=P.insertCardPaymentLifecycleEventWithId=P.insertCardPaymentLifecycleEvent=P.assertValidCardPaymentAttemptStatus=P.CardPaymentDbValidationError=P.requiresProviderProvenance=P.requiredProvenanceFor=P.reduceCardPaymentEvents=P.provenanceOfSource=P.isOwnerAttestationVerdict=P.OWNER_ATTESTATION_VERDICTS=P.CARD_PAYMENT_EVENT_REQUIRED_PROVENANCE=P.CARD_PAYMENT_SOURCE_PROVENANCE=P.CARD_PAYMENT_PROVENANCES=P.CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES=P.CARD_PAYMENT_UNMATCHED_SOURCES=P.CARD_PAYMENT_UNMATCHED_EVENT_TYPES=P.CARD_PAYMENT_SOURCES=P.CARD_PAYMENT_UNMATCHED_PROCESSORS=P.CARD_PAYMENT_PROCESSORS=P.CARD_PAYMENT_INTENTS=P.CARD_PAYMENT_EVENT_TYPES=P.CARD_PAYMENT_ATTEMPT_STATUSES=P.parseAccountOperationReceipt=P.cardStatusClaimsProcessorTruth=P.cardProofLevel=P.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION=P.ACCOUNT_OPERATION_PROOF_LEVELS=P.ACCOUNT_OPERATION_OUTCOMES=P.ACCOUNT_OPERATION_EVIDENCE_TYPES=P.checkTvcPinParity=P.TVC_SIGNER_POLICY_CONTRACT_VERSION=P.tvcCredentialLifecycleEvidence=P.parseTvcCredentialLifecycleEvidence=P.assertTvcCredentialRebindWindow=P.TVC_CREDENTIAL_REBIND_LEAD_SECONDS=P.TVC_CREDENTIAL_CONTRACT_SOURCES=P.tvcProviderCapacityEvidence=P.TVC_PROVIDER_WARN_THRESHOLD=P.parseTvcProviderCapacityEvidence=P.TURNKEY_SUBORG_RESOURCE_LIMITS=P.projectAgentOutcome=P.AGENT_OUTCOME_LABELS=void 0;P.computeSetupNextAction=P.UNBOUND_AWAITING_RUNTIME_LABEL=P.TARGETED_AWAITING_RUNTIME_LABEL=P.SETUP_TERMINAL_STATES=P.SETUP_STEP_STATUSES=P.SETUP_STEPS=P.SETUP_STATES=P.SETUP_RAIL_STEPS=P.SETUP_RAILS=P.SETUP_POLL_MS=P.SETUP_IDENTITY_STEPS=P.SETUP_DEFAULT_PER_PURCHASE_CENTS=P.SETUP_DEFAULT_DAILY_CENTS=P.SETUP_DEFAULT_AGGREGATE_CENTS=P.PROTECTED_CARD_MAX_DRAWS=P.SETUP_CONTRACT_VERSION=P.validateEncryptionKey=P.isPgcryptoIntegrityError=P.encryptSqlFragment=P.encrypt=P.encodeWireFormat=P.decryptSqlFragment=P.decrypt=P.decodeWireFormat=P.PgEncryptionWireFormatError=P.PgEncryptionKeyMissingError=P.PgEncryptionError=P.PgDecryptionFailedError=P.PG_ENCRYPTION_WIRE_VERSIONS=P.ENCRYPTION_KEY_MIN_BYTES=P.utf8ByteLength=P.isCanonicalText=P.isCanonicalOpaqueId=P.compareCanonicalKeys=P.assertCanonicalOpaqueId=P.CANONICAL_OPAQUE_ID_PATTERN=P.CANONICAL_OPAQUE_ID_MAX_BYTES=P.canonicalJson=P.parseAgentSelector=P.normalizeAgentName=P.computeAgentSelection=P.fetchWithTimeout=P.DEFAULT_FETCH_TIMEOUT_MS=P.PREVIEW_LEGACY_BALANCE_DRIFT_BASELINE=P.matchesPreviewLegacyBalanceDrift=P.resolveDeploymentEnvClass=P.resolveClickhouseEnvBinding=P.normalizeRailEnvironmentValue=P.isPublicPreviewRailEnvironment=P.isLiveVgsEnvironment=void 0;P.validateReleaseManifest=P.ReleaseManifestValidationError=P.RELEASE_MANIFEST_SCHEMA_VERSION=P.PROVIDER_CONFIGURATION_VARIABLE_KEYS=P.ACTIVE_RAILWAY_SERVICES=P.claimBindingMode=P.runtimesMatch=P.runtimeMatchAliases=P.canonicalRuntimeId=P.runtimeLabel=P.setupProgressSteps=P.setupPlanSteps=P.progressLadder=P.isTerminal=P.isSetupPlanSettled=P.computeSetupStepTargets=P.computeSetupStatus=P.computeSetupReadiness=void 0;var jte=kee();Object.defineProperty(P,"AGENT_OUTCOME_LABELS",{enumerable:!0,get:function(){return jte.AGENT_OUTCOME_LABELS}});Object.defineProperty(P,"projectAgentOutcome",{enumerable:!0,get:function(){return jte.projectAgentOutcome}});var wS=Mee();Object.defineProperty(P,"TURNKEY_SUBORG_RESOURCE_LIMITS",{enumerable:!0,get:function(){return wS.TURNKEY_SUBORG_RESOURCE_LIMITS}});Object.defineProperty(P,"parseTvcProviderCapacityEvidence",{enumerable:!0,get:function(){return wS.parseTvcProviderCapacityEvidence}});Object.defineProperty(P,"TVC_PROVIDER_WARN_THRESHOLD",{enumerable:!0,get:function(){return wS.TVC_PROVIDER_WARN_THRESHOLD}});Object.defineProperty(P,"tvcProviderCapacityEvidence",{enumerable:!0,get:function(){return wS.tvcProviderCapacityEvidence}});var cy=Bee();Object.defineProperty(P,"TVC_CREDENTIAL_CONTRACT_SOURCES",{enumerable:!0,get:function(){return cy.TVC_CREDENTIAL_CONTRACT_SOURCES}});Object.defineProperty(P,"TVC_CREDENTIAL_REBIND_LEAD_SECONDS",{enumerable:!0,get:function(){return cy.TVC_CREDENTIAL_REBIND_LEAD_SECONDS}});Object.defineProperty(P,"assertTvcCredentialRebindWindow",{enumerable:!0,get:function(){return cy.assertTvcCredentialRebindWindow}});Object.defineProperty(P,"parseTvcCredentialLifecycleEvidence",{enumerable:!0,get:function(){return cy.parseTvcCredentialLifecycleEvidence}});Object.defineProperty(P,"tvcCredentialLifecycleEvidence",{enumerable:!0,get:function(){return cy.tvcCredentialLifecycleEvidence}});var uVe=Uee();Object.defineProperty(P,"TVC_SIGNER_POLICY_CONTRACT_VERSION",{enumerable:!0,get:function(){return uVe.TVC_SIGNER_POLICY_CONTRACT_VERSION}});var dVe=Fee();Object.defineProperty(P,"checkTvcPinParity",{enumerable:!0,get:function(){return dVe.checkTvcPinParity}});var Pd=DD();Object.defineProperty(P,"ACCOUNT_OPERATION_EVIDENCE_TYPES",{enumerable:!0,get:function(){return Pd.ACCOUNT_OPERATION_EVIDENCE_TYPES}});Object.defineProperty(P,"ACCOUNT_OPERATION_OUTCOMES",{enumerable:!0,get:function(){return Pd.ACCOUNT_OPERATION_OUTCOMES}});Object.defineProperty(P,"ACCOUNT_OPERATION_PROOF_LEVELS",{enumerable:!0,get:function(){return Pd.ACCOUNT_OPERATION_PROOF_LEVELS}});Object.defineProperty(P,"ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION",{enumerable:!0,get:function(){return Pd.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION}});Object.defineProperty(P,"cardProofLevel",{enumerable:!0,get:function(){return Pd.cardProofLevel}});Object.defineProperty(P,"cardStatusClaimsProcessorTruth",{enumerable:!0,get:function(){return Pd.cardStatusClaimsProcessorTruth}});Object.defineProperty(P,"parseAccountOperationReceipt",{enumerable:!0,get:function(){return Pd.parseAccountOperationReceipt}});var or=LD();Object.defineProperty(P,"CARD_PAYMENT_ATTEMPT_STATUSES",{enumerable:!0,get:function(){return or.CARD_PAYMENT_ATTEMPT_STATUSES}});Object.defineProperty(P,"CARD_PAYMENT_EVENT_TYPES",{enumerable:!0,get:function(){return or.CARD_PAYMENT_EVENT_TYPES}});Object.defineProperty(P,"CARD_PAYMENT_INTENTS",{enumerable:!0,get:function(){return or.CARD_PAYMENT_INTENTS}});Object.defineProperty(P,"CARD_PAYMENT_PROCESSORS",{enumerable:!0,get:function(){return or.CARD_PAYMENT_PROCESSORS}});Object.defineProperty(P,"CARD_PAYMENT_UNMATCHED_PROCESSORS",{enumerable:!0,get:function(){return or.CARD_PAYMENT_UNMATCHED_PROCESSORS}});Object.defineProperty(P,"CARD_PAYMENT_SOURCES",{enumerable:!0,get:function(){return or.CARD_PAYMENT_SOURCES}});Object.defineProperty(P,"CARD_PAYMENT_UNMATCHED_EVENT_TYPES",{enumerable:!0,get:function(){return or.CARD_PAYMENT_UNMATCHED_EVENT_TYPES}});Object.defineProperty(P,"CARD_PAYMENT_UNMATCHED_SOURCES",{enumerable:!0,get:function(){return or.CARD_PAYMENT_UNMATCHED_SOURCES}});Object.defineProperty(P,"CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES",{enumerable:!0,get:function(){return or.CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES}});Object.defineProperty(P,"CARD_PAYMENT_PROVENANCES",{enumerable:!0,get:function(){return or.CARD_PAYMENT_PROVENANCES}});Object.defineProperty(P,"CARD_PAYMENT_SOURCE_PROVENANCE",{enumerable:!0,get:function(){return or.CARD_PAYMENT_SOURCE_PROVENANCE}});Object.defineProperty(P,"CARD_PAYMENT_EVENT_REQUIRED_PROVENANCE",{enumerable:!0,get:function(){return or.CARD_PAYMENT_EVENT_REQUIRED_PROVENANCE}});Object.defineProperty(P,"OWNER_ATTESTATION_VERDICTS",{enumerable:!0,get:function(){return or.OWNER_ATTESTATION_VERDICTS}});Object.defineProperty(P,"isOwnerAttestationVerdict",{enumerable:!0,get:function(){return or.isOwnerAttestationVerdict}});Object.defineProperty(P,"provenanceOfSource",{enumerable:!0,get:function(){return or.provenanceOfSource}});Object.defineProperty(P,"reduceCardPaymentEvents",{enumerable:!0,get:function(){return or.reduceCardPaymentEvents}});Object.defineProperty(P,"requiredProvenanceFor",{enumerable:!0,get:function(){return or.requiredProvenanceFor}});Object.defineProperty(P,"requiresProviderProvenance",{enumerable:!0,get:function(){return or.requiresProviderProvenance}});var vc=ste();Object.defineProperty(P,"CardPaymentDbValidationError",{enumerable:!0,get:function(){return vc.CardPaymentDbValidationError}});Object.defineProperty(P,"assertValidCardPaymentAttemptStatus",{enumerable:!0,get:function(){return vc.assertValidCardPaymentAttemptStatus}});Object.defineProperty(P,"insertCardPaymentLifecycleEvent",{enumerable:!0,get:function(){return vc.insertCardPaymentLifecycleEvent}});Object.defineProperty(P,"insertCardPaymentLifecycleEventWithId",{enumerable:!0,get:function(){return vc.insertCardPaymentLifecycleEventWithId}});Object.defineProperty(P,"insertCardPaymentUnmatchedEvent",{enumerable:!0,get:function(){return vc.insertCardPaymentUnmatchedEvent}});Object.defineProperty(P,"refreshCardPaymentAttemptProjection",{enumerable:!0,get:function(){return vc.refreshCardPaymentAttemptProjection}});Object.defineProperty(P,"validateCardPaymentEventInsertRow",{enumerable:!0,get:function(){return vc.validateCardPaymentEventInsertRow}});Object.defineProperty(P,"validateCardPaymentUnmatchedEventInsertRow",{enumerable:!0,get:function(){return vc.validateCardPaymentUnmatchedEventInsertRow}});var ks=lte();Object.defineProperty(P,"clickhouseDatabaseHasStagingMarker",{enumerable:!0,get:function(){return ks.clickhouseDatabaseHasStagingMarker}});Object.defineProperty(P,"detectDeploymentEnvNodeEnvMismatch",{enumerable:!0,get:function(){return ks.detectDeploymentEnvNodeEnvMismatch}});Object.defineProperty(P,"isExplicitPreviewPaymentRailOptIn",{enumerable:!0,get:function(){return ks.isExplicitPreviewPaymentRailOptIn}});Object.defineProperty(P,"isExplicitProductionRailEnvironment",{enumerable:!0,get:function(){return ks.isExplicitProductionRailEnvironment}});Object.defineProperty(P,"isLiveVgsEnvironment",{enumerable:!0,get:function(){return ks.isLiveVgsEnvironment}});Object.defineProperty(P,"isPublicPreviewRailEnvironment",{enumerable:!0,get:function(){return ks.isPublicPreviewRailEnvironment}});Object.defineProperty(P,"normalizeRailEnvironmentValue",{enumerable:!0,get:function(){return ks.normalizeRailEnvironmentValue}});Object.defineProperty(P,"resolveClickhouseEnvBinding",{enumerable:!0,get:function(){return ks.resolveClickhouseEnvBinding}});Object.defineProperty(P,"resolveDeploymentEnvClass",{enumerable:!0,get:function(){return ks.resolveDeploymentEnvClass}});var Mte=pte();Object.defineProperty(P,"matchesPreviewLegacyBalanceDrift",{enumerable:!0,get:function(){return Mte.matchesPreviewLegacyBalanceDrift}});Object.defineProperty(P,"PREVIEW_LEGACY_BALANCE_DRIFT_BASELINE",{enumerable:!0,get:function(){return Mte.PREVIEW_LEGACY_BALANCE_DRIFT_BASELINE}});var qte=mte();Object.defineProperty(P,"DEFAULT_FETCH_TIMEOUT_MS",{enumerable:!0,get:function(){return qte.DEFAULT_FETCH_TIMEOUT_MS}});Object.defineProperty(P,"fetchWithTimeout",{enumerable:!0,get:function(){return qte.fetchWithTimeout}});var ZD=hte();Object.defineProperty(P,"computeAgentSelection",{enumerable:!0,get:function(){return ZD.computeAgentSelection}});Object.defineProperty(P,"normalizeAgentName",{enumerable:!0,get:function(){return ZD.normalizeAgentName}});Object.defineProperty(P,"parseAgentSelector",{enumerable:!0,get:function(){return ZD.parseAgentSelector}});var lVe=Ec();Object.defineProperty(P,"canonicalJson",{enumerable:!0,get:function(){return lVe.canonicalJson}});var Td=_S();Object.defineProperty(P,"CANONICAL_OPAQUE_ID_MAX_BYTES",{enumerable:!0,get:function(){return Td.CANONICAL_OPAQUE_ID_MAX_BYTES}});Object.defineProperty(P,"CANONICAL_OPAQUE_ID_PATTERN",{enumerable:!0,get:function(){return Td.CANONICAL_OPAQUE_ID_PATTERN}});Object.defineProperty(P,"assertCanonicalOpaqueId",{enumerable:!0,get:function(){return Td.assertCanonicalOpaqueId}});Object.defineProperty(P,"compareCanonicalKeys",{enumerable:!0,get:function(){return Td.compareCanonicalKeys}});Object.defineProperty(P,"isCanonicalOpaqueId",{enumerable:!0,get:function(){return Td.isCanonicalOpaqueId}});Object.defineProperty(P,"isCanonicalText",{enumerable:!0,get:function(){return Td.isCanonicalText}});Object.defineProperty(P,"utf8ByteLength",{enumerable:!0,get:function(){return Td.utf8ByteLength}});var bn=Pte();Object.defineProperty(P,"ENCRYPTION_KEY_MIN_BYTES",{enumerable:!0,get:function(){return bn.ENCRYPTION_KEY_MIN_BYTES}});Object.defineProperty(P,"PG_ENCRYPTION_WIRE_VERSIONS",{enumerable:!0,get:function(){return bn.PG_ENCRYPTION_WIRE_VERSIONS}});Object.defineProperty(P,"PgDecryptionFailedError",{enumerable:!0,get:function(){return bn.PgDecryptionFailedError}});Object.defineProperty(P,"PgEncryptionError",{enumerable:!0,get:function(){return bn.PgEncryptionError}});Object.defineProperty(P,"PgEncryptionKeyMissingError",{enumerable:!0,get:function(){return bn.PgEncryptionKeyMissingError}});Object.defineProperty(P,"PgEncryptionWireFormatError",{enumerable:!0,get:function(){return bn.PgEncryptionWireFormatError}});Object.defineProperty(P,"decodeWireFormat",{enumerable:!0,get:function(){return bn.decodeWireFormat}});Object.defineProperty(P,"decrypt",{enumerable:!0,get:function(){return bn.decrypt}});Object.defineProperty(P,"decryptSqlFragment",{enumerable:!0,get:function(){return bn.decryptSqlFragment}});Object.defineProperty(P,"encodeWireFormat",{enumerable:!0,get:function(){return bn.encodeWireFormat}});Object.defineProperty(P,"encrypt",{enumerable:!0,get:function(){return bn.encrypt}});Object.defineProperty(P,"encryptSqlFragment",{enumerable:!0,get:function(){return bn.encryptSqlFragment}});Object.defineProperty(P,"isPgcryptoIntegrityError",{enumerable:!0,get:function(){return bn.isPgcryptoIntegrityError}});Object.defineProperty(P,"validateEncryptionKey",{enumerable:!0,get:function(){return bn.validateEncryptionKey}});var yt=Cte();Object.defineProperty(P,"SETUP_CONTRACT_VERSION",{enumerable:!0,get:function(){return yt.SETUP_CONTRACT_VERSION}});Object.defineProperty(P,"PROTECTED_CARD_MAX_DRAWS",{enumerable:!0,get:function(){return yt.PROTECTED_CARD_MAX_DRAWS}});Object.defineProperty(P,"SETUP_DEFAULT_AGGREGATE_CENTS",{enumerable:!0,get:function(){return yt.SETUP_DEFAULT_AGGREGATE_CENTS}});Object.defineProperty(P,"SETUP_DEFAULT_DAILY_CENTS",{enumerable:!0,get:function(){return yt.SETUP_DEFAULT_DAILY_CENTS}});Object.defineProperty(P,"SETUP_DEFAULT_PER_PURCHASE_CENTS",{enumerable:!0,get:function(){return yt.SETUP_DEFAULT_PER_PURCHASE_CENTS}});Object.defineProperty(P,"SETUP_IDENTITY_STEPS",{enumerable:!0,get:function(){return yt.SETUP_IDENTITY_STEPS}});Object.defineProperty(P,"SETUP_POLL_MS",{enumerable:!0,get:function(){return yt.SETUP_POLL_MS}});Object.defineProperty(P,"SETUP_RAILS",{enumerable:!0,get:function(){return yt.SETUP_RAILS}});Object.defineProperty(P,"SETUP_RAIL_STEPS",{enumerable:!0,get:function(){return yt.SETUP_RAIL_STEPS}});Object.defineProperty(P,"SETUP_STATES",{enumerable:!0,get:function(){return yt.SETUP_STATES}});Object.defineProperty(P,"SETUP_STEPS",{enumerable:!0,get:function(){return yt.SETUP_STEPS}});Object.defineProperty(P,"SETUP_STEP_STATUSES",{enumerable:!0,get:function(){return yt.SETUP_STEP_STATUSES}});Object.defineProperty(P,"SETUP_TERMINAL_STATES",{enumerable:!0,get:function(){return yt.SETUP_TERMINAL_STATES}});Object.defineProperty(P,"TARGETED_AWAITING_RUNTIME_LABEL",{enumerable:!0,get:function(){return yt.TARGETED_AWAITING_RUNTIME_LABEL}});Object.defineProperty(P,"UNBOUND_AWAITING_RUNTIME_LABEL",{enumerable:!0,get:function(){return yt.UNBOUND_AWAITING_RUNTIME_LABEL}});Object.defineProperty(P,"computeSetupNextAction",{enumerable:!0,get:function(){return yt.computeSetupNextAction}});Object.defineProperty(P,"computeSetupReadiness",{enumerable:!0,get:function(){return yt.computeSetupReadiness}});Object.defineProperty(P,"computeSetupStatus",{enumerable:!0,get:function(){return yt.computeSetupStatus}});Object.defineProperty(P,"computeSetupStepTargets",{enumerable:!0,get:function(){return yt.computeSetupStepTargets}});Object.defineProperty(P,"isSetupPlanSettled",{enumerable:!0,get:function(){return yt.isSetupPlanSettled}});Object.defineProperty(P,"isTerminal",{enumerable:!0,get:function(){return yt.isTerminal}});Object.defineProperty(P,"progressLadder",{enumerable:!0,get:function(){return yt.progressLadder}});Object.defineProperty(P,"setupPlanSteps",{enumerable:!0,get:function(){return yt.setupPlanSteps}});Object.defineProperty(P,"setupProgressSteps",{enumerable:!0,get:function(){return yt.setupProgressSteps}});var uy=Nte();Object.defineProperty(P,"runtimeLabel",{enumerable:!0,get:function(){return uy.runtimeLabel}});Object.defineProperty(P,"canonicalRuntimeId",{enumerable:!0,get:function(){return uy.canonicalRuntimeId}});Object.defineProperty(P,"runtimeMatchAliases",{enumerable:!0,get:function(){return uy.runtimeMatchAliases}});Object.defineProperty(P,"runtimesMatch",{enumerable:!0,get:function(){return uy.runtimesMatch}});Object.defineProperty(P,"claimBindingMode",{enumerable:!0,get:function(){return uy.claimBindingMode}});var dy=kte();Object.defineProperty(P,"ACTIVE_RAILWAY_SERVICES",{enumerable:!0,get:function(){return dy.ACTIVE_RAILWAY_SERVICES}});Object.defineProperty(P,"PROVIDER_CONFIGURATION_VARIABLE_KEYS",{enumerable:!0,get:function(){return dy.PROVIDER_CONFIGURATION_VARIABLE_KEYS}});Object.defineProperty(P,"RELEASE_MANIFEST_SCHEMA_VERSION",{enumerable:!0,get:function(){return dy.RELEASE_MANIFEST_SCHEMA_VERSION}});Object.defineProperty(P,"ReleaseManifestValidationError",{enumerable:!0,get:function(){return dy.ReleaseManifestValidationError}});Object.defineProperty(P,"validateReleaseManifest",{enumerable:!0,get:function(){return dy.validateReleaseManifest}})});var r4=g(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.PRODUCT_SPEND_POLICY_VERSION=void 0;En.canonicalMerchantOriginPattern=Vte;En.canonicalMerchantPathPrefix=Gte;En.canonicalMerchantTarget=Kte;En.canonicalOwnerProductSpendPolicy=Wte;En.canonicalRuntimeProductSpendAttenuation=zte;En.productSpendPolicyHash=Yte;En.isProductSpendPolicySubset=SVe;En.evaluateProductSpendPolicy=AVe;var fVe=require("node:crypto"),pVe=Fn();En.PRODUCT_SPEND_POLICY_VERSION=1;var mVe=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Hte=/^(?:0|[1-9][0-9]*)$/,Fte=/^eip155:[1-9][0-9]{0,15}$/,$te=/^eip155:[1-9][0-9]{0,15}\/erc20:0x[0-9a-f]{40}$/,gVe=128,hVe=64;function e4(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function t4(e,t,r){let n=new Set(r);for(let i of Object.keys(t))if(!n.has(i))throw new Error(`${e} contains unknown key '${i}'`)}function Ac(e,t){if(typeof t!="string"||!mVe.test(t))throw new Error(`${e} must be a UUID`);return t.toLowerCase()}function SS(e,t){if(!Number.isSafeInteger(t)||t<=0)throw new Error(`${e} must be a positive safe integer`);return t}function vS(e,t,r=!1){if(typeof t!="string"||!Hte.test(t)||!r&&t==="0")throw new Error(`${e} must be a ${r?"non-negative":"positive"} canonical integer string`);let n=BigInt(t);if(n>9223372036854775807n)throw new Error(`${e} exceeds bigint storage`);return n.toString()}function yVe(e,t){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp`);let r=Date.parse(t);if(!Number.isFinite(r))throw new Error(`${e} must be an ISO timestamp`);let n=new Date(r).toISOString();if(t!==n)throw new Error(`${e} must be canonical UTC ISO-8601`);return n}function Dte(e,t,r){if(!Array.isArray(t)||t.length===0||t.length>hVe)throw new Error(`${e} must be a non-empty bounded array`);let n=t.map(i=>{if(typeof i!="string"||!r.test(i))throw new Error(`${e} contains a non-canonical value`);return i});if(new Set(n).size!==n.length)throw new Error(`${e} must not repeat`);return[...n].sort()}function _Ve(e){if(e.startsWith("https://*.")){let t=e.slice(10);if(t.includes("*"))throw new Error("merchant wildcard must be the left-most full label");return{wildcard:!0,parseable:`https://wildcard.${t}`}}if(e.includes("*"))throw new Error("merchant wildcard must be the left-most full label");return{wildcard:!1,parseable:e}}function Jte(e,t){if(t.length===0||t.length>253||t.endsWith(".")||t.includes(":")||/^\d+(?:\.\d+){3}$/.test(t))throw new Error(`${e} must use a canonical DNS hostname`);for(let r of t.split("."))if(r.length===0||r.length>63||!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(r))throw new Error(`${e} must use a canonical DNS hostname`)}function Vte(e){if(typeof e!="string"||e.length===0||e.length>512)throw new Error("merchant origin pattern must be a bounded string");let{wildcard:t,parseable:r}=_Ve(e),n;try{n=new URL(r)}catch{throw new Error("merchant origin pattern must be a valid URL")}if(n.protocol!=="https:"||n.username!==""||n.password!==""||n.search!==""||n.hash!==""||n.pathname!=="/")throw new Error("merchant origin pattern must be a credential-free HTTPS origin");let i=t?n.hostname.replace(/^wildcard\./,""):n.hostname;if(Jte("merchant origin pattern",i),t&&!i.includes("."))throw new Error("merchant wildcard must retain a registrable parent label");return`https://${t?"*.":""}${i}${n.port===""?"":`:${n.port}`}`}function Gte(e){if(typeof e!="string"||e.length===0||e.length>1024)throw new Error("merchant path prefix must be a bounded string");if(!e.startsWith("/")||e.includes("?")||e.includes("#")||e.includes("\\"))throw new Error("merchant path prefix must be an absolute URL path");if(new URL(e,"https://policy.invalid").pathname!==e)throw new Error("merchant path prefix must be canonical");return e!=="/"&&e.endsWith("/")?e.slice(0,-1):e}function Kte(e){if(typeof e!="string"||e.length===0||e.length>2048)throw new Error("merchant target must be a bounded URL");let t;try{t=new URL(e)}catch{throw new Error("merchant target must be a valid URL")}if(t.protocol!=="https:"||t.username!==""||t.password!==""||t.hash!=="")throw new Error("merchant target must be a credential-free HTTPS URL");return Jte("merchant target",t.hostname),{origin:t.origin,path:t.pathname}}function bVe(e){if(!e4(e))throw new Error("merchant rule must be an object");if(t4("merchant rule",e,["effect","originPattern","pathPrefix"]),e.effect!=="allow"&&e.effect!=="deny")throw new Error("merchant rule effect must be allow or deny");return{effect:e.effect,originPattern:Vte(e.originPattern),pathPrefix:Gte(e.pathPrefix)}}function EVe(e,t){let r=`${e.effect}\0${e.originPattern}\0${e.pathPrefix}`,n=`${t.effect}\0${t.originPattern}\0${t.pathPrefix}`;return r<n?-1:r>n?1:0}function AS(e){if(e.v!==En.PRODUCT_SPEND_POLICY_VERSION)throw new Error("policy.v must be 1");let t=vS("totalMicros",e.totalMicros),r=vS("perTransactionMicros",e.perTransactionMicros,!0),n=e.dailyMicros===void 0?void 0:vS("dailyMicros",e.dailyMicros,!0),i=e.sessionMicros===void 0?void 0:vS("sessionMicros",e.sessionMicros,!0);for(let[u,d]of[["perTransactionMicros",r],["dailyMicros",n],["sessionMicros",i]])if(d!==void 0&&BigInt(d)>BigInt(t))throw new Error(`${u} cannot exceed totalMicros`);let o=Dte("networks",e.networks,Fte),s=Dte("assets",e.assets,$te);for(let u of s)if(!o.includes(u.slice(0,u.indexOf("/"))))throw new Error("each allowed asset must belong to an allowed network");if(e.merchantDefault!=="allow"&&e.merchantDefault!=="deny")throw new Error("merchantDefault must be allow or deny");if(!Array.isArray(e.merchantRules)||e.merchantRules.length>gVe)throw new Error("merchantRules must be a bounded array");let a=e.merchantRules.map(bVe).sort(EVe),c=a.map(u=>JSON.stringify(u));if(new Set(c).size!==c.length)throw new Error("merchantRules must not repeat");return{v:En.PRODUCT_SPEND_POLICY_VERSION,totalMicros:t,perTransactionMicros:r,...n===void 0?{}:{dailyMicros:n},...i===void 0?{}:{sessionMicros:i},networks:o,assets:s,merchantDefault:e.merchantDefault,merchantRules:a,expiresAt:yVe("expiresAt",e.expiresAt)}}function Wte(e){if(!e4(e))throw new Error("owner product spend policy must be an object");if(t4("owner product spend policy",e,["v","policyId","agentId","version","status","grantId","grantVersion","totalMicros","perTransactionMicros","dailyMicros","sessionMicros","networks","assets","merchantDefault","merchantRules","expiresAt"]),e.status!=="active"&&e.status!=="superseded"&&e.status!=="revoked")throw new Error("invalid product spend policy status");return{...AS(e),policyId:Ac("policyId",e.policyId),agentId:Ac("agentId",e.agentId),version:SS("version",e.version),status:e.status,grantId:Ac("grantId",e.grantId),grantVersion:SS("grantVersion",e.grantVersion)}}function zte(e){if(!e4(e))throw new Error("runtime product spend attenuation must be an object");return t4("runtime product spend attenuation",e,["v","attenuationId","agentId","runtimeId","version","ownerPolicyId","ownerPolicyVersion","supersedesAttenuationId","totalMicros","perTransactionMicros","dailyMicros","sessionMicros","networks","assets","merchantDefault","merchantRules","expiresAt"]),{...AS(e),attenuationId:Ac("attenuationId",e.attenuationId),agentId:Ac("agentId",e.agentId),runtimeId:Ac("runtimeId",e.runtimeId),version:SS("version",e.version),ownerPolicyId:Ac("ownerPolicyId",e.ownerPolicyId),ownerPolicyVersion:SS("ownerPolicyVersion",e.ownerPolicyVersion),...e.supersedesAttenuationId===void 0?{}:{supersedesAttenuationId:Ac("supersedesAttenuationId",e.supersedesAttenuationId)}}}function Yte(e){return(0,fVe.createHash)("sha256").update((0,pVe.canonicalJson)(e)).digest("base64url")}function Lte(e,t){let r=new Set(t);return e.every(n=>r.has(n))}function QD(e){let t=e.startsWith("https://*."),r=t?`https://wildcard.${e.slice(10)}`:e,n=new URL(r);return{wildcard:t,hostname:t?n.hostname.replace(/^wildcard\./,""):n.hostname,port:n.port}}function Xte(e,t){return t.wildcard?e.endsWith(`.${t.hostname}`)&&e!==t.hostname:e===t.hostname}function Zte(e,t){return t==="/"||e===t||e.startsWith(`${t}/`)}function wVe(e,t){let r=new URL(t.origin),n=QD(e.originPattern);return r.port===n.port&&Xte(r.hostname,n)&&Zte(t.path,e.pathPrefix)}function vVe(e,t){let r=QD(e),n=QD(t);return r.port!==n.port?!1:n.wildcard?r.wildcard?r.hostname===n.hostname||r.hostname.endsWith(`.${n.hostname}`):Xte(r.hostname,n):!r.wildcard&&r.hostname===n.hostname}function Bte(e,t){return vVe(e.originPattern,t.originPattern)&&Zte(e.pathPrefix,t.pathPrefix)}function Ute(e,t){return t===void 0?!0:e!==void 0&&BigInt(e)<=BigInt(t)}function SVe(e,t){let r,n;try{r=AS(e),n=AS(t)}catch{return!1}if(BigInt(r.totalMicros)>BigInt(n.totalMicros)||BigInt(r.perTransactionMicros)>BigInt(n.perTransactionMicros)||!Ute(r.dailyMicros,n.dailyMicros)||!Ute(r.sessionMicros,n.sessionMicros)||Date.parse(r.expiresAt)>Date.parse(n.expiresAt)||!Lte(r.networks,n.networks)||!Lte(r.assets,n.assets))return!1;let i=r.merchantRules.filter(({effect:u})=>u==="allow"),o=n.merchantRules.filter(({effect:u})=>u==="allow");if(n.merchantDefault==="deny"&&r.merchantDefault==="allow"||n.merchantDefault==="deny"&&!i.every(u=>o.some(d=>Bte(u,d))))return!1;let s=r.merchantRules.filter(({effect:u})=>u==="deny"),a=n.merchantRules.filter(({effect:u})=>u==="deny");return!(!(r.merchantDefault==="deny"&&i.length===0)&&!a.every(u=>s.some(d=>Bte(u,d))))}function Sc(e,t){if(typeof t!="string"||!Hte.test(t))throw new Error(`${e} must be a canonical non-negative integer string`);let r=BigInt(t);if(r>9223372036854775807n)throw new Error(`${e} exceeds bigint storage`);return r}function AVe(e){let t,r,n,i,o,s,a;try{if(t="policyId"in e.policy?Wte(e.policy):zte(e.policy),r=Sc("amountMicros",e.amountMicros),r===0n)throw new Error("amountMicros must be positive");if(n=e.hardMaximumMicros===void 0?void 0:Sc("hardMaximumMicros",e.hardMaximumMicros),!Fte.test(e.network)||!$te.test(e.asset))throw new Error("network or asset is not canonical");i=Kte(e.merchantUrl),o=Sc("totalSpentMicros",e.usage.totalSpentMicros)+Sc("totalReservedMicros",e.usage.totalReservedMicros),s=Sc("dailySpentMicros",e.usage.dailySpentMicros)+Sc("dailyReservedMicros",e.usage.dailyReservedMicros),a=Sc("sessionSpentMicros",e.usage.sessionSpentMicros)+Sc("sessionReservedMicros",e.usage.sessionReservedMicros)}catch{return{ok:!1,reason:"invalid_state"}}if("status"in t&&t.status!=="active")return{ok:!1,reason:"policy_not_active"};if(!Number.isFinite(e.nowMs))return{ok:!1,reason:"invalid_state"};if(e.nowMs>=Date.parse(t.expiresAt))return{ok:!1,reason:"policy_expired"};if(!t.networks.includes(e.network))return{ok:!1,reason:"network_not_allowed"};if(!t.assets.includes(e.asset))return{ok:!1,reason:"asset_not_allowed"};let c=t.merchantRules.filter(m=>wVe(m,i));if(c.some(({effect:m})=>m==="deny"))return{ok:!1,reason:"merchant_denied"};if(t.merchantDefault==="deny"&&!c.some(({effect:m})=>m==="allow"))return{ok:!1,reason:"merchant_not_allowed"};if(n!==void 0&&r>n)return{ok:!1,reason:"over_hard_maximum"};if(r>BigInt(t.perTransactionMicros))return{ok:!1,reason:"over_per_transaction"};let u=BigInt(t.totalMicros)-o;if(r>u)return{ok:!1,reason:"over_total"};let d=t.dailyMicros===void 0?null:BigInt(t.dailyMicros)-s;if(d!==null&&r>d)return{ok:!1,reason:"over_daily"};let l=t.sessionMicros===void 0?null:BigInt(t.sessionMicros)-a;return l!==null&&r>l?{ok:!1,reason:"over_session"}:{ok:!0,policyHash:Yte(t),totalRemainingMicros:(u-r).toString(),dailyRemainingMicros:d===null?null:(d-r).toString(),sessionRemainingMicros:l===null?null:(l-r).toString()}}});var ore=g(IS=>{"use strict";Object.defineProperty(IS,"__esModule",{value:!0});IS.canonicalLegacyWalletSpendPolicy=ire;IS.importLegacyWalletSpendPolicy=kVe;var ere=r4(),tre=9223372036854775807n,rre=/^eip155:[1-9][0-9]{0,15}$/,IVe=/^eip155:[1-9][0-9]{0,15}\/erc20:0x[0-9a-f]{40}$/,PVe=16,TVe=128;function xVe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function OVe(e){let t=new Set(["perTxCapUsd","dailyCapUsd","sessionBudgetUsd","allowedNetworks","merchantAllowlist","merchantDenylist","expiresAt"]);for(let r of Object.keys(e))if(!t.has(r))throw new Error(`legacy wallet policy contains unknown key '${r}'`)}function yp(e,t){if(typeof t!="string")throw new Error(`${e} must be a USD decimal string`);let r=/^(0|[1-9][0-9]*)(?:\.([0-9]{1,6}))?$/.exec(t);if(!r)throw new Error(`${e} must be a canonical USD amount with at most 6 decimals`);let n=BigInt(`${r[1]}${(r[2]??"").padEnd(6,"0")}`);if(n>tre)throw new Error(`${e} exceeds bigint storage`);return n.toString()}function nre(e,t){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp`);let r=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.exec(t);if(!r)throw new Error(`${e} must be an ISO timestamp with an explicit timezone`);let[,n,i,o,s,a,c]=r,u=Number(n),d=Number(i),l=Number(o),m=Number(s),p=Number(a),h=Number(c),y=new Date(0);if(y.setUTCFullYear(u,d-1,l),y.setUTCHours(m,p,h,0),u===0||y.getUTCFullYear()!==u||y.getUTCMonth()!==d-1||y.getUTCDate()!==l||y.getUTCHours()!==m||y.getUTCMinutes()!==p||y.getUTCSeconds()!==h)throw new Error(`${e} must contain a valid calendar instant`);let b=Date.parse(t);if(!Number.isFinite(b))throw new Error(`${e} must be an ISO timestamp`);return new Date(b).toISOString()}function RVe(e){if(!Array.isArray(e)||e.length===0||e.length>PVe)throw new Error("allowedNetworks must be a non-empty bounded array");let t=e.map(r=>{if(typeof r!="string"||!rre.test(r))throw new Error("allowedNetworks contains a non-canonical network");return r});return[...new Set(t)].sort()}function CVe(e){if(typeof e!="string"||e.length===0||e.length>255)throw new Error("legacy merchant host must be a bounded string");if(e.includes("/")||e.includes("@")||e.includes("*")||e.includes(":"))throw new Error("legacy merchant host must be an exact DNS host");let t;try{t=new URL(`https://${e}`)}catch{throw new Error("legacy merchant host must be a valid DNS host")}let r=t.host.toLowerCase();if(e.toLowerCase()!==r)throw new Error("legacy merchant host must already have canonical URL spelling");return(0,ere.canonicalMerchantOriginPattern)(`https://${r}`),r}function Qte(e,t){if(t!==void 0){if(!Array.isArray(t)||t.length>TVe)throw new Error(`${e} must be a bounded array`);return[...new Set(t.map(CVe))].sort()}}function ire(e){if(!xVe(e))throw new Error("legacy wallet policy must be an object");OVe(e);let t=Qte("merchantAllowlist",e.merchantAllowlist),r=Qte("merchantDenylist",e.merchantDenylist);return yp("perTxCapUsd",e.perTxCapUsd),yp("dailyCapUsd",e.dailyCapUsd),yp("sessionBudgetUsd",e.sessionBudgetUsd),{perTxCapUsd:e.perTxCapUsd,dailyCapUsd:e.dailyCapUsd,sessionBudgetUsd:e.sessionBudgetUsd,allowedNetworks:RVe(e.allowedNetworks),...t===void 0?{}:{merchantAllowlist:t},...r===void 0?{}:{merchantDenylist:r},...e.expiresAt===void 0?{}:{expiresAt:nre("expiresAt",e.expiresAt)}}}function n4(e,t){if(typeof t!="string"||!/^[1-9][0-9]*$/.test(t))throw new Error(`${e} must be a positive canonical micros string`);let r=BigInt(t);if(r>tre)throw new Error(`${e} exceeds bigint storage`);return r.toString()}function ly(e,t){return(BigInt(e)<=BigInt(t)?BigInt(e):BigInt(t)).toString()}function NVe(e){let t=(e.merchantAllowlist??[]).map(n=>({effect:"allow",originPattern:`https://${n}`,pathPrefix:"/"})),r=(e.merchantDenylist??[]).map(n=>({effect:"deny",originPattern:`https://${n}`,pathPrefix:"/"}));return[...t,...r]}function kVe(e){let t=ire(e.policy),r=n4("grantTotalMicros",e.context.grantTotalMicros),n=n4("grantPerTransactionMicros",e.context.grantPerTransactionMicros),i=e.context.grantDailyMicros===void 0?r:n4("grantDailyMicros",e.context.grantDailyMicros),o=nre("grantExpiresAt",e.context.grantExpiresAt);if(!rre.test(e.context.walletNetwork))throw new Error("walletNetwork must be a canonical CAIP-2 identifier");if(!IVe.test(e.context.walletAsset)||!e.context.walletAsset.startsWith(`${e.context.walletNetwork}/`))throw new Error("walletAsset must be the canonical asset on walletNetwork");if(!t.allowedNetworks.includes(e.context.walletNetwork))throw new Error("the legacy policy does not allow the active wallet network");let s=yp("perTxCapUsd",t.perTxCapUsd),a=yp("dailyCapUsd",t.dailyCapUsd),c=yp("sessionBudgetUsd",t.sessionBudgetUsd),u=t.expiresAt?new Date(Math.min(Date.parse(t.expiresAt),Date.parse(o))).toISOString():o;return{v:ere.PRODUCT_SPEND_POLICY_VERSION,totalMicros:r,perTransactionMicros:ly(s,ly(n,r)),dailyMicros:ly(a,ly(i,r)),sessionMicros:ly(c,r),networks:[e.context.walletNetwork],assets:[e.context.walletAsset],merchantDefault:t.merchantAllowlist===void 0?"allow":"deny",merchantRules:NVe(t),expiresAt:u}}});var Ic=g(PS=>{"use strict";Object.defineProperty(PS,"__esModule",{value:!0});PS.prepareRootSignedJws=jVe;PS.completeRootSignedJws=MVe;var i4=Ed();function jVe(e,t,r){let n=(0,i4.bytesToBase64Url)(new TextEncoder().encode(JSON.stringify({alg:"EdDSA",kid:t,typ:e}))),i=(0,i4.bytesToBase64Url)(new TextEncoder().encode(JSON.stringify(r)));return{signingInput:`${n}.${i}`}}function MVe(e,t,r){if(!(t instanceof Uint8Array)||t.length!==64)throw new Error(`${r} signature must be exactly 64 raw Ed25519 bytes`);return`${e}.${(0,i4.bytesToBase64Url)(t)}`}});var TS=g(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.HOSTED_RUNTIME_CERTIFICATE_PURPOSES=Et.RUNTIME_CERTIFICATE_PURPOSES=Et.CARD_RUNTIME_CERTIFICATE_MAX_TTL_SECONDS=Et.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS=Et.RUNTIME_CERTIFICATE_VERSION=Et.RUNTIME_CERTIFICATE_TYP=void 0;Et.runtimeCertificateMaxTtl=cre;Et.isCanonicalBase64Url32=s4;Et.prepareRuntimeCertificate=FVe;var sre=Ed(),are=W0(),qVe=Ic();Et.RUNTIME_CERTIFICATE_TYP="visa-agent-runtime-cert+jwt";Et.RUNTIME_CERTIFICATE_VERSION=1;Et.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS=1440*60;Et.CARD_RUNTIME_CERTIFICATE_MAX_TTL_SECONDS=366*24*60*60;function cre(e){return e.length===1&&e[0]==="card:vic"?Et.CARD_RUNTIME_CERTIFICATE_MAX_TTL_SECONDS:Et.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS}Et.RUNTIME_CERTIFICATE_PURPOSES=["tap","subway","card:vic","wallet:x402"];Et.HOSTED_RUNTIME_CERTIFICATE_PURPOSES=["card:vic","wallet:x402","tap"];var DVe=new Set(Et.RUNTIME_CERTIFICATE_PURPOSES),o4=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,LVe=/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;function s4(e){if(typeof e!="string"||!LVe.test(e))return!1;let t=(0,sre.base64UrlToBytes)(e);return t.length===32&&(0,sre.bytesToBase64Url)(t)===e}function BVe(e){return{kty:"OKP",crv:"Ed25519",x:e.x}}function UVe(e){if(!Array.isArray(e)||e.length===0)throw new Error("runtime certificate requires at least one purpose");let t=[...new Set(e)];if(t.length!==e.length||t.some(r=>!DVe.has(r)))throw new Error("runtime certificate purposes must be unique supported values");return t.sort()}function HVe(e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative unix-seconds integer`)}function FVe(e){let t=e.nowSec??Math.floor(Date.now()/1e3),r=e.ttlSeconds??Et.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS,n=cre(e.purposes),i=e.certificateId??globalThis.crypto.randomUUID();if(HVe("nowSec",t),!Number.isSafeInteger(r)||r<=0||r>n)throw new Error(`runtime certificate ttlSeconds must be in (0, ${n}]`);if(!o4.test(e.agentId)||!o4.test(e.runtimeId))throw new Error("runtime certificate agentId/runtimeId must be canonical UUIDs");if(!o4.test(i))throw new Error("runtime certificate certificateId must be a canonical UUID");if(!s4(e.rootJkt))throw new Error("runtime certificate rootJkt must be a canonical RFC 7638 thumbprint");if(!e.rootKid||e.rootKid.length>256)throw new Error("runtime certificate rootKid must be a bounded non-empty identifier");if((0,are.computeJkt)(e.rootPublicJwk)!==e.rootJkt)throw new Error("runtime certificate signer public key does not match rootJkt");let s=BVe(e.runtimePublicJwk);if(!s4(s.x))throw new Error("runtime certificate child key must be canonical Ed25519");let a=(0,are.computeJkt)(s);if(a===e.rootJkt)throw new Error("runtime certificate child key must differ from the identity root");let c={v:Et.RUNTIME_CERTIFICATE_VERSION,iss:e.rootJkt,sub:e.agentId,jti:i,runtimeId:e.runtimeId,cnf:{jwk:s,jkt:a},purposes:UVe(e.purposes),iat:t,nbf:t,exp:t+r};return{...(0,qVe.prepareRootSignedJws)(Et.RUNTIME_CERTIFICATE_TYP,e.rootKid,c),claims:c}}});var c4=g(Li=>{"use strict";var $Ve=Li&&Li.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),JVe=Li&&Li.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&$Ve(t,e,r)};Object.defineProperty(Li,"__esModule",{value:!0});Li.completeRuntimeCertificate=dre;Li.issueRuntimeCertificate=KVe;Li.peekRuntimeCertificate=YVe;Li.verifyRuntimeCertificate=XVe;var ure=Br(),a4=Un(),VVe=Ic();JVe(TS(),Li);var js=TS(),GVe=new Set(js.RUNTIME_CERTIFICATE_PURPOSES),fy=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function dre(e,t){return(0,VVe.completeRootSignedJws)(e.signingInput,t,"runtime certificate")}async function KVe(e){let t=(0,js.prepareRuntimeCertificate)({rootKid:e.signer.kid,rootPublicJwk:e.signer.publicJwk,rootJkt:e.rootJkt,agentId:e.agentId,runtimeId:e.runtimeId,runtimePublicJwk:e.runtimePublicJwk,purposes:e.purposes,...e.ttlSeconds===void 0?{}:{ttlSeconds:e.ttlSeconds},...e.nowSec===void 0?{}:{nowSec:e.nowSec},...e.certificateId===void 0?{}:{certificateId:e.certificateId}}),r=await e.signer.sign(new TextEncoder().encode(t.signingInput));return dre(t,r)}function WVe(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return Object.keys(t).length===3&&t.kty==="OKP"&&t.crv==="Ed25519"&&(0,js.isCanonicalBase64Url32)(t.x)}function zVe(e){return Array.isArray(e)&&e.length>0&&e.every(t=>typeof t=="string"?GVe.has(t):!1)&&new Set(e).size===e.length&&[...e].sort().every((t,r)=>t===e[r])}function YVe(e){let t=(0,a4.decodeJwt)(e);return!t||t.header.typ!==js.RUNTIME_CERTIFICATE_TYP||typeof t.claims.sub!="string"||!fy.test(t.claims.sub)||typeof t.claims.iss!="string"||!(0,js.isCanonicalBase64Url32)(t.claims.iss)||typeof t.claims.runtimeId!="string"||!fy.test(t.claims.runtimeId)||typeof t.claims.jti!="string"||!fy.test(t.claims.jti)?null:{agentId:t.claims.sub,rootJkt:t.claims.iss,runtimeId:t.claims.runtimeId,certificateId:t.claims.jti}}async function XVe(e,t){if(!Number.isSafeInteger(t.nowSec)||t.nowSec<0)return{ok:!1,reason:"bad_verification_time"};let r=await(0,a4.verifyJwtSignature)(e,t.jwks);if(!r.ok)return r;if(r.header.typ!==js.RUNTIME_CERTIFICATE_TYP)return{ok:!1,reason:"typ_mismatch"};let n=r.claims;if(n.v!==js.RUNTIME_CERTIFICATE_VERSION||n.iss!==t.expectedRootJkt||n.sub!==t.expectedAgentId||typeof n.jti!="string"||!fy.test(n.jti)||typeof n.runtimeId!="string"||!fy.test(n.runtimeId))return{ok:!1,reason:"claims_mismatch"};if(r.header.kid===void 0)return{ok:!1,reason:"kid_missing"};let i=t.jwks.keys.find(a=>a.kid===r.header.kid);if(!i||(0,ure.computeJkt)(i)!==t.expectedRootJkt)return{ok:!1,reason:"root_key_mismatch"};if(t.expectedRuntimeId!==void 0&&n.runtimeId!==t.expectedRuntimeId)return{ok:!1,reason:"runtime_mismatch"};if(t.expectedCertificateId!==void 0&&n.jti!==t.expectedCertificateId)return{ok:!1,reason:"certificate_mismatch"};if(!n.cnf||!WVe(n.cnf.jwk)||!(0,js.isCanonicalBase64Url32)(n.cnf.jkt))return{ok:!1,reason:"bad_cnf_key"};let o=(0,ure.computeJkt)(n.cnf.jwk);if(n.cnf.jkt!==o||o!==t.expectedRuntimeJkt)return{ok:!1,reason:"runtime_key_mismatch"};if(!zVe(n.purposes)||!n.purposes.includes(t.requiredPurpose))return{ok:!1,reason:"purpose_denied"};let s=(0,a4.temporalReason)(n,t.nowSec);return s?{ok:!1,reason:s}:typeof n.nbf!="number"||!Number.isSafeInteger(n.nbf)||n.nbf>t.nowSec||n.nbf!==n.iat?{ok:!1,reason:"not_yet_valid"}:typeof n.iat!="number"||typeof n.exp!="number"||!Number.isSafeInteger(n.iat)||!Number.isSafeInteger(n.exp)||n.exp-n.iat>(0,js.runtimeCertificateMaxTtl)(n.purposes)?{ok:!1,reason:"ttl_exceeded"}:{ok:!0,claims:n,rootJkt:t.expectedRootJkt,runtimeJkt:o}}});var xd=g(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.WALLET_BINDING_TYP=wn.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS=wn.RUNTIME_LEASE_MAX_TTL_SECONDS=wn.RUNTIME_DELEGATION_MAX_TTL_SECONDS=wn.RUNTIME_LEASE_SIGNING_MODES=wn.RUNTIME_DELEGATION_TYP=void 0;wn.RUNTIME_DELEGATION_TYP="visa-agent-runtime-delegation+jwt";wn.RUNTIME_LEASE_SIGNING_MODES=["eip3009:exact","permit2:upto"];var lre=vd();Object.defineProperty(wn,"RUNTIME_DELEGATION_MAX_TTL_SECONDS",{enumerable:!0,get:function(){return lre.RUNTIME_DELEGATION_MAX_TTL_SECONDS}});Object.defineProperty(wn,"RUNTIME_LEASE_MAX_TTL_SECONDS",{enumerable:!0,get:function(){return lre.RUNTIME_LEASE_MAX_TTL_SECONDS}});wn.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS=30;wn.WALLET_BINDING_TYP="visa-agent-wallet-binding+jwt"});var kS=g(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.TEMPO_LEASE_SIGNING_MODE=G.TEMPO_LEASE_NETWORK=G.TEMPO_LEASE_PURPOSE=G.RUNTIME_LEASE_PURPOSE=G.RUNTIME_LEASE_AUDIENCE=G.RUNTIME_LEASE_VERSION=G.RUNTIME_LEASE_TYP=G.RUNTIME_DELEGATION_RAILS=G.RUNTIME_CUSTODIES=G.RUNTIME_DELEGATION_LEGACY_VERSION=G.RUNTIME_DELEGATION_VERSION=G.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS=G.RUNTIME_LEASE_MAX_TTL_SECONDS=G.RUNTIME_DELEGATION_MAX_TTL_SECONDS=G.RUNTIME_LEASE_SIGNING_MODES=G.RUNTIME_DELEGATION_TYP=void 0;G.runtimeDelegationScope=hy;G.prepareRuntimeDelegation=mre;G.completeRuntimeDelegation=gre;G.issueRuntimeDelegation=tGe;G.issueRuntimeLease=rGe;G.issueTempoRuntimeLease=nGe;G.verifyRuntimeDelegation=yy;G.verifyRuntimeLeaseChain=sGe;G.verifyTempoRuntimeLeaseChain=aGe;var u4=require("node:crypto"),my=Br(),d4=Un(),py=Ic(),gy=xd();Object.defineProperty(G,"RUNTIME_DELEGATION_TYP",{enumerable:!0,get:function(){return gy.RUNTIME_DELEGATION_TYP}});Object.defineProperty(G,"RUNTIME_LEASE_SIGNING_MODES",{enumerable:!0,get:function(){return gy.RUNTIME_LEASE_SIGNING_MODES}});Object.defineProperty(G,"RUNTIME_DELEGATION_MAX_TTL_SECONDS",{enumerable:!0,get:function(){return gy.RUNTIME_DELEGATION_MAX_TTL_SECONDS}});Object.defineProperty(G,"RUNTIME_LEASE_MAX_TTL_SECONDS",{enumerable:!0,get:function(){return gy.RUNTIME_LEASE_MAX_TTL_SECONDS}});Object.defineProperty(G,"RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS",{enumerable:!0,get:function(){return gy.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS}});var Gt=xd();G.RUNTIME_DELEGATION_VERSION=2;G.RUNTIME_DELEGATION_LEGACY_VERSION=1;G.RUNTIME_CUSTODIES=["device","gate"];G.RUNTIME_DELEGATION_RAILS=["tempo","x402"];G.RUNTIME_LEASE_TYP="visa-agent-runtime-lease+jwt";G.RUNTIME_LEASE_VERSION=1;G.RUNTIME_LEASE_AUDIENCE="urn:visa:tvc:slipgate";G.RUNTIME_LEASE_PURPOSE="wallet:x402";G.TEMPO_LEASE_PURPOSE="wallet:tempo";G.TEMPO_LEASE_NETWORK="eip155:4217";G.TEMPO_LEASE_SIGNING_MODE="tempo:access-key";var Ms=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,ZVe=/^[A-Za-z0-9_-]{43}$/,l4=/^eip155:[1-9][0-9]{0,15}$/,Od=/^[A-Za-z0-9._:@/-]{1,256}$/,xS=new Map(Gt.RUNTIME_LEASE_SIGNING_MODES.map((e,t)=>[e,t]));function vn(e){if(typeof e!="string"||!ZVe.test(e))return!1;let t=Buffer.from(e,"base64url");return t.length===32&&t.toString("base64url")===e}function QVe(e){let t=e.toLowerCase();if(!l4.test(t))throw new Error("runtime authority network is invalid");return t}function Pc(e,t){if(!Ms.test(t))throw new Error(`${e} must be a canonical UUID`)}function fre(e,t){if(!Od.test(t))throw new Error(`${e} must be a bounded identifier`)}function OS(e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative unix-seconds integer`)}function RS(e){if(!Array.isArray(e)||e.length===0)throw new Error("runtime authority requires at least one signing mode");let t=[...new Set(e)];if(t.length!==e.length||t.some(r=>!xS.has(r)))throw new Error("runtime authority signing modes must be unique supported values");return t.sort((r,n)=>xS.get(r)-xS.get(n))}function CS(e,t){let r=Object.keys(e).sort(),n=[...t].sort();return r.length===n.length&&r.every((i,o)=>i===n[o])}function pre(e){if(!Array.isArray(e)||e.length===0||e.some(r=>typeof r!="string"||!xS.has(r)))return!1;let t=e;return new Set(t).size===t.length&&RS(t).every((r,n)=>r===t[n])}function hy(e){let t="custody"in e,r="rails"in e;if(e.v===G.RUNTIME_DELEGATION_LEGACY_VERSION)return t||r?null:{custody:null,tempo:!1};if(e.v!==G.RUNTIME_DELEGATION_VERSION||!t||!r)return null;let{custody:n,rails:i}=e;return!G.RUNTIME_CUSTODIES.includes(n)||!Array.isArray(i)||!eGe(i)||n==="gate"&&!(i.length===1&&i[0]==="x402")?null:{custody:n,tempo:i.includes("tempo")}}function eGe(e){let t=e.map(r=>G.RUNTIME_DELEGATION_RAILS.indexOf(r));return t.length>0&&t.every((r,n)=>r>=0&&(n===0||r>t[n-1]))&&e.includes("x402")}function mre(e){let t=e.nowSec??Math.floor(Date.now()/1e3),r=e.ttlSeconds??Gt.RUNTIME_DELEGATION_MAX_TTL_SECONDS,n=e.maxLeaseTtlSeconds??Gt.RUNTIME_LEASE_MAX_TTL_SECONDS,i=e.delegationId??(0,u4.randomUUID)();if(OS("nowSec",t),!Number.isSafeInteger(r)||r<=0||r>Gt.RUNTIME_DELEGATION_MAX_TTL_SECONDS)throw new Error(`runtime delegation ttlSeconds must be in (0, ${Gt.RUNTIME_DELEGATION_MAX_TTL_SECONDS}]`);if(!Number.isSafeInteger(n)||n<=0||n>Gt.RUNTIME_LEASE_MAX_TTL_SECONDS)throw new Error(`runtime delegation maxLeaseTtlSeconds must be in (0, ${Gt.RUNTIME_LEASE_MAX_TTL_SECONDS}]`);if(Pc("agentId",e.agentId),Pc("runtimeId",e.runtimeId),Pc("delegationId",i),fre("rootKid",e.rootKid),!vn(e.rootJkt)||(0,my.computeJkt)(e.rootPublicJwk)!==e.rootJkt)throw new Error("runtime delegation root public key does not match rootJkt");if(!vn(e.runtimeJkt)||!vn(e.leaseIssuerJkt))throw new Error("runtime delegation runtime/issuer JKT is invalid");if(new Set([e.rootJkt,e.runtimeJkt,e.leaseIssuerJkt]).size!==3)throw new Error("runtime delegation root, runtime, and issuer keys must be distinct");let o=e.custody!==null;if(!o&&e.rails!==void 0)throw new Error("an unmarked (v1) runtime delegation carries no rails");let s=[...e.rails??["x402"]];if(o&&hy({v:G.RUNTIME_DELEGATION_VERSION,custody:e.custody,rails:s})===null)throw new Error("runtime delegation custody must be device or gate, with sorted rails including x402 (tempo only for device)");let a=t+r;OS("runtime delegation expiration",a);let c={v:o?G.RUNTIME_DELEGATION_VERSION:G.RUNTIME_DELEGATION_LEGACY_VERSION,iss:e.rootJkt,sub:e.agentId,jti:i,runtimeId:e.runtimeId,runtimeJkt:e.runtimeJkt,leaseIssuerJkt:e.leaseIssuerJkt,purpose:G.RUNTIME_LEASE_PURPOSE,network:QVe(e.network),signingModes:RS(e.signingModes),...o?{custody:e.custody,rails:s}:{},maxLeaseTtlSeconds:n,iat:t,nbf:t,exp:a};return{...(0,py.prepareRootSignedJws)(Gt.RUNTIME_DELEGATION_TYP,e.rootKid,c),claims:c}}function gre(e,t){return(0,py.completeRootSignedJws)(e.signingInput,t,"runtime delegation")}async function tGe(e){let t=mre({...e,rootKid:e.signer.kid,rootPublicJwk:e.signer.publicJwk}),r=await e.signer.sign(new TextEncoder().encode(t.signingInput));return gre(t,r)}function hre(e){let t=e.nowSec??Math.floor(Date.now()/1e3),r=e.ttlSeconds??e.delegation.maxLeaseTtlSeconds,n=t+r,i=e.leaseId??(0,u4.randomUUID)();if(OS("nowSec",t),OS("delegationExpiresAt",e.delegation.exp),!Number.isSafeInteger(e.delegation.maxLeaseTtlSeconds)||e.delegation.maxLeaseTtlSeconds<=0||e.delegation.maxLeaseTtlSeconds>Gt.RUNTIME_LEASE_MAX_TTL_SECONDS)throw new Error("runtime lease maximum TTL is invalid");if(!Number.isSafeInteger(r)||r<=0||r>e.delegation.maxLeaseTtlSeconds||!Number.isSafeInteger(n)||n>e.delegation.exp)throw new Error("runtime lease TTL exceeds its delegation");if(Pc("agentId",e.delegation.sub),Pc("runtimeId",e.delegation.runtimeId),Pc("delegationId",e.delegation.jti),Pc("leaseId",i),Pc("grantId",e.grantId),fre("issuerKid",e.issuerKid),!vn(e.delegation.leaseIssuerJkt)||(0,my.computeJkt)(e.issuerPublicJwk)!==e.delegation.leaseIssuerJkt)throw new Error("runtime lease issuer public key does not match leaseIssuerJkt");if(!vn(e.delegation.iss)||!vn(e.delegation.runtimeJkt))throw new Error("runtime lease root/runtime JKT is invalid");if(new Set([e.delegation.iss,e.delegation.runtimeJkt,e.delegation.leaseIssuerJkt]).size!==3)throw new Error("runtime lease root, runtime, and issuer keys must be distinct");if(!Number.isSafeInteger(e.generation)||e.generation<1)throw new Error("runtime lease generation must be a positive safe integer");if(!Number.isSafeInteger(e.grantVersion)||e.grantVersion<1)throw new Error("runtime lease grantVersion must be a positive safe integer");if(!vn(e.delegationHash))throw new Error("runtime lease delegationHash is invalid");if(e.tempo){let a=hy(e.delegation);if(a?.custody!=="device"||!a.tempo)throw new Error("a Tempo lease needs a device delegation that covers tempo");let c={v:G.RUNTIME_LEASE_VERSION,iss:e.delegation.leaseIssuerJkt,sub:e.delegation.sub,aud:G.RUNTIME_LEASE_AUDIENCE,jti:i,delegationId:e.delegation.jti,delegationHash:e.delegationHash,rootJkt:e.delegation.iss,runtimeId:e.delegation.runtimeId,runtimeJkt:e.delegation.runtimeJkt,purpose:G.TEMPO_LEASE_PURPOSE,network:G.TEMPO_LEASE_NETWORK,signingModes:[G.TEMPO_LEASE_SIGNING_MODE],generation:e.generation,grantId:e.grantId,grantVersion:e.grantVersion,iat:t,nbf:t,exp:n};return{...(0,py.prepareRootSignedJws)(G.RUNTIME_LEASE_TYP,e.issuerKid,c),claims:c}}let o=RS(e.signingModes);if(!o.every(a=>e.delegation.signingModes.includes(a)))throw new Error("runtime lease signing modes exceed the verified delegation");let s={v:G.RUNTIME_LEASE_VERSION,iss:e.delegation.leaseIssuerJkt,sub:e.delegation.sub,aud:G.RUNTIME_LEASE_AUDIENCE,jti:i,delegationId:e.delegation.jti,delegationHash:e.delegationHash,rootJkt:e.delegation.iss,runtimeId:e.delegation.runtimeId,runtimeJkt:e.delegation.runtimeJkt,purpose:G.RUNTIME_LEASE_PURPOSE,network:e.delegation.network,signingModes:o,generation:e.generation,grantId:e.grantId,grantVersion:e.grantVersion,iat:t,nbf:t,exp:n};return{...(0,py.prepareRootSignedJws)(G.RUNTIME_LEASE_TYP,e.issuerKid,s),claims:s}}function yre(e,t){return(0,py.completeRootSignedJws)(e.signingInput,t,"runtime lease")}async function rGe(e){let t=e.nowSec??Math.floor(Date.now()/1e3),r=await yy(e.delegationToken,{...e.delegationVerification,nowSec:t});if(!r.ok)throw new Error(`runtime lease delegation refused: ${r.reason}`);let n=hre({delegation:r.delegation,delegationHash:NS(e.delegationToken),signingModes:e.signingModes,generation:e.generation,grantId:e.grantId,grantVersion:e.grantVersion,ttlSeconds:e.ttlSeconds,nowSec:t,leaseId:e.leaseId,issuerKid:e.signer.kid,issuerPublicJwk:e.signer.publicJwk}),i=await e.signer.sign(new TextEncoder().encode(n.signingInput));return yre(n,i)}async function nGe(e){let t=e.nowSec??Math.floor(Date.now()/1e3),r=await yy(e.delegationToken,{...e.delegationVerification,requiredCustody:"device",nowSec:t});if(!r.ok)throw new Error(`runtime lease delegation refused: ${r.reason}`);let n=hre({delegation:r.delegation,delegationHash:NS(e.delegationToken),signingModes:[],tempo:!0,generation:e.generation,grantId:e.grantId,grantVersion:e.grantVersion,ttlSeconds:e.ttlSeconds,nowSec:t,leaseId:e.leaseId,issuerKid:e.signer.kid,issuerPublicJwk:e.signer.publicJwk}),i=await e.signer.sign(new TextEncoder().encode(n.signingInput));return yre(n,i)}var _re=["v","iss","sub","jti","runtimeId","runtimeJkt","leaseIssuerJkt","purpose","network","signingModes","maxLeaseTtlSeconds","iat","nbf","exp"],iGe=[..._re,"custody","rails"],bre=["v","iss","sub","aud","jti","delegationId","delegationHash","rootJkt","runtimeId","runtimeJkt","purpose","network","signingModes","generation","grantId","grantVersion","iat","nbf","exp"],oGe=["alg","kid","typ"];function NS(e){return(0,u4.createHash)("sha256").update(e,"utf8").digest("base64url")}function Ere(e){try{let t=Buffer.from(e,"base64url");if(t.toString("base64url")!==e)return null;let r=new TextDecoder("utf-8",{fatal:!0}).decode(t),n=JSON.parse(r);return typeof n!="object"||n===null||Array.isArray(n)||JSON.stringify(n)!==r?null:n}catch{return null}}function f4(e){let t=e.split(".");return t.length===3&&Ere(t[1])!==null}function p4(e){let t=e.split(".");if(t.length!==3)return!1;let r=Ere(t[0]),n=Buffer.from(t[2],"base64url");return r!==null&&n.length===64&&n.toString("base64url")===t[2]&&CS(r,oGe)&&typeof r.alg=="string"&&typeof r.kid=="string"&&Od.test(r.kid)}function m4(e,t,r){return typeof e.iat!="number"||typeof e.nbf!="number"||typeof e.exp!="number"||!Number.isSafeInteger(e.iat)||!Number.isSafeInteger(e.nbf)||!Number.isSafeInteger(e.exp)||e.iat<0||e.nbf!==e.iat||e.exp<=e.iat||e.exp-e.iat>r?"ttl_exceeded":e.iat>t+Gt.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS||e.nbf>t+Gt.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS?"not_yet_valid":t>=e.exp?"expired":null}async function yy(e,t){if(!Number.isSafeInteger(t.nowSec)||t.nowSec<0||t.nowSec>Number.MAX_SAFE_INTEGER-Gt.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS||!Od.test(t.expectedRootKid))return{ok:!1,reason:"bad_verification_context"};if(!p4(e))return{ok:!1,reason:"delegation_header_invalid"};if(!f4(e))return{ok:!1,reason:"delegation_shape_invalid"};let r=await(0,d4.verifyJwtSignature)(e,t.ownerJwks);if(!r.ok)return r;if(r.header.typ!==Gt.RUNTIME_DELEGATION_TYP)return{ok:!1,reason:"delegation_typ_mismatch"};let n=r.claims;if(!CS(n,n.v===G.RUNTIME_DELEGATION_LEGACY_VERSION?_re:iGe))return{ok:!1,reason:"delegation_shape_invalid"};let i=t.ownerJwks.keys.find(a=>a.kid===t.expectedRootKid);if(r.header.kid!==t.expectedRootKid||!i||(0,my.computeJkt)(i)!==t.expectedRootJkt)return{ok:!1,reason:"root_key_mismatch"};let o=hy(n);if(o===null||t.requiredCustody!==void 0&&o.custody!==t.requiredCustody||n.iss!==t.expectedRootJkt||n.sub!==t.expectedAgentId||n.jti!==t.expectedDelegationId||n.runtimeId!==t.expectedRuntimeId||n.runtimeJkt!==t.expectedRuntimeJkt||n.leaseIssuerJkt!==t.expectedLeaseIssuerJkt||n.purpose!==G.RUNTIME_LEASE_PURPOSE||n.network!==t.expectedNetwork.toLowerCase()||!Ms.test(n.jti??"")||!Ms.test(n.runtimeId??"")||!vn(n.iss)||!vn(n.runtimeJkt)||!vn(n.leaseIssuerJkt)||new Set([n.iss,n.runtimeJkt,n.leaseIssuerJkt]).size!==3||!l4.test(n.network??"")||!pre(n.signingModes)||!Number.isSafeInteger(n.maxLeaseTtlSeconds)||n.maxLeaseTtlSeconds<=0||n.maxLeaseTtlSeconds>Gt.RUNTIME_LEASE_MAX_TTL_SECONDS)return{ok:!1,reason:"delegation_claims_mismatch"};let s=m4(n,t.nowSec,Gt.RUNTIME_DELEGATION_MAX_TTL_SECONDS);return s?{ok:!1,reason:`delegation_${s}`}:{ok:!0,delegation:n}}async function sGe(e,t,r){if(!Number.isSafeInteger(r.nowSec)||r.nowSec<0||r.nowSec>Number.MAX_SAFE_INTEGER-Gt.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS||!Number.isSafeInteger(r.expectedGeneration)||r.expectedGeneration<1||!Number.isSafeInteger(r.expectedGrantVersion)||r.expectedGrantVersion<1||!Od.test(r.expectedRootKid)||!Od.test(r.expectedLeaseIssuerKid))return{ok:!1,reason:"bad_verification_context"};let n;try{n=RS(r.allowedSigningModes)}catch{return{ok:!1,reason:"bad_verification_context"}}if(!n.includes(r.requiredSigningMode))return{ok:!1,reason:"current_policy_denied"};let i=await yy(e,r);if(!i.ok)return i;let o=i.delegation;if(!p4(t))return{ok:!1,reason:"lease_header_invalid"};if(!f4(t))return{ok:!1,reason:"lease_shape_invalid"};let s=await(0,d4.verifyJwtSignature)(t,r.issuerJwks);if(!s.ok)return s;if(s.header.typ!==G.RUNTIME_LEASE_TYP)return{ok:!1,reason:"lease_typ_mismatch"};let a=s.claims;if(!CS(a,bre))return{ok:!1,reason:"lease_shape_invalid"};let c=r.issuerJwks.keys.find(d=>d.kid===r.expectedLeaseIssuerKid);if(s.header.kid!==r.expectedLeaseIssuerKid||!c||(0,my.computeJkt)(c)!==r.expectedLeaseIssuerJkt)return{ok:!1,reason:"lease_issuer_mismatch"};if(a.v!==G.RUNTIME_LEASE_VERSION||a.iss!==r.expectedLeaseIssuerJkt||a.sub!==r.expectedAgentId||a.aud!==G.RUNTIME_LEASE_AUDIENCE||a.delegationId!==r.expectedDelegationId||a.delegationHash!==NS(e)||a.rootJkt!==r.expectedRootJkt||a.runtimeId!==r.expectedRuntimeId||a.runtimeJkt!==r.expectedRuntimeJkt||a.purpose!==G.RUNTIME_LEASE_PURPOSE||a.network!==r.expectedNetwork.toLowerCase()||a.generation!==r.expectedGeneration||a.grantId!==r.expectedGrantId||a.grantVersion!==r.expectedGrantVersion||!Ms.test(a.jti??"")||!Ms.test(a.delegationId??"")||!vn(a.delegationHash)||!Ms.test(a.runtimeId??"")||!Ms.test(a.grantId??"")||!vn(a.iss)||!vn(a.rootJkt)||!vn(a.runtimeJkt)||new Set([a.iss,a.rootJkt,a.runtimeJkt]).size!==3||!l4.test(a.network??"")||!pre(a.signingModes)||!Number.isSafeInteger(a.generation)||a.generation<1||!Number.isSafeInteger(a.grantVersion)||a.grantVersion<1)return{ok:!1,reason:"lease_claims_mismatch"};let u=m4(a,r.nowSec,Math.min(o.maxLeaseTtlSeconds,Gt.RUNTIME_LEASE_MAX_TTL_SECONDS));return u?{ok:!1,reason:`lease_${u}`}:a.iat<o.iat||a.exp>o.exp||!a.signingModes.every(d=>o.signingModes.includes(d))||!a.signingModes.every(d=>n.includes(d))||!o.signingModes.includes(r.requiredSigningMode)||!a.signingModes.includes(r.requiredSigningMode)?{ok:!1,reason:"lease_scope_exceeded"}:{ok:!0,delegation:o,lease:a}}async function aGe(e,t,r){if(!Number.isSafeInteger(r.nowSec)||r.nowSec<0||r.nowSec>Number.MAX_SAFE_INTEGER-Gt.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS||!Number.isSafeInteger(r.expectedGeneration)||r.expectedGeneration<1||!Number.isSafeInteger(r.expectedGrantVersion)||r.expectedGrantVersion<1||!Od.test(r.expectedRootKid)||!Od.test(r.expectedLeaseIssuerKid))return{ok:!1,reason:"bad_verification_context"};let n=await yy(e,{...r,requiredCustody:"device"});if(!n.ok)return n;let i=n.delegation;if(!hy(i)?.tempo)return{ok:!1,reason:"delegation_scope_refused"};if(!p4(t))return{ok:!1,reason:"lease_header_invalid"};if(!f4(t))return{ok:!1,reason:"lease_shape_invalid"};let o=await(0,d4.verifyJwtSignature)(t,r.issuerJwks);if(!o.ok)return o;if(o.header.typ!==G.RUNTIME_LEASE_TYP)return{ok:!1,reason:"lease_typ_mismatch"};let s=o.claims;if(!CS(s,bre))return{ok:!1,reason:"lease_shape_invalid"};let a=r.issuerJwks.keys.find(u=>u.kid===r.expectedLeaseIssuerKid);if(o.header.kid!==r.expectedLeaseIssuerKid||!a||(0,my.computeJkt)(a)!==r.expectedLeaseIssuerJkt)return{ok:!1,reason:"lease_issuer_mismatch"};if(s.v!==G.RUNTIME_LEASE_VERSION||s.iss!==r.expectedLeaseIssuerJkt||s.sub!==r.expectedAgentId||s.aud!==G.RUNTIME_LEASE_AUDIENCE||s.delegationId!==r.expectedDelegationId||s.delegationHash!==NS(e)||s.rootJkt!==r.expectedRootJkt||s.runtimeId!==r.expectedRuntimeId||s.runtimeJkt!==r.expectedRuntimeJkt||s.purpose!==G.TEMPO_LEASE_PURPOSE||s.network!==G.TEMPO_LEASE_NETWORK||s.generation!==r.expectedGeneration||s.grantId!==r.expectedGrantId||s.grantVersion!==r.expectedGrantVersion||!Array.isArray(s.signingModes)||s.signingModes.length!==1||s.signingModes[0]!==G.TEMPO_LEASE_SIGNING_MODE||!Ms.test(s.jti??"")||!Ms.test(s.grantId??""))return{ok:!1,reason:"lease_claims_mismatch"};let c=m4(s,r.nowSec,Math.min(i.maxLeaseTtlSeconds,Gt.RUNTIME_LEASE_MAX_TTL_SECONDS));return c?{ok:!1,reason:`lease_${c}`}:s.iat<i.iat||s.exp>i.exp?{ok:!1,reason:"lease_scope_exceeded"}:{ok:!0,delegation:i,lease:s}}});var h4=g(hi=>{"use strict";Object.defineProperty(hi,"__esModule",{value:!0});hi.RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS=hi.RUNTIME_LEASE_REQUEST_AUDIENCE=hi.RUNTIME_LEASE_REQUEST_VERSION=void 0;hi.runtimeLeaseRequestIntentHash=wre;hi.createRuntimeLeaseRequestProofWithSigner=hGe;var cGe=fm(),uGe=Ed(),dGe=dS(),lGe=xd(),fGe=vd();Object.defineProperty(hi,"RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS",{enumerable:!0,get:function(){return fGe.RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS}});hi.RUNTIME_LEASE_REQUEST_VERSION=1;hi.RUNTIME_LEASE_REQUEST_AUDIENCE="visa-runtime-lease-requests:v1";var pGe=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,mGe=new Set(lGe.RUNTIME_LEASE_SIGNING_MODES);function g4(e,t){if(!pGe.test(t))throw new Error(`${e} must be a canonical UUID`)}function gGe(e){if(g4("agentId",e.agentId),g4("runtimeId",e.runtimeId),g4("requestId",e.requestId),!mGe.has(e.signingMode))throw new Error("runtime lease request signingMode is unsupported");return{v:hi.RUNTIME_LEASE_REQUEST_VERSION,agentId:e.agentId,runtimeId:e.runtimeId,requestId:e.requestId,signingMode:e.signingMode}}function wre(e){return(0,uGe.bytesToBase64Url)((0,cGe.sha256)(new TextEncoder().encode(JSON.stringify(gGe(e)))))}function hGe(e,t){if(!Number.isSafeInteger(t.nowSec)||t.nowSec<0)throw new Error("runtime lease request nowSec must be a non-negative safe integer");return(0,dGe.createPopProofWithSigner)(e,{nonce:t.requestId,audience:hi.RUNTIME_LEASE_REQUEST_AUDIENCE,nowSec:t.nowSec,intentHash:wre(t)})}});var Sre=g(qs=>{"use strict";var yGe=qs&&qs.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),_Ge=qs&&qs.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&yGe(t,e,r)};Object.defineProperty(qs,"__esModule",{value:!0});qs.createRuntimeLeaseRequestProof=EGe;qs.verifyRuntimeLeaseRequestProof=wGe;var vre=wd();_Ge(h4(),qs);var _p=h4(),bGe=/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;function EGe(e,t){if(!Number.isSafeInteger(t.nowSec)||t.nowSec<0)throw new Error("runtime lease request nowSec must be a non-negative safe integer");return"createLeaseProof"in e&&e.createLeaseProof?((0,_p.runtimeLeaseRequestIntentHash)(t),e.createLeaseProof(t)):(0,vre.createAgentOperationPopProof)(e,{operationId:t.requestId,audience:_p.RUNTIME_LEASE_REQUEST_AUDIENCE,nowSec:t.nowSec,intentHash:(0,_p.runtimeLeaseRequestIntentHash)(t)})}async function wGe(e,t){if(!bGe.test(t.expectedRuntimeJkt))return{ok:!1,reason:"runtime_jkt_invalid"};if(!Number.isSafeInteger(t.nowSec)||t.nowSec<0)return{ok:!1,reason:"verification_time_invalid"};let r;try{r=(0,_p.runtimeLeaseRequestIntentHash)(t)}catch{return{ok:!1,reason:"request_invalid"}}let n=await(0,vre.verifyAgentOperationPopProof)(e,{operationId:t.requestId,audience:_p.RUNTIME_LEASE_REQUEST_AUDIENCE,nowSec:t.nowSec,expectedIntentHash:r,maxAgeSec:_p.RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS});return n.ok?n.runtimeCertificate!==void 0?{ok:!1,reason:"unexpected_runtime_certificate"}:n.jkt!==t.expectedRuntimeJkt?{ok:!1,reason:"runtime_jkt_mismatch"}:{ok:!0,runtimeJkt:n.jkt,requestId:t.requestId}:n}});var Pre=g(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});Rd.TAP_RUNTIME_SIGNATURE_DOMAIN=void 0;Rd.tapRuntimeSigningMessage=Ire;Rd.verifyTapRuntimeSignature=AGe;var Are=require("node:crypto"),vGe=c4();Rd.TAP_RUNTIME_SIGNATURE_DOMAIN="visa:tap:runtime-signature:v1";function Ire(e){if(!(e instanceof Uint8Array))throw new Error("TAP message must be bytes");let t=Buffer.from(Rd.TAP_RUNTIME_SIGNATURE_DOMAIN,"utf8"),r=Buffer.alloc(8);return r.writeBigUInt64BE(BigInt(e.byteLength)),Buffer.concat([t,Buffer.from([0]),r,Buffer.from(e)])}function SGe(e){if(typeof e!="string"||e.length!==86)return null;try{let t=Buffer.from(e,"base64url");return t.length!==64||t.toString("base64url")!==e?null:t}catch{return null}}async function AGe(e){if(!(e.message instanceof Uint8Array))return{ok:!1,reason:"malformed_message"};let t=SGe(e.signature);if(!t)return{ok:!1,reason:"malformed_signature"};let r=await(0,vGe.verifyRuntimeCertificate)(e.runtimeCertificate,{jwks:e.rootJwks,expectedAgentId:e.expectedAgentId,expectedRootJkt:e.expectedRootJkt,expectedRuntimeId:e.expectedRuntimeId,expectedRuntimeJkt:e.expectedRuntimeJkt,requiredPurpose:"tap",nowSec:e.nowSec});if(!r.ok)return{ok:!1,reason:`certificate_${r.reason}`};if(r.claims.purposes.length!==1||r.claims.purposes[0]!=="tap")return{ok:!1,reason:"certificate_purpose_not_singleton"};if(e.revokedCertificateIds?.has(r.claims.jti))return{ok:!1,reason:"certificate_revoked"};let n=!1;try{let i=(0,Are.createPublicKey)({key:r.claims.cnf.jwk,format:"jwk"});n=(0,Are.verify)(null,Ire(e.message),i,t)}catch{return{ok:!1,reason:"runtime_key_invalid"}}return n?{ok:!0,claims:r.claims,agentId:r.claims.sub,rootJkt:r.rootJkt,runtimeId:r.claims.runtimeId,runtimeJkt:r.runtimeJkt}:{ok:!1,reason:"invalid_signature"}}});var Dre=g(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.WALLET_BINDING_MAX_TTL_SECONDS=We.WALLET_BINDING_DERIVATION_VERSION=We.WALLET_BINDING_SIGNER_KIND=We.WALLET_BINDING_VERSION=We.WALLET_BINDING_TYP=void 0;We.prepareWalletBinding=Mre;We.completeWalletBinding=qre;We.issueWalletBinding=OGe;We.verifyWalletBinding=RGe;var IGe=require("node:crypto"),_4=_S(),xre=Br(),Tre=Un(),Ore=Ic(),PGe=xd();Object.defineProperty(We,"WALLET_BINDING_TYP",{enumerable:!0,get:function(){return PGe.WALLET_BINDING_TYP}});var Rre=xd();We.WALLET_BINDING_VERSION=2;We.WALLET_BINDING_SIGNER_KIND="turnkey_tvc_p256";We.WALLET_BINDING_DERIVATION_VERSION="visa-tvc-slipgate-v2";We.WALLET_BINDING_MAX_TTL_SECONDS=366*24*60*60;var b4=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,TGe=/^[A-Za-z0-9_-]{43}$/,Cre=/^0x[0-9a-f]{40}$/,Nre=/^eip155:[1-9][0-9]{0,15}$/,kre=/^(02|03)[0-9a-f]{64}$/;function jre(e){if(typeof e!="string"||!TGe.test(e))return!1;let t=Buffer.from(e,"base64url");return t.length===32&&t.toString("base64url")===e}function y4(e,t){if(!(0,_4.isCanonicalOpaqueId)(t))throw new Error(`${e} must be a bounded opaque identifier`)}function xGe(e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative unix-seconds integer`)}function Mre(e){let t=e.nowSec??Math.floor(Date.now()/1e3),r=e.ttlSeconds??We.WALLET_BINDING_MAX_TTL_SECONDS,n=e.bindingId??(0,IGe.randomUUID)();if(xGe("nowSec",t),!Number.isSafeInteger(r)||r<=0||r>We.WALLET_BINDING_MAX_TTL_SECONDS)throw new Error(`wallet binding ttlSeconds must be in (0, ${We.WALLET_BINDING_MAX_TTL_SECONDS}]`);if(!b4.test(e.agentId)||!b4.test(n))throw new Error("wallet binding agentId/bindingId must be canonical UUIDs");if(!jre(e.rootJkt)||(0,xre.computeJkt)(e.rootPublicJwk)!==e.rootJkt)throw new Error("wallet binding root public key does not match rootJkt");y4("rootKid",e.rootKid),y4("subOrganizationId",e.subOrganizationId),y4("walletId",e.walletId);let i=e.walletAddress.toLowerCase(),o=e.network.toLowerCase(),s=e.executor.publicKey.toLowerCase();if(!Cre.test(i))throw new Error("wallet binding address is invalid");if(!Nre.test(o))throw new Error("wallet binding network is invalid");if(e.executor.kind!==We.WALLET_BINDING_SIGNER_KIND||e.executor.derivationVersion!==We.WALLET_BINDING_DERIVATION_VERSION||!kre.test(s))throw new Error("wallet binding signer descriptor is unsupported or invalid");let a={v:We.WALLET_BINDING_VERSION,iss:e.rootJkt,sub:e.agentId,jti:n,subOrganizationId:e.subOrganizationId,walletId:e.walletId,walletAddress:i,network:o,executor:{kind:We.WALLET_BINDING_SIGNER_KIND,publicKey:s,derivationVersion:We.WALLET_BINDING_DERIVATION_VERSION},iat:t,nbf:t,exp:t+r};return{...(0,Ore.prepareRootSignedJws)(Rre.WALLET_BINDING_TYP,e.rootKid,a),claims:a}}function qre(e,t){return(0,Ore.completeRootSignedJws)(e.signingInput,t,"wallet binding")}async function OGe(e){let t=Mre({...e,rootKid:e.signer.kid,rootPublicJwk:e.signer.publicJwk});return qre(t,await e.signer.sign(new TextEncoder().encode(t.signingInput)))}async function RGe(e,t){if(!Number.isSafeInteger(t.nowSec)||t.nowSec<0)return{ok:!1,reason:"bad_verification_time"};let r=await(0,Tre.verifyJwtSignature)(e,t.jwks);if(!r.ok)return r;if(r.header.typ!==Rre.WALLET_BINDING_TYP)return{ok:!1,reason:"typ_mismatch"};let n=r.claims,i=t.expectedWalletAddress.toLowerCase(),o=t.expectedNetwork.toLowerCase(),s=t.expectedExecutor;if(n.v!==We.WALLET_BINDING_VERSION||n.iss!==t.expectedRootJkt||n.sub!==t.expectedAgentId||typeof n.jti!="string"||!b4.test(n.jti)||n.subOrganizationId!==t.expectedSubOrganizationId||n.walletId!==t.expectedWalletId||n.walletAddress!==i||n.network!==o||typeof n.executor!="object"||n.executor===null||n.executor.kind!==We.WALLET_BINDING_SIGNER_KIND||typeof n.executor.publicKey!="string"||!kre.test(n.executor.publicKey)||n.executor.derivationVersion!==We.WALLET_BINDING_DERIVATION_VERSION||s!==void 0&&(n.executor.kind!==s.kind||n.executor.publicKey!==s.publicKey.toLowerCase()||n.executor.derivationVersion!==s.derivationVersion))return{ok:!1,reason:"claims_mismatch"};if(!(0,_4.isCanonicalOpaqueId)(n.subOrganizationId)||!(0,_4.isCanonicalOpaqueId)(n.walletId))return{ok:!1,reason:"identifier_invalid"};if(!jre(n.iss)||!Cre.test(n.walletAddress))return{ok:!1,reason:"binding_invalid"};if(!Nre.test(n.network)||r.header.kid===void 0)return{ok:!1,reason:"binding_invalid"};let a=t.jwks.keys.find(u=>u.kid===r.header.kid);if(!a||(0,xre.computeJkt)(a)!==t.expectedRootJkt)return{ok:!1,reason:"root_key_mismatch"};let c=(0,Tre.temporalReason)(n,t.nowSec);return c?{ok:!1,reason:c}:typeof n.iat!="number"||typeof n.nbf!="number"||typeof n.exp!="number"||!Number.isSafeInteger(n.iat)||!Number.isSafeInteger(n.nbf)||!Number.isSafeInteger(n.exp)||n.nbf!==n.iat||n.nbf>t.nowSec||n.exp-n.iat>We.WALLET_BINDING_MAX_TTL_SECONDS?{ok:!1,reason:"ttl_exceeded"}:{ok:!0,claims:n}}});var Lre=g(bp=>{"use strict";Object.defineProperty(bp,"__esModule",{value:!0});bp.INTENT_HASH_VERSION=void 0;bp.canonicalIntentHash=jGe;var CGe=require("node:crypto"),NGe=new Set(["USD","EUR","GBP","CAD","AUD","JPY","CHF","CNY","HKD","SGD","INR","MXN","BRL","NZD","SEK","NOK","DKK","ZAR","AED"]);bp.INTENT_HASH_VERSION=1;var kGe=/^[A-Za-z0-9_-]{1,128}$/;function jGe(e){let{amount:t,currency:r,payee:n,intentId:i,settlementHash:o}=e;if(!Number.isSafeInteger(t)||t<=0)throw new Error(`intent.amount must be a positive safe integer in minor units (cents); got ${String(t)}`);let s=typeof r=="string"?r.toUpperCase():"";if(!NGe.has(s))throw new Error(`intent.currency must be a supported ISO 4217 code; got ${JSON.stringify(r)}`);if(typeof n!="string"||n.length===0)throw new Error("intent.payee must be a non-empty string");if(i!==void 0&&(typeof i!="string"||i.length===0))throw new Error("intent.intentId, when present, must be a non-empty string");if(o!==void 0&&!kGe.test(o))throw new Error("intent.settlementHash, when present, must be a base64url token (1-128 chars)");let a=JSON.stringify({v:bp.INTENT_HASH_VERSION,amount:t,currency:s,payee:n,intentId:i??null,settlementHash:o??null});return(0,CGe.createHash)("sha256").update(a,"utf8").digest().toString("base64url")}});var Hre=g(br=>{"use strict";Object.defineProperty(br,"__esModule",{value:!0});br.KillList=br.KILL_SWITCH_JWT_TYP=br.SUCCESSION_JWT_TYP=void 0;br.issueSuccession=qGe;br.verifySuccession=DGe;br.issueKillSwitch=LGe;br.verifyKillSwitch=BGe;br.attestationIsVoid=Ure;var MGe=Br(),jS=Un();br.SUCCESSION_JWT_TYP="agent-succession+jwt";br.KILL_SWITCH_JWT_TYP="agent-kill+jwt";async function qGe(e){let{principalKey:t,oldJkt:r,newJkt:n,agtId:i,nowSec:o=Math.floor(Date.now()/1e3)}=e,s={old_jkt:r,new_jkt:n,agt_id:i,iat:o};return(0,jS.signJwt)(t.privateJwk,{kid:t.kid,typ:br.SUCCESSION_JWT_TYP},{...s})}function Bre(e,t,r){let n=t.keys.find(i=>i.kid===e);return!n||(0,MGe.computeJkt)(n)!==r?"signer_not_owning_principal":null}async function DGe(e,t){let r=await(0,jS.verifyJwtSignature)(e,t.principalJwks);if(!r.ok)return{valid:!1,reason:r.reason};if(r.header.typ!==br.SUCCESSION_JWT_TYP)return{valid:!1,reason:"typ_mismatch"};let n=r.claims;if(typeof n.old_jkt!="string"||typeof n.new_jkt!="string"||typeof n.agt_id!="string"||typeof n.iat!="number")return{valid:!1,reason:"bad_claim_shape"};if(n.old_jkt===n.new_jkt)return{valid:!1,reason:"no_op_succession"};if(n.old_jkt!==t.registration.sub)return{valid:!1,reason:"agent_jkt_mismatch"};let i=Bre(r.header.kid,t.principalJwks,t.owningPrincipalJkt);return i?{valid:!1,reason:i}:{valid:!0,record:n}}async function LGe(e){let{principalKey:t,agentJkt:r,agtId:n,reason:i,nowSec:o=Math.floor(Date.now()/1e3)}=e,s={jkt:r,agt_id:n,iat:o,...i===void 0?{}:{reason:i}};return(0,jS.signJwt)(t.privateJwk,{kid:t.kid,typ:br.KILL_SWITCH_JWT_TYP},{...s})}async function BGe(e,t){let r=await(0,jS.verifyJwtSignature)(e,t.principalJwks);if(!r.ok)return{valid:!1,reason:r.reason};if(r.header.typ!==br.KILL_SWITCH_JWT_TYP)return{valid:!1,reason:"typ_mismatch"};let n=r.claims;if(typeof n.jkt!="string"||typeof n.agt_id!="string"||typeof n.iat!="number")return{valid:!1,reason:"bad_claim_shape"};if(n.jkt!==t.registration.sub)return{valid:!1,reason:"agent_jkt_mismatch"};let i=Bre(r.header.kid,t.principalJwks,t.owningPrincipalJkt);return i?{valid:!1,reason:i}:{valid:!0,record:n}}function Ure(e,t){return t.jkt===e.signerJkt&&e.signedAtSec>=t.iat}var E4=class{byJkt;constructor(t=[]){this.byJkt=new Map;for(let r of t){let n=this.byJkt.get(r.jkt);(!n||r.iat<n.iat)&&this.byJkt.set(r.jkt,r)}}get size(){return this.byJkt.size}isKilled(t,r){let n=this.byJkt.get(t);return n&&n.iat<=r?{killed:!0,...n.reason!==void 0?{reason:n.reason}:{},killedAtSec:n.iat}:{killed:!1}}voidsAttestation(t,r){let n=this.byJkt.get(t);return n?Ure({signerJkt:t,signedAtSec:r},n):!1}};br.KillList=E4});var $re=g(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.AGENT_PAIRING_TERMINAL_STATES=H.AGENT_PAIRING_STATES=H.AGENT_PAIRING_TTL_SECONDS=H.sha256=H.pairingInstrumentCommitment=H.pairingDeliveryArtifactV2Hash=H.canonicalPairingDeliveryArtifactV2=H.pairingArtifactHash=H.agentMailCredentialClaimMessageV2=H.keyRotationClaimHashV2=H.keyRotationClaimMessageV2=H.handoffAuthorityCapabilities=H.AGENT_HANDOFF_COMPOUND_AUTHORITY=H.AGENT_HANDOFF_AUTHORITIES=H.AGENT_CAPABILITY_ATTACH_CAPABILITIES=H.pairingActivationMessageV2=H.pairingActivationMessage=H.pairingClaimHashV2=H.pairingClaimMessageV2=H.pairingClaimMessage=H.pairingTermsV2Hash=H.pairingTermsHash=H.canonicalPairingTermsV2=H.canonicalPairingTerms=H.pairingConfirmationCode=H.pairingCodeFromClaimToken=H.pairingClaimTokenHash=H.randomPairingClaimToken=H.pairingCodeHash=H.isValidPairingCode=H.formatPairingCode=H.normalizePairingCode=H.randomPairingCode=H.pairingVerifierChallenge=H.randomPairingVerifier=H.randomPairingId=H.AGENT_PAIRING_CODE_LENGTH=H.AGENT_PAIRING_CODE_ALPHABET=H.AGENT_PAIRING_PROTOCOL_VERSION_V2=H.AGENT_PAIRING_PROTOCOL_VERSION=void 0;H.isAgentPairingState=FGe;H.canTransitionAgentPairing=Fre;H.assertAgentPairingTransition=$Ge;var Pe=D0();Object.defineProperty(H,"AGENT_PAIRING_PROTOCOL_VERSION",{enumerable:!0,get:function(){return Pe.AGENT_PAIRING_PROTOCOL_VERSION}});Object.defineProperty(H,"AGENT_PAIRING_PROTOCOL_VERSION_V2",{enumerable:!0,get:function(){return Pe.AGENT_PAIRING_PROTOCOL_VERSION_V2}});Object.defineProperty(H,"AGENT_PAIRING_CODE_ALPHABET",{enumerable:!0,get:function(){return Pe.AGENT_PAIRING_CODE_ALPHABET}});Object.defineProperty(H,"AGENT_PAIRING_CODE_LENGTH",{enumerable:!0,get:function(){return Pe.AGENT_PAIRING_CODE_LENGTH}});Object.defineProperty(H,"randomPairingId",{enumerable:!0,get:function(){return Pe.randomPairingId}});Object.defineProperty(H,"randomPairingVerifier",{enumerable:!0,get:function(){return Pe.randomPairingVerifier}});Object.defineProperty(H,"pairingVerifierChallenge",{enumerable:!0,get:function(){return Pe.pairingVerifierChallenge}});Object.defineProperty(H,"randomPairingCode",{enumerable:!0,get:function(){return Pe.randomPairingCode}});Object.defineProperty(H,"normalizePairingCode",{enumerable:!0,get:function(){return Pe.normalizePairingCode}});Object.defineProperty(H,"formatPairingCode",{enumerable:!0,get:function(){return Pe.formatPairingCode}});Object.defineProperty(H,"isValidPairingCode",{enumerable:!0,get:function(){return Pe.isValidPairingCode}});Object.defineProperty(H,"pairingCodeHash",{enumerable:!0,get:function(){return Pe.pairingCodeHash}});Object.defineProperty(H,"randomPairingClaimToken",{enumerable:!0,get:function(){return Pe.randomPairingClaimToken}});Object.defineProperty(H,"pairingClaimTokenHash",{enumerable:!0,get:function(){return Pe.pairingClaimTokenHash}});Object.defineProperty(H,"pairingCodeFromClaimToken",{enumerable:!0,get:function(){return Pe.pairingCodeFromClaimToken}});Object.defineProperty(H,"pairingConfirmationCode",{enumerable:!0,get:function(){return Pe.pairingConfirmationCode}});Object.defineProperty(H,"canonicalPairingTerms",{enumerable:!0,get:function(){return Pe.canonicalPairingTerms}});Object.defineProperty(H,"canonicalPairingTermsV2",{enumerable:!0,get:function(){return Pe.canonicalPairingTermsV2}});Object.defineProperty(H,"pairingTermsHash",{enumerable:!0,get:function(){return Pe.pairingTermsHash}});Object.defineProperty(H,"pairingTermsV2Hash",{enumerable:!0,get:function(){return Pe.pairingTermsV2Hash}});Object.defineProperty(H,"pairingClaimMessage",{enumerable:!0,get:function(){return Pe.pairingClaimMessage}});Object.defineProperty(H,"pairingClaimMessageV2",{enumerable:!0,get:function(){return Pe.pairingClaimMessageV2}});Object.defineProperty(H,"pairingClaimHashV2",{enumerable:!0,get:function(){return Pe.pairingClaimHashV2}});Object.defineProperty(H,"pairingActivationMessage",{enumerable:!0,get:function(){return Pe.pairingActivationMessage}});Object.defineProperty(H,"pairingActivationMessageV2",{enumerable:!0,get:function(){return Pe.pairingActivationMessageV2}});Object.defineProperty(H,"AGENT_CAPABILITY_ATTACH_CAPABILITIES",{enumerable:!0,get:function(){return Pe.AGENT_CAPABILITY_ATTACH_CAPABILITIES}});Object.defineProperty(H,"AGENT_HANDOFF_AUTHORITIES",{enumerable:!0,get:function(){return Pe.AGENT_HANDOFF_AUTHORITIES}});Object.defineProperty(H,"AGENT_HANDOFF_COMPOUND_AUTHORITY",{enumerable:!0,get:function(){return Pe.AGENT_HANDOFF_COMPOUND_AUTHORITY}});Object.defineProperty(H,"handoffAuthorityCapabilities",{enumerable:!0,get:function(){return Pe.handoffAuthorityCapabilities}});Object.defineProperty(H,"keyRotationClaimMessageV2",{enumerable:!0,get:function(){return Pe.keyRotationClaimMessageV2}});Object.defineProperty(H,"keyRotationClaimHashV2",{enumerable:!0,get:function(){return Pe.keyRotationClaimHashV2}});Object.defineProperty(H,"agentMailCredentialClaimMessageV2",{enumerable:!0,get:function(){return Pe.agentMailCredentialClaimMessageV2}});Object.defineProperty(H,"pairingArtifactHash",{enumerable:!0,get:function(){return Pe.pairingArtifactHash}});Object.defineProperty(H,"canonicalPairingDeliveryArtifactV2",{enumerable:!0,get:function(){return Pe.canonicalPairingDeliveryArtifactV2}});Object.defineProperty(H,"pairingDeliveryArtifactV2Hash",{enumerable:!0,get:function(){return Pe.pairingDeliveryArtifactV2Hash}});Object.defineProperty(H,"pairingInstrumentCommitment",{enumerable:!0,get:function(){return Pe.pairingInstrumentCommitment}});Object.defineProperty(H,"sha256",{enumerable:!0,get:function(){return Pe.pairingSha256}});var UGe=vd();Object.defineProperty(H,"AGENT_PAIRING_TTL_SECONDS",{enumerable:!0,get:function(){return UGe.AGENT_PAIRING_TTL_SECONDS}});H.AGENT_PAIRING_STATES=["awaiting_agent","agent_claimed","code_verified","awaiting_human","authorized","delivered","activated","expired","cancelled","failed","revoked"];H.AGENT_PAIRING_TERMINAL_STATES=new Set(["activated","expired","cancelled","failed","revoked"]);var HGe={awaiting_agent:new Set(["agent_claimed","expired","cancelled","failed"]),agent_claimed:new Set(["code_verified","expired","cancelled","failed"]),code_verified:new Set(["awaiting_human","expired","cancelled","failed"]),awaiting_human:new Set(["authorized","expired","cancelled","failed"]),authorized:new Set(["delivered","expired","cancelled","failed"]),delivered:new Set(["activated","expired","cancelled","failed"]),activated:new Set(["revoked"]),expired:new Set,cancelled:new Set,failed:new Set,revoked:new Set};function FGe(e){return typeof e=="string"&&H.AGENT_PAIRING_STATES.includes(e)}function Fre(e,t){return HGe[e].has(t)}function $Ge(e,t){if(!Fre(e,t))throw new Error(`invalid agent pairing transition: ${e} -> ${t}`)}});var Jre=g(w4=>{"use strict";Object.defineProperty(w4,"__esModule",{value:!0});w4.prepareIdentityPresenceDelegation=GGe;var JGe=kS(),VGe=Ic();function GGe(e){let{custody:t,rails:r,...n}=(0,JGe.prepareRuntimeDelegation)({...e,signingModes:["eip3009:exact"],custody:"gate"}).claims,i={...n,v:1,purpose:"runtime_presence_pop",signingModes:["presence"]};return{...(0,VGe.prepareRootSignedJws)("visa-agent-runtime-delegation+jwt",e.rootKid,i),claims:i}}});var P4=g(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.HOSTED_CONNECTOR_PROOF_TTL_SECONDS=Ue.HOSTED_CONNECTOR_PROOF_TYP=Ue.IDENTITY_PRESENCE_LEASE_TYP=Ue.IDENTITY_PRESENCE_SIGNING_MODE=Ue.IDENTITY_PRESENCE_PURPOSE=Ue.IDENTITY_PRESENCE_LEASE_AUDIENCE=void 0;Ue.issueHostedConnectorProof=XGe;Ue.verifyHostedConnectorProof=ZGe;Ue.issueIdentityPresenceLease=QGe;Ue.verifyIdentityPresenceLeaseChain=eKe;var Kre=require("node:crypto"),Vre=Fn(),I4=vd();Object.defineProperty(Ue,"HOSTED_CONNECTOR_PROOF_TTL_SECONDS",{enumerable:!0,get:function(){return I4.HOSTED_CONNECTOR_PROOF_TTL_SECONDS}});var v4=Br(),S4=Un(),Wre=fp(),Cd=xd();Ue.IDENTITY_PRESENCE_LEASE_AUDIENCE="urn:visa:tvc:identity-gate";Ue.IDENTITY_PRESENCE_PURPOSE="runtime_presence_pop";Ue.IDENTITY_PRESENCE_SIGNING_MODE="presence";Ue.IDENTITY_PRESENCE_LEASE_TYP="visa-agent-runtime-lease+jwt";Ue.HOSTED_CONNECTOR_PROOF_TYP="visa-hosted-connector-proof+jwt";var Ep=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,MS=/^[A-Za-z0-9_-]{43}$/,KGe=/^eip155:[1-9][0-9]{0,15}$/,WGe="exp,iat,iss,jti,leaseIssuerJkt,maxLeaseTtlSeconds,nbf,network,purpose,runtimeId,runtimeJkt,signingModes,sub,v",zGe="aud,delegationHash,delegationId,exp,generation,grantId,grantVersion,iat,iss,jti,nbf,network,purpose,rootJkt,runtimeId,runtimeJkt,signingModes,sub,v",YGe="agentId,aud,connectorKeyId,custody,exp,grantId,grantVersion,hostedAuthorityMode,iat,intentHash,iss,jti,operationId,requestId,runtimeId,v";function A4(e,t){return Object.keys(e).sort().join(",")===t}function Gre(e,t,r){return Number.isSafeInteger(e.iat)&&Number.isSafeInteger(e.nbf)&&Number.isSafeInteger(e.exp)&&e.iat>=0&&e.nbf===e.iat&&e.exp>e.iat&&e.exp-e.iat<=r&&e.iat<=t+Cd.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS&&t<e.exp}async function XGe(e){let t={v:1,iss:"visa:auth",aud:Ue.IDENTITY_PRESENCE_LEASE_AUDIENCE,jti:e.requestId,requestId:e.requestId,agentId:e.agentId,runtimeId:e.runtimeId,custody:"signer",hostedAuthorityMode:"standing",connectorKeyId:e.connectorKeyId,grantId:e.grantId,grantVersion:e.grantVersion,operationId:e.operationId,intentHash:e.intentHash,iat:e.issuedAtSec,exp:e.issuedAtSec+I4.HOSTED_CONNECTOR_PROOF_TTL_SECONDS};if(!zre(t))throw new Error("hosted_connector_proof_invalid");return(0,Wre.signJwtWithSigner)(e.signer,{typ:Ue.HOSTED_CONNECTOR_PROOF_TYP},{...t})}function zre(e){return A4(e,YGe)&&e.v===1&&e.iss==="visa:auth"&&e.aud===Ue.IDENTITY_PRESENCE_LEASE_AUDIENCE&&e.jti===e.requestId&&[e.jti,e.requestId,e.agentId,e.runtimeId,e.grantId,e.operationId].every(t=>Ep.test(t))&&e.custody==="signer"&&e.hostedAuthorityMode==="standing"&&typeof e.connectorKeyId=="string"&&/^[A-Za-z0-9._:@/-]{1,256}$/.test(e.connectorKeyId)&&MS.test(e.intentHash)&&Number.isSafeInteger(e.grantVersion)&&e.grantVersion>0&&Number.isSafeInteger(e.iat)&&e.iat>=0&&Number.isSafeInteger(e.exp)&&e.exp>e.iat&&e.exp-e.iat<=I4.HOSTED_CONNECTOR_PROOF_TTL_SECONDS}async function ZGe(e,t){let r=await(0,S4.verifyJwtSignature)(e,t.issuerJwks);if(!r.ok)return r;let n=r.claims,i=t.issuerJwks.keys.filter(s=>typeof s.kid=="string"&&s.kid===r.header.kid),o=t.maxAgeSeconds??30;return r.header.typ!==Ue.HOSTED_CONNECTOR_PROOF_TYP||i.length!==1||(0,v4.computeJkt)(i[0])!==r.header.kid||!zre(n)||!Number.isSafeInteger(t.nowSec)||!Number.isSafeInteger(o)||o<1||n.iat>t.nowSec+Cd.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS||t.nowSec-n.iat>o||n.exp<=t.nowSec||n.requestId!==t.expectedRequestId||n.agentId!==t.expectedAgentId||n.runtimeId!==t.expectedRuntimeId||n.connectorKeyId!==t.expectedConnectorKeyId||n.grantId!==t.expectedGrantId||n.grantVersion!==t.expectedGrantVersion||n.operationId!==t.expectedOperationId||t.expectedIntentHash!==void 0&&n.intentHash!==t.expectedIntentHash?{ok:!1,reason:"hosted_connector_proof_invalid"}:{ok:!0,claims:n}}async function QGe(e){if(!Ep.test(e.leaseId)||!Ep.test(e.grantId)||!Number.isSafeInteger(e.generation)||e.generation<1||!Number.isSafeInteger(e.grantVersion)||e.grantVersion<1||!Number.isSafeInteger(e.ttlSeconds)||e.ttlSeconds<1||e.ttlSeconds>Cd.RUNTIME_LEASE_MAX_TTL_SECONDS||e.ttlSeconds>e.delegation.maxLeaseTtlSeconds||e.delegation.leaseIssuerJkt!==e.signer.kid)throw new Error("identity presence lease input invalid");let t={v:1,iss:e.signer.kid,sub:e.delegation.sub,aud:Ue.IDENTITY_PRESENCE_LEASE_AUDIENCE,jti:e.leaseId,delegationId:e.delegation.jti,delegationHash:(0,Kre.createHash)("sha256").update(e.delegationToken).digest("base64url"),rootJkt:e.delegation.iss,runtimeId:e.delegation.runtimeId,runtimeJkt:e.delegation.runtimeJkt,purpose:Ue.IDENTITY_PRESENCE_PURPOSE,network:e.delegation.network,signingModes:[Ue.IDENTITY_PRESENCE_SIGNING_MODE],generation:e.generation,grantId:e.grantId,grantVersion:e.grantVersion,iat:e.nowSec,nbf:e.nowSec,exp:e.nowSec+e.ttlSeconds};return{lease:await(0,Wre.signJwtWithSigner)(e.signer,{typ:Ue.IDENTITY_PRESENCE_LEASE_TYP},{...t}),claims:t}}async function eKe(e,t,r){if(!Number.isSafeInteger(r.nowSec)||r.nowSec<0)return{ok:!1,reason:"bad_verification_context"};let n=await(0,S4.verifyJwtSignature)(e,r.ownerJwks),i=await(0,S4.verifyJwtSignature)(t,r.issuerJwks);if(!n.ok)return n;if(!i.ok)return i;let o=n.claims,s=i.claims,a=r.ownerJwks.keys.find(u=>u.kid===r.expectedRootKid),c=r.issuerJwks.keys.find(u=>u.kid===r.expectedLeaseIssuerKid);return n.header.typ!==Cd.RUNTIME_DELEGATION_TYP||n.header.kid!==r.expectedRootKid||i.header.typ!==Ue.IDENTITY_PRESENCE_LEASE_TYP||i.header.kid!==r.expectedLeaseIssuerKid||!a||!c||(0,v4.computeJkt)(a)!==r.expectedRootJkt||(0,v4.computeJkt)(c)!==r.expectedLeaseIssuerJkt||!A4(o,WGe)||!A4(s,zGe)||o.v!==1||o.iss!==r.expectedRootJkt||o.sub!==r.expectedAgentId||o.jti!==r.expectedDelegationId||o.runtimeId!==r.expectedRuntimeId||o.runtimeJkt!==r.expectedRuntimeJkt||o.leaseIssuerJkt!==r.expectedLeaseIssuerJkt||o.purpose!==Ue.IDENTITY_PRESENCE_PURPOSE||o.network!==r.expectedNetwork||(0,Vre.canonicalJson)(o.signingModes)!=='["presence"]'||!Ep.test(o.jti)||!Ep.test(o.runtimeId)||!MS.test(o.iss)||!MS.test(o.runtimeJkt)||!MS.test(o.leaseIssuerJkt)||!KGe.test(o.network)||!Number.isSafeInteger(o.maxLeaseTtlSeconds)||o.maxLeaseTtlSeconds<1||o.maxLeaseTtlSeconds>Cd.RUNTIME_LEASE_MAX_TTL_SECONDS||!Gre(o,r.nowSec,Cd.RUNTIME_DELEGATION_MAX_TTL_SECONDS)||s.v!==1||s.iss!==r.expectedLeaseIssuerJkt||s.sub!==r.expectedAgentId||s.aud!==Ue.IDENTITY_PRESENCE_LEASE_AUDIENCE||s.delegationId!==o.jti||s.delegationHash!==(0,Kre.createHash)("sha256").update(e).digest("base64url")||s.rootJkt!==r.expectedRootJkt||s.runtimeId!==r.expectedRuntimeId||s.runtimeJkt!==r.expectedRuntimeJkt||s.purpose!==Ue.IDENTITY_PRESENCE_PURPOSE||s.network!==r.expectedNetwork||(0,Vre.canonicalJson)(s.signingModes)!=='["presence"]'||s.generation!==r.expectedGeneration||s.grantId!==r.expectedGrantId||s.grantVersion!==r.expectedGrantVersion||!Ep.test(s.jti)||!Gre(s,r.nowSec,Cd.RUNTIME_LEASE_MAX_TTL_SECONDS)||s.exp>o.exp||s.exp-s.iat>o.maxLeaseTtlSeconds?{ok:!1,reason:"presence_chain_invalid"}:{ok:!0,delegation:o,lease:s}}});var R4=g(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.IDENTITY_TAP_LEASE_REQUEST_AUDIENCE=Pt.IDENTITY_TAP_LEASE_AUDIENCE=Pt.IDENTITY_TAP_PURPOSE=Pt.IDENTITY_TAP_PROFILE=void 0;Pt.prepareIdentityTapDelegation=ene;Pt.verifyIdentityTapDelegation=tne;Pt.issueIdentityTapLease=oKe;Pt.identityTapLeaseRequestIntentHash=O4;Pt.createIdentityTapLeaseRequestProof=aKe;Pt.verifyIdentityTapLeaseRequestProof=cKe;var Yre=require("node:crypto"),tKe=Fn(),rKe=Br(),Xre=Un(),T4=Ic(),Zre=wd(),nKe=kS();Pt.IDENTITY_TAP_PROFILE="identity-tap-v1";Pt.IDENTITY_TAP_PURPOSE="tap_signature_base";Pt.IDENTITY_TAP_LEASE_AUDIENCE="urn:visa:tvc:identity-gate";Pt.IDENTITY_TAP_LEASE_REQUEST_AUDIENCE="visa-identity-lease-requests:v1";var x4=e=>typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(e),qS=e=>Number.isSafeInteger(e)&&Number(e)>0,Qre=e=>(0,Yre.createHash)("sha256").update(e,"utf8").digest("base64url");function iKe(e){if(typeof e!="string"||Buffer.byteLength(e)>32768)throw new Error("identity_tap_token_invalid");let t=e.split(".");if(t.length!==3||t.some(r=>!r||Buffer.from(r,"base64url").toString("base64url")!==r)||Buffer.from(t[2],"base64url").length!==64)throw new Error("identity_tap_token_invalid");return t}function ene(e){let{custody:t,rails:r,...n}=(0,nKe.prepareRuntimeDelegation)({...e,signingModes:["eip3009:exact"],custody:"gate"}).claims,i={...n,v:1,purpose:Pt.IDENTITY_TAP_PURPOSE,signingModes:["tap"]};return{...(0,T4.prepareRootSignedJws)("visa-agent-runtime-delegation+jwt",e.rootKid,i),claims:i}}async function tne(e,t){let r=iKe(e),n=await(0,Xre.verifyJwtSignature)(e,t.ownerJwks);if(!n.ok)throw new Error("identity_tap_delegation_signature_invalid");let i=n.claims,o=t.ownerJwks.keys.find(a=>a.kid===t.expectedRootKid);if(!o||n.header.kid!==t.expectedRootKid||!Number.isSafeInteger(t.nowSec)||t.nowSec<0||!Number.isSafeInteger(i.iat)||!Number.isSafeInteger(i.exp)||i.iat>t.nowSec+30||i.exp<=t.nowSec)throw new Error("identity_tap_delegation_invalid");let s=ene({rootKid:t.expectedRootKid,rootPublicJwk:o,rootJkt:t.expectedRootJkt,agentId:t.expectedAgentId,runtimeId:t.expectedRuntimeId,runtimeJkt:t.expectedRuntimeJkt,leaseIssuerJkt:t.expectedLeaseIssuerJkt,network:t.expectedNetwork,delegationId:t.expectedDelegationId,nowSec:i.iat,ttlSeconds:i.exp-i.iat,maxLeaseTtlSeconds:i.maxLeaseTtlSeconds});if(r[0]+"."+r[1]!==s.signingInput)throw new Error("identity_tap_delegation_mismatch");return s.claims}async function oKe(e){let t=await tne(e.delegationToken,e.verification),r=e.verification.nowSec,n=e.ttlSeconds??120,i=e.leaseId??(0,Yre.randomUUID)();if(!qS(e.generation)||!qS(e.authorizationVersion)||!x4(e.authorizationId)||!x4(i)||!qS(n)||n>120||!Number.isSafeInteger(e.authorityExpiresAt)||(0,rKe.computeJkt)(e.signer.publicJwk)!==t.leaseIssuerJkt)throw new Error("identity_tap_lease_context_invalid");let o=Math.min(r+n,r+t.maxLeaseTtlSeconds,t.exp,e.authorityExpiresAt);if(!Number.isSafeInteger(o)||o<=r)throw new Error("identity_tap_lease_expired");let s={v:1,iss:t.leaseIssuerJkt,sub:t.sub,aud:Pt.IDENTITY_TAP_LEASE_AUDIENCE,jti:i,delegationId:t.jti,delegationHash:Qre(e.delegationToken),rootJkt:t.iss,runtimeId:t.runtimeId,runtimeJkt:t.runtimeJkt,purpose:Pt.IDENTITY_TAP_PURPOSE,network:t.network,signingModes:["tap"],generation:e.generation,grantId:e.authorizationId,grantVersion:e.authorizationVersion,iat:r,nbf:r,exp:o},a=(0,T4.prepareRootSignedJws)("visa-agent-runtime-lease+jwt",e.signer.kid,s),c=(0,T4.completeRootSignedJws)(a.signingInput,await e.signer.sign(Buffer.from(a.signingInput)),"identity TAP lease");if(!(await(0,Xre.verifyJwtSignature)(c,{keys:[e.signer.publicJwk]})).ok)throw new Error("identity_tap_lease_signer_invalid");return{lease:c,claims:s}}var sKe=["v","profile","associationId","associationVersion","agentId","runtimeId","generation","authorizationId","authorizationVersion","requestId","signingMode"].sort();function O4(e){if(!e||typeof e!="object"||Object.keys(e).sort().join(",")!==sKe.join(",")||e.v!==1||e.profile!==Pt.IDENTITY_TAP_PROFILE||e.signingMode!=="tap"||![e.associationId,e.agentId,e.runtimeId,e.authorizationId,e.requestId].every(x4)||![e.associationVersion,e.generation,e.authorizationVersion].every(qS))throw new Error("identity_tap_lease_request_invalid");return Qre((0,tKe.canonicalJson)(e))}function aKe(e,t,r){return(0,Zre.createPopProofWithSigner)(e,{nonce:t.requestId,audience:Pt.IDENTITY_TAP_LEASE_REQUEST_AUDIENCE,intentHash:O4(t),nowSec:r})}async function cKe(e,t,r,n){let i=await(0,Zre.verifyAgentOperationPopProof)(e,{operationId:t.requestId,audience:Pt.IDENTITY_TAP_LEASE_REQUEST_AUDIENCE,expectedIntentHash:O4(t),nowSec:n,maxAgeSec:60});if(!i.ok||i.jkt!==r||i.runtimeCertificate!==void 0)throw new Error("identity_tap_lease_request_proof_invalid")}});var one=g(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});Ds.IDENTITY_HOSTED_GATE_AUTHORIZATION_PURPOSES=void 0;Ds.identityDeviceEnrollmentPreimage=ine;Ds.verifyIdentityDeviceEnrollmentProof=pKe;Ds.prepareIdentityDeviceGateAuthorization=mKe;Ds.prepareIdentityHostedGateAuthorization=gKe;var rne=require("node:crypto"),nne=Ic(),uKe=Fn(),dKe=Br(),lKe=R4(),fKe=["v","profile","associationId","associationVersion","agentId","runtimeId","generation","requestId","runtimePublicJwk","runtimeJkt","rootJkt","certificateSha256","delegationSha256","gateAuthorizationSha256","iat","exp"].sort().join(","),C4=e=>typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(e),N4=e=>Number.isSafeInteger(e)&&Number(e)>0,DS=e=>typeof e=="string"&&Buffer.from(e,"base64url").length===32&&Buffer.from(e,"base64url").toString("base64url")===e;function ine(e){if(!e||Object.keys(e).sort().join(",")!==fKe||e.v!==1||e.profile!==lKe.IDENTITY_TAP_PROFILE||![e.associationId,e.agentId,e.runtimeId,e.requestId].every(C4)||![e.associationVersion,e.generation].every(N4)||![e.runtimeJkt,e.rootJkt,e.certificateSha256,e.delegationSha256,e.gateAuthorizationSha256].every(DS)||!e.runtimePublicJwk||Object.keys(e.runtimePublicJwk).sort().join(",")!=="crv,kty,x"||e.runtimePublicJwk.kty!=="OKP"||e.runtimePublicJwk.crv!=="Ed25519"||!DS(e.runtimePublicJwk.x)||(0,dKe.computeJkt)(e.runtimePublicJwk)!==e.runtimeJkt||e.runtimeJkt===e.rootJkt||!Number.isSafeInteger(e.iat)||e.iat<0||!Number.isSafeInteger(e.exp)||e.exp<=e.iat||e.exp-e.iat>600)throw new Error("identity_device_challenge_invalid");return Buffer.from("visa:authority:external-runtime-enrollment:v1\0"+(0,uKe.canonicalJson)(e),"utf8")}function pKe(e,t,r){let n=ine(e);if(!Number.isSafeInteger(r)||r<0||e.iat>r+5||e.exp<=r)throw new Error("identity_device_challenge_expired");if(typeof t!="string"||t.length!==86||Buffer.from(t,"base64url").toString("base64url")!==t||!(0,rne.verify)(null,n,(0,rne.createPublicKey)({key:e.runtimePublicJwk,format:"jwk"}),Buffer.from(t,"base64url")))throw new Error("identity_device_proof_invalid")}function mKe(e){if(![e.rootJkt,e.identityPrincipalJkt].every(DS)||![e.agentId,e.authorizationId].every(C4)||!N4(e.generation)||!Number.isSafeInteger(e.nowSec)||e.nowSec<0||!Number.isSafeInteger(e.expiresAt)||e.expiresAt<=e.nowSec||e.expiresAt-e.nowSec>366*86400||![e.rootKid,e.ownerSuborganizationId].every(r=>typeof r=="string"&&/^[\x21-\x7e]{1,256}$/.test(r)))throw new Error("identity_device_standing_authorization_invalid");let t={v:1,iss:e.rootJkt,sub:e.agentId,aud:"urn:visa:tvc:identity-gate",jti:e.authorizationId,ownerSuborganizationId:e.ownerSuborganizationId,turnkeyRootKeyId:e.rootKid,identityPrincipalJkt:e.identityPrincipalJkt,purposes:["tap_signature_base"],generation:e.generation,maxTtlSecondsByPurpose:{tap_signature_base:480},iat:e.nowSec,nbf:e.nowSec,exp:e.expiresAt};return{...(0,nne.prepareRootSignedJws)("visa-agent-identity-gate-authorization+jwt",e.rootKid,t),claims:t}}Ds.IDENTITY_HOSTED_GATE_AUTHORIZATION_PURPOSES=["runtime_presence_pop","tap_signature_base"];function gKe(e){if(![e.rootJkt,e.identityPrincipalJkt].every(DS)||![e.agentId,e.authorizationId].every(C4)||!N4(e.generation)||!Number.isSafeInteger(e.nowSec)||e.nowSec<0||!Number.isSafeInteger(e.expiresAt)||e.expiresAt<=e.nowSec||e.expiresAt-e.nowSec>366*86400||![e.rootKid,e.ownerSuborganizationId].every(r=>typeof r=="string"&&/^[\x21-\x7e]{1,256}$/.test(r)))throw new Error("identity_hosted_standing_authorization_invalid");let t={v:1,iss:e.rootJkt,sub:e.agentId,aud:"urn:visa:tvc:identity-gate",jti:e.authorizationId,ownerSuborganizationId:e.ownerSuborganizationId,turnkeyRootKeyId:e.rootKid,identityPrincipalJkt:e.identityPrincipalJkt,purposes:[...Ds.IDENTITY_HOSTED_GATE_AUTHORIZATION_PURPOSES],generation:e.generation,maxTtlSecondsByPurpose:{runtime_presence_pop:120,tap_signature_base:480},iat:e.nowSec,nbf:e.nowSec,exp:e.expiresAt};return{...(0,nne.prepareRootSignedJws)("visa-agent-identity-gate-authorization+jwt",e.rootKid,t),claims:t}}});var LS=g(_y=>{"use strict";Object.defineProperty(_y,"__esModule",{value:!0});_y.identityTapSigningBytes=k4;_y.identityTapPayloadSha256=yKe;_y.parseIdentityTapSignatureBase=_Ke;var hKe=require("node:crypto");function k4(e){let t=()=>{throw new Error("identity_tap_payload_invalid")};if(!e||typeof e!="object"||Array.isArray(e))return t();let r=e,n=["kind","method","authority","path","coveredComponents","paymentHeaderName","paymentHeaderValue","created","expires","keyId","nonce","tag","signatureBase"],i=["contentDigest","operationId","intentHash"];if(n.some(m=>!Object.hasOwn(r,m))||Object.keys(r).some(m=>!n.includes(m)&&!i.includes(m))||Object.hasOwn(r,"operationId")!==Object.hasOwn(r,"intentHash")||Object.hasOwn(r,"operationId")&&(typeof r.operationId!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(r.operationId)||typeof r.intentHash!="string"||!/^[A-Za-z0-9_-]{43}$/.test(r.intentHash)||Buffer.from(r.intentHash,"base64url").toString("base64url")!==r.intentHash))return t();let o=m=>typeof m=="string"&&m.length>0&&Buffer.byteLength(m)<=8192&&!/[\n\r\0]/.test(m),s=m=>typeof m=="string"&&/^[A-Za-z0-9_-]{43}$/.test(m)&&Buffer.from(m,"base64url").toString("base64url")===m;if(r.kind!=="tap_signature_base"||typeof r.method!="string"||!/^[A-Z]{1,16}$/.test(r.method)||!o(r.authority)||!o(r.path)||!r.path.startsWith("/")||!o(r.paymentHeaderValue)||!["payment-signature","x-payment","authorization"].includes(r.paymentHeaderName)||r.paymentHeaderName==="authorization"&&!/^payment \S/i.test(r.paymentHeaderValue)||r.tag!=="agent-payer-auth"||!s(r.keyId)||typeof r.nonce!="string"||!/^[A-Za-z0-9+/]{43}=$/.test(r.nonce)||Buffer.from(r.nonce,"base64").length!==32||Buffer.from(r.nonce,"base64").toString("base64")!==r.nonce||!Number.isSafeInteger(r.created)||r.created<0||!Number.isSafeInteger(r.expires)||r.expires<=r.created||typeof r.signatureBase!="string"||Buffer.byteLength(r.signatureBase)>65536||Object.hasOwn(r,"contentDigest")&&(!o(r.contentDigest)||!r.contentDigest.startsWith("sha-256=:"))||!Array.isArray(r.coveredComponents)||r.coveredComponents.length<1||r.coveredComponents.length>8)return t();let a={"@method":r.method,"@authority":r.authority,"@path":r.path,[r.paymentHeaderName]:r.paymentHeaderValue};Object.hasOwn(r,"contentDigest")&&(a["content-digest"]=r.contentDigest);let c=new Set,u=[];for(let m of r.coveredComponents){if(typeof m!="string"||!Object.hasOwn(a,m)||c.has(m))return t();c.add(m),u.push(`"${m}": ${a[m]}`)}if(["@method","@authority","@path",r.paymentHeaderName].some(m=>!c.has(m))||c.has("content-digest")!==Object.hasOwn(r,"contentDigest"))return t();let d=r.coveredComponents.map(m=>`"${m}"`).join(" ");u.push(`"@signature-params": (${d});created=${r.created};expires=${r.expires};keyid="${r.keyId}";alg="Ed25519";nonce="${r.nonce}";tag="agent-payer-auth"`);let l=u.join(`
96
+ `);return r.signatureBase!==l?t():Buffer.from(l,"utf8")}function yKe(e){return(0,hKe.createHash)("sha256").update(k4(e)).digest("base64url")}function _Ke(e){if(e.byteLength>65536)throw new Error("identity_tap_payload_invalid");let t=new TextDecoder("utf-8",{fatal:!0}).decode(e),r=t.split(`
97
+ `),n=/^"@signature-params": \(([^)]+)\);created=(\d+);expires=(\d+);keyid="([A-Za-z0-9_-]{43})";alg="Ed25519";nonce="([A-Za-z0-9+/]{43}=)";tag="agent-payer-auth"$/.exec(r.pop()??"");if(!n)throw new Error("identity_tap_payload_invalid");let i={};for(let a of r){let c=/^"([^"\n]+)": (.+)$/.exec(a);if(!c||Object.hasOwn(i,c[1]))throw new Error("identity_tap_payload_invalid");i[c[1]]=c[2]}let o=Object.hasOwn(i,"payment-signature")?"payment-signature":Object.hasOwn(i,"authorization")?"authorization":"x-payment",s={kind:"tap_signature_base",method:i["@method"]??"",authority:i["@authority"]??"",path:i["@path"]??"",coveredComponents:n[1].split(" ").map(a=>a.slice(1,-1)),paymentHeaderName:o,paymentHeaderValue:i[o]??"",...i["content-digest"]===void 0?{}:{contentDigest:i["content-digest"]},created:Number(n[2]),expires:Number(n[3]),keyId:n[4],nonce:n[5],tag:"agent-payer-auth",signatureBase:t};return k4(s),s}});var cne=g(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});Nd.IDENTITY_TAP_SLIP_REQUEST_TYP=void 0;Nd.validateIdentityTapSlipRequest=ane;Nd.issueIdentityTapSlip=TKe;var bKe=LS(),EKe=Fn(),sne=Br(),wKe=Un(),vKe=fp(),SKe=wd();Nd.IDENTITY_TAP_SLIP_REQUEST_TYP="visa-agent-identity-tap-slip-request+jwt";var AKe=e=>typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(e),IKe=e=>typeof e=="string"&&Buffer.from(e,"base64url").length===32&&Buffer.from(e,"base64url").toString("base64url")===e,PKe="v,iss,aud,jti,requestId,associationId,associationVersion,agentId,rootJkt,ownerSuborganizationId,runtimeId,runtimeJkt,generation,network,payloadSha256,leaseSha256,iat,exp".split(",").sort().join(",");function ane(e){if(!e||Object.keys(e).sort().join(",")!==PKe||e.v!==1||e.iss!=="urn:visa:authority:identity"||e.aud!=="visa:auth:identity-tap-slip"||![e.jti,e.requestId,e.associationId,e.agentId,e.runtimeId].every(AKe)||![e.rootJkt,e.runtimeJkt,e.payloadSha256,e.leaseSha256].every(IKe)||![e.associationVersion,e.generation].every(t=>Number.isSafeInteger(t)&&t>0)||!Number.isSafeInteger(e.iat)||e.iat<0||!Number.isSafeInteger(e.exp)||e.exp<=e.iat||e.exp-e.iat>60||typeof e.ownerSuborganizationId!="string"||!/^[\x21-\x7e]{1,256}$/.test(e.ownerSuborganizationId)||typeof e.network!="string"||!/^eip155:[1-9][0-9]{0,15}$/.test(e.network))throw new Error("identity_tap_slip_request_invalid")}async function TKe(e){if(typeof e.ticket!="string"||e.ticket.length>16384||typeof e.popJwt!="string"||e.popJwt.length>32768)throw new Error("identity_tap_slip_request_invalid");let t=(0,sne.computeJkt)(e.authorityPublicJwk),r=await(0,wKe.verifyJwtSignature)(e.ticket,{keys:[{...e.authorityPublicJwk,kid:t}]});if(!r.ok||r.header.typ!==Nd.IDENTITY_TAP_SLIP_REQUEST_TYP||r.header.kid!==t)throw new Error("identity_tap_slip_request_invalid");let n=r.claims;if(ane(n),!Number.isSafeInteger(e.nowSec)||e.nowSec<0||n.iat>e.nowSec+5||n.exp<=e.nowSec)throw new Error("identity_tap_slip_request_expired");if(Buffer.from((0,EKe.canonicalJson)(n)).toString("base64url")!==e.ticket.split(".")[1])throw new Error("identity_tap_slip_request_invalid");let i=(0,sne.computeJkt)(e.signer.publicJwk);if([t,n.rootJkt,n.runtimeJkt].includes(i))throw new Error("identity_slip_issuer_not_independent");if(!e.payload||typeof e.payload!="object"||e.payload.kind!=="tap_signature_base"||(0,bKe.identityTapPayloadSha256)(e.payload)!==n.payloadSha256)throw new Error("identity_tap_slip_payload_mismatch");let o=await(0,SKe.verifyAgentOperationPopProof)(e.popJwt,{operationId:n.requestId,audience:"urn:visa:tvc:identity-gate",expectedIntentHash:n.payloadSha256,nowSec:e.nowSec,maxAgeSec:60});if(!o.ok||o.jkt!==n.runtimeJkt||o.runtimeCertificate!==void 0)throw new Error("identity_tap_slip_proof_invalid");return(0,vKe.signJwtWithSigner)(e.signer,{typ:"visa-agent-identity-slip+jwt"},{v:1,iss:"visa:auth",aud:"urn:visa:tvc:identity-gate",jti:n.jti,requestId:n.requestId,iat:n.iat,exp:n.exp,purpose:"tap_signature_base",payloadSha256:n.payloadSha256,agentId:n.agentId,rootJkt:n.rootJkt,ownerSuborganizationId:n.ownerSuborganizationId,runtimeId:n.runtimeId,runtimeJkt:n.runtimeJkt,generation:n.generation,network:n.network})}});var j4=g(Bi=>{"use strict";Object.defineProperty(Bi,"__esModule",{value:!0});Bi.IDENTITY_HOSTED_TAP_SLIP_PURPOSE=Bi.IDENTITY_PRESENCE_SLIP_PURPOSE=void 0;Bi.hostedPresenceAttemptId=CKe;Bi.issueHostedPresenceIdentitySlip=NKe;Bi.issueHostedTapIdentitySlip=kKe;var xKe=require("node:crypto"),OKe=Br(),RKe=fp();Bi.IDENTITY_PRESENCE_SLIP_PURPOSE="runtime_presence_pop";Bi.IDENTITY_HOSTED_TAP_SLIP_PURPOSE="tap_signature_base";function CKe(e,t){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(e)||!Number.isSafeInteger(t)||t<0)throw new Error("hosted_presence_attempt_invalid");let r=(0,xKe.createHash)("sha256").update(`visa:hosted-presence-attempt:v1\0${e}\0${t}`,"utf8").digest().subarray(0,16);r[6]=r[6]&15|128,r[8]=r[8]&63|128;let n=r.toString("hex");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function NKe(e){return une(Bi.IDENTITY_PRESENCE_SLIP_PURPOSE,e)}function kKe(e){return une(Bi.IDENTITY_HOSTED_TAP_SLIP_PURPOSE,e)}async function une(e,t){let r=(0,OKe.computeJkt)(t.signer.publicJwk);if([t.rootJkt,t.runtimeJkt].includes(r))throw new Error("identity_slip_issuer_not_independent");if(!Number.isSafeInteger(t.iat)||!Number.isSafeInteger(t.exp)||t.iat<0||t.exp<=t.iat||!Number.isSafeInteger(t.generation)||t.generation<1||!/^eip155:[1-9][0-9]{0,15}$/.test(t.network)||!/^[A-Za-z0-9_-]{43}$/.test(t.payloadSha256)||!/^[A-Za-z0-9_-]{43}$/.test(t.rootJkt)||!/^[A-Za-z0-9_-]{43}$/.test(t.runtimeJkt)||!/^[\x21-\x7e]{1,256}$/.test(t.ownerSuborganizationId))throw new Error("identity_presence_slip_request_invalid");return(0,RKe.signJwtWithSigner)(t.signer,{typ:"visa-agent-identity-slip+jwt"},{v:1,iss:"visa:auth",aud:"urn:visa:tvc:identity-gate",jti:t.jti,requestId:t.requestId,iat:t.iat,exp:t.exp,purpose:e,payloadSha256:t.payloadSha256,agentId:t.agentId,rootJkt:t.rootJkt,ownerSuborganizationId:t.ownerSuborganizationId,runtimeId:t.runtimeId,runtimeJkt:t.runtimeJkt,generation:t.generation,network:t.network})}});var mne=g(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});Tc.IDENTITY_HOSTED_TAP_SLIP_REQUEST_TYP=void 0;Tc.validateIdentityHostedTapSlipRequest=fne;Tc.hostedTapPayloadNamesMerchantRequest=pne;Tc.issueHostedTapSlipFromTicket=FKe;var jKe=Fn(),dne=Br(),MKe=Un(),qKe=LS(),DKe=P4(),LKe=j4();Tc.IDENTITY_HOSTED_TAP_SLIP_REQUEST_TYP="visa-agent-identity-hosted-tap-slip-request+jwt";var BKe=e=>typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(e),lne=e=>typeof e=="string"&&Buffer.from(e,"base64url").length===32&&Buffer.from(e,"base64url").toString("base64url")===e,UKe=e=>Number.isSafeInteger(e)&&e>0,HKe="v,iss,aud,jti,requestId,associationId,associationVersion,agentId,rootJkt,ownerSuborganizationId,runtimeId,runtimeJkt,generation,network,custody,connectorKeyId,grantId,grantVersion,operationId,intentHash,payloadSha256,iat,exp".split(",").sort().join(",");function fne(e){if(!e||typeof e!="object"||Object.keys(e).sort().join(",")!==HKe||e.v!==1||e.iss!=="urn:visa:authority:identity"||e.aud!=="visa:auth:identity-tap-slip"||![e.jti,e.requestId,e.associationId,e.agentId,e.runtimeId,e.grantId,e.operationId].every(BKe)||![e.rootJkt,e.runtimeJkt,e.intentHash,e.payloadSha256].every(lne)||![e.associationVersion,e.generation,e.grantVersion].every(UKe)||e.custody!=="signer"||typeof e.connectorKeyId!="string"||!/^[A-Za-z0-9._:@/-]{1,256}$/.test(e.connectorKeyId)||!Number.isSafeInteger(e.iat)||e.iat<0||!Number.isSafeInteger(e.exp)||e.exp<=e.iat||e.exp-e.iat>60||typeof e.ownerSuborganizationId!="string"||!/^[\x21-\x7e]{1,256}$/.test(e.ownerSuborganizationId)||typeof e.network!="string"||!/^eip155:[1-9][0-9]{0,15}$/.test(e.network))throw new Error("identity_hosted_tap_slip_request_invalid")}function pne(e,t){let r;try{r=new URL(t.url)}catch{return!1}return r.protocol!=="https:"&&r.protocol!=="http:"||typeof t.method!="string"||e.method!==t.method.toUpperCase()||e.authority!==r.host||e.path!==(r.pathname||"/")?!1:e.contentDigest===void 0?t.bodySha256===void 0||t.bodySha256==="47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU":typeof t.bodySha256!="string"||!lne(t.bodySha256)?!1:e.contentDigest===`sha-256=:${Buffer.from(t.bodySha256,"base64url").toString("base64")}:`}async function FKe(e){if(typeof e.ticket!="string"||e.ticket.length>16384)throw new Error("identity_hosted_tap_slip_request_invalid");let t=(0,dne.computeJkt)(e.authorityPublicJwk),r=await(0,MKe.verifyJwtSignature)(e.ticket,{keys:[{...e.authorityPublicJwk,kid:t}]});if(!r.ok||r.header.typ!==Tc.IDENTITY_HOSTED_TAP_SLIP_REQUEST_TYP||r.header.kid!==t)throw new Error("identity_hosted_tap_slip_request_invalid");let n=r.claims;if(fne(n),!Number.isSafeInteger(e.nowSec)||e.nowSec<0||n.iat>e.nowSec+30||n.exp<=e.nowSec)throw new Error("identity_hosted_tap_slip_request_expired");if(Buffer.from((0,jKe.canonicalJson)(n)).toString("base64url")!==e.ticket.split(".")[1])throw new Error("identity_hosted_tap_slip_request_invalid");let i=(0,dne.computeJkt)(e.signer.publicJwk);if([t,n.rootJkt,n.runtimeJkt].includes(i))throw new Error("identity_slip_issuer_not_independent");let o=e.payload;if(!o||typeof o!="object"||o.kind!=="tap_signature_base"||(0,qKe.identityTapPayloadSha256)(o)!==n.payloadSha256||o.operationId!==n.operationId||o.intentHash!==n.intentHash)throw new Error("identity_hosted_tap_slip_payload_mismatch");let s=e.presence;if(!s||s.agentId!==n.agentId||s.runtimeId!==n.runtimeId||s.connectorKeyId!==n.connectorKeyId||s.operationId!==n.operationId||s.intentHash!==n.intentHash)throw new Error("identity_hosted_tap_connector_absent");if(!s.merchant||!pne(o,s.merchant))throw new Error("identity_hosted_tap_merchant_mismatch");let a=await(0,LKe.issueHostedTapIdentitySlip)({signer:e.signer,jti:n.jti,requestId:n.requestId,iat:n.iat,exp:n.exp,payloadSha256:n.payloadSha256,agentId:n.agentId,rootJkt:n.rootJkt,ownerSuborganizationId:n.ownerSuborganizationId,runtimeId:n.runtimeId,runtimeJkt:n.runtimeJkt,generation:n.generation,network:n.network}),c=await(0,DKe.issueHostedConnectorProof)({signer:e.signer,requestId:n.requestId,agentId:n.agentId,runtimeId:n.runtimeId,connectorKeyId:n.connectorKeyId,grantId:n.grantId,grantVersion:n.grantVersion,operationId:n.operationId,intentHash:n.intentHash,issuedAtSec:e.nowSec});return{identitySlip:a,connectorProof:c,claims:n}}});var _ne=g(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});xc.IDENTITY_DEVICE_HANDOFF_AUDIENCE=void 0;xc.identityDeviceProposalSha256=hne;xc.identityDeviceHandoffIntentHash=yne;xc.verifyIdentityDeviceHandoffProof=KKe;var $Ke=require("node:crypto"),JKe=Fn(),VKe=Br(),GKe=wd();xc.IDENTITY_DEVICE_HANDOFF_AUDIENCE="visa-device-handoff:v1";var by=e=>typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(e),gne=e=>typeof e=="string"&&Buffer.from(e,"base64url").length===32&&Buffer.from(e,"base64url").toString("base64url")===e,kd=(e,t)=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).sort().join(",")===t.sort().join(","),M4=e=>(0,$Ke.createHash)("sha256").update((0,JKe.canonicalJson)(e)).digest("base64url");function hne(e){if(!kd(e,["associationId","associationVersion","agentId","rootJkt","runtimeId","runtimePublicJwk","runtimeJkt"])||![e.associationId,e.agentId,e.runtimeId].every(by)||!Number.isSafeInteger(e.associationVersion)||e.associationVersion<1||![e.rootJkt,e.runtimeJkt].every(gne)||e.rootJkt===e.runtimeJkt||!kd(e.runtimePublicJwk,["kty","crv","x"])||e.runtimePublicJwk.kty!=="OKP"||e.runtimePublicJwk.crv!=="Ed25519"||!gne(e.runtimePublicJwk.x)||(0,VKe.computeJkt)(e.runtimePublicJwk)!==e.runtimeJkt)throw new Error("identity_device_proposal_invalid");return M4(e)}function yne(e){if(!kd(e,["v","operation","requestId","handoffId","proposal","body"])||e.v!==1||!by(e.requestId)||!by(e.handoffId))throw new Error("identity_device_handoff_invalid");let t=hne(e.proposal);if(e.operation==="create"){if(e.requestId!==e.handoffId||!kd(e.body,[]))throw new Error("identity_device_handoff_invalid")}else if(e.operation==="read"){if(!kd(e.body,[]))throw new Error("identity_device_handoff_invalid")}else if(e.operation==="cancel"){if(!kd(e.body,["enrollmentRequestId","generation"])||!(e.body.enrollmentRequestId===null&&e.body.generation===null)&&(!by(e.body.enrollmentRequestId)||!Number.isSafeInteger(e.body.generation)||e.body.generation<1))throw new Error("identity_device_handoff_invalid")}else if(e.operation==="proof"){if(!kd(e.body,["enrollmentRequestId","runtimeProof"])||!by(e.body.enrollmentRequestId)||typeof e.body.runtimeProof!="string"||e.body.runtimeProof.length!==86||Buffer.from(e.body.runtimeProof,"base64url").length!==64||Buffer.from(e.body.runtimeProof,"base64url").toString("base64url")!==e.body.runtimeProof)throw new Error("identity_device_handoff_invalid")}else throw new Error("identity_device_handoff_invalid");return M4({v:1,operation:e.operation,handoffId:e.handoffId,proposalSha256:t,bodySha256:M4(e.body)})}async function KKe(e,t,r){let n=await(0,GKe.verifyAgentOperationPopProof)(e,{operationId:t.requestId,audience:xc.IDENTITY_DEVICE_HANDOFF_AUDIENCE,expectedIntentHash:yne(t),nowSec:r,maxAgeSec:60});if(!n.ok||n.jkt!==t.proposal.runtimeJkt||n.runtimeCertificate!==void 0)throw new Error("identity_device_handoff_proof_invalid")}});var bne=g(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});Oc.PROTECTED_TAP_REGISTRY_ATTENTION_CODES=void 0;Oc.protectedTapRegistrySigningBytes=YKe;Oc.isProtectedTapRegistryAttentionCode=XKe;Oc.validateProtectedTapRegistryRequest=QKe;var WKe=Br(),zKe=Fn();function YKe(e,t){return Buffer.from(`visa:protected-tap-registry:v1
98
+ ${t}
99
+ ${(0,zKe.canonicalJson)(e)}`)}Oc.PROTECTED_TAP_REGISTRY_ATTENTION_CODES=["tap_registry_tenant_changed","tap_registry_subject_mismatch","tap_registry_public_key_mismatch","tap_registry_key_scan_incomplete","tap_registry_deactivation_unconfirmed"];function XKe(e){return typeof e=="string"&&Oc.PROTECTED_TAP_REGISTRY_ATTENTION_CODES.includes(e)}var ZKe=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function QKe(e){if(!e||typeof e!="object")throw new Error("tap_registry_request_invalid");let t=e,r=Object.keys(t).sort().join(",");if(!["create","reconcile","revoke"].includes(t.operation)||!ZKe.test(t.agentId)||r!==(t.operation==="create"?"agentId,key,operation":"agentId,key,operation,provider")||!t.key||Object.keys(t.key).sort().join(",")!=="jkt,jwk"||!t.key.jwk||Object.keys(t.key.jwk).sort().join(",")!=="crv,kty,x"||t.key.jwk.kty!=="OKP"||t.key.jwk.crv!=="Ed25519"||typeof t.key.jwk.x!="string"||!/^[A-Za-z0-9_-]{43}$/.test(t.key.jwk.x)||Buffer.from(t.key.jwk.x,"base64url").toString("base64url")!==t.key.jwk.x||(0,WKe.computeJkt)(t.key.jwk)!==t.key.jkt||t.operation!=="create"&&(!t.provider||Object.keys(t.provider).sort().join(",")!=="agentId,tenant"||typeof t.provider.tenant!="string"||t.provider.tenant.length>256||typeof t.provider.agentId!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(t.provider.agentId)))throw new Error("tap_registry_request_invalid");return t}});var Cc=g(_=>{"use strict";Object.defineProperty(_,"__esModule",{value:!0});_.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS=_.RUNTIME_CERTIFICATE_VERSION=_.RUNTIME_CERTIFICATE_TYP=_.verifyAgentOperationPopProof=_.verifyPopProof=_.createAgentOperationPopProof=_.createPopProofWithSigner=_.createPopProof=_.randomPopNonce=_.DEFAULT_POP_MAX_AGE_SEC=_.UNIVERSAL_AGENT_OPERATION_AUDIENCE=_.POP_JWT_TYP=_.importLegacyWalletSpendPolicy=_.canonicalLegacyWalletSpendPolicy=_.productSpendPolicyHash=_.isProductSpendPolicySubset=_.evaluateProductSpendPolicy=_.canonicalRuntimeProductSpendAttenuation=_.canonicalOwnerProductSpendPolicy=_.canonicalMerchantTarget=_.canonicalMerchantPathPrefix=_.canonicalMerchantOriginPattern=_.PRODUCT_SPEND_POLICY_VERSION=_.evaluateEconomic=_.verifyBindingChain=_.DEFAULT_MAX_STALENESS_SECONDS=_.InMemoryFreshnessStore=_.FreshnessService=_.verifyFreshness=_.issueFreshness=_.FRESHNESS_JWT_TYP=_.MAX_TTL_FRESH_HOURS=_.TTL_FRESH_HOURS=_.verifyRegistration=_.issueRegistration=_.registrationHash=_.derivePairwiseRef=_.REGISTRATION_JWT_TYP=_.TTL_REG_DAYS=_.isCanonicalEvmProviderAddress=_.canonicalEvmProviderAddress=_.turnkeyOwnerIdentityKey=_.verifyEip712TypedDataSignature=_.eip712DigestBase64Url=_.buildJwks=_.anchorKeyFromSeed=_.generateAnchorKey=_.agentKeyFromSeed=_.generateAgentKey=_.computeJkt=void 0;_.completeWalletBinding=_.prepareWalletBinding=_.WALLET_BINDING_DERIVATION_VERSION=_.WALLET_BINDING_SIGNER_KIND=_.WALLET_BINDING_MAX_TTL_SECONDS=_.WALLET_BINDING_VERSION=_.WALLET_BINDING_TYP=_.verifyTapRuntimeSignature=_.tapRuntimeSigningMessage=_.TAP_RUNTIME_SIGNATURE_DOMAIN=_.verifyRuntimeLeaseRequestProof=_.createRuntimeLeaseRequestProofWithSigner=_.createRuntimeLeaseRequestProof=_.runtimeLeaseRequestIntentHash=_.RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS=_.RUNTIME_LEASE_REQUEST_AUDIENCE=_.RUNTIME_LEASE_REQUEST_VERSION=_.verifyRuntimeLeaseChain=_.verifyRuntimeDelegation=_.issueRuntimeLease=_.issueRuntimeDelegation=_.completeRuntimeDelegation=_.prepareRuntimeDelegation=_.verifyTempoRuntimeLeaseChain=_.issueTempoRuntimeLease=_.TEMPO_LEASE_SIGNING_MODE=_.TEMPO_LEASE_NETWORK=_.TEMPO_LEASE_PURPOSE=_.RUNTIME_LEASE_SIGNING_MODES=_.RUNTIME_LEASE_PURPOSE=_.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS=_.RUNTIME_LEASE_MAX_TTL_SECONDS=_.RUNTIME_LEASE_AUDIENCE=_.RUNTIME_LEASE_VERSION=_.RUNTIME_LEASE_TYP=_.RUNTIME_DELEGATION_MAX_TTL_SECONDS=_.runtimeDelegationScope=_.RUNTIME_DELEGATION_RAILS=_.RUNTIME_CUSTODIES=_.RUNTIME_DELEGATION_LEGACY_VERSION=_.RUNTIME_DELEGATION_VERSION=_.RUNTIME_DELEGATION_TYP=_.verifyRuntimeCertificate=_.prepareRuntimeCertificate=_.peekRuntimeCertificate=_.issueRuntimeCertificate=_.completeRuntimeCertificate=_.HOSTED_RUNTIME_CERTIFICATE_PURPOSES=_.RUNTIME_CERTIFICATE_PURPOSES=_.CARD_RUNTIME_CERTIFICATE_MAX_TTL_SECONDS=void 0;_.pairingCodeFromClaimToken=_.pairingClaimTokenHash=_.randomPairingClaimToken=_.pairingCodeHash=_.isValidPairingCode=_.formatPairingCode=_.normalizePairingCode=_.randomPairingCode=_.pairingVerifierChallenge=_.randomPairingVerifier=_.randomPairingId=_.assertAgentPairingTransition=_.canTransitionAgentPairing=_.isAgentPairingState=_.AGENT_PAIRING_TERMINAL_STATES=_.AGENT_PAIRING_STATES=_.AGENT_PAIRING_CODE_LENGTH=_.AGENT_PAIRING_CODE_ALPHABET=_.AGENT_PAIRING_TTL_SECONDS=_.AGENT_PAIRING_PROTOCOL_VERSION_V2=_.AGENT_PAIRING_PROTOCOL_VERSION=_.KillList=_.attestationIsVoid=_.verifyKillSwitch=_.issueKillSwitch=_.verifySuccession=_.issueSuccession=_.KILL_SWITCH_JWT_TYP=_.SUCCESSION_JWT_TYP=_.issueRegistrationWithSigner=_.signerFromSignFn=_.signerFromAnchorKey=_.LocalSigner=_.signJwtWithSigner=_.walletVerifiedFromProof=_.verifyOwnershipProof=_.attestWalletOwnership=_.issueOwnershipProofWithSigner=_.issueOwnershipProof=_.verifyOwnershipSignature=_.buildOwnershipChallenge=_.CHALLENGE_MAX_AGE_SEC=_.MAX_TTL_OWNERSHIP_HOURS=_.TTL_OWNERSHIP_HOURS=_.OWNERSHIP_PROOF_JWT_TYP=_.OWNERSHIP_CHALLENGE_DOMAIN_V1=_.canonicalIntentHash=_.INTENT_HASH_VERSION=_.verifyWalletBinding=_.issueWalletBinding=void 0;_.walletAuthorizationRequestHash=_.spendAuthorizationIntentHash=_.agentAuthorityGrantHash=_.isCanonicalBase64Url32=_.centsToUsdMicros=_.canonicalSpendAuthorizationIntent=_.canonicalAgentChannelDescriptor=_.canonicalPayWithinBudget=_.canonicalAgentAuthorityGrant=_.defaultPayWithinBudget=_.WALLET_GRANT_SCOPE=_.grantPaymentRails=_.AGENT_PAYMENT_RAILS=_.AGENT_PAYMENT_SURFACES=_.AGENT_PAYMENT_MODE_NAMES=_.authorizationScopeFacts=_.VIC_PROCESSOR_ACTIONS=_.USD_MICROS_PER_CENT=_.AGENT_KEY_STATUSES=_.AGENT_KEY_CUSTODIES=_.AGENT_CHANNEL_STATUSES=_.AGENT_CHANNEL_ASSURANCES=_.AGENT_CHANNEL_KINDS=_.AGENT_EXECUTION_READINESS_REASONS=_.AGENT_AUTHORIZATION_SCOPES=_.AGENT_AUTHORITY_VALUATION_POLICY=_.AGENT_BUDGET_EPOCH_MODES=_.AGENT_AUTHORITY_VERSION=_.sha256=_.pairingInstrumentCommitment=_.pairingDeliveryArtifactV2Hash=_.canonicalPairingDeliveryArtifactV2=_.pairingArtifactHash=_.agentMailCredentialClaimMessageV2=_.keyRotationClaimHashV2=_.keyRotationClaimMessageV2=_.handoffAuthorityCapabilities=_.AGENT_HANDOFF_COMPOUND_AUTHORITY=_.AGENT_HANDOFF_AUTHORITIES=_.AGENT_CAPABILITY_ATTACH_CAPABILITIES=_.pairingActivationMessageV2=_.pairingActivationMessage=_.pairingClaimHashV2=_.pairingClaimMessageV2=_.pairingClaimMessage=_.pairingTermsV2Hash=_.pairingTermsHash=_.canonicalPairingTermsV2=_.canonicalPairingTerms=_.pairingConfirmationCode=void 0;_.isProtectedTapRegistryAttentionCode=_.protectedTapRegistrySigningBytes=_.validateProtectedTapRegistryRequest=_.verifyIdentityDeviceHandoffProof=_.identityDeviceHandoffIntentHash=_.identityDeviceProposalSha256=_.IDENTITY_DEVICE_HANDOFF_AUDIENCE=_.parseIdentityTapSignatureBase=_.identityTapPayloadSha256=_.identityTapSigningBytes=_.hostedTapPayloadNamesMerchantRequest=_.issueHostedTapSlipFromTicket=_.validateIdentityHostedTapSlipRequest=_.IDENTITY_HOSTED_TAP_SLIP_REQUEST_TYP=_.hostedPresenceAttemptId=_.issueHostedTapIdentitySlip=_.issueHostedPresenceIdentitySlip=_.IDENTITY_HOSTED_TAP_SLIP_PURPOSE=_.IDENTITY_PRESENCE_SLIP_PURPOSE=_.issueIdentityTapSlip=_.validateIdentityTapSlipRequest=_.IDENTITY_TAP_SLIP_REQUEST_TYP=_.verifyIdentityDeviceEnrollmentProof=_.IDENTITY_HOSTED_GATE_AUTHORIZATION_PURPOSES=_.prepareIdentityHostedGateAuthorization=_.prepareIdentityDeviceGateAuthorization=_.identityDeviceEnrollmentPreimage=_.verifyIdentityTapLeaseRequestProof=_.createIdentityTapLeaseRequestProof=_.identityTapLeaseRequestIntentHash=_.issueIdentityTapLease=_.verifyIdentityTapDelegation=_.prepareIdentityTapDelegation=_.IDENTITY_TAP_LEASE_REQUEST_AUDIENCE=_.IDENTITY_TAP_LEASE_AUDIENCE=_.IDENTITY_TAP_PURPOSE=_.IDENTITY_TAP_PROFILE=_.verifyIdentityPresenceLeaseChain=_.verifyHostedConnectorProof=_.issueIdentityPresenceLease=_.issueHostedConnectorProof=_.HOSTED_CONNECTOR_PROOF_TTL_SECONDS=_.HOSTED_CONNECTOR_PROOF_TYP=_.IDENTITY_PRESENCE_SIGNING_MODE=_.IDENTITY_PRESENCE_PURPOSE=_.IDENTITY_PRESENCE_LEASE_AUDIENCE=_.prepareIdentityPresenceDelegation=_.usdcAtomicToUsdMicros=void 0;var wp=Br();Object.defineProperty(_,"computeJkt",{enumerable:!0,get:function(){return wp.computeJkt}});Object.defineProperty(_,"generateAgentKey",{enumerable:!0,get:function(){return wp.generateAgentKey}});Object.defineProperty(_,"agentKeyFromSeed",{enumerable:!0,get:function(){return wp.agentKeyFromSeed}});Object.defineProperty(_,"generateAnchorKey",{enumerable:!0,get:function(){return wp.generateAnchorKey}});Object.defineProperty(_,"anchorKeyFromSeed",{enumerable:!0,get:function(){return wp.anchorKeyFromSeed}});Object.defineProperty(_,"buildJwks",{enumerable:!0,get:function(){return wp.buildJwks}});var Ene=rZ();Object.defineProperty(_,"eip712DigestBase64Url",{enumerable:!0,get:function(){return Ene.eip712DigestBase64Url}});Object.defineProperty(_,"verifyEip712TypedDataSignature",{enumerable:!0,get:function(){return Ene.verifyEip712TypedDataSignature}});var eWe=iZ();Object.defineProperty(_,"turnkeyOwnerIdentityKey",{enumerable:!0,get:function(){return eWe.turnkeyOwnerIdentityKey}});var wne=sZ();Object.defineProperty(_,"canonicalEvmProviderAddress",{enumerable:!0,get:function(){return wne.canonicalEvmProviderAddress}});Object.defineProperty(_,"isCanonicalEvmProviderAddress",{enumerable:!0,get:function(){return wne.isCanonicalEvmProviderAddress}});var vp=ey();Object.defineProperty(_,"TTL_REG_DAYS",{enumerable:!0,get:function(){return vp.TTL_REG_DAYS}});Object.defineProperty(_,"REGISTRATION_JWT_TYP",{enumerable:!0,get:function(){return vp.REGISTRATION_JWT_TYP}});Object.defineProperty(_,"derivePairwiseRef",{enumerable:!0,get:function(){return vp.derivePairwiseRef}});Object.defineProperty(_,"registrationHash",{enumerable:!0,get:function(){return vp.registrationHash}});Object.defineProperty(_,"issueRegistration",{enumerable:!0,get:function(){return vp.issueRegistration}});Object.defineProperty(_,"verifyRegistration",{enumerable:!0,get:function(){return vp.verifyRegistration}});var jd=ED();Object.defineProperty(_,"TTL_FRESH_HOURS",{enumerable:!0,get:function(){return jd.TTL_FRESH_HOURS}});Object.defineProperty(_,"MAX_TTL_FRESH_HOURS",{enumerable:!0,get:function(){return jd.MAX_TTL_FRESH_HOURS}});Object.defineProperty(_,"FRESHNESS_JWT_TYP",{enumerable:!0,get:function(){return jd.FRESHNESS_JWT_TYP}});Object.defineProperty(_,"issueFreshness",{enumerable:!0,get:function(){return jd.issueFreshness}});Object.defineProperty(_,"verifyFreshness",{enumerable:!0,get:function(){return jd.verifyFreshness}});Object.defineProperty(_,"FreshnessService",{enumerable:!0,get:function(){return jd.FreshnessService}});Object.defineProperty(_,"InMemoryFreshnessStore",{enumerable:!0,get:function(){return jd.InMemoryFreshnessStore}});var vne=wD();Object.defineProperty(_,"DEFAULT_MAX_STALENESS_SECONDS",{enumerable:!0,get:function(){return vne.DEFAULT_MAX_STALENESS_SECONDS}});Object.defineProperty(_,"verifyBindingChain",{enumerable:!0,get:function(){return vne.verifyBindingChain}});var tWe=Nee();Object.defineProperty(_,"evaluateEconomic",{enumerable:!0,get:function(){return tWe.evaluateEconomic}});var Ls=r4();Object.defineProperty(_,"PRODUCT_SPEND_POLICY_VERSION",{enumerable:!0,get:function(){return Ls.PRODUCT_SPEND_POLICY_VERSION}});Object.defineProperty(_,"canonicalMerchantOriginPattern",{enumerable:!0,get:function(){return Ls.canonicalMerchantOriginPattern}});Object.defineProperty(_,"canonicalMerchantPathPrefix",{enumerable:!0,get:function(){return Ls.canonicalMerchantPathPrefix}});Object.defineProperty(_,"canonicalMerchantTarget",{enumerable:!0,get:function(){return Ls.canonicalMerchantTarget}});Object.defineProperty(_,"canonicalOwnerProductSpendPolicy",{enumerable:!0,get:function(){return Ls.canonicalOwnerProductSpendPolicy}});Object.defineProperty(_,"canonicalRuntimeProductSpendAttenuation",{enumerable:!0,get:function(){return Ls.canonicalRuntimeProductSpendAttenuation}});Object.defineProperty(_,"evaluateProductSpendPolicy",{enumerable:!0,get:function(){return Ls.evaluateProductSpendPolicy}});Object.defineProperty(_,"isProductSpendPolicySubset",{enumerable:!0,get:function(){return Ls.isProductSpendPolicySubset}});Object.defineProperty(_,"productSpendPolicyHash",{enumerable:!0,get:function(){return Ls.productSpendPolicyHash}});var Sne=ore();Object.defineProperty(_,"canonicalLegacyWalletSpendPolicy",{enumerable:!0,get:function(){return Sne.canonicalLegacyWalletSpendPolicy}});Object.defineProperty(_,"importLegacyWalletSpendPolicy",{enumerable:!0,get:function(){return Sne.importLegacyWalletSpendPolicy}});var Bs=wd();Object.defineProperty(_,"POP_JWT_TYP",{enumerable:!0,get:function(){return Bs.POP_JWT_TYP}});Object.defineProperty(_,"UNIVERSAL_AGENT_OPERATION_AUDIENCE",{enumerable:!0,get:function(){return Bs.UNIVERSAL_AGENT_OPERATION_AUDIENCE}});Object.defineProperty(_,"DEFAULT_POP_MAX_AGE_SEC",{enumerable:!0,get:function(){return Bs.DEFAULT_POP_MAX_AGE_SEC}});Object.defineProperty(_,"randomPopNonce",{enumerable:!0,get:function(){return Bs.randomPopNonce}});Object.defineProperty(_,"createPopProof",{enumerable:!0,get:function(){return Bs.createPopProof}});Object.defineProperty(_,"createPopProofWithSigner",{enumerable:!0,get:function(){return Bs.createPopProofWithSigner}});Object.defineProperty(_,"createAgentOperationPopProof",{enumerable:!0,get:function(){return Bs.createAgentOperationPopProof}});Object.defineProperty(_,"verifyPopProof",{enumerable:!0,get:function(){return Bs.verifyPopProof}});Object.defineProperty(_,"verifyAgentOperationPopProof",{enumerable:!0,get:function(){return Bs.verifyAgentOperationPopProof}});var Ui=c4();Object.defineProperty(_,"RUNTIME_CERTIFICATE_TYP",{enumerable:!0,get:function(){return Ui.RUNTIME_CERTIFICATE_TYP}});Object.defineProperty(_,"RUNTIME_CERTIFICATE_VERSION",{enumerable:!0,get:function(){return Ui.RUNTIME_CERTIFICATE_VERSION}});Object.defineProperty(_,"RUNTIME_CERTIFICATE_MAX_TTL_SECONDS",{enumerable:!0,get:function(){return Ui.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS}});Object.defineProperty(_,"CARD_RUNTIME_CERTIFICATE_MAX_TTL_SECONDS",{enumerable:!0,get:function(){return Ui.CARD_RUNTIME_CERTIFICATE_MAX_TTL_SECONDS}});Object.defineProperty(_,"RUNTIME_CERTIFICATE_PURPOSES",{enumerable:!0,get:function(){return Ui.RUNTIME_CERTIFICATE_PURPOSES}});Object.defineProperty(_,"HOSTED_RUNTIME_CERTIFICATE_PURPOSES",{enumerable:!0,get:function(){return Ui.HOSTED_RUNTIME_CERTIFICATE_PURPOSES}});Object.defineProperty(_,"completeRuntimeCertificate",{enumerable:!0,get:function(){return Ui.completeRuntimeCertificate}});Object.defineProperty(_,"issueRuntimeCertificate",{enumerable:!0,get:function(){return Ui.issueRuntimeCertificate}});Object.defineProperty(_,"peekRuntimeCertificate",{enumerable:!0,get:function(){return Ui.peekRuntimeCertificate}});Object.defineProperty(_,"prepareRuntimeCertificate",{enumerable:!0,get:function(){return Ui.prepareRuntimeCertificate}});Object.defineProperty(_,"verifyRuntimeCertificate",{enumerable:!0,get:function(){return Ui.verifyRuntimeCertificate}});var dt=kS();Object.defineProperty(_,"RUNTIME_DELEGATION_TYP",{enumerable:!0,get:function(){return dt.RUNTIME_DELEGATION_TYP}});Object.defineProperty(_,"RUNTIME_DELEGATION_VERSION",{enumerable:!0,get:function(){return dt.RUNTIME_DELEGATION_VERSION}});Object.defineProperty(_,"RUNTIME_DELEGATION_LEGACY_VERSION",{enumerable:!0,get:function(){return dt.RUNTIME_DELEGATION_LEGACY_VERSION}});Object.defineProperty(_,"RUNTIME_CUSTODIES",{enumerable:!0,get:function(){return dt.RUNTIME_CUSTODIES}});Object.defineProperty(_,"RUNTIME_DELEGATION_RAILS",{enumerable:!0,get:function(){return dt.RUNTIME_DELEGATION_RAILS}});Object.defineProperty(_,"runtimeDelegationScope",{enumerable:!0,get:function(){return dt.runtimeDelegationScope}});Object.defineProperty(_,"RUNTIME_DELEGATION_MAX_TTL_SECONDS",{enumerable:!0,get:function(){return dt.RUNTIME_DELEGATION_MAX_TTL_SECONDS}});Object.defineProperty(_,"RUNTIME_LEASE_TYP",{enumerable:!0,get:function(){return dt.RUNTIME_LEASE_TYP}});Object.defineProperty(_,"RUNTIME_LEASE_VERSION",{enumerable:!0,get:function(){return dt.RUNTIME_LEASE_VERSION}});Object.defineProperty(_,"RUNTIME_LEASE_AUDIENCE",{enumerable:!0,get:function(){return dt.RUNTIME_LEASE_AUDIENCE}});Object.defineProperty(_,"RUNTIME_LEASE_MAX_TTL_SECONDS",{enumerable:!0,get:function(){return dt.RUNTIME_LEASE_MAX_TTL_SECONDS}});Object.defineProperty(_,"RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS",{enumerable:!0,get:function(){return dt.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS}});Object.defineProperty(_,"RUNTIME_LEASE_PURPOSE",{enumerable:!0,get:function(){return dt.RUNTIME_LEASE_PURPOSE}});Object.defineProperty(_,"RUNTIME_LEASE_SIGNING_MODES",{enumerable:!0,get:function(){return dt.RUNTIME_LEASE_SIGNING_MODES}});Object.defineProperty(_,"TEMPO_LEASE_PURPOSE",{enumerable:!0,get:function(){return dt.TEMPO_LEASE_PURPOSE}});Object.defineProperty(_,"TEMPO_LEASE_NETWORK",{enumerable:!0,get:function(){return dt.TEMPO_LEASE_NETWORK}});Object.defineProperty(_,"TEMPO_LEASE_SIGNING_MODE",{enumerable:!0,get:function(){return dt.TEMPO_LEASE_SIGNING_MODE}});Object.defineProperty(_,"issueTempoRuntimeLease",{enumerable:!0,get:function(){return dt.issueTempoRuntimeLease}});Object.defineProperty(_,"verifyTempoRuntimeLeaseChain",{enumerable:!0,get:function(){return dt.verifyTempoRuntimeLeaseChain}});Object.defineProperty(_,"prepareRuntimeDelegation",{enumerable:!0,get:function(){return dt.prepareRuntimeDelegation}});Object.defineProperty(_,"completeRuntimeDelegation",{enumerable:!0,get:function(){return dt.completeRuntimeDelegation}});Object.defineProperty(_,"issueRuntimeDelegation",{enumerable:!0,get:function(){return dt.issueRuntimeDelegation}});Object.defineProperty(_,"issueRuntimeLease",{enumerable:!0,get:function(){return dt.issueRuntimeLease}});Object.defineProperty(_,"verifyRuntimeDelegation",{enumerable:!0,get:function(){return dt.verifyRuntimeDelegation}});Object.defineProperty(_,"verifyRuntimeLeaseChain",{enumerable:!0,get:function(){return dt.verifyRuntimeLeaseChain}});var Md=Sre();Object.defineProperty(_,"RUNTIME_LEASE_REQUEST_VERSION",{enumerable:!0,get:function(){return Md.RUNTIME_LEASE_REQUEST_VERSION}});Object.defineProperty(_,"RUNTIME_LEASE_REQUEST_AUDIENCE",{enumerable:!0,get:function(){return Md.RUNTIME_LEASE_REQUEST_AUDIENCE}});Object.defineProperty(_,"RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS",{enumerable:!0,get:function(){return Md.RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS}});Object.defineProperty(_,"runtimeLeaseRequestIntentHash",{enumerable:!0,get:function(){return Md.runtimeLeaseRequestIntentHash}});Object.defineProperty(_,"createRuntimeLeaseRequestProof",{enumerable:!0,get:function(){return Md.createRuntimeLeaseRequestProof}});Object.defineProperty(_,"createRuntimeLeaseRequestProofWithSigner",{enumerable:!0,get:function(){return Md.createRuntimeLeaseRequestProofWithSigner}});Object.defineProperty(_,"verifyRuntimeLeaseRequestProof",{enumerable:!0,get:function(){return Md.verifyRuntimeLeaseRequestProof}});var q4=Pre();Object.defineProperty(_,"TAP_RUNTIME_SIGNATURE_DOMAIN",{enumerable:!0,get:function(){return q4.TAP_RUNTIME_SIGNATURE_DOMAIN}});Object.defineProperty(_,"tapRuntimeSigningMessage",{enumerable:!0,get:function(){return q4.tapRuntimeSigningMessage}});Object.defineProperty(_,"verifyTapRuntimeSignature",{enumerable:!0,get:function(){return q4.verifyTapRuntimeSignature}});var Us=Dre();Object.defineProperty(_,"WALLET_BINDING_TYP",{enumerable:!0,get:function(){return Us.WALLET_BINDING_TYP}});Object.defineProperty(_,"WALLET_BINDING_VERSION",{enumerable:!0,get:function(){return Us.WALLET_BINDING_VERSION}});Object.defineProperty(_,"WALLET_BINDING_MAX_TTL_SECONDS",{enumerable:!0,get:function(){return Us.WALLET_BINDING_MAX_TTL_SECONDS}});Object.defineProperty(_,"WALLET_BINDING_SIGNER_KIND",{enumerable:!0,get:function(){return Us.WALLET_BINDING_SIGNER_KIND}});Object.defineProperty(_,"WALLET_BINDING_DERIVATION_VERSION",{enumerable:!0,get:function(){return Us.WALLET_BINDING_DERIVATION_VERSION}});Object.defineProperty(_,"prepareWalletBinding",{enumerable:!0,get:function(){return Us.prepareWalletBinding}});Object.defineProperty(_,"completeWalletBinding",{enumerable:!0,get:function(){return Us.completeWalletBinding}});Object.defineProperty(_,"issueWalletBinding",{enumerable:!0,get:function(){return Us.issueWalletBinding}});Object.defineProperty(_,"verifyWalletBinding",{enumerable:!0,get:function(){return Us.verifyWalletBinding}});var Ane=Lre();Object.defineProperty(_,"INTENT_HASH_VERSION",{enumerable:!0,get:function(){return Ane.INTENT_HASH_VERSION}});Object.defineProperty(_,"canonicalIntentHash",{enumerable:!0,get:function(){return Ane.canonicalIntentHash}});var yi=jD();Object.defineProperty(_,"OWNERSHIP_CHALLENGE_DOMAIN_V1",{enumerable:!0,get:function(){return yi.OWNERSHIP_CHALLENGE_DOMAIN_V1}});Object.defineProperty(_,"OWNERSHIP_PROOF_JWT_TYP",{enumerable:!0,get:function(){return yi.OWNERSHIP_PROOF_JWT_TYP}});Object.defineProperty(_,"TTL_OWNERSHIP_HOURS",{enumerable:!0,get:function(){return yi.TTL_OWNERSHIP_HOURS}});Object.defineProperty(_,"MAX_TTL_OWNERSHIP_HOURS",{enumerable:!0,get:function(){return yi.MAX_TTL_OWNERSHIP_HOURS}});Object.defineProperty(_,"CHALLENGE_MAX_AGE_SEC",{enumerable:!0,get:function(){return yi.CHALLENGE_MAX_AGE_SEC}});Object.defineProperty(_,"buildOwnershipChallenge",{enumerable:!0,get:function(){return yi.buildOwnershipChallenge}});Object.defineProperty(_,"verifyOwnershipSignature",{enumerable:!0,get:function(){return yi.verifyOwnershipSignature}});Object.defineProperty(_,"issueOwnershipProof",{enumerable:!0,get:function(){return yi.issueOwnershipProof}});Object.defineProperty(_,"issueOwnershipProofWithSigner",{enumerable:!0,get:function(){return yi.issueOwnershipProofWithSigner}});Object.defineProperty(_,"attestWalletOwnership",{enumerable:!0,get:function(){return yi.attestWalletOwnership}});Object.defineProperty(_,"verifyOwnershipProof",{enumerable:!0,get:function(){return yi.verifyOwnershipProof}});Object.defineProperty(_,"walletVerifiedFromProof",{enumerable:!0,get:function(){return yi.walletVerifiedFromProof}});var Ey=fp();Object.defineProperty(_,"signJwtWithSigner",{enumerable:!0,get:function(){return Ey.signJwtWithSigner}});Object.defineProperty(_,"LocalSigner",{enumerable:!0,get:function(){return Ey.LocalSigner}});Object.defineProperty(_,"signerFromAnchorKey",{enumerable:!0,get:function(){return Ey.signerFromAnchorKey}});Object.defineProperty(_,"signerFromSignFn",{enumerable:!0,get:function(){return Ey.signerFromSignFn}});Object.defineProperty(_,"issueRegistrationWithSigner",{enumerable:!0,get:function(){return Ey.issueRegistrationWithSigner}});var Rc=Hre();Object.defineProperty(_,"SUCCESSION_JWT_TYP",{enumerable:!0,get:function(){return Rc.SUCCESSION_JWT_TYP}});Object.defineProperty(_,"KILL_SWITCH_JWT_TYP",{enumerable:!0,get:function(){return Rc.KILL_SWITCH_JWT_TYP}});Object.defineProperty(_,"issueSuccession",{enumerable:!0,get:function(){return Rc.issueSuccession}});Object.defineProperty(_,"verifySuccession",{enumerable:!0,get:function(){return Rc.verifySuccession}});Object.defineProperty(_,"issueKillSwitch",{enumerable:!0,get:function(){return Rc.issueKillSwitch}});Object.defineProperty(_,"verifyKillSwitch",{enumerable:!0,get:function(){return Rc.verifyKillSwitch}});Object.defineProperty(_,"attestationIsVoid",{enumerable:!0,get:function(){return Rc.attestationIsVoid}});Object.defineProperty(_,"KillList",{enumerable:!0,get:function(){return Rc.KillList}});var Ee=$re();Object.defineProperty(_,"AGENT_PAIRING_PROTOCOL_VERSION",{enumerable:!0,get:function(){return Ee.AGENT_PAIRING_PROTOCOL_VERSION}});Object.defineProperty(_,"AGENT_PAIRING_PROTOCOL_VERSION_V2",{enumerable:!0,get:function(){return Ee.AGENT_PAIRING_PROTOCOL_VERSION_V2}});Object.defineProperty(_,"AGENT_PAIRING_TTL_SECONDS",{enumerable:!0,get:function(){return Ee.AGENT_PAIRING_TTL_SECONDS}});Object.defineProperty(_,"AGENT_PAIRING_CODE_ALPHABET",{enumerable:!0,get:function(){return Ee.AGENT_PAIRING_CODE_ALPHABET}});Object.defineProperty(_,"AGENT_PAIRING_CODE_LENGTH",{enumerable:!0,get:function(){return Ee.AGENT_PAIRING_CODE_LENGTH}});Object.defineProperty(_,"AGENT_PAIRING_STATES",{enumerable:!0,get:function(){return Ee.AGENT_PAIRING_STATES}});Object.defineProperty(_,"AGENT_PAIRING_TERMINAL_STATES",{enumerable:!0,get:function(){return Ee.AGENT_PAIRING_TERMINAL_STATES}});Object.defineProperty(_,"isAgentPairingState",{enumerable:!0,get:function(){return Ee.isAgentPairingState}});Object.defineProperty(_,"canTransitionAgentPairing",{enumerable:!0,get:function(){return Ee.canTransitionAgentPairing}});Object.defineProperty(_,"assertAgentPairingTransition",{enumerable:!0,get:function(){return Ee.assertAgentPairingTransition}});Object.defineProperty(_,"randomPairingId",{enumerable:!0,get:function(){return Ee.randomPairingId}});Object.defineProperty(_,"randomPairingVerifier",{enumerable:!0,get:function(){return Ee.randomPairingVerifier}});Object.defineProperty(_,"pairingVerifierChallenge",{enumerable:!0,get:function(){return Ee.pairingVerifierChallenge}});Object.defineProperty(_,"randomPairingCode",{enumerable:!0,get:function(){return Ee.randomPairingCode}});Object.defineProperty(_,"normalizePairingCode",{enumerable:!0,get:function(){return Ee.normalizePairingCode}});Object.defineProperty(_,"formatPairingCode",{enumerable:!0,get:function(){return Ee.formatPairingCode}});Object.defineProperty(_,"isValidPairingCode",{enumerable:!0,get:function(){return Ee.isValidPairingCode}});Object.defineProperty(_,"pairingCodeHash",{enumerable:!0,get:function(){return Ee.pairingCodeHash}});Object.defineProperty(_,"randomPairingClaimToken",{enumerable:!0,get:function(){return Ee.randomPairingClaimToken}});Object.defineProperty(_,"pairingClaimTokenHash",{enumerable:!0,get:function(){return Ee.pairingClaimTokenHash}});Object.defineProperty(_,"pairingCodeFromClaimToken",{enumerable:!0,get:function(){return Ee.pairingCodeFromClaimToken}});Object.defineProperty(_,"pairingConfirmationCode",{enumerable:!0,get:function(){return Ee.pairingConfirmationCode}});Object.defineProperty(_,"canonicalPairingTerms",{enumerable:!0,get:function(){return Ee.canonicalPairingTerms}});Object.defineProperty(_,"canonicalPairingTermsV2",{enumerable:!0,get:function(){return Ee.canonicalPairingTermsV2}});Object.defineProperty(_,"pairingTermsHash",{enumerable:!0,get:function(){return Ee.pairingTermsHash}});Object.defineProperty(_,"pairingTermsV2Hash",{enumerable:!0,get:function(){return Ee.pairingTermsV2Hash}});Object.defineProperty(_,"pairingClaimMessage",{enumerable:!0,get:function(){return Ee.pairingClaimMessage}});Object.defineProperty(_,"pairingClaimMessageV2",{enumerable:!0,get:function(){return Ee.pairingClaimMessageV2}});Object.defineProperty(_,"pairingClaimHashV2",{enumerable:!0,get:function(){return Ee.pairingClaimHashV2}});Object.defineProperty(_,"pairingActivationMessage",{enumerable:!0,get:function(){return Ee.pairingActivationMessage}});Object.defineProperty(_,"pairingActivationMessageV2",{enumerable:!0,get:function(){return Ee.pairingActivationMessageV2}});Object.defineProperty(_,"AGENT_CAPABILITY_ATTACH_CAPABILITIES",{enumerable:!0,get:function(){return Ee.AGENT_CAPABILITY_ATTACH_CAPABILITIES}});Object.defineProperty(_,"AGENT_HANDOFF_AUTHORITIES",{enumerable:!0,get:function(){return Ee.AGENT_HANDOFF_AUTHORITIES}});Object.defineProperty(_,"AGENT_HANDOFF_COMPOUND_AUTHORITY",{enumerable:!0,get:function(){return Ee.AGENT_HANDOFF_COMPOUND_AUTHORITY}});Object.defineProperty(_,"handoffAuthorityCapabilities",{enumerable:!0,get:function(){return Ee.handoffAuthorityCapabilities}});Object.defineProperty(_,"keyRotationClaimMessageV2",{enumerable:!0,get:function(){return Ee.keyRotationClaimMessageV2}});Object.defineProperty(_,"keyRotationClaimHashV2",{enumerable:!0,get:function(){return Ee.keyRotationClaimHashV2}});Object.defineProperty(_,"agentMailCredentialClaimMessageV2",{enumerable:!0,get:function(){return Ee.agentMailCredentialClaimMessageV2}});Object.defineProperty(_,"pairingArtifactHash",{enumerable:!0,get:function(){return Ee.pairingArtifactHash}});Object.defineProperty(_,"canonicalPairingDeliveryArtifactV2",{enumerable:!0,get:function(){return Ee.canonicalPairingDeliveryArtifactV2}});Object.defineProperty(_,"pairingDeliveryArtifactV2Hash",{enumerable:!0,get:function(){return Ee.pairingDeliveryArtifactV2Hash}});Object.defineProperty(_,"pairingInstrumentCommitment",{enumerable:!0,get:function(){return Ee.pairingInstrumentCommitment}});Object.defineProperty(_,"sha256",{enumerable:!0,get:function(){return Ee.sha256}});var Fe=D0();Object.defineProperty(_,"AGENT_AUTHORITY_VERSION",{enumerable:!0,get:function(){return Fe.AGENT_AUTHORITY_VERSION}});Object.defineProperty(_,"AGENT_BUDGET_EPOCH_MODES",{enumerable:!0,get:function(){return Fe.AGENT_BUDGET_EPOCH_MODES}});Object.defineProperty(_,"AGENT_AUTHORITY_VALUATION_POLICY",{enumerable:!0,get:function(){return Fe.AGENT_AUTHORITY_VALUATION_POLICY}});Object.defineProperty(_,"AGENT_AUTHORIZATION_SCOPES",{enumerable:!0,get:function(){return Fe.AGENT_AUTHORIZATION_SCOPES}});Object.defineProperty(_,"AGENT_EXECUTION_READINESS_REASONS",{enumerable:!0,get:function(){return Fe.AGENT_EXECUTION_READINESS_REASONS}});Object.defineProperty(_,"AGENT_CHANNEL_KINDS",{enumerable:!0,get:function(){return Fe.AGENT_CHANNEL_KINDS}});Object.defineProperty(_,"AGENT_CHANNEL_ASSURANCES",{enumerable:!0,get:function(){return Fe.AGENT_CHANNEL_ASSURANCES}});Object.defineProperty(_,"AGENT_CHANNEL_STATUSES",{enumerable:!0,get:function(){return Fe.AGENT_CHANNEL_STATUSES}});Object.defineProperty(_,"AGENT_KEY_CUSTODIES",{enumerable:!0,get:function(){return Fe.AGENT_KEY_CUSTODIES}});Object.defineProperty(_,"AGENT_KEY_STATUSES",{enumerable:!0,get:function(){return Fe.AGENT_KEY_STATUSES}});Object.defineProperty(_,"USD_MICROS_PER_CENT",{enumerable:!0,get:function(){return Fe.USD_MICROS_PER_CENT}});Object.defineProperty(_,"VIC_PROCESSOR_ACTIONS",{enumerable:!0,get:function(){return Fe.VIC_PROCESSOR_ACTIONS}});Object.defineProperty(_,"authorizationScopeFacts",{enumerable:!0,get:function(){return Fe.authorizationScopeFacts}});Object.defineProperty(_,"AGENT_PAYMENT_MODE_NAMES",{enumerable:!0,get:function(){return Fe.AGENT_PAYMENT_MODE_NAMES}});Object.defineProperty(_,"AGENT_PAYMENT_SURFACES",{enumerable:!0,get:function(){return Fe.AGENT_PAYMENT_SURFACES}});Object.defineProperty(_,"AGENT_PAYMENT_RAILS",{enumerable:!0,get:function(){return Fe.AGENT_PAYMENT_RAILS}});Object.defineProperty(_,"grantPaymentRails",{enumerable:!0,get:function(){return Fe.grantPaymentRails}});Object.defineProperty(_,"WALLET_GRANT_SCOPE",{enumerable:!0,get:function(){return Fe.WALLET_GRANT_SCOPE}});Object.defineProperty(_,"defaultPayWithinBudget",{enumerable:!0,get:function(){return Fe.defaultPayWithinBudget}});Object.defineProperty(_,"canonicalAgentAuthorityGrant",{enumerable:!0,get:function(){return Fe.canonicalAgentAuthorityGrant}});Object.defineProperty(_,"canonicalPayWithinBudget",{enumerable:!0,get:function(){return Fe.canonicalPayWithinBudget}});Object.defineProperty(_,"canonicalAgentChannelDescriptor",{enumerable:!0,get:function(){return Fe.canonicalAgentChannelDescriptor}});Object.defineProperty(_,"canonicalSpendAuthorizationIntent",{enumerable:!0,get:function(){return Fe.canonicalSpendAuthorizationIntent}});Object.defineProperty(_,"centsToUsdMicros",{enumerable:!0,get:function(){return Fe.centsToUsdMicros}});Object.defineProperty(_,"isCanonicalBase64Url32",{enumerable:!0,get:function(){return Fe.isCanonicalBase64Url32}});Object.defineProperty(_,"agentAuthorityGrantHash",{enumerable:!0,get:function(){return Fe.agentAuthorityGrantHash}});Object.defineProperty(_,"spendAuthorizationIntentHash",{enumerable:!0,get:function(){return Fe.spendAuthorizationIntentHash}});Object.defineProperty(_,"walletAuthorizationRequestHash",{enumerable:!0,get:function(){return Fe.walletAuthorizationRequestHash}});Object.defineProperty(_,"usdcAtomicToUsdMicros",{enumerable:!0,get:function(){return Fe.usdcAtomicToUsdMicros}});var rWe=Jre();Object.defineProperty(_,"prepareIdentityPresenceDelegation",{enumerable:!0,get:function(){return rWe.prepareIdentityPresenceDelegation}});var Hs=P4();Object.defineProperty(_,"IDENTITY_PRESENCE_LEASE_AUDIENCE",{enumerable:!0,get:function(){return Hs.IDENTITY_PRESENCE_LEASE_AUDIENCE}});Object.defineProperty(_,"IDENTITY_PRESENCE_PURPOSE",{enumerable:!0,get:function(){return Hs.IDENTITY_PRESENCE_PURPOSE}});Object.defineProperty(_,"IDENTITY_PRESENCE_SIGNING_MODE",{enumerable:!0,get:function(){return Hs.IDENTITY_PRESENCE_SIGNING_MODE}});Object.defineProperty(_,"HOSTED_CONNECTOR_PROOF_TYP",{enumerable:!0,get:function(){return Hs.HOSTED_CONNECTOR_PROOF_TYP}});Object.defineProperty(_,"HOSTED_CONNECTOR_PROOF_TTL_SECONDS",{enumerable:!0,get:function(){return Hs.HOSTED_CONNECTOR_PROOF_TTL_SECONDS}});Object.defineProperty(_,"issueHostedConnectorProof",{enumerable:!0,get:function(){return Hs.issueHostedConnectorProof}});Object.defineProperty(_,"issueIdentityPresenceLease",{enumerable:!0,get:function(){return Hs.issueIdentityPresenceLease}});Object.defineProperty(_,"verifyHostedConnectorProof",{enumerable:!0,get:function(){return Hs.verifyHostedConnectorProof}});Object.defineProperty(_,"verifyIdentityPresenceLeaseChain",{enumerable:!0,get:function(){return Hs.verifyIdentityPresenceLeaseChain}});var Oo=R4();Object.defineProperty(_,"IDENTITY_TAP_PROFILE",{enumerable:!0,get:function(){return Oo.IDENTITY_TAP_PROFILE}});Object.defineProperty(_,"IDENTITY_TAP_PURPOSE",{enumerable:!0,get:function(){return Oo.IDENTITY_TAP_PURPOSE}});Object.defineProperty(_,"IDENTITY_TAP_LEASE_AUDIENCE",{enumerable:!0,get:function(){return Oo.IDENTITY_TAP_LEASE_AUDIENCE}});Object.defineProperty(_,"IDENTITY_TAP_LEASE_REQUEST_AUDIENCE",{enumerable:!0,get:function(){return Oo.IDENTITY_TAP_LEASE_REQUEST_AUDIENCE}});Object.defineProperty(_,"prepareIdentityTapDelegation",{enumerable:!0,get:function(){return Oo.prepareIdentityTapDelegation}});Object.defineProperty(_,"verifyIdentityTapDelegation",{enumerable:!0,get:function(){return Oo.verifyIdentityTapDelegation}});Object.defineProperty(_,"issueIdentityTapLease",{enumerable:!0,get:function(){return Oo.issueIdentityTapLease}});Object.defineProperty(_,"identityTapLeaseRequestIntentHash",{enumerable:!0,get:function(){return Oo.identityTapLeaseRequestIntentHash}});Object.defineProperty(_,"createIdentityTapLeaseRequestProof",{enumerable:!0,get:function(){return Oo.createIdentityTapLeaseRequestProof}});Object.defineProperty(_,"verifyIdentityTapLeaseRequestProof",{enumerable:!0,get:function(){return Oo.verifyIdentityTapLeaseRequestProof}});var wy=one();Object.defineProperty(_,"identityDeviceEnrollmentPreimage",{enumerable:!0,get:function(){return wy.identityDeviceEnrollmentPreimage}});Object.defineProperty(_,"prepareIdentityDeviceGateAuthorization",{enumerable:!0,get:function(){return wy.prepareIdentityDeviceGateAuthorization}});Object.defineProperty(_,"prepareIdentityHostedGateAuthorization",{enumerable:!0,get:function(){return wy.prepareIdentityHostedGateAuthorization}});Object.defineProperty(_,"IDENTITY_HOSTED_GATE_AUTHORIZATION_PURPOSES",{enumerable:!0,get:function(){return wy.IDENTITY_HOSTED_GATE_AUTHORIZATION_PURPOSES}});Object.defineProperty(_,"verifyIdentityDeviceEnrollmentProof",{enumerable:!0,get:function(){return wy.verifyIdentityDeviceEnrollmentProof}});var D4=cne();Object.defineProperty(_,"IDENTITY_TAP_SLIP_REQUEST_TYP",{enumerable:!0,get:function(){return D4.IDENTITY_TAP_SLIP_REQUEST_TYP}});Object.defineProperty(_,"validateIdentityTapSlipRequest",{enumerable:!0,get:function(){return D4.validateIdentityTapSlipRequest}});Object.defineProperty(_,"issueIdentityTapSlip",{enumerable:!0,get:function(){return D4.issueIdentityTapSlip}});var vy=j4();Object.defineProperty(_,"IDENTITY_PRESENCE_SLIP_PURPOSE",{enumerable:!0,get:function(){return vy.IDENTITY_PRESENCE_SLIP_PURPOSE}});Object.defineProperty(_,"IDENTITY_HOSTED_TAP_SLIP_PURPOSE",{enumerable:!0,get:function(){return vy.IDENTITY_HOSTED_TAP_SLIP_PURPOSE}});Object.defineProperty(_,"issueHostedPresenceIdentitySlip",{enumerable:!0,get:function(){return vy.issueHostedPresenceIdentitySlip}});Object.defineProperty(_,"issueHostedTapIdentitySlip",{enumerable:!0,get:function(){return vy.issueHostedTapIdentitySlip}});Object.defineProperty(_,"hostedPresenceAttemptId",{enumerable:!0,get:function(){return vy.hostedPresenceAttemptId}});var BS=mne();Object.defineProperty(_,"IDENTITY_HOSTED_TAP_SLIP_REQUEST_TYP",{enumerable:!0,get:function(){return BS.IDENTITY_HOSTED_TAP_SLIP_REQUEST_TYP}});Object.defineProperty(_,"validateIdentityHostedTapSlipRequest",{enumerable:!0,get:function(){return BS.validateIdentityHostedTapSlipRequest}});Object.defineProperty(_,"issueHostedTapSlipFromTicket",{enumerable:!0,get:function(){return BS.issueHostedTapSlipFromTicket}});Object.defineProperty(_,"hostedTapPayloadNamesMerchantRequest",{enumerable:!0,get:function(){return BS.hostedTapPayloadNamesMerchantRequest}});var L4=LS();Object.defineProperty(_,"identityTapSigningBytes",{enumerable:!0,get:function(){return L4.identityTapSigningBytes}});Object.defineProperty(_,"identityTapPayloadSha256",{enumerable:!0,get:function(){return L4.identityTapPayloadSha256}});Object.defineProperty(_,"parseIdentityTapSignatureBase",{enumerable:!0,get:function(){return L4.parseIdentityTapSignatureBase}});var US=_ne();Object.defineProperty(_,"IDENTITY_DEVICE_HANDOFF_AUDIENCE",{enumerable:!0,get:function(){return US.IDENTITY_DEVICE_HANDOFF_AUDIENCE}});Object.defineProperty(_,"identityDeviceProposalSha256",{enumerable:!0,get:function(){return US.identityDeviceProposalSha256}});Object.defineProperty(_,"identityDeviceHandoffIntentHash",{enumerable:!0,get:function(){return US.identityDeviceHandoffIntentHash}});Object.defineProperty(_,"verifyIdentityDeviceHandoffProof",{enumerable:!0,get:function(){return US.verifyIdentityDeviceHandoffProof}});var B4=bne();Object.defineProperty(_,"validateProtectedTapRegistryRequest",{enumerable:!0,get:function(){return B4.validateProtectedTapRegistryRequest}});Object.defineProperty(_,"protectedTapRegistrySigningBytes",{enumerable:!0,get:function(){return B4.protectedTapRegistrySigningBytes}});Object.defineProperty(_,"isProtectedTapRegistryAttentionCode",{enumerable:!0,get:function(){return B4.isProtectedTapRegistryAttentionCode}})});var Fs=g(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.AGENT_OPERATION_TRANSITION_SQL_PREDICATE=de.AGENT_OPERATION_TERMINAL_SQL_LIST=de.AGENT_OPERATION_RESUMABLE_SQL_LIST=de.AGENT_OPERATION_TERMINAL_STATES=de.AGENT_OPERATION_EVIDENCE_ELIGIBLE_STATES=de.AGENT_OPERATION_RESUMABLE_STATES=de.AGENT_OPERATION_ALLOWED_TRANSITIONS=de.AGENT_OPERATION_STATES=de.EXECUTOR_BINDING_VERSION=de.EXECUTION_EVIDENCE_VERSION=de.AGENT_OPERATION_RESULT_VERSION=de.AGENT_OPERATION_VERSION=de.canonicalJsonValue=de.canonicalJson=de.AgentOperationContractError=de.AGENT_OPERATION_CONTRACT_ERROR_CODES=de.canonicalEnvelopeJson=void 0;de.isAgentOperationTransitionAllowed=aWe;de.agentOperationIntentPreimage=cWe;de.parseAgentMoneyEconomics=Tne;de.parseAgentOperationStructure=xne;de.parseExecutionEvidence=lWe;de.parsePreparedAgentOperationStructure=fWe;de.agentOperationPopSigningInput=pWe;var ce=Ec(),Sy=Ec();Object.defineProperty(de,"canonicalEnvelopeJson",{enumerable:!0,get:function(){return Sy.canonicalEnvelopeJson}});Object.defineProperty(de,"AGENT_OPERATION_CONTRACT_ERROR_CODES",{enumerable:!0,get:function(){return Sy.AGENT_OPERATION_CONTRACT_ERROR_CODES}});Object.defineProperty(de,"AgentOperationContractError",{enumerable:!0,get:function(){return Sy.AgentOperationContractError}});Object.defineProperty(de,"canonicalJson",{enumerable:!0,get:function(){return Sy.canonicalJson}});Object.defineProperty(de,"canonicalJsonValue",{enumerable:!0,get:function(){return Sy.canonicalJsonValue}});de.AGENT_OPERATION_VERSION=1;de.AGENT_OPERATION_RESULT_VERSION=1;de.EXECUTION_EVIDENCE_VERSION=1;de.EXECUTOR_BINDING_VERSION=1;var nWe=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,iWe=/^[A-Za-z0-9_-]{43}$/,oWe=/^[a-z][a-z0-9]*(?:[._:-][a-z0-9]+)*$/,sWe=/^[A-Z][A-Z0-9]{2,11}$/,Pne=96*1024,U4=9223372036854775807n;de.AGENT_OPERATION_STATES=["claimed","reserved","dispatched","authorized","settling","committed","released","indeterminate","denied"];de.AGENT_OPERATION_ALLOWED_TRANSITIONS={claimed:["reserved","denied"],reserved:["dispatched","released","indeterminate","settling"],dispatched:["authorized","released","indeterminate","settling"],authorized:["settling","indeterminate"],settling:["committed","released","indeterminate"],committed:[],released:[],indeterminate:["settling"],denied:[]};de.AGENT_OPERATION_RESUMABLE_STATES=["claimed","reserved","dispatched"];de.AGENT_OPERATION_EVIDENCE_ELIGIBLE_STATES=["reserved","dispatched","authorized","indeterminate"];de.AGENT_OPERATION_TERMINAL_STATES=["committed","released","denied"];function aWe(e,t){return e===t||de.AGENT_OPERATION_ALLOWED_TRANSITIONS[e].includes(t)}function H4(e){return e.map(t=>`'${t}'`).join(", ")}de.AGENT_OPERATION_RESUMABLE_SQL_LIST=H4(de.AGENT_OPERATION_RESUMABLE_STATES);de.AGENT_OPERATION_TERMINAL_SQL_LIST=H4(de.AGENT_OPERATION_TERMINAL_STATES);de.AGENT_OPERATION_TRANSITION_SQL_PREDICATE=["NEW.state = OLD.state",...de.AGENT_OPERATION_STATES.filter(e=>de.AGENT_OPERATION_ALLOWED_TRANSITIONS[e].length>0).map(e=>`(OLD.state = '${e}' AND NEW.state IN (${H4(de.AGENT_OPERATION_ALLOWED_TRANSITIONS[e])}))`)].join(`
100
+ OR `);function _i(e,t,r=[]){let n=new Set([...t,...r]);if(t.some(i=>!(i in e))||Object.keys(e).some(i=>!n.has(i)))throw new ce.AgentOperationContractError("invalid_contract","contract contains missing or unknown fields")}function Sp(e,t){let r=(0,ce.bounded)(e,t,36).toLowerCase();if(!nWe.test(r))throw new ce.AgentOperationContractError("invalid_contract",`${t} must be a UUID`);return r}function Ro(e,t){let r=(0,ce.bounded)(e,t,43);if(!iWe.test(r)||!/[AEIMQUYcgkosw048]$/.test(r))throw new ce.AgentOperationContractError("invalid_contract",`${t} must be a canonical 32-byte hash`);return r}function HS(e,t){let r=(0,ce.bounded)(e,t,128);if(!oWe.test(r))throw new ce.AgentOperationContractError("invalid_contract",`${t} must be a stable lowercase token`);return r}function Ine(e,t){let r=(0,ce.bounded)(e,t,32),n=Date.parse(r);if(!Number.isFinite(n)||new Date(n).toISOString()!==r)throw new ce.AgentOperationContractError("invalid_contract",`${t} must be canonical ISO-8601`);return r}function cWe(e){let t={domain:"visa.agent-operation-intent.v1",operationId:e.operationId,idempotencyKey:e.idempotencyKey,agentId:e.agentId,runtimeId:e.runtimeId,rail:e.rail,effect:e.effect,execution:{adapter:e.execution.adapter,commitment:e.execution.commitment,payloadHash:e.execution.payloadHash},createdAt:e.createdAt,expiresAt:e.expiresAt};return(0,ce.canonicalJson)(t)}function uWe(e){let t=(0,ce.record)(e,"principal");if(t.kind==="identity_pop")return _i(t,["kind","popJwt","keyJkt"]),{kind:t.kind,popJwt:(0,ce.bounded)(t.popJwt,"popJwt",16384),keyJkt:Ro(t.keyJkt,"keyJkt")};if(t.kind==="certified_runtime_pop")return _i(t,["kind","popJwt","runtimeCertificate","rootJkt","childJkt"]),{kind:t.kind,popJwt:(0,ce.bounded)(t.popJwt,"popJwt",16384),runtimeCertificate:(0,ce.bounded)(t.runtimeCertificate,"runtimeCertificate",32768),rootJkt:Ro(t.rootJkt,"rootJkt"),childJkt:Ro(t.childJkt,"childJkt")};if(t.kind==="delegated_runtime_lease_pop"){if(_i(t,["kind","v","popJwt","delegation","lease","rootJkt","runtimeJkt"]),t.v!==2)throw new ce.AgentOperationContractError("invalid_principal","delegated runtime lease principal must use version 2");return{kind:t.kind,v:t.v,popJwt:(0,ce.bounded)(t.popJwt,"popJwt",16384),delegation:(0,ce.bounded)(t.delegation,"delegation",32768),lease:(0,ce.bounded)(t.lease,"lease",32768),rootJkt:Ro(t.rootJkt,"rootJkt"),runtimeJkt:Ro(t.runtimeJkt,"runtimeJkt")}}if(t.kind==="tap_signature")return _i(t,["kind","signature","runtimeCertificate","signedPayload"]),{kind:t.kind,signature:(0,ce.bounded)(t.signature,"signature",2048),runtimeCertificate:(0,ce.bounded)(t.runtimeCertificate,"runtimeCertificate",32768),signedPayload:Ro(t.signedPayload,"signedPayload")};throw new ce.AgentOperationContractError("invalid_principal","unsupported principal proof kind")}function Tne(e){let t=(0,ce.record)(e,"money economics");_i(t,["amountMicros","currency","merchant"]);let r=(0,ce.bounded)(t.amountMicros,"amountMicros",40);if(!/^[1-9][0-9]*$/.test(r)||BigInt(r)>U4)throw new ce.AgentOperationContractError("invalid_amount","amountMicros must be positive and canonical");let n=(0,ce.bounded)(t.currency,"currency",12);if(!sWe.test(n))throw new ce.AgentOperationContractError("invalid_currency","currency must be canonical");let i=(0,ce.record)(t.merchant,"merchant");return _i(i,["id"],["name","url"]),{amountMicros:r,currency:n,merchant:{id:(0,ce.bounded)(i.id,"merchant.id",512),...i.name===void 0?{}:{name:(0,ce.bounded)(i.name,"merchant.name",255)},...i.url===void 0?{}:{url:(0,ce.bounded)(i.url,"merchant.url",2048)}}}}function dWe(e){let t=(0,ce.record)(e,"effect");if(t.kind==="money"){_i(t,["kind","amountMicros","currency","merchant","grantId","budgetEpochId"],["maxAmountMicros"]);let r=Tne({amountMicros:t.amountMicros,currency:t.currency,merchant:t.merchant}),n;if(t.maxAmountMicros!==void 0&&(n=(0,ce.bounded)(t.maxAmountMicros,"maxAmountMicros",40),!/^[1-9][0-9]*$/.test(n)||BigInt(n)>U4))throw new ce.AgentOperationContractError("invalid_amount","maxAmountMicros must be positive and canonical");return{kind:t.kind,...r,grantId:Sp(t.grantId,"grantId"),budgetEpochId:Sp(t.budgetEpochId,"budgetEpochId"),...n===void 0?{}:{maxAmountMicros:n}}}if(t.kind==="resource")return _i(t,["kind","resource","action","audience"]),{kind:t.kind,resource:(0,ce.bounded)(t.resource,"resource",4096),action:HS(t.action,"action"),audience:(0,ce.bounded)(t.audience,"audience",255)};throw new ce.AgentOperationContractError("invalid_effect","unsupported operation effect")}function xne(e,t=Date.now()){let r=(0,ce.record)(e,"operation");if(_i(r,["v","operationId","idempotencyKey","agentId","runtimeId","rail","intentHash","principal","effect","execution","createdAt","expiresAt"]),r.v!==de.AGENT_OPERATION_VERSION)throw new ce.AgentOperationContractError("unsupported_version","unsupported operation version");let n=(0,ce.record)(r.execution,"execution");_i(n,["adapter","commitment","payloadHash","payload"]);let i=(0,ce.canonicalJsonValue)(n.payload);if(new TextEncoder().encode(JSON.stringify(i)).length>Pne)throw new ce.AgentOperationContractError("invalid_contract","execution payload is too large");let o=Ro(n.commitment,"execution.commitment"),s=Ro(n.payloadHash,"execution.payloadHash"),a=Ine(r.createdAt,"createdAt"),c=Ine(r.expiresAt,"expiresAt");if(!Number.isFinite(t)||Date.parse(a)>t+3e4||Date.parse(a)<t-5*6e4||Date.parse(c)<=t||Date.parse(c)<=Date.parse(a)||Date.parse(c)-Date.parse(a)>10*6e4)throw new ce.AgentOperationContractError("invalid_window","operation validity window is not currently usable");let u={v:de.AGENT_OPERATION_VERSION,operationId:Sp(r.operationId,"operationId"),idempotencyKey:(0,ce.bounded)(r.idempotencyKey,"idempotencyKey",255),agentId:Sp(r.agentId,"agentId"),runtimeId:Sp(r.runtimeId,"runtimeId"),rail:HS(r.rail,"rail"),intentHash:Ro(r.intentHash,"intentHash"),principal:uWe(r.principal),effect:dWe(r.effect),execution:{adapter:HS(n.adapter,"execution.adapter"),commitment:o,payloadHash:s,payload:i},createdAt:a,expiresAt:c};if(u.rail==="wallet:x402"&&u.effect.kind==="money"&&u.effect.merchant.url===void 0)throw new ce.AgentOperationContractError("invalid_contract","merchant.url is required for wallet:x402 operations");if(u.principal.kind==="tap_signature"&&u.principal.signedPayload!==u.intentHash)throw new ce.AgentOperationContractError("intent_mismatch","TAP signedPayload must equal the universal operation intentHash");return u}function lWe(e){let t=(0,ce.record)(e,"evidence");if(_i(t,["v","operationId","adapter","outcome","artifactHash","providerReference","proof"],["settledMicros"]),t.v!==de.EXECUTION_EVIDENCE_VERSION||t.outcome!=="committed"&&t.outcome!=="released")throw new ce.AgentOperationContractError("invalid_evidence","unsupported evidence version or outcome");let r;if(t.settledMicros!==void 0){if(r=(0,ce.bounded)(t.settledMicros,"settledMicros",40),!/^(?:0|[1-9][0-9]*)$/.test(r)||BigInt(r)>U4)throw new ce.AgentOperationContractError("invalid_evidence","settledMicros is not canonical");if(t.outcome==="released"&&r!=="0")throw new ce.AgentOperationContractError("settlement_amount_invalid","released evidence must settle zero")}let n=(0,ce.canonicalJsonValue)(t.proof);if(new TextEncoder().encode(JSON.stringify(n)).length>Pne)throw new ce.AgentOperationContractError("invalid_evidence","evidence proof is too large");return{v:de.EXECUTION_EVIDENCE_VERSION,operationId:Sp(t.operationId,"operationId"),adapter:HS(t.adapter,"adapter"),outcome:t.outcome,artifactHash:Ro(t.artifactHash,"artifactHash"),...r===void 0?{}:{settledMicros:r},providerReference:(0,ce.bounded)(t.providerReference,"providerReference",255),proof:n}}function fWe(e,t=Date.now()){let r=(0,ce.record)(e,"prepared operation");_i(r,["operationId","idempotencyKey","agentId","runtimeId","rail","intentHash","effect","execution","createdAt","expiresAt"]);let{v:n,principal:i,...o}=xne({...r,v:1,principal:{kind:"identity_pop",popJwt:"unsigned",keyJkt:"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}},t);return o}function pWe(e){let t=r=>btoa(String.fromCharCode(...new TextEncoder().encode(JSON.stringify(r)))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return`${t({alg:"EdDSA",kid:e.childJkt,typ:"visa-agent-pop+jwt"})}.${t({cnf:{jwk:{kty:e.childPublicJwk.kty,crv:e.childPublicJwk.crv,x:e.childPublicJwk.x}},nonce:e.operationId,aud:"visa-agent-operations:v1",iat:e.issuedAtSec,int:e.intentHash,...e.runtimeCertificate?{rkc:e.runtimeCertificate}:{}})}`}});var cie=g((Ldt,aie)=>{"use strict";var mWe=Object.create,VS=Object.defineProperty,gWe=Object.getOwnPropertyDescriptor,Une=Object.getOwnPropertyNames,hWe=Object.getPrototypeOf,yWe=Object.prototype.hasOwnProperty,_We=(e,t)=>function(){try{return t||(0,e[Une(e)[0]])((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},bWe=(e,t)=>{for(var r in t)VS(e,r,{get:t[r],enumerable:!0})},Hne=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Une(t))!yWe.call(e,i)&&i!==r&&VS(e,i,{get:()=>t[i],enumerable:!(n=gWe(t,i))||n.enumerable});return e},EWe=(e,t,r)=>(r=e!=null?mWe(hWe(e)):{},Hne(t||!e||!e.__esModule?VS(r,"default",{value:e,enumerable:!0}):r,e)),wWe=e=>Hne(VS({},"__esModule",{value:!0}),e),vWe=_We({"../shared/dist/canonical-contract.js"(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.CanonicalJsonError=e.CANONICAL_OPAQUE_ID_MAX_BYTES=e.CANONICAL_OPAQUE_ID_RE=e.CANONICAL_OPAQUE_ID_PATTERN=void 0,e.utf8ByteLength=n,e.isCanonicalText=i,e.compareCanonicalKeys=o,e.isCanonicalOpaqueId=s,e.assertCanonicalOpaqueId=a,e.canonicalJsonExact=d,e.CANONICAL_OPAQUE_ID_PATTERN="^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$",e.CANONICAL_OPAQUE_ID_RE=new RegExp(e.CANONICAL_OPAQUE_ID_PATTERN),e.CANONICAL_OPAQUE_ID_MAX_BYTES=128;var t=/[\u0000-\u001f\u007f\u2028\u2029]/,r=new TextEncoder;function n(l){return r.encode(l).length}function i(l,m){return typeof l=="string"&&l.length>0&&n(l)<=m&&l.trim()===l&&l.normalize("NFC")===l&&!t.test(l)}function o(l,m){let p=r.encode(l),h=r.encode(m),y=Math.min(p.length,h.length);for(let b=0;b<y;b+=1)if(p[b]!==h[b])return p[b]-h[b];return p.length-h.length}function s(l){return typeof l=="string"&&n(l)<=e.CANONICAL_OPAQUE_ID_MAX_BYTES&&e.CANONICAL_OPAQUE_ID_RE.test(l)}function a(l,m="value"){if(!s(l))throw new Error(`${m} must be a canonical opaque id (max 128 ASCII bytes)`)}var c=/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,u=class extends Error{constructor(l){super(l),this.name="CanonicalJsonError"}};e.CanonicalJsonError=u;function d(l,m=0){if(m>16)throw new u("nesting is deeper than 16");if(l===null||typeof l=="boolean")return JSON.stringify(l);if(typeof l=="string"){if(c.test(l))throw new u("text is not valid Unicode");return JSON.stringify(l)}if(typeof l=="number"){if(!Number.isSafeInteger(l)||Object.is(l,-0))throw new u("numbers must be whole and at most 2^53 - 1; put amounts and decimals in strings");return JSON.stringify(l)}if(Array.isArray(l)){if(l.length>1024)throw new u("an array has more than 1024 items");return`[${l.map(h=>d(h,m+1)).join(",")}]`}if(typeof l!="object"||Object.getPrototypeOf(l)!==Object.prototype)throw new u("only JSON objects, arrays, strings, whole numbers and booleans");let p=Object.keys(l);if(p.length>512)throw new u("an object has more than 512 keys");for(let h of p)if(!i(h,128))throw new u("keys must be non-empty trimmed NFC text of at most 128 bytes");return`{${p.sort(o).map(h=>`${JSON.stringify(h)}:${d(l[h],m+1)}`).join(",")}}`}}}),Fne={};bWe(Fne,{AGENT_AUTHORITY_VALUATION_POLICY:()=>JS,AGENT_AUTHORITY_VERSION:()=>Py,AGENT_AUTHORIZATION_SCOPES:()=>iL,AGENT_BUDGET_EPOCH_MODES:()=>zne,AGENT_CHANNEL_ASSURANCES:()=>Qne,AGENT_CHANNEL_KINDS:()=>Xne,AGENT_CHANNEL_STATUSES:()=>Zne,AGENT_EXECUTION_READINESS_REASONS:()=>tze,AGENT_KEY_CUSTODIES:()=>rze,AGENT_KEY_STATUSES:()=>nze,AGENT_PAYMENT_MODE_NAMES:()=>QWe,AGENT_PAYMENT_RAILS:()=>z4,AGENT_PAYMENT_SURFACES:()=>W4,USD_MICROS_PER_CENT:()=>nL,VIC_PROCESSOR_ACTIONS:()=>ZWe,WALLET_GRANT_SCOPE:()=>Yne,agentAuthorityGrantHash:()=>yze,authorizationScopeFacts:()=>mze,canonicalAgentAuthorityGrant:()=>oie,canonicalAgentChannelDescriptor:()=>hze,canonicalPayWithinBudget:()=>iie,canonicalSpendAuthorizationIntent:()=>aL,centsToUsdMicros:()=>fze,defaultPayWithinBudget:()=>eze,grantPaymentRails:()=>oL,isCanonicalBase64Url32:()=>xy,spendAuthorizationIntentHash:()=>sie,usdcAtomicToUsdMicros:()=>pze,walletAuthorizationRequestHash:()=>_ze});aie.exports=wWe(Fne);var SWe=e=>e/2**32|0,AWe=e=>e>>>0;function IWe(e,t,r,n){let i=SWe(r),o=AWe(r);e.setUint32(t,n?o:i,n),e.setUint32(t+4,n?i:o,n)}function One(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var J4=e=>e?`"${e}" `:"";function PWe(e,t=""){if(typeof e!="number")throw new TypeError(J4(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(J4(t)+"expected integer >= 0, got "+e);return e}function $ne(e,t,r=""){if(One(e)&&(t===void 0||e.length===t))return e;t!==void 0&&PWe(t,"length");let n=One(e),i=t!==void 0?` of length ${t}`:"",o=n?`length=${e.length}`:`type=${typeof e}`,s=J4(r)+"expected Uint8Array"+i+", got "+o;throw n?new RangeError(s):new TypeError(s)}var TWe=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},Rne=(e,t)=>{TWe(e,t);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function Cne(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function xWe(e,t){$ne(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw new RangeError('"output" expected length >= '+r)}function Nne(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function F4(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Co(e,t){return e<<32-t|e>>>t}function OWe(e,t,r="opts"){return Rne(e,"defaults"),t!==void 0&&Rne(t,r),Object.assign(Object.create(null),e,t)}function RWe(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=OWe({},t,"info");let r=(i,o)=>e(o).update(i).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=i=>e(i),Object.assign(r,t),Object.freeze(r)}var CWe=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function NWe(e,t,r){return e&t^~e&r}function kWe(e,t,r){return e&t^e&r^t&r}var jWe=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=F4(this.buffer)}update(e){Cne(this),$ne(e);let{view:t,buffer:r,blockLen:n}=this,i=e.length,o=!1;for(let s=0;s<i;){let a=Math.min(n-this.pos,i-s);if(a===n){let c=F4(e);for(;n<=i-s;s+=n)this.process(c,s);o=!0;continue}r.set(s===0&&a===i?e:e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===n&&(this.process(t,0),this.pos=0,o=!0)}return this.length+=e.length,o&&this.roundClean(),this}digestInto(e){Cne(this),xWe(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,t.fill(0,o),this.padOffset>n-o&&(this.process(r,0),t.fill(0)),IWe(r,n-8,this.length*8,i),this.process(r,0),this.roundClean();let s=e===t?r:F4(e),a=this.outputLen,c=a/4,u=this.get();if(a%4||c>u.length)throw new Error("invalid outputLen");for(let d=0;d<c;d++)s.setUint32(4*d,u[d],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:n,destroyed:i,pos:o}=this;return e.destroyed=i,e.finished=n,e.length=r,e.pos=o,o&&e.buffer.set(t),e}clone(){return this._cloneInto()}},MWe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),qWe=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Nc=new Uint32Array(64),DWe=class extends jWe{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:r,D:n,E:i,F:o,G:s,H:a}=this;return[e,t,r,n,i,o,s,a]}set(e,t,r,n,i,o,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=s|0,this.H=a|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let d=0;d<16;d++,t+=4)Nc[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let l=Nc[d-15],m=Nc[d-2],p=Co(l,7)^Co(l,18)^l>>>3,h=Co(m,17)^Co(m,19)^m>>>10;Nc[d]=h+Nc[d-7]+p+Nc[d-16]|0}let{A:r,B:n,C:i,D:o,E:s,F:a,G:c,H:u}=this;for(let d=0;d<64;d++){let l=Co(s,6)^Co(s,11)^Co(s,25),m=u+l+NWe(s,a,c)+qWe[d]+Nc[d]|0,h=(Co(r,2)^Co(r,13)^Co(r,22))+kWe(r,n,i)|0;u=c,c=a,a=s,s=o+m|0,o=i,i=n,n=r,r=m+h|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,i,o,s,a,c,u)}roundClean(){Nne(Nc)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Nne(this.buffer)}},LWe=class extends DWe{constructor(){super(32,MWe)}},Z4=RWe(()=>new LWe,CWe(1)),Jne=EWe(vWe()),Q4=Object.freeze,Ip=0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,V4=0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,FS=0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,G4=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,K4=0x6666666666666666666666666666666666666666666666666666666666666658n,$S=Ip-1n,BWe=Q4({p:Ip,n:V4,h:8n,a:$S,d:FS,Gx:G4,Gy:K4}),Vne=32,kne=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&e.BYTES_PER_ELEMENT===1,GS=(e,t,r="")=>{if(kne(e)&&(t===void 0||e.length===t))return e;let n=kne(e),i=t!==void 0?` of length ${t}`:"",o=n?`length=${e.length}`:`type=${typeof e}`,s=(r?`"${r}" `:"")+"expected Uint8Array"+i+", got "+o;throw n?new RangeError(s):new TypeError(s)},UWe=(e,t="",r)=>Uint8Array.from(GS(e,r,t)),Gne=(e,t)=>e.toString(16).padStart(t,"0"),eL=e=>{let t="";for(let r of GS(e))t+=Gne(r,2);return t},tL=e=>{let t="hex invalid";if(typeof e!="string")throw new TypeError(t);if(e.length%2||!/^[\da-f]*$/i.test(e))throw new RangeError(t);let r=new Uint8Array(e.length/2);for(let n=0,i=0;n<r.length;n++,i+=2){let o=e.charCodeAt(i),s=e.charCodeAt(i+1);r[n]=((o&15)+(o>>6)*9)*16+(s&15)+(s>>6)*9}return r},HWe=(...e)=>{let t=0;for(let i of e)t+=GS(i).length;let r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return r},FWe=(e=Vne)=>{let t=globalThis?.crypto;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined, consider polyfill");return t.getRandomValues(new Uint8Array(e))},qd=(e,t,r,n="bad number: out of range")=>{if(typeof e!="bigint")throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},_t=(e,t=Ip)=>(e%=t)>=0n?e:t+e,jne=(1n<<255n)-1n,Z=e=>{if(e<0n)throw new RangeError("negative coordinate");let t=(e>>255n)*19n+(e&jne);return t=(t>>255n)*19n+(t&jne),t%Ip},Kne=(e,t)=>{if(e===0n)throw new Error("invert: expected non-zero number");if(t<=1n)throw new Error("invert: expected modulus > 1, got "+t);let r=_t(e,t),n=t,i=0n,o=1n;for(;r!==0n;){let a=n/r,c=n-r*a,u=i-o*a;n=r,r=c,i=o,o=u}if(n!==1n)throw new Error("invert: does not exist");return _t(i,t)},$4=e=>{if(e instanceof Oy)return e;throw new TypeError("Point expected")},Wne=2n**256n,Oy=class Dd{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=Wne;this.X=qd(t,0n,o),this.Y=qd(r,0n,o),this.Z=qd(n,1n,o),this.T=qd(i,0n,o),Q4(this)}static CURVE(){return BWe}static fromAffine(t){return new Dd(t.x,t.y,1n,Z(t.x*t.y))}static fromBytes(t,r=!1){let n=UWe(t,"point",Vne),i=n[31];n[31]=i&-129;let o=JWe(n);r||qd(o,0n,Ip);let s=Z(o*o),a=_t(s-1n),c=Z(FS*s+1n),{isValid:u,value:d}=GWe(a,c);if(!u)throw new Error("bad point: y not sqrt");let l=!!(i&128);if(!r&&d===0n&&l)throw new Error("bad point: x==0, isLastByteOdd");return l!==!!(d&1n)&&(d=_t(-d)),new Dd(d,o,1n,Z(d*o))}static fromHex(t,r){return Dd.fromBytes(tL(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=$S,r=FS,n=this;if(n.is0())throw new Error("bad point: ZERO");let{X:i,Y:o,Z:s,T:a}=n,c=Z(i*i),u=Z(o*o),d=Z(s*s),l=Z(d*d),m=Z(c*t),p=Z(d*(m+u)),h=_t(l+Z(r*Z(c*u)));if(p!==h)throw new Error("bad point: equation left != right (1)");let y=Z(i*o),b=Z(s*a);if(y!==b)throw new Error("bad point: equation left != right (2)");return this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=$4(t);return Z(r*a)===Z(o*i)&&Z(n*a)===Z(s*i)}is0(){return this.equals(Ld)}negate(){return new Dd(_t(-this.X),this.Y,this.Z,_t(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=$S,o=Z(t*t),s=Z(r*r),a=Z(2n*n*n),c=Z(i*o),u=_t(t+r),d=_t(Z(u*u)-o-s),l=_t(c+s),m=_t(l-a),p=_t(c-s),h=Z(d*m),y=Z(l*p),b=Z(d*p),v=Z(m*l);return new Dd(h,y,v,b)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=$4(t),d=$S,l=FS,m=Z(r*s),p=Z(n*a),h=Z(Z(o*l)*u),y=Z(i*c),b=_t(Z(_t(r+n)*_t(s+a))-m-p),v=_t(y-h),A=_t(y+h),E=_t(p-Z(d*m)),S=Z(b*v),I=Z(A*E),T=Z(b*E),x=Z(v*A);return new Dd(S,I,x,T)}subtract(t){return this.add($4(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(qd(t,1n,V4),!r&&this.is0()))return Ld;if(t===1n)return this;if(this.equals(Iy))return WWe(t).p;let n=Ld,i=Iy,o=this;for(let s=0;r?s<256:t>0n;s++)t&1n?n=n.add(o):r&&(i=i.add(o)),o=o.double(),t>>=1n;return n}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:r,Z:n}=this;if(this.equals(Ld))return{x:0n,y:1n};let i=Kne(n,Ip);if(Z(n*i)!==1n)throw new Error("invalid inverse");return{x:Z(t*i),y:Z(r*i)}}toBytes(){let{x:t,y:r}=this.toAffine(),n=$We(r);return n[31]|=t&1n?128:0,n}toHex(){return eL(this.toBytes())}clearCofactor(){return this.multiply(8n,!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return this.multiply(V4/2n,!1).double().add(this).is0()}},Iy=new Oy(G4,K4,1n,_t(G4*K4)),Ld=new Oy(0n,1n,1n,0n);Oy.BASE=Iy;Oy.ZERO=Ld;var $We=e=>tL(Gne(qd(e,0n,Wne),64)).reverse(),JWe=e=>BigInt("0x"+eL(Uint8Array.from(GS(e)).reverse())),No=(e,t)=>{let r=e;for(;t-- >0;)r=Z(r*r);return r},VWe=e=>{let t=Z(e*e),r=Z(t*e),n=Z(No(r,2)*r),i=Z(No(n,1)*e),o=Z(No(i,5)*i),s=Z(No(o,10)*o),a=Z(No(s,20)*s),c=Z(No(a,40)*a),u=Z(No(c,80)*c),d=Z(No(u,80)*c),l=Z(No(d,10)*o);return Z(No(l,2)*e)},Mne=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,GWe=(e,t)=>{let r=Z(t*Z(t*t)),n=Z(Z(r*r)*t),i=VWe(Z(e*n)),o=Z(e*Z(r*i)),s=Z(t*Z(o*o)),a=o,c=Z(o*Mne),u=s===e,d=s===_t(-e),l=s===_t(-e*Mne);return u&&(o=a),(d||l)&&(o=c),(_t(o)&1n)===1n&&(o=_t(-o)),{isValid:u||d,value:o}},rL=Q4({bytesToHex:eL,hexToBytes:tL,concatBytes:HWe,mod:_t,invert:Kne,randomBytes:FWe}),KWe=()=>{let e=[],t=Iy,r;for(let n=0;n<33;n++){r=t,e.push(r);for(let i=1;i<128;i++)r=r.add(t),e.push(r);t=r.double()}return e},qne=void 0,Dne=(e,t)=>{let r=t.negate();return e?r:t},WWe=e=>{let t=qne||(qne=KWe()),r=Ld,n=Iy;for(let i=0;i<33;i++){let o=Number(e&255n);e>>=8n,o>128&&(o-=256,e+=1n);let s=i*128,a=s+Math.abs(o)-1,c=i%2!==0,u=o<0;o===0?n=n.add(Dne(c,t[s])):r=r.add(Dne(u,t[a]))}if(e!==0n)throw new Error("invalid wnaf");return{p:r,f:n}},Mdt=rL.bytesToHex,qdt=rL.hexToBytes,Ddt=rL.concatBytes;function zWe(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function YWe(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function KS(e){return zWe(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function XWe(e){let t=e.length%4===0?0:4-e.length%4,r=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return YWe(r)}var Py=2,zne=["new","continue"],ZWe=["charge_and_capture","authorize_only"],nL=10000n,JS="nominal_usd_usdc_parity",iL=["card:vic","wallet:x402"],Yne="wallet:x402",W4=["connector","laptop"],z4=["card:vic","wallet:tempo","wallet:x402"];function oL(e){let t=new Set(e);return e.includes(Yne)&&t.add("wallet:tempo"),[...t].sort((r,n)=>Ty(r,n))}var QWe={ask:"Ask me each time",budget:"Pay within my budget"};function eze(e,t){return e!=="laptop"?[]:oL(t).map(r=>({surface:"laptop",scope:r}))}var tze=["hosted_identity_key_migration_required","identity_key_expired","identity_key_rotated","identity_key_lost","identity_key_inactive","agent_inactive","current_grant_missing","current_grant_replaced","current_grant_expired","current_grant_inactive","required_scope_missing","managed_wallet_authority_unverified","authority_projection_unknown","authorization_version_unsupported","identity_key_custody_unsupported","owner_eligibility_required"],rze=["runtime","turnkey","server_encrypted","server_kms","external"],nze=["pending","active","retired","revoked","lost"],Xne=["dotvisa","tap","email","messaging"],Zne=["provisioning","active","needs_attention","suspended","disabled"],Qne=["routing_only","provider_verified","agent_key_bound"],ize=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,oze=/^[A-Za-z0-9_-]{43}$/,sze=/^(?:0|[1-9][0-9]*)$/,aze=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})$/,eie=/[\u0000-\u001f\u007f]/,cze=2147483647,tie=9223372036854775807n,Lne=100,uze=512,Bne=32,dze=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.visa$/,rie=/^0x[0-9a-f]{40}$/,sL=new TextEncoder;function Ty(e,t){return(0,Jne.compareCanonicalKeys)(e,t)}function Ud(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xy(e){if(typeof e!="string"||!oze.test(e))return!1;try{let t=XWe(e);return t.byteLength===32&&KS(t)===e}catch{return!1}}function Hd(e,t,r){let n=Object.keys(t).filter(i=>!r.has(i));if(n.length>0)throw new Error(`${e} contains unknown field(s): ${n.sort().join(", ")}`)}function lze(e,t){if(typeof t!="string"||!ize.test(t))throw new Error(`${e} must be a UUID`)}function Sn(e,t){return lze(e,t),t.toLowerCase()}function Y4(e,t){if(!(0,Jne.isCanonicalOpaqueId)(t))throw new Error(`${e} must be a non-empty opaque id (max 128 chars)`)}function Ap(e,t){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let r=aze.exec(t);if(!r)throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let[,n,i,o,s,a,c]=r,u=Number(n),d=Number(i),l=Number(o),m=Number(s),p=Number(a),h=Number(c),y=new Date(0);if(y.setUTCFullYear(u,d-1,l),y.setUTCHours(m,p,h,0),u===0||y.getUTCFullYear()!==u||y.getUTCMonth()!==d-1||y.getUTCDate()!==l||y.getUTCHours()!==m||y.getUTCMinutes()!==p||y.getUTCSeconds()!==h)throw new Error(`${e} must be a valid calendar timestamp`);let b=Date.parse(t);if(!Number.isFinite(b))throw new Error(`${e} must be a valid ISO timestamp`);return new Date(b).toISOString()}function Bd(e,t,r=!1){if(typeof t!="string"||!sze.test(t))throw new Error(`${e} must be a canonical non-negative integer micros string`);if(!r&&t==="0")throw new Error(`${e} must be positive`);if(BigInt(t)>tie)throw new Error(`${e} exceeds the PostgreSQL BIGINT range`);return t}function nie(e,t){if(typeof t!="number"||!Number.isInteger(t)||t<=0||t>cze)throw new Error(`${e} must be a positive PostgreSQL INTEGER`);return t}function X4(e,t){if(typeof t!="string")throw new Error(`${e} must be a string`);if(eie.test(t))throw new Error(`${e} must be a bounded non-empty payee without control characters`);let r=t.normalize("NFC").trim();if(r.length===0||r.length>uze)throw new Error(`${e} must be a bounded non-empty payee without control characters`);return r}function Ay(e,t,r){if(typeof t!="string")throw new Error(`${e} must be a string`);if(eie.test(t))throw new Error(`${e} must be bounded, non-empty text without control characters`);let n=t.normalize("NFC").trim();if(n.length===0||n.length>r)throw new Error(`${e} must be bounded, non-empty text without control characters`);return n}function ko(e,t){return typeof e=="string"&&t.includes(e)}function fze(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("cents must be a non-negative safe integer");let t=BigInt(e)*nL;if(t>tie)throw new Error("cents exceed the PostgreSQL BIGINT micros range");return t.toString()}function pze(e){return Bd("amountAtomic",e,!0)}function mze(e){if(e==="card:vic")return{scope:e,paymentRail:"card",protocol:null,instrumentKind:"vic_card"};if(e==="wallet:x402")return{scope:e,paymentRail:"stablecoin",protocol:"x402",instrumentKind:"turnkey_wallet"};throw new Error(`unknown authorization scope: ${String(e)}`)}function gze(e,t,r){if(!Ud(e))throw new Error("keyLink must be an object");Hd("channel keyLink",e,new Set(["keyId","agentId","purpose","fingerprint"]));let n=Sn("keyLink.keyId",e.keyId),i=Sn("keyLink.agentId",e.agentId);if(i!==t)throw new Error("keyLink.agentId must match the channel agentId");if(!ko(e.purpose,["identity","email_signing"]))throw new Error("channel keyLink cannot use a wallet-signing key");if(r==="email"&&e.purpose!=="email_signing")throw new Error("an agent-key-bound email channel requires an email_signing key");if((r==="tap"||r==="dotvisa")&&e.purpose!=="identity")throw new Error(`${r} requires an identity key`);let o=Ay("keyLink.fingerprint",e.fingerprint,255);if(!xy(o))throw new Error(`an ${e.purpose} key link fingerprint must be a 43-char RFC 7638 JKT`);return{keyId:n,agentId:i,purpose:e.purpose,fingerprint:o}}function hze(e){if(!Ud(e))throw new Error("agent channel descriptor must be an object");Hd("agent channel descriptor",e,new Set(["channelId","agentId","kind","status","assurance","address","providerRef","keyLink","capabilities","createdAt","verifiedAt","disabledAt"])),Y4("channelId",e.channelId);let t=Sn("agentId",e.agentId);if(!ko(e.kind,Xne))throw new Error("invalid channel kind");if(!ko(e.status,Zne))throw new Error("invalid channel status");if(!ko(e.assurance,Qne))throw new Error("invalid channel assurance");let r=e.address===void 0?void 0:Ay("address",e.address,320),n=e.kind==="dotvisa"?r?.toLowerCase():r;if((e.kind==="email"||e.kind==="dotvisa")&&n===void 0)throw new Error(`${e.kind} channels require an address`);if(e.kind==="dotvisa"&&n!==void 0&&!dze.test(n))throw new Error("dotvisa channel address must be a canonical lowercase .visa address");if(e.kind==="tap"&&n!==void 0)throw new Error("tap channels use providerRef and cannot claim a public address");let i=e.providerRef===void 0?void 0:Ay("providerRef",e.providerRef,255);if(!Array.isArray(e.capabilities)||e.capabilities.length===0||e.capabilities.length>Bne)throw new Error(`capabilities must contain between 1 and ${Bne} entries`);let o=e.capabilities.map(l=>Ay("capability",l,64));if(new Set(o).size!==o.length)throw new Error("capabilities must not repeat");let s=Ap("createdAt",e.createdAt),a=e.verifiedAt===void 0?void 0:Ap("verifiedAt",e.verifiedAt),c=e.disabledAt===void 0?void 0:Ap("disabledAt",e.disabledAt);if(a!==void 0&&Date.parse(a)<Date.parse(s))throw new Error("verifiedAt cannot be before createdAt");if(c!==void 0&&Date.parse(c)<Date.parse(s))throw new Error("disabledAt cannot be before createdAt");if(c!==void 0&&a!==void 0&&Date.parse(c)<Date.parse(a))throw new Error("disabledAt cannot be before verifiedAt");if(e.status==="disabled"!=(c!==void 0))throw new Error("status='disabled' and disabledAt must be set together");let u={channelId:e.channelId,agentId:t,kind:e.kind,status:e.status,...n!==void 0?{address:n}:{},...i!==void 0?{providerRef:i}:{},capabilities:[...o].sort(Ty),createdAt:s,...c!==void 0?{disabledAt:c}:{}};if(e.assurance==="routing_only"){if(a!==void 0||e.keyLink!==void 0)throw new Error("routing_only channels cannot claim verification or an agent key link");return{...u,assurance:"routing_only"}}if(i===void 0||a===void 0)throw new Error(`${e.assurance} channels require providerRef and verifiedAt`);if(e.assurance==="provider_verified"){if(e.keyLink!==void 0)throw new Error("provider_verified channels cannot claim an agent key link");return{...u,assurance:"provider_verified",providerRef:i,verifiedAt:a}}let d=gze(e.keyLink,t,e.kind);return{...u,assurance:"agent_key_bound",providerRef:i,verifiedAt:a,keyLink:d}}function iie(e,t){if(!Array.isArray(e)||e.length>W4.length*z4.length)throw new Error("payWithinBudget must be an array of surface/scope entries");let r=e.map(i=>{if(!Ud(i))throw new Error("payWithinBudget entry must be an object");if(Hd("payWithinBudget entry",i,new Set(["surface","scope"])),!ko(i.surface,W4))throw new Error("payWithinBudget surface must be laptop or connector");if(!ko(i.scope,z4))throw new Error("payWithinBudget scope is not a payment rail");if(!oL(t).includes(i.scope))throw new Error(i.scope==="wallet:tempo"?"payWithinBudget wallet:tempo needs the wallet:x402 grant scope":"payWithinBudget scope must be present in grant scopes");return{surface:i.surface,scope:i.scope}}),n=r.map(({surface:i,scope:o})=>`${i}:${o}`);if(new Set(n).size!==n.length)throw new Error("payWithinBudget must not repeat");return[...r].sort((i,o)=>Ty(`${i.surface}:${i.scope}`,`${o.surface}:${o.scope}`))}function oie(e){if(!Ud(e))throw new Error("agent authority grant must be an object");if(Hd("agent authority grant",e,new Set(["v","grantId","agentId","version","budgetEpochId","budgetEpochMode","status","currency","valuationPolicy","totalMicros","perTransactionMicros","dailyMicros","scopes","payWithinBudget","payeeConstraints","effectiveAt","expiresAt","supersedesGrantId"])),e.v!==Py)throw new Error("grant.v must be 2");let t=Sn("grantId",e.grantId),r=Sn("agentId",e.agentId),n=nie("version",e.version),i=Sn("budgetEpochId",e.budgetEpochId);if(!ko(e.budgetEpochMode,zne))throw new Error("budgetEpochMode must be new or continue");if(!ko(e.status,["active","superseded","revoked"]))throw new Error("invalid grant status");if(e.currency!=="USD")throw new Error("currency must be 'USD'");if(e.valuationPolicy!==JS)throw new Error(`valuationPolicy must be '${JS}'`);let o=Bd("totalMicros",e.totalMicros),s=Bd("perTransactionMicros",e.perTransactionMicros);if(BigInt(s)>BigInt(o))throw new Error("perTransactionMicros cannot exceed totalMicros");let a=e.dailyMicros===void 0?void 0:Bd("dailyMicros",e.dailyMicros);if(a!==void 0){if(BigInt(a)>BigInt(o))throw new Error("dailyMicros cannot exceed totalMicros");if(BigInt(s)>BigInt(a))throw new Error("perTransactionMicros cannot exceed dailyMicros")}if(!Array.isArray(e.scopes)||e.scopes.length===0)throw new Error("scopes must be a non-empty array");let c=e.scopes.map(p=>{if(!Ud(p))throw new Error("grant scope must be an object");if(Hd("grant scope",p,new Set(["scope","totalMicros","perTransactionMicros","instrumentRef"])),!ko(p.scope,iL))throw new Error("invalid authorization scope");let h=p.totalMicros===void 0?void 0:Bd("scope.totalMicros",p.totalMicros),y=p.perTransactionMicros===void 0?void 0:Bd("scope.perTransactionMicros",p.perTransactionMicros);if(h!==void 0&&BigInt(h)>BigInt(o))throw new Error("scope.totalMicros cannot exceed the aggregate totalMicros");if(y!==void 0&&BigInt(y)>BigInt(s))throw new Error("scope.perTransactionMicros cannot exceed the aggregate perTransactionMicros");if(h!==void 0&&y!==void 0&&BigInt(y)>BigInt(h))throw new Error("scope.perTransactionMicros cannot exceed scope.totalMicros");let b=Ay("scope.instrumentRef",p.instrumentRef,255);return{scope:p.scope,...h!==void 0?{totalMicros:h}:{},...y!==void 0?{perTransactionMicros:y}:{},instrumentRef:b}});if(new Set(c.map(({scope:p})=>p)).size!==c.length)throw new Error("scopes must not repeat");let u=e.payWithinBudget===void 0?void 0:iie(e.payWithinBudget,c.map(({scope:p})=>p)),d;if(e.payeeConstraints!==void 0){if(!Array.isArray(e.payeeConstraints)||e.payeeConstraints.length===0||e.payeeConstraints.length>Lne)throw new Error(`payeeConstraints must contain between 1 and ${Lne} entries`);if(d=e.payeeConstraints.map(h=>{if(!Ud(h))throw new Error("payee constraint must be an object");if(Hd("payee constraint",h,new Set(["scope","kind","canonicalId"])),h.scope==="card:vic"&&h.kind==="processor_merchant_id")return{scope:h.scope,kind:h.kind,canonicalId:X4("payee constraint canonicalId",h.canonicalId)};if(h.scope==="wallet:x402"&&h.kind==="evm_address"){let y=X4("payee constraint canonicalId",h.canonicalId).toLowerCase();if(!rie.test(y))throw new Error("wallet payee constraint canonicalId must be an EVM address");return{scope:h.scope,kind:h.kind,canonicalId:y}}throw new Error("payee constraint scope/kind combination is invalid")}),d.some(h=>!c.some(({scope:y})=>y===h.scope)))throw new Error("payee constraint scope must be present in grant scopes");let p=d.map(({scope:h,kind:y,canonicalId:b})=>`${h}:${y}:${b}`);if(new Set(p).size!==p.length)throw new Error("payeeConstraints must not repeat after normalization")}let l=Ap("effectiveAt",e.effectiveAt),m=Ap("expiresAt",e.expiresAt);if(Date.parse(m)<=Date.parse(l))throw new Error("expiresAt must be after effectiveAt");if(e.supersedesGrantId!==void 0&&Sn("supersedesGrantId",e.supersedesGrantId)===t)throw new Error("a grant cannot supersede itself");return{v:Py,grantId:t,agentId:r,version:n,budgetEpochId:i,budgetEpochMode:e.budgetEpochMode,status:e.status,currency:"USD",valuationPolicy:JS,totalMicros:o,perTransactionMicros:s,...a!==void 0?{dailyMicros:a}:{},scopes:[...c].sort((p,h)=>Ty(p.scope,h.scope)),...u!==void 0?{payWithinBudget:u}:{},...d!==void 0?{payeeConstraints:[...d].sort((p,h)=>Ty(`${p.scope}:${p.kind}:${p.canonicalId}`,`${h.scope}:${h.kind}:${h.canonicalId}`))}:{},effectiveAt:l,expiresAt:m,...e.supersedesGrantId!==void 0?{supersedesGrantId:Sn("supersedesGrantId",e.supersedesGrantId)}:{}}}function yze(e){let t=oie(e),{status:r,...n}=t;return KS(Z4(sL.encode(`visa-agent-authority-grant:v2:${JSON.stringify(n)}`)))}function aL(e){if(!Ud(e))throw new Error("spend authorization intent must be an object");if(Hd("spend authorization intent",e,new Set(["v","authorizationId","agentId","keyJkt","grantId","grantVersion","budgetEpochId","scope","amountMicros","currency","payee","intentId","economicIntentId","settlementHash","settlementExpiresAt"])),e.v!==Py)throw new Error("intent.v must be 2");let t=Sn("authorizationId",e.authorizationId),r=Sn("agentId",e.agentId);if(!xy(e.keyJkt))throw new Error("keyJkt must be a 43-char RFC 7638 thumbprint");let n=Sn("grantId",e.grantId),i=nie("grantVersion",e.grantVersion),o=Sn("budgetEpochId",e.budgetEpochId);if(!ko(e.scope,iL))throw new Error("invalid authorization scope");let s=Bd("amountMicros",e.amountMicros);if(e.scope==="card:vic"&&BigInt(s)%nL!==0n)throw new Error("card:vic amountMicros must represent a whole number of card cents");if(e.currency!=="USD")throw new Error("currency must be 'USD'");let a=X4("payee",e.payee),c=e.scope==="wallet:x402"?a.toLowerCase():a;if(e.scope==="wallet:x402"&&!rie.test(c))throw new Error("wallet:x402 payee must be an EVM address");if(Y4("intentId",e.intentId),Y4("economicIntentId",e.economicIntentId),!xy(e.settlementHash))throw new Error("settlementHash is required and must be a 32-byte base64url commitment");let u=Ap("settlementExpiresAt",e.settlementExpiresAt);return{v:Py,authorizationId:t,agentId:r,keyJkt:e.keyJkt,grantId:n,grantVersion:i,budgetEpochId:o,scope:e.scope,amountMicros:s,currency:"USD",payee:c,intentId:e.intentId,economicIntentId:e.economicIntentId,settlementHash:e.settlementHash,settlementExpiresAt:u}}function sie(e){let t=aL(e),r=JSON.stringify({v:t.v,authorizationId:t.authorizationId,agentId:t.agentId,keyJkt:t.keyJkt,grantId:t.grantId,grantVersion:t.grantVersion,budgetEpochId:t.budgetEpochId,scope:t.scope,amountMicros:t.amountMicros,currency:t.currency,payee:t.payee,intentId:t.intentId,economicIntentId:t.economicIntentId,settlementHash:t.settlementHash,settlementExpiresAt:t.settlementExpiresAt});return KS(Z4(sL.encode(`visa-agent-spend-authorization:v2:${r}`)))}function _ze(e){let t=aL(e.intent),r=Sn("walletApiKeyId",e.walletApiKeyId),n=Sn("runtimeSessionId",e.runtimeSessionId);if(e.executionChannel!=="cli"&&e.executionChannel!=="mcp")throw new Error("executionChannel must be cli or mcp");if(!xy(e.resourceCommitment))throw new Error("resourceCommitment must be a 32-byte base64url commitment");let i=JSON.stringify({v:1,intentHash:sie(t),walletApiKeyId:r,runtimeSessionId:n,executionChannel:e.executionChannel,resourceCommitment:e.resourceCommitment});return KS(Z4(sL.encode(`visa-wallet-authorization-request:v1:${i}`)))}});var mie=g(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.FINANCIAL_REVOCATION_TYPE=Ae.FinancialProofError=Ae.FINANCIAL_REQUEST_MAX_BYTES=Ae.FINANCIAL_JWS_MAX_BYTES=Ae.FINANCIAL_APPROVAL_TYPE=Ae.FINANCIAL_APPROVAL_AUDIENCE=void 0;Ae.parseFinancialCanonicalJson=Ny;Ae.parseCardDisclosureConsent=die;Ae.parseFinancialOwnerApproval=cL;Ae.financialRootJkt=XS;Ae.prepareFinancialOwnerApproval=uL;Ae.verifyFinancialOwnerApproval=lie;Ae.completeFinancialOwnerApproval=vze;Ae.parseFinancialOwnerChallengeView=Sze;Ae.parseFinancialOwnerRevocation=dL;Ae.prepareFinancialOwnerRevocation=fie;Ae.verifyFinancialOwnerRevocation=pie;Ae.completeFinancialOwnerRevocation=Aze;var uie=cie(),kc=Ed(),bze=fm(),Ry=Fs();Ae.FINANCIAL_APPROVAL_AUDIENCE="urn:visa:authority:financial";Ae.FINANCIAL_APPROVAL_TYPE="visa-financial-grant-approval+jwt";Ae.FINANCIAL_JWS_MAX_BYTES=16384;Ae.FINANCIAL_REQUEST_MAX_BYTES=262144;var Eze=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Js=new TextEncoder,zS=new TextDecoder("utf-8",{fatal:!0}),wze=["v","purpose","audience","approvalId","challenge","ownerPrincipalId","associationId","associationVersion","agentId","rootJkt","grantHash","previousGrantId","previousGrantVersion","iat","exp"],YS=class extends Error{constructor(t){super(t),this.name="FinancialProofError"}};Ae.FinancialProofError=YS;function xe(e){throw new YS(e)}function $s(e,t){if(!e||typeof e!="object"||Array.isArray(e))return xe("Expected a closed object");let r=e;return Object.keys(r).length!==t.length||t.some(n=>!Object.hasOwn(r,n))?xe("Unexpected or missing field"):r}function jo(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function Cy(e){return typeof e=="string"&&Eze.test(e)}function Hi(e,t){if(typeof e!="string"||!/^[A-Za-z0-9_-]+$/.test(e))return xe("Invalid base64url");let r=new Uint8Array((0,kc.base64UrlToBytes)(e));return(0,kc.bytesToBase64Url)(r)!==e||t!==void 0&&r.length!==t?xe("Noncanonical base64url"):r}function WS(e){if(typeof e=="string")for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(++t);n>=56320&&n<=57343||xe("Invalid Unicode")}else r>=56320&&r<=57343&&xe("Invalid Unicode")}else if(Array.isArray(e))for(let t of e)WS(t);else if(e&&typeof e=="object")for(let[t,r]of Object.entries(e))WS(t),WS(r)}function Ny(e,t=Ae.FINANCIAL_REQUEST_MAX_BYTES){if(Js.encode(e).length>t)return xe("Financial input too large");let r;try{r=JSON.parse(e)}catch{return xe("Invalid JSON")}return WS(r),(0,Ry.canonicalEnvelopeJson)(r)!==e?xe("Noncanonical JSON"):r}function die(e){let t=$s(e,["v","runtimeId","mode"]);return t.v!==1||!Cy(t.runtimeId)||t.mode!=="private"&&t.mode!=="agent_history"?xe("Invalid card disclosure consent"):{v:1,runtimeId:t.runtimeId,mode:t.mode}}function cL(e){let t=e?.v,r=$s(e,[...wze,...t===2?["cardDisclosure"]:[]]);if(r.v!==1&&r.v!==2||r.purpose!=="financial.grant.approve"||r.audience!==Ae.FINANCIAL_APPROVAL_AUDIENCE)return xe("Wrong financial approval profile");for(let n of["approvalId","ownerPrincipalId","associationId","agentId"])if(!Cy(r[n]))return xe("Invalid approval identity");for(let n of["challenge","rootJkt","grantHash"])Hi(r[n],32);return!jo(r.associationVersion)||!jo(r.iat)||!jo(r.exp)||r.exp<=r.iat||r.exp-r.iat>300?xe("Invalid approval version or window"):(r.previousGrantId===null?r.previousGrantVersion!==null:!Cy(r.previousGrantId)||!jo(r.previousGrantVersion))?xe("Invalid grant predecessor"):{...r,...r.v===2?{cardDisclosure:die(r.cardDisclosure)}:{}}}async function XS(e){let t=$s(e,["kty","crv","x"]);return t.kty!=="OKP"||t.crv!=="Ed25519"?xe("Expected owner Ed25519 root"):(Hi(t.x,32),(0,bze.computeJkt)(t))}function uL(e,t){let r=cL(e),n=(0,uie.canonicalAgentAuthorityGrant)(t);if(n.status!=="active"||n.agentId!==r.agentId||(0,uie.agentAuthorityGrantHash)(n)!==r.grantHash)return xe("Displayed grant does not match approval");if(r.v===2&&!n.scopes.some(s=>s.scope==="card:vic"))return xe("Card disclosure requires a card spending scope");let i={alg:"EdDSA",typ:Ae.FINANCIAL_APPROVAL_TYPE,kid:r.rootJkt},o=`${(0,kc.bytesToBase64Url)(Js.encode((0,Ry.canonicalJson)(i)))}.${(0,kc.bytesToBase64Url)(Js.encode((0,Ry.canonicalJson)(r)))}`;return{statement:r,grant:n,signingInput:o}}async function lie(e,t,r){if(typeof e!="string"||Js.encode(e).length>Ae.FINANCIAL_JWS_MAX_BYTES)return xe("Financial proof too large");let n=e.split(".");if(n.length!==3)return xe("Invalid compact JWS");let i=$s(Ny(zS.decode(Hi(n[0])),Ae.FINANCIAL_JWS_MAX_BYTES),["alg","typ","kid"]),o=cL(Ny(zS.decode(Hi(n[1])),Ae.FINANCIAL_JWS_MAX_BYTES));if(i.alg!=="EdDSA"||i.typ!==Ae.FINANCIAL_APPROVAL_TYPE||i.kid!==o.rootJkt||await XS(t)!==o.rootJkt)return xe("Wrong owner approval key or purpose");if(!jo(r)||o.iat>r+5||r>=o.exp)return xe("Owner approval expired or not yet valid");let s=await crypto.subtle.importKey("raw",Hi(t.x,32),{name:"Ed25519"},!1,["verify"]);return await crypto.subtle.verify("Ed25519",s,Hi(n[2],64),Js.encode(`${n[0]}.${n[1]}`))?o:xe("Invalid owner signature")}async function vze(e,t,r,n,i){if(n.length!==64)return xe("Invalid owner signature length");let{signingInput:o}=uL(e,t),s=`${o}.${(0,kc.bytesToBase64Url)(n)}`;return await lie(s,r,i),s}async function Sze(e){let t=$s(e,["v","statement","grant","root","projection"]);if(t.v!==1)return xe("Unknown owner review version");let{statement:r,grant:n}=uL(t.statement,t.grant),i=$s(t.root,["organizationId","rootKeyId","publicJwk"]);for(let s of["organizationId","rootKeyId"])if(typeof i[s]!="string"||!/^[-_A-Za-z0-9]{1,256}$/.test(i[s]))return xe("Invalid protected root coordinates");if(await XS(i.publicJwk)!==r.rootJkt)return xe("Protected root does not match owner approval");let o=$s(t.projection,["agentId","ownerPublicId"]);return o.agentId!==r.agentId||!Cy(o.ownerPublicId)||o.ownerPublicId===r.ownerPrincipalId?xe("Invalid protected owner projection"):{v:1,statement:r,grant:n,root:{organizationId:i.organizationId,rootKeyId:i.rootKeyId,publicJwk:{...i.publicJwk}},projection:{agentId:r.agentId,ownerPublicId:o.ownerPublicId}}}Ae.FINANCIAL_REVOCATION_TYPE="visa-financial-grant-revocation+jwt";function dL(e){let t=$s(e,["v","purpose","audience","approvalId","ownerPrincipalId","associationId","associationVersion","agentId","rootJkt","grantId","grantVersion","grantHash","iat","exp"]);if(t.v!==1||t.purpose!=="financial.grant.revoke"||t.audience!==Ae.FINANCIAL_APPROVAL_AUDIENCE)return xe("Wrong financial revocation profile");for(let r of["approvalId","ownerPrincipalId","associationId","agentId","grantId"])if(!Cy(t[r]))return xe("Invalid revocation identity");for(let r of["rootJkt","grantHash"])Hi(t[r],32);return!jo(t.associationVersion)||!jo(t.grantVersion)||!jo(t.iat)||!jo(t.exp)||t.exp<=t.iat||t.exp-t.iat>300?xe("Invalid revocation version or window"):{...t}}function fie(e){let t=dL(e),r={alg:"EdDSA",typ:Ae.FINANCIAL_REVOCATION_TYPE,kid:t.rootJkt};return{statement:t,signingInput:`${(0,kc.bytesToBase64Url)(Js.encode((0,Ry.canonicalJson)(r)))}.${(0,kc.bytesToBase64Url)(Js.encode((0,Ry.canonicalJson)(t)))}`}}async function pie(e,t,r){if(typeof e!="string"||Js.encode(e).length>Ae.FINANCIAL_JWS_MAX_BYTES)return xe("Financial proof too large");let n=e.split(".");if(n.length!==3)return xe("Invalid compact JWS");let i=$s(Ny(zS.decode(Hi(n[0])),Ae.FINANCIAL_JWS_MAX_BYTES),["alg","typ","kid"]),o=dL(Ny(zS.decode(Hi(n[1])),Ae.FINANCIAL_JWS_MAX_BYTES));if(i.alg!=="EdDSA"||i.typ!==Ae.FINANCIAL_REVOCATION_TYPE||i.kid!==o.rootJkt||await XS(t)!==o.rootJkt)return xe("Wrong owner revocation key or purpose");if(!jo(r)||o.iat>r+5||r>=o.exp)return xe("Owner revocation expired or not yet valid");let s=await crypto.subtle.importKey("raw",Hi(t.x,32),{name:"Ed25519"},!1,["verify"]);return await crypto.subtle.verify("Ed25519",s,Hi(n[2],64),Js.encode(`${n[0]}.${n[1]}`))?o:xe("Invalid owner signature")}async function Aze(e,t,r,n){if(r.length!==64)return xe("Invalid owner signature length");let i=`${fie(e).signingInput}.${(0,kc.bytesToBase64Url)(r)}`;return await pie(i,t,n),i}});var hL=g(An=>{"use strict";Object.defineProperty(An,"__esModule",{value:!0});An.FINANCIAL_DEVICE_OPERATIONS_AUDIENCE=An.FINANCIAL_DEVICE_ENROLLMENT_AUDIENCE=An.WALLET_DEVICE_HANDOFF_AUDIENCE=An.CARD_DEVICE_HANDOFF_AUDIENCE=void 0;An.assertFinancialDevicePair=Pze;An.financialDeviceProposalHash=fL;An.financialDeviceOperationsRequestHash=Tze;An.financialDeviceEnrollmentChallengeHash=xze;var pL=fm(),mL=Ed(),ZS=Fs(),Ize=mie(),lL=TS();function Pze(e,t){if(fL(e),fL(t),e.v!==1||t.v!==2||e.agentId!==t.agentId||e.associationId!==t.associationId||e.associationVersion!==t.associationVersion||e.rootJkt!==t.rootJkt||e.requestId===t.requestId||e.runtimeId===t.runtimeId||e.publicJwk.x===t.publicJwk.x)throw new Error("financial_device_pair_invalid")}An.CARD_DEVICE_HANDOFF_AUDIENCE="visa:financial:card-device-handoff:v1";An.WALLET_DEVICE_HANDOFF_AUDIENCE="visa:financial:wallet-device-handoff:v1";function fL(e){let t=["v","purpose","requestId","associationId","associationVersion","agentId","runtimeId","rootJkt","publicJwk"];if(e?.v===2&&t.push("rail"),!e||Object.keys(e).sort().join(",")!==t.sort().join(",")||!(e.v===1||e.v===2&&e.rail==="card:vic")||e.purpose!=="financial.runtime.device.proposal"||![e.requestId,e.associationId,e.runtimeId].every(r=>typeof r=="string"&&gL.test(r))||typeof e.agentId!="string"||!e.agentId||e.agentId.length>256||!Number.isSafeInteger(e.associationVersion)||e.associationVersion<1||!(0,lL.isCanonicalBase64Url32)(e.rootJkt)||!e.publicJwk||Object.keys(e.publicJwk).sort().join(",")!=="crv,kty,x"||e.publicJwk.crv!=="Ed25519"||e.publicJwk.kty!=="OKP"||!(0,lL.isCanonicalBase64Url32)(e.publicJwk.x))throw new Error("financial_device_proposal_invalid");return(0,mL.bytesToBase64Url)((0,pL.sha256)(new TextEncoder().encode((0,ZS.canonicalJson)(e))))}An.FINANCIAL_DEVICE_ENROLLMENT_AUDIENCE="visa:financial:device-enrollment:v1";An.FINANCIAL_DEVICE_OPERATIONS_AUDIENCE="visa:financial:device-operations:v1";function Tze(e){let t=["v","purpose","requestId","agentId","runtimeId","limit"];if(!e||typeof e!="object"||Object.keys(e).sort().join(",")!==t.sort().join(",")||e.v!==1||e.purpose!=="financial.wallet.operations.read"||![e.requestId,e.agentId,e.runtimeId].every(r=>typeof r=="string"&&gL.test(r))||!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>50)throw new Error("financial_device_operations_request_invalid");return(0,mL.bytesToBase64Url)((0,pL.sha256)(new TextEncoder().encode((0,ZS.canonicalJson)(e))))}var gie=["v","purpose","requestId","associationId","associationVersion","runtimeId","runtimeGeneration","childJkt","preparedCertificate","preparedDelegation","expiresAt"],gL=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function xze(e){let t=(0,Ize.parseFinancialCanonicalJson)((0,ZS.canonicalJson)(e));if(!t||Array.isArray(t)||Object.keys(t).length!==gie.length||gie.some(r=>!Object.hasOwn(t,r))||t.v!==1||t.purpose!=="financial.runtime.device.enroll"||!["requestId","associationId","runtimeId"].every(r=>typeof t[r]=="string"&&gL.test(t[r]))||!["associationVersion","runtimeGeneration","expiresAt"].every(r=>Number.isSafeInteger(t[r])&&t[r]>0)||!(0,lL.isCanonicalBase64Url32)(t.childJkt))throw new Error("financial_device_challenge_invalid");for(let r of["preparedCertificate","preparedDelegation"]){let n=t[r];if(!n||Array.isArray(n)||Object.keys(n).sort().join(",")!=="claims,signingInput"||typeof n.signingInput!="string"||n.signingInput.length>16384||!n.claims||typeof n.claims!="object"||Array.isArray(n.claims))throw new Error("financial_device_challenge_invalid")}return(0,mL.bytesToBase64Url)((0,pL.sha256)(new TextEncoder().encode((0,ZS.canonicalJson)(t))))}});var eA=g(QS=>{"use strict";Object.defineProperty(QS,"__esModule",{value:!0});QS.parsePurchaseTerms=hie;QS.purchaseTermsPreimage=Cze;var De=Ec(),Oze=Fs();function Pp(e,t){if(Object.keys(e).sort().join(",")!==[...t].sort().join(","))throw new De.AgentOperationContractError("invalid_contract","purchase terms fields are not canonical")}function hie(e){let t=(0,De.record)(e,"purchase terms"),r=t.profile==="exact_card_checkout_v1";if(Pp(t,["v","profile","alternatives",...r?["checkout","disclosureMode",...t.merchantCountryCode===void 0?[]:["merchantCountryCode"]]:[]]),t.v!==1||typeof t.profile!="string"||!["url_resource_v1","approved_x402_request_v1","exact_card_checkout_v1"].includes(String(t.profile)))throw new De.AgentOperationContractError("unsupported_version","unsupported purchase terms profile");if(!Array.isArray(t.alternatives)||t.alternatives.length<1||t.alternatives.length>2)throw new De.AgentOperationContractError("invalid_contract","purchase requires one or two exact rail alternatives");let n=t.profile==="approved_x402_request_v1";if(n&&t.alternatives.length!==1)throw new De.AgentOperationContractError("invalid_contract","request-bound purchase requires one wallet alternative");let i=t.alternatives.map(o=>{let s=(0,De.record)(o,"purchase alternative"),a=(0,Oze.parseAgentMoneyEconomics)(s.economics),c=(0,De.bounded)(a.merchant.url,"purchase resource URL",2048),u;try{u=new URL(c)}catch{throw new De.AgentOperationContractError("invalid_contract","purchase resource URL is invalid")}if(u.protocol!=="https:"||u.username||u.password||u.hash)throw new De.AgentOperationContractError("invalid_contract","purchase requires an HTTPS resource without credentials or fragment");if(s.rail==="wallet:x402"){Pp(s,["rail","economics","network","asset","payee",...n?["requestHash"]:[]]);let d=n?(0,De.bounded)(s.requestHash,"request hash",43):void 0;if(d!==void 0&&!/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/.test(d))throw new De.AgentOperationContractError("invalid_contract","invalid request hash");let l=(0,De.bounded)(s.network,"network",64),m=(0,De.bounded)(s.asset,"asset",128),p=(0,De.bounded)(s.payee,"payee",42);if(!/^eip155:[1-9][0-9]{0,15}$/.test(l)||!new RegExp(`^${l}/erc20:0x[0-9a-f]{40}$`).test(m)||!/^0x[0-9a-f]{40}$/.test(p)||a.currency!=="USDC")throw new De.AgentOperationContractError("invalid_contract","invalid exact wallet economic coordinates");return{rail:s.rail,economics:a,network:l,asset:m,payee:p,...d?{requestHash:d}:{}}}if(s.rail==="card:vic"&&!n){if(Pp(s,["rail","economics","processorAction","captureMode"]),s.processorAction!=="charge_and_capture"||s.captureMode!=="exact"||a.currency!=="USD"||BigInt(a.amountMicros)%10000n!==0n)throw new De.AgentOperationContractError("invalid_contract","purchase card profile requires exact whole-cent capture");return{rail:s.rail,economics:a,processorAction:"charge_and_capture",captureMode:"exact"}}throw new De.AgentOperationContractError("invalid_contract","unsupported purchase rail")});if(new Set(i.map(o=>o.rail)).size!==i.length)throw new De.AgentOperationContractError("invalid_contract","purchase rail alternatives must be unique");if(i.sort((o,s)=>o.rail<s.rail?-1:o.rail>s.rail?1:0),r){if(i.length!==1||i[0].rail!=="card:vic"||!i[0].economics.merchant.name)throw new De.AgentOperationContractError("invalid_contract","exact checkout requires one card alternative");if(t.disclosureMode!=="private"&&t.disclosureMode!=="agent_history")throw new De.AgentOperationContractError("invalid_contract","unsupported card disclosure mode");if(t.merchantCountryCode!==void 0&&(typeof t.merchantCountryCode!="string"||!/^[A-Z]{2}$/.test(t.merchantCountryCode)))throw new De.AgentOperationContractError("invalid_contract","invalid merchant country");return{v:1,profile:"exact_card_checkout_v1",...t.merchantCountryCode===void 0?{}:{merchantCountryCode:t.merchantCountryCode},alternatives:i,checkout:Rze(t.checkout,i[0].economics.amountMicros),disclosureMode:t.disclosureMode}}return{v:1,profile:t.profile,alternatives:i}}function Rze(e,t){let r=(0,De.record)(e,"checkout");Pp(r,["id","revision","source","expiresAt","items","taxMicros","shippingMicros","discountMicros","fulfillment","customerHash"]);let n=()=>{throw new De.AgentOperationContractError("invalid_contract","invalid exact card checkout")},i=l=>((typeof l!="string"||!/^(0|[1-9][0-9]{0,17})$/.test(l)||BigInt(l)%10000n!==0n)&&n(),l),o=l=>((typeof l!="string"||!/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/.test(l))&&n(),l);(r.source!=="runtime_observed"||typeof r.expiresAt!="string"||!Number.isFinite(Date.parse(r.expiresAt))||new Date(r.expiresAt).toISOString()!==r.expiresAt||!Array.isArray(r.items)||r.items.length<1||r.items.length>100)&&n();let s=r.items.map(l=>{let m=(0,De.record)(l,"checkout item");return Pp(m,["id","name","quantity","totalMicros"]),(!Number.isSafeInteger(m.quantity)||Number(m.quantity)<1||Number(m.quantity)>1e6)&&n(),{id:(0,De.bounded)(m.id,"checkout item ID",256),name:(0,De.bounded)(m.name,"checkout item name",512),quantity:m.quantity,totalMicros:i(m.totalMicros)}});new Set(s.map(l=>l.id)).size!==s.length&&n();let a=i(r.taxMicros),c=i(r.shippingMicros),u=i(r.discountMicros);s.reduce((l,m)=>l+BigInt(m.totalMicros),0n)+BigInt(a)+BigInt(c)-BigInt(u)!==BigInt(t)&&n();let d=(0,De.record)(r.fulfillment,"checkout fulfillment");return Pp(d,["method","detailsHash"]),{id:(0,De.bounded)(r.id,"checkout ID",256),revision:(0,De.bounded)(r.revision,"checkout revision",256),source:"runtime_observed",expiresAt:r.expiresAt,items:s,taxMicros:a,shippingMicros:c,discountMicros:u,fulfillment:{method:(0,De.bounded)(d.method,"fulfillment method",256),detailsHash:o(d.detailsHash)},customerHash:o(r.customerHash)}}function Cze(e){return(0,De.canonicalJson)({domain:"visa.purchase-terms.v1",terms:hie(e)})}});var bie=g($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.PURCHASE_RESOURCE_AUDIENCE=$n.PURCHASE_OBSERVATIONS=void 0;$n.parsePurchaseReceipt=jze;$n.parsePurchaseResourceRequest=_ie;$n.purchaseResourceRequestHash=Mze;var Nze=require("node:crypto"),Mo=Ec(),kze=eA(),yie=DD();$n.PURCHASE_OBSERVATIONS=["credential_delivered","submission_started","buyer_action_required","order_reported","submission_failed"];function jze(e,t){let r=(0,Mo.record)(e,"purchase receipt"),n=(0,Mo.record)(r.outcome,"purchase outcome");if(!t||r.operationId!==t||typeof r.credentialIssued!="boolean"||!yie.ACCOUNT_OPERATION_OUTCOMES.includes(n.status)||!yie.ACCOUNT_OPERATION_PROOF_LEVELS.includes(n.proofLevel)||typeof n.final!="boolean"||!Array.isArray(r.observations)||r.observations.length>$n.PURCHASE_OBSERVATIONS.length||r.observations.some(o=>!$n.PURCHASE_OBSERVATIONS.includes(o))||new Set(r.observations).size!==r.observations.length)throw new Mo.AgentOperationContractError("invalid_contract","invalid purchase receipt");let i=r.refusal===void 0?void 0:(0,Mo.record)(r.refusal,"refusal");if(i!==void 0&&(!Number.isSafeInteger(i.providerStatus)||Number(i.providerStatus)<100||Number(i.providerStatus)>999||typeof i.providerCode!="string"||!/^[a-z0-9_]{1,64}$/.test(i.providerCode)||n.status!=="failed"||n.final!==!0||r.credentialIssued!==!1))throw new Mo.AgentOperationContractError("invalid_contract","invalid purchase refusal");return{operationId:t,credentialIssued:r.credentialIssued,outcome:{status:n.status,proofLevel:n.proofLevel,final:n.final},observations:r.observations,...i?{refusal:{providerStatus:Number(i.providerStatus),providerCode:i.providerCode}}:{}}}$n.PURCHASE_RESOURCE_AUDIENCE="visa:purchase-resource:v1";function _ie(e){let t=(0,Mo.record)(e,"purchase request"),r=()=>{throw new Mo.AgentOperationContractError("invalid_contract","invalid purchase request")};(t.v!==1||typeof t.action!="string"||!["create","retrieve","cancel"].includes(t.action))&&r();let n=["v","action","requestId","agentId","runtimeId",...t.action==="create"?["requestKey","terms"]:["purchaseId"],...t.action==="retrieve"&&t.include!==void 0?["include"]:[],...t.action==="retrieve"&&t.observation!==void 0?["observation"]:[]];Object.keys(t).sort().join(",")!==n.sort().join(",")&&r(),t.include!==void 0&&t.include!=="card"&&r();let i;if(t.observation!==void 0){t.include!==void 0&&r();let s=(0,Mo.record)(t.observation,"purchase observation");(Object.keys(s).sort().join(",")!=="attemptId,kind,termsHash"||!$n.PURCHASE_OBSERVATIONS.includes(s.kind)||typeof s.attemptId!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(s.attemptId)||typeof s.termsHash!="string"||!/^[A-Za-z0-9_-]{43}$/.test(s.termsHash))&&r(),i=s}for(let s of["requestId","agentId","runtimeId",...t.action==="create"?[]:["purchaseId"]])(typeof t[s]!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(t[s]))&&r();let o={v:1,requestId:t.requestId,agentId:t.agentId,runtimeId:t.runtimeId};if(t.action==="create"){let s=(0,kze.parsePurchaseTerms)(t.terms);return(s.profile!=="exact_card_checkout_v1"||s.alternatives.length!==1||s.alternatives[0].rail!=="card:vic")&&r(),{...o,action:"create",requestKey:(0,Mo.bounded)(t.requestKey,"purchase request key",256),terms:s}}return{...o,action:t.action,purchaseId:t.purchaseId,...t.action==="retrieve"&&t.include==="card"?{include:"card"}:{},...i?{observation:i}:{}}}function Mze(e){return(0,Nze.createHash)("sha256").update((0,Mo.canonicalJson)({domain:$n.PURCHASE_RESOURCE_AUDIENCE,request:_ie(e)})).digest("base64url")}});var wie=g(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});Fi.PURCHASE_TERMS_INPUT_SCHEMA=Fi.PURCHASE_MERCHANT_COUNTRY_SCHEMA=Fi.PURCHASE_REQUEST_KEY_SCHEMA=Fi.purchaseSchemaObject=void 0;var jc={type:"string",minLength:1},tA={type:"string",pattern:"^(0|[1-9][0-9]{0,13}0000)$",description:"Canonical nonnegative whole-cent USD micros; one cent is 10000. No leading zeros."},qze={type:"string",pattern:"^[1-9][0-9]{0,14}0000$",description:"Positive exact final USD total in whole-cent micros, no greater than 9223372036854775807. Must equal the sum of item totalMicros plus taxMicros and shippingMicros minus discountMicros."},Eie={type:"string",pattern:"^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$"},Dze=(e,t=Object.keys(e))=>({type:"object",additionalProperties:!1,properties:e,required:t});Fi.purchaseSchemaObject=Dze;var Fd=Fi.purchaseSchemaObject;Fi.PURCHASE_REQUEST_KEY_SCHEMA={...jc,maxLength:256,description:"Optional stable retry key; otherwise derived from the exact terms. Changing keys cannot create a second purchase for the same checkout."};Fi.PURCHASE_MERCHANT_COUNTRY_SCHEMA={type:"string",pattern:"^[A-Z]{2}$",description:"Actual two-letter merchant country. Do not infer it from the currency."};Fi.PURCHASE_TERMS_INPUT_SCHEMA=Fd({v:{const:1},profile:{const:"exact_card_checkout_v1"},merchantCountryCode:{type:"string",pattern:"^[A-Z]{2}$"},disclosureMode:{const:"agent_history"},alternatives:{type:"array",minItems:1,maxItems:1,items:Fd({rail:{const:"card:vic"},processorAction:{const:"charge_and_capture"},captureMode:{const:"exact"},economics:Fd({amountMicros:qze,currency:{const:"USD"},merchant:Fd({id:{...jc,maxLength:512},name:{...jc,maxLength:255},url:{type:"string",format:"uri",pattern:"^https://[^/#?@]+(?:[/?][^#]*)?$",maxLength:2048,description:"HTTPS checkout URL with no username, password or fragment."}},["name","url"])},["amountMicros","merchant"])},["economics"])},checkout:Fd({id:{...jc,maxLength:256},revision:{...jc,maxLength:256},source:{const:"runtime_observed"},expiresAt:{type:"string",format:"date-time",pattern:"^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$",description:"Exact UTC ISO instant with milliseconds and Z, as produced by Date.toISOString(), for example 2026-09-17T12:00:00.000Z. Use the final quote expiry, at most 24 hours ahead; preserve it unchanged on retry."},items:{type:"array",minItems:1,maxItems:100,items:Fd({id:{...jc,maxLength:256},name:{...jc,maxLength:512},quantity:{type:"integer",minimum:1,maximum:1e6},totalMicros:{...tA,description:"This line total already includes quantity. Each item ID must be unique."}})},taxMicros:tA,shippingMicros:tA,discountMicros:tA,fulfillment:Fd({method:{...jc,maxLength:256},detailsHash:{...Eie,description:"SHA-256 commitment to the exact private fulfillment snapshot. Keep its nonce and address in the host."}}),customerHash:{...Eie,description:"SHA-256 commitment to the exact private customer snapshot. Never pass an address or card number here."}},["id","revision","expiresAt","items","taxMicros","shippingMicros","discountMicros","fulfillment","customerHash"])},["alternatives","checkout"])});var bL=g($e=>{"use strict";var Lze=$e&&$e.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),rA=$e&&$e.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Lze(t,e,r)};Object.defineProperty($e,"__esModule",{value:!0});$e.CARD_ADMISSION_RECOVERY_AUDIENCE=void 0;$e.cardAdmissionRecoveryRequestHash=Bze;$e.agentOperationIntentHash=yL;$e.agentExecutionCommitment=_L;$e.purchaseTermsHash=Uze;$e.purchaseAlternativeFromOperation=Hze;$e.x402ResourceCommitment=Fze;$e.agentOperationIdempotencyKey=Sie;$e.purchaseAttemptIdempotencyKey=$ze;$e.agentOperationTermsFingerprint=Aie;$e.legacyAgentOperationEnvelopeFingerprint=Iie;$e.persistedAgentOperationMatchesTerms=Jze;$e.artifactHash=Vze;$e.prepareAgentOperationV1=Pie;$e.finalizeAgentOperationV1=Tie;$e.createAgentOperationV1=Kze;$e.parseHistoricalAgentOperation=Wze;$e.parseAgentOperation=ky;var qo=require("node:crypto"),Tt=Ec(),vie=eA();rA(eA(),$e);rA(bie(),$e);rA(wie(),$e);var nA=Fs();rA(Fs(),$e);$e.CARD_ADMISSION_RECOVERY_AUDIENCE="visa:card-admission-recovery:v1";function Bze(e,t){return(0,qo.createHash)("sha256").update("visa:card-admission-recovery:v1\0","utf8").update((0,Tt.canonicalJson)({original:e,replacement:t}),"utf8").digest("base64url")}function yL(e){return(0,qo.createHash)("sha256").update((0,nA.agentOperationIntentPreimage)(e)).digest("base64url")}function _L(e){return(0,qo.createHash)("sha256").update((0,Tt.canonicalJson)(e)).digest("base64url")}function Uze(e){return(0,qo.createHash)("sha256").update((0,vie.purchaseTermsPreimage)(e)).digest("base64url")}function Hze(e,t=Date.now()){let r=ky(e,t);if(r.effect.kind!=="money")throw new Tt.AgentOperationContractError("invalid_effect","purchase requires financial economics");let{amountMicros:n,currency:i,merchant:o}=r.effect,s={amountMicros:n,currency:i,merchant:o},a=(0,Tt.record)(r.execution.payload,"purchase native payload"),c=r.rail==="wallet:x402"?["scheme","network","asset","payer","typedData","nonce","keyRef",...a.walletBinding===void 0?[]:["walletBinding"],...a.approvedRequest===void 0&&a.requestHash===void 0?[]:["approvedRequest","requestHash"]]:["mandateId","tokenId","processorIntentId","processorAction","captureMode"];if(Object.keys(a).sort().join(",")!==c.sort().join(","))throw new Tt.AgentOperationContractError("invalid_contract","purchase producer has unrepresented native fields");let u;if(r.rail==="wallet:x402"&&r.execution.adapter==="wallet.eip3009"){let d=(0,Tt.record)(a.typedData,"wallet typed data"),l=(0,Tt.record)(d.message,"wallet message");if(a.scheme!=="exact"||l.value!==n)throw new Tt.AgentOperationContractError("invalid_amount","wallet value differs from purchase amount");u={rail:r.rail,economics:s,network:a.network,asset:a.asset,payee:l.to,...a.approvedRequest===void 0&&a.requestHash===void 0?{}:{requestHash:a.requestHash}}}else if(r.rail==="card:vic"&&r.execution.adapter==="card.vic")u={rail:r.rail,economics:s,processorAction:a.processorAction,captureMode:a.captureMode};else throw new Tt.AgentOperationContractError("invalid_contract","unsupported purchase producer profile");if(a.requestHash!==void 0&&(0,qo.createHash)("sha256").update((0,Tt.canonicalJson)(a.approvedRequest)).digest("base64url")!==a.requestHash)throw new Tt.AgentOperationContractError("invalid_contract","purchase request hash mismatch");return(0,vie.parsePurchaseTerms)({v:1,profile:a.requestHash===void 0?"url_resource_v1":"approved_x402_request_v1",alternatives:[u]}).alternatives[0]}function Fze(e){let t=(0,Tt.bounded)(e,"x402 resource",2048);return(0,qo.createHash)("sha256").update(`visa-x402-resource:v1:${t}`,"utf8").digest("base64url")}function Sie(e){return`economic:${(0,qo.createHash)("sha256").update((0,Tt.canonicalJson)({domain:"visa.agent-operation-idempotency.v1",agentId:e.agentId,economicIntentId:e.economicIntentId})).digest("base64url")}`}function $ze(e){let t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;for(let r of["agentId","purchaseId","attemptId"])if(typeof e[r]!="string"||!t.test(e[r]))throw new Tt.AgentOperationContractError("invalid_contract",`${r} must be a canonical UUID`);if(typeof e.termsHash!="string"||!/^[A-Za-z0-9_-]{43}$/.test(e.termsHash)||Buffer.from(e.termsHash,"base64url").toString("base64url")!==e.termsHash)throw new Tt.AgentOperationContractError("invalid_contract","termsHash must be canonical SHA-256");return Sie({agentId:e.agentId,economicIntentId:`purchase:${e.purchaseId}:attempt:${e.attemptId}:terms:${e.termsHash}`})}function Aie(e){return(0,qo.createHash)("sha256").update((0,Tt.canonicalJson)({domain:"visa.agent-operation-terms.v1",operationId:e.operationId,idempotencyKey:e.idempotencyKey,agentId:e.agentId,runtimeId:e.runtimeId,rail:e.rail,effect:e.effect,execution:e.execution})).digest("base64url")}function Iie(e){return(0,qo.createHash)("sha256").update((0,Tt.canonicalJson)(e)).digest("base64url")}function Jze(e,t,r){return t===r?!0:Aie(e)!==r?!1:t===Iie(e)}function Vze(e){return(0,qo.createHash)("sha256").update((0,Tt.canonicalJson)(e)).digest("base64url")}var Gze={kind:"identity_pop",popJwt:"unsigned",keyJkt:Buffer.alloc(32).toString("base64url")};function Pie(e,t=Date.now()){let r={v:nA.AGENT_OPERATION_VERSION,...e,principal:Gze,intentHash:Buffer.alloc(32).toString("base64url"),execution:{...e.execution,payloadHash:_L(e.execution.payload)}};r.intentHash=yL(r);let n=ky(r,t),{v:i,principal:o,...s}=n;return s}function Tie(e,t,r=Date.now()){return ky({v:nA.AGENT_OPERATION_VERSION,...e,principal:t},r)}function Kze(e,t=Date.now()){let{principal:r,...n}=e;return Tie(Pie(n,t),r,t)}function Wze(e){let t=(0,Tt.record)(e,"historical operation");if(typeof t.createdAt!="string")throw new Tt.AgentOperationContractError("invalid_window","historical operation creation time is missing");return ky(e,Date.parse(t.createdAt))}function ky(e,t=Date.now()){let r=(0,nA.parseAgentOperationStructure)(e,t);if(_L(r.execution.payload)!==r.execution.payloadHash)throw new Tt.AgentOperationContractError("commitment_mismatch","execution payload does not match its commitment");if(yL(r)!==r.intentHash)throw new Tt.AgentOperationContractError("intent_mismatch","intentHash does not bind the exact operation effect and execution commitment");return r}});var xL=g(Gd=>{"use strict";Object.defineProperty(Gd,"__esModule",{value:!0});Gd.formatCents=nYe;Gd.formatUsd=iYe;Gd.formatMicros=oYe;Gd.formatMoney=aYe;Gd.formatTime=cYe;var TL=1e6,rYe=100;function nYe(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let i=(e/rYe).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${i}`:i}function iYe(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let n=e.toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${n}`:n}function oYe(e,t={}){let r=t.fallback??"\u2014",n=typeof e=="string"?e===""?null:Number(e):e;if(n==null||!Number.isFinite(n))return r;let o=(n/TL).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??6});return t.showPlusSign&&n>0?`+${o}`:o}var sYe=/^-?\d+$/;function aYe(e,t={}){if(typeof e!="bigint"&&!(typeof e=="string"&&sYe.test(e)))throw new TypeError("formatMoney: expected integer micros");let r=BigInt(e),n=r<0n,i=n?-r:r,o=i/BigInt(TL),s=(i%BigInt(TL)).toString().padStart(6,"0"),a=t.precision??"cents",c=a==="exact"?s:a==="cents"||i%10000n===0n?s.slice(0,2):s.replace(/0+$/,""),u=n?"-":"",d=t.currency??"USD",l=`${o.toString()}.${c}`;return d==="USD"?`${u}$${l}`:`${u}${l} ${d}`}function cYe(e,t={}){let r=t.fallback??"\u2014";if(!e)return r;let n=new Date(e);return Number.isNaN(n.getTime())?r:n.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",timeZone:t.timeZone??"UTC"})}});var RL=g(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.AGENT_GRANT_MAX_PER_PURCHASE_CENTS=bi.AGENT_GRANT_MAX_AGGREGATE_CEILING_CENTS=bi.AGENT_GRANT_MIN_LIMIT_MICROS=bi.AGENT_GRANT_MAX_PER_PURCHASE_MICROS=bi.AGENT_GRANT_MAX_AGGREGATE_CEILING_MICROS=void 0;var OL=CL();bi.AGENT_GRANT_MAX_AGGREGATE_CEILING_MICROS=(0,OL.micros)(1000000000n);bi.AGENT_GRANT_MAX_PER_PURCHASE_MICROS=(0,OL.micros)(50000000n);bi.AGENT_GRANT_MIN_LIMIT_MICROS=(0,OL.micros)(1000n);bi.AGENT_GRANT_MAX_AGGREGATE_CEILING_CENTS=1e5;bi.AGENT_GRANT_MAX_PER_PURCHASE_CENTS=5e3});var Jie=g(Jn=>{"use strict";Object.defineProperty(Jn,"__esModule",{value:!0});Jn.MAX_BUDGET_DRAWS=void 0;Jn.derivePurchaseCountDetail=Hie;Jn.derivePurchaseCountDetailMicros=Fie;Jn.derivePurchaseCount=$ie;Jn.describePurchaseCount=fYe;Jn.describePurchaseCountMicros=pYe;var Cp=xL(),uYe=RL();Jn.MAX_BUDGET_DRAWS=20;function Uie(e,t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${e}: expected a positive safe integer of cents, got ${t}`)}function Hie(e,t){Uie("aggregateCeilingCents",e),Uie("perPurchaseCents",t);let r=Math.ceil(e/t),n=Math.max(1,Math.min(Jn.MAX_BUDGET_DRAWS,r)),i=r>Jn.MAX_BUDGET_DRAWS;return{count:n,clamped:i,unreachableCents:i?e-n*t:0}}function qy(e,t){if(!/^[1-9]\d{0,18}$/.test(t))throw new TypeError(`${e}: expected canonical positive integer micros, got ${t}`);return BigInt(t)}function Fie(e,t){let r=qy("aggregateCeilingMicros",e),n=qy("perPurchaseMicros",t),i=(r+n-1n)/n,o=Math.max(1,Math.min(Jn.MAX_BUDGET_DRAWS,Number(i))),s=i>BigInt(Jn.MAX_BUDGET_DRAWS);return{count:o,clamped:s,unreachableMicros:s?(r-BigInt(o)*n).toString():"0"}}function $ie(e,t){return Hie(e,t).count}function dYe(e){let t=[Math.floor(e/5),Math.floor(e/4),Math.floor(e/2)].filter(r=>r>=1);for(let r of t){let n=$ie(e,r);if(n>=2)return{perCents:r,count:n}}return null}function lYe(e){let t=qy("aggregateCeilingMicros",e),r=[t/5n,t/4n,t/2n].filter(n=>n>=uYe.AGENT_GRANT_MIN_LIMIT_MICROS);for(let n of r){let i=Fie(e,n.toString()).count;if(i>=2)return{perMicros:n.toString(),count:i}}return null}function fYe(e,t,r){let n=(0,Cp.formatCents)(t);if(e.clamped)return`This budget covers ${e.count} purchases \u2014 the most one budget allows. Each can be up to ${n}. ${(0,Cp.formatCents)(e.unreachableCents)} of the total can never be spent. Raise the per-purchase amount to use all of it.`;if(e.count===1){let i=dYe(r),o=i?` Lower the per-purchase amount to allow more purchases \u2014 ${(0,Cp.formatCents)(i.perCents)} allows ${i.count}.`:" Lower the per-purchase amount to allow more purchases.";return`This budget covers 1 purchase of up to ${n}. A smaller charge still uses that one purchase, and leftover budget sits unused.${o}`}return`This budget covers ${e.count} purchases. Each can be up to ${n}. Smaller charges are fine \u2014 each one still counts as a purchase.`}function pYe(e,t,r){qy("perPurchaseMicros",t),qy("aggregateCeilingMicros",r);let n=(0,Cp.formatMicros)(t);if(e.clamped)return`This budget covers ${e.count} purchases \u2014 the most one budget allows. Each can be up to ${n}. ${(0,Cp.formatMicros)(e.unreachableMicros)} of the total can never be spent. Raise the per-purchase amount to use all of it.`;if(e.count===1){let i=lYe(r),o=i?` Lower the per-purchase amount to allow more purchases \u2014 ${(0,Cp.formatMicros)(i.perMicros)} allows ${i.count}.`:" Lower the per-purchase amount to allow more purchases.";return`This budget covers 1 purchase of up to ${n}. A smaller charge still uses that one purchase, and leftover budget sits unused.${o}`}return`This budget covers ${e.count} purchases. Each can be up to ${n}. Smaller charges are fine \u2014 each one still counts as a purchase.`}});var CL=g(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.describePurchaseCountMicros=he.describePurchaseCount=he.derivePurchaseCountDetailMicros=he.derivePurchaseCountDetail=he.derivePurchaseCount=he.MAX_BUDGET_DRAWS=he.AGENT_GRANT_MAX_PER_PURCHASE_CENTS=he.AGENT_GRANT_MAX_AGGREGATE_CEILING_CENTS=he.AGENT_GRANT_MIN_LIMIT_MICROS=he.AGENT_GRANT_MAX_PER_PURCHASE_MICROS=he.AGENT_GRANT_MAX_AGGREGATE_CEILING_MICROS=he.formatTime=he.formatMoney=he.formatMicros=he.formatUsd=he.formatCents=void 0;he.micros=mYe;he.fromCents=gYe;he.fromUsdc=hYe;he.fromUsd=yYe;he.toCents=_Ye;he.toCentsForAcquirer=bYe;he.toUsdc=EYe;he.toWire=wYe;he.fromWire=vYe;he.toDisplay=SYe;he.toUsdRounded2dp=AYe;he.toUsdNumber=IYe;he.add=PYe;he.sub=TYe;he.clampNonNegative=xYe;he.max=OYe;he.min=RYe;var Gs=10000n,aA=1000000n;function mYe(e){return e}function gYe(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*Gs}function hYe(e){return e}function yYe(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function _Ye(e){if(e>=0n)return Number(e/Gs);let t=e/Gs,r=e%Gs;return Number(r===0n?t:t-1n)}function bYe(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/Gs)}function EYe(e){return e}function wYe(e){return e.toString()}function vYe(e){if(typeof e!="string"||e.length===0)throw new TypeError(`fromWire: expected non-empty string, got ${typeof e} ${JSON.stringify(e)}`);if(!/^-?\d+$/.test(e))throw new TypeError(`fromWire: not a valid micros integer: ${JSON.stringify(e)}`);return BigInt(e)}function SYe(e,t={}){let r=t.decimals??2,n=t.symbol??"$",i=e<0n,o=i?-e:e,s=o/aA,a=o%aA,c=i?"-":"";if(r===0)return`${c}${n}${s.toString()}`;let u=a.toString().padStart(6,"0").slice(0,r);return`${c}${n}${s.toString()}.${u}`}function AYe(e){let t=e<0n,r=t?-e:e,n=r/Gs,o=r%Gs*2n,s;o<Gs?s=n:o>Gs?s=n+1n:s=n%2n===0n?n:n+1n;let a=Number(s)/100;return t?-a:a}function IYe(e){let t=e<0n,r=t?-e:e,n=Number(r/aA)+Number(r%aA)/1e6;return t?-n:n}function PYe(e,t){return e+t}function TYe(e,t){return e-t}function xYe(e){return e<0n?0n:e}function OYe(e,t){return e>t?e:t}function RYe(e,t){return e<t?e:t}var Dy=xL();Object.defineProperty(he,"formatCents",{enumerable:!0,get:function(){return Dy.formatCents}});Object.defineProperty(he,"formatUsd",{enumerable:!0,get:function(){return Dy.formatUsd}});Object.defineProperty(he,"formatMicros",{enumerable:!0,get:function(){return Dy.formatMicros}});Object.defineProperty(he,"formatMoney",{enumerable:!0,get:function(){return Dy.formatMoney}});Object.defineProperty(he,"formatTime",{enumerable:!0,get:function(){return Dy.formatTime}});var Ly=RL();Object.defineProperty(he,"AGENT_GRANT_MAX_AGGREGATE_CEILING_MICROS",{enumerable:!0,get:function(){return Ly.AGENT_GRANT_MAX_AGGREGATE_CEILING_MICROS}});Object.defineProperty(he,"AGENT_GRANT_MAX_PER_PURCHASE_MICROS",{enumerable:!0,get:function(){return Ly.AGENT_GRANT_MAX_PER_PURCHASE_MICROS}});Object.defineProperty(he,"AGENT_GRANT_MIN_LIMIT_MICROS",{enumerable:!0,get:function(){return Ly.AGENT_GRANT_MIN_LIMIT_MICROS}});Object.defineProperty(he,"AGENT_GRANT_MAX_AGGREGATE_CEILING_CENTS",{enumerable:!0,get:function(){return Ly.AGENT_GRANT_MAX_AGGREGATE_CEILING_CENTS}});Object.defineProperty(he,"AGENT_GRANT_MAX_PER_PURCHASE_CENTS",{enumerable:!0,get:function(){return Ly.AGENT_GRANT_MAX_PER_PURCHASE_CENTS}});var Np=Jie();Object.defineProperty(he,"MAX_BUDGET_DRAWS",{enumerable:!0,get:function(){return Np.MAX_BUDGET_DRAWS}});Object.defineProperty(he,"derivePurchaseCount",{enumerable:!0,get:function(){return Np.derivePurchaseCount}});Object.defineProperty(he,"derivePurchaseCountDetail",{enumerable:!0,get:function(){return Np.derivePurchaseCountDetail}});Object.defineProperty(he,"derivePurchaseCountDetailMicros",{enumerable:!0,get:function(){return Np.derivePurchaseCountDetailMicros}});Object.defineProperty(he,"describePurchaseCount",{enumerable:!0,get:function(){return Np.describePurchaseCount}});Object.defineProperty(he,"describePurchaseCountMicros",{enumerable:!0,get:function(){return Np.describePurchaseCountMicros}})});var VA=require("node:child_process"),GA=require("node:crypto"),Kt=require("node:fs"),Gp=require("node:path");var zse=se(T3());var WA={update_required:{kind:"caller",fix:"npm install -g @visa/cli@rc",nextAction:"Upgrade Visa CLI to the minimum compatible version or newer, then retry the command."},session_required:{kind:"caller",fix:"agent_enroll",nextAction:"Run visa connect (shell) or call agent_enroll (MCP) and complete the browser sign-in. Both resume where they left off. Retry the original command after that."},identity_required:{kind:"caller",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"Call agent_enroll or run visa connect, open the printed URL, enter the code at /agent/enroll/protected-agent, and have the owner approve the device and its limits. Both entrances use the same protected enrollment implementation."},legacy_door_removed:{kind:"caller",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"Call agent_enroll or run visa connect, open the printed URL, enter the code at /agent/enroll/protected-agent, approve the device and its limits, then pay with the pay tool. Do not retry the retired command; nothing was signed, paired, or paid."},agent_selection_required:{kind:"caller",fix:null,nextAction:"Retry the command with one exact agent id from the executable choices in the error."},invalid_argument:{kind:"caller",fix:null,nextAction:"Correct the invalid argument named in the error, then retry the command once. Do not escalate this as a platform incident."},rate_limited:{kind:"caller",fix:"sleep <retry-after-seconds>",nextAction:"Wait the exact Retry-After duration named in the error, then retry the same request once. Do not retry sooner or switch agents to bypass the limit."},activity_entry_not_found:{kind:"caller",fix:"history",nextAction:"Call history for the same agent and find the entry by its exact id in that list, or read the visa://receipt/<id> resource."},wallet_network_mismatch:{kind:"caller",fix:"discover",nextAction:"The unpaid challenge offered no Tempo USDC.e payment this wallet can make. Nothing was reserved, signed, or paid. Choose a service that accepts Tempo; do not retry the same challenge unchanged."},agent_operations_cli_upgrade_required:{kind:"caller",fix:null,nextAction:"Use a reviewed CLI build at or above the minimum version named by the server, restart the agent session, and retry once. The payment was not sent."},agent_operation_forbidden:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This owner, agent, runtime, rail, or rollout state is not admitted to the universal payment route. Ask the owner to inspect the selected agent; do not retry through a legacy path."},runtime_context_not_found:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The server cannot find a current managed runtime contract for this exact agent and device. Ask the owner to inspect or renew that runtime before retrying."},product_policy_not_active:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The wallet setup did not install its server-owned spend policy. Resume the owner-approved wallet setup for this agent; do not retry the payment unchanged."},runtime_spend_session_not_active:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The wallet setup has no active runtime spend session. Resume the owner-approved wallet setup for this agent; do not retry the payment unchanged."},runtime_spend_attenuation_not_active:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The wallet runtime spend limits are not bound to the active owner policy. Resume the owner-approved wallet setup for this agent; do not retry the payment unchanged."},runtime_revoked:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This exact runtime has been revoked. Do not reuse it; ask the owner to certify a new runtime for the same agent if access should continue.",remedy:{path:"/agent/enroll/agents",label:"Check the agent in the Console"}},certified_runtime_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This payment requires an owner-certified runtime. Ask the owner to approve the wallet runtime certificate, then retry once."},runtime_certificate_invalid:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The wallet runtime certificate is invalid, expired, or no longer current. Ask the owner to renew it; do not retry unchanged."},runtime_delegation_missing:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This runtime has no active owner delegation for short signing leases. Ask the owner to finish secure wallet setup before retrying.",remedy:{path:"/agent/enroll/agents",label:"Finish the agent's wallet setup"}},runtime_delegation_expired:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This runtime owner delegation has expired. Ask the owner to renew secure wallet authority before retrying.",remedy:{path:"/agent/enroll/agents",label:"Renew the agent's approval"}},runtime_authority_unavailable:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"The server could not verify runtime authority. Surface the outage to an operator and do not retry or fall back until authority health is restored."},universal_required_managed_only:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The universal route requires a fully managed TVC wallet for this agent. Ask the owner to finish managed wallet setup before retrying."},wallet_authority_cli_upgrade_required:{kind:"caller",fix:null,nextAction:"Upgrade the CLI to the minimum version named by the server, restart this agent session, and retry once. Nothing was signed or paid."},tap_signature_required:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"Escalate to a human. A TAP identity signer is available on this runtime but could not sign, so the paid request was not sent unsigned and nothing was paid. Do not retry the payment unsigned. Probe remains unsigned."},wallet_owner_approval_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was paid. Show the owner the approval link in details.approval.url, bare, and ask them to approve this exact payment before details.approval.expiresAt. Then call pay again with the SAME target, max, body and economicIntentId: until they sign, the retry returns this same refusal (safe to repeat every 15-30 seconds); once they sign, the identical authorization resumes. Do not change the payment or start a new one. If the approval expires first, the retry says so and nothing is paid: stop then."},wallet_owner_approval_expired:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was paid. The owner's approval for this exact payment can no longer be used (it expired before the payment completed). Stop: do not call pay again with this economicIntentId, it will keep answering this. Tell the owner; only if they still want it, start a NEW payment with a NEW economicIntentId, which asks them to approve again."},attestation_key_drift:{kind:"caller",fix:"visa connect",nextAction:"This device holds a credential the server does not recognize (machine swap, keychain wipe, restored backup). Clear the stale local credential, enroll a fresh protected agent with visa connect, then retry."},rc_access_required:{kind:"platform",escalation:"awaiting_human",fix:"export VISA_RC_CODE=<access code>",nextAction:"This is a release-candidate build restricted to Visa employees. Set VISA_RC_CODE in this process, then retry. Ask your team lead or Visa Crypto Labs for the code \u2014 do not guess it."},early_access_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Escalate to a human: an admin must enable this tool for the account. Do not retry until they confirm."},capability_attach_pending_approval:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Ask the owner to finish the approval already open in their browser at /agent/enroll/protected-agent \u2014 the device and its limits are approved there. Do not start a second ceremony; wait for the owner, then retry the original command."},card_checkout_not_on_pay:{kind:"caller",fix:"purchase_create",nextAction:"Nothing was probed further, created or charged. This URL answered no payment challenge, so it is an ordinary merchant checkout and `pay` cannot do it: `pay` spends from the agent wallet only. Card checkouts are the `purchase` resource (`purchase_create`, then `purchase_retrieve`), where Visa issues the credential and YOUR runtime drives the browser. Do not retry this target on `pay`."},card_draw_not_live:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Escalate to a human now. The card-draw surface is not live on this build (it is opt-in server-side), so no local configuration change makes this command work. Do not retry."},checkout_review_refused:{kind:"caller",fix:null,nextAction:"Nothing was charged. This checkout needs a supported card-field adapter. Choose another supported checkout, or give the merchant and adapter details to the product team; do not retry unchanged."},checkout_action_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was charged and no payment credential was requested. Ask the human to complete the named verification step, then retry the review once."},checkout_mandate_blocked:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was charged. Ask the owner to approve a mandate that covers the exact merchant, amount, and currency, then start a new review. Do not widen authority yourself."},card_mandate_activation_uncertain:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The owner approved the budget but the card network did not confirm its activation. No budget is usable and nothing was charged. Do not start another approval while this one is valid: ask the owner to review the budget in the Visa Console and, once the approval has expired or been revoked there, approve a fresh budget. Quote the request id when reporting it."},ucp_platform_profile_unavailable:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Do not retry this checkout. Escalate to the Visa deployment owner: the exact UCP platform profile advertised to merchants must serve a valid HTTPS JSON profile without redirects before checkout handoff can work."},wallet_capability_unavailable:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Escalate to a human now. The wallet capability is not served by this build. Do not retry."},surface_disabled:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Escalate to a human now. The server reports this surface disabled or not configured (kill switch or missing server config \u2014 see the flag and correlation_id in the error). No retry or local change resolves it."},wallet_grant_required:{kind:"platform",escalation:"awaiting_human",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"The Turnkey wallet is delegated by the human owner, not self-minted here. Call agent_enroll or ask the owner to run visa connect and approve the device and its limits at /agent/enroll/protected-agent, then retry.",remedy:{path:"/agent/enroll/agents",label:"Approve this agent in the Console"}},wallet_credential_required:{kind:"platform",escalation:"awaiting_human",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"Call agent_enroll or ask the owner to run visa connect for the intended agent and approve the device and its limits at /agent/enroll/protected-agent, then retry. Identity alone does not grant spend authority.",remedy:{path:"/agent/enroll/agents",label:"Approve this agent in the Console"}},grant_expired:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was reserved, signed, or charged. The owner's spending approval for this agent has expired. Ask the owner to renew it in the Visa Console at /agent/enroll/limits?agent=<agent-id> (the same limits are pre-filled), then retry the same payment once. Do not create a new agent or reconnect.",remedy:{path:"/agent/enroll/limits",label:"Renew the agent's approval"}},managed_limits_owner_controlled:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. Managed wallet limits are owner-set on the server. Read them with get_status, then ask the owner to change them in the Visa Console at /agent/enroll/limits?agent=<agent-id>.",remedy:{path:"/agent/enroll/limits",label:"Change the agent's limits"}},agent_paused:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Ask the owner to resume this exact agent in the Visa Console (Agents). Retry only after get_status reports it ready; do not create a replacement credential while the agent is paused.",remedy:{path:"/agent/enroll/agents",label:"Resume the agent in the Console"}},owner_declined:{kind:"caller",fix:null,nextAction:"The owner declined this payment; don't retry it. Nothing was charged. Tell the owner and move on; only if they ask for it again, start a new payment (a new economicIntentId or a new purchase), which asks them again."},setup_declined:{kind:"caller",fix:null,nextAction:"The owner declined this setup, so no agent was connected; don't retry it. Tell the owner, and only if they ask for it again start a new setup (agent_enroll with restart:true, or `visa connect --restart`), which asks them again."},owner_withdrawal_pending:{kind:"caller",fix:null,nextAction:"Nothing was signed or paid. The owner is withdrawing from this wallet and that transfer is still settling (at most about ten minutes). Retry the same payment in a minute; the budget is unchanged."},kill_switch_engaged:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Visa has paused payments on this rail (card, wallet or Tempo), or could not confirm they are open. Nothing was paid. Tell the owner, and try the same purchase again later; do not loop, switch rails to get around it, or create a replacement."},agent_revoked:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This agent is permanently revoked. Do not retry or reuse its credentials; ask the owner whether to pair a new agent identity.",remedy:{path:"/agent/enroll/agents",label:"Connect a new agent in the Console"}},device_key_replaced:{kind:"platform",escalation:"awaiting_human",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"Nothing was paid. This computer's keys for the agent were replaced on another computer, which now is the agent. Do not retry here. To use this computer too, call agent_enroll (or have the owner run visa connect) and approve it as a new agent."},agent_stale:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The server cannot prove this agent is currently usable. Ask the owner to inspect its lifecycle and reauthorize it before retrying.",remedy:{path:"/agent/enroll/agents",label:"Check the agent in the Console"}},agent_lifecycle_unknown:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"The lifecycle state is unknown. Surface the full preflight result to a human and do not retry a money operation until the server reports active."},wallet_delivery_required:{kind:"platform",escalation:"awaiting_human",fix:"visa connect",nextAction:"The approved wallet runtime was not delivered completely. Ask the owner to re-run visa connect and re-approve the device and its limits before paying; do not self-mint a mainnet wallet.",remedy:{path:"/agent/enroll/agents",label:"Reconnect this agent in the Console"}},wallet_authority_revoked:{kind:"caller",fix:"get_status",nextAction:"This wallet is preserved for recovery only. Inspect its balance and receipts with get_status or history; do not retry a payment or policy change until the owner approves a new wallet grant."},wallet_authority_replacement_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This compatibility error came from an older single-wallet runtime. Upgrade the CLI and re-run the wallet grant; current builds isolate wallet authority per agent."},wallet_policy_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed. Ask the owner to set per-purchase and daily spend caps in the Visa Console at /agent/enroll/limits?agent=<agent-id>, then retry once. Caps are enforced before anything is signed.",remedy:{path:"/agent/enroll/limits",label:"Set spending caps in the Console"}},wallet_funding_required:{kind:"caller",fix:"get_status",nextAction:"Ask the owner to add USDC.e on Tempo to their wallet before paying: the Visa Console shows the wallet's address and balance under Payments.",remedy:{path:"/agent/enroll/payments",label:"Add funds to the wallet"}},wallet_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Ask the owner to finish wallet setup in the Visa console (their account has no usable wallet yet), then re-run the grant. Do not keep polling: the ceremony cannot complete until the wallet exists.",remedy:{path:"/agent/enroll/payments",label:"Finish wallet setup"}},checkout_agent_access_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Escalate to a human: this account is not enabled for agent checkout, so grant ceremonies are refused server-side. Do not retry until an admin confirms the account has access."},unknown_tool:{kind:"caller",fix:null,nextAction:"Call tools/list and dispatch one of the served names. The tool you asked for is not registered on this runtime."},handoff_not_found:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The Console claim code was not found or was mistyped. Ask the human for a fresh claim code from the Visa Console; do not retry this code."},handoff_expired:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This Console claim code has expired. Ask the human to create a new setup code in the Visa Console."},handoff_already_redeemed:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This Console claim code has already been redeemed. Ask the human to create a new setup code in the Visa Console."},no_paired_agent:{kind:"caller",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"No protected agent on this device. Call agent_enroll or run visa connect and complete the owner ceremony at /agent/enroll/protected-agent first."},agent_id_required:{kind:"caller",fix:null,nextAction:"Pass the agentId to identify which agent ceremony to operate on."},already_terminal:{kind:"caller",fix:null,nextAction:"This ceremony is already terminal or cancelled. No further action needed."},purchase_transport_uncertain:{kind:"caller",fix:null,nextAction:"Wait briefly, then repeat the identical Visa purchase call with the same arguments, request key and purchase ID. The original request may have succeeded; its journal recovers the same attempt. Do not cancel, create a replacement or submit Pay at the merchant again. Escalate repeated transport failures."},purchase_refused:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The authority refused this purchase request. Use the recorded upstream status and error to resolve the refusal before trying again. Preserve the original purchase and request key; a refusal is not permission to mint a replacement or repeat merchant payment."},recovery_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Inspect the original purchase and checkout with the owner or support. Preserve the purchase ID and request key. Do not create a replacement, release uncertain liability or submit Pay again."},card_recovery_unconfigured:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Card recovery is not configured. Ask support to restore the protected recovery worker before retrying the same Visa request. Preserve the purchase ID; do not create another purchase or click merchant Pay again."},card_recovery_original_not_expired:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The original credential attempt is still live. Retrieve the same purchase without include:card and follow its continuation; do not force recovery, create another purchase or click merchant Pay again."},card_recovery_liability_present:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The original attempt still has liability. Ask support to reconcile that attempt and inspect the existing checkout. Do not release funds, issue replacement credentials or click merchant Pay again."},card_recovery_issuance_conflict:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Recovery found conflicting issuance evidence. Stop and ask support to reconcile the original purchase and attempt. Do not create another purchase or click merchant Pay again."},card_recovery_proof_invalid:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The recovery proof could not be verified. Ask support to repair recovery for the existing device and purchase; do not replay the invalid proof, replace the identity or click merchant Pay again."},card_purchase_quarantined:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This purchase is quarantined for reconciliation. Ask support to inspect its original attempt and the existing checkout. Do not create another purchase, release its liability or click merchant Pay again."},card_credential_not_available:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Credentials are not available for this purchase state. Retrieve the same purchase without include:card and follow its continuation. Do not recreate the purchase or click merchant Pay again."},purchase_submission_observed:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Submission was already reported for this purchase. Inspect the existing merchant checkout and report its current state on the same purchase. Do not request replacement credentials or click merchant Pay again."},protected_card_request_invalid:{kind:"caller",fix:null,nextAction:"The card executor refused the saved delivery request, usually because its admission has expired. Retrieve the same purchase and follow its continuation; if it reads expired, run purchase create again with the same request file. Do not create a replacement purchase by hand."},protected_card_delivery_conflict:{kind:"caller",fix:null,nextAction:"The saved delivery request differs from the one already in progress for this attempt. Retrieve the same purchase and follow its continuation; do not alter or replay edited request bytes."},protected_card_authority_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The card authority did not answer the executor. Nothing was issued. Wait a moment and retrieve the same purchase; recovery continues server-side."},purchase_cancelled:{kind:"caller",fix:null,nextAction:"This purchase was cancelled; it accepts no new credential. Create a new purchase for a fresh checkout if the buyer still wants it. Do not click merchant Pay."},card_intent_unobserved:{kind:"caller",fix:null,nextAction:"The owner's card allowance for this agent is not active yet. Follow next.open_url so the owner finishes card setup, then retry the same checkout."},card_intent_mandate_exists:{kind:"caller",fix:null,nextAction:"The owner's current approval already has a card allowance in progress. Wait for it to finish (or ask the owner to check the limits page), then retry the same checkout."},card_intent_conflict:{kind:"caller",fix:null,nextAction:"A different card allowance request already exists under this id. Retrieve current status instead of resending edited request bytes."},card_vic_provider_refused:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The provider refused credential issuance. Ask the owner or support to inspect the original purchase and provider refusal before retrying; an HTTP error does not prove its reservation was released. Do not create a replacement purchase or click merchant Pay again."},terms_conflict:{kind:"caller",fix:null,nextAction:"The request conflicts with the existing checkout commitment or quote bound. Retrieve the original purchase and compare the exact final terms. Do not change the request key or checkout ID to bypass the conflict; resolve it under the checkout replacement rules."},card_checkout_expired:{kind:"caller",fix:null,nextAction:"The exact checkout quote expired. Inspect the original purchase before obtaining a new final quote. Do not reuse stale terms or bypass checkout replacement rules by changing the request key or checkout ID."},card_mandate_expired:{kind:"caller",fix:null,nextAction:"The owner's card allowance for this agent lapsed (the provider limits each one to 7 days) while the approval itself is still valid; Visa is issuing a replacement under that approval. Wait afterMs and run the same purchase create again. Do not involve the owner or create a replacement purchase."},card_allowance_preparing:{kind:"caller",fix:null,nextAction:"Visa is issuing this agent's card allowance under the owner's existing approval. Wait afterMs and run the same purchase create again; the wait loop does this for you. Do not involve the owner or create a replacement purchase."},protected_card_instrument_inactive:{kind:"platform",escalation:"awaiting_human",fix:"purchase_create",nextAction:"This agent's card connection points at a saved-card record the owner has since replaced (re-verifying the card) or removed. Call purchase_create again with the saved resumeId: it returns one open_url that reconnects this agent to the owner's current saved card. The owner opens it once, then the same saved purchase resumes. Do not ask for card details, create another agent or purchase, or click merchant Pay again."},card_reservation_expired:{kind:"caller",fix:null,nextAction:"Retrieve the same purchase to resolve its expired reservation. Follow its current continuation; do not replay stale admission bytes or create a replacement to hide an unresolved attempt."},card_merchant_country_mismatch:{kind:"caller",fix:null,nextAction:"Use the actual merchant country consistently in the signed checkout terms and settlement envelope. Preserve the existing purchase commitment; do not change keys to bypass a terms conflict."},protected_grant_proof_mismatch:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Ask the owner or support to verify the current grant and runtime proof for this existing agent. Do not retry an unchanged invalid proof or create replacement authority."},purchase_resume_invalid:{kind:"caller",fix:null,nextAction:"Use the exact saved purchase resume reference by itself; do not combine it with a new request. Preserve the original purchase and merchant checkout."},purchase_draft_invalid:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The saved purchase request is damaged or changed. Stop and ask support to recover the original draft; do not overwrite it, invent new terms or click merchant Pay again."},purchase_draft_not_found:{kind:"caller",fix:null,nextAction:"Use the original device and exact saved resume reference. Locate the existing draft before continuing; do not recreate the request or click merchant Pay again."},purchase_draft_agent_invalid:{kind:"caller",fix:null,nextAction:"Select the existing protected agent by its exact UUID and resume the original draft. Do not create a replacement identity or purchase."},purchase_draft_agent_mismatch:{kind:"caller",fix:null,nextAction:"Resume this draft with the same protected agent it already selected. Do not switch agents, replace the draft or click merchant Pay again."},purchase_draft_owner_mismatch:{kind:"caller",fix:null,nextAction:"Sign in as the owner who started this draft on the original device, then resume that same draft. Do not transfer it to another owner or create a replacement purchase."},purchase_draft_owner_required:{kind:"caller",fix:null,nextAction:"Complete the returned owner sign-in step, then resume the same saved draft. Do not start another identity enrollment or purchase."},purchase_draft_busy:{kind:"caller",fix:null,nextAction:"Wait for the current Visa purchase call to finish, then repeat the same resume reference. Do not run concurrent purchase calls, create a replacement or click merchant Pay again."},purchase_not_found:{kind:"caller",fix:null,nextAction:"Check the original purchase ID and selected agent. Recover the existing purchase record; do not mint a replacement merely because a read could not find it."},invalid_contract:{kind:"caller",fix:null,nextAction:"Correct the request using the declared tool schema, then retry only with valid input. Never fabricate facts or change existing payment identifiers to bypass their commitment."},invalid_amount:{kind:"caller",fix:null,nextAction:"Supply a positive canonical amount in the units required by the selected tool. Follow its total and precision constraints; never change identifiers to bypass an existing payment commitment."},invalid_currency:{kind:"caller",fix:null,nextAction:"Use the currency required by the selected payment profile. Do not infer merchant country from currency."},unsupported_version:{kind:"caller",fix:null,nextAction:"Use a supported protocol version and profile. Check the current tool schema or update Visa CLI, then retry the same logical operation without bypassing its existing commitment."},keychain_not_found:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This Mac user has no default keychain, so no agent key was stored or read and no system dialog was opened. Ask the owner to restore or create their login keychain in Keychain Access, then retry. On a server with no keychain, the owner can choose file custody explicitly with VISA_RUNTIME_CUSTODY_PROFILE=headless."},custody_store_unreadable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The agent key store on this machine could not be read (its permissions or the disk), so nothing was signed and nothing was changed. Ask the owner to restore read access to Visa CLI's agent-keys directory, then retry. Do not re-enroll: the key may still be there."},keychain_locked_or_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The macOS login keychain is locked or refused, so this agent's key could not be read. Nothing was signed or sent, and no new key was made. Ask the owner to unlock the login keychain (log in to the Mac, or open Keychain Access), then retry once."},custody_unavailable:{kind:"platform",escalation:"awaiting_human",fix:"visa connect",nextAction:"This agent's key is not on this computer: it was set up by an older Visa CLI or on another computer. Nothing was signed or sent. Ask the owner to update Visa CLI (npm i -g @visa/cli@rc) and run visa connect on this computer, then approve the new agent in the browser."},protected_card_enrollment_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. The owner must verify a payment card once for this account. Ask the owner to sign in at /agent/enroll and complete the Verify your card step, then retry the original command once.",remedy:{path:"/agent/enroll?enrollCard=1",label:"Verify a payment card"}},financial_rollout_approval_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. The owner account is not approved for protected payments yet. Surface this to the owner; do not retry until they confirm access was granted."},key_purpose_mismatch:{kind:"platform",escalation:"awaiting_human",fix:"npm i -g @visa/cli@rc",nextAction:"The native signer refused to sign because this device key is bound to a different purpose (wallet, card, or identity) than the operation asked of it. Nothing was signed or sent. This is a Visa CLI defect or a CLI/signer version mismatch, not something a retry changes: ask the owner to update Visa CLI, then retry once. If it persists on the latest build, report it."},legacy_custody_profile_required:{kind:"platform",escalation:"awaiting_human",fix:"npm i -g @visa/cli@rc",nextAction:"The native signer refused to sign a wallet or card proof with an identity key. Nothing was signed or sent. This is a Visa CLI defect or a CLI/signer version mismatch: ask the owner to update Visa CLI, then retry once. If it persists on the latest build, report it."},identity_binding_mismatch:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The native signer refused because the request named a different agent or runtime than the device key is bound to. Nothing was signed or sent. Read get_status, then retry once with that agent's id; if it repeats, surface it to the owner rather than retrying."},proof_time_invalid:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The native signer refused a proof whose timestamp is outside its one-minute window, which means this machine's clock is wrong. Nothing was signed or sent. Ask the owner to sync the system clock, then retry once."},secret_service_locked_or_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The Linux Secret Service (the desktop keyring) is locked or refused Visa CLI, so the agent's key could not be read. Ask the owner to unlock the login keyring; on a machine without a desktop session (SSH, WSL, a server), set VISA_RUNTIME_CUSTODY_PROFILE=headless and run visa connect instead. Do not retry on your own."},secret_service_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"No Linux Secret Service is reachable (no desktop session: SSH, WSL, a container, or a server), so the agent's key could not be read. On such a machine, set VISA_RUNTIME_CUSTODY_PROFILE=headless (an owner-only key file) and run visa connect; in a desktop session, unlock the keyring (gnome-keyring or KWallet). Do not retry on your own."},secret_service_timeout:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The Linux Secret Service did not answer Visa CLI in time, usually because an unlock prompt is waiting. Ask the owner to answer or unlock the keyring, then retry once."},dpapi_locked_or_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Windows data protection (DPAPI) refused to open the agent key, usually because this is a different Windows user or profile than the one that set the agent up. Ask the owner to run Visa CLI as that user; do not retry on your own."},enrollment_device_approval_pending:{kind:"platform",escalation:"awaiting_human",fix:"visa connect",nextAction:"This computer's agent setup is waiting for the owner's device approval, and starting another would strand it. Nothing was changed. Run visa connect (without --restart) to reopen the same approval, ask the owner to approve it, and only then use visa connect --restart if a replacement is still wanted."},enrollment_expired:{kind:"caller",fix:"visa connect --restart",nextAction:"This approval link expired. Run `visa connect --restart` (agent_enroll: restart:true) for a new link, and give the owner the new link and code."},enrollment_owner_mismatch:{kind:"platform",escalation:"awaiting_human",fix:"visa connect --restart (keep the signed-in account) or visa disconnect --all, then visa connect (switch accounts)",nextAction:"The agent approved for this terminal belongs to a different Visa account than the one this terminal is signed in to (the error names it), so nothing was connected. Let the owner choose. To keep the signed-in account: run visa connect --restart and open the new link while signed in to that account. To switch to the other account: visa disconnect --all signs this terminal out, but it also removes the Visa MCP server from every AI client, the spend HUD and any local card-delivery files, so run it only with the owner's say-so; then run visa connect and the owner signs in with the other account. Never approve for them."},wallet_key_setup_pending:{kind:"platform",escalation:"awaiting_human",fix:"visa connect",nextAction:"This agent is connected but cannot pay yet: its key on the owner's Tempo wallet is not set up. The owner's open approval page finishes it on its own (it asks for USDC.e first if the wallet has none); if that page was closed, opening the Visa Console finishes it the same way. Then run visa connect (or call get_status) to confirm. Do not run visa connect --restart, and do not try a payment until it reports the key ready.",remedy:{path:"/agent/enroll/payments",label:"Finish the wallet in Payments"}},unspecified_error:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"This failure could not be classified, so it is reported as platform to avoid a silent retry loop. Surface the human-readable error to a human rather than retrying."},tempo_over_max:{kind:"caller",fix:null,nextAction:"Nothing was signed or paid. The charge costs more than max: raise max only if the human agreed to that price, otherwise stop."},tempo_budget_refused:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. The owner's spending budget or per-payment limit does not allow this payment. Ask the human to raise it in the Visa Console; do not retry until they have.",remedy:{path:"/agent/enroll/limits",label:"Change the agent's limits"}},tempo_chain_limit:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. The wallet's weekly on-chain safety limit for this agent is used up; it refills on its weekly schedule, shown with the agent's limits in the Visa Console. Do not retry before then; tell the human if the purchase cannot wait.",remedy:{path:"/agent/enroll/limits",label:"Change the agent's limits"}},tempo_charge_expired:{kind:"caller",fix:"pay",nextAction:"Nothing was paid. The merchant charge expired before it was signed. Call pay again for the same target to get a fresh charge."},tempo_payment_unclear:{kind:"caller",fix:"pay",nextAction:"The payment may have gone through (charged: null). Do not start a new purchase. Call pay again with the SAME economicIntentId in about a minute: it reports whether the earlier payment landed and pays only if it provably did not. history shows it too."},tempo_payment_in_progress:{kind:"caller",fix:"pay",nextAction:"Another call is paying this exact purchase right now. Do not pay again; call pay again with the same economicIntentId in a minute to read its outcome."},tempo_payment_refused:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"Nothing was signed or paid. Visa refused this Tempo payment before signing. Tell the human and stop; do not retry."},tempo_charge_mismatch:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. The merchant's Tempo charge does not match what this payment allows (payee, currency or paying account), checked on this machine. Do not retry; tell the human."},tempo_not_enabled:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was paid. This agent's wallet setup is not finished. Ask the owner to open Payments in the Visa Console (/agent/enroll/payments): the wallet finishes setting up there once it has funds. Then call pay again with the same economicIntentId.",remedy:{path:"/agent/enroll/payments",label:"Finish the wallet in Payments"}},tempo_unavailable:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Nothing was paid. Visa has wallet payments switched off right now. Tell the human; do not retry until Visa turns them on, and do not look for another way to pay this merchant."},merchant_not_supported:{kind:"caller",fix:null,nextAction:"Nothing was charged. This merchant does not accept Visa wallet payments (MPP on Tempo). Do not retry it on `pay`; pay a merchant that accepts Tempo, or tell the human."},merchant_unreachable:{kind:"caller",fix:null,nextAction:"Nothing was charged. The merchant URL could not be reached to read its price. Check the URL, then call pay again with the same economicIntentId."},purchase_on_retired_rail:{kind:"caller",fix:null,nextAction:"Nothing was paid. This purchase was started with the earlier wallet, before Visa moved wallet payments to Tempo. Do not pay it again: check `history` for its outcome, and use a new economicIntentId only for a genuinely new purchase."},tempo_owner_approval_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:`Nothing was paid. The owner chose "Ask me each time" for this agent's wallet payments, and this Tempo payment could not be sent to them for approval. Call pay again with the same economicIntentId: it asks the owner (the answer then carries the approval link). If it keeps failing, ask the human.`}},LZe=Object.keys(WA);function r0(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(WA,e)}function Yse(e){return e.remedy?{remedyPath:e.remedy.path,remedyLabel:e.remedy.label}:{}}function Vc(e,t={}){let r=WA[e],n=t.fix!==void 0?t.fix:r.fix;if(r.kind==="platform"&&r.escalation!=="awaiting_human"&&n!==null)throw new Error(`agent-contract: ${r.escalation} code "${e}" cannot carry a fix \u2014 no command resolves it`);return{code:e,kind:r.kind,fix:n,nextAction:t.nextAction??r.nextAction,...t.agentId?{agentId:t.agentId}:{},...Yse(r)}}var Rt=class extends Error{diagnostic;details;constructor(t,r,n={}){super(t),this.name="AgentContractError";let i=n.agentId??(typeof n.details?.agentId=="string"?n.details.agentId:void 0);this.diagnostic=Vc(r,{...n,...i?{agentId:i}:{}}),this.details=n.details}get code(){return this.diagnostic.code}};function tl(e){if(e instanceof Rt)return e.diagnostic;if(e&&typeof e=="object"){let t=e,r=typeof t.agentId=="string"?t.agentId:t.details&&typeof t.details=="object"&&typeof t.details.agentId=="string"?t.details.agentId:void 0,n=r?{agentId:r}:{},i=e.underlying;if(i instanceof Rt)return i.diagnostic;let o=i?.code;if(o==="agent_paused"||o==="agent_revoked"||o==="device_key_replaced"||o==="grant_expired")return Vc(o,n);let s=e.code??e.errorCode;if(r0(s))return Vc(s,n);if(typeof s=="string"){let c=s.toLowerCase();if(r0(c))return Vc(c,n)}let a=e.message;return r0(a)?Vc(a,n):Vc("unspecified_error",n)}return Vc("unspecified_error")}var cl=require("node:crypto"),Go=se(require("node:fs")),iI=se(require("node:path"));var zc=require("child_process"),eB=require("util"),zt=se(require("fs")),tm=se(require("os")),al=se(require("path"));var C3=se(require("crypto"));var x3="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var Xse="VISA_ALLOW_INSECURE_MOCKS",O3,R3;function N3(e){return`${e}-${C3.randomBytes(24).toString("base64url")}`}function Zse(e=process.env){return e.NODE_ENV==="test"||e[Xse]==="true"}function Si(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&Zse(e)}function k3(){return O3??=N3("mock-session"),O3}function zA(e=process.env){return e.NODE_ENV==="test"?x3:(R3??=N3("mock-rc"),R3)}var j3=se(require("crypto")),M3=se(require("os")),n0=se(require("path")),q3="VISA_CLI_HOME";function Xe(e=process.env){let t=e[q3];return typeof t=="string"&&t.trim().length>0?t:n0.join(M3.homedir(),".visa-cli")}function D3(e=process.env){let t=e[q3];return typeof t=="string"&&t.trim().length>0}function L3(e=process.env){let t=n0.resolve(Xe(e));return j3.createHash("sha256").update(t).digest("hex").slice(0,16)}var o0=require("node:crypto"),oa=se(require("node:fs")),s0=se(require("node:path"));var B3=require("node:crypto"),YA=se(require("node:fs")),Kc=se(require("node:path")),U3=require("node:util"),nl=1024*1024,Xp=class extends Error{constructor(t){super(t),this.name="PrivateStateSecurityError"}};function Qse(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function Wt(e,t){return new Xp(`${e} ${t}`)}function H3(e=process.platform){if(e==="win32")throw new Xp("owner-only identity files are not supported on Windows yet; protocol-v2 pairing is disabled until verified ACL storage is available")}function Gc(e,t,r,n){try{return r.lstatSync(e)}catch(i){if(n&&Qse(i))return null;throw Wt(t,"could not be inspected safely")}}function F3(e,t){H3(t);let r=e.expectedUid??process.geteuid?.();if(!Number.isSafeInteger(r)||r<0)throw new Xp("private state owner could not be verified against the process effective uid");return r}function rl(e,t,r){return!(r!=="win32"||e.dev!==0||t.dev!==0||e.ino!==0||t.ino!==0)||e.dev===t.dev&&e.ino===t.ino}function i0(e,t,r,n){if(e.isSymbolicLink()||!e.isDirectory())throw Wt(t,"must be a real owner-only directory, not a symlink");if(r!=="win32"){if(e.uid!==n)throw Wt(t,"must be owned by the current effective user");if((e.mode&63)!==0)throw Wt(t,"must not grant access to group or other users (use mode 0700)")}}function Yp(e,t,r,n){if(e.isSymbolicLink()||!e.isFile())throw Wt(t,"must be a real owner-only regular file, not a symlink");if(r!=="win32"){if(e.uid!==n)throw Wt(t,"must be owned by the current effective user");if((e.mode&63)!==0)throw Wt(t,"must not grant access to group or other users (use mode 0600)")}}function Lr(e,t={}){let r=t.ops??YA,n=t.platform??process.platform,i=F3(t,n),o=Gc(e,"private state directory",r,!0);return o?(i0(o,"private state directory",n,i),!0):!1}function eae(e,t={}){let r=t.ops??YA,n=t.platform??process.platform,i=t.maxBytes??nl;if(!Number.isSafeInteger(i)||i<1)throw new Error("private state maximum size must be a positive safe integer");let o=F3(t,n),s=Kc.dirname(e),a=Gc(s,"private state directory",r,!0);if(!a)return null;i0(a,"private state directory",n,o);let c=Gc(e,"private state file",r,!0);if(!c)return null;Yp(c,"private state file",n,o);let u;try{try{u=r.openSync(e,r.constants.O_RDONLY|(r.constants.O_NOFOLLOW??0))}catch{throw Wt("private state file","changed or could not be opened safely")}let d=r.fstatSync(u);if(Yp(d,"private state file",n,o),!rl(c,d,n))throw Wt("private state file","changed while it was being opened");if(!Number.isSafeInteger(d.size)||d.size<0||d.size>i)throw Wt("private state file",`exceeds the ${i}-byte safety limit`);let l=Gc(e,"private state file",r,!1);if(Yp(l,"private state file",n,o),!rl(d,l,n))throw Wt("private state file","changed while it was being opened");let m=Gc(s,"private state directory",r,!1);if(i0(m,"private state directory",n,o),!rl(a,m,n))throw Wt("private state directory","changed while private state was being opened");let p=[],h=0;for(;h<=i;){let E=Buffer.allocUnsafe(Math.min(65536,i+1-h)),S=r.readSync(u,E,0,E.length,null);if(S===0)break;if(h+=S,h>i)throw Wt("private state file",`exceeds the ${i}-byte safety limit`);p.push(E.subarray(0,S))}let y=r.fstatSync(u);if(Yp(y,"private state file",n,o),!rl(d,y,n)||y.size!==d.size||y.mtimeMs!==d.mtimeMs||y.ctimeMs!==d.ctimeMs||h!==y.size)throw Wt("private state file","changed while it was being read");let b=Gc(e,"private state file",r,!1);if(Yp(b,"private state file",n,o),!rl(y,b,n))throw Wt("private state file","changed while it was being read");let v=Gc(s,"private state directory",r,!1);if(i0(v,"private state directory",n,o),!rl(a,v,n))throw Wt("private state directory","changed while private state was being read");let A;try{A=new U3.TextDecoder("utf-8",{fatal:!0}).decode(Buffer.concat(p,h))}catch{throw Wt("private state file","must contain valid UTF-8")}return{contents:A,mtimeMs:y.mtimeMs}}finally{u!==void 0&&r.closeSync(u)}}function cr(e,t={}){return eae(e,t)?.contents??null}function Ht(e,t,r=YA,n=process.platform){H3(n);let i=Kc.dirname(e),o=Kc.join(i,`.${Kc.basename(e)}.${process.pid}.${(0,B3.randomBytes)(8).toString("hex")}.tmp`),s=r.constants.O_NOFOLLOW??0,a,c=!1;try{a=r.openSync(o,r.constants.O_WRONLY|r.constants.O_CREAT|r.constants.O_EXCL|s,384),r.writeFileSync(a,t,{encoding:"utf8"}),r.fsyncSync(a),r.closeSync(a),a=void 0,r.renameSync(o,e),c=!0;let u;try{u=r.openSync(e,r.constants.O_RDONLY|s),r.fsyncSync(u)}finally{u!==void 0&&r.closeSync(u)}let d;try{let l=r.constants.O_DIRECTORY??0;d=r.openSync(i,r.constants.O_RDONLY|l|s),r.fsyncSync(d)}finally{d!==void 0&&r.closeSync(d)}}finally{a!==void 0&&r.closeSync(a),c||r.rmSync(o,{force:!0})}}var tae=/^op_[a-f0-9]{24}$/,XA=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function ZA(e=process.env){return s0.join(Xe(e),"owner-profiles")}function QA(e=process.env){return s0.join(ZA(e),"profiles.json")}function J3(e,t){return`op_${(0,o0.createHash)("sha256").update(`${eI(e)}\0${t}`).digest("hex").slice(0,24)}`}function eI(e){let t=new URL(e);if(t.username||t.password||t.search||t.hash||t.pathname!==""&&t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","::1"].includes(t.hostname)))throw new Error("owner profile auth origin must be HTTPS (or HTTP loopback)");return t.origin}function V3(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(!tae.test(String(t.profileId??""))||!XA.test(String(t.ownerPublicId??""))||!XA.test(String(t.runtimeId??""))||typeof t.loginLabel!="string"||t.loginLabel.length<1||t.loginLabel.length>320||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt)))return!1;try{return eI(String(t.authOrigin??""))===t.authOrigin&&J3(String(t.authOrigin),String(t.ownerPublicId))===t.profileId}catch{return!1}}function $3(){return{version:1,activeProfileId:null,profiles:[]}}function Zp(e=process.env){let t=QA(e);if(!oa.existsSync(t))return $3();let r=cr(t,{maxBytes:128*1024});if(r===null)return $3();let n;try{n=JSON.parse(r)}catch{throw new Error(`owner profile registry contains invalid JSON at ${t}. Rename that file out of the directory, then run \`visa connect\` to rebuild it; this signs local profiles out.`)}if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`owner profile registry is invalid at ${t}. Rename that file out of the directory, then run \`visa connect\` to rebuild it; this signs local profiles out.`);let i=n;if(i.version!==1||!Array.isArray(i.profiles)||!i.profiles.every(V3))throw new Error(`owner profile registry is invalid at ${t}. Rename that file out of the directory, then run \`visa connect\` to rebuild it; this signs local profiles out.`);let o=i.profiles,s=new Set(o.map(c=>c.profileId));if(s.size!==o.length)throw new Error(`owner profile registry has duplicate profiles at ${t}. Rename that file out of the directory, then run \`visa connect\` to rebuild it; this signs local profiles out.`);let a=i.activeProfileId;if(a!==null&&(typeof a!="string"||!s.has(a)))throw new Error(`owner profile registry active profile is invalid at ${t}. Rename that file out of the directory, then run \`visa connect\` to rebuild it; this signs local profiles out.`);return{version:1,activeProfileId:a,profiles:o}}function G3(e,t=process.env){let r=ZA(t);oa.mkdirSync(r,{recursive:!0,mode:448}),oa.chmodSync(r,448),Lr(r),Ht(QA(t),JSON.stringify(e,null,2))}function il(e=process.env){return[...Zp(e).profiles]}function Xr(e=process.env){let t=Zp(e);return t.profiles.find(r=>r.profileId===t.activeProfileId)??null}function K3(e){let t=e.env??process.env,r=eI(e.authOrigin);if(!XA.test(e.ownerPublicId))throw new Error("owner profile requires a stable owner UUID");let n=e.loginLabel.normalize("NFC").trim();if(!n||n.length>320)throw new Error("owner profile login label is invalid");let i=Zp(t),o=J3(r,e.ownerPublicId),s=i.profiles.find(c=>c.profileId===o);return s?{...s,loginLabel:n}:{profileId:o,authOrigin:r,ownerPublicId:e.ownerPublicId,loginLabel:n,runtimeId:(0,o0.randomUUID)(),createdAt:(e.now??new Date).toISOString()}}function W3(e,t=process.env){if(!V3(e))throw new Error("refusing to activate an invalid owner profile");let r=Zp(t);return G3({version:1,activeProfileId:e.profileId,profiles:[...r.profiles.filter(n=>n.profileId!==e.profileId),e]},t),e}function z3(e,t=process.env){let r=Zp(t),n=r.profiles.filter(i=>i.profileId!==e);G3({version:1,activeProfileId:r.activeProfileId===e?null:r.activeProfileId,profiles:n},t)}function Y3(e=process.env){let t=QA(e);try{oa.unlinkSync(t)}catch(r){if(r.code!=="ENOENT")throw r}}function a0(e){return`session-token:${e.profileId}`}function sa(e,t=process.env){return s0.join(ZA(t),e.profileId,"session-token")}function X3(e){return`attestation-key:${e.profileId}:${e.runtimeId}`}var Zr=(0,eB.promisify)(zc.execFile);function Wi(e=process.env){let t=e.VISA_CLI_HOME,r=typeof t=="string"&&t.trim().length>0?t:tm.homedir();return al.join(r,".visa-mcp","session-token")}function ol(e=process.env){let t=e.VISA_CLI_HOME,r=typeof t=="string"&&t.trim().length>0?t:tm.homedir();return al.join(r,".visa-mcp","rc-access")}var Qr="visa-cli",Vo="session-token",Jo="rc-access";function c0(e=process.env){return D3(e)?`rc-access:home:${L3(e)}`:Jo}var rae=5e3,d0=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function nae(e){let t=e;return[t?.message,t?.stderr].filter(r=>typeof r=="string").join(`
101
+ `)}function tI(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let r=nae(e).toLowerCase();return r.includes("operation not permitted")||r.includes("permission denied")}var Z3=null,Qp=null,iae="attestation-key";async function oae(e){try{await Zr("security",["delete-generic-password","-s",Qr,"-a",e],{timeout:5e3})}catch{}}async function sae(e=il()){if(!await zi())return;let t=new Set([...e.map(X3),iae]);for(let r of t)await oae(r)}function zi(){return process.platform!=="darwin"?Promise.resolve(!1):(Z3??=(async()=>{try{return await Zr("security",["default-keychain","-d","user"],{timeout:5e3}),!0}catch(e){return tI(e)}})(),Z3)}function aae(){if(process.platform!=="darwin")return!1;if(Qp!==null)return Qp;try{(0,zc.execFileSync)("security",["default-keychain","-d","user"],{timeout:1e3,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),Qp=!0}catch{Qp=!1}return Qp}async function cae(e=Vo){if(!await zi())return null;try{let{stdout:t}=await Zr("security",["find-generic-password","-s",Qr,"-a",e,"-w"],{timeout:5e3});return t.trim()||null}catch(t){if(tI(t))throw new d0("Unable to read Visa CLI credentials from macOS Keychain. In sandboxed agents such as Codex, rerun with keychain access or run this command outside the sandbox.");return null}}async function uae(e,t=Vo){if(!await zi())return!1;try{try{await Zr("security",["delete-generic-password","-s",Qr,"-a",t],{timeout:5e3})}catch{}return await Zr("security",["add-generic-password","-s",Qr,"-a",t,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function dae(e=Vo){if(await zi())try{await Zr("security",["delete-generic-password","-s",Qr,"-a",e],{timeout:5e3})}catch{}}async function lae(e=Vo){if(!rI())return null;try{let{stdout:t}=await Zr("secret-tool",["lookup","service",Qr,"account",e],{timeout:5e3});return t.trim()||null}catch{return null}}async function fae(e,t=Vo){if(!rI())return!1;try{let r=(0,zc.execFile)("secret-tool",["store","--label",`${Qr} ${t}`,"service",Qr,"account",t]);return r.stdin?(r.stdin.write(e),r.stdin.end(),await Promise.race([new Promise((n,i)=>{r.on("exit",o=>o===0?n():i(new Error(`secret-tool exited ${o}`))),r.on("error",i)}),new Promise((n,i)=>setTimeout(()=>{r.kill(),i(new Error("secret-tool timed out"))},rae))]),!0):!1}catch{return!1}}async function pae(e=Vo){if(rI())try{await Zr("secret-tool",["clear","service",Qr,"account",e],{timeout:5e3})}catch{}}function rI(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function mae(e=Jo){if(!await zi())return null;try{let{stdout:t}=await Zr("security",["find-generic-password","-s",Qr,"-a",e,"-w"],{timeout:5e3});return t.trim()||null}catch{return null}}async function gae(e,t=Jo){if(await zi())try{try{await Zr("security",["delete-generic-password","-s",Qr,"-a",t],{timeout:5e3})}catch{}await Zr("security",["add-generic-password","-s",Qr,"-a",t,"-w",e],{timeout:5e3})}catch{}}async function Q3(e=Jo){if(await zi())try{await Zr("security",["delete-generic-password","-s",Qr,"-a",e],{timeout:5e3})}catch{}}function hae(e=Jo){if(!aae())return null;try{return(0,zc.execFileSync)("security",["find-generic-password","-s",Qr,"-a",e,"-w"],{timeout:1e3,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()||null}catch{return null}}function sl(e=Wi()){try{return zt.readFileSync(e,"utf-8").trim()||null}catch(t){if(tI(t))throw new d0(`Unable to read Visa CLI credentials from ${e}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function u0(e,t=Wi()){let r=al.dirname(t);zt.mkdirSync(r,{recursive:!0,mode:448}),zt.writeFileSync(t,e,{mode:384}),process.platform==="win32"&&yae(t)}function Wc(e=Wi()){try{zt.unlinkSync(e)}catch{}}function yae(e){try{let t=tm.userInfo().username;(0,zc.execFile)("icacls",[e,"/inheritance:r","/grant:r",`${t}:F`],{timeout:5e3},r=>{r&&console.error(`[visa-cli] icacls ACL restriction failed: ${r.message}`)})}catch(t){console.error(`[visa-cli] Failed to invoke icacls: ${t instanceof Error?t.message:String(t)}`)}}function em(e=Vo,t=Wi()){switch(process.platform){case"darwin":return{get:()=>cae(e),store:r=>uae(r,e),delete:()=>dae(e)};case"linux":return{get:()=>lae(e),store:r=>fae(r,e),delete:()=>pae(e)};default:return{get:async()=>sl(t),store:async r=>{try{return u0(r,t),!0}catch{return!1}},delete:async()=>Wc(t),storesInSessionFile:!0}}}var Ai=class{static profileBackend(t){return em(a0(t),sa(t))}static async getSessionToken(t=process.env){if(Si(t))return Promise.resolve(k3());let r=Xr(t);if(!r&&il(t).length>0)return null;let n=r?this.profileBackend(r):em(),i=r?sa(r,t):Wi(t),o=await n.get();if(o)return o;let s=sl(i);return s?(await n.store(s),s):null}static async saveSessionToken(t,r={}){let n=r.env??process.env;if(Si(n))return;let i=Xr(n);if(i){await this.saveProfileSessionToken(i,t,r);return}let o=em(),s=Wi(n),a=await o.store(t);if(a&&await o.get()===t){o.storesInSessionFile||Wc(s);return}if(a&&await o.delete(),u0(t,s),sl(s)!==t)throw new Error("Failed to persist session token in the unlabeled slot.")}static async saveProfileSessionToken(t,r,n={}){let i=n.env??process.env;if(Si(i))return;let o=this.profileBackend(t),s=sa(t,i);if(await o.store(r)){if(await o.get()===r){o.storesInSessionFile||Wc(s),n.preserveLegacy||await this.deleteLegacySessionToken(i);return}await o.delete()}if(u0(r,s),sl(s)!==r)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${al.dirname(s)} is writable.`));n.preserveLegacy||await this.deleteLegacySessionToken(i)}static async retireLegacySessionToken(t=process.env){Si(t)||await this.deleteLegacySessionToken(t)}static async deleteLegacySessionToken(t=process.env){await em().delete(),Wc(Wi(t))}static async getRcAccessRecord(t=process.env){if(Si(t)){let s=zA(t);return{token:s,source:s?"keychain":null}}let r=c0(t),n=ol(t),i=await mae(r);if(i)return{token:i,source:"keychain"};let o=sl(n);return o?{token:o,source:"file"}:{token:null,source:null}}static getRcAccessRecordSync(t=process.env){if(Si(t)){let s=zA(t);return{token:s,source:s?"keychain":null}}let r=c0(t),n=ol(t),i=hae(r);if(i)return{token:i,source:"keychain"};let o=sl(n);return o?{token:o,source:"file"}:{token:null,source:null}}static async getRcAccessToken(t=process.env){return(await this.getRcAccessRecord(t)).token}static getRcAccessTokenSync(t=process.env){return this.getRcAccessRecordSync(t).token}static async saveRcAccessToken(t,r=process.env){if(Si(r))return;let n=c0(r),i=ol(r);await gae(t,n);try{u0(t,i)}catch{}}static async deleteRcAccessToken(t=process.env){if(Si(t))return;let r=c0(t),n=ol(t);await Q3(r),r!==Jo&&await Q3(Jo),Wc(n)}static async deleteSessionToken(t=process.env){if(Si(t))return;let r=Xr(t),n=r?this.profileBackend(r):em(),i=r?sa(r,t):Wi(t);await n.delete(),Wc(i)}static async deleteProfileSessionToken(t,r=process.env){Si(r)||(await this.profileBackend(t).delete(),Wc(sa(t,r)))}static async listKeychainItems(t){if(!await zi())return[];try{let{stdout:r}=await Zr("security",["dump-keychain"],{timeout:5e3}),n=r.split(`
102
+ `),i=[],o=null,s=null;for(let a of n){a.includes("keychain:")&&(o===t&&s&&!i.includes(s)&&i.push(s),o=null,s=null);let c=a.match(/"svce"<blob>="([^"]+)"/);c&&(o=c[1]);let u=a.match(/"acct"<blob>="([^"]+)"/);u&&(s=u[1])}return o===t&&s&&!i.includes(s)&&i.push(s),i}catch{return[]}}static async listStoredCredentials(t={}){let r=t.env??process.env,n=[];if(process.platform==="darwin"&&await zi())for(let a of["visa-cli","visa-mcp"]){let c=await this.listKeychainItems(a);for(let u of c)n.push({service:a,account:u,backend:"keychain"})}let i=Wi(r);zt.existsSync(i)&&n.push({service:"visa-cli",account:Vo,backend:"file",path:i});let o=il(r);for(let a of o){let c=sa(a,r);zt.existsSync(c)&&n.push({service:"visa-cli",account:a0(a),backend:"file",path:c})}let s=ol(r);return zt.existsSync(s)&&n.push({service:"visa-cli",account:Jo,backend:"file",path:s}),n}static async purgeAll(t={}){let r=t.env??process.env,n=[];if(process.platform==="darwin"&&await zi())for(let a of["visa-cli","visa-mcp"]){let c=await this.listKeychainItems(a);for(let u of c)try{await Zr("security",["delete-generic-password","-s",a,"-a",u],{timeout:5e3}),n.push({service:a,account:u,backend:"keychain"})}catch{}}let i=Wi(r);if(zt.existsSync(i))try{zt.unlinkSync(i),n.push({service:"visa-cli",account:Vo,backend:"file",path:i})}catch{}let o=ol(r);if(zt.existsSync(o))try{zt.unlinkSync(o),n.push({service:"visa-cli",account:Jo,backend:"file",path:o})}catch{}let s=il(r);for(let a of s){let c=sa(a,r);if(zt.existsSync(c))try{zt.unlinkSync(c),n.push({service:"visa-cli",account:a0(a),backend:"file",path:c})}catch{}}try{Y3(r)}catch{}return await sae(s),n}static async clearAll(t=process.env){for(let r of il(t))await this.deleteProfileSessionToken(r,t);await this.deleteLegacySessionToken(t),await this.deleteRcAccessToken(t)}};var _ae=15*6e4;function Ko(e=process.env){return iI.join(Xe(e),"session-recovery")}var bae="pending.json",nI=/^[A-Za-z0-9_-]{43}$/,tB="ABCDEFGHJKMNPQRSTUVWXYZ23456789",Eae=6,wae=512,vae=2048,nB=2147483647;function Yc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function l0(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Sae(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function en(e){if(typeof e!="string"||e.length===0||e.length>vae)throw new Error("v4 sign-in URL must be a bounded web origin");let t;try{t=new URL(e)}catch{throw new Error("v4 sign-in URL must be a bounded web origin")}if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.pathname!==""&&t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&Sae(t.hostname)))throw new Error("v4 sign-in URL must use an HTTPS origin (or HTTP loopback)");return t.origin}function Yi(e){let t=(0,cl.createHash)("sha256").update(`${e}:visa-cli-handoff-confirm`,"utf8").digest(),r="";for(let n=0;n<Eae;n+=1)r+=tB[t[n]%tB.length];return r}function nm(e=Ko()){return iI.join(e,bae)}function Aae(e){Go.mkdirSync(e,{recursive:!0,mode:448});let t=Go.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("login recovery directory must be a real directory, not a symlink");Go.chmodSync(e,448),Lr(e)}function Iae(e){if(!Yc(e)||!l0(e,["verifier","challenge","baseUrl","createdAt","expiresAt","serverSkewMs"])||typeof e.verifier!="string"||!nI.test(e.verifier)||typeof e.challenge!="string"||!nI.test(e.challenge)||typeof e.baseUrl!="string"||!Number.isSafeInteger(e.createdAt)||e.createdAt<0||e.expiresAt!==void 0&&(!Number.isSafeInteger(e.expiresAt)||e.expiresAt<0)||e.serverSkewMs!==void 0&&!Number.isSafeInteger(e.serverSkewMs))return!1;try{return en(e.baseUrl)===e.baseUrl&&(0,cl.createHash)("sha256").update(e.verifier,"utf8").digest("base64url")===e.challenge}catch{return!1}}function iB(e=Ko()){let t=cr(nm(e),{maxBytes:8192});if(t===null)return null;let r;try{r=JSON.parse(t)}catch{throw new Error("local login recovery state contains invalid JSON")}if(!Iae(r))throw new Error("local login recovery state is invalid");return r}function oI(e){return e.expiresAt!==void 0?{deadline:e.expiresAt,skewMs:e.serverSkewMs??0,source:"server"}:{deadline:e.createdAt+_ae,skewMs:0,source:"local"}}function f0(e=Date.now(),t=Ko()){let r=iB(t);if(!r)return null;let n=Yi(r.verifier),{deadline:i,skewMs:o,source:s}=oI(r),a=Math.max(0,i-(e+o)),c=Math.floor(a/1e3),u=cB(r,e);return{verifier:r.verifier,challenge:r.challenge,confirmCode:n,baseUrl:r.baseUrl,createdAt:r.createdAt,expiresAt:new Date(i-o).toISOString(),remainingSeconds:c,likelyExpired:u,expirySource:s}}function rB(e=Ko()){Lr(e)&&Go.rmSync(nm(e),{force:!0})}var Pae="/api/vgs/cli-handoff/announce",oB="This Visa server has no terminal sign-in endpoint, so sign-in cannot finish. This is a server problem, not something you did. Please report it.";function sB(e){return!Yc(e)||typeof e.error!="string"&&e.ok===void 0}async function Tae(e,t,r,n){try{let i=await r(`${e.baseUrl}${Pae}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({challenge:e.challenge}),signal:AbortSignal.timeout(n),redirect:"error"}),o=await i.json().catch(()=>null);if(i.status===404&&sB(o))return"route_missing";if(!i.ok||!Yc(o)||o.ok!==!0)return null;let s=typeof o.serverTime=="string"?Date.parse(o.serverTime):NaN,a=o.ttlMs;return!Number.isSafeInteger(s)||s<0||typeof a!="number"||!Number.isSafeInteger(a)||a<=0||a>nB?null:{expiresAt:s+a,skewMs:s-t}}catch{return null}}async function aB(e,t=Date.now(),r=Ko(),n={}){if(!Number.isSafeInteger(t)||t<0)throw new Error("login handoff time is invalid");let i=en(e),o=rm(n.requestTimeoutMs,5e3,"login announce timeout"),s=n.fetchImpl??fetch;if(n.verifier!==void 0&&!nI.test(n.verifier))throw new Error("login handoff verifier is invalid");let a=n.verifier??(0,cl.randomBytes)(32).toString("base64url"),c=(0,cl.createHash)("sha256").update(a,"utf8").digest("base64url"),u={verifier:a,challenge:c,baseUrl:i,createdAt:t};Aae(r),Ht(nm(r),JSON.stringify(u,null,2));let d=await Tae(u,t,s,o);if(d==="route_missing")throw Go.rmSync(nm(r),{force:!0}),new Error(oB);d&&(u.expiresAt=d.expiresAt,u.serverSkewMs=d.skewMs,Ht(nm(r),JSON.stringify(u,null,2)));let{deadline:l,skewMs:m,source:p}=oI(u);return{challenge:c,confirmCode:Yi(a),expiresAt:new Date(l-m).toISOString(),expirySource:p}}function rm(e,t,r){let n=e??t;if(!Number.isSafeInteger(n)||n<=0||n>nB)throw new Error(`${r} must be a positive integer within the supported range`);return n}function cB(e,t=Date.now()){let{deadline:r,skewMs:n}=oI(e);return t+n>r}function xae(e){if(!Yc(e)||!l0(e,["payload"])||!Yc(e.payload)||!l0(e.payload,["cliSessionToken","ownerProfile"]))return null;let t=e.payload.cliSessionToken,r=e.payload.ownerProfile;return typeof t!="string"||!t.trim()||t.length>wae||!Yc(r)||!l0(r,["ownerPublicId","loginLabel","authOrigin"])||typeof r.ownerPublicId!="string"||typeof r.loginLabel!="string"||typeof r.authOrigin!="string"?null:{sessionToken:t,ownerProfile:{ownerPublicId:r.ownerPublicId,loginLabel:r.loginLabel,authOrigin:r.authOrigin}}}async function p0(e,t={}){let r=t.loginDir??Ko(),n;try{n=iB(r)}catch(v){return{status:"error",message:v instanceof Error?v.message:String(v)}}if(!n)return{status:"no_pending"};if(e!==void 0){let v;try{v=en(e)}catch(A){return{status:"error",message:A instanceof Error?A.message:String(A)}}if(v!==n.baseUrl)return{status:"error",message:"V4 sign-in origin does not match the pending handoff. Run agent login again."}}let i,o,s,a;try{i=rm(t.attempts,1,"login claim attempts"),o=rm(t.delayMs,1e3,"login claim interval"),s=rm(t.requestTimeoutMs,1e4,"login claim request timeout"),a=t.overallTimeoutMs===void 0?void 0:rm(t.overallTimeoutMs,1,"login claim overall timeout")}catch(v){return{status:"error",message:v instanceof Error?v.message:String(v)}}let c=t.fetchImpl??fetch,u=t.sleep??(v=>new Promise(A=>setTimeout(A,v))),d=t.now??Date.now,l=a===void 0?void 0:d()+a,m=`${n.baseUrl}/api/vgs/cli-handoff/claim`,p=null,h=n,y=h.expiresAt!==void 0,b=()=>p==="expired"||p==="unknown"&&y?{status:"not_ready",likelyExpired:!0,expirySource:"server"}:p==="pending"?{status:"not_ready",likelyExpired:!1,expirySource:"server"}:{status:"not_ready",likelyExpired:cB(h,d()),expirySource:"local"};for(let v=0;v<i;v+=1){let A=l===void 0?s:l-d();if(A<=0)return b();let E,S=AbortSignal.timeout(Math.max(1,Math.min(s,A)));try{E=await c(m,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({verifier:n.verifier}),signal:S,redirect:"error"})}catch(T){if(S.aborted||Yc(T)&&T.name==="TimeoutError"){if(l!==void 0&&d()>=l)return b();if(v+1<i){let x=l===void 0?o:l-d();if(x<=0)return b();await u(Math.min(o,x));continue}return{status:"error",message:"V4 sign-in claim request timed out."}}if(v+1<i){let x=l===void 0?o:l-d();if(x<=0)return b();await u(Math.min(o,x));continue}return{status:"error",message:`Could not reach the v4 sign-in service: ${T instanceof Error?T.message:String(T)}`}}if(E.ok){let T=await E.json().catch(()=>null),x=xae(T);if(!x)return{status:"error",message:"Sign-in response was not a session-only handoff. Restart with visa agent login --restart."};try{let C=K3(x.ownerProfile);await Ai.saveProfileSessionToken(C,x.sessionToken,{preserveLegacy:!0}),W3(C),await Ai.retireLegacySessionToken()}catch{return{status:"error",message:"The session reached this device but could not be saved. Fix local credential storage, then restart with visa agent login --restart."}}return rB(r),{status:"claimed"}}if(E.status===404){let T=await E.json().catch(()=>null);if(sB(T))return{status:"error",message:oB};let x=typeof T?.serverTime=="string"&&typeof T.error=="string"?T.error:null;if(x==="expired"?p="expired":x==="unknown_handoff"?p="unknown":x==="not_ready"&&(p="pending"),p==="expired"||p==="unknown"&&y)return b();if(v+1<i){let C=l===void 0?o:l-d();if(C<=0)return b();await u(Math.min(o,C))}continue}if(E.status===409)return{status:"confirm_mismatch",confirmCode:Yi(n.verifier)};if(E.status===422)return rB(r),{status:"error",message:"Sign-in pickup was not login-only. Run agent login again."};if(E.status===429)return b();let I=await E.json().catch(()=>null);return{status:"error",message:typeof I?.error=="string"&&I.error.length<=512?I.error:`V4 sign-in claim failed (${E.status}).`}}return b()}var ul=se(require("fs")),uI=require("node:net"),gB=se(require("os")),hB=se(require("path"));var g0=se(require("fs")),sI=se(require("path")),uB=se(require("os")),m0=class{static ensureConfigDir(){let t=this.getConfigDir();g0.existsSync(t)||g0.mkdirSync(t,{recursive:!0,mode:448})}static getConfigDir(){let t=process.env.VISA_CLI_HOME;return typeof t=="string"&&t.trim().length>0?sI.join(t,".visa-mcp"):sI.join(uB.homedir(),".visa-mcp")}};var tn=se(require("fs")),cI=se(require("path")),dB=se(require("os")),aI=cI.join(dB.homedir(),".visa-mcp"),im=cI.join(aI,"mcp-server.log"),Oae=5*1024*1024,om=null;function Rae(){tn.existsSync(aI)||tn.mkdirSync(aI,{recursive:!0,mode:448})}function Cae(){if(!om){if(Rae(),tn.existsSync(im)&&tn.statSync(im).size>Oae){let t=im+".1";tn.existsSync(t)&&tn.unlinkSync(t),tn.renameSync(im,t)}om=tn.createWriteStream(im,{flags:"a"})}return om}function Nae(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"}function h0(e,...t){let r=new Date().toISOString(),n=t.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),i=`[${r}] [${e}] ${n}
103
+ `;Nae(e)&&process.stderr.write(i),Cae().write(i)}var ne={debug:(...e)=>h0("DEBUG",...e),info:(...e)=>h0("INFO",...e),warn:(...e)=>h0("WARN",...e),error:(...e)=>h0("ERROR",...e)};function lB(e=2e3){let t=om;return t?(om=null,new Promise(r=>{let n=setTimeout(r,e);n.unref?.(),t.end(()=>{clearTimeout(n),r()})})):Promise.resolve()}function pB(e){let t=gB.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}var jae="settings.json",Mae="must use https unless it points at localhost/loopback for local development";function qae(){return hB.join(m0.getConfigDir(),jae)}function yB(e){if((0,uI.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function Dae(e){let t=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!t)return!1;let r=Number.parseInt(t[1],16),n=Number.parseInt(t[2],16);if(!Number.isFinite(r)||!Number.isFinite(n))return!1;let i=[r>>8&255,r&255,n>>8&255,n&255].join(".");return yB(i)}function Lae(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let r=(0,uI.isIP)(t);return r===4?yB(t):r===6?t==="::1"||Dae(t):!1}function mB(e,t="auth.serverUrl"){let r;try{r=new URL(e)}catch{throw new Error(`${t} must be a valid URL (got: ${JSON.stringify(e)})`)}if(r.username||r.password)throw new Error(`${t} must not include username or password credentials`);if(r.protocol!=="https:"&&!(r.protocol==="http:"&&Lae(r.hostname)))throw new Error(`${t} ${Mae}`)}function Bae(){let e=qae();if(!ul.existsSync(e))return{};try{let t=ul.readFileSync(e,"utf-8"),r=JSON.parse(t);return!r||typeof r!="object"||Array.isArray(r)?(ne.warn("settings:corrupt",{path:pB(e),reason:"not_object"}),{}):r}catch(t){return ne.warn("settings:corrupt",{path:pB(e),error:t?.message||String(t)}),{}}}function dI(e){let t=Bae()[e];return typeof t=="string"?t:void 0}var Uae="https://auth.visacli.sh",lI="https://auth-visa-code-preview.up.railway.app";function Hae(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Fae(){try{let e=fB();return Hae(e.version)}catch{return!1}}function $ae(e){return e.envVar!==void 0&&e.envVar!==""?(mB(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(mB(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?lI:Uae}function aa(){return $ae({envVar:process.env.VISA_AUTH_URL,settingValue:dI("auth.serverUrl"),isPrerelease:Fae()})}var Jae="5.0.0-rc.408",Vae="https://app.visacli.sh",_B="https://web-visa-code-preview.up.railway.app",Gae="/agent/enroll";function Kae(e=Jae){return/-(?:rc|alpha|beta)\./i.test(e)}function fI(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Wae(e=process.env){let t=e.VISA_AUTH_URL?.trim()||dI("auth.serverUrl");if(!t)return!1;try{return new URL(t).origin===new URL(lI).origin}catch{return!1}}function ca(e=process.env){let t=e.VISA_VERIFY_WEB_URL?.trim();return t?fI(t):Wae(e)||Kae()?_B:Vae}function bB(e){return`${fI(e)}${Gae}`}var EB="one-code-terminal-sign-in";async function wB(e,t){let r=t?.fetchImpl??fetch,n=t?.maxAttempts??3,i=t?.timeoutMs??5e3,o=t?.sleep??(d=>new Promise(l=>setTimeout(l,d))),s=`${fI(e)}/api/agent-enroll/health`,a=null,c=null;for(let d=1;d<=n;d++){t?.onProgress?.(d,n,s);try{if(c=await r(s,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(i)}),c.ok||c.status<500)break;d<n&&await o(d*100)}catch(l){c=null,a=l,d<n&&await o(d*100)}}if(!c){let d=a instanceof Error?a.message:String(a??"network error");return{ready:!1,kind:"network",warning:`Could not reach ${s}: ${d} \u2014 the link may not work yet.`,healthUrl:s}}if(!c.ok)return c.status<500?{ready:!1,kind:"client",warning:`V4 sign-in is unavailable on this deployment (${c.status} at ${s}); refusing to open the retired GitHub flow.`,healthUrl:s}:{ready:!1,kind:"server",warning:`V4 sign-in readiness check failed (${c.status}) at ${s} \u2014 the link may not work yet.`,healthUrl:s};let u=await c.json().catch(()=>null);return u?.clients?.auth!=="turnkey"?{ready:!1,kind:"auth_mode_mismatch",warning:`V4 sign-in is not enabled on this deployment (${e}); refusing to open the retired GitHub flow.`,healthUrl:s}:{ready:!0,healthUrl:s,features:Array.isArray(u.features)?u.features.filter(d=>typeof d=="string"):[]}}var oA=require("node:fs"),jy=require("node:path"),$d=require("node:crypto"),SL=se(Cc()),Vs=se(Fs()),Jd=se(hL());var lt=se(require("node:fs")),Mc=se(require("node:path")),Rie=require("node:crypto");var Oie=se(bL());var xie=se(bL());function Cie(e){return e?.code==="ENOENT"}function sr(e){let t=JSON.parse(e),r=!1;function n(i){if(!(!i||typeof i!="object"))for(let[o,s]of Object.entries(i)){if(["networkToken","cryptogramValue","card","privateJwk","private_jwk","seed","secretKey","secret_key","privateKey","d"].includes(o))throw new Error("native_metadata_contains_private_material");if(o==="runtimeKey"&&s&&typeof s=="object"){let a=s;r||=a.v===1&&typeof a.handle=="string"&&/^[0-9a-f]{64}$/.test(a.handle)&&typeof a.binding=="object"}n(s)}}if(n(t),!r)throw new Error("native_metadata_record_required")}function Nie(e,t=process.platform){if(t!=="win32")return Lr(e);try{let r=lt.lstatSync(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("native_metadata_directory_invalid");return!0}catch(r){if(Cie(r))return!1;throw r}}function $i(e,t=process.platform){return kie(e,t,sr)}function kie(e,t,r){if(t!=="win32")return cr(e);if(!Nie(Mc.dirname(e),t))return null;let n;try{let i=lt.lstatSync(e);if(!i.isFile()||i.isSymbolicLink()||i.size>nl)throw new Error("native_metadata_file_invalid");n=lt.openSync(e,lt.constants.O_RDONLY|(lt.constants.O_NOFOLLOW??0));let o=lt.fstatSync(n);if(!o.isFile()||o.dev!==i.dev||o.ino!==i.ino)throw new Error("native_metadata_file_changed");let s=Buffer.alloc(nl+1),a=0;for(;a<s.length;){let u=lt.readSync(n,s,a,s.length-a,null);if(u===0)break;a+=u}if(a>nl)throw new Error("native_metadata_file_too_large");let c=new TextDecoder("utf-8",{fatal:!0}).decode(s.subarray(0,a));return r(c),c}catch(i){if(Cie(i))return null;throw i}finally{n!==void 0&&lt.closeSync(n)}}function In(e,t,r=process.platform){zze(e,t,r,sr)}function zze(e,t,r,n){if(r!=="win32")return Ht(e,t);if(n(t),Buffer.byteLength(t)>nl)throw new Error("native_metadata_file_too_large");if(!Nie(Mc.dirname(e),r))throw new Error("native_metadata_directory_missing");let i=Mc.join(Mc.dirname(e),`.${Mc.basename(e)}.${(0,Rie.randomUUID)()}.tmp`),o;try{if(o=lt.openSync(i,"wx",384),lt.writeFileSync(o,t,"utf8"),lt.fsyncSync(o),lt.closeSync(o),o=void 0,lt.renameSync(i,e),kie(e,r,n)!==t)throw new Error("native_metadata_readback_failed")}finally{o!==void 0&&lt.closeSync(o),lt.rmSync(i,{force:!0})}}var iA=se(Cc());async function EL(e){let{key:t,approved:r,result:n}=e;if(!n.certificate.startsWith(r.preparedCertificate.signingInput+".")||!n.delegation.startsWith(r.preparedDelegation.signingInput+"."))throw new Error("financial_device_owner_result_invalid");let i={keys:[{...e.rootPublicJwk,kid:e.rootKid}]},o=Math.floor((e.nowMs??Date.now())/1e3),s=await(0,iA.verifyRuntimeCertificate)(n.certificate,{jwks:i,nowSec:e.certificateAsOfIssue?r.preparedCertificate.claims.iat:o,expectedAgentId:t.binding.agentId,expectedRootJkt:t.binding.rootJkt,expectedRuntimeId:t.runtimeId,expectedRuntimeJkt:t.jkt,requiredPurpose:"wallet:x402"}),a=await(0,iA.verifyRuntimeDelegation)(n.delegation,{ownerJwks:i,nowSec:o,expectedRootKid:e.rootKid,expectedRootJkt:t.binding.rootJkt,expectedAgentId:t.binding.agentId,expectedRuntimeId:t.runtimeId,expectedRuntimeJkt:t.jkt,expectedNetwork:"eip155:8453",expectedLeaseIssuerJkt:r.preparedDelegation.claims.leaseIssuerJkt,expectedDelegationId:r.preparedDelegation.claims.jti});if(!a.ok&&a.reason==="delegation_expired")throw new Error("runtime_delegation_expired");if(n.v!==1||n.runtimeId!==t.runtimeId||n.childJkt!==t.jkt||!s.ok||!a.ok||a.delegation.custody==="gate")throw new Error("financial_device_owner_result_invalid");return n}function xp(e,t){if(!/^[0-9a-f-]{36}$/.test(e))throw new Error("financial_device_agent_invalid");let r=(0,jy.join)(Xe(t),"financial-device");return(0,oA.mkdirSync)(r,{recursive:!0,mode:448}),(0,jy.join)(r,e+".pending.json")}function Op(e,t){let r=$i(xp(e,t));if(r===null)return null;sr(r);let n=JSON.parse(r);if((0,Jd.financialDeviceProposalHash)(n.proposal),n.cardProposal&&(0,Jd.assertFinancialDevicePair)(n.proposal,n.cardProposal),n.v===1&&!Object.prototype.hasOwnProperty.call(n,"ceremony")){let i=xp(e,t),o=i.replace(".pending.json",`.outdated.${n.proposal.requestId}.json`);throw(0,oA.renameSync)(i,o),new Error(`financial_device_record_outdated: this device's wallet approval was started by an older Visa CLI and cannot be resumed (kept as ${(0,jy.basename)(o)}). Re-enroll: run \`visa connect\` again.`)}if(n.v!==1||!n.ceremony||typeof n.ceremony!="object"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(n.ceremony.ceremonyId)||!/^[A-Za-z0-9_-]{43}$/.test(n.ceremony.challenge)||!/^[A-Za-z0-9_-]{43}$/.test(n.ceremony.verifier)||(0,$d.createHash)("sha256").update(n.ceremony.verifier).digest("base64url")!==n.ceremony.challenge||n.proposal.agentId!==e||n.runtimeKey.binding.agentId!==e||n.runtimeKey.runtimeId!==n.proposal.runtimeId||n.runtimeKey.binding.rootJkt!==n.proposal.rootJkt||(0,SL.computeJkt)(n.rootPublicJwk)!==n.proposal.rootJkt)throw new Error("financial_device_record_invalid");return n}function wL(e,t){let r=JSON.stringify(e);sr(r),In(xp(e.proposal.agentId,t),r)}async function My(e){let t=Op(e.agentId,e.env);if(t){if((0,Vs.canonicalJson)(t.ceremony)!==(0,Vs.canonicalJson)(e.ceremony))throw new Error("financial_device_ceremony_changed");let s=await e.api.financialRuntimeRequest("device-handoff-create",{requestId:t.proposal.requestId,proposal:t.proposal,ceremony:t.ceremony,...t.cardProposal?{cardProposal:t.cardProposal}:{}}),a=Math.floor(Date.now()/1e3),c=s.prepared?.status==="active",u=p=>{if(typeof p!="string")throw new Error("financial_device_record_invalid");let h=JSON.parse(Buffer.from(p.split(".")[1]??"","base64url").toString()).exp;if(!Number.isSafeInteger(h))throw new Error("financial_device_record_invalid");return h>a},d=c&&u(s.prepared?.certificate)&&u(s.prepared?.delegation),l=!s.prepared||s.prepared.status==="pending"&&s.prepared.challenge.expiresAt>a;if(d||!c&&!s.expired&&l)return t;let m={v:1,ceremony:t.ceremony,proposal:{...t.proposal,requestId:(0,$d.randomUUID)()},runtimeKey:t.runtimeKey,rootKid:t.rootKid,rootPublicJwk:t.rootPublicJwk,...t.cardProposal?{cardProposal:t.cardProposal}:{}};try{await e.api.financialRuntimeRequest("device-handoff-create",{requestId:m.proposal.requestId,proposal:m.proposal,ceremony:m.ceremony,...m.cardProposal?{cardProposal:m.cardProposal}:{}})}catch(p){let h=jie(p)?await Mie(e.agentId,e.env,t.proposal.requestId):null;if(h)return h;throw p}return In(xp(e.agentId,e.env).replace(".pending.json",`.expired.${t.proposal.requestId}.json`),JSON.stringify(t)),wL(m,e.env),m}let r=await e.api.financialRuntimeRequest("device-context",{requestId:(0,$d.randomUUID)(),agentId:e.agentId});if(r.agentId!==e.agentId||(0,SL.computeJkt)(r.rootPublicJwk)!==r.rootJkt)throw new Error("financial_device_context_invalid");if(e.ownerPublicId!==void 0&&typeof r.ownerPublicId=="string"&&r.ownerPublicId!==e.ownerPublicId)throw new Error("Protected wallet owner differs from the active profile");let n=await e.signer.create({profile:"legacy-root-certified-v1",purpose:"wallet:x402",agentId:e.agentId,rootJkt:r.rootJkt}),i={v:1,purpose:"financial.runtime.device.proposal",requestId:(0,$d.randomUUID)(),associationId:r.associationId,associationVersion:r.associationVersion,agentId:e.agentId,runtimeId:n.runtimeId,rootJkt:r.rootJkt,publicJwk:n.publicJwk};(0,Jd.financialDeviceProposalHash)(i),e.cardProposal&&(0,Jd.assertFinancialDevicePair)(i,e.cardProposal);let o={v:1,ceremony:e.ceremony,proposal:i,...e.cardProposal?{cardProposal:e.cardProposal}:{},runtimeKey:n,rootKid:r.rootKid,rootPublicJwk:r.rootPublicJwk};return wL(o,e.env),o}var Tp=class extends Error{constructor(r=!1){super(r?Yze:"This enrollment ceremony expired. Start a fresh enrollment; this expired proposal cannot be approved.");this.stopped=r;this.name="FinancialDeviceExpiredError"}stopped},Yze="The owner stopped this device approval (the agent was removed), so visa connect did not renew it. Nothing was connected. Run visa connect again once the owner wants this agent connected.";function jie(e){return e instanceof Error&&e.name==="ProtectedAuthorityRefusedError"&&Number(e.status)<500&&!vL(e)}async function Mie(e,t,r){for(let n=0;;n++){let i=Op(e,t);if(i&&i.proposal.requestId!==r)return i;if(n>=Xze)return null;await new Promise(o=>setTimeout(o,Zze))}}var Xze=20,Zze=50;function vL(e){return e instanceof Error&&e.name==="ProtectedAuthorityRefusedError"&&e.code==="agent_revoked"}async function Rp(e){let t=e.pending,r=t.proposal,n=await e.signer.describe(t.runtimeKey.handle);if((0,Vs.canonicalJson)(n)!==(0,Vs.canonicalJson)(t.runtimeKey)||n.binding.profile!=="legacy-root-certified-v1"||n.binding.purpose!=="wallet:x402")throw new Error("financial_device_handle_changed");let i=async(c,u={})=>e.api.financialRuntimeRequest(c,{requestId:r.requestId,proposal:r,...c==="device-handoff-create"?{ceremony:t.ceremony,...t.cardProposal?{cardProposal:t.cardProposal}:{}}:{},...u}),o=await i("device-handoff-create");if(o.expired&&o.prepared?.status!=="active")throw new Tp(o.prepared?.status==="revoked");if((0,Vs.canonicalJson)(o.proposal)!==(0,Vs.canonicalJson)(r))throw new Error("financial_device_proposal_mismatch");let s=o.evidence?.owner_signatures,a=o.prepared;if(s&&a&&!o.evidence?.device_proof){if(await EL({key:n,rootKid:t.rootKid,rootPublicJwk:t.rootPublicJwk,approved:a.challenge,result:{v:1,runtimeId:r.runtimeId,childJkt:n.jkt,...s}}),t.challenge&&(0,Vs.canonicalJson)(t.challenge)!==(0,Vs.canonicalJson)(a.challenge))throw new Error("financial_device_challenge_changed");t.childPop||(t.challenge=a.challenge,t.childPop=await e.signer.financialEnrollmentProof(n.handle,a.challenge),wL(t,e.env)),o=await i("device-handoff-proof",{childPop:t.childPop})}return o}function Vd(e,t){let r=$i(xp(e,t).replace(".pending.json",".active.json"));if(r===null)return null;sr(r);let n=JSON.parse(r);if((0,Jd.financialDeviceProposalHash)(n.proposal),n.v!==1||n.proposal.agentId!==e||n.runtimeKey.binding.agentId!==e||n.runtimeKey.binding.profile!=="legacy-root-certified-v1"||n.runtimeKey.binding.purpose!=="wallet:x402"||!n.challenge||!n.certificate||!n.delegation)throw new Error("financial_device_record_invalid");return n}async function Qze(e){let t=await Rp(e);return e.onView?.(t),AL({...e,view:t})}async function AL(e){let t=e.pending,r=t.proposal,n=e.view;if(n?.prepared?.status!=="active")return null;let i=await e.signer.describe(t.runtimeKey.handle),o=await EL({key:i,rootKid:t.rootKid,rootPublicJwk:t.rootPublicJwk,approved:n.prepared.challenge,result:{v:1,runtimeId:r.runtimeId,childJkt:i.jkt,certificate:n.prepared.certificate,delegation:n.prepared.delegation}}),s=await e.api.financialRuntimeRequest("device-context",{requestId:(0,$d.randomUUID)(),agentId:r.agentId});if(s.associationId!==r.associationId||s.associationVersion!==r.associationVersion||s.rootJkt!==r.rootJkt||typeof s.grantId!="string"||!Number.isSafeInteger(s.grantVersion)||s.grantVersion<1||typeof s.ownerPublicId!="string")throw new Error("financial_device_activation_changed");let a={...t,challenge:n.prepared.challenge,certificate:o.certificate,delegation:o.delegation,organizationId:s.organizationId,ownerPublicId:s.ownerPublicId,grantId:s.grantId,grantVersion:s.grantVersion},c=JSON.stringify(a);return sr(c),In(xp(r.agentId,e.env).replace(".pending.json",".active.json"),c),a}async function qie(e){try{return{active:await Qze(e),pending:e.pending,renewed:!1}}catch(t){if(vL(t))throw new Tp(!0);let r=e.pending.ceremony&&jie(t)?await Mie(e.pending.proposal.agentId,e.env,e.pending.proposal.requestId):null;if(r)return{active:null,pending:r,renewed:!0};if(!(t instanceof Tp)||!e.pending.ceremony||t.stopped)throw t;let n=e.pending.proposal.requestId,i;try{i=await My({api:e.api,signer:e.signer,agentId:e.pending.proposal.agentId,ceremony:e.pending.ceremony,env:e.env}),e.onView?.(await Rp({...e,pending:i}))}catch(o){let s=o instanceof Error&&o.name==="ProtectedAuthorityRefusedError"&&o.status<500;throw ne.warn("agent:device_approval_renewal_refused",{agentId:e.pending.proposal.agentId,expiredRequestId:n,refused:s,error:o instanceof Error?o.message:String(o)}),vL(o)?new Tp(!0):s?t:o}return ne.info("agent:device_approval_renewed",{agentId:i.proposal.agentId,expiredRequestId:n,requestId:i.proposal.requestId}),{active:null,pending:i,renewed:!0}}}var Uy=require("node:crypto"),Lo=require("node:fs"),ar=require("node:path");var Die=/^[A-Za-z0-9_-]{43}$/,eYe=/^[0-9a-f]{64}$/,tYe=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function IL(e,t){let r=e;return!!r&&typeof r=="object"&&eYe.test(r.handle)&&tYe.test(r.runtimeId)&&r.purpose===t&&Die.test(r.jkt)&&!!r.publicJwk&&r.publicJwk.kty==="OKP"&&r.publicJwk.crv==="Ed25519"&&Die.test(r.publicJwk.x)}function PL(e){let t=e;if(!t||t.v!==2||!IL(t.wallet,"wallet:x402")||!IL(t.card,"card:vic")||!IL(t.tap,"tap")||new Set([t.wallet.jkt,t.card.jkt,t.tap.jkt]).size!==3)throw new Error("device_key_reservation_invalid");return t}async function Lie(e){return{v:2,wallet:await e.reserve("wallet:x402"),card:await e.reserve("card:vic"),tap:await e.reserve("tap")}}function sA(e){return`${e.wallet.jkt}.${e.card.jkt}.${e.tap.jkt}`}function Bie(e,t){let r={"wallet:x402":t.wallet,"card:vic":t.card,tap:t.tap};return{create:(n,i)=>e.adopt(r[n.purpose].handle,n,i),describe:n=>e.describe(n),delete:n=>e.delete(n),enrollmentProof:(n,i)=>e.enrollmentProof(n,i),handoffProof:(n,i)=>e.handoffProof(n,i),leaseProof:(n,i)=>e.leaseProof(n,i),tapProof:(n,i,o)=>e.tapProof(n,i,o),financialEnrollmentProof:(n,i)=>e.financialEnrollmentProof(n,i),cardEnrollmentProof:(n,i)=>e.cardEnrollmentProof(n,i),legacyProof:(n,i)=>e.legacyProof(n,i),legacyLeaseProof:(n,i)=>e.legacyLeaseProof(n,i),proofKey:n=>e.proofKey(n),close:()=>e.close()}}var noe=se(Cc()),Ks=se(CL()),dA=se(Fn()),Mp=se(Fs());var Vie=se(require("fs")),Gie=se(require("os")),kp=se(require("path"));function CYe(e){return[["openclaw",kp.join(e,".openclaw")],["hermes",kp.join(e,".hermes")],["claude-code",kp.join(e,".claude")],["codex",kp.join(e,".codex")],["gemini",kp.join(e,".gemini")]]}function Kie(e=process.env,t={}){if(e.VISA_CLI_RUNTIME&&e.VISA_CLI_RUNTIME.trim().length>0)return e.VISA_CLI_RUNTIME.trim();if(e.AGENT_RUNTIME&&e.AGENT_RUNTIME.trim().length>0)return e.AGENT_RUNTIME.trim();let r=s=>Object.entries(e).some(([a,c])=>a.startsWith(s)&&typeof c=="string"&&c.trim()!==""),n=new Set;if(r("CODEX_")&&n.add("codex"),(typeof e.CLAUDECODE=="string"&&e.CLAUDECODE.trim()!==""||r("CLAUDE_CODE_")||typeof e.CLAUDE_PROJECT_DIR=="string"&&e.CLAUDE_PROJECT_DIR.trim()!=="")&&n.add("claude-code"),r("OPENCLAW_")&&n.add("openclaw"),r("HERMES_")&&n.add("hermes"),(r("ANTIGRAVITY_")||r("GEMINI_"))&&n.add("gemini"),n.size>0)return n.size===1?n.values().next().value:void 0;let i=t.home??Gie.homedir(),o=CYe(i).filter(([,s])=>Vie.existsSync(s));return o.length===1?o[0][0]:void 0}var zie=require("node:child_process"),Yie=se(require("node:os")),NYe=64,kYe={platform:process.platform,computerName:()=>{try{return(0,zie.execFileSync)("scutil",["--get","ComputerName"],{encoding:"utf8",timeout:1e3,stdio:["ignore","pipe","ignore"]})}catch{return null}},hostname:()=>Yie.default.hostname()};function cA(e=kYe){let t=e.platform==="darwin"?[e.computerName(),Wie(e)]:[Wie(e)];for(let r of t){let n=jYe(r);if(n)return n}return null}function Wie(e){try{return e.hostname().replace(/\.local\.?$/i,"")}catch{return null}}function jYe(e){if(typeof e!="string")return null;let t=e.normalize("NFC").replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu," ").replace(/\s+/gu," ").trim();return t&&Array.from(t).slice(0,NYe).join("").trim()||null}var Zie=require("node:crypto");var NL=null,Xie=null,kL=null;function MYe(){return kL||(kL=`ms_${(0,Zie.randomUUID)().replace(/-/g,"")}`),kL}function qYe(){return NL?Xie?`${NL}/${Xie}`.slice(0,96):NL:null}function jp(){let e={"X-Visa-MCP-Session":MYe()},t=qYe();return t&&(e["X-Visa-MCP-Client"]=t),e}var DYe=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Qie(e){return jL(e)!==null}function ML(e,t){let r=jL(e),n=jL(t);if(!r||!n)return!1;for(let i=0;i<3;i++)if(r.main[i]!==n.main[i])return r.main[i]>n.main[i];return r.pre&&!n.pre?!1:!r.pre&&n.pre?!0:!r.pre&&!n.pre?!1:LYe(r.pre,n.pre)>0}function jL(e){if(typeof e!="string")return null;let r=e.trim().replace(/^v/,"").match(DYe);return r?{main:[Number(r[1]),Number(r[2]),Number(r[3])],pre:r[4]??null}:null}function LYe(e,t){let r=e.split("."),n=t.split("."),i=Math.max(r.length,n.length);for(let o=0;o<i;o++){if(o>=r.length)return-1;if(o>=n.length)return 1;let s=r[o],a=n[o],c=/^\d+$/.test(s),u=/^\d+$/.test(a);if(c&&u){let d=Number(s)-Number(a);if(d!==0)return d}else{if(c)return-1;if(u)return 1;if(s<a)return-1;if(s>a)return 1}}return 0}var qL="4.1.0-rc.70",By=class extends Error{code="update_required";errorCode="update_required";runningVersion;minCompatibleVersion;updateCommand;constructor(t,r,n){let i=`CLI/MCP update required${n?` for ${n}`:""}: running v${t}, minimum compatible version is v${r}. Run: npm install -g @visa/cli@rc`;super(i),this.name="UpdateRequiredError",this.runningVersion=t,this.minCompatibleVersion=r,this.updateCommand="npm install -g @visa/cli@rc"}toJSON(){return{success:!1,error_code:this.errorCode,error:this.message,runningVersion:this.runningVersion,minCompatibleVersion:this.minCompatibleVersion,updateCommand:this.updateCommand}}};function uA(e,t,r){let n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},i=e<200||e>=300||n.ok===!1||n.success===!1;if(e!==426&&!(i&&[n.error,n.code,n.error_code,n.errorCode].includes("update_required")))return null;let o=(s,a)=>typeof s=="string"&&s.length<=64&&!/[^0-9A-Za-z.+-]/.test(s)&&Qie(s)?s.replace(/^v/,""):a;return new By(o(n.runningVersion,r),o(n.minCompatibleVersion,qL))}var eoe="5.0.0-rc.408",BYe=(0,Ks.toDisplay)((0,Ks.fromCents)(dA.SETUP_DEFAULT_DAILY_CENTS),{decimals:0,symbol:""}),UYe=(0,Ks.toDisplay)((0,Ks.fromCents)(dA.SETUP_DEFAULT_PER_PURCHASE_CENTS),{decimals:0,symbol:""}),qc=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Hy=/^[A-Za-z0-9_-]{43}$/,ioe=e=>(0,Uy.createHash)("sha256").update(e).digest("base64url");function Dc(e){let t=en(e);if(new URL(t).protocol!=="https:")throw new Error("Protected enrollment requires the HTTPS Auth origin");return t}function Kd(e){let t=(0,ar.join)(Xe(e),"protected-enrollment");return(0,Lo.mkdirSync)(t,{recursive:!0,mode:448}),Lr(t),t}function BL(e,t,r){if(!e||e.status!=="active"||e.v!==1||!qc.test(e.ceremonyId)||e.challenge!==t||e.confirmCode!==r||!Hy.test(t)||!/^[ABCDEFGHJKMNPQRSTUVWXYZ23456789]{6}$/.test(r)||!qc.test(e.agentId)||!qc.test(e.ownerPublicId)||!qc.test(e.associationId)||!Number.isSafeInteger(e.associationVersion)||e.associationVersion<1||typeof e.rootKid!="string"||!e.rootKid||typeof e.organizationId!="string"||!e.organizationId||(0,noe.computeJkt)(e.rootPublicJwk)!==e.rootJkt)throw new Error("Protected enrollment result does not match this terminal")}function Ei(e){let t=cr((0,ar.join)(Kd(e),"pending.json"));if(t===null)return null;let r=JSON.parse(t);if(r.v!==1||!Hy.test(r.verifier)||ioe(r.verifier)!==r.challenge||Dc(r.authorityOrigin)!==r.authorityOrigin||Dc(r.executionOrigin)!==r.executionOrigin||en(r.webOrigin)!==r.webOrigin||!Number.isSafeInteger(r.createdAt)||!(/^(?:ca_[A-Za-z0-9_-]{24})$/.test(r.ceremonyId)||qc.test(r.ceremonyId))||r.signIn!==void 0&&r.signIn!==!0||r.restart!==void 0&&r.restart!==!0||r.requestedLimits!==void 0&&!ooe(r.requestedLimits))throw new Error("Protected enrollment pending state or transport profile changed");if(r.transportProfileId!==(Xr(e)?.profileId??null)&&!UL(r,e))throw new Error("Protected enrollment pending state or transport profile changed");if(r.binding&&(BL(r.binding,r.challenge,Yi(r.verifier)),r.ceremonyId!==r.binding.ceremonyId))throw new Error("Protected enrollment ceremony changed");if(r.deviceKeys!==void 0&&PL(r.deviceKeys),r.webStartKey!==void 0&&!Hy.test(r.webStartKey))throw new Error("Protected enrollment pending state or transport profile changed");return r}function ooe(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e,r=n=>n===void 0||Number.isSafeInteger(n)&&n>0;return Object.keys(t).every(n=>n==="dailyCents"||n==="perPurchaseCents")&&(t.dailyCents!==void 0||t.perPurchaseCents!==void 0)&&r(t.dailyCents)&&r(t.perPurchaseCents)}function LL(e){if(!e)return null;let t={...e.dailyCents!==void 0?{dailyCents:e.dailyCents}:{},...e.perPurchaseCents!==void 0?{perPurchaseCents:e.perPurchaseCents}:{}};return t.dailyCents===void 0&&t.perPurchaseCents===void 0?null:t}function HYe(e,t){return e?.dailyCents===t?.dailyCents&&e?.perPurchaseCents===t?.perPurchaseCents}function toe(e){return e?[...e.dailyCents!==void 0?[`${(0,Ks.formatCents)(e.dailyCents)} a day`]:[],...e.perPurchaseCents!==void 0?[`${(0,Ks.formatCents)(e.perPurchaseCents)} a purchase`]:[]].join(" and "):"no limits"}function soe(e,t){let r=LL(t),n=LL(e.requestedLimits);if(!(!r||HYe(n,r)))throw ne.warn("agent:protected_enrollment_limits_mismatch",{ceremonyId:e.ceremonyId,savedDailyCents:n?.dailyCents??null,savedPerPurchaseCents:n?.perPurchaseCents??null,requestedDailyCents:r.dailyCents??null,requestedPerPurchaseCents:r.perPurchaseCents??null}),new Rt(`This computer's setup is already waiting for the owner's approval and asked for ${toe(n)}, not ${toe(r)}. Nothing was changed.`,"invalid_argument",{fix:"visa connect --restart",nextAction:"To keep the open approval, run `visa connect` without --ceiling/--per-transaction (agent_enroll: omit ceiling and per_transaction); the owner can still change the limits on the page. To ask for the new limits instead, run `visa connect --restart` with them (agent_enroll: restart:true) and give the owner the new link and code.",details:{savedLimits:n,requestedLimits:r}})}var aoe=Hy;function UL(e,t){let r=Xr(t);return e.signIn!==!0||e.binding||e.transportProfileId!==null||!r?!1:(e.transportProfileId=r.profileId,Ht((0,ar.join)(Kd(t),"pending.json"),JSON.stringify(e)),!0)}function Wd(e){return e.signIn===!0&&e.transportProfileId===null&&!e.binding}async function coe(e,t,r){return e.deviceKeys?PL(e.deviceKeys):(e.deviceKeys=await Lie(t),Ht((0,ar.join)(Kd(r),"pending.json"),JSON.stringify(e)),e.deviceKeys)}function uoe(e,t){let r;try{r=Ei(t)}catch{return null}return r?.challenge===e&&r.deviceKeys?sA(r.deviceKeys):null}var Lc=9e5;function Fy(e,t){if(!e.binding)return!1;try{return Vd(e.binding.agentId,t)?.ceremony?.challenge===e.challenge}catch{return!1}}function FYe(e){try{return Ei(e)}catch(t){return ne.warn("agent:protected_enrollment_pending_replaced",{reason:t instanceof Error?t.message:"pending record could not be read"}),null}}function doe(e,t){let r,n;try{r=Ei(t),n=Dc(aa()),e=en(e)}catch{return!1}return r?.restart===!0&&Date.now()-r.createdAt<Lc&&r.authorityOrigin===n&&r.executionOrigin===n&&r.webOrigin===e&&!Fy(r,t)}function loe(e){let t=LL(e.requestedLimits);if(t&&!ooe(t))throw new Rt("Requested limits must be whole positive cents.","invalid_argument");let r=Dc(aa()),n=en(e.webOrigin);if(e.webStartKey!==void 0&&!Hy.test(e.webStartKey))throw new Rt("That setup key is not one Visa issued. Copy the whole `visa connect --setup` line from the page that started the setup.","invalid_argument");let i=FYe(e.env),o=e.restart===!0||e.webStartKey!==void 0&&i?.webStartKey!==e.webStartKey,s=i!==null&&Date.now()-i.createdAt<Lc;if(i&&s&&!o){if(i.authorityOrigin!==r||i.webOrigin!==n||i.executionOrigin!==r)throw new Error("Resume requires the original protected authority and browser origins");return soe(i,t),i}if(i?.binding&&s&&o&&!Fy(i,e.env))throw new Rt("This enrollment is already bound. Resume its device approval before starting another agent.","enrollment_device_approval_pending");let a=(0,Uy.randomBytes)(32).toString("base64url"),c={v:1,verifier:a,challenge:ioe(a),authorityOrigin:r,executionOrigin:r,webOrigin:n,transportProfileId:Xr(e.env)?.profileId??null,createdAt:Date.now(),ceremonyId:"ca_"+(0,Uy.randomBytes)(18).toString("base64url"),...e.webStartKey!==void 0?{webStartKey:e.webStartKey}:{},...e.signIn&&!Xr(e.env)?{signIn:!0}:{},...e.restart===!0?{restart:!0}:{},...t?{requestedLimits:t}:{}};return Ht((0,ar.join)(Kd(e.env),"pending.json"),JSON.stringify(c)),c}var DL={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes",gemini:"gemini",antigravity:"gemini","gemini-cli":"gemini"};function HL(e=process.env,t){let r=(t??"").trim().toLowerCase().replace(/[\s_]+/g,"-");if(r&&DL[r])return DL[r];let n=Kie(e);return n&&DL[n]||null}var $Ye="/api/vgs/cli-handoff/enrollment-code";async function foe(e,t=fetch,r=5e3){if(e.binding)return!1;try{return(await t(`${e.webOrigin}${$Ye}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({challenge:e.challenge,confirm:Yi(e.verifier)}),redirect:"error",signal:AbortSignal.timeout(r)})).ok}catch{return!1}}var JYe="/api/vgs/cli-handoff/web-start-pickup";async function poe(e,t=fetch,r=5e3,n={name:()=>cA(),os:process.platform}){if(!e.webStartKey||!e.deviceKeys||e.binding)return!1;let i=e.challenge.slice(0,8),o=Date.now();try{let s=await t(`${e.webOrigin}${JYe}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({startKey:e.webStartKey,challenge:e.challenge,confirm:Yi(e.verifier),keys:sA(e.deviceKeys),signIn:Wd(e),device:{name:n.name(),os:n.os},...e.requestedLimits?{limits:e.requestedLimits}:{}}),redirect:"error",signal:AbortSignal.timeout(r)});return ne.info("connect:web_start_announce",{ref:i,elapsedMs:Date.now()-o,ok:s.ok,...s.ok?{}:{status:s.status}}),s.ok}catch(s){return ne.info("connect:web_start_announce",{ref:i,elapsedMs:Date.now()-o,ok:!1,error:qp(s)||"unknown"}),!1}}var VYe=8;function moe(e,t,{heldAgentId:r=null,priorRuntimes:n=[],limits:i=null}={}){let o=new URL("/agent/enroll/protected-agent",e.webOrigin);o.searchParams.set("cliChallenge",e.challenge),r&&qc.test(r)&&!e.webStartKey&&o.searchParams.set("held",r),e.deviceKeys&&o.searchParams.set("keys",sA(e.deviceKeys)),e.webStartKey&&o.searchParams.set("start",e.webStartKey),t&&o.searchParams.set("app",t);let s=n.filter(a=>qc.test(a)).slice(0,VYe);return s.length&&!e.webStartKey&&o.searchParams.set("prior",s.join(",")),Wd(e)&&o.searchParams.set("signin","1"),i?.dailyCents!==void 0&&o.searchParams.set("limitDaily",String(i.dailyCents)),i?.perPurchaseCents!==void 0&&o.searchParams.set("limitPer",String(i.perPurchaseCents)),o.toString()}var GYe=2e4;var Do=class extends Error{constructor(r,n,i){super(n==="timeout"?`${r} timed out after ${Math.round(i/1e3)} s`:n==="response"?`${r} answered, but the answer could not be read`:`${r} could not be reached`);this.reason=n;this.name="ProtectedAuthorityTransportError"}reason},Pn=class extends Error{constructor(r,n,i,o=null,s=null,a=null){super(`${r} refused this request (HTTP ${n}${i?`, ${i}`:""})`);this.status=n;this.code=i;this.reason=o;this.purchaseId=s;this.approval=a;this.name="ProtectedAuthorityRefusedError"}status;code;reason;purchaseId;approval};function qp(e){let t=e&&typeof e=="object"?e.name:void 0;return typeof t=="string"?t:""}var KYe=/^[a-z][a-z0-9_]{0,63}$/;function WYe(e){let t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},r=i=>typeof i=="string"&&KYe.test(i)?i:null,n=r(t.code);return{code:n,reason:r(t.reason),approval:n==="owner_approval_required"?zYe(t.approval):null,purchaseId:t.reason==="terms_conflict"&&typeof t.purchaseId=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(t.purchaseId)?t.purchaseId:null}}function zYe(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let{approvalId:t,url:r,expiresAt:n}=e;return typeof t!="string"||t.length>64||typeof r!="string"||r.length>2048||typeof n!="string"||n.length>64?null:{approvalId:t,url:r,expiresAt:n}}async function goe(e,t,r,n,i="Protected authority",o=GYe,s={}){let a;try{a=await n(Dc(e)+t,{method:"POST",headers:{...s,"content-type":"application/json","X-Source":"cli","X-Visa-CLI-Version":eoe,...jp()},body:(0,Mp.canonicalJson)(JSON.parse(JSON.stringify(r))),redirect:"error",signal:AbortSignal.timeout(o)})}catch(u){let d=qp(u);throw new Do(i,d==="TimeoutError"||d==="AbortError"?"timeout":"network",o)}if(!a.ok){let u;try{let m=await a.text();m.length<=262144&&(u=JSON.parse(m))}catch{}let d=uA(a.status,u,eoe);if(d)throw d;let l=WYe(u);throw new Pn(i,a.status,l.code,l.reason,l.purchaseId,l.approval)}let c;try{c=await a.text()}catch{throw new Do(i,"response",o)}if(c.length>262144)throw new Do(i,"response",o);try{return JSON.parse(c)}catch{throw new Do(i,"response",o)}}function YYe(e,t=fetch){return Dc(e),{financialRuntimeRequest:(r,n)=>goe(e,`/v1/financial-runtime/${r}`,n,t)}}function XYe(e){return`This agent belongs to a different Visa account than ${e}, the account this terminal is signed in to, so nothing was connected. To use ${e}: run \`visa connect --restart\` and open the new link while signed in to ${e}. To use the other account instead: run \`visa disconnect --all\` to sign this terminal out, then \`visa connect\` and sign in with that account. \`visa disconnect --all\` also removes the Visa MCP server from every AI client, the spend HUD and any local card-delivery files; \`visa connect\` puts the server and HUD back for the client it runs for. Nothing is revoked on the server.`}async function hoe(e,t,r=fetch){if(e.transportProfileId!==(Xr(t)?.profileId??null))throw new Error("Protected enrollment transport profile changed");if(e.binding)return roe(e,e.binding,t),e.binding;if(Wd(e))return null;let n=await goe(e.executionOrigin,"/v1/enrollment/cli-claim",{verifier:e.verifier},r);if(n?.ok!==!0)throw new Error("Protected authority refused enrollment pickup");if(n.result?.status==="pending")return null;let i=n.result;BL(i,e.challenge,Yi(e.verifier));let o=Xr(t);if(o&&i.ownerPublicId!==o.ownerPublicId)throw new Rt(XYe(o.loginLabel),"enrollment_owner_mismatch");return e.ceremonyId=i.ceremonyId,e.binding=i,Ht((0,ar.join)(Kd(t),"pending.json"),JSON.stringify(e)),roe(e,i,t),i}function ZYe(e,t){let r=Xe(t);if((0,Lo.existsSync)((0,ar.join)(r,"financial-device",`${e}.active.json`)))return!0;try{let n=cr((0,ar.join)(r,"card-device",`${e}.json`));if(n&&JSON.parse(n)?.certificate)return!0}catch{}return!1}function roe(e,t,r){let n={v:1,authorityOrigin:e.authorityOrigin,executionOrigin:e.executionOrigin,transportProfileId:e.transportProfileId,binding:t},i=(0,ar.join)(Kd(r),`${t.agentId}.json`),o=cr(i);if(o!==null&&(0,Mp.canonicalJson)(JSON.parse(o))!==(0,Mp.canonicalJson)(n)){let s=null;try{s=JSON.parse(o)}catch{}if(!(s!==null&&QYe(s,n)||!ZYe(t.agentId,r)))throw new Error("Protected agent selection changed");eXe(t.agentId,r)}Ht(i,JSON.stringify(n))}function QYe(e,t){let r=e?.binding,n=t.binding;return e?.v===1&&!!r&&r.agentId===n.agentId&&r.associationId===n.associationId&&r.ownerPublicId===n.ownerPublicId&&r.organizationId===n.organizationId&&r.rootJkt===n.rootJkt&&e.authorityOrigin===t.authorityOrigin&&e.executionOrigin===t.executionOrigin&&e.transportProfileId===t.transportProfileId&&r.challenge!==n.challenge&&Number.isSafeInteger(r.associationVersion)&&n.associationVersion>=r.associationVersion}function eXe(e,t){if(!/^[0-9a-f-]{36}$/.test(e))throw new Error("Protected agent id is invalid");let r=`.replaced-${new Date().toISOString().replace(/[:.]/g,"-")}`,n=Xe(t),i=o=>(o===`${e}.json`||o.startsWith(`${e}.`))&&o.endsWith(".json")&&!o.includes(".replaced-")&&!o.includes(".bak");for(let o of[(0,ar.join)(n,"protected-enrollment"),(0,ar.join)(n,"protected-enrollment","retired"),(0,ar.join)(n,"card-device"),(0,ar.join)(n,"financial-device"),(0,ar.join)(n,"financial-device-presence")])if((0,Lo.existsSync)(o))for(let s of(0,Lo.readdirSync)(o))i(s)&&(0,Lo.renameSync)((0,ar.join)(o,s),(0,ar.join)(o,s+r));ne.info("protected-enrollment:replaced-agent-records-archived",{agentId:e})}function Bo(e,t=fetch){let r=YYe(e.executionOrigin,t);return{financialRuntimeRequest:async(n,i)=>{let o=await r.financialRuntimeRequest(n,i);if(n==="device-context"){let s=e.binding;if(o.agentId!==s.agentId||o.ownerPublicId!==s.ownerPublicId||o.associationId!==s.associationId||o.associationVersion!==s.associationVersion||o.rootJkt!==s.rootJkt||o.rootKid!==s.rootKid||o.organizationId!==s.organizationId||(0,Mp.canonicalJson)(o.rootPublicJwk)!==(0,Mp.canonicalJson)(s.rootPublicJwk))throw new Error("Protected device context differs from the independently claimed owner")}return o}}}function FL(e){let t=Kd(e);return(0,Lo.readdirSync)(t).filter(r=>qc.test(r.replace(/\.json$/,""))&&r.endsWith(".json")).flatMap(r=>{let n=cr((0,ar.join)(t,r));if(n===null)return[];let i=JSON.parse(n);if(i.v!==1||Dc(i.authorityOrigin)!==i.authorityOrigin||Dc(i.executionOrigin)!==i.executionOrigin||i.binding.agentId+".json"!==r)throw new Error("Protected selection is invalid");return BL(i.binding,i.binding.challenge,i.binding.confirmCode),[i]})}function Dp(e){let t=Xr(e)?.profileId??null;return FL(e).filter(r=>r.transportProfileId===t)}function yoe(e,t){let r=Dp(t).find(i=>i.binding.agentId===e.agentId&&i.binding.ownerPublicId===e.ownerPublicId&&i.authorityOrigin===e.authUrl);if(!r||!e.financialDeviceRuntimeId)return;let n=Vd(e.agentId,t);if(!n||n.runtimeKey.runtimeId!==e.financialDeviceRuntimeId||n.ownerPublicId!==r.binding.ownerPublicId||n.proposal.associationId!==r.binding.associationId||n.proposal.associationVersion!==r.binding.associationVersion||n.proposal.rootJkt!==r.binding.rootJkt||n.rootKid!==r.binding.rootKid)throw new Error("Protected wallet installation differs from its independently claimed owner");return r}var pA=se(require("node:fs")),voe=se(require("node:path"));var wi=se(require("node:fs")),_oe=se(require("node:os")),Ws=se(require("node:path"));var boe=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,tXe=boe;function Uo(e=process.env){if(e.VISA_V4_HOME)return e.VISA_V4_HOME;let t=e.VISA_CLI_HOME;return typeof t=="string"&&t.trim().length>0?Ws.join(t,".visa-v4"):Ws.join(_oe.homedir(),".visa-v4")}function Eoe(e=Uo()){return Ws.join(e,"owners")}function $L(e=Uo(),t){if(t!==void 0){if(!tXe.test(t))throw new Error("wallet owner id must be a canonical UUID");return Ws.join(Eoe(e),t.toLowerCase(),"agents")}return Ws.join(e,"agents")}function Lp(e,t=Uo(),r){if(!boe.test(e))throw new Error("wallet agent id must be a canonical UUID");return Ws.join($L(t,r),e.toLowerCase())}function lA(e){try{let t=wi.lstatSync(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`wallet runtime path is not a private directory: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t;wi.mkdirSync(e,{mode:448})}wi.chmodSync(e,448)}function woe(e,t=Uo(),r){if(wi.mkdirSync(t,{recursive:!0,mode:448}),r!==void 0){let o=Eoe(t);lA(o),lA(Ws.dirname($L(t,r)))}let n=$L(t,r);lA(n);let i=Lp(e,t,r);return lA(i),i}var rXe=/^0x[0-9a-f]{40}$/i,nXe=/^eip155:[1-9][0-9]{0,18}$/,fA=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,iXe="wallet-authority.json";function JL(e=process.env){return Uo(e)}function VL(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.version===1&&(t.financialDeviceRuntimeId===void 0||typeof t.financialDeviceRuntimeId=="string"&&fA.test(t.financialDeviceRuntimeId))&&(t.executionMode===void 0||t.executionMode==="direct_runtime"||t.executionMode==="managed")&&(t.walletBinding===void 0||/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(t.walletBinding)&&t.walletBinding.length<=32*1024)&&(t.managedWallet===void 0||typeof t.managedWallet=="object"&&t.managedWallet!==null&&typeof t.managedWallet.organizationId=="string"&&t.managedWallet.organizationId.length>0&&typeof t.managedWallet.walletId=="string"&&t.managedWallet.walletId.length>0&&typeof t.managedWallet.address=="string"&&rXe.test(t.managedWallet.address)&&typeof t.managedWallet.network=="string"&&nXe.test(t.managedWallet.network))&&(t.activationState===void 0||t.activationState==="pending"||t.activationState==="active")&&(t.executionState===void 0||t.executionState==="active"||t.executionState==="recovery_only")&&typeof t.agentId=="string"&&fA.test(t.agentId)&&typeof t.agentName=="string"&&t.agentName.length>0&&t.agentName.length<=120&&(t.ownerPublicId===void 0||fA.test(t.ownerPublicId))&&typeof t.grantId=="string"&&fA.test(t.grantId)&&Number.isSafeInteger(t.grantVersion)&&t.grantVersion>0&&t.rail==="wallet:x402"&&typeof t.authUrl=="string"&&oXe(t.authUrl)&&typeof t.activatedAt=="string"&&Number.isFinite(Date.parse(t.activatedAt))}function oXe(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:")&&t.username===""&&t.password===""&&t.pathname==="/"&&t.search===""&&t.hash===""&&e===t.origin}catch{return!1}}function Soe(e=JL()){return voe.join(e,iXe)}function sXe(e,t){if(!VL(e))throw new zd("wallet authority binding is invalid");pA.mkdirSync(t,{recursive:!0,mode:448}),pA.chmodSync(t,448),Lr(t),Ht(Soe(t),`${JSON.stringify(e,null,2)}
104
+ `)}function Aoe(e=JL()){let t=cr(Soe(e));if(t===null)return null;try{let r=JSON.parse(t);if(!VL(r))throw new zd("wallet authority binding is malformed");return r}catch(r){throw r instanceof zd?r:new zd("wallet authority binding is malformed")}}var zd=class extends Error{code="wallet_delivery_required";constructor(t){super(`wallet delivery unusable: ${t}`),this.name="WalletDeliveryRequiredError"}};function Ioe(e){let t={...e.authorityBinding,executionMode:"managed",activationState:"active"};if(!t.financialDeviceRuntimeId||!VL(t))throw new zd("wallet authority binding is invalid");let r=e.homeDir??woe(t.agentId,JL(),t.ownerPublicId);sXe(t,r),ne.info("wallet-delivery: device authority binding installed",{agentId:t.agentId,runtimeId:t.financialDeviceRuntimeId})}var aXe=60*6e4,xoe=6e4,GL=1e3,Poe=15e3,Toe=1e3;function cXe(e){let t=typeof e?.expiresAt=="string"?Date.parse(e.expiresAt):NaN,r=e?.prepared?.status==="pending"&&typeof e.prepared.challenge?.expiresAt=="number"?e.prepared.challenge.expiresAt*1e3:NaN,n=[t,r].filter(i=>Number.isFinite(i));return n.length?Math.min(...n):null}function uXe(e){let t=GL;if(e.now-e.fastSince>=xoe){let r=Math.min(GL*2**Math.min(e.slowTicks,10),Poe);t=Math.min(Math.round(r*(.8+.4*e.random())),Poe)}return e.closesAt!==null&&e.closesAt+Toe>e.now&&(t=Math.min(t,e.closesAt+Toe-e.now)),Math.max(GL,Math.min(t,e.deadline-e.now))}async function Ooe(e){let t=e.sleep??(h=>new Promise(y=>setTimeout(y,h))),r=e.now??(()=>Date.now()),n=e.random??Math.random,i=null,o=h=>{i=cXe(h)},s=await My(e);o(await Rp({...e,pending:s})),await e.onProposalPublished?.(s);let a=r(),c=0,u=async()=>{let h=await qie({...e,pending:s,onView:o});return h.renewed&&(s=h.pending,await e.onProposalPublished?.(s)),h.active},d=await u(),l=d?KL(e,d):null,m=d?.grantId,p=s.cardProposal?await e.advanceCompanion?.()===!0:!0;if(await e.advanceTap?.(),!d||!p){let h=r()+aXe;for(;(!d||!p)&&r()<h;){let y=r();y-a>=xoe&&c++,await t(uXe({now:y,fastSince:a,slowTicks:c,closesAt:i,deadline:h,random:n})),d=await u(),d&&(!l||d.grantId!==m)&&(l=KL(e,d),m=d.grantId),p=s.cardProposal?await e.advanceCompanion?.()===!0:!0,await e.advanceTap?.()}}if(!d||!p||!l)throw new Error("Device approval is still pending. Keep this enrollment command running; the native key and owner request are preserved.");return l}async function Roe(e){let t=await AL(e);return t?KL(e,t):!1}function KL(e,t){if(t.ownerPublicId!==e.ownerPublicId)throw new Error("Protected wallet owner differs from the active profile");return Ioe({authorityBinding:{version:1,agentId:e.agentId,ownerPublicId:e.ownerPublicId,agentName:e.agentName,grantId:t.grantId,grantVersion:t.grantVersion,rail:"wallet:x402",authUrl:new URL(e.authUrl).origin,activatedAt:new Date().toISOString(),financialDeviceRuntimeId:t.runtimeKey.runtimeId},homeDir:e.walletHomeDir}),!0}var Xs=require("node:fs"),EA=require("node:path"),Zs=require("node:crypto"),Yr=se(Fs()),AA=se(Cc()),IA=se(hL());var xt=require("node:fs"),Bc=require("node:crypto"),Jy=require("node:path"),Ys=se(Fn()),hA=se(Cc());var $y=require("node:crypto"),Yd=se(Fn()),mA=se(Cc());function Coe(e,t){let r=t.tapPublicMaterial;if(!t.gateEnrollment||!r||r.associationId!==e.proposal.associationId||r.associationVersion!==e.proposal.associationVersion||r.agentId!==e.proposal.agentId||r.rootJkt!==e.proposal.rootJkt||!Number.isSafeInteger(r.tapKeyEpoch)||r.tapKeyEpoch<0||(0,mA.computeJkt)(r.tapKey.jwk)!==r.tapKey.jkt||r.custody!==void 0&&!["root-via-gate","runtime"].includes(r.custody)||typeof r.observation!="string"||!Number.isSafeInteger(r.expiresAt)||r.expiresAt<=Math.floor(Date.now()/1e3))throw new Error("identity_device_public_material_invalid");return{...r,custody:r.custody??"root-via-gate"}}function Noe(e){if(e?.ok!==!0||!e.result||typeof e.result!="object")throw new Error("identity_device_response_invalid");return e.result}async function WL(e){let t=Noe(await e.api.identityDeviceRequest("association",{agentId:e.agentId}));if(t.agentId!==e.agentId||t.rootJkt!==e.expectedRootJkt||t.associationId!==e.associationId)throw new Error("identity_device_owner_root_mismatch");let r=await e.native.describe(e.key.handle);if((0,Yd.canonicalJson)(r)!==(0,Yd.canonicalJson)(e.key)||r.binding.profile!=="identity-tap-v1"||r.binding.purpose!=="tap"||r.binding.associationId!==t.associationId||r.binding.agentId!==e.agentId||r.binding.rootJkt!==e.expectedRootJkt)throw new Error("identity_device_tap_key_binding_mismatch");let n={v:1,handoffId:(0,$y.randomUUID)(),runtimeKey:r,proposal:{...t,runtimeId:r.runtimeId,runtimeJkt:r.jkt,runtimePublicJwk:r.publicJwk}};return(0,mA.identityDeviceProposalSha256)(n.proposal),await e.persist(n),await zs(e.api,e.native,n,"create"),n}async function zs(e,t,r,n,i,o,s){let a=await t.describe(r.runtimeKey.handle);if((0,Yd.canonicalJson)(a)!==(0,Yd.canonicalJson)(r.runtimeKey)||a.jkt!==r.proposal.runtimeJkt||a.runtimeId!==r.proposal.runtimeId)throw new Error("native_runtime_handle_mismatch");let c=n==="cancel"?{v:1,operation:n,requestId:(0,$y.randomUUID)(),handoffId:r.handoffId,proposal:r.proposal,body:{enrollmentRequestId:o??null,generation:s??null}}:n==="proof"?{v:1,operation:n,requestId:(0,$y.randomUUID)(),handoffId:r.handoffId,proposal:r.proposal,body:{enrollmentRequestId:o,runtimeProof:i}}:{v:1,operation:n,requestId:n==="create"?r.handoffId:(0,$y.randomUUID)(),handoffId:r.handoffId,proposal:r.proposal,body:{}},u=await t.handoffProof(a.handle,c),d=Noe(await e.identityDeviceRequest("handoff",{request:c,runtimeProof:u}));if(d.handoffId!==r.handoffId||(0,Yd.canonicalJson)(d.proposal)!==(0,Yd.canonicalJson)(r.proposal)||!Number.isSafeInteger(d.expiresAt)||!["proposed","pending","active","expired","retired","revoked","cancelled"].includes(d.status))throw new Error("identity_device_response_invalid");return d}async function gA(e,t,r){let n=await zs(e,t,r,"read");if(n.status==="pending"&&!n.runtimeProof){if(!n.challenge||n.enrollmentRequestId!==n.challenge.requestId)throw new Error("identity_device_response_invalid");let i=await t.enrollmentProof(r.runtimeKey.handle,n.challenge);return zs(e,t,r,"proof",i,n.enrollmentRequestId)}return n}function koe(e,t,r={}){let n=`?device=${encodeURIComponent(t.handoffId)}&association=${encodeURIComponent(t.proposal.associationId)}&tap=${encodeURIComponent(t.proposal.runtimeJkt)}`+(r.revoke?"&deviceAction=revoke":"");return`${e}${r.revoke?"":"/protected-agent"}${n}`}var yA=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(e),dXe=600*1e3;function lXe(e){if(!Number.isSafeInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return!!(t&&typeof t=="object"&&t.code==="EPERM")}}function Xd(e){if(!yA(e.agentId))throw new Error("identity_device_agent_invalid");let t=(0,Jy.join)(Xe(e.env),"identity-runtime-renewal-locks");(0,xt.mkdirSync)(t,{recursive:!0,mode:448}),(0,xt.chmodSync)(t,448);let r=(0,Jy.join)(t,`${e.agentId}.${e.purpose??"tap"}.lock`),n=e.now??new Date,i=e.staleMs??dXe;for(let o=0;o<2;o+=1){let s=(0,Bc.randomUUID)(),a={version:1,pid:process.pid,token:s,createdAt:n.toISOString()};try{let c=(0,xt.openSync)(r,"wx",384);try{(0,xt.writeFileSync)(c,JSON.stringify(a),"utf8"),(0,xt.fsyncSync)(c)}finally{(0,xt.closeSync)(c)}return()=>{try{JSON.parse((0,xt.readFileSync)(r,"utf8")).token===s&&(0,xt.unlinkSync)(r)}catch{}}}catch(c){if(!c||typeof c!="object"||c.code!=="EEXIST")throw c;let u=!1;try{let d=JSON.parse((0,xt.readFileSync)(r,"utf8")),l=typeof d.createdAt=="string"?Date.parse(d.createdAt):NaN;if(d.version===1&&Number.isSafeInteger(d.pid)&&(d.pid??0)>0&&typeof d.token=="string"&&d.token.length>0&&Number.isFinite(l))u=!lXe(d.pid);else{let p=Number.isFinite(l)?l:(0,xt.statSync)(r).mtimeMs;u=n.getTime()-p>=i}}catch{try{u=n.getTime()-(0,xt.statSync)(r).mtimeMs>=i}catch{u=!0}}if(!u)return null;try{(0,xt.unlinkSync)(r)}catch(d){if(!d||typeof d!="object"||d.code!=="ENOENT")return null}}}return null}function Vy(e,t){if(!yA(e))throw new Error("identity_device_agent_invalid");let r=(0,Jy.join)(Xe(t),"financial-device-presence");return(0,xt.mkdirSync)(r,{recursive:!0,mode:448}),(0,Jy.join)(r,`${e}.pending.json`)}function Bp(e,t){let r=$i(Vy(e,t));if(r===null)return null;sr(r);let n=JSON.parse(r);if(n.v!==1||n.proposal?.agentId!==e||!yA(n.handoffId)||!n.runtimeKey?.handle)throw new Error("identity_device_record_invalid");return n}function _A(e,t){sr(JSON.stringify(e));let r=Vy(e.proposal.agentId,t),n=$i(r);if(n){let i=JSON.parse(n);i.handoffId!==e.handoffId&&In(r.replace(".pending.json",`.${i.handoffId}.history.json`),n)}In(r,JSON.stringify(e))}async function Gy(e){let{pending:t,view:r}=e,n=Math.floor(Date.now()/1e3);if(r.handoffId!==t.handoffId||r.status!=="active"||!r.authorizationId||!yA(r.authorizationId)||!Number.isSafeInteger(r.authorizationVersion)||Number(r.authorizationVersion)<1||!r.certificate||!r.delegation||!r.gateAuthorization||(0,Ys.canonicalJson)(r.proposal)!==(0,Ys.canonicalJson)(t.proposal))throw new Error("identity_device_activation_invalid");Coe(t,r);let i=r.challenge;if(!i||i.runtimeId!==t.proposal.runtimeId||i.runtimeJkt!==t.proposal.runtimeJkt||i.associationId!==t.proposal.associationId||i.associationVersion!==t.proposal.associationVersion)throw new Error("identity_device_challenge_invalid");for(let[l,m]of[[r.certificate,i.certificateSha256],[r.delegation,i.delegationSha256],[r.gateAuthorization,i.gateAuthorizationSha256]])if((0,Bc.createHash)("sha256").update(l.split(".").slice(0,2).join(".")).digest("base64url")!==m)throw new Error("identity_device_signed_preparation_mismatch");if(!(await(0,hA.verifyRuntimeCertificate)(r.certificate,{jwks:{keys:[{...e.rootPublicJwk,kid:e.rootKid}]},expectedAgentId:t.proposal.agentId,expectedRootJkt:t.proposal.rootJkt,expectedRuntimeJkt:t.proposal.runtimeJkt,expectedRuntimeId:t.proposal.runtimeId,requiredPurpose:"tap",nowSec:e.collectedRenewal?JSON.parse(Buffer.from(r.certificate.split(".")[1],"base64url").toString("utf8")).iat:n})).ok)throw new Error("identity_device_certificate_invalid");let s=JSON.parse(Buffer.from(r.delegation.split(".")[1],"base64url").toString("utf8"));await(0,hA.verifyIdentityTapDelegation)(r.delegation,{ownerJwks:{keys:[{...e.rootPublicJwk,kid:e.rootKid}]},expectedRootKid:e.rootKid,expectedRootJkt:t.proposal.rootJkt,expectedAgentId:t.proposal.agentId,expectedRuntimeId:t.proposal.runtimeId,expectedRuntimeJkt:t.proposal.runtimeJkt,expectedLeaseIssuerJkt:s.leaseIssuerJkt,expectedNetwork:s.network,expectedDelegationId:s.jti,nowSec:n});let a=r.gateAuthorization.split("."),c={ok:a.length===3&&(0,Bc.verify)(null,Buffer.from(a.slice(0,2).join(".")),(0,Bc.createPublicKey)({key:e.rootPublicJwk,format:"jwk"}),Buffer.from(a[2],"base64url")),header:JSON.parse(Buffer.from(a[0],"base64url").toString("utf8")),claims:JSON.parse(Buffer.from(a[1],"base64url").toString("utf8"))};if(!c.ok||c.header.alg!=="EdDSA"||c.header.kid!==e.rootKid||c.header.typ!=="visa-agent-identity-gate-authorization+jwt"||c.claims.iss!==t.proposal.rootJkt||c.claims.sub!==t.proposal.agentId||c.claims.aud!=="urn:visa:tvc:identity-gate"||c.claims.generation!==r.challenge?.generation||!Number.isSafeInteger(c.claims.exp)||Number(c.claims.exp)<=n||!Number.isSafeInteger(c.claims.nbf)||Number(c.claims.nbf)>n||(0,Ys.canonicalJson)(c.claims.purposes)!==(0,Ys.canonicalJson)(["tap_signature_base"]))throw new Error("identity_device_gate_authorization_invalid");let u=await e.native.describe(t.runtimeKey.handle);if((0,Ys.canonicalJson)(u)!==(0,Ys.canonicalJson)(t.runtimeKey))throw new Error("native_runtime_handle_mismatch");let d={...t,active:r,rootPublicJwk:e.rootPublicJwk,rootKid:e.rootKid};return sr(JSON.stringify(d)),In(Vy(t.proposal.agentId,e.env).replace(".pending.json",`.${t.proposal.runtimeId}.active.json`),JSON.stringify(d)),In(Vy(t.proposal.agentId,e.env).replace(".pending.json",".selected.json"),JSON.stringify(d)),ne.info("identity_device_selected",{agentId:t.proposal.agentId,handoffId:t.handoffId}),d}function fXe(e){let t=e.runtimeKey?.binding;return t?t.profile==="identity-tap-v1"?t.purpose==="tap"&&t.associationId===e.proposal?.associationId:t.profile==="legacy-root-certified-v1"&&t.purpose==="wallet:x402":!1}function zL(e){return e.runtimeKey.binding.profile==="legacy-root-certified-v1"}function Ji(e,t){let r=$i(Vy(e,t).replace(".pending.json",".selected.json"));if(r===null)return null;sr(r);let n=JSON.parse(r);if(n.v!==1||n.revoked!==void 0&&n.revoked!==!0||n.proposal?.agentId!==e||!fXe(n)||n.active?.status!=="active"||n.active.handoffId!==n.handoffId||!n.rootKid||!n.rootPublicJwk||(0,Ys.canonicalJson)(n.active.proposal)!==(0,Ys.canonicalJson)(n.proposal))throw new Error("identity_device_selected_invalid");return n}function pXe(e,t){return e?e.ceremonyId===t.binding.ceremonyId&&e.challenge===t.binding.challenge&&/^[A-Za-z0-9_-]{43}$/.test(e.verifier)&&(0,Zs.createHash)("sha256").update(e.verifier).digest("base64url")===e.challenge:!0}function XL(e,t){if(e&&(e.ceremonyId!==t.binding.ceremonyId||e.challenge!==t.binding.challenge||!/^[A-Za-z0-9_-]{43}$/.test(e.verifier)||(0,Zs.createHash)("sha256").update(e.verifier).digest("base64url")!==e.challenge))throw new Error("card_device_ceremony_changed")}function Ky(e,t){if(!/^[0-9a-f-]{36}$/.test(e))throw new Error("card_device_agent_invalid");let r=(0,EA.join)(Xe(t),"card-device");return(0,Xs.mkdirSync)(r,{recursive:!0,mode:448}),(0,EA.join)(r,`${e}.json`)}function bA(e,t){let r=JSON.stringify(e);sr(r),In(Ky(e.proposal.agentId,t),r)}function wA(e,t){return Ky(e,t).replace(/\.json$/,".renewal.json")}function joe(e,t){let r=JSON.stringify(e);sr(r),In(wA(e.proposal.agentId,t),r)}function Doe(e,t){let r=$i(e);if(r===null)return null;sr(r);let n=JSON.parse(r),i=n.proposal,o=t.binding,s=n.runtimeKey;if((0,IA.financialDeviceProposalHash)(i),!n.certificate&&(!pXe(n.ceremony,t)||i.associationId!==o.associationId||i.associationVersion!==o.associationVersion||i.rootJkt!==o.rootJkt)){let c=e.replace(".json",`.${i?.requestId??(0,Zs.randomUUID)()}.superseded.json`);return(0,Xs.renameSync)(e,c),null}if(XL(n.ceremony,t),n.v!==1||n.initialConnection!==void 0&&n.initialConnection!==!0||i.v!==2||i.agentId!==o.agentId||i.associationId!==o.associationId||i.associationVersion!==o.associationVersion||i.rootJkt!==o.rootJkt||s.binding.profile!=="legacy-root-certified-v1"||s.binding.purpose!=="card:vic"||s.binding.agentId!==o.agentId||s.binding.rootJkt!==o.rootJkt||s.runtimeId!==i.runtimeId||s.jkt!==(0,AA.computeJkt)(i.publicJwk)||(0,Yr.canonicalJson)(s.publicJwk)!==(0,Yr.canonicalJson)(i.publicJwk))throw new Error("card_device_record_invalid");return n}function Uc(e,t){return Doe(Ky(e.binding.agentId,t),e)}function YL(e,t,r){let n=Doe(wA(e.binding.agentId,r),e);if(n&&(n.ceremony||n.initialConnection))throw new Error("card_device_record_invalid");return n&&(0,Yr.canonicalJson)(n.runtimeKey)===(0,Yr.canonicalJson)(t.runtimeKey)?n:null}function Loe(e,t,r,n){let i=en(e);if(new URL(i).protocol!=="https:")throw new Error("card_connection_https_required");(0,IA.financialDeviceProposalHash)(t.proposal);let o=new URL("/agent/enroll/protected-agent",i);if(t.ceremony){o.searchParams.set("cliChallenge",t.ceremony.challenge);let s=uoe(t.ceremony.challenge,n);s&&o.searchParams.set("keys",s)}else o.searchParams.set("cardDevice",Buffer.from((0,Yr.canonicalJson)(t.proposal)).toString("base64url"));return r&&o.searchParams.set("app",r),o.toString()}async function vA(e,t,r,n=Math.floor(Date.now()/1e3)){let i=e.challenge,o=e.proposal;if(!i||i.v!==1||i.audience!=="visa:financial:card-actor-enrollment:v1"||i.requestId!==o.requestId||i.associationId!==o.associationId||i.associationVersion!==o.associationVersion||i.runtimeId!==o.runtimeId||i.childJkt!==e.runtimeKey.jkt||i.generation!==1||!Number.isSafeInteger(i.expiresAt)||!r.startsWith(i.preparedCertificate.signingInput+"."))throw new Error("card_device_certificate_changed");let s=await(0,AA.verifyRuntimeCertificate)(r,{jwks:{keys:[{...t.binding.rootPublicJwk,kid:t.binding.rootKid}]},nowSec:n,expectedAgentId:e.proposal.agentId,expectedRootJkt:e.proposal.rootJkt,expectedRuntimeId:e.proposal.runtimeId,expectedRuntimeJkt:e.runtimeKey.jkt,requiredPurpose:"card:vic"});if(!s.ok||(0,Yr.canonicalJson)(s.claims.purposes)!=='["card:vic"]')throw new Error("card_device_certificate_invalid");return s.claims}async function Boe(e){let{selection:t,signer:r,env:n}=e,i=Uc(t,n);if(!i){let o=await r.create({profile:"legacy-root-certified-v1",purpose:"card:vic",agentId:t.binding.agentId,rootJkt:t.binding.rootJkt});i={v:1,runtimeKey:o,ceremony:e.ceremony,...e.initialConnection?{initialConnection:!0}:{},proposal:{v:2,rail:"card:vic",purpose:"financial.runtime.device.proposal",requestId:(0,Zs.randomUUID)(),agentId:t.binding.agentId,associationId:t.binding.associationId,associationVersion:t.binding.associationVersion,rootJkt:t.binding.rootJkt,runtimeId:o.runtimeId,publicJwk:o.publicJwk}},bA(i,n)}return i}async function Uoe(e){XL(e.ceremony,e.selection);let t=Xd({agentId:e.selection.binding.agentId,purpose:"card",env:e.env});if(!t)throw new Error("card_device_busy");try{let r=await Boe(e);if((0,Yr.canonicalJson)(await e.signer.describe(r.runtimeKey.handle))!==(0,Yr.canonicalJson)(r.runtimeKey))throw new Error("card_device_handle_changed");return r}finally{t()}}async function Moe(e,t,r,n){let{selection:i,signer:o,api:s,env:a}=r,c=e.proposal,u;try{u=await s.financialRuntimeRequest("device-handoff-read",{requestId:c.requestId,proposal:c})}catch(m){if(!(m instanceof Pn)||m.status!==400||m.code!=="financial_runtime_refused")throw m;u={proposal:c,published:!1,prepared:null,expired:!1,evidence:{}}}if(u.published===!1&&e.ceremony)try{u=await s.financialRuntimeRequest("device-handoff-create",{requestId:c.requestId,proposal:c,ceremony:e.ceremony})}catch(m){if(!(m instanceof Pn)||m.status!==400||m.code!=="financial_runtime_refused")throw m;delete e.ceremony,n(e)}if((0,Yr.canonicalJson)(u.proposal)!==(0,Yr.canonicalJson)(c))throw new Error("card_device_proposal_changed");let d=u.prepared?.challenge,l=u.evidence?.owner_signatures?.certificate;if(u.prepared?.status==="revoked"||u.prepared?.status==="expired")throw new Error("card_device_connection_revoked");if(u.expired&&u.prepared?.status!=="active"){In(Ky(c.agentId,a).replace(".json",`.${c.requestId}.expired.json`),JSON.stringify(e));let m=e.ceremony||u.prepared?.kind==="enroll"?await o.create(t.binding):t;return n({v:1,runtimeKey:m,ceremony:e.ceremony,proposal:{...c,requestId:(0,Zs.randomUUID)(),runtimeId:m.runtimeId,publicJwk:m.publicJwk}}),{status:"retry"}}if(d&&typeof l=="string"){if(e.challenge&&(0,Yr.canonicalJson)(e.challenge)!==(0,Yr.canonicalJson)(d))throw new Error("card_device_challenge_changed");e.challenge=d;let m=await vA(e,i,l,u.prepared?.status==="active"?d.preparedCertificate.claims.iat:void 0);if(!u.evidence?.device_proof&&u.prepared?.status!=="active"&&(e.childPop||(e.childPop=await o.cardEnrollmentProof(t.handle,d),n(e)),u=await s.financialRuntimeRequest("device-handoff-proof",{requestId:c.requestId,proposal:c,childPop:e.childPop})),u.prepared?.status==="active"){if(u.prepared.certificate!==l)throw new Error("card_device_certificate_changed");return e.certificate=l,n(e),m.exp<=Math.floor(Date.now()/1e3)+30?{status:"retry"}:{status:"active",record:e}}}if(u.expired)throw new Error("card_device_preparation_expired");return{status:"awaiting_owner",proposal:c,hash:(0,IA.financialDeviceProposalHash)(c),published:u.published!==!1}}function qoe(e,t){In(Ky(e.proposal.agentId,t).replace(".json",`.${e.proposal.requestId}.completed.json`),JSON.stringify(e))}async function Wy(e){let{selection:t,signer:r,env:n}=e;XL(e.ceremony,t);let i=Xd({agentId:t.binding.agentId,purpose:"card",env:n});if(!i)return{status:"busy"};try{let o=await Boe(e),s=await r.describe(o.runtimeKey.handle);if((0,Yr.canonicalJson)(s)!==(0,Yr.canonicalJson)(o.runtimeKey))throw new Error("card_device_handle_changed");if(o.certificate){let a=JSON.parse(Buffer.from(o.certificate.split(".")[1]??"","base64url").toString());await vA(o,t,o.certificate,a.iat);let c=Math.floor(Date.now()/1e3);if(a.exp>c+30){await vA(o,t,o.certificate);let d=e.renewWithinSeconds===void 0?null:YL(t,o,n);if(!d&&a.exp>c+(e.renewWithinSeconds??0))return{status:"active",record:o};let l=d??{v:1,proposal:{...o.proposal,requestId:(0,Zs.randomUUID)()},runtimeKey:o.runtimeKey};d||joe(l,n);let m=await Moe(l,s,e,p=>joe(p,n));return m.status!=="active"||(qoe(o,n),bA(m.record,n),(0,Xs.rmSync)(wA(t.binding.agentId,n),{force:!0})),m}qoe(o,n);let u=YL(t,o,n);o=u??{v:1,proposal:{...o.proposal,requestId:(0,Zs.randomUUID)()},runtimeKey:o.runtimeKey},bA(o,n),u&&(0,Xs.rmSync)(wA(t.binding.agentId,n),{force:!0})}return await Moe(o,s,e,a=>bA(a,n))}finally{i()}}var SA=720*60*60;async function ZL(e,t,r=Math.floor(Date.now()/1e3)){let n={state:"none",renew:!1},i=e.binding.agentId,o;try{o=Uc(e,t)}catch{return n}if(!o)return n;if(!o.certificate){let a=!1;try{a=(0,Xs.readdirSync)((0,EA.join)(Xe(t),"card-device")).some(c=>c.startsWith(`${i}.`)&&c.endsWith(".completed.json"))}catch{a=!1}return a&&!o.ceremony&&!o.initialConnection?{state:"renewing",renew:!0}:n}let s;try{s=JSON.parse(Buffer.from(o.certificate.split(".")[1]??"","base64url").toString()),await vA(o,e,o.certificate,s.iat)}catch{return n}try{if(YL(e,o,t))return{state:"renewing",renew:!0}}catch{}return s.exp<=r+30?{state:"expired",renew:!0}:s.exp-r<SA?{state:"renew_due",renew:s.exp-s.iat>=SA}:{state:"live",renew:!1}}var Er=require("node:crypto"),Vi=se(Fn()),xA=se(Cc()),mXe={"wallet:x402":["visa-agent-operations:v1","visa-wallet-authority:local-v1","visa:financial:wallet-device-handoff:v1","visa:financial:device-operations:v1","visa-tempo-mpp-payment:v1","visa-tempo-mpp-report:v1","visa-tempo-mpp-history:v1"],"card:vic":["visa-agent-operations:v1","visa-auth-card-draw","visa:purchase-resource:v1","visa:financial:card-device-handoff:v1","visa:card-admission-recovery:v1"]},Joe=Number.MAX_SAFE_INTEGER,gXe=Buffer.from("302e020100300506032b657004220420","hex");function J(e){throw new Error(e)}var hXe=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,bt=e=>typeof e=="string"&&hXe.test(e);function Yy(e){if(!/^[A-Za-z0-9_-]*$/.test(e))return null;let t=Buffer.from(e,"base64url");return t.toString("base64url")===e?t:null}var Hc=e=>typeof e=="string"&&Yy(e)?.length===32,Qs=e=>(0,Er.createHash)("sha256").update(e).digest("base64url");function Fc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ut(e,t){return Fc(e)||J("request_invalid"),(Object.keys(e).filter(n=>e[n]!==void 0).length!==t.length||t.some(n=>!Object.hasOwn(e,n)))&&J("request_invalid"),e}function F(e,t){let r=e[t];return typeof r!="string"&&J("request_invalid"),r}function ke(e,t){let r=e[t];return(typeof r!="number"||!Number.isSafeInteger(r)||r<0||r>Joe)&&J("request_invalid"),r}function Ho(e,t){try{return(0,Vi.canonicalJson)(e)===(0,Vi.canonicalJson)(t)}catch{return!1}}function Hoe(e){let t=Yy(e);t||J("request_invalid");try{return JSON.parse(t.toString("utf8"))}catch{J("request_invalid")}}var Up=class{constructor(t,r,n){this.binding=r;this.runtimeId=n;let i=Buffer.concat([gXe,t]);try{this.#e=(0,Er.createPrivateKey)({key:i,format:"der",type:"pkcs8"})}finally{i.fill(0)}let o=(0,Er.createPublicKey)(this.#e).export({format:"jwk"}).x;typeof o!="string"&&J("custody_record_invalid"),this.publicJwk={kty:"OKP",crv:"Ed25519",x:o},this.jkt=Qs((0,Vi.canonicalJson)(this.publicJwk))}binding;runtimeId;publicJwk;jkt;#e;signature(t){return(0,Er.sign)(null,Buffer.from(t),this.#e)}signer(){return{kid:this.jkt,publicJwk:this.publicJwk,sign:async t=>new Uint8Array(this.signature(t))}}};function QL(e){Fc(e)||J("identity_binding_invalid");let t=["profile","associationId","agentId","rootJkt","purpose"];Object.keys(e).some(u=>!t.includes(u))&&J("identity_binding_invalid");let{profile:r,associationId:n,agentId:i,rootJkt:o,purpose:s}=e,a=r==="identity-tap-v1"&&s==="tap"&&bt(n),c=r==="legacy-root-certified-v1"&&n===void 0&&(s==="wallet:x402"||s==="card:vic");return(!bt(i)||!Hc(o)||!(a||c))&&J("identity_binding_invalid"),a?{profile:"identity-tap-v1",associationId:n,agentId:i,rootJkt:o,purpose:"tap"}:{profile:"legacy-root-certified-v1",agentId:i,rootJkt:o,purpose:s}}function yXe(e){let t={agentId:"00000000-0000-4000-8000-000000000000",rootJkt:"A".repeat(43)};return e==="tap"?{profile:"identity-tap-v1",associationId:"00000000-0000-4000-8000-000000000000",...t,purpose:e}:{profile:"legacy-root-certified-v1",...t,purpose:e}}function zy(e){return e.binding.profile==="identity-tap-v1"&&e.binding.purpose==="tap"||e.binding.profile==="legacy-root-certified-v1"&&e.binding.purpose==="wallet:x402"}function e3(e,t){e.binding.purpose!==t&&J("key_purpose_mismatch")}function PA(e){e.binding.profile!=="legacy-root-certified-v1"&&J("legacy_custody_profile_required")}function Foe(e,t){let r=F(t,"associationId"),n=e.binding.profile==="identity-tap-v1"?e.binding.associationId:void 0;(!(n!==void 0?n===r:zy(e)&&bt(r))||F(t,"agentId")!==e.binding.agentId||F(t,"runtimeId")!==e.runtimeId)&&J("identity_binding_mismatch"),(ke(t,"associationVersion")===0||ke(t,"generation")===0)&&J("request_invalid")}function t3(e,t){let r=Ut(e,["claims","signingInput"]),n=F(r,"signingInput");n.length>16384&&J("request_invalid");let i=n.split(".");i.length!==2&&J("request_invalid");let o=Ut(Hoe(i[0]),["alg","kid","typ"]),s=F(o,"kid");return(F(o,"alg")!=="EdDSA"||F(o,"typ")!==t||s.length===0||s.length>256||!/^[A-Za-z0-9._:@/-]+$/.test(s)||!Ho(Hoe(i[1]),r.claims))&&J("request_invalid"),Fc(r.claims)||J("request_invalid"),{claims:r.claims,kid:s}}var Voe=["v","iss","sub","jti","runtimeId","runtimeJkt","leaseIssuerJkt","purpose","network","signingModes","maxLeaseTtlSeconds","iat","nbf","exp"],_Xe=[...Voe,"custody","rails"],$oe=["v","iss","sub","jti","runtimeId","cnf","purposes","iat","nbf","exp"],TA=class{#e;#t;constructor(t,r={}){this.#e=t,this.#t=r.nowSec??(()=>Math.floor(Date.now()/1e3))}async holds(t){try{return await this.load(t),"held"}catch(r){return r.message==="custody_unavailable"?"missing":"unknown"}}async load(t){/^[0-9a-f]{64}$/.test(t)||J("custody_handle_invalid");let r=await this.#e.read(t),n;try{n=JSON.parse(Buffer.from(r).toString("utf8"))}catch{J("custody_record_invalid")}finally{r.fill(0)}(!Fc(n)||n.v!==1||typeof n.seed!="string")&&J("custody_record_invalid"),n.reservation!==void 0&&J("custody_record_unbound");let i=Yy(n.seed);(!i||i.length!==32||!bt(n.runtimeId))&&J("custody_record_invalid");let o;try{o=QL(n.binding)}catch{J("custody_record_invalid")}try{return new Up(i,o,n.runtimeId)}finally{i.fill(0)}}describeKey(t,r){return{v:1,handle:t,runtimeId:r.runtimeId,binding:r.binding,publicJwk:r.publicJwk,jkt:r.jkt}}async create(t,r){let n=QL(t);(r!==void 0&&!bt(r)||n.profile==="identity-tap-v1"&&r!==void 0)&&J("identity_binding_invalid");let i=(0,Er.randomBytes)(32),o=(0,Er.randomBytes)(32).toString("hex"),s={v:1,seed:i.toString("base64url"),binding:n,runtimeId:r??(0,Er.randomUUID)()},a=Buffer.from(JSON.stringify(s),"utf8");try{await this.#e.create(o,a);let c=await this.#e.read(o);try{Buffer.from(c).equals(a)||J("custody_readback_failed")}finally{c.fill(0)}let u=new Up(i,n,s.runtimeId);return this.describeKey(o,u)}finally{i.fill(0),a.fill(0)}}async reserve(t){t!=="wallet:x402"&&t!=="card:vic"&&t!=="tap"&&J("identity_binding_invalid");let r=(0,Er.randomBytes)(32),n=(0,Er.randomBytes)(32).toString("hex"),i={v:1,seed:r.toString("base64url"),runtimeId:(0,Er.randomUUID)(),reservation:t==="tap"?{profile:"identity-tap-v1",purpose:t}:{profile:"legacy-root-certified-v1",purpose:t}},o=Buffer.from(JSON.stringify(i),"utf8");try{await this.#e.create(n,o);let s=await this.#e.read(n);Buffer.from(s).equals(o)||J("custody_readback_failed");let a=new Up(r,yXe(t),i.runtimeId);return{handle:n,runtimeId:i.runtimeId,purpose:t,publicJwk:a.publicJwk,jkt:a.jkt}}finally{r.fill(0),o.fill(0)}}async adopt(t,r,n){/^[0-9a-f]{64}$/.test(t)||J("custody_handle_invalid");let i=QL(r),o=(0,Er.createHash)("sha256").update("visa-agent-key-adopt:v1\0").update(t).update("\0").update((0,Vi.canonicalJson)(i)).digest("hex"),s=null;try{s=JSON.parse(Buffer.from(await this.#e.read(t)).toString("utf8"))}catch(d){if(d.message!=="custody_unavailable")throw d;let l=await this.describe(o);return n!==void 0&&l.runtimeId!==n&&J("identity_binding_invalid"),l}(!Fc(s)||s.v!==1||!Fc(s.reservation)||s.reservation.profile!==i.profile||s.reservation.purpose!==i.purpose||!bt(s.runtimeId)||n!==void 0&&n!==s.runtimeId)&&J("identity_binding_invalid");let a=Yy(s.seed);(!a||a.length!==32)&&J("custody_record_invalid");let c={v:1,seed:s.seed,binding:i,runtimeId:s.runtimeId},u=Buffer.from(JSON.stringify(c),"utf8");try{try{await this.#e.create(o,u)}catch(m){if(m.message!=="custody_handle_exists")throw m}let d=await this.#e.read(o);Buffer.from(d).equals(u)||J("custody_readback_failed");let l=new Up(a,i,c.runtimeId);return await this.#e.delete(t),this.describeKey(o,l)}finally{a.fill(0),u.fill(0)}}async describe(t){return this.describeKey(t,await this.load(t))}async delete(t){/^[0-9a-f]{64}$/.test(t)||J("custody_handle_invalid"),await this.#e.delete(t)}pop(t,r,n,i,o,s){(!(bt(r)||Hc(r))||!Hc(i))&&J("request_invalid");let a={nonce:r,audience:n,nowSec:o,intentHash:i,...s===void 0?{}:{runtimeCertificate:s}};return(0,xA.createPopProofWithSigner)(t.signer(),a)}async enrollmentProof(t,r){let n=await this.load(t);zy(n)||J("protected_association_required");let i=Ut(r,["v","profile","associationId","associationVersion","agentId","runtimeId","generation","requestId","runtimePublicJwk","runtimeJkt","rootJkt","certificateSha256","delegationSha256","gateAuthorizationSha256","iat","exp"]);Foe(n,i),(ke(i,"v")!==1||F(i,"profile")!=="identity-tap-v1"||!bt(F(i,"requestId"))||!Ho(i.runtimePublicJwk,n.publicJwk)||F(i,"runtimeJkt")!==n.jkt||F(i,"rootJkt")!==n.binding.rootJkt||!Hc(F(i,"certificateSha256"))||!Hc(F(i,"delegationSha256"))||!Hc(F(i,"gateAuthorizationSha256")))&&J("identity_binding_mismatch");let o=ke(i,"iat"),s=ke(i,"exp"),a=this.#t();return(o>a+5||s<=a||s<=o||s-o>600)&&J("challenge_expired"),n.signature((0,xA.identityDeviceEnrollmentPreimage)(r)).toString("base64url")}async handoffProof(t,r){let n=await this.load(t);zy(n)||J("protected_association_required");let i=Ut(r,["v","operation","requestId","handoffId","proposal","body"]),o=Ut(i.proposal,["associationId","associationVersion","agentId","rootJkt","runtimeId","runtimePublicJwk","runtimeJkt"]),s=n.binding.profile==="identity-tap-v1"?n.binding.associationId:void 0;(ke(i,"v")!==1||!bt(F(i,"requestId"))||!bt(F(i,"handoffId"))||(s!==void 0?F(o,"associationId")!==s:!bt(F(o,"associationId")))||F(o,"agentId")!==n.binding.agentId||F(o,"rootJkt")!==n.binding.rootJkt||F(o,"runtimeId")!==n.runtimeId||ke(o,"associationVersion")===0||!Ho(o.runtimePublicJwk,n.publicJwk)||F(o,"runtimeJkt")!==n.jkt)&&J("identity_binding_mismatch");let a=i.body,c=F(i,"operation");if(c==="create")Ut(a,[]),F(i,"requestId")!==F(i,"handoffId")&&J("request_invalid");else if(c==="read")Ut(a,[]);else if(c==="cancel"){let l=Ut(a,["enrollmentRequestId","generation"]);!(l.enrollmentRequestId===null&&l.generation===null)&&(!bt(F(l,"enrollmentRequestId"))||ke(l,"generation")===0||ke(l,"generation")>Joe)&&J("request_invalid")}else if(c==="proof"){let l=Ut(a,["enrollmentRequestId","runtimeProof"]),m=F(l,"runtimeProof");(!bt(F(l,"enrollmentRequestId"))||m.length!==86||Yy(m)?.length!==64)&&J("request_invalid")}else J("request_invalid");let u=Qs((0,Vi.canonicalJson)({v:1,operation:c,handoffId:F(i,"handoffId"),proposalSha256:Qs((0,Vi.canonicalJson)(o)),bodySha256:Qs((0,Vi.canonicalJson)(a))})),d=F(i,"requestId");return bt(d)||J("request_invalid"),this.pop(n,d,"visa-device-handoff:v1",u,this.#t())}async leaseProof(t,r){let n=await this.load(t);zy(n)||J("protected_association_required");let i=Ut(r,["v","profile","associationId","associationVersion","agentId","runtimeId","generation","authorizationId","authorizationVersion","requestId","signingMode"]);Foe(n,i),(ke(i,"v")!==1||F(i,"profile")!=="identity-tap-v1"||F(i,"signingMode")!=="tap"||!bt(F(i,"authorizationId"))||ke(i,"authorizationVersion")===0)&&J("request_invalid");let o=F(i,"requestId");return bt(o)||J("request_invalid"),this.pop(n,o,"visa-identity-lease-requests:v1",Qs((0,Vi.canonicalJson)(i)),this.#t())}async tapProof(t,r,n){let i=await this.load(t);zy(i)||J("protected_association_required"),Fc(n)||J("request_invalid");let o=["kind","method","authority","path","coveredComponents","paymentHeaderName","paymentHeaderValue","created","expires","keyId","nonce","tag","signatureBase"];n.contentDigest!==void 0&&o.push("contentDigest");let s=Ut(n,o);(F(s,"kind")!=="tap_signature_base"||F(s,"tag")!=="agent-payer-auth"||!Hc(F(s,"keyId")))&&J("request_invalid");let a=ke(s,"created"),c=ke(s,"expires"),u=this.#t();(a>u+30||c<=u||c<=a||c-a>480)&&J("tap_expired");let d=F(s,"method"),l=F(s,"authority"),m=F(s,"path"),p=F(s,"paymentHeaderName"),h=F(s,"paymentHeaderValue"),y=C=>C.length>0&&Buffer.byteLength(C)<=8192&&!/[\0\r\n]/.test(C);(d.length===0||d.length>16||!/^[A-Z]+$/.test(d)||!y(l)||!y(m)||!m.startsWith("/")||!y(h)||!["payment-signature","x-payment","authorization"].includes(p)||p==="authorization"&&!/^payment \S/i.test(h))&&J("tap_payload_invalid");let b=F(s,"nonce"),v=/^[A-Za-z0-9+/]*={0,2}$/.test(b)?Buffer.from(b,"base64"):null;(!v||v.length!==32||v.toString("base64")!==b)&&J("tap_payload_invalid");let A=s.coveredComponents;(!Array.isArray(A)||A.length<4||A.length>5)&&J("tap_payload_invalid");let E=new Set,S=[],I=[];for(let C of A){(typeof C!="string"||E.has(C))&&J("tap_payload_invalid"),E.add(C);let k;if(C==="@method")k=d;else if(C==="@authority")k=l;else if(C==="@path")k=m;else if(C==="content-digest"){let N=F(s,"contentDigest");(!y(N)||!N.startsWith("sha-256=:"))&&J("tap_payload_invalid"),k=N}else C===p?k=h:J("tap_payload_invalid");I.push(`"${C}"`),S.push(`"${C}": ${k}`)}(!["@method","@authority","@path",p].every(C=>E.has(C))||E.has("content-digest")!==(s.contentDigest!==void 0))&&J("tap_payload_invalid");let T=`(${I.join(" ")});created=${a};expires=${c};keyid="${F(s,"keyId")}";alg="Ed25519";nonce="${b}";tag="agent-payer-auth"`;S.push(`"@signature-params": ${T}`);let x=F(s,"signatureBase");return S.join(`
105
+ `)!==x&&J("tap_payload_invalid"),bt(r)||J("request_invalid"),this.pop(i,r,"urn:visa:tvc:identity-gate",Qs(x),u)}async financialEnrollmentProof(t,r){let n=await this.load(t);PA(n),e3(n,"wallet:x402");let i=Ut(r,["v","purpose","requestId","associationId","associationVersion","runtimeId","runtimeGeneration","childJkt","preparedCertificate","preparedDelegation","expiresAt"]);(ke(i,"v")!==1||F(i,"purpose")!=="financial.runtime.device.enroll"||!bt(F(i,"requestId"))||!bt(F(i,"associationId"))||ke(i,"associationVersion")===0||ke(i,"runtimeGeneration")===0)&&J("request_invalid"),(F(i,"runtimeId")!==n.runtimeId||F(i,"childJkt")!==n.jkt||n.binding.rootJkt===n.jkt)&&J("identity_binding_mismatch");let o=t3(i.preparedCertificate,"visa-agent-runtime-cert+jwt"),s=t3(i.preparedDelegation,"visa-agent-runtime-delegation+jwt");Ut(o.claims,$oe);let a=Ut(o.claims.cnf,["jwk","jkt"]),c="custody"in s.claims||"rails"in s.claims;Ut(s.claims,c?_Xe:Voe);let u=c?2:1;(ke(s.claims,"v")!==u||c&&(F(s.claims,"custody")!=="device"||!(Ho(s.claims.rails,["tempo","x402"])||Ho(s.claims.rails,["x402"]))))&&J("identity_binding_mismatch");let d=F(s.claims,"leaseIssuerJkt");(o.kid!==s.kid||!Ho(a.jwk,n.publicJwk)||F(a,"jkt")!==n.jkt||!Ho(o.claims.purposes,["wallet:x402"])||F(s.claims,"runtimeJkt")!==n.jkt||F(s.claims,"purpose")!=="wallet:x402"||F(s.claims,"network")!=="eip155:8453"||!Ho(s.claims.signingModes,["eip3009:exact"])||ke(s.claims,"maxLeaseTtlSeconds")!==300||!Hc(d)||d===n.jkt||d===n.binding.rootJkt)&&J("identity_binding_mismatch");let l=this.#t(),m=ke(o.claims,"iat"),p=ke(i,"expiresAt");(p!==m+300||p<=l||p>l+330)&&J("challenge_expired");for(let[h,y,b]of[[o.claims,86400,1],[s.claims,366*86400,u]]){(ke(h,"v")!==b||F(h,"iss")!==n.binding.rootJkt||F(h,"sub")!==n.binding.agentId||F(h,"runtimeId")!==n.runtimeId||!bt(F(h,"jti")))&&J("identity_binding_mismatch");let v=ke(h,"exp");(ke(h,"iat")!==m||ke(h,"nbf")!==m||v<p||v<=m||v-m>y)&&J("challenge_expired")}return this.pop(n,F(i,"requestId"),"visa:financial:device-enrollment:v1",Qs((0,Vi.canonicalJson)(i)),l)}async cardEnrollmentProof(t,r){let n=await this.load(t);PA(n),e3(n,"card:vic");let i=Ut(r,["v","audience","requestId","associationId","associationVersion","instrumentId","runtimeId","generation","childJkt","preparedCertificate","expiresAt"]);(ke(i,"v")!==1||F(i,"audience")!=="visa:financial:card-actor-enrollment:v1"||!bt(F(i,"requestId"))||!bt(F(i,"associationId"))||!bt(F(i,"instrumentId"))||ke(i,"associationVersion")===0||ke(i,"generation")===0)&&J("request_invalid");let o=t3(i.preparedCertificate,"visa-agent-runtime-cert+jwt");Ut(o.claims,$oe);let s=Ut(o.claims.cnf,["jwk","jkt"]);(F(i,"runtimeId")!==n.runtimeId||F(i,"childJkt")!==n.jkt||n.binding.rootJkt===n.jkt||ke(o.claims,"v")!==1||F(o.claims,"iss")!==n.binding.rootJkt||F(o.claims,"sub")!==n.binding.agentId||F(o.claims,"runtimeId")!==n.runtimeId||!bt(F(o.claims,"jti"))||!Ho(s.jwk,n.publicJwk)||F(s,"jkt")!==n.jkt||!Ho(o.claims.purposes,["card:vic"]))&&J("identity_binding_mismatch");let a=this.#t(),c=ke(o.claims,"iat"),u=ke(i,"expiresAt"),d=ke(o.claims,"exp");return(u!==c+300||u<=a||u>a+330||ke(o.claims,"nbf")!==c||d<u||d<=c||d-c>366*86400)&&J("challenge_expired"),this.pop(n,F(i,"requestId"),F(i,"audience"),Qs((0,Vi.canonicalJson)(i)),a)}async legacyProof(t,r){let n=await this.load(t);PA(n);let i=["nonce","audience","nowSec","intentHash"];Fc(r)&&r.runtimeCertificate!==void 0&&i.push("runtimeCertificate");let o=Ut(r,i),s=F(o,"audience");(mXe[n.binding.purpose]??[]).includes(s)||J("key_purpose_mismatch");let a=o.runtimeCertificate===void 0?void 0:F(o,"runtimeCertificate");return a!==void 0&&(a.length>16384||a.split(".").length!==3)&&J("runtime_certificate_invalid"),this.pop(n,F(o,"nonce"),s,F(o,"intentHash"),this.proofTime(o),a)}async legacyLeaseProof(t,r){let n=await this.load(t);PA(n),e3(n,"wallet:x402");let i=Ut(r,["agentId","runtimeId","requestId","signingMode","nowSec"]);(F(i,"agentId")!==n.binding.agentId||F(i,"runtimeId")!==n.runtimeId)&&J("identity_binding_mismatch");let o=F(i,"signingMode");o!=="eip3009:exact"&&o!=="permit2:upto"&&J("key_purpose_mismatch");let s=F(i,"requestId"),a=Qs(JSON.stringify({v:1,agentId:n.binding.agentId,runtimeId:n.runtimeId,requestId:s,signingMode:o}));return this.pop(n,s,"visa-runtime-lease-requests:v1",a,this.proofTime(i))}proofTime(t){let r=ke(t,"nowSec"),n=this.#t();return(r>n+30||r+60<n)&&J("proof_time_invalid"),r}async proofKey(t){let r=await this.describe(t);return(r.binding.profile!=="legacy-root-certified-v1"||!["wallet:x402","card:vic"].includes(r.binding.purpose))&&J("key_purpose_mismatch"),{jkt:r.jkt,publicJwk:r.publicJwk,createProof:n=>this.legacyProof(t,n),createLeaseProof:n=>this.legacyLeaseProof(t,n)}}close(){}};var zoe=require("node:child_process"),Ye=require("node:fs"),NA=require("node:path");var RA="com.visacli.agent-key.v2",Hp=16384,bXe=/^[0-9a-f]{64}$/;function ea(e){if(!bXe.test(e))throw new Error("custody_handle_invalid")}function kA(e){if(e.length===0||e.length>Hp)throw new Error("custody_record_too_large")}var Goe=null;var a3=(e,t,r,n)=>Goe!==null?Promise.reject(new Error(Goe)):EXe(e,t,r,n),EXe=(e,t,r,n)=>new Promise(i=>{let o="",s="",a=!1,c=(0,zoe.spawn)(e,[...t],{stdio:["pipe","pipe","pipe"],windowsHide:!0}),u=l=>{a||(a=!0,clearTimeout(d),i(l))},d=setTimeout(()=>{c.kill(),u({status:null,stdout:o,stderr:s,error:"timeout"})},n);d.unref(),c.stdout.setEncoding("utf8").on("data",l=>{o+=l}),c.stderr.setEncoding("utf8").on("data",l=>{s+=l}),c.on("error",l=>u({status:null,stdout:o,stderr:s,error:l.code==="ENOENT"?"missing":"failed"})),c.on("close",l=>u({status:l,stdout:o,stderr:s})),c.stdin.on("error",()=>{}),c.stdin.end(r)}),OA="/usr/bin/security",Koe=44,wXe=45,n3=class{#e;#t;#r=!1;constructor(t={}){if(t.keychain!==void 0&&/["\n\r]/.test(t.keychain))throw new Error("custody_directory_invalid");this.#e=t.keychain,this.#t=t.run??a3}target(){return this.#e===void 0?[]:[this.#e]}refused(){return new Error("keychain_locked_or_unavailable")}async requireKeychain(){if(this.#r)return;let t=this.#e;if(t===void 0){let r=await this.#t(OA,["default-keychain","-d","user"],"",5e3);if(t=r.stdout.trim().replace(/^"(.*)"$/,"$1"),r.status!==0||r.error||!t)throw new Error("keychain_not_found")}if(!(0,Ye.existsSync)(t))throw new Error("keychain_not_found");this.#r=!0}async create(t,r){ea(t),kA(r),await this.requireKeychain();let n=this.#e===void 0?"":` "${this.#e}"`,i=Buffer.from(r).toString("base64"),o=await this.#t(OA,["-i"],`add-generic-password -s ${RA} -a ${t} -l visa-cli-agent-key -w ${i}${n}
106
+ `,1e4);if(!(o.status===0&&!o.error))throw o.status===wXe?new Error("custody_handle_exists"):this.refused()}async read(t){ea(t),await this.requireKeychain();let r=await this.#t(OA,["find-generic-password","-s",RA,"-a",t,"-w",...this.target()],"",1e4);if(r.status===Koe)throw new Error("custody_unavailable");if(r.status!==0||r.error)throw this.refused();let n=r.stdout.trim(),i=/^[A-Za-z0-9+/]+={0,2}$/.test(n)?Buffer.from(n,"base64"):null;if(!i||i.toString("base64")!==n||i.length>Hp)throw new Error("custody_record_invalid");return i}async delete(t){ea(t),await this.requireKeychain();let r=await this.#t(OA,["delete-generic-password","-s",RA,"-a",t,...this.target()],"",1e4);if(!(r.status===0||r.status===Koe))throw this.refused()}},r3="secret-tool",i3=class{#e;constructor(t={}){this.#e=t.run??a3}attributes(t){return["service",RA,"handle",t]}refused(t){return t.error==="missing"?new Error("secret_service_unavailable"):/d-?bus|DBUS_SESSION_BUS_ADDRESS|\$DISPLAY|Could not connect/i.test(t.stderr)?new Error("secret_service_unavailable"):t.error==="timeout"?new Error("secret_service_timeout"):new Error("secret_service_locked_or_unavailable")}async lookup(t){let r=await this.#e(r3,["lookup",...this.attributes(t)],"",1e4);if(r.status===0&&!r.error)return r.stdout;if(r.status===1&&!r.error&&r.stderr.trim()==="")return null;throw this.refused(r)}async create(t,r){if(ea(t),kA(r),await this.lookup(t)!==null)throw new Error("custody_handle_exists");let n=await this.#e(r3,["store","--label=Visa CLI agent key",...this.attributes(t)],Buffer.from(r).toString("base64"),1e4);if(n.status!==0||n.error)throw this.refused(n)}async read(t){ea(t);let r=await this.lookup(t);if(r===null)throw new Error("custody_unavailable");let n=r.trim(),i=/^[A-Za-z0-9+/]+={0,2}$/.test(n)?Buffer.from(n,"base64"):null;if(!i||i.toString("base64")!==n||i.length>Hp)throw new Error("custody_record_invalid");return i}async delete(t){ea(t);let r=await this.#e(r3,["clear",...this.attributes(t)],"",1e4);if(!(r.status===1&&!r.error&&r.stderr.trim()==="")&&(r.status!==0||r.error))throw this.refused(r)}};function Yoe(e){if(!(0,Ye.existsSync)(e)){(0,Ye.mkdirSync)(e,{recursive:!0,mode:448}),process.platform!=="win32"&&(0,Ye.chmodSync)(e,448);return}let t=(0,Ye.lstatSync)(e);if(!t.isDirectory())throw new Error("custody_directory_invalid");if(process.platform!=="win32"&&(t.mode&63)!==0)throw new Error("custody_directory_not_private")}function Xoe(e,t){let r;try{r=(0,Ye.openSync)(e,"wx",384)}catch(i){throw i.code==="EEXIST"?new Error("custody_handle_exists"):new Error("custody_create_failed")}let n=0;try{for(;n<t.length;)n+=(0,Ye.writeSync)(r,t,n)}catch{throw(0,Ye.closeSync)(r),(0,Ye.rmSync)(e,{force:!0}),new Error("custody_create_failed")}(0,Ye.closeSync)(r)}function Woe(e){return new Error(e?.code==="ENOENT"?"custody_unavailable":"custody_store_unreadable")}function Zoe(e){let t;try{t=(0,Ye.lstatSync)(e)}catch(r){throw Woe(r)}if(!t.isFile()||t.size>Hp*2)throw new Error("custody_file_invalid");try{return(0,Ye.readFileSync)(e)}catch(r){throw Woe(r)}}var o3=class{constructor(t){this.directory=t}directory;path(t){return ea(t),(0,NA.join)(this.directory,`${t}.key`)}async create(t,r){let n=this.path(t);kA(r),Yoe(this.directory),Xoe(n,r)}async read(t){let r=this.path(t);if(process.platform!=="win32"&&(0,Ye.existsSync)(this.directory)){let i=(0,Ye.lstatSync)(this.directory);if(!i.isDirectory()||(i.mode&63)!==0)throw new Error("custody_directory_not_private")}let n=Zoe(r);if(process.platform!=="win32"&&((0,Ye.lstatSync)(r).mode&63)!==0)throw new Error("custody_file_invalid");if(n.length===0||n.length>Hp)throw new Error("custody_file_invalid");return n}async delete(t){(0,Ye.rmSync)(this.path(t),{force:!0})}},vXe="powershell.exe";function SXe(e,t){return ea(t),["$ErrorActionPreference = 'Stop'","Add-Type -AssemblyName System.Security","$payload = [Convert]::FromBase64String([Console]::In.ReadToEnd().Trim())",`$entropy = [Text.Encoding]::UTF8.GetBytes('visa-agent-key:${t}')`,`$result = [System.Security.Cryptography.ProtectedData]::${e}($payload, $entropy, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)`,"[Console]::Out.Write([Convert]::ToBase64String($result))"].join("; ")}var s3=class{constructor(t,r={}){this.directory=t;this.#e=r.run??a3}directory;#e;path(t){return ea(t),(0,NA.join)(this.directory,`${t}.dpapi`)}async call(t,r,n){let i=await this.#e(vXe,["-NoProfile","-NonInteractive","-Command",SXe(t,r)],Buffer.from(n).toString("base64"),3e4),o=i.stdout.trim();if(i.status!==0||i.error||!/^[A-Za-z0-9+/]+={0,2}$/.test(o))throw new Error("dpapi_locked_or_unavailable");return Buffer.from(o,"base64")}async create(t,r){let n=this.path(t);if(kA(r),Yoe(this.directory),(0,Ye.existsSync)(n))throw new Error("custody_handle_exists");Xoe(n,await this.call("Protect",t,r))}async read(t){let r=Zoe(this.path(t)),n=await this.call("Unprotect",t,r);if(n.length===0||n.length>Hp)throw new Error("custody_record_invalid");return n}async delete(t){(0,Ye.rmSync)(this.path(t),{force:!0})}};function CA(e=process.env){return(0,NA.join)(Xe(e),"agent-keys")}function Qoe(e=process.env,t=process.platform){let r=e.VISA_RUNTIME_CUSTODY_PROFILE??"os";if(r==="headless")return new o3(CA(e));if(r!=="os")throw new Error("native_runtime_custody_profile_invalid");if(t==="darwin")return new n3;if(t==="win32")return new s3(CA(e));if(t==="linux")return new i3;throw new Error("custody_platform_unsupported")}var jA=new Map;function Zd(e=process.env){let t=`${e.VISA_RUNTIME_CUSTODY_PROFILE??"os"}\0${CA(e)}`,r=jA.get(t);return r||(r=new TA(Qoe(e)),jA.set(t,r)),r}function AXe(){for(let e of jA.values())e.close();jA.clear()}process.once("exit",AXe);var Qy=require("node:crypto");async function ese(e,t,r){let{timeoutMs:n=3e4,...i}=t??{},o=i.signal===void 0&&e instanceof Request?e.signal:i.signal;o?.throwIfAborted();let s=new AbortController,{signal:a}=s,c=()=>s.abort(o?.reason);o?.addEventListener("abort",c,{once:!0});let u,d=new Promise((m,p)=>{u=()=>p(a.reason),a.addEventListener("abort",u,{once:!0})}),l=setTimeout(()=>s.abort(),n);try{return await Promise.race([(async()=>{let m=await fetch(e,{...i,signal:a});a.throwIfAborted();let p=await r(m,a);return a.throwIfAborted(),p})(),d])}finally{clearTimeout(l),o?.removeEventListener("abort",c),a.removeEventListener("abort",u)}}var MA=class extends Error{code="ATTESTATION_KEY_DRIFT";kind="attestation";nextAction="visa disconnect --all";fix="Run `visa disconnect --all` to clear the stale device credential, then `visa connect` to enroll again.";hint;constructor(t,r){super(t),this.name="AttestationDriftError",this.hint=r}},Xy=class extends Error{code="session_required";kind="session";nextAction="visa connect";fix="visa connect";status;constructor(t,r){super(t),this.name="SessionRequiredError",this.status=r}},qA=class extends Error{code="server_unavailable";kind="server";nextAction=void 0;fix;status;retryable;constructor(t,r=503,n=!0){super(t),this.name="ServerUnavailableError",this.status=r,this.retryable=n,this.fix=n?"Wait a moment and retry. If the outage persists check https://visacli.sh for status.":"Do not retry this request automatically; inspect the server error and reconcile the existing attempt."}},DA=class extends Error{code="surface_disabled";kind="server";nextAction=void 0;fix="This surface is disabled or not configured on the server (kill switch or missing config). Escalate to a human \u2014 retrying will not help.";status;disabledSurface;flag;correlationId;constructor(t,r={}){super(t),this.name="SurfaceDisabledError",this.status=r.status??503,this.disabledSurface=r.disabledSurface,this.flag=r.flag,this.correlationId=r.correlationId}},LA=class extends Error{constructor(r,n){super(r);this.retryAfterSeconds=n;this.name="RateLimitError",this.nextAction=void 0,this.fix=`Wait ${n}s before retrying.`}retryAfterSeconds;code="rate_limited";kind="rate_limit";fix;status=429;nextAction=void 0};var IXe=["UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_VERIFY_LEAF_SIGNATURE","SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","CERT_UNTRUSTED"],PXe="This machine does not trust the certificate offered for the Visa CLI server, so the request never left it. The server is not down, and neither retrying nor signing in again can help. A network that inspects TLS traffic does this: point Node at its root certificate with NODE_EXTRA_CA_CERTS=/path/to/root.pem, or use a network that does not inspect. Do not disable certificate verification.";function TXe(){return Object.fromEntries(IXe.map(e=>[e,PXe]))}var tse={ENOTFOUND:"Cannot resolve the Visa CLI server hostname (DNS error). Check your internet connection or the auth.serverUrl setting.",EAI_AGAIN:"DNS lookup for the Visa CLI server failed temporarily. Check your internet connection and try again.",ECONNREFUSED:"The Visa CLI server refused the connection. The service may be down \u2014 check https://visacli.sh for status.",ECONNRESET:"The connection to the Visa CLI server was reset mid-request. Try again in a moment.",EHOSTUNREACH:"The Visa CLI server is unreachable from this network. Check your internet connection.",ETIMEDOUT:"The connection to the Visa CLI server timed out. Try again or check https://visacli.sh for status.",CERT_HAS_EXPIRED:"The Visa CLI server's TLS certificate is expired. Check https://visacli.sh for status; do not bypass the cert.",...TXe(),ERR_TLS_CERT_ALTNAME_INVALID:"The certificate offered for the Visa CLI server is for a different hostname. Check the auth.serverUrl setting. Do not disable certificate verification.",UND_ERR_CONNECT_TIMEOUT:"The connection to the Visa CLI server timed out before it could be established. Try again in a moment.",UND_ERR_SOCKET:"The connection to the Visa CLI server was interrupted. Try again in a moment."};function c3(e){if(!e||typeof e!="object")return null;let t=e,n=(t.cause&&typeof t.cause=="object"?t.cause.code:void 0)??(typeof t.code=="string"?t.code:void 0);return typeof n=="string"&&n.length>0?n:null}function BA(e){let t=e&&typeof e=="object"?e:{};if(t.name==="AbortError"||typeof t.message=="string"&&t.message.includes("aborted"))return"The request timed out. The server may be under heavy load. Please try again.";let r=c3(e);return r&&tse[r]?tse[r]:`Network error contacting the Visa CLI server (${r?`${r}: ${typeof t.message=="string"?t.message:"unknown"}`:typeof t.message=="string"&&t.message.length>0?t.message:"unknown error"}). Check https://visacli.sh for status.`}var xXe="visa connect",OXe="agent_enroll",RXe="/agent/enroll/protected-agent",mft=Object.freeze(["setup_start","setup_status","setup_resume","setup_cancel","setup_agent","enroll_agent","agent_pairing_cancel","agent_handoff_claim","agent_connect","agent_connect_cancel","agent_connect_poll","feedback"]),gft=Object.freeze(["create","verify","enroll-claim","pair","claim","pairing-resume","cancel","handoff-claim","connect","grant-wallet","grant-card","grant-activate","grant-claim","grants","grant-cancel","grant-batch"]),hft=Object.freeze(["setup","agent","wallet","find","inspect","receipt","connections","keys","security","checkout","mandate","logout","capabilities","feedback","status","pay","purchase","limits","fund","activity"]);function rse(){return`Run ${xXe} or call ${OXe}, open the printed URL, enter the code at ${RXe}, approve the device and its limits, then pay with the pay tool. Do not retry the retired command; nothing was signed, paired, or paid.`}function ise(){return!!(nse(process.env.VISA_CLI_NO_UPDATE_CHECK)||nse(process.env.CI)||process.env.NODE_ENV==="test")}function nse(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var Zy="5.0.0-rc.408",CXe="1",NXe=/^vk_(?:live|test)_[A-Za-z0-9_-]{16,128}$/,kXe=5e3,wt=class extends Error{constructor(r,n,i,o,s,a){super(r);this.status=n;this.code=i;this.detail=o;this.serverRetryable=s;this.details=a;this.name="ApiHttpError"}status;code;detail;serverRetryable;details;get retryable(){return this.serverRetryable??(this.status>=500||this.status===408||this.status===425||this.status===429)}};function jXe(e){if(e===null||!/^\d{1,4}$/.test(e))return 3;let t=Number(e);return Number.isSafeInteger(t)&&t>=1&&t<=3600?t:3}var UA=class extends Error{constructor(r){super("Failed to retrieve task: Task not found");this.taskId=r;this.name="McpTaskNotFoundError"}taskId;rpcCode=-32602},MXe=new Set(["agent_paused","agent_revoked","device_key_replaced","grant_expired","owner_withdrawal_pending"]);function qXe(e,t){if(e===410&&(t?.code==="route_retired"||t?.error==="route_retired"))return new Rt(typeof t?.message=="string"&&t.message.length>0?t.message:"This legacy agent setup route was removed.","legacy_door_removed",{nextAction:rse(),details:{stage:"retired_door",...typeof t?.replacement=="string"?{replacement:t.replacement}:{}}});if(t?.error==="capability_attach_state_conflict"&&t?.attachId){let c=t.expiresAt?` (expires ${t.expiresAt})`:"",u=t.state?` in state '${t.state}'`:"";return new wt(`A pending capability-attach ceremony (${t.attachId}) is already${u}${c}. Cancel it in the Visa Console, or wait for it to expire.`,e,"capability_attach_state_conflict",void 0,!1)}if((t?.reason==="policy_step_up_required"||t?.error==="spend_policy_step_up_required")&&typeof t?.stepUp?.reviewUrl=="string")return new wt(`Owner confirmation required before this payment. Ask the owner to review it at ${t.stepUp.reviewUrl}. Nothing was paid.`,e,typeof t?.error=="string"?t.error:void 0,"policy_step_up_required",!1);if(t?.error==="owner_approval_required"&&t?.approval&&typeof t.approval=="object"&&!Array.isArray(t.approval))return new wt(typeof t?.message=="string"&&t.message?t.message:"owner_approval_required",e,"owner_approval_required",void 0,!1,{approval:t.approval});let r=typeof t?.error=="string"?t.error:typeof t?.code=="string"&&MXe.has(t.code)?t.code:void 0,n=typeof t?.reason=="string"?t.reason:void 0,i=typeof t?.retryable=="boolean"?t.retryable:void 0,o=typeof t?.message=="string"&&t.message||n||r||"";if(o)return new wt(o,e,r,n,i);let s=e>=500||e===408||e===425||e===429;return i??s?new wt(`Request failed (${e}). Try again.`,e,void 0,void 0,i):e===404?new wt(`Request failed (${e}) \u2014 not found; check the identifier or slug.`,e,void 0,void 0,i):new wt(`Request failed (${e}).`,e,void 0,void 0,i)}var DXe="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function Gi(e){return typeof e=="string"?e.trim():""}function LXe(e){let t=Gi(e.error_code)||Gi(e.error);return t?t==="SURFACE_DISABLED"||/(_disabled|_not_configured)$/.test(t):!1}function BXe(e){let t=e&&typeof e=="object"?e:{},r=Gi(t.error)||Gi(t.message);if(!r)return DXe;let n=Gi(t.error_code),i=[["surface",Gi(t.disabled_surface)],["flag",Gi(t.flag)],["correlation_id",Gi(t.correlation_id)]].filter(([,s])=>s).map(([s,a])=>`${s}=${a}`),o=i.length?` (${i.join(" ")})`:"";return n?`503 [${n}] ${r}${o}`:`503 ${r}${o}`}function UXe(e=process.env,t=process.stdin.isTTY){let r=["Not logged in. No local Visa CLI session credentials were found."],n=e.VISA_CLI_API_KEY?.trim();return n&&(NXe.test(n)?(r.push("VISA_CLI_API_KEY is set, but this operation requires an enrolled device session."),r.push("Use the Visa Key with X-Api-Key on the /v2/harness/* surface.")):r.push("VISA_CLI_API_KEY is set but has invalid format (expected vk_live_<...> or vk_test_<...>).")),r.push("Run `visa connect` to sign in and connect this device session."),t===!1&&r.push("Complete sign-in in a normal terminal with `visa connect`, then restart the MCP client."),r.join(`
107
+ `)}function na(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ta(e){return e===null||typeof e=="string"}function ra(e,t){let r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function HXe(e){if(!na(e))throw new Error("account activity returned a malformed entry");let t=e.rail;if(t!=="card"&&t!=="x402")throw new Error("account activity entry is missing a valid rail label");let r=e.amountUsd,n={id:e.id,operationId:e.operationId,merchant:e.merchant,description:e.description,currency:e.currency,status:e.status,createdAt:e.createdAt};for(let[i,o]of Object.entries(n))if(typeof o!="string"||o.length===0)throw new Error(`account activity entry is missing ${i}`);if(typeof r!="number"||!Number.isFinite(r))throw new Error("account activity entry is missing a numeric amount");return{id:n.id,operationId:n.operationId,merchant:n.merchant,description:n.description,amountUsd:r,currency:n.currency,status:n.status,rail:t,createdAt:n.createdAt,...ra(e,"failurePhase")?{failurePhase:e.failurePhase}:{},...ra(e,"finalizesBy")?{finalizesBy:e.finalizesBy}:{},...ra(e,"agentId")?{agentId:e.agentId}:{},...ra(e,"agentName")?{agentName:e.agentName}:{},...ra(e,"grantId")?{grantId:e.grantId}:{},...ra(e,"mandateId")?{mandateId:e.mandateId}:{},...ra(e,"drawId")?{drawId:e.drawId}:{},...ra(e,"transactionHash")?{transactionHash:e.transactionHash}:{},...ra(e,"transactionNetwork")?{transactionNetwork:e.transactionNetwork}:{}}}function FXe(e){if(!na(e))return null;let{payment:t,route:r,party:n,authority:i,outcome:o}=e;return e.schemaVersion!==1||typeof e.operationId!="string"||typeof e.activityId!="string"||!na(t)||typeof t.amountAtomic!="string"||typeof t.decimals!="number"||!Number.isSafeInteger(t.decimals)||t.decimals<0||typeof t.currency!="string"||typeof t.merchant!="string"||typeof t.description!="string"||typeof t.createdAt!="string"||!na(r)||r.rail!=="wallet"&&r.rail!=="card"||!ta(r.protocol)||!ta(r.network)||!ta(r.cardLast4)||!na(n)||!ta(n.agentId)||!ta(n.agentName)||!na(i)||!ta(i.grantId)||!ta(i.mandateId)||!ta(i.drawId)||!na(o)||typeof o.status!="string"||typeof o.proofLevel!="string"||typeof o.final!="boolean"||typeof o.updatedAt!="string"||!ta(o.finalizesBy)||!Array.isArray(e.evidence)||!e.evidence.every(na)||!Array.isArray(e.timeline)||!e.timeline.every(na)||e.dataCompleteness!=="complete"&&e.dataCompleteness!=="partial"?null:e}var Fp=class{constructor(t){this.getSessionToken=t;this.baseUrl=aa()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!ise()){let r=t.headers.get("X-Latest-Version");r&&ML(r,Zy)&&(this.lastSignals.updateAvailable={currentVersion:Zy,latestVersion:r})}}getClientVersion(){return Zy}getAuthServerOrigin(){return this.baseUrl}async signUcpRequest(t){let r=await this.request("POST","/v4/ucp/sign",t,15e3);if(!r||typeof r!="object"||Array.isArray(r)||!r.headers||typeof r.headers!="object"||Array.isArray(r.headers))throw new Error("UCP signing service returned a malformed response");let n=r.headers,i=Object.keys(n).sort(),o=["content-digest","signature","signature-input"];if(i.length!==o.length||i.some((s,a)=>s!==o[a])||o.some(s=>typeof n[s]!="string"||n[s].length===0||n[s].length>16384||/[\r\n]/.test(n[s])))throw new Error("UCP signing service returned invalid signature headers");return n}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new MA(t.error||"Your biometric key is out of sync with the server.",typeof t.hint=="string"?t.hint:void 0)}async throwServerUnavailable(t,r){let n=null;try{n=await t.json()}catch{r.throwIfAborted()}let i=BXe(n),o=n&&typeof n=="object"?n:{};throw LXe(o)?new DA(i,{status:t.status,disabledSurface:Gi(o.disabled_surface)||void 0,flag:Gi(o.flag)||void 0,correlationId:Gi(o.correlation_id)||void 0}):new qA(i,t.status,typeof o.retryable=="boolean"?o.retryable:!0)}async financialRuntimeRequest(t,r){return this.request("POST",`/v1/financial-runtime/${t}`,r,2e4)}async identityDeviceRequest(t,r){return this.request("POST",`/v1/identity-device/${t}`,r,2e4)}async request(t,r,n,i,o){let s=await this.getSessionToken();if(!s)throw new Xy(UXe());let a={Authorization:`Bearer ${s}`};o&&(t==="GET"?a["X-User-Context"]=encodeURIComponent(o.replace(/[\r\n\0]/g," ").slice(0,1e3)):n={...n||{},user_context:o}),n&&(a["Content-Type"]="application/json");let c;try{return await ese(`${this.baseUrl}${r}`,{method:t,headers:{...a,"X-Visa-CLI-Version":Zy,"X-Visa-Agent-Operations-Version":CXe,"X-Source":"cli",...jp()},body:n?JSON.stringify(n):void 0,timeoutMs:i},(u,d)=>(c=d,this.consumeResponse(u,d,t,r)))}catch(u){if(c&&!c.aborted)throw u;let d=new Error(BA(u)),l=c3(u);throw l&&(d.code=l),d}}async consumeResponse(t,r,n,i){if(this.parseServerSignals(t),t.status===401)throw new Xy("Your device session has expired. Run `visa connect` to refresh it (the device is already enrolled).",t.status);if(t.status===429){let s=jXe(t.headers.get("Retry-After"));throw new LA(`Rate limited \u2014 wait ${s}s, then retry.`,s)}t.status===503&&await this.throwServerUnavailable(t,r);let o;try{o=await t.json()}catch{if(r.throwIfAborted(),t.status===500)throw new wt(`Server error on ${i}. Try again or check https://visacli.sh for status.`,t.status);if(!t.ok){let s=t.status>=500||t.status===429||n==="GET"&&(t.status===408||t.status===425);throw new wt(s?`Unexpected response from ${i}. Try again.`:`Unexpected response from ${i} (${t.status}).`,t.status,void 0,void 0,s)}throw new Error(`Unexpected response from ${i}.`)}if(!t.ok){if(t.status===426||o?.error==="update_required"||o?.error_code==="update_required"||o?.errorCode==="update_required"){let s=typeof o?.runningVersion=="string"?o.runningVersion:Zy,a=typeof o?.minCompatibleVersion=="string"?o.minCompatibleVersion:qL;throw new By(s,a,i)}if(t.status===500){let s=typeof o?.retryable=="boolean"?o.retryable:void 0;throw new wt(s===!1?`Server error on ${i}. Inspect the server error and reconcile the existing attempt.`:`Server error on ${i}. Try again or check https://visacli.sh for status.`,t.status,typeof o?.error=="string"?o.error:void 0,typeof o?.reason=="string"?o.reason:void 0,s)}throw this.throwIfAttestationDrift(o),qXe(t.status,o)}return o}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t},kXe)}async merchantDirectorySearch(t,r){let n=new URLSearchParams;return t.provider&&n.set("provider",t.provider),t.q&&n.set("q",t.q),t.protocol&&n.set("protocol",t.protocol),t.maxPriceUsd&&n.set("max_price_usd",t.maxPriceUsd),t.verify&&n.set("verify",t.verify),n.set("limit",String(t.limit)),n.set("offset",String(t.offset)),this.request("GET",`/v1/merchant-directory/search?${n.toString()}`,void 0,void 0,r)}async merchantDirectoryCertified(t){return this.request("GET","/v1/merchant-directory/certified",void 0,void 0,t)}async getAccountActivity(t,r,n){let i=new URLSearchParams;t!==void 0&&i.set("limit",String(t)),r!==void 0&&i.set("agentId",r),n!==void 0&&i.set("cursor",n);let o=i.size>0?`?${i.toString()}`:"",s=await this.request("GET",`/v4/account/activity${o}`);if(!s||!Array.isArray(s.activity))throw new Error("account activity service returned an invalid response");let a=typeof s.next_cursor=="string"&&s.next_cursor.length>0?s.next_cursor:null;return{activity:s.activity.map(HXe),nextCursor:a}}async getAccountActivityMerchants(t){let r=new URLSearchParams;t!==void 0&&r.set("agentId",t);let n=r.size>0?`?${r.toString()}`:"",i=await this.request("GET",`/v4/account/activity/merchants${n}`);if(!i||i.window!=="90d"||typeof i.truncated!="boolean"||!Array.isArray(i.merchants))throw new Error("account activity totals returned an invalid response");return{window:"90d",truncated:i.truncated,merchants:i.merchants}}async getAccountActivityReceipt(t){let r;try{r=await this.request("GET",`/v4/account/activity/${encodeURIComponent(t)}`)}catch(i){throw i instanceof wt&&i.status===404?new Rt(`account activity entry not found: ${t}`,"activity_entry_not_found"):i}let n=FXe(r);if(!n)throw new Error("account receipt service returned an invalid or unsupported response");return n}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getAgentTapStatus(t){try{return await this.request("GET",`/v4/agent-bindings/${encodeURIComponent(t)}/tap-status`)}catch{return null}}async listAccountAgents(){try{let t=await this.request("GET","/v4/account/agents");return!t||!Array.isArray(t.agents)?null:t.agents.flatMap(r=>{if(!r||typeof r!="object")return[];let n=r,i=typeof n.agentId=="string"&&n.agentId.length>0?n.agentId:null,o=typeof n.agentJkt=="string"&&n.agentJkt.length>0?n.agentJkt:null;if(i===null&&o===null)return[];let s=n.approvedAuthority,a=s&&typeof s=="object"&&typeof s.grantId=="string"&&typeof s.status=="string"&&typeof s.totalMicros=="string"&&typeof s.perTransactionMicros=="string"&&typeof s.spentMicros=="string"&&typeof s.reservedMicros=="string"&&Array.isArray(s.scopes)?(()=>{let p=s;return{grantId:p.grantId,status:p.status,totalMicros:p.totalMicros,perTransactionMicros:p.perTransactionMicros,spentMicros:p.spentMicros,reservedMicros:p.reservedMicros,scopes:p.scopes.filter(h=>typeof h=="string"),...typeof p.expiresAt=="string"?{expiresAt:p.expiresAt}:{}}})():void 0,c=p=>typeof n[p]=="string"&&n[p].length>0?n[p]:void 0,u=n.executionReadiness,d=u&&typeof u=="object"&&!Array.isArray(u)?(()=>{let p=u,h=["shared","card","wallet"];if(Object.keys(p).some(b=>!h.includes(b))||Object.values(p).some(b=>typeof b!="string"))return;let y=Object.fromEntries(h.filter(b=>b in p).map(b=>[b,p[b]]));return Object.keys(y).length>0?y:void 0})():void 0,l=n.wallet,m=l&&typeof l=="object"&&!Array.isArray(l)?(()=>{let p=l,h=v=>typeof p[v]=="string"?{[v]:p[v]}:{},y=v=>typeof p[v]=="number"&&Number.isFinite(p[v])?{[v]:p[v]}:{},b={...h("walletAddress"),...h("network"),...typeof p.provisioned=="boolean"?{provisioned:p.provisioned}:{},...y("totalLimitCents").totalLimitCents!==void 0?y("totalLimitCents"):typeof p.dailyLimitCents=="number"&&Number.isFinite(p.dailyLimitCents)?{totalLimitCents:p.dailyLimitCents}:{},...y("perTransactionLimitCents")};return Object.keys(b).length>0?b:void 0})():void 0;return[{agentId:i,agentJkt:o,name:typeof n.name=="string"?n.name:"",revoked:n.revoked===!0,paused:n.paused===!0,...a?{approvedAuthority:a}:{},...c("executionStatus")?{executionStatus:c("executionStatus")}:{},...c("executionStatusReason")?{executionStatusReason:c("executionStatusReason")}:{},...d?{executionReadiness:d}:{},...c("identityKeyStatus")?{identityKeyStatus:c("identityKeyStatus")}:{},...c("tapStatus")?{tapStatus:c("tapStatus")}:{},...m?{wallet:m}:{}}]})}catch{return null}}async revokeAccountCardMandate(t){try{return await this.request("POST",`/v4/account/card-mandates/${encodeURIComponent(t)}/revoke`)}catch{return null}}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async logout(t,r){return this.request("POST","/v4/logout",t,void 0,r)}async putMcpTask(t,r){return this.request("PUT",`/v1/mcp-tasks/${encodeURIComponent(t)}`,r)}async getMcpTask(t){try{return await this.request("GET",`/v1/mcp-tasks/${encodeURIComponent(t)}`)}catch(r){throw r instanceof UA?r:r instanceof wt&&r.status===404?new UA(t):r}}async revokeSpendingAuthority(t){let r=await this.request("POST",`/v4/agents/${encodeURIComponent(t)}/spending-authority/revoke`,{});if(typeof r?.revoked!="boolean")throw new Error("spending authority revoke service returned an invalid response");return{revoked:r.revoked}}async claimAgentForApp(t,r,n){return{claimed:(await this.request("POST","/v4/account/agent-apps",{agentId:t,harnessId:r,...n?{deviceName:n}:{}}))?.claimed===!0}}async signTurnkeyTapPayload(t,r){let n=await this.request("POST",`/v4/account/agents/${encodeURIComponent(t)}/keychain/tap-sign`,{signatureBase:r});if(typeof n.signature!="string"||typeof n.keyId!="string")throw new Error("TAP signing service returned an invalid response");return{signature:n.signature,keyId:n.keyId}}};var ose=se(vd());var u3=new Set(["retired","revoked"]);async function sse(e){let{binding:t,signer:r,api:n,env:i}=e,o=Ji(t.agentId,i);if(o&&!o.revoked)return"connected";let s=Xd({agentId:t.agentId,env:i});if(!s)return"pending";try{let a=await r.create({profile:"identity-tap-v1",associationId:t.associationId,agentId:t.agentId,rootJkt:t.rootJkt,purpose:"tap"}),c=Bp(t.agentId,i),u=async p=>_A(p,i),d=c&&c.runtimeKey.handle===a.handle?c:await WL({api:n,native:r,key:a,agentId:t.agentId,associationId:t.associationId,expectedRootJkt:t.rootJkt,persist:u}),l=async()=>(d={...d,handoffId:(0,Qy.randomUUID)()},await u(d),await zs(n,r,d,"create"),"pending"),m;try{m=await gA(n,r,d)}catch(p){if(p instanceof wt&&p.code==="device_handoff_expired")return l();throw p}return m.status==="active"?(await Gy({pending:d,view:m,native:r,rootPublicJwk:t.rootPublicJwk,rootKid:t.rootKid,env:i}),"connected"):u3.has(m.status)?"stopped":m.status==="expired"||m.status==="cancelled"?l():"pending"}finally{s()}}async function ase(e){let{binding:t,native:r,api:n,env:i}=e,o=Ji(t.agentId,i);if(o&&!o.revoked)return"connected";let s=Bp(t.agentId,i);if(!s||s.runtimeKey.binding.profile!=="identity-tap-v1"||s.proposal.associationId!==t.associationId||s.proposal.rootJkt!==t.rootJkt)return"absent";let a=Xd({agentId:t.agentId,env:i});if(!a)return"pending";try{let c=async()=>{let d={...s,handoffId:(0,Qy.randomUUID)()};return _A(d,i),await zs(n,r,d,"create"),"pending"},u;try{u=await gA(n,r,s)}catch(d){if(d instanceof wt&&d.code==="device_handoff_expired")return c();throw d}return u.status==="active"?(await Gy({pending:s,view:u,native:r,rootPublicJwk:t.rootPublicJwk,rootKid:t.rootKid,env:i}),"connected"):u3.has(u.status)?"stopped":u.status==="expired"||u.status==="cancelled"?c():"pending"}finally{a()}}function $Xe(e){if(typeof e!="string"||e.split(".").length!==3)return null;try{let t=JSON.parse(Buffer.from(e.split(".")[1],"base64url").toString("utf8")).exp;return Number.isSafeInteger(t)?t:null}catch{return null}}function e0(e,t,r=Math.floor(Date.now()/1e3)){let n;try{n=Ji(e,t)}catch{return"missing"}if(!n||n.revoked||n.runtimeKey.binding.profile!=="identity-tap-v1")return"missing";let i=[n.active.delegation,n.active.gateAuthorization].map($Xe);if(i.some(s=>s===null))return"missing";let o=Math.min(...i);return o<=r?"expired":o-r<ose.TAP_RENEW_WINDOW_SECONDS?"renew_due":"live"}async function JXe(e){let{binding:t,native:r,api:n,env:i}=e,o;try{o=Ji(t.agentId,i)}catch{return!1}if(!o||o.revoked||o.runtimeKey.binding.profile!=="identity-tap-v1")return!1;let s=await zs(n,r,o,"read"),a=Number(o.active.challenge?.generation??0);return s.status!=="active"||!(Number(s.challenge?.generation??0)>a)?!1:(await Gy({pending:o,view:s,native:r,rootPublicJwk:t.rootPublicJwk,rootKid:t.rootKid,env:i,collectedRenewal:!0}),ne.info("identity_device_tap_renewal_collected",{agentId:t.agentId,generation:s.challenge?.generation}),!0)}async function d3(e){let{binding:t,native:r,api:n,env:i}=e,o=e0(t.agentId,i,e.nowSec);if(o==="live")return{state:"connected"};if(o!=="missing")return await JXe({binding:t,native:r,api:n,env:i})?{state:"renewed"}:{state:"owner_renews"};let s=Xd({agentId:t.agentId,env:i});if(!s){let a=Bp(t.agentId,i);return a?{state:"pending",pending:a}:{state:"connected"}}try{let a=Bp(t.agentId,i),c=async l=>_A(l,i),u=a&&a.runtimeKey.binding.profile==="identity-tap-v1"&&a.proposal.associationId===t.associationId&&a.proposal.rootJkt===t.rootJkt?a:null;if(!u){let l=await r.create({profile:"identity-tap-v1",associationId:t.associationId,agentId:t.agentId,rootJkt:t.rootJkt,purpose:"tap"});return u=await WL({api:n,native:r,key:l,agentId:t.agentId,associationId:t.associationId,expectedRootJkt:t.rootJkt,persist:c}),ne.info("identity_device_tap_key_proposed",{agentId:t.agentId}),{state:"pending",pending:u}}let d;try{d=await gA(n,r,u)}catch(l){if(!(l instanceof wt)||l.code!=="device_handoff_expired")throw l;return u={...u,handoffId:(0,Qy.randomUUID)()},await c(u),await zs(n,r,u,"create"),{state:"pending",pending:u}}return d.status==="active"?(await Gy({pending:u,view:d,native:r,rootPublicJwk:t.rootPublicJwk,rootKid:t.rootKid,env:i}),ne.info("identity_device_tap_connected",{agentId:t.agentId}),{state:"connected"}):u3.has(d.status)?{state:"stopped"}:((d.status==="expired"||d.status==="cancelled")&&(u={...u,handoffId:(0,Qy.randomUUID)()},await c(u),await zs(n,r,u,"create")),{state:"pending",pending:u})}finally{s()}}function cse(e,t){try{let r=Bp(e,t);if(!r||r.runtimeKey.binding.profile!=="identity-tap-v1")return!1;let n;try{n=Ji(e,t)}catch{n=null}return r.handoffId!==n?.handoffId}catch{return!1}}var use="5.0.0-rc.408",VXe=["association","handoff","lease","tap-sign"],dse=262144,GXe=2e4;function $p(e={}){let t=(e.origin??aa()).replace(/\/+$/,""),r=e.fetch;return{async identityDeviceRequest(n,i){if(!VXe.includes(n))throw new Error("identity_device_action_invalid");let o=JSON.stringify(i);if(Buffer.byteLength(o)>dse)throw new Error("identity_device_request_too_large");let s=`${t}/v1/identity-device/${n}`,a={method:"POST",headers:{"Content-Type":"application/json","X-Visa-CLI-Version":use,"X-Source":"cli",...jp()},body:o},c;try{c=await(r??fetch)(s,{...a,signal:AbortSignal.timeout(GXe)})}catch(l){throw new Error(BA(l))}let u;try{let l=Buffer.from(await c.arrayBuffer());if(l.byteLength>dse)throw new Error("response_too_large");u=JSON.parse(l.toString("utf8"))}catch{u=void 0}let d=uA(c.status,u,use);if(d)throw d;if(typeof u?.ok!="boolean")throw new wt(`Identity device relay returned an invalid response for ${n} (${c.status}).`,c.status,"identity_device_response_invalid",void 0,!1);if(!c.ok||u.ok!==!0){let l=typeof u.code=="string"?u.code:void 0,m=typeof u.retryable=="boolean"?u.retryable:void 0;throw new wt(`Identity device ${n} refused (${c.status}${l?` ${l}`:""}).`,c.status,l,void 0,m)}return u}}}var lse=require("node:crypto");var Jft=30*1e3,KXe=new Map;function WXe(){KXe.clear()}function zXe(e){let t=Aoe(e.homeDir),r=t?.financialDeviceRuntimeId;if(!t||t.agentId!==e.agentId||!r)return null;let n=Vd(e.agentId,e.env);if(!n||n.runtimeKey.runtimeId!==r)return null;let i=yoe(t,e.env),o=i?Bo(i):e.api;return{runtimeId:r,active:n,api:o}}async function YXe(e,t,r){return await e.financialRuntimeRequest("tempo-context",{requestId:(0,lse.randomUUID)(),agentId:t,runtimeId:r})}function fse(e){let t=e?.code;return t==="agent_revoked"||t==="device_key_replaced"}async function HA(e){let t;try{t=zXe(e)}catch{return"unknown"}if(!t)return"unknown";let r;try{r=await YXe(t.api,e.agentId,t.runtimeId)}catch(n){if(fse(n))throw n;return"unknown"}return r?.v!==1||typeof r.enrolled!="boolean"?"unknown":r.available===!1?"switched_off":(r.enrolled&&WXe(),r.enrolled?"enrolled":"setup_pending")}var l3={begin:async(e,t,r)=>{let n=Ko(r),i=f0(Date.now(),n);i&&i.verifier===t&&!i.likelyExpired||await aB(e,Date.now(),n,{verifier:t})},claim:(e,t)=>p0(e,{loginDir:Ko(t),attempts:1}),revert:async(e=process.env)=>{let t=Xr(e);if(t)try{await Ai.deleteProfileSessionToken(t,e)}finally{z3(t.profileId,e)}}};async function pse(e=process.env,t=wB){try{if(FL(e).length!==0)return null}catch{return null}let r=en(ca(e));try{let i=Ei(e);if(i&&Wd(i))return{baseUrl:r}}catch{}let n=await t(r);return n.ready&&n.features.includes(EB)?{baseUrl:r}:null}var mse={start:loe,claim:hoe,bindApi:Bo,custody:Zd,beginDevice:My,advanceDevice:Rp,connectDevice:Ooe,finishDevice:Roe,beginCard:Uoe,advanceCard:Wy,advanceTap:sse,identityDevice:$p,walletHomeForAgent:Lp,walletStateRoot:Uo,claimApp:(e,t,r)=>new Fp(()=>Ai.getSessionToken()).claimAgentForApp(e,t,r),deviceName:()=>cA(),tempoKey:HA,sleep:e=>new Promise(t=>setTimeout(t,e)),now:()=>Date.now(),signIn:l3,announceCode:e=>foe(e),announcePickup:e=>poe(e)},XXe=new Set(["identity_authority_not_configured"]);function f3(e){return e instanceof Do?!0:e instanceof Pn?!(e.code!==null&&XXe.has(e.code))&&(e.status>=500||e.status===429):qp(e)==="ProtectedAuthorityTransportError"}var ZXe=12e4,p3=12e4,QXe=3,m3=1e3,eZe=15e3,g3=1800*1e3;function tZe(e){return Math.min(m3*2**Math.max(0,e-1),eZe)}async function rZe(e,t,r){let n=t.app??HL(t.env);if(!n)return;let i=null;try{i=e.deviceName?e.deviceName():null}catch{i=null}try{let o=await e.claimApp(r,n,i);ne.info("agent:protected_enrollment_app_stamped",{agentId:r,harnessId:n,claimed:o.claimed,deviceReported:i!==null})}catch(o){ne.warn("agent:protected_enrollment_app_stamp_failed",{agentId:r,harnessId:n,error:o instanceof Error?o.message:"request refused"})}}async function nZe(e,t=mse){if(!Number.isSafeInteger(e.attempts)||e.attempts<1||e.attempts>900)throw new Error("Attempts must be between 1 and 900");let r=t.start({webOrigin:e.webOrigin,restart:e.restart,env:e.env,...e.webStartKey!==void 0?{webStartKey:e.webStartKey}:{},...e.signIn?{signIn:!0}:{},requestedLimits:e.requestedLimits??null});await coe(r,t.custody(e.env),e.env);let n=e.signIn&&Wd(r)?e.signIn:null,i=n?t.signIn??l3:null;n&&i&&await i.begin(n.baseUrl,r.verifier,e.env),await t.announceCode?.(r),r.webStartKey&&await t.announcePickup?.(r);let o=moe(r,e.app??HL(e.env),{heldAgentId:e.heldAgentId,priorRuntimes:e.priorRuntimes,limits:r.requestedLimits??null});r.requestedLimits&&ne.info("agent:protected_enrollment_requested_limits",{ceremonyId:r.ceremonyId,dailyCents:r.requestedLimits.dailyCents??null,perPurchaseCents:r.requestedLimits.perPurchaseCents??null}),!r.binding&&!r.webStartKey&&ne.info("agent:protected_enrollment_prior_runtimes",{ceremonyId:r.ceremonyId,challenge:r.challenge.slice(0,8),heldAgent:!!e.heldAgentId,priorRuntimes:e.priorRuntimes?.length??0});let s=Yi(r.verifier);r.binding||await e.announce({kind:"owner_enrollment",url:o,confirmCode:s});let a=null,c=0,u=null,d=t.now??(()=>Date.now()),l=d();for(let m=0;m<e.attempts;m++){if(d()-l>=g3){ne.warn("agent:protected_enrollment_pickup_deadline",{attempt:m+1,waitedMs:d()-l});break}m>0&&await t.sleep(c>0?tZe(c):m3);try{if(n&&i&&Wd(r)){let p=await i.claim(n.baseUrl,e.env);if(p.status==="confirm_mismatch")throw new Error("The code entered in the browser does not match this terminal, so it was not signed in. Run `visa connect --restart` and enter the code this terminal shows.");if(p.status==="error")throw new Do("Visa sign-in","network",0);if(p.status!=="claimed"||!UL(r,e.env))continue}try{a=await t.claim(r,e.env)}catch(p){if(r.signIn===!0&&p instanceof Rt&&p.code==="enrollment_owner_mismatch")try{await(t.signIn??l3).revert(e.env)}catch(h){ne.warn("agent:protected_enrollment_sign_in_revert_failed",{reason:h instanceof Error?h.name:typeof h})}throw p}}catch(p){if(!f3(p))throw p;c++,u=p,ne.warn("agent:protected_enrollment_pickup_retry",{attempt:m+1,consecutiveFailures:c,status:p instanceof Pn?p.status:null,reason:p instanceof Do?p.reason:null});continue}if(c=0,u=null,a)break}return a?{status:"identity_active",pending:r,binding:a,enrollmentUrl:o}:{status:"awaiting_owner_enrollment",browserUrl:o,confirmCode:s,...u?{lastPickupFailure:u instanceof Error?u.message:"Authority unavailable"}:{}}}async function gse(e,t=mse){if(e.perTransactionLimitCents>e.dailyLimitCents)throw new Rt("Per-purchase limit exceeds daily limit","invalid_argument");if(!Number.isSafeInteger(e.attempts)||e.attempts<1||e.attempts>900)throw new Rt("Attempts must be between 1 and 900","invalid_argument");let r=await nZe(e,t);if(r.status!=="identity_active")return r;let{pending:n,binding:i,enrollmentUrl:o}=r,s={v:1,authorityOrigin:n.authorityOrigin,executionOrigin:n.executionOrigin,transportProfileId:n.transportProfileId,binding:i},a=t.bindApi(s),c=Bie(t.custody(e.env),n.deviceKeys),u={api:a,signer:c,selection:s,env:e.env,ceremony:{ceremonyId:i.ceremonyId,challenge:n.challenge,verifier:n.verifier}},d=t.identityDevice({origin:n.executionOrigin}),l="pending",m,p,h=!1,y=async()=>{if(!(l==="connected"||l==="stopped"||h))try{l=await t.advanceTap({binding:i,signer:c,api:d,env:e.env}),m=void 0,p=void 0}catch(j){l="failed",h=!f3(j),m=j instanceof Error?j.message:"TAP connection refused",p=tl(j),ne.warn("agent:protected_enrollment_tap_pending",{agentId:i.agentId,errorName:qp(j),code:p.code,...j instanceof Pn?{status:j.status}:{}})}},b=await t.beginCard({...u,initialConnection:!0});await y();let v=async()=>{try{return(await t.advanceCard(u)).status==="active"}catch(j){if(!f3(j))throw j;return ne.warn("agent:protected_card_connection_pending",{agentId:i.agentId,errorName:qp(j),...j instanceof Pn?{status:j.status}:{}}),!1}},A=()=>t.walletHomeForAgent(i.agentId,t.walletStateRoot(e.env),i.ownerPublicId),E=async j=>t.tempoKey?t.tempoKey({api:a,agentId:i.agentId,homeDir:j,env:e.env}):"enrolled",S=async j=>(j!=="enrolled"&&ne.warn("agent:protected_enrollment_wallet_key_owed",{agentId:i.agentId,walletKey:j}),ne.info("agent:protected_enrollment_connected",{agentId:i.agentId,tap:l,walletKey:j,wait:e.wait}),await rZe(t,e,i.agentId),{status:"connected",agentId:i.agentId,tap:l,...l==="failed"&&m?{tapError:m}:{},...l==="failed"&&p?{tapDiagnostic:p}:{},walletKey:j});if(!e.wait){let j=await t.beginDevice({api:a,signer:c,agentId:i.agentId,ownerPublicId:i.ownerPublicId,cardProposal:b.proposal,ceremony:{ceremonyId:i.ceremonyId,challenge:n.challenge,verifier:n.verifier},env:e.env}),D=await t.advanceDevice({api:a,signer:c,pending:j,env:e.env}),U=j.cardProposal?await v():!0;await y();let q=l==="failed"?{tap:l,tapError:m,tapDiagnostic:p}:{};if(!(D?.prepared?.status==="active"||!!D?.evidence?.owner_signatures))return{status:"awaiting_owner_device_approval",browserUrl:o,agentId:i.agentId,...q};let V=A();return U&&await t.finishDevice({api:a,signer:c,agentId:i.agentId,ownerPublicId:i.ownerPublicId,agentName:"Protected agent",authUrl:n.authorityOrigin,walletHomeDir:V,pending:j,view:D,env:e.env})?S(await E(V)):(ne.info("agent:protected_enrollment_device_finishing",{agentId:i.agentId,active:D?.prepared?.status==="active",companionReady:U}),{status:"finishing_device_setup",browserUrl:o,agentId:i.agentId,...q})}let I=A();await t.connectDevice({api:a,signer:c,agentId:i.agentId,ownerPublicId:i.ownerPublicId,cardProposal:b.proposal,advanceCompanion:v,advanceTap:async()=>{l==="failed"&&!h&&(l="pending"),await y()},ceremony:{ceremonyId:i.ceremonyId,challenge:n.challenge,verifier:n.verifier},agentName:"Protected agent",authUrl:n.authorityOrigin,walletHomeDir:I,env:e.env});let T=t.now??(()=>Date.now()),x=T()+ZXe,C=T()+p3,k=await E(I),N=()=>(l==="pending"||l==="failed")&&!h,M=()=>k==="setup_pending"||k==="unknown";for(let j=1;;j++){let D=N()&&T()<x,U=M()&&T()<C;if(!D&&!U)break;await t.sleep(m3),D&&(l==="failed"&&(l="pending"),await y()),U&&j%QXe===0&&(k=await E(I))}return S(k)}var hse=require("node:path");function iZe(e,t){return Ji(e,t),(0,hse.join)(Xe(t),"financial-device-presence",`${e}.revocation.json`)}function FA(e,t){let r=$i(iZe(e,t));if(r===null)return null;sr(r);let n=JSON.parse(r);if(n.v!==1||n.selected?.proposal.agentId!==e||!Array.isArray(n.keys)||!n.keys.length||!["awaiting_owner","revocation_verified","complete"].includes(n.phase)||n.keys.some(({record:o})=>o.proposal.agentId!==e||o.proposal.runtimeId!==n.selected.proposal.runtimeId||o.proposal.associationId!==n.selected.proposal.associationId))throw new Error("identity_device_revocation_invalid");if(Ji(e,t)?.handoffId!==n.selected.handoffId){if(n.phase==="complete")return null;throw new Error("identity_device_selection_changed")}return n}var Qd=require("node:fs"),Jp=require("node:path"),Ese=require("node:crypto");var _se=require("node:crypto");var yse=e=>e instanceof Error&&e.message?e.message:String(e);function Fo(e,t){try{let r=FA(e,t);if(r&&r.phase!=="complete"&&zL(r.selected))return{state:"revoking"};let n=Ji(e,t);if(n?.revoked&&zL(n))return{state:"revoked"}}catch(r){return{state:"unreadable",detail:`presence: ${yse(r)}`}}try{let r=Vd(e,t);if(r)return{state:"installed",runtimeId:r.runtimeKey.runtimeId,record:r};let n=Op(e,t);if(n)return{state:"wallet_setup_pending",runtimeId:n.runtimeKey.runtimeId}}catch(r){return{state:"unreadable",detail:yse(r)}}return{state:"missing"}}function oZe(e){let t=e?.deviceWalletAuthority;return t==="live"||t==="expired"||t==="absent"?t:"unreachable"}function sZe(e){let t=e?.code;if(t==="agent_revoked")return"revoked";if(t==="device_key_replaced")return"replaced";let r=e?.status;return typeof r=="number"&&r>=400&&r<500&&r!==408&&r!==429?"refused":"unreachable"}async function bse(e,t=(n,i)=>Bo(e).financialRuntimeRequest(n,i),r){try{return oZe(await t("device-context",{requestId:(0,_se.randomUUID)(),agentId:e.binding.agentId,...r?{runtimeId:r}:{}}))}catch(n){if(h3(n))throw n;return sZe(n)}}function h3(e){return e instanceof Error&&/independently claimed owner/.test(e.message)}var aZe=["revoked","key_not_held","replaced","superseded"],$A=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function t0(e){let t=(0,Jp.join)(Xe(e),"protected-enrollment","retired");return(0,Qd.mkdirSync)(t,{recursive:!0,mode:448}),Lr(t),t}function y3(e,t,r,n=()=>new Date){if(!$A.test(e))throw new Error("retired_agent_id_invalid");let i=(0,Jp.join)(t0(r),`${e}.json`),o=wse(i);if(o)return o;let s={v:1,agentId:e,reason:t,retiredAt:n().toISOString()};return Ht(i,JSON.stringify(s)),s}function wse(e){let t=cr(e);if(t===null)return null;let r=JSON.parse(t);if(r?.v!==1||!$A.test(r.agentId)||!aZe.includes(r.reason)||typeof r.retiredAt!="string")throw new Error("retired_agent_record_invalid");return r}function _3(e){let t=new Map,r;try{r=(0,Qd.readdirSync)(t0(e))}catch{return t}for(let n of r)if(!(!n.endsWith(".json")||!$A.test(n.slice(0,-5))))try{let i=wse((0,Jp.join)(t0(e),n));i&&`${i.agentId}.json`===n&&t.set(i.agentId,i)}catch{}return t}function Vp(e){let t=_3(e);return Dp(e).filter(r=>!t.has(r.binding.agentId))}async function vse(e,t){let r=e.binding.agentId,n=[],i=null,o=Fo(r,t.env);o.state==="installed"&&(n.push(o.record.runtimeKey.handle),i=o.record.runtimeKey.runtimeId);try{let s=Uc(e,t.env);s?.certificate&&n.push(s.runtimeKey.handle)}catch{}if(n.length>0&&(await Promise.all(n.map(a=>t.holds(a)))).every(a=>a==="missing")&&ne.warn("agent:held_agent_keys_not_in_this_store",{agentId:r}),i)try{await t.api(e).financialRuntimeRequest("tempo-context",{requestId:(0,Ese.randomUUID)(),agentId:r,runtimeId:i})}catch(s){if(s instanceof Pn&&s.code==="agent_revoked")return{agentId:r,verdict:"retire",reason:"revoked"};if(s instanceof Pn&&s.code==="device_key_replaced")return{agentId:r,verdict:"retire",reason:"replaced"}}if((t.resumable??JA)(e,t.env))return{agentId:r,verdict:"usable"};try{if(await t.association?.(e)==="revoked")return{agentId:r,verdict:"retire",reason:"revoked"}}catch{}return{agentId:r,verdict:"usable"}}async function cZe(e){let t=[],r,n;try{r=_3(e.env),n=Dp(e.env)}catch{return t}for(let i of n){let o=i.binding.agentId;if(r.get(o)?.reason==="key_not_held")try{if((await vse(i,e)).verdict==="retire"){(0,Qd.rmSync)((0,Jp.join)(t0(e.env),`${o}.json`),{force:!0}),y3(o,"revoked",e.env);continue}(0,Qd.rmSync)((0,Jp.join)(t0(e.env),`${o}.json`),{force:!0}),ne.info("agent:held_agent_restored",{agentId:o}),t.push(o)}catch(s){ne.warn("agent:held_agent_restore_failed",{agentId:o,error:s instanceof Error?s.message:String(s)})}}return t}async function Sse(e){let t;try{t=Vp(e.env)}catch{return[]}await cZe(e);try{t=Vp(e.env)}catch{return[]}let r=[];for(let n of t)try{let i=await vse(n,e);if(i.verdict!=="retire")continue;let o=y3(i.agentId,i.reason,e.env);ne.warn("agent:held_agent_retired",{agentId:o.agentId,reason:o.reason}),r.push(o)}catch(i){ne.warn("agent:held_agent_judge_failed",{agentId:n.binding.agentId,error:i instanceof Error?i.message:String(i)})}return r}function b3(e){let t;try{t=Vp(e)}catch{return[]}let r=new Map(t.map(i=>{try{return[i.binding.agentId,E3(i,e)]}catch{return[i.binding.agentId,null]}}));if(![...r.values()].includes("installed"))return[];let n=[];for(let i of t){let o=i.binding.agentId;if(r.get(o)!=="unfinished"||JA(i,e))continue;let s=Fo(o,e);if(s.state!=="wallet_setup_pending"&&s.state!=="missing"){s.state==="unreadable"&&ne.warn("agent:held_agent_setup_unreadable",{agentId:o,detail:s.detail});continue}try{if(Uc(i,e)?.certificate)continue}catch{ne.warn("agent:held_agent_setup_unreadable",{agentId:o,detail:"card record"});continue}try{let a=y3(o,"superseded",e);ne.warn("agent:held_agent_retired",{agentId:o,reason:a.reason}),n.push(a)}catch(a){ne.warn("agent:held_agent_retire_failed",{agentId:o,error:a instanceof Error?a.message:String(a)})}}return n}async function Ase(e){try{return await $p({origin:e.executionOrigin}).identityDeviceRequest("association",{agentId:e.binding.agentId}),"active"}catch(t){return t instanceof wt&&(t.code==="association_inactive"||t.code==="agent_revoked")?"revoked":"unknown"}}function E3(e,t){if(Fo(e.binding.agentId,t).state!=="installed")return"unfinished";try{let r=Uc(e,t);if(r&&!r.certificate)return"unfinished"}catch{}return"installed"}function JA(e,t){let r;try{r=Ei(t)}catch{return!1}return!!(r?.binding&&r.binding.agentId===e.binding.agentId&&r.binding.associationId===e.binding.associationId&&Date.now()-r.createdAt<Lc)}async function Ise(e,t,r){let n=[],i=Fo(e.binding.agentId,r);i.state==="installed"&&n.push(i.record.runtimeKey.handle);try{let s=Uc(e,r);s?.certificate&&n.push(s.runtimeKey.handle)}catch{}return n.length===0?"readable":(await Promise.all(n.map(s=>t(s).catch(()=>"unknown")))).every(s=>s==="missing")?"unreadable":"readable"}function uZe(e,t,r){return e===null||r||e.state==="installed"||t?.certificate||e.state!=="wallet_setup_pending"&&e.state!=="missing"&&e.state!=="revoked"?!1:e.state==="wallet_setup_pending"||!!t}function Pse(e){let t,r;try{t=Dp(e),r=_3(e)}catch{return[]}let n=new Set;for(let i of t){let o=i.binding.agentId,s=r.get(o)?.reason;if(s==="replaced"||s==="revoked")continue;let a=null;try{a=Fo(o,e)}catch{}let c=null,u=!1;try{c=Uc(i,e)}catch{u=!0}s===void 0&&!uZe(a,c,u)||((a?.state==="installed"||a?.state==="wallet_setup_pending")&&n.add(a.runtimeId),c&&n.add(c.runtimeKey.runtimeId))}return[...n].filter(i=>$A.test(i))}var dZe=new Set(["registered","removal_pending","pending","blocked","not_requested","deactivated","contact_required","unavailable"]);function lZe(e){return typeof e=="string"&&dZe.has(e)?e:"unknown"}function fZe(e,t,r){return{key:e0(e,r),directory:lZe(t?.find(n=>n.agentId===e)?.tapStatus)}}async function Tse(e,t,r){let n=null;try{n=await t()}catch{n=null}return fZe(e,n,r)}function xse(e){return Tse(e,()=>new Fp(()=>Ai.getSessionToken()).listAccountAgents())}async function pZe(e){try{if(await Ai.getSessionToken())return"already"}catch{}try{let t=f0();if(!t||t.likelyExpired||e===!0)return null;let r=en(ca()),n=await p0(r,{attempts:1});return n.status==="confirm_mismatch"?n:n.status==="claimed"?"claimed":null}catch{return null}}var Ose=e=>e==="setup_pending"?"finish_wallet_key":e==="switched_off"?"wallet_switched_off":e==="unknown"?"confirm_wallet_key":"none";async function mZe(e){try{return await HA({api:Bo(e),agentId:e.binding.agentId,homeDir:Lp(e.binding.agentId,Uo(),e.binding.ownerPublicId)})}catch{return"unknown"}}async function gZe(e){let t=e.binding,r=Fo(t.agentId);if(r.state==="installed"){try{await bse(e)}catch(s){if(h3(s))throw s}let o=r.record;if(o.ownerPublicId!==t.ownerPublicId||o.organizationId!==t.organizationId||o.proposal.associationId!==t.associationId||o.proposal.associationVersion!==t.associationVersion||o.proposal.rootJkt!==t.rootJkt||o.rootKid!==t.rootKid)throw new Error("Protected wallet installation differs from its independently claimed owner");return}let n;try{n=Op(t.agentId)}catch{return}if(!n)return;let i=Ei();if(i?.binding?.agentId!==t.agentId||i.binding.ceremonyId!==t.ceremonyId||i.executionOrigin!==e.executionOrigin||i.authorityOrigin!==e.authorityOrigin||Date.now()-i.createdAt>=Lc||n.ceremony.ceremonyId!==i.ceremonyId||n.ceremony.challenge!==i.challenge||n.ceremony.verifier!==i.verifier||n.proposal.associationId!==t.associationId||n.proposal.associationVersion!==t.associationVersion||n.proposal.rootJkt!==t.rootJkt)throw new Error("Existing wallet setup cannot resume this identity; call get_status before restarting enrollment")}async function hZe(e,t,r){let n=e.binding.agentId,i=Fo(n).state,o=i==="revoking"||i==="revoked";try{let a=FA(n);o||=!!(a&&a.phase!=="complete")}catch{}if(o)return{state:"revoking"};let s={binding:e.binding,native:Zd(),api:$p({origin:e.executionOrigin})};try{let a=await ase(s);if(a==="stopped")return{state:"stopped"};let c=a==="pending";if(!c)try{c=cse(n)||e0(n)!=="live"}catch{c=!0}if(!c)return{state:"live"};let u=Date.now()+Math.max(1,r)*1e3,d=await d3(s);for(;d.state==="pending"&&t&&Date.now()<u;)await new Promise(l=>setTimeout(l,1e3)),d=await d3(s);return d.state!=="pending"?{state:d.state}:{state:"awaiting_owner",url:koe(bB(ca()),d.pending),fingerprint:d.pending.proposal.runtimeJkt}}catch(a){return{state:"failed",error:a}}}async function yZe(e,t,r){let n=await ZL(e);if(!t||!n.renew)return{card:{state:"untouched"},cardKey:n.state};try{let i={api:Bo(e),signer:Zd(),selection:e,renewWithinSeconds:SA},o=await Wy(i);return o.status==="retry"&&(o=await Wy(i)),o.status==="active"?{card:{state:"renewed"},cardKey:(await ZL(e)).state}:o.status==="awaiting_owner"?{card:{state:"awaiting_owner",url:Loe(ca({...process.env,VISA_AUTH_URL:e.authorityOrigin}),{proposal:o.proposal},r)},cardKey:"renewing"}:{card:{state:"busy"},cardKey:"renewing"}}catch(i){return{card:{state:"failed",error:i},cardKey:n.state}}}function _Ze(e){if(e!==void 0&&!aoe.test(e))throw new Rt("That setup key is not one Visa issued. Copy the whole `visa connect --setup` line from the page that started the setup.","invalid_argument")}async function Rse(e){_Ze(e.webStartKey);let t=[],r=[],n=await pZe(e.restart),i=typeof n=="object"?n:null,o=typeof n=="string"?n:null;o==="already"&&e.verifySession&&await e.verifySession()===!1&&(o=null);let s=o||i?null:await pse();if(s&&(o="one_code"),!o){let y=await e.signIn(i);if(!y.done)return{leg:"signin",pending:y.pending,signIn:"pending",retired:t,superseded:r,nextAction:"sign_in"};o="interactive"}let a={signIn:o,retired:t,superseded:r},c=null,u=null;if(!e.restart){t.push(...await Sse({holds:async b=>Zd().holds(b),api:b=>Bo(b),association:Ase}),...b3());let y=e.webStartKey===void 0?Vp()[0]:void 0;if(y){let b=y.binding.agentId;await gZe(y);let v=E3(y)==="unfinished";if(v&&JA(y))c=b;else if(doe(ca()))u={heldAgentId:b};else{if(v)return{...a,leg:"unfinished_expired",agentId:b,nextAction:"restart_to_replace"};if(await Ise(y,async A=>Zd().holds(A))==="unreadable")return{...a,leg:"unreadable_keys",agentId:b,nextAction:"restart_new_agent"};{let A=await hZe(y,e.tapWait,e.tapAttempts??e.attempts),E=A.state==="awaiting_owner"?null:await mZe(y),S;try{S=Fo(b).state!=="missing"}catch{S=!0}let I=Ose(E),T=I!=="none"&&(S||I!=="confirm_wallet_key"),x=A.state==="awaiting_owner"?"approve_device":A.state==="failed"?tl(A.error).code==="update_required"?"update_cli":"retry_tap":T?I:A.state==="owner_renews"?"owner_renews_tap":"none",{card:C,cardKey:k}=await yZe(y,x==="none",e.app),N=x!=="none"?x:C.state==="awaiting_owner"?"approve_card":C.state==="failed"||C.state==="busy"?"retry_card":I;return{...a,leg:"held",agentId:b,tap:A,walletKey:E,tapStatus:await xse(b),card:C,cardKey:k,nextAction:N}}}}}let d=null,l;try{l=e.webStartKey===void 0?Vp()[0]?.binding.agentId:void 0}catch{l=void 0}let m=await gse({webOrigin:ca(),...l!==void 0?{heldAgentId:l}:{},...s?{signIn:s}:{},...e.app!==void 0?{app:e.app}:{},restart:e.restart,...e.webStartKey!==void 0?{webStartKey:e.webStartKey}:{},...e.webStartKey===void 0&&c===null?{priorRuntimes:Pse()}:{},wait:e.wait,attempts:e.attempts,dailyLimitCents:e.dailyLimitCents,perTransactionLimitCents:e.perTransactionLimitCents,requestedLimits:e.requestedLimits??null,announce:async y=>{d=y,await e.announce?.(y,s!==null)}});m.status!=="awaiting_owner_enrollment"&&r.push(...b3());let p=m.status==="awaiting_owner_enrollment"?"approve":m.status==="awaiting_owner_device_approval"?"approve_device":m.status==="finishing_device_setup"?"finish_device":Ose(m.walletKey),h=m.status==="awaiting_owner_enrollment"?null:await xse(m.agentId);return{...a,leg:"enroll",resumed:c,result:m,announcement:d,tapStatus:h,restartPickup:u,nextAction:p}}var bZe=1e3,EZe=900,jse=g3+p3+6e4;var smt=60*6e4,Mse=jse+6e4;function w3(e){return"enr_"+(0,GA.createHash)("sha256").update(e).digest("base64url").slice(0,16)}function qse(e){let t=(0,Gp.join)(Xe(e),"protected-enrollment");return(0,Kt.mkdirSync)(t,{recursive:!0,mode:448}),Lr(t),t}var Dse=e=>(0,Gp.join)(qse(e),"finisher.json"),Lse=e=>(0,Gp.join)(qse(e),"finisher.lock");function wZe(e){let t=cr(Dse(e));if(t===null)return null;let r=JSON.parse(t);if(r?.v!==1||typeof r.ref!="string"||!["finishing","connected","failed","expired","stopped"].includes(r.state)||!Number.isFinite(r.startedAt)||!Number.isFinite(r.updatedAt))throw new Error("Enrollment finisher record is malformed");return r}function vZe(e,t){Ht(Dse(t),JSON.stringify(e))}function Cse(e,t,r,n,i={}){let o=null;try{o=wZe(n)}catch{o=null}if(i.keepOtherRef&&o&&o.ref!==e)return null;let a={...o&&o.ref===e?o:{v:1,ref:e,state:"finishing",startedAt:r,updatedAt:r,pid:null},...t,v:1,ref:e,updatedAt:r};return vZe(a,n),a}function SZe(e){if(!Number.isSafeInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}function Nse(e){try{let t=JSON.parse((0,Kt.readFileSync)(Lse(e),"utf8"));return t.version===1&&Number.isSafeInteger(t.pid)&&typeof t.token=="string"&&Number.isFinite(t.createdAt)&&(t.pidStart===void 0||t.pidStart===null||typeof t.pidStart=="string")&&(t.holder===void 0||t.holder==="finisher"||t.holder==="connect")?t:null}catch{return null}}function AZe(e){if(process.platform==="win32"||!Number.isSafeInteger(e)||e<=0)return null;try{return(0,VA.execFileSync)("ps",["-o","lstart=","-p",String(e)],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim()||null}catch{return null}}function IZe(e,t){if(!SZe(e.pid))return!1;let r=null;try{r=v3.processStart(e.pid)}catch{r=null}return e.pidStart&&r?r===e.pidStart:t-e.createdAt<Mse}function PZe(e,t=Date.now(),r=process.pid,n="finisher"){let i=Lse(e),o=null;try{o=v3.processStart(r)}catch{o=null}for(let s=0;s<2;s++){let a=(0,GA.randomUUID)();try{let c=(0,Kt.openSync)(i,"wx",384);try{(0,Kt.writeFileSync)(c,JSON.stringify({version:1,pid:r,token:a,createdAt:t,pidStart:o,holder:n}),"utf8"),(0,Kt.fsyncSync)(c)}finally{(0,Kt.closeSync)(c)}let u=()=>Nse(e)?.token===a;return Object.assign(()=>{if(u())try{(0,Kt.unlinkSync)(i)}catch{}},{held:u})}catch(c){if(c?.code!=="EEXIST")throw c;let u=Nse(e),d;if(u)d=!IZe(u,t);else try{d=t-(0,Kt.statSync)(i).mtimeMs>=Mse}catch{d=!0}if(!d)return null;try{(0,Kt.unlinkSync)(i)}catch(l){if(l?.code!=="ENOENT")throw l}}}return null}function TZe(e=__dirname){for(let t of[(0,Gp.join)(e,"enrollment-finisher.js"),(0,Gp.join)(e,"..","enrollment-finisher.js")])if((0,Kt.existsSync)(t))return t;return null}var xZe=(e,t)=>{if(t.JEST_WORKER_ID!==void 0||t.VITEST!==void 0||t.NODE_ENV==="test")return{spawned:!1,reason:"test_runner"};let r=TZe();if(!r)return{spawned:!1,reason:"finisher_entry_missing"};let n=(0,VA.spawn)(process.execPath,[r,...e],{detached:!0,stdio:"ignore",env:t,windowsHide:!0});return n.on("error",i=>ne.warn("agent:enrollment_finisher_spawn_failed",{errorName:i.name})),n.unref(),{spawned:!0}},v3={spawn:xZe,sleep:e=>new Promise(t=>setTimeout(t,e)),now:()=>Date.now(),processStart:AZe};var OZe={setup:Rse,readPending:Ei,now:()=>v3.now(),pid:process.pid,deadlineMs:jse,approvalFinished:Fy},kse=e=>e instanceof Error?e.message:String(e);function RZe(e,t){let r=t.after&&w3(t.after.challenge)===t.ref;if(e.leg==="held"){let i=t.after;return r&&i!==null&&i.binding?.agentId===e.agentId&&t.approvalFinished(i)?{state:"connected",leg:"held",agentId:e.agentId,nextAction:e.nextAction,...e.walletKey?{walletKey:e.walletKey}:{},tap:e.tap.state,...e.tap.state==="awaiting_owner"?{tapUrl:e.tap.url,tapFingerprint:e.tap.fingerprint}:{},...e.tap.state==="failed"?{tapError:kse(e.tap.error)}:{},card:e.card.state,...e.card.state==="awaiting_owner"?{cardUrl:e.card.url}:{},...e.card.state==="failed"?{cardError:kse(e.card.error)}:{}}:{state:"failed",code:"setup_not_picked_up",reason:`This computer answered with agent ${e.agentId}, which it already held, instead of picking up this setup's approval.`}}if(e.leg==="signin")return{state:"failed",code:"session_required",reason:"This computer is signed out."};if(e.leg==="unfinished_expired"||e.leg==="unreadable_keys")return{state:"failed",agentId:e.agentId,code:e.leg,reason:e.nextAction};let n=e.result;if(n.status==="connected"){let i=t.after?.binding?.agentId;return!r||i!==void 0&&i!==n.agentId?{state:"stopped",reason:"The setup request changed."}:{state:"connected",leg:"enroll",agentId:n.agentId,walletKey:n.walletKey,tap:n.tap,...n.tapError?{tapError:n.tapError}:{},nextAction:e.nextAction}}return n.status==="awaiting_owner_enrollment"?{state:"expired",reason:n.lastPickupFailure?`Visa was unavailable while waiting (${n.lastPickupFailure}).`:"The owner did not approve within the setup window."}:{state:"expired",agentId:n.agentId,reason:n.status}}async function Bse(e,t=OZe){let r=e.env??process.env,n=PZe(r,t.now(),t.pid);if(!n)return ne.info("agent:enrollment_finisher_already_running",{ref:e.ref}),"already_running";let i=t.now(),o,s;try{let u=null;try{u=t.readPending(r)}catch{u=null}if(!u||w3(u.challenge)!==e.ref)o={state:"stopped",reason:"The setup request changed."};else if(t.now()-u.createdAt>=Lc&&!u.binding)o={state:"expired",reason:"The setup request expired before it was approved."};else{Cse(e.ref,{state:"finishing",pid:t.pid},t.now(),r,{keepOtherRef:!0}),ne.info("agent:enrollment_finisher_start",{ref:e.ref,pid:t.pid,phase:u.binding?"device":"owner_approval"});let d=new Promise(h=>{s=setTimeout(()=>h({state:"expired",reason:"The background setup reached its time limit."}),t.deadlineMs),s.unref?.()}),l=u.webStartKey,m=t.approvalFinished??Fy,p=t.setup({...l!==void 0?{webStartKey:l}:{},wait:!0,attempts:EZe,tapWait:!1,dailyLimitCents:e.dailyLimitCents,perTransactionLimitCents:e.perTransactionLimitCents,...e.app!==void 0?{app:e.app}:{},signIn:async()=>({done:!1,pending:null})}).then(h=>{let y;try{y=t.readPending(r)}catch{y=null}return RZe(h,{ref:e.ref,after:y,approvalFinished:b=>m(b,r)})});o=await Promise.race([p,d])}}catch(u){o={state:"failed",code:tl(u).code,reason:u instanceof Error?u.message:String(u)}}finally{s&&clearTimeout(s)}let a=!n.held();try{a||Cse(e.ref,{...o,pid:t.pid},t.now(),r,{keepOtherRef:!0})}finally{n()}return a&&ne.info("agent:enrollment_finisher_superseded_exit",{ref:e.ref,outcome:o.state}),(o.state==="connected"?ne.info:ne.warn)("agent:enrollment_finisher_exit",{ref:e.ref,outcome:o.state,...o.agentId?{agentId:o.agentId}:{},...o.code?{code:o.code}:{},...o.walletKey?{walletKey:o.walletKey}:{},...o.nextAction?{nextAction:o.nextAction}:{},...o.leg?{leg:o.leg}:{},durationMs:t.now()-i}),o.state}function CZe(e,t,r=Ei,n=bZe){let i=!1,o=()=>{if(!i)try{let a=r(t);a&&a.binding&&w3(a.challenge)===e&&(i=!0)}catch{}};o();let s=setInterval(o,n);return s.unref?.(),{safeToExit:()=>(o(),!i),dispose:()=>clearInterval(s)}}function Use(e){let t=CZe(e.ref,e.env,e.readPending),r=e.on??((i,o)=>process.on(i,o)),n=!1;return r("SIGTERM",()=>{n||(n=!0,t.safeToExit()?(ne.info("agent:enrollment_finisher_signal_exit",{ref:e.ref}),e.exit(143)):ne.info("agent:enrollment_finisher_signal_deferred",{ref:e.ref,reason:"device_legs"}))}),{stopRequested:()=>n,dispose:t.dispose}}function Hse(e){let t=s=>{let a=e.indexOf(s);return a>=0?e[a+1]:void 0},r=t("--ref"),n=Number(t("--daily-cents")),i=Number(t("--per-transaction-cents"));if(!r||!/^enr_[A-Za-z0-9_-]{16}$/.test(r))throw new Error("finisher_ref_invalid");if(!Number.isSafeInteger(n)||n<=0||!Number.isSafeInteger(i)||i<=0)throw new Error("finisher_limits_invalid");let o=t("--app");return{ref:r,dailyLimitCents:n,perTransactionLimitCents:i,app:o??null}}function S3(e){lB().finally(()=>process.exit(e))}async function NZe(){let e;try{e=Hse(process.argv.slice(2))}catch(r){return ne.warn("agent:enrollment_finisher_bad_args",{reason:r instanceof Error?r.message:"invalid"}),2}let t=Use({ref:e.ref,exit:S3});try{let r=await Bse(e);return t.stopRequested()?143:r==="connected"||r==="already_running"?0:1}finally{t.dispose()}}NZe().then(S3,e=>{ne.error("agent:enrollment_finisher_crashed",{errorName:e instanceof Error?e.name:typeof e}),S3(1)});
108
+ /*! Bundled license information:
109
+
110
+ @noble/ed25519/index.js:
111
+ (*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
112
+ */
113
+ /*! Bundled license information:
114
+
115
+ @noble/hashes/utils.js:
116
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
117
+
118
+ @noble/curves/abstract/utils.js:
119
+ @noble/curves/abstract/modular.js:
120
+ @noble/curves/abstract/curve.js:
121
+ @noble/curves/abstract/weierstrass.js:
122
+ @noble/curves/_shortw_utils.js:
123
+ @noble/curves/secp256k1.js:
124
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
125
+ */