mppx 0.17.0 → 0.17.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/dist/BodyDigest.js +13 -1
  3. package/dist/Method.d.ts +5 -0
  4. package/dist/Store.d.ts +225 -0
  5. package/dist/Store.js +358 -0
  6. package/dist/cli/cli.js +136 -135
  7. package/dist/cli/plugins/index.js +12 -11
  8. package/dist/cli/sessions/Manager.js +12 -1
  9. package/dist/cli/sessions/store.js +7 -1
  10. package/dist/cli/utils.d.ts +2 -0
  11. package/dist/cli/utils.js +6 -0
  12. package/dist/cli/validate/helpers.d.ts +1 -1
  13. package/dist/cli/validate/helpers.js +14 -2
  14. package/dist/client/Mppx.d.ts +1 -1
  15. package/dist/client/Mppx.js +18 -6
  16. package/dist/client/internal/Fetch.d.ts +3 -1
  17. package/dist/client/internal/Fetch.js +68 -3
  18. package/dist/client/internal/MethodResponse.d.ts +8 -0
  19. package/dist/client/internal/MethodResponse.js +9 -0
  20. package/dist/client/internal/ProofRealm.d.ts +3 -3
  21. package/dist/client/internal/ProofRealm.js +4 -4
  22. package/dist/client/internal/protocols/Mcp.d.ts +4 -0
  23. package/dist/client/internal/protocols/Mcp.js +27 -14
  24. package/dist/identity/Client.js +7 -1
  25. package/dist/internal/AcceptPayment.d.ts +12 -2
  26. package/dist/internal/AcceptPayment.js +12 -3
  27. package/dist/internal/sse.d.ts +21 -0
  28. package/dist/internal/sse.js +65 -0
  29. package/dist/internal/version.d.ts +2 -2
  30. package/dist/internal/version.js +1 -1
  31. package/dist/mcp/client/McpClient.d.ts +2 -2
  32. package/dist/mcp/client/McpClient.js +6 -3
  33. package/dist/proxy/Proxy.d.ts +17 -0
  34. package/dist/proxy/Proxy.js +116 -3
  35. package/dist/proxy/internal/Replay.d.ts +105 -0
  36. package/dist/proxy/internal/Replay.js +257 -0
  37. package/dist/server/Mppx.d.ts +2 -0
  38. package/dist/server/Mppx.js +7 -5
  39. package/dist/server/Transport.js +1 -1
  40. package/dist/server/internal/html/config.d.ts +7 -1
  41. package/dist/server/internal/html/config.js +4 -0
  42. package/dist/stripe/internal/types.d.ts +82 -6
  43. package/dist/stripe/server/Charge.js +1 -2
  44. package/dist/stripe/server/internal/html.gen.js +1 -1
  45. package/dist/tempo/client/Charge.d.ts +9 -0
  46. package/dist/tempo/client/Charge.js +13 -9
  47. package/dist/tempo/client/Methods.d.ts +2 -0
  48. package/dist/tempo/internal/fee-payer.d.ts +85 -10
  49. package/dist/tempo/internal/fee-payer.js +183 -19
  50. package/dist/tempo/legacy/session/Chain.js +2 -0
  51. package/dist/tempo/server/Charge.js +6 -3
  52. package/dist/tempo/server/Subscription.js +1 -0
  53. package/dist/tempo/server/internal/html.gen.js +1 -1
  54. package/dist/tempo/server/internal/transport.d.ts +6 -0
  55. package/dist/tempo/server/internal/transport.js +21 -21
  56. package/dist/tempo/session/client/ChannelOps.d.ts +2 -0
  57. package/dist/tempo/session/client/ChannelStore.d.ts +2 -0
  58. package/dist/tempo/session/client/ChannelStore.js +5 -0
  59. package/dist/tempo/session/client/CredentialState.js +2 -0
  60. package/dist/tempo/session/client/Session.d.ts +37 -2
  61. package/dist/tempo/session/client/Session.js +111 -7
  62. package/dist/tempo/session/client/SessionManager.d.ts +2 -1
  63. package/dist/tempo/session/client/SessionManager.js +60 -9
  64. package/dist/tempo/session/client/Transports.d.ts +4 -0
  65. package/dist/tempo/session/client/Transports.js +35 -3
  66. package/dist/tempo/session/precompile/Chain.js +1 -0
  67. package/dist/tempo/session/precompile/Voucher.js +20 -7
  68. package/dist/tempo/session/server/ChannelStore.d.ts +9 -0
  69. package/dist/tempo/session/server/ChannelStore.js +8 -1
  70. package/dist/tempo/session/server/MeteredStream.d.ts +4 -0
  71. package/dist/tempo/session/server/MeteredStream.js +6 -1
  72. package/dist/tempo/session/server/Session.d.ts +2 -1
  73. package/dist/tempo/session/server/Session.js +2 -1
  74. package/dist/tempo/session/server/Settlement.d.ts +4 -2
  75. package/dist/tempo/session/server/Settlement.js +2 -2
  76. package/dist/tempo/session/server/Sse.d.ts +59 -0
  77. package/dist/tempo/session/server/Sse.js +175 -10
  78. package/dist/tempo/session/server/Ws.js +29 -12
  79. package/dist/zod.d.ts +2 -1
  80. package/dist/zod.js +1 -1
  81. package/package.json +1 -3
  82. package/dist/stripe/server/internal/html/types.d.ts +0 -2
  83. package/dist/stripe/server/internal/html/types.js +0 -2
