mppx 0.21.4 → 0.22.1
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 +29 -0
- package/dist/BodyDigest.d.ts +3 -3
- package/dist/BodyDigest.js +5 -3
- package/dist/Challenge.js +12 -2
- package/dist/Credential.js +9 -1
- package/dist/Errors.d.ts +62 -8
- package/dist/Errors.js +57 -6
- package/dist/Store.d.ts +7 -4
- package/dist/Store.js +18 -8
- package/dist/cli/account.d.ts +2 -1
- package/dist/cli/account.js +22 -11
- package/dist/cli/cli.js +135 -135
- package/dist/cli/internal.js +1 -1
- package/dist/cli/plugins/index.js +12 -12
- package/dist/client/Budget.d.ts +49 -0
- package/dist/client/Budget.js +101 -0
- package/dist/client/Mppx.d.ts +8 -3
- package/dist/client/Mppx.js +55 -13
- package/dist/client/Spend.d.ts +134 -0
- package/dist/client/Spend.js +58 -0
- package/dist/client/core.d.ts +2 -0
- package/dist/client/core.js +2 -0
- package/dist/client/internal/Fetch.d.ts +23 -3
- package/dist/client/internal/Fetch.js +155 -37
- package/dist/client/internal/FundsMoved.d.ts +9 -0
- package/dist/client/internal/FundsMoved.js +18 -0
- package/dist/client/internal/SpendGate.d.ts +136 -0
- package/dist/client/internal/SpendGate.js +608 -0
- package/dist/client/internal/SpendHooks.d.ts +42 -0
- package/dist/client/internal/SpendHooks.js +36 -0
- package/dist/client/internal/protocols/Mcp.d.ts +9 -0
- package/dist/client/internal/protocols/Mcp.js +27 -0
- package/dist/client/internal/protocols/Mpp.js +20 -3
- package/dist/client/internal/protocols/Shared.js +29 -3
- package/dist/evm/client/Charge.js +20 -8
- 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.d.ts +7 -1
- package/dist/extensions/identity/erc8004/server/index.js +16 -2
- package/dist/extensions/identity/link/client/index.js +57 -5
- 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/Client.d.ts +7 -3
- package/dist/identity/Client.js +178 -13
- 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 +18 -3
- package/dist/integrations/x402/Negotiator.js +4 -1
- package/dist/integrations/x402/Solana.d.ts +75 -0
- package/dist/integrations/x402/Solana.js +143 -0
- package/dist/internal/challengeMeta.d.ts +17 -2
- package/dist/internal/challengeMeta.js +35 -7
- package/dist/internal/version.d.ts +2 -2
- package/dist/internal/version.js +1 -1
- package/dist/mcp/client/McpClient.d.ts +6 -1
- package/dist/mcp/client/McpClient.js +48 -10
- 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 +14 -1
- package/dist/server/Mppx.js +59 -6
- package/dist/server/Transport.js +46 -2
- package/dist/stripe/server/internal/html.gen.js +1 -1
- package/dist/tempo/client/Charge.js +81 -17
- package/dist/tempo/server/Charge.d.ts +7 -1
- package/dist/tempo/server/Charge.js +98 -12
- package/dist/tempo/server/internal/html.gen.js +1 -1
- package/dist/tempo/session/client/SessionManager.js +3 -0
- package/dist/x402/server/EvmCharge.js +3 -0
- 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 T,signTypedData as E,waitForTransactionReceipt as ee}from"viem/actions";import*as D from"viem/chains";import{tempo as te}from"viem/chains";import{AbiParameters as O,Base64 as k,Bytes as A,Hash as j,Hex as M,Json as N}from"ox";import*as P from"zod/mini";import*as F from"node:child_process";import*as I from"node:fs";import*as L from"node:os";import*as R from"node:path";import{z}from"zod";import"node:readline";import{tempo as B,tempoModerato as ne}from"viem/tempo/chains";import{ousd as re,pathusd as ie,usdce as ae}from"viem/tokens";import{Abis as oe,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,U={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},Qe={payment:`Payment`},$e={evm:`evm`,stripe:`stripe`,tempo:`tempo`},et={charge:`charge`,session:`session`,subscription:`subscription`},tt={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},nt={v1:`v1`,v2:`v2`};function rt(e,t){if(!(!e||typeof e!=`object`))return e[t]}function it(e,t){return t?`${e} Add funds at ${t}`:e}var at=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}}}},ot=class extends at{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 at{name=`VerificationFailedError`;title=`Verification Failed`;type=`https://paymentauth.org/problems/verification-failed`;constructor(e={}){let{details:t,fundingUrl:n,reason:r}=e;super(it(r?`Payment verification failed: ${r}.`:`Payment verification failed.`,n),{details:t,fundingUrl:n})}},st=class extends at{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.`)}},ct=class extends at{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}},lt=class extends Error{name=`LegacyUnicodeEscapedChallengeError`;constructor(){super(`Legacy unicode-escaped challenge: the server escaped a bound parameter as \\uXXXX; upgrade the server.`)}},ut=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}},dt=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})}},ft=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})}},pt=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})}},mt=class extends at{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(it(r?`Insufficient balance: ${r}.`:`Insufficient balance.`,n),{cause:t,fundingUrl:n})}};function ht(e){let t=k.toString(e);return JSON.parse(t)}function gt(e){let t=N.canonicalize(e);return k.fromString(t,{pad:!1,url:!0})}var G=Ce({address:()=>q,amount:()=>K,datetime:()=>vt,datetimeInput:()=>yt,hash:()=>J,period:()=>St,signature:()=>Y,toDate:()=>bt,toDatetimeString:()=>xt,unwrapOptional:()=>Ct});import*as _t from"zod/mini";Te(G,_t);function K(){return P.string().check(P.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function vt(){return P.string().check(P.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 yt(e=`Invalid ISO 8601 datetime`){return P.pipe(P.union([vt(),P.custom(e=>e instanceof Date)]),P.transform(bt)).check(P.refine(e=>Number.isFinite(e.getTime()),e))}function bt(e){return e instanceof Date?e:new Date(e)}function xt(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function q(){return P.string().check(P.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function J(){return P.string().check(P.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function St(){return P.string().check(P.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function Y(){return P.string().check(P.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function Ct(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}const wt=Symbol(`mppx.Challenge.legacyUnicodeEscape`),Tt=new Set([`digest`,`expires`,`header`,`intent`,`method`,`opaque`,`realm`,`request`]),Et=`Unsupported credential header: challenges may only select Payment-Authorization.`;var Dt=class extends Error{name=`UnsupportedCredentialHeaderError`;constructor(){super(Et)}};const Ot=G.object({description:G.optional(G.string()),digest:G.optional(G.string().check(G.regex(/^sha-256=/,`Invalid digest format`))),expires:G.optional(vt()),header:G.optional(G.string().check(G.refine($t,Et))),id:G.string().check(G.minLength(1)),intent:G.string(),method:G.string(),meta:G.optional(G.record(G.string(),G.string())),opaque:G.optional(G.string()),realm:G.string(),request:G.record(G.string(),G.unknown())}),kt=G.extend(Ot,{header:G.optional(G.string())});function At(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=en(o),f=e.expires?xt(e.expires):void 0,p=e.opaque??(i===void 0?void 0:gt(i)),m=u?nn({...e,expires:f,header:d,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return Ot.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 jt=/^[a-z]+$/;var Mt=class extends Error{name=`InvalidMethodError`;constructor(e){super(`Invalid method: "${e}". Must be lowercase letters a-z per spec.`)}};function Nt(e){if(!jt.test(e))throw new Mt(e)}function Pt(e,t){let n=Lt(e);if(!n)throw Error(`Missing Payment scheme.`);let r=new Set,{request:i,opaque:a,header:o,...s}=Rt(n,r);if(!i)throw Error(`Missing request parameter.`);if(i.length>16384)throw Error(`Request parameter too large.`);if(s.method!==void 0&&Nt(s.method),o!==void 0&&!$t(o))throw new Dt;let c=At({...s,request:ht(i),...a&&{opaque:a}},t),l=o===void 0?c:{...c,header:o};return[...r].some(e=>Tt.has(e))&&(l[wt]=!0),l}function Ft(e){return!!(e&&typeof e==`object`&&e[wt])}function It(e){if(Ft(e))throw new lt}function Lt(e){let t=Qe.payment,[n]=Ut(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 Rt(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]=zt(e,r);if(r=s,c&&t?.add(a),a in n)throw Error(`Duplicate parameter: ${a}`);n[a]=o}return n}function zt(e,t){if(e[t]===`"`)return Bt(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function Bt(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 Vt(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 Ht(e){return Ut(e,Qe.payment).length>0||e.split(`,`).some(e=>e.trim().toLowerCase()===Qe.payment.toLowerCase())}function Ut(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(!Vt(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 Wt(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return Gt(e.headers,t)}function Gt(e,t){let n=e.get(U.wwwAuthenticate);if(!n)throw Error(`Missing ${U.wwwAuthenticate} header.`);return Kt(n,t)}function Kt(e,t){let n=Yt(e);if(n.length===0)throw Error(`No Payment schemes found.`);return n.flatMap(e=>{try{return[Pt(e,t)]}catch(e){if(e instanceof Dt||e instanceof Mt)return[];throw e}})}function qt(e){return e?Yt(e).filter(e=>{try{return Pt(e),!1}catch(e){return e instanceof Dt}}).length:0}function Jt(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 Yt(e){let t=Ut(e,Qe.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 Xt(e){let t=[e.realm,e.method,e.intent,gt(e.request),e.expires??``,e.digest??``],n=tn(e.header);return n!==void 0&&t.push(n),t.push(e.opaque??(e.meta?gt(e.meta):``)),t.join(`|`)}function Zt(e){let{header:t}=e;return t===void 0?U.authorization:$t(t)?U.paymentAuthorization:t}function Qt(e){if(typeof e!=`object`||!e||!(`header`in e))return!1;let{header:t}=e;return t!==void 0&&!(typeof t==`string`&&$t(t))}function $t(e){return/^payment-authorization$/i.test(e)}function en(e){return tn(e)===void 0?void 0:U.paymentAuthorization}function tn(e){if(e!==void 0&&!/^authorization$/i.test(e)){if($t(e))return e;throw new Dt}}function nn(e,t){let n=Xt(e),r=A.fromString(t.secretKey),i=A.fromString(n),a=j.hmac256(r,i,{as:`Bytes`});return k.fromBytes(a,{url:!0,pad:!1})}const rn=65536;var an=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},on=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}};function sn(e){if(e.length>rn)throw new on;let t=e.match(RegExp(`^${Qe.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new an;try{let e=k.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=cn(r);return{challenge:Ot.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:ht(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new on}}function cn(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!ln(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:gt(e)}}function ln(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function un(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function dn(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:gt(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:gt(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=k.fromString(s,{pad:!1,url:!0});return`${Qe.payment} ${c}`}function fn(e){return e.length>rn?null:e.split(`,`).map(e=>e.trim()).find(e=>RegExp(`^${Qe.payment}\\s+`,`i`).test(e))??null}const pn=Symbol.for(`mppx.x402.challenge`);function mn(e){return Object.defineProperty(e,pn,{value:!0}),e}function hn(e){return!!e?.[pn]}function gn(e,t){if(!e)throw new ot({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new ot({...t&&{id:t},reason:`malformed expires timestamp`});if(Date.parse(e)<=Date.now())throw new st({expires:e})}function _n(e){let{_mppx_nonce:t,_mppx_identity:n,_mppx_expiry_grace:r,...i}=e??{};return Object.keys(i).length?i:void 0}function vn(e){return e}function yn(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,async createCredential(e){return It(e.challenge),i.call(this,e)}}}function bn(e){return{encode(t){return k.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(k.toString(t)))}catch{throw new xn}}}}var xn=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}};const Sn=[`exact`],Cn=`PAYMENT-REQUIRED`,wn=`PAYMENT-SIGNATURE`,Tn=G.string().check(G.minLength(1)),En=G.number().check(G.refine(e=>e>0,`Must be positive`)),Dn=G.string().check(G.regex(/^\d+$/,`Invalid atomic amount`)),On=q(),kn=G.string().check(G.regex(RegExp(`^eip155:\\d+$`),`Invalid EVM CAIP-2 network`)),An=G.object({description:G.optional(G.string()),iconUrl:G.optional(G.string()),mimeType:G.optional(G.string()),serviceName:G.optional(G.string()),tags:G.optional(G.array(G.string())),url:Tn});G.discriminatedUnion(`type`,[G.object({name:Tn,type:G.literal(`eip3009`),version:Tn}),G.object({name:G.optional(G.string()),type:G.literal(`permit2`),version:G.optional(G.string())})]);const jn=G.object({amount:Dn,asset:Tn,extra:G.optional(G.record(G.string(),G.unknown())),maxTimeoutSeconds:En,network:kn,payTo:Tn,scheme:G.enum(Sn)}),Mn=G.looseObject({info:G.record(G.string(),G.unknown()),schema:G.record(G.string(),G.unknown())}),Nn=G.record(G.string(),Mn),Pn=G.object({accepts:G.array(jn).check(G.minLength(1)),error:G.optional(G.string()),extensions:G.optional(Nn),resource:An,x402Version:G.literal(2)}),Fn=G.object({authorization:G.object({from:On,nonce:J(),to:On,validAfter:Dn,validBefore:Dn,value:Dn}),signature:Y()}),In=G.object({permit2Authorization:G.object({deadline:Dn,from:On,nonce:Dn,permitted:G.object({amount:Dn,token:On}),spender:On,witness:G.object({to:On,validAfter:Dn})}),signature:Y()}),Ln=G.union([Fn,In]),Rn=G.object({accepted:jn,extensions:G.optional(Nn),payload:Ln,resource:G.optional(An),x402Version:G.literal(2)});G.object({extensions:G.optional(G.record(G.string(),G.unknown())),extra:G.optional(G.record(G.string(),G.unknown())),invalidMessage:G.optional(G.string()),invalidReason:G.optional(G.string()),isValid:G.boolean(),payer:G.optional(G.string())});const zn=G.object({amount:G.optional(Dn),errorMessage:G.optional(G.string()),errorReason:G.optional(G.string()),extensions:G.optional(G.record(G.string(),G.unknown())),extra:G.optional(G.record(G.string(),G.unknown())),network:Tn,payer:G.optional(G.string()),success:G.boolean(),transaction:G.string()}),Bn=G.object({extra:G.optional(G.record(G.string(),G.unknown())),network:Tn,scheme:Tn,x402Version:G.number()});G.object({extensions:G.optional(G.array(G.string())),kinds:G.array(Bn),signers:G.optional(G.record(G.string(),G.array(G.string())))});function Vn(e){let{extensions:t,resource:n,...r}=e;return jn.parse(r)}const Hn=bn(Pn),Un=bn(Rn),Wn=bn(zn);Hn.encode,Hn.decode;function Gn(e){try{let t=JSON.parse(k.toString(e));return qn(t)}catch{throw new xn}}const Kn=Un.encode;Un.decode,Wn.encode,Wn.decode;const qn=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new xn;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new xn;let n=An.parse(t.resource),r=t.extensions===void 0?void 0:Nn.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}};function Jn(e){let t=[gt(e.accepted),gt(e.resource),gt(e.extensions)].join(`|`);return j.sha256(A.fromString(t),{as:`Hex`})}async function Yn(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=Vn(n);if($n(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?tr(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?Jn({accepted:r,extensions:i,resource:n.resource}):rr(),to:c(r.payTo),validAfter:(l-600).toString(),validBefore:(l+r.maxTimeoutSeconds).toString(),value:r.amount},d=await t.signTypedData({domain:{chainId:Qn(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:Zn});return Kn({accepted:r,...i?{extensions:i}:{},payload:{authorization:u,signature:d},...n.resource?{resource:n.resource}:{},x402Version:2})}function Xn(e){let t=e.challenge.request,n;try{n=Vn(t),$n(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 Zn={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 Qn(e){return Number(e.slice(7))}function $n(e,t){let n=Qn(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=er(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 er(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 tr(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:nr()}}}:e}function nr(){return ir().slice(2)}function rr(){return ir()}function ir(){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 ar=[`authorization`],or=G.string().check(G.regex(/^\d+$/,`Invalid atomic amount`));G.object({name:G.string().check(G.minLength(1)),version:G.string().check(G.minLength(1))});const sr=G.object({chainId:G.number(),credentialTypes:G.optional(G.array(G.enum(ar)).check(G.minLength(1))),decimals:G.optional(G.number()),permit2Address:G.optional(q()),splits:G.optional(G.array(G.object({amount:or,recipient:q()})))});G.object({amount:or,currency:q(),description:G.optional(G.string()),externalId:G.optional(G.string()),methodDetails:sr,recipient:q()});const cr=G.object({amount:K(),chainId:G.number(),currency:q(),credentialTypes:G.optional(G.array(G.enum(ar)).check(G.minLength(1))),decimals:G.number(),description:G.optional(G.string()),externalId:G.optional(G.string()),permit2Address:G.optional(q()),recipient:q(),splits:G.optional(G.array(G.object({amount:or,recipient:q()})))}),lr=G.object({from:q(),nonce:J(),signature:Y(),to:q(),type:G.literal(`authorization`),validAfter:or,validBefore:or,value:or}),ur={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 dr(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function fr(e){return j.keccak256(A.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function pr(e){return`eip155:${e}`}function mr(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const hr=vn({name:`evm`,intent:`charge`,schema:{credential:{payload:lr},request:G.pipe(cr,G.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 gr(e){return yn(hr,{canHandleChallenge({challenge:t}){return!_r(t)||Xn({challenge:t,config:e})},context:G.object({account:G.optional(G.custom())}),async createCredential({challenge:t,context:n}){if(_r(t))return Yn({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;if(vr(e,i),!i.methodDetails.credentialTypes?.includes(`authorization`))throw Error(`EVM authorization is not accepted by this challenge.`);if(i.methodDetails.splits?.length)throw Error(`EVM authorization does not support payment splits.`);let a=yr(e,i),o=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return dn(un({challenge:t,payload:{from:c(r.address),nonce:fr(t),signature:await r.signTypedData({domain:dr({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:c(r.address),nonce:fr(t),to:c(i.recipient),validAfter:0n,validBefore:BigInt(o),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:ur}),to:c(i.recipient),type:`authorization`,validAfter:`0`,validBefore:o,value:i.amount},source:mr({address:c(r.address),chainId:i.methodDetails.chainId})}))}})}function _r(e){return hn(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function vr(e,t){let n=t.methodDetails.chainId,r=pr(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=br(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 yr(e,t){let n=e.currencies??e.assets,r=c(t.currency),i=pr(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 br(e,t){let n=e.currencies??e.assets,r=c(t.currency),i=pr(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 xr(e){return[xr.charge(e)]}(function(e){e.charge=gr,e.assets=Ke,e.chains=qe})(xr||={});var Sr=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 wr(this,e)}},Cr=class extends Sr{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 wr(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},Tr={ousd:re(Z.mainnet).address,usdc:c(ae(Z.mainnet).address),pathUsd:ie(Z.mainnet).address},Er={[Z.mainnet]:Tr.usdc,[Z.testnet]:Tr.pathUsd},Dr=Object.freeze({[Z.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[Z.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})});Z.mainnet,Z.testnet;const Or={[Z.mainnet]:`https://rpc.tempo.xyz`,[Z.testnet]:`https://rpc.moderato.tempo.xyz`};function kr(e,t){return X.link(e,t)}function Ar(e){return e.startsWith(`tempo:`)}function jr(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 Mr={mainnet:Or[Z.mainnet],testnet:Or[Z.testnet]};function Nr(e,t={}){return e??(t.network?Mr[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}async function Pr(t={}){let n=Nr(t.rpcUrl,{network:t.network});if(!n)return B;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 Fr(e){return typeof e==`bigint`?e:e.amount}function Ir(e){return e.id!==B.id}async function Lr(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(Fr).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 Rr(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:1e4}function zr(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function Br(e){return new Cr({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 Vr(e){if(e&&zr(e,`secret-tool`))throw Br(e)}function Hr(e,t){return new Promise(n=>{F.execFile(e,t,{timeout:Rr()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function Ur(){let e=R.join(process.env.XDG_CONFIG_HOME||R.join(L.homedir(),`.config`),`mppx`,`default`);return{get(){try{return I.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(t){I.mkdirSync(R.dirname(e),{recursive:!0}),I.writeFileSync(e,t,`utf-8`)},clear(){try{I.unlinkSync(e)}catch{}}}}function Wr(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:Ur().get())}function Gr(e=`main`){let t=`mppx`;return{async list(){let e=L.platform();if(e===`darwin`){let{stdout:e,error:n}=await Hr(`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 Hr(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(Vr(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=L.platform();if(n===`darwin`){let{stdout:n,error:r}=await Hr(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await Hr(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return Vr(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=L.platform();if(r===`darwin`){await Hr(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await Hr(`security`,[`add-generic-password`,`-s`,t,`-a`,e,`-w`,n]);if(r)throw r;return}if(r===`linux`){let r=F.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),Rr());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(zr(e,`secret-tool`)?Br(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=L.platform();if(n===`darwin`){await Hr(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await Hr(`secret-tool`,[`clear`,`service`,t,`account`,e]);Vr(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function Kr(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=Wr(e),i=await Gr(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function qr(e){return(await Kr(e)).account}function Jr(e){return e}function Yr(){return Jr({method:`evm`,supports:e=>e.method===`evm`&&!hn(e),async setup({challenge:t,options:n}){let r=t.request,i=r.methodDetails,o=i?.chainId,s=o?Xr(o):void 0,c=r.currency,l=await qr(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:[...xr({account:l,currencies:d})]}}})}function Xr(e){return Object.values(D).find(t=>t.id===e)}function Zr(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 Qr=G.object({customer:G.optional(G.string().check(G.minLength(1))),hooks:G.optional(G.object({inputs:G.object({tax:G.object({calculation:G.string().check(G.minLength(1))})})})),metadata:G.optional(G.record(G.string(),G.string())),receipt_email:G.optional(G.string().check(G.minLength(1)))}),$r=G.custom(e=>typeof e==`function`),ei=G.union([Qr,$r]),ti=vn({name:`stripe`,intent:`charge`,schema:{credential:{payload:G.object({externalId:G.optional(G.string()),spt:G.string()})},request:G.pipe(G.object({amount:K(),currency:G.string(),decimals:G.number(),description:G.optional(G.string()),externalId:G.optional(G.string()),metadata:G.optional(G.record(G.string(),G.string())),networkId:G.string(),paymentIntentOptions:G.optional(ei),paymentMethodTypes:G.array(G.string()).check(G.minLength(1)),recipient:G.optional(G.string())}),G.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:Zr(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});function ni(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return yn(ti,{context:G.object({paymentMethod:G.optional(G.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 dn({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function ri(e){return[ni(e)]}(function(e){e.charge=ni})(ri||={});function ii(){return Jr({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=oi(z.object({paymentMethod:z.string(),secretKey:z.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new Cr({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:[ri.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=ai(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 Cr({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${(await d.json()).error.message}`,exitCode:77})}else throw new Cr({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&&ai(e)?`/test`:``}/payments/${t}`;return X.link(n,t,!0)}}})}function ai(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function oi(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 si=Symbol.for(`mppx.fetch.skipPayment`);Object.freeze({phase:`unproved`});function ci(e,t,n={}){return async(r,i)=>{let a=new Request(r,i),o=li(a.headers)??n.challenge,{response:s}=await t.send((t,n)=>e(t,{...n,...i?.[si]?{[si]:!0}:{}}),a,{...n,challenge:o});if(s.status===402&&o)for(let e of ui(s))e.method===o.method&&e.intent===o.intent&&await t.challenge(s,{challenge:e},a.url);return s}}function li(e){for(let[,t]of e){let e=fn(t);if(e)try{return sn(e).challenge}catch{}}}function ui(e){try{return Wt(e)}catch{return[]}}const di=Symbol(`mppx.deferredContext`);function fi(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=_i(n)}return t}function pi(e,t){let n=fi(e),r=wi(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[_i(e)]??1,index:t}));return{definition:r,entries:i,header:hi(i),keys:n}}function mi(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)=>Si(e,t))}function hi(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${Oi(n)}`}).join(`, `)}function gi(e,t,n,r){let i=new Map;for(let e of t){let t=_i(e),n=i.get(t);n?n.push(e):i.set(t,[e])}let a=e.flatMap((e,t)=>{let a=i.get(_i(e));if(!a)return[];let o=vi(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)=>xi(e.challenge)-xi(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})=>!Ft(e));return o.length===0&&a[0]&&It(a[0].challenge),o}function _i(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function vi(e,t){let n;for(let r of t){if(!yi(e,r))continue;let t={...r,specificity:bi(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 yi(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function bi(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function xi(e){return+!!hn(e)}function Si(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 Ci(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=Ei(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function Ci(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function wi(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>_i(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]=Ti(t,`payment preference "${e}"`)}return a}function Ti(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return Di(e,t)}function Ei(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 Di(Number(e),t)}function Di(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 Oi(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}`)}function Ai(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 ji=[U.authorization,Cn,`PAYMENT-RESPONSE`,wn];function Mi(e,t,n){let r=new Headers(e.headers);for(let e of ji)e===U.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}function Ni(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 Pi(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}}const Fi=1048576,Ii=new WeakMap;function Li(e){let t=Ni(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 Ri(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 zi(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(!kt.safeParse(e).success)return;if(Qt(e))continue;let t=Ot.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 Bi(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:zi(e.error.data):zi(e.result?._meta?.[`org.paymentauth/payment-required`])}function Vi(e,t){return!e||e.id!==t?[]:Bi(e)?.challenges??[]}async function Hi(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=Ai(e=>{if(!(i||!e.data)&&(i=!0,e.event===`message`))try{a=Ri(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>Fi)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function Ui(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 Ri(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>Fi)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function Wi(e){let t=Ii.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>Fi)){if(t.includes(`application/json`))return Ui(e);if(t.includes(`text/event-stream`))return Hi(e)}})();return Ii.set(e,n),n}function Gi(){return{getChallenges(e,t){let n=Li(t);return e.status===402||n===void 0?[]:Wi(e).then(e=>Vi(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=sn(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,"org.paymentauth/credential":r}}})}}}}function Ki(){return{getChallenges(e){let t=e.headers.get(U.wwwAuthenticate);return e.status!==402||!t||!Ht(t)?[]:Wt(e)},setCredential(e,t,n){return Mi(e,n?.challenge?Zt(n.challenge):U.authorization,t)}}}function qi(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(Cn);if(!t)return[];let n=Gn(t);return n.accepts.flatMap((e,t)=>{let r=jn.safeParse(e);if(!r.success)return[];let i=r.data;return mn(At({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 Mi(e,wn,t)}}}function Ji(e){return e}function Yi(){let e=[Ki(),qi(),Gi()],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 Ji({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 Xi=new WeakMap;function Zi(e,t){return Xi.set(e,t),e}function Qi(e){return Xi.has(e)}function $i(e,t){return Promise.resolve(Xi.get(e)?.(t))}function ea(e){return Xi.get(e)}const ta=new WeakMap,na=new WeakMap,ra=new WeakMap,ia=new WeakMap;function aa(e,t){return ta.set(e,t),e}function oa(e){ta.delete(e)}function sa(e,t,n){ta.has(e)&&na.set(t,n)}function ca(e){return na.get(e)}function la(e,t){return Promise.resolve(ta.get(e)?.(t)??t.response)}function ua(e,t){return ia.set(e,t),e}function da(e,t){try{return ia.get(e)?.(t)}catch{return}}function fa(e,t){ra.set(e,t)}function pa(e){return ra.get(e)??na.get(e)?.origin}async function ma(e,t){let{attempts:n,signal:r}=t;for(let t=1;;t++){r?.throwIfAborted();try{return await e()}catch(e){if(!(e instanceof pt)||t>=n)throw e;r?.throwIfAborted()}}}function ha(e,t,n){if(!ga(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&&_a(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 ga(e){if(e.method!==`tempo`||e.intent!==`charge`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function _a(e){try{return new URL(e).origin.toLowerCase()}catch{return e.toLowerCase()}}const va=Symbol.for(`mppx.fetch.wrapper`),ya=Symbol.for(`mppx.fetch.identity`),ba=Symbol.for(`mppx.fetch.skipPayment`);function xa(e={}){return{...e,[ba]:!0}}const Sa=65536,Ca=new WeakMap;async function wa(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>Sa){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,Sa),{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 Ta(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 Ea(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=3,methods:a,onChallenge:o,orderChallenges:s,transport:c=Yi(),trustedTempoProofRealms:l}=e,u=e.identity??(e.fetch&&Ya(e.fetch)),d=e.eventDispatcher??Oa(),f=t??pi(a),p=Xa(r),m=async(e,t,n)=>u?u.send((e,n)=>p(e,t?.[ba]?xa(n):n),new Request(e,t),n):{response:await p(e,t),headers:[]},h=async(e,t,r)=>{let g=Ja(e,t?.headers),_=g.has(U.acceptPayment),v=no(g,f),y=Ka(e,t,g),b=Ga(e,t,g,v.header,_,n),x=await m(Za(b.input),b.init),S=x.response,C=x.headers,w=qa(b.init,await y);if(t?.[ba]||Pi(w)||!await c.isPaymentRequired(S,w))return S;let T=t?.context,{context:E,orderChallenges:ee,...D}=w??{},te,O,k,A,j;try{for(let n=0;n<i;n++){O=await c.getChallenges(S,w);let f=(await ro(gi(O,a,v.entries,T),ee??s))[0];if(!f){if(await Ta(A,{challenges:O,response:S,status:`rejected`}),n>0)return S;throw Error(Jt(`No method found for challenges: ${O.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`,fo(S)))}let g=f.challenge;te=g,k=f.method,te.expires&&gn(te.expires,te.id),await u?.challenge(S,{challenge:g},so(b.input).href);let _=await uo(S,b.input,b.input,D);ha(g,()=>so(_),l);let y=A,x=po(g),E=y?.method===f.method&&y?.key===x,M=!1;if(y){let e=await Ta(y,{challenges:O,response:S,status:E?`pending`:`rejected`});M=E&&!e}A=M?y:void 0;let N=Na(async n=>{if(n===void 0&&M&&y)return y.promise;M&&y&&(await Ta(y,{status:`rejected`}),A=void 0),Qa(e,t)?.throwIfAborted();let r=n??T;if(!Qi(f.method))return ma(()=>to(g,f.method,r,co(_)),{attempts:i,signal:Qa(e,t)});let a={origin:so(_).origin,prepare:()=>$i(f.method,{challenge:g,context:r,fetch:u?ci(p,u,{challenge:g}):p,input:_,signal:Qa(e,t)})},o=a.prepare().then(()=>to(g,f.method,r,a));return A={context:r,attempt:a,key:n===void 0?x:void 0,method:f.method,promise:o},o}),P=await d.emit(`challenge.received`,Pa({challenge:g,challenges:O,createCredential:N,init:t,input:e,method:f.method,response:S}))??(o?await o(te,{createCredential:N}):void 0)??await N(),F=A;F&&await F.promise.catch(()=>void 0)!==P&&(await Ta(F,{status:`rejected`}),A=void 0);let I=A?A.context:T;eo(P);let L=$a(P,g);await d.emit(`credential.created`,Fa({challenge:g,credential:P,init:t,input:e,method:f.method,response:S}));let R=e=>new ct({cause:e,challenge:g,credential:P,transactionHash:da(f.method,P)});try{({response:S}=await m(_,{...c.setCredential({...D,headers:b.headers},P,{challenge:g}),redirect:`manual`},{challenge:L,headers:C}))}catch(e){throw j=R(e),e}let z=await c.isPaymentRequired(S,w);if(z||(await Ta(F,{response:S,status:S.status>=300&&S.status<400?`pending`:S.ok?`accepted`:`rejected`}),A=void 0),S.ok&&ka(d,`payment.response`)&&await d.emit(`payment.response`,Ia({challenge:g,credential:P,init:t,input:e,method:f.method,response:S})),!z){if(S.status>=500&&ka(d,`payment.failed`)){try{S=await wa(S)}catch(e){throw j=R(e),S=new Response(null,{headers:S.headers,status:S.status,statusText:S.statusText}),e}await d.emit(`payment.failed`,La({challenge:g,challenges:O,error:R(),init:t,input:e,method:f.method,response:S}))}return S.ok?la(f.method,{context:I,challenge:g,credential:P,fetch:p,headers:b.headers,input:_,...r?{refetch:()=>h(Za(b.input),t,!1)}:{},response:S,signal:Qa(e,t)}):S}}O=void 0;try{O=await c.getChallenges(S,w)}catch{}return await Ta(A,{challenges:O,response:S,status:`rejected`}),S}catch(n){throw await Ta(A,{challenges:O,response:S,status:`rejected`}),await d.emit(`payment.failed`,La({challenge:te,challenges:O,error:j??n,init:t,input:e,method:k,response:S})),n}},g=(e,t)=>h(e,t,!0);return g[va]=p,u&&(g[ya]=u),g}function Da(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 Oa(){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 Aa(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await Ma(e[`*`],t,n),r}case`credential.created`:await ja(e[`credential.created`],n),await Ma(e[`*`],t,n);return;case`payment.failed`:await ja(e[`payment.failed`],n),await Ma(e[`*`],t,n);return;case`payment.response`:await ja(e[`payment.response`],n),await Ma(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 Ca.set(t,t=>e[t].size>0||e[`*`].size>0),t}function ka(e,t){return Ca.get(e)?.(t)??!0}async function Aa(e,t){try{return await e(t)}catch{return}}async function ja(e,t){for(let n of e)try{await n(t)}catch{}}async function Ma(e,t,n){await ja(e,Object.freeze({name:t,payload:n}))}function Na(e){let t;return n=>(t??=e(n),t)}function Pa(e){return Object.freeze({challenge:Ha(e.challenge),challenges:e.challenges.map(e=>Ha(e)),createCredential:e.createCredential,init:Ra(e.init),input:za(e.input),method:Ba(e.method),response:Va(e.response)})}function Fa(e){return Object.freeze({challenge:Ha(e.challenge),credential:e.credential,init:Ra(e.init),input:za(e.input),method:Ba(e.method),...e.response===void 0?{}:{response:Va(e.response)}})}function Ia(e){return Object.freeze({challenge:Ha(e.challenge),credential:e.credential,init:Ra(e.init),input:za(e.input),method:Ba(e.method),response:Va(e.response)})}function La(e){return Object.freeze({...e.challenge?{challenge:Ha(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>Ha(e))}:{},error:e.error,init:Ra(e.init),input:za(e.input),...e.method?{method:Ba(e.method)}:{},...e.response===void 0?{}:{response:Va(e.response)}})}function Ra(e){if(e)return Wa({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function za(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function Ba(e){return Wa(Object.assign({},e))}function Va(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 Ha(e)}function Ha(e){try{return Ua(structuredClone(e))}catch{return Wa(e)}}function Ua(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Ua(t);return e}function Wa(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function Ga(e,t,n,r,i,a){let o=!!r&&!i&&io(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 Ka(e,t,n){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{return e.clone().text().catch(()=>void 0)}catch{return}}}function qa(e,t){return t===void 0?e:{...e,body:t}}function Ja(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function Ya(e){return e[ya]}function Xa(e){let t=e;for(;t[va];)t=t[va];return t}function Za(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function Qa(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function $a(e,t){try{let{challenge:n}=sn(e);return n.id===t.id?t:{...n,...t.header!==void 0&&{header:t.header}}}catch{return t}}function eo(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 to(e,t,n,r){let i=t.context&&n!==void 0?t.context.parse(n):void 0,a=i===void 0?{challenge:e}:{challenge:e,context:i};return r?.origin&&fa(a,r.origin),r&&`prepare`in r&&sa(t,a,r),t.createCredential(a)}function no(e,t){let n=e.get(U.acceptPayment);if(!n)return t;try{return{...t,entries:mi(n),header:n}}catch{return t}}async function ro(e,t){return t?t(e):e}function io(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=so(e);return t===`same-origin`?!oo()||n.origin===globalThis.location.origin:t.origins.some(e=>ao(n,e))}function ao(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 oo(){return globalThis.location!==void 0}function so(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,oo()?globalThis.location.href:void 0)}function co(e){try{return{origin:so(e).origin}}catch{return}}function lo(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 uo(e,t,n,r){if(lo(t,r),!e.url)return t;let i=new URL(e.url),a=so(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 fo(e){return!(e instanceof Response)||e.status!==402?0:qt(e.headers.get(U.wwwAuthenticate))}function po(e){let{description:t,...n}=e;return N.canonicalize(n)}function mo(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 ho(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}const go={[B.id]:B,[ne.id]:ne};function _o(e,t={}){return u(e.url,{fetchFn:e.fetch,fetchOptions:{headers:ho(e)},...t})}function vo(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}),_o(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),_o(o)):u(r);return e({chain:go[n]??{...i,id:n},transport:a})}}function yo(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 bo(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}const xo=M.slice(j.keccak256(A.fromString(`mpp`),{as:`Hex`}),0,4);function So(e){let t=j.keccak256(A.fromString(e),{as:`Hex`});return M.toBytes(M.slice(t,0,10))}function Co(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(M.toBytes(xo),0),i[4]=1,i.set(So(t),5),n&&i.set(So(n),15),i.set(wo(r),25),M.fromBytes(i)}function wo(e){let t=j.keccak256(A.fromString(e),{as:`Hex`});return M.toBytes(M.slice(t,0,7))}function To(e,t){return _e.resolve(e).toLowerCase()===_e.resolve(t).toLowerCase()}const Eo=10000n,Do=[Tr.pathUsd,Tr.usdc,Tr.ousd];async function Oo(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||To(t,i)||c.some(e=>To(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/Eo;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/Eo,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 Ao({currency:i})}function ko(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`&&To(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var Ao=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}};function jo(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 Mo(e,t,n){t&&(n&&!n.some(e=>To(e,t))||e.some(e=>To(e,t))||e.push(t))}async function No(e,t,n){try{return(await V.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function Po(e){let t=e.chain?.feeToken;if(t)return le.toAddress(t);let n=e.chain?.id;return n?Er[n]:void 0}function Fo(e){let t=[];return Mo(t,Tr.pathUsd),Mo(t,Er[e]),t}async function Io(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])Mo(o,e,n);if(Mo(o,await V.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),Mo(o,Po(i),n),!a)for(let e of r??[])Mo(o,e,n);for(let e of o)if(await No(i,t,e))return e;return o[0]}const Lo=m([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`]);function Ro(e){if(e!==void 0)return Dr[e]}function zo(e){let t=Ro(e.chainId);return!!t&&d(e.currency,{strict:!1})&&f(e.currency,t.token)}function Bo(e){let t=Ro(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:oe.tip20,functionName:`approve`,args:[t.swap,r]}),to:t.token},{data:i({abi:Lo,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 Vo(e,t){let n=Bo(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 Ho=10n**BigInt(4);function Uo(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+Ho-1n)/Ho,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 Wo(e,t){let n=Ro(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 Go(e,t){let{account:n,amount:r,chainId:i}=t,a=await Wo(e,{account:n,chainId:i});if(a===void 0||a>=r)return;let s=e=>`${o(e,6)} MACH`,c=r-a;return{fundingUrl:Uo({address:n,amount:c,chainId:i}),reason:`requested ${s(r)}, available ${s(a)}`,shortfall:c}}async function Ko(e,t){let n=await Go(e,t);if(n)return new mt({fundingUrl:n.fundingUrl,reason:n.reason})}const qo={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]};function Jo(e){return{name:`MPP`,version:`3`,chainId:e}}function Yo(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function Xo(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:Jo(n),types:qo,primaryType:`Proof`,message:Yo({account:t,challengeId:r,realm:i})}}function Zo(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const Qo=[...oe.accountKeychain.filter(e=>e.type===`error`),...oe.tip20.filter(e=>e.type===`error`)];function $o(e){let t=new Set,n=e;for(;typeof n==`object`&&n&&!t.has(n);){t.add(n);let e=n.data;if(ns(e))return e;let r=e?.data;if(ns(r))return r;n=n.cause}}function es(e,t){let n=$o(e);if(!n)return;let i=(()=>{try{return r({abi:Qo,data:n})}catch{return}})();if(i?.errorName===`SpendingLimitExceeded`){let n=t.account.accessKeyAddress;return new ft({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 mt({cause:e,reason:`${t.account.address} holds ${n} of token ${a}, but the payment requires ${r}`})}}async function ts(e,t){try{return await t()}catch(t){throw es(t,e)??t}}function ns(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{8}/.test(e)}const rs=7200n,is=64n,as=s({abi:oe.zonePortal,name:`WithdrawalProcessed`});function os(e){return Number.isInteger(e)&&e>0&&e<4217e5}function ss(e,t){return os(t)?e===!0||(e?.includes(t)??!1):!1}function cs(e){return ce.zonePortal(e)}cs(0).slice(0,-16).toLowerCase();function ls(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 us(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 ds(e){return j.keccak256(O.encodePacked([`address`,`bytes32`,`uint64`],[e.sender,e.transactionHash,e.fallbackNonce]))}async function fs(e,t){let{blockNumber:n,sender:r,transactionHash:i}=t,a=t=>x(e,{abi:oe.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>is)throw Error(`Zone withdrawal transaction ${i} has ${s-o} candidate sender tags, more than ${is}.`);let c=[];for(let e=o+1n;e<=s;e++)c.push(ds({fallbackNonce:e,sender:r,transactionHash:i}));return c}async function ps(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>rs?i-rs:0n,o=Date.now()+r;for(;;){if(a<=i){let[r]=await y(e,{address:t.portal,event:as,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 ms=[`push`,`pull`],hs=G.object({amount:K(),memo:G.optional(J()),recipient:G.pipe(G.string(),G.transform(e=>e))}),gs=(1n<<64n)-1n,_s={dev_second:1n,day:86400n,week:604800n},vs=G.pipe(q(),G.transform(e=>e.toLowerCase())),ys=G.object({accessKeyAddress:vs,keyType:G.enum([`p256`,`secp256k1`,`webAuthn`]),keyToken:G.optional(G.pipe(G.string().check(G.regex(/^0x[0-9a-fA-F]{120}$/)),G.transform(e=>e)))}),bs=G.object({accessKey:G.optional(ys),chainId:G.optional(G.number())}),xs=yt(`subscriptionExpires must be a valid date`).check(G.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),Ss=G.enum([`dev_second`,`day`,`week`]),Cs=G.pipe(G.union([G.string(),G.bigint(),G.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),G.transform(e=>e.toString())).check(G.regex(/^[1-9]\d*$/,`Invalid periodCount`),G.refine(e=>{try{return BigInt(e)<=gs}catch{return!1}},`periodCount exceeds uint64`));function ws(e){return G.refine(e=>{let{amount:t,decimals:n}=e;return g(t,n)>0n},e)}function Ts(e){let{periodCount:t,periodUnit:n}=e;try{let e=_s[n];return e!==void 0&&BigInt(t)*e<=gs}catch{return!1}}const Es=vn({name:`tempo`,intent:`charge`,schema:{credential:{payload:G.discriminatedUnion(`type`,[G.object({hash:J(),type:G.literal(`hash`)}),G.object({signature:Y(),type:G.literal(`transaction`)}),G.object({signature:Y(),type:G.literal(`proof`)}),G.object({hash:J(),senderTag:J(),type:G.literal(`zone`),zoneId:G.number().check(G.refine(os,`Invalid Zone ID`))})])},request:G.pipe(G.object({machineTokenEnabled:G.optional(G.boolean()),amount:K(),chainId:G.optional(G.number()),currency:G.string(),decimals:G.number(),description:G.optional(G.string()),externalId:G.optional(G.string()),feePayer:G.optional(G.pipe(G.union([G.boolean(),G.custom()]),G.transform(e=>typeof e==`object`||e))),memo:G.optional(G.never()),recipient:G.optional(G.string()),splits:G.optional(G.array(hs).check(G.minLength(1),G.maxLength(10))),supportedModes:G.optional(G.array(G.enum(ms)).check(G.minLength(1))),zones:G.optional(G.union([G.literal(!0),G.array(G.number().check(G.refine(os,`Invalid Zone ID`))).check(G.minLength(1))]))}).check(G.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`)),G.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}}}:{}})))}}),Ds=vn({name:`tempo`,intent:`session`,schema:{credential:{payload:G.discriminatedUnion(`action`,[G.object({action:G.literal(`open`),authorizedSigner:G.optional(G.string()),channelId:J(),cumulativeAmount:K(),descriptor:G.optional(G.custom()),signature:Y(),transaction:Y(),type:G.literal(`transaction`)}),G.object({action:G.literal(`topUp`),additionalDeposit:K(),channelId:J(),descriptor:G.optional(G.custom()),transaction:Y(),type:G.literal(`transaction`)}),G.object({action:G.literal(`voucher`),channelId:J(),cumulativeAmount:K(),descriptor:G.optional(G.custom()),signature:Y()}),G.object({action:G.literal(`close`),channelId:J(),closeSignature:Y(),cumulativeAmount:K(),descriptor:G.optional(G.custom()),signature:Y()})])},request:G.pipe(G.object({amount:K(),chainId:G.optional(G.number()),channelId:G.optional(J()),configurableVouchers:G.optional(G.boolean()),currency:G.string(),decimals:G.number(),escrowContract:G.optional(G.string()),feePayer:G.optional(G.pipe(G.union([G.boolean(),G.custom()]),G.transform(e=>typeof e==`object`||e))),feeToken:G.optional(q()),minVoucherDelta:G.optional(K()),operator:G.optional(q()),recipient:G.optional(G.string()),sessionProtocol:G.optional(G.enum([nt.v2,nt.v1])),sessionSnapshot:G.optional(G.custom()),suggestedDeposit:G.optional(K()),unitType:G.string()}).check(G.refine(({amount:e,decimals:t})=>g(e,t)>0n,`Session amount must be greater than 0`)),G.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&&{[tt.sessionProtocol]:u},...d!==void 0&&{[tt.sessionSnapshot]:d}}})))}}),Os=vn({name:`tempo`,intent:`subscription`,schema:{credential:{payload:G.object({signature:Y(),type:G.literal(`keyAuthorization`)})},request:G.pipe(G.object({amount:K(),accessKey:G.optional(ys),chainId:G.optional(G.number()),currency:vs,decimals:G.number(),description:G.optional(G.string()),externalId:G.optional(G.string()),methodDetails:G.optional(bs),periodCount:Cs,periodUnit:Ss,recipient:vs,subscriptionExpires:xs}).check(ws(`Subscription amount must be greater than 0`),G.refine(Ts,`Subscription period exceeds uint64`)),G.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}:{}}}))}}),ks=G.object({account:G.optional(G.custom()),autoSwap:G.optional(G.custom()),feeToken:G.optional(G.custom()),mode:G.optional(G.enum(ms))});function As(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??[])Ks(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=vo({chain:B,getClient:e.getClient,rpcUrl:Or}),i=mo({account:e.account});Rs(e.zone);let a=new Map,o=yn(Es,{canHandleChallenge({challenge:t}){try{return qs(e,n,t.request),!0}catch{return!1}},context:ks,async createCredential(o){let{challenge:s,context:c}=o;qs(e,n,s.request);let l=s.request.methodDetails?.chainId,u=l??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),d=await r({chainId:u});yo(d,u);let f=u??d.chain?.id;if(bo(e.allowedChainIds,f),f===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");l===void 0&&qs(e,n,s.request,f);let{request:p}=s,{amount:m,methodDetails:h}=p,g=h?.supportedModes??[`pull`,`push`],_=e.zone?.client.chain,v=e.zone?e.zone.zoneId??ls(_?.id??0):void 0,y=_?.sourceId??(_?us(_.id):void 0),x=c?.mode??e.mode;if(BigInt(m)>0n&&e.zone&&v!==void 0&&y===f&&g.includes(`push`)&&(x===void 0||x===`push`)&&ss(h?.zones,v)&&!h?.splits){let r={assertFee:t=>qs(e,n,p,f,t),challenge:s,clientId:t,client:d,origin:Ls(pa(o)),pending:a,zone:e.zone,zoneId:v},i=Ps(r);if(i)return Fs(r,i);if(s.expires&&gn(s.expires,s.id),zs(s.expires,e.zone.settlementTimeoutMs))return Ns(r)}let C=i(d,c),ee=async t=>await e.resolveAccount?.({account:C,chainId:f,operation:t})??C;if(BigInt(m)===0n){let e=await ee({kind:`signPaymentProof`});return dn({challenge:s,payload:{signature:await E(d,{account:e,...Xo({account:e.address,chainId:f,challengeId:s.id,realm:s.realm})}),type:`proof`},source:Zo({address:e.address,chainId:f})})}let D=p.currency,te=zo({chainId:f,currency:D}),O=Co({challengeId:s.id,clientId:t,serverId:s.realm}),k=jo({amount:m,methodDetails:{...h,memo:O},recipient:p.recipient}),A=k.map(e=>V.token.transfer.call(d,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:D})),j=ko(c?.autoSwap??e.autoSwap,Do),M=h?.machineTokenEnabled===!0?Bo({chainId:f,currency:D,transfers:k}):void 0,N=C,P,F=!1;if(M){let e=await(async()=>{try{return await ee({calls:M.calls,kind:`executeCalls`})}catch{return}})();e&&(P=await Vo(d,{account:e.address,chainId:f,currency:D,transfers:k}),P?N=e:F=!0)}let I;if(!P&&(N=await ee({kind:`executeCalls`,...j?{}:{calls:A}}),I=j?await Oo(d,{account:N.address,amountOut:BigInt(m),tokenOut:D,tokenIn:j.tokenIn,slippage:j.slippage,maxAmountIn:j.maxAmountIn}):void 0,F&&!j)){let e=await js(d,{account:N.address,amount:BigInt(m),chainId:f,currency:D});if(e)throw e}let L=P?.calls??[...I??[],...A],R=Fo(f),z=(c?.feeToken??e.feeToken)||(P||te?await Io({account:N.address,allowedTokens:R,candidateTokens:R,client:d,prioritizeCandidates:!0}):void 0),B=(()=>{let t=c?.mode??e.mode;if(t){if(!g.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=N.type===`json-rpc`?`push`:`pull`;return g.includes(n)?n:g[0]})(),ne=(()=>{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)})();if(B===`push`){let{receipts:e}=N.type===`local`?{receipts:[await ts({account:N},()=>w(d,{account:N,calls:L,...z?{feeToken:z}:{},nonceKey:`expiring`,validBefore:ne}))]}:await S(d,{account:N,...z?{capabilities:{feeToken:z}}:{},calls:L,experimental_fallback:L.length===1,forceAtomic:L.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return dn({challenge:s,payload:{hash:t,type:`hash`},source:Zo({address:N.address,chainId:f})})}let re=()=>{if(h?.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(!(ne*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.`)};re();let ie=await ts({account:N},()=>b(d,{account:N,calls:L,...z?{feeToken:z}:{},nonceKey:`expiring`,validBefore:ne}));if(ie.gas=(ie.gas??0n)+5000n,h?.feePayer){let e=ie;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return re(),dn({challenge:s,payload:{signature:await T(d,ie),type:`transaction`},source:Zo({address:N.address,chainId:f})})}}),s=new Map,c=async t=>{qs(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,a=s.get(i);return a||(a=o.createCredential(t).finally(()=>s.delete(i)),s.set(i,a)),a};return ua({...o,createCredential:c},Ms)}async function js(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 Ko(e,{account:n,amount:r,chainId:i})}function Ms(e){let t=Es.schema.credential.payload.safeParse(sn(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 Ns(e){let{challenge:t,origin:n,pending:r,zoneId:i}=e,a={sent:!1},o={challenge:t,origin:n,terms:Hs(t,i),waiters:0,withdrawal:Gs(e,a)},s=Vs(t);return r.set(s,o),o.withdrawal.catch(()=>{!a.sent&&r.get(s)===o&&r.delete(s)}),Fs(e,o)}function Ps(e){let{challenge:t,pending:n,zoneId:r}=e,i=n.get(Vs(t));if(i)return i;let a=Hs(t,r);if(a!==void 0){for(let[e,t]of n)if(t.terms===a){if(!Ws(t.challenge.expires)){n.delete(e);continue}if(t.redeemedLate)throw new pt({challengeId:t.challenge.id,senderTags:t.senderTags,zoneId:r});if(!(t.waiters>0))return t}}}async function Fs(e,t){t.waiters++;try{return await Is(e,t)}finally{t.waiters--}}async function Is(e,t){let{client:n,origin:r,pending:i,zone:a,zoneId:o}=e,{challenge:s}=t,c=s.request.recipient,l=Vs(s);if((l===Vs(e.challenge)?r!==void 0&&t.origin!==void 0&&r!==t.origin:!r||r!==t.origin)||!Ws(s.expires))throw new pt({challengeId:s.id,zoneId:o});let u=await t.withdrawal,d=u.senderTags??await fs(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}),t}),f;try{f=await ps(n,{portal:cs(o),senderTags:d,timeoutMs:Bs(s.expires,a.settlementTimeoutMs),to:c})}catch(e){throw new pt({cause:e,challengeId:s.id,senderTags:d,zoneId:o})}i.get(l)===t&&(Us(s.expires)?(t.redeemedLate=!0,t.senderTags=[f.senderTag]):i.delete(l));let{hash:p,senderTag:m}=f;return dn({challenge:s,payload:{hash:p,senderTag:m,type:`zone`,zoneId:o}})}function Ls(e){if(e)try{let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`?void 0:t.origin}catch{return}}function Rs(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||us(n)===void 0)return;let r=ls(n);if(r!==e.zoneId)throw Error(`zone.zoneId ${e.zoneId} does not match Zone ${r} of the zone.client chain ${n}.`)}function zs(e,t){if(!e)return!0;let n=t??6e4;return new Date(e).getTime()-Date.now()>n+15e3}function Bs(e,t){let n=t??6e4;return e?Math.max(0,Math.min(n,new Date(e).getTime()-Date.now())):n}function Vs(e){return JSON.stringify(e)}function Hs(e,t){let n;try{n=e.opaque===void 0?e.meta:ht(e.opaque)}catch{return}let{digest:r,intent:i,method:a,realm:o,request:s}=e;return gt({digest:r,intent:i,meta:_n(n),method:a,realm:o,request:s,zoneId:t})}function Us(e){if(!e)return!1;let t=new Date(e).getTime();return!Number.isNaN(t)&&Date.now()>=t}function Ws(e){if(!e)return!0;let t=new Date(e).getTime();return Number.isNaN(t)||Date.now()<t+3e5}async function Gs(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=Co({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 T(a.client,g);t.sent=!0;let v=p(_),y=await C(a.client,{serializedTransaction:_}).catch(e=>ee(a.client,{hash:v,timeout:15e3}).catch(()=>{let t=Error(`Zone withdrawal outcome is unknown: transaction ${v} may have been sent. Retrying this challenge does not withdraw again.`);throw Object.defineProperty(t,"cause",{configurable:!0,value:e,writable:!0}),t}));if(y.status===`reverted`)throw t.sent=!1,Error(`Zone withdrawal transaction ${y.transactionHash} reverted.`);let[x]=h({abi:oe.zoneOutbox,eventName:`WithdrawalRequested`,logs:y.logs});return{blockNumber:y.blockNumber,sender:s.address,senderTags:x?[ds({fallbackNonce:x.args.fallbackNonce,sender:x.args.sender,transactionHash:y.transactionHash})]:void 0,transactionHash:y.transactionHash}}function Ks(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 qs(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)&&bo(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>Ks(t.maxAmount,c?.decimals))throw Error(`Tempo charge ${u} maxAmount.`)}const Js=(1n<<96n)-1n;function Ys(e){return e>=0n&&e<=Js}function Xs(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return Ys(t)?t:void 0}function Zs(e){return Qs(e),e}function Qs(e){if(!Ys(e))throw Error(`Value ${e} is outside uint96 bounds.`)}const $s=new Set([`open`,`topUp`,`voucher`,`close`]);function ec(e){return typeof e==`object`&&!!e}function tc(e){return typeof e==`string`&&$s.has(e)}function nc(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!tc(t.action))}function rc(e,t=`No session credential context available.`){if(!nc(e))throw Error(t);return e}function ic(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function ac(e){return ec(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function oc(e){return ec(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 sc(e){let t=k.toString(e),n=JSON.parse(t);if(!oc(n))throw Error(`Invalid session receipt.`);return n}function cc(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function lc(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{return yl(e,n,t.request),!0}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;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 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=uc(r);return ac(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=uc(r);return oc(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function uc(e){try{return JSON.parse(e)}catch{return null}}function dc(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function fc(){return JSON.stringify({mpp:`payment-close-request`})}function pc(e){let t=mc(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`&&oc(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`&&ac(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&oc(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function mc(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}const hc=`0x4d50500000000000000000000000000000000000`;function gc(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function _c(e){let t=O.encode(O.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 j.keccak256(t)}function vc(e){return ve.encodeForSigning(e)}function yc(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function bc(e,t){return j.keccak256(M.concat(vc(e),t.sender))}const xc=[{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`}],Sc=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],Cc={name:`descriptor`,type:`tuple`,components:xc},wc=[{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:[Cc,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[Cc,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[Cc,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[Cc],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[Cc],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[Cc],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:xc},{name:`state`,type:`tuple`,components:Sc}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:Sc}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:Sc}]},{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:[Cc,{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 Tc(e){return e.type===`secp256k1`?e.signature.s<=57896044618658097711785492504343953926418782139537452191302581570759080747168n:e.type===`p256`||e.type===`webAuthn`?e.signature.s<=57896044605178124381348723474703786764998477612067880171211129530534256022184n:!0}function Ec(e){if(e.type===`configurable`)return{...e,signatures:e.signatures.map(e=>Ec(e))};if(Tc(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 Dc(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function Oc(e){return e===void 0||BigInt(e)===0n}function kc(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(!Dc(t.type)||!Tc(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=>To(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 Ac(e,t){let{account:n,commitment:r,payload:i}=t;if(!To(e.account,n)||BigInt(e.config.version??0n)===0n&&e.config.owners.some(({owner:t})=>To(t,e.account)))return!1;if(Oc(r)){if(BigInt(e.config.version??0n)!==0n||!To(me.getAddress(e.config),n))return!1}else if(me.getCommitment(e.config).toLowerCase()!==r.toLowerCase())return!1;return kc(e,i)}function jc(e,t){return{name:`TIP20 Channel Reserve`,version:`1`,chainId:t,verifyingContract:e}}const Mc={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},Nc={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]};function Pc(e,t,n){return l({domain:jc(e,t),types:Nc,primaryType:`CloseAuthorization`,message:n})}function Fc(e,t){return he.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function Ic(e,t,n){return e.toLowerCase()===he.address.toLowerCase()?Fc(t,n):l({domain:jc(e,t),types:Mc,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function Lc(e,t,n,r){let i=Rc(e);return i?zc(i,t,n,r):!1}function Rc(e){let t=H.from(e);if(H.serialize(t).toLowerCase()===e.toLowerCase())return t}function zc(e,t,n,r){if(e.type===`configurable`)return r.configurable?Ac(e,{account:n,commitment:r.openingCommitment,payload:t}):!1;if(!Dc(e.type)||!Tc(e)||!Oc(r.openingCommitment))return!1;let i=H.extractAddress({payload:t,signature:e});return H.verify(e,{address:i,payload:t})&&To(i,n)}function Bc(e){return e.source===`configurable`}function Vc(e){return e.source===`accessKey`&&`accessKeyAddress`in e}function Hc(e,t){return se.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function Uc(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===he.address.toLowerCase())try{return await Hc(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return E(e,{account:t,domain:jc(r,i),types:Mc,primaryType:`Voucher`,message:n})})(),o=H.from(a);if(!Dc(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(Ec(o))}async function Wc(e,t,n,r,i){let a=Vc(t)?await t.sign({hash:Pc(r,i,n),raw:!0}):await E(e,{account:t,domain:jc(r,i),types:Nc,primaryType:`CloseAuthorization`,message:n}),o=H.from(a);if(!Dc(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(Ec(o))}function Gc(e,t,n,r,i={}){try{let a=Ic(e,t,n);return Lc(n.signature,a,r,i)}catch{return!1}}function Kc(e){return typeof e==`object`&&!!e}function qc(e){return typeof e==`string`&&d(e,{strict:!1})?e:void 0}function Jc(e){return qc(e.accessKeyAddress)}function Yc(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(M.random(8))%e)}function Xc(e){return Jc(e)??e.address}function Zc(e){return Qc(e)!==void 0}function Qc(e){let t=Jc(e);if(t===void 0)return Bc(e)?e:void 0;let n=e.delegate;if(n&&Bc(n)&&n.address.toLowerCase()===t.toLowerCase())return n}async function $c(e,t){let n=Qc(t);if(!n)return M.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 el(e,t){let n=$o(e);if(n)try{let i=r({abi:wc,data:n});if(i.errorName!==`SignerConfigChanged`&&i.errorName!==`RootKeyRetired`)return;let[a]=i.args;return a.toLowerCase()===t.signer.toLowerCase()?new dt({cause:e,channelId:t.channelId,reason:i.errorName,signer:a}):void 0}catch{return}}async function tl(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return ts({account:n},()=>b(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}}))}async function nl(e,t){return await T(e,t)}function rl(e,t,n=!1){let r=e.request.methodDetails,i=Kc(r)?qc(r.escrowContract)??qc(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!al(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!al(i,a)?i:a}function il(e,t,n,r){return dn({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${t.descriptor?.payer??r.address}`})}function al(e,t){return e.toLowerCase()===t.toLowerCase()}function ol(e,t){let n=Qc(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 sl(e,t,n,r,i,a=hc){let o=_c({...n,chainId:i,escrow:a}),s=Zs(r);ol(t,n);let c=await Uc(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function cl(e,t,n,r,i,a=hc){let o=await sl(e,t,n,r,i,a),s=await Wc(e,t,{channelId:o.channelId,cumulativeAmount:Zs(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function ll(e,t,n){let r=Xc(t),a=n.escrow??`0x4d50500000000000000000000000000000000000`,o=n.operator??`0x0000000000000000000000000000000000000000`,s=n.salt??await $c(e,t),c=Zs(n.deposit),l=Zs(n.initialAmount),u=i({abi:wc,functionName:`open`,args:[n.payee,o,n.token,c,s,r]}),d=await nl(e,await tl(e,{account:t,calls:[...n.prefixCalls??[],{to:a,data:u}],feePayer:n.feePayer,feeToken:n.feeToken??n.token,validAfter:Yc()})),f=ue.deserialize(d),p={authorizedSigner:r,expiringNonceHash:bc(yc({...n.feePayer?{feePayer:!0}:{},transaction:f}),{sender:t.address}),operator:o,payee:n.payee,payer:t.address,salt:s,token:n.token},m=_c({...p,chainId:n.chainId,escrow:a});return{action:`open`,type:`transaction`,channelId:m,transaction:d,signature:await Uc(e,t,{channelId:m,cumulativeAmount:l},a,n.chainId),descriptor:p,cumulativeAmount:l.toString(),authorizedSigner:p.authorizedSigner}}async function ul(e,t,n,r,a,o,s=hc,c=[],l=n.token){let u=_c({...n,chainId:a,escrow:s}),d=Zs(r);return{action:`topUp`,type:`transaction`,channelId:u,transaction:await nl(e,await tl(e,{account:t,calls:[...c,{to:s,data:i({abi:wc,functionName:`topUp`,args:[n,d]})}],feePayer:o,feeToken:l,validAfter:Yc()}).catch(e=>{throw el(e,{channelId:u,signer:gc(n)})??e})),descriptor:n,additionalDeposit:d.toString()}}function dl(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function Q(e){return dl({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function fl(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(Q(t),t)},delete(t){e.delete(t)}}}const pl=new WeakMap,ml=new WeakMap;function hl(e,t){ml.set(e,ml.get(t)??t)}async function gl(e,t,n){let r=pl.get(e);r||(r=new Map,pl.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 _l(e,t,n){return gl(ml.get(e)??e,`funding:${t}`,n)}async function vl(e,t){await gl(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 yl(e,t){await gl(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}const bl=2n**96n-1n;function xl(e){if(e<0n||e>bl)throw new W({reason:`amount exceeds uint96 range`})}async function Sl(e,t,n=hc){let{cumulativeAmount:r,descriptor:i,signature:a}=t;return x(e,{address:n,abi:wc,functionName:`verifyVoucher`,args:[Tl(i),r,a]})}async function Cl(e,t,n=hc,r){return wl(await x(e,{address:n,abi:wc,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function wl(e){return xl(e.settled),xl(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}function Tl(e){return{payer:e.payer,payee:e.payee,operator:e.operator,token:e.token,salt:e.salt,authorizedSigner:e.authorizedSigner,expiringNonceHash:e.expiringNonceHash}}const El=G.custom(e=>typeof e==`string`&&d(e,{strict:!1})),Dl=G.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),Ol=G.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),kl=G.object({authorizedSigner:El,expiringNonceHash:Dl,operator:El,payee:El,payer:El,salt:Dl,token:El}),Al=bn(G.object({acceptedCumulative:G.string(),chainId:G.number(),channelId:Dl,closeRequestedAt:G.optional(G.string()),deposit:G.string(),descriptor:kl,escrow:El,highestVoucher:G.optional(G.object({channelId:Dl,cumulativeAmount:G.string(),signature:Ol})),requiredCumulative:G.string(),settled:G.string(),spent:G.string(),units:G.optional(G.number())}));function jl(e){return Al.encode(e)}function Ml(e){return Al.decode(e)}const Nl={status:`idle`};function Pl(e){return{status:`active`,...e}}function Fl(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:Rl(e.challengeId,t.snapshot),effects:[]}:$(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:Zl({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:zl(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:$(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:eu(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?Ll({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:zl(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:zl(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 Il(e,t){let n=Fl(e.state,t);return e.state=n.state,n}function Ll(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 Rl(e,t){return Pl({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function zl(e,t,n,r){return Pl({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 Bl(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function Vl(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`);Bl({cumulativeAmount:i,maxVoucherCumulative:n}),Bl({cumulativeAmount:a,maxVoucherCumulative:n})}function Hl(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;Vl({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function Ul(e,t){return typeof e==`bigint`?e:g(e,t)}function Wl(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(Kl(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 Gl(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;Bl({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 Kl(e,t){Bl({cumulativeAmount:e,maxVoucherCumulative:t??null})}function ql(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 Jl(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function Yl(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!Ys(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>Jl({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function Xl(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=Xs(r),s=Xs(a.spent);return o===void 0||s===void 0||!Ys(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function Zl(e){return Pl({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 Ql(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:Nl}}function $l(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=Hl({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&Il(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function eu(e,t){return Pl({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function tu(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=Xs(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 nu(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 Fl(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function ru(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 iu(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 au(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(fc()),e.waitForCloseReady()))(),a=BigInt(i.spent);Yl({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=>Xl({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(dc(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}function ou(e){return`cumulativeAmount`in e}function su(e){if(ou(e))return BigInt(e.cumulativeAmount)}async function cu(e,t){e.origin!==void 0&&(t={...t,origin:e.origin}),t.opened?await vl(e.store,t):await yl(e.store,Q(t)),e.notifyUpdate(t)}async function lu(e,t,n){let r=su(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 cu(e,i))}const uu=G.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),du=G.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),fu=G.object({account:G.optional(G.custom()),autoSwap:G.optional(G.custom()),action:G.optional(G.enum([`open`,`topUp`,`voucher`,`close`])),channelId:G.optional(du),cumulativeAmount:G.optional(K()),cumulativeAmountRaw:G.optional(G.string()),transaction:G.optional(uu),descriptor:G.optional(G.custom()),additionalDeposit:G.optional(K()),additionalDepositRaw:G.optional(G.string()),depositRaw:G.optional(G.string())});function pu(e){return e?.action!==void 0}function mu(e){return pu(e)&&e.descriptor!==void 0}function hu(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 gu(e,t,n,r){let i=hu(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}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){let t=e.request.methodDetails;return _u(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:vu(t.escrowContract),escrow:vu(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:vu(t.feeToken),operator:vu(t.operator),configurableVouchers:typeof t.configurableVouchers==`boolean`?t.configurableVouchers:void 0,sessionSnapshot:rt(t,tt.sessionSnapshot)}:{}}function bu(e,t){if(typeof e==`string`&&d(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function xu(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function Su(e){return typeof e==`string`?e:void 0}async function Cu(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=yu(n);(o.chainId!==void 0||i?.length===0)&&bo(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});yo(c,s);let l=s??c.chain?.id;if(bo(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=rl(n,r,t),d=bu(n.request.recipient,`recipient`),f=bu(n.request.currency,`currency`);return{amount:xu(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:dl({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:Su(n.request.suggestedDeposit),token:f}}async function wu(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=Cl}=e,o=_c({...r,chainId:i.chainId,escrow:i.escrow});Tu({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 Tu(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(!al(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!al(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!al(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!al(gc(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function Eu(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function Du(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=hu(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function Ou(e){let{account:t,client:n,readChannelState:r,snapshot:i,verifyVoucherOnChain:a=Sl}=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=gc(i.descriptor),h=Zc(t);if(!(Gc(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 wu({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:Xc(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 ku(e,t){return al(e.address,t.payer)?al(Xc(e),gc(t)):!1}function Au(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(pu(r)){if(!mu(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=Eu({context:r,snapshot:o.snapshot});return!n&&s&&ku(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&ku(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 ju(e,t,n=!1){switch(e.type){case`open`:return Pu(e,t,n);case`recover`:return Fu(e,t);case`voucher`:return Iu(e,t);case`manual`:return Lu(e,t,n)}}async function Mu(e,t){if(e)return await Oo(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage,maxAmountIn:e.maxAmountIn})}async function Nu(e,t){let{account:n,amount:r,chainId:i,client:a,token:o}=t;if(e||!zo({chainId:i,currency:o}))return;let s=await Ko(a,{account:n,amount:r,chainId:i});if(s)throw s}async function Pu(e,t,n){let{account:r,resolved:i}=e;if(Zc(r)&&i.configurableVouchers!==!0)throw new ut({signer:r.address});let a=Wl({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw});await Nu(n,{account:r.address,amount:a,chainId:i.chainId,client:i.client,token:i.token});let o=await ll(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 Mu(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await cu(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function Fu(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await wu({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:Xc(n),token:o.token}}),l=Du({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`);Kl(l,a);let u=await sl(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await cu(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 Iu(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;Kl(a,e.maxDeposit);let o=await sl(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await cu(t,r),o}async function Lu(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=_c({...s,chainId:o.chainId,escrow:o.escrow});Tu({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:Xc(r),token:o.token});let l=await Ru({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await lu(t,o.key,l),l}async function Ru(e,t){switch(e.context.action){case`open`:return zu(e);case`topUp`:return Bu(e,t);case`voucher`:return Vu(e);case`close`:return Hu(e)}}async function zu(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=gu(r,i,`cumulativeAmount`,`open`),c=await sl(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 Bu(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=gu(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:(await Nu(t,{account:n.address,amount:c,chainId:s.chainId,client:s.client,token:s.token}),ul(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await Mu(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken))}function Vu(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return sl(a.client,t,i,gu(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function Hu(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return cl(a.client,t,i,gu(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}const Uu={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};function Wu(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=Uu.CLOSED,r=null}if(a.type===`open`&&(i=Uu.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 Gu(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function Ku(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=Ul(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 qu(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:eu(s,u)}:i?{channel:u,state:Zl({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function Ju(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=Gu(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:Zs(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function Yu(e){return e.method===$e.tempo&&e.intent===et.session}function Xu(e){return Yu(e)&&rt(e.request.methodDetails,tt.sessionProtocol)===nt.v2}function Zu(e){return rt(e.request.methodDetails,tt.sessionSnapshot)}function Qu(e,t,n,r){let i=e instanceof Request?e.headers:void 0;return Mi({...t,redirect:`manual`,headers:{...Da(i),...Da(t?.headers)}},Zt(r),n)}function $u(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 ed(e){try{let t=typeof location>`u`?void 0:location.href,n=$u(e)?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function td(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function nd(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 rd=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 id(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 ad({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 rd&&(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?sc(i):void 0}async function ad(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(ed(e.input),{method:`POST`,signal:r.signal,redirect:`manual`,headers:kd(t,n,e.input,e.headers)}),s])}catch(t){throw e.context.action===`topUp`?new rd(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=Wt(n).find(Xu);return r?t(r):n}async function od(e){let t=sd({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,Qu(e.input,e.init,t,r))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(U.paymentReceipt)&&await l(),u}function sd(e){let t=Wt(e.response).find(Xu);if(!t)return;let n=Zu(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function cd(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=$u(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?ed(r):e.lastUrl,{...i,method:`POST`,redirect:`manual`,headers:kd(a,s,e.lastUrl,e.headers)})},o=await a(e.target.challenge);if(o.status===402){let t=Wt(o).find(Xu);t&&(e.setChallenge?.(t),o=await a(t,!0))}if(!o.ok){let e=await nd(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=sc(s);if(!c.txHash||!M.validate(c.txHash,{strict:!0})||M.size(c.txHash)!==32||!Xl({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 ld(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...Da(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!cc(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),ud(e,c,{onReceipt:r,signal:o},n,s.headers)}function ud(e,t,n,r,i){if(!cc(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let a=r.getChallenge();return dd({onNeedVoucher:t=>gd({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*dd(e){for await(let t of fd(e))t.data!==void 0&&(yield t.data)}async function*fd(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=pd(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=lc(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 hd(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=fd({...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 gd(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await Ju({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 ad({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 _d(e){let t=new URL(e.input.toString()),n=td(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=Wt(r).find(Xu);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 vd(e){e.signal?.throwIfAborted();let t=await _d(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function yd(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:sn(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:ic(t)}}function bd(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function xd(e){if(!bd(e))return`received mismatched payment-close-ready frame`;let t=Xs(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 Sd(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!bd(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!Xl({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function Cd(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=yd({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=Wu(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===Uu.CONNECTING||s.readyState===Uu.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 Td({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await wd(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(dc(n)),await e.waitForReceipt(),l.socket}function wd(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 Td(e){let t=pc(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`:Ed(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 Dd(e,t.data);return;case`payment-receipt`:Od(e,t.data);return}}function Ed(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=xd({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 Dd(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 Ju({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(dc(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function Od(e,t){let n=Sd({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 kd(e,t,n,r){let i=Zt(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(`${Qe.payment} `)&&a.set(U.authorization,e)}return a.set(i,t),a}const Ad=new WeakMap;async function jd(e,t){let n=Ad.get(e)??new Map;Ad.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 Md(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function Nd(e,t,n){try{let r=e.response?.headers.get(U.paymentReceipt);if(r){let e=sc(r);if(e.challengeId===t.id&&Md(n,e))return!0}}catch{}return e.challenges?.some(e=>Xu(e)?Md(n,Zu(e)):!1)??!1}function Pd(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??[])Fd(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 Fd(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 Id(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>Fd(e.maxAmount,r?.decimals))throw Error(`Tempo session amount exceeds maxAmount.`)}function Ld(e,t){try{return Id(e,t),!0}catch{return!1}}function Rd(e){return typeof e==`object`&&!!e&&e.action===`close`}function zd(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=Pd(e),m=vo({chain:te,getClient:c,rpcUrl:Or}),h=mo({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??fl(),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??Eu({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:gc(i)}:{}}})??r},S=async(e,t,n)=>{let{decimals:r,maxDeposit:i}=_(e.challenge.request,e.chainId);return Au({account:await x(e,t,n),entry:n,context:t,decimals:r,maxDeposit:i,resolved:e})},C=yn(Ds,{canHandleChallenge:({challenge:e,context:t})=>Xu(e)&&(Rd(t)||t===di||Ld(p,e.request)),context:fu,async createCredential(e){let{challenge:t,context:i}=e;i?.action!==`close`&&Id(p,t.request);let a=await Cu({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:m});i?.action!==`close`&&t.request.methodDetails?.chainId===void 0&&Id(p,t.request,a.chainId);let c=ca(e),l=pa(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=!pu(i)&&i?.descriptor===void 0;e&&(d=await jd(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 jd(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 il(t,await ju(o,f,ko(i?.autoSwap??r,Do)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||Nd(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 vl(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 fa(r,Bd(n)),C.createCredential(r)}let T=async({autoSwap:e,challenge:t,channel:n,deposit:r,fetch:i,input:a,requiredCumulative:o,signal:s})=>_l(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=Gl({deposit:l,maxDeposit:u,requiredCumulative:o,suggestedDeposit:t.request.suggestedDeposit===void 0?void 0:BigInt(t.request.suggestedDeposit),topUpAmount:d});f>0n&&await id({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 vl(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 vl(y,g),b.notifyUpdate(g)});return Zi(C,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!Xu(e))return;let c=t===void 0?void 0:fu.parse(t);if(pu(c))return;Id(p,e.request);let l=await Cu({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m}),u=await y.get(l.key);if(!u?.opened)return;let d=Bd(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+ic(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||!ku(await x(l,c,u),u.descriptor)||await T({autoSwap:c?.autoSwap,challenge:e,channel:u,deposit:b,fetch:r,input:i,requiredCumulative:_,signal:a})}),aa(C,async({challenge:e,context:t,credential:r,fetch:i,headers:a,input:c,refetch:l,response:u,signal:d})=>{if(!Xu(e))return u;if(!cc(u))return rc(sn(r).payload).action===`open`&&a.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await l?.()??u:u;let f=(await Cu({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m})).key,p=await y.get(f),h={assertVoucherWithinLocalLimit:t=>Kl(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 T({autoSwap:t===void 0?void 0:fu.parse(t).autoSwap,challenge:e,channel:p,deposit:p.deposit>n?p.deposit:n,fetch:i,input:c,requiredCumulative:r,signal:a})}};return hd({onNeedVoucher:(t,n)=>gd({challenge:e,driver:h,headers:a,input:c,signal:n},t),onReceipt(){},response:u,signal:d})})}function Bd(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 Vd=new WeakMap;function Hd(e,t){Vd.set(e,t)}function Ud(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 Wd(e){let t=Ud(`close-ready`),n=Ud(`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 Gd(e){return e.method===$e.tempo&&e.intent===et.charge}function Kd(e){if(!Gd(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function qd(e,t,n){if(!n)return t;let r={...Da($u(e)?e.headers:void 0),...Da(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===U.paymentSession.toLowerCase())?t:{...t,headers:{...r,[U.paymentSession]:n}}}function Jd(e,t){return e===void 0?t:{...fu.parse(e),...t}}function Yd(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 Xd(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&bo(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=Yd(e),i;function a(e){let t=new URL($u(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}let o=Ya(r.fetch),s=Xa(r.fetch);r.fetch=async(e,t)=>{let n=a(e),r=await s(e,{...t,redirect:(t?.redirect??($u(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=ci(c,o));let l=vo({chain:te,getClient:e.client?()=>e.client:e.getClient,rpcUrl:Or}),u=mo({account:e.account}),d=Ql(),f=e.credentialContext===void 0?void 0:Jd(e.credentialContext,{}),p=Wd({getSocketSession:()=>d.socketSession}),m=e.channelStore??fl(),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,vl(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=>yl(m,e)};hl(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(yl(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(yl(m,t)).catch(()=>void 0)}e.created.clear(),await oe(e.committed??e.previous)}}function S(e){let t=rt(e.request.methodDetails,tt.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=ru({channel:d.channel,spent:d.spent,state:d.state}),!0;return!1}function C(e){return Il(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 T(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=ru({channel:d.channel,spent:d.spent,state:d.state}))}let E=zd({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()}),T(e)}}),ee=ea(E);ee&&Zi(E,e=>ne(()=>Promise.resolve(ee(e)),e.signal)),oa(E);let D=As({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),O=Ea({trustedTempoProofRealms:e.trustedTempoProofRealms,fetch:c,identity:o,methods:[E],onChallenge:async(e,t)=>{if(!Yu(e))return;let n=g,r=n&&n.challengesReceived>0&&e.id===d.lastChallenge?.id,i=r&&po(e)===po(d.lastChallenge);n&&n.challengesReceived++,!i&&(S(e)||(n?.created.size?await x():r&&await oe(n.committed??n.previous)),d.lastChallenge=e,C({type:`challengeReceived`,challengeId:e.id}))}});function k(e,t){let n={challenge:e,context:Jd(f,t)};return i&&fa(n,i),E.createCredential(n)}function A(e){$l({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:d})}function j(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 M(t){let r=t.headers.get(U.paymentSessionSnapshot);if(!r)return;let i=Ml(r);bo(e.allowedChainIds,i.chainId),rl({request:{methodDetails:{escrow:i.escrow}}},e.escrow,n);let a=await l({chainId:i.chainId});yo(a,i.chainId);let o=u(a),{entry:s,spent:c}=await Ou({account:await e.resolveAccount?.({account:o,chainId:i.chainId,operation:{authority:gc(i.descriptor),kind:`authorizePaymentChannel`}})??o,client:a,snapshot:i});return R(s.cumulativeAmount),await Promise.resolve(y.set(s)).catch(()=>void 0),d.channel=s,d.spent=c,s}async function N(t,n){if(!e.bootstrap||d.channel?.opened)return;let i=$u(t)?t.headers:void 0,{body:a,method:o,...s}=n??{},c=$u(t)?t.url:t,l={...s,method:`HEAD`,headers:{...Da(i),...Da(n?.headers),[U.acceptPayment]:`${$e.tempo}/${et.charge}`}};try{let t=await r.fetch(c,l);if(t.status!==402)return await M(t);let n=Wt(t).find(Gd);if(!n||!Kd(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;ha(n,i,e.trustedTempoProofRealms);let a=await D.createCredential({challenge:n,context:{}}),o=await r.fetch(c,Mi({...l,redirect:`manual`},Zt(n),a));return o.ok?await M(o):void 0}catch{return}}function P(e,t){let n=d.socketSession;return tu({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 F(e,t){let n=Zu(t);if(!n)return;if(_c({...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 I(e,t){let n=F(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 L(e,t=e.challenge,n=!1){let r=(n?I(e,t):F(e.channel,t))?.acceptedCumulative??P(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return R(r),r.toString()}function R(e){Bl({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}let z,B;async function ne(e,t){if(B)throw B;for(;;){let e=z;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(),B)throw B;let n=e();z=n;try{return await n}catch(e){throw e instanceof rd&&(B=Error(`Session funding outcome is unknown; reconcile the pending payment before creating a new session manager.`)),e}finally{z===n&&(z=void 0)}}async function re(e){if(!d.channel)throw Error(`Cannot top up session: no active channel`);return _l(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 id({...n,channel:d.channel,createSessionCredential:k,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),T(n)}});A(a);let o=d.channel,s=qu({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()}),T(e)}return a})}async function ie(e){return ne(async()=>{e.signal?.throwIfAborted();let t=d.channel?.channelId===e.channelId?d.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=Gl({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 re({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})},e.signal)}async function ae(e,t){let n=nu({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 oe(e){let t=iu(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?sc(n):null;return t&&A(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?.[ba])return se(await r.fetch(e,xa(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=ru({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 N(e,t),i.trackCreates=!0;let a=qd(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=qd(e,t,void 0),!0)}for(;;){let t;try{t=await O(e,a)}catch(e){if(i.created.size?await x():await oe(i.committed??n),await s())continue;throw e}let o=se(t),c=!1;if(o.status===402){let t=await od({input:e,init:a,response:o,createSessionCredential:k,fetch:r.fetch,getChannel:()=>d.channel,restoreCumulative:ae,setChallenge(e){d.lastChallenge=e},topUpIfNeeded:ie});t&&(c=!0,o=se(t))}if(!c&&!o.ok&&!o.receipt){if(i.created.size?await x():await oe(i.committed??n),await s())continue;return o}return o}}finally{g=void 0}}async function ce(e){let t=await cd({createSessionCredential:k,fetch:r.fetch,getMinimumSpent:()=>d.spent,headers:d.lastHeaders,lastUrl:d.lastUrl,resolveSignedCloseAmount:t=>L(e,t,!0),signedCloseAmount:L(e),setChallenge(e){d.lastChallenge=e},target:e});return t&&(j(),C({type:`closeStarted`}),C({type:`closed`,receipt:t})),t}let le={createSessionCredential:k,doFetch:V,fetch:r.fetch,getChannel:()=>d.channel,getChallenge:()=>d.lastChallenge,assertVoucherWithinLocalLimit:R,acceptReceipt(e){A(e)},topUpIfNeeded:ie},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=Ku({amount:e,assertVoucherWithinLocalLimit:R,channel:d.channel,decimals:r.decimals,lastChallenge:d.lastChallenge,lastUrl:d.lastUrl});return ne(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=Ku({amount:e,assertVoucherWithinLocalLimit:R,channel:d.channel,decimals:r.decimals,lastChallenge:t.challenge,lastUrl:t.input});return re({additionalDeposit:n.additionalDeposit,challenge:n.challenge,channelId:n.channelId,headers:d.lastHeaders,input:n.input})})},async sse(e,t){if(t?.[ba])throw Error(`SessionManager.sse requires payment; use fetch for unpaid streams.`);return ld(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=td(e);a(n);let i=t?.signal?{signal:t.signal}:void 0;await N(n,i);let o=d.channel?.opened?d.channel.channelId:void 0,{challenge:s,credential:c,httpUrl:l,wsUrl:u}=await vd({async createSessionCredential(e,i){return d.lastChallenge=e,await $i(E,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),k(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){d.lastUrl=e.toString()},probeInit:qd(n,i,o),signal:t?.signal});return d.lastChallenge=s,Cd({challenge:s,credential:c,httpUrl:l,WebSocket:r.WebSocket,wsUrl:u,options:t,createSessionCredential:k,getChannel:()=>d.channel,setSocketSession(e){d.socketSession=e},async refreshChallenge(){let e=await _d({fetch:r.fetch,input:l,probeInit:qd(l,i,d.channel?.opened?d.channel.channelId:void 0),signal:t?.signal});return d.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:R,acceptReceipt:A,rejectCloseReady:p.rejectCloseReady,rejectReceipt:p.rejectReceipt,settleCloseReady:p.settleCloseReady,settleReceipt:p.settleReceipt,topUpIfNeeded:ie,waitForReceipt:p.waitForReceipt})},async close(){let e=d.socketSession,t=ql({channel:d.channel,currentSocket:e,lastChallenge:d.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===Uu.OPEN){let r=await au({activeSocket:n,createSessionCredential:k,currentSocket:e,spent:d.spent,target:t,waitForCloseReady:p.waitForCloseReady,waitForReceipt:p.waitForReceipt});return j(),C({type:`closeStarted`}),C({type:`closed`,receipt:r}),r}return ce(t)}};return Hd(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 ud(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(!Yu(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.`);R(e.cumulativeAmount);let o=F(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=jl,e.deserializeSnapshot=Ml})(Xd||={});const Zd=(1n<<64n)-1n,Qd={dev_second:1n,day:86400n,week:604800n};function $d(e){return e instanceof Date?e:new Date(e)}function ef(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 tf(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new W({reason:`periodCount is invalid`});let t=Qd[e.periodUnit];if(t===void 0)throw new W({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>Zd)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 nf(e){let{challengeExpires:t,request:n}=e;tf(n);let r=ef($d(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 rf(e){return[{address:_f(e.currency,`currency`),selector:`0x95777d59`,recipients:[_f(e.recipient,`recipient`)]}]}function af(e){try{let t=M.fromBytes(k.toBytes(e));if(M.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new W({reason:`challenge id must encode 32 bytes`})}}async function of(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=cf({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(Ec(c))})}function sf(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=lf(i.signature),s=uf(o);if(df({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==af(n))throw new W({reason:`keyAuthorization challenge mismatch`});return ff(o,a),mf(pf(o),a),hf(o.scopes,a),{authorization:o,source:{address:gf(o,s),chainId:r}}}function cf(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return ge.from({address:_f(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:ef($d(i.subscriptionExpires)),limits:[{token:_f(i.currency,`currency`),limit:BigInt(i.amount),period:tf(i)}],scopes:rf(i),type:t.keyType,witness:af(n)})}function lf(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 uf(e){let t=e.signature;if(!t)throw new W({reason:`keyAuthorization must use a primitive signature`});return t}function df(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,_f(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 ff(e,t){if(nf({request:t}),e.expiry!==ef($d(t.subscriptionExpires)))throw new W({reason:`keyAuthorization expiry mismatch`})}function pf(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 mf(e,t){if(!f(e.token,_f(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!==tf(t))throw new W({reason:`keyAuthorization period mismatch`})}function hf(e,t){if(!e||e.length!==1)throw new W({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=_f(t.currency,`currency`),r=_f(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=vf(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 gf(e,t){let n=ge.getSignPayload(e);try{let e=H.extractAddress({payload:n,signature:t});if(!Tc(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 _f(e,t){if(!d(e))throw new W({reason:`${t} must be an address`});return e.toLowerCase()}function vf(e){return typeof e==`string`?e.toLowerCase():``}const yf=G.object({accessKey:G.optional(G.custom()),account:G.optional(G.custom())});function bf(e={}){let t=vo({chain:B,requireChain:!0,getClient:e.getClient,rpcUrl:Or}),n=mo({account:e.account});return yn(Os,{context:yf,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.");Sf(r.request),await e.validateRequest?.(r.request);let l=await xf(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),u=sf({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 dn({challenge:r,payload:{signature:ge.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function xf(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await of({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:ef($d(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:M.fromNumber(BigInt(o.amount)),period:tf(o)}],scopes:rf(o),witness:af(i)}]});return ge.fromRpc(c.keyAuthorization)}function Sf(e){tf(e),ef($d(e.subscriptionExpires))}const Cf=Object.assign(zd,{manager:Xd});function wf(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[As(e),Cf(n)]}(function(e){e.charge=As,e.common=wf,e.session=Cf,e.subscription=bf})(wf||={});const Tf=z.union([z.boolean(),z.literal(`true`).transform(()=>!0),z.literal(`false`).transform(()=>!1)]);async function Ef(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}const Df=z.object({allowCustomEscrow:z.optional(Tf),autoSwap:z.optional(Tf),channel:z.optional(z.coerce.string()),deposit:z.optional(z.union([z.string(),z.number()])),payWith:z.optional(z.string()),slippage:z.optional(z.coerce.number()),tokenIn:z.optional(z.string())}),Of=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`];function kf(){let t;return Jr({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:n,options:r,methodOpts:i}){let a=Wr(r.account),o=n.request,s=o.currency,c=Ff(i),l=zf({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()||(Ar(a)?void 0:await Gr(a).get());if(!_&&Ar(a)&&Jf()){g=!0;let t=Kf(a);if(t){let i=Nr(r.rpcUrl,{network:r.network});h=e({chain:await Pr({network:r.network,rpcUrl:i}),transport:u(i)}),Lf({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let a=s?await Lr(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=Xf();if(e){let t=await Gr(e).get();t&&(m=pe(t))}if(!m)throw r.account?new Cr({code:`ACCOUNT_NOT_FOUND`,message:`Account "${a}" not found.`,exitCode:69}):new Cr({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!g&&m){let t=Nr(r.rpcUrl,{network:r.network});h=e({chain:await Pr({network:r.network,rpcUrl:t}),transport:u(t)}),Lf({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let i=s?await Lr(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 Yf(t)}};if(!m||!h)throw new Cr({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let v=wf({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??(Ir(h.chain)?`10`:void 0);if(!t)throw new Cr({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=Vf(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 Uc(h,m,c,i,a);return dn({challenge:n,payload:{action:o,channelId:e,...o===`close`?{closeSignature:await Wc(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=sn(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(
|
|
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};
|