mppx 0.22.0 → 0.22.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/dist/cli/account.d.ts +2 -1
- package/dist/cli/account.js +22 -11
- package/dist/cli/cli.js +18 -18
- package/dist/cli/plugins/index.js +12 -12
- package/dist/extensions/identity/attestation/client/index.js +1 -0
- package/dist/extensions/identity/attestation/server/index.js +1 -0
- package/dist/extensions/identity/email-otp/server/index.js +1 -0
- package/dist/extensions/identity/erc8004/client/index.js +1 -0
- package/dist/extensions/identity/erc8004/server/index.js +3 -1
- package/dist/extensions/identity/link/server/index.js +1 -0
- package/dist/extensions/identity/poppy/server/index.js +1 -0
- package/dist/extensions/identity/tempo/client/index.js +1 -0
- package/dist/extensions/identity/tempo/server/index.js +7 -1
- package/dist/extensions/identity/world/server/index.js +1 -0
- package/dist/identity/Headers.d.ts +3 -2
- package/dist/identity/Headers.js +3 -2
- package/dist/identity/Server.d.ts +8 -0
- package/dist/identity/Server.js +18 -0
- package/dist/identity/Types.d.ts +16 -2
- package/dist/internal/version.d.ts +2 -2
- package/dist/internal/version.js +1 -1
- package/dist/proxy/Proxy.js +59 -46
- package/dist/proxy/internal/Headers.d.ts +9 -2
- package/dist/proxy/internal/Headers.js +16 -3
- package/dist/server/Mppx.d.ts +2 -0
- package/dist/server/Mppx.js +1 -0
- package/dist/tempo/client/Charge.js +19 -0
- package/dist/tempo/server/Charge.d.ts +7 -0
- package/dist/tempo/server/Charge.js +100 -12
- package/dist/tempo/server/internal/html.gen.js +1 -1
- package/package.json +1 -1
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
import{createClient as e,createTransport as t,custom as n,decodeErrorResult as r,encodeFunctionData as i,erc20Abi as a,formatUnits as o,getAbiItem as s,getAddress as c,hashTypedData as l,http as u,isAddress as d,isAddressEqual as f,keccak256 as p,parseAbi as m,parseEventLogs as h,parseUnits as g}from"viem";import{call as _,getBlockNumber as v,getLogs as y,prepareTransactionRequest as b,readContract as x,sendCallsSync as S,sendRawTransactionSync as C,sendTransactionSync as w,signTransaction as ee,signTypedData as T,waitForTransactionReceipt as te}from"viem/actions";import*as ne from"viem/chains";import{tempo as re}from"viem/chains";import{AbiParameters as E,Base64 as D,Bytes as O,Hash as k,Hex as A,Json as j}from"ox";import*as M from"zod/mini";import*as N from"node:child_process";import*as P from"node:fs";import*as F from"node:os";import*as I from"node:path";import{z as L}from"zod";import"node:readline";import{tempo as R,tempoModerato as z}from"viem/tempo/chains";import{ousd as ie,pathusd as ae,usdce as oe}from"viem/tokens";import{Abis as B,Account as se,Actions as V,Addresses as ce,TokenId as le,Transaction as ue,withFeePayer as de}from"viem/tempo";import{parseAccount as fe,privateKeyToAccount as pe}from"viem/accounts";import{AccountConfig as me,Channel as he,KeyAuthorization as ge,SignatureEnvelope as H,TempoAddress as _e,TxEnvelopeTempo as ve}from"ox/tempo";var ye=Object.defineProperty,be=Object.getOwnPropertyDescriptor,xe=Object.getOwnPropertyNames,Se=Object.prototype.hasOwnProperty,Ce=(e,t)=>{let n={};for(var r in e)ye(n,r,{get:e[r],enumerable:!0});return t||ye(n,Symbol.toStringTag,{value:`Module`}),n},we=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=xe(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Se.call(e,s)&&s!==n&&ye(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=be(t,s))||r.enumerable});return e},Te=(e,t,n)=>(we(e,t,`default`),n&&we(n,t,`default`));function Ee(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function De(e,t){let{chainId:n,decimals:r}=t;if(typeof e==`string`)return{address:e,chainId:n,decimals:r};if(Ee(e))return e.addresses[n]?e(n):void 0;if(e.chainId===n)return e}function Oe(e,t,n={}){let{chainId:r,decimals:i}=n,a=e=>e.toLowerCase()===t.toLowerCase();for(let t of e){if(typeof t==`string`){if(a(t))return{currency:t,decimals:i};continue}if((r===void 0?Ee(t)?Object.keys(t.addresses).map(e=>De(t,{chainId:Number(e)})):[t]:[De(t,{chainId:r})]).some(e=>e&&a(e.address)))return{currency:t,decimals:t.decimals}}}const ke=Symbol(`mppx.x402.asset`);function Ae(e){return{[ke]:!0,address:e.address,chainId:We(e.network),decimals:e.decimals,network:e.network,transfer:e.transfer}}function je(e,t){let n=e(t.chainId);return Ae({address:n.address,decimals:n.decimals,network:Ue(t.chainId),transfer:Ge(t.transfer,n)})}const Me={USDC:Ae({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},Ne={USDC:Ae({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},Pe={USDC:Ae({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:Ae({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},Fe={USDC:Ae({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},Ie=[Me,Ne,Pe,Fe].flatMap(e=>Object.values(e));function Le(e,t){let n=e.toLowerCase();return Ie.find(e=>e.network===t&&e.address.toLowerCase()===n)}function Re(e){return typeof e!=`object`||!e?!1:e[ke]===!0}const ze=Ee;function Be(e){return typeof e==`string`}function Ve(e,t){if(Re(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(typeof e==`string`)return{address:e};let n=De(e,{chainId:We(t)});if(n)return{address:n.address,decimals:n.decimals,name:n.name}}function He(e,t,n){let r=Ve(e,n);return r?c(r.address)===c(t):!1}function Ue(e){return`eip155:${e}`}function We(e){return Number(e.slice(7))}function Ge(e,t){if(e.type!==`eip3009`)return e;if(e.name)return{...e,name:e.name};if(!t.name)throw Error(`EIP-3009 token assets require a token name.`);return{...e,name:t.name}}var Ke=Ce({base:()=>Me,baseSepolia:()=>Ne,celo:()=>Pe,celoSepolia:()=>Fe,define:()=>Ae,fromToken:()=>je,isAsset:()=>Re,isRawAddress:()=>Be,isToken:()=>ze,lookup:()=>Le,matches:()=>He,resolve:()=>Ve,toChainId:()=>We,toNetwork:()=>Ue}),qe=Ce({base:()=>Je,baseSepolia:()=>Ye,celo:()=>Xe,celoSepolia:()=>Ze});const Je=8453,Ye=84532,Xe=42220,Ze=11142220,Qe=new WeakMap,$e=new WeakMap,et=new WeakMap;function tt(e,t){return Qe.set(e,t),e}function nt(e){return Qe.get(e)}function rt(e,t){$e.set(e,t)}function it(e){return $e.get(e)}function at(e,t){t===void 0||t===e?et.delete(e):et.set(e,t)}function ot(e){return et.get(e)}const U={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},st={payment:`Payment`},ct={evm:`evm`,stripe:`stripe`,tempo:`tempo`},lt={charge:`charge`,session:`session`,subscription:`subscription`},ut={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},dt={v1:`v1`,v2:`v2`};function ft(e,t){if(!(!e||typeof e!=`object`))return e[t]}function pt(e,t){return t?`${e} Add funds at ${t}`:e}var mt=class extends Error{details;status=402;hint;fundingUrl;constructor(e,t={}){super(e),this.details=t.details,this.fundingUrl=t.fundingUrl,t.cause!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t.cause,writable:!0})}toProblemDetails(e){return{type:this.type,title:this.title,status:this.status,detail:this.message,...this.details&&Object.keys(this.details).length>0&&{details:this.details},...this.hint&&{hint:this.hint},...this.fundingUrl&&{fundingUrl:this.fundingUrl},...e&&{challengeId:e}}}},ht=class extends mt{name=`InvalidChallengeError`;title=`Invalid Challenge`;status=402;type=`https://paymentauth.org/problems/invalid-challenge`;constructor(e={}){let{id:t,reason:n}=e,r=t?` "${t}"`:``,i=n?`: ${n}`:``;super(`Challenge${r} is invalid${i}.`)}},W=class extends mt{name=`VerificationFailedError`;title=`Verification Failed`;type=`https://paymentauth.org/problems/verification-failed`;constructor(e={}){let{details:t,fundingUrl:n,reason:r}=e;super(pt(r?`Payment verification failed: ${r}.`:`Payment verification failed.`,n),{details:t,fundingUrl:n})}},gt=class extends mt{name=`PaymentExpiredError`;title=`Payment Expired`;type=`https://paymentauth.org/problems/payment-expired`;constructor(e={}){let{expires:t}=e;super(t?`Payment expired at ${t}.`:`Payment has expired.`)}},_t=class extends mt{name=`PaymentOutcomeUnknownError`;title=`Payment Outcome Unknown`;type=`https://paymentauth.org/problems/payment-outcome-unknown`;challenge;credential;transactionHash;constructor(e){let{cause:t,challenge:n,credential:r,transactionHash:i}=e;super(`Payment outcome is unknown after sending a credential for challenge "${n.id}". Do not blindly retry.`,{cause:t}),this.challenge=n,this.credential=r,this.transactionHash=i}},vt=class extends Error{name=`BroadcastOutcomeUnknownError`;transactionHash;validBefore;constructor(e){let{cause:t,transactionHash:n,validBefore:r}=e;super(`Broadcast outcome is unknown for transaction ${n}. Look up its receipt before retrying.`),this.transactionHash=n,this.validBefore=r,t!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t,writable:!0})}},yt=class extends Error{name=`LegacyUnicodeEscapedChallengeError`;constructor(){super(`Legacy unicode-escaped challenge: the server escaped a bound parameter as \\uXXXX; upgrade the server.`)}},bt=class extends Error{name=`ConfigurableVouchersUnsupportedError`;signer;constructor(e){let{signer:t}=e;super(`Configurable account ${t} signs vouchers with TIP-1166 configurable account signatures, but the session challenge does not advertise \`configurableVouchers\`, so the channel was not opened.`),this.signer=t}},xt=class extends Error{name=`SignerConfigChangedError`;channelId;reason;signer;constructor(e){let{cause:t,channelId:n,reason:r,signer:i}=e;super(`Signer ${i} of channel ${n} changed its account config since the channel opened, so the top-up was not signed. Close the channel and open a new one.`),this.channelId=n,this.reason=r,this.signer=i,t!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t,writable:!0})}},St=class extends Error{name=`SpendingLimitExceededError`;accessKey;account;constructor(e){let{accessKey:t,account:n,cause:r}=e;super(`Access key spending limit exceeded: ${t?`key ${t} of `:``}account ${n} cannot pay this amount, so the payment was not signed.`),this.accessKey=t,this.account=n,r!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:r,writable:!0})}},Ct=class extends Error{name=`ZoneSettlementPendingError`;challengeId;senderTag;senderTags;zoneId;constructor(e){let{cause:t,challengeId:n,zoneId:r}=e,i=e.senderTags??(e.senderTag?[e.senderTag]:[]),a=i.length===1?i[0]:void 0,o=a??(i.length?`with sender tag ${i.join(` or `)}`:void 0);super(`Zone ${r} withdrawal ${o?`${o} `:``}for challenge "${n}" has not settled on Tempo yet. Retry the challenge to resume waiting instead of paying again.`),this.challengeId=n,this.senderTag=a,this.senderTags=i,this.zoneId=r,t!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t,writable:!0})}},wt=class extends Error{name=`PaymentLimitExceededError`;limit;reason;constructor(e){let{limit:t,reason:n}=e,r=t===`budget`?`the remaining budget`:`maxPayment`;super(n===`amount`?`Payment exceeds ${r}, so no credential was created.`:n===`credential`?`Credential cannot be checked against ${r}: it is unreadable or pays no single challenge the response offered, so it was not used.`:n===`intent`?`Payment intent cannot be checked against ${r}: spending options accept only charges, so no credential was created.`:`Payment asset cannot be checked against ${r}: no limit names it, or the client does not configure its currency and decimals. No credential was created.`),this.limit=t,this.reason=n}},Tt=class extends mt{name=`InsufficientBalanceError`;title=`Insufficient Balance`;status=402;type=`https://paymentauth.org/problems/session/insufficient-balance`;constructor(e={}){let{cause:t,fundingUrl:n,reason:r}=e;super(pt(r?`Insufficient balance: ${r}.`:`Insufficient balance.`,n),{cause:t,fundingUrl:n})}};function Et(e){let t=D.toString(e);return JSON.parse(t)}function G(e){let t=j.canonicalize(e);return D.fromString(t,{pad:!1,url:!0})}var K=Ce({address:()=>J,amount:()=>q,datetime:()=>Ot,datetimeInput:()=>kt,hash:()=>Mt,period:()=>Nt,signature:()=>Y,toDate:()=>At,toDatetimeString:()=>jt,unwrapOptional:()=>Pt});import*as Dt from"zod/mini";Te(K,Dt);function q(){return M.string().check(M.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function Ot(){return M.string().check(M.regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,`Invalid ISO 8601 datetime`))}function kt(e=`Invalid ISO 8601 datetime`){return M.pipe(M.union([Ot(),M.custom(e=>e instanceof Date)]),M.transform(At)).check(M.refine(e=>Number.isFinite(e.getTime()),e))}function At(e){return e instanceof Date?e:new Date(e)}function jt(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function J(){return M.string().check(M.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function Mt(){return M.string().check(M.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function Nt(){return M.string().check(M.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function Y(){return M.string().check(M.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function Pt(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}const Ft=Symbol(`mppx.Challenge.legacyUnicodeEscape`),It=new Set([`digest`,`expires`,`header`,`intent`,`method`,`opaque`,`realm`,`request`]),Lt=`Unsupported credential header: challenges may only select Payment-Authorization.`;var Rt=class extends Error{name=`UnsupportedCredentialHeaderError`;constructor(){super(Lt)}};const zt=K.object({description:K.optional(K.string()),digest:K.optional(K.string().check(K.regex(/^sha-256=/,`Invalid digest format`))),expires:K.optional(Ot()),header:K.optional(K.string().check(K.refine(fn,Lt))),id:K.string().check(K.minLength(1)),intent:K.string(),method:K.string(),meta:K.optional(K.record(K.string(),K.string())),opaque:K.optional(K.string()),realm:K.string(),request:K.record(K.string(),K.unknown())}),Bt=K.extend(zt,{header:K.optional(K.string())});function Vt(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=pn(o),f=e.expires?jt(e.expires):void 0,p=e.opaque??(i===void 0?void 0:G(i)),m=u?hn({...e,expires:f,header:d,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return zt.parse({id:m,realm:c,method:a,intent:s,request:l,...n&&{description:n},...r&&{digest:r},...f&&{expires:f},...d!==void 0&&{header:d},...i!==void 0&&{meta:i},...p!==void 0&&{opaque:p}})}const Ht=/^[a-z]+$/;var Ut=class extends Error{name=`InvalidMethodError`;constructor(e){super(`Invalid method: "${e}". Must be lowercase letters a-z per spec.`)}};function Wt(e){if(!Ht.test(e))throw new Ut(e)}function Gt(e,t){let n=Jt(e);if(!n)throw Error(`Missing Payment scheme.`);let r=new Set,{request:i,opaque:a,header:o,...s}=Yt(n,r);if(!i)throw Error(`Missing request parameter.`);if(i.length>16384)throw Error(`Request parameter too large.`);if(s.method!==void 0&&Wt(s.method),o!==void 0&&!fn(o))throw new Rt;let c=Vt({...s,request:Et(i),...a&&{opaque:a}},t),l=o===void 0?c:{...c,header:o};return[...r].some(e=>It.has(e))&&(l[Ft]=!0),l}function Kt(e){return!!(e&&typeof e==`object`&&e[Ft])}function qt(e){if(Kt(e))throw new yt}function Jt(e){let t=st.payment,[n]=tn(e,t);if(n===void 0)return null;let r=n+t.length;for(;r<e.length&&/\s/.test(e[r]??``);)r++;return e.slice(r)}function Yt(e,t){let n=Object.create(null),r=0;for(;r<e.length;){for(;r<e.length&&/[\s,]/.test(e[r]??``);)r++;if(r>=e.length)break;let i=r;for(;r<e.length&&/[A-Za-z0-9_-]/.test(e[r]??``);)r++;let a=e.slice(i,r).toLowerCase();if(!a)throw Error(`Malformed auth-param.`);for(;r<e.length&&/\s/.test(e[r]??``);)r++;if(e[r]!==`=`)break;for(r++;r<e.length&&/\s/.test(e[r]??``);)r++;let[o,s,c]=Xt(e,r);for(r=s,c&&t?.add(a);r<e.length&&/\s/.test(e[r]??``);)r++;if(r<e.length&&e[r]!==`,`)throw Error(`Malformed auth-param.`);if(a in n)throw Error(`Duplicate parameter: ${a}`);n[a]=o}return n}function Xt(e,t){if(e[t]===`"`)return Qt(e,t+1);let n=t;for(;n<e.length&&Zt.test(e[n]??``);)n++;if(n===t)throw Error(`Malformed auth-param.`);return[e.slice(t,n),n]}const Zt=/[!#$%&'*+\-.^_`|~0-9A-Za-z]/;function Qt(e,t){let n=t,r=!1,i=!1,a=t,o;for(;n<e.length;){let s=e[n];if(n++,r){s===`u`&&/^[0-9a-fA-F]{4}/.test(e.slice(n,n+4))&&(i=!0),o??=[],o.push(s),a=n,r=!1;continue}if(s===`\\`){o??=[],o.push(e.slice(a,n-1)),a=n,r=!0;continue}if(s===`"`)return[o?[...o,e.slice(a,n-1)].join(``):e.slice(t,n-1),n,i]}throw Error(`Unterminated quoted-string.`)}function $t(e,t,n){if(e.slice(t,t+n.length).toLowerCase()!==n.toLowerCase())return!1;let r=e[t+n.length];return!!(r&&/\s/.test(r))}function en(e){return tn(e,st.payment).length>0||e.split(`,`).some(e=>e.trim().toLowerCase()===st.payment.toLowerCase())}function tn(e,t){let n=[],r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(r){i?i=!1:o===`\\`?i=!0:o===`"`&&(r=!1);continue}if(o===`"`){r=!0;continue}if(!$t(e,a,t))continue;let s=a-1;for(;s>=0&&/\s/.test(e[s]??``);)s--;s>=0&&e[s]!==`,`||n.push(a)}return n}function nn(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return rn(e.headers,t)}function rn(e,t){let n=e.get(U.wwwAuthenticate);if(!n)throw Error(`Missing ${U.wwwAuthenticate} header.`);return an(n,t)}function an(e,t){let n=cn(e);if(n.length===0)throw Error(`No Payment schemes found.`);return n.flatMap(e=>{try{return[Gt(e,t)]}catch(e){if(e instanceof Rt||e instanceof Ut)return[];throw e}})}function on(e){return e?cn(e).filter(e=>{try{return Gt(e),!1}catch(e){return e instanceof Rt}}).length:0}function sn(e,t){return t<=0?e:t===1?`${e}. Skipped 1 challenge that selects a credential header other than Payment-Authorization`:`${e}. Skipped ${t} challenges that select a credential header other than Payment-Authorization`}function cn(e){let t=tn(e,st.payment);return t.map((n,r)=>{let i=r+1<t.length?t[r+1]:e.length;return e.slice(n,i).replace(/,\s*$/,``)})}function ln(e){let t=[e.realm,e.method,e.intent,G(e.request),e.expires??``,e.digest??``],n=mn(e.header);return n!==void 0&&t.push(n),t.push(e.opaque??(e.meta?G(e.meta):``)),t.join(`|`)}function un(e){let{header:t}=e;return t===void 0?U.authorization:fn(t)?U.paymentAuthorization:t}function dn(e){if(typeof e!=`object`||!e||!(`header`in e))return!1;let{header:t}=e;return t!==void 0&&!(typeof t==`string`&&fn(t))}function fn(e){return/^payment-authorization$/i.test(e)}function pn(e){return mn(e)===void 0?void 0:U.paymentAuthorization}function mn(e){if(e!==void 0&&!/^authorization$/i.test(e)){if(fn(e))return e;throw new Rt}}function hn(e,t){let n=ln(e),r=O.fromString(t.secretKey),i=O.fromString(n),a=k.hmac256(r,i,{as:`Bytes`});return D.fromBytes(a,{url:!0,pad:!1})}const gn=65536;var _n=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},vn=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}};function yn(e){if(e.length>gn)throw new vn;let t=e.match(RegExp(`^${st.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new _n;try{let e=D.toString(t[1]),n=JSON.parse(e);if(!xn(n.payload))throw Error(`Invalid payload.`);if(n.source!==void 0&&typeof n.source!=`string`)throw Error(`Invalid source.`);let{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=bn(r);return{challenge:zt.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:Et(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new vn}}function bn(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!Sn(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:G(e)}}function xn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Sn(e){return xn(e)?Object.values(e).every(e=>typeof e==`string`):!1}function Cn(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function wn(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:G(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:G(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=D.fromString(s,{pad:!1,url:!0});return`${st.payment} ${c}`}function Tn(e){return e.length>gn?null:e.split(`,`).map(e=>e.trim()).find(e=>RegExp(`^${st.payment}\\s+`,`i`).test(e))??null}const En=Symbol.for(`mppx.x402.challenge`);function Dn(e){return Object.defineProperty(e,En,{value:!0}),e}function On(e){return!!e?.[En]}function kn(e,t){if(!e)throw new ht({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new ht({...t&&{id:t},reason:`malformed expires timestamp`});if(Date.parse(e)<=Date.now())throw new gt({expires:e})}function An(e){let{_mpp_nonce:t,_mppx_nonce:n,_mppx_identity:r,_mppx_expiry_grace:i,...a}=e??{};return Object.keys(a).length?a:void 0}function jn(e){return e}function Mn(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,async createCredential(e){return qt(e.challenge),i.call(this,e)}}}function Nn(e){return{encode(t){return D.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(D.toString(t)))}catch{throw new Pn}}}}var Pn=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}};const Fn=[`exact`],In=`PAYMENT-REQUIRED`,Ln=`PAYMENT-SIGNATURE`,Rn=`PAYMENT-RESPONSE`,zn=K.string().check(K.minLength(1)),Bn=K.number().check(K.refine(e=>e>0,`Must be positive`)),Vn=K.string().check(K.regex(/^\d+$/,`Invalid atomic amount`)),Hn=J(),Un=K.string().check(K.regex(RegExp(`^eip155:\\d+$`),`Invalid EVM CAIP-2 network`)),Wn=K.object({description:K.optional(K.string()),iconUrl:K.optional(K.string()),mimeType:K.optional(K.string()),serviceName:K.optional(K.string()),tags:K.optional(K.array(K.string())),url:zn});K.discriminatedUnion(`type`,[K.object({name:zn,type:K.literal(`eip3009`),version:zn}),K.object({name:K.optional(K.string()),type:K.literal(`permit2`),version:K.optional(K.string())})]);const Gn=K.object({amount:Vn,asset:zn,extra:K.optional(K.record(K.string(),K.unknown())),maxTimeoutSeconds:Bn,network:Un,payTo:zn,scheme:K.enum(Fn)}),Kn=K.looseObject({info:K.record(K.string(),K.unknown()),schema:K.record(K.string(),K.unknown())}),qn=K.record(K.string(),Kn),Jn=K.object({accepts:K.array(Gn).check(K.minLength(1)),error:K.optional(K.string()),extensions:K.optional(qn),resource:Wn,x402Version:K.literal(2)}),Yn=K.object({authorization:K.object({from:Hn,nonce:Mt(),to:Hn,validAfter:Vn,validBefore:Vn,value:Vn}),signature:Y()}),Xn=K.object({permit2Authorization:K.object({deadline:Vn,from:Hn,nonce:Vn,permitted:K.object({amount:Vn,token:Hn}),spender:Hn,witness:K.object({to:Hn,validAfter:Vn})}),signature:Y()}),Zn=K.union([Yn,Xn]),Qn=K.object({accepted:Gn,extensions:K.optional(qn),payload:Zn,resource:K.optional(Wn),x402Version:K.literal(2)});K.object({extensions:K.optional(K.record(K.string(),K.unknown())),extra:K.optional(K.record(K.string(),K.unknown())),invalidMessage:K.optional(K.string()),invalidReason:K.optional(K.string()),isValid:K.boolean(),payer:K.optional(K.string())});const $n=K.object({amount:K.optional(Vn),errorMessage:K.optional(K.string()),errorReason:K.optional(K.string()),extensions:K.optional(K.record(K.string(),K.unknown())),extra:K.optional(K.record(K.string(),K.unknown())),network:zn,payer:K.optional(K.string()),success:K.boolean(),transaction:K.string()}),er=K.object({extra:K.optional(K.record(K.string(),K.unknown())),network:zn,scheme:zn,x402Version:K.number()});K.object({extensions:K.optional(K.array(K.string())),kinds:K.array(er),signers:K.optional(K.record(K.string(),K.array(K.string())))});function tr(e){let{extensions:t,resource:n,...r}=e;return Gn.parse(r)}const nr=Nn(Jn),rr=Nn(Qn),ir=Nn($n);nr.encode,nr.decode;function ar(e){try{let t=JSON.parse(D.toString(e));return cr(t)}catch{throw new Pn}}const or=rr.encode,sr=rr.decode;ir.encode,ir.decode;const cr=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new Pn;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new Pn;let n=Wn.parse(t.resource),r=t.extensions===void 0?void 0:qn.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}};function lr(e){let t=[G(e.accepted),G(e.resource),G(e.extensions)].join(`|`);return k.sha256(O.fromString(t),{as:`Hex`})}async function ur(e){let t=e.context?.account??e.config.account;if(!t?.signTypedData)throw Error(`x402 exact requires a typed-data signer.`);let n=e.challenge.request,r=tr(n);if(mr(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?gr(n.extensions):n.extensions,a=r.extra?.assetTransferMethod??`eip3009`;if(a!==`eip3009`)throw Error(`x402 exact ${String(a)} signing is not implemented yet.`);let o=r.extra?.name,s=r.extra?.version;if(typeof o!=`string`||typeof s!=`string`)throw Error(`x402 exact EIP-3009 requires token name and version.`);let l=Math.floor(Date.now()/1e3),u={from:c(t.address),nonce:i?.mppx?lr({accepted:r,extensions:i,resource:n.resource}):vr(),to:c(r.payTo),validAfter:(l-600).toString(),validBefore:(l+r.maxTimeoutSeconds).toString(),value:r.amount},d=await t.signTypedData({domain:{chainId:pr(r.network),name:o,verifyingContract:c(r.asset),version:s},message:{...u,value:BigInt(u.value),validAfter:BigInt(u.validAfter),validBefore:BigInt(u.validBefore)},primaryType:`TransferWithAuthorization`,types:fr});return or({accepted:r,...i?{extensions:i}:{},payload:{authorization:u,signature:d},...n.resource?{resource:n.resource}:{},x402Version:2})}function dr(e){let t=e.challenge.request,n;try{n=tr(t),mr(e.config,n)}catch{return!1}if(!t.resource||(n.extra?.assetTransferMethod??`eip3009`)!==`eip3009`)return!1;let r=n.extra?.name,i=n.extra?.version;return typeof r==`string`&&typeof i==`string`}const fr={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function pr(e){return Number(e.slice(7))}function mr(e,t){let n=pr(t.network);if(e.networks&&!e.networks.includes(n))throw Error(`x402 exact chain ID is not allowed: ${n}.`);let r=e.currencies??e.assets;if(r?.some(e=>Be(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=c(t.asset);if(!r.some(n=>He(n,e,t.network)))throw Error(`x402 exact currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`x402 exact amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=hr(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>g(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function hr(e,t){let n=e.currencies??e.assets,r=c(t.asset),i=n?.find(e=>He(e,r,t.network)),a=i?Ve(i,t.network):void 0;return a?.decimals===void 0?e.decimals===void 0?Le(r,t.network)?.decimals:e.decimals:a.decimals}function gr(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:_r()}}}:e}function _r(){return yr().slice(2)}function vr(){return yr()}function yr(){let e=globalThis.crypto;if(!e?.getRandomValues)throw Error(`x402 exact requires crypto randomness.`);let t=e.getRandomValues(new Uint8Array(32));return`0x${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}const br=[`authorization`],xr=K.string().check(K.regex(/^\d+$/,`Invalid atomic amount`));K.object({name:K.string().check(K.minLength(1)),version:K.string().check(K.minLength(1))});const Sr=K.object({chainId:K.number(),credentialTypes:K.optional(K.array(K.enum(br)).check(K.minLength(1))),decimals:K.optional(K.number()),permit2Address:K.optional(J()),splits:K.optional(K.array(K.object({amount:xr,recipient:J()})))});K.object({amount:xr,currency:J(),description:K.optional(K.string()),externalId:K.optional(K.string()),methodDetails:Sr,recipient:J()});const Cr=K.object({amount:q(),chainId:K.number(),currency:J(),credentialTypes:K.optional(K.array(K.enum(br)).check(K.minLength(1))),decimals:K.number(),description:K.optional(K.string()),externalId:K.optional(K.string()),permit2Address:K.optional(J()),recipient:J(),splits:K.optional(K.array(K.object({amount:xr,recipient:J()})))}),wr=K.object({from:J(),nonce:Mt(),signature:Y(),to:J(),type:K.literal(`authorization`),validAfter:xr,validBefore:xr,value:xr}),Tr={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function Er(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function Dr(e){return k.keccak256(O.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function Or(e){return`eip155:${e}`}function kr(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const Ar=jn({name:`evm`,intent:`charge`,schema:{credential:{payload:wr},request:K.pipe(Cr,K.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:o,splits:s,...l})=>({...l,amount:g(e,i).toString(),currency:c(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:c(a)}:{},...s?{splits:s}:{}},recipient:c(o)})))}});function jr(e){return tt(Mn(Ar,{canHandleChallenge({challenge:t}){return!Mr(t)||dr({challenge:t,config:e})},context:K.object({account:K.optional(K.custom())}),async createCredential({challenge:t,context:n}){if(Mr(t))return ur({challenge:t,config:e,context:n});let r=n?.account??e.account;if(!r?.signTypedData)throw Error(`EVM authorization requires a typed-data signer.`);let i=t.request;Nr(e,i);let a=Fr(e,i),o=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return wn(Cn({challenge:t,payload:{from:c(r.address),nonce:Dr(t),signature:await r.signTypedData({domain:Er({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:c(r.address),nonce:Dr(t),to:c(i.recipient),validAfter:0n,validBefore:BigInt(o),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:Tr}),to:c(i.recipient),type:`authorization`,validAfter:`0`,validBefore:o,value:i.amount},source:kr({address:c(r.address),chainId:i.methodDetails.chainId})}))}}),{assert(t){Mr(t)||Nr(e,t.request)}})}function Mr(e){return On(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function Nr(e,t){if(Pr(e,t),!t.methodDetails.credentialTypes?.includes(`authorization`))throw Error(`EVM authorization is not accepted by this challenge.`);if(t.methodDetails.splits?.length)throw Error(`EVM authorization does not support payment splits.`)}function Pr(e,t){let n=t.methodDetails.chainId,r=Or(n);if(e.networks&&!e.networks.includes(n))throw Error(`EVM chain ID is not allowed: ${n}.`);let i=e.currencies??e.assets;if(i?.some(e=>Be(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=c(t.currency);if(!i.some(t=>He(t,e,r)))throw Error(`EVM currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`EVM charge amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=Ir(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>g(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function Fr(e,t){let n=e.currencies??e.assets,r=c(t.currency),i=Or(t.methodDetails.chainId),a=n?.find(e=>He(e,r,i)),o=a?Ve(a,i):void 0;if(o?.transfer?.type===`eip3009`)return{name:o.transfer.name,version:o.transfer.version};if(e.authorization)return e.authorization;let s=Le(r,i)?.transfer;if(s?.type===`eip3009`)return{name:s.name,version:s.version};throw Error(`EVM authorization requires token name and version.`)}function Ir(e,t){let n=e.currencies??e.assets,r=c(t.currency),i=Or(t.methodDetails.chainId),a=n?.find(e=>He(e,r,i)),o=a?Ve(a,i):void 0;return o?.decimals===void 0?e.decimals===void 0?Le(r,i)?.decimals:e.decimals:o.decimals}function Lr(e){return[Lr.charge(e)]}(function(e){e.charge=jr,e.assets=Ke,e.chains=qe})(Lr||={});var Rr=class extends Error{name=`Incur.BaseError`;shortMessage;details;constructor(e,t={}){let n=t.cause instanceof Error?t.cause.message:void 0,r=n?`${e}\n\nDetails: ${n}`:e;super(r,t.cause?{cause:t.cause}:void 0),this.shortMessage=e,this.details=n}walk(e){return Br(this,e)}},zr=class extends Rr{name=`Incur.IncurError`;code;hint;retryable;exitCode;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.code=e.code,this.hint=e.hint,this.retryable=e.retryable??!1,this.exitCode=e.exitCode}};function Br(e,t){if(t){let n=e?.cause;for(;n;){if(t(n))return n;n=n?.cause}return}let n=e;for(;n?.cause;)n=n.cause;return n}const X=(()=>{let e=process||{},t=e.argv||[],n=e.env||{},r=!(n.NO_COLOR||t.includes(`--no-color`))&&(!!n.FORCE_COLOR||t.includes(`--color`)||(e.stdout||{}).isTTY&&n.TERM!==`dumb`||!!n.CI),i=(e,t,n,r)=>{let i=``,a=0,o=r;do i+=e.substring(a,o)+n,a=o+t.length,o=e.indexOf(t,a);while(~o);return i+e.substring(a)},a=r?(e,t,n=e)=>r=>{let a=`${r}`,o=a.indexOf(t,e.length);return~o?e+i(a,t,n,o)+t:e+a+t}:()=>String;return{isColorSupported:r,reset:a(`\x1B[0m`,`\x1B[0m`),bold:a(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:a(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:a(`\x1B[3m`,`\x1B[23m`),underline:a(`\x1B[4m`,`\x1B[24m`),inverse:a(`\x1B[7m`,`\x1B[27m`),hidden:a(`\x1B[8m`,`\x1B[28m`),strikethrough:a(`\x1B[9m`,`\x1B[29m`),black:a(`\x1B[30m`,`\x1B[39m`),red:a(`\x1B[31m`,`\x1B[39m`),green:a(`\x1B[32m`,`\x1B[39m`),yellow:a(`\x1B[33m`,`\x1B[39m`),blue:a(`\x1B[34m`,`\x1B[39m`),magenta:a(`\x1B[35m`,`\x1B[39m`),cyan:a(`\x1B[36m`,`\x1B[39m`),white:a(`\x1B[37m`,`\x1B[39m`),gray:a(`\x1B[90m`,`\x1B[39m`),bgBlack:a(`\x1B[40m`,`\x1B[49m`),bgRed:a(`\x1B[41m`,`\x1B[49m`),bgGreen:a(`\x1B[42m`,`\x1B[49m`),bgYellow:a(`\x1B[43m`,`\x1B[49m`),bgBlue:a(`\x1B[44m`,`\x1B[49m`),bgMagenta:a(`\x1B[45m`,`\x1B[49m`),bgCyan:a(`\x1B[46m`,`\x1B[49m`),bgWhite:a(`\x1B[47m`,`\x1B[49m`),blackBright:a(`\x1B[90m`,`\x1B[39m`),redBright:a(`\x1B[91m`,`\x1B[39m`),greenBright:a(`\x1B[92m`,`\x1B[39m`),yellowBright:a(`\x1B[93m`,`\x1B[39m`),blueBright:a(`\x1B[94m`,`\x1B[39m`),magentaBright:a(`\x1B[95m`,`\x1B[39m`),cyanBright:a(`\x1B[96m`,`\x1B[39m`),whiteBright:a(`\x1B[97m`,`\x1B[39m`),bgBlackBright:a(`\x1B[100m`,`\x1B[49m`),bgRedBright:a(`\x1B[101m`,`\x1B[49m`),bgGreenBright:a(`\x1B[102m`,`\x1B[49m`),bgYellowBright:a(`\x1B[103m`,`\x1B[49m`),bgBlueBright:a(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:a(`\x1B[105m`,`\x1B[49m`),bgCyanBright:a(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:a(`\x1B[107m`,`\x1B[49m`),link(e,t,n){return r?`\x1b]8;;${e}\x07${n?t:X.underline(t)}\x1b]8;;\x07`:t}}})(),Z={mainnet:4217,testnet:42431},Vr={ousd:ie(Z.mainnet).address,usdc:c(oe(Z.mainnet).address),pathUsd:ae(Z.mainnet).address},Hr={[Z.mainnet]:Vr.usdc,[Z.testnet]:Vr.pathUsd},Ur=Object.freeze({[Z.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[Z.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})});Z.mainnet,Z.testnet;const Wr={[Z.mainnet]:`https://rpc.tempo.xyz`,[Z.testnet]:`https://rpc.moderato.tempo.xyz`};function Gr(e,t){return X.link(e,t)}function Kr(e){return e.startsWith(`tempo:`)}function qr(e,t,n=6,r){let[i,a]=(Number(e)/10**n).toString().split(`.`),o=i.replace(/\B(?=(\d{3})+(?!\d))/g,`_`),s=r?.explorerUrl&&r.token?X.dim(X.link(`${r.explorerUrl}/token/${r.token}`,t,!0)):X.dim(t);return`${a?`${o}.${a}`:o} ${s}`}const Jr={mainnet:Wr[Z.mainnet],testnet:Wr[Z.testnet]};function Yr(e,t={}){return e??(t.network?Jr[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}async function Xr(t={}){let n=Yr(t.rpcUrl,{network:t.network});if(!n)return R;let{getChainId:r}=await import(`viem/actions`),i=await r(e({transport:u(n)})),a=Object.values(await import(`viem/tempo/chains`)).filter(e=>typeof e==`object`&&!!e&&`id`in e&&e.id===i),o=a.find(e=>`serializers`in e&&e.serializers)??a[0];if(!o)throw Error(`Unknown chain ID ${i} from RPC ${n}`);return o}function Zr(e){return typeof e==`bigint`?e:e.amount}function Qr(e){return e.id!==R.id}async function $r(e,t,n,r={}){let{Actions:i}=await import(`viem/tempo`),[a,o]=await Promise.all([i.token.getBalance(e,{account:n,token:t}).then(Zr).catch(()=>0n),i.token.getMetadata(e,{token:t}).catch(e=>{if(r.requireDecimals)throw e;return{symbol:t}})]),s={"0x20c0000000000000000000000000000000000000":`PathUSD`,"0x20C000000000000000000000b9537d11c60E8b50":`USDC`}[t]??o.symbol,c=`decimals`in o&&typeof o.decimals==`number`?o.decimals:6;if(r.requireDecimals&&!(`decimals`in o&&typeof o.decimals==`number`))throw Error(`Token decimals are unavailable.`);return{balance:a,symbol:s,decimals:c,token:t}}function ei(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:1e4}function ti(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function ni(e){return new zr({code:`KEYCHAIN_UNAVAILABLE`,message:`Linux keyring requires secret-tool. Install libsecret-tools.`,hint:`On Debian/Ubuntu, run: sudo apt install libsecret-tools gnome-keyring dbus-x11`,exitCode:69,cause:e})}function ri(e){if(e&&ti(e,`secret-tool`))throw ni(e)}function ii(e,t){return new Promise(n=>{N.execFile(e,t,{timeout:ei()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function ai(){let e=I.join(process.env.XDG_CONFIG_HOME||I.join(F.homedir(),`.config`),`mppx`,`default`);return{get(){try{return P.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(t){P.mkdirSync(I.dirname(e),{recursive:!0}),P.writeFileSync(e,t,`utf-8`)},clear(){try{P.unlinkSync(e)}catch{}}}}function oi(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:ai().get())}function si(e=`main`){let t=`mppx`;return{async list(){let e=F.platform();if(e===`darwin`){let{stdout:e,error:n}=await ii(`security`,[`dump-keychain`]);if(n)return[];let r=[],i=e.split(`keychain:`);for(let e of i){let n=e.match(/"svce"<blob>="([^"]*)"/),i=e.match(/"acct"<blob>="([^"]*)"/);n?.[1]===t&&i?.[1]&&r.push(i[1])}return r}if(e===`linux`){let{stdout:e,stderr:n,error:r}=await ii(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(ri(r),r)return[];let i=`${e}\n${n}`,a=[],o=i.matchAll(/\baccount = (.+)/g);for(let e of o)e[1]&&a.push(e[1]);return a}throw Error(`Unsupported platform: ${e}`)},async get(){let n=F.platform();if(n===`darwin`){let{stdout:n,error:r}=await ii(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await ii(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return ri(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=F.platform();if(r===`darwin`){await ii(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await ii(`security`,[`add-generic-password`,`-s`,t,`-a`,e,`-w`,n]);if(r)throw r;return}if(r===`linux`){let r=N.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),ei());return r.stdin?.write(n),r.stdin?.end(),new Promise((e,t)=>{r.on(`close`,n=>{clearTimeout(i),n===0?e():t(Error(`secret-tool exited with code ${n}`))}),r.on(`error`,e=>{clearTimeout(i),t(ti(e,`secret-tool`)?ni(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=F.platform();if(n===`darwin`){await ii(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await ii(`secret-tool`,[`clear`,`service`,t,`account`,e]);ri(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function ci(e){let{privateKeyToAccount:t}=await import(`viem/accounts`),n=process.env.MPPX_PRIVATE_KEY?.trim();if(n)return{account:t(n),source:`environment`};let r=oi(e),i=await si(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function li(e){return(await ci(e)).account}function ui(e){return e}function di(){return ui({method:`evm`,supports:e=>e.method===`evm`&&!On(e),async setup({challenge:t,options:n}){let r=t.request,i=r.methodDetails,o=i?.chainId,s=o?fi(o):void 0,c=r.currency,l=await li(n.account),d=[...Object.values(Me),...Object.values(Ne),...Object.values(Pe),...Object.values(Fe)],f=c??``;if(s&&c)try{let t=e({chain:s,transport:u()}),n=await x(t,{address:c,abi:a,functionName:`symbol`});n&&(f=n)}catch{}return{tokenSymbol:f,tokenDecimals:i?.decimals??6,explorerUrl:s?.blockExplorers?.default?.url,methods:[...Lr({account:l,currencies:d})]}}})}function fi(e){return Object.values(ne).find(t=>t.id===e)}function pi(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`Decimals must be a non-negative integer.`);if(!/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e))throw TypeError(`Value \`${e}\` is not a valid decimal number.`);let n=e.startsWith(`-`),[r=`0`,i=``]=(n?e.slice(1):e).split(`.`),a=i.slice(0,t).padEnd(t,`0`),o=BigInt(`${r||`0`}${a}`);return i.length>t&&i[t]>=`5`&&(o+=1n),n?-o:o}const mi=K.object({customer:K.optional(K.string().check(K.minLength(1))),hooks:K.optional(K.object({inputs:K.object({tax:K.object({calculation:K.string().check(K.minLength(1))})})})),metadata:K.optional(K.record(K.string(),K.string())),receipt_email:K.optional(K.string().check(K.minLength(1)))}),hi=K.custom(e=>typeof e==`function`),gi=K.union([mi,hi]),_i=jn({name:`stripe`,intent:`charge`,schema:{credential:{payload:K.object({externalId:K.optional(K.string()),spt:K.string()})},request:K.pipe(K.object({amount:q(),currency:K.string(),decimals:K.number(),description:K.optional(K.string()),externalId:K.optional(K.string()),metadata:K.optional(K.record(K.string(),K.string())),networkId:K.string(),paymentIntentOptions:K.optional(gi),paymentMethodTypes:K.array(K.string()).check(K.minLength(1)),recipient:K.optional(K.string())}),K.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:pi(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});function vi(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return Mn(_i,{context:K.object({paymentMethod:K.optional(K.string())}),async createCredential({challenge:e,context:a}){let o=a?.paymentMethod??i;if(!o)throw Error(`paymentMethod is required (pass via context or parameters)`);let s=e.request.amount,c=e.request.currency,l=typeof e.request.externalId==`string`?e.request.externalId:void 0,u=e.request.methodDetails?.networkId;if(!u)throw Error(`networkId is required in challenge.methodDetails`);let d=e.request.methodDetails?.metadata;if(d?.externalId)throw Error(`methodDetails.metadata.externalId is reserved; use credential externalId instead`);let f=e.expires?Math.floor(new Date(e.expires).getTime()/1e3):Math.floor(Date.now()/1e3)+3600,p=await n({amount:s,challenge:e,client:t,currency:c,expiresAt:f,metadata:d,networkId:u,paymentMethod:o}),m=l??r;return wn({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function yi(e){return[vi(e)]}(function(e){e.charge=vi})(yi||={});function bi(){return ui({method:`stripe`,supports(e){return e.method===`stripe`&&e.intent===`charge`},async setup({challenge:e,methodOpts:t}){let n=e.request,r=n.currency,i=Si(L.object({paymentMethod:L.string(),secretKey:L.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new zr({code:`MISSING_ENV`,message:`MPPX_STRIPE_SECRET_KEY environment variable is required for Stripe payments.`,exitCode:2});return{tokenSymbol:r?.toUpperCase()??``,tokenDecimals:n.decimals??2,methods:[yi.charge({paymentMethod:i.paymentMethod,createToken:async({paymentMethod:e,amount:t,currency:n,networkId:r,expiresAt:i,metadata:o})=>{let s=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()}),c=xi(a),l=process.env.MPPX_STRIPE_SPT_URL?process.env.MPPX_STRIPE_SPT_URL:c?`https://api.stripe.com/v1/test_helpers/shared_payment/granted_tokens`:`https://api.stripe.com/v1/shared_payment/issued_tokens`;if(r){let e=c?`seller_details[network_id]`:`seller_details[network_business_profile]`;s.set(e,r)}if(o)for(let[e,t]of Object.entries(o))s.set(`metadata[${e}]`,t);let u={Authorization:`Basic ${btoa(`${a}:`)}`,"Content-Type":`application/x-www-form-urlencoded`,"Stripe-Version":`2026-07-29.preview`},d=await globalThis.fetch(l,{method:`POST`,headers:u,body:s});if(!d.ok){let a=await d.json();if(c&&(o||r)&&a.error.message.includes(`Received unknown parameter`)){let r=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()});if(d=await globalThis.fetch(l,{method:`POST`,headers:u,body:r}),!d.ok)throw new zr({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${(await d.json()).error.message}`,exitCode:77})}else throw new zr({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${a.error.message}`,exitCode:77})}let{id:f}=await d.json();return f}})]}},formatReceiptField(e,t){if(e===`reference`&&typeof t==`string`&&t.startsWith(`pi_`)){let e=process.env.MPPX_STRIPE_SECRET_KEY,n=`https://dashboard.stripe.com${e!==void 0&&xi(e)?`/test`:``}/payments/${t}`;return X.link(n,t,!0)}}})}function xi(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function Si(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}const Ci=Symbol.for(`mppx.fetch.skipPayment`);Object.freeze({phase:`unproved`});function wi(e,t,n={}){return async(r,i)=>{let a=new Request(r,i),o=Ti(a.headers)??n.challenge,{response:s}=await t.send((t,n)=>e(t,{...n,...i?.[Ci]?{[Ci]:!0}:{}}),a,{...n,challenge:o});if(s.status===402&&o)for(let e of Ei(s))e.method===o.method&&e.intent===o.intent&&await t.challenge(s,{challenge:e},a.url);return s}}function Ti(e){for(let[,t]of e){let e=Tn(t);if(e)try{return yn(e).challenge}catch{}}}function Ei(e){try{return nn(e)}catch{return[]}}const Di=Symbol(`mppx.deferredContext`);function Oi(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=Ni(n)}return t}function ki(e,t){let n=Oi(e),r=Bi(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[Ni(e)]??1,index:t}));return{definition:r,entries:i,header:ji(i),keys:n}}function Ai(e){let t=e.split(/\s*,\s*/).map(e=>e.trim()).filter(Boolean);if(t.length===0)throw Error(`Accept-Payment header is empty.`);return t.map((e,t)=>Ri(e,t))}function ji(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${Wi(n)}`}).join(`, `)}function Mi(e,t,n,r){let i=new Map;for(let e of t){let t=Ni(e),n=i.get(t);n?n.push(e):i.set(t,[e])}let a=e.flatMap((e,t)=>{let a=i.get(Ni(e));if(!a)return[];let o=Pi(e,n);return!o||o.q<=0?[]:a.filter(t=>t.canHandleChallenge?.(r===void 0?{challenge:e}:{challenge:e,context:r})??!0).map(n=>({challenge:e,index:t,match:o,method:n}))}).sort((e,t)=>Li(e.challenge)-Li(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n}),o=a.filter(({challenge:e})=>!Kt(e));return o.length===0&&a[0]&&qt(a[0].challenge),o}function Ni(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function Pi(e,t){let n;for(let r of t){if(!Fi(e,r))continue;let t={...r,specificity:Ii(r)};(!n||t.specificity>n.specificity||t.specificity===n.specificity&&t.q>n.q||t.specificity===n.specificity&&t.q===n.q&&t.index<n.index)&&(n=t)}return n}function Fi(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function Ii(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function Li(e){return+!!On(e)}function Ri(e,t){let n=/^(?<method>[^/;\s]+|\*)\s*\/\s*(?<intent>[^/;\s]+|\*)(?<params>(?:\s*;\s*.+)?)$/u.exec(e),r=n?.groups?.method,i=n?.groups?.intent;if(!r||!i)throw Error(`Invalid Accept-Payment entry: ${e}`);Gi(r,`method`),Gi(i,`intent`);let a=1;for(let t of zi(n.groups?.params)){if(!t)continue;let n=/^(?<name>[A-Za-z0-9_-]+)\s*=\s*(?<value>\S+)$/u.exec(t),r=n?.groups?.name,i=n?.groups?.value;if(!r||!i)throw Error(`Invalid Accept-Payment parameter: ${t}`);r===`q`&&(a=Hi(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function zi(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function Bi(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>Ni(e))),a={};for(let[e,t]of Object.entries(r??{})){if(!i.has(e))throw Error(`Unknown payment preference "${e}". Available: ${[...i].join(`, `)}`);a[e]=Vi(t,`payment preference "${e}"`)}return a}function Vi(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return Ui(e,t)}function Hi(e,t){if(!/^0(?:\.\d{0,3})?$|^1(?:\.0{0,3})?$/.test(e))throw Error(`Invalid q-value for ${t}. Expected an HTTP qvalue.`);return Ui(Number(e),t)}function Ui(e,t){if(e<0||e>1)throw Error(`Invalid q-value for ${t}. Expected a value between 0 and 1.`);let n=Math.round(e*1e3);if(Math.abs(e*1e3-n)>1e-9)throw Error(`Invalid q-value for ${t}. Expected at most 3 decimal places.`);return n/1e3}function Wi(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function Gi(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}const Ki={extensions:K.optional(K.record(K.string(),K.unknown())),fundingCurrency:K.optional(K.string()),method:K.string(),reference:K.string(),externalId:K.optional(K.string()),subscriptionId:K.optional(K.string()),status:K.literal(`success`),timestamp:Ot()};K.object(Ki);const qi=K.looseObject(Ki);function Ji(e){let t=D.toString(e);return Yi(JSON.parse(t))}function Yi(e){return qi.parse(e)}const Xi=8192;function Zi(e){let t=e.headers.get(U.paymentReceipt);if(t!==null){if(t.length>Xi)return;try{let e=Ji(t);return Qi(`mpp`,e.reference,e)}catch{return}}let n=e.headers.get(Rn);if(!(n===null||n.length>Xi))try{let e=atob(n.trim().replace(/-/g,`+`).replace(/_/g,`/`)),t=Uint8Array.from(e,e=>e.charCodeAt(0)),r=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(t)),i=$n.safeParse(r);return!i.success||!i.data.success?void 0:Qi(`x402`,i.data.transaction,r)}catch{return}}function Qi(e,t,n){return Object.freeze({protocol:e,...t?{reference:t}:{},.../^0x[\da-fA-F]{64}$/.test(t)?{transactionHash:t}:{},raw:Object.freeze({...n})})}function $i(e){let t=``,n=!1,r=!1,i,a=``;function o(t){if(t===``){i!==void 0&&e({data:i,event:a||`message`}),i=void 0,a=``;return}let n=t.indexOf(`:`);if(n===0)return;let r=n===-1?t:t.slice(0,n);if(r!==`data`&&r!==`event`)return;let o=``;n!==-1&&(o=t.slice(t.charCodeAt(n+1)===32?n+2:n+1)),r===`event`?a=o:i=i===void 0?o:i+`
|
|
1
|
+
import{createClient as e,createTransport as t,custom as n,decodeErrorResult as r,encodeFunctionData as i,erc20Abi as a,formatUnits as o,getAbiItem as s,getAddress as c,hashTypedData as l,http as u,isAddress as d,isAddressEqual as f,keccak256 as p,parseAbi as m,parseEventLogs as h,parseUnits as g}from"viem";import{call as _,getBlockNumber as v,getLogs as y,prepareTransactionRequest as b,readContract as x,sendCallsSync as S,sendRawTransactionSync as C,sendTransactionSync as w,signTransaction as ee,signTypedData as T,waitForTransactionReceipt as te}from"viem/actions";import*as ne from"viem/chains";import{tempo as re}from"viem/chains";import{AbiParameters as E,Base64 as D,Bytes as O,Hash as k,Hex as A,Json as j}from"ox";import*as M from"zod/mini";import*as N from"node:child_process";import*as P from"node:fs";import*as F from"node:os";import*as I from"node:path";import{z as L}from"zod";import"node:readline";import{tempo as R,tempoModerato as z}from"viem/tempo/chains";import{ousd as ie,pathusd as ae,usdce as oe}from"viem/tokens";import{Abis as B,Account as se,Actions as V,Addresses as ce,TokenId as le,Transaction as ue,withFeePayer as de}from"viem/tempo";import{parseAccount as fe,privateKeyToAccount as pe}from"viem/accounts";import{AccountConfig as me,Channel as he,KeyAuthorization as ge,SignatureEnvelope as H,TempoAddress as _e,TxEnvelopeTempo as ve}from"ox/tempo";var ye=Object.defineProperty,be=Object.getOwnPropertyDescriptor,xe=Object.getOwnPropertyNames,Se=Object.prototype.hasOwnProperty,Ce=(e,t)=>{let n={};for(var r in e)ye(n,r,{get:e[r],enumerable:!0});return t||ye(n,Symbol.toStringTag,{value:`Module`}),n},we=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=xe(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Se.call(e,s)&&s!==n&&ye(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=be(t,s))||r.enumerable});return e},Te=(e,t,n)=>(we(e,t,`default`),n&&we(n,t,`default`));function Ee(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function De(e,t){let{chainId:n,decimals:r}=t;if(typeof e==`string`)return{address:e,chainId:n,decimals:r};if(Ee(e))return e.addresses[n]?e(n):void 0;if(e.chainId===n)return e}function Oe(e,t,n={}){let{chainId:r,decimals:i}=n,a=e=>e.toLowerCase()===t.toLowerCase();for(let t of e){if(typeof t==`string`){if(a(t))return{currency:t,decimals:i};continue}if((r===void 0?Ee(t)?Object.keys(t.addresses).map(e=>De(t,{chainId:Number(e)})):[t]:[De(t,{chainId:r})]).some(e=>e&&a(e.address)))return{currency:t,decimals:t.decimals}}}const ke=Symbol(`mppx.x402.asset`);function Ae(e){return{[ke]:!0,address:e.address,chainId:We(e.network),decimals:e.decimals,network:e.network,transfer:e.transfer}}function je(e,t){let n=e(t.chainId);return Ae({address:n.address,decimals:n.decimals,network:Ue(t.chainId),transfer:Ge(t.transfer,n)})}const Me={USDC:Ae({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},Ne={USDC:Ae({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},Pe={USDC:Ae({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:Ae({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},Fe={USDC:Ae({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},Ie=[Me,Ne,Pe,Fe].flatMap(e=>Object.values(e));function Le(e,t){let n=e.toLowerCase();return Ie.find(e=>e.network===t&&e.address.toLowerCase()===n)}function Re(e){return typeof e!=`object`||!e?!1:e[ke]===!0}const ze=Ee;function Be(e){return typeof e==`string`}function Ve(e,t){if(Re(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(typeof e==`string`)return{address:e};let n=De(e,{chainId:We(t)});if(n)return{address:n.address,decimals:n.decimals,name:n.name}}function He(e,t,n){let r=Ve(e,n);return r?c(r.address)===c(t):!1}function Ue(e){return`eip155:${e}`}function We(e){return Number(e.slice(7))}function Ge(e,t){if(e.type!==`eip3009`)return e;if(e.name)return{...e,name:e.name};if(!t.name)throw Error(`EIP-3009 token assets require a token name.`);return{...e,name:t.name}}var Ke=Ce({base:()=>Me,baseSepolia:()=>Ne,celo:()=>Pe,celoSepolia:()=>Fe,define:()=>Ae,fromToken:()=>je,isAsset:()=>Re,isRawAddress:()=>Be,isToken:()=>ze,lookup:()=>Le,matches:()=>He,resolve:()=>Ve,toChainId:()=>We,toNetwork:()=>Ue}),qe=Ce({base:()=>Je,baseSepolia:()=>Ye,celo:()=>Xe,celoSepolia:()=>Ze});const Je=8453,Ye=84532,Xe=42220,Ze=11142220,Qe=new WeakMap,$e=new WeakMap,et=new WeakMap;function tt(e,t){return Qe.set(e,t),e}function nt(e){return Qe.get(e)}function rt(e,t){$e.set(e,t)}function it(e){return $e.get(e)}function at(e,t){t===void 0||t===e?et.delete(e):et.set(e,t)}function ot(e){return et.get(e)}const U={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},st={payment:`Payment`},ct={evm:`evm`,stripe:`stripe`,tempo:`tempo`},lt={charge:`charge`,session:`session`,subscription:`subscription`},ut={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},dt={v1:`v1`,v2:`v2`};function ft(e,t){if(!(!e||typeof e!=`object`))return e[t]}function pt(e,t){return t?`${e} Add funds at ${t}`:e}var mt=class extends Error{details;status=402;hint;fundingUrl;constructor(e,t={}){super(e),this.details=t.details,this.fundingUrl=t.fundingUrl,t.cause!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t.cause,writable:!0})}toProblemDetails(e){return{type:this.type,title:this.title,status:this.status,detail:this.message,...this.details&&Object.keys(this.details).length>0&&{details:this.details},...this.hint&&{hint:this.hint},...this.fundingUrl&&{fundingUrl:this.fundingUrl},...e&&{challengeId:e}}}},ht=class extends mt{name=`InvalidChallengeError`;title=`Invalid Challenge`;status=402;type=`https://paymentauth.org/problems/invalid-challenge`;constructor(e={}){let{id:t,reason:n}=e,r=t?` "${t}"`:``,i=n?`: ${n}`:``;super(`Challenge${r} is invalid${i}.`)}},W=class extends mt{name=`VerificationFailedError`;title=`Verification Failed`;type=`https://paymentauth.org/problems/verification-failed`;constructor(e={}){let{details:t,fundingUrl:n,reason:r}=e;super(pt(r?`Payment verification failed: ${r}.`:`Payment verification failed.`,n),{details:t,fundingUrl:n})}},gt=class extends mt{name=`PaymentExpiredError`;title=`Payment Expired`;type=`https://paymentauth.org/problems/payment-expired`;constructor(e={}){let{expires:t}=e;super(t?`Payment expired at ${t}.`:`Payment has expired.`)}},_t=class extends mt{name=`PaymentOutcomeUnknownError`;title=`Payment Outcome Unknown`;type=`https://paymentauth.org/problems/payment-outcome-unknown`;challenge;credential;transactionHash;constructor(e){let{cause:t,challenge:n,credential:r,transactionHash:i}=e;super(`Payment outcome is unknown after sending a credential for challenge "${n.id}". Do not blindly retry.`,{cause:t}),this.challenge=n,this.credential=r,this.transactionHash=i}},vt=class extends Error{name=`BroadcastOutcomeUnknownError`;transactionHash;validBefore;constructor(e){let{cause:t,transactionHash:n,validBefore:r}=e;super(`Broadcast outcome is unknown for transaction ${n}. Look up its receipt before retrying.`),this.transactionHash=n,this.validBefore=r,t!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t,writable:!0})}},yt=class extends Error{name=`LegacyUnicodeEscapedChallengeError`;constructor(){super(`Legacy unicode-escaped challenge: the server escaped a bound parameter as \\uXXXX; upgrade the server.`)}},bt=class extends Error{name=`ConfigurableVouchersUnsupportedError`;signer;constructor(e){let{signer:t}=e;super(`Configurable account ${t} signs vouchers with TIP-1166 configurable account signatures, but the session challenge does not advertise \`configurableVouchers\`, so the channel was not opened.`),this.signer=t}},xt=class extends Error{name=`SignerConfigChangedError`;channelId;reason;signer;constructor(e){let{cause:t,channelId:n,reason:r,signer:i}=e;super(`Signer ${i} of channel ${n} changed its account config since the channel opened, so the top-up was not signed. Close the channel and open a new one.`),this.channelId=n,this.reason=r,this.signer=i,t!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t,writable:!0})}},St=class extends Error{name=`SpendingLimitExceededError`;accessKey;account;constructor(e){let{accessKey:t,account:n,cause:r}=e;super(`Access key spending limit exceeded: ${t?`key ${t} of `:``}account ${n} cannot pay this amount, so the payment was not signed.`),this.accessKey=t,this.account=n,r!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:r,writable:!0})}},Ct=class extends Error{name=`ZoneSettlementPendingError`;challengeId;senderTag;senderTags;zoneId;constructor(e){let{cause:t,challengeId:n,zoneId:r}=e,i=e.senderTags??(e.senderTag?[e.senderTag]:[]),a=i.length===1?i[0]:void 0,o=a??(i.length?`with sender tag ${i.join(` or `)}`:void 0);super(`Zone ${r} withdrawal ${o?`${o} `:``}for challenge "${n}" has not settled on Tempo yet. Retry the challenge to resume waiting instead of paying again.`),this.challengeId=n,this.senderTag=a,this.senderTags=i,this.zoneId=r,t!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t,writable:!0})}},wt=class extends Error{name=`PaymentLimitExceededError`;limit;reason;constructor(e){let{limit:t,reason:n}=e,r=t===`budget`?`the remaining budget`:`maxPayment`;super(n===`amount`?`Payment exceeds ${r}, so no credential was created.`:n===`credential`?`Credential cannot be checked against ${r}: it is unreadable or pays no single challenge the response offered, so it was not used.`:n===`intent`?`Payment intent cannot be checked against ${r}: spending options accept only charges, so no credential was created.`:`Payment asset cannot be checked against ${r}: no limit names it, or the client does not configure its currency and decimals. No credential was created.`),this.limit=t,this.reason=n}},Tt=class extends mt{name=`InsufficientBalanceError`;title=`Insufficient Balance`;status=402;type=`https://paymentauth.org/problems/session/insufficient-balance`;constructor(e={}){let{cause:t,fundingUrl:n,reason:r}=e;super(pt(r?`Insufficient balance: ${r}.`:`Insufficient balance.`,n),{cause:t,fundingUrl:n})}};function Et(e){let t=D.toString(e);return JSON.parse(t)}function G(e){let t=j.canonicalize(e);return D.fromString(t,{pad:!1,url:!0})}var K=Ce({address:()=>J,amount:()=>q,datetime:()=>Ot,datetimeInput:()=>kt,hash:()=>Mt,period:()=>Nt,signature:()=>Y,toDate:()=>At,toDatetimeString:()=>jt,unwrapOptional:()=>Pt});import*as Dt from"zod/mini";Te(K,Dt);function q(){return M.string().check(M.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function Ot(){return M.string().check(M.regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,`Invalid ISO 8601 datetime`))}function kt(e=`Invalid ISO 8601 datetime`){return M.pipe(M.union([Ot(),M.custom(e=>e instanceof Date)]),M.transform(At)).check(M.refine(e=>Number.isFinite(e.getTime()),e))}function At(e){return e instanceof Date?e:new Date(e)}function jt(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function J(){return M.string().check(M.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function Mt(){return M.string().check(M.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function Nt(){return M.string().check(M.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function Y(){return M.string().check(M.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function Pt(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}const Ft=Symbol(`mppx.Challenge.legacyUnicodeEscape`),It=new Set([`digest`,`expires`,`header`,`intent`,`method`,`opaque`,`realm`,`request`]),Lt=`Unsupported credential header: challenges may only select Payment-Authorization.`;var Rt=class extends Error{name=`UnsupportedCredentialHeaderError`;constructor(){super(Lt)}};const zt=K.object({description:K.optional(K.string()),digest:K.optional(K.string().check(K.regex(/^sha-256=/,`Invalid digest format`))),expires:K.optional(Ot()),header:K.optional(K.string().check(K.refine(fn,Lt))),id:K.string().check(K.minLength(1)),intent:K.string(),method:K.string(),meta:K.optional(K.record(K.string(),K.string())),opaque:K.optional(K.string()),realm:K.string(),request:K.record(K.string(),K.unknown())}),Bt=K.extend(zt,{header:K.optional(K.string())});function Vt(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=pn(o),f=e.expires?jt(e.expires):void 0,p=e.opaque??(i===void 0?void 0:G(i)),m=u?hn({...e,expires:f,header:d,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return zt.parse({id:m,realm:c,method:a,intent:s,request:l,...n&&{description:n},...r&&{digest:r},...f&&{expires:f},...d!==void 0&&{header:d},...i!==void 0&&{meta:i},...p!==void 0&&{opaque:p}})}const Ht=/^[a-z]+$/;var Ut=class extends Error{name=`InvalidMethodError`;constructor(e){super(`Invalid method: "${e}". Must be lowercase letters a-z per spec.`)}};function Wt(e){if(!Ht.test(e))throw new Ut(e)}function Gt(e,t){let n=Jt(e);if(!n)throw Error(`Missing Payment scheme.`);let r=new Set,{request:i,opaque:a,header:o,...s}=Yt(n,r);if(!i)throw Error(`Missing request parameter.`);if(i.length>16384)throw Error(`Request parameter too large.`);if(s.method!==void 0&&Wt(s.method),o!==void 0&&!fn(o))throw new Rt;let c=Vt({...s,request:Et(i),...a&&{opaque:a}},t),l=o===void 0?c:{...c,header:o};return[...r].some(e=>It.has(e))&&(l[Ft]=!0),l}function Kt(e){return!!(e&&typeof e==`object`&&e[Ft])}function qt(e){if(Kt(e))throw new yt}function Jt(e){let t=st.payment,[n]=tn(e,t);if(n===void 0)return null;let r=n+t.length;for(;r<e.length&&/\s/.test(e[r]??``);)r++;return e.slice(r)}function Yt(e,t){let n=Object.create(null),r=0;for(;r<e.length;){for(;r<e.length&&/[\s,]/.test(e[r]??``);)r++;if(r>=e.length)break;let i=r;for(;r<e.length&&/[A-Za-z0-9_-]/.test(e[r]??``);)r++;let a=e.slice(i,r).toLowerCase();if(!a)throw Error(`Malformed auth-param.`);for(;r<e.length&&/\s/.test(e[r]??``);)r++;if(e[r]!==`=`)break;for(r++;r<e.length&&/\s/.test(e[r]??``);)r++;let[o,s,c]=Xt(e,r);for(r=s,c&&t?.add(a);r<e.length&&/\s/.test(e[r]??``);)r++;if(r<e.length&&e[r]!==`,`)throw Error(`Malformed auth-param.`);if(a in n)throw Error(`Duplicate parameter: ${a}`);n[a]=o}return n}function Xt(e,t){if(e[t]===`"`)return Qt(e,t+1);let n=t;for(;n<e.length&&Zt.test(e[n]??``);)n++;if(n===t)throw Error(`Malformed auth-param.`);return[e.slice(t,n),n]}const Zt=/[!#$%&'*+\-.^_`|~0-9A-Za-z]/;function Qt(e,t){let n=t,r=!1,i=!1,a=t,o;for(;n<e.length;){let s=e[n];if(n++,r){s===`u`&&/^[0-9a-fA-F]{4}/.test(e.slice(n,n+4))&&(i=!0),o??=[],o.push(s),a=n,r=!1;continue}if(s===`\\`){o??=[],o.push(e.slice(a,n-1)),a=n,r=!0;continue}if(s===`"`)return[o?[...o,e.slice(a,n-1)].join(``):e.slice(t,n-1),n,i]}throw Error(`Unterminated quoted-string.`)}function $t(e,t,n){if(e.slice(t,t+n.length).toLowerCase()!==n.toLowerCase())return!1;let r=e[t+n.length];return!!(r&&/\s/.test(r))}function en(e){return tn(e,st.payment).length>0||e.split(`,`).some(e=>e.trim().toLowerCase()===st.payment.toLowerCase())}function tn(e,t){let n=[],r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(r){i?i=!1:o===`\\`?i=!0:o===`"`&&(r=!1);continue}if(o===`"`){r=!0;continue}if(!$t(e,a,t))continue;let s=a-1;for(;s>=0&&/\s/.test(e[s]??``);)s--;s>=0&&e[s]!==`,`||n.push(a)}return n}function nn(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return rn(e.headers,t)}function rn(e,t){let n=e.get(U.wwwAuthenticate);if(!n)throw Error(`Missing ${U.wwwAuthenticate} header.`);return an(n,t)}function an(e,t){let n=cn(e);if(n.length===0)throw Error(`No Payment schemes found.`);return n.flatMap(e=>{try{return[Gt(e,t)]}catch(e){if(e instanceof Rt||e instanceof Ut)return[];throw e}})}function on(e){return e?cn(e).filter(e=>{try{return Gt(e),!1}catch(e){return e instanceof Rt}}).length:0}function sn(e,t){return t<=0?e:t===1?`${e}. Skipped 1 challenge that selects a credential header other than Payment-Authorization`:`${e}. Skipped ${t} challenges that select a credential header other than Payment-Authorization`}function cn(e){let t=tn(e,st.payment);return t.map((n,r)=>{let i=r+1<t.length?t[r+1]:e.length;return e.slice(n,i).replace(/,\s*$/,``)})}function ln(e){let t=[e.realm,e.method,e.intent,G(e.request),e.expires??``,e.digest??``],n=mn(e.header);return n!==void 0&&t.push(n),t.push(e.opaque??(e.meta?G(e.meta):``)),t.join(`|`)}function un(e){let{header:t}=e;return t===void 0?U.authorization:fn(t)?U.paymentAuthorization:t}function dn(e){if(typeof e!=`object`||!e||!(`header`in e))return!1;let{header:t}=e;return t!==void 0&&!(typeof t==`string`&&fn(t))}function fn(e){return/^payment-authorization$/i.test(e)}function pn(e){return mn(e)===void 0?void 0:U.paymentAuthorization}function mn(e){if(e!==void 0&&!/^authorization$/i.test(e)){if(fn(e))return e;throw new Rt}}function hn(e,t){let n=ln(e),r=O.fromString(t.secretKey),i=O.fromString(n),a=k.hmac256(r,i,{as:`Bytes`});return D.fromBytes(a,{url:!0,pad:!1})}const gn=65536;var _n=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},vn=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}};function yn(e){if(e.length>gn)throw new vn;let t=e.match(RegExp(`^${st.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new _n;try{let e=D.toString(t[1]),n=JSON.parse(e);if(!xn(n.payload))throw Error(`Invalid payload.`);if(n.source!==void 0&&typeof n.source!=`string`)throw Error(`Invalid source.`);let{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=bn(r);return{challenge:zt.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:Et(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new vn}}function bn(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!Sn(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:G(e)}}function xn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Sn(e){return xn(e)?Object.values(e).every(e=>typeof e==`string`):!1}function Cn(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function wn(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:G(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:G(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=D.fromString(s,{pad:!1,url:!0});return`${st.payment} ${c}`}function Tn(e){return e.length>gn?null:e.split(`,`).map(e=>e.trim()).find(e=>RegExp(`^${st.payment}\\s+`,`i`).test(e))??null}const En=Symbol.for(`mppx.x402.challenge`);function Dn(e){return Object.defineProperty(e,En,{value:!0}),e}function On(e){return!!e?.[En]}function kn(e,t){if(!e)throw new ht({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new ht({...t&&{id:t},reason:`malformed expires timestamp`});if(Date.parse(e)<=Date.now())throw new gt({expires:e})}function An(e){let{_mpp_nonce:t,_mppx_nonce:n,_mppx_identity:r,_mppx_expiry_grace:i,...a}=e??{};return Object.keys(a).length?a:void 0}function jn(e){return e}function Mn(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,async createCredential(e){return qt(e.challenge),i.call(this,e)}}}function Nn(e){return{encode(t){return D.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(D.toString(t)))}catch{throw new Pn}}}}var Pn=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}};const Fn=[`exact`],In=`PAYMENT-REQUIRED`,Ln=`PAYMENT-SIGNATURE`,Rn=`PAYMENT-RESPONSE`,zn=K.string().check(K.minLength(1)),Bn=K.number().check(K.refine(e=>e>0,`Must be positive`)),Vn=K.string().check(K.regex(/^\d+$/,`Invalid atomic amount`)),Hn=J(),Un=K.string().check(K.regex(RegExp(`^eip155:\\d+$`),`Invalid EVM CAIP-2 network`)),Wn=K.object({description:K.optional(K.string()),iconUrl:K.optional(K.string()),mimeType:K.optional(K.string()),serviceName:K.optional(K.string()),tags:K.optional(K.array(K.string())),url:zn});K.discriminatedUnion(`type`,[K.object({name:zn,type:K.literal(`eip3009`),version:zn}),K.object({name:K.optional(K.string()),type:K.literal(`permit2`),version:K.optional(K.string())})]);const Gn=K.object({amount:Vn,asset:zn,extra:K.optional(K.record(K.string(),K.unknown())),maxTimeoutSeconds:Bn,network:Un,payTo:zn,scheme:K.enum(Fn)}),Kn=K.looseObject({info:K.record(K.string(),K.unknown()),schema:K.record(K.string(),K.unknown())}),qn=K.record(K.string(),Kn),Jn=K.object({accepts:K.array(Gn).check(K.minLength(1)),error:K.optional(K.string()),extensions:K.optional(qn),resource:Wn,x402Version:K.literal(2)}),Yn=K.object({authorization:K.object({from:Hn,nonce:Mt(),to:Hn,validAfter:Vn,validBefore:Vn,value:Vn}),signature:Y()}),Xn=K.object({permit2Authorization:K.object({deadline:Vn,from:Hn,nonce:Vn,permitted:K.object({amount:Vn,token:Hn}),spender:Hn,witness:K.object({to:Hn,validAfter:Vn})}),signature:Y()}),Zn=K.union([Yn,Xn]),Qn=K.object({accepted:Gn,extensions:K.optional(qn),payload:Zn,resource:K.optional(Wn),x402Version:K.literal(2)});K.object({extensions:K.optional(K.record(K.string(),K.unknown())),extra:K.optional(K.record(K.string(),K.unknown())),invalidMessage:K.optional(K.string()),invalidReason:K.optional(K.string()),isValid:K.boolean(),payer:K.optional(K.string())});const $n=K.object({amount:K.optional(Vn),errorMessage:K.optional(K.string()),errorReason:K.optional(K.string()),extensions:K.optional(K.record(K.string(),K.unknown())),extra:K.optional(K.record(K.string(),K.unknown())),network:zn,payer:K.optional(K.string()),success:K.boolean(),transaction:K.string()}),er=K.object({extra:K.optional(K.record(K.string(),K.unknown())),network:zn,scheme:zn,x402Version:K.number()});K.object({extensions:K.optional(K.array(K.string())),kinds:K.array(er),signers:K.optional(K.record(K.string(),K.array(K.string())))});function tr(e){let{extensions:t,resource:n,...r}=e;return Gn.parse(r)}const nr=Nn(Jn),rr=Nn(Qn),ir=Nn($n);nr.encode,nr.decode;function ar(e){try{let t=JSON.parse(D.toString(e));return cr(t)}catch{throw new Pn}}const or=rr.encode,sr=rr.decode;ir.encode,ir.decode;const cr=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new Pn;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new Pn;let n=Wn.parse(t.resource),r=t.extensions===void 0?void 0:qn.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}};function lr(e){let t=[G(e.accepted),G(e.resource),G(e.extensions)].join(`|`);return k.sha256(O.fromString(t),{as:`Hex`})}async function ur(e){let t=e.context?.account??e.config.account;if(!t?.signTypedData)throw Error(`x402 exact requires a typed-data signer.`);let n=e.challenge.request,r=tr(n);if(mr(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?gr(n.extensions):n.extensions,a=r.extra?.assetTransferMethod??`eip3009`;if(a!==`eip3009`)throw Error(`x402 exact ${String(a)} signing is not implemented yet.`);let o=r.extra?.name,s=r.extra?.version;if(typeof o!=`string`||typeof s!=`string`)throw Error(`x402 exact EIP-3009 requires token name and version.`);let l=Math.floor(Date.now()/1e3),u={from:c(t.address),nonce:i?.mppx?lr({accepted:r,extensions:i,resource:n.resource}):vr(),to:c(r.payTo),validAfter:(l-600).toString(),validBefore:(l+r.maxTimeoutSeconds).toString(),value:r.amount},d=await t.signTypedData({domain:{chainId:pr(r.network),name:o,verifyingContract:c(r.asset),version:s},message:{...u,value:BigInt(u.value),validAfter:BigInt(u.validAfter),validBefore:BigInt(u.validBefore)},primaryType:`TransferWithAuthorization`,types:fr});return or({accepted:r,...i?{extensions:i}:{},payload:{authorization:u,signature:d},...n.resource?{resource:n.resource}:{},x402Version:2})}function dr(e){let t=e.challenge.request,n;try{n=tr(t),mr(e.config,n)}catch{return!1}if(!t.resource||(n.extra?.assetTransferMethod??`eip3009`)!==`eip3009`)return!1;let r=n.extra?.name,i=n.extra?.version;return typeof r==`string`&&typeof i==`string`}const fr={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function pr(e){return Number(e.slice(7))}function mr(e,t){let n=pr(t.network);if(e.networks&&!e.networks.includes(n))throw Error(`x402 exact chain ID is not allowed: ${n}.`);let r=e.currencies??e.assets;if(r?.some(e=>Be(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=c(t.asset);if(!r.some(n=>He(n,e,t.network)))throw Error(`x402 exact currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`x402 exact amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=hr(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>g(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function hr(e,t){let n=e.currencies??e.assets,r=c(t.asset),i=n?.find(e=>He(e,r,t.network)),a=i?Ve(i,t.network):void 0;return a?.decimals===void 0?e.decimals===void 0?Le(r,t.network)?.decimals:e.decimals:a.decimals}function gr(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:_r()}}}:e}function _r(){return yr().slice(2)}function vr(){return yr()}function yr(){let e=globalThis.crypto;if(!e?.getRandomValues)throw Error(`x402 exact requires crypto randomness.`);let t=e.getRandomValues(new Uint8Array(32));return`0x${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}const br=[`authorization`],xr=K.string().check(K.regex(/^\d+$/,`Invalid atomic amount`));K.object({name:K.string().check(K.minLength(1)),version:K.string().check(K.minLength(1))});const Sr=K.object({chainId:K.number(),credentialTypes:K.optional(K.array(K.enum(br)).check(K.minLength(1))),decimals:K.optional(K.number()),permit2Address:K.optional(J()),splits:K.optional(K.array(K.object({amount:xr,recipient:J()})))});K.object({amount:xr,currency:J(),description:K.optional(K.string()),externalId:K.optional(K.string()),methodDetails:Sr,recipient:J()});const Cr=K.object({amount:q(),chainId:K.number(),currency:J(),credentialTypes:K.optional(K.array(K.enum(br)).check(K.minLength(1))),decimals:K.number(),description:K.optional(K.string()),externalId:K.optional(K.string()),permit2Address:K.optional(J()),recipient:J(),splits:K.optional(K.array(K.object({amount:xr,recipient:J()})))}),wr=K.object({from:J(),nonce:Mt(),signature:Y(),to:J(),type:K.literal(`authorization`),validAfter:xr,validBefore:xr,value:xr}),Tr={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function Er(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function Dr(e){return k.keccak256(O.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function Or(e){return`eip155:${e}`}function kr(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const Ar=jn({name:`evm`,intent:`charge`,schema:{credential:{payload:wr},request:K.pipe(Cr,K.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:o,splits:s,...l})=>({...l,amount:g(e,i).toString(),currency:c(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:c(a)}:{},...s?{splits:s}:{}},recipient:c(o)})))}});function jr(e){return tt(Mn(Ar,{canHandleChallenge({challenge:t}){return!Mr(t)||dr({challenge:t,config:e})},context:K.object({account:K.optional(K.custom())}),async createCredential({challenge:t,context:n}){if(Mr(t))return ur({challenge:t,config:e,context:n});let r=n?.account??e.account;if(!r?.signTypedData)throw Error(`EVM authorization requires a typed-data signer.`);let i=t.request;Nr(e,i);let a=Fr(e,i),o=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return wn(Cn({challenge:t,payload:{from:c(r.address),nonce:Dr(t),signature:await r.signTypedData({domain:Er({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:c(r.address),nonce:Dr(t),to:c(i.recipient),validAfter:0n,validBefore:BigInt(o),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:Tr}),to:c(i.recipient),type:`authorization`,validAfter:`0`,validBefore:o,value:i.amount},source:kr({address:c(r.address),chainId:i.methodDetails.chainId})}))}}),{assert(t){Mr(t)||Nr(e,t.request)}})}function Mr(e){return On(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function Nr(e,t){if(Pr(e,t),!t.methodDetails.credentialTypes?.includes(`authorization`))throw Error(`EVM authorization is not accepted by this challenge.`);if(t.methodDetails.splits?.length)throw Error(`EVM authorization does not support payment splits.`)}function Pr(e,t){let n=t.methodDetails.chainId,r=Or(n);if(e.networks&&!e.networks.includes(n))throw Error(`EVM chain ID is not allowed: ${n}.`);let i=e.currencies??e.assets;if(i?.some(e=>Be(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=c(t.currency);if(!i.some(t=>He(t,e,r)))throw Error(`EVM currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`EVM charge amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=Ir(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>g(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function Fr(e,t){let n=e.currencies??e.assets,r=c(t.currency),i=Or(t.methodDetails.chainId),a=n?.find(e=>He(e,r,i)),o=a?Ve(a,i):void 0;if(o?.transfer?.type===`eip3009`)return{name:o.transfer.name,version:o.transfer.version};if(e.authorization)return e.authorization;let s=Le(r,i)?.transfer;if(s?.type===`eip3009`)return{name:s.name,version:s.version};throw Error(`EVM authorization requires token name and version.`)}function Ir(e,t){let n=e.currencies??e.assets,r=c(t.currency),i=Or(t.methodDetails.chainId),a=n?.find(e=>He(e,r,i)),o=a?Ve(a,i):void 0;return o?.decimals===void 0?e.decimals===void 0?Le(r,i)?.decimals:e.decimals:o.decimals}function Lr(e){return[Lr.charge(e)]}(function(e){e.charge=jr,e.assets=Ke,e.chains=qe})(Lr||={});var Rr=class extends Error{name=`Incur.BaseError`;shortMessage;details;constructor(e,t={}){let n=t.cause instanceof Error?t.cause.message:void 0,r=n?`${e}\n\nDetails: ${n}`:e;super(r,t.cause?{cause:t.cause}:void 0),this.shortMessage=e,this.details=n}walk(e){return Br(this,e)}},zr=class extends Rr{name=`Incur.IncurError`;code;hint;retryable;exitCode;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.code=e.code,this.hint=e.hint,this.retryable=e.retryable??!1,this.exitCode=e.exitCode}};function Br(e,t){if(t){let n=e?.cause;for(;n;){if(t(n))return n;n=n?.cause}return}let n=e;for(;n?.cause;)n=n.cause;return n}const X=(()=>{let e=process||{},t=e.argv||[],n=e.env||{},r=!(n.NO_COLOR||t.includes(`--no-color`))&&(!!n.FORCE_COLOR||t.includes(`--color`)||(e.stdout||{}).isTTY&&n.TERM!==`dumb`||!!n.CI),i=(e,t,n,r)=>{let i=``,a=0,o=r;do i+=e.substring(a,o)+n,a=o+t.length,o=e.indexOf(t,a);while(~o);return i+e.substring(a)},a=r?(e,t,n=e)=>r=>{let a=`${r}`,o=a.indexOf(t,e.length);return~o?e+i(a,t,n,o)+t:e+a+t}:()=>String;return{isColorSupported:r,reset:a(`\x1B[0m`,`\x1B[0m`),bold:a(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:a(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:a(`\x1B[3m`,`\x1B[23m`),underline:a(`\x1B[4m`,`\x1B[24m`),inverse:a(`\x1B[7m`,`\x1B[27m`),hidden:a(`\x1B[8m`,`\x1B[28m`),strikethrough:a(`\x1B[9m`,`\x1B[29m`),black:a(`\x1B[30m`,`\x1B[39m`),red:a(`\x1B[31m`,`\x1B[39m`),green:a(`\x1B[32m`,`\x1B[39m`),yellow:a(`\x1B[33m`,`\x1B[39m`),blue:a(`\x1B[34m`,`\x1B[39m`),magenta:a(`\x1B[35m`,`\x1B[39m`),cyan:a(`\x1B[36m`,`\x1B[39m`),white:a(`\x1B[37m`,`\x1B[39m`),gray:a(`\x1B[90m`,`\x1B[39m`),bgBlack:a(`\x1B[40m`,`\x1B[49m`),bgRed:a(`\x1B[41m`,`\x1B[49m`),bgGreen:a(`\x1B[42m`,`\x1B[49m`),bgYellow:a(`\x1B[43m`,`\x1B[49m`),bgBlue:a(`\x1B[44m`,`\x1B[49m`),bgMagenta:a(`\x1B[45m`,`\x1B[49m`),bgCyan:a(`\x1B[46m`,`\x1B[49m`),bgWhite:a(`\x1B[47m`,`\x1B[49m`),blackBright:a(`\x1B[90m`,`\x1B[39m`),redBright:a(`\x1B[91m`,`\x1B[39m`),greenBright:a(`\x1B[92m`,`\x1B[39m`),yellowBright:a(`\x1B[93m`,`\x1B[39m`),blueBright:a(`\x1B[94m`,`\x1B[39m`),magentaBright:a(`\x1B[95m`,`\x1B[39m`),cyanBright:a(`\x1B[96m`,`\x1B[39m`),whiteBright:a(`\x1B[97m`,`\x1B[39m`),bgBlackBright:a(`\x1B[100m`,`\x1B[49m`),bgRedBright:a(`\x1B[101m`,`\x1B[49m`),bgGreenBright:a(`\x1B[102m`,`\x1B[49m`),bgYellowBright:a(`\x1B[103m`,`\x1B[49m`),bgBlueBright:a(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:a(`\x1B[105m`,`\x1B[49m`),bgCyanBright:a(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:a(`\x1B[107m`,`\x1B[49m`),link(e,t,n){return r?`\x1b]8;;${e}\x07${n?t:X.underline(t)}\x1b]8;;\x07`:t}}})(),Z={mainnet:4217,testnet:42431},Vr={ousd:ie(Z.mainnet).address,usdc:c(oe(Z.mainnet).address),pathUsd:ae(Z.mainnet).address},Hr={[Z.mainnet]:Vr.usdc,[Z.testnet]:Vr.pathUsd},Ur=Object.freeze({[Z.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[Z.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})});Z.mainnet,Z.testnet;const Wr={[Z.mainnet]:`https://rpc.tempo.xyz`,[Z.testnet]:`https://rpc.moderato.tempo.xyz`};function Gr(e,t){return X.link(e,t)}function Kr(e){return e.startsWith(`tempo:`)}function qr(e,t,n=6,r){let[i,a]=(Number(e)/10**n).toString().split(`.`),o=i.replace(/\B(?=(\d{3})+(?!\d))/g,`_`),s=r?.explorerUrl&&r.token?X.dim(X.link(`${r.explorerUrl}/token/${r.token}`,t,!0)):X.dim(t);return`${a?`${o}.${a}`:o} ${s}`}const Jr={mainnet:Wr[Z.mainnet],testnet:Wr[Z.testnet]};function Yr(e,t={}){return e??(t.network?Jr[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}async function Xr(t={}){let n=Yr(t.rpcUrl,{network:t.network});if(!n)return R;let{getChainId:r}=await import(`viem/actions`),i=await r(e({transport:u(n)})),a=Object.values(await import(`viem/tempo/chains`)).filter(e=>typeof e==`object`&&!!e&&`id`in e&&e.id===i),o=a.find(e=>`serializers`in e&&e.serializers)??a[0];if(!o)throw Error(`Unknown chain ID ${i} from RPC ${n}`);return o}function Zr(e){return typeof e==`bigint`?e:e.amount}function Qr(e){return e.id!==R.id}async function $r(e,t,n,r={}){let{Actions:i}=await import(`viem/tempo`),[a,o]=await Promise.all([i.token.getBalance(e,{account:n,token:t}).then(Zr).catch(()=>0n),i.token.getMetadata(e,{token:t}).catch(e=>{if(r.requireDecimals)throw e;return{symbol:t}})]),s={"0x20c0000000000000000000000000000000000000":`PathUSD`,"0x20C000000000000000000000b9537d11c60E8b50":`USDC`}[t]??o.symbol,c=`decimals`in o&&typeof o.decimals==`number`?o.decimals:6;if(r.requireDecimals&&!(`decimals`in o&&typeof o.decimals==`number`))throw Error(`Token decimals are unavailable.`);return{balance:a,symbol:s,decimals:c,token:t}}function ei(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:1e4}function ti(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function ni(e){return new zr({code:`KEYCHAIN_UNAVAILABLE`,message:`Linux keyring requires secret-tool. Install libsecret-tools.`,hint:`On Debian/Ubuntu, run: sudo apt install libsecret-tools gnome-keyring dbus-x11`,exitCode:69,cause:e})}function ri(e){if(e&&ti(e,`secret-tool`))throw ni(e)}function ii(e){return e.map(e=>{if(/[\r\n]/.test(e))throw Error(`Keychain values cannot contain line breaks.`);return`"${e.replace(/["\\]/g,`\\$&`)}"`}).join(` `)}function ai(e,t,n){return new Promise(r=>{let i=N.execFile(e,t,{timeout:ei()},(e,t,n)=>{r({stdout:t.trim(),stderr:n.trim(),error:e})});n!==void 0&&i.stdin?.end(n)})}function oi(){let e=I.join(process.env.XDG_CONFIG_HOME||I.join(F.homedir(),`.config`),`mppx`,`default`);return{get(){try{return P.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(t){P.mkdirSync(I.dirname(e),{recursive:!0}),P.writeFileSync(e,t,`utf-8`)},clear(){try{P.unlinkSync(e)}catch{}}}}function si(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:oi().get())}function ci(e=`main`){let t=`mppx`;return{async list(){let e=F.platform();if(e===`darwin`){let{stdout:e,error:n}=await ai(`security`,[`dump-keychain`]);if(n)return[];let r=[],i=e.split(`keychain:`);for(let e of i){let n=e.match(/"svce"<blob>="([^"]*)"/),i=e.match(/"acct"<blob>="([^"]*)"/);n?.[1]===t&&i?.[1]&&r.push(i[1])}return r}if(e===`linux`){let{stdout:e,stderr:n,error:r}=await ai(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(ri(r),r)return[];let i=`${e}\n${n}`,a=[],o=i.matchAll(/\baccount = (.+)/g);for(let e of o)e[1]&&a.push(e[1]);return a}throw Error(`Unsupported platform: ${e}`)},async get(){let n=F.platform();if(n===`darwin`){let{stdout:n,error:r}=await ai(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await ai(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return ri(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=F.platform();if(r===`darwin`){let r=`${ii([`add-generic-password`,`-s`,t,`-a`,e,`-w`,n])}\n`;await ai(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:i}=await ai(`security`,[`-i`],r);if(i)throw i;return}if(r===`linux`){let r=N.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),ei());return r.stdin?.write(n),r.stdin?.end(),new Promise((e,t)=>{r.on(`close`,n=>{clearTimeout(i),n===0?e():t(Error(`secret-tool exited with code ${n}`))}),r.on(`error`,e=>{clearTimeout(i),t(ti(e,`secret-tool`)?ni(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=F.platform();if(n===`darwin`){await ai(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await ai(`secret-tool`,[`clear`,`service`,t,`account`,e]);ri(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function li(e){let{privateKeyToAccount:t}=await import(`viem/accounts`),n=process.env.MPPX_PRIVATE_KEY?.trim();if(n)return{account:t(n),source:`environment`};let r=si(e),i=await ci(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function ui(e){return(await li(e)).account}function di(e){return e}function fi(){return di({method:`evm`,supports:e=>e.method===`evm`&&!On(e),async setup({challenge:t,options:n}){let r=t.request,i=r.methodDetails,o=i?.chainId,s=o?pi(o):void 0,c=r.currency,l=await ui(n.account),d=[...Object.values(Me),...Object.values(Ne),...Object.values(Pe),...Object.values(Fe)],f=c??``;if(s&&c)try{let t=e({chain:s,transport:u()}),n=await x(t,{address:c,abi:a,functionName:`symbol`});n&&(f=n)}catch{}return{tokenSymbol:f,tokenDecimals:i?.decimals??6,explorerUrl:s?.blockExplorers?.default?.url,methods:[...Lr({account:l,currencies:d})]}}})}function pi(e){return Object.values(ne).find(t=>t.id===e)}function mi(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`Decimals must be a non-negative integer.`);if(!/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e))throw TypeError(`Value \`${e}\` is not a valid decimal number.`);let n=e.startsWith(`-`),[r=`0`,i=``]=(n?e.slice(1):e).split(`.`),a=i.slice(0,t).padEnd(t,`0`),o=BigInt(`${r||`0`}${a}`);return i.length>t&&i[t]>=`5`&&(o+=1n),n?-o:o}const hi=K.object({customer:K.optional(K.string().check(K.minLength(1))),hooks:K.optional(K.object({inputs:K.object({tax:K.object({calculation:K.string().check(K.minLength(1))})})})),metadata:K.optional(K.record(K.string(),K.string())),receipt_email:K.optional(K.string().check(K.minLength(1)))}),gi=K.custom(e=>typeof e==`function`),_i=K.union([hi,gi]),vi=jn({name:`stripe`,intent:`charge`,schema:{credential:{payload:K.object({externalId:K.optional(K.string()),spt:K.string()})},request:K.pipe(K.object({amount:q(),currency:K.string(),decimals:K.number(),description:K.optional(K.string()),externalId:K.optional(K.string()),metadata:K.optional(K.record(K.string(),K.string())),networkId:K.string(),paymentIntentOptions:K.optional(_i),paymentMethodTypes:K.array(K.string()).check(K.minLength(1)),recipient:K.optional(K.string())}),K.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:mi(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});function yi(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return Mn(vi,{context:K.object({paymentMethod:K.optional(K.string())}),async createCredential({challenge:e,context:a}){let o=a?.paymentMethod??i;if(!o)throw Error(`paymentMethod is required (pass via context or parameters)`);let s=e.request.amount,c=e.request.currency,l=typeof e.request.externalId==`string`?e.request.externalId:void 0,u=e.request.methodDetails?.networkId;if(!u)throw Error(`networkId is required in challenge.methodDetails`);let d=e.request.methodDetails?.metadata;if(d?.externalId)throw Error(`methodDetails.metadata.externalId is reserved; use credential externalId instead`);let f=e.expires?Math.floor(new Date(e.expires).getTime()/1e3):Math.floor(Date.now()/1e3)+3600,p=await n({amount:s,challenge:e,client:t,currency:c,expiresAt:f,metadata:d,networkId:u,paymentMethod:o}),m=l??r;return wn({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function bi(e){return[yi(e)]}(function(e){e.charge=yi})(bi||={});function xi(){return di({method:`stripe`,supports(e){return e.method===`stripe`&&e.intent===`charge`},async setup({challenge:e,methodOpts:t}){let n=e.request,r=n.currency,i=Ci(L.object({paymentMethod:L.string(),secretKey:L.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new zr({code:`MISSING_ENV`,message:`MPPX_STRIPE_SECRET_KEY environment variable is required for Stripe payments.`,exitCode:2});return{tokenSymbol:r?.toUpperCase()??``,tokenDecimals:n.decimals??2,methods:[bi.charge({paymentMethod:i.paymentMethod,createToken:async({paymentMethod:e,amount:t,currency:n,networkId:r,expiresAt:i,metadata:o})=>{let s=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()}),c=Si(a),l=process.env.MPPX_STRIPE_SPT_URL?process.env.MPPX_STRIPE_SPT_URL:c?`https://api.stripe.com/v1/test_helpers/shared_payment/granted_tokens`:`https://api.stripe.com/v1/shared_payment/issued_tokens`;if(r){let e=c?`seller_details[network_id]`:`seller_details[network_business_profile]`;s.set(e,r)}if(o)for(let[e,t]of Object.entries(o))s.set(`metadata[${e}]`,t);let u={Authorization:`Basic ${btoa(`${a}:`)}`,"Content-Type":`application/x-www-form-urlencoded`,"Stripe-Version":`2026-07-29.preview`},d=await globalThis.fetch(l,{method:`POST`,headers:u,body:s});if(!d.ok){let a=await d.json();if(c&&(o||r)&&a.error.message.includes(`Received unknown parameter`)){let r=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()});if(d=await globalThis.fetch(l,{method:`POST`,headers:u,body:r}),!d.ok)throw new zr({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${(await d.json()).error.message}`,exitCode:77})}else throw new zr({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${a.error.message}`,exitCode:77})}let{id:f}=await d.json();return f}})]}},formatReceiptField(e,t){if(e===`reference`&&typeof t==`string`&&t.startsWith(`pi_`)){let e=process.env.MPPX_STRIPE_SECRET_KEY,n=`https://dashboard.stripe.com${e!==void 0&&Si(e)?`/test`:``}/payments/${t}`;return X.link(n,t,!0)}}})}function Si(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function Ci(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}const wi=Symbol.for(`mppx.fetch.skipPayment`);Object.freeze({phase:`unproved`});function Ti(e,t,n={}){return async(r,i)=>{let a=new Request(r,i),o=Ei(a.headers)??n.challenge,{response:s}=await t.send((t,n)=>e(t,{...n,...i?.[wi]?{[wi]:!0}:{}}),a,{...n,challenge:o});if(s.status===402&&o)for(let e of Di(s))e.method===o.method&&e.intent===o.intent&&await t.challenge(s,{challenge:e},a.url);return s}}function Ei(e){for(let[,t]of e){let e=Tn(t);if(e)try{return yn(e).challenge}catch{}}}function Di(e){try{return nn(e)}catch{return[]}}const Oi=Symbol(`mppx.deferredContext`);function ki(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=Pi(n)}return t}function Ai(e,t){let n=ki(e),r=Vi(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[Pi(e)]??1,index:t}));return{definition:r,entries:i,header:Mi(i),keys:n}}function ji(e){let t=e.split(/\s*,\s*/).map(e=>e.trim()).filter(Boolean);if(t.length===0)throw Error(`Accept-Payment header is empty.`);return t.map((e,t)=>zi(e,t))}function Mi(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${Gi(n)}`}).join(`, `)}function Ni(e,t,n,r){let i=new Map;for(let e of t){let t=Pi(e),n=i.get(t);n?n.push(e):i.set(t,[e])}let a=e.flatMap((e,t)=>{let a=i.get(Pi(e));if(!a)return[];let o=Fi(e,n);return!o||o.q<=0?[]:a.filter(t=>t.canHandleChallenge?.(r===void 0?{challenge:e}:{challenge:e,context:r})??!0).map(n=>({challenge:e,index:t,match:o,method:n}))}).sort((e,t)=>Ri(e.challenge)-Ri(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n}),o=a.filter(({challenge:e})=>!Kt(e));return o.length===0&&a[0]&&qt(a[0].challenge),o}function Pi(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function Fi(e,t){let n;for(let r of t){if(!Ii(e,r))continue;let t={...r,specificity:Li(r)};(!n||t.specificity>n.specificity||t.specificity===n.specificity&&t.q>n.q||t.specificity===n.specificity&&t.q===n.q&&t.index<n.index)&&(n=t)}return n}function Ii(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function Li(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function Ri(e){return+!!On(e)}function zi(e,t){let n=/^(?<method>[^/;\s]+|\*)\s*\/\s*(?<intent>[^/;\s]+|\*)(?<params>(?:\s*;\s*.+)?)$/u.exec(e),r=n?.groups?.method,i=n?.groups?.intent;if(!r||!i)throw Error(`Invalid Accept-Payment entry: ${e}`);Ki(r,`method`),Ki(i,`intent`);let a=1;for(let t of Bi(n.groups?.params)){if(!t)continue;let n=/^(?<name>[A-Za-z0-9_-]+)\s*=\s*(?<value>\S+)$/u.exec(t),r=n?.groups?.name,i=n?.groups?.value;if(!r||!i)throw Error(`Invalid Accept-Payment parameter: ${t}`);r===`q`&&(a=Ui(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function Bi(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function Vi(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>Pi(e))),a={};for(let[e,t]of Object.entries(r??{})){if(!i.has(e))throw Error(`Unknown payment preference "${e}". Available: ${[...i].join(`, `)}`);a[e]=Hi(t,`payment preference "${e}"`)}return a}function Hi(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return Wi(e,t)}function Ui(e,t){if(!/^0(?:\.\d{0,3})?$|^1(?:\.0{0,3})?$/.test(e))throw Error(`Invalid q-value for ${t}. Expected an HTTP qvalue.`);return Wi(Number(e),t)}function Wi(e,t){if(e<0||e>1)throw Error(`Invalid q-value for ${t}. Expected a value between 0 and 1.`);let n=Math.round(e*1e3);if(Math.abs(e*1e3-n)>1e-9)throw Error(`Invalid q-value for ${t}. Expected at most 3 decimal places.`);return n/1e3}function Gi(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function Ki(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}const qi={extensions:K.optional(K.record(K.string(),K.unknown())),fundingCurrency:K.optional(K.string()),method:K.string(),reference:K.string(),externalId:K.optional(K.string()),subscriptionId:K.optional(K.string()),status:K.literal(`success`),timestamp:Ot()};K.object(qi);const Ji=K.looseObject(qi);function Yi(e){let t=D.toString(e);return Xi(JSON.parse(t))}function Xi(e){return Ji.parse(e)}const Zi=8192;function Qi(e){let t=e.headers.get(U.paymentReceipt);if(t!==null){if(t.length>Zi)return;try{let e=Yi(t);return $i(`mpp`,e.reference,e)}catch{return}}let n=e.headers.get(Rn);if(!(n===null||n.length>Zi))try{let e=atob(n.trim().replace(/-/g,`+`).replace(/_/g,`/`)),t=Uint8Array.from(e,e=>e.charCodeAt(0)),r=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(t)),i=$n.safeParse(r);return!i.success||!i.data.success?void 0:$i(`x402`,i.data.transaction,r)}catch{return}}function $i(e,t,n){return Object.freeze({protocol:e,...t?{reference:t}:{},.../^0x[\da-fA-F]{64}$/.test(t)?{transactionHash:t}:{},raw:Object.freeze({...n})})}function ea(e){let t=``,n=!1,r=!1,i,a=``;function o(t){if(t===``){i!==void 0&&e({data:i,event:a||`message`}),i=void 0,a=``;return}let n=t.indexOf(`:`);if(n===0)return;let r=n===-1?t:t.slice(0,n);if(r!==`data`&&r!==`event`)return;let o=``;n!==-1&&(o=t.slice(t.charCodeAt(n+1)===32?n+2:n+1)),r===`event`?a=o:i=i===void 0?o:i+`
|
|
2
2
|
`+o}return{feed(e){if(!n&&e&&(n=!0,e.startsWith(``)&&(e=e.slice(1))),r&&e&&(r=!1,e.startsWith(`
|
|
3
3
|
`)&&(e=e.slice(1))),t+=e,e.indexOf(`
|
|
4
4
|
`)===-1&&e.indexOf(`\r`)===-1)return;let i=0,a=t.indexOf(`
|
|
5
5
|
`),s=t.indexOf(`\r`);for(;a!==-1||s!==-1;){let e=a===-1?s:s===-1?a:Math.min(a,s);o(t.slice(i,e)),i=e+1,e===s&&(i===t.length?r=!0:a===i&&i++,s=t.indexOf(`\r`,i)),a!==-1&&a<i&&(a=t.indexOf(`
|
|
6
|
-
`,i))}t=t.slice(i)}}}const ea=[U.authorization,U.paymentAuthorization,In,Rn,Ln];function ta(e,t,n){let r=new Headers(e.headers);for(let e of ea){let t=r.get(e);if(t===null)continue;if(!ia(e)){r.delete(e);continue}let n=na(t);n!==t&&(n?r.set(e,n):r.delete(e))}return r.set(t,n),{...e,headers:r}}function na(e){let t=e.split(`,`).map(e=>e.trim()),n=t.filter(e=>!ra.test(e));return n.length===t.length?e:n.filter(Boolean).join(`, `)}const ra=RegExp(`^${st.payment}(?:\\s|$)`,`i`);function ia(e){return e===U.authorization||e===U.paymentAuthorization}function aa(e){if(typeof e==`string`)try{let t=JSON.parse(e),n=t?.id;return t?.jsonrpc!==`2.0`||typeof t?.method!=`string`?void 0:typeof n==`string`||typeof n==`number`?n:void 0}catch{return}}function oa(e){if(typeof e?.body!=`string`)return!1;try{let t=JSON.parse(e.body);return t?.jsonrpc===`2.0`&&t?.method===`tools/call`&&t.params?._meta?.[`mppx/payment-client`]===!0}catch{return!1}}function sa(e){if(typeof e?.body!=`string`)return!1;try{let t=JSON.parse(e.body);return t?.jsonrpc===`2.0`&&t.params?._meta?.[`org.paymentauth/credential`]!=null}catch{return!1}}const ca=1048576,la=new WeakMap;function ua(e){let t=aa(e?.body);if(t===void 0)return;let n=new Headers(e?.headers);if(n.has(`mcp-method`))return t;let r=n.get(`accept`)?.toLowerCase()??``;return r.includes(`application/json`)&&r.includes(`text/event-stream`)?t:void 0}function da(e){if(!e||typeof e!=`object`)return;let t=e,n=t.id;if(t.jsonrpc!==`2.0`||n!==void 0&&typeof n!=`string`&&typeof n!=`number`)return;let r=`error`in t;if(r!==`result`in t)return r?Number.isInteger(t.error?.code)&&typeof t.error?.message==`string`?e:void 0:n!==void 0&&typeof t.result==`object`?e:void 0}function fa(e){if(!e||typeof e!=`object`)return;let t=e?.challenges;if(!Array.isArray(t)||t.length===0)return;let n=[];for(let e of t){if(!Bt.safeParse(e).success)return;if(dn(e))continue;let t=zt.safeParse(e);if(!t.success)return;n.push(t.data)}if(n.length===0)return;let{httpStatus:r,problem:i}=e;return{challenges:n,...typeof r==`number`?{httpStatus:r}:{},...i===void 0?{}:{problem:i}}}function pa(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:fa(e.error.data):fa(e.result?._meta?.[`org.paymentauth/payment-required`])}function ma(e,t){return!e||e.id!==t?[]:pa(e)?.challenges??[]}async function ha(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=$i(e=>{if(!(i||!e.data)&&(i=!0,e.event===`message`))try{a=da(JSON.parse(e.data))}catch{}});try{for(;;){if(i)return a;let{done:e,value:s}=await t.read();if(e)return o.feed(n.decode()),a;if(r+=s.byteLength,r>ca)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function ga(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=``;try{for(;;){let{done:e,value:a}=await t.read();if(e)return da(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>ca)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function _a(e){let t=la.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>ca)){if(t.includes(`application/json`))return ga(e);if(t.includes(`text/event-stream`))return ha(e)}})();return la.set(e,n),n}function va(){return{getChallenges(e,t){let n=ua(t);return e.status===402||n===void 0?[]:_a(e).then(e=>ma(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=yn(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,"org.paymentauth/credential":r}}})}}}}async function ya(e,t){let n=ua(t);if(e.status===402||n===void 0)return!1;let r=await _a(e);return!r||r.id!==n?!1:pa(r)?.problem?.type===ba}const ba=`https://paymentauth.org/problems/invalid-challenge`;function xa(){return{getChallenges(e){let t=e.headers.get(U.wwwAuthenticate);return e.status!==402||!t||!en(t)?[]:nn(e)},setCredential(e,t,n){let r=n?.challenge??Ca(t);return ta(e,r?un(r):U.authorization,t)}}}const Sa=/^Payment [A-Za-z0-9_-]+={0,2}$/;function Ca(e){if(Sa.test(e))try{return yn(e).challenge}catch{return}}function wa(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(In);if(!t)return[];let n=ar(t);return n.accepts.flatMap((e,t)=>{let r=Gn.safeParse(e);if(!r.success)return[];let i=r.data;return Dn(Vt({id:`x402:${t}`,intent:`charge`,method:`evm`,realm:new URL(n.resource.url).host,request:{...i,...n.extensions?{extensions:n.extensions}:{},resource:n.resource}}))})},setCredential(e,t){return ta(e,Ln,t)}}}function Ta(e){return e}function Ea(){let e=[xa(),wa(),va()],t=new WeakMap,n=(e,n)=>{for(let r of n)t.set(r,e);return n},r=(t,r)=>{let i=(a,o)=>{for(let s=a;s<e.length;s++){let a=e[s],c=a.getChallenges(t,r);if(c instanceof Promise)return c.then(e=>i(s+1,[...o,...n(a,e)]));o.push(...n(a,c))}return o};return i(0,[])};return Ta({name:`http`,isPaymentRequired(e,t){if(e.status===402)return!0;let n=r(e,t);return n instanceof Promise?n.then(e=>e.length>0):n.length>0},getChallenges(e,t){return r(e,t)},setCredential(n,r,i){let a=i?.challenge?t.get(i.challenge):void 0,o=e[0];if(!a&&!o)throw Error(`No protocol to attach the credential.`);return(a??o).setCredential(n,r,i)}})}const Da=new WeakMap;function Oa(e,t){return Da.set(e,t),e}function ka(e){return Da.has(e)}function Aa(e,t){return Promise.resolve(Da.get(e)?.(t))}function ja(e){return Da.get(e)}const Ma=new WeakMap,Na=new WeakMap,Pa=new WeakMap,Fa=new WeakMap;function Ia(e,t){return Ma.set(e,t),e}function La(e){Ma.delete(e)}function Ra(e,t,n){Ma.has(e)&&Na.set(t,n)}function za(e){return Na.get(e)}function Ba(e,t){return Promise.resolve(Ma.get(e)?.(t)??t.response)}function Va(e,t){return Fa.set(e,t),e}function Ha(e,t){try{return Fa.get(e)?.(t)}catch{return}}function Ua(e,t){Pa.set(e,t)}function Wa(e){return Pa.get(e)??Na.get(e)?.origin}async function Ga(e,t){let{attempts:n,signal:r}=t;for(let t=1;;t++){r?.throwIfAborted();try{return await e()}catch(e){if(!(e instanceof Ct)||t>=n)throw e;r?.throwIfAborted()}}}function Ka(e,t,n){if(!qa(e)&&(e.method!==`tempo`||e.intent!==`session`))return;t=typeof t==`function`?t():t;let{realm:r}=e;if(r.toLowerCase()===t.hostname.toLowerCase())return;let i=t.origin.toLowerCase();for(let[e,t]of Object.entries(n??{}))if(t===r&&Ja(e)===i)return;throw Error(`Refusing to sign Tempo proof for realm ${JSON.stringify(r)} from ${t.origin}. Pin the realm to this origin with \`trustedTempoProofRealms\` if this server is expected to issue it.`)}function qa(e){if(e.method!==`tempo`||e.intent!==`charge`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function Ja(e){try{return new URL(e).origin.toLowerCase()}catch{return e.toLowerCase()}}const Ya=Symbol.for(`mppx.client.fundsMayHaveMoved`);function Xa(e){return Object.defineProperty(e,Ya,{value:!0}),e}function Za(e){return typeof e==`object`&&!!e&&e[Ya]===!0}const Qa=[4217,42431],$a=[ie,ae,oe],eo=[{network:`stripe`,asset:`usd`,currency:`USD`,decimals:2}],to=`charge`,no=new WeakSet,ro=new WeakMap,io=new WeakSet,ao=/^(\d+)(?:\.(\d+))?$/;function oo(e){let{authorize:t,funders:n=[],maxPayment:r,tokens:i}=e;if(r!==void 0&&Oo(r),t!==void 0&&typeof t!=`function`)throw TypeError(`authorize must be a function.`);if(!Array.isArray(n)||n.some(e=>typeof e?.fund!=`function`))throw TypeError(`funders must be an array of objects with a fund function.`);let a=Lo(i),o=e=>Ao(e,a),s=r!==void 0||t!==void 0||n.length>0,c=r===void 0?`budget`:`maxPayment`;return{limit:c,resolve(e){if(e.intent===to)try{return o(e)}catch{return}},prepare:s?async(e,{method:i,signal:a}={})=>{if(a?.throwIfAborted(),e.intent!==to)throw new wt({limit:c,reason:`intent`});e.expires&&kn(e.expires,e.id);let s=i&&nt(i);if(s?.resumes?.(e))return Object.freeze({settlement:Ro(void 0),constraints:l(!0)});let u=mo(e),d=o(e);r!==void 0&&ko(d,r),s?.assert?.(e);let f=Object.freeze({challenge:So(e),...a?{signal:a}:{}}),p=Object.freeze({requirement:d});no.add(p);let m=Ro(await t?.(p,f)??void 0);try{for(let e of n)a?.throwIfAborted(),await e.fund(d,f);if(a?.throwIfAborted(),mo(e)!==u)throw Error(`Cannot check spending limits: the challenge changed while checked.`);e.expires&&kn(e.expires,e.id)}catch(e){throw m.release(),e}return Object.freeze({settlement:m,constraints:l(!1)})}:void 0};function l(e){let n=Object.freeze({limit:c,resume:e});return ro.set(n,t),n}}function so(e){let t=ot(e);return t!==void 0&&io.has(t)&&ro.has(t)&&ro.get(t)===ro.get(e)}function co(e){return e!==void 0&&(e.maxPayment!==void 0||e.authorize!==void 0||e.funders!==void 0&&e.funders.length>0||e.tokens!==void 0)}function lo(e){let{authorize:t,funders:n,maxPayment:r,tokens:i}=e;return{...t!==void 0&&{authorize:t},...n!==void 0&&{funders:n},...r!==void 0&&{maxPayment:r},...i!==void 0&&{tokens:i}}}function uo(e,t){if(!co(t))return lo(e);if(co(e))throw TypeError(`The fetch passed in already has spending options (maxPayment, authorize, funders or tokens). Set them on one fetch only.`);return t}function fo(e,t){return t?e.then(e=>(t.commit(),e),e=>{throw e instanceof Ct||e instanceof vt||Za(e)?t.commit():t.release(),e}):e}function po(e,t,n,r){let i,a=!1,o,s=()=>i??=Promise.resolve(e.prepare?.(t,{method:r,signal:n})),c=async()=>{if(!e.prepare)return;n?.throwIfAborted();let r=a?void 0:await s();if(r&&!r.constraints.resume)return r.settlement.commit();(await e.prepare(t,{signal:n})).settlement.commit()},l=async()=>{await o,(await i?.catch(()=>void 0))?.settlement.release()};return{prepare:s,async track(e){let r=await s();if(r&&n?.aborted&&(r.settlement.release(),n.throwIfAborted()),r&&!r.constraints.resume&&t.expires)try{kn(t.expires,t.id)}catch(e){throw r.settlement.release(),e}let i=fo(e(r?.constraints),r&&{commit(){a=!0,so(r.constraints)?r.settlement.release():(r.settlement.commit(),r.constraints.resume||io.add(r.constraints))},release(){}});return o=i.then(()=>{},()=>{}),i},commit:c,async commitReplacement(r,i){if(!e.prepare)return;let a=go(r,i);if(!a)throw xo(e);return ho(a)===ho(t)?(await c(),a):(await l(),await po(e,a,n).commit(),a)},release:l}}function mo(e){let{digest:t,expires:n,id:r,intent:i,meta:a,method:o,opaque:s,realm:c,request:l}=e;return JSON.stringify([On(e),r,c,o,i,G(l),n??null,t??null,s??(a===void 0?null:G(a))])}function ho(e){try{return mo(e)}catch{return}}function go(e,t){let n=_o(e,t)??vo(e,t);return n?.length===1?n[0]:void 0}function _o(e,t){let n;try{n=yn(e).challenge}catch{return}let r=ho(n);return r===void 0?[]:t.filter(e=>ho(e)===r)}function vo(e,t){let n;try{n=sr(e)}catch{return}return t.filter(e=>On(e)&&yo(n,e))}function yo(e,t){let n=Gn.safeParse(t.request);if(!n.success)return!1;let r=n.data;try{if(G(r)!==G(e.accepted))return!1;let t=BigInt(r.amount),n=e.payload;if(`authorization`in n)return bo(n.authorization.to,r.payTo)&&BigInt(n.authorization.value)===t;let{permitted:i,witness:a}=n.permit2Authorization;return bo(i.token,r.asset)&&BigInt(i.amount)===t&&bo(a.to,r.payTo)}catch{return!1}}function bo(e,t){return e.toLowerCase()===t.toLowerCase()}function xo(e){return new wt({limit:e.limit,reason:`credential`})}function So(e){let t;try{t=structuredClone(e)}catch{t=JSON.parse(JSON.stringify(e))}return On(e)&&Dn(t),Co(t)}function Co(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Co(t);return e}function wo(e,t){let n=/^0x[\da-fA-F]{40}$/.test(t)||e===`stripe`?t.toLowerCase():t;return JSON.stringify([e,n])}function To(e,t){let[,n=`0`,r=``]=ao.exec(e)??[];return BigInt(`${n}${r.slice(0,t).padEnd(t,`0`)}`)}function Eo(e,t){let{currency:n,value:r}=e??{};if(typeof n!=`string`||!n.trim())throw TypeError(`${t} currency must be a non-empty string.`);if(typeof r!=`string`||r.length>1024||!ao.test(r))throw TypeError(`${t} value must be a non-negative decimal string.`)}function Do(e){if(typeof e!=`object`||!e)return!1;let{amount:t,asset:n,network:r}=e;return typeof r==`string`&&r.length>0&&typeof n==`string`&&n.length>0&&typeof t==`bigint`&&t>=0n}function Oo(e){if(!Array.isArray(e))return Eo(e,`maxPayment`);let t=new Set;for(let n of e){if(!Do(n))throw TypeError(`Each maxPayment limit needs a network, an asset and a bigint amount.`);let e=wo(n.network,n.asset);if(t.has(e))throw TypeError(`Duplicate maxPayment limit for ${n.asset}.`);t.add(e)}}function ko(e,t){let n=e=>new wt({limit:`maxPayment`,reason:e});if(Array.isArray(t)){let r=wo(e.network,e.asset),i=t.find(e=>wo(e.network,e.asset)===r);if(!i)throw n(`asset`);if(e.amount>i.amount)throw n(`amount`);return}let r=t,{currency:i,decimals:a}=e;if(i===void 0||a===void 0||i.toUpperCase()!==r.currency.toUpperCase())throw n(`asset`);if(e.amount>To(r.value,a))throw n(`amount`)}function Ao(e,t){let n=On(e)?Mo(e):No(e),r=t.get(wo(n.network,n.asset)),i={method:e.method,intent:e.intent,...n,...r?{currency:r.currency,decimals:r.decimals}:{}};return Object.defineProperty(i,"toJSON",{value:jo}),Object.freeze(i)}function jo(){return{...this,amount:this.amount.toString(),...this.splits&&{splits:this.splits.map(e=>({...e,amount:e.amount.toString()}))}}}function Mo(e){let t=Gn.safeParse(e.request);if(!t.success)throw Error(`Cannot check spending limits: invalid x402 requirements.`);let{amount:n,asset:r,network:i,payTo:a}=t.data;return{protocol:`x402`,network:i,asset:r,amount:Io(n),recipient:a}}function No(e){let t=e.request,n=typeof t.methodDetails==`object`&&t.methodDetails!==null?t.methodDetails:{},r=n.chainId;if(r!==void 0&&(!Number.isSafeInteger(r)||r<=0))throw Error(`Cannot check spending limits: invalid challenge chain ID.`);if(t.chainId!==void 0&&t.chainId!==r)throw Error(`Cannot check spending limits: challenge names a chain outside methodDetails.chainId.`);let i=t.currency;if(typeof i!=`string`||!i)throw Error(`Cannot check spending limits: challenge names no currency.`);let a=Io(t.amount),o=Po(e.method,t,n),s=Fo(n.splits,a);return{protocol:`mpp`,network:r===void 0?e.method:`eip155:${r}`,asset:i,amount:a,...o===void 0?{}:{recipient:o},...s?{splits:s}:{}}}function Po(e,t,n){if(e===`stripe`){if(typeof n.networkId!=`string`||!n.networkId)throw Error(`Cannot check spending limits: Stripe challenge names no networkId.`);return n.networkId}return typeof t.recipient==`string`?t.recipient:void 0}function Fo(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)throw Error(`Cannot check spending limits: invalid payment splits.`);let n=0n,r=e.map(e=>{let{amount:t,recipient:r}=e??{};if(typeof r!=`string`||!r)throw Error(`Cannot check spending limits: payment split names no recipient.`);let i=Io(t);return n+=i,Object.freeze({recipient:r,amount:i})});if(n>=t)throw Error(`Cannot check spending limits: payment splits are not less than the amount.`);return Object.freeze(r)}function Io(e){if(typeof e!=`string`||!/^\d+$/.test(e))throw Error(`Cannot check spending limits: challenge amount is not an atomic integer.`);return BigInt(e)}function Lo(e){let t=new Map;for(let e of $a)for(let n of Qa){let r=e.addresses[n];r&&t.set(wo(`eip155:${n}`,r),{currency:e.currency,decimals:e.decimals})}for(let{asset:e,currency:n,decimals:r,network:i}of eo)t.set(wo(i,e),{currency:n,decimals:r});if(e===void 0)return t;if(!Array.isArray(e))throw TypeError(`tokens must be an array.`);let n=new Map;for(let t of e){let{currency:e,decimals:r}=t??{};if(typeof e!=`string`||!e.trim())throw TypeError(`Each token needs a currency, such as USD.`);if(typeof r!=`number`||!Number.isInteger(r)||r<0||r>255)throw TypeError(`Token decimals must be an integer from 0 to 255.`);let i=typeof t==`function`?Object.entries(t.addresses).map(([e,t])=>[Number(e),t]):[[t.chainId,t.address]];for(let[t,a]of i){if(!Number.isSafeInteger(t)||t<=0||typeof a!=`string`||!a)throw TypeError(`Each token needs an address and a chain ID.`);let i=wo(`eip155:${t}`,a),o=n.get(i);if(o&&(o.currency.toUpperCase()!==e.toUpperCase()||o.decimals!==r))throw TypeError(`tokens configure conflicting metadata for ${a}.`);n.set(i,Object.freeze({currency:e,decimals:r}))}}for(let[e,r]of n)t.set(e,r);return t}function Ro(e){let t=!0,n=n=>{t&&(t=!1,n?.call(e))};return Object.freeze({commit:()=>n(e?.commit),release:()=>n(e?.release)})}const zo=Symbol.for(`mppx.fetch.wrapper`),Bo=Symbol.for(`mppx.fetch.identity`),Vo=Symbol.for(`mppx.fetch.spend`),Ho=Symbol.for(`mppx.fetch.skipPayment`);function Uo(e={}){return{...e,[Ho]:!0}}const Wo=65536,Go=new WeakMap;async function Ko(e){if(!e.body)return e;let t=e.clone().body.getReader(),n=[],r=0,i=!1,a=setTimeout(()=>{i=!0,t.cancel().catch(()=>{})},2e3);try{for(;;){let{done:e,value:a}=await t.read();if(e)break;if(n.push(a),r+=a.byteLength,r>Wo){i=!0;break}}}finally{clearTimeout(a),t.cancel().catch(()=>{})}if(!i)return e;e.body.cancel().catch(()=>{});let o=new Headers(e.headers);o.delete(`content-length`),o.set(`Mppx-Body-Truncated`,`true`);let s=new Response(new Blob(n).slice(0,Wo),{headers:o,status:e.status,statusText:e.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{value:e[t]});return s}async function qo(e,t){let n=e?.attempt.settle;if(!n)return t.status!==`pending`;e.attempt.settle=void 0;let r=await n(t);return r||(e.attempt.settle=n),r}function Jo(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=3,methods:a,onChallenge:o,orderChallenges:s,transport:c=Ea(),trustedTempoProofRealms:l}=e,u=e.identity??(e.fetch&&_s(e.fetch)),d=e.eventDispatcher??Xo(),f=t??ki(a),p=uo(e,e.fetch&&vs(e.fetch)),m=oo(p),h=ys(r),g=async(e,t,n)=>u?u.send((e,n)=>h(e,t?.[Ho]?Uo(n):n),new Request(e,t),n):{response:await h(e,t),headers:[]},_=async(e,t,r)=>{let p=gs(e,t?.headers),v=p.has(U.acceptPayment),y=Ts(p,f),b=xs(e,t),x=ms(e,t,p,m.prepare?b:void 0),S=ps(e,t,p,y.header,v,n);if(m.prepare){let e=await x;if(b?.throwIfAborted(),oa(hs(S.init,e)))throw TypeError(`This fetch has spending options (maxPayment, authorize or funders), but McpClient.wrap pays MCP tool calls itself. Set them on McpClient.wrap and give its transport a fetch without them.`)}let C=await g(bs(S.input),S.init),w=C.response,ee=C.headers,T=hs(S.init,await x);if(t?.[Ho]||oa(T)||!await c.isPaymentRequired(w,T))return w;let te=t?.context,{context:ne,orderChallenges:re,...E}=T??{},D=Ls(p)||sa(T),O,k,A,j,M;try{for(let n=0;n<i;n++){if(k=await c.getChallenges(w,T),(n>0||D)&&await Is(w,T))return await qo(j,{challenges:k,response:w,status:`rejected`}),w;let f=(await Es(Mi(k,a,y.entries,te),re??s))[0];if(!f){if(await qo(j,{challenges:k,response:w,status:`rejected`}),n>0)return w;throw Error(sn(`No method found for challenges: ${k.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`,Ps(w)))}let p=f.challenge;O=p,A=f.method,O.expires&&kn(O.expires,O.id),await u?.challenge(w,{challenge:p},As(S.input).href);let v=await Ns(w,S.input,S.input,E);Ka(p,()=>As(v),l);let b=j,x=Fs(p),C=b?.method===f.method&&b?.key===x,ne=!1;if(b){let e=await qo(b,{challenges:k,response:w,status:C?`pending`:`rejected`});ne=C&&!e}j=ne?b:void 0;let N=po(m,p,xs(e,t),f.method),P,F=ts(async n=>{if(n===void 0&&ne&&b)return P=b.promise,b.promise;ne&&b&&(await qo(b,{status:`rejected`}),j=void 0),xs(e,t)?.throwIfAborted();let r=n??te;if(!ka(f.method))return P=N.track(n=>Ga(()=>ws(p,f.method,r,js(v),n),{attempts:i,signal:xs(e,t)})),P;let a={origin:As(v).origin,prepare:()=>Aa(f.method,{challenge:p,context:r,fetch:u?wi(h,u,{challenge:p}):h,input:v,signal:xs(e,t)})},o=N.track(e=>a.prepare().then(()=>ws(p,f.method,r,a,e)));return P=o,j={context:r,attempt:a,key:n===void 0?x:void 0,method:f.method,promise:o},o}),I,L,R,z=!1;try{let n=await d.emit(`challenge.received`,ns({challenge:p,challenges:k,createCredential:F,init:t,input:e,method:f.method,response:w}))??(o?await o(O,{createCredential:F}):void 0);if(n===!1)return await N.release(),await qo(j,{challenges:k,response:w,status:`rejected`}),j=void 0,w;I=n??await F(),L=j,L&&await L.promise.catch(()=>void 0)!==I&&(await qo(L,{status:`rejected`}),j=void 0),Cs(I),z=P!==void 0&&await P.catch(()=>void 0)===I,z||(R=await N.commitReplacement(I,k))}catch(e){throw await N.release(),e}let ie=j?j.context:te,ae=Ss(I,p);await d.emit(`credential.created`,rs({challenge:p,credential:I,init:t,input:e,method:f.method,response:w}));let oe=e=>new _t({cause:e,challenge:p,credential:I,transactionHash:Ha(f.method,I)});try{({response:w,headers:ee}=await g(v,{...c.setCredential({...E,headers:S.headers},I,{challenge:R??p}),redirect:`manual`},{challenge:ae,headers:ee}))}catch(e){throw M=oe(e),e}let B=await c.isPaymentRequired(w,T);if(B||(await qo(L,{response:w,status:w.status>=300&&w.status<400?`pending`:w.ok?`accepted`:`rejected`}),j=void 0),w.ok&&Zo(d,`payment.response`)){let n=z?p:R??go(I,k);await d.emit(`payment.response`,is({challenge:p,credential:I,init:t,input:e,method:f.method,requirement:n&&m.resolve(n),response:w}))}if(!B){if(w.status>=500&&Zo(d,`payment.failed`)){try{w=await Ko(w)}catch(e){throw M=oe(e),w=new Response(null,{headers:w.headers,status:w.status,statusText:w.statusText}),e}await d.emit(`payment.failed`,as({challenge:p,challenges:k,error:oe(),init:t,input:e,method:f.method,response:w}))}return w.ok?Ba(f.method,{context:ie,challenge:p,credential:I,fetch:h,headers:S.headers,input:v,...r?{refetch:()=>_(bs(S.input),t,!1)}:{},response:w,signal:xs(e,t)}):w}}k=void 0;try{k=await c.getChallenges(w,T)}catch{}return await qo(j,{challenges:k,response:w,status:`rejected`}),w}catch(n){throw await qo(j,{challenges:k,response:w,status:`rejected`}),await d.emit(`payment.failed`,as({challenge:O,challenges:k,error:M??n,init:t,input:e,method:A,response:w})),n}},v=(e,t)=>_(e,t,!0);return v[zo]=h,u&&(v[Bo]=u),co(p)&&(v[Vo]=p),v}function Yo(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return Array.isArray(e)?Object.fromEntries(e):e}function Xo(){let e={"*":new Set,"challenge.received":new Set,"credential.created":new Set,"payment.failed":new Set,"payment.response":new Set},t={async emit(t,n){switch(t){case`challenge.received`:{let r;for(let t of e[`challenge.received`]){let e=await Qo(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await es(e[`*`],t,n),r}case`credential.created`:await $o(e[`credential.created`],n),await es(e[`*`],t,n);return;case`payment.failed`:await $o(e[`payment.failed`],n),await es(e[`*`],t,n);return;case`payment.response`:await $o(e[`payment.response`],n),await es(e[`*`],t,n);return}},on:(t,n)=>{switch(t){case`*`:case`challenge.received`:case`credential.created`:case`payment.failed`:case`payment.response`:return e[t].add(n),()=>e[t].delete(n);default:throw Error(`Unknown client event "${String(t)}".`)}}};return Go.set(t,t=>e[t].size>0||e[`*`].size>0),t}function Zo(e,t){return Go.get(e)?.(t)??!0}async function Qo(e,t){try{return await e(t)}catch{return}}async function $o(e,t){for(let n of e)try{await n(t)}catch{}}async function es(e,t,n){await $o(e,Object.freeze({name:t,payload:n}))}function ts(e){let t;return n=>(t??=e(n),t)}function ns(e){return Object.freeze({challenge:us(e.challenge),challenges:e.challenges.map(e=>us(e)),createCredential:e.createCredential,init:os(e.init),input:ss(e.input),method:cs(e.method),response:ls(e.response)})}function rs(e){return Object.freeze({challenge:us(e.challenge),credential:e.credential,init:os(e.init),input:ss(e.input),method:cs(e.method),...e.response===void 0?{}:{response:ls(e.response)}})}function is(e){let{requirement:t,response:n}=e,r=n instanceof Response?Zi(n):void 0;return Object.freeze({...t?{amount:t.amount.toString(),requirement:t}:{},...r?{receipt:r}:{},challenge:us(e.challenge),credential:e.credential,init:os(e.init),input:ss(e.input),method:cs(e.method),response:ls(e.response)})}function as(e){return Object.freeze({...e.challenge?{challenge:us(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>us(e))}:{},error:e.error,init:os(e.init),input:ss(e.input),...e.method?{method:cs(e.method)}:{},...e.response===void 0?{}:{response:ls(e.response)}})}function os(e){if(e)return fs({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function ss(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function cs(e){return fs(Object.assign({},e))}function ls(e){if(e instanceof Response)try{return e.clone()}catch{let t=new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText});for(let n of[`redirected`,`type`,`url`])Object.defineProperty(t,n,{value:e[n]});return t}return us(e)}function us(e){try{return ds(structuredClone(e))}catch{return fs(e)}}function ds(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))ds(t);return e}function fs(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function ps(e,t,n,r,i,a){let o=!!r&&!i&&Ds(e,a);if(!o)return{headers:n,init:t,input:e};let s=new Headers(e instanceof Request?e.headers:void 0);return n.forEach((e,t)=>{s.set(t,e)}),s.set(U.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function ms(e,t,n,r){if(!(!(e instanceof Request)||t?.body!==void 0||!e.body||e.bodyUsed)){if(!n.has(`mcp-method`)){let e=n.get(`accept`)?.toLowerCase()??``;if(!e.includes(`application/json`)||!e.includes(`text/event-stream`))return}try{let t=e.clone();return(r&&t.body?new Response(t.body.pipeThrough(new TransformStream,{signal:r})):t).text().catch(()=>void 0)}catch{return}}}function hs(e,t){return t===void 0?e:{...e,body:t}}function gs(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function _s(e){return e[Bo]}function vs(e){return e[Vo]}function ys(e){let t=e;for(;t[zo];)t=t[zo];return t}function bs(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function xs(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function Ss(e,t){try{let{challenge:n}=yn(e);return n.id===t.id?t:{...n,...t.header!==void 0&&{header:t.header}}}catch{return t}}function Cs(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
|
|
7
|
-
`))throw Error(`Credential header value contains illegal newline characters`)}async function ws(e,t,n,r,i){let a=t.context&&n!==void 0?t.context.parse(n):void 0,o=a===void 0?{challenge:e}:{challenge:e,context:a};return i&&rt(o,i),r?.origin&&Ua(o,r.origin),r&&`prepare`in r&&Ra(t,o,r),t.createCredential(o)}function Ts(e,t){let n=e.get(U.acceptPayment);if(!n)return t;try{return{...t,entries:Ai(n),header:n}}catch{return t}}async function Es(e,t){return t?t(e):e}function Ds(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=As(e);return t===`same-origin`?!ks()||n.origin===globalThis.location.origin:t.origins.some(e=>Os(n,e))}function Os(e,t){if(t.startsWith(`*.`)){let n=t.slice(1);return e.hostname.endsWith(n)||e.hostname===t.slice(2)}return e.origin===new URL(t).origin}function ks(){return globalThis.location!==void 0}function As(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,ks()?globalThis.location.href:void 0)}function js(e){try{return{origin:As(e).origin}}catch{return}}function Ms(e,t){let n=e instanceof Request?e:void 0;if((t.mode??n?.mode)===`no-cors`)throw Error(`Cannot automatically pay a no-cors request: it cannot carry a credential.`);if((t.cache??n?.cache)===`only-if-cached`)throw Error(`Cannot automatically pay an only-if-cached request: its retry cannot reach the server.`)}async function Ns(e,t,n,r){if(Ms(t,r),!e.url)return t;let i=new URL(e.url),a=As(n);if(i.origin!==a.origin)throw Error(`Refusing to send payment credential across redirect from ${a.origin} to ${i.origin}`);let o=(r.method??(t instanceof Request?t.method:`GET`)).toUpperCase();if(e.redirected&&o!==`GET`&&o!==`HEAD`)throw Error(`Cannot automatically pay a redirected ${o} request. Use prepareRequest() to preserve redirect semantics.`);if(t instanceof Request){let n=r.body==null?t.clone():t,i=new Request(n,t.mode===`navigate`&&r.mode===void 0?{...r,mode:`same-origin`}:r);return i.url.split(`#`)[0]===e.url?i:i.body?new Request(e.url,{body:await i.arrayBuffer(),cache:i.cache,credentials:i.credentials,headers:i.headers,integrity:i.integrity,keepalive:i.keepalive,method:i.method,mode:i.mode,redirect:i.redirect,referrer:i.referrer,referrerPolicy:i.referrerPolicy,signal:i.signal}):new Request(e.url,i)}return e.url}function Ps(e){return!(e instanceof Response)||e.status!==402?0:on(e.headers.get(U.wwwAuthenticate))}function Fs(e){let{description:t,...n}=e;return j.canonicalize(n)}async function Is(e,t){if(!(e instanceof globalThis.Response))return!1;if(await ya(e,t))return!0;if(!e.headers.get(`Content-Type`)?.includes(`application/problem+json`))return!1;try{return(await e.clone().json()).type===`https://paymentauth.org/problems/invalid-challenge`}catch{return!1}}function Ls(e){return e.get(U.paymentAuthorization)?!0:/(^|,)\s*Payment\s+\S/i.test(e.get(U.authorization)??``)}function Rs(e={}){let{account:t}=e;return(e,{account:n}={})=>{let r=n??t;if(!r){if(!e.account)throw Error("No `account` provided. Pass `account` to parameters or context.");return e.account}return fe(r)}}function zs(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}const Bs={[R.id]:R,[z.id]:z};function Vs(e,t={}){return u(e.url,{fetchFn:e.fetch,fetchOptions:{headers:zs(e)},...t})}function Hs(r){let{chain:i,getClient:a,remoteFeePayer:o,rpcUrl:s}=r;return a?!i?.serializers&&!o&&!r.requireChain?a:async e=>{let s=await a(e);if(r.requireChain&&(s.chain?.id===void 0||s.chain.id!==e.chainId))throw Error(`Subscription chain mismatch: expected ${e.chainId}, got ${s.chain?.id??`unknown`}.`);let c=s;if(o&&s.transport.key!==`feePayer`){let e=s.request.bind(s),r=de(n({request:t=>e(t)},{retryCount:0}),Vs(o,{retryCount:s.transport.retryCount}))({account:s.account,chain:s.chain,pollingInterval:s.pollingInterval,retryCount:0}),i=t({...r.config,retryCount:0},r.value);c=Object.assign({},s,{request:i.request,transport:{...i.config,...i.value}})}return!i?.serializers||c.chain?.serializers?.transaction?c:Object.assign({},c,{chain:{...i,...e.chainId===void 0?{}:{id:e.chainId},...c.chain,formatters:c.chain?.formatters??i.formatters,prepareTransactionRequest:c.chain?.prepareTransactionRequest??i.prepareTransactionRequest,serializers:c.chain?.serializers?.transaction?c.chain.serializers:i.serializers}})}:({chainId:t})=>{if(!s)throw Error("No `rpcUrl` provided.");let n=t||Number(Object.keys(s)[0]),r=s[n];if(!r)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let a=o?de(u(r),Vs(o)):u(r);return e({chain:Bs[n]??{...i,id:n},transport:a})}}function Us(e,t){if(t!==void 0&&e.chain?.id!==void 0&&e.chain.id!==t)throw Error(`Chain ID mismatch: expected ${t}, got ${e.chain.id}.`)}function Ws(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}const Gs=A.slice(k.keccak256(O.fromString(`mpp`),{as:`Hex`}),0,4);function Ks(e){let t=k.keccak256(O.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,10))}function qs(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(A.toBytes(Gs),0),i[4]=1,i.set(Ks(t),5),n&&i.set(Ks(n),15),i.set(Js(r),25),A.fromBytes(i)}function Js(e){let t=k.keccak256(O.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,7))}function Ys(e,t){return _e.resolve(e).toLowerCase()===_e.resolve(t).toLowerCase()}const Xs=10000n,Zs=[Vr.pathUsd,Vr.usdc,Vr.ousd];async function Qs(e,t){let{account:n,amountOut:r,tokenOut:i,tokenIn:a,slippage:o}=t;if(!Number.isFinite(o)||o<0||o>50)throw Error(`Auto-swap slippage must be between 0 and 50 percent.`);if(t.maxAmountIn!==void 0&&t.maxAmountIn<=0n)throw Error(`Auto-swap maxAmountIn must be positive.`);let s=e.chain?.id,c=[];for(let e of a){let t=typeof e==`string`?e:s===void 0?void 0:De(e,{chainId:s})?.address;!t||Ys(t,i)||c.some(e=>Ys(e,t))||c.push(t)}let l=await Promise.allSettled([x(e,{...V.token.getBalance.call(e,{account:n,token:i}),account:null}),...c.map(t=>x(e,{...V.token.getBalance.call(e,{account:n,token:t}),account:null}))]),u=l[0];if(u.status!==`fulfilled`)throw u.reason;let d=u.value;if(d>=r)return;let f=r-d,p=BigInt(Math.round(o*100)),m=t.maxAmountIn??f+f*p/Xs;for(let t=0;t<c.length;t++){let n=l[t+1];if(n.status!==`fulfilled`)continue;let r=n.value;if(r<=0n)continue;let a=c[t];try{let t=await V.dex.getBuyQuote(e,{account:null,tokenIn:a,tokenOut:i,amountOut:f});if(t<=0n||t>m)continue;let n=t+t*p/Xs,o=n<m?n:m;if(r>=o)return[V.token.approve.call(e,{amount:o,spender:ce.stablecoinDex,token:a}),V.dex.buy.call({tokenIn:a,tokenOut:i,amountOut:f,maxAmountIn:o})]}catch{}}throw new ec({currency:i})}function $s(e,t){return e?e===!0?{tokenIn:t,slippage:1}:{tokenIn:e.tokenIn?[...e.tokenIn,...e.fallback===!1?[]:t.filter(t=>!e.tokenIn.some(e=>typeof e==`string`&&Ys(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var ec=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}};function tc(e){let t=BigInt(e.amount),n=e.methodDetails?.splits??[],r=n.reduce((e,t)=>e+BigInt(t.amount),0n);if(r>=t)throw Error(`Invalid charge request: split total must be less than total amount.`);let i=t-r;if(i<=0n)throw Error(`Invalid charge request: primary transfer amount must be positive.`);return[{amount:i.toString(),memo:e.methodDetails?.memo,recipient:e.recipient},...n.map(e=>({amount:BigInt(e.amount).toString(),memo:e.memo,recipient:e.recipient}))]}function nc(e,t,n){t&&(n&&!n.some(e=>Ys(e,t))||e.some(e=>Ys(e,t))||e.push(t))}async function rc(e,t,n){try{return(await V.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function ic(e){let t=e.chain?.feeToken;if(t)return le.toAddress(t);let n=e.chain?.id;return n?Hr[n]:void 0}function ac(e){let t=[];return nc(t,Vr.pathUsd),nc(t,Hr[e]),t}async function oc(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])nc(o,e,n);if(nc(o,await V.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),nc(o,ic(i),n),!a)for(let e of r??[])nc(o,e,n);for(let e of o)if(await rc(i,t,e))return e;return o[0]}const sc=m([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`]);function cc(e){if(e!==void 0)return Ur[e]}function lc(e){let t=cc(e.chainId);return!!t&&d(e.currency,{strict:!1})&&f(e.currency,t.token)}function uc(e){let t=cc(e.chainId),n=e.transfers.length===1?e.transfers[0]:void 0;if(!t||!n?.memo)return;let r=BigInt(n.amount),a=n.memo;return{calls:[{data:i({abi:B.tip20,functionName:`approve`,args:[t.swap,r]}),to:t.token},{data:i({abi:sc,functionName:`swapTo`,args:[t.token,r,e.currency,n.recipient,a]}),to:t.swap}],settlementSender:t.swap,transfers:[{amount:r,memo:a,recipient:n.recipient}]}}async function dc(e,t){let n=uc(t);if(n)try{return await x(e,V.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await _(e,{account:t.account,calls:n.calls}),n)}catch{return}}const fc=10n**BigInt(4);function pc(e={}){let{address:t,amount:n,chainId:r=Z.mainnet}=e;if(r!==Z.mainnet)return;let i=new URL(`https://wallet.tempo.xyz/agent?action=fund&intent=mach&chainId=4217`);if(t&&d(t,{strict:!1})&&i.searchParams.set(`address`,c(t)),n!==void 0&&n>0n){let e=(n+fc-1n)/fc,t=e%100n,r=(e/100n).toString();i.searchParams.set(`amount`,t===0n?r:`${r}.${t.toString().padStart(2,`0`).replace(/0$/,``)}`)}return i.toString()}async function mc(e,t){let n=cc(t.chainId);if(!n)return;let r=await x(e,V.token.getBalance.call(e,{account:t.account,token:n.token})).catch(()=>void 0);return typeof r==`bigint`?r:void 0}async function hc(e,t){let{account:n,amount:r,chainId:i}=t,a=await mc(e,{account:n,chainId:i});if(a===void 0||a>=r)return;let s=e=>`${o(e,6)} MACH`,c=r-a;return{fundingUrl:pc({address:n,amount:c,chainId:i}),reason:`requested ${s(r)}, available ${s(a)}`,shortfall:c}}async function gc(e,t){let n=await hc(e,t);if(n)return new Tt({fundingUrl:n.fundingUrl,reason:n.reason})}const _c={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]};function vc(e){return{name:`MPP`,version:`3`,chainId:e}}function yc(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function bc(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:vc(n),types:_c,primaryType:`Proof`,message:yc({account:t,challengeId:r,realm:i})}}function xc(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const Sc=[...B.accountKeychain.filter(e=>e.type===`error`),...B.tip20.filter(e=>e.type===`error`)];function Cc(e){let t=new Set,n=e;for(;typeof n==`object`&&n&&!t.has(n);){t.add(n);let e=n.data;if(Ec(e))return e;let r=e?.data;if(Ec(r))return r;n=n.cause}}function wc(e,t){let n=Cc(e);if(!n)return;let i=(()=>{try{return r({abi:Sc,data:n})}catch{return}})();if(i?.errorName===`SpendingLimitExceeded`){let n=t.account.accessKeyAddress;return new St({accessKey:typeof n==`string`?n:void 0,account:t.account.address,cause:e})}if(i?.errorName===`InsufficientBalance`){let[n,r,a]=i.args;return new Tt({cause:e,reason:`${t.account.address} holds ${n} of token ${a}, but the payment requires ${r}`})}}async function Tc(e,t){try{return await t()}catch(t){throw wc(t,e)??t}}function Ec(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{8}/.test(e)}const Dc=7200n,Oc=64n,kc=s({abi:B.zonePortal,name:`WithdrawalProcessed`});function Ac(e){return Number.isInteger(e)&&e>0&&e<4217e5}function jc(e,t){return Ac(t)?e===!0||(e?.includes(t)??!1):!1}function Mc(e){return ce.zonePortal(e)}Mc(0).slice(0,-16).toLowerCase();function Nc(e){if(e>=2**32)return e%2**32;if(e>142431e4&&e<142432e4)return e-142431e4;if(e>4217e5&&e<42171e4)return e-4217e5;throw Error(`Cannot derive a Zone ID from chain ID ${e}. Pass \`zoneId\`.`)}function Pc(e){if(e>=2**32)return Math.floor(e/2**32);if(e>142431e4&&e<142432e4)return 42431;if(e>4217e5&&e<42171e4)return 4217}function Fc(e){return k.keccak256(E.encodePacked([`address`,`bytes32`,`uint64`],[e.sender,e.transactionHash,e.fallbackNonce]))}async function Ic(e,t){let{blockNumber:n,sender:r,transactionHash:i}=t,a=t=>x(e,{abi:B.zoneOutbox,address:ce.zoneOutbox,blockNumber:t,functionName:`lastFallbackNonce`}),[o,s]=await Promise.all([a(n-1n),a(n)]);if(s<=o)throw Error(`Zone withdrawal transaction ${i} did not request a withdrawal from the outbox.`);if(s-o>Oc)throw Error(`Zone withdrawal transaction ${i} has ${s-o} candidate sender tags, more than ${Oc}.`);let c=[];for(let e=o+1n;e<=s;e++)c.push(Fc({fallbackNonce:e,sender:r,transactionHash:i}));return c}async function Lc(e,t){let{senderTags:n,timeoutMs:r=6e4}=t;if(!Number.isFinite(r)||r<0)throw Error(`Zone settlement timeout must be a finite, non-negative number.`);if(n.length===0)throw Error(`Zone settlement needs at least one sender tag.`);let i=await v(e,{cacheTime:0}),a=i>Dc?i-Dc:0n,o=Date.now()+r;for(;;){if(a<=i){let[r]=await y(e,{address:t.portal,event:kc,args:{senderTag:[...n],...t.to?{to:t.to}:{}},fromBlock:a,toBlock:i});if(r?.transactionHash&&r.args.senderTag)return{hash:r.transactionHash,senderTag:r.args.senderTag};a=i+1n}if(Date.now()+500>o)throw Error(`Zone withdrawal ${n.join(` or `)} did not settle on Tempo within ${r}ms.`);await new Promise(e=>setTimeout(e,500)),i=await v(e,{cacheTime:0})}}const Rc=[`push`,`pull`],zc=K.object({amount:q(),memo:K.optional(Mt()),recipient:K.pipe(K.string(),K.transform(e=>e))}),Bc=(1n<<64n)-1n,Vc={dev_second:1n,day:86400n,week:604800n},Hc=K.pipe(J(),K.transform(e=>e.toLowerCase())),Uc=K.object({accessKeyAddress:Hc,keyType:K.enum([`p256`,`secp256k1`,`webAuthn`]),keyToken:K.optional(K.pipe(K.string().check(K.regex(/^0x[0-9a-fA-F]{120}$/)),K.transform(e=>e)))}),Wc=K.object({accessKey:K.optional(Uc),chainId:K.optional(K.number())}),Gc=kt(`subscriptionExpires must be a valid date`).check(K.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),Kc=K.enum([`dev_second`,`day`,`week`]),qc=K.pipe(K.union([K.string(),K.bigint(),K.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),K.transform(e=>e.toString())).check(K.regex(/^[1-9]\d*$/,`Invalid periodCount`),K.refine(e=>{try{return BigInt(e)<=Bc}catch{return!1}},`periodCount exceeds uint64`));function Jc(e){return K.refine(e=>{let{amount:t,decimals:n}=e;return g(t,n)>0n},e)}function Yc(e){let{periodCount:t,periodUnit:n}=e;try{let e=Vc[n];return e!==void 0&&BigInt(t)*e<=Bc}catch{return!1}}const Xc=jn({name:`tempo`,intent:`charge`,schema:{credential:{payload:K.discriminatedUnion(`type`,[K.object({hash:Mt(),type:K.literal(`hash`)}),K.object({signature:Y(),type:K.literal(`transaction`)}),K.object({signature:Y(),type:K.literal(`proof`)}),K.object({hash:Mt(),senderTag:Mt(),type:K.literal(`zone`),zoneId:K.number().check(K.refine(Ac,`Invalid Zone ID`))})])},request:K.pipe(K.object({machineTokenEnabled:K.optional(K.boolean()),amount:q(),chainId:K.optional(K.number()),currency:K.string(),decimals:K.number(),description:K.optional(K.string()),externalId:K.optional(K.string()),feePayer:K.optional(K.pipe(K.union([K.boolean(),K.custom()]),K.transform(e=>typeof e==`object`||e))),memo:K.optional(K.never()),recipient:K.optional(K.string()),splits:K.optional(K.array(zc).check(K.minLength(1),K.maxLength(10))),supportedModes:K.optional(K.array(K.enum(Rc)).check(K.minLength(1))),zones:K.optional(K.union([K.literal(!0),K.array(K.number().check(K.refine(Ac,`Invalid Zone ID`))).check(K.minLength(1))]))}).check(K.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=g(e,t),i=n.reduce((e,n)=>e+g(n.amount,t),0n);return n.every(e=>g(e.amount,t)>0n)&&i<r},`Invalid splits`)),K.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,zones:c,...l})=>({...l,amount:g(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==void 0||c!==void 0?{methodDetails:{...e!==void 0&&{machineTokenEnabled:e},...n!==void 0&&{chainId:n},...i!==void 0&&{feePayer:i},...o!==void 0&&{splits:o.map(e=>({...e,amount:g(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s},...c!==void 0&&{zones:c}}}:{}})))}}),Zc=jn({name:`tempo`,intent:`session`,schema:{credential:{payload:K.discriminatedUnion(`action`,[K.object({action:K.literal(`open`),authorizedSigner:K.optional(K.string()),channelId:Mt(),cumulativeAmount:q(),descriptor:K.optional(K.custom()),signature:Y(),transaction:Y(),type:K.literal(`transaction`)}),K.object({action:K.literal(`topUp`),additionalDeposit:q(),channelId:Mt(),descriptor:K.optional(K.custom()),transaction:Y(),type:K.literal(`transaction`)}),K.object({action:K.literal(`voucher`),channelId:Mt(),cumulativeAmount:q(),descriptor:K.optional(K.custom()),signature:Y()}),K.object({action:K.literal(`close`),channelId:Mt(),closeSignature:Y(),cumulativeAmount:q(),descriptor:K.optional(K.custom()),signature:Y()})])},request:K.pipe(K.object({amount:q(),chainId:K.optional(K.number()),channelId:K.optional(Mt()),configurableVouchers:K.optional(K.boolean()),currency:K.string(),decimals:K.number(),escrowContract:K.optional(K.string()),feePayer:K.optional(K.pipe(K.union([K.boolean(),K.custom()]),K.transform(e=>typeof e==`object`||e))),feeToken:K.optional(J()),minVoucherDelta:K.optional(q()),operator:K.optional(J()),recipient:K.optional(K.string()),sessionProtocol:K.optional(K.enum([dt.v2,dt.v1])),sessionSnapshot:K.optional(K.custom()),suggestedDeposit:K.optional(q()),unitType:K.string()}).check(K.refine(({amount:e,decimals:t})=>g(e,t)>0n,`Session amount must be greater than 0`)),K.transform(({amount:e,chainId:t,channelId:n,configurableVouchers:r,decimals:i,escrowContract:a,feePayer:o,feeToken:s,minVoucherDelta:c,operator:l,sessionProtocol:u,sessionSnapshot:d,suggestedDeposit:f,...p})=>({...p,amount:g(e,i).toString(),...f?{suggestedDeposit:g(f,i).toString()}:{},methodDetails:{escrowContract:a,...n!==void 0&&{channelId:n},...c!==void 0&&{minVoucherDelta:g(c,i).toString()},...t!==void 0&&{chainId:t},...o!==void 0&&{feePayer:o},...s!==void 0&&{feeToken:s},...l!==void 0&&{operator:l},...r!==void 0&&{configurableVouchers:r},...u!==void 0&&{[ut.sessionProtocol]:u},...d!==void 0&&{[ut.sessionSnapshot]:d}}})))}}),Qc=jn({name:`tempo`,intent:`subscription`,schema:{credential:{payload:K.object({signature:Y(),type:K.literal(`keyAuthorization`)})},request:K.pipe(K.object({amount:q(),accessKey:K.optional(Uc),chainId:K.optional(K.number()),currency:Hc,decimals:K.number(),description:K.optional(K.string()),externalId:K.optional(K.string()),methodDetails:K.optional(Wc),periodCount:qc,periodUnit:Kc,recipient:Hc,subscriptionExpires:Gc}).check(Jc(`Subscription amount must be greater than 0`),K.refine(Yc,`Subscription period exceeds uint64`)),K.transform(({accessKey:e,amount:t,chainId:n,decimals:r,methodDetails:i,subscriptionExpires:a,...o})=>{let s={...i,...e!==void 0&&{accessKey:e},...n!==void 0&&{chainId:n}};return{...o,amount:g(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}}),$c=K.object({account:K.optional(K.custom()),autoSwap:K.optional(K.custom()),feeToken:K.optional(K.custom()),mode:K.optional(K.enum(Rc))});function el(e={}){let{clientId:t}=e;if((e.maxAmount!==void 0||e.maxAtomicAmount!==void 0)&&e.currencies===void 0)throw Error(`Tempo charge maxAmount and maxAtomicAmount require currencies.`);for(let t of e.currencies??[])_l(e.maxAmount,typeof t==`string`?e.decimals:t.decimals);let n={maxAmount:e.maxAmount,maxAtomicAmount:e.maxAtomicAmount===void 0?void 0:BigInt(e.maxAtomicAmount)},r=Hs({chain:R,getClient:e.getClient,rpcUrl:Wr}),i=Rs({account:e.account});ll(e.zone);let a=new Map,o=Mn(Xc,{canHandleChallenge({challenge:t}){try{return vl(e,n,t.request),!0}catch{return!1}},context:$c,async createCredential(o){let{challenge:s,context:c}=o,l=it(o),u=()=>Error(`The Zone withdrawal this challenge resumes is no longer outstanding. Retry the request to pay it.`);vl(e,n,s.request);let d=s.request.methodDetails?.chainId,f=d??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),p=await r({chainId:f});Us(p,f);let m=f??p.chain?.id;if(Ws(e.allowedChainIds,m),m===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");d===void 0&&vl(e,n,s.request,m);let{request:h}=s,{amount:g,methodDetails:_}=h,v=_?.supportedModes??[`pull`,`push`],y=e.zone?.client.chain,x=e.zone?e.zone.zoneId??Nc(y?.id??0):void 0,C=y?.sourceId??(y?Pc(y.id):void 0),te=c?.mode??e.mode;if(BigInt(g)>0n&&e.zone&&x!==void 0&&C===m&&v.includes(`push`)&&(te===void 0||te===`push`)&&jc(_?.zones,x)&&!_?.splits){let r={assertFee:t=>vl(e,n,h,m,t),challenge:s,clientId:t,client:p,origin:cl(Wa(o)),pending:a,zone:e.zone,zoneId:x},i=il(r);if(i)return ol(r,i);if(l?.resume)throw u();if(s.expires&&kn(s.expires,s.id),ul(s.expires,e.zone.settlementTimeoutMs))return rl(r)}if(l?.resume)throw u();let ne=i(p,c),re=async t=>await e.resolveAccount?.({account:ne,chainId:m,operation:t})??ne;if(BigInt(g)===0n){let e=await re({kind:`signPaymentProof`});return wn({challenge:s,payload:{signature:await T(p,{account:e,...bc({account:e.address,chainId:m,challengeId:s.id,realm:s.realm})}),type:`proof`},source:xc({address:e.address,chainId:m})})}let E=h.currency,D=lc({chainId:m,currency:E}),O=_?.memo??qs({challengeId:s.id,clientId:t,serverId:s.realm}),k=tc({amount:g,methodDetails:{..._,memo:O},recipient:h.recipient}),A=k.map(e=>V.token.transfer.call(p,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:E})),j=$s(c?.autoSwap??e.autoSwap,Zs),M=_?.machineTokenEnabled===!0&&!l?uc({chainId:m,currency:E,transfers:k}):void 0,N=ne,P,F=!1;if(M){let e=await(async()=>{try{return await re({calls:M.calls,kind:`executeCalls`})}catch{return}})();e&&(P=await dc(p,{account:e.address,chainId:m,currency:E,transfers:k}),P?N=e:F=!0)}let I;if(!P){if(N=await re({kind:`executeCalls`,...j?{}:{calls:A}}),I=j?await Qs(p,{account:N.address,amountOut:BigInt(g),tokenOut:E,tokenIn:j.tokenIn,slippage:j.slippage,maxAmountIn:j.maxAmountIn}):void 0,l&&I)throw new wt({limit:l.limit,reason:`asset`});if(F&&!j){let e=await tl(p,{account:N.address,amount:BigInt(g),chainId:m,currency:E});if(e)throw e}}let L=P?.calls??[...I??[],...A],R=ac(m),z=(c?.feeToken??e.feeToken)||(P||D?await oc({account:N.address,allowedTokens:R,candidateTokens:R,client:p,prioritizeCandidates:!0}):void 0),ie=(()=>{let t=c?.mode??e.mode;if(t){if(!v.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=N.type===`json-rpc`?`push`:`pull`;return v.includes(n)?n:v[0]})(),ae=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!s.expires)return e;let t=Math.floor(new Date(s.expires).getTime()/1e3)+1;return Math.min(e,t)})(),oe=()=>{l&&s.expires&&kn(s.expires,s.id)};if(ie===`push`){oe();let{receipts:e}=N.type===`local`?{receipts:[await Tc({account:N},()=>w(p,{account:N,calls:L,...z?{feeToken:z}:{},nonceKey:`expiring`,validBefore:ae}))]}:await S(p,{account:N,...z?{capabilities:{feeToken:z}}:{},calls:L,experimental_fallback:L.length===1,forceAtomic:L.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Xa(Error(`No transaction receipt returned.`));return wn({challenge:s,payload:{hash:t,type:`hash`},source:xc({address:N.address,chainId:m})})}let B=()=>{if(_?.feePayer!==!0)return;let e=15e3,t=s.expires?new Date(s.expires).getTime():1/0,n=Date.now();if(!(t-n>=e))throw Error(`Sponsored challenge expires in less than 15 seconds; the fee payer would reject the transaction. Request a new challenge.`);if(!(ae*1e3-n>=e))throw Error(`Sponsored transaction preparation took too long: less than 15 seconds of its validity window remain, so the fee payer would reject it.`)};B();let se=await Tc({account:N},()=>b(p,{account:N,calls:L,...z?{feeToken:z}:{},nonceKey:`expiring`,validBefore:ae}));if(se.gas=(se.gas??0n)+5000n,_?.feePayer){let e=se;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return B(),oe(),wn({challenge:s,payload:{signature:await ee(p,se),type:`transaction`},source:xc({address:N.address,chainId:m})})}}),s=new Map,c=async t=>{vl(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,a=it(t),c=s.get(i);if(a&&at(a,c?.constraints),c)return c.promise;let l=o.createCredential(t).finally(()=>s.delete(i));return s.set(i,{constraints:a,promise:l}),l};return tt(Va({...o,createCredential:c},nl),{assert:t=>vl(e,n,t.request),resumes:t=>al(a,t,e.zone&&(e.zone.zoneId??Nc(e.zone.client.chain?.id??0)))})}async function tl(e,t){let{account:n,amount:r,chainId:i,currency:a}=t,o=await x(e,V.token.getBalance.call(e,{account:n,token:a})).catch(()=>void 0);if(!(typeof o!=`bigint`||o>=r))return gc(e,{account:n,amount:r,chainId:i})}function nl(e){let t=Xc.schema.credential.payload.safeParse(yn(e).payload);if(!t.success)return;let n=t.data;if(n.type===`hash`||n.type===`zone`)return n.hash;let r=n.signature;if(n.type!==`transaction`||!r.startsWith(ve.serializedType))return;let i=ve.deserialize(r);if(!(!i.signature||i.feePayerSignature===null)&&ve.serialize(i)===r)return p(r)}function rl(e){let{challenge:t,origin:n,pending:r,zoneId:i}=e,a={sent:!1},o={challenge:t,origin:n,terms:pl(t,i),waiters:0,withdrawal:gl(e,a)},s=fl(t);return r.set(s,o),o.withdrawal.catch(()=>{!a.sent&&r.get(s)===o&&r.delete(s)}),ol(e,o)}function il(e){let{challenge:t,pending:n,zoneId:r}=e,i=n.get(fl(t));if(i)return i;let a=pl(t,r);if(a!==void 0){for(let[e,t]of n)if(t.terms===a){if(!hl(t.challenge.expires)){n.delete(e);continue}if(t.redeemedLate)throw new Ct({challengeId:t.challenge.id,senderTags:t.senderTags,zoneId:r});if(!(t.waiters>0))return t}}}function al(e,t,n){if(n===void 0||e.size===0)return!1;if(e.has(fl(t)))return!0;let r=pl(t,n);if(r===void 0)return!1;for(let t of e.values())if(t.terms===r&&hl(t.challenge.expires)&&(t.redeemedLate||t.waiters===0))return!0;return!1}async function ol(e,t){t.waiters++;try{return await sl(e,t)}finally{t.waiters--}}async function sl(e,t){let{client:n,origin:r,pending:i,zone:a,zoneId:o}=e,{challenge:s}=t,c=s.request.recipient,l=fl(s);if((l===fl(e.challenge)?r!==void 0&&t.origin!==void 0&&r!==t.origin:!r||r!==t.origin)||!hl(s.expires))throw new Ct({challengeId:s.id,zoneId:o});let u=await t.withdrawal,d=u.senderTags??await Ic(a.client,u).catch(e=>{let t=Error(`Zone withdrawal transaction ${u.transactionHash} was sent, but its sender tag could not be read from the Zone. Retry the challenge to resume without withdrawing again.`);throw Object.defineProperty(t,"cause",{configurable:!0,value:e,writable:!0}),Xa(t)}),f;try{f=await Lc(n,{portal:Mc(o),senderTags:d,timeoutMs:dl(s.expires,a.settlementTimeoutMs),to:c})}catch(e){throw new Ct({cause:e,challengeId:s.id,senderTags:d,zoneId:o})}i.get(l)===t&&(ml(s.expires)?(t.redeemedLate=!0,t.senderTags=[f.senderTag]):i.delete(l));let{hash:p,senderTag:m}=f;return wn({challenge:s,payload:{hash:p,senderTag:m,type:`zone`,zoneId:o}})}function cl(e){if(e)try{let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`?void 0:t.origin}catch{return}}function ll(e){let t=e?.settlementTimeoutMs;if(t!==void 0&&(!Number.isFinite(t)||t<0))throw Error("`zone.settlementTimeoutMs` must be a finite, non-negative number.");let n=e?.client.chain?.id;if(e?.zoneId===void 0||n===void 0||Pc(n)===void 0)return;let r=Nc(n);if(r!==e.zoneId)throw Error(`zone.zoneId ${e.zoneId} does not match Zone ${r} of the zone.client chain ${n}.`)}function ul(e,t){if(!e)return!0;let n=t??6e4;return new Date(e).getTime()-Date.now()>n+15e3}function dl(e,t){let n=t??6e4;return e?Math.max(0,Math.min(n,new Date(e).getTime()-Date.now())):n}function fl(e){return JSON.stringify(e)}function pl(e,t){let n;try{n=e.opaque===void 0?e.meta:Et(e.opaque)}catch{return}let{digest:r,intent:i,method:a,realm:o,request:s}=e;return G({digest:r,intent:i,meta:An(n),method:a,realm:o,request:s,zoneId:t})}function ml(e){if(!e)return!1;let t=new Date(e).getTime();return!Number.isNaN(t)&&Date.now()>=t}function hl(e){if(!e)return!0;let t=new Date(e).getTime();return Number.isNaN(t)||Date.now()<t+3e5}async function gl(e,t){let{assertFee:n,challenge:r,clientId:i,zone:a}=e,o=r.request,s=a.client.account;if(!s)throw Error("`zone.client` requires an account.");let c=BigInt(o.amount),l=o.currency,u=o.recipient,d=qs({challengeId:r.id,clientId:i,serverId:r.realm}),f=await V.zone.getWithdrawalFee(a.client);n(f);let[,m]=V.zone.requestWithdrawal.calls({amount:c,fallbackRecipient:s.address,memo:d,to:u,token:l}),g=await b(a.client,{account:s,calls:[V.token.approve.call({amount:c+f,spender:ce.zoneOutbox,token:l}),m]}),_=await ee(a.client,g);t.sent=!0;let v=p(_),y=await C(a.client,{serializedTransaction:_}).catch(e=>te(a.client,{hash:v,timeout:15e3}).catch(()=>{let t=new vt({cause:e,transactionHash:v});throw t.message=`Zone withdrawal outcome is unknown: transaction ${v} may have been sent. Retrying this challenge does not withdraw again.`,t}));if(y.status===`reverted`)throw t.sent=!1,Error(`Zone withdrawal transaction ${y.transactionHash} reverted.`);let[x]=h({abi:B.zoneOutbox,eventName:`WithdrawalRequested`,logs:y.logs});return{blockNumber:y.blockNumber,sender:s.address,senderTags:x?[Fc({fallbackNonce:x.args.fallbackNonce,sender:x.args.sender,transactionHash:y.transactionHash})]:void 0,transactionHash:y.transactionHash}}function _l(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo charge maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo charge maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return g(e,t)}}function vl(e,t,n,r,i){let{methodDetails:a,recipient:o}=n,s=a?.chainId;if(e.expectedChainId!==void 0&&s!==void 0&&s!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${s}.`);(s!==void 0||e.allowedChainIds?.length===0)&&Ws(e.allowedChainIds,s);let c=e.currencies?Oe(e.currencies,n.currency,{chainId:s??r??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),decimals:e.decimals}):void 0;if(e.currencies&&!c)throw Error(`Tempo charge currency is not allowed: ${n.currency}.`);if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase()));if(!o||!t.has(o.toLowerCase()))throw Error(`Unexpected primary recipient: ${o}`);let n=a?.splits;if(n){for(let e of n)if(!t.has(e.recipient.toLowerCase()))throw Error(`Unexpected split recipient: ${e.recipient}`)}}if(t.maxAtomicAmount===void 0&&t.maxAmount===void 0)return;let l=BigInt(n.amount)+(i??0n),u=i===void 0?`amount exceeds`:`amount plus Zone withdrawal fee exceeds`;if(t.maxAtomicAmount!==void 0&&l>t.maxAtomicAmount)throw Error(`Tempo charge ${u} maxAtomicAmount.`);if(t.maxAmount!==void 0&&l>_l(t.maxAmount,c?.decimals))throw Error(`Tempo charge ${u} maxAmount.`)}const yl=(1n<<96n)-1n;function bl(e){return e>=0n&&e<=yl}function xl(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return bl(t)?t:void 0}function Sl(e){return Cl(e),e}function Cl(e){if(!bl(e))throw Error(`Value ${e} is outside uint96 bounds.`)}const wl=new Set([`open`,`topUp`,`voucher`,`close`]);function Tl(e){return typeof e==`object`&&!!e}function El(e){return typeof e==`string`&&wl.has(e)}function Dl(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!El(t.action))}function Ol(e,t=`No session credential context available.`){if(!Dl(e))throw Error(t);return e}function kl(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function Al(e){return Tl(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function jl(e){return Tl(e)?e.method===`tempo`&&e.intent===`session`&&e.status===`success`&&typeof e.timestamp==`string`&&typeof e.reference==`string`&&typeof e.challengeId==`string`&&typeof e.channelId==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.spent==`string`&&(e.units===void 0||typeof e.units==`number`)&&(e.txHash===void 0||typeof e.txHash==`string`):!1}function Ml(e){let t=D.toString(e),n=JSON.parse(t);if(!jl(n))throw Error(`Invalid session receipt.`);return n}function Nl(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function Pl(e){let t=`message`,n=[];for(let r of e.split(`
|
|
6
|
+
`,i))}t=t.slice(i)}}}const ta=[U.authorization,U.paymentAuthorization,In,Rn,Ln];function na(e,t,n){let r=new Headers(e.headers);for(let e of ta){let t=r.get(e);if(t===null)continue;if(!aa(e)){r.delete(e);continue}let n=ra(t);n!==t&&(n?r.set(e,n):r.delete(e))}return r.set(t,n),{...e,headers:r}}function ra(e){let t=e.split(`,`).map(e=>e.trim()),n=t.filter(e=>!ia.test(e));return n.length===t.length?e:n.filter(Boolean).join(`, `)}const ia=RegExp(`^${st.payment}(?:\\s|$)`,`i`);function aa(e){return e===U.authorization||e===U.paymentAuthorization}function oa(e){if(typeof e==`string`)try{let t=JSON.parse(e),n=t?.id;return t?.jsonrpc!==`2.0`||typeof t?.method!=`string`?void 0:typeof n==`string`||typeof n==`number`?n:void 0}catch{return}}function sa(e){if(typeof e?.body!=`string`)return!1;try{let t=JSON.parse(e.body);return t?.jsonrpc===`2.0`&&t?.method===`tools/call`&&t.params?._meta?.[`mppx/payment-client`]===!0}catch{return!1}}function ca(e){if(typeof e?.body!=`string`)return!1;try{let t=JSON.parse(e.body);return t?.jsonrpc===`2.0`&&t.params?._meta?.[`org.paymentauth/credential`]!=null}catch{return!1}}const la=1048576,ua=new WeakMap;function da(e){let t=oa(e?.body);if(t===void 0)return;let n=new Headers(e?.headers);if(n.has(`mcp-method`))return t;let r=n.get(`accept`)?.toLowerCase()??``;return r.includes(`application/json`)&&r.includes(`text/event-stream`)?t:void 0}function fa(e){if(!e||typeof e!=`object`)return;let t=e,n=t.id;if(t.jsonrpc!==`2.0`||n!==void 0&&typeof n!=`string`&&typeof n!=`number`)return;let r=`error`in t;if(r!==`result`in t)return r?Number.isInteger(t.error?.code)&&typeof t.error?.message==`string`?e:void 0:n!==void 0&&typeof t.result==`object`?e:void 0}function pa(e){if(!e||typeof e!=`object`)return;let t=e?.challenges;if(!Array.isArray(t)||t.length===0)return;let n=[];for(let e of t){if(!Bt.safeParse(e).success)return;if(dn(e))continue;let t=zt.safeParse(e);if(!t.success)return;n.push(t.data)}if(n.length===0)return;let{httpStatus:r,problem:i}=e;return{challenges:n,...typeof r==`number`?{httpStatus:r}:{},...i===void 0?{}:{problem:i}}}function ma(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:pa(e.error.data):pa(e.result?._meta?.[`org.paymentauth/payment-required`])}function ha(e,t){return!e||e.id!==t?[]:ma(e)?.challenges??[]}async function ga(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=ea(e=>{if(!(i||!e.data)&&(i=!0,e.event===`message`))try{a=fa(JSON.parse(e.data))}catch{}});try{for(;;){if(i)return a;let{done:e,value:s}=await t.read();if(e)return o.feed(n.decode()),a;if(r+=s.byteLength,r>la)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function _a(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=``;try{for(;;){let{done:e,value:a}=await t.read();if(e)return fa(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>la)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function va(e){let t=ua.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>la)){if(t.includes(`application/json`))return _a(e);if(t.includes(`text/event-stream`))return ga(e)}})();return ua.set(e,n),n}function ya(){return{getChallenges(e,t){let n=da(t);return e.status===402||n===void 0?[]:va(e).then(e=>ha(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=yn(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,"org.paymentauth/credential":r}}})}}}}async function ba(e,t){let n=da(t);if(e.status===402||n===void 0)return!1;let r=await va(e);return!r||r.id!==n?!1:ma(r)?.problem?.type===xa}const xa=`https://paymentauth.org/problems/invalid-challenge`;function Sa(){return{getChallenges(e){let t=e.headers.get(U.wwwAuthenticate);return e.status!==402||!t||!en(t)?[]:nn(e)},setCredential(e,t,n){let r=n?.challenge??wa(t);return na(e,r?un(r):U.authorization,t)}}}const Ca=/^Payment [A-Za-z0-9_-]+={0,2}$/;function wa(e){if(Ca.test(e))try{return yn(e).challenge}catch{return}}function Ta(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(In);if(!t)return[];let n=ar(t);return n.accepts.flatMap((e,t)=>{let r=Gn.safeParse(e);if(!r.success)return[];let i=r.data;return Dn(Vt({id:`x402:${t}`,intent:`charge`,method:`evm`,realm:new URL(n.resource.url).host,request:{...i,...n.extensions?{extensions:n.extensions}:{},resource:n.resource}}))})},setCredential(e,t){return na(e,Ln,t)}}}function Ea(e){return e}function Da(){let e=[Sa(),Ta(),ya()],t=new WeakMap,n=(e,n)=>{for(let r of n)t.set(r,e);return n},r=(t,r)=>{let i=(a,o)=>{for(let s=a;s<e.length;s++){let a=e[s],c=a.getChallenges(t,r);if(c instanceof Promise)return c.then(e=>i(s+1,[...o,...n(a,e)]));o.push(...n(a,c))}return o};return i(0,[])};return Ea({name:`http`,isPaymentRequired(e,t){if(e.status===402)return!0;let n=r(e,t);return n instanceof Promise?n.then(e=>e.length>0):n.length>0},getChallenges(e,t){return r(e,t)},setCredential(n,r,i){let a=i?.challenge?t.get(i.challenge):void 0,o=e[0];if(!a&&!o)throw Error(`No protocol to attach the credential.`);return(a??o).setCredential(n,r,i)}})}const Oa=new WeakMap;function ka(e,t){return Oa.set(e,t),e}function Aa(e){return Oa.has(e)}function ja(e,t){return Promise.resolve(Oa.get(e)?.(t))}function Ma(e){return Oa.get(e)}const Na=new WeakMap,Pa=new WeakMap,Fa=new WeakMap,Ia=new WeakMap;function La(e,t){return Na.set(e,t),e}function Ra(e){Na.delete(e)}function za(e,t,n){Na.has(e)&&Pa.set(t,n)}function Ba(e){return Pa.get(e)}function Va(e,t){return Promise.resolve(Na.get(e)?.(t)??t.response)}function Ha(e,t){return Ia.set(e,t),e}function Ua(e,t){try{return Ia.get(e)?.(t)}catch{return}}function Wa(e,t){Fa.set(e,t)}function Ga(e){return Fa.get(e)??Pa.get(e)?.origin}async function Ka(e,t){let{attempts:n,signal:r}=t;for(let t=1;;t++){r?.throwIfAborted();try{return await e()}catch(e){if(!(e instanceof Ct)||t>=n)throw e;r?.throwIfAborted()}}}function qa(e,t,n){if(!Ja(e)&&(e.method!==`tempo`||e.intent!==`session`))return;t=typeof t==`function`?t():t;let{realm:r}=e;if(r.toLowerCase()===t.hostname.toLowerCase())return;let i=t.origin.toLowerCase();for(let[e,t]of Object.entries(n??{}))if(t===r&&Ya(e)===i)return;throw Error(`Refusing to sign Tempo proof for realm ${JSON.stringify(r)} from ${t.origin}. Pin the realm to this origin with \`trustedTempoProofRealms\` if this server is expected to issue it.`)}function Ja(e){if(e.method!==`tempo`||e.intent!==`charge`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function Ya(e){try{return new URL(e).origin.toLowerCase()}catch{return e.toLowerCase()}}const Xa=Symbol.for(`mppx.client.fundsMayHaveMoved`);function Za(e){return Object.defineProperty(e,Xa,{value:!0}),e}function Qa(e){return typeof e==`object`&&!!e&&e[Xa]===!0}const $a=[4217,42431],eo=[ie,ae,oe],to=[{network:`stripe`,asset:`usd`,currency:`USD`,decimals:2}],no=`charge`,ro=new WeakSet,io=new WeakMap,ao=new WeakSet,oo=/^(\d+)(?:\.(\d+))?$/;function so(e){let{authorize:t,funders:n=[],maxPayment:r,tokens:i}=e;if(r!==void 0&&ko(r),t!==void 0&&typeof t!=`function`)throw TypeError(`authorize must be a function.`);if(!Array.isArray(n)||n.some(e=>typeof e?.fund!=`function`))throw TypeError(`funders must be an array of objects with a fund function.`);let a=Ro(i),o=e=>jo(e,a),s=r!==void 0||t!==void 0||n.length>0,c=r===void 0?`budget`:`maxPayment`;return{limit:c,resolve(e){if(e.intent===no)try{return o(e)}catch{return}},prepare:s?async(e,{method:i,signal:a}={})=>{if(a?.throwIfAborted(),e.intent!==no)throw new wt({limit:c,reason:`intent`});e.expires&&kn(e.expires,e.id);let s=i&&nt(i);if(s?.resumes?.(e))return Object.freeze({settlement:zo(void 0),constraints:l(!0)});let u=ho(e),d=o(e);r!==void 0&&Ao(d,r),s?.assert?.(e);let f=Object.freeze({challenge:Co(e),...a?{signal:a}:{}}),p=Object.freeze({requirement:d});ro.add(p);let m=zo(await t?.(p,f)??void 0);try{for(let e of n)a?.throwIfAborted(),await e.fund(d,f);if(a?.throwIfAborted(),ho(e)!==u)throw Error(`Cannot check spending limits: the challenge changed while checked.`);e.expires&&kn(e.expires,e.id)}catch(e){throw m.release(),e}return Object.freeze({settlement:m,constraints:l(!1)})}:void 0};function l(e){let n=Object.freeze({limit:c,resume:e});return io.set(n,t),n}}function co(e){let t=ot(e);return t!==void 0&&ao.has(t)&&io.has(t)&&io.get(t)===io.get(e)}function lo(e){return e!==void 0&&(e.maxPayment!==void 0||e.authorize!==void 0||e.funders!==void 0&&e.funders.length>0||e.tokens!==void 0)}function uo(e){let{authorize:t,funders:n,maxPayment:r,tokens:i}=e;return{...t!==void 0&&{authorize:t},...n!==void 0&&{funders:n},...r!==void 0&&{maxPayment:r},...i!==void 0&&{tokens:i}}}function fo(e,t){if(!lo(t))return uo(e);if(lo(e))throw TypeError(`The fetch passed in already has spending options (maxPayment, authorize, funders or tokens). Set them on one fetch only.`);return t}function po(e,t){return t?e.then(e=>(t.commit(),e),e=>{throw e instanceof Ct||e instanceof vt||Qa(e)?t.commit():t.release(),e}):e}function mo(e,t,n,r){let i,a=!1,o,s=()=>i??=Promise.resolve(e.prepare?.(t,{method:r,signal:n})),c=async()=>{if(!e.prepare)return;n?.throwIfAborted();let r=a?void 0:await s();if(r&&!r.constraints.resume)return r.settlement.commit();(await e.prepare(t,{signal:n})).settlement.commit()},l=async()=>{await o,(await i?.catch(()=>void 0))?.settlement.release()};return{prepare:s,async track(e){let r=await s();if(r&&n?.aborted&&(r.settlement.release(),n.throwIfAborted()),r&&!r.constraints.resume&&t.expires)try{kn(t.expires,t.id)}catch(e){throw r.settlement.release(),e}let i=po(e(r?.constraints),r&&{commit(){a=!0,co(r.constraints)?r.settlement.release():(r.settlement.commit(),r.constraints.resume||ao.add(r.constraints))},release(){}});return o=i.then(()=>{},()=>{}),i},commit:c,async commitReplacement(r,i){if(!e.prepare)return;let a=_o(r,i);if(!a)throw So(e);return go(a)===go(t)?(await c(),a):(await l(),await mo(e,a,n).commit(),a)},release:l}}function ho(e){let{digest:t,expires:n,id:r,intent:i,meta:a,method:o,opaque:s,realm:c,request:l}=e;return JSON.stringify([On(e),r,c,o,i,G(l),n??null,t??null,s??(a===void 0?null:G(a))])}function go(e){try{return ho(e)}catch{return}}function _o(e,t){let n=vo(e,t)??yo(e,t);return n?.length===1?n[0]:void 0}function vo(e,t){let n;try{n=yn(e).challenge}catch{return}let r=go(n);return r===void 0?[]:t.filter(e=>go(e)===r)}function yo(e,t){let n;try{n=sr(e)}catch{return}return t.filter(e=>On(e)&&bo(n,e))}function bo(e,t){let n=Gn.safeParse(t.request);if(!n.success)return!1;let r=n.data;try{if(G(r)!==G(e.accepted))return!1;let t=BigInt(r.amount),n=e.payload;if(`authorization`in n)return xo(n.authorization.to,r.payTo)&&BigInt(n.authorization.value)===t;let{permitted:i,witness:a}=n.permit2Authorization;return xo(i.token,r.asset)&&BigInt(i.amount)===t&&xo(a.to,r.payTo)}catch{return!1}}function xo(e,t){return e.toLowerCase()===t.toLowerCase()}function So(e){return new wt({limit:e.limit,reason:`credential`})}function Co(e){let t;try{t=structuredClone(e)}catch{t=JSON.parse(JSON.stringify(e))}return On(e)&&Dn(t),wo(t)}function wo(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))wo(t);return e}function To(e,t){let n=/^0x[\da-fA-F]{40}$/.test(t)||e===`stripe`?t.toLowerCase():t;return JSON.stringify([e,n])}function Eo(e,t){let[,n=`0`,r=``]=oo.exec(e)??[];return BigInt(`${n}${r.slice(0,t).padEnd(t,`0`)}`)}function Do(e,t){let{currency:n,value:r}=e??{};if(typeof n!=`string`||!n.trim())throw TypeError(`${t} currency must be a non-empty string.`);if(typeof r!=`string`||r.length>1024||!oo.test(r))throw TypeError(`${t} value must be a non-negative decimal string.`)}function Oo(e){if(typeof e!=`object`||!e)return!1;let{amount:t,asset:n,network:r}=e;return typeof r==`string`&&r.length>0&&typeof n==`string`&&n.length>0&&typeof t==`bigint`&&t>=0n}function ko(e){if(!Array.isArray(e))return Do(e,`maxPayment`);let t=new Set;for(let n of e){if(!Oo(n))throw TypeError(`Each maxPayment limit needs a network, an asset and a bigint amount.`);let e=To(n.network,n.asset);if(t.has(e))throw TypeError(`Duplicate maxPayment limit for ${n.asset}.`);t.add(e)}}function Ao(e,t){let n=e=>new wt({limit:`maxPayment`,reason:e});if(Array.isArray(t)){let r=To(e.network,e.asset),i=t.find(e=>To(e.network,e.asset)===r);if(!i)throw n(`asset`);if(e.amount>i.amount)throw n(`amount`);return}let r=t,{currency:i,decimals:a}=e;if(i===void 0||a===void 0||i.toUpperCase()!==r.currency.toUpperCase())throw n(`asset`);if(e.amount>Eo(r.value,a))throw n(`amount`)}function jo(e,t){let n=On(e)?No(e):Po(e),r=t.get(To(n.network,n.asset)),i={method:e.method,intent:e.intent,...n,...r?{currency:r.currency,decimals:r.decimals}:{}};return Object.defineProperty(i,"toJSON",{value:Mo}),Object.freeze(i)}function Mo(){return{...this,amount:this.amount.toString(),...this.splits&&{splits:this.splits.map(e=>({...e,amount:e.amount.toString()}))}}}function No(e){let t=Gn.safeParse(e.request);if(!t.success)throw Error(`Cannot check spending limits: invalid x402 requirements.`);let{amount:n,asset:r,network:i,payTo:a}=t.data;return{protocol:`x402`,network:i,asset:r,amount:Lo(n),recipient:a}}function Po(e){let t=e.request,n=typeof t.methodDetails==`object`&&t.methodDetails!==null?t.methodDetails:{},r=n.chainId;if(r!==void 0&&(!Number.isSafeInteger(r)||r<=0))throw Error(`Cannot check spending limits: invalid challenge chain ID.`);if(t.chainId!==void 0&&t.chainId!==r)throw Error(`Cannot check spending limits: challenge names a chain outside methodDetails.chainId.`);let i=t.currency;if(typeof i!=`string`||!i)throw Error(`Cannot check spending limits: challenge names no currency.`);let a=Lo(t.amount),o=Fo(e.method,t,n),s=Io(n.splits,a);return{protocol:`mpp`,network:r===void 0?e.method:`eip155:${r}`,asset:i,amount:a,...o===void 0?{}:{recipient:o},...s?{splits:s}:{}}}function Fo(e,t,n){if(e===`stripe`){if(typeof n.networkId!=`string`||!n.networkId)throw Error(`Cannot check spending limits: Stripe challenge names no networkId.`);return n.networkId}return typeof t.recipient==`string`?t.recipient:void 0}function Io(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)throw Error(`Cannot check spending limits: invalid payment splits.`);let n=0n,r=e.map(e=>{let{amount:t,recipient:r}=e??{};if(typeof r!=`string`||!r)throw Error(`Cannot check spending limits: payment split names no recipient.`);let i=Lo(t);return n+=i,Object.freeze({recipient:r,amount:i})});if(n>=t)throw Error(`Cannot check spending limits: payment splits are not less than the amount.`);return Object.freeze(r)}function Lo(e){if(typeof e!=`string`||!/^\d+$/.test(e))throw Error(`Cannot check spending limits: challenge amount is not an atomic integer.`);return BigInt(e)}function Ro(e){let t=new Map;for(let e of eo)for(let n of $a){let r=e.addresses[n];r&&t.set(To(`eip155:${n}`,r),{currency:e.currency,decimals:e.decimals})}for(let{asset:e,currency:n,decimals:r,network:i}of to)t.set(To(i,e),{currency:n,decimals:r});if(e===void 0)return t;if(!Array.isArray(e))throw TypeError(`tokens must be an array.`);let n=new Map;for(let t of e){let{currency:e,decimals:r}=t??{};if(typeof e!=`string`||!e.trim())throw TypeError(`Each token needs a currency, such as USD.`);if(typeof r!=`number`||!Number.isInteger(r)||r<0||r>255)throw TypeError(`Token decimals must be an integer from 0 to 255.`);let i=typeof t==`function`?Object.entries(t.addresses).map(([e,t])=>[Number(e),t]):[[t.chainId,t.address]];for(let[t,a]of i){if(!Number.isSafeInteger(t)||t<=0||typeof a!=`string`||!a)throw TypeError(`Each token needs an address and a chain ID.`);let i=To(`eip155:${t}`,a),o=n.get(i);if(o&&(o.currency.toUpperCase()!==e.toUpperCase()||o.decimals!==r))throw TypeError(`tokens configure conflicting metadata for ${a}.`);n.set(i,Object.freeze({currency:e,decimals:r}))}}for(let[e,r]of n)t.set(e,r);return t}function zo(e){let t=!0,n=n=>{t&&(t=!1,n?.call(e))};return Object.freeze({commit:()=>n(e?.commit),release:()=>n(e?.release)})}const Bo=Symbol.for(`mppx.fetch.wrapper`),Vo=Symbol.for(`mppx.fetch.identity`),Ho=Symbol.for(`mppx.fetch.spend`),Uo=Symbol.for(`mppx.fetch.skipPayment`);function Wo(e={}){return{...e,[Uo]:!0}}const Go=65536,Ko=new WeakMap;async function qo(e){if(!e.body)return e;let t=e.clone().body.getReader(),n=[],r=0,i=!1,a=setTimeout(()=>{i=!0,t.cancel().catch(()=>{})},2e3);try{for(;;){let{done:e,value:a}=await t.read();if(e)break;if(n.push(a),r+=a.byteLength,r>Go){i=!0;break}}}finally{clearTimeout(a),t.cancel().catch(()=>{})}if(!i)return e;e.body.cancel().catch(()=>{});let o=new Headers(e.headers);o.delete(`content-length`),o.set(`Mppx-Body-Truncated`,`true`);let s=new Response(new Blob(n).slice(0,Go),{headers:o,status:e.status,statusText:e.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{value:e[t]});return s}async function Jo(e,t){let n=e?.attempt.settle;if(!n)return t.status!==`pending`;e.attempt.settle=void 0;let r=await n(t);return r||(e.attempt.settle=n),r}function Yo(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=3,methods:a,onChallenge:o,orderChallenges:s,transport:c=Da(),trustedTempoProofRealms:l}=e,u=e.identity??(e.fetch&&vs(e.fetch)),d=e.eventDispatcher??Zo(),f=t??Ai(a),p=fo(e,e.fetch&&ys(e.fetch)),m=so(p),h=bs(r),g=async(e,t,n)=>u?u.send((e,n)=>h(e,t?.[Uo]?Wo(n):n),new Request(e,t),n):{response:await h(e,t),headers:[]},_=async(e,t,r)=>{let p=_s(e,t?.headers),v=p.has(U.acceptPayment),y=Es(p,f),b=Ss(e,t),x=hs(e,t,p,m.prepare?b:void 0),S=ms(e,t,p,y.header,v,n);if(m.prepare){let e=await x;if(b?.throwIfAborted(),sa(gs(S.init,e)))throw TypeError(`This fetch has spending options (maxPayment, authorize or funders), but McpClient.wrap pays MCP tool calls itself. Set them on McpClient.wrap and give its transport a fetch without them.`)}let C=await g(xs(S.input),S.init),w=C.response,ee=C.headers,T=gs(S.init,await x);if(t?.[Uo]||sa(T)||!await c.isPaymentRequired(w,T))return w;let te=t?.context,{context:ne,orderChallenges:re,...E}=T??{},D=Rs(p)||ca(T),O,k,A,j,M;try{for(let n=0;n<i;n++){if(k=await c.getChallenges(w,T),(n>0||D)&&await Ls(w,T))return await Jo(j,{challenges:k,response:w,status:`rejected`}),w;let f=(await Ds(Ni(k,a,y.entries,te),re??s))[0];if(!f){if(await Jo(j,{challenges:k,response:w,status:`rejected`}),n>0)return w;throw Error(sn(`No method found for challenges: ${k.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`,Fs(w)))}let p=f.challenge;O=p,A=f.method,O.expires&&kn(O.expires,O.id),await u?.challenge(w,{challenge:p},js(S.input).href);let v=await Ps(w,S.input,S.input,E);qa(p,()=>js(v),l);let b=j,x=Is(p),C=b?.method===f.method&&b?.key===x,ne=!1;if(b){let e=await Jo(b,{challenges:k,response:w,status:C?`pending`:`rejected`});ne=C&&!e}j=ne?b:void 0;let N=mo(m,p,Ss(e,t),f.method),P,F=ns(async n=>{if(n===void 0&&ne&&b)return P=b.promise,b.promise;ne&&b&&(await Jo(b,{status:`rejected`}),j=void 0),Ss(e,t)?.throwIfAborted();let r=n??te;if(!Aa(f.method))return P=N.track(n=>Ka(()=>Ts(p,f.method,r,Ms(v),n),{attempts:i,signal:Ss(e,t)})),P;let a={origin:js(v).origin,prepare:()=>ja(f.method,{challenge:p,context:r,fetch:u?Ti(h,u,{challenge:p}):h,input:v,signal:Ss(e,t)})},o=N.track(e=>a.prepare().then(()=>Ts(p,f.method,r,a,e)));return P=o,j={context:r,attempt:a,key:n===void 0?x:void 0,method:f.method,promise:o},o}),I,L,R,z=!1;try{let n=await d.emit(`challenge.received`,rs({challenge:p,challenges:k,createCredential:F,init:t,input:e,method:f.method,response:w}))??(o?await o(O,{createCredential:F}):void 0);if(n===!1)return await N.release(),await Jo(j,{challenges:k,response:w,status:`rejected`}),j=void 0,w;I=n??await F(),L=j,L&&await L.promise.catch(()=>void 0)!==I&&(await Jo(L,{status:`rejected`}),j=void 0),ws(I),z=P!==void 0&&await P.catch(()=>void 0)===I,z||(R=await N.commitReplacement(I,k))}catch(e){throw await N.release(),e}let ie=j?j.context:te,ae=Cs(I,p);await d.emit(`credential.created`,is({challenge:p,credential:I,init:t,input:e,method:f.method,response:w}));let oe=e=>new _t({cause:e,challenge:p,credential:I,transactionHash:Ua(f.method,I)});try{({response:w,headers:ee}=await g(v,{...c.setCredential({...E,headers:S.headers},I,{challenge:R??p}),redirect:`manual`},{challenge:ae,headers:ee}))}catch(e){throw M=oe(e),e}let B=await c.isPaymentRequired(w,T);if(B||(await Jo(L,{response:w,status:w.status>=300&&w.status<400?`pending`:w.ok?`accepted`:`rejected`}),j=void 0),w.ok&&Qo(d,`payment.response`)){let n=z?p:R??_o(I,k);await d.emit(`payment.response`,as({challenge:p,credential:I,init:t,input:e,method:f.method,requirement:n&&m.resolve(n),response:w}))}if(!B){if(w.status>=500&&Qo(d,`payment.failed`)){try{w=await qo(w)}catch(e){throw M=oe(e),w=new Response(null,{headers:w.headers,status:w.status,statusText:w.statusText}),e}await d.emit(`payment.failed`,os({challenge:p,challenges:k,error:oe(),init:t,input:e,method:f.method,response:w}))}return w.ok?Va(f.method,{context:ie,challenge:p,credential:I,fetch:h,headers:S.headers,input:v,...r?{refetch:()=>_(xs(S.input),t,!1)}:{},response:w,signal:Ss(e,t)}):w}}k=void 0;try{k=await c.getChallenges(w,T)}catch{}return await Jo(j,{challenges:k,response:w,status:`rejected`}),w}catch(n){throw await Jo(j,{challenges:k,response:w,status:`rejected`}),await d.emit(`payment.failed`,os({challenge:O,challenges:k,error:M??n,init:t,input:e,method:A,response:w})),n}},v=(e,t)=>_(e,t,!0);return v[Bo]=h,u&&(v[Vo]=u),lo(p)&&(v[Ho]=p),v}function Xo(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return Array.isArray(e)?Object.fromEntries(e):e}function Zo(){let e={"*":new Set,"challenge.received":new Set,"credential.created":new Set,"payment.failed":new Set,"payment.response":new Set},t={async emit(t,n){switch(t){case`challenge.received`:{let r;for(let t of e[`challenge.received`]){let e=await $o(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await ts(e[`*`],t,n),r}case`credential.created`:await es(e[`credential.created`],n),await ts(e[`*`],t,n);return;case`payment.failed`:await es(e[`payment.failed`],n),await ts(e[`*`],t,n);return;case`payment.response`:await es(e[`payment.response`],n),await ts(e[`*`],t,n);return}},on:(t,n)=>{switch(t){case`*`:case`challenge.received`:case`credential.created`:case`payment.failed`:case`payment.response`:return e[t].add(n),()=>e[t].delete(n);default:throw Error(`Unknown client event "${String(t)}".`)}}};return Ko.set(t,t=>e[t].size>0||e[`*`].size>0),t}function Qo(e,t){return Ko.get(e)?.(t)??!0}async function $o(e,t){try{return await e(t)}catch{return}}async function es(e,t){for(let n of e)try{await n(t)}catch{}}async function ts(e,t,n){await es(e,Object.freeze({name:t,payload:n}))}function ns(e){let t;return n=>(t??=e(n),t)}function rs(e){return Object.freeze({challenge:ds(e.challenge),challenges:e.challenges.map(e=>ds(e)),createCredential:e.createCredential,init:ss(e.init),input:cs(e.input),method:ls(e.method),response:us(e.response)})}function is(e){return Object.freeze({challenge:ds(e.challenge),credential:e.credential,init:ss(e.init),input:cs(e.input),method:ls(e.method),...e.response===void 0?{}:{response:us(e.response)}})}function as(e){let{requirement:t,response:n}=e,r=n instanceof Response?Qi(n):void 0;return Object.freeze({...t?{amount:t.amount.toString(),requirement:t}:{},...r?{receipt:r}:{},challenge:ds(e.challenge),credential:e.credential,init:ss(e.init),input:cs(e.input),method:ls(e.method),response:us(e.response)})}function os(e){return Object.freeze({...e.challenge?{challenge:ds(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>ds(e))}:{},error:e.error,init:ss(e.init),input:cs(e.input),...e.method?{method:ls(e.method)}:{},...e.response===void 0?{}:{response:us(e.response)}})}function ss(e){if(e)return ps({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function cs(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function ls(e){return ps(Object.assign({},e))}function us(e){if(e instanceof Response)try{return e.clone()}catch{let t=new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText});for(let n of[`redirected`,`type`,`url`])Object.defineProperty(t,n,{value:e[n]});return t}return ds(e)}function ds(e){try{return fs(structuredClone(e))}catch{return ps(e)}}function fs(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))fs(t);return e}function ps(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function ms(e,t,n,r,i,a){let o=!!r&&!i&&Os(e,a);if(!o)return{headers:n,init:t,input:e};let s=new Headers(e instanceof Request?e.headers:void 0);return n.forEach((e,t)=>{s.set(t,e)}),s.set(U.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function hs(e,t,n,r){if(!(!(e instanceof Request)||t?.body!==void 0||!e.body||e.bodyUsed)){if(!n.has(`mcp-method`)){let e=n.get(`accept`)?.toLowerCase()??``;if(!e.includes(`application/json`)||!e.includes(`text/event-stream`))return}try{let t=e.clone();return(r&&t.body?new Response(t.body.pipeThrough(new TransformStream,{signal:r})):t).text().catch(()=>void 0)}catch{return}}}function gs(e,t){return t===void 0?e:{...e,body:t}}function _s(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function vs(e){return e[Vo]}function ys(e){return e[Ho]}function bs(e){let t=e;for(;t[Bo];)t=t[Bo];return t}function xs(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function Ss(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function Cs(e,t){try{let{challenge:n}=yn(e);return n.id===t.id?t:{...n,...t.header!==void 0&&{header:t.header}}}catch{return t}}function ws(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
|
|
7
|
+
`))throw Error(`Credential header value contains illegal newline characters`)}async function Ts(e,t,n,r,i){let a=t.context&&n!==void 0?t.context.parse(n):void 0,o=a===void 0?{challenge:e}:{challenge:e,context:a};return i&&rt(o,i),r?.origin&&Wa(o,r.origin),r&&`prepare`in r&&za(t,o,r),t.createCredential(o)}function Es(e,t){let n=e.get(U.acceptPayment);if(!n)return t;try{return{...t,entries:ji(n),header:n}}catch{return t}}async function Ds(e,t){return t?t(e):e}function Os(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=js(e);return t===`same-origin`?!As()||n.origin===globalThis.location.origin:t.origins.some(e=>ks(n,e))}function ks(e,t){if(t.startsWith(`*.`)){let n=t.slice(1);return e.hostname.endsWith(n)||e.hostname===t.slice(2)}return e.origin===new URL(t).origin}function As(){return globalThis.location!==void 0}function js(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,As()?globalThis.location.href:void 0)}function Ms(e){try{return{origin:js(e).origin}}catch{return}}function Ns(e,t){let n=e instanceof Request?e:void 0;if((t.mode??n?.mode)===`no-cors`)throw Error(`Cannot automatically pay a no-cors request: it cannot carry a credential.`);if((t.cache??n?.cache)===`only-if-cached`)throw Error(`Cannot automatically pay an only-if-cached request: its retry cannot reach the server.`)}async function Ps(e,t,n,r){if(Ns(t,r),!e.url)return t;let i=new URL(e.url),a=js(n);if(i.origin!==a.origin)throw Error(`Refusing to send payment credential across redirect from ${a.origin} to ${i.origin}`);let o=(r.method??(t instanceof Request?t.method:`GET`)).toUpperCase();if(e.redirected&&o!==`GET`&&o!==`HEAD`)throw Error(`Cannot automatically pay a redirected ${o} request. Use prepareRequest() to preserve redirect semantics.`);if(t instanceof Request){let n=r.body==null?t.clone():t,i=new Request(n,t.mode===`navigate`&&r.mode===void 0?{...r,mode:`same-origin`}:r);return i.url.split(`#`)[0]===e.url?i:i.body?new Request(e.url,{body:await i.arrayBuffer(),cache:i.cache,credentials:i.credentials,headers:i.headers,integrity:i.integrity,keepalive:i.keepalive,method:i.method,mode:i.mode,redirect:i.redirect,referrer:i.referrer,referrerPolicy:i.referrerPolicy,signal:i.signal}):new Request(e.url,i)}return e.url}function Fs(e){return!(e instanceof Response)||e.status!==402?0:on(e.headers.get(U.wwwAuthenticate))}function Is(e){let{description:t,...n}=e;return j.canonicalize(n)}async function Ls(e,t){if(!(e instanceof globalThis.Response))return!1;if(await ba(e,t))return!0;if(!e.headers.get(`Content-Type`)?.includes(`application/problem+json`))return!1;try{return(await e.clone().json()).type===`https://paymentauth.org/problems/invalid-challenge`}catch{return!1}}function Rs(e){return e.get(U.paymentAuthorization)?!0:/(^|,)\s*Payment\s+\S/i.test(e.get(U.authorization)??``)}function zs(e={}){let{account:t}=e;return(e,{account:n}={})=>{let r=n??t;if(!r){if(!e.account)throw Error("No `account` provided. Pass `account` to parameters or context.");return e.account}return fe(r)}}function Bs(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}const Vs={[R.id]:R,[z.id]:z};function Hs(e,t={}){return u(e.url,{fetchFn:e.fetch,fetchOptions:{headers:Bs(e)},...t})}function Us(r){let{chain:i,getClient:a,remoteFeePayer:o,rpcUrl:s}=r;return a?!i?.serializers&&!o&&!r.requireChain?a:async e=>{let s=await a(e);if(r.requireChain&&(s.chain?.id===void 0||s.chain.id!==e.chainId))throw Error(`Subscription chain mismatch: expected ${e.chainId}, got ${s.chain?.id??`unknown`}.`);let c=s;if(o&&s.transport.key!==`feePayer`){let e=s.request.bind(s),r=de(n({request:t=>e(t)},{retryCount:0}),Hs(o,{retryCount:s.transport.retryCount}))({account:s.account,chain:s.chain,pollingInterval:s.pollingInterval,retryCount:0}),i=t({...r.config,retryCount:0},r.value);c=Object.assign({},s,{request:i.request,transport:{...i.config,...i.value}})}return!i?.serializers||c.chain?.serializers?.transaction?c:Object.assign({},c,{chain:{...i,...e.chainId===void 0?{}:{id:e.chainId},...c.chain,formatters:c.chain?.formatters??i.formatters,prepareTransactionRequest:c.chain?.prepareTransactionRequest??i.prepareTransactionRequest,serializers:c.chain?.serializers?.transaction?c.chain.serializers:i.serializers}})}:({chainId:t})=>{if(!s)throw Error("No `rpcUrl` provided.");let n=t||Number(Object.keys(s)[0]),r=s[n];if(!r)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let a=o?de(u(r),Hs(o)):u(r);return e({chain:Vs[n]??{...i,id:n},transport:a})}}function Ws(e,t){if(t!==void 0&&e.chain?.id!==void 0&&e.chain.id!==t)throw Error(`Chain ID mismatch: expected ${t}, got ${e.chain.id}.`)}function Gs(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}const Ks=A.slice(k.keccak256(O.fromString(`mpp`),{as:`Hex`}),0,4);function qs(e){let t=k.keccak256(O.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,10))}function Js(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(A.toBytes(Ks),0),i[4]=1,i.set(qs(t),5),n&&i.set(qs(n),15),i.set(Ys(r),25),A.fromBytes(i)}function Ys(e){let t=k.keccak256(O.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,7))}function Xs(e,t){return _e.resolve(e).toLowerCase()===_e.resolve(t).toLowerCase()}const Zs=10000n,Qs=[Vr.pathUsd,Vr.usdc,Vr.ousd];async function $s(e,t){let{account:n,amountOut:r,tokenOut:i,tokenIn:a,slippage:o}=t;if(!Number.isFinite(o)||o<0||o>50)throw Error(`Auto-swap slippage must be between 0 and 50 percent.`);if(t.maxAmountIn!==void 0&&t.maxAmountIn<=0n)throw Error(`Auto-swap maxAmountIn must be positive.`);let s=e.chain?.id,c=[];for(let e of a){let t=typeof e==`string`?e:s===void 0?void 0:De(e,{chainId:s})?.address;!t||Xs(t,i)||c.some(e=>Xs(e,t))||c.push(t)}let l=await Promise.allSettled([x(e,{...V.token.getBalance.call(e,{account:n,token:i}),account:null}),...c.map(t=>x(e,{...V.token.getBalance.call(e,{account:n,token:t}),account:null}))]),u=l[0];if(u.status!==`fulfilled`)throw u.reason;let d=u.value;if(d>=r)return;let f=r-d,p=BigInt(Math.round(o*100)),m=t.maxAmountIn??f+f*p/Zs;for(let t=0;t<c.length;t++){let n=l[t+1];if(n.status!==`fulfilled`)continue;let r=n.value;if(r<=0n)continue;let a=c[t];try{let t=await V.dex.getBuyQuote(e,{account:null,tokenIn:a,tokenOut:i,amountOut:f});if(t<=0n||t>m)continue;let n=t+t*p/Zs,o=n<m?n:m;if(r>=o)return[V.token.approve.call(e,{amount:o,spender:ce.stablecoinDex,token:a}),V.dex.buy.call({tokenIn:a,tokenOut:i,amountOut:f,maxAmountIn:o})]}catch{}}throw new tc({currency:i})}function ec(e,t){return e?e===!0?{tokenIn:t,slippage:1}:{tokenIn:e.tokenIn?[...e.tokenIn,...e.fallback===!1?[]:t.filter(t=>!e.tokenIn.some(e=>typeof e==`string`&&Xs(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var tc=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}};function nc(e){let t=BigInt(e.amount),n=e.methodDetails?.splits??[],r=n.reduce((e,t)=>e+BigInt(t.amount),0n);if(r>=t)throw Error(`Invalid charge request: split total must be less than total amount.`);let i=t-r;if(i<=0n)throw Error(`Invalid charge request: primary transfer amount must be positive.`);return[{amount:i.toString(),memo:e.methodDetails?.memo,recipient:e.recipient},...n.map(e=>({amount:BigInt(e.amount).toString(),memo:e.memo,recipient:e.recipient}))]}function rc(e,t,n){t&&(n&&!n.some(e=>Xs(e,t))||e.some(e=>Xs(e,t))||e.push(t))}async function ic(e,t,n){try{return(await V.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function ac(e){let t=e.chain?.feeToken;if(t)return le.toAddress(t);let n=e.chain?.id;return n?Hr[n]:void 0}function oc(e){let t=[];return rc(t,Vr.pathUsd),rc(t,Hr[e]),t}async function sc(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])rc(o,e,n);if(rc(o,await V.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),rc(o,ac(i),n),!a)for(let e of r??[])rc(o,e,n);for(let e of o)if(await ic(i,t,e))return e;return o[0]}const cc=m([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`]);function lc(e){if(e!==void 0)return Ur[e]}function uc(e){let t=lc(e.chainId);return!!t&&d(e.currency,{strict:!1})&&f(e.currency,t.token)}function dc(e){let t=lc(e.chainId),n=e.transfers.length===1?e.transfers[0]:void 0;if(!t||!n?.memo)return;let r=BigInt(n.amount),a=n.memo;return{calls:[{data:i({abi:B.tip20,functionName:`approve`,args:[t.swap,r]}),to:t.token},{data:i({abi:cc,functionName:`swapTo`,args:[t.token,r,e.currency,n.recipient,a]}),to:t.swap}],settlementSender:t.swap,transfers:[{amount:r,memo:a,recipient:n.recipient}]}}async function fc(e,t){let n=dc(t);if(n)try{return await x(e,V.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await _(e,{account:t.account,calls:n.calls}),n)}catch{return}}const pc=10n**BigInt(4);function mc(e={}){let{address:t,amount:n,chainId:r=Z.mainnet}=e;if(r!==Z.mainnet)return;let i=new URL(`https://wallet.tempo.xyz/agent?action=fund&intent=mach&chainId=4217`);if(t&&d(t,{strict:!1})&&i.searchParams.set(`address`,c(t)),n!==void 0&&n>0n){let e=(n+pc-1n)/pc,t=e%100n,r=(e/100n).toString();i.searchParams.set(`amount`,t===0n?r:`${r}.${t.toString().padStart(2,`0`).replace(/0$/,``)}`)}return i.toString()}async function hc(e,t){let n=lc(t.chainId);if(!n)return;let r=await x(e,V.token.getBalance.call(e,{account:t.account,token:n.token})).catch(()=>void 0);return typeof r==`bigint`?r:void 0}async function gc(e,t){let{account:n,amount:r,chainId:i}=t,a=await hc(e,{account:n,chainId:i});if(a===void 0||a>=r)return;let s=e=>`${o(e,6)} MACH`,c=r-a;return{fundingUrl:mc({address:n,amount:c,chainId:i}),reason:`requested ${s(r)}, available ${s(a)}`,shortfall:c}}async function _c(e,t){let n=await gc(e,t);if(n)return new Tt({fundingUrl:n.fundingUrl,reason:n.reason})}const vc={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]};function yc(e){return{name:`MPP`,version:`3`,chainId:e}}function bc(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function xc(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:yc(n),types:vc,primaryType:`Proof`,message:bc({account:t,challengeId:r,realm:i})}}function Sc(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const Cc=[...B.accountKeychain.filter(e=>e.type===`error`),...B.tip20.filter(e=>e.type===`error`)];function wc(e){let t=new Set,n=e;for(;typeof n==`object`&&n&&!t.has(n);){t.add(n);let e=n.data;if(Dc(e))return e;let r=e?.data;if(Dc(r))return r;n=n.cause}}function Tc(e,t){let n=wc(e);if(!n)return;let i=(()=>{try{return r({abi:Cc,data:n})}catch{return}})();if(i?.errorName===`SpendingLimitExceeded`){let n=t.account.accessKeyAddress;return new St({accessKey:typeof n==`string`?n:void 0,account:t.account.address,cause:e})}if(i?.errorName===`InsufficientBalance`){let[n,r,a]=i.args;return new Tt({cause:e,reason:`${t.account.address} holds ${n} of token ${a}, but the payment requires ${r}`})}}async function Ec(e,t){try{return await t()}catch(t){throw Tc(t,e)??t}}function Dc(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{8}/.test(e)}const Oc=7200n,kc=64n,Ac=s({abi:B.zonePortal,name:`WithdrawalProcessed`});function jc(e){return Number.isInteger(e)&&e>0&&e<4217e5}function Mc(e,t){return jc(t)?e===!0||(e?.includes(t)??!1):!1}function Nc(e){return ce.zonePortal(e)}Nc(0).slice(0,-16).toLowerCase();function Pc(e){if(e>=2**32)return e%2**32;if(e>142431e4&&e<142432e4)return e-142431e4;if(e>4217e5&&e<42171e4)return e-4217e5;throw Error(`Cannot derive a Zone ID from chain ID ${e}. Pass \`zoneId\`.`)}function Fc(e){if(e>=2**32)return Math.floor(e/2**32);if(e>142431e4&&e<142432e4)return 42431;if(e>4217e5&&e<42171e4)return 4217}function Ic(e){return k.keccak256(E.encodePacked([`address`,`bytes32`,`uint64`],[e.sender,e.transactionHash,e.fallbackNonce]))}async function Lc(e,t){let{blockNumber:n,sender:r,transactionHash:i}=t,a=t=>x(e,{abi:B.zoneOutbox,address:ce.zoneOutbox,blockNumber:t,functionName:`lastFallbackNonce`}),[o,s]=await Promise.all([a(n-1n),a(n)]);if(s<=o)throw Error(`Zone withdrawal transaction ${i} did not request a withdrawal from the outbox.`);if(s-o>kc)throw Error(`Zone withdrawal transaction ${i} has ${s-o} candidate sender tags, more than ${kc}.`);let c=[];for(let e=o+1n;e<=s;e++)c.push(Ic({fallbackNonce:e,sender:r,transactionHash:i}));return c}async function Rc(e,t){let{senderTags:n,timeoutMs:r=6e4}=t;if(!Number.isFinite(r)||r<0)throw Error(`Zone settlement timeout must be a finite, non-negative number.`);if(n.length===0)throw Error(`Zone settlement needs at least one sender tag.`);let i=await v(e,{cacheTime:0}),a=i>Oc?i-Oc:0n,o=Date.now()+r;for(;;){if(a<=i){let[r]=await y(e,{address:t.portal,event:Ac,args:{senderTag:[...n],...t.to?{to:t.to}:{}},fromBlock:a,toBlock:i});if(r?.transactionHash&&r.args.senderTag)return{hash:r.transactionHash,senderTag:r.args.senderTag};a=i+1n}if(Date.now()+500>o)throw Error(`Zone withdrawal ${n.join(` or `)} did not settle on Tempo within ${r}ms.`);await new Promise(e=>setTimeout(e,500)),i=await v(e,{cacheTime:0})}}const zc=[`push`,`pull`],Bc=K.object({amount:q(),memo:K.optional(Mt()),recipient:K.pipe(K.string(),K.transform(e=>e))}),Vc=(1n<<64n)-1n,Hc={dev_second:1n,day:86400n,week:604800n},Uc=K.pipe(J(),K.transform(e=>e.toLowerCase())),Wc=K.object({accessKeyAddress:Uc,keyType:K.enum([`p256`,`secp256k1`,`webAuthn`]),keyToken:K.optional(K.pipe(K.string().check(K.regex(/^0x[0-9a-fA-F]{120}$/)),K.transform(e=>e)))}),Gc=K.object({accessKey:K.optional(Wc),chainId:K.optional(K.number())}),Kc=kt(`subscriptionExpires must be a valid date`).check(K.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),qc=K.enum([`dev_second`,`day`,`week`]),Jc=K.pipe(K.union([K.string(),K.bigint(),K.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),K.transform(e=>e.toString())).check(K.regex(/^[1-9]\d*$/,`Invalid periodCount`),K.refine(e=>{try{return BigInt(e)<=Vc}catch{return!1}},`periodCount exceeds uint64`));function Yc(e){return K.refine(e=>{let{amount:t,decimals:n}=e;return g(t,n)>0n},e)}function Xc(e){let{periodCount:t,periodUnit:n}=e;try{let e=Hc[n];return e!==void 0&&BigInt(t)*e<=Vc}catch{return!1}}const Zc=jn({name:`tempo`,intent:`charge`,schema:{credential:{payload:K.discriminatedUnion(`type`,[K.object({hash:Mt(),type:K.literal(`hash`)}),K.object({signature:Y(),type:K.literal(`transaction`)}),K.object({signature:Y(),type:K.literal(`proof`)}),K.object({hash:Mt(),senderTag:Mt(),type:K.literal(`zone`),zoneId:K.number().check(K.refine(jc,`Invalid Zone ID`))})])},request:K.pipe(K.object({machineTokenEnabled:K.optional(K.boolean()),amount:q(),chainId:K.optional(K.number()),currency:K.string(),decimals:K.number(),description:K.optional(K.string()),externalId:K.optional(K.string()),feePayer:K.optional(K.pipe(K.union([K.boolean(),K.custom()]),K.transform(e=>typeof e==`object`||e))),memo:K.optional(K.never()),recipient:K.optional(K.string()),splits:K.optional(K.array(Bc).check(K.minLength(1),K.maxLength(10))),supportedModes:K.optional(K.array(K.enum(zc)).check(K.minLength(1))),zones:K.optional(K.union([K.literal(!0),K.array(K.number().check(K.refine(jc,`Invalid Zone ID`))).check(K.minLength(1))]))}).check(K.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=g(e,t),i=n.reduce((e,n)=>e+g(n.amount,t),0n);return n.every(e=>g(e.amount,t)>0n)&&i<r},`Invalid splits`)),K.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,zones:c,...l})=>({...l,amount:g(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==void 0||c!==void 0?{methodDetails:{...e!==void 0&&{machineTokenEnabled:e},...n!==void 0&&{chainId:n},...i!==void 0&&{feePayer:i},...o!==void 0&&{splits:o.map(e=>({...e,amount:g(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s},...c!==void 0&&{zones:c}}}:{}})))}}),Qc=jn({name:`tempo`,intent:`session`,schema:{credential:{payload:K.discriminatedUnion(`action`,[K.object({action:K.literal(`open`),authorizedSigner:K.optional(K.string()),channelId:Mt(),cumulativeAmount:q(),descriptor:K.optional(K.custom()),signature:Y(),transaction:Y(),type:K.literal(`transaction`)}),K.object({action:K.literal(`topUp`),additionalDeposit:q(),channelId:Mt(),descriptor:K.optional(K.custom()),transaction:Y(),type:K.literal(`transaction`)}),K.object({action:K.literal(`voucher`),channelId:Mt(),cumulativeAmount:q(),descriptor:K.optional(K.custom()),signature:Y()}),K.object({action:K.literal(`close`),channelId:Mt(),closeSignature:Y(),cumulativeAmount:q(),descriptor:K.optional(K.custom()),signature:Y()})])},request:K.pipe(K.object({amount:q(),chainId:K.optional(K.number()),channelId:K.optional(Mt()),configurableVouchers:K.optional(K.boolean()),currency:K.string(),decimals:K.number(),escrowContract:K.optional(K.string()),feePayer:K.optional(K.pipe(K.union([K.boolean(),K.custom()]),K.transform(e=>typeof e==`object`||e))),feeToken:K.optional(J()),minVoucherDelta:K.optional(q()),operator:K.optional(J()),recipient:K.optional(K.string()),sessionProtocol:K.optional(K.enum([dt.v2,dt.v1])),sessionSnapshot:K.optional(K.custom()),suggestedDeposit:K.optional(q()),unitType:K.string()}).check(K.refine(({amount:e,decimals:t})=>g(e,t)>0n,`Session amount must be greater than 0`)),K.transform(({amount:e,chainId:t,channelId:n,configurableVouchers:r,decimals:i,escrowContract:a,feePayer:o,feeToken:s,minVoucherDelta:c,operator:l,sessionProtocol:u,sessionSnapshot:d,suggestedDeposit:f,...p})=>({...p,amount:g(e,i).toString(),...f?{suggestedDeposit:g(f,i).toString()}:{},methodDetails:{escrowContract:a,...n!==void 0&&{channelId:n},...c!==void 0&&{minVoucherDelta:g(c,i).toString()},...t!==void 0&&{chainId:t},...o!==void 0&&{feePayer:o},...s!==void 0&&{feeToken:s},...l!==void 0&&{operator:l},...r!==void 0&&{configurableVouchers:r},...u!==void 0&&{[ut.sessionProtocol]:u},...d!==void 0&&{[ut.sessionSnapshot]:d}}})))}}),$c=jn({name:`tempo`,intent:`subscription`,schema:{credential:{payload:K.object({signature:Y(),type:K.literal(`keyAuthorization`)})},request:K.pipe(K.object({amount:q(),accessKey:K.optional(Wc),chainId:K.optional(K.number()),currency:Uc,decimals:K.number(),description:K.optional(K.string()),externalId:K.optional(K.string()),methodDetails:K.optional(Gc),periodCount:Jc,periodUnit:qc,recipient:Uc,subscriptionExpires:Kc}).check(Yc(`Subscription amount must be greater than 0`),K.refine(Xc,`Subscription period exceeds uint64`)),K.transform(({accessKey:e,amount:t,chainId:n,decimals:r,methodDetails:i,subscriptionExpires:a,...o})=>{let s={...i,...e!==void 0&&{accessKey:e},...n!==void 0&&{chainId:n}};return{...o,amount:g(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}}),el=K.object({account:K.optional(K.custom()),autoSwap:K.optional(K.custom()),feeToken:K.optional(K.custom()),mode:K.optional(K.enum(zc))});function tl(e={}){let{clientId:t}=e;if((e.maxAmount!==void 0||e.maxAtomicAmount!==void 0)&&e.currencies===void 0)throw Error(`Tempo charge maxAmount and maxAtomicAmount require currencies.`);for(let t of e.currencies??[])vl(e.maxAmount,typeof t==`string`?e.decimals:t.decimals);let n={maxAmount:e.maxAmount,maxAtomicAmount:e.maxAtomicAmount===void 0?void 0:BigInt(e.maxAtomicAmount)},r=Us({chain:R,getClient:e.getClient,rpcUrl:Wr}),i=zs({account:e.account});ul(e.zone);let a=new Map,o=Mn(Zc,{canHandleChallenge({challenge:t}){try{yl(e,n,t.request);let{amount:r,methodDetails:i}=t.request,a=i?.supportedModes;return!(i?.memo!==void 0&&a&&!a.includes(`pull`)&&BigInt(r)>0n)}catch{return!1}},context:el,async createCredential(o){let{challenge:s,context:c}=o,l=it(o),u=()=>Error(`The Zone withdrawal this challenge resumes is no longer outstanding. Retry the request to pay it.`);yl(e,n,s.request);let d=s.request.methodDetails?.chainId,f=d??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),p=await r({chainId:f});Ws(p,f);let m=f??p.chain?.id;if(Gs(e.allowedChainIds,m),m===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");d===void 0&&yl(e,n,s.request,m);let{request:h}=s,{amount:g,methodDetails:_}=h,v=_?.supportedModes??[`pull`,`push`],y=e.zone?.client.chain,x=e.zone?e.zone.zoneId??Pc(y?.id??0):void 0,C=y?.sourceId??(y?Fc(y.id):void 0),te=c?.mode??e.mode;if(BigInt(g)>0n&&e.zone&&x!==void 0&&C===m&&v.includes(`push`)&&(te===void 0||te===`push`)&&Mc(_?.zones,x)&&!_?.splits){let r={assertFee:t=>yl(e,n,h,m,t),challenge:s,clientId:t,client:p,origin:ll(Ga(o)),pending:a,zone:e.zone,zoneId:x},i=al(r);if(i)return sl(r,i);if(l?.resume)throw u();if(s.expires&&kn(s.expires,s.id),dl(s.expires,e.zone.settlementTimeoutMs))return il(r)}if(l?.resume)throw u();let ne=i(p,c),re=async t=>await e.resolveAccount?.({account:ne,chainId:m,operation:t})??ne;if(BigInt(g)===0n){let e=await re({kind:`signPaymentProof`});return wn({challenge:s,payload:{signature:await T(p,{account:e,...xc({account:e.address,chainId:m,challengeId:s.id,realm:s.realm})}),type:`proof`},source:Sc({address:e.address,chainId:m})})}let E=h.currency,D=uc({chainId:m,currency:E}),O=_?.memo??Js({challengeId:s.id,clientId:t,serverId:s.realm}),k=nc({amount:g,methodDetails:{..._,memo:O},recipient:h.recipient}),A=k.map(e=>V.token.transfer.call(p,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:E})),j=ec(c?.autoSwap??e.autoSwap,Qs),M=_?.machineTokenEnabled===!0&&!l?dc({chainId:m,currency:E,transfers:k}):void 0,N=ne,P,F=!1;if(M){let e=await(async()=>{try{return await re({calls:M.calls,kind:`executeCalls`})}catch{return}})();e&&(P=await fc(p,{account:e.address,chainId:m,currency:E,transfers:k}),P?N=e:F=!0)}let I;if(!P){if(N=await re({kind:`executeCalls`,...j?{}:{calls:A}}),I=j?await $s(p,{account:N.address,amountOut:BigInt(g),tokenOut:E,tokenIn:j.tokenIn,slippage:j.slippage,maxAmountIn:j.maxAmountIn}):void 0,l&&I)throw new wt({limit:l.limit,reason:`asset`});if(F&&!j){let e=await nl(p,{account:N.address,amount:BigInt(g),chainId:m,currency:E});if(e)throw e}}let L=P?.calls??[...I??[],...A],R=oc(m),z=(c?.feeToken??e.feeToken)||(P||D?await sc({account:N.address,allowedTokens:R,candidateTokens:R,client:p,prioritizeCandidates:!0}):void 0),ie=(()=>{let t=c?.mode??e.mode,n=_?.memo!==void 0;if(t){if(!v.includes(t))throw Error(`Challenge does not support ${t} mode.`);if(n&&t===`push`)throw Error(`Push mode is not supported for a challenge with a memo.`);return t}if(n){if(!v.includes(`pull`))throw Error(`Challenge has a memo but does not support pull mode.`);return`pull`}let r=N.type===`json-rpc`?`push`:`pull`;return v.includes(r)?r:v[0]})(),ae=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!s.expires)return e;let t=Math.floor(new Date(s.expires).getTime()/1e3)+1;return Math.min(e,t)})(),oe=()=>{l&&s.expires&&kn(s.expires,s.id)};if(ie===`push`){oe();let{receipts:e}=N.type===`local`?{receipts:[await Ec({account:N},()=>w(p,{account:N,calls:L,...z?{feeToken:z}:{},nonceKey:`expiring`,validBefore:ae}))]}:await S(p,{account:N,...z?{capabilities:{feeToken:z}}:{},calls:L,experimental_fallback:L.length===1,forceAtomic:L.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Za(Error(`No transaction receipt returned.`));return wn({challenge:s,payload:{hash:t,type:`hash`},source:Sc({address:N.address,chainId:m})})}let B=()=>{if(_?.feePayer!==!0)return;let e=15e3,t=s.expires?new Date(s.expires).getTime():1/0,n=Date.now();if(!(t-n>=e))throw Error(`Sponsored challenge expires in less than 15 seconds; the fee payer would reject the transaction. Request a new challenge.`);if(!(ae*1e3-n>=e))throw Error(`Sponsored transaction preparation took too long: less than 15 seconds of its validity window remain, so the fee payer would reject it.`)};B();let se=await Ec({account:N},()=>b(p,{account:N,calls:L,...z?{feeToken:z}:{},nonceKey:`expiring`,validBefore:ae}));if(se.gas=(se.gas??0n)+5000n,_?.feePayer){let e=se;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return B(),oe(),wn({challenge:s,payload:{signature:await ee(p,se),type:`transaction`},source:Sc({address:N.address,chainId:m})})}}),s=new Map,c=async t=>{yl(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,a=it(t),c=s.get(i);if(a&&at(a,c?.constraints),c)return c.promise;let l=o.createCredential(t).finally(()=>s.delete(i));return s.set(i,{constraints:a,promise:l}),l};return tt(Ha({...o,createCredential:c},rl),{assert:t=>yl(e,n,t.request),resumes:t=>ol(a,t,e.zone&&(e.zone.zoneId??Pc(e.zone.client.chain?.id??0)))})}async function nl(e,t){let{account:n,amount:r,chainId:i,currency:a}=t,o=await x(e,V.token.getBalance.call(e,{account:n,token:a})).catch(()=>void 0);if(!(typeof o!=`bigint`||o>=r))return _c(e,{account:n,amount:r,chainId:i})}function rl(e){let t=Zc.schema.credential.payload.safeParse(yn(e).payload);if(!t.success)return;let n=t.data;if(n.type===`hash`||n.type===`zone`)return n.hash;let r=n.signature;if(n.type!==`transaction`||!r.startsWith(ve.serializedType))return;let i=ve.deserialize(r);if(!(!i.signature||i.feePayerSignature===null)&&ve.serialize(i)===r)return p(r)}function il(e){let{challenge:t,origin:n,pending:r,zoneId:i}=e,a={sent:!1},o={challenge:t,origin:n,terms:ml(t,i),waiters:0,withdrawal:_l(e,a)},s=pl(t);return r.set(s,o),o.withdrawal.catch(()=>{!a.sent&&r.get(s)===o&&r.delete(s)}),sl(e,o)}function al(e){let{challenge:t,pending:n,zoneId:r}=e,i=n.get(pl(t));if(i)return i;let a=ml(t,r);if(a!==void 0){for(let[e,t]of n)if(t.terms===a){if(!gl(t.challenge.expires)){n.delete(e);continue}if(t.redeemedLate)throw new Ct({challengeId:t.challenge.id,senderTags:t.senderTags,zoneId:r});if(!(t.waiters>0))return t}}}function ol(e,t,n){if(n===void 0||e.size===0)return!1;if(e.has(pl(t)))return!0;let r=ml(t,n);if(r===void 0)return!1;for(let t of e.values())if(t.terms===r&&gl(t.challenge.expires)&&(t.redeemedLate||t.waiters===0))return!0;return!1}async function sl(e,t){t.waiters++;try{return await cl(e,t)}finally{t.waiters--}}async function cl(e,t){let{client:n,origin:r,pending:i,zone:a,zoneId:o}=e,{challenge:s}=t,c=s.request.recipient,l=pl(s);if((l===pl(e.challenge)?r!==void 0&&t.origin!==void 0&&r!==t.origin:!r||r!==t.origin)||!gl(s.expires))throw new Ct({challengeId:s.id,zoneId:o});let u=await t.withdrawal,d=u.senderTags??await Lc(a.client,u).catch(e=>{let t=Error(`Zone withdrawal transaction ${u.transactionHash} was sent, but its sender tag could not be read from the Zone. Retry the challenge to resume without withdrawing again.`);throw Object.defineProperty(t,"cause",{configurable:!0,value:e,writable:!0}),Za(t)}),f;try{f=await Rc(n,{portal:Nc(o),senderTags:d,timeoutMs:fl(s.expires,a.settlementTimeoutMs),to:c})}catch(e){throw new Ct({cause:e,challengeId:s.id,senderTags:d,zoneId:o})}i.get(l)===t&&(hl(s.expires)?(t.redeemedLate=!0,t.senderTags=[f.senderTag]):i.delete(l));let{hash:p,senderTag:m}=f;return wn({challenge:s,payload:{hash:p,senderTag:m,type:`zone`,zoneId:o}})}function ll(e){if(e)try{let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`?void 0:t.origin}catch{return}}function ul(e){let t=e?.settlementTimeoutMs;if(t!==void 0&&(!Number.isFinite(t)||t<0))throw Error("`zone.settlementTimeoutMs` must be a finite, non-negative number.");let n=e?.client.chain?.id;if(e?.zoneId===void 0||n===void 0||Fc(n)===void 0)return;let r=Pc(n);if(r!==e.zoneId)throw Error(`zone.zoneId ${e.zoneId} does not match Zone ${r} of the zone.client chain ${n}.`)}function dl(e,t){if(!e)return!0;let n=t??6e4;return new Date(e).getTime()-Date.now()>n+15e3}function fl(e,t){let n=t??6e4;return e?Math.max(0,Math.min(n,new Date(e).getTime()-Date.now())):n}function pl(e){return JSON.stringify(e)}function ml(e,t){let n;try{n=e.opaque===void 0?e.meta:Et(e.opaque)}catch{return}let{digest:r,intent:i,method:a,realm:o,request:s}=e;return G({digest:r,intent:i,meta:An(n),method:a,realm:o,request:s,zoneId:t})}function hl(e){if(!e)return!1;let t=new Date(e).getTime();return!Number.isNaN(t)&&Date.now()>=t}function gl(e){if(!e)return!0;let t=new Date(e).getTime();return Number.isNaN(t)||Date.now()<t+3e5}async function _l(e,t){let{assertFee:n,challenge:r,clientId:i,zone:a}=e,o=r.request,s=a.client.account;if(!s)throw Error("`zone.client` requires an account.");let c=BigInt(o.amount),l=o.currency,u=o.recipient,d=Js({challengeId:r.id,clientId:i,serverId:r.realm}),f=await V.zone.getWithdrawalFee(a.client);n(f);let[,m]=V.zone.requestWithdrawal.calls({amount:c,fallbackRecipient:s.address,memo:d,to:u,token:l}),g=await b(a.client,{account:s,calls:[V.token.approve.call({amount:c+f,spender:ce.zoneOutbox,token:l}),m]}),_=await ee(a.client,g);t.sent=!0;let v=p(_),y=await C(a.client,{serializedTransaction:_}).catch(e=>te(a.client,{hash:v,timeout:15e3}).catch(()=>{let t=new vt({cause:e,transactionHash:v});throw t.message=`Zone withdrawal outcome is unknown: transaction ${v} may have been sent. Retrying this challenge does not withdraw again.`,t}));if(y.status===`reverted`)throw t.sent=!1,Error(`Zone withdrawal transaction ${y.transactionHash} reverted.`);let[x]=h({abi:B.zoneOutbox,eventName:`WithdrawalRequested`,logs:y.logs});return{blockNumber:y.blockNumber,sender:s.address,senderTags:x?[Ic({fallbackNonce:x.args.fallbackNonce,sender:x.args.sender,transactionHash:y.transactionHash})]:void 0,transactionHash:y.transactionHash}}function vl(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo charge maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo charge maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return g(e,t)}}function yl(e,t,n,r,i){let{methodDetails:a,recipient:o}=n,s=a?.chainId;if(e.expectedChainId!==void 0&&s!==void 0&&s!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${s}.`);(s!==void 0||e.allowedChainIds?.length===0)&&Gs(e.allowedChainIds,s);let c=e.currencies?Oe(e.currencies,n.currency,{chainId:s??r??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),decimals:e.decimals}):void 0;if(e.currencies&&!c)throw Error(`Tempo charge currency is not allowed: ${n.currency}.`);if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase()));if(!o||!t.has(o.toLowerCase()))throw Error(`Unexpected primary recipient: ${o}`);let n=a?.splits;if(n){for(let e of n)if(!t.has(e.recipient.toLowerCase()))throw Error(`Unexpected split recipient: ${e.recipient}`)}}if(t.maxAtomicAmount===void 0&&t.maxAmount===void 0)return;let l=BigInt(n.amount)+(i??0n),u=i===void 0?`amount exceeds`:`amount plus Zone withdrawal fee exceeds`;if(t.maxAtomicAmount!==void 0&&l>t.maxAtomicAmount)throw Error(`Tempo charge ${u} maxAtomicAmount.`);if(t.maxAmount!==void 0&&l>vl(t.maxAmount,c?.decimals))throw Error(`Tempo charge ${u} maxAmount.`)}const bl=(1n<<96n)-1n;function xl(e){return e>=0n&&e<=bl}function Sl(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return xl(t)?t:void 0}function Cl(e){return wl(e),e}function wl(e){if(!xl(e))throw Error(`Value ${e} is outside uint96 bounds.`)}const Tl=new Set([`open`,`topUp`,`voucher`,`close`]);function El(e){return typeof e==`object`&&!!e}function Dl(e){return typeof e==`string`&&Tl.has(e)}function Ol(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!Dl(t.action))}function kl(e,t=`No session credential context available.`){if(!Ol(e))throw Error(t);return e}function Al(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function jl(e){return El(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function Ml(e){return El(e)?e.method===`tempo`&&e.intent===`session`&&e.status===`success`&&typeof e.timestamp==`string`&&typeof e.reference==`string`&&typeof e.challengeId==`string`&&typeof e.channelId==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.spent==`string`&&(e.units===void 0||typeof e.units==`number`)&&(e.txHash===void 0||typeof e.txHash==`string`):!1}function Nl(e){let t=D.toString(e),n=JSON.parse(t);if(!Ml(n))throw Error(`Invalid session receipt.`);return n}function Pl(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function Fl(e){let t=`message`,n=[];for(let r of e.split(`
|
|
8
8
|
`))r.startsWith(`event: `)?t=r.slice(7).trim():r.startsWith(`data: `)?n.push(r.slice(6)):r===`data:`&&n.push(``);if(n.length===0)return null;let r=n.join(`
|
|
9
|
-
`);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=Fl(r);return Al(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=Fl(r);return jl(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function Fl(e){try{return JSON.parse(e)}catch{return null}}function Il(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function Ll(){return JSON.stringify({mpp:`payment-close-request`})}function Rl(e){let t=zl(e);return t?t.mpp===`authorization`&&typeof t.authorization==`string`?{mpp:`authorization`,authorization:t.authorization}:t.mpp===`message`&&typeof t.data==`string`?{mpp:`message`,data:t.data}:t.mpp===`payment-close-request`?{mpp:`payment-close-request`}:t.mpp===`payment-close-ready`&&jl(t.data)?{mpp:`payment-close-ready`,data:t.data}:t.mpp===`payment-error`&&typeof t.status==`number`&&typeof t.message==`string`?{mpp:`payment-error`,status:t.status,message:t.message}:t.mpp===`payment-need-voucher`&&Al(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&jl(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function zl(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}const Bl=`0x4d50500000000000000000000000000000000000`;function Vl(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function Hl(e){let t=E.encode(E.from([`address payer`,`address payee`,`address operator`,`address token`,`bytes32 salt`,`address authorizedSigner`,`bytes32 expiringNonceHash`,`address escrow`,`uint256 chainId`]),[e.payer,e.payee,e.operator,e.token,e.salt,e.authorizedSigner,e.expiringNonceHash,e.escrow??`0x4d50500000000000000000000000000000000000`,BigInt(e.chainId)]);return k.keccak256(t)}function Ul(e){return ve.encodeForSigning(e)}function Wl(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function Gl(e,t){return k.keccak256(A.concat(Ul(e),t.sender))}const Kl=[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],ql=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],Jl={name:`descriptor`,type:`tuple`,components:Kl},Yl=[{type:`function`,name:`CLOSE_GRACE_PERIOD`,stateMutability:`view`,inputs:[],outputs:[{type:`uint64`}]},{type:`function`,name:`VOUCHER_TYPEHASH`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`function`,name:`open`,stateMutability:`nonpayable`,inputs:[{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`deposit`,type:`uint96`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`}],outputs:[{name:`channelId`,type:`bytes32`}]},{type:`function`,name:`settle`,stateMutability:`nonpayable`,inputs:[Jl,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[Jl,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[Jl,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[Jl],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[Jl],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[Jl],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:Kl},{name:`state`,type:`tuple`,components:ql}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:ql}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:ql}]},{type:`function`,name:`computeChannelId`,stateMutability:`view`,inputs:[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`getVoucherDigest`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`verifyVoucher`,stateMutability:`view`,inputs:[Jl,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[{name:`valid`,type:`bool`}]},{type:`function`,name:`domainSeparator`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`event`,name:`ChannelOpened`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`authorizedSigner`,type:`address`},{name:`salt`,type:`bytes32`},{name:`expiringNonceHash`,type:`bytes32`},{name:`deposit`,type:`uint96`}]},{type:`event`,name:`OpeningCommitmentRecorded`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`signer`,type:`address`,indexed:!0},{name:`commitment`,type:`bytes32`}]},{type:`event`,name:`Settled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`cumulativeAmount`,type:`uint96`},{name:`deltaPaid`,type:`uint96`},{name:`newSettled`,type:`uint96`}]},{type:`event`,name:`TopUp`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`additionalDeposit`,type:`uint96`},{name:`newDeposit`,type:`uint96`}]},{type:`event`,name:`CloseRequested`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`closeGraceEnd`,type:`uint256`}]},{type:`event`,name:`ChannelClosed`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`settledToPayee`,type:`uint96`},{name:`refundedToPayer`,type:`uint96`}]},{type:`event`,name:`CloseRequestCancelled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0}]},{type:`error`,name:`RootKeyRetired`,inputs:[{name:`account`,type:`address`}]},{type:`error`,name:`SignerConfigChanged`,inputs:[{name:`signer`,type:`address`}]},{type:`error`,name:`SaltNotSignerCommitment`,inputs:[{name:`signer`,type:`address`},{name:`commitment`,type:`bytes32`}]}];function Xl(e){return e.type===`secp256k1`?e.signature.s<=57896044618658097711785492504343953926418782139537452191302581570759080747168n:e.type===`p256`||e.type===`webAuthn`?e.signature.s<=57896044605178124381348723474703786764998477612067880171211129530534256022184n:!0}function Zl(e){if(e.type===`configurable`)return{...e,signatures:e.signatures.map(e=>Zl(e))};if(Xl(e))return e;if(e.type===`secp256k1`){let{r:t,s:n,yParity:r}=e.signature;return{...e,signature:{r:t,s:115792089237316195423570985008687907852837564279074904382605163141518161494337n-n,yParity:+(r===0)}}}return e.type===`p256`||e.type===`webAuthn`?{...e,signature:{...e.signature,s:115792089210356248762697446949407573529996955224135760342422259061068512044369n-e.signature.s}}:e}function Ql(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function $l(e){return e===void 0||BigInt(e)===0n}function eu(e,t){let{account:n,config:r,signatures:i}=e,a=me.getSignPayload({account:n,config:r,payload:t}),o=Number(r.threshold),s,c=0,l;for(let[e,t]of i.entries()){if(!Ql(t.type)||!Xl(t)||e>0&&c>=o)return!1;let n=H.extractAddress({payload:a,signature:t});if(!H.verify(t,{address:n,payload:a}))return!1;let i=r.owners.find(e=>Ys(e.owner,n));if(!i)return!1;let u=Number(i.weight);if(u===0)return!1;let d=BigInt(n);if(s!==void 0&&s>=d)return!1;s=d,c+=u,l=l===void 0?u:Math.min(l,u)}return!(i.length===0||c<o||l!==void 0&&c>=o+l)}function tu(e,t){let{account:n,commitment:r,payload:i}=t;if(!Ys(e.account,n)||BigInt(e.config.version??0n)===0n&&e.config.owners.some(({owner:t})=>Ys(t,e.account)))return!1;if($l(r)){if(BigInt(e.config.version??0n)!==0n||!Ys(me.getAddress(e.config),n))return!1}else if(me.getCommitment(e.config).toLowerCase()!==r.toLowerCase())return!1;return eu(e,i)}function nu(e,t){return{name:`TIP20 Channel Reserve`,version:`1`,chainId:t,verifyingContract:e}}const ru={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},iu={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]};function au(e,t,n){return l({domain:nu(e,t),types:iu,primaryType:`CloseAuthorization`,message:n})}function ou(e,t){return he.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function su(e,t,n){return e.toLowerCase()===he.address.toLowerCase()?ou(t,n):l({domain:nu(e,t),types:ru,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function cu(e,t,n,r){let i=lu(e);return i?uu(i,t,n,r):!1}function lu(e){let t=H.from(e);if(H.serialize(t).toLowerCase()===e.toLowerCase())return t}function uu(e,t,n,r){if(e.type===`configurable`)return r.configurable?tu(e,{account:n,commitment:r.openingCommitment,payload:t}):!1;if(!Ql(e.type)||!Xl(e)||!$l(r.openingCommitment))return!1;let i=H.extractAddress({payload:t,signature:e});return H.verify(e,{address:i,payload:t})&&Ys(i,n)}function du(e){return e.source===`configurable`}function fu(e){return e.source===`accessKey`&&`accessKeyAddress`in e}function pu(e,t){return se.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function mu(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===he.address.toLowerCase())try{return await pu(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return T(e,{account:t,domain:nu(r,i),types:ru,primaryType:`Voucher`,message:n})})(),o=H.from(a);if(!Ql(o.type)&&o.type!==`configurable`)throw Error(`TIP-1034 vouchers require a TIP-1020 primitive or TIP-1166 configurable account signature; received "${o.type}".`);return H.serialize(Zl(o))}async function hu(e,t,n,r,i){let a=fu(t)?await t.sign({hash:au(r,i,n),raw:!0}):await T(e,{account:t,domain:nu(r,i),types:iu,primaryType:`CloseAuthorization`,message:n}),o=H.from(a);if(!Ql(o.type)&&o.type!==`configurable`)throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive or TIP-1166 configurable account signature; received "${o.type}".`);return H.serialize(Zl(o))}function gu(e,t,n,r,i={}){try{let a=su(e,t,n);return cu(n.signature,a,r,i)}catch{return!1}}function _u(e){return typeof e==`object`&&!!e}function vu(e){return typeof e==`string`&&d(e,{strict:!1})?e:void 0}function yu(e){return vu(e.accessKeyAddress)}function bu(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(A.random(8))%e)}function xu(e){return yu(e)??e.address}function Su(e){return Cu(e)!==void 0}function Cu(e){let t=yu(e);if(t===void 0)return du(e)?e:void 0;let n=e.delegate;if(n&&du(n)&&n.address.toLowerCase()===t.toLowerCase())return n}async function wu(e,t){let n=Cu(t);if(!n)return A.random(32);let{config:r}=n,i=await V.accounts.getConfigCommitment(e,{account:n.address}),a=r?me.getCommitment(r):void 0;if(BigInt(i)!==0n){if(a&&a.toLowerCase()!==i.toLowerCase())throw Error(`Configurable account ${n.address} holds a config whose commitment ${a} does not match its on-chain commitment ${i}. Use the account's current config.`);return i}if(!a||BigInt(r.version??0n)!==0n)throw Error(`Configurable account ${n.address} is not registered, so it needs its version-zero config to open a channel.`);return a}function Tu(e,t){let n=Cc(e);if(n)try{let i=r({abi:Yl,data:n});if(i.errorName!==`SignerConfigChanged`&&i.errorName!==`RootKeyRetired`)return;let[a]=i.args;return a.toLowerCase()===t.signer.toLowerCase()?new xt({cause:e,channelId:t.channelId,reason:i.errorName,signer:a}):void 0}catch{return}}async function Eu(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return Tc({account:n},()=>b(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}}))}async function Du(e,t){return await ee(e,t)}function Ou(e,t,n=!1){let r=e.request.methodDetails,i=_u(r)?vu(r.escrowContract)??vu(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!Au(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!Au(i,a)?i:a}function ku(e,t,n,r){return wn({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${t.descriptor?.payer??r.address}`})}function Au(e,t){return e.toLowerCase()===t.toLowerCase()}function ju(e,t){let n=Cu(e);if(!n?.config)return;let{config:r}=n;if(me.getCommitment(r).toLowerCase()!==t.salt.toLowerCase()&&(BigInt(r.version??0n)!==0n||me.getAddress(r).toLowerCase()!==n.address.toLowerCase()))throw Error(`Configurable account ${n.address} holds a config that does not match the channel's opening commitment (salt ${t.salt}), so it cannot sign a voucher the channel settles. Sign with the config the channel opened with, or close the channel and open a new one.`)}async function Mu(e,t,n,r,i,a=Bl){let o=Hl({...n,chainId:i,escrow:a}),s=Sl(r);ju(t,n);let c=await mu(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function Nu(e,t,n,r,i,a=Bl){let o=await Mu(e,t,n,r,i,a),s=await hu(e,t,{channelId:o.channelId,cumulativeAmount:Sl(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function Pu(e,t,n){let r=xu(t),a=n.escrow??`0x4d50500000000000000000000000000000000000`,o=n.operator??`0x0000000000000000000000000000000000000000`,s=n.salt??await wu(e,t),c=Sl(n.deposit),l=Sl(n.initialAmount),u=i({abi:Yl,functionName:`open`,args:[n.payee,o,n.token,c,s,r]}),d=await Du(e,await Eu(e,{account:t,calls:[...n.prefixCalls??[],{to:a,data:u}],feePayer:n.feePayer,feeToken:n.feeToken??n.token,validAfter:bu()})),f=ue.deserialize(d),p={authorizedSigner:r,expiringNonceHash:Gl(Wl({...n.feePayer?{feePayer:!0}:{},transaction:f}),{sender:t.address}),operator:o,payee:n.payee,payer:t.address,salt:s,token:n.token},m=Hl({...p,chainId:n.chainId,escrow:a});return{action:`open`,type:`transaction`,channelId:m,transaction:d,signature:await mu(e,t,{channelId:m,cumulativeAmount:l},a,n.chainId),descriptor:p,cumulativeAmount:l.toString(),authorizedSigner:p.authorizedSigner}}async function Fu(e,t,n,r,a,o,s=Bl,c=[],l=n.token){let u=Hl({...n,chainId:a,escrow:s}),d=Sl(r);return{action:`topUp`,type:`transaction`,channelId:u,transaction:await Du(e,await Eu(e,{account:t,calls:[...c,{to:s,data:i({abi:Yl,functionName:`topUp`,args:[n,d]})}],feePayer:o,feeToken:l,validAfter:bu()}).catch(e=>{throw Tu(e,{channelId:u,signer:Vl(n)})??e})),descriptor:n,additionalDeposit:d.toString()}}function Iu(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function Q(e){return Iu({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function Lu(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(Q(t),t)},delete(t){e.delete(t)}}}const Ru=new WeakMap,zu=new WeakMap;function Bu(e,t){zu.set(e,zu.get(t)??t)}async function Vu(e,t,n){let r=Ru.get(e);r||(r=new Map,Ru.set(e,r));let i=(r.get(t)??Promise.resolve()).catch(()=>{}).then(n);r.set(t,i);try{return await i}finally{r.get(t)===i&&r.delete(t)}}function Hu(e,t,n){return Vu(zu.get(e)??e,`funding:${t}`,n)}async function Uu(e,t){await Vu(e,`write:${Q(t)}`,async()=>{let n=await e.get(Q(t));if(n?.origin!==void 0){if(t.origin!==void 0&&t.origin!==n.origin)throw Error(`SessionManager: stored channel origin mismatch`);t.origin=n.origin}if(n?.uncertainTopUp){if(n.channelId!==t.channelId)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);t.uncertainTopUp=!0}await e.set(t)})}async function Wu(e,t){await Vu(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}const Gu=2n**96n-1n;function Ku(e){if(e<0n||e>Gu)throw new W({reason:`amount exceeds uint96 range`})}async function qu(e,t,n=Bl){let{cumulativeAmount:r,descriptor:i,signature:a}=t;return x(e,{address:n,abi:Yl,functionName:`verifyVoucher`,args:[Xu(i),r,a]})}async function Ju(e,t,n=Bl,r){return Yu(await x(e,{address:n,abi:Yl,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function Yu(e){return Ku(e.settled),Ku(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}function Xu(e){return{payer:e.payer,payee:e.payee,operator:e.operator,token:e.token,salt:e.salt,authorizedSigner:e.authorizedSigner,expiringNonceHash:e.expiringNonceHash}}const Zu=K.custom(e=>typeof e==`string`&&d(e,{strict:!1})),Qu=K.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),$u=K.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),ed=K.object({authorizedSigner:Zu,expiringNonceHash:Qu,operator:Zu,payee:Zu,payer:Zu,salt:Qu,token:Zu}),td=Nn(K.object({acceptedCumulative:K.string(),chainId:K.number(),channelId:Qu,closeRequestedAt:K.optional(K.string()),deposit:K.string(),descriptor:ed,escrow:Zu,highestVoucher:K.optional(K.object({channelId:Qu,cumulativeAmount:K.string(),signature:$u})),requiredCumulative:K.string(),settled:K.string(),spent:K.string(),units:K.optional(K.number())}));function nd(e){return td.encode(e)}function rd(e){return td.decode(e)}const id={status:`idle`};function ad(e){return{status:`active`,...e}}function od(e,t){switch(t.type){case`challengeReceived`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:{status:`challenged`,challengeId:t.challengeId},effects:[]};case`challenge`:return e.status!==`idle`&&e.status!==`active`?$(e,t):t.snapshot?{state:{status:`hydrating`,challengeId:t.challengeId,snapshot:t.snapshot},effects:[{type:`hydrate`,snapshot:t.snapshot}]}:{state:{status:`opening`,challengeId:t.challengeId},effects:[{type:`open`}]};case`hydrated`:return e.status===`hydrating`?{state:ld(e.challengeId,t.snapshot),effects:[]}:$(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:Sd({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:ud(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:$(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:Td(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?cd({challengeId:e.challengeId,descriptor:t.descriptor,event:t.event}):$(e,t);case`topUpStarted`:return e.status===`voucherNeeded`?{state:{status:`toppingUp`,challengeId:e.challengeId,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[]}:$(e,t);case`voucherAccepted`:return e.status!==`voucherNeeded`&&e.status!==`toppingUp`?$(e,t):{state:ud(e.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]};case`settleStarted`:return e.status===`active`?{state:{status:`settling`,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[{type:`settle`,channelId:e.channelId}]}:$(e,t);case`settled`:return e.status===`settling`?{state:ud(t.receipt.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]}:$(e,t);case`closeRequested`:return e.status===`active`?{state:{status:`closeRequested`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`requestClose`,channelId:e.channelId}]}:$(e,t);case`withdrawable`:return e.status===`closeRequested`?{state:{status:`withdrawable`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`withdraw`,channelId:e.channelId}]}:$(e,t);case`closeStarted`:return e.status!==`active`&&e.status!==`withdrawable`&&e.status!==`closeRequested`?$(e,t):{state:{status:`closing`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`close`,channelId:e.channelId}]};case`closed`:return e.status!==`closing`&&e.status!==`withdrawable`?$(e,t):{state:{status:`closed`,channelId:e.channelId,descriptor:e.descriptor},effects:[]}}}function sd(e,t){let n=od(e.state,t);return e.state=n.state,n}function cd(e){let{challengeId:t,descriptor:n,event:r}=e,i=BigInt(r.requiredCumulative),a=BigInt(r.deposit);return i>a?{state:{status:`toppingUp`,challengeId:t,channelId:r.channelId,descriptor:n,deposit:r.deposit},effects:[{type:`topUp`,channelId:r.channelId,amount:(i-a).toString()}]}:{state:{status:`voucherNeeded`,challengeId:t,channelId:r.channelId,descriptor:n,requiredCumulative:r.requiredCumulative,deposit:r.deposit},effects:[{type:`voucher`}]}}function ld(e,t){return ad({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function ud(e,t,n,r){return ad({challengeId:e,channelId:t.channelId,descriptor:n,acceptedCumulative:t.acceptedCumulative,deposit:r,spent:t.spent,units:t.units??0})}function $(e,t){throw Error(`Invalid session transition: ${e.status} + ${t.type}`)}function dd(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function fd(e){let{channel:t,maxVoucherCumulative:n,receipt:r}=e;if(!t||r.channelId!==t.channelId)return;let i=BigInt(r.acceptedCumulative),a=BigInt(r.spent);if(a>i)throw Error(`receipt spent exceeds accepted cumulative voucher amount`);if(i>t.cumulativeAmount)throw Error(`receipt accepted cumulative exceeds local voucher state`);if(a>t.cumulativeAmount)throw Error(`receipt spent exceeds local voucher state`);dd({cumulativeAmount:i,maxVoucherCumulative:n}),dd({cumulativeAmount:a,maxVoucherCumulative:n})}function pd(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;fd({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function md(e,t){return typeof e==`bigint`?e:g(e,t)}function hd(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(_d(r,n),t!==void 0){let e=BigInt(t);if(e<r)throw Error(`opening deposit ${e} below request amount ${r}`);return e}let a=i===void 0?void 0:BigInt(i),o=a!==void 0&&a>r?a:r;return n===void 0||o<n?o:n}function gd(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;dd({cumulativeAmount:r,maxVoucherCumulative:n??null});let o=r-t,s=a??i??o,c=s>o?s:o;if(n==null)return c;let l=n-t;return c<l?c:l}function _d(e,t){dd({cumulativeAmount:e,maxVoucherCumulative:t??null})}function vd(e){let{channel:t,currentSocket:n,lastChallenge:r}=e;if(!t?.opened)return;let i=n?.challenge??r,a=n?.channelId??t.channelId;if(!i)throw Error(`Cannot close session: no challenge available. This usually means close() was called on a SessionManager instance that was recreated after the session was opened. Use the same SessionManager instance that opened the session, or make a request first to receive a fresh 402 challenge.`);if(!a)throw Error(`Cannot close session: no channel ID available. The session may not have been fully opened.`);return{challenge:i,channel:t,channelId:a}}function yd(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function bd(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!bl(n))throw Error(`close-ready spent is not a uint96 amount`);if(n<r)throw Error(`close-ready spent is below locally confirmed spend`);if(n>yd({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function xd(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=xl(r),s=xl(a.spent);return o===void 0||s===void 0||!bl(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function Sd(e){return ad({challengeId:e.challengeId,channelId:e.entry.channelId,descriptor:e.entry.descriptor,acceptedCumulative:e.entry.cumulativeAmount.toString(),deposit:e.entry.deposit.toString(),spent:e.spent,units:e.units})}function Cd(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:id}}function wd(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=pd({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&sd(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function Td(e,t){return ad({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function Ed(e){let{challengeId:t,channelId:n,closeReadyReceipt:r,cumulativeAmount:i,deliveredChunks:a=0n,socketChallengeId:o,socketChannelId:s,spent:c,tickCost:l=0n}=e;if(c>i)throw Error(`locally confirmed spend exceeds local voucher state`);if(r&&r.challengeId===t&&r.channelId===n){let e=xl(r.spent);if(e===void 0)throw Error(`close-ready spent is not a uint96 amount`);return e>c?e:c}if(o===t&&s===n&&l>0n){let e=a*l,t=c>e?c:e;return t>i?i:t}return i}function Dd(e){let{channel:t,channelId:n,challengeId:r,cumulativeAmount:i,spent:a,state:o}=e;if(!(!t||t.channelId!==n)&&(t.cumulativeAmount=i,r))return od(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function Od(e){return{channel:e.channel===null?null:{entry:e.channel,cumulativeAmount:e.channel.cumulativeAmount,deposit:e.channel.deposit,opened:e.channel.opened},spent:e.spent,state:e.state}}function kd(e,t){return e.channel?(e.channel.entry.cumulativeAmount=e.channel.cumulativeAmount,e.channel.entry.deposit=e.channel.deposit,e.channel.entry.opened=e.channel.opened,{channel:e.channel.entry,spent:e.spent,state:e.state}):(t&&(t.opened=!1),{channel:null,spent:e.spent,state:e.state})}async function Ad(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(Ll()),e.waitForCloseReady()))(),a=BigInt(i.spent);bd({cumulativeAmount:r.channel.cumulativeAmount,readySpent:a,spent:e.spent});let o=await e.createSessionCredential(r.challenge,{action:`close`,channelId:r.channelId,descriptor:r.channel.descriptor,cumulativeAmountRaw:a.toString()}),s=a.toString();n.expectedCloseAmount=s;try{let i=e.waitForReceipt(e=>xd({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(Il(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}function jd(e){return`cumulativeAmount`in e}function Md(e){if(jd(e))return BigInt(e.cumulativeAmount)}async function Nd(e,t){e.origin!==void 0&&(t={...t,origin:e.origin}),t.opened?await Uu(e.store,t):await Wu(e.store,Q(t)),e.notifyUpdate(t)}async function Pd(e,t,n){let r=Md(n);if(r===void 0)return;let i=await e.store.get(t);i&&i.channelId.toLowerCase()===n.channelId.toLowerCase()&&(i.cumulativeAmount=i.cumulativeAmount>r?i.cumulativeAmount:r,n.action===`close`&&(i.opened=!1),await Nd(e,i))}const Fd=K.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),Id=K.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),Ld=K.object({account:K.optional(K.custom()),autoSwap:K.optional(K.custom()),action:K.optional(K.enum([`open`,`topUp`,`voucher`,`close`])),channelId:K.optional(Id),cumulativeAmount:K.optional(q()),cumulativeAmountRaw:K.optional(K.string()),transaction:K.optional(Fd),descriptor:K.optional(K.custom()),additionalDeposit:K.optional(q()),additionalDepositRaw:K.optional(K.string()),depositRaw:K.optional(K.string())});function Rd(e){return e?.action!==void 0}function zd(e){return Rd(e)&&e.descriptor!==void 0}function Bd(e,t,n){let r=n===`additionalDeposit`?e.additionalDepositRaw:e.cumulativeAmountRaw,i=n===`additionalDeposit`?e.additionalDeposit:e.cumulativeAmount;if(r)return BigInt(r);if(i)return g(i,t)}function Vd(e,t,n,r){let i=Bd(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function Hd(e){return typeof e==`object`&&!!e}function Ud(e){return typeof e==`string`&&d(e,{strict:!1})?e:void 0}function Wd(e){let t=e.request.methodDetails;return Hd(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:Ud(t.escrowContract),escrow:Ud(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:Ud(t.feeToken),operator:Ud(t.operator),configurableVouchers:typeof t.configurableVouchers==`boolean`?t.configurableVouchers:void 0,sessionSnapshot:ft(t,ut.sessionSnapshot)}:{}}function Gd(e,t){if(typeof e==`string`&&d(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function Kd(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function qd(e){return typeof e==`string`?e:void 0}async function Jd(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=Wd(n);(o.chainId!==void 0||i?.length===0)&&Ws(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});Us(c,s);let l=s??c.chain?.id;if(Ws(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=Ou(n,r,t),d=Gd(n.request.recipient,`recipient`),f=Gd(n.request.currency,`currency`);return{amount:Kd(n.request.amount),challenge:n,chainId:l,client:c,...o.configurableVouchers===void 0?{}:{configurableVouchers:o.configurableVouchers},escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:Iu({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:qd(n.request.suggestedDeposit),token:f}}async function Yd(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=Ju}=e,o=Hl({...r,chainId:i.chainId,escrow:i.escrow});Xd({channelId:t,descriptor:r,expectedChannelId:o,payee:i.payee,payer:i.payer,authorizedSigner:i.authorizedSigner,token:i.token});let s=await a(n,o,i.escrow);if(s.deposit===0n)throw Error(`Channel ${o} cannot be reused (closed or not found on-chain).`);if(s.closeRequestedAt!==0)throw Error(`Channel ${o} cannot be reused (pending close request).`);return{channelId:o,state:s}}function Xd(e){let{authorizedSigner:t,channelId:n,descriptor:r,expectedChannelId:i,payee:a,payer:o,token:s}=e;if(n&&n.toLowerCase()!==i.toLowerCase())throw Error(`context channelId does not match descriptor`);if(!Au(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!Au(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!Au(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!Au(Vl(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function Zd(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function Qd(e){let{context:t,decimals:n,requestAmount:r,snapshot:i,settled:a}=e;if(i)return[BigInt(i.acceptedCumulative),BigInt(i.requiredCumulative),BigInt(i.spent)+r,a].reduce((e,t)=>t>e?t:e,0n);let o=Bd(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function $d(e){let{account:t,client:n,readChannelState:r,snapshot:i,verifyVoucherOnChain:a=qu}=e,o=i.highestVoucher;if(!o)throw Error(`session snapshot is missing its highest signed voucher`);if(o.channelId.toLowerCase()!==i.channelId.toLowerCase())throw Error(`session snapshot voucher channelId does not match snapshot channelId`);let s=BigInt(i.acceptedCumulative),c=BigInt(o.cumulativeAmount),l=BigInt(i.requiredCumulative),u=BigInt(i.deposit),d=BigInt(i.settled),f=BigInt(i.spent);if(c!==s)throw Error(`session snapshot voucher amount does not match acceptedCumulative`);if(f>s)throw Error(`session snapshot spent exceeds acceptedCumulative`);if(d>u)throw Error(`session snapshot settled amount exceeds deposit`);let p={channelId:o.channelId,cumulativeAmount:c,signature:o.signature},m=Vl(i.descriptor),h=Su(t);if(!(gu(i.escrow,i.chainId,p,m,h?{configurable:!0,openingCommitment:i.descriptor.salt}:{})||h&&await a(n,{descriptor:i.descriptor,cumulativeAmount:c,signature:p.signature},i.escrow).catch(()=>!1)))throw Error(`session snapshot highest voucher signature is invalid`);let g=await Yd({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:xu(t),token:i.descriptor.token},readChannelState:r}),_=[s,l,g.state.settled].reduce((e,t)=>t>e?t:e,0n);if(_>g.state.deposit)throw Error(`recovered session cumulative amount exceeds on-chain channel deposit`);return{entry:{channelId:g.channelId,cumulativeAmount:_,deposit:g.state.deposit,descriptor:i.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0},spent:f}}function ef(e,t){return Au(e.address,t.payer)?Au(xu(e),Vl(t)):!1}function tf(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(Rd(r)){if(!zd(r))throw Error(`descriptor required for TIP-1034 session action`);return{type:`manual`,account:t,context:r,decimals:i,resolved:o}}if(!n&&r?.channelId&&!r.descriptor)throw Error(`descriptor required to reuse TIP-1034 channel`);let s=Zd({context:r,snapshot:o.snapshot});return!n&&s&&ef(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&ef(t,n.descriptor)?{type:`voucher`,account:t,entry:n,maxDeposit:a,resolved:o}:{type:`open`,account:t,context:r,maxDeposit:a,resolved:o}}async function nf(e,t,n=!1){switch(e.type){case`open`:return of(e,t,n);case`recover`:return sf(e,t);case`voucher`:return cf(e,t);case`manual`:return lf(e,t,n)}}async function rf(e,t){if(e)return await Qs(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage,maxAmountIn:e.maxAmountIn})}async function af(e,t){let{account:n,amount:r,chainId:i,client:a,token:o}=t;if(e||!lc({chainId:i,currency:o}))return;let s=await gc(a,{account:n,amount:r,chainId:i});if(s)throw s}async function of(e,t,n){let{account:r,resolved:i}=e;if(Su(r)&&i.configurableVouchers!==!0)throw new bt({signer:r.address});let a=hd({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw});await af(n,{account:r.address,amount:a,chainId:i.chainId,client:i.client,token:i.token});let o=await Pu(i.client,r,{chainId:i.chainId,deposit:a,escrow:i.escrow,feePayer:i.feePayer,feeToken:i.feeToken,initialAmount:i.amount,operator:i.operator,payee:i.payee,prefixCalls:await rf(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await Nd(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function sf(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await Yd({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:xu(n),token:o.token}}),l=Qd({context:r,decimals:i,requestAmount:o.amount,settled:c.state.settled,snapshot:o.snapshot});if(l>c.state.deposit)throw Error(`recovered voucher amount exceeds on-chain channel deposit`);_d(l,a);let u=await Mu(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await Nd(t,{...d?.channelId===c.channelId&&d.uncertainTopUp?{uncertainTopUp:!0}:{},channelId:c.channelId,cumulativeAmount:l,deposit:c.state.deposit,descriptor:s,escrow:o.escrow,chainId:o.chainId,opened:!0}),u}async function cf(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;_d(a,e.maxDeposit);let o=await Mu(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await Nd(t,r),o}async function lf(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=Hl({...s,chainId:o.chainId,escrow:o.escrow});Xd({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:xu(r),token:o.token});let l=await uf({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await Pd(t,o.key,l),l}async function uf(e,t){switch(e.context.action){case`open`:return df(e);case`topUp`:return ff(e,t);case`voucher`:return pf(e);case`close`:return mf(e)}}async function df(e){let{account:t,channelId:n,context:r,decimals:i,descriptor:a,resolved:o}=e;if(!r.transaction)throw Error(`transaction required for open action`);let s=Vd(r,i,`cumulativeAmount`,`open`),c=await Mu(o.client,t,a,s,o.chainId,o.escrow);return{action:`open`,type:`transaction`,channelId:n,transaction:r.transaction,signature:c.signature,descriptor:a,cumulativeAmount:s.toString(),authorizedSigner:a.authorizedSigner}}async function ff(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=Vd(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:(await af(t,{account:n.address,amount:c,chainId:s.chainId,client:s.client,token:s.token}),Fu(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await rf(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken))}function pf(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Mu(a.client,t,i,Vd(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function mf(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Nu(a.client,t,i,Vd(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}const hf={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};function gf(e){let t=new Map,n=!1,r=[],i=e.readyState,a=(e,n,i)=>{let a=t.get(e);if(a||(a=new Set,t.set(e,a)),a.add({once:typeof i==`object`&&i.once===!0,value:n}),e===`message`&&r){let e=r;r=null;for(let t of e)s(`message`,t)}},o=(e,n)=>{let r=t.get(e);if(r)for(let e of r)e.value===n&&r.delete(e)};function s(e,a){if(a.type===`close`){if(n)return;n=!0,i=hf.CLOSED,r=null}if(a.type===`open`&&(i=hf.OPEN),a.type===`message`&&r){r.push(a);return}switch(a.type){case`close`:l.onclose?.(a);break;case`error`:l.onerror?.(a);break;case`message`:l.onmessage?.(a);break;case`open`:l.onopen?.(a)}let o=t.get(e);if(o)for(let e of Array.from(o))typeof e.value==`function`?e.value(a):e.value.handleEvent(a),e.once&&o.delete(e)}let c=null,l={addEventListener:a,close(t,n){e.close(t,n)},get bufferedAmount(){return e.bufferedAmount},get extensions(){return e.extensions},on(e,t){a(e,t)},onclose:null,onerror:null,get onmessage(){return c},set onmessage(e){if(c=e,e&&r){let e=r;r=null;for(let t of e)s(`message`,t)}},onopen:null,off(e,t){o(e,t)},get protocol(){return e.protocol},get readyState(){return i},removeEventListener:o,send(t){e.send(t)},get url(){return e.url}};return{emit:s,socket:l}}function _f(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function vf(e){let{amount:t,assertVoucherWithinLocalLimit:n,channel:r,decimals:i,lastChallenge:a,lastUrl:o}=e;if(!r?.opened)throw Error(`Cannot top up session: no open channel.`);if(!a)throw Error(`Cannot top up session: no challenge available. Make a request first.`);if(!o)throw Error(`Cannot top up session: no URL available. Call fetch(), sse(), or ws() first.`);let s=md(t,i);if(s<=0n)throw Error(`Top-up amount must be greater than zero.`);return n(r.cumulativeAmount+s),{additionalDeposit:s,challenge:a,channelId:r.channelId,input:o}}function yf(e){let{additionalDeposit:t,channel:n,channelId:r,challengeId:i,currentState:a,knownDeposit:o,receipt:s,spent:c}=e;if(n?.channelId!==r)return;let l=o!==void 0&&o>n.deposit?o:n.deposit,u={...n,deposit:l+t};return s?{channel:u,state:Td(s,u)}:i?{channel:u,state:Sd({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function bf(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=_f(e.event);e.assertVoucherWithinLocalLimit(t.requiredCumulative),await e.topUpIfNeeded({challenge:e.challenge,input:e.input,headers:e.headers,channelId:e.expectedChannelId,deposit:t.deposit,requiredCumulative:t.requiredCumulative,...e.signal?{signal:e.signal}:{}});let n=e.getChannel();if(!n||n.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`missing-channel`};let r=n.cumulativeAmount>t.requiredCumulative?n.cumulativeAmount:Sl(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function xf(e){return e.method===ct.tempo&&e.intent===lt.session}function Sf(e){return xf(e)&&ft(e.request.methodDetails,ut.sessionProtocol)===dt.v2}function Cf(e){return ft(e.request.methodDetails,ut.sessionSnapshot)}function wf(e,t,n,r){let i=e instanceof Request?e.headers:void 0;return ta({...t,redirect:`manual`,headers:{...Yo(i),...Yo(t?.headers)}},un(r),n)}function Tf(e){return e instanceof Request||typeof e==`object`&&!!e&&!(e instanceof URL)&&typeof e.url==`string`&&typeof e.method==`string`&&typeof e.clone==`function`}function Ef(e){try{let t=typeof location>`u`?void 0:location.href,n=Tf(e)?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function Df(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function Of(e){let t=await e.text().catch(()=>``);if(!t)return``;if(!e.headers.get(`Content-Type`)?.includes(`application/problem+json`))return t;try{return JSON.parse(t).detail??t}catch{return t}}var kf=class extends Error{constructor(e){let t=e instanceof Error||e instanceof DOMException?e.message:String(e);super(`${t}; payment outcome unknown`),this.name=`UncertainFundingError`}};async function Af(e){let{channel:t,channelId:n}=e;if(!t?.descriptor||t.channelId!==n)throw Error(`Cannot top up session: no local channel descriptor available.`);if(t.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let r=await jf({challenge:e.challenge,context:{action:`topUp`,...e.autoSwap===void 0?{}:{autoSwap:e.autoSwap},channelId:n,descriptor:t.descriptor,additionalDepositRaw:e.additionalDeposit.toString()},createSessionCredential:e.createSessionCredential,fetch:e.fetch,headers:e.headers,input:e.input,signal:e.signal}).catch(async n=>{throw n instanceof kf&&(t.uncertainTopUp=!0,await e.onUncertainFunding?.(t)),n});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(U.paymentReceipt);return i?Ml(i):void 0}async function jf(e){let t=async t=>{e.signal?.throwIfAborted();let n=await e.createSessionCredential(t,e.context);e.signal?.throwIfAborted();let r=new AbortController,i=()=>r.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,i,{once:!0});let a=setTimeout(()=>r.abort(new DOMException(`Session management request timed out; payment outcome unknown`,`TimeoutError`)),3e4),o,s=new Promise((e,t)=>{o=()=>t(r.signal.reason),r.signal.addEventListener(`abort`,o,{once:!0})});try{return await Promise.race([e.fetch(Ef(e.input),{method:`POST`,signal:r.signal,redirect:`manual`,headers:tp(t,n,e.input,e.headers)}),s])}catch(t){throw e.context.action===`topUp`?new kf(t):t}finally{clearTimeout(a),e.signal?.removeEventListener(`abort`,i),r.signal.removeEventListener(`abort`,o)}},n=await t(e.challenge);if(n.status!==402)return n;let r=nn(n).find(Sf);return r?t(r):n}async function Mf(e){let t=Nf({channel:e.getChannel(),response:e.response});if(!t)return;let{channel:n,challenge:r,snapshot:i}=t;e.setChallenge(r);let a=BigInt(i.requiredCumulative),o=n.cumulativeAmount;await e.topUpIfNeeded({challenge:r,input:e.input,headers:e.init?.headers,channelId:i.channelId,deposit:BigInt(i.deposit),requiredCumulative:a,signal:e.init?.signal??(e.input instanceof Request?e.input.signal:void 0)});let s=e.getChannel();if(!s?.descriptor||s.channelId!==i.channelId)return;let c=s.cumulativeAmount>a?s.cumulativeAmount:a,l=()=>e.restoreCumulative(i.channelId,o),u;try{let t=await e.createSessionCredential(r,{action:`voucher`,channelId:i.channelId,descriptor:s.descriptor,cumulativeAmountRaw:c.toString()});u=await e.fetch(e.input,wf(e.input,e.init,t,r))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(U.paymentReceipt)&&await l(),u}function Nf(e){let t=nn(e.response).find(Sf);if(!t)return;let n=Cf(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function Pf(e){if(!e.lastUrl)throw Error(`Cannot close session: no URL available. This usually means close() was called on a SessionManager instance that was recreated after the session was opened. Use the same SessionManager instance that opened the session, or call fetch()/sse() before close().`);let t=e.target.challenge,n=e.signedCloseAmount,r=Tf(e.lastUrl)?e.lastUrl:void 0,i=r?{cache:r.cache,credentials:r.credentials,integrity:r.integrity,keepalive:r.keepalive,mode:r.mode===`navigate`?`same-origin`:r.mode,referrer:r.referrer,referrerPolicy:r.referrerPolicy}:void 0,a=async(a,o=!1)=>{t=a,n=(o?e.resolveSignedCloseAmount?.(a):void 0)??e.signedCloseAmount;let s=await e.createSessionCredential(a,{action:`close`,channelId:e.target.channelId,descriptor:e.target.channel.descriptor,cumulativeAmountRaw:n});return e.fetch(r?Ef(r):e.lastUrl,{...i,method:`POST`,redirect:`manual`,headers:tp(a,s,e.lastUrl,e.headers)})},o=await a(e.target.challenge);if(o.status===402){let t=nn(o).find(Sf);t&&(e.setChallenge?.(t),o=await a(t,!0))}if(!o.ok){let e=await Of(o),t=o.headers.get(U.wwwAuthenticate)??``;throw Error(`Close request failed with status ${o.status}${e?`: ${e}`:``}${t?` [${U.wwwAuthenticate}: ${t}]`:``}`)}let s=o.headers.get(U.paymentReceipt);if(!s)return;let c=Ml(s);if(!c.txHash||!A.validate(c.txHash,{strict:!0})||A.size(c.txHash)!==32||!xd({challengeId:t.id,channelId:e.target.channelId,expectedCloseAmount:n,minimumSpent:0n,receipt:c}))throw Error(`Session close response included a mismatched payment receipt.`);return c}async function Ff(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...Yo(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!Nl(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),If(e,c,{onReceipt:r,signal:o},n,s.headers)}function If(e,t,n,r,i){if(!Nl(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let a=r.getChallenge();return Lf({onNeedVoucher:t=>Hf({challenge:a,driver:r,headers:i,input:e,signal:n?.signal},t),onReceipt(e){r.acceptReceipt(e),n?.onReceipt?.(e)},response:t,signal:n?.signal})}async function*Lf(e){for await(let t of Rf(e))t.data!==void 0&&(yield t.data)}async function*Rf(e){if(!e.response.body)throw Error(`Response has no body.`);let t=e.response.body.getReader(),n=new TextDecoder,r=``,i=!1,a=()=>{t.cancel(e.signal?.reason).catch(()=>void 0)};e.signal?.addEventListener(`abort`,a,{once:!0}),e.signal?.aborted&&a();try{for(;!e.signal?.aborted;){let{done:a,value:o}=await t.read();for(a?(i=!0,r+=n.decode()):r+=n.decode(o,{stream:!0});;){let t=zf(r,a);if(!t)break;let n=t.index+t.length,i=r.slice(0,t.index),o=r.slice(0,n);if(r=r.slice(n),!i.trim())continue;let s=Pl(i.replace(/\r\n|\r/g,`
|
|
10
|
-
`));if(!s){yield{raw:o};continue}switch(s.type){case`message`:yield{data:s.data,raw:o};break;case`payment-need-voucher`:await e.onNeedVoucher(s.data,e.signal);break;case`payment-receipt`:e.onReceipt(s.data)}}if(a)break}}finally{e.signal?.removeEventListener(`abort`,a),i||await t.cancel().catch(()=>void 0),t.releaseLock()}}function
|
|
9
|
+
`);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=Il(r);return jl(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=Il(r);return Ml(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function Il(e){try{return JSON.parse(e)}catch{return null}}function Ll(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function Rl(){return JSON.stringify({mpp:`payment-close-request`})}function zl(e){let t=Bl(e);return t?t.mpp===`authorization`&&typeof t.authorization==`string`?{mpp:`authorization`,authorization:t.authorization}:t.mpp===`message`&&typeof t.data==`string`?{mpp:`message`,data:t.data}:t.mpp===`payment-close-request`?{mpp:`payment-close-request`}:t.mpp===`payment-close-ready`&&Ml(t.data)?{mpp:`payment-close-ready`,data:t.data}:t.mpp===`payment-error`&&typeof t.status==`number`&&typeof t.message==`string`?{mpp:`payment-error`,status:t.status,message:t.message}:t.mpp===`payment-need-voucher`&&jl(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&Ml(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function Bl(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}const Vl=`0x4d50500000000000000000000000000000000000`;function Hl(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function Ul(e){let t=E.encode(E.from([`address payer`,`address payee`,`address operator`,`address token`,`bytes32 salt`,`address authorizedSigner`,`bytes32 expiringNonceHash`,`address escrow`,`uint256 chainId`]),[e.payer,e.payee,e.operator,e.token,e.salt,e.authorizedSigner,e.expiringNonceHash,e.escrow??`0x4d50500000000000000000000000000000000000`,BigInt(e.chainId)]);return k.keccak256(t)}function Wl(e){return ve.encodeForSigning(e)}function Gl(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function Kl(e,t){return k.keccak256(A.concat(Wl(e),t.sender))}const ql=[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],Jl=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],Yl={name:`descriptor`,type:`tuple`,components:ql},Xl=[{type:`function`,name:`CLOSE_GRACE_PERIOD`,stateMutability:`view`,inputs:[],outputs:[{type:`uint64`}]},{type:`function`,name:`VOUCHER_TYPEHASH`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`function`,name:`open`,stateMutability:`nonpayable`,inputs:[{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`deposit`,type:`uint96`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`}],outputs:[{name:`channelId`,type:`bytes32`}]},{type:`function`,name:`settle`,stateMutability:`nonpayable`,inputs:[Yl,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[Yl,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[Yl,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[Yl],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[Yl],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[Yl],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:ql},{name:`state`,type:`tuple`,components:Jl}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:Jl}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:Jl}]},{type:`function`,name:`computeChannelId`,stateMutability:`view`,inputs:[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`getVoucherDigest`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`verifyVoucher`,stateMutability:`view`,inputs:[Yl,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[{name:`valid`,type:`bool`}]},{type:`function`,name:`domainSeparator`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`event`,name:`ChannelOpened`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`authorizedSigner`,type:`address`},{name:`salt`,type:`bytes32`},{name:`expiringNonceHash`,type:`bytes32`},{name:`deposit`,type:`uint96`}]},{type:`event`,name:`OpeningCommitmentRecorded`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`signer`,type:`address`,indexed:!0},{name:`commitment`,type:`bytes32`}]},{type:`event`,name:`Settled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`cumulativeAmount`,type:`uint96`},{name:`deltaPaid`,type:`uint96`},{name:`newSettled`,type:`uint96`}]},{type:`event`,name:`TopUp`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`additionalDeposit`,type:`uint96`},{name:`newDeposit`,type:`uint96`}]},{type:`event`,name:`CloseRequested`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`closeGraceEnd`,type:`uint256`}]},{type:`event`,name:`ChannelClosed`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`settledToPayee`,type:`uint96`},{name:`refundedToPayer`,type:`uint96`}]},{type:`event`,name:`CloseRequestCancelled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0}]},{type:`error`,name:`RootKeyRetired`,inputs:[{name:`account`,type:`address`}]},{type:`error`,name:`SignerConfigChanged`,inputs:[{name:`signer`,type:`address`}]},{type:`error`,name:`SaltNotSignerCommitment`,inputs:[{name:`signer`,type:`address`},{name:`commitment`,type:`bytes32`}]}];function Zl(e){return e.type===`secp256k1`?e.signature.s<=57896044618658097711785492504343953926418782139537452191302581570759080747168n:e.type===`p256`||e.type===`webAuthn`?e.signature.s<=57896044605178124381348723474703786764998477612067880171211129530534256022184n:!0}function Ql(e){if(e.type===`configurable`)return{...e,signatures:e.signatures.map(e=>Ql(e))};if(Zl(e))return e;if(e.type===`secp256k1`){let{r:t,s:n,yParity:r}=e.signature;return{...e,signature:{r:t,s:115792089237316195423570985008687907852837564279074904382605163141518161494337n-n,yParity:+(r===0)}}}return e.type===`p256`||e.type===`webAuthn`?{...e,signature:{...e.signature,s:115792089210356248762697446949407573529996955224135760342422259061068512044369n-e.signature.s}}:e}function $l(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function eu(e){return e===void 0||BigInt(e)===0n}function tu(e,t){let{account:n,config:r,signatures:i}=e,a=me.getSignPayload({account:n,config:r,payload:t}),o=Number(r.threshold),s,c=0,l;for(let[e,t]of i.entries()){if(!$l(t.type)||!Zl(t)||e>0&&c>=o)return!1;let n=H.extractAddress({payload:a,signature:t});if(!H.verify(t,{address:n,payload:a}))return!1;let i=r.owners.find(e=>Xs(e.owner,n));if(!i)return!1;let u=Number(i.weight);if(u===0)return!1;let d=BigInt(n);if(s!==void 0&&s>=d)return!1;s=d,c+=u,l=l===void 0?u:Math.min(l,u)}return!(i.length===0||c<o||l!==void 0&&c>=o+l)}function nu(e,t){let{account:n,commitment:r,payload:i}=t;if(!Xs(e.account,n)||BigInt(e.config.version??0n)===0n&&e.config.owners.some(({owner:t})=>Xs(t,e.account)))return!1;if(eu(r)){if(BigInt(e.config.version??0n)!==0n||!Xs(me.getAddress(e.config),n))return!1}else if(me.getCommitment(e.config).toLowerCase()!==r.toLowerCase())return!1;return tu(e,i)}function ru(e,t){return{name:`TIP20 Channel Reserve`,version:`1`,chainId:t,verifyingContract:e}}const iu={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},au={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]};function ou(e,t,n){return l({domain:ru(e,t),types:au,primaryType:`CloseAuthorization`,message:n})}function su(e,t){return he.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function cu(e,t,n){return e.toLowerCase()===he.address.toLowerCase()?su(t,n):l({domain:ru(e,t),types:iu,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function lu(e,t,n,r){let i=uu(e);return i?du(i,t,n,r):!1}function uu(e){let t=H.from(e);if(H.serialize(t).toLowerCase()===e.toLowerCase())return t}function du(e,t,n,r){if(e.type===`configurable`)return r.configurable?nu(e,{account:n,commitment:r.openingCommitment,payload:t}):!1;if(!$l(e.type)||!Zl(e)||!eu(r.openingCommitment))return!1;let i=H.extractAddress({payload:t,signature:e});return H.verify(e,{address:i,payload:t})&&Xs(i,n)}function fu(e){return e.source===`configurable`}function pu(e){return e.source===`accessKey`&&`accessKeyAddress`in e}function mu(e,t){return se.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function hu(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===he.address.toLowerCase())try{return await mu(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return T(e,{account:t,domain:ru(r,i),types:iu,primaryType:`Voucher`,message:n})})(),o=H.from(a);if(!$l(o.type)&&o.type!==`configurable`)throw Error(`TIP-1034 vouchers require a TIP-1020 primitive or TIP-1166 configurable account signature; received "${o.type}".`);return H.serialize(Ql(o))}async function gu(e,t,n,r,i){let a=pu(t)?await t.sign({hash:ou(r,i,n),raw:!0}):await T(e,{account:t,domain:ru(r,i),types:au,primaryType:`CloseAuthorization`,message:n}),o=H.from(a);if(!$l(o.type)&&o.type!==`configurable`)throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive or TIP-1166 configurable account signature; received "${o.type}".`);return H.serialize(Ql(o))}function _u(e,t,n,r,i={}){try{let a=cu(e,t,n);return lu(n.signature,a,r,i)}catch{return!1}}function vu(e){return typeof e==`object`&&!!e}function yu(e){return typeof e==`string`&&d(e,{strict:!1})?e:void 0}function bu(e){return yu(e.accessKeyAddress)}function xu(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(A.random(8))%e)}function Su(e){return bu(e)??e.address}function Cu(e){return wu(e)!==void 0}function wu(e){let t=bu(e);if(t===void 0)return fu(e)?e:void 0;let n=e.delegate;if(n&&fu(n)&&n.address.toLowerCase()===t.toLowerCase())return n}async function Tu(e,t){let n=wu(t);if(!n)return A.random(32);let{config:r}=n,i=await V.accounts.getConfigCommitment(e,{account:n.address}),a=r?me.getCommitment(r):void 0;if(BigInt(i)!==0n){if(a&&a.toLowerCase()!==i.toLowerCase())throw Error(`Configurable account ${n.address} holds a config whose commitment ${a} does not match its on-chain commitment ${i}. Use the account's current config.`);return i}if(!a||BigInt(r.version??0n)!==0n)throw Error(`Configurable account ${n.address} is not registered, so it needs its version-zero config to open a channel.`);return a}function Eu(e,t){let n=wc(e);if(n)try{let i=r({abi:Xl,data:n});if(i.errorName!==`SignerConfigChanged`&&i.errorName!==`RootKeyRetired`)return;let[a]=i.args;return a.toLowerCase()===t.signer.toLowerCase()?new xt({cause:e,channelId:t.channelId,reason:i.errorName,signer:a}):void 0}catch{return}}async function Du(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return Ec({account:n},()=>b(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}}))}async function Ou(e,t){return await ee(e,t)}function ku(e,t,n=!1){let r=e.request.methodDetails,i=vu(r)?yu(r.escrowContract)??yu(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!ju(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!ju(i,a)?i:a}function Au(e,t,n,r){return wn({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${t.descriptor?.payer??r.address}`})}function ju(e,t){return e.toLowerCase()===t.toLowerCase()}function Mu(e,t){let n=wu(e);if(!n?.config)return;let{config:r}=n;if(me.getCommitment(r).toLowerCase()!==t.salt.toLowerCase()&&(BigInt(r.version??0n)!==0n||me.getAddress(r).toLowerCase()!==n.address.toLowerCase()))throw Error(`Configurable account ${n.address} holds a config that does not match the channel's opening commitment (salt ${t.salt}), so it cannot sign a voucher the channel settles. Sign with the config the channel opened with, or close the channel and open a new one.`)}async function Nu(e,t,n,r,i,a=Vl){let o=Ul({...n,chainId:i,escrow:a}),s=Cl(r);Mu(t,n);let c=await hu(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function Pu(e,t,n,r,i,a=Vl){let o=await Nu(e,t,n,r,i,a),s=await gu(e,t,{channelId:o.channelId,cumulativeAmount:Cl(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function Fu(e,t,n){let r=Su(t),a=n.escrow??`0x4d50500000000000000000000000000000000000`,o=n.operator??`0x0000000000000000000000000000000000000000`,s=n.salt??await Tu(e,t),c=Cl(n.deposit),l=Cl(n.initialAmount),u=i({abi:Xl,functionName:`open`,args:[n.payee,o,n.token,c,s,r]}),d=await Ou(e,await Du(e,{account:t,calls:[...n.prefixCalls??[],{to:a,data:u}],feePayer:n.feePayer,feeToken:n.feeToken??n.token,validAfter:xu()})),f=ue.deserialize(d),p={authorizedSigner:r,expiringNonceHash:Kl(Gl({...n.feePayer?{feePayer:!0}:{},transaction:f}),{sender:t.address}),operator:o,payee:n.payee,payer:t.address,salt:s,token:n.token},m=Ul({...p,chainId:n.chainId,escrow:a});return{action:`open`,type:`transaction`,channelId:m,transaction:d,signature:await hu(e,t,{channelId:m,cumulativeAmount:l},a,n.chainId),descriptor:p,cumulativeAmount:l.toString(),authorizedSigner:p.authorizedSigner}}async function Iu(e,t,n,r,a,o,s=Vl,c=[],l=n.token){let u=Ul({...n,chainId:a,escrow:s}),d=Cl(r);return{action:`topUp`,type:`transaction`,channelId:u,transaction:await Ou(e,await Du(e,{account:t,calls:[...c,{to:s,data:i({abi:Xl,functionName:`topUp`,args:[n,d]})}],feePayer:o,feeToken:l,validAfter:xu()}).catch(e=>{throw Eu(e,{channelId:u,signer:Hl(n)})??e})),descriptor:n,additionalDeposit:d.toString()}}function Lu(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function Q(e){return Lu({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function Ru(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(Q(t),t)},delete(t){e.delete(t)}}}const zu=new WeakMap,Bu=new WeakMap;function Vu(e,t){Bu.set(e,Bu.get(t)??t)}async function Hu(e,t,n){let r=zu.get(e);r||(r=new Map,zu.set(e,r));let i=(r.get(t)??Promise.resolve()).catch(()=>{}).then(n);r.set(t,i);try{return await i}finally{r.get(t)===i&&r.delete(t)}}function Uu(e,t,n){return Hu(Bu.get(e)??e,`funding:${t}`,n)}async function Wu(e,t){await Hu(e,`write:${Q(t)}`,async()=>{let n=await e.get(Q(t));if(n?.origin!==void 0){if(t.origin!==void 0&&t.origin!==n.origin)throw Error(`SessionManager: stored channel origin mismatch`);t.origin=n.origin}if(n?.uncertainTopUp){if(n.channelId!==t.channelId)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);t.uncertainTopUp=!0}await e.set(t)})}async function Gu(e,t){await Hu(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}const Ku=2n**96n-1n;function qu(e){if(e<0n||e>Ku)throw new W({reason:`amount exceeds uint96 range`})}async function Ju(e,t,n=Vl){let{cumulativeAmount:r,descriptor:i,signature:a}=t;return x(e,{address:n,abi:Xl,functionName:`verifyVoucher`,args:[Zu(i),r,a]})}async function Yu(e,t,n=Vl,r){return Xu(await x(e,{address:n,abi:Xl,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function Xu(e){return qu(e.settled),qu(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}function Zu(e){return{payer:e.payer,payee:e.payee,operator:e.operator,token:e.token,salt:e.salt,authorizedSigner:e.authorizedSigner,expiringNonceHash:e.expiringNonceHash}}const Qu=K.custom(e=>typeof e==`string`&&d(e,{strict:!1})),$u=K.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),ed=K.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),td=K.object({authorizedSigner:Qu,expiringNonceHash:$u,operator:Qu,payee:Qu,payer:Qu,salt:$u,token:Qu}),nd=Nn(K.object({acceptedCumulative:K.string(),chainId:K.number(),channelId:$u,closeRequestedAt:K.optional(K.string()),deposit:K.string(),descriptor:td,escrow:Qu,highestVoucher:K.optional(K.object({channelId:$u,cumulativeAmount:K.string(),signature:ed})),requiredCumulative:K.string(),settled:K.string(),spent:K.string(),units:K.optional(K.number())}));function rd(e){return nd.encode(e)}function id(e){return nd.decode(e)}const ad={status:`idle`};function od(e){return{status:`active`,...e}}function sd(e,t){switch(t.type){case`challengeReceived`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:{status:`challenged`,challengeId:t.challengeId},effects:[]};case`challenge`:return e.status!==`idle`&&e.status!==`active`?$(e,t):t.snapshot?{state:{status:`hydrating`,challengeId:t.challengeId,snapshot:t.snapshot},effects:[{type:`hydrate`,snapshot:t.snapshot}]}:{state:{status:`opening`,challengeId:t.challengeId},effects:[{type:`open`}]};case`hydrated`:return e.status===`hydrating`?{state:ud(e.challengeId,t.snapshot),effects:[]}:$(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:Cd({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:dd(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:$(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:Ed(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?ld({challengeId:e.challengeId,descriptor:t.descriptor,event:t.event}):$(e,t);case`topUpStarted`:return e.status===`voucherNeeded`?{state:{status:`toppingUp`,challengeId:e.challengeId,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[]}:$(e,t);case`voucherAccepted`:return e.status!==`voucherNeeded`&&e.status!==`toppingUp`?$(e,t):{state:dd(e.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]};case`settleStarted`:return e.status===`active`?{state:{status:`settling`,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[{type:`settle`,channelId:e.channelId}]}:$(e,t);case`settled`:return e.status===`settling`?{state:dd(t.receipt.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]}:$(e,t);case`closeRequested`:return e.status===`active`?{state:{status:`closeRequested`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`requestClose`,channelId:e.channelId}]}:$(e,t);case`withdrawable`:return e.status===`closeRequested`?{state:{status:`withdrawable`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`withdraw`,channelId:e.channelId}]}:$(e,t);case`closeStarted`:return e.status!==`active`&&e.status!==`withdrawable`&&e.status!==`closeRequested`?$(e,t):{state:{status:`closing`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`close`,channelId:e.channelId}]};case`closed`:return e.status!==`closing`&&e.status!==`withdrawable`?$(e,t):{state:{status:`closed`,channelId:e.channelId,descriptor:e.descriptor},effects:[]}}}function cd(e,t){let n=sd(e.state,t);return e.state=n.state,n}function ld(e){let{challengeId:t,descriptor:n,event:r}=e,i=BigInt(r.requiredCumulative),a=BigInt(r.deposit);return i>a?{state:{status:`toppingUp`,challengeId:t,channelId:r.channelId,descriptor:n,deposit:r.deposit},effects:[{type:`topUp`,channelId:r.channelId,amount:(i-a).toString()}]}:{state:{status:`voucherNeeded`,challengeId:t,channelId:r.channelId,descriptor:n,requiredCumulative:r.requiredCumulative,deposit:r.deposit},effects:[{type:`voucher`}]}}function ud(e,t){return od({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function dd(e,t,n,r){return od({challengeId:e,channelId:t.channelId,descriptor:n,acceptedCumulative:t.acceptedCumulative,deposit:r,spent:t.spent,units:t.units??0})}function $(e,t){throw Error(`Invalid session transition: ${e.status} + ${t.type}`)}function fd(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function pd(e){let{channel:t,maxVoucherCumulative:n,receipt:r}=e;if(!t||r.channelId!==t.channelId)return;let i=BigInt(r.acceptedCumulative),a=BigInt(r.spent);if(a>i)throw Error(`receipt spent exceeds accepted cumulative voucher amount`);if(i>t.cumulativeAmount)throw Error(`receipt accepted cumulative exceeds local voucher state`);if(a>t.cumulativeAmount)throw Error(`receipt spent exceeds local voucher state`);fd({cumulativeAmount:i,maxVoucherCumulative:n}),fd({cumulativeAmount:a,maxVoucherCumulative:n})}function md(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;pd({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function hd(e,t){return typeof e==`bigint`?e:g(e,t)}function gd(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(vd(r,n),t!==void 0){let e=BigInt(t);if(e<r)throw Error(`opening deposit ${e} below request amount ${r}`);return e}let a=i===void 0?void 0:BigInt(i),o=a!==void 0&&a>r?a:r;return n===void 0||o<n?o:n}function _d(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;fd({cumulativeAmount:r,maxVoucherCumulative:n??null});let o=r-t,s=a??i??o,c=s>o?s:o;if(n==null)return c;let l=n-t;return c<l?c:l}function vd(e,t){fd({cumulativeAmount:e,maxVoucherCumulative:t??null})}function yd(e){let{channel:t,currentSocket:n,lastChallenge:r}=e;if(!t?.opened)return;let i=n?.challenge??r,a=n?.channelId??t.channelId;if(!i)throw Error(`Cannot close session: no challenge available. This usually means close() was called on a SessionManager instance that was recreated after the session was opened. Use the same SessionManager instance that opened the session, or make a request first to receive a fresh 402 challenge.`);if(!a)throw Error(`Cannot close session: no channel ID available. The session may not have been fully opened.`);return{challenge:i,channel:t,channelId:a}}function bd(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function xd(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!xl(n))throw Error(`close-ready spent is not a uint96 amount`);if(n<r)throw Error(`close-ready spent is below locally confirmed spend`);if(n>bd({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function Sd(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=Sl(r),s=Sl(a.spent);return o===void 0||s===void 0||!xl(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function Cd(e){return od({challengeId:e.challengeId,channelId:e.entry.channelId,descriptor:e.entry.descriptor,acceptedCumulative:e.entry.cumulativeAmount.toString(),deposit:e.entry.deposit.toString(),spent:e.spent,units:e.units})}function wd(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:ad}}function Td(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=md({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&cd(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function Ed(e,t){return od({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function Dd(e){let{challengeId:t,channelId:n,closeReadyReceipt:r,cumulativeAmount:i,deliveredChunks:a=0n,socketChallengeId:o,socketChannelId:s,spent:c,tickCost:l=0n}=e;if(c>i)throw Error(`locally confirmed spend exceeds local voucher state`);if(r&&r.challengeId===t&&r.channelId===n){let e=Sl(r.spent);if(e===void 0)throw Error(`close-ready spent is not a uint96 amount`);return e>c?e:c}if(o===t&&s===n&&l>0n){let e=a*l,t=c>e?c:e;return t>i?i:t}return i}function Od(e){let{channel:t,channelId:n,challengeId:r,cumulativeAmount:i,spent:a,state:o}=e;if(!(!t||t.channelId!==n)&&(t.cumulativeAmount=i,r))return sd(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function kd(e){return{channel:e.channel===null?null:{entry:e.channel,cumulativeAmount:e.channel.cumulativeAmount,deposit:e.channel.deposit,opened:e.channel.opened},spent:e.spent,state:e.state}}function Ad(e,t){return e.channel?(e.channel.entry.cumulativeAmount=e.channel.cumulativeAmount,e.channel.entry.deposit=e.channel.deposit,e.channel.entry.opened=e.channel.opened,{channel:e.channel.entry,spent:e.spent,state:e.state}):(t&&(t.opened=!1),{channel:null,spent:e.spent,state:e.state})}async function jd(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(Rl()),e.waitForCloseReady()))(),a=BigInt(i.spent);xd({cumulativeAmount:r.channel.cumulativeAmount,readySpent:a,spent:e.spent});let o=await e.createSessionCredential(r.challenge,{action:`close`,channelId:r.channelId,descriptor:r.channel.descriptor,cumulativeAmountRaw:a.toString()}),s=a.toString();n.expectedCloseAmount=s;try{let i=e.waitForReceipt(e=>Sd({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(Ll(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}function Md(e){return`cumulativeAmount`in e}function Nd(e){if(Md(e))return BigInt(e.cumulativeAmount)}async function Pd(e,t){e.origin!==void 0&&(t={...t,origin:e.origin}),t.opened?await Wu(e.store,t):await Gu(e.store,Q(t)),e.notifyUpdate(t)}async function Fd(e,t,n){let r=Nd(n);if(r===void 0)return;let i=await e.store.get(t);i&&i.channelId.toLowerCase()===n.channelId.toLowerCase()&&(i.cumulativeAmount=i.cumulativeAmount>r?i.cumulativeAmount:r,n.action===`close`&&(i.opened=!1),await Pd(e,i))}const Id=K.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),Ld=K.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),Rd=K.object({account:K.optional(K.custom()),autoSwap:K.optional(K.custom()),action:K.optional(K.enum([`open`,`topUp`,`voucher`,`close`])),channelId:K.optional(Ld),cumulativeAmount:K.optional(q()),cumulativeAmountRaw:K.optional(K.string()),transaction:K.optional(Id),descriptor:K.optional(K.custom()),additionalDeposit:K.optional(q()),additionalDepositRaw:K.optional(K.string()),depositRaw:K.optional(K.string())});function zd(e){return e?.action!==void 0}function Bd(e){return zd(e)&&e.descriptor!==void 0}function Vd(e,t,n){let r=n===`additionalDeposit`?e.additionalDepositRaw:e.cumulativeAmountRaw,i=n===`additionalDeposit`?e.additionalDeposit:e.cumulativeAmount;if(r)return BigInt(r);if(i)return g(i,t)}function Hd(e,t,n,r){let i=Vd(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function Ud(e){return typeof e==`object`&&!!e}function Wd(e){return typeof e==`string`&&d(e,{strict:!1})?e:void 0}function Gd(e){let t=e.request.methodDetails;return Ud(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:Wd(t.escrowContract),escrow:Wd(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:Wd(t.feeToken),operator:Wd(t.operator),configurableVouchers:typeof t.configurableVouchers==`boolean`?t.configurableVouchers:void 0,sessionSnapshot:ft(t,ut.sessionSnapshot)}:{}}function Kd(e,t){if(typeof e==`string`&&d(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function qd(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function Jd(e){return typeof e==`string`?e:void 0}async function Yd(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=Gd(n);(o.chainId!==void 0||i?.length===0)&&Gs(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});Ws(c,s);let l=s??c.chain?.id;if(Gs(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=ku(n,r,t),d=Kd(n.request.recipient,`recipient`),f=Kd(n.request.currency,`currency`);return{amount:qd(n.request.amount),challenge:n,chainId:l,client:c,...o.configurableVouchers===void 0?{}:{configurableVouchers:o.configurableVouchers},escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:Lu({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:Jd(n.request.suggestedDeposit),token:f}}async function Xd(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=Yu}=e,o=Ul({...r,chainId:i.chainId,escrow:i.escrow});Zd({channelId:t,descriptor:r,expectedChannelId:o,payee:i.payee,payer:i.payer,authorizedSigner:i.authorizedSigner,token:i.token});let s=await a(n,o,i.escrow);if(s.deposit===0n)throw Error(`Channel ${o} cannot be reused (closed or not found on-chain).`);if(s.closeRequestedAt!==0)throw Error(`Channel ${o} cannot be reused (pending close request).`);return{channelId:o,state:s}}function Zd(e){let{authorizedSigner:t,channelId:n,descriptor:r,expectedChannelId:i,payee:a,payer:o,token:s}=e;if(n&&n.toLowerCase()!==i.toLowerCase())throw Error(`context channelId does not match descriptor`);if(!ju(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!ju(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!ju(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!ju(Hl(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function Qd(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function $d(e){let{context:t,decimals:n,requestAmount:r,snapshot:i,settled:a}=e;if(i)return[BigInt(i.acceptedCumulative),BigInt(i.requiredCumulative),BigInt(i.spent)+r,a].reduce((e,t)=>t>e?t:e,0n);let o=Vd(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function ef(e){let{account:t,client:n,readChannelState:r,snapshot:i,verifyVoucherOnChain:a=Ju}=e,o=i.highestVoucher;if(!o)throw Error(`session snapshot is missing its highest signed voucher`);if(o.channelId.toLowerCase()!==i.channelId.toLowerCase())throw Error(`session snapshot voucher channelId does not match snapshot channelId`);let s=BigInt(i.acceptedCumulative),c=BigInt(o.cumulativeAmount),l=BigInt(i.requiredCumulative),u=BigInt(i.deposit),d=BigInt(i.settled),f=BigInt(i.spent);if(c!==s)throw Error(`session snapshot voucher amount does not match acceptedCumulative`);if(f>s)throw Error(`session snapshot spent exceeds acceptedCumulative`);if(d>u)throw Error(`session snapshot settled amount exceeds deposit`);let p={channelId:o.channelId,cumulativeAmount:c,signature:o.signature},m=Hl(i.descriptor),h=Cu(t);if(!(_u(i.escrow,i.chainId,p,m,h?{configurable:!0,openingCommitment:i.descriptor.salt}:{})||h&&await a(n,{descriptor:i.descriptor,cumulativeAmount:c,signature:p.signature},i.escrow).catch(()=>!1)))throw Error(`session snapshot highest voucher signature is invalid`);let g=await Xd({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:Su(t),token:i.descriptor.token},readChannelState:r}),_=[s,l,g.state.settled].reduce((e,t)=>t>e?t:e,0n);if(_>g.state.deposit)throw Error(`recovered session cumulative amount exceeds on-chain channel deposit`);return{entry:{channelId:g.channelId,cumulativeAmount:_,deposit:g.state.deposit,descriptor:i.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0},spent:f}}function tf(e,t){return ju(e.address,t.payer)?ju(Su(e),Hl(t)):!1}function nf(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(zd(r)){if(!Bd(r))throw Error(`descriptor required for TIP-1034 session action`);return{type:`manual`,account:t,context:r,decimals:i,resolved:o}}if(!n&&r?.channelId&&!r.descriptor)throw Error(`descriptor required to reuse TIP-1034 channel`);let s=Qd({context:r,snapshot:o.snapshot});return!n&&s&&tf(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&tf(t,n.descriptor)?{type:`voucher`,account:t,entry:n,maxDeposit:a,resolved:o}:{type:`open`,account:t,context:r,maxDeposit:a,resolved:o}}async function rf(e,t,n=!1){switch(e.type){case`open`:return sf(e,t,n);case`recover`:return cf(e,t);case`voucher`:return lf(e,t);case`manual`:return uf(e,t,n)}}async function af(e,t){if(e)return await $s(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage,maxAmountIn:e.maxAmountIn})}async function of(e,t){let{account:n,amount:r,chainId:i,client:a,token:o}=t;if(e||!uc({chainId:i,currency:o}))return;let s=await _c(a,{account:n,amount:r,chainId:i});if(s)throw s}async function sf(e,t,n){let{account:r,resolved:i}=e;if(Cu(r)&&i.configurableVouchers!==!0)throw new bt({signer:r.address});let a=gd({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw});await of(n,{account:r.address,amount:a,chainId:i.chainId,client:i.client,token:i.token});let o=await Fu(i.client,r,{chainId:i.chainId,deposit:a,escrow:i.escrow,feePayer:i.feePayer,feeToken:i.feeToken,initialAmount:i.amount,operator:i.operator,payee:i.payee,prefixCalls:await af(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await Pd(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function cf(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await Xd({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:Su(n),token:o.token}}),l=$d({context:r,decimals:i,requestAmount:o.amount,settled:c.state.settled,snapshot:o.snapshot});if(l>c.state.deposit)throw Error(`recovered voucher amount exceeds on-chain channel deposit`);vd(l,a);let u=await Nu(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await Pd(t,{...d?.channelId===c.channelId&&d.uncertainTopUp?{uncertainTopUp:!0}:{},channelId:c.channelId,cumulativeAmount:l,deposit:c.state.deposit,descriptor:s,escrow:o.escrow,chainId:o.chainId,opened:!0}),u}async function lf(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;vd(a,e.maxDeposit);let o=await Nu(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await Pd(t,r),o}async function uf(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=Ul({...s,chainId:o.chainId,escrow:o.escrow});Zd({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:Su(r),token:o.token});let l=await df({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await Fd(t,o.key,l),l}async function df(e,t){switch(e.context.action){case`open`:return ff(e);case`topUp`:return pf(e,t);case`voucher`:return mf(e);case`close`:return hf(e)}}async function ff(e){let{account:t,channelId:n,context:r,decimals:i,descriptor:a,resolved:o}=e;if(!r.transaction)throw Error(`transaction required for open action`);let s=Hd(r,i,`cumulativeAmount`,`open`),c=await Nu(o.client,t,a,s,o.chainId,o.escrow);return{action:`open`,type:`transaction`,channelId:n,transaction:r.transaction,signature:c.signature,descriptor:a,cumulativeAmount:s.toString(),authorizedSigner:a.authorizedSigner}}async function pf(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=Hd(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:(await of(t,{account:n.address,amount:c,chainId:s.chainId,client:s.client,token:s.token}),Iu(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await af(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken))}function mf(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Nu(a.client,t,i,Hd(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function hf(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Pu(a.client,t,i,Hd(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}const gf={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};function _f(e){let t=new Map,n=!1,r=[],i=e.readyState,a=(e,n,i)=>{let a=t.get(e);if(a||(a=new Set,t.set(e,a)),a.add({once:typeof i==`object`&&i.once===!0,value:n}),e===`message`&&r){let e=r;r=null;for(let t of e)s(`message`,t)}},o=(e,n)=>{let r=t.get(e);if(r)for(let e of r)e.value===n&&r.delete(e)};function s(e,a){if(a.type===`close`){if(n)return;n=!0,i=gf.CLOSED,r=null}if(a.type===`open`&&(i=gf.OPEN),a.type===`message`&&r){r.push(a);return}switch(a.type){case`close`:l.onclose?.(a);break;case`error`:l.onerror?.(a);break;case`message`:l.onmessage?.(a);break;case`open`:l.onopen?.(a)}let o=t.get(e);if(o)for(let e of Array.from(o))typeof e.value==`function`?e.value(a):e.value.handleEvent(a),e.once&&o.delete(e)}let c=null,l={addEventListener:a,close(t,n){e.close(t,n)},get bufferedAmount(){return e.bufferedAmount},get extensions(){return e.extensions},on(e,t){a(e,t)},onclose:null,onerror:null,get onmessage(){return c},set onmessage(e){if(c=e,e&&r){let e=r;r=null;for(let t of e)s(`message`,t)}},onopen:null,off(e,t){o(e,t)},get protocol(){return e.protocol},get readyState(){return i},removeEventListener:o,send(t){e.send(t)},get url(){return e.url}};return{emit:s,socket:l}}function vf(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function yf(e){let{amount:t,assertVoucherWithinLocalLimit:n,channel:r,decimals:i,lastChallenge:a,lastUrl:o}=e;if(!r?.opened)throw Error(`Cannot top up session: no open channel.`);if(!a)throw Error(`Cannot top up session: no challenge available. Make a request first.`);if(!o)throw Error(`Cannot top up session: no URL available. Call fetch(), sse(), or ws() first.`);let s=hd(t,i);if(s<=0n)throw Error(`Top-up amount must be greater than zero.`);return n(r.cumulativeAmount+s),{additionalDeposit:s,challenge:a,channelId:r.channelId,input:o}}function bf(e){let{additionalDeposit:t,channel:n,channelId:r,challengeId:i,currentState:a,knownDeposit:o,receipt:s,spent:c}=e;if(n?.channelId!==r)return;let l=o!==void 0&&o>n.deposit?o:n.deposit,u={...n,deposit:l+t};return s?{channel:u,state:Ed(s,u)}:i?{channel:u,state:Cd({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function xf(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=vf(e.event);e.assertVoucherWithinLocalLimit(t.requiredCumulative),await e.topUpIfNeeded({challenge:e.challenge,input:e.input,headers:e.headers,channelId:e.expectedChannelId,deposit:t.deposit,requiredCumulative:t.requiredCumulative,...e.signal?{signal:e.signal}:{}});let n=e.getChannel();if(!n||n.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`missing-channel`};let r=n.cumulativeAmount>t.requiredCumulative?n.cumulativeAmount:Cl(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function Sf(e){return e.method===ct.tempo&&e.intent===lt.session}function Cf(e){return Sf(e)&&ft(e.request.methodDetails,ut.sessionProtocol)===dt.v2}function wf(e){return ft(e.request.methodDetails,ut.sessionSnapshot)}function Tf(e,t,n,r){let i=e instanceof Request?e.headers:void 0;return na({...t,redirect:`manual`,headers:{...Xo(i),...Xo(t?.headers)}},un(r),n)}function Ef(e){return e instanceof Request||typeof e==`object`&&!!e&&!(e instanceof URL)&&typeof e.url==`string`&&typeof e.method==`string`&&typeof e.clone==`function`}function Df(e){try{let t=typeof location>`u`?void 0:location.href,n=Ef(e)?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function Of(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function kf(e){let t=await e.text().catch(()=>``);if(!t)return``;if(!e.headers.get(`Content-Type`)?.includes(`application/problem+json`))return t;try{return JSON.parse(t).detail??t}catch{return t}}var Af=class extends Error{constructor(e){let t=e instanceof Error||e instanceof DOMException?e.message:String(e);super(`${t}; payment outcome unknown`),this.name=`UncertainFundingError`}};async function jf(e){let{channel:t,channelId:n}=e;if(!t?.descriptor||t.channelId!==n)throw Error(`Cannot top up session: no local channel descriptor available.`);if(t.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let r=await Mf({challenge:e.challenge,context:{action:`topUp`,...e.autoSwap===void 0?{}:{autoSwap:e.autoSwap},channelId:n,descriptor:t.descriptor,additionalDepositRaw:e.additionalDeposit.toString()},createSessionCredential:e.createSessionCredential,fetch:e.fetch,headers:e.headers,input:e.input,signal:e.signal}).catch(async n=>{throw n instanceof Af&&(t.uncertainTopUp=!0,await e.onUncertainFunding?.(t)),n});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(U.paymentReceipt);return i?Nl(i):void 0}async function Mf(e){let t=async t=>{e.signal?.throwIfAborted();let n=await e.createSessionCredential(t,e.context);e.signal?.throwIfAborted();let r=new AbortController,i=()=>r.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,i,{once:!0});let a=setTimeout(()=>r.abort(new DOMException(`Session management request timed out; payment outcome unknown`,`TimeoutError`)),3e4),o,s=new Promise((e,t)=>{o=()=>t(r.signal.reason),r.signal.addEventListener(`abort`,o,{once:!0})});try{return await Promise.race([e.fetch(Df(e.input),{method:`POST`,signal:r.signal,redirect:`manual`,headers:np(t,n,e.input,e.headers)}),s])}catch(t){throw e.context.action===`topUp`?new Af(t):t}finally{clearTimeout(a),e.signal?.removeEventListener(`abort`,i),r.signal.removeEventListener(`abort`,o)}},n=await t(e.challenge);if(n.status!==402)return n;let r=nn(n).find(Cf);return r?t(r):n}async function Nf(e){let t=Pf({channel:e.getChannel(),response:e.response});if(!t)return;let{channel:n,challenge:r,snapshot:i}=t;e.setChallenge(r);let a=BigInt(i.requiredCumulative),o=n.cumulativeAmount;await e.topUpIfNeeded({challenge:r,input:e.input,headers:e.init?.headers,channelId:i.channelId,deposit:BigInt(i.deposit),requiredCumulative:a,signal:e.init?.signal??(e.input instanceof Request?e.input.signal:void 0)});let s=e.getChannel();if(!s?.descriptor||s.channelId!==i.channelId)return;let c=s.cumulativeAmount>a?s.cumulativeAmount:a,l=()=>e.restoreCumulative(i.channelId,o),u;try{let t=await e.createSessionCredential(r,{action:`voucher`,channelId:i.channelId,descriptor:s.descriptor,cumulativeAmountRaw:c.toString()});u=await e.fetch(e.input,Tf(e.input,e.init,t,r))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(U.paymentReceipt)&&await l(),u}function Pf(e){let t=nn(e.response).find(Cf);if(!t)return;let n=wf(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function Ff(e){if(!e.lastUrl)throw Error(`Cannot close session: no URL available. This usually means close() was called on a SessionManager instance that was recreated after the session was opened. Use the same SessionManager instance that opened the session, or call fetch()/sse() before close().`);let t=e.target.challenge,n=e.signedCloseAmount,r=Ef(e.lastUrl)?e.lastUrl:void 0,i=r?{cache:r.cache,credentials:r.credentials,integrity:r.integrity,keepalive:r.keepalive,mode:r.mode===`navigate`?`same-origin`:r.mode,referrer:r.referrer,referrerPolicy:r.referrerPolicy}:void 0,a=async(a,o=!1)=>{t=a,n=(o?e.resolveSignedCloseAmount?.(a):void 0)??e.signedCloseAmount;let s=await e.createSessionCredential(a,{action:`close`,channelId:e.target.channelId,descriptor:e.target.channel.descriptor,cumulativeAmountRaw:n});return e.fetch(r?Df(r):e.lastUrl,{...i,method:`POST`,redirect:`manual`,headers:np(a,s,e.lastUrl,e.headers)})},o=await a(e.target.challenge);if(o.status===402){let t=nn(o).find(Cf);t&&(e.setChallenge?.(t),o=await a(t,!0))}if(!o.ok){let e=await kf(o),t=o.headers.get(U.wwwAuthenticate)??``;throw Error(`Close request failed with status ${o.status}${e?`: ${e}`:``}${t?` [${U.wwwAuthenticate}: ${t}]`:``}`)}let s=o.headers.get(U.paymentReceipt);if(!s)return;let c=Nl(s);if(!c.txHash||!A.validate(c.txHash,{strict:!0})||A.size(c.txHash)!==32||!Sd({challengeId:t.id,channelId:e.target.channelId,expectedCloseAmount:n,minimumSpent:0n,receipt:c}))throw Error(`Session close response included a mismatched payment receipt.`);return c}async function If(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...Xo(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!Pl(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),Lf(e,c,{onReceipt:r,signal:o},n,s.headers)}function Lf(e,t,n,r,i){if(!Pl(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let a=r.getChallenge();return Rf({onNeedVoucher:t=>Uf({challenge:a,driver:r,headers:i,input:e,signal:n?.signal},t),onReceipt(e){r.acceptReceipt(e),n?.onReceipt?.(e)},response:t,signal:n?.signal})}async function*Rf(e){for await(let t of zf(e))t.data!==void 0&&(yield t.data)}async function*zf(e){if(!e.response.body)throw Error(`Response has no body.`);let t=e.response.body.getReader(),n=new TextDecoder,r=``,i=!1,a=()=>{t.cancel(e.signal?.reason).catch(()=>void 0)};e.signal?.addEventListener(`abort`,a,{once:!0}),e.signal?.aborted&&a();try{for(;!e.signal?.aborted;){let{done:a,value:o}=await t.read();for(a?(i=!0,r+=n.decode()):r+=n.decode(o,{stream:!0});;){let t=Bf(r,a);if(!t)break;let n=t.index+t.length,i=r.slice(0,t.index),o=r.slice(0,n);if(r=r.slice(n),!i.trim())continue;let s=Fl(i.replace(/\r\n|\r/g,`
|
|
10
|
+
`));if(!s){yield{raw:o};continue}switch(s.type){case`message`:yield{data:s.data,raw:o};break;case`payment-need-voucher`:await e.onNeedVoucher(s.data,e.signal);break;case`payment-receipt`:e.onReceipt(s.data)}}if(a)break}}finally{e.signal?.removeEventListener(`abort`,a),i||await t.cancel().catch(()=>void 0),t.releaseLock()}}function Bf(e,t){for(let n=0;n<e.length;n++){let r=Vf(e,n,t);if(!r)continue;let i=Vf(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function Vf(e,t,n){return e[t]===`
|
|
11
11
|
`?1:e[t]===`\r`?e[t+1]===`
|
|
12
|
-
`?2:t+1===e.length&&!n?0:1:0}function Vf(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=Rf({...e,signal:t.signal}),i=new TextEncoder,a=new Headers(e.response.headers);a.delete(`content-length`);let o=()=>e.signal?.removeEventListener(`abort`,n),s=new Response(new ReadableStream({async pull(e){try{let t=await r.next();if(t.done)return o(),e.close();e.enqueue(i.encode(t.value.raw))}catch(e){throw o(),e}},async cancel(){o(),t.abort(),await r.return(void 0)}}),{headers:a,status:e.response.status,statusText:e.response.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{configurable:!0,get:()=>e.response[t]});return s}async function Hf(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await bf({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:e.challenge,event:t,expectedChannelId:n.channelId,getChannel:e.driver.getChannel,headers:e.headers,input:e.input,signal:e.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status!==`ready`)return;let i=await jf({challenge:e.challenge,context:r.context,createSessionCredential:e.driver.createSessionCredential,fetch:e.driver.fetch,headers:e.headers,input:e.input,signal:e.signal});if(!i.ok)throw Error(`Voucher POST failed with status ${i.status}`)}async function Uf(e){let t=new URL(e.input.toString()),n=Df(t);e.onProbeUrl?.(n);let r=await e.fetch(n,{...e.probeInit,...e.signal?{signal:e.signal}:{}});if(r.status!==402)throw Error(`Expected a 402 payment challenge from ${n}, received ${r.status} instead.`);let i=nn(r).find(Sf);if(!i)throw Error(`No payment challenge received from HTTP endpoint for this WebSocket URL. The server may not require payment or did not advertise a challenge.`);return{challenge:i,httpUrl:n,wsUrl:t}}async function Wf(e){e.signal?.throwIfAborted();let t=await Uf(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function Gf(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:yn(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:kl(t)}}function Kf(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function qf(e){if(!Kf(e))return`received mismatched payment-close-ready frame`;let t=xl(e.receipt.spent);if(t===void 0)return`received invalid payment-close-ready spend`;if(t>e.cumulativeAmount)return`received payment-close-ready beyond local voucher state`}function Jf(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!Kf(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!xd({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function Yf(e){let{challenge:t,credential:n,options:r,WebSocket:i,wsUrl:a}=e,o=r?.signal;o?.throwIfAborted();let s=new i(a,r?.protocols),c=Gf({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=gf(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===hf.CONNECTING||s.readyState===hf.OPEN)&&s.close(3008,t)},d=()=>{e.rejectReceipt(Error(`WebSocket payment flow aborted.`)),e.rejectCloseReady(Error(`WebSocket payment flow aborted.`)),s.close()};s.addEventListener(`close`,t=>{o?.removeEventListener(`abort`,d),c.socket=null,c.expectedCloseAmount=null,e.rejectReceipt(Error(`WebSocket closed before the payment flow completed.`)),e.rejectCloseReady(Error(`WebSocket closed before the payment flow completed.`)),l.emit(`close`,{code:t.code??1e3,reason:t.reason??``,type:`close`,wasClean:!0})}),s.addEventListener(`error`,()=>{l.emit(`error`,{type:`error`})}),s.addEventListener(`message`,async t=>{let n=typeof t.data==`string`?t.data:void 0;n&&await Zf({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await Xf(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(Il(n)),await e.waitForReceipt(),l.socket}function Xf(e,t,n,r){return new Promise((i,a)=>{let o=()=>{e.removeEventListener(`open`,s),e.removeEventListener(`error`,c),e.removeEventListener(`close`,c),r?.removeEventListener(`abort`,l)},s=()=>{o(),t(`open`,{type:`open`}),i()},c=()=>{o(),a(Error(`WebSocket connection to ${n} failed to open.`))},l=()=>{o(),a(r?.reason)};e.addEventListener(`open`,s,{once:!0}),e.addEventListener(`error`,c,{once:!0}),e.addEventListener(`close`,c,{once:!0}),r?.addEventListener(`abort`,l,{once:!0}),r?.aborted&&l()})}async function Zf(e){let t=Rl(e.message);if(!t){e.managedEmit(`message`,{data:e.message,type:`message`});return}switch(t.mpp){case`authorization`:return;case`message`:e.socketState.deliveredChunks+=1n,e.managedEmit(`message`,{data:t.data,type:`message`});return;case`payment-close-ready`:Qf(e,t.data);return;case`payment-error`:e.driver.rejectReceipt(Error(t.message)),e.driver.rejectCloseReady(Error(t.message));return;case`payment-need-voucher`:await $f(e,t.data);return;case`payment-receipt`:ep(e,t.data);return}}function Qf(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=qf({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,cumulativeAmount:n,receipt:t});if(r){e.failSocketFlow(r);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleCloseReady(t),e.managedEmit(`close`,{code:1e3,reason:`stream complete`,type:`close`,wasClean:!0})}async function $f(e,t){try{let n=e.driver.challenge;n.expires&&new Date(n.expires).getTime()<=Date.now()+5e3&&(n=await e.driver.refreshChallenge(),e.driver.challenge=n,e.socketState.challenge=n);let r=await bf({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:n,event:t,expectedChannelId:e.socketState.channelId,getChannel:e.driver.getChannel,input:e.driver.httpUrl,signal:e.driver.options?.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status===`ignored`){e.failSocketFlow(r.reason===`channel-mismatch`?`received mismatched payment-need-voucher frame`:`cannot create voucher: no active channel`);return}let i=await e.driver.createSessionCredential(n,r.context);e.rawSocket.send(Il(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function ep(e,t){let n=Jf({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,expectedCloseAmount:e.socketState.expectedCloseAmount,receipt:t});if(n){e.failSocketFlow(n);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleReceipt(t)}function tp(e,t,n,r){let i=un(e),a=new Headers;if(i.toLowerCase()!==U.authorization.toLowerCase()){let e=new Headers(r).get(U.authorization)??(n instanceof Request?n.headers.get(U.authorization):null);e&&!e.startsWith(`${st.payment} `)&&a.set(U.authorization,e)}return a.set(i,t),a}const np=new WeakMap;async function rp(e,t){let n=np.get(e)??new Map;np.set(e,n);let r=n.get(t),i,a=new Promise(e=>{i=e});return n.set(t,a),await r,()=>{i(),n.get(t)===a&&n.delete(t)}}function ip(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function ap(e,t,n){try{let r=e.response?.headers.get(U.paymentReceipt);if(r){let e=Ml(r);if(e.challengeId===t.id&&ip(n,e))return!0}}catch{}return e.challenges?.some(e=>Sf(e)?ip(n,Cf(e)):!1)??!1}function op(e){let{allowedChainIds:t,currencies:n,decimals:r,expectedRecipients:i,maxAmount:a,maxAtomicAmount:o}=e;if((a!==void 0||o!==void 0)&&n===void 0)throw Error(`Tempo session maxAmount and maxAtomicAmount require currencies.`);for(let e of n??[])sp(a,typeof e==`string`?r:e.decimals);return{chainId:t?.length===1?t[0]:void 0,currencies:n,decimals:r,expectedRecipients:i?new Set(i.map(e=>e.toLowerCase())):void 0,maxAmount:a,maxAtomicAmount:o===void 0?void 0:BigInt(o)}}function sp(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo session maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo session maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return g(e,t)}}function cp(e,t,n){let r=e.currencies?Oe(e.currencies,t.currency,{chainId:t.methodDetails?.chainId??n??e.chainId,decimals:e.decimals}):void 0;if(e.currencies&&!r)throw Error(`Tempo session currency is not allowed: ${t.currency}.`);if(e.expectedRecipients&&(!t.recipient||!e.expectedRecipients.has(t.recipient.toLowerCase())))throw Error(`Unexpected session recipient: ${t.recipient}`);let i=BigInt(t.amount);if(e.maxAtomicAmount!==void 0&&i>e.maxAtomicAmount)throw Error(`Tempo session amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0&&i>sp(e.maxAmount,r?.decimals))throw Error(`Tempo session amount exceeds maxAmount.`)}function lp(e,t){try{return cp(e,t),!0}catch{return!1}}function up(e){return typeof e==`object`&&!!e&&e.action===`close`}function dp(e={}){let{account:t,allowCustomEscrow:n=!1,autoSwap:r,channelStore:i,decimals:a,escrow:o,allowedChainIds:s,getClient:c,maxDeposit:l,topUpAmount:u,onChannelUpdate:d,resolveAccount:f}=e,p=op(e),m=Hs({chain:re,getClient:c,rpcUrl:Wr}),h=Rs({account:t}),_=(e,t)=>{let n=(p.currencies?Oe(p.currencies,e.currency,{chainId:e.methodDetails?.chainId??t??p.chainId,decimals:a}):void 0)?.decimals??a??6;return{decimals:n,maxDeposit:l===void 0?void 0:g(l,n),topUpAmount:u===void 0?void 0:g(u,n)}};l!==void 0&&g(l,6),u!==void 0&&g(u,6);let v=e.origin===void 0?void 0:new URL(e.origin);if(v&&![`http:`,`https:`].includes(v.protocol))throw Error(`Session origins require HTTP or HTTPS`);let y=i??Lu(),b={store:y,notifyUpdate:e=>d?.(e)},x=async(e,t,n)=>{let r=h(e.client,t),i=t?.action?t.descriptor:n?.descriptor??Zd({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:Vl(i)}:{}}})??r},S=async(e,t,n)=>{let{decimals:r,maxDeposit:i}=_(e.challenge.request,e.chainId);return tf({account:await x(e,t,n),entry:n,context:t,decimals:r,maxDeposit:i,resolved:e})},C=Mn(Zc,{canHandleChallenge:({challenge:e,context:t})=>Sf(e)&&(up(t)||t===Di||lp(p,e.request)),context:Ld,async createCredential(e){let{challenge:t,context:i}=e;i?.action!==`close`&&cp(p,t.request);let a=await Jd({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:m});i?.action!==`close`&&t.request.methodDetails?.chainId===void 0&&cp(p,t.request,a.chainId);let c=za(e),l=Wa(e)??v?.origin;if(l!==void 0&&(l===`null`||![`http:`,`https:`].includes(new URL(l).protocol)))throw Error(`Session payments require an HTTP or HTTPS origin`);if(v&&l!==v.origin)throw Error(`Session channel origin mismatch`);let u={...b,origin:l},d=()=>{};try{let e=!Rd(i)&&i?.descriptor===void 0;e&&(d=await rp(y,a.key),c&&(await y.get(a.key))?.opened&&await c.prepare());let n=await y.get(a.key);if(n&&n.origin!==l)throw Error(`Session channel origin mismatch`);if(l&&!n&&a.snapshot&&!i?.descriptor&&!v)throw Error(`Session snapshot recovery requires an explicitly configured origin or descriptor`);let o=await S(a,i,n);if(!e&&c&&o.type===`open`){d=await rp(y,a.key);let e=await y.get(a.key);if(e&&e.origin!==l)throw Error(`Session channel origin mismatch`);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await c.prepare(),n=await y.get(a.key)),o=await S(a,i,n))}let s,f=c&&o.type===`open`?{store:{get:e=>y.get(e),async set(e){s=l?{...e,origin:l}:e},delete:e=>y.delete(e)},notifyUpdate(){}}:u,p=await ku(t,await nf(o,f,$s(i?.autoSwap??r,Zs)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||ap(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await y.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await Uu(y,e),b.notifyUpdate(e))}return!0}finally{d()}}}else d();return p}catch(e){throw d(),e}}});function w(e,t,n){let r={challenge:e,context:t};return Ua(r,fp(n)),C.createCredential(r)}let ee=async({autoSwap:e,challenge:t,channel:n,deposit:r,fetch:i,input:a,requiredCumulative:o,signal:s})=>Hu(y,Q(n),async()=>{s?.throwIfAborted();let c=await y.get(Q(n));if(c?.channelId===n.channelId&&(n=c),n.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let l=n.deposit>r?n.deposit:r,{maxDeposit:u,topUpAmount:d}=_(t.request,n.chainId),f=gd({deposit:l,maxDeposit:u,requiredCumulative:o,suggestedDeposit:t.request.suggestedDeposit===void 0?void 0:BigInt(t.request.suggestedDeposit),topUpAmount:d});f>0n&&await Af({autoSwap:e,additionalDeposit:f,challenge:t,channel:n,channelId:n.channelId,createSessionCredential:(e,t)=>w(e,t,a),onUncertainFunding:async e=>{let t=await y.get(Q(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};await Uu(y,n),b.notifyUpdate(n)},fetch:i,input:a,signal:s});let p=l+f;if(p===n.deposit)return;let m=await y.get(Q(n)),h=m?.channelId.toLowerCase()===n.channelId.toLowerCase()?m:n,g={...h,deposit:h.deposit>p?h.deposit:p};await Uu(y,g),b.notifyUpdate(g)});return Oa(C,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!Sf(e))return;let c=t===void 0?void 0:Ld.parse(t);if(Rd(c))return;cp(p,e.request);let l=await Jd({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m}),u=await y.get(l.key);if(!u?.opened)return;let d=fp(i);if(u.origin!==d)throw Error(`Session channel origin mismatch`);let f=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,h=u.cumulativeAmount+kl(e),g=f?BigInt(f.requiredCumulative):h,_=g>h?g:h,v=f?BigInt(f.deposit):u.deposit,b=v>u.deposit?v:u.deposit;_<=b&&b===u.deposit||!ef(await x(l,c,u),u.descriptor)||await ee({autoSwap:c?.autoSwap,challenge:e,channel:u,deposit:b,fetch:r,input:i,requiredCumulative:_,signal:a})}),Ia(C,async({challenge:e,context:t,credential:r,fetch:i,headers:a,input:c,refetch:l,response:u,signal:d})=>{if(!Sf(e))return u;if(!Nl(u))return Ol(yn(r).payload).action===`open`&&a.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await l?.()??u:u;let f=(await Jd({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m})).key,p=await y.get(f),h={assertVoucherWithinLocalLimit:t=>_d(t,_(e.request,p?.chainId).maxDeposit),createSessionCredential:(e,t)=>w(e,t,c),fetch:i,getChannel:()=>p??null,async topUpIfNeeded({deposit:n,requiredCumulative:r,signal:a}){p&&await ee({autoSwap:t===void 0?void 0:Ld.parse(t).autoSwap,challenge:e,channel:p,deposit:p.deposit>n?p.deposit:n,fetch:i,input:c,requiredCumulative:r,signal:a})}};return Vf({onNeedVoucher:(t,n)=>Hf({challenge:e,driver:h,headers:a,input:c,signal:n},t),onReceipt(){},response:u,signal:d})})}function fp(e){let t=new URL(e instanceof Request?e.url:e,globalThis.location===void 0?void 0:globalThis.location.href);if(![`http:`,`https:`].includes(t.protocol))throw Error(`Session payments require an HTTP or HTTPS origin`);return t.origin}const pp=new WeakMap;function mp(e,t){pp.set(e,t)}function hp(e){let t=null;return{wait(n=()=>!0){if(t)throw Error(`${e} wait already in progress`);return new Promise((e,r)=>{t={predicate:n,resolve:e,reject:r}})},settle(e){if(!t||!t.predicate(e))return;let n=t;t=null,n.resolve(e)},reject(e){if(!t)return;let n=t;t=null,n.reject(e)}}}function gp(e){let t=hp(`close-ready`),n=hp(`receipt`);return{waitForReceipt(e){return n.wait(e)},waitForCloseReady(){let n=e.getSocketSession()?.closeReadyReceipt;return n?Promise.resolve(n):t.wait()},settleReceipt(e){n.settle(e)},settleCloseReady(n){let r=e.getSocketSession();r&&r.challenge.id===n.challengeId&&r.channelId===n.channelId&&(r.closeReadyReceipt=n),t.settle(n)},rejectReceipt(e){n.reject(e)},rejectCloseReady(e){t.reject(e)}}}function _p(e){return e.method===ct.tempo&&e.intent===lt.charge}function vp(e){if(!_p(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function yp(e,t,n){if(!n)return t;let r={...Yo(Tf(e)?e.headers:void 0),...Yo(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===U.paymentSession.toLowerCase())?t:{...t,headers:{...r,[U.paymentSession]:n}}}function bp(e,t){return e===void 0?t:{...Ld.parse(e),...t}}function xp(e){let t=e.decimals??6,n=e.webSocket??globalThis.WebSocket;return{decimals:t,fetch:e.fetch??globalThis.fetch.bind(globalThis),maxVoucherCumulative:e.maxDeposit===void 0?null:g(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:g(e.topUpAmount,t),WebSocket:n}}function Sp(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&Ws(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=xp(e),i;function a(e){let t=new URL(Tf(e)?e.url:String(e),typeof location>`u`?void 0:location.href);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`SessionManager: session payments require an HTTP origin`);let n=t.origin;if(i!==void 0&&i!==n)throw Error(`SessionManager: session payment origin mismatch`);return i=n,n}if(vs(r.fetch))throw TypeError(`SessionManager: the fetch sets spending options (maxPayment, authorize, funders or tokens), which accept only charges. Pass a fetch without them.`);let o=_s(r.fetch),s=ys(r.fetch);r.fetch=async(e,t)=>{let n=a(e),r=await s(e,{...t,redirect:(t?.redirect??(Tf(e)?e.redirect:void 0))===`manual`?`manual`:`error`});if(r.url&&new URL(r.url).origin!==n)throw Error(`SessionManager: session response origin mismatch`);return r};let c=r.fetch;o&&(r.fetch=wi(c,o));let l=Hs({chain:re,getClient:e.client?()=>e.client:e.getClient,rpcUrl:Wr}),u=Rs({account:e.account}),d=Cd(),f=e.credentialContext===void 0?void 0:bp(e.credentialContext,{}),p=gp({getSocketSession:()=>d.socketSession}),m=e.channelStore??Lu(),h=new Set,g;async function _(e){let t=await m.get(e);if(t?.opened&&!h.has(t.channelId)){if(t.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return t}}let v=e=>{if(e.origin!==void 0&&e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return e.origin=i,Uu(m,e)},y={async get(e){let t=await _(e);return t&&g&&(g.seenExisting.add(e),!g.committed&&!g.created.has(e)&&(g.resumed??=t)),t},async set(e){let t=Q(e);e.opened&&h.delete(e.channelId),g?.trackCreates&&!g.seenExisting.has(t)&&g.created.set(t,e),await v(e)},delete:e=>Wu(m,e)};Bu(y,m);async function b(e){let t=Q(e),n=await m.get(t);if(e.uncertainTopUp||n?.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);h.add(e.channelId),g?.seenExisting.delete(t),g?.resumed===e&&(g.resumed=void 0),await Promise.resolve(Wu(m,t)).catch(()=>void 0)}async function x(){let e=g;if(e?.created.size){for(let[t,n]of e.created){let e=await m.get(t);if(n.uncertainTopUp||e?.channelId===n.channelId&&e.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before discarding the channel.`);h.add(n.channelId),await Promise.resolve(Wu(m,t)).catch(()=>void 0)}e.created.clear(),await B(e.committed??e.previous)}}function S(e){let t=ft(e.request.methodDetails,ut.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=g;if(!n?.created.size||!d.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&d.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=Od({channel:d.channel,spent:d.spent,state:d.state}),!0;return!1}function C(e){return sd(d,e)}function w(){let e=d.state.status===`active`?d.state:g?.committed?.state??g?.previous.state;return e?.status===`active`?e.units:0}function ee(e){let t=g,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit&&!e.uncertainTopUp||(t.resumed=void 0,t.committed=Od({channel:d.channel,spent:d.spent,state:d.state}))}let T=dp({account:e.account,allowCustomEscrow:n,autoSwap:e.autoSwap,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount,escrow:e.escrow,allowedChainIds:e.allowedChainIds,decimals:r.decimals,maxDeposit:e.maxDeposit,topUpAmount:e.topUpAmount,channelStore:y,onChannelUpdate(e){e.channelId!==d.channel?.channelId&&(d.spent=0n),d.channel=e,d.lastChallenge&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),ee(e)}}),te=ja(T);te&&Oa(T,e=>z(()=>Promise.resolve(te(e)),e.signal)),La(T);let ne=el({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),E=Jo({trustedTempoProofRealms:e.trustedTempoProofRealms,fetch:c,identity:o,methods:[T],onChallenge:async(e,t)=>{if(!xf(e))return;let n=g,r=n&&n.challengesReceived>0&&e.id===d.lastChallenge?.id,i=r&&Fs(e)===Fs(d.lastChallenge);n&&n.challengesReceived++,!i&&(S(e)||(n?.created.size?await x():r&&await B(n.committed??n.previous)),d.lastChallenge=e,C({type:`challengeReceived`,challengeId:e.id}))}});function D(e,t){let n={challenge:e,context:bp(f,t)};return i&&Ua(n,i),T.createCredential(n)}function O(e){wd({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:d})}function k(e=d.state.status===`active`?d.state.units:0){!d.channel||!d.lastChallenge||d.state.status!==`active`&&d.state.status!==`withdrawable`&&d.state.status!==`closeRequested`&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:d.channel,spent:d.spent.toString(),units:e})}async function A(t){let r=t.headers.get(U.paymentSessionSnapshot);if(!r)return;let i=rd(r);Ws(e.allowedChainIds,i.chainId),Ou({request:{methodDetails:{escrow:i.escrow}}},e.escrow,n);let a=await l({chainId:i.chainId});Us(a,i.chainId);let o=u(a),{entry:s,spent:c}=await $d({account:await e.resolveAccount?.({account:o,chainId:i.chainId,operation:{authority:Vl(i.descriptor),kind:`authorizePaymentChannel`}})??o,client:a,snapshot:i});return I(s.cumulativeAmount),await Promise.resolve(y.set(s)).catch(()=>void 0),d.channel=s,d.spent=c,s}async function j(t,n){if(!e.bootstrap||d.channel?.opened)return;let i=Tf(t)?t.headers:void 0,{body:a,method:o,...s}=n??{},c=Tf(t)?t.url:t,l={...s,method:`HEAD`,headers:{...Yo(i),...Yo(n?.headers),[U.acceptPayment]:`${ct.tempo}/${lt.charge}`}};try{let t=await r.fetch(c,l);if(t.status!==402)return await A(t);let n=nn(t).find(_p);if(!n||!vp(n))return;let i=new URL(String(c),typeof location<`u`?location.href:void 0);if(t.url&&new URL(t.url).origin!==i.origin)return;Ka(n,i,e.trustedTempoProofRealms);let a=await ne.createCredential({challenge:n,context:{}}),o=await r.fetch(c,ta({...l,redirect:`manual`},un(n),a));return o.ok?await A(o):void 0}catch{return}}function M(e,t){let n=d.socketSession;return Ed({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:d.channel?.channelId===t?d.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:d.spent,tickCost:n?.tickCost})}function N(e,t){let n=Cf(t);if(!n)return;if(Hl({...n.descriptor,chainId:n.chainId,escrow:n.escrow}).toLowerCase()!==n.channelId.toLowerCase())throw Error(`close snapshot descriptor does not match its channel ID`);if(n.channelId.toLowerCase()!==e.channelId.toLowerCase())throw Error(`close snapshot channel ID does not match local session`);if(n.chainId!==e.chainId||n.escrow.toLowerCase()!==e.escrow.toLowerCase())throw Error(`close snapshot payment scope does not match local session`);let r=BigInt(n.acceptedCumulative),i=BigInt(n.spent);if(r<0n||i<0n)throw Error(`close snapshot amounts must not be negative`);if(i>r)throw Error(`close snapshot spent exceeds accepted cumulative amount`);if(r>e.cumulativeAmount)throw Error(`close snapshot accepted cumulative exceeds local voucher state`);return{acceptedCumulative:r,spent:i}}function P(e,t){let n=N(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(d.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>d.spent&&(d.spent=i),n}function F(e,t=e.challenge,n=!1){let r=(n?P(e,t):N(e.channel,t))?.acceptedCumulative??M(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return I(r),r.toString()}function I(e){dd({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}let L,R;async function z(e,t){if(R)throw R;for(;;){let e=L;if(!e)break;if(!t)await e;else{t.throwIfAborted();let n;try{await Promise.race([e,new Promise((e,r)=>{n=()=>r(t.reason),t.addEventListener(`abort`,n,{once:!0})})])}finally{t.removeEventListener(`abort`,n)}}}if(t?.throwIfAborted(),R)throw R;let n=e();L=n;try{return await n}catch(e){throw e instanceof kf&&(R=Error(`Session funding outcome is unknown; reconcile the pending payment before creating a new session manager.`)),e}finally{L===n&&(L=void 0)}}async function ie(e){if(!d.channel)throw Error(`Cannot top up session: no active channel`);return Hu(m,Q(d.channel),async()=>{let{knownDeposit:t,...n}=e,i=d.channel?await y.get(Q(d.channel)):void 0;if(i?.channelId===e.channelId&&i.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let a=await Af({...n,channel:d.channel,createSessionCredential:D,fetch:r.fetch,onUncertainFunding:async e=>{let t=await y.get(Q(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};d.channel?.channelId===e.channelId&&(d.channel=n),await y.set(n),ee(n)}});O(a);let o=d.channel,s=yf({additionalDeposit:e.additionalDeposit,channel:d.channel,channelId:e.channelId,challengeId:d.lastChallenge?.id,currentState:d.state,knownDeposit:t,receipt:a,spent:d.spent});if(s?.channel&&d.lastChallenge){let e=s.channel;for(;;){await y.set(e);let t=d.channel;if(t===o)break;if(!t)return a;let n=s.channel;e=t.channelId===n.channelId?{...t,deposit:t.deposit>n.deposit?t.deposit:n.deposit,cumulativeAmount:t.cumulativeAmount>n.cumulativeAmount?t.cumulativeAmount:n.cumulativeAmount}:t,o=t}if(e.channelId!==s.channel.channelId)return a;d.channel=e,C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),ee(e)}return a})}async function ae(e){return z(async()=>{e.signal?.throwIfAborted();let t=d.channel?.channelId===e.channelId?d.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=gd({deposit:n,maxDeposit:r.maxVoucherCumulative,requiredCumulative:e.requiredCumulative,suggestedDeposit:e.challenge.request.suggestedDeposit===void 0?void 0:BigInt(e.challenge.request.suggestedDeposit),topUpAmount:r.topUpAmount});i!==0n&&await ie({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})},e.signal)}async function oe(e,t){let n=Dd({channel:d.channel,channelId:e,challengeId:d.lastChallenge?.id,cumulativeAmount:t,spent:d.spent,state:d.state});n&&d.channel&&(C({type:`activated`,challengeId:n.challengeId,entry:d.channel,spent:n.spent,units:n.units}),await v(d.channel))}async function B(e){let t=kd(e,d.channel);d.channel=t.channel,d.spent=t.spent,d.state=t.state,d.channel?.opened&&await v(d.channel)}function se(e,t=!0){let n=e.headers.get(U.paymentReceipt),r=n?Ml(n):null;return t&&O(r),Object.assign(e,{receipt:r,challenge:d.lastChallenge,channelId:d.channel?.channelId??null,cumulative:d.channel?.cumulativeAmount??0n})}async function V(e,t){if(t?.[Ho])return se(await r.fetch(e,Uo(t)),!1);if(g)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);a(e),d.lastUrl=e,d.lastHeaders=t?.headers;let n=Od({channel:d.channel,spent:d.spent,state:d.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};g=i;try{await j(e,t),i.trackCreates=!0;let a=yp(e,t,d.channel?.opened?d.channel.channelId:void 0);f&&(a={...a,context:f});let o=!n.channel?.opened;async function s(){let n=i.resumed;return!o||!n?!1:(o=!1,await b(n),a=yp(e,t,void 0),!0)}for(;;){let t;try{t=await E(e,a)}catch(e){if(i.created.size?await x():await B(i.committed??n),await s())continue;throw e}let o=se(t),c=!1;if(o.status===402){let t=await Mf({input:e,init:a,response:o,createSessionCredential:D,fetch:r.fetch,getChannel:()=>d.channel,restoreCumulative:oe,setChallenge(e){d.lastChallenge=e},topUpIfNeeded:ae});t&&(c=!0,o=se(t))}if(!c&&!o.ok&&!o.receipt){if(i.created.size?await x():await B(i.committed??n),await s())continue;return o}return o}}finally{g=void 0}}async function ce(e){let t=await Pf({createSessionCredential:D,fetch:r.fetch,getMinimumSpent:()=>d.spent,headers:d.lastHeaders,lastUrl:d.lastUrl,resolveSignedCloseAmount:t=>F(e,t,!0),signedCloseAmount:F(e),setChallenge(e){d.lastChallenge=e},target:e});return t&&(k(),C({type:`closeStarted`}),C({type:`closed`,receipt:t})),t}let le={createSessionCredential:D,doFetch:V,fetch:r.fetch,getChannel:()=>d.channel,getChallenge:()=>d.lastChallenge,assertVoucherWithinLocalLimit:I,acceptReceipt(e){O(e)},topUpIfNeeded:ae},ue={get channelId(){return d.channel?.channelId},get cumulative(){return d.channel?.cumulativeAmount??0n},get opened(){return d.channel?.opened??!1},get state(){return d.state},fetch:V,async topUp(e){let t=vf({amount:e,assertVoucherWithinLocalLimit:I,channel:d.channel,decimals:r.decimals,lastChallenge:d.lastChallenge,lastUrl:d.lastUrl});return z(async()=>{if(d.channel?.channelId!==t.channelId||d.lastChallenge!==t.challenge||d.lastUrl!==t.input)throw Error(`Session changed while waiting to top up`);let n=vf({amount:e,assertVoucherWithinLocalLimit:I,channel:d.channel,decimals:r.decimals,lastChallenge:t.challenge,lastUrl:t.input});return ie({additionalDeposit:n.additionalDeposit,challenge:n.challenge,channelId:n.channelId,headers:d.lastHeaders,input:n.input})})},async sse(e,t){if(t?.[Ho])throw Error(`SessionManager.sse requires payment; use fetch for unpaid streams.`);return Ff(e,t,le)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=Df(e);a(n);let i=t?.signal?{signal:t.signal}:void 0;await j(n,i);let o=d.channel?.opened?d.channel.channelId:void 0,{challenge:s,credential:c,httpUrl:l,wsUrl:u}=await Wf({async createSessionCredential(e,i){return d.lastChallenge=e,await Aa(T,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),D(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){d.lastUrl=e.toString()},probeInit:yp(n,i,o),signal:t?.signal});return d.lastChallenge=s,Yf({challenge:s,credential:c,httpUrl:l,WebSocket:r.WebSocket,wsUrl:u,options:t,createSessionCredential:D,getChannel:()=>d.channel,setSocketSession(e){d.socketSession=e},async refreshChallenge(){let e=await Uf({fetch:r.fetch,input:l,probeInit:yp(l,i,d.channel?.opened?d.channel.channelId:void 0),signal:t?.signal});return d.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:I,acceptReceipt:O,rejectCloseReady:p.rejectCloseReady,rejectReceipt:p.rejectReceipt,settleCloseReady:p.settleCloseReady,settleReceipt:p.settleReceipt,topUpIfNeeded:ae,waitForReceipt:p.waitForReceipt})},async close(){let e=d.socketSession,t=vd({channel:d.channel,currentSocket:e,lastChallenge:d.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===hf.OPEN){let r=await Ad({activeSocket:n,createSessionCredential:D,currentSocket:e,spent:d.spent,target:t,waitForCloseReady:p.waitForCloseReady,waitForReceipt:p.waitForReceipt});return k(),C({type:`closeStarted`}),C({type:`closed`,receipt:r}),r}return ce(t)}};return mp(ue,{consumeSseResponse(e,t,n){let r=a(e);if(t.url&&new URL(t.url).origin!==r)throw Error(`SessionManager: session response origin mismatch`);return If(e,t,n,le)},rehydrate({channel:e,challenge:t,input:n,spent:r}){let i=a(n);if(e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!xf(t))throw Error(`Cannot restore session: challenge is not tempo/session.`);if(r<0n)throw Error(`Cannot restore session: spent must not be negative.`);if(r>e.cumulativeAmount)throw Error(`Cannot restore session: spent exceeds local voucher state.`);I(e.cumulativeAmount);let o=N(e,t),s=o&&o.spent>r?o.spent:r;d.lastUrl=n,d.lastChallenge=t,d.channel=e,d.spent=s,C({type:`challengeReceived`,challengeId:t.id}),C({type:`activated`,challengeId:t.id,entry:e,spent:s.toString(),units:0})}}),ue}(function(e){e.serializeSnapshot=nd,e.deserializeSnapshot=rd})(Sp||={});const Cp=(1n<<64n)-1n,wp={dev_second:1n,day:86400n,week:604800n};function Tp(e){return e instanceof Date?e:new Date(e)}function Ep(e){let t=e.getTime();if(!Number.isFinite(t))throw new W({reason:`subscriptionExpires is invalid`});if(t%1e3!=0)throw new W({reason:`subscriptionExpires must be representable as whole seconds`});let n=t/1e3;if(n<=0||!Number.isSafeInteger(n))throw new W({reason:`subscriptionExpires cannot be represented in a Tempo key authorization`});return n}function Dp(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new W({reason:`periodCount is invalid`});let t=wp[e.periodUnit];if(t===void 0)throw new W({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>Cp)throw new W({reason:`subscription period cannot be represented as an unsigned 64-bit integer`});if(n>BigInt(2**53-1))throw new W({reason:`subscription period cannot be represented exactly by this Tempo client`});return Number(n)}function Op(e){let{challengeExpires:t,request:n}=e;Dp(n);let r=Ep(Tp(n.subscriptionExpires));if(t){let e=Math.floor(new Date(t).getTime()/1e3);if(!Number.isFinite(e)||r<=e)throw new W({reason:`subscriptionExpires must be strictly later than challenge expires`})}}function kp(e){return[{address:Hp(e.currency,`currency`),selector:`0x95777d59`,recipients:[Hp(e.recipient,`recipient`)]}]}function Ap(e){try{let t=A.fromBytes(D.toBytes(e));if(A.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new W({reason:`challenge id must encode 32 bytes`})}}async function jp(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=Np({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:ge.getSignPayload(o)}),c=H.from(s);if(c.type===`keychain`||c.type===`configurable`)throw new W({reason:`keyAuthorization must use a primitive signature`});return ge.from(o,{signature:H.serialize(Zl(c))})}function Mp(e){let{accessKey:t,challengeId:n,chainId:r,payload:i,request:a}=e;if(i.type!==`keyAuthorization`)throw new W({reason:`invalid keyAuthorization payload`});let o=Pp(i.signature),s=Fp(o);if(Ip({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==Ap(n))throw new W({reason:`keyAuthorization challenge mismatch`});return Lp(o,a),zp(Rp(o),a),Bp(o.scopes,a),{authorization:o,source:{address:Vp(o,s),chainId:r}}}function Np(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return ge.from({address:Hp(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:Ep(Tp(i.subscriptionExpires)),limits:[{token:Hp(i.currency,`currency`),limit:BigInt(i.amount),period:Dp(i)}],scopes:kp(i),type:t.keyType,witness:Ap(n)})}function Pp(e){try{return ge.deserialize(e)}catch(e){throw e instanceof ge.InvalidSignatureTypeError?new W({reason:`keyAuthorization must use a primitive signature`}):new W({reason:`invalid keyAuthorization payload`})}}function Fp(e){let t=e.signature;if(!t)throw new W({reason:`keyAuthorization must use a primitive signature`});return t}function Ip(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new W({reason:`keyAuthorization chainId mismatch`});if(t){if(!f(n.address,Hp(t.accessKeyAddress,`accessKeyAddress`)))throw new W({reason:`keyAuthorization access key mismatch`});if(n.type!==t.keyType)throw new W({reason:`keyAuthorization key type mismatch`})}}function Lp(e,t){if(Op({request:t}),e.expiry!==Ep(Tp(t.subscriptionExpires)))throw new W({reason:`keyAuthorization expiry mismatch`})}function Rp(e){let[t]=e.limits??[];if(!t||e.limits?.length!==1)throw new W({reason:`keyAuthorization must contain exactly one token limit`});return t}function zp(e,t){if(!f(e.token,Hp(t.currency,`currency`)))throw new W({reason:`keyAuthorization currency mismatch`});if(e.limit!==BigInt(t.amount))throw new W({reason:`keyAuthorization amount mismatch`});if(e.period!==Dp(t))throw new W({reason:`keyAuthorization period mismatch`})}function Bp(e,t){if(!e||e.length!==1)throw new W({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=Hp(t.currency,`currency`),r=Hp(t.recipient,`recipient`),i=new Set;for(let t of e){if(!f(t.address,n))throw new W({reason:`keyAuthorization call target mismatch`});let e=Up(t.selector);if(e!==`0xa9059cbb`&&e!==`0x95777d59`)throw new W({reason:`keyAuthorization selector not allowed`});if(i.has(e))throw new W({reason:`keyAuthorization duplicate selector`});if(i.add(e),t.recipients?.length!==1||!f(t.recipients[0],r))throw new W({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new W({reason:`keyAuthorization must allow transferWithMemo`})}function Vp(e,t){let n=ge.getSignPayload(e);try{let e=H.extractAddress({payload:n,signature:t});if(!Xl(t)||!H.verify(t,{address:e,payload:n}))throw new W({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof W?e:new W({reason:`keyAuthorization signature is invalid`})}}function Hp(e,t){if(!d(e))throw new W({reason:`${t} must be an address`});return e.toLowerCase()}function Up(e){return typeof e==`string`?e.toLowerCase():``}const Wp=K.object({accessKey:K.optional(K.custom()),account:K.optional(K.custom())});function Gp(e={}){let t=Hs({chain:R,requireChain:!0,getClient:e.getClient,rpcUrl:Wr}),n=Rs({account:e.account});return Mn(Qc,{context:Wp,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??Z.testnet,o=await t({chainId:a});if(o.chain?.id!==a)throw Error(`Subscription chain mismatch: expected ${a}, got ${o.chain?.id??`unknown`}.`);let s=n(o,i),c=i?.accessKey??e.accessKey??r.request.methodDetails?.accessKey;if(!c)throw Error("No `accessKey` provided. The subscription challenge must include `accessKey`, or the client must pass one to parameters/context.");qp(r.request),await e.validateRequest?.(r.request);let l=await Kp(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),u=Mp({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:ge.serialize(l),type:`keyAuthorization`},request:r.request});if(!f(u.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return wn({challenge:r,payload:{signature:ge.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function Kp(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await jp({accessKey:n,account:r,challengeId:i,chainId:a,request:o});if(s)return s;let c=await e.request({method:`wallet_authorizeAccessKey`,params:[{address:n.accessKeyAddress,expiry:Ep(Tp(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:A.fromNumber(BigInt(o.amount)),period:Dp(o)}],scopes:kp(o),witness:Ap(i)}]});return ge.fromRpc(c.keyAuthorization)}function qp(e){Dp(e),Ep(Tp(e.subscriptionExpires))}const Jp=Object.assign(dp,{manager:Sp});function Yp(e={}){let t=e.expectedChainId!==void 0&&(e.allowedChainIds===void 0||e.allowedChainIds.includes(e.expectedChainId)),n=e.expectedChainId===void 0?e:{...e,allowedChainIds:t?[e.expectedChainId]:[]};return[el(e),Jp(n)]}(function(e){e.charge=el,e.common=Yp,e.session=Jp,e.subscription=Gp})(Yp||={});const Xp=L.union([L.boolean(),L.literal(`true`).transform(()=>!0),L.literal(`false`).transform(()=>!1)]);async function Zp(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}const Qp=L.object({allowCustomEscrow:L.optional(Xp),autoSwap:L.optional(Xp),channel:L.optional(L.coerce.string()),deposit:L.optional(L.union([L.string(),L.number()])),payWith:L.optional(L.string()),slippage:L.optional(L.coerce.number()),tokenIn:L.optional(L.string())}),$p=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`];function em(){let t;return ui({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:n,options:r,methodOpts:i}){let a=oi(r.account),o=n.request,s=o.currency,c=om(i),l=um({autoSwap:c.autoSwap??r.autoSwap,payWith:c.payWith??r.payWith,slippage:c.slippage??r.slippage,tokenIn:c.tokenIn}),d=s??``,f=o.decimals??6,p,m,h,g=!1,_=process.env.MPPX_PRIVATE_KEY?.trim()||(Kr(a)?void 0:await si(a).get());if(!_&&Kr(a)&&ym()){g=!0;let t=_m(a);if(t){let i=Yr(r.rpcUrl,{network:r.network});h=e({chain:await Xr({network:r.network,rpcUrl:i}),transport:u(i)}),cm({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let a=s?await $r(h,s,t.wallet_address).catch(()=>void 0):void 0;d=a?.symbol??s??``,f=a?.decimals??o.decimals??6}}else if(_)m=pe(_);else{let e=xm();if(e){let t=await si(e).get();t&&(m=pe(t))}if(!m)throw r.account?new zr({code:`ACCOUNT_NOT_FOUND`,message:`Account "${a}" not found.`,exitCode:69}):new zr({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!g&&m){let t=Yr(r.rpcUrl,{network:r.network});h=e({chain:await Xr({network:r.network,rpcUrl:t}),transport:u(t)}),cm({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let i=s?await $r(h,s,m.address).catch(()=>void 0):void 0;d=i?.symbol??s??``,f=i?.decimals??o.decimals??6}if(g)return{tokenSymbol:d,tokenDecimals:f,explorerUrl:p,methods:[],async createCredential(e){let t=e.headers.get(`www-authenticate`);if(!t)throw Error(`No WWW-Authenticate header in 402 response.`);return bm(t)}};if(!m||!h)throw new zr({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let v=Yp({account:m,...c.allowCustomEscrow===void 0?{}:{allowCustomEscrow:c.allowCustomEscrow},getClient:()=>h,...l===void 0?{}:{autoSwap:l},maxDeposit:(()=>{if(n.intent!==`session`)return;let e=n.request.suggestedDeposit,t=(c.deposit===void 0?void 0:String(c.deposit))??e??(Qr(h.chain)?`10`:void 0);if(!t)throw new zr({code:`MISSING_DEPOSIT`,message:`Session payment requires a deposit. Use -M deposit=<amount> or connect to testnet.`,exitCode:2});return t})()}),y=(()=>{if(!c.channel)return;let e=c.channel,t=fm(e);return{channelId:e,...t!==void 0&&{cumulativeAmountRaw:t.toString()}}})();return t={descriptor:void 0,async signVoucher({channelId:e,cumulativeAmount:r,escrowContract:i,chainId:a,action:o=`voucher`}){let s=t?.descriptor;if(!s)throw Error(`session descriptor not available`);let c={channelId:e,cumulativeAmount:r},l=await mu(h,m,c,i,a);return wn({challenge:n,payload:{action:o,channelId:e,...o===`close`?{closeSignature:await hu(h,m,c,i,a)}:{},descriptor:s,cumulativeAmount:r.toString(),signature:l},source:`did:pkh:eip155:${a}:${m.address}`})},source:`did:pkh:eip155:${h.chain.id}:${m.address}`},{tokenSymbol:d,tokenDecimals:f,explorerUrl:p,methods:[...v],credentialContext:y}},prepareCredentialRequest({challenge:e,headers:t}){e.intent===`session`&&(t.Accept=`text/event-stream`)},async handleResponse(e){if(e.challenge.intent!==`session`||!t)return!1;let{challenge:n,credential:r,response:i,fetchUrl:a,fetchInit:o,verbose:s}=e,{silent:c,confirmEnabled:l,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,shownKeys:p}=e,m=c?e=>{}:e=>process.stderr.write(e),h=yn(r),g=n.request,_=g.methodDetails,v=h.payload.channelId,y=_?.escrowContract??_?.escrow??`0x4d50500000000000000000000000000000000000`,b=_?.chainId??0,x=BigInt(g.amount),S=`cumulativeAmount`in h.payload&&h.payload.cumulativeAmount?BigInt(h.payload.cumulativeAmount):0n;if(`descriptor`in h.payload&&(t.descriptor=h.payload.descriptor),s>=1){if(h.payload.action===`open`){let e=g.suggestedDeposit,t=e?` ${X.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
|
|
12
|
+
`?2:t+1===e.length&&!n?0:1:0}function Hf(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=zf({...e,signal:t.signal}),i=new TextEncoder,a=new Headers(e.response.headers);a.delete(`content-length`);let o=()=>e.signal?.removeEventListener(`abort`,n),s=new Response(new ReadableStream({async pull(e){try{let t=await r.next();if(t.done)return o(),e.close();e.enqueue(i.encode(t.value.raw))}catch(e){throw o(),e}},async cancel(){o(),t.abort(),await r.return(void 0)}}),{headers:a,status:e.response.status,statusText:e.response.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{configurable:!0,get:()=>e.response[t]});return s}async function Uf(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await xf({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:e.challenge,event:t,expectedChannelId:n.channelId,getChannel:e.driver.getChannel,headers:e.headers,input:e.input,signal:e.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status!==`ready`)return;let i=await Mf({challenge:e.challenge,context:r.context,createSessionCredential:e.driver.createSessionCredential,fetch:e.driver.fetch,headers:e.headers,input:e.input,signal:e.signal});if(!i.ok)throw Error(`Voucher POST failed with status ${i.status}`)}async function Wf(e){let t=new URL(e.input.toString()),n=Of(t);e.onProbeUrl?.(n);let r=await e.fetch(n,{...e.probeInit,...e.signal?{signal:e.signal}:{}});if(r.status!==402)throw Error(`Expected a 402 payment challenge from ${n}, received ${r.status} instead.`);let i=nn(r).find(Cf);if(!i)throw Error(`No payment challenge received from HTTP endpoint for this WebSocket URL. The server may not require payment or did not advertise a challenge.`);return{challenge:i,httpUrl:n,wsUrl:t}}async function Gf(e){e.signal?.throwIfAborted();let t=await Wf(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function Kf(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:yn(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:Al(t)}}function qf(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function Jf(e){if(!qf(e))return`received mismatched payment-close-ready frame`;let t=Sl(e.receipt.spent);if(t===void 0)return`received invalid payment-close-ready spend`;if(t>e.cumulativeAmount)return`received payment-close-ready beyond local voucher state`}function Yf(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!qf(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!Sd({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function Xf(e){let{challenge:t,credential:n,options:r,WebSocket:i,wsUrl:a}=e,o=r?.signal;o?.throwIfAborted();let s=new i(a,r?.protocols),c=Kf({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=_f(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===gf.CONNECTING||s.readyState===gf.OPEN)&&s.close(3008,t)},d=()=>{e.rejectReceipt(Error(`WebSocket payment flow aborted.`)),e.rejectCloseReady(Error(`WebSocket payment flow aborted.`)),s.close()};s.addEventListener(`close`,t=>{o?.removeEventListener(`abort`,d),c.socket=null,c.expectedCloseAmount=null,e.rejectReceipt(Error(`WebSocket closed before the payment flow completed.`)),e.rejectCloseReady(Error(`WebSocket closed before the payment flow completed.`)),l.emit(`close`,{code:t.code??1e3,reason:t.reason??``,type:`close`,wasClean:!0})}),s.addEventListener(`error`,()=>{l.emit(`error`,{type:`error`})}),s.addEventListener(`message`,async t=>{let n=typeof t.data==`string`?t.data:void 0;n&&await Qf({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await Zf(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(Ll(n)),await e.waitForReceipt(),l.socket}function Zf(e,t,n,r){return new Promise((i,a)=>{let o=()=>{e.removeEventListener(`open`,s),e.removeEventListener(`error`,c),e.removeEventListener(`close`,c),r?.removeEventListener(`abort`,l)},s=()=>{o(),t(`open`,{type:`open`}),i()},c=()=>{o(),a(Error(`WebSocket connection to ${n} failed to open.`))},l=()=>{o(),a(r?.reason)};e.addEventListener(`open`,s,{once:!0}),e.addEventListener(`error`,c,{once:!0}),e.addEventListener(`close`,c,{once:!0}),r?.addEventListener(`abort`,l,{once:!0}),r?.aborted&&l()})}async function Qf(e){let t=zl(e.message);if(!t){e.managedEmit(`message`,{data:e.message,type:`message`});return}switch(t.mpp){case`authorization`:return;case`message`:e.socketState.deliveredChunks+=1n,e.managedEmit(`message`,{data:t.data,type:`message`});return;case`payment-close-ready`:$f(e,t.data);return;case`payment-error`:e.driver.rejectReceipt(Error(t.message)),e.driver.rejectCloseReady(Error(t.message));return;case`payment-need-voucher`:await ep(e,t.data);return;case`payment-receipt`:tp(e,t.data);return}}function $f(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=Jf({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,cumulativeAmount:n,receipt:t});if(r){e.failSocketFlow(r);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleCloseReady(t),e.managedEmit(`close`,{code:1e3,reason:`stream complete`,type:`close`,wasClean:!0})}async function ep(e,t){try{let n=e.driver.challenge;n.expires&&new Date(n.expires).getTime()<=Date.now()+5e3&&(n=await e.driver.refreshChallenge(),e.driver.challenge=n,e.socketState.challenge=n);let r=await xf({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:n,event:t,expectedChannelId:e.socketState.channelId,getChannel:e.driver.getChannel,input:e.driver.httpUrl,signal:e.driver.options?.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status===`ignored`){e.failSocketFlow(r.reason===`channel-mismatch`?`received mismatched payment-need-voucher frame`:`cannot create voucher: no active channel`);return}let i=await e.driver.createSessionCredential(n,r.context);e.rawSocket.send(Ll(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function tp(e,t){let n=Yf({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,expectedCloseAmount:e.socketState.expectedCloseAmount,receipt:t});if(n){e.failSocketFlow(n);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleReceipt(t)}function np(e,t,n,r){let i=un(e),a=new Headers;if(i.toLowerCase()!==U.authorization.toLowerCase()){let e=new Headers(r).get(U.authorization)??(n instanceof Request?n.headers.get(U.authorization):null);e&&!e.startsWith(`${st.payment} `)&&a.set(U.authorization,e)}return a.set(i,t),a}const rp=new WeakMap;async function ip(e,t){let n=rp.get(e)??new Map;rp.set(e,n);let r=n.get(t),i,a=new Promise(e=>{i=e});return n.set(t,a),await r,()=>{i(),n.get(t)===a&&n.delete(t)}}function ap(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function op(e,t,n){try{let r=e.response?.headers.get(U.paymentReceipt);if(r){let e=Nl(r);if(e.challengeId===t.id&&ap(n,e))return!0}}catch{}return e.challenges?.some(e=>Cf(e)?ap(n,wf(e)):!1)??!1}function sp(e){let{allowedChainIds:t,currencies:n,decimals:r,expectedRecipients:i,maxAmount:a,maxAtomicAmount:o}=e;if((a!==void 0||o!==void 0)&&n===void 0)throw Error(`Tempo session maxAmount and maxAtomicAmount require currencies.`);for(let e of n??[])cp(a,typeof e==`string`?r:e.decimals);return{chainId:t?.length===1?t[0]:void 0,currencies:n,decimals:r,expectedRecipients:i?new Set(i.map(e=>e.toLowerCase())):void 0,maxAmount:a,maxAtomicAmount:o===void 0?void 0:BigInt(o)}}function cp(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo session maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo session maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return g(e,t)}}function lp(e,t,n){let r=e.currencies?Oe(e.currencies,t.currency,{chainId:t.methodDetails?.chainId??n??e.chainId,decimals:e.decimals}):void 0;if(e.currencies&&!r)throw Error(`Tempo session currency is not allowed: ${t.currency}.`);if(e.expectedRecipients&&(!t.recipient||!e.expectedRecipients.has(t.recipient.toLowerCase())))throw Error(`Unexpected session recipient: ${t.recipient}`);let i=BigInt(t.amount);if(e.maxAtomicAmount!==void 0&&i>e.maxAtomicAmount)throw Error(`Tempo session amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0&&i>cp(e.maxAmount,r?.decimals))throw Error(`Tempo session amount exceeds maxAmount.`)}function up(e,t){try{return lp(e,t),!0}catch{return!1}}function dp(e){return typeof e==`object`&&!!e&&e.action===`close`}function fp(e={}){let{account:t,allowCustomEscrow:n=!1,autoSwap:r,channelStore:i,decimals:a,escrow:o,allowedChainIds:s,getClient:c,maxDeposit:l,topUpAmount:u,onChannelUpdate:d,resolveAccount:f}=e,p=sp(e),m=Us({chain:re,getClient:c,rpcUrl:Wr}),h=zs({account:t}),_=(e,t)=>{let n=(p.currencies?Oe(p.currencies,e.currency,{chainId:e.methodDetails?.chainId??t??p.chainId,decimals:a}):void 0)?.decimals??a??6;return{decimals:n,maxDeposit:l===void 0?void 0:g(l,n),topUpAmount:u===void 0?void 0:g(u,n)}};l!==void 0&&g(l,6),u!==void 0&&g(u,6);let v=e.origin===void 0?void 0:new URL(e.origin);if(v&&![`http:`,`https:`].includes(v.protocol))throw Error(`Session origins require HTTP or HTTPS`);let y=i??Ru(),b={store:y,notifyUpdate:e=>d?.(e)},x=async(e,t,n)=>{let r=h(e.client,t),i=t?.action?t.descriptor:n?.descriptor??Qd({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:Hl(i)}:{}}})??r},S=async(e,t,n)=>{let{decimals:r,maxDeposit:i}=_(e.challenge.request,e.chainId);return nf({account:await x(e,t,n),entry:n,context:t,decimals:r,maxDeposit:i,resolved:e})},C=Mn(Qc,{canHandleChallenge:({challenge:e,context:t})=>Cf(e)&&(dp(t)||t===Oi||up(p,e.request)),context:Rd,async createCredential(e){let{challenge:t,context:i}=e;i?.action!==`close`&&lp(p,t.request);let a=await Yd({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:m});i?.action!==`close`&&t.request.methodDetails?.chainId===void 0&&lp(p,t.request,a.chainId);let c=Ba(e),l=Ga(e)??v?.origin;if(l!==void 0&&(l===`null`||![`http:`,`https:`].includes(new URL(l).protocol)))throw Error(`Session payments require an HTTP or HTTPS origin`);if(v&&l!==v.origin)throw Error(`Session channel origin mismatch`);let u={...b,origin:l},d=()=>{};try{let e=!zd(i)&&i?.descriptor===void 0;e&&(d=await ip(y,a.key),c&&(await y.get(a.key))?.opened&&await c.prepare());let n=await y.get(a.key);if(n&&n.origin!==l)throw Error(`Session channel origin mismatch`);if(l&&!n&&a.snapshot&&!i?.descriptor&&!v)throw Error(`Session snapshot recovery requires an explicitly configured origin or descriptor`);let o=await S(a,i,n);if(!e&&c&&o.type===`open`){d=await ip(y,a.key);let e=await y.get(a.key);if(e&&e.origin!==l)throw Error(`Session channel origin mismatch`);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await c.prepare(),n=await y.get(a.key)),o=await S(a,i,n))}let s,f=c&&o.type===`open`?{store:{get:e=>y.get(e),async set(e){s=l?{...e,origin:l}:e},delete:e=>y.delete(e)},notifyUpdate(){}}:u,p=await Au(t,await rf(o,f,ec(i?.autoSwap??r,Qs)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||op(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await y.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await Wu(y,e),b.notifyUpdate(e))}return!0}finally{d()}}}else d();return p}catch(e){throw d(),e}}});function w(e,t,n){let r={challenge:e,context:t};return Wa(r,pp(n)),C.createCredential(r)}let ee=async({autoSwap:e,challenge:t,channel:n,deposit:r,fetch:i,input:a,requiredCumulative:o,signal:s})=>Uu(y,Q(n),async()=>{s?.throwIfAborted();let c=await y.get(Q(n));if(c?.channelId===n.channelId&&(n=c),n.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let l=n.deposit>r?n.deposit:r,{maxDeposit:u,topUpAmount:d}=_(t.request,n.chainId),f=_d({deposit:l,maxDeposit:u,requiredCumulative:o,suggestedDeposit:t.request.suggestedDeposit===void 0?void 0:BigInt(t.request.suggestedDeposit),topUpAmount:d});f>0n&&await jf({autoSwap:e,additionalDeposit:f,challenge:t,channel:n,channelId:n.channelId,createSessionCredential:(e,t)=>w(e,t,a),onUncertainFunding:async e=>{let t=await y.get(Q(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};await Wu(y,n),b.notifyUpdate(n)},fetch:i,input:a,signal:s});let p=l+f;if(p===n.deposit)return;let m=await y.get(Q(n)),h=m?.channelId.toLowerCase()===n.channelId.toLowerCase()?m:n,g={...h,deposit:h.deposit>p?h.deposit:p};await Wu(y,g),b.notifyUpdate(g)});return ka(C,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!Cf(e))return;let c=t===void 0?void 0:Rd.parse(t);if(zd(c))return;lp(p,e.request);let l=await Yd({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m}),u=await y.get(l.key);if(!u?.opened)return;let d=pp(i);if(u.origin!==d)throw Error(`Session channel origin mismatch`);let f=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,h=u.cumulativeAmount+Al(e),g=f?BigInt(f.requiredCumulative):h,_=g>h?g:h,v=f?BigInt(f.deposit):u.deposit,b=v>u.deposit?v:u.deposit;_<=b&&b===u.deposit||!tf(await x(l,c,u),u.descriptor)||await ee({autoSwap:c?.autoSwap,challenge:e,channel:u,deposit:b,fetch:r,input:i,requiredCumulative:_,signal:a})}),La(C,async({challenge:e,context:t,credential:r,fetch:i,headers:a,input:c,refetch:l,response:u,signal:d})=>{if(!Cf(e))return u;if(!Pl(u))return kl(yn(r).payload).action===`open`&&a.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await l?.()??u:u;let f=(await Yd({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m})).key,p=await y.get(f),h={assertVoucherWithinLocalLimit:t=>vd(t,_(e.request,p?.chainId).maxDeposit),createSessionCredential:(e,t)=>w(e,t,c),fetch:i,getChannel:()=>p??null,async topUpIfNeeded({deposit:n,requiredCumulative:r,signal:a}){p&&await ee({autoSwap:t===void 0?void 0:Rd.parse(t).autoSwap,challenge:e,channel:p,deposit:p.deposit>n?p.deposit:n,fetch:i,input:c,requiredCumulative:r,signal:a})}};return Hf({onNeedVoucher:(t,n)=>Uf({challenge:e,driver:h,headers:a,input:c,signal:n},t),onReceipt(){},response:u,signal:d})})}function pp(e){let t=new URL(e instanceof Request?e.url:e,globalThis.location===void 0?void 0:globalThis.location.href);if(![`http:`,`https:`].includes(t.protocol))throw Error(`Session payments require an HTTP or HTTPS origin`);return t.origin}const mp=new WeakMap;function hp(e,t){mp.set(e,t)}function gp(e){let t=null;return{wait(n=()=>!0){if(t)throw Error(`${e} wait already in progress`);return new Promise((e,r)=>{t={predicate:n,resolve:e,reject:r}})},settle(e){if(!t||!t.predicate(e))return;let n=t;t=null,n.resolve(e)},reject(e){if(!t)return;let n=t;t=null,n.reject(e)}}}function _p(e){let t=gp(`close-ready`),n=gp(`receipt`);return{waitForReceipt(e){return n.wait(e)},waitForCloseReady(){let n=e.getSocketSession()?.closeReadyReceipt;return n?Promise.resolve(n):t.wait()},settleReceipt(e){n.settle(e)},settleCloseReady(n){let r=e.getSocketSession();r&&r.challenge.id===n.challengeId&&r.channelId===n.channelId&&(r.closeReadyReceipt=n),t.settle(n)},rejectReceipt(e){n.reject(e)},rejectCloseReady(e){t.reject(e)}}}function vp(e){return e.method===ct.tempo&&e.intent===lt.charge}function yp(e){if(!vp(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function bp(e,t,n){if(!n)return t;let r={...Xo(Ef(e)?e.headers:void 0),...Xo(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===U.paymentSession.toLowerCase())?t:{...t,headers:{...r,[U.paymentSession]:n}}}function xp(e,t){return e===void 0?t:{...Rd.parse(e),...t}}function Sp(e){let t=e.decimals??6,n=e.webSocket??globalThis.WebSocket;return{decimals:t,fetch:e.fetch??globalThis.fetch.bind(globalThis),maxVoucherCumulative:e.maxDeposit===void 0?null:g(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:g(e.topUpAmount,t),WebSocket:n}}function Cp(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&Gs(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=Sp(e),i;function a(e){let t=new URL(Ef(e)?e.url:String(e),typeof location>`u`?void 0:location.href);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`SessionManager: session payments require an HTTP origin`);let n=t.origin;if(i!==void 0&&i!==n)throw Error(`SessionManager: session payment origin mismatch`);return i=n,n}if(ys(r.fetch))throw TypeError(`SessionManager: the fetch sets spending options (maxPayment, authorize, funders or tokens), which accept only charges. Pass a fetch without them.`);let o=vs(r.fetch),s=bs(r.fetch);r.fetch=async(e,t)=>{let n=a(e),r=await s(e,{...t,redirect:(t?.redirect??(Ef(e)?e.redirect:void 0))===`manual`?`manual`:`error`});if(r.url&&new URL(r.url).origin!==n)throw Error(`SessionManager: session response origin mismatch`);return r};let c=r.fetch;o&&(r.fetch=Ti(c,o));let l=Us({chain:re,getClient:e.client?()=>e.client:e.getClient,rpcUrl:Wr}),u=zs({account:e.account}),d=wd(),f=e.credentialContext===void 0?void 0:xp(e.credentialContext,{}),p=_p({getSocketSession:()=>d.socketSession}),m=e.channelStore??Ru(),h=new Set,g;async function _(e){let t=await m.get(e);if(t?.opened&&!h.has(t.channelId)){if(t.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return t}}let v=e=>{if(e.origin!==void 0&&e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);return e.origin=i,Wu(m,e)},y={async get(e){let t=await _(e);return t&&g&&(g.seenExisting.add(e),!g.committed&&!g.created.has(e)&&(g.resumed??=t)),t},async set(e){let t=Q(e);e.opened&&h.delete(e.channelId),g?.trackCreates&&!g.seenExisting.has(t)&&g.created.set(t,e),await v(e)},delete:e=>Gu(m,e)};Vu(y,m);async function b(e){let t=Q(e),n=await m.get(t);if(e.uncertainTopUp||n?.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);h.add(e.channelId),g?.seenExisting.delete(t),g?.resumed===e&&(g.resumed=void 0),await Promise.resolve(Gu(m,t)).catch(()=>void 0)}async function x(){let e=g;if(e?.created.size){for(let[t,n]of e.created){let e=await m.get(t);if(n.uncertainTopUp||e?.channelId===n.channelId&&e.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before discarding the channel.`);h.add(n.channelId),await Promise.resolve(Gu(m,t)).catch(()=>void 0)}e.created.clear(),await B(e.committed??e.previous)}}function S(e){let t=ft(e.request.methodDetails,ut.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=g;if(!n?.created.size||!d.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&d.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=kd({channel:d.channel,spent:d.spent,state:d.state}),!0;return!1}function C(e){return cd(d,e)}function w(){let e=d.state.status===`active`?d.state:g?.committed?.state??g?.previous.state;return e?.status===`active`?e.units:0}function ee(e){let t=g,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit&&!e.uncertainTopUp||(t.resumed=void 0,t.committed=kd({channel:d.channel,spent:d.spent,state:d.state}))}let T=fp({account:e.account,allowCustomEscrow:n,autoSwap:e.autoSwap,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount,escrow:e.escrow,allowedChainIds:e.allowedChainIds,decimals:r.decimals,maxDeposit:e.maxDeposit,topUpAmount:e.topUpAmount,channelStore:y,onChannelUpdate(e){e.channelId!==d.channel?.channelId&&(d.spent=0n),d.channel=e,d.lastChallenge&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),ee(e)}}),te=Ma(T);te&&ka(T,e=>z(()=>Promise.resolve(te(e)),e.signal)),Ra(T);let ne=tl({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),E=Yo({trustedTempoProofRealms:e.trustedTempoProofRealms,fetch:c,identity:o,methods:[T],onChallenge:async(e,t)=>{if(!Sf(e))return;let n=g,r=n&&n.challengesReceived>0&&e.id===d.lastChallenge?.id,i=r&&Is(e)===Is(d.lastChallenge);n&&n.challengesReceived++,!i&&(S(e)||(n?.created.size?await x():r&&await B(n.committed??n.previous)),d.lastChallenge=e,C({type:`challengeReceived`,challengeId:e.id}))}});function D(e,t){let n={challenge:e,context:xp(f,t)};return i&&Wa(n,i),T.createCredential(n)}function O(e){Td({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:d})}function k(e=d.state.status===`active`?d.state.units:0){!d.channel||!d.lastChallenge||d.state.status!==`active`&&d.state.status!==`withdrawable`&&d.state.status!==`closeRequested`&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:d.channel,spent:d.spent.toString(),units:e})}async function A(t){let r=t.headers.get(U.paymentSessionSnapshot);if(!r)return;let i=id(r);Gs(e.allowedChainIds,i.chainId),ku({request:{methodDetails:{escrow:i.escrow}}},e.escrow,n);let a=await l({chainId:i.chainId});Ws(a,i.chainId);let o=u(a),{entry:s,spent:c}=await ef({account:await e.resolveAccount?.({account:o,chainId:i.chainId,operation:{authority:Hl(i.descriptor),kind:`authorizePaymentChannel`}})??o,client:a,snapshot:i});return I(s.cumulativeAmount),await Promise.resolve(y.set(s)).catch(()=>void 0),d.channel=s,d.spent=c,s}async function j(t,n){if(!e.bootstrap||d.channel?.opened)return;let i=Ef(t)?t.headers:void 0,{body:a,method:o,...s}=n??{},c=Ef(t)?t.url:t,l={...s,method:`HEAD`,headers:{...Xo(i),...Xo(n?.headers),[U.acceptPayment]:`${ct.tempo}/${lt.charge}`}};try{let t=await r.fetch(c,l);if(t.status!==402)return await A(t);let n=nn(t).find(vp);if(!n||!yp(n))return;let i=new URL(String(c),typeof location<`u`?location.href:void 0);if(t.url&&new URL(t.url).origin!==i.origin)return;qa(n,i,e.trustedTempoProofRealms);let a=await ne.createCredential({challenge:n,context:{}}),o=await r.fetch(c,na({...l,redirect:`manual`},un(n),a));return o.ok?await A(o):void 0}catch{return}}function M(e,t){let n=d.socketSession;return Dd({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:d.channel?.channelId===t?d.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:d.spent,tickCost:n?.tickCost})}function N(e,t){let n=wf(t);if(!n)return;if(Ul({...n.descriptor,chainId:n.chainId,escrow:n.escrow}).toLowerCase()!==n.channelId.toLowerCase())throw Error(`close snapshot descriptor does not match its channel ID`);if(n.channelId.toLowerCase()!==e.channelId.toLowerCase())throw Error(`close snapshot channel ID does not match local session`);if(n.chainId!==e.chainId||n.escrow.toLowerCase()!==e.escrow.toLowerCase())throw Error(`close snapshot payment scope does not match local session`);let r=BigInt(n.acceptedCumulative),i=BigInt(n.spent);if(r<0n||i<0n)throw Error(`close snapshot amounts must not be negative`);if(i>r)throw Error(`close snapshot spent exceeds accepted cumulative amount`);if(r>e.cumulativeAmount)throw Error(`close snapshot accepted cumulative exceeds local voucher state`);return{acceptedCumulative:r,spent:i}}function P(e,t){let n=N(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(d.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>d.spent&&(d.spent=i),n}function F(e,t=e.challenge,n=!1){let r=(n?P(e,t):N(e.channel,t))?.acceptedCumulative??M(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return I(r),r.toString()}function I(e){fd({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}let L,R;async function z(e,t){if(R)throw R;for(;;){let e=L;if(!e)break;if(!t)await e;else{t.throwIfAborted();let n;try{await Promise.race([e,new Promise((e,r)=>{n=()=>r(t.reason),t.addEventListener(`abort`,n,{once:!0})})])}finally{t.removeEventListener(`abort`,n)}}}if(t?.throwIfAborted(),R)throw R;let n=e();L=n;try{return await n}catch(e){throw e instanceof Af&&(R=Error(`Session funding outcome is unknown; reconcile the pending payment before creating a new session manager.`)),e}finally{L===n&&(L=void 0)}}async function ie(e){if(!d.channel)throw Error(`Cannot top up session: no active channel`);return Uu(m,Q(d.channel),async()=>{let{knownDeposit:t,...n}=e,i=d.channel?await y.get(Q(d.channel)):void 0;if(i?.channelId===e.channelId&&i.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let a=await jf({...n,channel:d.channel,createSessionCredential:D,fetch:r.fetch,onUncertainFunding:async e=>{let t=await y.get(Q(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};d.channel?.channelId===e.channelId&&(d.channel=n),await y.set(n),ee(n)}});O(a);let o=d.channel,s=bf({additionalDeposit:e.additionalDeposit,channel:d.channel,channelId:e.channelId,challengeId:d.lastChallenge?.id,currentState:d.state,knownDeposit:t,receipt:a,spent:d.spent});if(s?.channel&&d.lastChallenge){let e=s.channel;for(;;){await y.set(e);let t=d.channel;if(t===o)break;if(!t)return a;let n=s.channel;e=t.channelId===n.channelId?{...t,deposit:t.deposit>n.deposit?t.deposit:n.deposit,cumulativeAmount:t.cumulativeAmount>n.cumulativeAmount?t.cumulativeAmount:n.cumulativeAmount}:t,o=t}if(e.channelId!==s.channel.channelId)return a;d.channel=e,C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),ee(e)}return a})}async function ae(e){return z(async()=>{e.signal?.throwIfAborted();let t=d.channel?.channelId===e.channelId?d.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=_d({deposit:n,maxDeposit:r.maxVoucherCumulative,requiredCumulative:e.requiredCumulative,suggestedDeposit:e.challenge.request.suggestedDeposit===void 0?void 0:BigInt(e.challenge.request.suggestedDeposit),topUpAmount:r.topUpAmount});i!==0n&&await ie({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})},e.signal)}async function oe(e,t){let n=Od({channel:d.channel,channelId:e,challengeId:d.lastChallenge?.id,cumulativeAmount:t,spent:d.spent,state:d.state});n&&d.channel&&(C({type:`activated`,challengeId:n.challengeId,entry:d.channel,spent:n.spent,units:n.units}),await v(d.channel))}async function B(e){let t=Ad(e,d.channel);d.channel=t.channel,d.spent=t.spent,d.state=t.state,d.channel?.opened&&await v(d.channel)}function se(e,t=!0){let n=e.headers.get(U.paymentReceipt),r=n?Nl(n):null;return t&&O(r),Object.assign(e,{receipt:r,challenge:d.lastChallenge,channelId:d.channel?.channelId??null,cumulative:d.channel?.cumulativeAmount??0n})}async function V(e,t){if(t?.[Uo])return se(await r.fetch(e,Wo(t)),!1);if(g)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);a(e),d.lastUrl=e,d.lastHeaders=t?.headers;let n=kd({channel:d.channel,spent:d.spent,state:d.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};g=i;try{await j(e,t),i.trackCreates=!0;let a=bp(e,t,d.channel?.opened?d.channel.channelId:void 0);f&&(a={...a,context:f});let o=!n.channel?.opened;async function s(){let n=i.resumed;return!o||!n?!1:(o=!1,await b(n),a=bp(e,t,void 0),!0)}for(;;){let t;try{t=await E(e,a)}catch(e){if(i.created.size?await x():await B(i.committed??n),await s())continue;throw e}let o=se(t),c=!1;if(o.status===402){let t=await Nf({input:e,init:a,response:o,createSessionCredential:D,fetch:r.fetch,getChannel:()=>d.channel,restoreCumulative:oe,setChallenge(e){d.lastChallenge=e},topUpIfNeeded:ae});t&&(c=!0,o=se(t))}if(!c&&!o.ok&&!o.receipt){if(i.created.size?await x():await B(i.committed??n),await s())continue;return o}return o}}finally{g=void 0}}async function ce(e){let t=await Ff({createSessionCredential:D,fetch:r.fetch,getMinimumSpent:()=>d.spent,headers:d.lastHeaders,lastUrl:d.lastUrl,resolveSignedCloseAmount:t=>F(e,t,!0),signedCloseAmount:F(e),setChallenge(e){d.lastChallenge=e},target:e});return t&&(k(),C({type:`closeStarted`}),C({type:`closed`,receipt:t})),t}let le={createSessionCredential:D,doFetch:V,fetch:r.fetch,getChannel:()=>d.channel,getChallenge:()=>d.lastChallenge,assertVoucherWithinLocalLimit:I,acceptReceipt(e){O(e)},topUpIfNeeded:ae},ue={get channelId(){return d.channel?.channelId},get cumulative(){return d.channel?.cumulativeAmount??0n},get opened(){return d.channel?.opened??!1},get state(){return d.state},fetch:V,async topUp(e){let t=yf({amount:e,assertVoucherWithinLocalLimit:I,channel:d.channel,decimals:r.decimals,lastChallenge:d.lastChallenge,lastUrl:d.lastUrl});return z(async()=>{if(d.channel?.channelId!==t.channelId||d.lastChallenge!==t.challenge||d.lastUrl!==t.input)throw Error(`Session changed while waiting to top up`);let n=yf({amount:e,assertVoucherWithinLocalLimit:I,channel:d.channel,decimals:r.decimals,lastChallenge:t.challenge,lastUrl:t.input});return ie({additionalDeposit:n.additionalDeposit,challenge:n.challenge,channelId:n.channelId,headers:d.lastHeaders,input:n.input})})},async sse(e,t){if(t?.[Uo])throw Error(`SessionManager.sse requires payment; use fetch for unpaid streams.`);return If(e,t,le)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=Of(e);a(n);let i=t?.signal?{signal:t.signal}:void 0;await j(n,i);let o=d.channel?.opened?d.channel.channelId:void 0,{challenge:s,credential:c,httpUrl:l,wsUrl:u}=await Gf({async createSessionCredential(e,i){return d.lastChallenge=e,await ja(T,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),D(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){d.lastUrl=e.toString()},probeInit:bp(n,i,o),signal:t?.signal});return d.lastChallenge=s,Xf({challenge:s,credential:c,httpUrl:l,WebSocket:r.WebSocket,wsUrl:u,options:t,createSessionCredential:D,getChannel:()=>d.channel,setSocketSession(e){d.socketSession=e},async refreshChallenge(){let e=await Wf({fetch:r.fetch,input:l,probeInit:bp(l,i,d.channel?.opened?d.channel.channelId:void 0),signal:t?.signal});return d.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:I,acceptReceipt:O,rejectCloseReady:p.rejectCloseReady,rejectReceipt:p.rejectReceipt,settleCloseReady:p.settleCloseReady,settleReceipt:p.settleReceipt,topUpIfNeeded:ae,waitForReceipt:p.waitForReceipt})},async close(){let e=d.socketSession,t=yd({channel:d.channel,currentSocket:e,lastChallenge:d.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===gf.OPEN){let r=await jd({activeSocket:n,createSessionCredential:D,currentSocket:e,spent:d.spent,target:t,waitForCloseReady:p.waitForCloseReady,waitForReceipt:p.waitForReceipt});return k(),C({type:`closeStarted`}),C({type:`closed`,receipt:r}),r}return ce(t)}};return hp(ue,{consumeSseResponse(e,t,n){let r=a(e);if(t.url&&new URL(t.url).origin!==r)throw Error(`SessionManager: session response origin mismatch`);return Lf(e,t,n,le)},rehydrate({channel:e,challenge:t,input:n,spent:r}){let i=a(n);if(e.origin!==i)throw Error(`SessionManager: stored channel origin mismatch`);if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!Sf(t))throw Error(`Cannot restore session: challenge is not tempo/session.`);if(r<0n)throw Error(`Cannot restore session: spent must not be negative.`);if(r>e.cumulativeAmount)throw Error(`Cannot restore session: spent exceeds local voucher state.`);I(e.cumulativeAmount);let o=N(e,t),s=o&&o.spent>r?o.spent:r;d.lastUrl=n,d.lastChallenge=t,d.channel=e,d.spent=s,C({type:`challengeReceived`,challengeId:t.id}),C({type:`activated`,challengeId:t.id,entry:e,spent:s.toString(),units:0})}}),ue}(function(e){e.serializeSnapshot=rd,e.deserializeSnapshot=id})(Cp||={});const wp=(1n<<64n)-1n,Tp={dev_second:1n,day:86400n,week:604800n};function Ep(e){return e instanceof Date?e:new Date(e)}function Dp(e){let t=e.getTime();if(!Number.isFinite(t))throw new W({reason:`subscriptionExpires is invalid`});if(t%1e3!=0)throw new W({reason:`subscriptionExpires must be representable as whole seconds`});let n=t/1e3;if(n<=0||!Number.isSafeInteger(n))throw new W({reason:`subscriptionExpires cannot be represented in a Tempo key authorization`});return n}function Op(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new W({reason:`periodCount is invalid`});let t=Tp[e.periodUnit];if(t===void 0)throw new W({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>wp)throw new W({reason:`subscription period cannot be represented as an unsigned 64-bit integer`});if(n>BigInt(2**53-1))throw new W({reason:`subscription period cannot be represented exactly by this Tempo client`});return Number(n)}function kp(e){let{challengeExpires:t,request:n}=e;Op(n);let r=Dp(Ep(n.subscriptionExpires));if(t){let e=Math.floor(new Date(t).getTime()/1e3);if(!Number.isFinite(e)||r<=e)throw new W({reason:`subscriptionExpires must be strictly later than challenge expires`})}}function Ap(e){return[{address:Up(e.currency,`currency`),selector:`0x95777d59`,recipients:[Up(e.recipient,`recipient`)]}]}function jp(e){try{let t=A.fromBytes(D.toBytes(e));if(A.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new W({reason:`challenge id must encode 32 bytes`})}}async function Mp(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=Pp({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:ge.getSignPayload(o)}),c=H.from(s);if(c.type===`keychain`||c.type===`configurable`)throw new W({reason:`keyAuthorization must use a primitive signature`});return ge.from(o,{signature:H.serialize(Ql(c))})}function Np(e){let{accessKey:t,challengeId:n,chainId:r,payload:i,request:a}=e;if(i.type!==`keyAuthorization`)throw new W({reason:`invalid keyAuthorization payload`});let o=Fp(i.signature),s=Ip(o);if(Lp({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==jp(n))throw new W({reason:`keyAuthorization challenge mismatch`});return Rp(o,a),Bp(zp(o),a),Vp(o.scopes,a),{authorization:o,source:{address:Hp(o,s),chainId:r}}}function Pp(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return ge.from({address:Up(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:Dp(Ep(i.subscriptionExpires)),limits:[{token:Up(i.currency,`currency`),limit:BigInt(i.amount),period:Op(i)}],scopes:Ap(i),type:t.keyType,witness:jp(n)})}function Fp(e){try{return ge.deserialize(e)}catch(e){throw e instanceof ge.InvalidSignatureTypeError?new W({reason:`keyAuthorization must use a primitive signature`}):new W({reason:`invalid keyAuthorization payload`})}}function Ip(e){let t=e.signature;if(!t)throw new W({reason:`keyAuthorization must use a primitive signature`});return t}function Lp(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new W({reason:`keyAuthorization chainId mismatch`});if(t){if(!f(n.address,Up(t.accessKeyAddress,`accessKeyAddress`)))throw new W({reason:`keyAuthorization access key mismatch`});if(n.type!==t.keyType)throw new W({reason:`keyAuthorization key type mismatch`})}}function Rp(e,t){if(kp({request:t}),e.expiry!==Dp(Ep(t.subscriptionExpires)))throw new W({reason:`keyAuthorization expiry mismatch`})}function zp(e){let[t]=e.limits??[];if(!t||e.limits?.length!==1)throw new W({reason:`keyAuthorization must contain exactly one token limit`});return t}function Bp(e,t){if(!f(e.token,Up(t.currency,`currency`)))throw new W({reason:`keyAuthorization currency mismatch`});if(e.limit!==BigInt(t.amount))throw new W({reason:`keyAuthorization amount mismatch`});if(e.period!==Op(t))throw new W({reason:`keyAuthorization period mismatch`})}function Vp(e,t){if(!e||e.length!==1)throw new W({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=Up(t.currency,`currency`),r=Up(t.recipient,`recipient`),i=new Set;for(let t of e){if(!f(t.address,n))throw new W({reason:`keyAuthorization call target mismatch`});let e=Wp(t.selector);if(e!==`0xa9059cbb`&&e!==`0x95777d59`)throw new W({reason:`keyAuthorization selector not allowed`});if(i.has(e))throw new W({reason:`keyAuthorization duplicate selector`});if(i.add(e),t.recipients?.length!==1||!f(t.recipients[0],r))throw new W({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new W({reason:`keyAuthorization must allow transferWithMemo`})}function Hp(e,t){let n=ge.getSignPayload(e);try{let e=H.extractAddress({payload:n,signature:t});if(!Zl(t)||!H.verify(t,{address:e,payload:n}))throw new W({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof W?e:new W({reason:`keyAuthorization signature is invalid`})}}function Up(e,t){if(!d(e))throw new W({reason:`${t} must be an address`});return e.toLowerCase()}function Wp(e){return typeof e==`string`?e.toLowerCase():``}const Gp=K.object({accessKey:K.optional(K.custom()),account:K.optional(K.custom())});function Kp(e={}){let t=Us({chain:R,requireChain:!0,getClient:e.getClient,rpcUrl:Wr}),n=zs({account:e.account});return Mn($c,{context:Gp,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??Z.testnet,o=await t({chainId:a});if(o.chain?.id!==a)throw Error(`Subscription chain mismatch: expected ${a}, got ${o.chain?.id??`unknown`}.`);let s=n(o,i),c=i?.accessKey??e.accessKey??r.request.methodDetails?.accessKey;if(!c)throw Error("No `accessKey` provided. The subscription challenge must include `accessKey`, or the client must pass one to parameters/context.");Jp(r.request),await e.validateRequest?.(r.request);let l=await qp(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),u=Np({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:ge.serialize(l),type:`keyAuthorization`},request:r.request});if(!f(u.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return wn({challenge:r,payload:{signature:ge.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function qp(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await Mp({accessKey:n,account:r,challengeId:i,chainId:a,request:o});if(s)return s;let c=await e.request({method:`wallet_authorizeAccessKey`,params:[{address:n.accessKeyAddress,expiry:Dp(Ep(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:A.fromNumber(BigInt(o.amount)),period:Op(o)}],scopes:Ap(o),witness:jp(i)}]});return ge.fromRpc(c.keyAuthorization)}function Jp(e){Op(e),Dp(Ep(e.subscriptionExpires))}const Yp=Object.assign(fp,{manager:Cp});function Xp(e={}){let t=e.expectedChainId!==void 0&&(e.allowedChainIds===void 0||e.allowedChainIds.includes(e.expectedChainId)),n=e.expectedChainId===void 0?e:{...e,allowedChainIds:t?[e.expectedChainId]:[]};return[tl(e),Yp(n)]}(function(e){e.charge=tl,e.common=Xp,e.session=Yp,e.subscription=Kp})(Xp||={});const Zp=L.union([L.boolean(),L.literal(`true`).transform(()=>!0),L.literal(`false`).transform(()=>!1)]);async function Qp(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}const $p=L.object({allowCustomEscrow:L.optional(Zp),autoSwap:L.optional(Zp),channel:L.optional(L.coerce.string()),deposit:L.optional(L.union([L.string(),L.number()])),payWith:L.optional(L.string()),slippage:L.optional(L.coerce.number()),tokenIn:L.optional(L.string())}),em=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`];function tm(){let t;return di({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:n,options:r,methodOpts:i}){let a=si(r.account),o=n.request,s=o.currency,c=sm(i),l=dm({autoSwap:c.autoSwap??r.autoSwap,payWith:c.payWith??r.payWith,slippage:c.slippage??r.slippage,tokenIn:c.tokenIn}),d=s??``,f=o.decimals??6,p,m,h,g=!1,_=process.env.MPPX_PRIVATE_KEY?.trim()||(Kr(a)?void 0:await ci(a).get());if(!_&&Kr(a)&&bm()){g=!0;let t=vm(a);if(t){let i=Yr(r.rpcUrl,{network:r.network});h=e({chain:await Xr({network:r.network,rpcUrl:i}),transport:u(i)}),lm({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let a=s?await $r(h,s,t.wallet_address).catch(()=>void 0):void 0;d=a?.symbol??s??``,f=a?.decimals??o.decimals??6}}else if(_)m=pe(_);else{let e=Sm();if(e){let t=await ci(e).get();t&&(m=pe(t))}if(!m)throw r.account?new zr({code:`ACCOUNT_NOT_FOUND`,message:`Account "${a}" not found.`,exitCode:69}):new zr({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!g&&m){let t=Yr(r.rpcUrl,{network:r.network});h=e({chain:await Xr({network:r.network,rpcUrl:t}),transport:u(t)}),lm({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let i=s?await $r(h,s,m.address).catch(()=>void 0):void 0;d=i?.symbol??s??``,f=i?.decimals??o.decimals??6}if(g)return{tokenSymbol:d,tokenDecimals:f,explorerUrl:p,methods:[],async createCredential(e){let t=e.headers.get(`www-authenticate`);if(!t)throw Error(`No WWW-Authenticate header in 402 response.`);return xm(t)}};if(!m||!h)throw new zr({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let v=Xp({account:m,...c.allowCustomEscrow===void 0?{}:{allowCustomEscrow:c.allowCustomEscrow},getClient:()=>h,...l===void 0?{}:{autoSwap:l},maxDeposit:(()=>{if(n.intent!==`session`)return;let e=n.request.suggestedDeposit,t=(c.deposit===void 0?void 0:String(c.deposit))??e??(Qr(h.chain)?`10`:void 0);if(!t)throw new zr({code:`MISSING_DEPOSIT`,message:`Session payment requires a deposit. Use -M deposit=<amount> or connect to testnet.`,exitCode:2});return t})()}),y=(()=>{if(!c.channel)return;let e=c.channel,t=pm(e);return{channelId:e,...t!==void 0&&{cumulativeAmountRaw:t.toString()}}})();return t={descriptor:void 0,async signVoucher({channelId:e,cumulativeAmount:r,escrowContract:i,chainId:a,action:o=`voucher`}){let s=t?.descriptor;if(!s)throw Error(`session descriptor not available`);let c={channelId:e,cumulativeAmount:r},l=await hu(h,m,c,i,a);return wn({challenge:n,payload:{action:o,channelId:e,...o===`close`?{closeSignature:await gu(h,m,c,i,a)}:{},descriptor:s,cumulativeAmount:r.toString(),signature:l},source:`did:pkh:eip155:${a}:${m.address}`})},source:`did:pkh:eip155:${h.chain.id}:${m.address}`},{tokenSymbol:d,tokenDecimals:f,explorerUrl:p,methods:[...v],credentialContext:y}},prepareCredentialRequest({challenge:e,headers:t}){e.intent===`session`&&(t.Accept=`text/event-stream`)},async handleResponse(e){if(e.challenge.intent!==`session`||!t)return!1;let{challenge:n,credential:r,response:i,fetchUrl:a,fetchInit:o,verbose:s}=e,{silent:c,confirmEnabled:l,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,shownKeys:p}=e,m=c?e=>{}:e=>process.stderr.write(e),h=yn(r),g=n.request,_=g.methodDetails,v=h.payload.channelId,y=_?.escrowContract??_?.escrow??`0x4d50500000000000000000000000000000000000`,b=_?.chainId??0,x=BigInt(g.amount),S=`cumulativeAmount`in h.payload&&h.payload.cumulativeAmount?BigInt(h.payload.cumulativeAmount):0n;if(`descriptor`in h.payload&&(t.descriptor=h.payload.descriptor),s>=1){if(h.payload.action===`open`){let e=g.suggestedDeposit,t=e?` ${X.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
|
|
13
13
|
`}${X.dim(`Channel opened ${h.payload.channelId}`)}${t}\n`)}else m(`${l?``:`
|
|
14
|
-
`}${X.dim(`Channel reused ${h.payload.channelId}`)}\n`)}let C=i;C.ok&&!C.headers.get(`Content-Type`)?.includes(`text/event-stream`)&&h.payload.action===`open`&&`cumulativeAmount`in h.payload&&(S=BigInt(h.payload.cumulativeAmount));let w=C.headers.get(U.paymentReceipt);if(w)try{let e=JSON.parse(D.toString(w));
|
|
15
|
-
`})}catch{}return(C.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await
|
|
16
|
-
`),l&&!await e.confirm(`Close channel?`,!0)?s>=1&&m(`${X.dim(`Kept channel open.`)}\n`):await
|
|
17
|
-
`)}function
|
|
14
|
+
`}${X.dim(`Channel reused ${h.payload.channelId}`)}\n`)}let C=i;C.ok&&!C.headers.get(`Content-Type`)?.includes(`text/event-stream`)&&h.payload.action===`open`&&`cumulativeAmount`in h.payload&&(S=BigInt(h.payload.cumulativeAmount));let w=C.headers.get(U.paymentReceipt);if(w)try{let e=JSON.parse(D.toString(w));rm(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&mm(v,S),s>=1&&nm(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
|
|
15
|
+
`})}catch{}return(C.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await im(C,{challenge:n,channelId:v,escrowContract:y,chainId:b,cumulativeAmount:S,tickCost:x,fetchUrl:a,fetchInit:o,session:t,info:m,verbose:s,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this}):(await Qp(C),v&&y&&b&&(l&&m(`
|
|
16
|
+
`),l&&!await e.confirm(`Close channel?`,!0)?s>=1&&m(`${X.dim(`Kept channel open.`)}\n`):await am({channelId:v,cumulativeAmount:S,escrowContract:y,chainId:b,fetchUrl:a,fetchInit:o,session:t,info:m,verbose:s,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,confirmEnabled:l}))),!0},formatReceiptField(e,t){(e===`reference`||e===`txHash`)&&typeof t==`string`&&t.startsWith(`0x`)}})}function nm(e,t){t.info(`${t.prefix??``}${X.bold(X.green(`Payment Receipt`))}\n`);let n=[],r=e.channelId&&e.reference&&e.channelId===e.reference,i=new Set([`acceptedCumulative`,`spent`]);for(let[a,o]of Object.entries(e)){if(o===void 0||t.shownKeys.has(a)||a===`reference`&&r)continue;let e=t.handler.formatReceiptField?.(a,o);e===void 0?i.has(a)&&typeof o==`string`?n.push([a,`${o} ${X.dim(`(${qr(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,Gr(`${t.explorerUrl}/tx/${o}`,o)]):n.push([a,String(o)]):n.push([a,e])}n.sort(([e],[t])=>e.localeCompare(t));let a=Math.max(...n.map(([e])=>e.length));for(let[e,r]of n)t.info(` ${X.dim(e.padEnd(a))} ${r}\n`);t.prefix&&t.info(`
|
|
17
|
+
`)}function rm(e,t){if(typeof e.acceptedCumulative!=`string`)return;let n=BigInt(e.acceptedCumulative),r=typeof e.spent==`string`?BigInt(e.spent):0n;if(r>n)throw Error(`receipt spent exceeds accepted cumulative voucher amount`);if(n>t)throw Error(`receipt accepted cumulative exceeds locally signed voucher amount`);if(r>t)throw Error(`receipt spent exceeds locally signed voucher amount`)}async function im(e,t){let n=t.cumulativeAmount,r=e.body?.getReader();if(!r)throw Error(`No response body`);let i=new TextDecoder,a=``,o=``,s=t.verbose?await om():void 0,c=(()=>{if(!s||!X.isColorSupported)return;let e=e=>Math.max(0,Math.min(255,Math.round(e))),t=.299*s.r+.587*s.g+.114*s.b<128?1:-1,n=n=>r=>`\x1b[48;2;${e(s.r+n*t)};${e(s.g+n*t)};${e(s.b+n*t)}m${r}\x1b[49m`;return[n(12),n(24)]})(),l=0,u=e=>{if(c){let t=c[l%c.length];process.stdout.write(e.replace(/[^\n]+/g,e=>t(e))),l++}else process.stdout.write(e)},d=async e=>{for(let r of e){if(r.startsWith(`event: `)){o=r.slice(7).trim();continue}if(!r.startsWith(`data: `)){r===``&&(o=``);continue}let e=r.slice(6);if(e.trim()!==`[DONE]`){if(o===`payment-need-voucher`&&t.channelId&&t.escrowContract&&t.chainId){try{let r=JSON.parse(e);if(r.channelId!==t.channelId)throw Error(`payment-need-voucher channelId does not match current session`);let i=BigInt(r.requiredCumulative);if(i>n+t.tickCost)throw Error(`payment-need-voucher exceeds next locally billable amount`);n=n>i?n:i;let a=await t.session.signVoucher({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId});await globalThis.fetch(t.fetchUrl,{method:`POST`,headers:{[U.authorization]:a}})}catch(e){t.info(X.dim(X.yellow(` [voucher failed: ${e instanceof Error?e.message:e}]`)))}o=``;continue}if(o===`payment-receipt`){if(t.verbose>=1)try{nm(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
|
|
18
18
|
|
|
19
19
|
`})}catch{}o=``;continue}if(e.length===0)u(`
|
|
20
20
|
`);else try{let t=JSON.parse(e);u(t.token??t.choices?.[0]?.delta?.content??e)}catch{u(e)}o=``}}};for(;;){let{done:e,value:t}=await r.read();if(e)break;a+=i.decode(t,{stream:!0});let n=a.split(`
|
|
21
|
-
`);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await
|
|
22
|
-
`)){let e=r.trim();if(e===`[[keys]]`){n?.wallet_address&&t.push(n),n={wallet_type:`local`,wallet_address:``,chain_id:0};continue}if(!n)continue;let i=e.match(/^(\w+)\s*=\s*"?([^"]*)"?$/);if(!i)continue;let[,a,o]=i;a===`wallet_type`?n.wallet_type=o:a===`wallet_address`?n.wallet_address=o:a===`chain_id`&&(n.chain_id=Number.parseInt(o,10))}return n?.wallet_address&&t.push(n),t}catch{return[]}}function
|
|
21
|
+
`);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await am({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId,fetchUrl:t.fetchUrl,fetchInit:t.fetchInit,session:t.session,info:t.info,verbose:t.verbose,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,confirmEnabled:!1})}async function am(e){let t=await e.session.signVoucher({channelId:e.channelId,cumulativeAmount:e.cumulativeAmount,escrowContract:e.escrowContract,chainId:e.chainId,action:`close`}),n=await globalThis.fetch(e.fetchUrl,{...e.fetchInit,headers:{...Xo(e.fetchInit.headers),Authorization:t}});if(n.ok){if(hm(e.channelId),e.verbose>=1){let t=n.headers.get(U.paymentReceipt),r;if(t)try{let e=JSON.parse(D.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${X.dim(Gr(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${X.dim(`Channel closed.`)} ${X.dim(`Spent ${qr(e.cumulativeAmount,e.tokenSymbol,e.tokenDecimals)}.`)}${i}\n`)}}else{let t=await n.text().catch(()=>``);e.info(`\n${X.dim(X.yellow(`Channel close failed`))} ${X.dim(`(${n.status})`)}\n`),e.info(`${X.dim(` channelId: ${e.channelId}`)}\n${X.dim(` cumulativeAmount: ${e.cumulativeAmount}`)}\n${X.dim(` escrowContract: ${e.escrowContract}`)}\n${X.dim(` chainId: ${e.chainId}`)}\n${X.dim(` response: ${t||`(empty)`}`)}\n`)}}function om(e=100){return!process.stdin.isTTY||!process.stdout.isTTY?Promise.resolve(void 0):new Promise(t=>{let n=process.stdin.isRaw,r=``,i=()=>{clearTimeout(a),process.stdin.removeListener(`data`,o),process.stdin.isTTY&&process.stdin.setRawMode(n??!1),process.stdin.pause()},a=setTimeout(()=>{i(),t(void 0)},e),o=e=>{r+=e.toString();let n=r.match(/\x1b\]11;rgb:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!n)return;i();let a=e=>Number.parseInt(e.slice(0,2),16);t({r:a(n[1]),g:a(n[2]),b:a(n[3])})};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on(`data`,o),process.stdout.write(`\x1B]11;?\x07`)})}function sm(e){return cm($p,e,em)}function cm(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}function lm(e){let t=e.challenge.request.methodDetails?.chainId;if(!t||!e.clientChainId||t===e.clientChainId)return;let n=t===4217?` Use --network mainnet or --rpc-url https://rpc.tempo.xyz.`:t===42431?` Use --network testnet or --rpc-url https://rpc.moderato.tempo.xyz.`:``;throw new zr({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function um(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function dm(e){let t=um(e.tokenIn)??um(e.payWith);if(!(!e.autoSwap&&!t&&e.slippage===void 0)){if(e.autoSwap===!1&&!t&&e.slippage===void 0)return!1;if(e.slippage!==void 0&&(!Number.isFinite(e.slippage)||e.slippage<0))throw Error(`Invalid CLI options (slippage: expected a non-negative number)`);return{...t?{tokenIn:t}:{},...e.slippage===void 0?{}:{slippage:e.slippage}}}}function fm(){return I.join(process.env.XDG_CONFIG_HOME||I.join(F.homedir(),`.config`),`mppx`,`channels`)}function pm(e){try{let t=P.readFileSync(I.join(fm(),e),`utf-8`).trim();return t?BigInt(t):void 0}catch{return}}function mm(e,t){let n=fm();P.mkdirSync(n,{recursive:!0}),P.writeFileSync(I.join(n,e),t.toString(),`utf-8`)}function hm(e){try{P.unlinkSync(I.join(fm(),e))}catch{}}function gm(){return F.platform()===`darwin`?I.join(F.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):I.join(process.env.XDG_DATA_HOME||I.join(F.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function _m(){try{let e=P.readFileSync(gm(),`utf-8`),t=[],n;for(let r of e.split(`
|
|
22
|
+
`)){let e=r.trim();if(e===`[[keys]]`){n?.wallet_address&&t.push(n),n={wallet_type:`local`,wallet_address:``,chain_id:0};continue}if(!n)continue;let i=e.match(/^(\w+)\s*=\s*"?([^"]*)"?$/);if(!i)continue;let[,a,o]=i;a===`wallet_type`?n.wallet_type=o:a===`wallet_address`?n.wallet_address=o:a===`chain_id`&&(n.chain_id=Number.parseInt(o,10))}return n?.wallet_address&&t.push(n),t}catch{return[]}}function vm(e){let t=_m();if(t.length===0)return;let n=e.slice(6);if(n==="default"||n===``)return t[0];let r=Number.parseInt(n,10);if(!Number.isNaN(r)&&r>=0&&r<t.length)return t[r]}let ym;function bm(){if(ym!==void 0)return ym;try{N.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),ym=!0}catch{ym=!1}return ym}async function xm(e){return new Promise((t,n)=>{N.execFile(`tempo`,[`mpp`,`sign`,`--challenge`,e],(e,r,i)=>{if(e){let t=i?.trim()||e.message;n(Error(`tempo mpp sign failed: ${t}`));return}let a=r.trim();if(!a){n(Error(`tempo mpp sign returned empty output`));return}t(a)})})}function Sm(){let e=oi();if(Kr(e.get())&&!bm()&&F.platform()===`darwin`)try{let t=N.execFileSync(`security`,[`dump-keychain`],{encoding:`utf-8`}),n=[];for(let e of t.split(`keychain:`)){let t=e.match(/"svce"<blob>="([^"]*)"/),r=e.match(/"acct"<blob>="([^"]*)"/);t?.[1]===`mppx`&&r?.[1]&&n.push(r[1])}if(n.length>0)return e.set(n[0]),n[0]}catch{}}const Cm=[...Object.entries(Me),...Object.entries(Ne),...Object.entries(Pe),...Object.entries(Fe)];function wm(){return di({method:`evm`,supports:Tm,async setup({challenge:e,options:t}){let n=e.request,r=n.network?Em(We(n.network)):void 0,i=n.network&&n.asset?Cm.find(([,e])=>He(e,n.asset,n.network)):void 0,a=n.extra?.name,o=n.extra?.version,s=n.asset&&n.network&&typeof a==`string`&&typeof o==`string`?Ae({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await ui(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...Lr({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function Tm(e){if(!On(e))return!1;let t=e.request,n=t.extra,r=n?.assetTransferMethod;return t.scheme===`exact`&&typeof t.asset==`string`&&typeof t.network==`string`&&typeof n?.name==`string`&&typeof n?.version==`string`&&(r===void 0||r===`eip3009`)}function Em(e){return Object.values(ne).find(t=>t.id===e)}export{di as createPlugin,fi as evm,xi as stripe,tm as tempo,wm as x402};
|