@@ -1,17 +1,18 @@
1
- import{createClient as e,createTransport as t,custom as n,encodeFunctionData as r,erc20Abi as i,getAddress as a,hashTypedData as o,http as s,isAddress as c,isAddressEqual as l,keccak256 as u,parseAbi as d,parseUnits as f}from"viem";import{call as p,prepareTransactionRequest as m,readContract as h,sendCallsSync as g,sendTransactionSync as _,signTransaction as v,signTypedData as y}from"viem/actions";import*as b from"viem/chains";import{tempo as x}from"viem/chains";import{AbiParameters as S,Base64 as C,Bytes as w,Hash as T,Hex as E,Json as D}from"ox";import{z as O}from"zod/mini";import*as k from"node:child_process";import*as A from"node:fs";import*as j from"node:os";import*as M from"node:path";import{z as N}from"zod";import"node:readline";import{tempo as P,tempoModerato as F}from"viem/tempo/chains";import{ousd as I,pathusd as L,usdce as ee}from"viem/tokens";import{Abis as te,Account as ne,Actions as R,Addresses as re,TokenId as ie,Transaction as ae,withFeePayer as oe}from"viem/tempo";import{parseAccount as se,privateKeyToAccount as ce}from"viem/accounts";import{createParser as le}from"eventsource-parser";import{Channel as ue,KeyAuthorization as de,SignatureEnvelope as z,TempoAddress as fe,TxEnvelopeTempo as pe}from"ox/tempo";var me=Object.defineProperty,he=Object.getOwnPropertyDescriptor,ge=Object.getOwnPropertyNames,_e=Object.prototype.hasOwnProperty,ve=(e,t)=>{let n={};for(var r in e)me(n,r,{get:e[r],enumerable:!0});return t||me(n,Symbol.toStringTag,{value:`Module`}),n},ye=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=ge(t),a=0,o=i.length,s;a<o;a++)s=i[a],!_e.call(e,s)&&s!==n&&me(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=he(t,s))||r.enumerable});return e},be=(e,t,n)=>(ye(e,t,`default`),n&&ye(n,t,`default`));const xe=Symbol(`mppx.x402.asset`);function Se(e){return{[xe]:!0,address:e.address,decimals:e.decimals,network:e.network,transfer:e.transfer}}function Ce(e,t){let n=e(t.chainId);return Se({address:n.address,decimals:n.decimals,network:Ne(t.chainId),transfer:Fe(t.transfer,n)})}const we={USDC:Se({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},Te={USDC:Se({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},Ee={USDC:Se({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:Se({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},De={USDC:Se({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})};function Oe(e){return typeof e!=`object`||!e?!1:e[xe]===!0}function ke(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function Ae(e){return typeof e==`string`}function je(e,t){if(Oe(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(ke(e)){let n=e.addresses[Pe(t)];return n?{address:n,decimals:e.decimals,name:e.name}:void 0}return{address:e}}function Me(e,t,n){let r=je(e,n);return r?a(r.address)===a(t):!1}function Ne(e){return`eip155:${e}`}function Pe(e){return Number(e.slice(7))}function Fe(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 Ie=ve({base:()=>we,baseSepolia:()=>Te,celo:()=>Ee,celoSepolia:()=>De,define:()=>Se,fromToken:()=>Ce,isAsset:()=>Oe,isRawAddress:()=>Ae,isToken:()=>ke,matches:()=>Me,resolve:()=>je,toChainId:()=>Pe,toNetwork:()=>Ne}),Le=ve({base:()=>Re,baseSepolia:()=>ze,celo:()=>Be,celoSepolia:()=>Ve});const Re=8453,ze=84532,Be=42220,Ve=11142220,B={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},He={payment:`Payment`},Ue={evm:`evm`,stripe:`stripe`,tempo:`tempo`},We={charge:`charge`,session:`session`,subscription:`subscription`},Ge={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},Ke={v1:`v1`,v2:`v2`};function qe(e,t){if(!(!e||typeof e!=`object`))return e[t]}function Je(e){let t=C.toString(e);return JSON.parse(t)}function V(e){let t=D.canonicalize(e);return C.fromString(t,{pad:!1,url:!0})}var H=ve({address:()=>W,amount:()=>U,datetime:()=>Xe,datetimeInput:()=>Ze,hash:()=>G,period:()=>et,signature:()=>K,toDate:()=>Qe,toDatetimeString:()=>$e,unwrapOptional:()=>tt});import*as Ye from"zod/mini";be(H,Ye);function U(){return O.string().check(O.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function Xe(){return O.string().check(O.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 Ze(e=`Invalid ISO 8601 datetime`){return O.pipe(O.union([Xe(),O.custom(e=>e instanceof Date)]),O.transform(Qe)).check(O.refine(e=>Number.isFinite(e.getTime()),e))}function Qe(e){return e instanceof Date?e:new Date(e)}function $e(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function W(){return O.string().check(O.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function G(){return O.string().check(O.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function et(){return O.string().check(O.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function K(){return O.string().check(O.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function tt(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}const nt=H.object({description:H.optional(H.string()),digest:H.optional(H.string().check(H.regex(/^sha-256=/,`Invalid digest format`))),expires:H.optional(Xe()),header:H.optional(H.string().check(H.regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,`Invalid HTTP header name`))),id:H.string().check(H.minLength(1)),intent:H.string(),method:H.string(),meta:H.optional(H.record(H.string(),H.string())),opaque:H.optional(H.string()),realm:H.string(),request:H.record(H.string(),H.unknown())});function rt(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=vt(o)?void 0:o,f=e.expires?$e(e.expires):void 0,p=e.opaque??(i===void 0?void 0:V(i)),m=u?yt({...e,expires:f,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return nt.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}})}function it(e){let t=[q(`id`,e.id),q(`realm`,e.realm),q(`method`,e.method),q(`intent`,e.intent),q(`request`,V(e.request))];e.description!==void 0&&t.push(q(`description`,e.description)),e.digest!==void 0&&t.push(q(`digest`,e.digest)),e.expires!==void 0&&t.push(q(`expires`,e.expires));let n=e.header;return n!==void 0&&!vt(n)&&t.push(q(`header`,n)),e.opaque===void 0?e.meta!==void 0&&t.push(q(`opaque`,V(e.meta))):t.push(q(`opaque`,e.opaque)),`${He.payment} ${t.join(`, `)}`}function q(e,t){if(/[\r\n]/.test(t))throw Error(`Invalid quoted-string value.`);return`${e}="${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/[\u0100-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}"`}function at(e,t){let n=ot(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,...a}=st(n);if(!r)throw Error(`Missing request parameter.`);if(r.length>16384)throw Error(`Request parameter too large.`);if(a.method&&!/^[a-z][a-z0-9:_-]*$/.test(a.method))throw Error(`Invalid method: "${a.method}". Must be lowercase per spec.`);return rt({...a,request:Je(r),...i&&{opaque:i}},t)}function ot(e){let t=He.payment,[n]=ft(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 st(e){let t=Object.create(null),n=0;for(;n<e.length;){for(;n<e.length&&/[\s,]/.test(e[n]??``);)n++;if(n>=e.length)break;let r=n;for(;n<e.length&&/[A-Za-z0-9_-]/.test(e[n]??``);)n++;let i=e.slice(r,n).toLowerCase();if(!i)throw Error(`Malformed auth-param.`);for(;n<e.length&&/\s/.test(e[n]??``);)n++;if(e[n]!==`=`)break;for(n++;n<e.length&&/\s/.test(e[n]??``);)n++;let[a,o]=ct(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function ct(e,t){if(e[t]===`"`)return lt(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function lt(e,t){let n=t,r=!1,i=t,a;for(;n<e.length;){let o=e[n];if(n++,r){a??=[];let t=o===`u`?e.slice(n,n+4):void 0;t&&/^[0-9A-Fa-f]{4}$/.test(t)?(a.push(String.fromCharCode(Number.parseInt(t,16))),n+=4):a.push(o),i=n,r=!1;continue}if(o===`\\`){a??=[],a.push(e.slice(i,n-1)),i=n,r=!0;continue}if(o===`"`)return[a?[...a,e.slice(i,n-1)].join(``):e.slice(t,n-1),n]}throw Error(`Unterminated quoted-string.`)}function ut(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 dt(e){return ft(e,He.payment).length>0||e.split(`,`).some(e=>e.trim().toLowerCase()===He.payment.toLowerCase())}function ft(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(!ut(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 pt(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return mt(e.headers,t)}function mt(e,t){let n=e.get(B.wwwAuthenticate);if(!n)throw Error(`Missing ${B.wwwAuthenticate} header.`);return ht(n,t)}function ht(e,t){let n=ft(e,He.payment);if(n.length===0)throw Error(`No Payment schemes found.`);return n.map((r,i)=>{let a=i+1<n.length?n[i+1]:e.length;return at(e.slice(r,a).replace(/,\s*$/,``),t)})}function gt(e){let t=[e.realm,e.method,e.intent,V(e.request),e.expires??``,e.digest??``],n=e.header;return n!==void 0&&!vt(n)&&t.push(n),t.push(e.opaque??(e.meta?V(e.meta):``)),t.join(`|`)}function _t(e){return e.header??B.authorization}function vt(e){return e?.toLowerCase()===B.authorization.toLowerCase()}function yt(e,t){let n=gt(e),r=w.fromString(t.secretKey),i=w.fromString(n),a=T.hmac256(r,i,{as:`Bytes`});return C.fromBytes(a,{url:!0,pad:!1})}const bt=65536;var xt=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},St=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}};function Ct(e){if(e.length>bt)throw new St;let t=e.match(RegExp(`^${He.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new xt;try{let e=C.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=wt(r);return{challenge:nt.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:Je(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new St}}function wt(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!Tt(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:V(e)}}function Tt(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function Et(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function Dt(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:V(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:V(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=C.fromString(s,{pad:!1,url:!0});return`${He.payment} ${c}`}function Ot(e){return e.length>bt?null:e.split(`,`).map(e=>e.trim()).find(e=>RegExp(`^${He.payment}\\s+`,`i`).test(e))??null}var kt=class extends Error{details;status=402;hint;constructor(e,t={}){super(e),this.details=t.details,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},...e&&{challengeId:e}}}},At=class extends kt{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}.`)}},J=class extends kt{name=`VerificationFailedError`;title=`Verification Failed`;type=`https://paymentauth.org/problems/verification-failed`;constructor(e={}){let{details:t,reason:n}=e;super(n?`Payment verification failed: ${n}.`:`Payment verification failed.`,{details:t})}},jt=class extends kt{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.`)}},Mt=class extends kt{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}};function Nt(e,t){if(!e)throw new At({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new At({...t&&{id:t},reason:`malformed expires timestamp`});if(Date.parse(e)<=Date.now())throw new jt({expires:e})}function Pt(e){return e}function Ft(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}function It(e){return{encode(t){return C.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(C.toString(t)))}catch{throw new Lt}}}}var Lt=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}};const Rt=[`exact`],zt=`PAYMENT-REQUIRED`,Bt=`PAYMENT-SIGNATURE`,Vt=H.string().check(H.minLength(1)),Ht=H.number().check(H.refine(e=>e>0,`Must be positive`)),Y=H.string().check(H.regex(/^\d+$/,`Invalid atomic amount`)),Ut=W(),Wt=H.string().check(H.regex(RegExp(`^eip155:\\d+$`),`Invalid EVM CAIP-2 network`)),Gt=H.object({description:H.optional(H.string()),iconUrl:H.optional(H.string()),mimeType:H.optional(H.string()),serviceName:H.optional(H.string()),tags:H.optional(H.array(H.string())),url:Vt});H.discriminatedUnion(`type`,[H.object({name:Vt,type:H.literal(`eip3009`),version:Vt}),H.object({name:H.optional(H.string()),type:H.literal(`permit2`),version:H.optional(H.string())})]);const Kt=H.object({amount:Y,asset:Vt,extra:H.optional(H.record(H.string(),H.unknown())),maxTimeoutSeconds:Ht,network:Wt,payTo:Vt,scheme:H.enum(Rt)}),qt=H.object({info:H.record(H.string(),H.unknown()),schema:H.record(H.string(),H.unknown())}),Jt=H.record(H.string(),qt),Yt=H.object({accepts:H.array(Kt).check(H.minLength(1)),error:H.optional(H.string()),extensions:H.optional(Jt),resource:Gt,x402Version:H.literal(2)}),Xt=H.object({authorization:H.object({from:Ut,nonce:G(),to:Ut,validAfter:Y,validBefore:Y,value:Y}),signature:K()}),Zt=H.object({permit2Authorization:H.object({deadline:Y,from:Ut,nonce:Y,permitted:H.object({amount:Y,token:Ut}),spender:Ut,witness:H.object({to:Ut,validAfter:Y})}),signature:K()}),Qt=H.union([Xt,Zt]),$t=H.object({accepted:Kt,extensions:H.optional(Jt),payload:Qt,resource:H.optional(Gt),x402Version:H.literal(2)});H.object({extensions:H.optional(Jt),extra:H.optional(H.record(H.string(),H.unknown())),invalidMessage:H.optional(H.string()),invalidReason:H.optional(H.string()),isValid:H.boolean(),payer:H.optional(H.string())});const en=H.object({amount:H.optional(Y),errorMessage:H.optional(H.string()),errorReason:H.optional(H.string()),extensions:H.optional(Jt),extra:H.optional(H.record(H.string(),H.unknown())),network:Vt,payer:H.optional(H.string()),success:H.boolean(),transaction:H.string()});function tn(e){let{extensions:t,resource:n,...r}=e;return Kt.parse(r)}const nn=It(Yt),rn=It($t),an=It(en);nn.encode,nn.decode;function on(e){try{let t=JSON.parse(C.toString(e));return cn(t)}catch{throw new Lt}}const sn=rn.encode;rn.decode,an.encode,an.decode;const cn=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new Lt;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new Lt;let n=Gt.parse(t.resource),r=t.extensions===void 0?void 0:Jt.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}};function ln(e){let t=[V(e.accepted),V(e.resource),V(e.extensions)].join(`|`);return T.sha256(w.fromString(t),{as:`Hex`})}async function un(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=tn(n);if(mn(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?gn(n.extensions):n.extensions,o=r.extra?.assetTransferMethod??`eip3009`;if(o!==`eip3009`)throw Error(`x402 exact ${String(o)} signing is not implemented yet.`);let s=r.extra?.name,c=r.extra?.version;if(typeof s!=`string`||typeof c!=`string`)throw Error(`x402 exact EIP-3009 requires token name and version.`);let l=Math.floor(Date.now()/1e3),u={from:a(t.address),nonce:i?.mppx?ln({accepted:r,extensions:i,resource:n.resource}):vn(),to:a(r.payTo),validAfter:(l-600).toString(),validBefore:(l+r.maxTimeoutSeconds).toString(),value:r.amount},d=await t.signTypedData({domain:{chainId:pn(r.network),name:s,verifyingContract:a(r.asset),version:c},message:{...u,value:BigInt(u.value),validAfter:BigInt(u.validAfter),validBefore:BigInt(u.validBefore)},primaryType:`TransferWithAuthorization`,types:fn});return sn({accepted:r,...i?{extensions:i}:{},payload:{authorization:u,signature:d},...n.resource?{resource:n.resource}:{},x402Version:2})}function dn(e){let t=e.challenge.request,n;try{n=tn(t),mn(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 fn={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 pn(e){return Number(e.slice(7))}function mn(e,t){let n=pn(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=>Ae(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=a(t.asset);if(!r.some(n=>Me(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=hn(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>f(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function hn(e,t){let n=e.currencies??e.assets,r=a(t.asset),i=n?.find(e=>Me(e,r,t.network)),o=i?je(i,t.network):void 0;return o?.decimals===void 0?e.decimals:o.decimals}function gn(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:_n()}}}:e}function _n(){return yn().slice(2)}function vn(){return yn()}function yn(){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 bn=Symbol.for(`mppx.x402.challenge`);function xn(e){return Object.defineProperty(e,bn,{value:!0}),e}function Sn(e){return!!e?.[bn]}const Cn=[`authorization`],wn=H.string().check(H.regex(/^\d+$/,`Invalid atomic amount`));H.object({name:H.string().check(H.minLength(1)),version:H.string().check(H.minLength(1))});const Tn=H.object({chainId:H.number(),credentialTypes:H.optional(H.array(H.enum(Cn)).check(H.minLength(1))),decimals:H.optional(H.number()),permit2Address:H.optional(W()),splits:H.optional(H.array(H.object({amount:wn,recipient:W()})))});H.object({amount:wn,currency:W(),description:H.optional(H.string()),externalId:H.optional(H.string()),methodDetails:Tn,recipient:W()});const En=H.object({amount:U(),chainId:H.number(),currency:W(),credentialTypes:H.optional(H.array(H.enum(Cn)).check(H.minLength(1))),decimals:H.number(),description:H.optional(H.string()),externalId:H.optional(H.string()),permit2Address:H.optional(W()),recipient:W(),splits:H.optional(H.array(H.object({amount:wn,recipient:W()})))}),Dn=H.object({from:W(),nonce:G(),signature:K(),to:W(),type:H.literal(`authorization`),validAfter:wn,validBefore:wn,value:wn}),On={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 kn(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function An(e){return T.keccak256(w.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function jn(e){return`eip155:${e}`}function Mn(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const Nn=Pt({name:`evm`,intent:`charge`,schema:{credential:{payload:Dn},request:H.pipe(En,H.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:o,recipient:s,splits:c,...l})=>({...l,amount:f(e,i).toString(),currency:a(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...o?{permit2Address:a(o)}:{},...c?{splits:c}:{}},recipient:a(s)})))}});function Pn(e){return Ft(Nn,{canHandleChallenge({challenge:t}){return!Fn(t)||dn({challenge:t,config:e})},context:H.object({account:H.optional(H.custom())}),async createCredential({challenge:t,context:n}){if(Fn(t))return un({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(In(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 o=Ln(e,i),s=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return Dt(Et({challenge:t,payload:{from:a(r.address),nonce:An(t),signature:await r.signTypedData({domain:kn({authorization:o,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:a(r.address),nonce:An(t),to:a(i.recipient),validAfter:0n,validBefore:BigInt(s),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:On}),to:a(i.recipient),type:`authorization`,validAfter:`0`,validBefore:s,value:i.amount},source:Mn({address:a(r.address),chainId:i.methodDetails.chainId})}))}})}function Fn(e){return Sn(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function In(e,t){let n=t.methodDetails.chainId,r=jn(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=>Ae(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=a(t.currency);if(!i.some(t=>Me(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=Rn(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>f(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function Ln(e,t){let n=e.currencies??e.assets,r=a(t.currency),i=jn(t.methodDetails.chainId),o=n?.find(e=>Me(e,r,i)),s=o?je(o,i):void 0;if(s?.transfer?.type===`eip3009`)return{name:s.transfer.name,version:s.transfer.version};if(e.authorization)return e.authorization;throw Error(`EVM authorization requires token name and version.`)}function Rn(e,t){let n=e.currencies??e.assets,r=a(t.currency),i=jn(t.methodDetails.chainId),o=n?.find(e=>Me(e,r,i)),s=o?je(o,i):void 0;return s?.decimals===void 0?e.decimals:s.decimals}function zn(e){return[zn.charge(e)]}(function(e){e.charge=Pn,e.assets=Ie,e.chains=Le})(zn||={});var Bn=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 Hn(this,e)}},Vn=class extends Bn{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 Hn(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={mainnet:4217,testnet:42431},Un={ousd:I(X.mainnet).address,usdc:a(ee(X.mainnet).address),pathUsd:L(X.mainnet).address},Wn={[X.mainnet]:Un.usdc,[X.testnet]:Un.pathUsd},Gn=Object.freeze({[X.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[X.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})});X.mainnet,X.testnet;const Kn={[X.mainnet]:`https://rpc.tempo.xyz`,[X.testnet]:`https://rpc.moderato.tempo.xyz`},Z=(()=>{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:Z.underline(t)}\x1b]8;;\x07`:t}}})();function qn(e,t){return Z.link(e,t)}function Jn(e){return e.startsWith(`tempo:`)}function Yn(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?Z.dim(Z.link(`${r.explorerUrl}/token/${r.token}`,t,!0)):Z.dim(t);return`${a?`${o}.${a}`:o} ${s}`}const Xn={mainnet:Kn[X.mainnet],testnet:Kn[X.testnet]};function Zn(e,t={}){return e??(t.network?Xn[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}async function Qn(t={}){let n=Zn(t.rpcUrl,{network:t.network});if(!n)return P;let{getChainId:r}=await import(`viem/actions`),i=await r(e({transport:s(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 $n(e){return typeof e==`bigint`?e:e.amount}function er(e){return e.id!==P.id}async function tr(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($n).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 nr(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:1e4}function rr(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function ir(e){return new Vn({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 ar(e){if(e&&rr(e,`secret-tool`))throw ir(e)}function or(e,t){return new Promise(n=>{k.execFile(e,t,{timeout:nr()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function sr(){let e=M.join(process.env.XDG_CONFIG_HOME||M.join(j.homedir(),`.config`),`mppx`,`default`);return{get(){try{return A.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(t){A.mkdirSync(M.dirname(e),{recursive:!0}),A.writeFileSync(e,t,`utf-8`)},clear(){try{A.unlinkSync(e)}catch{}}}}function cr(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:sr().get())}function lr(e=`main`){let t=`mppx`;return{async list(){let e=j.platform();if(e===`darwin`){let{stdout:e,error:n}=await or(`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 or(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(ar(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=j.platform();if(n===`darwin`){let{stdout:n,error:r}=await or(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await or(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return ar(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=j.platform();if(r===`darwin`){await or(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await or(`security`,[`add-generic-password`,`-s`,t,`-a`,e,`-w`,n]);if(r)throw r;return}if(r===`linux`){let r=k.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),nr());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(rr(e,`secret-tool`)?ir(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=j.platform();if(n===`darwin`){await or(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await or(`secret-tool`,[`clear`,`service`,t,`account`,e]);ar(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function ur(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=cr(e),i=await lr(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function dr(e){return(await ur(e)).account}function fr(e){return e}function pr(){return fr({method:`evm`,supports:e=>e.method===`evm`&&!Sn(e),async setup({challenge:t,options:n}){let r=t.request,a=r.methodDetails,o=a?.chainId,c=o?mr(o):void 0,l=r.currency,u=await dr(n.account),d=[...Object.values(we),...Object.values(Te),...Object.values(Ee),...Object.values(De)],f=l??``;if(c&&l)try{let t=e({chain:c,transport:s()}),n=await h(t,{address:l,abi:i,functionName:`symbol`});n&&(f=n)}catch{}return{tokenSymbol:f,tokenDecimals:a?.decimals??6,explorerUrl:c?.blockExplorers?.default?.url,methods:[...zn({account:u,currencies:d})]}}})}function mr(e){return Object.values(b).find(t=>t.id===e)}function hr(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 gr=H.object({customer:H.optional(H.string().check(H.minLength(1))),hooks:H.optional(H.object({inputs:H.object({tax:H.object({calculation:H.string().check(H.minLength(1))})})})),metadata:H.optional(H.record(H.string(),H.string())),receipt_email:H.optional(H.string().check(H.minLength(1)))}),_r=H.custom(e=>typeof e==`function`),vr=H.union([gr,_r]),yr=Pt({name:`stripe`,intent:`charge`,schema:{credential:{payload:H.object({externalId:H.optional(H.string()),spt:H.string()})},request:H.pipe(H.object({amount:U(),currency:H.string(),decimals:H.number(),description:H.optional(H.string()),externalId:H.optional(H.string()),metadata:H.optional(H.record(H.string(),H.string())),networkId:H.string(),paymentIntentOptions:H.optional(vr),paymentMethodTypes:H.array(H.string()).check(H.minLength(1)),recipient:H.optional(H.string())}),H.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:hr(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});function br(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return Ft(yr,{context:H.object({paymentMethod:H.optional(H.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 Dt({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function xr(e){return[br(e)]}(function(e){e.charge=br})(xr||={});function Sr(){return fr({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=wr(N.object({paymentMethod:N.string(),secretKey:N.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new Vn({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:[xr.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=Cr(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 Vn({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${(await d.json()).error.message}`,exitCode:77})}else throw new Vn({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&&Cr(e)?`/test`:``}/payments/${t}`;return Z.link(n,t,!0)}}})}function Cr(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function wr(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 Tr(e,t,n){return async(r,i)=>{let a=new Request(r,i),o=Dr(a.headers)??n?.challenge,{response:s}=await t.send(e,a,{...n,challenge:o});if(s.status===402&&o)for(let e of Er(s))e.method===o.method&&e.intent===o.intent&&await t.challenge(s,{...n,challenge:e},a.url);return s}}function Er(e){try{return pt(e)}catch{return[]}}function Dr(e){for(let[,t]of e){let e=Ot(t);if(e)try{return Ct(e).challenge}catch{}}}function Or(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=Nr(n)}return t}function kr(e,t){let n=Or(e),r=Br(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[Nr(e)]??1,index:t}));return{definition:r,entries:i,header:jr(i),keys:n}}function Ar(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)=>Rr(e,t))}function jr(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${Wr(n)}`}).join(`, `)}function Mr(e,t,n){let r=new Map;for(let e of t){let t=Nr(e),n=r.get(t);n?n.push(e):r.set(t,[e])}return e.flatMap((e,t)=>{let i=r.get(Nr(e));if(!i)return[];let a=Pr(e,n);return!a||a.q<=0?[]:i.filter(t=>t.canHandleChallenge?.({challenge:e})??!0).map(n=>({challenge:e,index:t,match:a,method:n}))}).sort((e,t)=>Lr(e.challenge)-Lr(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function Nr(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function Pr(e,t){let n;for(let r of t){if(!Fr(e,r))continue;let t={...r,specificity:Ir(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 Fr(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function Ir(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function Lr(e){return+!!Sn(e)}function Rr(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}`);Gr(r,`method`),Gr(i,`intent`);let a=1;for(let t of zr(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=Hr(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function zr(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function Br(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>Nr(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]=Vr(t,`payment preference "${e}"`)}return a}function Vr(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return Ur(e,t)}function Hr(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 Ur(Number(e),t)}function Ur(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 Wr(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function Gr(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}const Kr=[B.authorization,zt,`PAYMENT-RESPONSE`,Bt];function qr(e,t,n){let r=new Headers(e.headers);for(let e of Kr)e===B.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}function Jr(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}}const Yr=1048576,Xr=new WeakMap;function Zr(e){let t=Jr(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 Qr(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 $r(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){let t=nt.safeParse(e);if(!t.success)return;n.push(t.data)}let{httpStatus:r,problem:i}=e;return{challenges:n,...typeof r==`number`?{httpStatus:r}:{},...i===void 0?{}:{problem:i}}}function ei(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:$r(e.error.data):$r(e.result?._meta?.[`org.paymentauth/payment-required`])}function ti(e,t){return!e||e.id!==t?[]:ei(e)?.challenges??[]}async function ni(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=le({onEvent(e){if(!(i||!e.data)&&(i=!0,!(e.event&&e.event!==`message`)))try{a=Qr(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()),o.reset({consume:!0}),a;if(r+=s.byteLength,r>Yr)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function ri(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 Qr(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>Yr)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function ii(e){let t=Xr.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>Yr)){if(t.includes(`application/json`))return ri(e);if(t.includes(`text/event-stream`))return ni(e)}})();return Xr.set(e,n),n}function ai(){return{getChallenges(e,t){let n=Zr(t);return e.status===402||n===void 0?[]:ii(e).then(e=>ti(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=Ct(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,"org.paymentauth/credential":r}}})}}}}function oi(){return{getChallenges(e){let t=e.headers.get(B.wwwAuthenticate);return e.status!==402||!t||!dt(t)?[]:pt(e)},setCredential(e,t,n){return qr(e,n?.challenge?_t(n.challenge):B.authorization,t)}}}function si(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(zt);if(!t)return[];let n=on(t);return n.accepts.flatMap((e,t)=>{let r=Kt.safeParse(e);if(!r.success)return[];let i=r.data;return xn(rt({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 qr(e,Bt,t)}}}function ci(e){return e}function li(){let e=[oi(),si(),ai()],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 ci({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 ui=new WeakMap;function di(e,t){return ui.set(e,t),e}function fi(e){return ui.has(e)}function pi(e,t){return Promise.resolve(ui.get(e)?.(t))}function mi(e){return ui.get(e)}const hi=new WeakMap,gi=new WeakMap,_i=new WeakMap;function vi(e,t){return hi.set(e,t),e}function yi(e){hi.delete(e)}function bi(e,t,n){hi.has(e)&&gi.set(t,n)}function xi(e){return gi.get(e)}function Si(e,t){return Promise.resolve(hi.get(e)?.(t)??t.response)}function Ci(e,t){return _i.set(e,t),e}function wi(e,t){try{return _i.get(e)?.(t)}catch{return}}function Ti(e,t,n){if(!Ei(e))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&&Di(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 Ei(e){if(e.method!==`tempo`||e.intent!==`charge`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function Di(e){try{return new URL(e).origin.toLowerCase()}catch{return e.toLowerCase()}}const Oi=Symbol.for(`mppx.fetch.wrapper`),ki=Symbol.for(`mppx.fetch.identity`),Ai=65536,ji=new WeakMap;async function Mi(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>Ai){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,Ai),{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 Ni(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 Pi(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=3,methods:a,onChallenge:o,orderChallenges:s,transport:c=li(),trustedTempoProofRealms:l}=e,u=e.identity??(e.fetch&&ra(e.fetch)),d=e.eventDispatcher??Ii(),f=t??kr(a),p=ia(r),m=async(e,t,n)=>u?(await u.send(p,new Request(e,t),n)).response:p(e,t),h=async(e,t,r)=>{let g=na(e,t?.headers),_=g.has(B.acceptPayment),v=la(g,f),y=ea(e,t,g),b=$i(e,t,g,v.header,_,n),x=await m(aa(b.input),b.init),S=ta(b.init,await y);if(!await c.isPaymentRequired(x,S))return x;let C=t?.context,{context:w,orderChallenges:T,...E}=S??{},D,O,k,A,j;try{for(let n=0;n<i;n++){O=await c.getChallenges(x,S);let i=(await ua(Mr(O,a,v.entries),T??s))[0];if(!i){if(await Ni(A,{challenges:O,response:x,status:`rejected`}),n>0)return x;throw Error(`No method found for challenges: ${O.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`)}let f=i.challenge;D=f,k=i.method,D.expires&&Nt(D.expires,D.id),await u?.challenge(x,{challenge:f},ma(b.input).href);let g=ha(x,b.input,b.input);Ti(f,()=>ma(g),l);let _=A,y=it(f),w=_?.method===i.method&&_?.key===y,M=!1;if(_){let e=await Ni(_,{challenges:O,response:x,status:w?`pending`:`rejected`});M=w&&!e}A=M?_:void 0;let N=Vi(async n=>{if(n===void 0&&M&&_)return _.promise;M&&_&&(await Ni(_,{status:`rejected`}),A=void 0);let r=n??C;if(!fi(i.method))return ca(f,i.method,r);let a={prepare:()=>pi(i.method,{challenge:f,context:r,fetch:u?Tr(p,u,{challenge:f}):p,input:g,signal:oa(e,t)})},o=a.prepare().then(()=>ca(f,i.method,r,a));return A={attempt:a,key:n===void 0?y:void 0,method:i.method,promise:o},o}),P=await d.emit(`challenge.received`,Hi({challenge:f,challenges:O,createCredential:N,init:t,input:e,method:i.method,response:x}))??(o?await o(D,{createCredential:N}):void 0)??await N(),F=A;F&&await F.promise.catch(()=>void 0)!==P&&(await Ni(F,{status:`rejected`}),A=void 0),sa(P),await d.emit(`credential.created`,Ui({challenge:f,credential:P,init:t,input:e,method:i.method,response:x}));let I=e=>new Mt({cause:e,challenge:f,credential:P,transactionHash:wi(i.method,P)});try{x=await m(g,{...c.setCredential({...E,headers:b.headers},P,{challenge:f}),redirect:`manual`},{challenge:f})}catch(e){throw j=I(e),e}let L=await c.isPaymentRequired(x,S);if(L||(await Ni(F,{response:x,status:x.status>=300&&x.status<400?`pending`:x.ok?`accepted`:`rejected`}),A=void 0),x.ok&&Li(d,`payment.response`)&&await d.emit(`payment.response`,Wi({challenge:f,credential:P,init:t,input:e,method:i.method,response:x})),!L){if(x.status>=500&&Li(d,`payment.failed`)){try{x=await Mi(x)}catch(e){throw j=I(e),x=new Response(null,{headers:x.headers,status:x.status,statusText:x.statusText}),e}await d.emit(`payment.failed`,Gi({challenge:f,challenges:O,error:I(),init:t,input:e,method:i.method,response:x}))}return x.ok?Si(i.method,{challenge:f,credential:P,fetch:p,headers:b.headers,input:g,...r?{refetch:()=>h(aa(b.input),t,!1)}:{},response:x,signal:oa(e,t)}):x}}O=void 0;try{O=await c.getChallenges(x,S)}catch{}return await Ni(A,{challenges:O,response:x,status:`rejected`}),x}catch(n){throw await Ni(A,{challenges:O,response:x,status:`rejected`}),await d.emit(`payment.failed`,Gi({challenge:D,challenges:O,error:j??n,init:t,input:e,method:k,response:x})),n}},g=(e,t)=>h(e,t,!0);return g[Oi]=p,u&&(g[ki]=u),g}function Fi(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 Ii(){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 Ri(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await Bi(e[`*`],t,n),r}case`credential.created`:await zi(e[`credential.created`],n),await Bi(e[`*`],t,n);return;case`payment.failed`:await zi(e[`payment.failed`],n),await Bi(e[`*`],t,n);return;case`payment.response`:await zi(e[`payment.response`],n),await Bi(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 ji.set(t,t=>e[t].size>0||e[`*`].size>0),t}function Li(e,t){return ji.get(e)?.(t)??!0}async function Ri(e,t){try{return await e(t)}catch{return}}async function zi(e,t){for(let n of e)try{await n(t)}catch{}}async function Bi(e,t,n){await zi(e,Object.freeze({name:t,payload:n}))}function Vi(e){let t;return n=>(t??=e(n),t)}function Hi(e){return Object.freeze({challenge:Xi(e.challenge),challenges:e.challenges.map(e=>Xi(e)),createCredential:e.createCredential,init:Ki(e.init),input:qi(e.input),method:Ji(e.method),response:Yi(e.response)})}function Ui(e){return Object.freeze({challenge:Xi(e.challenge),credential:e.credential,init:Ki(e.init),input:qi(e.input),method:Ji(e.method),...e.response===void 0?{}:{response:Yi(e.response)}})}function Wi(e){return Object.freeze({challenge:Xi(e.challenge),credential:e.credential,init:Ki(e.init),input:qi(e.input),method:Ji(e.method),response:Yi(e.response)})}function Gi(e){return Object.freeze({...e.challenge?{challenge:Xi(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>Xi(e))}:{},error:e.error,init:Ki(e.init),input:qi(e.input),...e.method?{method:Ji(e.method)}:{},...e.response===void 0?{}:{response:Yi(e.response)}})}function Ki(e){if(e)return Qi({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function qi(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function Ji(e){return Qi(Object.assign({},e))}function Yi(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 Xi(e)}function Xi(e){try{return Zi(structuredClone(e))}catch{return Qi(e)}}function Zi(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Zi(t);return e}function Qi(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function $i(e,t,n,r,i,a){let o=!!r&&!i&&da(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(B.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function ea(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 ta(e,t){return t===void 0?e:{...e,body:t}}function na(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function ra(e){return e[ki]}function ia(e){let t=e;for(;t[Oi];)t=t[Oi];return t}function aa(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function oa(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function sa(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
2
- `))throw Error(`Credential header value contains illegal newline characters`)}async function ca(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&&bi(t,a,r),t.createCredential(a)}function la(e,t){let n=e.get(B.acceptPayment);if(!n)return t;try{return{...t,entries:Ar(n),header:n}}catch{return t}}async function ua(e,t){return t?t(e):e}function da(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=ma(e);return t===`same-origin`?!pa()||n.origin===globalThis.location.origin:t.origins.some(e=>fa(n,e))}function fa(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 pa(){return globalThis.location!==void 0}function ma(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,pa()?globalThis.location.href:void 0)}function ha(e,t,n){if(!e.url)return t;let r=new URL(e.url),i=ma(n);if(r.origin!==i.origin)throw Error(`Refusing to send payment credential across redirect from ${i.origin} to ${r.origin}`);return e.url}function ga(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 se(r)}}function _a(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}const va={[P.id]:P,[F.id]:F};function ya(e,t={}){return s(e.url,{fetchFn:e.fetch,fetchOptions:{headers:_a(e)},...t})}function ba(r){let{chain:i,getClient:a,remoteFeePayer:o,rpcUrl:c}=r;return a?!i?.serializers&&!o?a:async e=>{let r=await a(e),s=r;if(o&&r.transport.key!==`feePayer`){let e=r.request.bind(r),i=oe(n({request:t=>e(t)},{retryCount:0}),ya(o,{retryCount:r.transport.retryCount}))({account:r.account,chain:r.chain,pollingInterval:r.pollingInterval,retryCount:0}),a=t({...i.config,retryCount:0},i.value);s=Object.assign({},r,{request:a.request,transport:{...a.config,...a.value}})}return!i?.serializers||s.chain?.serializers?.transaction?s:Object.assign({},s,{chain:{...i,...e.chainId===void 0?{}:{id:e.chainId},...s.chain,formatters:s.chain?.formatters??i.formatters,prepareTransactionRequest:s.chain?.prepareTransactionRequest??i.prepareTransactionRequest,serializers:s.chain?.serializers?.transaction?s.chain.serializers:i.serializers}})}:({chainId:t})=>{if(!c)throw Error("No `rpcUrl` provided.");let n=t||Number(Object.keys(c)[0]),r=c[n];if(!r)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let a=o?oe(s(r),ya(o)):s(r);return e({chain:va[n]??{...i,id:n},transport:a})}}function xa(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 Sa(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}const Ca=E.slice(T.keccak256(w.fromString(`mpp`),{as:`Hex`}),0,4);function wa(e){let t=T.keccak256(w.fromString(e),{as:`Hex`});return E.toBytes(E.slice(t,0,10))}function Ta(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(E.toBytes(Ca),0),i[4]=1,i.set(wa(t),5),n&&i.set(wa(n),15),i.set(Ea(r),25),E.fromBytes(i)}function Ea(e){let t=T.keccak256(w.fromString(e),{as:`Hex`});return E.toBytes(E.slice(t,0,7))}function Da(e,t){return fe.resolve(e).toLowerCase()===fe.resolve(t).toLowerCase()}const Oa=10000n,ka=[Un.pathUsd,Un.usdc,Un.ousd];async function Aa(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=a.filter(e=>!Da(e,i)),c=await Promise.allSettled([h(e,{...R.token.getBalance.call(e,{account:n,token:i}),account:null}),...s.map(t=>h(e,{...R.token.getBalance.call(e,{account:n,token:t}),account:null}))]),l=c[0];if(l.status!==`fulfilled`)throw l.reason;let u=l.value;if(u>=r)return;let d=r-u,f=BigInt(Math.round(o*100)),p=t.maxAmountIn??d+d*f/Oa;for(let t=0;t<s.length;t++){let n=c[t+1];if(n.status!==`fulfilled`)continue;let r=n.value;if(r<=0n)continue;let a=s[t];try{let t=await R.dex.getBuyQuote(e,{account:null,tokenIn:a,tokenOut:i,amountOut:d});if(t<=0n||t>p)continue;let n=t+t*f/Oa,o=n<p?n:p;if(r>=o)return[R.token.approve.call(e,{amount:o,spender:re.stablecoinDex,token:a}),R.dex.buy.call({tokenIn:a,tokenOut:i,amountOut:d,maxAmountIn:o})]}catch{}}throw new Ma({currency:i})}function ja(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=>Da(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var Ma=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}};function Na(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 Pa(e,t,n){t&&(n&&!n.some(e=>Da(e,t))||e.some(e=>Da(e,t))||e.push(t))}async function Fa(e,t,n){try{return(await R.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function Ia(e){let t=e.chain?.feeToken;if(t)return ie.toAddress(t);let n=e.chain?.id;return n?Wn[n]:void 0}function La(e){let t=[];return Pa(t,Un.pathUsd),Pa(t,Wn[e]),t}async function Ra(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])Pa(o,e,n);if(Pa(o,await R.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),Pa(o,Ia(i),n),!a)for(let e of r??[])Pa(o,e,n);for(let e of o)if(await Fa(i,t,e))return e;return o[0]}const za=d([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`]);function Ba(e){if(e!==void 0)return Gn[e]}function Va(e){let t=Ba(e.chainId);return!!t&&c(e.currency,{strict:!1})&&l(e.currency,t.token)}function Ha(e){let t=Ba(e.chainId),n=e.transfers.length===1?e.transfers[0]:void 0;if(!t||!n?.memo)return;let i=BigInt(n.amount),a=n.memo;return{calls:[{data:r({abi:te.tip20,functionName:`approve`,args:[t.swap,i]}),to:t.token},{data:r({abi:za,functionName:`swapTo`,args:[t.token,i,e.currency,n.recipient,a]}),to:t.swap}],settlementSender:t.swap,transfers:[{amount:i,memo:a,recipient:n.recipient}]}}async function Ua(e,t){let n=Ha(t);if(n)try{return await h(e,R.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await p(e,{account:t.account,calls:n.calls}),n)}catch{return}}const Wa={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]};function Ga(e){return{name:`MPP`,version:`3`,chainId:e}}function Ka(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function qa(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:Ga(n),types:Wa,primaryType:`Proof`,message:Ka({account:t,challengeId:r,realm:i})}}function Ja(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const Ya=[`push`,`pull`],Xa=H.object({amount:U(),memo:H.optional(G()),recipient:H.pipe(H.string(),H.transform(e=>e))}),Za=(1n<<64n)-1n,Qa={dev_second:1n,day:86400n,week:604800n},$a=H.pipe(W(),H.transform(e=>e.toLowerCase())),eo=H.object({accessKeyAddress:$a,keyType:H.enum([`p256`,`secp256k1`,`webAuthn`]),keyToken:H.optional(H.pipe(H.string().check(H.regex(/^0x[0-9a-fA-F]{120}$/)),H.transform(e=>e)))}),to=H.object({accessKey:H.optional(eo),chainId:H.optional(H.number())}),no=Ze(`subscriptionExpires must be a valid date`).check(H.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),ro=H.enum([`dev_second`,`day`,`week`]),io=H.pipe(H.union([H.string(),H.bigint(),H.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),H.transform(e=>e.toString())).check(H.regex(/^[1-9]\d*$/,`Invalid periodCount`),H.refine(e=>{try{return BigInt(e)<=Za}catch{return!1}},`periodCount exceeds uint64`));function ao(e){return H.refine(e=>{let{amount:t,decimals:n}=e;return f(t,n)>0n},e)}function oo(e){let{periodCount:t,periodUnit:n}=e;try{let e=Qa[n];return e!==void 0&&BigInt(t)*e<=Za}catch{return!1}}const so=Pt({name:`tempo`,intent:`charge`,schema:{credential:{payload:H.discriminatedUnion(`type`,[H.object({hash:G(),type:H.literal(`hash`)}),H.object({signature:K(),type:H.literal(`transaction`)}),H.object({signature:K(),type:H.literal(`proof`)})])},request:H.pipe(H.object({machineTokenEnabled:H.optional(H.boolean()),amount:U(),chainId:H.optional(H.number()),currency:H.string(),decimals:H.number(),description:H.optional(H.string()),externalId:H.optional(H.string()),feePayer:H.optional(H.pipe(H.union([H.boolean(),H.custom()]),H.transform(e=>typeof e==`object`||e))),memo:H.optional(H.never()),recipient:H.optional(H.string()),splits:H.optional(H.array(Xa).check(H.minLength(1),H.maxLength(10))),supportedModes:H.optional(H.array(H.enum(Ya)).check(H.minLength(1)))}).check(H.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=f(e,t),i=n.reduce((e,n)=>e+f(n.amount,t),0n);return n.every(e=>f(e.amount,t)>0n)&&i<r},`Invalid splits`)),H.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,...c})=>({...c,amount:f(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==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:f(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s}}}:{}})))}}),co=Pt({name:`tempo`,intent:`session`,schema:{credential:{payload:H.discriminatedUnion(`action`,[H.object({action:H.literal(`open`),authorizedSigner:H.optional(H.string()),channelId:G(),cumulativeAmount:U(),descriptor:H.optional(H.custom()),signature:K(),transaction:K(),type:H.literal(`transaction`)}),H.object({action:H.literal(`topUp`),additionalDeposit:U(),channelId:G(),descriptor:H.optional(H.custom()),transaction:K(),type:H.literal(`transaction`)}),H.object({action:H.literal(`voucher`),channelId:G(),cumulativeAmount:U(),descriptor:H.optional(H.custom()),signature:K()}),H.object({action:H.literal(`close`),channelId:G(),closeSignature:K(),cumulativeAmount:U(),descriptor:H.optional(H.custom()),signature:K()})])},request:H.pipe(H.object({amount:U(),chainId:H.optional(H.number()),channelId:H.optional(G()),currency:H.string(),decimals:H.number(),escrowContract:H.optional(H.string()),feePayer:H.optional(H.pipe(H.union([H.boolean(),H.custom()]),H.transform(e=>typeof e==`object`||e))),feeToken:H.optional(W()),minVoucherDelta:H.optional(U()),operator:H.optional(W()),recipient:H.optional(H.string()),sessionProtocol:H.optional(H.enum([Ke.v2,Ke.v1])),sessionSnapshot:H.optional(H.custom()),suggestedDeposit:H.optional(U()),unitType:H.string()}).check(H.refine(({amount:e,decimals:t})=>f(e,t)>0n,`Session amount must be greater than 0`)),H.transform(({amount:e,chainId:t,channelId:n,decimals:r,escrowContract:i,feePayer:a,feeToken:o,minVoucherDelta:s,operator:c,sessionProtocol:l,sessionSnapshot:u,suggestedDeposit:d,...p})=>({...p,amount:f(e,r).toString(),...d?{suggestedDeposit:f(d,r).toString()}:{},methodDetails:{escrowContract:i,...n!==void 0&&{channelId:n},...s!==void 0&&{minVoucherDelta:f(s,r).toString()},...t!==void 0&&{chainId:t},...a!==void 0&&{feePayer:a},...o!==void 0&&{feeToken:o},...c!==void 0&&{operator:c},...l!==void 0&&{[Ge.sessionProtocol]:l},...u!==void 0&&{[Ge.sessionSnapshot]:u}}})))}}),lo=Pt({name:`tempo`,intent:`subscription`,schema:{credential:{payload:H.object({signature:K(),type:H.literal(`keyAuthorization`)})},request:H.pipe(H.object({amount:U(),accessKey:H.optional(eo),chainId:H.optional(H.number()),currency:$a,decimals:H.number(),description:H.optional(H.string()),externalId:H.optional(H.string()),methodDetails:H.optional(to),periodCount:io,periodUnit:ro,recipient:$a,subscriptionExpires:no}).check(ao(`Subscription amount must be greater than 0`),H.refine(oo,`Subscription period exceeds uint64`)),H.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:f(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}}),uo=H.object({account:H.optional(H.custom()),autoSwap:H.optional(H.custom()),mode:H.optional(H.enum(Ya))});function fo(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.`);let n={maxAmount:mo(e.maxAmount,e.decimals),maxAtomicAmount:e.maxAtomicAmount===void 0?void 0:BigInt(e.maxAtomicAmount)},r=ba({chain:P,getClient:e.getClient,rpcUrl:Kn}),i=ga({account:e.account}),a=Ft(so,{canHandleChallenge({challenge:t}){try{return ho(e,n,t.request),!0}catch{return!1}},context:uo,async createCredential({challenge:a,context:o}){ho(e,n,a.request);let s=a.request.methodDetails?.chainId??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),c=await r({chainId:s});xa(c,s);let l=s??c.chain?.id;if(Sa(e.allowedChainIds,l),l===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");let{request:u}=a,{amount:d,methodDetails:f}=u,p=f?.supportedModes??[`pull`,`push`],h=i(c,o),b=async t=>await e.resolveAccount?.({account:h,chainId:l,operation:t})??h;if(BigInt(d)===0n){let e=await b({kind:`signPaymentProof`});return Dt({challenge:a,payload:{signature:await y(c,{account:e,...qa({account:e.address,chainId:l,challengeId:a.id,realm:a.realm})}),type:`proof`},source:Ja({address:e.address,chainId:l})})}let x=u.currency,S=Va({chainId:l,currency:x}),C=Ta({challengeId:a.id,clientId:t,serverId:a.realm}),w=Na({amount:d,methodDetails:{...f,memo:C},recipient:u.recipient}),T=w.map(e=>R.token.transfer.call(c,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:x})),E=ja(o?.autoSwap??e.autoSwap,ka),D=f?.machineTokenEnabled===!0?Ha({chainId:l,currency:x,transfers:w}):void 0,O=h,k;if(D){let e=await(async()=>{try{return await b({calls:D.calls,kind:`executeCalls`})}catch{return}})();e&&(k=await Ua(c,{account:e.address,chainId:l,currency:x,transfers:w}),k&&(O=e))}let A;k||(O=await b({kind:`executeCalls`,...E?{}:{calls:T}}),A=E?await Aa(c,{account:O.address,amountOut:BigInt(d),tokenOut:x,tokenIn:E.tokenIn,slippage:E.slippage,maxAmountIn:E.maxAmountIn}):void 0);let j=k?.calls??[...A??[],...T],M=La(l),N=k||S?await Ra({account:O.address,allowedTokens:M,candidateTokens:M,client:c,prioritizeCandidates:!0}):void 0,P=(()=>{let t=o?.mode??e.mode;if(t){if(!p.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=O.type===`json-rpc`?`push`:`pull`;return p.includes(n)?n:p[0]})(),F=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!a.expires)return e;let t=Math.floor(new Date(a.expires).getTime()/1e3)+1;return Math.min(e,t)})();if(P===`push`){let{receipts:e}=O.type===`local`?{receipts:[await _(c,{account:O,calls:j,...N?{feeToken:N}:{},nonceKey:`expiring`,validBefore:F})]}:await g(c,{account:O,...N?{capabilities:{feeToken:N}}:{},calls:j,experimental_fallback:j.length===1,forceAtomic:j.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return Dt({challenge:a,payload:{hash:t,type:`hash`},source:Ja({address:O.address,chainId:l})})}let I=()=>{if(f?.feePayer!==!0)return;let e=15e3,t=a.expires?new Date(a.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(!(F*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.`)};I();let L=await m(c,{account:O,calls:j,...N?{feeToken:N}:{},nonceKey:`expiring`,validBefore:F});if(L.gas=(L.gas??0n)+5000n,f?.feePayer){let e=L;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return I(),Dt({challenge:a,payload:{signature:await v(c,L),type:`transaction`},source:Ja({address:O.address,chainId:l})})}}),o=new Map,s=async t=>{ho(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,s=o.get(i);return s||(s=a.createCredential(t).finally(()=>o.delete(i)),o.set(i,s)),s};return Ci({...a,createCredential:s},po)}function po(e){let t=so.schema.credential.payload.safeParse(Ct(e).payload);if(!t.success)return;let n=t.data;if(n.type===`hash`)return n.hash;let r=n.signature;if(n.type!==`transaction`||!r.startsWith(pe.serializedType))return;let i=pe.deserialize(r);if(!(!i.signature||i.feePayerSignature===null)&&pe.serialize(i)===r)return u(r)}function mo(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 f(e,t)}}function ho(e,t,n){let{amount:r,methodDetails:i,recipient:a}=n,o=i?.chainId;if(e.expectedChainId!==void 0&&o!==void 0&&o!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${o}.`);if((o!==void 0||e.allowedChainIds?.length===0)&&Sa(e.allowedChainIds,o),e.currencies&&!e.currencies.some(e=>e.toLowerCase()===n.currency.toLowerCase()))throw Error(`Tempo charge currency is not allowed: ${n.currency}.`);if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase()));if(!a||!t.has(a.toLowerCase()))throw Error(`Unexpected primary recipient: ${a}`);let n=i?.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&&BigInt(r)>t.maxAtomicAmount)throw Error(`Tempo charge amount exceeds maxAtomicAmount.`);if(t.maxAmount!==void 0&&BigInt(r)>t.maxAmount)throw Error(`Tempo charge amount exceeds maxAmount.`)}const go=(1n<<96n)-1n;function _o(e){return e>=0n&&e<=go}function vo(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return _o(t)?t:void 0}function yo(e){return bo(e),e}function bo(e){if(!_o(e))throw Error(`Value ${e} is outside uint96 bounds.`)}const xo=new Set([`open`,`topUp`,`voucher`,`close`]);function So(e){return typeof e==`object`&&!!e}function Co(e){return typeof e==`string`&&xo.has(e)}function wo(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!Co(t.action))}function To(e,t=`No session credential context available.`){if(!wo(e))throw Error(t);return e}function Eo(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function Do(e){return So(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function Oo(e){return So(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 ko(e){let t=C.toString(e),n=JSON.parse(t);if(!Oo(n))throw Error(`Invalid session receipt.`);return n}function Ao(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function jo(e){let t=`message`,n=[];for(let r of e.split(`
1
+ import{createClient as e,createTransport as t,custom as n,encodeFunctionData as r,erc20Abi as i,getAddress as a,hashTypedData as o,http as s,isAddress as c,isAddressEqual as l,keccak256 as u,parseAbi as d,parseUnits as f}from"viem";import{call as p,prepareTransactionRequest as m,readContract as h,sendCallsSync as g,sendTransactionSync as _,signTransaction as v,signTypedData as y}from"viem/actions";import*as b from"viem/chains";import{tempo as x}from"viem/chains";import{AbiParameters as S,Base64 as C,Bytes as w,Hash as T,Hex as E,Json as D}from"ox";import*as O from"zod/mini";import*as k from"node:child_process";import*as A from"node:fs";import*as j from"node:os";import*as M from"node:path";import{z as N}from"zod";import"node:readline";import{tempo as P,tempoModerato as F}from"viem/tempo/chains";import{ousd as ee,pathusd as I,usdce as te}from"viem/tokens";import{Abis as ne,Account as re,Actions as L,Addresses as ie,TokenId as ae,Transaction as oe,withFeePayer as se}from"viem/tempo";import{parseAccount as ce,privateKeyToAccount as le}from"viem/accounts";import{Channel as ue,KeyAuthorization as R,SignatureEnvelope as z,TempoAddress as de,TxEnvelopeTempo as fe}from"ox/tempo";var pe=Object.defineProperty,me=Object.getOwnPropertyDescriptor,he=Object.getOwnPropertyNames,ge=Object.prototype.hasOwnProperty,_e=(e,t)=>{let n={};for(var r in e)pe(n,r,{get:e[r],enumerable:!0});return t||pe(n,Symbol.toStringTag,{value:`Module`}),n},ve=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=he(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ge.call(e,s)&&s!==n&&pe(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=me(t,s))||r.enumerable});return e},ye=(e,t,n)=>(ve(e,t,`default`),n&&ve(n,t,`default`));const be=Symbol(`mppx.x402.asset`);function xe(e){return{[be]:!0,address:e.address,decimals:e.decimals,network:e.network,transfer:e.transfer}}function Se(e,t){let n=e(t.chainId);return xe({address:n.address,decimals:n.decimals,network:Me(t.chainId),transfer:Pe(t.transfer,n)})}const Ce={USDC:xe({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},we={USDC:xe({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},Te={USDC:xe({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:xe({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},Ee={USDC:xe({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})};function De(e){return typeof e!=`object`||!e?!1:e[be]===!0}function Oe(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function ke(e){return typeof e==`string`}function Ae(e,t){if(De(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(Oe(e)){let n=e.addresses[Ne(t)];return n?{address:n,decimals:e.decimals,name:e.name}:void 0}return{address:e}}function je(e,t,n){let r=Ae(e,n);return r?a(r.address)===a(t):!1}function Me(e){return`eip155:${e}`}function Ne(e){return Number(e.slice(7))}function Pe(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 Fe=_e({base:()=>Ce,baseSepolia:()=>we,celo:()=>Te,celoSepolia:()=>Ee,define:()=>xe,fromToken:()=>Se,isAsset:()=>De,isRawAddress:()=>ke,isToken:()=>Oe,matches:()=>je,resolve:()=>Ae,toChainId:()=>Ne,toNetwork:()=>Me}),Ie=_e({base:()=>Le,baseSepolia:()=>Re,celo:()=>ze,celoSepolia:()=>Be});const Le=8453,Re=84532,ze=42220,Be=11142220,B={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},V={payment:`Payment`},Ve={evm:`evm`,stripe:`stripe`,tempo:`tempo`},He={charge:`charge`,session:`session`,subscription:`subscription`},Ue={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},We={v1:`v1`,v2:`v2`};function Ge(e,t){if(!(!e||typeof e!=`object`))return e[t]}function Ke(e){let t=C.toString(e);return JSON.parse(t)}function H(e){let t=D.canonicalize(e);return C.fromString(t,{pad:!1,url:!0})}var U=_e({address:()=>G,amount:()=>W,datetime:()=>Je,datetimeInput:()=>Ye,hash:()=>K,period:()=>Qe,signature:()=>q,toDate:()=>Xe,toDatetimeString:()=>Ze,unwrapOptional:()=>$e});import*as qe from"zod/mini";ye(U,qe);function W(){return O.string().check(O.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function Je(){return O.string().check(O.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 Ye(e=`Invalid ISO 8601 datetime`){return O.pipe(O.union([Je(),O.custom(e=>e instanceof Date)]),O.transform(Xe)).check(O.refine(e=>Number.isFinite(e.getTime()),e))}function Xe(e){return e instanceof Date?e:new Date(e)}function Ze(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function G(){return O.string().check(O.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function K(){return O.string().check(O.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function Qe(){return O.string().check(O.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function q(){return O.string().check(O.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function $e(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}const et=U.object({description:U.optional(U.string()),digest:U.optional(U.string().check(U.regex(/^sha-256=/,`Invalid digest format`))),expires:U.optional(Je()),header:U.optional(U.string().check(U.regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,`Invalid HTTP header name`))),id:U.string().check(U.minLength(1)),intent:U.string(),method:U.string(),meta:U.optional(U.record(U.string(),U.string())),opaque:U.optional(U.string()),realm:U.string(),request:U.record(U.string(),U.unknown())});function tt(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=gt(o)?void 0:o,f=e.expires?Ze(e.expires):void 0,p=e.opaque??(i===void 0?void 0:H(i)),m=u?_t({...e,expires:f,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return et.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}})}function nt(e){let t=[J(`id`,e.id),J(`realm`,e.realm),J(`method`,e.method),J(`intent`,e.intent),J(`request`,H(e.request))];e.description!==void 0&&t.push(J(`description`,e.description)),e.digest!==void 0&&t.push(J(`digest`,e.digest)),e.expires!==void 0&&t.push(J(`expires`,e.expires));let n=e.header;return n!==void 0&&!gt(n)&&t.push(J(`header`,n)),e.opaque===void 0?e.meta!==void 0&&t.push(J(`opaque`,H(e.meta))):t.push(J(`opaque`,e.opaque)),`${V.payment} ${t.join(`, `)}`}function J(e,t){if(/[\r\n]/.test(t))throw Error(`Invalid quoted-string value.`);return`${e}="${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/[\u0100-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}"`}function rt(e,t){let n=it(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,...a}=at(n);if(!r)throw Error(`Missing request parameter.`);if(r.length>16384)throw Error(`Request parameter too large.`);if(a.method&&!/^[a-z][a-z0-9:_-]*$/.test(a.method))throw Error(`Invalid method: "${a.method}". Must be lowercase per spec.`);return tt({...a,request:Ke(r),...i&&{opaque:i}},t)}function it(e){let t=V.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 at(e){let t=Object.create(null),n=0;for(;n<e.length;){for(;n<e.length&&/[\s,]/.test(e[n]??``);)n++;if(n>=e.length)break;let r=n;for(;n<e.length&&/[A-Za-z0-9_-]/.test(e[n]??``);)n++;let i=e.slice(r,n).toLowerCase();if(!i)throw Error(`Malformed auth-param.`);for(;n<e.length&&/\s/.test(e[n]??``);)n++;if(e[n]!==`=`)break;for(n++;n<e.length&&/\s/.test(e[n]??``);)n++;let[a,o]=ot(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function ot(e,t){if(e[t]===`"`)return st(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function st(e,t){let n=t,r=!1,i=t,a;for(;n<e.length;){let o=e[n];if(n++,r){a??=[];let t=o===`u`?e.slice(n,n+4):void 0;t&&/^[0-9A-Fa-f]{4}$/.test(t)?(a.push(String.fromCharCode(Number.parseInt(t,16))),n+=4):a.push(o),i=n,r=!1;continue}if(o===`\\`){a??=[],a.push(e.slice(i,n-1)),i=n,r=!0;continue}if(o===`"`)return[a?[...a,e.slice(i,n-1)].join(``):e.slice(t,n-1),n]}throw Error(`Unterminated quoted-string.`)}function ct(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 lt(e){return ut(e,V.payment).length>0||e.split(`,`).some(e=>e.trim().toLowerCase()===V.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(!ct(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 dt(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return ft(e.headers,t)}function ft(e,t){let n=e.get(B.wwwAuthenticate);if(!n)throw Error(`Missing ${B.wwwAuthenticate} header.`);return pt(n,t)}function pt(e,t){let n=ut(e,V.payment);if(n.length===0)throw Error(`No Payment schemes found.`);return n.map((r,i)=>{let a=i+1<n.length?n[i+1]:e.length;return rt(e.slice(r,a).replace(/,\s*$/,``),t)})}function mt(e){let t=[e.realm,e.method,e.intent,H(e.request),e.expires??``,e.digest??``],n=e.header;return n!==void 0&&!gt(n)&&t.push(n),t.push(e.opaque??(e.meta?H(e.meta):``)),t.join(`|`)}function ht(e){return e.header??B.authorization}function gt(e){return e?.toLowerCase()===B.authorization.toLowerCase()}function _t(e,t){let n=mt(e),r=w.fromString(t.secretKey),i=w.fromString(n),a=T.hmac256(r,i,{as:`Bytes`});return C.fromBytes(a,{url:!0,pad:!1})}const vt=65536;var yt=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},bt=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}};function xt(e){if(e.length>vt)throw new bt;let t=e.match(RegExp(`^${V.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new yt;try{let e=C.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=St(r);return{challenge:et.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:Ke(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new bt}}function St(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!Ct(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:H(e)}}function Ct(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function wt(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function Tt(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:H(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:H(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=C.fromString(s,{pad:!1,url:!0});return`${V.payment} ${c}`}function Et(e){return e.length>vt?null:e.split(`,`).map(e=>e.trim()).find(e=>RegExp(`^${V.payment}\\s+`,`i`).test(e))??null}var Dt=class extends Error{details;status=402;hint;constructor(e,t={}){super(e),this.details=t.details,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},...e&&{challengeId:e}}}},Ot=class extends Dt{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}.`)}},Y=class extends Dt{name=`VerificationFailedError`;title=`Verification Failed`;type=`https://paymentauth.org/problems/verification-failed`;constructor(e={}){let{details:t,reason:n}=e;super(n?`Payment verification failed: ${n}.`:`Payment verification failed.`,{details:t})}},kt=class extends Dt{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.`)}},At=class extends Dt{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}};function jt(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 kt({expires:e})}function Mt(e){return e}function Nt(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}function Pt(e){return{encode(t){return C.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(C.toString(t)))}catch{throw new Ft}}}}var Ft=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}};const It=[`exact`],Lt=`PAYMENT-REQUIRED`,Rt=`PAYMENT-SIGNATURE`,zt=U.string().check(U.minLength(1)),Bt=U.number().check(U.refine(e=>e>0,`Must be positive`)),Vt=U.string().check(U.regex(/^\d+$/,`Invalid atomic amount`)),Ht=G(),Ut=U.string().check(U.regex(RegExp(`^eip155:\\d+$`),`Invalid EVM CAIP-2 network`)),Wt=U.object({description:U.optional(U.string()),iconUrl:U.optional(U.string()),mimeType:U.optional(U.string()),serviceName:U.optional(U.string()),tags:U.optional(U.array(U.string())),url:zt});U.discriminatedUnion(`type`,[U.object({name:zt,type:U.literal(`eip3009`),version:zt}),U.object({name:U.optional(U.string()),type:U.literal(`permit2`),version:U.optional(U.string())})]);const Gt=U.object({amount:Vt,asset:zt,extra:U.optional(U.record(U.string(),U.unknown())),maxTimeoutSeconds:Bt,network:Ut,payTo:zt,scheme:U.enum(It)}),Kt=U.object({info:U.record(U.string(),U.unknown()),schema:U.record(U.string(),U.unknown())}),qt=U.record(U.string(),Kt),Jt=U.object({accepts:U.array(Gt).check(U.minLength(1)),error:U.optional(U.string()),extensions:U.optional(qt),resource:Wt,x402Version:U.literal(2)}),Yt=U.object({authorization:U.object({from:Ht,nonce:K(),to:Ht,validAfter:Vt,validBefore:Vt,value:Vt}),signature:q()}),Xt=U.object({permit2Authorization:U.object({deadline:Vt,from:Ht,nonce:Vt,permitted:U.object({amount:Vt,token:Ht}),spender:Ht,witness:U.object({to:Ht,validAfter:Vt})}),signature:q()}),Zt=U.union([Yt,Xt]),Qt=U.object({accepted:Gt,extensions:U.optional(qt),payload:Zt,resource:U.optional(Wt),x402Version:U.literal(2)});U.object({extensions:U.optional(qt),extra:U.optional(U.record(U.string(),U.unknown())),invalidMessage:U.optional(U.string()),invalidReason:U.optional(U.string()),isValid:U.boolean(),payer:U.optional(U.string())});const $t=U.object({amount:U.optional(Vt),errorMessage:U.optional(U.string()),errorReason:U.optional(U.string()),extensions:U.optional(qt),extra:U.optional(U.record(U.string(),U.unknown())),network:zt,payer:U.optional(U.string()),success:U.boolean(),transaction:U.string()});function en(e){let{extensions:t,resource:n,...r}=e;return Gt.parse(r)}const tn=Pt(Jt),nn=Pt(Qt),rn=Pt($t);tn.encode,tn.decode;function an(e){try{let t=JSON.parse(C.toString(e));return sn(t)}catch{throw new Ft}}const on=nn.encode;nn.decode,rn.encode,rn.decode;const sn=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new Ft;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new Ft;let n=Wt.parse(t.resource),r=t.extensions===void 0?void 0:qt.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}};function cn(e){let t=[H(e.accepted),H(e.resource),H(e.extensions)].join(`|`);return T.sha256(w.fromString(t),{as:`Hex`})}async function ln(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=en(n);if(pn(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?hn(n.extensions):n.extensions,o=r.extra?.assetTransferMethod??`eip3009`;if(o!==`eip3009`)throw Error(`x402 exact ${String(o)} signing is not implemented yet.`);let s=r.extra?.name,c=r.extra?.version;if(typeof s!=`string`||typeof c!=`string`)throw Error(`x402 exact EIP-3009 requires token name and version.`);let l=Math.floor(Date.now()/1e3),u={from:a(t.address),nonce:i?.mppx?cn({accepted:r,extensions:i,resource:n.resource}):_n(),to:a(r.payTo),validAfter:(l-600).toString(),validBefore:(l+r.maxTimeoutSeconds).toString(),value:r.amount},d=await t.signTypedData({domain:{chainId:fn(r.network),name:s,verifyingContract:a(r.asset),version:c},message:{...u,value:BigInt(u.value),validAfter:BigInt(u.validAfter),validBefore:BigInt(u.validBefore)},primaryType:`TransferWithAuthorization`,types:dn});return on({accepted:r,...i?{extensions:i}:{},payload:{authorization:u,signature:d},...n.resource?{resource:n.resource}:{},x402Version:2})}function un(e){let t=e.challenge.request,n;try{n=en(t),pn(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 dn={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 fn(e){return Number(e.slice(7))}function pn(e,t){let n=fn(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=>ke(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=a(t.asset);if(!r.some(n=>je(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=mn(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>f(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function mn(e,t){let n=e.currencies??e.assets,r=a(t.asset),i=n?.find(e=>je(e,r,t.network)),o=i?Ae(i,t.network):void 0;return o?.decimals===void 0?e.decimals:o.decimals}function hn(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:gn()}}}:e}function gn(){return vn().slice(2)}function _n(){return vn()}function vn(){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 yn=Symbol.for(`mppx.x402.challenge`);function bn(e){return Object.defineProperty(e,yn,{value:!0}),e}function xn(e){return!!e?.[yn]}const Sn=[`authorization`],Cn=U.string().check(U.regex(/^\d+$/,`Invalid atomic amount`));U.object({name:U.string().check(U.minLength(1)),version:U.string().check(U.minLength(1))});const wn=U.object({chainId:U.number(),credentialTypes:U.optional(U.array(U.enum(Sn)).check(U.minLength(1))),decimals:U.optional(U.number()),permit2Address:U.optional(G()),splits:U.optional(U.array(U.object({amount:Cn,recipient:G()})))});U.object({amount:Cn,currency:G(),description:U.optional(U.string()),externalId:U.optional(U.string()),methodDetails:wn,recipient:G()});const Tn=U.object({amount:W(),chainId:U.number(),currency:G(),credentialTypes:U.optional(U.array(U.enum(Sn)).check(U.minLength(1))),decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),permit2Address:U.optional(G()),recipient:G(),splits:U.optional(U.array(U.object({amount:Cn,recipient:G()})))}),En=U.object({from:G(),nonce:K(),signature:q(),to:G(),type:U.literal(`authorization`),validAfter:Cn,validBefore:Cn,value:Cn}),Dn={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 On(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function kn(e){return T.keccak256(w.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function An(e){return`eip155:${e}`}function jn(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const Mn=Mt({name:`evm`,intent:`charge`,schema:{credential:{payload:En},request:U.pipe(Tn,U.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:o,recipient:s,splits:c,...l})=>({...l,amount:f(e,i).toString(),currency:a(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...o?{permit2Address:a(o)}:{},...c?{splits:c}:{}},recipient:a(s)})))}});function Nn(e){return Nt(Mn,{canHandleChallenge({challenge:t}){return!Pn(t)||un({challenge:t,config:e})},context:U.object({account:U.optional(U.custom())}),async createCredential({challenge:t,context:n}){if(Pn(t))return ln({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(Fn(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 o=In(e,i),s=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return Tt(wt({challenge:t,payload:{from:a(r.address),nonce:kn(t),signature:await r.signTypedData({domain:On({authorization:o,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:a(r.address),nonce:kn(t),to:a(i.recipient),validAfter:0n,validBefore:BigInt(s),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:Dn}),to:a(i.recipient),type:`authorization`,validAfter:`0`,validBefore:s,value:i.amount},source:jn({address:a(r.address),chainId:i.methodDetails.chainId})}))}})}function Pn(e){return xn(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function Fn(e,t){let n=t.methodDetails.chainId,r=An(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=>ke(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=a(t.currency);if(!i.some(t=>je(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=Ln(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>f(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function In(e,t){let n=e.currencies??e.assets,r=a(t.currency),i=An(t.methodDetails.chainId),o=n?.find(e=>je(e,r,i)),s=o?Ae(o,i):void 0;if(s?.transfer?.type===`eip3009`)return{name:s.transfer.name,version:s.transfer.version};if(e.authorization)return e.authorization;throw Error(`EVM authorization requires token name and version.`)}function Ln(e,t){let n=e.currencies??e.assets,r=a(t.currency),i=An(t.methodDetails.chainId),o=n?.find(e=>je(e,r,i)),s=o?Ae(o,i):void 0;return s?.decimals===void 0?e.decimals:s.decimals}function Rn(e){return[Rn.charge(e)]}(function(e){e.charge=Nn,e.assets=Fe,e.chains=Ie})(Rn||={});var zn=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 Vn(this,e)}},Bn=class extends zn{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 Vn(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={mainnet:4217,testnet:42431},Hn={ousd:ee(X.mainnet).address,usdc:a(te(X.mainnet).address),pathUsd:I(X.mainnet).address},Un={[X.mainnet]:Hn.usdc,[X.testnet]:Hn.pathUsd},Wn=Object.freeze({[X.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[X.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})});X.mainnet,X.testnet;const Gn={[X.mainnet]:`https://rpc.tempo.xyz`,[X.testnet]:`https://rpc.moderato.tempo.xyz`},Z=(()=>{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:Z.underline(t)}\x1b]8;;\x07`:t}}})();function Kn(e,t){return Z.link(e,t)}function qn(e){return e.startsWith(`tempo:`)}function Jn(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?Z.dim(Z.link(`${r.explorerUrl}/token/${r.token}`,t,!0)):Z.dim(t);return`${a?`${o}.${a}`:o} ${s}`}const Yn={mainnet:Gn[X.mainnet],testnet:Gn[X.testnet]};function Xn(e,t={}){return e??(t.network?Yn[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}async function Zn(t={}){let n=Xn(t.rpcUrl,{network:t.network});if(!n)return P;let{getChainId:r}=await import(`viem/actions`),i=await r(e({transport:s(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 Qn(e){return typeof e==`bigint`?e:e.amount}function $n(e){return e.id!==P.id}async function er(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(Qn).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 tr(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:1e4}function nr(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function rr(e){return new Bn({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 ir(e){if(e&&nr(e,`secret-tool`))throw rr(e)}function ar(e,t){return new Promise(n=>{k.execFile(e,t,{timeout:tr()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function or(){let e=M.join(process.env.XDG_CONFIG_HOME||M.join(j.homedir(),`.config`),`mppx`,`default`);return{get(){try{return A.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(t){A.mkdirSync(M.dirname(e),{recursive:!0}),A.writeFileSync(e,t,`utf-8`)},clear(){try{A.unlinkSync(e)}catch{}}}}function sr(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:or().get())}function cr(e=`main`){let t=`mppx`;return{async list(){let e=j.platform();if(e===`darwin`){let{stdout:e,error:n}=await ar(`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 ar(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(ir(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=j.platform();if(n===`darwin`){let{stdout:n,error:r}=await ar(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await ar(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return ir(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=j.platform();if(r===`darwin`){await ar(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await ar(`security`,[`add-generic-password`,`-s`,t,`-a`,e,`-w`,n]);if(r)throw r;return}if(r===`linux`){let r=k.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),tr());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(nr(e,`secret-tool`)?rr(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=j.platform();if(n===`darwin`){await ar(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await ar(`secret-tool`,[`clear`,`service`,t,`account`,e]);ir(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function lr(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=sr(e),i=await cr(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function ur(e){return(await lr(e)).account}function dr(e){return e}function fr(){return dr({method:`evm`,supports:e=>e.method===`evm`&&!xn(e),async setup({challenge:t,options:n}){let r=t.request,a=r.methodDetails,o=a?.chainId,c=o?pr(o):void 0,l=r.currency,u=await ur(n.account),d=[...Object.values(Ce),...Object.values(we),...Object.values(Te),...Object.values(Ee)],f=l??``;if(c&&l)try{let t=e({chain:c,transport:s()}),n=await h(t,{address:l,abi:i,functionName:`symbol`});n&&(f=n)}catch{}return{tokenSymbol:f,tokenDecimals:a?.decimals??6,explorerUrl:c?.blockExplorers?.default?.url,methods:[...Rn({account:u,currencies:d})]}}})}function pr(e){return Object.values(b).find(t=>t.id===e)}function mr(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 hr=U.object({customer:U.optional(U.string().check(U.minLength(1))),hooks:U.optional(U.object({inputs:U.object({tax:U.object({calculation:U.string().check(U.minLength(1))})})})),metadata:U.optional(U.record(U.string(),U.string())),receipt_email:U.optional(U.string().check(U.minLength(1)))}),gr=U.custom(e=>typeof e==`function`),_r=U.union([hr,gr]),vr=Mt({name:`stripe`,intent:`charge`,schema:{credential:{payload:U.object({externalId:U.optional(U.string()),spt:U.string()})},request:U.pipe(U.object({amount:W(),currency:U.string(),decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),metadata:U.optional(U.record(U.string(),U.string())),networkId:U.string(),paymentIntentOptions:U.optional(_r),paymentMethodTypes:U.array(U.string()).check(U.minLength(1)),recipient:U.optional(U.string())}),U.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:mr(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});function yr(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return Nt(vr,{context:U.object({paymentMethod:U.optional(U.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 Tt({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function br(e){return[yr(e)]}(function(e){e.charge=yr})(br||={});function xr(){return dr({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=Cr(N.object({paymentMethod:N.string(),secretKey:N.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new Bn({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:[br.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=Sr(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 Bn({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${(await d.json()).error.message}`,exitCode:77})}else throw new Bn({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&&Sr(e)?`/test`:``}/payments/${t}`;return Z.link(n,t,!0)}}})}function Sr(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function Cr(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 wr=Symbol.for(`mppx.fetch.skipPayment`);function Tr(e,t,n){return async(r,i)=>{let a=new Request(r,i),o=Dr(a.headers)??n?.challenge,{response:s}=await t.send((t,n)=>e(t,{...n,...i?.[wr]?{[wr]:!0}:{}}),a,{...n,challenge:o});if(s.status===402&&o)for(let e of Er(s))e.method===o.method&&e.intent===o.intent&&await t.challenge(s,{...n,challenge:e},a.url);return s}}function Er(e){try{return dt(e)}catch{return[]}}function Dr(e){for(let[,t]of e){let e=Et(t);if(e)try{return xt(e).challenge}catch{}}}const Or=Symbol(`mppx.deferredContext`);function kr(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=Pr(n)}return t}function Ar(e,t){let n=kr(e),r=Vr(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[Pr(e)]??1,index:t}));return{definition:r,entries:i,header:Mr(i),keys:n}}function jr(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)=>zr(e,t))}function Mr(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${Gr(n)}`}).join(`, `)}function Nr(e,t,n,r){let i=new Map;for(let e of t){let t=Pr(e),n=i.get(t);n?n.push(e):i.set(t,[e])}return e.flatMap((e,t)=>{let a=i.get(Pr(e));if(!a)return[];let o=Fr(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)=>Rr(e.challenge)-Rr(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function Pr(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function Fr(e,t){let n;for(let r of t){if(!Ir(e,r))continue;let t={...r,specificity:Lr(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 Ir(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function Lr(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function Rr(e){return+!!xn(e)}function zr(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}`);Kr(r,`method`),Kr(i,`intent`);let a=1;for(let t of Br(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=Ur(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function Br(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function Vr(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>Pr(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]=Hr(t,`payment preference "${e}"`)}return a}function Hr(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return Wr(e,t)}function Ur(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 Wr(Number(e),t)}function Wr(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 Gr(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function Kr(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}function qr(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}if(t.startsWith(`:`))return;let n=t.indexOf(`:`),r=n===-1?t:t.slice(0,n),o=n===-1?``:t.slice(n+1);o.startsWith(` `)&&(o=o.slice(1)),r===`data`?i=i===void 0?o:`${i}\n${o}`:r===`event`&&(a=o)}return{feed(e){if(!n&&e&&(n=!0,e.startsWith(``)&&(e=e.slice(1))),r&&e&&(r=!1,e.startsWith(`
2
+ `)&&(e=e.slice(1))),t+=e,!/[\r\n]/.test(e))return;let i=0,a=/\r\n?|\n/g;for(let e=a.exec(t);e;e=a.exec(t))o(t.slice(i,e.index)),i=a.lastIndex,e[0]===`\r`&&i===t.length&&(r=!0);t=t.slice(i)}}}const Jr=[B.authorization,Lt,`PAYMENT-RESPONSE`,Rt];function Yr(e,t,n){let r=new Headers(e.headers);for(let e of Jr)e===B.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}function Xr(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 Zr(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 Qr=1048576,$r=new WeakMap;function ei(e){let t=Xr(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 ti(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 ni(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){let t=et.safeParse(e);if(!t.success)return;n.push(t.data)}let{httpStatus:r,problem:i}=e;return{challenges:n,...typeof r==`number`?{httpStatus:r}:{},...i===void 0?{}:{problem:i}}}function ri(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:ni(e.error.data):ni(e.result?._meta?.[`org.paymentauth/payment-required`])}function ii(e,t){return!e||e.id!==t?[]:ri(e)?.challenges??[]}async function ai(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=qr(e=>{if(!(i||!e.data)&&(i=!0,e.event===`message`))try{a=ti(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>Qr)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function oi(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 ti(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>Qr)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function si(e){let t=$r.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>Qr)){if(t.includes(`application/json`))return oi(e);if(t.includes(`text/event-stream`))return ai(e)}})();return $r.set(e,n),n}function ci(){return{getChallenges(e,t){let n=ei(t);return e.status===402||n===void 0?[]:si(e).then(e=>ii(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=xt(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,"org.paymentauth/credential":r}}})}}}}function li(){return{getChallenges(e){let t=e.headers.get(B.wwwAuthenticate);return e.status!==402||!t||!lt(t)?[]:dt(e)},setCredential(e,t,n){return Yr(e,n?.challenge?ht(n.challenge):B.authorization,t)}}}function ui(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(Lt);if(!t)return[];let n=an(t);return n.accepts.flatMap((e,t)=>{let r=Gt.safeParse(e);if(!r.success)return[];let i=r.data;return bn(tt({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 Yr(e,Rt,t)}}}function di(e){return e}function fi(){let e=[li(),ui(),ci()],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 di({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 pi=new WeakMap;function mi(e,t){return pi.set(e,t),e}function hi(e){return pi.has(e)}function gi(e,t){return Promise.resolve(pi.get(e)?.(t))}function _i(e){return pi.get(e)}const vi=new WeakMap,yi=new WeakMap,bi=new WeakMap,xi=new WeakMap;function Si(e,t){return vi.set(e,t),e}function Ci(e){vi.delete(e)}function wi(e,t,n){vi.has(e)&&yi.set(t,n)}function Ti(e){return yi.get(e)}function Ei(e,t){return Promise.resolve(vi.get(e)?.(t)??t.response)}function Di(e,t){return xi.set(e,t),e}function Oi(e,t){try{return xi.get(e)?.(t)}catch{return}}function ki(e,t){bi.set(e,t)}function Ai(e){return bi.get(e)??yi.get(e)?.origin}function ji(e,t,n){if(!Mi(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&&Ni(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 Mi(e){if(e.method!==`tempo`||e.intent!==`charge`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function Ni(e){try{return new URL(e).origin.toLowerCase()}catch{return e.toLowerCase()}}const Pi=Symbol.for(`mppx.fetch.wrapper`),Fi=Symbol.for(`mppx.fetch.identity`),Ii=Symbol.for(`mppx.fetch.skipPayment`),Li=65536,Ri=new WeakMap;async function zi(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>Li){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,Li),{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 Bi(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 Vi(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=3,methods:a,onChallenge:o,orderChallenges:s,transport:c=fi(),trustedTempoProofRealms:l}=e,u=e.identity??(e.fetch&&ua(e.fetch)),d=e.eventDispatcher??Ui(),f=t??Ar(a),p=da(r),m=async(e,t,n)=>u?(await u.send(p,new Request(e,t),n)).response:p(e,t),h=async(e,t,r)=>{let g=la(e,t?.headers),_=g.has(B.acceptPayment),v=ga(g,f),y=sa(e,t,g),b=oa(e,t,g,v.header,_,n),x=await m(fa(b.input),b.init),S=ca(b.init,await y);if(t?.[Ii]||Zr(S)||!await c.isPaymentRequired(x,S))return x;let C=t?.context,{context:w,orderChallenges:T,...E}=S??{},D,O,k,A,j;try{for(let n=0;n<i;n++){O=await c.getChallenges(x,S);let i=(await _a(Nr(O,a,v.entries,C),T??s))[0];if(!i){if(await Bi(A,{challenges:O,response:x,status:`rejected`}),n>0)return x;throw Error(`No method found for challenges: ${O.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`)}let f=i.challenge;D=f,k=i.method,D.expires&&jt(D.expires,D.id),await u?.challenge(x,{challenge:f},xa(b.input).href);let g=await Ca(x,b.input,b.input,E);ji(f,()=>xa(g),l);let _=A,y=nt(f),w=_?.method===i.method&&_?.key===y,M=!1;if(_){let e=await Bi(_,{challenges:O,response:x,status:w?`pending`:`rejected`});M=w&&!e}A=M?_:void 0;let N=Ji(async n=>{if(n===void 0&&M&&_)return _.promise;M&&_&&(await Bi(_,{status:`rejected`}),A=void 0),pa(e,t)?.throwIfAborted();let r=n??C;if(!hi(i.method))return ha(f,i.method,r);let a={origin:xa(g).origin,prepare:()=>gi(i.method,{challenge:f,context:r,fetch:u?Tr(p,u,{challenge:f}):p,input:g,signal:pa(e,t)})},o=a.prepare().then(()=>ha(f,i.method,r,a));return A={context:r,attempt:a,key:n===void 0?y:void 0,method:i.method,promise:o},o}),P=await d.emit(`challenge.received`,Yi({challenge:f,challenges:O,createCredential:N,init:t,input:e,method:i.method,response:x}))??(o?await o(D,{createCredential:N}):void 0)??await N(),F=A;F&&await F.promise.catch(()=>void 0)!==P&&(await Bi(F,{status:`rejected`}),A=void 0);let ee=A?A.context:C;ma(P),await d.emit(`credential.created`,Xi({challenge:f,credential:P,init:t,input:e,method:i.method,response:x}));let I=e=>new At({cause:e,challenge:f,credential:P,transactionHash:Oi(i.method,P)});try{x=await m(g,{...c.setCredential({...E,headers:b.headers},P,{challenge:f}),redirect:`manual`},{challenge:f})}catch(e){throw j=I(e),e}let te=await c.isPaymentRequired(x,S);if(te||(await Bi(F,{response:x,status:x.status>=300&&x.status<400?`pending`:x.ok?`accepted`:`rejected`}),A=void 0),x.ok&&Wi(d,`payment.response`)&&await d.emit(`payment.response`,Zi({challenge:f,credential:P,init:t,input:e,method:i.method,response:x})),!te){if(x.status>=500&&Wi(d,`payment.failed`)){try{x=await zi(x)}catch(e){throw j=I(e),x=new Response(null,{headers:x.headers,status:x.status,statusText:x.statusText}),e}await d.emit(`payment.failed`,Qi({challenge:f,challenges:O,error:I(),init:t,input:e,method:i.method,response:x}))}return x.ok?Ei(i.method,{context:ee,challenge:f,credential:P,fetch:p,headers:b.headers,input:g,...r?{refetch:()=>h(fa(b.input),t,!1)}:{},response:x,signal:pa(e,t)}):x}}O=void 0;try{O=await c.getChallenges(x,S)}catch{}return await Bi(A,{challenges:O,response:x,status:`rejected`}),x}catch(n){throw await Bi(A,{challenges:O,response:x,status:`rejected`}),await d.emit(`payment.failed`,Qi({challenge:D,challenges:O,error:j??n,init:t,input:e,method:k,response:x})),n}},g=(e,t)=>h(e,t,!0);return g[Pi]=p,u&&(g[Fi]=u),g}function Hi(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 Ui(){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 Gi(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await qi(e[`*`],t,n),r}case`credential.created`:await Ki(e[`credential.created`],n),await qi(e[`*`],t,n);return;case`payment.failed`:await Ki(e[`payment.failed`],n),await qi(e[`*`],t,n);return;case`payment.response`:await Ki(e[`payment.response`],n),await qi(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 Ri.set(t,t=>e[t].size>0||e[`*`].size>0),t}function Wi(e,t){return Ri.get(e)?.(t)??!0}async function Gi(e,t){try{return await e(t)}catch{return}}async function Ki(e,t){for(let n of e)try{await n(t)}catch{}}async function qi(e,t,n){await Ki(e,Object.freeze({name:t,payload:n}))}function Ji(e){let t;return n=>(t??=e(n),t)}function Yi(e){return Object.freeze({challenge:ra(e.challenge),challenges:e.challenges.map(e=>ra(e)),createCredential:e.createCredential,init:$i(e.init),input:ea(e.input),method:ta(e.method),response:na(e.response)})}function Xi(e){return Object.freeze({challenge:ra(e.challenge),credential:e.credential,init:$i(e.init),input:ea(e.input),method:ta(e.method),...e.response===void 0?{}:{response:na(e.response)}})}function Zi(e){return Object.freeze({challenge:ra(e.challenge),credential:e.credential,init:$i(e.init),input:ea(e.input),method:ta(e.method),response:na(e.response)})}function Qi(e){return Object.freeze({...e.challenge?{challenge:ra(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>ra(e))}:{},error:e.error,init:$i(e.init),input:ea(e.input),...e.method?{method:ta(e.method)}:{},...e.response===void 0?{}:{response:na(e.response)}})}function $i(e){if(e)return aa({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function ea(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function ta(e){return aa(Object.assign({},e))}function na(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 ra(e)}function ra(e){try{return ia(structuredClone(e))}catch{return aa(e)}}function ia(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))ia(t);return e}function aa(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function oa(e,t,n,r,i,a){let o=!!r&&!i&&va(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(B.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function sa(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 ca(e,t){return t===void 0?e:{...e,body:t}}function la(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function ua(e){return e[Fi]}function da(e){let t=e;for(;t[Pi];)t=t[Pi];return t}function fa(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function pa(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function ma(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
3
+ `))throw Error(`Credential header value contains illegal newline characters`)}async function ha(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&&ki(a,r.origin),r&&wi(t,a,r),t.createCredential(a)}function ga(e,t){let n=e.get(B.acceptPayment);if(!n)return t;try{return{...t,entries:jr(n),header:n}}catch{return t}}async function _a(e,t){return t?t(e):e}function va(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=xa(e);return t===`same-origin`?!ba()||n.origin===globalThis.location.origin:t.origins.some(e=>ya(n,e))}function ya(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 ba(){return globalThis.location!==void 0}function xa(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,ba()?globalThis.location.href:void 0)}function Sa(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 Ca(e,t,n,r){if(Sa(t,r),!e.url)return t;let i=new URL(e.url),a=xa(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 wa(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 ce(r)}}function Ta(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}const Ea={[P.id]:P,[F.id]:F};function Da(e,t={}){return s(e.url,{fetchFn:e.fetch,fetchOptions:{headers:Ta(e)},...t})}function Oa(r){let{chain:i,getClient:a,remoteFeePayer:o,rpcUrl:c}=r;return a?!i?.serializers&&!o?a:async e=>{let r=await a(e),s=r;if(o&&r.transport.key!==`feePayer`){let e=r.request.bind(r),i=se(n({request:t=>e(t)},{retryCount:0}),Da(o,{retryCount:r.transport.retryCount}))({account:r.account,chain:r.chain,pollingInterval:r.pollingInterval,retryCount:0}),a=t({...i.config,retryCount:0},i.value);s=Object.assign({},r,{request:a.request,transport:{...a.config,...a.value}})}return!i?.serializers||s.chain?.serializers?.transaction?s:Object.assign({},s,{chain:{...i,...e.chainId===void 0?{}:{id:e.chainId},...s.chain,formatters:s.chain?.formatters??i.formatters,prepareTransactionRequest:s.chain?.prepareTransactionRequest??i.prepareTransactionRequest,serializers:s.chain?.serializers?.transaction?s.chain.serializers:i.serializers}})}:({chainId:t})=>{if(!c)throw Error("No `rpcUrl` provided.");let n=t||Number(Object.keys(c)[0]),r=c[n];if(!r)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let a=o?se(s(r),Da(o)):s(r);return e({chain:Ea[n]??{...i,id:n},transport:a})}}function ka(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 Aa(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}const ja=E.slice(T.keccak256(w.fromString(`mpp`),{as:`Hex`}),0,4);function Ma(e){let t=T.keccak256(w.fromString(e),{as:`Hex`});return E.toBytes(E.slice(t,0,10))}function Na(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(E.toBytes(ja),0),i[4]=1,i.set(Ma(t),5),n&&i.set(Ma(n),15),i.set(Pa(r),25),E.fromBytes(i)}function Pa(e){let t=T.keccak256(w.fromString(e),{as:`Hex`});return E.toBytes(E.slice(t,0,7))}function Fa(e,t){return de.resolve(e).toLowerCase()===de.resolve(t).toLowerCase()}const Ia=10000n,La=[Hn.pathUsd,Hn.usdc,Hn.ousd];async function Ra(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=a.filter(e=>!Fa(e,i)),c=await Promise.allSettled([h(e,{...L.token.getBalance.call(e,{account:n,token:i}),account:null}),...s.map(t=>h(e,{...L.token.getBalance.call(e,{account:n,token:t}),account:null}))]),l=c[0];if(l.status!==`fulfilled`)throw l.reason;let u=l.value;if(u>=r)return;let d=r-u,f=BigInt(Math.round(o*100)),p=t.maxAmountIn??d+d*f/Ia;for(let t=0;t<s.length;t++){let n=c[t+1];if(n.status!==`fulfilled`)continue;let r=n.value;if(r<=0n)continue;let a=s[t];try{let t=await L.dex.getBuyQuote(e,{account:null,tokenIn:a,tokenOut:i,amountOut:d});if(t<=0n||t>p)continue;let n=t+t*f/Ia,o=n<p?n:p;if(r>=o)return[L.token.approve.call(e,{amount:o,spender:ie.stablecoinDex,token:a}),L.dex.buy.call({tokenIn:a,tokenOut:i,amountOut:d,maxAmountIn:o})]}catch{}}throw new Ba({currency:i})}function za(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=>Fa(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var Ba=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}};function Va(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 Ha(e,t,n){t&&(n&&!n.some(e=>Fa(e,t))||e.some(e=>Fa(e,t))||e.push(t))}async function Ua(e,t,n){try{return(await L.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function Wa(e){let t=e.chain?.feeToken;if(t)return ae.toAddress(t);let n=e.chain?.id;return n?Un[n]:void 0}function Ga(e){let t=[];return Ha(t,Hn.pathUsd),Ha(t,Un[e]),t}async function Ka(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])Ha(o,e,n);if(Ha(o,await L.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),Ha(o,Wa(i),n),!a)for(let e of r??[])Ha(o,e,n);for(let e of o)if(await Ua(i,t,e))return e;return o[0]}const qa=d([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`]);function Ja(e){if(e!==void 0)return Wn[e]}function Ya(e){let t=Ja(e.chainId);return!!t&&c(e.currency,{strict:!1})&&l(e.currency,t.token)}function Xa(e){let t=Ja(e.chainId),n=e.transfers.length===1?e.transfers[0]:void 0;if(!t||!n?.memo)return;let i=BigInt(n.amount),a=n.memo;return{calls:[{data:r({abi:ne.tip20,functionName:`approve`,args:[t.swap,i]}),to:t.token},{data:r({abi:qa,functionName:`swapTo`,args:[t.token,i,e.currency,n.recipient,a]}),to:t.swap}],settlementSender:t.swap,transfers:[{amount:i,memo:a,recipient:n.recipient}]}}async function Za(e,t){let n=Xa(t);if(n)try{return await h(e,L.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await p(e,{account:t.account,calls:n.calls}),n)}catch{return}}const Qa={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]};function $a(e){return{name:`MPP`,version:`3`,chainId:e}}function eo(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function to(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:$a(n),types:Qa,primaryType:`Proof`,message:eo({account:t,challengeId:r,realm:i})}}function no(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const ro=[`push`,`pull`],io=U.object({amount:W(),memo:U.optional(K()),recipient:U.pipe(U.string(),U.transform(e=>e))}),ao=(1n<<64n)-1n,oo={dev_second:1n,day:86400n,week:604800n},so=U.pipe(G(),U.transform(e=>e.toLowerCase())),co=U.object({accessKeyAddress:so,keyType:U.enum([`p256`,`secp256k1`,`webAuthn`]),keyToken:U.optional(U.pipe(U.string().check(U.regex(/^0x[0-9a-fA-F]{120}$/)),U.transform(e=>e)))}),lo=U.object({accessKey:U.optional(co),chainId:U.optional(U.number())}),uo=Ye(`subscriptionExpires must be a valid date`).check(U.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),fo=U.enum([`dev_second`,`day`,`week`]),po=U.pipe(U.union([U.string(),U.bigint(),U.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),U.transform(e=>e.toString())).check(U.regex(/^[1-9]\d*$/,`Invalid periodCount`),U.refine(e=>{try{return BigInt(e)<=ao}catch{return!1}},`periodCount exceeds uint64`));function mo(e){return U.refine(e=>{let{amount:t,decimals:n}=e;return f(t,n)>0n},e)}function ho(e){let{periodCount:t,periodUnit:n}=e;try{let e=oo[n];return e!==void 0&&BigInt(t)*e<=ao}catch{return!1}}const go=Mt({name:`tempo`,intent:`charge`,schema:{credential:{payload:U.discriminatedUnion(`type`,[U.object({hash:K(),type:U.literal(`hash`)}),U.object({signature:q(),type:U.literal(`transaction`)}),U.object({signature:q(),type:U.literal(`proof`)})])},request:U.pipe(U.object({machineTokenEnabled:U.optional(U.boolean()),amount:W(),chainId:U.optional(U.number()),currency:U.string(),decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),feePayer:U.optional(U.pipe(U.union([U.boolean(),U.custom()]),U.transform(e=>typeof e==`object`||e))),memo:U.optional(U.never()),recipient:U.optional(U.string()),splits:U.optional(U.array(io).check(U.minLength(1),U.maxLength(10))),supportedModes:U.optional(U.array(U.enum(ro)).check(U.minLength(1)))}).check(U.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=f(e,t),i=n.reduce((e,n)=>e+f(n.amount,t),0n);return n.every(e=>f(e.amount,t)>0n)&&i<r},`Invalid splits`)),U.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,...c})=>({...c,amount:f(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==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:f(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s}}}:{}})))}}),_o=Mt({name:`tempo`,intent:`session`,schema:{credential:{payload:U.discriminatedUnion(`action`,[U.object({action:U.literal(`open`),authorizedSigner:U.optional(U.string()),channelId:K(),cumulativeAmount:W(),descriptor:U.optional(U.custom()),signature:q(),transaction:q(),type:U.literal(`transaction`)}),U.object({action:U.literal(`topUp`),additionalDeposit:W(),channelId:K(),descriptor:U.optional(U.custom()),transaction:q(),type:U.literal(`transaction`)}),U.object({action:U.literal(`voucher`),channelId:K(),cumulativeAmount:W(),descriptor:U.optional(U.custom()),signature:q()}),U.object({action:U.literal(`close`),channelId:K(),closeSignature:q(),cumulativeAmount:W(),descriptor:U.optional(U.custom()),signature:q()})])},request:U.pipe(U.object({amount:W(),chainId:U.optional(U.number()),channelId:U.optional(K()),currency:U.string(),decimals:U.number(),escrowContract:U.optional(U.string()),feePayer:U.optional(U.pipe(U.union([U.boolean(),U.custom()]),U.transform(e=>typeof e==`object`||e))),feeToken:U.optional(G()),minVoucherDelta:U.optional(W()),operator:U.optional(G()),recipient:U.optional(U.string()),sessionProtocol:U.optional(U.enum([We.v2,We.v1])),sessionSnapshot:U.optional(U.custom()),suggestedDeposit:U.optional(W()),unitType:U.string()}).check(U.refine(({amount:e,decimals:t})=>f(e,t)>0n,`Session amount must be greater than 0`)),U.transform(({amount:e,chainId:t,channelId:n,decimals:r,escrowContract:i,feePayer:a,feeToken:o,minVoucherDelta:s,operator:c,sessionProtocol:l,sessionSnapshot:u,suggestedDeposit:d,...p})=>({...p,amount:f(e,r).toString(),...d?{suggestedDeposit:f(d,r).toString()}:{},methodDetails:{escrowContract:i,...n!==void 0&&{channelId:n},...s!==void 0&&{minVoucherDelta:f(s,r).toString()},...t!==void 0&&{chainId:t},...a!==void 0&&{feePayer:a},...o!==void 0&&{feeToken:o},...c!==void 0&&{operator:c},...l!==void 0&&{[Ue.sessionProtocol]:l},...u!==void 0&&{[Ue.sessionSnapshot]:u}}})))}}),vo=Mt({name:`tempo`,intent:`subscription`,schema:{credential:{payload:U.object({signature:q(),type:U.literal(`keyAuthorization`)})},request:U.pipe(U.object({amount:W(),accessKey:U.optional(co),chainId:U.optional(U.number()),currency:so,decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),methodDetails:U.optional(lo),periodCount:po,periodUnit:fo,recipient:so,subscriptionExpires:uo}).check(mo(`Subscription amount must be greater than 0`),U.refine(ho,`Subscription period exceeds uint64`)),U.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:f(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}}),yo=U.object({account:U.optional(U.custom()),autoSwap:U.optional(U.custom()),feeToken:U.optional(U.custom()),mode:U.optional(U.enum(ro))});function bo(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.`);let n={maxAmount:So(e.maxAmount,e.decimals),maxAtomicAmount:e.maxAtomicAmount===void 0?void 0:BigInt(e.maxAtomicAmount)},r=Oa({chain:P,getClient:e.getClient,rpcUrl:Gn}),i=wa({account:e.account}),a=Nt(go,{canHandleChallenge({challenge:t}){try{return Co(e,n,t.request),!0}catch{return!1}},context:yo,async createCredential({challenge:a,context:o}){Co(e,n,a.request);let s=a.request.methodDetails?.chainId??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),c=await r({chainId:s});ka(c,s);let l=s??c.chain?.id;if(Aa(e.allowedChainIds,l),l===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");let{request:u}=a,{amount:d,methodDetails:f}=u,p=f?.supportedModes??[`pull`,`push`],h=i(c,o),b=async t=>await e.resolveAccount?.({account:h,chainId:l,operation:t})??h;if(BigInt(d)===0n){let e=await b({kind:`signPaymentProof`});return Tt({challenge:a,payload:{signature:await y(c,{account:e,...to({account:e.address,chainId:l,challengeId:a.id,realm:a.realm})}),type:`proof`},source:no({address:e.address,chainId:l})})}let x=u.currency,S=Ya({chainId:l,currency:x}),C=Na({challengeId:a.id,clientId:t,serverId:a.realm}),w=Va({amount:d,methodDetails:{...f,memo:C},recipient:u.recipient}),T=w.map(e=>L.token.transfer.call(c,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:x})),E=za(o?.autoSwap??e.autoSwap,La),D=f?.machineTokenEnabled===!0?Xa({chainId:l,currency:x,transfers:w}):void 0,O=h,k;if(D){let e=await(async()=>{try{return await b({calls:D.calls,kind:`executeCalls`})}catch{return}})();e&&(k=await Za(c,{account:e.address,chainId:l,currency:x,transfers:w}),k&&(O=e))}let A;k||(O=await b({kind:`executeCalls`,...E?{}:{calls:T}}),A=E?await Ra(c,{account:O.address,amountOut:BigInt(d),tokenOut:x,tokenIn:E.tokenIn,slippage:E.slippage,maxAmountIn:E.maxAmountIn}):void 0);let j=k?.calls??[...A??[],...T],M=Ga(l),N=(o?.feeToken??e.feeToken)||(k||S?await Ka({account:O.address,allowedTokens:M,candidateTokens:M,client:c,prioritizeCandidates:!0}):void 0),P=(()=>{let t=o?.mode??e.mode;if(t){if(!p.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=O.type===`json-rpc`?`push`:`pull`;return p.includes(n)?n:p[0]})(),F=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!a.expires)return e;let t=Math.floor(new Date(a.expires).getTime()/1e3)+1;return Math.min(e,t)})();if(P===`push`){let{receipts:e}=O.type===`local`?{receipts:[await _(c,{account:O,calls:j,...N?{feeToken:N}:{},nonceKey:`expiring`,validBefore:F})]}:await g(c,{account:O,...N?{capabilities:{feeToken:N}}:{},calls:j,experimental_fallback:j.length===1,forceAtomic:j.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return Tt({challenge:a,payload:{hash:t,type:`hash`},source:no({address:O.address,chainId:l})})}let ee=()=>{if(f?.feePayer!==!0)return;let e=15e3,t=a.expires?new Date(a.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(!(F*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.`)};ee();let I=await m(c,{account:O,calls:j,...N?{feeToken:N}:{},nonceKey:`expiring`,validBefore:F});if(I.gas=(I.gas??0n)+5000n,f?.feePayer){let e=I;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return ee(),Tt({challenge:a,payload:{signature:await v(c,I),type:`transaction`},source:no({address:O.address,chainId:l})})}}),o=new Map,s=async t=>{Co(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,s=o.get(i);return s||(s=a.createCredential(t).finally(()=>o.delete(i)),o.set(i,s)),s};return Di({...a,createCredential:s},xo)}function xo(e){let t=go.schema.credential.payload.safeParse(xt(e).payload);if(!t.success)return;let n=t.data;if(n.type===`hash`)return n.hash;let r=n.signature;if(n.type!==`transaction`||!r.startsWith(fe.serializedType))return;let i=fe.deserialize(r);if(!(!i.signature||i.feePayerSignature===null)&&fe.serialize(i)===r)return u(r)}function So(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 f(e,t)}}function Co(e,t,n){let{amount:r,methodDetails:i,recipient:a}=n,o=i?.chainId;if(e.expectedChainId!==void 0&&o!==void 0&&o!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${o}.`);if((o!==void 0||e.allowedChainIds?.length===0)&&Aa(e.allowedChainIds,o),e.currencies&&!e.currencies.some(e=>e.toLowerCase()===n.currency.toLowerCase()))throw Error(`Tempo charge currency is not allowed: ${n.currency}.`);if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase()));if(!a||!t.has(a.toLowerCase()))throw Error(`Unexpected primary recipient: ${a}`);let n=i?.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&&BigInt(r)>t.maxAtomicAmount)throw Error(`Tempo charge amount exceeds maxAtomicAmount.`);if(t.maxAmount!==void 0&&BigInt(r)>t.maxAmount)throw Error(`Tempo charge amount exceeds maxAmount.`)}const wo=(1n<<96n)-1n;function To(e){return e>=0n&&e<=wo}function Eo(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return To(t)?t:void 0}function Do(e){return Oo(e),e}function Oo(e){if(!To(e))throw Error(`Value ${e} is outside uint96 bounds.`)}const ko=new Set([`open`,`topUp`,`voucher`,`close`]);function Ao(e){return typeof e==`object`&&!!e}function jo(e){return typeof e==`string`&&ko.has(e)}function Mo(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!jo(t.action))}function No(e,t=`No session credential context available.`){if(!Mo(e))throw Error(t);return e}function Po(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function Fo(e){return Ao(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function Io(e){return Ao(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 Lo(e){let t=C.toString(e),n=JSON.parse(t);if(!Io(n))throw Error(`Invalid session receipt.`);return n}function Ro(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function zo(e){let t=`message`,n=[];for(let r of e.split(`
3
4
  `))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(`
4
- `);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=Mo(r);return Do(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=Mo(r);return Oo(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function Mo(e){try{return JSON.parse(e)}catch{return null}}function No(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function Po(){return JSON.stringify({mpp:`payment-close-request`})}function Fo(e){let t=Io(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`&&Oo(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`&&Do(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&Oo(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function Io(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}const Lo=`0x4d50500000000000000000000000000000000000`;function Ro(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function zo(e){let t=S.encode(S.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 T.keccak256(t)}function Bo(e){return pe.encodeForSigning(e)}function Vo(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function Ho(e,t){return T.keccak256(E.concat(Bo(e),t.sender))}const Uo=[{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`}],Wo=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],Go={name:`descriptor`,type:`tuple`,components:Uo},Ko=[{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:[Go,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[Go,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[Go,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[Go],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[Go],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[Go],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:Uo},{name:`state`,type:`tuple`,components:Wo}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:Wo}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:Wo}]},{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:`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:`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}]}];function qo(e,t){return{name:`TIP20 Channel Reserve`,version:`1`,chainId:t,verifyingContract:e}}const Jo={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},Yo={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]};function Xo(e,t){return ue.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function Zo(e,t,n){return e.toLowerCase()===ue.address.toLowerCase()?Xo(t,n):o({domain:qo(e,t),types:Jo,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function Qo(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function $o(e,t){return ne.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function es(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===ue.address.toLowerCase())try{return await $o(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return y(e,{account:t,domain:qo(r,i),types:Jo,primaryType:`Voucher`,message:n})})(),o=z.from(a);if(!Qo(o.type))throw Error(`TIP-1034 vouchers require a TIP-1020 primitive signature; received "${o.type}".`);return z.serialize(o)}async function ts(e,t,n,r,i){let a=await y(e,{account:t,domain:qo(r,i),types:Yo,primaryType:`CloseAuthorization`,message:n}),o=z.from(a);if(!Qo(o.type))throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive signature; received "${o.type}".`);return z.serialize(o)}function ns(e,t,n,r){try{let i=z.from(n.signature);if(!Qo(i.type)||z.serialize(i).toLowerCase()!==n.signature.toLowerCase())return!1;let a=Zo(e,t,n),o=z.extractAddress({payload:a,signature:i});return z.verify(i,{address:o,payload:a})&&Da(o,r)}catch{return!1}}function rs(e){return typeof e==`object`&&!!e}function is(e){return typeof e==`string`&&c(e,{strict:!1})?e:void 0}function as(e){return is(e.accessKeyAddress)}function os(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(E.random(8))%e)}function ss(e){return as(e)??e.address}async function cs(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return m(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}})}async function ls(e,t){return await v(e,t)}function us(e,t,n=!1){let r=e.request.methodDetails,i=rs(r)?is(r.escrowContract)??is(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!fs(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!fs(i,a)?i:a}function ds(e,t,n,r){return Dt({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}function fs(e,t){return e.toLowerCase()===t.toLowerCase()}async function ps(e,t,n,r,i,a=Lo){let o=zo({...n,chainId:i,escrow:a}),s=yo(r),c=await es(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function ms(e,t,n,r,i,a=Lo){let o=await ps(e,t,n,r,i,a),s=await ts(e,t,{channelId:o.channelId,cumulativeAmount:yo(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function hs(e,t,n){let i=ss(t),a=n.escrow??`0x4d50500000000000000000000000000000000000`,o=n.operator??`0x0000000000000000000000000000000000000000`,s=E.random(32),c=yo(n.deposit),l=yo(n.initialAmount),u=r({abi:Ko,functionName:`open`,args:[n.payee,o,n.token,c,s,i]}),d=await ls(e,await cs(e,{account:t,calls:[...n.prefixCalls??[],{to:a,data:u}],feePayer:n.feePayer,feeToken:n.feeToken??n.token})),f=ae.deserialize(d),p={authorizedSigner:i,expiringNonceHash:Ho(Vo({...n.feePayer?{feePayer:!0}:{},transaction:f}),{sender:t.address}),operator:o,payee:n.payee,payer:t.address,salt:s,token:n.token},m=zo({...p,chainId:n.chainId,escrow:a});return{action:`open`,type:`transaction`,channelId:m,transaction:d,signature:await es(e,t,{channelId:m,cumulativeAmount:l},a,n.chainId),descriptor:p,cumulativeAmount:l.toString(),authorizedSigner:p.authorizedSigner}}async function gs(e,t,n,i,a,o,s=Lo,c=[],l=n.token){let u=zo({...n,chainId:a,escrow:s}),d=yo(i);return{action:`topUp`,type:`transaction`,channelId:u,transaction:await ls(e,await cs(e,{account:t,calls:[...c,{to:s,data:r({abi:Ko,functionName:`topUp`,args:[n,d]})}],feePayer:o,feeToken:l,validAfter:os()})),descriptor:n,additionalDeposit:d.toString()}}function _s(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function Q(e){return _s({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function vs(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(Q(t),t)},delete(t){e.delete(t)}}}const ys=new WeakMap,bs=new WeakMap;function xs(e,t){bs.set(e,bs.get(t)??t)}async function Ss(e,t,n){let r=ys.get(e);r||(r=new Map,ys.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 Cs(e,t,n){return Ss(bs.get(e)??e,`funding:${t}`,n)}async function ws(e,t){await Ss(e,`write:${Q(t)}`,async()=>{let n=await e.get(Q(t));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 Ts(e,t){await Ss(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}const Es=2n**96n-1n;function Ds(e){if(e<0n||e>Es)throw new J({reason:`amount exceeds uint96 range`})}async function Os(e,t,n=Lo,r){return ks(await h(e,{address:n,abi:Ko,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function ks(e){return Ds(e.settled),Ds(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}const As=H.custom(e=>typeof e==`string`&&c(e,{strict:!1})),js=H.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),Ms=H.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),Ns=H.object({authorizedSigner:As,expiringNonceHash:js,operator:As,payee:As,payer:As,salt:js,token:As}),Ps=It(H.object({acceptedCumulative:H.string(),chainId:H.number(),channelId:js,closeRequestedAt:H.optional(H.string()),deposit:H.string(),descriptor:Ns,escrow:As,highestVoucher:H.optional(H.object({channelId:js,cumulativeAmount:H.string(),signature:Ms})),requiredCumulative:H.string(),settled:H.string(),spent:H.string(),units:H.optional(H.number())}));function Fs(e){return Ps.encode(e)}function Is(e){return Ps.decode(e)}const Ls={status:`idle`};function Rs(e){return{status:`active`,...e}}function zs(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:Hs(e.challengeId,t.snapshot),effects:[]}:$(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:tc({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:Us(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:$(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:ic(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?Vs({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:Us(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:Us(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 Bs(e,t){let n=zs(e.state,t);return e.state=n.state,n}function Vs(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 Hs(e,t){return Rs({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function Us(e,t,n,r){return Rs({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 Ws(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function Gs(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`);Ws({cumulativeAmount:i,maxVoucherCumulative:n}),Ws({cumulativeAmount:a,maxVoucherCumulative:n})}function Ks(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;Gs({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function qs(e,t){return typeof e==`bigint`?e:f(e,t)}function Js(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(Xs(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 Ys(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;Ws({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 Xs(e,t){Ws({cumulativeAmount:e,maxVoucherCumulative:t??null})}function Zs(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 Qs(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function $s(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!_o(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>Qs({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function ec(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=vo(r),s=vo(a.spent);return o===void 0||s===void 0||!_o(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function tc(e){return Rs({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 nc(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:Ls}}function rc(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=Ks({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&Bs(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function ic(e,t){return Rs({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function ac(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=vo(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 oc(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 zs(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function sc(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 cc(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 lc(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(Po()),e.waitForCloseReady()))(),a=BigInt(i.spent);$s({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=>ec({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(No(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}function uc(e){return`cumulativeAmount`in e}function dc(e){if(uc(e))return BigInt(e.cumulativeAmount)}async function fc(e,t){t.opened?await ws(e.store,t):await Ts(e.store,Q(t)),e.notifyUpdate(t)}async function pc(e,t,n){let r=dc(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 fc(e,i))}const mc=H.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),hc=H.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),gc=H.object({account:H.optional(H.custom()),autoSwap:H.optional(H.custom()),action:H.optional(H.enum([`open`,`topUp`,`voucher`,`close`])),channelId:H.optional(hc),cumulativeAmount:H.optional(U()),cumulativeAmountRaw:H.optional(H.string()),transaction:H.optional(mc),descriptor:H.optional(H.custom()),additionalDeposit:H.optional(U()),additionalDepositRaw:H.optional(H.string()),depositRaw:H.optional(H.string())});function _c(e){return e?.action!==void 0}function vc(e){return _c(e)&&e.descriptor!==void 0}function yc(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 f(i,t)}function bc(e,t,n,r){let i=yc(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function xc(e){return typeof e==`object`&&!!e}function Sc(e){return typeof e==`string`&&c(e,{strict:!1})?e:void 0}function Cc(e){let t=e.request.methodDetails;return xc(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:Sc(t.escrowContract),escrow:Sc(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:Sc(t.feeToken),operator:Sc(t.operator),sessionSnapshot:qe(t,Ge.sessionSnapshot)}:{}}function wc(e,t){if(typeof e==`string`&&c(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function Tc(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function Ec(e){return typeof e==`string`?e:void 0}async function Dc(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=Cc(n);(o.chainId!==void 0||i?.length===0)&&Sa(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});xa(c,s);let l=s??c.chain?.id;if(Sa(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=us(n,r,t),d=wc(n.request.recipient,`recipient`),f=wc(n.request.currency,`currency`);return{amount:Tc(n.request.amount),challenge:n,chainId:l,client:c,escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:_s({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:Ec(n.request.suggestedDeposit),token:f}}async function Oc(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=Os}=e,o=zo({...r,chainId:i.chainId,escrow:i.escrow});kc({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 kc(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(!fs(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!fs(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!fs(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!fs(Ro(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function Ac(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function jc(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=yc(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function Mc(e){let{account:t,client:n,readChannelState:r,snapshot:i}=e,a=i.highestVoucher;if(!a)throw Error(`session snapshot is missing its highest signed voucher`);if(a.channelId.toLowerCase()!==i.channelId.toLowerCase())throw Error(`session snapshot voucher channelId does not match snapshot channelId`);let o=BigInt(i.acceptedCumulative),s=BigInt(a.cumulativeAmount),c=BigInt(i.requiredCumulative),l=BigInt(i.deposit),u=BigInt(i.settled),d=BigInt(i.spent);if(s!==o)throw Error(`session snapshot voucher amount does not match acceptedCumulative`);if(d>o)throw Error(`session snapshot spent exceeds acceptedCumulative`);if(u>l)throw Error(`session snapshot settled amount exceeds deposit`);if(!ns(i.escrow,i.chainId,{channelId:a.channelId,cumulativeAmount:s,signature:a.signature},Ro(i.descriptor)))throw Error(`session snapshot highest voucher signature is invalid`);let f=await Oc({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:ss(t),token:i.descriptor.token},readChannelState:r}),p=[o,c,f.state.settled].reduce((e,t)=>t>e?t:e,0n);if(p>f.state.deposit)throw Error(`recovered session cumulative amount exceeds on-chain channel deposit`);return{entry:{channelId:f.channelId,cumulativeAmount:p,deposit:f.state.deposit,descriptor:i.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0},spent:d}}function Nc(e,t){return fs(e.address,t.payer)?fs(ss(e),Ro(t)):!1}function Pc(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(_c(r)){if(!vc(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=Ac({context:r,snapshot:o.snapshot});return!n&&s&&Nc(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&Nc(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 Fc(e,t,n=!1){switch(e.type){case`open`:return Lc(e,t,n);case`recover`:return Rc(e,t);case`voucher`:return zc(e,t);case`manual`:return Bc(e,t,n)}}async function Ic(e,t){if(e)return await Aa(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage,maxAmountIn:e.maxAmountIn})}async function Lc(e,t,n){let{account:r,resolved:i}=e,a=Js({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw}),o=await hs(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 Ic(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await fc(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function Rc(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await Oc({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:ss(n),token:o.token}}),l=jc({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`);Xs(l,a);let u=await ps(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await fc(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 zc(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;Xs(a,e.maxDeposit);let o=await ps(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await fc(t,r),o}async function Bc(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=zo({...s,chainId:o.chainId,escrow:o.escrow});kc({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:ss(r),token:o.token});let l=await Vc({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await pc(t,o.key,l),l}async function Vc(e,t){switch(e.context.action){case`open`:return Hc(e);case`topUp`:return Uc(e,t);case`voucher`:return Wc(e);case`close`:return Gc(e)}}async function Hc(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=bc(r,i,`cumulativeAmount`,`open`),c=await ps(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 Uc(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=bc(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:gs(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await Ic(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken)}function Wc(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return ps(a.client,t,i,bc(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function Gc(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return ms(a.client,t,i,bc(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}const Kc={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};function qc(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=Kc.CLOSED,r=null}if(a.type===`open`&&(i=Kc.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 Jc(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function Yc(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=qs(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 Xc(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:ic(s,u)}:i?{channel:u,state:tc({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function Zc(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=Jc(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:yo(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function Qc(e){return e.method===Ue.tempo&&e.intent===We.session}function $c(e){return Qc(e)&&qe(e.request.methodDetails,Ge.sessionProtocol)===Ke.v2}function el(e){return qe(e.request.methodDetails,Ge.sessionSnapshot)}function tl(e,t,n,r){let i=e instanceof Request?e.headers:void 0;return qr({...t,redirect:`manual`,headers:{...Fi(i),...Fi(t?.headers)}},_t(r),n)}function nl(e){try{let t=typeof location>`u`?void 0:location.href,n=e instanceof Request?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function rl(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function il(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 al=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 ol(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 sl({challenge:e.challenge,context:{action:`topUp`,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 al&&(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(B.paymentReceipt);return i?ko(i):void 0}async function sl(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(nl(e.input),{method:`POST`,signal:r.signal,redirect:`manual`,headers:jl(t,n,e.input,e.headers)}),s])}catch(t){throw e.context.action===`topUp`?new al(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=pt(n).find($c);return r?t(r):n}async function cl(e){let t=ll({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,tl(e.input,e.init,t,r))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(B.paymentReceipt)&&await l(),u}function ll(e){let t=pt(e.response).find($c);if(!t)return;let n=el(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function ul(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=async(r,i=!1)=>{t=r,n=(i?e.resolveSignedCloseAmount?.(r):void 0)??e.signedCloseAmount;let a=await e.createSessionCredential(r,{action:`close`,channelId:e.target.channelId,descriptor:e.target.channel.descriptor,cumulativeAmountRaw:n});return e.fetch(e.lastUrl,{method:`POST`,redirect:`manual`,headers:jl(r,a,e.lastUrl,e.headers)})},i=await r(e.target.challenge);if(i.status===402){let t=pt(i).find($c);t&&(e.setChallenge?.(t),i=await r(t,!0))}if(!i.ok){let e=await il(i),t=i.headers.get(B.wwwAuthenticate)??``;throw Error(`Close request failed with status ${i.status}${e?`: ${e}`:``}${t?` [${B.wwwAuthenticate}: ${t}]`:``}`)}let a=i.headers.get(B.paymentReceipt);if(!a)return;let o=ko(a);if(!o.txHash||!E.validate(o.txHash,{strict:!0})||E.size(o.txHash)!==32||!ec({challengeId:t.id,channelId:e.target.channelId,expectedCloseAmount:n,minimumSpent:e.getMinimumSpent?.()??0n,receipt:o}))throw Error(`Session close response included a mismatched payment receipt.`);return o}async function dl(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...Fi(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!Ao(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),fl(e,c,{onReceipt:r,signal:o},n,s.headers)}function fl(e,t,n,r,i){if(!Ao(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let a=r.getChallenge();return pl({onNeedVoucher:t=>vl({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*pl(e){for await(let t of ml(e))t.data!==void 0&&(yield t.data)}async function*ml(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=hl(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=jo(i.replace(/\r\n|\r/g,`
5
- `));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 hl(e,t){for(let n=0;n<e.length;n++){let r=gl(e,n,t);if(!r)continue;let i=gl(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function gl(e,t,n){return e[t]===`
5
+ `);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=Bo(r);return Fo(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=Bo(r);return Io(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function Bo(e){try{return JSON.parse(e)}catch{return null}}function Vo(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function Ho(){return JSON.stringify({mpp:`payment-close-request`})}function Uo(e){let t=Wo(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`&&Io(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`&&Fo(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&Io(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function Wo(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}const Go=`0x4d50500000000000000000000000000000000000`;function Ko(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function qo(e){let t=S.encode(S.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 T.keccak256(t)}function Jo(e){return fe.encodeForSigning(e)}function Yo(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function Xo(e,t){return T.keccak256(E.concat(Jo(e),t.sender))}const Zo=[{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`}],Qo=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],$o={name:`descriptor`,type:`tuple`,components:Zo},es=[{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:[$o,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[$o,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[$o,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[$o],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[$o],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[$o],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:Zo},{name:`state`,type:`tuple`,components:Qo}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:Qo}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:Qo}]},{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:`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:`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}]}];function ts(e,t){return{name:`TIP20 Channel Reserve`,version:`1`,chainId:t,verifyingContract:e}}const ns={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},rs={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]};function is(e,t,n){return o({domain:ts(e,t),types:rs,primaryType:`CloseAuthorization`,message:n})}function as(e,t){return ue.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function os(e,t,n){return e.toLowerCase()===ue.address.toLowerCase()?as(t,n):o({domain:ts(e,t),types:ns,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function ss(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function cs(e){return e.source===`accessKey`&&`accessKeyAddress`in e}function ls(e,t){return re.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function us(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===ue.address.toLowerCase())try{return await ls(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return y(e,{account:t,domain:ts(r,i),types:ns,primaryType:`Voucher`,message:n})})(),o=z.from(a);if(!ss(o.type))throw Error(`TIP-1034 vouchers require a TIP-1020 primitive signature; received "${o.type}".`);return z.serialize(o)}async function ds(e,t,n,r,i){let a=cs(t)?await t.sign({hash:is(r,i,n),raw:!0}):await y(e,{account:t,domain:ts(r,i),types:rs,primaryType:`CloseAuthorization`,message:n}),o=z.from(a);if(!ss(o.type))throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive signature; received "${o.type}".`);return z.serialize(o)}function fs(e,t,n,r){try{let i=z.from(n.signature);if(!ss(i.type)||z.serialize(i).toLowerCase()!==n.signature.toLowerCase())return!1;let a=os(e,t,n),o=z.extractAddress({payload:a,signature:i});return z.verify(i,{address:o,payload:a})&&Fa(o,r)}catch{return!1}}function ps(e){return typeof e==`object`&&!!e}function ms(e){return typeof e==`string`&&c(e,{strict:!1})?e:void 0}function hs(e){return ms(e.accessKeyAddress)}function gs(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(E.random(8))%e)}function _s(e){return hs(e)??e.address}async function vs(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return m(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}})}async function ys(e,t){return await v(e,t)}function bs(e,t,n=!1){let r=e.request.methodDetails,i=ps(r)?ms(r.escrowContract)??ms(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!Ss(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!Ss(i,a)?i:a}function xs(e,t,n,r){return Tt({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}function Ss(e,t){return e.toLowerCase()===t.toLowerCase()}async function Cs(e,t,n,r,i,a=Go){let o=qo({...n,chainId:i,escrow:a}),s=Do(r),c=await us(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function ws(e,t,n,r,i,a=Go){let o=await Cs(e,t,n,r,i,a),s=await ds(e,t,{channelId:o.channelId,cumulativeAmount:Do(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function Ts(e,t,n){let i=_s(t),a=n.escrow??`0x4d50500000000000000000000000000000000000`,o=n.operator??`0x0000000000000000000000000000000000000000`,s=E.random(32),c=Do(n.deposit),l=Do(n.initialAmount),u=r({abi:es,functionName:`open`,args:[n.payee,o,n.token,c,s,i]}),d=await ys(e,await vs(e,{account:t,calls:[...n.prefixCalls??[],{to:a,data:u}],feePayer:n.feePayer,feeToken:n.feeToken??n.token})),f=oe.deserialize(d),p={authorizedSigner:i,expiringNonceHash:Xo(Yo({...n.feePayer?{feePayer:!0}:{},transaction:f}),{sender:t.address}),operator:o,payee:n.payee,payer:t.address,salt:s,token:n.token},m=qo({...p,chainId:n.chainId,escrow:a});return{action:`open`,type:`transaction`,channelId:m,transaction:d,signature:await us(e,t,{channelId:m,cumulativeAmount:l},a,n.chainId),descriptor:p,cumulativeAmount:l.toString(),authorizedSigner:p.authorizedSigner}}async function Es(e,t,n,i,a,o,s=Go,c=[],l=n.token){let u=qo({...n,chainId:a,escrow:s}),d=Do(i);return{action:`topUp`,type:`transaction`,channelId:u,transaction:await ys(e,await vs(e,{account:t,calls:[...c,{to:s,data:r({abi:es,functionName:`topUp`,args:[n,d]})}],feePayer:o,feeToken:l,validAfter:gs()})),descriptor:n,additionalDeposit:d.toString()}}function Ds(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function Q(e){return Ds({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function Os(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(Q(t),t)},delete(t){e.delete(t)}}}const ks=new WeakMap,As=new WeakMap;function js(e,t){As.set(e,As.get(t)??t)}async function Ms(e,t,n){let r=ks.get(e);r||(r=new Map,ks.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 Ns(e,t,n){return Ms(As.get(e)??e,`funding:${t}`,n)}async function Ps(e,t){await Ms(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 Fs(e,t){await Ms(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}const Is=2n**96n-1n;function Ls(e){if(e<0n||e>Is)throw new Y({reason:`amount exceeds uint96 range`})}async function Rs(e,t,n=Go,r){return zs(await h(e,{address:n,abi:es,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function zs(e){return Ls(e.settled),Ls(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}const Bs=U.custom(e=>typeof e==`string`&&c(e,{strict:!1})),Vs=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),Hs=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),Us=U.object({authorizedSigner:Bs,expiringNonceHash:Vs,operator:Bs,payee:Bs,payer:Bs,salt:Vs,token:Bs}),Ws=Pt(U.object({acceptedCumulative:U.string(),chainId:U.number(),channelId:Vs,closeRequestedAt:U.optional(U.string()),deposit:U.string(),descriptor:Us,escrow:Bs,highestVoucher:U.optional(U.object({channelId:Vs,cumulativeAmount:U.string(),signature:Hs})),requiredCumulative:U.string(),settled:U.string(),spent:U.string(),units:U.optional(U.number())}));function Gs(e){return Ws.encode(e)}function Ks(e){return Ws.decode(e)}const qs={status:`idle`};function Js(e){return{status:`active`,...e}}function Ys(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:Qs(e.challengeId,t.snapshot),effects:[]}:$(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:dc({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:$s(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:$(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:mc(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?Zs({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:$s(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:$s(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 Xs(e,t){let n=Ys(e.state,t);return e.state=n.state,n}function Zs(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 Qs(e,t){return Js({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function $s(e,t,n,r){return Js({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 ec(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function tc(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`);ec({cumulativeAmount:i,maxVoucherCumulative:n}),ec({cumulativeAmount:a,maxVoucherCumulative:n})}function nc(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;tc({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function rc(e,t){return typeof e==`bigint`?e:f(e,t)}function ic(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(oc(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 ac(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;ec({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 oc(e,t){ec({cumulativeAmount:e,maxVoucherCumulative:t??null})}function sc(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 cc(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function lc(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!To(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>cc({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function uc(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=Eo(r),s=Eo(a.spent);return o===void 0||s===void 0||!To(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function dc(e){return Js({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 fc(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:qs}}function pc(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=nc({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&Xs(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function mc(e,t){return Js({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function hc(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=Eo(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 gc(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 Ys(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function _c(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 vc(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 yc(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(Ho()),e.waitForCloseReady()))(),a=BigInt(i.spent);lc({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=>uc({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(Vo(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}function bc(e){return`cumulativeAmount`in e}function xc(e){if(bc(e))return BigInt(e.cumulativeAmount)}async function Sc(e,t){e.origin!==void 0&&(t={...t,origin:e.origin}),t.opened?await Ps(e.store,t):await Fs(e.store,Q(t)),e.notifyUpdate(t)}async function Cc(e,t,n){let r=xc(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 Sc(e,i))}const wc=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),Tc=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),Ec=U.object({account:U.optional(U.custom()),autoSwap:U.optional(U.custom()),action:U.optional(U.enum([`open`,`topUp`,`voucher`,`close`])),channelId:U.optional(Tc),cumulativeAmount:U.optional(W()),cumulativeAmountRaw:U.optional(U.string()),transaction:U.optional(wc),descriptor:U.optional(U.custom()),additionalDeposit:U.optional(W()),additionalDepositRaw:U.optional(U.string()),depositRaw:U.optional(U.string())});function Dc(e){return e?.action!==void 0}function Oc(e){return Dc(e)&&e.descriptor!==void 0}function kc(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 f(i,t)}function Ac(e,t,n,r){let i=kc(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function jc(e){return typeof e==`object`&&!!e}function Mc(e){return typeof e==`string`&&c(e,{strict:!1})?e:void 0}function Nc(e){let t=e.request.methodDetails;return jc(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:Mc(t.escrowContract),escrow:Mc(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:Mc(t.feeToken),operator:Mc(t.operator),sessionSnapshot:Ge(t,Ue.sessionSnapshot)}:{}}function Pc(e,t){if(typeof e==`string`&&c(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function Fc(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function Ic(e){return typeof e==`string`?e:void 0}async function Lc(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=Nc(n);(o.chainId!==void 0||i?.length===0)&&Aa(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});ka(c,s);let l=s??c.chain?.id;if(Aa(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=bs(n,r,t),d=Pc(n.request.recipient,`recipient`),f=Pc(n.request.currency,`currency`);return{amount:Fc(n.request.amount),challenge:n,chainId:l,client:c,escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:Ds({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:Ic(n.request.suggestedDeposit),token:f}}async function Rc(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=Rs}=e,o=qo({...r,chainId:i.chainId,escrow:i.escrow});zc({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 zc(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(!Ss(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!Ss(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!Ss(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!Ss(Ko(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function Bc(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function Vc(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=kc(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function Hc(e){let{account:t,client:n,readChannelState:r,snapshot:i}=e,a=i.highestVoucher;if(!a)throw Error(`session snapshot is missing its highest signed voucher`);if(a.channelId.toLowerCase()!==i.channelId.toLowerCase())throw Error(`session snapshot voucher channelId does not match snapshot channelId`);let o=BigInt(i.acceptedCumulative),s=BigInt(a.cumulativeAmount),c=BigInt(i.requiredCumulative),l=BigInt(i.deposit),u=BigInt(i.settled),d=BigInt(i.spent);if(s!==o)throw Error(`session snapshot voucher amount does not match acceptedCumulative`);if(d>o)throw Error(`session snapshot spent exceeds acceptedCumulative`);if(u>l)throw Error(`session snapshot settled amount exceeds deposit`);if(!fs(i.escrow,i.chainId,{channelId:a.channelId,cumulativeAmount:s,signature:a.signature},Ko(i.descriptor)))throw Error(`session snapshot highest voucher signature is invalid`);let f=await Rc({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:_s(t),token:i.descriptor.token},readChannelState:r}),p=[o,c,f.state.settled].reduce((e,t)=>t>e?t:e,0n);if(p>f.state.deposit)throw Error(`recovered session cumulative amount exceeds on-chain channel deposit`);return{entry:{channelId:f.channelId,cumulativeAmount:p,deposit:f.state.deposit,descriptor:i.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0},spent:d}}function Uc(e,t){return Ss(e.address,t.payer)?Ss(_s(e),Ko(t)):!1}function Wc(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(Dc(r)){if(!Oc(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=Bc({context:r,snapshot:o.snapshot});return!n&&s&&Uc(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&Uc(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 Gc(e,t,n=!1){switch(e.type){case`open`:return qc(e,t,n);case`recover`:return Jc(e,t);case`voucher`:return Yc(e,t);case`manual`:return Xc(e,t,n)}}async function Kc(e,t){if(e)return await Ra(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage,maxAmountIn:e.maxAmountIn})}async function qc(e,t,n){let{account:r,resolved:i}=e,a=ic({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw}),o=await Ts(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 Kc(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await Sc(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function Jc(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await Rc({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:_s(n),token:o.token}}),l=Vc({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`);oc(l,a);let u=await Cs(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await Sc(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 Yc(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;oc(a,e.maxDeposit);let o=await Cs(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await Sc(t,r),o}async function Xc(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=qo({...s,chainId:o.chainId,escrow:o.escrow});zc({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:_s(r),token:o.token});let l=await Zc({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await Cc(t,o.key,l),l}async function Zc(e,t){switch(e.context.action){case`open`:return Qc(e);case`topUp`:return $c(e,t);case`voucher`:return el(e);case`close`:return tl(e)}}async function Qc(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=Ac(r,i,`cumulativeAmount`,`open`),c=await Cs(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 $c(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=Ac(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:Es(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await Kc(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken)}function el(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Cs(a.client,t,i,Ac(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function tl(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return ws(a.client,t,i,Ac(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}const nl={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};function rl(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=nl.CLOSED,r=null}if(a.type===`open`&&(i=nl.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 il(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function al(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=rc(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 ol(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:mc(s,u)}:i?{channel:u,state:dc({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function sl(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=il(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:Do(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function cl(e){return e.method===Ve.tempo&&e.intent===He.session}function ll(e){return cl(e)&&Ge(e.request.methodDetails,Ue.sessionProtocol)===We.v2}function ul(e){return Ge(e.request.methodDetails,Ue.sessionSnapshot)}function dl(e,t,n,r){let i=e instanceof Request?e.headers:void 0;return Yr({...t,redirect:`manual`,headers:{...Hi(i),...Hi(t?.headers)}},ht(r),n)}function fl(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 pl(e){try{let t=typeof location>`u`?void 0:location.href,n=fl(e)?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function ml(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function hl(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 gl=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 _l(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 vl({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 gl&&(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(B.paymentReceipt);return i?Lo(i):void 0}async function vl(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(pl(e.input),{method:`POST`,signal:r.signal,redirect:`manual`,headers:Hl(t,n,e.input,e.headers)}),s])}catch(t){throw e.context.action===`topUp`?new gl(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=dt(n).find(ll);return r?t(r):n}async function yl(e){let t=bl({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,dl(e.input,e.init,t,r))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(B.paymentReceipt)&&await l(),u}function bl(e){let t=dt(e.response).find(ll);if(!t)return;let n=ul(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function xl(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=fl(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?pl(r):e.lastUrl,{...i,method:`POST`,redirect:`manual`,headers:Hl(a,s,e.lastUrl,e.headers)})},o=await a(e.target.challenge);if(o.status===402){let t=dt(o).find(ll);t&&(e.setChallenge?.(t),o=await a(t,!0))}if(!o.ok){let e=await hl(o),t=o.headers.get(B.wwwAuthenticate)??``;throw Error(`Close request failed with status ${o.status}${e?`: ${e}`:``}${t?` [${B.wwwAuthenticate}: ${t}]`:``}`)}let s=o.headers.get(B.paymentReceipt);if(!s)return;let c=Lo(s);if(!c.txHash||!E.validate(c.txHash,{strict:!0})||E.size(c.txHash)!==32||!uc({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 Sl(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...Hi(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!Ro(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),Cl(e,c,{onReceipt:r,signal:o},n,s.headers)}function Cl(e,t,n,r,i){if(!Ro(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let a=r.getChallenge();return wl({onNeedVoucher:t=>kl({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*wl(e){for await(let t of Tl(e))t.data!==void 0&&(yield t.data)}async function*Tl(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=El(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=zo(i.replace(/\r\n|\r/g,`
6
+ `));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 El(e,t){for(let n=0;n<e.length;n++){let r=Dl(e,n,t);if(!r)continue;let i=Dl(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function Dl(e,t,n){return e[t]===`
6
7
  `?1:e[t]===`\r`?e[t+1]===`
7
- `?2:t+1===e.length&&!n?0:1:0}function _l(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=ml({...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 vl(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await Zc({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 sl({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 yl(e){let t=new URL(e.input.toString()),n=rl(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=pt(r).find($c);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 bl(e){e.signal?.throwIfAborted();let t=await yl(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function xl(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:Ct(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:Eo(t)}}function Sl(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function Cl(e){if(!Sl(e))return`received mismatched payment-close-ready frame`;let t=vo(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 wl(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!Sl(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!ec({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function Tl(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=xl({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=qc(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===Kc.CONNECTING||s.readyState===Kc.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 Dl({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await El(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(No(n)),await e.waitForReceipt(),l.socket}function El(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 Dl(e){let t=Fo(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`:Ol(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 kl(e,t.data);return;case`payment-receipt`:Al(e,t.data);return}}function Ol(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=Cl({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 kl(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 Zc({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(No(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function Al(e,t){let n=wl({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 jl(e,t,n,r){let i=_t(e),a=new Headers;if(i.toLowerCase()!==B.authorization.toLowerCase()){let e=new Headers(r).get(B.authorization)??(n instanceof Request?n.headers.get(B.authorization):null);e&&!e.startsWith(`${He.payment} `)&&a.set(B.authorization,e)}return a.set(i,t),a}const Ml=new WeakMap;async function Nl(e,t){let n=Ml.get(e)??new Map;Ml.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 Pl(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function Fl(e,t,n){try{let r=e.response?.headers.get(B.paymentReceipt);if(r){let e=ko(r);if(e.challengeId===t.id&&Pl(n,e))return!0}}catch{}return e.challenges?.some(e=>$c(e)?Pl(n,el(e)):!1)??!1}function Il(e={}){let{account:t,allowCustomEscrow:n=!1,autoSwap:r,channelStore:i,decimals:a=6,escrow:o,allowedChainIds:s,getClient:c,maxDeposit:l,topUpAmount:u,onChannelUpdate:d,resolveAccount:p}=e,m=ba({chain:x,getClient:c,rpcUrl:Kn}),h=ga({account:t}),g=l===void 0?void 0:f(l,a),_=u===void 0?void 0:f(u,a),v=i??vs(),y={store:v,notifyUpdate:e=>d?.(e)},b=async(e,t,n)=>{let r=h(e.client,t),i=t?.action?t.descriptor:n?.descriptor??Ac({context:t,snapshot:e.snapshot})?.descriptor;return await p?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:Ro(i)}:{}}})??r},S=async(e,t,n)=>Pc({account:await b(e,t,n),entry:n,context:t,decimals:a,maxDeposit:g,resolved:e}),C=Ft(co,{canHandleChallenge:({challenge:e})=>$c(e),context:gc,async createCredential(e){let{challenge:t,context:i}=e,a=await Dc({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:m}),c=xi(e),l=()=>{};try{let e=!_c(i)&&i?.descriptor===void 0;e&&(l=await Nl(v,a.key),c&&(await v.get(a.key))?.opened&&await c.prepare());let n=await v.get(a.key),o=await S(a,i,n);if(!e&&c&&o.type===`open`){l=await Nl(v,a.key);let e=await v.get(a.key);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await c.prepare(),n=await v.get(a.key)),o=await S(a,i,n))}let s,u=c&&o.type===`open`?{store:{get:e=>v.get(e),async set(e){s=e},delete:e=>v.delete(e)},notifyUpdate(){}}:y,d=await ds(t,await Fc(o,u,ja(i?.autoSwap??r,ka)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||Fl(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await v.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await ws(v,e),y.notifyUpdate(e))}return!0}finally{l()}}}else l();return d}catch(e){throw l(),e}}}),w=async({challenge:e,channel:t,deposit:n,fetch:r,input:i,requiredCumulative:a,signal:o})=>Cs(v,Q(t),async()=>{o?.throwIfAborted();let s=await v.get(Q(t));if(s?.channelId===t.channelId&&(t=s),t.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let c=t.deposit>n?t.deposit:n,l=Ys({deposit:c,maxDeposit:g,requiredCumulative:a,suggestedDeposit:e.request.suggestedDeposit===void 0?void 0:BigInt(e.request.suggestedDeposit),topUpAmount:_});l>0n&&await ol({additionalDeposit:l,challenge:e,channel:t,channelId:t.channelId,createSessionCredential:(e,t)=>C.createCredential({challenge:e,context:t}),onUncertainFunding:async e=>{let t=await v.get(Q(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};await ws(v,n),y.notifyUpdate(n)},fetch:r,input:i,signal:o});let u=c+l;if(u===t.deposit)return;let d=await v.get(Q(t)),f=d?.channelId.toLowerCase()===t.channelId.toLowerCase()?d:t,p={...f,deposit:f.deposit>u?f.deposit:u};await ws(v,p),y.notifyUpdate(p)});return di(C,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!$c(e))return;let c=t===void 0?void 0:gc.parse(t);if(_c(c))return;let l=await Dc({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m}),u=await v.get(l.key);if(!u?.opened)return;let d=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,f=u.cumulativeAmount+Eo(e),p=d?BigInt(d.requiredCumulative):f,h=p>f?p:f,g=d?BigInt(d.deposit):u.deposit,_=g>u.deposit?g:u.deposit;h<=_&&_===u.deposit||!Nc(await b(l,c,u),u.descriptor)||await w({challenge:e,channel:u,deposit:_,fetch:r,input:i,requiredCumulative:h,signal:a})}),vi(C,async({challenge:e,credential:t,fetch:r,headers:i,input:a,refetch:c,response:l,signal:u})=>{if(!$c(e))return l;if(!Ao(l))return To(Ct(t).payload).action===`open`&&i.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await c?.()??l:l;let d=(await Dc({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m})).key,f=await v.get(d),p={assertVoucherWithinLocalLimit:e=>Xs(e,g),createSessionCredential:(e,t)=>C.createCredential({challenge:e,context:t}),fetch:r,getChannel:()=>f??null,async topUpIfNeeded({deposit:t,requiredCumulative:n,signal:i}){f&&await w({challenge:e,channel:f,deposit:f.deposit>t?f.deposit:t,fetch:r,input:a,requiredCumulative:n,signal:i})}};return _l({onNeedVoucher:(t,n)=>vl({challenge:e,driver:p,headers:i,input:a,signal:n},t),onReceipt(){},response:l,signal:u})})}const Ll=new WeakMap;function Rl(e,t){Ll.set(e,t)}function zl(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 Bl(e){let t=zl(`close-ready`),n=zl(`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 Vl(e){return e.method===Ue.tempo&&e.intent===We.charge}function Hl(e){if(!Vl(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function Ul(e,t,n){if(!n)return t;let r={...Fi(e instanceof Request?e.headers:void 0),...Fi(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===B.paymentSession.toLowerCase())?t:{...t,headers:{...r,[B.paymentSession]:n}}}function Wl(e,t){return e===void 0?t:{...gc.parse(e),...t}}function Gl(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:f(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:f(e.topUpAmount,t),WebSocket:n}}function Kl(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&Sa(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=Gl(e),i=ba({chain:x,getClient:e.client?()=>e.client:e.getClient,rpcUrl:Kn}),a=ga({account:e.account}),o=nc(),s=e.credentialContext===void 0?void 0:Wl(e.credentialContext,{}),c=Bl({getSocketSession:()=>o.socketSession}),l=e.channelStore??vs(),u=new Set,d;async function f(e){let t=await l.get(e);if(t?.opened&&!u.has(t.channelId))return t}let p=e=>ws(l,e),m={async get(e){let t=await f(e);return t&&d&&(d.seenExisting.add(e),!d.committed&&!d.created.has(e)&&(d.resumed??=t)),t},async set(e){let t=Q(e);e.opened&&u.delete(e.channelId),d?.trackCreates&&!d.seenExisting.has(t)&&d.created.set(t,e),await p(e)},delete:e=>Ts(l,e)};xs(m,l);async function h(e){let t=Q(e),n=await l.get(t);if(e.uncertainTopUp||n?.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);u.add(e.channelId),d?.seenExisting.delete(t),d?.resumed===e&&(d.resumed=void 0),await Promise.resolve(Ts(l,t)).catch(()=>void 0)}async function g(){let e=d;if(e?.created.size){for(let[t,n]of e.created){let e=await l.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.`);u.add(n.channelId),await Promise.resolve(Ts(l,t)).catch(()=>void 0)}e.created.clear(),await re(e.committed??e.previous)}}function _(e){let t=qe(e.request.methodDetails,Ge.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=d;if(!n?.created.size||!o.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&o.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=sc({channel:o.channel,spent:o.spent,state:o.state}),!0;return!1}function v(e){return Bs(o,e)}function y(){let e=o.state.status===`active`?o.state:d?.committed?.state??d?.previous.state;return e?.status===`active`?e.units:0}function b(e){let t=d,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=sc({channel:o.channel,spent:o.spent,state:o.state}))}let S=Il({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:m,onChannelUpdate(e){e.channelId!==o.channel?.channelId&&(o.spent=0n),o.channel=e,o.lastChallenge&&v({type:`activated`,challengeId:o.lastChallenge.id,entry:e,spent:o.spent.toString(),units:y()}),b(e)}}),C=mi(S);C&&di(S,e=>ee(()=>Promise.resolve(C(e)),e.signal)),yi(S);let w=fo({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),T=Pi({fetch:r.fetch,methods:[S],onChallenge:async(e,t)=>{if(!Qc(e))return;let n=d,r=n&&n.challengesReceived>0&&e.id===o.lastChallenge?.id,i=r&&it(e)===it(o.lastChallenge);n&&n.challengesReceived++,!i&&(_(e)||(n?.created.size?await g():r&&await re(n.committed??n.previous)),o.lastChallenge=e,v({type:`challengeReceived`,challengeId:e.id}))}});function E(e,t){return S.createCredential({challenge:e,context:Wl(s,t)})}function D(e){rc({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:o})}function O(e=o.state.status===`active`?o.state.units:0){!o.channel||!o.lastChallenge||o.state.status!==`active`&&o.state.status!==`withdrawable`&&o.state.status!==`closeRequested`&&v({type:`activated`,challengeId:o.lastChallenge.id,entry:o.channel,spent:o.spent.toString(),units:e})}async function k(t){let n=t.headers.get(B.paymentSessionSnapshot);if(!n)return;let r=Is(n);Sa(e.allowedChainIds,r.chainId);let s=await i({chainId:r.chainId});xa(s,r.chainId);let c=a(s),{entry:l,spent:u}=await Mc({account:await e.resolveAccount?.({account:c,chainId:r.chainId,operation:{authority:Ro(r.descriptor),kind:`authorizePaymentChannel`}})??c,client:s,snapshot:r});return F(l.cumulativeAmount),await Promise.resolve(m.set(l)).catch(()=>void 0),o.channel=l,o.spent=u,l}async function A(t,n){if(!e.bootstrap||o.channel?.opened)return;let i=t instanceof Request?t.headers:void 0,{body:a,method:s,...c}=n??{},l=t instanceof Request?t.url:t,u={...c,method:`HEAD`,headers:{...Fi(i),...Fi(n?.headers),[B.acceptPayment]:`${Ue.tempo}/${We.charge}`}};try{let t=await r.fetch(l,u);if(t.status!==402)return await k(t);let n=pt(t).find(Vl);if(!n||!Hl(n))return;let i=new URL(String(l),typeof location<`u`?location.href:void 0);if(t.url&&new URL(t.url).origin!==i.origin)return;Ti(n,i,e.trustedTempoProofRealms);let a=await w.createCredential({challenge:n,context:{}}),o=await r.fetch(l,qr({...u,redirect:`manual`},_t(n),a));return o.ok?await k(o):void 0}catch{return}}function j(e,t){let n=o.socketSession;return ac({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:o.channel?.channelId===t?o.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:o.spent,tickCost:n?.tickCost})}function M(e,t){let n=el(t);if(!n)return;if(zo({...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 N(e,t){let n=M(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(o.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>o.spent&&(o.spent=i),n}function P(e,t=e.challenge,n=!1){let r=(n?N(e,t):M(e.channel,t))?.acceptedCumulative??j(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return F(r),r.toString()}function F(e){Ws({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}let I,L;async function ee(e,t){if(L)throw L;for(;;){let e=I;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(),L)throw L;let n=e();I=n;try{return await n}catch(e){throw e instanceof al&&(L=Error(`Session funding outcome is unknown; reconcile the pending payment before creating a new session manager.`)),e}finally{I===n&&(I=void 0)}}async function te(e){if(!o.channel)throw Error(`Cannot top up session: no active channel`);return Cs(l,Q(o.channel),async()=>{let{knownDeposit:t,...n}=e,i=o.channel?await m.get(Q(o.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 ol({...n,channel:o.channel,createSessionCredential:E,fetch:r.fetch,onUncertainFunding:async e=>{let t=await m.get(Q(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};o.channel?.channelId===e.channelId&&(o.channel=n),await m.set(n),b(n)}});D(a);let s=o.channel,c=Xc({additionalDeposit:e.additionalDeposit,channel:o.channel,channelId:e.channelId,challengeId:o.lastChallenge?.id,currentState:o.state,knownDeposit:t,receipt:a,spent:o.spent});if(c?.channel&&o.lastChallenge){let e=c.channel;for(;;){await m.set(e);let t=o.channel;if(t===s)break;if(!t)return a;let n=c.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,s=t}if(e.channelId!==c.channel.channelId)return a;o.channel=e,v({type:`activated`,challengeId:o.lastChallenge.id,entry:e,spent:o.spent.toString(),units:y()}),b(e)}return a})}async function ne(e){return ee(async()=>{e.signal?.throwIfAborted();let t=o.channel?.channelId===e.channelId?o.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=Ys({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 te({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})},e.signal)}async function R(e,t){let n=oc({channel:o.channel,channelId:e,challengeId:o.lastChallenge?.id,cumulativeAmount:t,spent:o.spent,state:o.state});n&&o.channel&&(v({type:`activated`,challengeId:n.challengeId,entry:o.channel,spent:n.spent,units:n.units}),await p(o.channel))}async function re(e){let t=cc(e,o.channel);o.channel=t.channel,o.spent=t.spent,o.state=t.state,o.channel?.opened&&await p(o.channel)}function ie(e){let t=e.headers.get(B.paymentReceipt),n=t?ko(t):null;return D(n),Object.assign(e,{receipt:n,challenge:o.lastChallenge,channelId:o.channel?.channelId??null,cumulative:o.channel?.cumulativeAmount??0n})}async function ae(e,t){if(d)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);o.lastUrl=e,o.lastHeaders=t?.headers;let n=sc({channel:o.channel,spent:o.spent,state:o.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};d=i;try{await A(e,t),i.trackCreates=!0;let a=Ul(e,t,o.channel?.opened?o.channel.channelId:void 0);s&&(a={...a,context:s});let c=!n.channel?.opened;async function l(){let n=i.resumed;return!c||!n?!1:(c=!1,await h(n),a=Ul(e,t,void 0),!0)}for(;;){let t;try{t=await T(e,a)}catch(e){if(i.created.size?await g():await re(i.committed??n),await l())continue;throw e}let s=ie(t),c=!1;if(s.status===402){let t=await cl({input:e,init:a,response:s,createSessionCredential:E,fetch:r.fetch,getChannel:()=>o.channel,restoreCumulative:R,setChallenge(e){o.lastChallenge=e},topUpIfNeeded:ne});t&&(c=!0,s=ie(t))}if(!c&&!s.ok&&!s.receipt){if(i.created.size?await g():await re(i.committed??n),await l())continue;return s}return s}}finally{d=void 0}}async function oe(e){let t=await ul({createSessionCredential:E,fetch:r.fetch,getMinimumSpent:()=>o.spent,headers:o.lastHeaders,lastUrl:o.lastUrl,resolveSignedCloseAmount:t=>P(e,t,!0),signedCloseAmount:P(e),setChallenge(e){o.lastChallenge=e},target:e});return t&&(O(),v({type:`closeStarted`}),v({type:`closed`,receipt:t})),t}let se={createSessionCredential:E,doFetch:ae,fetch:r.fetch,getChannel:()=>o.channel,getChallenge:()=>o.lastChallenge,assertVoucherWithinLocalLimit:F,acceptReceipt(e){D(e)},topUpIfNeeded:ne},ce={get channelId(){return o.channel?.channelId},get cumulative(){return o.channel?.cumulativeAmount??0n},get opened(){return o.channel?.opened??!1},get state(){return o.state},fetch:ae,async topUp(e){let t=Yc({amount:e,assertVoucherWithinLocalLimit:F,channel:o.channel,decimals:r.decimals,lastChallenge:o.lastChallenge,lastUrl:o.lastUrl});return ee(async()=>{if(o.channel?.channelId!==t.channelId||o.lastChallenge!==t.challenge||o.lastUrl!==t.input)throw Error(`Session changed while waiting to top up`);let n=Yc({amount:e,assertVoucherWithinLocalLimit:F,channel:o.channel,decimals:r.decimals,lastChallenge:t.challenge,lastUrl:t.input});return te({additionalDeposit:n.additionalDeposit,challenge:n.challenge,channelId:n.channelId,headers:o.lastHeaders,input:n.input})})},async sse(e,t){return dl(e,t,se)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=rl(e),i=t?.signal?{signal:t.signal}:void 0;await A(n,i);let a=o.channel?.opened?o.channel.channelId:void 0,{challenge:s,credential:l,httpUrl:u,wsUrl:d}=await bl({async createSessionCredential(e,i){return o.lastChallenge=e,await pi(S,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),E(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){o.lastUrl=e.toString()},probeInit:Ul(n,i,a),signal:t?.signal});return o.lastChallenge=s,Tl({challenge:s,credential:l,httpUrl:u,WebSocket:r.WebSocket,wsUrl:d,options:t,createSessionCredential:E,getChannel:()=>o.channel,setSocketSession(e){o.socketSession=e},async refreshChallenge(){let e=await yl({fetch:r.fetch,input:u,probeInit:Ul(u,i,o.channel?.opened?o.channel.channelId:void 0),signal:t?.signal});return o.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:F,acceptReceipt:D,rejectCloseReady:c.rejectCloseReady,rejectReceipt:c.rejectReceipt,settleCloseReady:c.settleCloseReady,settleReceipt:c.settleReceipt,topUpIfNeeded:ne,waitForReceipt:c.waitForReceipt})},async close(){let e=o.socketSession,t=Zs({channel:o.channel,currentSocket:e,lastChallenge:o.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===Kc.OPEN){let r=await lc({activeSocket:n,createSessionCredential:E,currentSocket:e,spent:o.spent,target:t,waitForCloseReady:c.waitForCloseReady,waitForReceipt:c.waitForReceipt});return O(),v({type:`closeStarted`}),v({type:`closed`,receipt:r}),r}return oe(t)}};return Rl(ce,{consumeSseResponse(e,t,n){return fl(e,t,n,se)},rehydrate({channel:e,challenge:t,input:n,spent:r}){if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!Qc(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.`);F(e.cumulativeAmount);let i=M(e,t),a=i&&i.spent>r?i.spent:r;o.lastUrl=n,o.lastChallenge=t,o.channel=e,o.spent=a,v({type:`challengeReceived`,challengeId:t.id}),v({type:`activated`,challengeId:t.id,entry:e,spent:a.toString(),units:0})}}),ce}(function(e){e.serializeSnapshot=Fs,e.deserializeSnapshot=Is})(Kl||={});const ql=(1n<<64n)-1n,Jl={dev_second:1n,day:86400n,week:604800n};function Yl(e){return e instanceof Date?e:new Date(e)}function Xl(e){let t=e.getTime();if(!Number.isFinite(t))throw new J({reason:`subscriptionExpires is invalid`});if(t%1e3!=0)throw new J({reason:`subscriptionExpires must be representable as whole seconds`});let n=t/1e3;if(n<=0||!Number.isSafeInteger(n))throw new J({reason:`subscriptionExpires cannot be represented in a Tempo key authorization`});return n}function Zl(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new J({reason:`periodCount is invalid`});let t=Jl[e.periodUnit];if(t===void 0)throw new J({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>ql)throw new J({reason:`subscription period cannot be represented as an unsigned 64-bit integer`});if(n>BigInt(2**53-1))throw new J({reason:`subscription period cannot be represented exactly by this Tempo client`});return Number(n)}function Ql(e){let{challengeExpires:t,request:n}=e;Zl(n);let r=Xl(Yl(n.subscriptionExpires));if(t){let e=Math.floor(new Date(t).getTime()/1e3);if(!Number.isFinite(e)||r<=e)throw new J({reason:`subscriptionExpires must be strictly later than challenge expires`})}}function $l(e){return[{address:fu(e.currency,`currency`),selector:`0x95777d59`,recipients:[fu(e.recipient,`recipient`)]}]}function eu(e){try{let t=E.fromBytes(C.toBytes(e));if(E.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new J({reason:`challenge id must encode 32 bytes`})}}async function tu(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=ru({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:de.getSignPayload(o)}),c=z.from(s);if(c.type===`keychain`||c.type===`multisig`)throw new J({reason:`keyAuthorization must use a primitive signature`});return de.from(o,{signature:s})}function nu(e){let{accessKey:t,challengeId:n,chainId:r,payload:i,request:a}=e;if(i.type!==`keyAuthorization`)throw new J({reason:`invalid keyAuthorization payload`});let o=iu(i.signature),s=au(o);if(ou({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==eu(n))throw new J({reason:`keyAuthorization challenge mismatch`});return su(o,a),lu(cu(o),a),uu(o.scopes,a),{authorization:o,source:{address:du(o,s),chainId:r}}}function ru(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return de.from({address:fu(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:Xl(Yl(i.subscriptionExpires)),limits:[{token:fu(i.currency,`currency`),limit:BigInt(i.amount),period:Zl(i)}],scopes:$l(i),type:t.keyType,witness:eu(n)})}function iu(e){try{return de.deserialize(e)}catch(e){throw e instanceof de.InvalidSignatureTypeError?new J({reason:`keyAuthorization must use a primitive signature`}):new J({reason:`invalid keyAuthorization payload`})}}function au(e){let t=e.signature;if(!t)throw new J({reason:`keyAuthorization must use a primitive signature`});return t}function ou(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new J({reason:`keyAuthorization chainId mismatch`});if(t){if(!l(n.address,fu(t.accessKeyAddress,`accessKeyAddress`)))throw new J({reason:`keyAuthorization access key mismatch`});if(n.type!==t.keyType)throw new J({reason:`keyAuthorization key type mismatch`})}}function su(e,t){if(Ql({request:t}),e.expiry!==Xl(Yl(t.subscriptionExpires)))throw new J({reason:`keyAuthorization expiry mismatch`})}function cu(e){let[t]=e.limits??[];if(!t||e.limits?.length!==1)throw new J({reason:`keyAuthorization must contain exactly one token limit`});return t}function lu(e,t){if(!l(e.token,fu(t.currency,`currency`)))throw new J({reason:`keyAuthorization currency mismatch`});if(e.limit!==BigInt(t.amount))throw new J({reason:`keyAuthorization amount mismatch`});if(e.period!==Zl(t))throw new J({reason:`keyAuthorization period mismatch`})}function uu(e,t){if(!e||e.length!==1)throw new J({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=fu(t.currency,`currency`),r=fu(t.recipient,`recipient`),i=new Set;for(let t of e){if(!l(t.address,n))throw new J({reason:`keyAuthorization call target mismatch`});let e=pu(t.selector);if(e!==`0xa9059cbb`&&e!==`0x95777d59`)throw new J({reason:`keyAuthorization selector not allowed`});if(i.has(e))throw new J({reason:`keyAuthorization duplicate selector`});if(i.add(e),t.recipients?.length!==1||!l(t.recipients[0],r))throw new J({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new J({reason:`keyAuthorization must allow transferWithMemo`})}function du(e,t){let n=de.getSignPayload(e);try{let e=z.extractAddress({payload:n,signature:t});if(!z.verify(t,{address:e,payload:n}))throw new J({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof J?e:new J({reason:`keyAuthorization signature is invalid`})}}function fu(e,t){if(!c(e))throw new J({reason:`${t} must be an address`});return e.toLowerCase()}function pu(e){return typeof e==`string`?e.toLowerCase():``}const mu=H.object({accessKey:H.optional(H.custom()),account:H.optional(H.custom())});function hu(e={}){let t=ba({chain:P,getClient:e.getClient,rpcUrl:Kn}),n=ga({account:e.account});return Ft(lo,{context:mu,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??X.testnet,o=await t({chainId:a}),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.");_u(r.request),await e.validateRequest?.(r.request);let u=await gu(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),d=nu({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:de.serialize(u),type:`keyAuthorization`},request:r.request});if(!l(d.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return Dt({challenge:r,payload:{signature:de.serialize(u),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function gu(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await tu({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:Xl(Yl(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:E.fromNumber(BigInt(o.amount)),period:Zl(o)}],scopes:$l(o),witness:eu(i)}]});return de.fromRpc(c.keyAuthorization)}function _u(e){Zl(e),Xl(Yl(e.subscriptionExpires))}const vu=Object.assign(Il,{manager:Kl});function yu(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[fo(e),vu(n)]}(function(e){e.charge=fo,e.common=yu,e.session=vu,e.subscription=hu})(yu||={});const bu=N.union([N.boolean(),N.literal(`true`).transform(()=>!0),N.literal(`false`).transform(()=>!1)]);async function xu(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}const Su=N.object({allowCustomEscrow:N.optional(bu),autoSwap:N.optional(bu),channel:N.optional(N.coerce.string()),deposit:N.optional(N.union([N.string(),N.number()])),payWith:N.optional(N.string()),slippage:N.optional(N.coerce.number()),tokenIn:N.optional(N.string())}),Cu=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`];function wu(){let t;return fr({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:n,options:r,methodOpts:i}){let a=cr(r.account),o=n.request,c=o.currency,l=Au(i),u=Pu({autoSwap:l.autoSwap??r.autoSwap,payWith:l.payWith??r.payWith,slippage:l.slippage??r.slippage,tokenIn:l.tokenIn}),d=c??``,f=o.decimals??6,p,m,h,g=!1,_=process.env.MPPX_PRIVATE_KEY?.trim()||(Jn(a)?void 0:await lr(a).get());if(!_&&Jn(a)&&Uu()){g=!0;let t=Vu(a);if(t){let i=Zn(r.rpcUrl,{network:r.network});h=e({chain:await Qn({network:r.network,rpcUrl:i}),transport:s(i)}),Mu({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let a=c?await tr(h,c,t.wallet_address).catch(()=>void 0):void 0;d=a?.symbol??c??``,f=a?.decimals??o.decimals??6}}else if(_)m=ce(_);else{let e=Gu();if(e){let t=await lr(e).get();t&&(m=ce(t))}if(!m)throw r.account?new Vn({code:`ACCOUNT_NOT_FOUND`,message:`Account "${a}" not found.`,exitCode:69}):new Vn({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!g&&m){let t=Zn(r.rpcUrl,{network:r.network});h=e({chain:await Qn({network:r.network,rpcUrl:t}),transport:s(t)}),Mu({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let i=c?await tr(h,c,m.address).catch(()=>void 0):void 0;d=i?.symbol??c??``,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 Wu(t)}};if(!m||!h)throw new Vn({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let v=yu({account:m,...l.allowCustomEscrow===void 0?{}:{allowCustomEscrow:l.allowCustomEscrow},getClient:()=>h,...u===void 0?{}:{autoSwap:u},maxDeposit:(()=>{if(n.intent!==`session`)return;let e=n.request.suggestedDeposit,t=(l.deposit===void 0?void 0:String(l.deposit))??e??(er(h.chain)?`10`:void 0);if(!t)throw new Vn({code:`MISSING_DEPOSIT`,message:`Session payment requires a deposit. Use -M deposit=<amount> or connect to testnet.`,exitCode:2});return t})()}),y=(()=>{if(!l.channel)return;let e=l.channel,t=Iu(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 es(h,m,c,i,a);return Dt({challenge:n,payload:{action:o,channelId:e,...o===`close`?{closeSignature:await ts(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=Ct(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?` ${Z.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
8
+ `?2:t+1===e.length&&!n?0:1:0}function Ol(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=Tl({...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 kl(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await sl({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 vl({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 Al(e){let t=new URL(e.input.toString()),n=ml(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=dt(r).find(ll);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 jl(e){e.signal?.throwIfAborted();let t=await Al(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function Ml(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:xt(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:Po(t)}}function Nl(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function Pl(e){if(!Nl(e))return`received mismatched payment-close-ready frame`;let t=Eo(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 Fl(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!Nl(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!uc({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function Il(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=Ml({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=rl(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===nl.CONNECTING||s.readyState===nl.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 Rl({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await Ll(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(Vo(n)),await e.waitForReceipt(),l.socket}function Ll(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 Rl(e){let t=Uo(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`:zl(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 Bl(e,t.data);return;case`payment-receipt`:Vl(e,t.data);return}}function zl(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=Pl({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 Bl(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 sl({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(Vo(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function Vl(e,t){let n=Fl({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 Hl(e,t,n,r){let i=ht(e),a=new Headers;if(i.toLowerCase()!==B.authorization.toLowerCase()){let e=new Headers(r).get(B.authorization)??(n instanceof Request?n.headers.get(B.authorization):null);e&&!e.startsWith(`${V.payment} `)&&a.set(B.authorization,e)}return a.set(i,t),a}const Ul=new WeakMap;async function Wl(e,t){let n=Ul.get(e)??new Map;Ul.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 Gl(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function Kl(e,t,n){try{let r=e.response?.headers.get(B.paymentReceipt);if(r){let e=Lo(r);if(e.challengeId===t.id&&Gl(n,e))return!0}}catch{}return e.challenges?.some(e=>ll(e)?Gl(n,ul(e)):!1)??!1}function ql(e){let{currencies:t,decimals:n,expectedRecipients:r,maxAmount:i,maxAtomicAmount:a}=e;if((i!==void 0||a!==void 0)&&t===void 0)throw Error(`Tempo session maxAmount and maxAtomicAmount require currencies.`);return{currencies:t?.map(e=>e.toLowerCase()),expectedRecipients:r?new Set(r.map(e=>e.toLowerCase())):void 0,maxAmount:Jl(i,n),maxAtomicAmount:a===void 0?void 0:BigInt(a)}}function Jl(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 f(e,t)}}function Yl(e,t){if(e.currencies&&!e.currencies.includes(t.currency.toLowerCase()))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 n=BigInt(t.amount);if(e.maxAtomicAmount!==void 0&&n>e.maxAtomicAmount)throw Error(`Tempo session amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0&&n>e.maxAmount)throw Error(`Tempo session amount exceeds maxAmount.`)}function Xl(e,t){try{return Yl(e,t),!0}catch{return!1}}function Zl(e){return typeof e==`object`&&!!e&&e.action===`close`}function Ql(e={}){let{account:t,allowCustomEscrow:n=!1,autoSwap:r,channelStore:i,decimals:a=6,escrow:o,allowedChainIds:s,getClient:c,maxDeposit:l,topUpAmount:u,onChannelUpdate:d,resolveAccount:p}=e,m=ql(e),h=Oa({chain:x,getClient:c,rpcUrl:Gn}),g=wa({account:t}),_=l===void 0?void 0:f(l,a),v=u===void 0?void 0:f(u,a),y=e.origin===void 0?void 0:new URL(e.origin);if(y&&![`http:`,`https:`].includes(y.protocol))throw Error(`Session origins require HTTP or HTTPS`);let b=i??Os(),S={store:b,notifyUpdate:e=>d?.(e)},C=async(e,t,n)=>{let r=g(e.client,t),i=t?.action?t.descriptor:n?.descriptor??Bc({context:t,snapshot:e.snapshot})?.descriptor;return await p?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:Ko(i)}:{}}})??r},w=async(e,t,n)=>Wc({account:await C(e,t,n),entry:n,context:t,decimals:a,maxDeposit:_,resolved:e}),T=Nt(_o,{canHandleChallenge:({challenge:e,context:t})=>ll(e)&&(Zl(t)||t===Or||Xl(m,e.request)),context:Ec,async createCredential(e){let{challenge:t,context:i}=e;i?.action!==`close`&&Yl(m,t.request);let a=await Lc({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:h}),c=Ti(e),l=Ai(e)??y?.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(y&&l!==y.origin)throw Error(`Session channel origin mismatch`);let u={...S,origin:l},d=()=>{};try{let e=!Dc(i)&&i?.descriptor===void 0;e&&(d=await Wl(b,a.key),c&&(await b.get(a.key))?.opened&&await c.prepare());let n=await b.get(a.key);if(n&&n.origin!==l)throw Error(`Session channel origin mismatch`);if(l&&!n&&a.snapshot&&!i?.descriptor&&!y)throw Error(`Session snapshot recovery requires an explicitly configured origin or descriptor`);let o=await w(a,i,n);if(!e&&c&&o.type===`open`){d=await Wl(b,a.key);let e=await b.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 b.get(a.key)),o=await w(a,i,n))}let s,f=c&&o.type===`open`?{store:{get:e=>b.get(e),async set(e){s=l?{...e,origin:l}:e},delete:e=>b.delete(e)},notifyUpdate(){}}:u,p=await xs(t,await Gc(o,f,za(i?.autoSwap??r,La)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||Kl(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await b.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await Ps(b,e),S.notifyUpdate(e))}return!0}finally{d()}}}else d();return p}catch(e){throw d(),e}}});function E(e,t,n){let r={challenge:e,context:t};return ki(r,$l(n)),T.createCredential(r)}let D=async({autoSwap:e,challenge:t,channel:n,deposit:r,fetch:i,input:a,requiredCumulative:o,signal:s})=>Ns(b,Q(n),async()=>{s?.throwIfAborted();let c=await b.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,u=ac({deposit:l,maxDeposit:_,requiredCumulative:o,suggestedDeposit:t.request.suggestedDeposit===void 0?void 0:BigInt(t.request.suggestedDeposit),topUpAmount:v});u>0n&&await _l({autoSwap:e,additionalDeposit:u,challenge:t,channel:n,channelId:n.channelId,createSessionCredential:(e,t)=>E(e,t,a),onUncertainFunding:async e=>{let t=await b.get(Q(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};await Ps(b,n),S.notifyUpdate(n)},fetch:i,input:a,signal:s});let d=l+u;if(d===n.deposit)return;let f=await b.get(Q(n)),p=f?.channelId.toLowerCase()===n.channelId.toLowerCase()?f:n,m={...p,deposit:p.deposit>d?p.deposit:d};await Ps(b,m),S.notifyUpdate(m)});return mi(T,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!ll(e))return;let c=t===void 0?void 0:Ec.parse(t);if(Dc(c))return;Yl(m,e.request);let l=await Lc({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:h}),u=await b.get(l.key);if(!u?.opened)return;let d=$l(i);if(u.origin!==d)throw Error(`Session channel origin mismatch`);let f=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,p=u.cumulativeAmount+Po(e),g=f?BigInt(f.requiredCumulative):p,_=g>p?g:p,v=f?BigInt(f.deposit):u.deposit,y=v>u.deposit?v:u.deposit;_<=y&&y===u.deposit||!Uc(await C(l,c,u),u.descriptor)||await D({autoSwap:c?.autoSwap,challenge:e,channel:u,deposit:y,fetch:r,input:i,requiredCumulative:_,signal:a})}),Si(T,async({challenge:e,context:t,credential:r,fetch:i,headers:a,input:c,refetch:l,response:u,signal:d})=>{if(!ll(e))return u;if(!Ro(u))return No(xt(r).payload).action===`open`&&a.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await l?.()??u:u;let f=(await Lc({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:h})).key,p=await b.get(f),m={assertVoucherWithinLocalLimit:e=>oc(e,_),createSessionCredential:(e,t)=>E(e,t,c),fetch:i,getChannel:()=>p??null,async topUpIfNeeded({deposit:n,requiredCumulative:r,signal:a}){p&&await D({autoSwap:t===void 0?void 0:Ec.parse(t).autoSwap,challenge:e,channel:p,deposit:p.deposit>n?p.deposit:n,fetch:i,input:c,requiredCumulative:r,signal:a})}};return Ol({onNeedVoucher:(t,n)=>kl({challenge:e,driver:m,headers:a,input:c,signal:n},t),onReceipt(){},response:u,signal:d})})}function $l(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 eu=new WeakMap;function tu(e,t){eu.set(e,t)}function nu(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 ru(e){let t=nu(`close-ready`),n=nu(`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 iu(e){return e.method===Ve.tempo&&e.intent===He.charge}function au(e){if(!iu(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function ou(e,t,n){if(!n)return t;let r={...Hi(fl(e)?e.headers:void 0),...Hi(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===B.paymentSession.toLowerCase())?t:{...t,headers:{...r,[B.paymentSession]:n}}}function su(e,t){return e===void 0?t:{...Ec.parse(e),...t}}function cu(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:f(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:f(e.topUpAmount,t),WebSocket:n}}function lu(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&Aa(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=cu(e),i;function a(e){let t=new URL(fl(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=ua(r.fetch),s=da(r.fetch);r.fetch=async(e,t)=>{let n=a(e),r=await s(e,{...t,redirect:(t?.redirect??(fl(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=Tr(c,o));let l=Oa({chain:x,getClient:e.client?()=>e.client:e.getClient,rpcUrl:Gn}),u=wa({account:e.account}),d=fc(),f=e.credentialContext===void 0?void 0:su(e.credentialContext,{}),p=ru({getSocketSession:()=>d.socketSession}),m=e.channelStore??Os(),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,Ps(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=>Fs(m,e)};js(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(Fs(m,t)).catch(()=>void 0)}async function S(){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(Fs(m,t)).catch(()=>void 0)}e.created.clear(),await le(e.committed??e.previous)}}function C(e){let t=Ge(e.request.methodDetails,Ue.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=_c({channel:d.channel,spent:d.spent,state:d.state}),!0;return!1}function w(e){return Xs(d,e)}function T(){let e=d.state.status===`active`?d.state:g?.committed?.state??g?.previous.state;return e?.status===`active`?e.units:0}function E(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=_c({channel:d.channel,spent:d.spent,state:d.state}))}let D=Ql({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&&w({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:T()}),E(e)}}),O=_i(D);O&&mi(D,e=>ae(()=>Promise.resolve(O(e)),e.signal)),Ci(D);let k=bo({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),A=Vi({trustedTempoProofRealms:e.trustedTempoProofRealms,fetch:c,identity:o,methods:[D],onChallenge:async(e,t)=>{if(!cl(e))return;let n=g,r=n&&n.challengesReceived>0&&e.id===d.lastChallenge?.id,i=r&&nt(e)===nt(d.lastChallenge);n&&n.challengesReceived++,!i&&(C(e)||(n?.created.size?await S():r&&await le(n.committed??n.previous)),d.lastChallenge=e,w({type:`challengeReceived`,challengeId:e.id}))}});function j(e,t){let n={challenge:e,context:su(f,t)};return i&&ki(n,i),D.createCredential(n)}function M(e){pc({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:d})}function N(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`&&w({type:`activated`,challengeId:d.lastChallenge.id,entry:d.channel,spent:d.spent.toString(),units:e})}async function P(t){let n=t.headers.get(B.paymentSessionSnapshot);if(!n)return;let r=Ks(n);Aa(e.allowedChainIds,r.chainId);let i=await l({chainId:r.chainId});ka(i,r.chainId);let a=u(i),{entry:o,spent:s}=await Hc({account:await e.resolveAccount?.({account:a,chainId:r.chainId,operation:{authority:Ko(r.descriptor),kind:`authorizePaymentChannel`}})??a,client:i,snapshot:r});return re(o.cumulativeAmount),await Promise.resolve(y.set(o)).catch(()=>void 0),d.channel=o,d.spent=s,o}async function F(t,n){if(!e.bootstrap||d.channel?.opened)return;let i=fl(t)?t.headers:void 0,{body:a,method:o,...s}=n??{},c=fl(t)?t.url:t,l={...s,method:`HEAD`,headers:{...Hi(i),...Hi(n?.headers),[B.acceptPayment]:`${Ve.tempo}/${He.charge}`}};try{let t=await r.fetch(c,l);if(t.status!==402)return await P(t);let n=dt(t).find(iu);if(!n||!au(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;ji(n,i,e.trustedTempoProofRealms);let a=await k.createCredential({challenge:n,context:{}}),o=await r.fetch(c,Yr({...l,redirect:`manual`},ht(n),a));return o.ok?await P(o):void 0}catch{return}}function ee(e,t){let n=d.socketSession;return hc({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 I(e,t){let n=ul(t);if(!n)return;if(qo({...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 te(e,t){let n=I(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 ne(e,t=e.challenge,n=!1){let r=(n?te(e,t):I(e.channel,t))?.acceptedCumulative??ee(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return re(r),r.toString()}function re(e){ec({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}let L,ie;async function ae(e,t){if(ie)throw ie;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(),ie)throw ie;let n=e();L=n;try{return await n}catch(e){throw e instanceof gl&&(ie=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 oe(e){if(!d.channel)throw Error(`Cannot top up session: no active channel`);return Ns(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 _l({...n,channel:d.channel,createSessionCredential:j,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),E(n)}});M(a);let o=d.channel,s=ol({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,w({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:T()}),E(e)}return a})}async function se(e){return ae(async()=>{e.signal?.throwIfAborted();let t=d.channel?.channelId===e.channelId?d.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=ac({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 oe({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})},e.signal)}async function ce(e,t){let n=gc({channel:d.channel,channelId:e,challengeId:d.lastChallenge?.id,cumulativeAmount:t,spent:d.spent,state:d.state});n&&d.channel&&(w({type:`activated`,challengeId:n.challengeId,entry:d.channel,spent:n.spent,units:n.units}),await v(d.channel))}async function le(e){let t=vc(e,d.channel);d.channel=t.channel,d.spent=t.spent,d.state=t.state,d.channel?.opened&&await v(d.channel)}function ue(e){let t=e.headers.get(B.paymentReceipt),n=t?Lo(t):null;return M(n),Object.assign(e,{receipt:n,challenge:d.lastChallenge,channelId:d.channel?.channelId??null,cumulative:d.channel?.cumulativeAmount??0n})}async function R(e,t){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=_c({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 F(e,t),i.trackCreates=!0;let a=ou(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=ou(e,t,void 0),!0)}for(;;){let t;try{t=await A(e,a)}catch(e){if(i.created.size?await S():await le(i.committed??n),await s())continue;throw e}let o=ue(t),c=!1;if(o.status===402){let t=await yl({input:e,init:a,response:o,createSessionCredential:j,fetch:r.fetch,getChannel:()=>d.channel,restoreCumulative:ce,setChallenge(e){d.lastChallenge=e},topUpIfNeeded:se});t&&(c=!0,o=ue(t))}if(!c&&!o.ok&&!o.receipt){if(i.created.size?await S():await le(i.committed??n),await s())continue;return o}return o}}finally{g=void 0}}async function z(e){let t=await xl({createSessionCredential:j,fetch:r.fetch,getMinimumSpent:()=>d.spent,headers:d.lastHeaders,lastUrl:d.lastUrl,resolveSignedCloseAmount:t=>ne(e,t,!0),signedCloseAmount:ne(e),setChallenge(e){d.lastChallenge=e},target:e});return t&&(N(),w({type:`closeStarted`}),w({type:`closed`,receipt:t})),t}let de={createSessionCredential:j,doFetch:R,fetch:r.fetch,getChannel:()=>d.channel,getChallenge:()=>d.lastChallenge,assertVoucherWithinLocalLimit:re,acceptReceipt(e){M(e)},topUpIfNeeded:se},fe={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:R,async topUp(e){let t=al({amount:e,assertVoucherWithinLocalLimit:re,channel:d.channel,decimals:r.decimals,lastChallenge:d.lastChallenge,lastUrl:d.lastUrl});return ae(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=al({amount:e,assertVoucherWithinLocalLimit:re,channel:d.channel,decimals:r.decimals,lastChallenge:t.challenge,lastUrl:t.input});return oe({additionalDeposit:n.additionalDeposit,challenge:n.challenge,channelId:n.channelId,headers:d.lastHeaders,input:n.input})})},async sse(e,t){return Sl(e,t,de)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=ml(e);a(n);let i=t?.signal?{signal:t.signal}:void 0;await F(n,i);let o=d.channel?.opened?d.channel.channelId:void 0,{challenge:s,credential:c,httpUrl:l,wsUrl:u}=await jl({async createSessionCredential(e,i){return d.lastChallenge=e,await gi(D,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),j(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){d.lastUrl=e.toString()},probeInit:ou(n,i,o),signal:t?.signal});return d.lastChallenge=s,Il({challenge:s,credential:c,httpUrl:l,WebSocket:r.WebSocket,wsUrl:u,options:t,createSessionCredential:j,getChannel:()=>d.channel,setSocketSession(e){d.socketSession=e},async refreshChallenge(){let e=await Al({fetch:r.fetch,input:l,probeInit:ou(l,i,d.channel?.opened?d.channel.channelId:void 0),signal:t?.signal});return d.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:re,acceptReceipt:M,rejectCloseReady:p.rejectCloseReady,rejectReceipt:p.rejectReceipt,settleCloseReady:p.settleCloseReady,settleReceipt:p.settleReceipt,topUpIfNeeded:se,waitForReceipt:p.waitForReceipt})},async close(){let e=d.socketSession,t=sc({channel:d.channel,currentSocket:e,lastChallenge:d.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===nl.OPEN){let r=await yc({activeSocket:n,createSessionCredential:j,currentSocket:e,spent:d.spent,target:t,waitForCloseReady:p.waitForCloseReady,waitForReceipt:p.waitForReceipt});return N(),w({type:`closeStarted`}),w({type:`closed`,receipt:r}),r}return z(t)}};return tu(fe,{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 Cl(e,t,n,de)},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(!cl(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.`);re(e.cumulativeAmount);let o=I(e,t),s=o&&o.spent>r?o.spent:r;d.lastUrl=n,d.lastChallenge=t,d.channel=e,d.spent=s,w({type:`challengeReceived`,challengeId:t.id}),w({type:`activated`,challengeId:t.id,entry:e,spent:s.toString(),units:0})}}),fe}(function(e){e.serializeSnapshot=Gs,e.deserializeSnapshot=Ks})(lu||={});const uu=(1n<<64n)-1n,du={dev_second:1n,day:86400n,week:604800n};function fu(e){return e instanceof Date?e:new Date(e)}function pu(e){let t=e.getTime();if(!Number.isFinite(t))throw new Y({reason:`subscriptionExpires is invalid`});if(t%1e3!=0)throw new Y({reason:`subscriptionExpires must be representable as whole seconds`});let n=t/1e3;if(n<=0||!Number.isSafeInteger(n))throw new Y({reason:`subscriptionExpires cannot be represented in a Tempo key authorization`});return n}function mu(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new Y({reason:`periodCount is invalid`});let t=du[e.periodUnit];if(t===void 0)throw new Y({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>uu)throw new Y({reason:`subscription period cannot be represented as an unsigned 64-bit integer`});if(n>BigInt(2**53-1))throw new Y({reason:`subscription period cannot be represented exactly by this Tempo client`});return Number(n)}function hu(e){let{challengeExpires:t,request:n}=e;mu(n);let r=pu(fu(n.subscriptionExpires));if(t){let e=Math.floor(new Date(t).getTime()/1e3);if(!Number.isFinite(e)||r<=e)throw new Y({reason:`subscriptionExpires must be strictly later than challenge expires`})}}function gu(e){return[{address:ku(e.currency,`currency`),selector:`0x95777d59`,recipients:[ku(e.recipient,`recipient`)]}]}function _u(e){try{let t=E.fromBytes(C.toBytes(e));if(E.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new Y({reason:`challenge id must encode 32 bytes`})}}async function vu(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=bu({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:R.getSignPayload(o)}),c=z.from(s);if(c.type===`keychain`||c.type===`multisig`)throw new Y({reason:`keyAuthorization must use a primitive signature`});return R.from(o,{signature:s})}function yu(e){let{accessKey:t,challengeId:n,chainId:r,payload:i,request:a}=e;if(i.type!==`keyAuthorization`)throw new Y({reason:`invalid keyAuthorization payload`});let o=xu(i.signature),s=Su(o);if(Cu({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==_u(n))throw new Y({reason:`keyAuthorization challenge mismatch`});return wu(o,a),Eu(Tu(o),a),Du(o.scopes,a),{authorization:o,source:{address:Ou(o,s),chainId:r}}}function bu(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return R.from({address:ku(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:pu(fu(i.subscriptionExpires)),limits:[{token:ku(i.currency,`currency`),limit:BigInt(i.amount),period:mu(i)}],scopes:gu(i),type:t.keyType,witness:_u(n)})}function xu(e){try{return R.deserialize(e)}catch(e){throw e instanceof R.InvalidSignatureTypeError?new Y({reason:`keyAuthorization must use a primitive signature`}):new Y({reason:`invalid keyAuthorization payload`})}}function Su(e){let t=e.signature;if(!t)throw new Y({reason:`keyAuthorization must use a primitive signature`});return t}function Cu(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new Y({reason:`keyAuthorization chainId mismatch`});if(t){if(!l(n.address,ku(t.accessKeyAddress,`accessKeyAddress`)))throw new Y({reason:`keyAuthorization access key mismatch`});if(n.type!==t.keyType)throw new Y({reason:`keyAuthorization key type mismatch`})}}function wu(e,t){if(hu({request:t}),e.expiry!==pu(fu(t.subscriptionExpires)))throw new Y({reason:`keyAuthorization expiry mismatch`})}function Tu(e){let[t]=e.limits??[];if(!t||e.limits?.length!==1)throw new Y({reason:`keyAuthorization must contain exactly one token limit`});return t}function Eu(e,t){if(!l(e.token,ku(t.currency,`currency`)))throw new Y({reason:`keyAuthorization currency mismatch`});if(e.limit!==BigInt(t.amount))throw new Y({reason:`keyAuthorization amount mismatch`});if(e.period!==mu(t))throw new Y({reason:`keyAuthorization period mismatch`})}function Du(e,t){if(!e||e.length!==1)throw new Y({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=ku(t.currency,`currency`),r=ku(t.recipient,`recipient`),i=new Set;for(let t of e){if(!l(t.address,n))throw new Y({reason:`keyAuthorization call target mismatch`});let e=Au(t.selector);if(e!==`0xa9059cbb`&&e!==`0x95777d59`)throw new Y({reason:`keyAuthorization selector not allowed`});if(i.has(e))throw new Y({reason:`keyAuthorization duplicate selector`});if(i.add(e),t.recipients?.length!==1||!l(t.recipients[0],r))throw new Y({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new Y({reason:`keyAuthorization must allow transferWithMemo`})}function Ou(e,t){let n=R.getSignPayload(e);try{let e=z.extractAddress({payload:n,signature:t});if(!z.verify(t,{address:e,payload:n}))throw new Y({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof Y?e:new Y({reason:`keyAuthorization signature is invalid`})}}function ku(e,t){if(!c(e))throw new Y({reason:`${t} must be an address`});return e.toLowerCase()}function Au(e){return typeof e==`string`?e.toLowerCase():``}const ju=U.object({accessKey:U.optional(U.custom()),account:U.optional(U.custom())});function Mu(e={}){let t=Oa({chain:P,getClient:e.getClient,rpcUrl:Gn}),n=wa({account:e.account});return Nt(vo,{context:ju,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??X.testnet,o=await t({chainId:a}),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.");Pu(r.request),await e.validateRequest?.(r.request);let u=await Nu(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),d=yu({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:R.serialize(u),type:`keyAuthorization`},request:r.request});if(!l(d.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return Tt({challenge:r,payload:{signature:R.serialize(u),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function Nu(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await vu({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:pu(fu(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:E.fromNumber(BigInt(o.amount)),period:mu(o)}],scopes:gu(o),witness:_u(i)}]});return R.fromRpc(c.keyAuthorization)}function Pu(e){mu(e),pu(fu(e.subscriptionExpires))}const Fu=Object.assign(Ql,{manager:lu});function Iu(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[bo(e),Fu(n)]}(function(e){e.charge=bo,e.common=Iu,e.session=Fu,e.subscription=Mu})(Iu||={});const Lu=N.union([N.boolean(),N.literal(`true`).transform(()=>!0),N.literal(`false`).transform(()=>!1)]);async function Ru(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}const zu=N.object({allowCustomEscrow:N.optional(Lu),autoSwap:N.optional(Lu),channel:N.optional(N.coerce.string()),deposit:N.optional(N.union([N.string(),N.number()])),payWith:N.optional(N.string()),slippage:N.optional(N.coerce.number()),tokenIn:N.optional(N.string())}),Bu=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`];function Vu(){let t;return dr({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:n,options:r,methodOpts:i}){let a=sr(r.account),o=n.request,c=o.currency,l=qu(i),u=Zu({autoSwap:l.autoSwap??r.autoSwap,payWith:l.payWith??r.payWith,slippage:l.slippage??r.slippage,tokenIn:l.tokenIn}),d=c??``,f=o.decimals??6,p,m,h,g=!1,_=process.env.MPPX_PRIVATE_KEY?.trim()||(qn(a)?void 0:await cr(a).get());if(!_&&qn(a)&&od()){g=!0;let t=id(a);if(t){let i=Xn(r.rpcUrl,{network:r.network});h=e({chain:await Zn({network:r.network,rpcUrl:i}),transport:s(i)}),Yu({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let a=c?await er(h,c,t.wallet_address).catch(()=>void 0):void 0;d=a?.symbol??c??``,f=a?.decimals??o.decimals??6}}else if(_)m=le(_);else{let e=cd();if(e){let t=await cr(e).get();t&&(m=le(t))}if(!m)throw r.account?new Bn({code:`ACCOUNT_NOT_FOUND`,message:`Account "${a}" not found.`,exitCode:69}):new Bn({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!g&&m){let t=Xn(r.rpcUrl,{network:r.network});h=e({chain:await Zn({network:r.network,rpcUrl:t}),transport:s(t)}),Yu({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let i=c?await er(h,c,m.address).catch(()=>void 0):void 0;d=i?.symbol??c??``,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 sd(t)}};if(!m||!h)throw new Bn({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let v=Iu({account:m,...l.allowCustomEscrow===void 0?{}:{allowCustomEscrow:l.allowCustomEscrow},getClient:()=>h,...u===void 0?{}:{autoSwap:u},maxDeposit:(()=>{if(n.intent!==`session`)return;let e=n.request.suggestedDeposit,t=(l.deposit===void 0?void 0:String(l.deposit))??e??($n(h.chain)?`10`:void 0);if(!t)throw new Bn({code:`MISSING_DEPOSIT`,message:`Session payment requires a deposit. Use -M deposit=<amount> or connect to testnet.`,exitCode:2});return t})()}),y=(()=>{if(!l.channel)return;let e=l.channel,t=$u(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 us(h,m,c,i,a);return Tt({challenge:n,payload:{action:o,channelId:e,...o===`close`?{closeSignature:await ds(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=xt(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?` ${Z.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
8
9
  `}${Z.dim(`Channel opened ${h.payload.channelId}`)}${t}\n`)}else m(`${l?``:`
9
- `}${Z.dim(`Channel reused ${h.payload.channelId}`)}\n`)}let w=i;w.ok&&!w.headers.get(`Content-Type`)?.includes(`text/event-stream`)&&h.payload.action===`open`&&`cumulativeAmount`in h.payload&&(S=BigInt(h.payload.cumulativeAmount));let T=w.headers.get(B.paymentReceipt);if(T)try{let e=JSON.parse(C.toString(T));Eu(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&Lu(v,S),s>=1&&Tu(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
10
- `})}catch{}return(w.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await Du(w,{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 xu(w),v&&y&&b&&(l&&m(`
11
- `),l&&!await e.confirm(`Close channel?`,!0)?s>=1&&m(`${Z.dim(`Kept channel open.`)}\n`):await Ou({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 Tu(e,t){t.info(`${t.prefix??``}${Z.bold(Z.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} ${Z.dim(`(${Yn(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,qn(`${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(` ${Z.dim(e.padEnd(a))} ${r}\n`);t.prefix&&t.info(`
12
- `)}function Eu(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 Du(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 ku():void 0,c=(()=>{if(!s||!Z.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:{[B.authorization]:a}})}catch(e){t.info(Z.dim(Z.yellow(` [voucher failed: ${e instanceof Error?e.message:e}]`)))}o=``;continue}if(o===`payment-receipt`){if(t.verbose>=1)try{Tu(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
10
+ `}${Z.dim(`Channel reused ${h.payload.channelId}`)}\n`)}let w=i;w.ok&&!w.headers.get(`Content-Type`)?.includes(`text/event-stream`)&&h.payload.action===`open`&&`cumulativeAmount`in h.payload&&(S=BigInt(h.payload.cumulativeAmount));let T=w.headers.get(B.paymentReceipt);if(T)try{let e=JSON.parse(C.toString(T));Uu(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&ed(v,S),s>=1&&Hu(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
11
+ `})}catch{}return(w.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await Wu(w,{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 Ru(w),v&&y&&b&&(l&&m(`
12
+ `),l&&!await e.confirm(`Close channel?`,!0)?s>=1&&m(`${Z.dim(`Kept channel open.`)}\n`):await Gu({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 Hu(e,t){t.info(`${t.prefix??``}${Z.bold(Z.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} ${Z.dim(`(${Jn(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,Kn(`${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(` ${Z.dim(e.padEnd(a))} ${r}\n`);t.prefix&&t.info(`
13
+ `)}function Uu(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 Wu(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 Ku():void 0,c=(()=>{if(!s||!Z.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:{[B.authorization]:a}})}catch(e){t.info(Z.dim(Z.yellow(` [voucher failed: ${e instanceof Error?e.message:e}]`)))}o=``;continue}if(o===`payment-receipt`){if(t.verbose>=1)try{Hu(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
13
14
 
14
15
  `})}catch{}o=``;continue}if(e.length===0)u(`
15
16
  `);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(`
16
- `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await Ou({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 Ou(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:{...Fi(e.fetchInit.headers),Authorization:t}});if(n.ok){if(Ru(e.channelId),e.verbose>=1){let t=n.headers.get(B.paymentReceipt),r;if(t)try{let e=JSON.parse(C.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${Z.dim(qn(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${Z.dim(`Channel closed.`)} ${Z.dim(`Spent ${Yn(e.cumulativeAmount,e.tokenSymbol,e.tokenDecimals)}.`)}${i}\n`)}}else{let t=await n.text().catch(()=>``);e.info(`\n${Z.dim(Z.yellow(`Channel close failed`))} ${Z.dim(`(${n.status})`)}\n`),e.info(`${Z.dim(` channelId: ${e.channelId}`)}\n${Z.dim(` cumulativeAmount: ${e.cumulativeAmount}`)}\n${Z.dim(` escrowContract: ${e.escrowContract}`)}\n${Z.dim(` chainId: ${e.chainId}`)}\n${Z.dim(` response: ${t||`(empty)`}`)}\n`)}}function ku(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 Au(e){return ju(Su,e,Cu)}function ju(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 Mu(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 Vn({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function Nu(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function Pu(e){let t=Nu(e.tokenIn)??Nu(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 Fu(){return M.join(process.env.XDG_CONFIG_HOME||M.join(j.homedir(),`.config`),`mppx`,`channels`)}function Iu(e){try{let t=A.readFileSync(M.join(Fu(),e),`utf-8`).trim();return t?BigInt(t):void 0}catch{return}}function Lu(e,t){let n=Fu();A.mkdirSync(n,{recursive:!0}),A.writeFileSync(M.join(n,e),t.toString(),`utf-8`)}function Ru(e){try{A.unlinkSync(M.join(Fu(),e))}catch{}}function zu(){return j.platform()===`darwin`?M.join(j.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):M.join(process.env.XDG_DATA_HOME||M.join(j.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function Bu(){try{let e=A.readFileSync(zu(),`utf-8`),t=[],n;for(let r of e.split(`
17
- `)){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 Vu(e){let t=Bu();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 Hu;function Uu(){if(Hu!==void 0)return Hu;try{k.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),Hu=!0}catch{Hu=!1}return Hu}async function Wu(e){return new Promise((t,n)=>{k.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 Gu(){let e=sr();if(Jn(e.get())&&!Uu()&&j.platform()===`darwin`)try{let t=k.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 Ku=[...Object.entries(we),...Object.entries(Te),...Object.entries(Ee),...Object.entries(De)];function qu(){return fr({method:`evm`,supports:Ju,async setup({challenge:e,options:t}){let n=e.request,r=n.network?Yu(Pe(n.network)):void 0,i=n.network&&n.asset?Ku.find(([,e])=>Me(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`?Se({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await dr(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...zn({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function Ju(e){if(!Sn(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 Yu(e){return Object.values(b).find(t=>t.id===e)}export{fr as createPlugin,pr as evm,Sr as stripe,wu as tempo,qu as x402};
17
+ `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await Gu({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 Gu(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:{...Hi(e.fetchInit.headers),Authorization:t}});if(n.ok){if(td(e.channelId),e.verbose>=1){let t=n.headers.get(B.paymentReceipt),r;if(t)try{let e=JSON.parse(C.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${Z.dim(Kn(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${Z.dim(`Channel closed.`)} ${Z.dim(`Spent ${Jn(e.cumulativeAmount,e.tokenSymbol,e.tokenDecimals)}.`)}${i}\n`)}}else{let t=await n.text().catch(()=>``);e.info(`\n${Z.dim(Z.yellow(`Channel close failed`))} ${Z.dim(`(${n.status})`)}\n`),e.info(`${Z.dim(` channelId: ${e.channelId}`)}\n${Z.dim(` cumulativeAmount: ${e.cumulativeAmount}`)}\n${Z.dim(` escrowContract: ${e.escrowContract}`)}\n${Z.dim(` chainId: ${e.chainId}`)}\n${Z.dim(` response: ${t||`(empty)`}`)}\n`)}}function Ku(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 qu(e){return Ju(zu,e,Bu)}function Ju(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 Yu(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 Bn({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function Xu(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function Zu(e){let t=Xu(e.tokenIn)??Xu(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 Qu(){return M.join(process.env.XDG_CONFIG_HOME||M.join(j.homedir(),`.config`),`mppx`,`channels`)}function $u(e){try{let t=A.readFileSync(M.join(Qu(),e),`utf-8`).trim();return t?BigInt(t):void 0}catch{return}}function ed(e,t){let n=Qu();A.mkdirSync(n,{recursive:!0}),A.writeFileSync(M.join(n,e),t.toString(),`utf-8`)}function td(e){try{A.unlinkSync(M.join(Qu(),e))}catch{}}function nd(){return j.platform()===`darwin`?M.join(j.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):M.join(process.env.XDG_DATA_HOME||M.join(j.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function rd(){try{let e=A.readFileSync(nd(),`utf-8`),t=[],n;for(let r of e.split(`
18
+ `)){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 id(e){let t=rd();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 ad;function od(){if(ad!==void 0)return ad;try{k.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),ad=!0}catch{ad=!1}return ad}async function sd(e){return new Promise((t,n)=>{k.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 cd(){let e=or();if(qn(e.get())&&!od()&&j.platform()===`darwin`)try{let t=k.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 ld=[...Object.entries(Ce),...Object.entries(we),...Object.entries(Te),...Object.entries(Ee)];function ud(){return dr({method:`evm`,supports:dd,async setup({challenge:e,options:t}){let n=e.request,r=n.network?fd(Ne(n.network)):void 0,i=n.network&&n.asset?ld.find(([,e])=>je(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`?xe({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await ur(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...Rn({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function dd(e){if(!xn(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 fd(e){return Object.values(b).find(t=>t.id===e)}export{dr as createPlugin,fr as evm,xr as stripe,Vu as tempo,ud as x402};