mppx 0.18.0 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/Currency.d.ts +59 -0
  3. package/dist/Currency.js +60 -0
  4. package/dist/Errors.d.ts +13 -0
  5. package/dist/Errors.js +15 -6
  6. package/dist/cli/cli.js +135 -135
  7. package/dist/cli/plugins/index.js +12 -12
  8. package/dist/cli/plugins/tempo.js +13 -1
  9. package/dist/client/internal/Fetch.d.ts +5 -0
  10. package/dist/client/internal/Fetch.js +7 -0
  11. package/dist/cloudflare/ChannelStore.d.ts +1 -2
  12. package/dist/cloudflare/ChannelStore.js +14 -20
  13. package/dist/cloudflare/Channels.d.ts +20 -2
  14. package/dist/cloudflare/Channels.js +47 -4
  15. package/dist/cloudflare/index.d.ts +1 -1
  16. package/dist/cloudflare/index.js +1 -1
  17. package/dist/discovery/Discovery.d.ts +116 -9
  18. package/dist/discovery/Discovery.js +169 -0
  19. package/dist/evm/server/Charge.js +2 -3
  20. package/dist/evm/server/Methods.d.ts +1 -1
  21. package/dist/evm/server/Methods.js +3 -2
  22. package/dist/extensions/identity/email-otp/client/index.js +4 -4
  23. package/dist/extensions/identity/index.d.ts +4 -0
  24. package/dist/extensions/identity/index.js +4 -0
  25. package/dist/extensions/identity/link/Constants.d.ts +102 -0
  26. package/dist/extensions/identity/link/Constants.js +16 -0
  27. package/dist/extensions/identity/link/client/index.d.ts +80 -0
  28. package/dist/extensions/identity/link/client/index.js +211 -0
  29. package/dist/extensions/identity/link/index.d.ts +12 -0
  30. package/dist/extensions/identity/link/index.js +12 -0
  31. package/dist/extensions/identity/link/server/index.d.ts +124 -0
  32. package/dist/extensions/identity/link/server/index.js +518 -0
  33. package/dist/extensions/identity/persona/Constants.d.ts +24 -0
  34. package/dist/extensions/identity/persona/Constants.js +24 -0
  35. package/dist/extensions/identity/persona/Did.d.ts +24 -0
  36. package/dist/extensions/identity/persona/Did.js +24 -0
  37. package/dist/extensions/identity/persona/Types.d.ts +21 -0
  38. package/dist/extensions/identity/persona/Types.js +2 -0
  39. package/dist/extensions/identity/persona/index.d.ts +10 -0
  40. package/dist/extensions/identity/persona/index.js +9 -0
  41. package/dist/extensions/identity/persona/server/index.d.ts +152 -0
  42. package/dist/extensions/identity/persona/server/index.js +263 -0
  43. package/dist/identity/Headers.d.ts +6 -1
  44. package/dist/identity/Headers.js +6 -1
  45. package/dist/identity/Server.js +2 -0
  46. package/dist/identity/Types.d.ts +5 -0
  47. package/dist/index.d.ts +1 -0
  48. package/dist/index.js +1 -0
  49. package/dist/internal/version.d.ts +2 -2
  50. package/dist/internal/version.js +1 -1
  51. package/dist/proxy/internal/Headers.js +4 -4
  52. package/dist/server/Mppx.js +5 -2
  53. package/dist/stripe/server/internal/html.gen.js +1 -1
  54. package/dist/tempo/client/Charge.d.ts +11 -8
  55. package/dist/tempo/client/Charge.js +53 -6
  56. package/dist/tempo/index.d.ts +4 -0
  57. package/dist/tempo/index.js +4 -0
  58. package/dist/tempo/internal/auto-swap.d.ts +6 -5
  59. package/dist/tempo/internal/auto-swap.js +17 -2
  60. package/dist/tempo/internal/currencies.d.ts +5 -4
  61. package/dist/tempo/internal/currencies.js +13 -9
  62. package/dist/tempo/internal/defaults.d.ts +7 -0
  63. package/dist/tempo/internal/defaults.js +7 -0
  64. package/dist/tempo/internal/fee-payer.js +8 -2
  65. package/dist/tempo/internal/machine-token-charge.d.ts +52 -0
  66. package/dist/tempo/internal/machine-token-charge.js +82 -1
  67. package/dist/tempo/server/Charge.js +59 -2
  68. package/dist/tempo/server/Methods.d.ts +1 -1
  69. package/dist/tempo/server/internal/html.gen.js +1 -1
  70. package/dist/tempo/server/internal/transport.d.ts +1 -1
  71. package/dist/tempo/server/internal/transport.js +9 -16
  72. package/dist/tempo/session/client/CredentialState.js +31 -0
  73. package/dist/tempo/session/client/Session.d.ts +12 -6
  74. package/dist/tempo/session/client/Session.js +64 -18
  75. package/dist/tempo/session/server/ChannelStore.d.ts +22 -1
  76. package/dist/tempo/session/server/ChannelStore.js +58 -8
  77. package/dist/tempo/session/server/CloseSupervisor.d.ts +5 -1
  78. package/dist/tempo/session/server/CloseSupervisor.js +110 -12
  79. package/dist/tempo/session/server/CredentialVerification.d.ts +2 -0
  80. package/dist/tempo/session/server/CredentialVerification.js +6 -32
  81. package/dist/tempo/session/server/Session.js +6 -3
  82. package/dist/tempo/session/server/Settlement.d.ts +7 -0
  83. package/dist/tempo/session/server/Settlement.js +36 -6
  84. package/dist/tempo/session/server/Sse.d.ts +2 -0
  85. package/dist/tempo/session/server/Sse.js +12 -12
  86. package/dist/tempo/subscription/KeyAuthorization.d.ts +1 -1
  87. package/dist/tempo/subscription/KeyAuthorization.js +1 -1
  88. package/dist/x402/Assets.d.ts +14 -5
  89. package/dist/x402/Assets.js +11 -16
  90. package/package.json +15 -3
@@ -1,22 +1,22 @@
1
- import{createClient as e,createTransport as t,custom as n,encodeFunctionData as r,erc20Abi as i,getAbiItem as a,getAddress as o,hashTypedData as s,http as c,isAddress as l,isAddressEqual as u,keccak256 as d,parseAbi as f,parseEventLogs as p,parseUnits as m}from"viem";import{call as h,getBlockNumber as g,getLogs as _,prepareTransactionRequest as v,readContract as y,sendCallsSync as b,sendRawTransactionSync as x,sendTransactionSync as S,signTransaction as C,signTypedData as w,waitForTransactionReceipt as T}from"viem/actions";import*as E from"viem/chains";import{tempo as ee}from"viem/chains";import{AbiParameters as te,Base64 as D,Bytes as O,Hash as k,Hex as A,Json as j}from"ox";import*as M from"zod/mini";import*as N from"node:child_process";import*as P from"node:fs";import*as F from"node:os";import*as I from"node:path";import{z as L}from"zod";import"node:readline";import{tempo as R,tempoModerato as ne}from"viem/tempo/chains";import{ousd as re,pathusd as ie,usdce as ae}from"viem/tokens";import{Abis as oe,Account as se,Actions as z,Addresses as ce,TokenId as le,Transaction as ue,withFeePayer as de}from"viem/tempo";import{parseAccount as fe,privateKeyToAccount as pe}from"viem/accounts";import{Channel as me,KeyAuthorization as he,SignatureEnvelope as B,TempoAddress as ge,TxEnvelopeTempo as _e}from"ox/tempo";var ve=Object.defineProperty,ye=Object.getOwnPropertyDescriptor,be=Object.getOwnPropertyNames,xe=Object.prototype.hasOwnProperty,Se=(e,t)=>{let n={};for(var r in e)ve(n,r,{get:e[r],enumerable:!0});return t||ve(n,Symbol.toStringTag,{value:`Module`}),n},Ce=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=be(t),a=0,o=i.length,s;a<o;a++)s=i[a],!xe.call(e,s)&&s!==n&&ve(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=ye(t,s))||r.enumerable});return e},we=(e,t,n)=>(Ce(e,t,`default`),n&&Ce(n,t,`default`));const Te=Symbol(`mppx.x402.asset`);function Ee(e){return{[Te]:!0,address:e.address,decimals:e.decimals,network:e.network,transfer:e.transfer}}function De(e,t){let n=e(t.chainId);return Ee({address:n.address,decimals:n.decimals,network:Le(t.chainId),transfer:ze(t.transfer,n)})}const Oe={USDC:Ee({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},ke={USDC:Ee({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},Ae={USDC:Ee({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:Ee({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},je={USDC:Ee({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})};function Me(e){return typeof e!=`object`||!e?!1:e[Te]===!0}function Ne(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function Pe(e){return typeof e==`string`}function Fe(e,t){if(Me(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(Ne(e)){let n=e.addresses[Re(t)];return n?{address:n,decimals:e.decimals,name:e.name}:void 0}return{address:e}}function Ie(e,t,n){let r=Fe(e,n);return r?o(r.address)===o(t):!1}function Le(e){return`eip155:${e}`}function Re(e){return Number(e.slice(7))}function ze(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 Be=Se({base:()=>Oe,baseSepolia:()=>ke,celo:()=>Ae,celoSepolia:()=>je,define:()=>Ee,fromToken:()=>De,isAsset:()=>Me,isRawAddress:()=>Pe,isToken:()=>Ne,matches:()=>Ie,resolve:()=>Fe,toChainId:()=>Re,toNetwork:()=>Le}),Ve=Se({base:()=>He,baseSepolia:()=>Ue,celo:()=>We,celoSepolia:()=>Ge});const He=8453,Ue=84532,We=42220,Ge=11142220,V={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},Ke={payment:`Payment`},qe={evm:`evm`,stripe:`stripe`,tempo:`tempo`},Je={charge:`charge`,session:`session`,subscription:`subscription`},Ye={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},Xe={v1:`v1`,v2:`v2`};function Ze(e,t){if(!(!e||typeof e!=`object`))return e[t]}function Qe(e){let t=D.toString(e);return JSON.parse(t)}function H(e){let t=j.canonicalize(e);return D.fromString(t,{pad:!1,url:!0})}var U=Se({address:()=>G,amount:()=>W,datetime:()=>et,datetimeInput:()=>tt,hash:()=>K,period:()=>it,signature:()=>q,toDate:()=>nt,toDatetimeString:()=>rt,unwrapOptional:()=>at});import*as $e from"zod/mini";we(U,$e);function W(){return M.string().check(M.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function et(){return M.string().check(M.regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,`Invalid ISO 8601 datetime`))}function tt(e=`Invalid ISO 8601 datetime`){return M.pipe(M.union([et(),M.custom(e=>e instanceof Date)]),M.transform(nt)).check(M.refine(e=>Number.isFinite(e.getTime()),e))}function nt(e){return e instanceof Date?e:new Date(e)}function rt(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function G(){return M.string().check(M.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function K(){return M.string().check(M.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function it(){return M.string().check(M.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function q(){return M.string().check(M.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function at(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}const ot=U.object({description:U.optional(U.string()),digest:U.optional(U.string().check(U.regex(/^sha-256=/,`Invalid digest format`))),expires:U.optional(et()),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 st(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=St(o)?void 0:o,f=e.expires?rt(e.expires):void 0,p=e.opaque??(i===void 0?void 0:H(i)),m=u?Ct({...e,expires:f,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return ot.parse({id:m,realm:c,method:a,intent:s,request:l,...n&&{description:n},...r&&{digest:r},...f&&{expires:f},...d!==void 0&&{header:d},...i!==void 0&&{meta:i},...p!==void 0&&{opaque:p}})}function ct(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&&!St(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)),`${Ke.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 lt(e,t){let n=ut(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,...a}=dt(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 st({...a,request:Qe(r),...i&&{opaque:i}},t)}function ut(e){let t=Ke.payment,[n]=gt(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 dt(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]=ft(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function ft(e,t){if(e[t]===`"`)return pt(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function pt(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 mt(e,t,n){if(e.slice(t,t+n.length).toLowerCase()!==n.toLowerCase())return!1;let r=e[t+n.length];return!!(r&&/\s/.test(r))}function ht(e){return gt(e,Ke.payment).length>0||e.split(`,`).some(e=>e.trim().toLowerCase()===Ke.payment.toLowerCase())}function gt(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(!mt(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 _t(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return vt(e.headers,t)}function vt(e,t){let n=e.get(V.wwwAuthenticate);if(!n)throw Error(`Missing ${V.wwwAuthenticate} header.`);return yt(n,t)}function yt(e,t){let n=gt(e,Ke.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 lt(e.slice(r,a).replace(/,\s*$/,``),t)})}function bt(e){let t=[e.realm,e.method,e.intent,H(e.request),e.expires??``,e.digest??``],n=e.header;return n!==void 0&&!St(n)&&t.push(n),t.push(e.opaque??(e.meta?H(e.meta):``)),t.join(`|`)}function xt(e){return e.header??V.authorization}function St(e){return e?.toLowerCase()===V.authorization.toLowerCase()}function Ct(e,t){let n=bt(e),r=O.fromString(t.secretKey),i=O.fromString(n),a=k.hmac256(r,i,{as:`Bytes`});return D.fromBytes(a,{url:!0,pad:!1})}const wt=65536;var Tt=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},Et=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}};function Dt(e){if(e.length>wt)throw new Et;let t=e.match(RegExp(`^${Ke.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new Tt;try{let e=D.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=Ot(r);return{challenge:ot.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:Qe(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new Et}}function Ot(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!kt(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:H(e)}}function kt(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function At(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function jt(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=D.fromString(s,{pad:!1,url:!0});return`${Ke.payment} ${c}`}function Mt(e){return e.length>wt?null:e.split(`,`).map(e=>e.trim()).find(e=>RegExp(`^${Ke.payment}\\s+`,`i`).test(e))??null}var Nt=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}}}},Pt=class extends Nt{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 Nt{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})}},Ft=class extends Nt{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.`)}},It=class extends Nt{name=`PaymentOutcomeUnknownError`;title=`Payment Outcome Unknown`;type=`https://paymentauth.org/problems/payment-outcome-unknown`;challenge;credential;transactionHash;constructor(e){let{cause:t,challenge:n,credential:r,transactionHash:i}=e;super(`Payment outcome is unknown after sending a credential for challenge "${n.id}". Do not blindly retry.`,{cause:t}),this.challenge=n,this.credential=r,this.transactionHash=i}},Lt=class extends Error{name=`ZoneSettlementPendingError`;challengeId;senderTag;zoneId;constructor(e){let{cause:t,challengeId:n,senderTag:r,zoneId:i}=e;super(`Zone ${i} withdrawal ${r} for challenge "${n}" has not settled on Tempo yet. Retry the challenge to resume waiting instead of paying again.`),this.challengeId=n,this.senderTag=r,this.zoneId=i,t!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t,writable:!0})}};function Rt(e,t){if(!e)throw new Pt({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new Pt({...t&&{id:t},reason:`malformed expires timestamp`});if(Date.parse(e)<=Date.now())throw new Ft({expires:e})}function zt(e){return e}function Bt(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}function Vt(e){return{encode(t){return D.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(D.toString(t)))}catch{throw new Ht}}}}var Ht=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}};const Ut=[`exact`],Wt=`PAYMENT-REQUIRED`,Gt=`PAYMENT-SIGNATURE`,Kt=U.string().check(U.minLength(1)),qt=U.number().check(U.refine(e=>e>0,`Must be positive`)),Jt=U.string().check(U.regex(/^\d+$/,`Invalid atomic amount`)),Yt=G(),Xt=U.string().check(U.regex(RegExp(`^eip155:\\d+$`),`Invalid EVM CAIP-2 network`)),Zt=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:Kt});U.discriminatedUnion(`type`,[U.object({name:Kt,type:U.literal(`eip3009`),version:Kt}),U.object({name:U.optional(U.string()),type:U.literal(`permit2`),version:U.optional(U.string())})]);const Qt=U.object({amount:Jt,asset:Kt,extra:U.optional(U.record(U.string(),U.unknown())),maxTimeoutSeconds:qt,network:Xt,payTo:Kt,scheme:U.enum(Ut)}),$t=U.object({info:U.record(U.string(),U.unknown()),schema:U.record(U.string(),U.unknown())}),en=U.record(U.string(),$t),tn=U.object({accepts:U.array(Qt).check(U.minLength(1)),error:U.optional(U.string()),extensions:U.optional(en),resource:Zt,x402Version:U.literal(2)}),nn=U.object({authorization:U.object({from:Yt,nonce:K(),to:Yt,validAfter:Jt,validBefore:Jt,value:Jt}),signature:q()}),rn=U.object({permit2Authorization:U.object({deadline:Jt,from:Yt,nonce:Jt,permitted:U.object({amount:Jt,token:Yt}),spender:Yt,witness:U.object({to:Yt,validAfter:Jt})}),signature:q()}),an=U.union([nn,rn]),on=U.object({accepted:Qt,extensions:U.optional(en),payload:an,resource:U.optional(Zt),x402Version:U.literal(2)});U.object({extensions:U.optional(en),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 sn=U.object({amount:U.optional(Jt),errorMessage:U.optional(U.string()),errorReason:U.optional(U.string()),extensions:U.optional(en),extra:U.optional(U.record(U.string(),U.unknown())),network:Kt,payer:U.optional(U.string()),success:U.boolean(),transaction:U.string()});function cn(e){let{extensions:t,resource:n,...r}=e;return Qt.parse(r)}const ln=Vt(tn),un=Vt(on),dn=Vt(sn);ln.encode,ln.decode;function fn(e){try{let t=JSON.parse(D.toString(e));return mn(t)}catch{throw new Ht}}const pn=un.encode;un.decode,dn.encode,dn.decode;const mn=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new Ht;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new Ht;let n=Zt.parse(t.resource),r=t.extensions===void 0?void 0:en.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}};function hn(e){let t=[H(e.accepted),H(e.resource),H(e.extensions)].join(`|`);return k.sha256(O.fromString(t),{as:`Hex`})}async function gn(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=cn(n);if(bn(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?Sn(n.extensions):n.extensions,a=r.extra?.assetTransferMethod??`eip3009`;if(a!==`eip3009`)throw Error(`x402 exact ${String(a)} 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:o(t.address),nonce:i?.mppx?hn({accepted:r,extensions:i,resource:n.resource}):wn(),to:o(r.payTo),validAfter:(l-600).toString(),validBefore:(l+r.maxTimeoutSeconds).toString(),value:r.amount},d=await t.signTypedData({domain:{chainId:yn(r.network),name:s,verifyingContract:o(r.asset),version:c},message:{...u,value:BigInt(u.value),validAfter:BigInt(u.validAfter),validBefore:BigInt(u.validBefore)},primaryType:`TransferWithAuthorization`,types:vn});return pn({accepted:r,...i?{extensions:i}:{},payload:{authorization:u,signature:d},...n.resource?{resource:n.resource}:{},x402Version:2})}function _n(e){let t=e.challenge.request,n;try{n=cn(t),bn(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 vn={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 yn(e){return Number(e.slice(7))}function bn(e,t){let n=yn(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=>Pe(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=o(t.asset);if(!r.some(n=>Ie(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=xn(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>m(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function xn(e,t){let n=e.currencies??e.assets,r=o(t.asset),i=n?.find(e=>Ie(e,r,t.network)),a=i?Fe(i,t.network):void 0;return a?.decimals===void 0?e.decimals:a.decimals}function Sn(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:Cn()}}}:e}function Cn(){return Tn().slice(2)}function wn(){return Tn()}function Tn(){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 En=Symbol.for(`mppx.x402.challenge`);function Dn(e){return Object.defineProperty(e,En,{value:!0}),e}function On(e){return!!e?.[En]}const kn=[`authorization`],An=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 jn=U.object({chainId:U.number(),credentialTypes:U.optional(U.array(U.enum(kn)).check(U.minLength(1))),decimals:U.optional(U.number()),permit2Address:U.optional(G()),splits:U.optional(U.array(U.object({amount:An,recipient:G()})))});U.object({amount:An,currency:G(),description:U.optional(U.string()),externalId:U.optional(U.string()),methodDetails:jn,recipient:G()});const Mn=U.object({amount:W(),chainId:U.number(),currency:G(),credentialTypes:U.optional(U.array(U.enum(kn)).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:An,recipient:G()})))}),Nn=U.object({from:G(),nonce:K(),signature:q(),to:G(),type:U.literal(`authorization`),validAfter:An,validBefore:An,value:An}),Pn={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{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function In(e){return k.keccak256(O.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function Ln(e){return`eip155:${e}`}function Rn(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const zn=zt({name:`evm`,intent:`charge`,schema:{credential:{payload:Nn},request:U.pipe(Mn,U.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:s,splits:c,...l})=>({...l,amount:m(e,i).toString(),currency:o(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:o(a)}:{},...c?{splits:c}:{}},recipient:o(s)})))}});function Bn(e){return Bt(zn,{canHandleChallenge({challenge:t}){return!Vn(t)||_n({challenge:t,config:e})},context:U.object({account:U.optional(U.custom())}),async createCredential({challenge:t,context:n}){if(Vn(t))return gn({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(Hn(e,i),!i.methodDetails.credentialTypes?.includes(`authorization`))throw Error(`EVM authorization is not accepted by this challenge.`);if(i.methodDetails.splits?.length)throw Error(`EVM authorization does not support payment splits.`);let a=Un(e,i),s=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return jt(At({challenge:t,payload:{from:o(r.address),nonce:In(t),signature:await r.signTypedData({domain:Fn({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:o(r.address),nonce:In(t),to:o(i.recipient),validAfter:0n,validBefore:BigInt(s),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:Pn}),to:o(i.recipient),type:`authorization`,validAfter:`0`,validBefore:s,value:i.amount},source:Rn({address:o(r.address),chainId:i.methodDetails.chainId})}))}})}function Vn(e){return On(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function Hn(e,t){let n=t.methodDetails.chainId,r=Ln(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=>Pe(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=o(t.currency);if(!i.some(t=>Ie(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=Wn(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>m(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function Un(e,t){let n=e.currencies??e.assets,r=o(t.currency),i=Ln(t.methodDetails.chainId),a=n?.find(e=>Ie(e,r,i)),s=a?Fe(a,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 Wn(e,t){let n=e.currencies??e.assets,r=o(t.currency),i=Ln(t.methodDetails.chainId),a=n?.find(e=>Ie(e,r,i)),s=a?Fe(a,i):void 0;return s?.decimals===void 0?e.decimals:s.decimals}function Gn(e){return[Gn.charge(e)]}(function(e){e.charge=Bn,e.assets=Be,e.chains=Ve})(Gn||={});var Kn=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 Jn(this,e)}},qn=class extends Kn{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 Jn(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},Yn={ousd:re(X.mainnet).address,usdc:o(ae(X.mainnet).address),pathUsd:ie(X.mainnet).address},Xn={[X.mainnet]:Yn.usdc,[X.testnet]:Yn.pathUsd},Zn=Object.freeze({[X.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[X.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})});X.mainnet,X.testnet;const Qn={[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 $n(e,t){return Z.link(e,t)}function er(e){return e.startsWith(`tempo:`)}function tr(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 nr={mainnet:Qn[X.mainnet],testnet:Qn[X.testnet]};function rr(e,t={}){return e??(t.network?nr[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}async function ir(t={}){let n=rr(t.rpcUrl,{network:t.network});if(!n)return R;let{getChainId:r}=await import(`viem/actions`),i=await r(e({transport:c(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 ar(e){return typeof e==`bigint`?e:e.amount}function or(e){return e.id!==R.id}async function sr(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(ar).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 cr(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:1e4}function lr(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function ur(e){return new qn({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 dr(e){if(e&&lr(e,`secret-tool`))throw ur(e)}function fr(e,t){return new Promise(n=>{N.execFile(e,t,{timeout:cr()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function pr(){let e=I.join(process.env.XDG_CONFIG_HOME||I.join(F.homedir(),`.config`),`mppx`,`default`);return{get(){try{return P.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(t){P.mkdirSync(I.dirname(e),{recursive:!0}),P.writeFileSync(e,t,`utf-8`)},clear(){try{P.unlinkSync(e)}catch{}}}}function mr(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:pr().get())}function hr(e=`main`){let t=`mppx`;return{async list(){let e=F.platform();if(e===`darwin`){let{stdout:e,error:n}=await fr(`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 fr(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(dr(r),r)return[];let i=`${e}\n${n}`,a=[],o=i.matchAll(/\baccount = (.+)/g);for(let e of o)e[1]&&a.push(e[1]);return a}throw Error(`Unsupported platform: ${e}`)},async get(){let n=F.platform();if(n===`darwin`){let{stdout:n,error:r}=await fr(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await fr(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return dr(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=F.platform();if(r===`darwin`){await fr(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await fr(`security`,[`add-generic-password`,`-s`,t,`-a`,e,`-w`,n]);if(r)throw r;return}if(r===`linux`){let r=N.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),cr());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(lr(e,`secret-tool`)?ur(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=F.platform();if(n===`darwin`){await fr(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await fr(`secret-tool`,[`clear`,`service`,t,`account`,e]);dr(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function gr(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=mr(e),i=await hr(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function _r(e){return(await gr(e)).account}function vr(e){return e}function yr(){return vr({method:`evm`,supports:e=>e.method===`evm`&&!On(e),async setup({challenge:t,options:n}){let r=t.request,a=r.methodDetails,o=a?.chainId,s=o?br(o):void 0,l=r.currency,u=await _r(n.account),d=[...Object.values(Oe),...Object.values(ke),...Object.values(Ae),...Object.values(je)],f=l??``;if(s&&l)try{let t=e({chain:s,transport:c()}),n=await y(t,{address:l,abi:i,functionName:`symbol`});n&&(f=n)}catch{}return{tokenSymbol:f,tokenDecimals:a?.decimals??6,explorerUrl:s?.blockExplorers?.default?.url,methods:[...Gn({account:u,currencies:d})]}}})}function br(e){return Object.values(E).find(t=>t.id===e)}function xr(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 Sr=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)))}),Cr=U.custom(e=>typeof e==`function`),wr=U.union([Sr,Cr]),Tr=zt({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(wr),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:xr(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});function Er(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return Bt(Tr,{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 jt({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function Dr(e){return[Er(e)]}(function(e){e.charge=Er})(Dr||={});function Or(){return vr({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=Ar(L.object({paymentMethod:L.string(),secretKey:L.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new qn({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:[Dr.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=kr(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 qn({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${(await d.json()).error.message}`,exitCode:77})}else throw new qn({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&&kr(e)?`/test`:``}/payments/${t}`;return Z.link(n,t,!0)}}})}function kr(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function Ar(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 jr=Symbol.for(`mppx.fetch.skipPayment`);Object.freeze({phase:`unproved`});function Mr(e,t,n={}){return async(r,i)=>{let a=new Request(r,i),o=Nr(a.headers)??n.challenge,{response:s}=await t.send((t,n)=>e(t,{...n,...i?.[jr]?{[jr]:!0}:{}}),a,{...n,challenge:o});if(s.status===402&&o)for(let e of Pr(s))e.method===o.method&&e.intent===o.intent&&await t.challenge(s,{challenge:e},a.url);return s}}function Nr(e){for(let[,t]of e){let e=Mt(t);if(e)try{return Dt(e).challenge}catch{}}}function Pr(e){try{return _t(e)}catch{return[]}}const Fr=Symbol(`mppx.deferredContext`);function Ir(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=Vr(n)}return t}function Lr(e,t){let n=Ir(e),r=Jr(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[Vr(e)]??1,index:t}));return{definition:r,entries:i,header:zr(i),keys:n}}function Rr(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)=>Kr(e,t))}function zr(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${Qr(n)}`}).join(`, `)}function Br(e,t,n,r){let i=new Map;for(let e of t){let t=Vr(e),n=i.get(t);n?n.push(e):i.set(t,[e])}return e.flatMap((e,t)=>{let a=i.get(Vr(e));if(!a)return[];let o=Hr(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)=>Gr(e.challenge)-Gr(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function Vr(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function Hr(e,t){let n;for(let r of t){if(!Ur(e,r))continue;let t={...r,specificity:Wr(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 Ur(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function Wr(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function Gr(e){return+!!On(e)}function Kr(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}`);$r(r,`method`),$r(i,`intent`);let a=1;for(let t of qr(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=Xr(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function qr(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function Jr(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>Vr(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]=Yr(t,`payment preference "${e}"`)}return a}function Yr(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return Zr(e,t)}function Xr(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 Zr(Number(e),t)}function Zr(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 Qr(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function $r(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}function ei(e){let t=``,n=!1,r=!1,i,a=``;function o(t){if(t===``){i!==void 0&&e({data:i,event:a||`message`}),i=void 0,a=``;return}let n=t.indexOf(`:`);if(n===0)return;let r=n===-1?t:t.slice(0,n);if(r!==`data`&&r!==`event`)return;let o=``;n!==-1&&(o=t.slice(t.charCodeAt(n+1)===32?n+2:n+1)),r===`event`?a=o:i=i===void 0?o:i+`
1
+ import{createClient as e,createTransport as t,custom as n,encodeFunctionData as r,erc20Abi as i,formatUnits as a,getAbiItem as o,getAddress as s,hashTypedData as c,http as l,isAddress as u,isAddressEqual as d,keccak256 as f,parseAbi as p,parseEventLogs as m,parseUnits as h}from"viem";import{call as g,getBlockNumber as _,getLogs as v,prepareTransactionRequest as y,readContract as b,sendCallsSync as ee,sendRawTransactionSync as x,sendTransactionSync as S,signTransaction as C,signTypedData as te,waitForTransactionReceipt as w}from"viem/actions";import*as T from"viem/chains";import{tempo as ne}from"viem/chains";import{AbiParameters as E,Base64 as D,Bytes as O,Hash as k,Hex as A,Json as j}from"ox";import*as M from"zod/mini";import*as N from"node:child_process";import*as P from"node:fs";import*as F from"node:os";import*as I from"node:path";import{z as L}from"zod";import"node:readline";import{tempo as R,tempoModerato as re}from"viem/tempo/chains";import{ousd as ie,pathusd as ae,usdce as oe}from"viem/tokens";import{Abis as se,Account as ce,Actions as z,Addresses as le,TokenId as ue,Transaction as de,withFeePayer as fe}from"viem/tempo";import{parseAccount as pe,privateKeyToAccount as me}from"viem/accounts";import{Channel as he,KeyAuthorization as ge,SignatureEnvelope as B,TempoAddress as _e,TxEnvelopeTempo as ve}from"ox/tempo";var ye=Object.defineProperty,be=Object.getOwnPropertyDescriptor,xe=Object.getOwnPropertyNames,Se=Object.prototype.hasOwnProperty,Ce=(e,t)=>{let n={};for(var r in e)ye(n,r,{get:e[r],enumerable:!0});return t||ye(n,Symbol.toStringTag,{value:`Module`}),n},we=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=xe(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Se.call(e,s)&&s!==n&&ye(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=be(t,s))||r.enumerable});return e},Te=(e,t,n)=>(we(e,t,`default`),n&&we(n,t,`default`));function Ee(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function De(e,t){let{chainId:n,decimals:r}=t;if(typeof e==`string`)return{address:e,chainId:n,decimals:r};if(Ee(e))return e.addresses[n]?e(n):void 0;if(e.chainId===n)return e}function Oe(e,t,n={}){let{chainId:r,decimals:i}=n,a=e=>e.toLowerCase()===t.toLowerCase();for(let t of e){if(typeof t==`string`){if(a(t))return{currency:t,decimals:i};continue}if((r===void 0?Ee(t)?Object.keys(t.addresses).map(e=>De(t,{chainId:Number(e)})):[t]:[De(t,{chainId:r})]).some(e=>e&&a(e.address)))return{currency:t,decimals:t.decimals}}}const ke=Symbol(`mppx.x402.asset`);function Ae(e){return{[ke]:!0,address:e.address,chainId:He(e.network),decimals:e.decimals,network:e.network,transfer:e.transfer}}function je(e,t){let n=e(t.chainId);return Ae({address:n.address,decimals:n.decimals,network:Ve(t.chainId),transfer:Ue(t.transfer,n)})}const Me={USDC:Ae({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},Ne={USDC:Ae({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},Pe={USDC:Ae({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:Ae({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},Fe={USDC:Ae({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})};function Ie(e){return typeof e!=`object`||!e?!1:e[ke]===!0}const Le=Ee;function Re(e){return typeof e==`string`}function ze(e,t){if(Ie(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(typeof e==`string`)return{address:e};let n=De(e,{chainId:He(t)});if(n)return{address:n.address,decimals:n.decimals,name:n.name}}function Be(e,t,n){let r=ze(e,n);return r?s(r.address)===s(t):!1}function Ve(e){return`eip155:${e}`}function He(e){return Number(e.slice(7))}function Ue(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 We=Ce({base:()=>Me,baseSepolia:()=>Ne,celo:()=>Pe,celoSepolia:()=>Fe,define:()=>Ae,fromToken:()=>je,isAsset:()=>Ie,isRawAddress:()=>Re,isToken:()=>Le,matches:()=>Be,resolve:()=>ze,toChainId:()=>He,toNetwork:()=>Ve}),Ge=Ce({base:()=>Ke,baseSepolia:()=>qe,celo:()=>Je,celoSepolia:()=>Ye});const Ke=8453,qe=84532,Je=42220,Ye=11142220,V={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},Xe={payment:`Payment`},Ze={evm:`evm`,stripe:`stripe`,tempo:`tempo`},Qe={charge:`charge`,session:`session`,subscription:`subscription`},$e={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},et={v1:`v1`,v2:`v2`};function tt(e,t){if(!(!e||typeof e!=`object`))return e[t]}function nt(e){let t=D.toString(e);return JSON.parse(t)}function H(e){let t=j.canonicalize(e);return D.fromString(t,{pad:!1,url:!0})}var U=Ce({address:()=>G,amount:()=>W,datetime:()=>it,datetimeInput:()=>at,hash:()=>K,period:()=>ct,signature:()=>q,toDate:()=>ot,toDatetimeString:()=>st,unwrapOptional:()=>lt});import*as rt from"zod/mini";Te(U,rt);function W(){return M.string().check(M.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function it(){return M.string().check(M.regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,`Invalid ISO 8601 datetime`))}function at(e=`Invalid ISO 8601 datetime`){return M.pipe(M.union([it(),M.custom(e=>e instanceof Date)]),M.transform(ot)).check(M.refine(e=>Number.isFinite(e.getTime()),e))}function ot(e){return e instanceof Date?e:new Date(e)}function st(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function G(){return M.string().check(M.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function K(){return M.string().check(M.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function ct(){return M.string().check(M.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function q(){return M.string().check(M.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function lt(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}const ut=U.object({description:U.optional(U.string()),digest:U.optional(U.string().check(U.regex(/^sha-256=/,`Invalid digest format`))),expires:U.optional(it()),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 dt(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=Et(o)?void 0:o,f=e.expires?st(e.expires):void 0,p=e.opaque??(i===void 0?void 0:H(i)),m=u?Dt({...e,expires:f,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return ut.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 ft(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&&!Et(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)),`${Xe.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 pt(e,t){let n=mt(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,...a}=ht(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 dt({...a,request:nt(r),...i&&{opaque:i}},t)}function mt(e){let t=Xe.payment,[n]=bt(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 ht(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]=gt(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function gt(e,t){if(e[t]===`"`)return _t(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function _t(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 vt(e,t,n){if(e.slice(t,t+n.length).toLowerCase()!==n.toLowerCase())return!1;let r=e[t+n.length];return!!(r&&/\s/.test(r))}function yt(e){return bt(e,Xe.payment).length>0||e.split(`,`).some(e=>e.trim().toLowerCase()===Xe.payment.toLowerCase())}function bt(e,t){let n=[],r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(r){i?i=!1:o===`\\`?i=!0:o===`"`&&(r=!1);continue}if(o===`"`){r=!0;continue}if(!vt(e,a,t))continue;let s=a-1;for(;s>=0&&/\s/.test(e[s]??``);)s--;s>=0&&e[s]!==`,`||n.push(a)}return n}function xt(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return St(e.headers,t)}function St(e,t){let n=e.get(V.wwwAuthenticate);if(!n)throw Error(`Missing ${V.wwwAuthenticate} header.`);return Ct(n,t)}function Ct(e,t){let n=bt(e,Xe.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 pt(e.slice(r,a).replace(/,\s*$/,``),t)})}function wt(e){let t=[e.realm,e.method,e.intent,H(e.request),e.expires??``,e.digest??``],n=e.header;return n!==void 0&&!Et(n)&&t.push(n),t.push(e.opaque??(e.meta?H(e.meta):``)),t.join(`|`)}function Tt(e){return e.header??V.authorization}function Et(e){return e?.toLowerCase()===V.authorization.toLowerCase()}function Dt(e,t){let n=wt(e),r=O.fromString(t.secretKey),i=O.fromString(n),a=k.hmac256(r,i,{as:`Bytes`});return D.fromBytes(a,{url:!0,pad:!1})}const Ot=65536;var kt=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},At=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}};function jt(e){if(e.length>Ot)throw new At;let t=e.match(RegExp(`^${Xe.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new kt;try{let e=D.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=Mt(r);return{challenge:ut.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:nt(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new At}}function Mt(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!Nt(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:H(e)}}function Nt(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function Pt(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function Ft(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=D.fromString(s,{pad:!1,url:!0});return`${Xe.payment} ${c}`}function It(e){return e.length>Ot?null:e.split(`,`).map(e=>e.trim()).find(e=>RegExp(`^${Xe.payment}\\s+`,`i`).test(e))??null}function Lt(e,t){return t?`${e} Add funds at ${t}`:e}var Rt=class extends Error{details;status=402;hint;fundingUrl;constructor(e,t={}){super(e),this.details=t.details,this.fundingUrl=t.fundingUrl,t.cause!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t.cause,writable:!0})}toProblemDetails(e){return{type:this.type,title:this.title,status:this.status,detail:this.message,...this.details&&Object.keys(this.details).length>0&&{details:this.details},...this.hint&&{hint:this.hint},...this.fundingUrl&&{fundingUrl:this.fundingUrl},...e&&{challengeId:e}}}},zt=class extends Rt{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 Rt{name=`VerificationFailedError`;title=`Verification Failed`;type=`https://paymentauth.org/problems/verification-failed`;constructor(e={}){let{details:t,fundingUrl:n,reason:r}=e;super(Lt(r?`Payment verification failed: ${r}.`:`Payment verification failed.`,n),{details:t,fundingUrl:n})}},Bt=class extends Rt{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.`)}},Vt=class extends Rt{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}},Ht=class extends Error{name=`ZoneSettlementPendingError`;challengeId;senderTag;zoneId;constructor(e){let{cause:t,challengeId:n,senderTag:r,zoneId:i}=e;super(`Zone ${i} withdrawal ${r} for challenge "${n}" has not settled on Tempo yet. Retry the challenge to resume waiting instead of paying again.`),this.challengeId=n,this.senderTag=r,this.zoneId=i,t!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t,writable:!0})}},Ut=class extends Rt{name=`InsufficientBalanceError`;title=`Insufficient Balance`;status=402;type=`https://paymentauth.org/problems/session/insufficient-balance`;constructor(e={}){let{fundingUrl:t,reason:n}=e;super(Lt(n?`Insufficient balance: ${n}.`:`Insufficient balance.`,t),{fundingUrl:t})}};function Wt(e,t){if(!e)throw new zt({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new zt({...t&&{id:t},reason:`malformed expires timestamp`});if(Date.parse(e)<=Date.now())throw new Bt({expires:e})}function Gt(e){return e}function Kt(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}function qt(e){return{encode(t){return D.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(D.toString(t)))}catch{throw new Jt}}}}var Jt=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}};const Yt=[`exact`],Xt=`PAYMENT-REQUIRED`,Zt=`PAYMENT-SIGNATURE`,Qt=U.string().check(U.minLength(1)),$t=U.number().check(U.refine(e=>e>0,`Must be positive`)),en=U.string().check(U.regex(/^\d+$/,`Invalid atomic amount`)),tn=G(),nn=U.string().check(U.regex(RegExp(`^eip155:\\d+$`),`Invalid EVM CAIP-2 network`)),rn=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:Qt});U.discriminatedUnion(`type`,[U.object({name:Qt,type:U.literal(`eip3009`),version:Qt}),U.object({name:U.optional(U.string()),type:U.literal(`permit2`),version:U.optional(U.string())})]);const an=U.object({amount:en,asset:Qt,extra:U.optional(U.record(U.string(),U.unknown())),maxTimeoutSeconds:$t,network:nn,payTo:Qt,scheme:U.enum(Yt)}),on=U.object({info:U.record(U.string(),U.unknown()),schema:U.record(U.string(),U.unknown())}),sn=U.record(U.string(),on),cn=U.object({accepts:U.array(an).check(U.minLength(1)),error:U.optional(U.string()),extensions:U.optional(sn),resource:rn,x402Version:U.literal(2)}),ln=U.object({authorization:U.object({from:tn,nonce:K(),to:tn,validAfter:en,validBefore:en,value:en}),signature:q()}),un=U.object({permit2Authorization:U.object({deadline:en,from:tn,nonce:en,permitted:U.object({amount:en,token:tn}),spender:tn,witness:U.object({to:tn,validAfter:en})}),signature:q()}),dn=U.union([ln,un]),fn=U.object({accepted:an,extensions:U.optional(sn),payload:dn,resource:U.optional(rn),x402Version:U.literal(2)});U.object({extensions:U.optional(sn),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 pn=U.object({amount:U.optional(en),errorMessage:U.optional(U.string()),errorReason:U.optional(U.string()),extensions:U.optional(sn),extra:U.optional(U.record(U.string(),U.unknown())),network:Qt,payer:U.optional(U.string()),success:U.boolean(),transaction:U.string()});function mn(e){let{extensions:t,resource:n,...r}=e;return an.parse(r)}const hn=qt(cn),gn=qt(fn),_n=qt(pn);hn.encode,hn.decode;function vn(e){try{let t=JSON.parse(D.toString(e));return bn(t)}catch{throw new Jt}}const yn=gn.encode;gn.decode,_n.encode,_n.decode;const bn=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new Jt;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new Jt;let n=rn.parse(t.resource),r=t.extensions===void 0?void 0:sn.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}};function xn(e){let t=[H(e.accepted),H(e.resource),H(e.extensions)].join(`|`);return k.sha256(O.fromString(t),{as:`Hex`})}async function Sn(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=mn(n);if(En(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?On(n.extensions):n.extensions,a=r.extra?.assetTransferMethod??`eip3009`;if(a!==`eip3009`)throw Error(`x402 exact ${String(a)} signing is not implemented yet.`);let o=r.extra?.name,c=r.extra?.version;if(typeof o!=`string`||typeof c!=`string`)throw Error(`x402 exact EIP-3009 requires token name and version.`);let l=Math.floor(Date.now()/1e3),u={from:s(t.address),nonce:i?.mppx?xn({accepted:r,extensions:i,resource:n.resource}):An(),to:s(r.payTo),validAfter:(l-600).toString(),validBefore:(l+r.maxTimeoutSeconds).toString(),value:r.amount},d=await t.signTypedData({domain:{chainId:Tn(r.network),name:o,verifyingContract:s(r.asset),version:c},message:{...u,value:BigInt(u.value),validAfter:BigInt(u.validAfter),validBefore:BigInt(u.validBefore)},primaryType:`TransferWithAuthorization`,types:wn});return yn({accepted:r,...i?{extensions:i}:{},payload:{authorization:u,signature:d},...n.resource?{resource:n.resource}:{},x402Version:2})}function Cn(e){let t=e.challenge.request,n;try{n=mn(t),En(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 wn={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 Tn(e){return Number(e.slice(7))}function En(e,t){let n=Tn(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=>Re(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=s(t.asset);if(!r.some(n=>Be(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=Dn(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>h(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function Dn(e,t){let n=e.currencies??e.assets,r=s(t.asset),i=n?.find(e=>Be(e,r,t.network)),a=i?ze(i,t.network):void 0;return a?.decimals===void 0?e.decimals:a.decimals}function On(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:kn()}}}:e}function kn(){return jn().slice(2)}function An(){return jn()}function jn(){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 Mn=Symbol.for(`mppx.x402.challenge`);function Nn(e){return Object.defineProperty(e,Mn,{value:!0}),e}function Pn(e){return!!e?.[Mn]}const Fn=[`authorization`],In=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 Ln=U.object({chainId:U.number(),credentialTypes:U.optional(U.array(U.enum(Fn)).check(U.minLength(1))),decimals:U.optional(U.number()),permit2Address:U.optional(G()),splits:U.optional(U.array(U.object({amount:In,recipient:G()})))});U.object({amount:In,currency:G(),description:U.optional(U.string()),externalId:U.optional(U.string()),methodDetails:Ln,recipient:G()});const Rn=U.object({amount:W(),chainId:U.number(),currency:G(),credentialTypes:U.optional(U.array(U.enum(Fn)).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:In,recipient:G()})))}),zn=U.object({from:G(),nonce:K(),signature:q(),to:G(),type:U.literal(`authorization`),validAfter:In,validBefore:In,value:In}),Bn={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 Vn(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function Hn(e){return k.keccak256(O.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function Un(e){return`eip155:${e}`}function Wn(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const Gn=Gt({name:`evm`,intent:`charge`,schema:{credential:{payload:zn},request:U.pipe(Rn,U.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:o,splits:c,...l})=>({...l,amount:h(e,i).toString(),currency:s(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:s(a)}:{},...c?{splits:c}:{}},recipient:s(o)})))}});function Kn(e){return Kt(Gn,{canHandleChallenge({challenge:t}){return!qn(t)||Cn({challenge:t,config:e})},context:U.object({account:U.optional(U.custom())}),async createCredential({challenge:t,context:n}){if(qn(t))return Sn({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(Jn(e,i),!i.methodDetails.credentialTypes?.includes(`authorization`))throw Error(`EVM authorization is not accepted by this challenge.`);if(i.methodDetails.splits?.length)throw Error(`EVM authorization does not support payment splits.`);let a=Yn(e,i),o=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return Ft(Pt({challenge:t,payload:{from:s(r.address),nonce:Hn(t),signature:await r.signTypedData({domain:Vn({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:s(r.address),nonce:Hn(t),to:s(i.recipient),validAfter:0n,validBefore:BigInt(o),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:Bn}),to:s(i.recipient),type:`authorization`,validAfter:`0`,validBefore:o,value:i.amount},source:Wn({address:s(r.address),chainId:i.methodDetails.chainId})}))}})}function qn(e){return Pn(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function Jn(e,t){let n=t.methodDetails.chainId,r=Un(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=>Re(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=s(t.currency);if(!i.some(t=>Be(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=Xn(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>h(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function Yn(e,t){let n=e.currencies??e.assets,r=s(t.currency),i=Un(t.methodDetails.chainId),a=n?.find(e=>Be(e,r,i)),o=a?ze(a,i):void 0;if(o?.transfer?.type===`eip3009`)return{name:o.transfer.name,version:o.transfer.version};if(e.authorization)return e.authorization;throw Error(`EVM authorization requires token name and version.`)}function Xn(e,t){let n=e.currencies??e.assets,r=s(t.currency),i=Un(t.methodDetails.chainId),a=n?.find(e=>Be(e,r,i)),o=a?ze(a,i):void 0;return o?.decimals===void 0?e.decimals:o.decimals}function Zn(e){return[Zn.charge(e)]}(function(e){e.charge=Kn,e.assets=We,e.chains=Ge})(Zn||={});var Qn=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 er(this,e)}},$n=class extends Qn{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 er(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},tr={ousd:ie(X.mainnet).address,usdc:s(oe(X.mainnet).address),pathUsd:ae(X.mainnet).address},nr={[X.mainnet]:tr.usdc,[X.testnet]:tr.pathUsd},rr=Object.freeze({[X.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[X.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})});X.mainnet,X.testnet;const ir={[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 ar(e,t){return Z.link(e,t)}function or(e){return e.startsWith(`tempo:`)}function sr(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 cr={mainnet:ir[X.mainnet],testnet:ir[X.testnet]};function lr(e,t={}){return e??(t.network?cr[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}async function ur(t={}){let n=lr(t.rpcUrl,{network:t.network});if(!n)return R;let{getChainId:r}=await import(`viem/actions`),i=await r(e({transport:l(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 dr(e){return typeof e==`bigint`?e:e.amount}function fr(e){return e.id!==R.id}async function pr(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(dr).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 mr(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:1e4}function hr(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function gr(e){return new $n({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 _r(e){if(e&&hr(e,`secret-tool`))throw gr(e)}function vr(e,t){return new Promise(n=>{N.execFile(e,t,{timeout:mr()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function yr(){let e=I.join(process.env.XDG_CONFIG_HOME||I.join(F.homedir(),`.config`),`mppx`,`default`);return{get(){try{return P.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(t){P.mkdirSync(I.dirname(e),{recursive:!0}),P.writeFileSync(e,t,`utf-8`)},clear(){try{P.unlinkSync(e)}catch{}}}}function br(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:yr().get())}function xr(e=`main`){let t=`mppx`;return{async list(){let e=F.platform();if(e===`darwin`){let{stdout:e,error:n}=await vr(`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 vr(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(_r(r),r)return[];let i=`${e}\n${n}`,a=[],o=i.matchAll(/\baccount = (.+)/g);for(let e of o)e[1]&&a.push(e[1]);return a}throw Error(`Unsupported platform: ${e}`)},async get(){let n=F.platform();if(n===`darwin`){let{stdout:n,error:r}=await vr(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await vr(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return _r(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=F.platform();if(r===`darwin`){await vr(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await vr(`security`,[`add-generic-password`,`-s`,t,`-a`,e,`-w`,n]);if(r)throw r;return}if(r===`linux`){let r=N.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),mr());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(hr(e,`secret-tool`)?gr(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=F.platform();if(n===`darwin`){await vr(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await vr(`secret-tool`,[`clear`,`service`,t,`account`,e]);_r(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function Sr(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=br(e),i=await xr(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function Cr(e){return(await Sr(e)).account}function wr(e){return e}function Tr(){return wr({method:`evm`,supports:e=>e.method===`evm`&&!Pn(e),async setup({challenge:t,options:n}){let r=t.request,a=r.methodDetails,o=a?.chainId,s=o?Er(o):void 0,c=r.currency,u=await Cr(n.account),d=[...Object.values(Me),...Object.values(Ne),...Object.values(Pe),...Object.values(Fe)],f=c??``;if(s&&c)try{let t=e({chain:s,transport:l()}),n=await b(t,{address:c,abi:i,functionName:`symbol`});n&&(f=n)}catch{}return{tokenSymbol:f,tokenDecimals:a?.decimals??6,explorerUrl:s?.blockExplorers?.default?.url,methods:[...Zn({account:u,currencies:d})]}}})}function Er(e){return Object.values(T).find(t=>t.id===e)}function Dr(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 Or=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)))}),kr=U.custom(e=>typeof e==`function`),Ar=U.union([Or,kr]),jr=Gt({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(Ar),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:Dr(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});function Mr(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return Kt(jr,{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 Ft({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function Nr(e){return[Mr(e)]}(function(e){e.charge=Mr})(Nr||={});function Pr(){return wr({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=Ir(L.object({paymentMethod:L.string(),secretKey:L.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new $n({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:[Nr.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=Fr(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 $n({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${(await d.json()).error.message}`,exitCode:77})}else throw new $n({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&&Fr(e)?`/test`:``}/payments/${t}`;return Z.link(n,t,!0)}}})}function Fr(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function Ir(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 Lr=Symbol.for(`mppx.fetch.skipPayment`);Object.freeze({phase:`unproved`});function Rr(e,t,n={}){return async(r,i)=>{let a=new Request(r,i),o=zr(a.headers)??n.challenge,{response:s}=await t.send((t,n)=>e(t,{...n,...i?.[Lr]?{[Lr]:!0}:{}}),a,{...n,challenge:o});if(s.status===402&&o)for(let e of Br(s))e.method===o.method&&e.intent===o.intent&&await t.challenge(s,{challenge:e},a.url);return s}}function zr(e){for(let[,t]of e){let e=It(t);if(e)try{return jt(e).challenge}catch{}}}function Br(e){try{return xt(e)}catch{return[]}}const Vr=Symbol(`mppx.deferredContext`);function Hr(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=qr(n)}return t}function Ur(e,t){let n=Hr(e),r=ei(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[qr(e)]??1,index:t}));return{definition:r,entries:i,header:Gr(i),keys:n}}function Wr(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)=>Qr(e,t))}function Gr(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${ii(n)}`}).join(`, `)}function Kr(e,t,n,r){let i=new Map;for(let e of t){let t=qr(e),n=i.get(t);n?n.push(e):i.set(t,[e])}return e.flatMap((e,t)=>{let a=i.get(qr(e));if(!a)return[];let o=Jr(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)=>Zr(e.challenge)-Zr(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function qr(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function Jr(e,t){let n;for(let r of t){if(!Yr(e,r))continue;let t={...r,specificity:Xr(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 Yr(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function Xr(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function Zr(e){return+!!Pn(e)}function Qr(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}`);ai(r,`method`),ai(i,`intent`);let a=1;for(let t of $r(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=ni(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function $r(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function ei(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>qr(e))),a={};for(let[e,t]of Object.entries(r??{})){if(!i.has(e))throw Error(`Unknown payment preference "${e}". Available: ${[...i].join(`, `)}`);a[e]=ti(t,`payment preference "${e}"`)}return a}function ti(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return ri(e,t)}function ni(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 ri(Number(e),t)}function ri(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 ii(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function ai(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}function oi(e){let t=``,n=!1,r=!1,i,a=``;function o(t){if(t===``){i!==void 0&&e({data:i,event:a||`message`}),i=void 0,a=``;return}let n=t.indexOf(`:`);if(n===0)return;let r=n===-1?t:t.slice(0,n);if(r!==`data`&&r!==`event`)return;let o=``;n!==-1&&(o=t.slice(t.charCodeAt(n+1)===32?n+2:n+1)),r===`event`?a=o:i=i===void 0?o:i+`
2
2
  `+o}return{feed(e){if(!n&&e&&(n=!0,e.startsWith(``)&&(e=e.slice(1))),r&&e&&(r=!1,e.startsWith(`
3
3
  `)&&(e=e.slice(1))),t+=e,e.indexOf(`
4
4
  `)===-1&&e.indexOf(`\r`)===-1)return;let i=0,a=t.indexOf(`
5
5
  `),s=t.indexOf(`\r`);for(;a!==-1||s!==-1;){let e=a===-1?s:s===-1?a:Math.min(a,s);o(t.slice(i,e)),i=e+1,e===s&&(i===t.length?r=!0:a===i&&i++,s=t.indexOf(`\r`,i)),a!==-1&&a<i&&(a=t.indexOf(`
6
- `,i))}t=t.slice(i)}}}const ti=[V.authorization,Wt,`PAYMENT-RESPONSE`,Gt];function ni(e,t,n){let r=new Headers(e.headers);for(let e of ti)e===V.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}function ri(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 ii(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 ai=1048576,oi=new WeakMap;function si(e){let t=ri(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 ci(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 li(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=ot.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 ui(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:li(e.error.data):li(e.result?._meta?.[`org.paymentauth/payment-required`])}function di(e,t){return!e||e.id!==t?[]:ui(e)?.challenges??[]}async function fi(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=ei(e=>{if(!(i||!e.data)&&(i=!0,e.event===`message`))try{a=ci(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>ai)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function pi(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 ci(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>ai)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function mi(e){let t=oi.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>ai)){if(t.includes(`application/json`))return pi(e);if(t.includes(`text/event-stream`))return fi(e)}})();return oi.set(e,n),n}function hi(){return{getChallenges(e,t){let n=si(t);return e.status===402||n===void 0?[]:mi(e).then(e=>di(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=Dt(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,"org.paymentauth/credential":r}}})}}}}function gi(){return{getChallenges(e){let t=e.headers.get(V.wwwAuthenticate);return e.status!==402||!t||!ht(t)?[]:_t(e)},setCredential(e,t,n){return ni(e,n?.challenge?xt(n.challenge):V.authorization,t)}}}function _i(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(Wt);if(!t)return[];let n=fn(t);return n.accepts.flatMap((e,t)=>{let r=Qt.safeParse(e);if(!r.success)return[];let i=r.data;return Dn(st({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 ni(e,Gt,t)}}}function vi(e){return e}function yi(){let e=[gi(),_i(),hi()],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 vi({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 bi=new WeakMap;function xi(e,t){return bi.set(e,t),e}function Si(e){return bi.has(e)}function Ci(e,t){return Promise.resolve(bi.get(e)?.(t))}function wi(e){return bi.get(e)}const Ti=new WeakMap,Ei=new WeakMap,Di=new WeakMap,Oi=new WeakMap;function ki(e,t){return Ti.set(e,t),e}function Ai(e){Ti.delete(e)}function ji(e,t,n){Ti.has(e)&&Ei.set(t,n)}function Mi(e){return Ei.get(e)}function Ni(e,t){return Promise.resolve(Ti.get(e)?.(t)??t.response)}function Pi(e,t){return Oi.set(e,t),e}function Fi(e,t){try{return Oi.get(e)?.(t)}catch{return}}function Ii(e,t){Di.set(e,t)}function Li(e){return Di.get(e)??Ei.get(e)?.origin}function Ri(e,t,n){if(!zi(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&&Bi(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 zi(e){if(e.method!==`tempo`||e.intent!==`charge`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function Bi(e){try{return new URL(e).origin.toLowerCase()}catch{return e.toLowerCase()}}const Vi=Symbol.for(`mppx.fetch.wrapper`),Hi=Symbol.for(`mppx.fetch.identity`),Ui=Symbol.for(`mppx.fetch.skipPayment`),Wi=65536,Gi=new WeakMap;async function Ki(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>Wi){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,Wi),{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 qi(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 Ji(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=3,methods:a,onChallenge:o,orderChallenges:s,transport:c=yi(),trustedTempoProofRealms:l}=e,u=e.identity??(e.fetch&&_a(e.fetch)),d=e.eventDispatcher??Xi(),f=t??Lr(a),p=va(r),m=async(e,t,n)=>u?u.send(p,new Request(e,t),n):{response:await p(e,t),headers:[]},h=async(e,t,r)=>{let g=ga(e,t?.headers),_=g.has(V.acceptPayment),v=Ca(g,f),y=ma(e,t,g),b=pa(e,t,g,v.header,_,n),x=await m(ya(b.input),b.init),S=x.response,C=x.headers,w=ha(b.init,await y);if(t?.[Ui]||ii(w)||!await c.isPaymentRequired(S,w))return S;let T=t?.context,{context:E,orderChallenges:ee,...te}=w??{},D,O,k,A,j;try{for(let n=0;n<i;n++){O=await c.getChallenges(S,w);let i=(await wa(Br(O,a,v.entries,T),ee??s))[0];if(!i){if(await qi(A,{challenges:O,response:S,status:`rejected`}),n>0)return S;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&&Rt(D.expires,D.id),await u?.challenge(S,{challenge:f},Oa(b.input).href);let g=await Aa(S,b.input,b.input,te);Ri(f,()=>Oa(g),l);let _=A,y=ct(f),x=_?.method===i.method&&_?.key===y,E=!1;if(_){let e=await qi(_,{challenges:O,response:S,status:x?`pending`:`rejected`});E=x&&!e}A=E?_:void 0;let M=ta(async n=>{if(n===void 0&&E&&_)return _.promise;E&&_&&(await qi(_,{status:`rejected`}),A=void 0),ba(e,t)?.throwIfAborted();let r=n??T;if(!Si(i.method))return Sa(f,i.method,r);let a={origin:Oa(g).origin,prepare:()=>Ci(i.method,{challenge:f,context:r,fetch:u?Mr(p,u,{challenge:f}):p,input:g,signal:ba(e,t)})},o=a.prepare().then(()=>Sa(f,i.method,r,a));return A={context:r,attempt:a,key:n===void 0?y:void 0,method:i.method,promise:o},o}),N=await d.emit(`challenge.received`,na({challenge:f,challenges:O,createCredential:M,init:t,input:e,method:i.method,response:S}))??(o?await o(D,{createCredential:M}):void 0)??await M(),P=A;P&&await P.promise.catch(()=>void 0)!==N&&(await qi(P,{status:`rejected`}),A=void 0);let F=A?A.context:T;xa(N),await d.emit(`credential.created`,ra({challenge:f,credential:N,init:t,input:e,method:i.method,response:S}));let I=e=>new It({cause:e,challenge:f,credential:N,transactionHash:Fi(i.method,N)});try{({response:S}=await m(g,{...c.setCredential({...te,headers:b.headers},N,{challenge:f}),redirect:`manual`},{challenge:f,headers:C}))}catch(e){throw j=I(e),e}let L=await c.isPaymentRequired(S,w);if(L||(await qi(P,{response:S,status:S.status>=300&&S.status<400?`pending`:S.ok?`accepted`:`rejected`}),A=void 0),S.ok&&Zi(d,`payment.response`)&&await d.emit(`payment.response`,ia({challenge:f,credential:N,init:t,input:e,method:i.method,response:S})),!L){if(S.status>=500&&Zi(d,`payment.failed`)){try{S=await Ki(S)}catch(e){throw j=I(e),S=new Response(null,{headers:S.headers,status:S.status,statusText:S.statusText}),e}await d.emit(`payment.failed`,aa({challenge:f,challenges:O,error:I(),init:t,input:e,method:i.method,response:S}))}return S.ok?Ni(i.method,{context:F,challenge:f,credential:N,fetch:p,headers:b.headers,input:g,...r?{refetch:()=>h(ya(b.input),t,!1)}:{},response:S,signal:ba(e,t)}):S}}O=void 0;try{O=await c.getChallenges(S,w)}catch{}return await qi(A,{challenges:O,response:S,status:`rejected`}),S}catch(n){throw await qi(A,{challenges:O,response:S,status:`rejected`}),await d.emit(`payment.failed`,aa({challenge:D,challenges:O,error:j??n,init:t,input:e,method:k,response:S})),n}},g=(e,t)=>h(e,t,!0);return g[Vi]=p,u&&(g[Hi]=u),g}function Yi(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 Xi(){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 Qi(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await ea(e[`*`],t,n),r}case`credential.created`:await $i(e[`credential.created`],n),await ea(e[`*`],t,n);return;case`payment.failed`:await $i(e[`payment.failed`],n),await ea(e[`*`],t,n);return;case`payment.response`:await $i(e[`payment.response`],n),await ea(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 Gi.set(t,t=>e[t].size>0||e[`*`].size>0),t}function Zi(e,t){return Gi.get(e)?.(t)??!0}async function Qi(e,t){try{return await e(t)}catch{return}}async function $i(e,t){for(let n of e)try{await n(t)}catch{}}async function ea(e,t,n){await $i(e,Object.freeze({name:t,payload:n}))}function ta(e){let t;return n=>(t??=e(n),t)}function na(e){return Object.freeze({challenge:ua(e.challenge),challenges:e.challenges.map(e=>ua(e)),createCredential:e.createCredential,init:oa(e.init),input:sa(e.input),method:ca(e.method),response:la(e.response)})}function ra(e){return Object.freeze({challenge:ua(e.challenge),credential:e.credential,init:oa(e.init),input:sa(e.input),method:ca(e.method),...e.response===void 0?{}:{response:la(e.response)}})}function ia(e){return Object.freeze({challenge:ua(e.challenge),credential:e.credential,init:oa(e.init),input:sa(e.input),method:ca(e.method),response:la(e.response)})}function aa(e){return Object.freeze({...e.challenge?{challenge:ua(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>ua(e))}:{},error:e.error,init:oa(e.init),input:sa(e.input),...e.method?{method:ca(e.method)}:{},...e.response===void 0?{}:{response:la(e.response)}})}function oa(e){if(e)return fa({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function sa(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function ca(e){return fa(Object.assign({},e))}function la(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 ua(e)}function ua(e){try{return da(structuredClone(e))}catch{return fa(e)}}function da(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))da(t);return e}function fa(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function pa(e,t,n,r,i,a){let o=!!r&&!i&&Ta(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(V.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function ma(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 ha(e,t){return t===void 0?e:{...e,body:t}}function ga(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function _a(e){return e[Hi]}function va(e){let t=e;for(;t[Vi];)t=t[Vi];return t}function ya(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function ba(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function xa(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
7
- `))throw Error(`Credential header value contains illegal newline characters`)}async function Sa(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&&Ii(a,r.origin),r&&ji(t,a,r),t.createCredential(a)}function Ca(e,t){let n=e.get(V.acceptPayment);if(!n)return t;try{return{...t,entries:Rr(n),header:n}}catch{return t}}async function wa(e,t){return t?t(e):e}function Ta(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=Oa(e);return t===`same-origin`?!Da()||n.origin===globalThis.location.origin:t.origins.some(e=>Ea(n,e))}function Ea(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 Da(){return globalThis.location!==void 0}function Oa(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,Da()?globalThis.location.href:void 0)}function ka(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 Aa(e,t,n,r){if(ka(t,r),!e.url)return t;let i=new URL(e.url),a=Oa(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 ja(e={}){let{account:t}=e;return(e,{account:n}={})=>{let r=n??t;if(!r){if(!e.account)throw Error("No `account` provided. Pass `account` to parameters or context.");return e.account}return fe(r)}}function Ma(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}const Na={[R.id]:R,[ne.id]:ne};function Pa(e,t={}){return c(e.url,{fetchFn:e.fetch,fetchOptions:{headers:Ma(e)},...t})}function Fa(r){let{chain:i,getClient:a,remoteFeePayer:o,rpcUrl:s}=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=de(n({request:t=>e(t)},{retryCount:0}),Pa(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(!s)throw Error("No `rpcUrl` provided.");let n=t||Number(Object.keys(s)[0]),r=s[n];if(!r)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let a=o?de(c(r),Pa(o)):c(r);return e({chain:Na[n]??{...i,id:n},transport:a})}}function Ia(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 La(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}const Ra=A.slice(k.keccak256(O.fromString(`mpp`),{as:`Hex`}),0,4);function za(e){let t=k.keccak256(O.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,10))}function Ba(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(A.toBytes(Ra),0),i[4]=1,i.set(za(t),5),n&&i.set(za(n),15),i.set(Va(r),25),A.fromBytes(i)}function Va(e){let t=k.keccak256(O.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,7))}function Ha(e,t){return ge.resolve(e).toLowerCase()===ge.resolve(t).toLowerCase()}const Ua=10000n,Wa=[Yn.pathUsd,Yn.usdc,Yn.ousd];async function Ga(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=>!Ha(e,i)),c=await Promise.allSettled([y(e,{...z.token.getBalance.call(e,{account:n,token:i}),account:null}),...s.map(t=>y(e,{...z.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/Ua;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 z.dex.getBuyQuote(e,{account:null,tokenIn:a,tokenOut:i,amountOut:d});if(t<=0n||t>p)continue;let n=t+t*f/Ua,o=n<p?n:p;if(r>=o)return[z.token.approve.call(e,{amount:o,spender:ce.stablecoinDex,token:a}),z.dex.buy.call({tokenIn:a,tokenOut:i,amountOut:d,maxAmountIn:o})]}catch{}}throw new qa({currency:i})}function Ka(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=>Ha(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var qa=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}};function Ja(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 Ya(e,t,n){t&&(n&&!n.some(e=>Ha(e,t))||e.some(e=>Ha(e,t))||e.push(t))}async function Xa(e,t,n){try{return(await z.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function Za(e){let t=e.chain?.feeToken;if(t)return le.toAddress(t);let n=e.chain?.id;return n?Xn[n]:void 0}function Qa(e){let t=[];return Ya(t,Yn.pathUsd),Ya(t,Xn[e]),t}async function $a(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])Ya(o,e,n);if(Ya(o,await z.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),Ya(o,Za(i),n),!a)for(let e of r??[])Ya(o,e,n);for(let e of o)if(await Xa(i,t,e))return e;return o[0]}const eo=f([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`]);function to(e){if(e!==void 0)return Zn[e]}function no(e){let t=to(e.chainId);return!!t&&l(e.currency,{strict:!1})&&u(e.currency,t.token)}function ro(e){let t=to(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:oe.tip20,functionName:`approve`,args:[t.swap,i]}),to:t.token},{data:r({abi:eo,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 io(e,t){let n=ro(t);if(n)try{return await y(e,z.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await h(e,{account:t.account,calls:n.calls}),n)}catch{return}}const ao={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]};function oo(e){return{name:`MPP`,version:`3`,chainId:e}}function so(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function co(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:oo(n),types:ao,primaryType:`Proof`,message:so({account:t,challengeId:r,realm:i})}}function lo(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const uo=7200n,fo=a({abi:oe.zonePortal,name:`WithdrawalProcessed`});function po(e){return Number.isInteger(e)&&e>0&&e<4217e5}function mo(e,t){return po(t)?e===!0||(e?.includes(t)??!1):!1}function ho(e){return ce.zonePortal(e)}function go(e){if(e>=2**32)return e%2**32;if(e>142431e4&&e<142432e4)return e-142431e4;if(e>4217e5&&e<42171e4)return e-4217e5;throw Error(`Cannot derive a Zone ID from chain ID ${e}. Pass \`zoneId\`.`)}function _o(e){if(e>=2**32)return Math.floor(e/2**32);if(e>142431e4&&e<142432e4)return 42431;if(e>4217e5&&e<42171e4)return 4217}function vo(e){return k.keccak256(te.encodePacked([`address`,`bytes32`,`uint64`],[e.sender,e.transactionHash,e.fallbackNonce]))}async function yo(e,t){let{timeoutMs:n=6e4}=t;if(!Number.isFinite(n)||n<0)throw Error(`Zone settlement timeout must be a finite, non-negative number.`);let r=await g(e,{cacheTime:0}),i=r>uo?r-uo:0n,a=Date.now()+n;for(;;){if(i<=r){let n=(await _(e,{address:t.portal,event:fo,args:{senderTag:t.senderTag,...t.to?{to:t.to}:{}},fromBlock:i,toBlock:r}))[0]?.transactionHash;if(n)return n;i=r+1n}if(Date.now()+500>a)throw Error(`Zone withdrawal ${t.senderTag} did not settle on Tempo within ${n}ms.`);await new Promise(e=>setTimeout(e,500)),r=await g(e,{cacheTime:0})}}const bo=[`push`,`pull`],xo=U.object({amount:W(),memo:U.optional(K()),recipient:U.pipe(U.string(),U.transform(e=>e))}),So=(1n<<64n)-1n,Co={dev_second:1n,day:86400n,week:604800n},wo=U.pipe(G(),U.transform(e=>e.toLowerCase())),To=U.object({accessKeyAddress:wo,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)))}),Eo=U.object({accessKey:U.optional(To),chainId:U.optional(U.number())}),Do=tt(`subscriptionExpires must be a valid date`).check(U.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),Oo=U.enum([`dev_second`,`day`,`week`]),ko=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)<=So}catch{return!1}},`periodCount exceeds uint64`));function Ao(e){return U.refine(e=>{let{amount:t,decimals:n}=e;return m(t,n)>0n},e)}function jo(e){let{periodCount:t,periodUnit:n}=e;try{let e=Co[n];return e!==void 0&&BigInt(t)*e<=So}catch{return!1}}const Mo=zt({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`)}),U.object({hash:K(),senderTag:K(),type:U.literal(`zone`),zoneId:U.number().check(U.refine(po,`Invalid Zone ID`))})])},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(xo).check(U.minLength(1),U.maxLength(10))),supportedModes:U.optional(U.array(U.enum(bo)).check(U.minLength(1))),zones:U.optional(U.union([U.literal(!0),U.array(U.number().check(U.refine(po,`Invalid Zone ID`))).check(U.minLength(1))]))}).check(U.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=m(e,t),i=n.reduce((e,n)=>e+m(n.amount,t),0n);return n.every(e=>m(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,zones:c,...l})=>({...l,amount:m(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==void 0||c!==void 0?{methodDetails:{...e!==void 0&&{machineTokenEnabled:e},...n!==void 0&&{chainId:n},...i!==void 0&&{feePayer:i},...o!==void 0&&{splits:o.map(e=>({...e,amount:m(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s},...c!==void 0&&{zones:c}}}:{}})))}}),No=zt({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([Xe.v2,Xe.v1])),sessionSnapshot:U.optional(U.custom()),suggestedDeposit:U.optional(W()),unitType:U.string()}).check(U.refine(({amount:e,decimals:t})=>m(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,...f})=>({...f,amount:m(e,r).toString(),...d?{suggestedDeposit:m(d,r).toString()}:{},methodDetails:{escrowContract:i,...n!==void 0&&{channelId:n},...s!==void 0&&{minVoucherDelta:m(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&&{[Ye.sessionProtocol]:l},...u!==void 0&&{[Ye.sessionSnapshot]:u}}})))}}),Po=zt({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(To),chainId:U.optional(U.number()),currency:wo,decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),methodDetails:U.optional(Eo),periodCount:ko,periodUnit:Oo,recipient:wo,subscriptionExpires:Do}).check(Ao(`Subscription amount must be greater than 0`),U.refine(jo,`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:m(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}}),Fo=U.object({account:U.optional(U.custom()),autoSwap:U.optional(U.custom()),feeToken:U.optional(U.custom()),mode:U.optional(U.enum(bo))});function Io(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:Wo(e.maxAmount,e.decimals),maxAtomicAmount:e.maxAtomicAmount===void 0?void 0:BigInt(e.maxAtomicAmount)},r=Fa({chain:R,getClient:e.getClient,rpcUrl:Qn}),i=ja({account:e.account});zo(e.zone);let a=new Map,o=Bt(Mo,{canHandleChallenge({challenge:t}){try{return Go(e,n,t.request),!0}catch{return!1}},context:Fo,async createCredential({challenge:o,context:s}){Go(e,n,o.request);let c=o.request.methodDetails?.chainId??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),l=await r({chainId:c});Ia(l,c);let u=c??l.chain?.id;if(La(e.allowedChainIds,u),u===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");let{request:d}=o,{amount:f,methodDetails:p}=d,m=p?.supportedModes??[`pull`,`push`],h=e.zone?.client.chain,g=e.zone?e.zone.zoneId??go(h?.id??0):void 0,_=h?.sourceId??(h?_o(h.id):void 0),y=s?.mode??e.mode;if(BigInt(f)>0n&&e.zone&&g!==void 0&&_===u&&m.includes(`push`)&&(y===void 0||y===`push`)&&mo(p?.zones,g)&&!p?.splits&&(a.has(Ho(o))||Bo(o.expires,e.zone.settlementTimeoutMs)))return Ro({challenge:o,clientId:t,client:l,pending:a,zone:e.zone,zoneId:g});let x=i(l,s),T=async t=>await e.resolveAccount?.({account:x,chainId:u,operation:t})??x;if(BigInt(f)===0n){let e=await T({kind:`signPaymentProof`});return jt({challenge:o,payload:{signature:await w(l,{account:e,...co({account:e.address,chainId:u,challengeId:o.id,realm:o.realm})}),type:`proof`},source:lo({address:e.address,chainId:u})})}let E=d.currency,ee=no({chainId:u,currency:E}),te=Ba({challengeId:o.id,clientId:t,serverId:o.realm}),D=Ja({amount:f,methodDetails:{...p,memo:te},recipient:d.recipient}),O=D.map(e=>z.token.transfer.call(l,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:E})),k=Ka(s?.autoSwap??e.autoSwap,Wa),A=p?.machineTokenEnabled===!0?ro({chainId:u,currency:E,transfers:D}):void 0,j=x,M;if(A){let e=await(async()=>{try{return await T({calls:A.calls,kind:`executeCalls`})}catch{return}})();e&&(M=await io(l,{account:e.address,chainId:u,currency:E,transfers:D}),M&&(j=e))}let N;M||(j=await T({kind:`executeCalls`,...k?{}:{calls:O}}),N=k?await Ga(l,{account:j.address,amountOut:BigInt(f),tokenOut:E,tokenIn:k.tokenIn,slippage:k.slippage,maxAmountIn:k.maxAmountIn}):void 0);let P=M?.calls??[...N??[],...O],F=Qa(u),I=(s?.feeToken??e.feeToken)||(M||ee?await $a({account:j.address,allowedTokens:F,candidateTokens:F,client:l,prioritizeCandidates:!0}):void 0),L=(()=>{let t=s?.mode??e.mode;if(t){if(!m.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=j.type===`json-rpc`?`push`:`pull`;return m.includes(n)?n:m[0]})(),R=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!o.expires)return e;let t=Math.floor(new Date(o.expires).getTime()/1e3)+1;return Math.min(e,t)})();if(L===`push`){let{receipts:e}=j.type===`local`?{receipts:[await S(l,{account:j,calls:P,...I?{feeToken:I}:{},nonceKey:`expiring`,validBefore:R})]}:await b(l,{account:j,...I?{capabilities:{feeToken:I}}:{},calls:P,experimental_fallback:P.length===1,forceAtomic:P.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return jt({challenge:o,payload:{hash:t,type:`hash`},source:lo({address:j.address,chainId:u})})}let ne=()=>{if(p?.feePayer!==!0)return;let e=15e3,t=o.expires?new Date(o.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(!(R*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.`)};ne();let re=await v(l,{account:j,calls:P,...I?{feeToken:I}:{},nonceKey:`expiring`,validBefore:R});if(re.gas=(re.gas??0n)+5000n,p?.feePayer){let e=re;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return ne(),jt({challenge:o,payload:{signature:await C(l,re),type:`transaction`},source:lo({address:j.address,chainId:u})})}}),s=new Map,c=async t=>{Go(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,a=s.get(i);return a||(a=o.createCredential(t).finally(()=>s.delete(i)),s.set(i,a)),a};return Pi({...o,createCredential:c},Lo)}function Lo(e){let t=Mo.schema.credential.payload.safeParse(Dt(e).payload);if(!t.success)return;let n=t.data;if(n.type===`hash`||n.type===`zone`)return n.hash;let r=n.signature;if(n.type!==`transaction`||!r.startsWith(_e.serializedType))return;let i=_e.deserialize(r);if(!(!i.signature||i.feePayerSignature===null)&&_e.serialize(i)===r)return d(r)}async function Ro(e){let{challenge:t,client:n,pending:r,zone:i,zoneId:a}=e,o=t.request.recipient,s=Ho(t),c=r.get(s);if(!c){let t={sent:!1};c=Uo(e,t),r.set(s,c),c.catch(()=>{t.sent||r.delete(s)})}let l=await c,u;try{u=await yo(n,{portal:ho(a),senderTag:l,timeoutMs:Vo(t.expires,i.settlementTimeoutMs),to:o})}catch(e){throw new Lt({cause:e,challengeId:t.id,senderTag:l,zoneId:a})}return r.delete(s),jt({challenge:t,payload:{hash:u,senderTag:l,type:`zone`,zoneId:a}})}function zo(e){let t=e?.settlementTimeoutMs;if(t!==void 0&&(!Number.isFinite(t)||t<0))throw Error("`zone.settlementTimeoutMs` must be a finite, non-negative number.");let n=e?.client.chain?.id;if(e?.zoneId===void 0||n===void 0||_o(n)===void 0)return;let r=go(n);if(r!==e.zoneId)throw Error(`zone.zoneId ${e.zoneId} does not match Zone ${r} of the zone.client chain ${n}.`)}function Bo(e,t){if(!e)return!0;let n=t??6e4;return new Date(e).getTime()-Date.now()>n+15e3}function Vo(e,t){let n=t??6e4;return e?Math.max(0,Math.min(n,new Date(e).getTime()-Date.now())):n}function Ho(e){return JSON.stringify(e)}async function Uo(e,t){let{challenge:n,clientId:r,zone:i}=e,a=n.request,o=i.client.account;if(!o)throw Error("`zone.client` requires an account.");let s=BigInt(a.amount),c=a.currency,l=a.recipient,u=Ba({challengeId:n.id,clientId:r,serverId:n.realm}),f=await z.zone.getWithdrawalFee(i.client),[,m]=z.zone.requestWithdrawal.calls({amount:s,fallbackRecipient:o.address,memo:u,to:l,token:c}),h=await v(i.client,{account:o,calls:[z.token.approve.call({amount:s+f,spender:ce.zoneOutbox,token:c}),m]}),g=await C(i.client,h);t.sent=!0;let _=d(g),y=await x(i.client,{serializedTransaction:g}).catch(e=>T(i.client,{hash:_,timeout:15e3}).catch(()=>{let t=Error(`Zone withdrawal outcome is unknown: transaction ${_} may have been sent. Retrying this challenge does not withdraw again.`);throw Object.defineProperty(t,"cause",{configurable:!0,value:e,writable:!0}),t}));if(y.status===`reverted`)throw t.sent=!1,Error(`Zone withdrawal transaction ${y.transactionHash} reverted.`);let[b]=p({abi:oe.zoneOutbox,eventName:`WithdrawalRequested`,logs:y.logs});if(!b)throw Error("Zone withdrawal request did not emit `WithdrawalRequested`.");return vo({fallbackNonce:b.args.fallbackNonce,sender:b.args.sender,transactionHash:y.transactionHash})}function Wo(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 m(e,t)}}function Go(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)&&La(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 Ko=(1n<<96n)-1n;function qo(e){return e>=0n&&e<=Ko}function Jo(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return qo(t)?t:void 0}function Yo(e){return Xo(e),e}function Xo(e){if(!qo(e))throw Error(`Value ${e} is outside uint96 bounds.`)}const Zo=new Set([`open`,`topUp`,`voucher`,`close`]);function Qo(e){return typeof e==`object`&&!!e}function $o(e){return typeof e==`string`&&Zo.has(e)}function es(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!$o(t.action))}function ts(e,t=`No session credential context available.`){if(!es(e))throw Error(t);return e}function ns(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function rs(e){return Qo(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function is(e){return Qo(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 as(e){let t=D.toString(e),n=JSON.parse(t);if(!is(n))throw Error(`Invalid session receipt.`);return n}function os(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function ss(e){let t=`message`,n=[];for(let r of e.split(`
6
+ `,i))}t=t.slice(i)}}}const si=[V.authorization,Xt,`PAYMENT-RESPONSE`,Zt];function ci(e,t,n){let r=new Headers(e.headers);for(let e of si)e===V.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}function li(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 ui(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 di=1048576,fi=new WeakMap;function pi(e){let t=li(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 mi(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 hi(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=ut.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 gi(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:hi(e.error.data):hi(e.result?._meta?.[`org.paymentauth/payment-required`])}function _i(e,t){return!e||e.id!==t?[]:gi(e)?.challenges??[]}async function vi(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=oi(e=>{if(!(i||!e.data)&&(i=!0,e.event===`message`))try{a=mi(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>di)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function yi(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 mi(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>di)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function bi(e){let t=fi.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>di)){if(t.includes(`application/json`))return yi(e);if(t.includes(`text/event-stream`))return vi(e)}})();return fi.set(e,n),n}function xi(){return{getChallenges(e,t){let n=pi(t);return e.status===402||n===void 0?[]:bi(e).then(e=>_i(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=jt(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,"org.paymentauth/credential":r}}})}}}}function Si(){return{getChallenges(e){let t=e.headers.get(V.wwwAuthenticate);return e.status!==402||!t||!yt(t)?[]:xt(e)},setCredential(e,t,n){return ci(e,n?.challenge?Tt(n.challenge):V.authorization,t)}}}function Ci(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(Xt);if(!t)return[];let n=vn(t);return n.accepts.flatMap((e,t)=>{let r=an.safeParse(e);if(!r.success)return[];let i=r.data;return Nn(dt({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 ci(e,Zt,t)}}}function wi(e){return e}function Ti(){let e=[Si(),Ci(),xi()],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 wi({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 Ei=new WeakMap;function Di(e,t){return Ei.set(e,t),e}function Oi(e){return Ei.has(e)}function ki(e,t){return Promise.resolve(Ei.get(e)?.(t))}function Ai(e){return Ei.get(e)}const ji=new WeakMap,Mi=new WeakMap,Ni=new WeakMap,Pi=new WeakMap;function Fi(e,t){return ji.set(e,t),e}function Ii(e){ji.delete(e)}function Li(e,t,n){ji.has(e)&&Mi.set(t,n)}function Ri(e){return Mi.get(e)}function zi(e,t){return Promise.resolve(ji.get(e)?.(t)??t.response)}function Bi(e,t){return Pi.set(e,t),e}function Vi(e,t){try{return Pi.get(e)?.(t)}catch{return}}function Hi(e,t){Ni.set(e,t)}function Ui(e){return Ni.get(e)??Mi.get(e)?.origin}function Wi(e,t,n){if(!Gi(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&&Ki(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 Gi(e){if(e.method!==`tempo`||e.intent!==`charge`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function Ki(e){try{return new URL(e).origin.toLowerCase()}catch{return e.toLowerCase()}}const qi=Symbol.for(`mppx.fetch.wrapper`),Ji=Symbol.for(`mppx.fetch.identity`),Yi=Symbol.for(`mppx.fetch.skipPayment`),Xi=65536,Zi=new WeakMap;async function Qi(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>Xi){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,Xi),{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 $i(e,t){let n=e?.attempt.settle;if(!n)return t.status!==`pending`;e.attempt.settle=void 0;let r=await n(t);return r||(e.attempt.settle=n),r}function ea(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=3,methods:a,onChallenge:o,orderChallenges:s,transport:c=Ti(),trustedTempoProofRealms:l}=e,u=e.identity??(e.fetch&&Ca(e.fetch)),d=e.eventDispatcher??na(),f=t??Ur(a),p=wa(r),m=async(e,t,n)=>u?u.send(p,new Request(e,t),n):{response:await p(e,t),headers:[]},h=async(e,t,r)=>{let g=Sa(e,t?.headers),_=g.has(V.acceptPayment),v=ka(g,f),y=ba(e,t,g),b=ya(e,t,g,v.header,_,n),ee=await m(Ta(b.input),b.init),x=ee.response,S=ee.headers,C=xa(b.init,await y);if(t?.[Yi]||ui(C)||!await c.isPaymentRequired(x,C))return x;let te=t?.context,{context:w,orderChallenges:T,...ne}=C??{},E,D,O,k,A;try{for(let n=0;n<i;n++){D=await c.getChallenges(x,C);let i=(await Aa(Kr(D,a,v.entries,te),T??s))[0];if(!i){if(await $i(k,{challenges:D,response:x,status:`rejected`}),n>0)return x;throw Error(`No method found for challenges: ${D.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`)}let f=i.challenge;E=f,O=i.method,E.expires&&Wt(E.expires,E.id),await u?.challenge(x,{challenge:f},Pa(b.input).href);let g=await Ia(x,b.input,b.input,ne);Wi(f,()=>Pa(g),l);let _=k,y=ft(f),ee=_?.method===i.method&&_?.key===y,w=!1;if(_){let e=await $i(_,{challenges:D,response:x,status:ee?`pending`:`rejected`});w=ee&&!e}k=w?_:void 0;let j=sa(async n=>{if(n===void 0&&w&&_)return _.promise;w&&_&&(await $i(_,{status:`rejected`}),k=void 0),Ea(e,t)?.throwIfAborted();let r=n??te;if(!Oi(i.method))return Oa(f,i.method,r);let a={origin:Pa(g).origin,prepare:()=>ki(i.method,{challenge:f,context:r,fetch:u?Rr(p,u,{challenge:f}):p,input:g,signal:Ea(e,t)})},o=a.prepare().then(()=>Oa(f,i.method,r,a));return k={context:r,attempt:a,key:n===void 0?y:void 0,method:i.method,promise:o},o}),M=await d.emit(`challenge.received`,ca({challenge:f,challenges:D,createCredential:j,init:t,input:e,method:i.method,response:x}))??(o?await o(E,{createCredential:j}):void 0)??await j(),N=k;N&&await N.promise.catch(()=>void 0)!==M&&(await $i(N,{status:`rejected`}),k=void 0);let P=k?k.context:te;Da(M),await d.emit(`credential.created`,la({challenge:f,credential:M,init:t,input:e,method:i.method,response:x}));let F=e=>new Vt({cause:e,challenge:f,credential:M,transactionHash:Vi(i.method,M)});try{({response:x}=await m(g,{...c.setCredential({...ne,headers:b.headers},M,{challenge:f}),redirect:`manual`},{challenge:f,headers:S}))}catch(e){throw A=F(e),e}let I=await c.isPaymentRequired(x,C);if(I||(await $i(N,{response:x,status:x.status>=300&&x.status<400?`pending`:x.ok?`accepted`:`rejected`}),k=void 0),x.ok&&ra(d,`payment.response`)&&await d.emit(`payment.response`,ua({challenge:f,credential:M,init:t,input:e,method:i.method,response:x})),!I){if(x.status>=500&&ra(d,`payment.failed`)){try{x=await Qi(x)}catch(e){throw A=F(e),x=new Response(null,{headers:x.headers,status:x.status,statusText:x.statusText}),e}await d.emit(`payment.failed`,da({challenge:f,challenges:D,error:F(),init:t,input:e,method:i.method,response:x}))}return x.ok?zi(i.method,{context:P,challenge:f,credential:M,fetch:p,headers:b.headers,input:g,...r?{refetch:()=>h(Ta(b.input),t,!1)}:{},response:x,signal:Ea(e,t)}):x}}D=void 0;try{D=await c.getChallenges(x,C)}catch{}return await $i(k,{challenges:D,response:x,status:`rejected`}),x}catch(n){throw await $i(k,{challenges:D,response:x,status:`rejected`}),await d.emit(`payment.failed`,da({challenge:E,challenges:D,error:A??n,init:t,input:e,method:O,response:x})),n}},g=(e,t)=>h(e,t,!0);return g[qi]=p,u&&(g[Ji]=u),g}function ta(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 na(){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 ia(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await oa(e[`*`],t,n),r}case`credential.created`:await aa(e[`credential.created`],n),await oa(e[`*`],t,n);return;case`payment.failed`:await aa(e[`payment.failed`],n),await oa(e[`*`],t,n);return;case`payment.response`:await aa(e[`payment.response`],n),await oa(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 Zi.set(t,t=>e[t].size>0||e[`*`].size>0),t}function ra(e,t){return Zi.get(e)?.(t)??!0}async function ia(e,t){try{return await e(t)}catch{return}}async function aa(e,t){for(let n of e)try{await n(t)}catch{}}async function oa(e,t,n){await aa(e,Object.freeze({name:t,payload:n}))}function sa(e){let t;return n=>(t??=e(n),t)}function ca(e){return Object.freeze({challenge:ga(e.challenge),challenges:e.challenges.map(e=>ga(e)),createCredential:e.createCredential,init:fa(e.init),input:pa(e.input),method:ma(e.method),response:ha(e.response)})}function la(e){return Object.freeze({challenge:ga(e.challenge),credential:e.credential,init:fa(e.init),input:pa(e.input),method:ma(e.method),...e.response===void 0?{}:{response:ha(e.response)}})}function ua(e){return Object.freeze({challenge:ga(e.challenge),credential:e.credential,init:fa(e.init),input:pa(e.input),method:ma(e.method),response:ha(e.response)})}function da(e){return Object.freeze({...e.challenge?{challenge:ga(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>ga(e))}:{},error:e.error,init:fa(e.init),input:pa(e.input),...e.method?{method:ma(e.method)}:{},...e.response===void 0?{}:{response:ha(e.response)}})}function fa(e){if(e)return va({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function pa(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function ma(e){return va(Object.assign({},e))}function ha(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 ga(e)}function ga(e){try{return _a(structuredClone(e))}catch{return va(e)}}function _a(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))_a(t);return e}function va(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function ya(e,t,n,r,i,a){let o=!!r&&!i&&ja(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(V.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function ba(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 xa(e,t){return t===void 0?e:{...e,body:t}}function Sa(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function Ca(e){return e[Ji]}function wa(e){let t=e;for(;t[qi];)t=t[qi];return t}function Ta(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function Ea(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function Da(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
7
+ `))throw Error(`Credential header value contains illegal newline characters`)}async function Oa(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&&Hi(a,r.origin),r&&Li(t,a,r),t.createCredential(a)}function ka(e,t){let n=e.get(V.acceptPayment);if(!n)return t;try{return{...t,entries:Wr(n),header:n}}catch{return t}}async function Aa(e,t){return t?t(e):e}function ja(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=Pa(e);return t===`same-origin`?!Na()||n.origin===globalThis.location.origin:t.origins.some(e=>Ma(n,e))}function Ma(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 Na(){return globalThis.location!==void 0}function Pa(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,Na()?globalThis.location.href:void 0)}function Fa(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 Ia(e,t,n,r){if(Fa(t,r),!e.url)return t;let i=new URL(e.url),a=Pa(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 La(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 pe(r)}}function Ra(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}const za={[R.id]:R,[re.id]:re};function Ba(e,t={}){return l(e.url,{fetchFn:e.fetch,fetchOptions:{headers:Ra(e)},...t})}function Va(r){let{chain:i,getClient:a,remoteFeePayer:o,rpcUrl:s}=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=fe(n({request:t=>e(t)},{retryCount:0}),Ba(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(!s)throw Error("No `rpcUrl` provided.");let n=t||Number(Object.keys(s)[0]),r=s[n];if(!r)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let a=o?fe(l(r),Ba(o)):l(r);return e({chain:za[n]??{...i,id:n},transport:a})}}function Ha(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 Ua(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}const Wa=A.slice(k.keccak256(O.fromString(`mpp`),{as:`Hex`}),0,4);function Ga(e){let t=k.keccak256(O.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,10))}function Ka(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(A.toBytes(Wa),0),i[4]=1,i.set(Ga(t),5),n&&i.set(Ga(n),15),i.set(qa(r),25),A.fromBytes(i)}function qa(e){let t=k.keccak256(O.fromString(e),{as:`Hex`});return A.toBytes(A.slice(t,0,7))}function Ja(e,t){return _e.resolve(e).toLowerCase()===_e.resolve(t).toLowerCase()}const Ya=10000n,Xa=[tr.pathUsd,tr.usdc,tr.ousd];async function Za(e,t){let{account:n,amountOut:r,tokenOut:i,tokenIn:a,slippage:o}=t;if(!Number.isFinite(o)||o<0||o>50)throw Error(`Auto-swap slippage must be between 0 and 50 percent.`);if(t.maxAmountIn!==void 0&&t.maxAmountIn<=0n)throw Error(`Auto-swap maxAmountIn must be positive.`);let s=e.chain?.id,c=[];for(let e of a){let t=typeof e==`string`?e:s===void 0?void 0:De(e,{chainId:s})?.address;!t||Ja(t,i)||c.some(e=>Ja(e,t))||c.push(t)}let l=await Promise.allSettled([b(e,{...z.token.getBalance.call(e,{account:n,token:i}),account:null}),...c.map(t=>b(e,{...z.token.getBalance.call(e,{account:n,token:t}),account:null}))]),u=l[0];if(u.status!==`fulfilled`)throw u.reason;let d=u.value;if(d>=r)return;let f=r-d,p=BigInt(Math.round(o*100)),m=t.maxAmountIn??f+f*p/Ya;for(let t=0;t<c.length;t++){let n=l[t+1];if(n.status!==`fulfilled`)continue;let r=n.value;if(r<=0n)continue;let a=c[t];try{let t=await z.dex.getBuyQuote(e,{account:null,tokenIn:a,tokenOut:i,amountOut:f});if(t<=0n||t>m)continue;let n=t+t*p/Ya,o=n<m?n:m;if(r>=o)return[z.token.approve.call(e,{amount:o,spender:le.stablecoinDex,token:a}),z.dex.buy.call({tokenIn:a,tokenOut:i,amountOut:f,maxAmountIn:o})]}catch{}}throw new $a({currency:i})}function Qa(e,t){return e?e===!0?{tokenIn:t,slippage:1}:{tokenIn:e.tokenIn?[...e.tokenIn,...e.fallback===!1?[]:t.filter(t=>!e.tokenIn.some(e=>typeof e==`string`&&Ja(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var $a=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}};function eo(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 to(e,t,n){t&&(n&&!n.some(e=>Ja(e,t))||e.some(e=>Ja(e,t))||e.push(t))}async function no(e,t,n){try{return(await z.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function ro(e){let t=e.chain?.feeToken;if(t)return ue.toAddress(t);let n=e.chain?.id;return n?nr[n]:void 0}function io(e){let t=[];return to(t,tr.pathUsd),to(t,nr[e]),t}async function ao(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])to(o,e,n);if(to(o,await z.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),to(o,ro(i),n),!a)for(let e of r??[])to(o,e,n);for(let e of o)if(await no(i,t,e))return e;return o[0]}const oo=p([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`]);function so(e){if(e!==void 0)return rr[e]}function co(e){let t=so(e.chainId);return!!t&&u(e.currency,{strict:!1})&&d(e.currency,t.token)}function lo(e){let t=so(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:se.tip20,functionName:`approve`,args:[t.swap,i]}),to:t.token},{data:r({abi:oo,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 uo(e,t){let n=lo(t);if(n)try{return await b(e,z.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await g(e,{account:t.account,calls:n.calls}),n)}catch{return}}const fo=10n**BigInt(4);function po(e={}){let{address:t,amount:n,chainId:r=X.mainnet}=e;if(r!==X.mainnet)return;let i=new URL(`https://wallet.tempo.xyz/agent?action=fund&intent=mach&chainId=4217`);if(t&&u(t,{strict:!1})&&i.searchParams.set(`address`,s(t)),n!==void 0&&n>0n){let e=(n+fo-1n)/fo,t=e%100n,r=(e/100n).toString();i.searchParams.set(`amount`,t===0n?r:`${r}.${t.toString().padStart(2,`0`).replace(/0$/,``)}`)}return i.toString()}async function mo(e,t){let n=so(t.chainId);if(!n)return;let r=await b(e,z.token.getBalance.call(e,{account:t.account,token:n.token})).catch(()=>void 0);return typeof r==`bigint`?r:void 0}async function ho(e,t){let{account:n,amount:r,chainId:i}=t,o=await mo(e,{account:n,chainId:i});if(o===void 0||o>=r)return;let s=e=>`${a(e,6)} MACH`,c=r-o;return{fundingUrl:po({address:n,amount:c,chainId:i}),reason:`requested ${s(r)}, available ${s(o)}`,shortfall:c}}async function go(e,t){let n=await ho(e,t);if(n)return new Ut({fundingUrl:n.fundingUrl,reason:n.reason})}const _o={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]};function vo(e){return{name:`MPP`,version:`3`,chainId:e}}function yo(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function bo(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:vo(n),types:_o,primaryType:`Proof`,message:yo({account:t,challengeId:r,realm:i})}}function xo(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}const So=7200n,Co=o({abi:se.zonePortal,name:`WithdrawalProcessed`});function wo(e){return Number.isInteger(e)&&e>0&&e<4217e5}function To(e,t){return wo(t)?e===!0||(e?.includes(t)??!1):!1}function Eo(e){return le.zonePortal(e)}function Do(e){if(e>=2**32)return e%2**32;if(e>142431e4&&e<142432e4)return e-142431e4;if(e>4217e5&&e<42171e4)return e-4217e5;throw Error(`Cannot derive a Zone ID from chain ID ${e}. Pass \`zoneId\`.`)}function Oo(e){if(e>=2**32)return Math.floor(e/2**32);if(e>142431e4&&e<142432e4)return 42431;if(e>4217e5&&e<42171e4)return 4217}function ko(e){return k.keccak256(E.encodePacked([`address`,`bytes32`,`uint64`],[e.sender,e.transactionHash,e.fallbackNonce]))}async function Ao(e,t){let{timeoutMs:n=6e4}=t;if(!Number.isFinite(n)||n<0)throw Error(`Zone settlement timeout must be a finite, non-negative number.`);let r=await _(e,{cacheTime:0}),i=r>So?r-So:0n,a=Date.now()+n;for(;;){if(i<=r){let n=(await v(e,{address:t.portal,event:Co,args:{senderTag:t.senderTag,...t.to?{to:t.to}:{}},fromBlock:i,toBlock:r}))[0]?.transactionHash;if(n)return n;i=r+1n}if(Date.now()+500>a)throw Error(`Zone withdrawal ${t.senderTag} did not settle on Tempo within ${n}ms.`);await new Promise(e=>setTimeout(e,500)),r=await _(e,{cacheTime:0})}}const jo=[`push`,`pull`],Mo=U.object({amount:W(),memo:U.optional(K()),recipient:U.pipe(U.string(),U.transform(e=>e))}),No=(1n<<64n)-1n,Po={dev_second:1n,day:86400n,week:604800n},Fo=U.pipe(G(),U.transform(e=>e.toLowerCase())),Io=U.object({accessKeyAddress:Fo,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(Io),chainId:U.optional(U.number())}),Ro=at(`subscriptionExpires must be a valid date`).check(U.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),zo=U.enum([`dev_second`,`day`,`week`]),Bo=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)<=No}catch{return!1}},`periodCount exceeds uint64`));function Vo(e){return U.refine(e=>{let{amount:t,decimals:n}=e;return h(t,n)>0n},e)}function Ho(e){let{periodCount:t,periodUnit:n}=e;try{let e=Po[n];return e!==void 0&&BigInt(t)*e<=No}catch{return!1}}const Uo=Gt({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`)}),U.object({hash:K(),senderTag:K(),type:U.literal(`zone`),zoneId:U.number().check(U.refine(wo,`Invalid Zone ID`))})])},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(Mo).check(U.minLength(1),U.maxLength(10))),supportedModes:U.optional(U.array(U.enum(jo)).check(U.minLength(1))),zones:U.optional(U.union([U.literal(!0),U.array(U.number().check(U.refine(wo,`Invalid Zone ID`))).check(U.minLength(1))]))}).check(U.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=h(e,t),i=n.reduce((e,n)=>e+h(n.amount,t),0n);return n.every(e=>h(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,zones:c,...l})=>({...l,amount:h(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==void 0||c!==void 0?{methodDetails:{...e!==void 0&&{machineTokenEnabled:e},...n!==void 0&&{chainId:n},...i!==void 0&&{feePayer:i},...o!==void 0&&{splits:o.map(e=>({...e,amount:h(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s},...c!==void 0&&{zones:c}}}:{}})))}}),Wo=Gt({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([et.v2,et.v1])),sessionSnapshot:U.optional(U.custom()),suggestedDeposit:U.optional(W()),unitType:U.string()}).check(U.refine(({amount:e,decimals:t})=>h(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,...f})=>({...f,amount:h(e,r).toString(),...d?{suggestedDeposit:h(d,r).toString()}:{},methodDetails:{escrowContract:i,...n!==void 0&&{channelId:n},...s!==void 0&&{minVoucherDelta:h(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&&{[$e.sessionProtocol]:l},...u!==void 0&&{[$e.sessionSnapshot]:u}}})))}}),Go=Gt({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(Io),chainId:U.optional(U.number()),currency:Fo,decimals:U.number(),description:U.optional(U.string()),externalId:U.optional(U.string()),methodDetails:U.optional(Lo),periodCount:Bo,periodUnit:zo,recipient:Fo,subscriptionExpires:Ro}).check(Vo(`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:h(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}}),Ko=U.object({account:U.optional(U.custom()),autoSwap:U.optional(U.custom()),feeToken:U.optional(U.custom()),mode:U.optional(U.enum(jo))});function qo(e={}){let{clientId:t}=e;if((e.maxAmount!==void 0||e.maxAtomicAmount!==void 0)&&e.currencies===void 0)throw Error(`Tempo charge maxAmount and maxAtomicAmount require currencies.`);for(let t of e.currencies??[])ns(e.maxAmount,typeof t==`string`?e.decimals:t.decimals);let n={maxAmount:e.maxAmount,maxAtomicAmount:e.maxAtomicAmount===void 0?void 0:BigInt(e.maxAtomicAmount)},r=Va({chain:R,getClient:e.getClient,rpcUrl:ir}),i=La({account:e.account});Zo(e.zone);let a=new Map,o=Kt(Uo,{canHandleChallenge({challenge:t}){try{return rs(e,n,t.request),!0}catch{return!1}},context:Ko,async createCredential({challenge:o,context:s}){rs(e,n,o.request);let c=o.request.methodDetails?.chainId,l=c??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),u=await r({chainId:l});Ha(u,l);let d=l??u.chain?.id;if(Ua(e.allowedChainIds,d),d===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");c===void 0&&rs(e,n,o.request,d);let{request:f}=o,{amount:p,methodDetails:m}=f,h=m?.supportedModes??[`pull`,`push`],g=e.zone?.client.chain,_=e.zone?e.zone.zoneId??Do(g?.id??0):void 0,v=g?.sourceId??(g?Oo(g.id):void 0),b=s?.mode??e.mode;if(BigInt(p)>0n&&e.zone&&_!==void 0&&v===d&&h.includes(`push`)&&(b===void 0||b===`push`)&&To(m?.zones,_)&&!m?.splits&&(a.has(es(o))||Qo(o.expires,e.zone.settlementTimeoutMs)))return Xo({challenge:o,clientId:t,client:u,pending:a,zone:e.zone,zoneId:_});let x=i(u,s),w=async t=>await e.resolveAccount?.({account:x,chainId:d,operation:t})??x;if(BigInt(p)===0n){let e=await w({kind:`signPaymentProof`});return Ft({challenge:o,payload:{signature:await te(u,{account:e,...bo({account:e.address,chainId:d,challengeId:o.id,realm:o.realm})}),type:`proof`},source:xo({address:e.address,chainId:d})})}let T=f.currency,ne=co({chainId:d,currency:T}),E=Ka({challengeId:o.id,clientId:t,serverId:o.realm}),D=eo({amount:p,methodDetails:{...m,memo:E},recipient:f.recipient}),O=D.map(e=>z.token.transfer.call(u,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:T})),k=Qa(s?.autoSwap??e.autoSwap,Xa),A=m?.machineTokenEnabled===!0?lo({chainId:d,currency:T,transfers:D}):void 0,j=x,M,N=!1;if(A){let e=await(async()=>{try{return await w({calls:A.calls,kind:`executeCalls`})}catch{return}})();e&&(M=await uo(u,{account:e.address,chainId:d,currency:T,transfers:D}),M?j=e:N=!0)}let P;if(!M&&(j=await w({kind:`executeCalls`,...k?{}:{calls:O}}),P=k?await Za(u,{account:j.address,amountOut:BigInt(p),tokenOut:T,tokenIn:k.tokenIn,slippage:k.slippage,maxAmountIn:k.maxAmountIn}):void 0,N&&!k)){let e=await Jo(u,{account:j.address,amount:BigInt(p),chainId:d,currency:T});if(e)throw e}let F=M?.calls??[...P??[],...O],I=io(d),L=(s?.feeToken??e.feeToken)||(M||ne?await ao({account:j.address,allowedTokens:I,candidateTokens:I,client:u,prioritizeCandidates:!0}):void 0),R=(()=>{let t=s?.mode??e.mode;if(t){if(!h.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=j.type===`json-rpc`?`push`:`pull`;return h.includes(n)?n:h[0]})(),re=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!o.expires)return e;let t=Math.floor(new Date(o.expires).getTime()/1e3)+1;return Math.min(e,t)})();if(R===`push`){let{receipts:e}=j.type===`local`?{receipts:[await S(u,{account:j,calls:F,...L?{feeToken:L}:{},nonceKey:`expiring`,validBefore:re})]}:await ee(u,{account:j,...L?{capabilities:{feeToken:L}}:{},calls:F,experimental_fallback:F.length===1,forceAtomic:F.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return Ft({challenge:o,payload:{hash:t,type:`hash`},source:xo({address:j.address,chainId:d})})}let ie=()=>{if(m?.feePayer!==!0)return;let e=15e3,t=o.expires?new Date(o.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(!(re*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.`)};ie();let ae=await y(u,{account:j,calls:F,...L?{feeToken:L}:{},nonceKey:`expiring`,validBefore:re});if(ae.gas=(ae.gas??0n)+5000n,m?.feePayer){let e=ae;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return ie(),Ft({challenge:o,payload:{signature:await C(u,ae),type:`transaction`},source:xo({address:j.address,chainId:d})})}}),s=new Map,c=async t=>{rs(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,a=s.get(i);return a||(a=o.createCredential(t).finally(()=>s.delete(i)),s.set(i,a)),a};return Bi({...o,createCredential:c},Yo)}async function Jo(e,t){let{account:n,amount:r,chainId:i,currency:a}=t,o=await b(e,z.token.getBalance.call(e,{account:n,token:a})).catch(()=>void 0);if(!(typeof o!=`bigint`||o>=r))return go(e,{account:n,amount:r,chainId:i})}function Yo(e){let t=Uo.schema.credential.payload.safeParse(jt(e).payload);if(!t.success)return;let n=t.data;if(n.type===`hash`||n.type===`zone`)return n.hash;let r=n.signature;if(n.type!==`transaction`||!r.startsWith(ve.serializedType))return;let i=ve.deserialize(r);if(!(!i.signature||i.feePayerSignature===null)&&ve.serialize(i)===r)return f(r)}async function Xo(e){let{challenge:t,client:n,pending:r,zone:i,zoneId:a}=e,o=t.request.recipient,s=es(t),c=r.get(s);if(!c){let t={sent:!1};c=ts(e,t),r.set(s,c),c.catch(()=>{t.sent||r.delete(s)})}let l=await c,u;try{u=await Ao(n,{portal:Eo(a),senderTag:l,timeoutMs:$o(t.expires,i.settlementTimeoutMs),to:o})}catch(e){throw new Ht({cause:e,challengeId:t.id,senderTag:l,zoneId:a})}return r.delete(s),Ft({challenge:t,payload:{hash:u,senderTag:l,type:`zone`,zoneId:a}})}function Zo(e){let t=e?.settlementTimeoutMs;if(t!==void 0&&(!Number.isFinite(t)||t<0))throw Error("`zone.settlementTimeoutMs` must be a finite, non-negative number.");let n=e?.client.chain?.id;if(e?.zoneId===void 0||n===void 0||Oo(n)===void 0)return;let r=Do(n);if(r!==e.zoneId)throw Error(`zone.zoneId ${e.zoneId} does not match Zone ${r} of the zone.client chain ${n}.`)}function Qo(e,t){if(!e)return!0;let n=t??6e4;return new Date(e).getTime()-Date.now()>n+15e3}function $o(e,t){let n=t??6e4;return e?Math.max(0,Math.min(n,new Date(e).getTime()-Date.now())):n}function es(e){return JSON.stringify(e)}async function ts(e,t){let{challenge:n,clientId:r,zone:i}=e,a=n.request,o=i.client.account;if(!o)throw Error("`zone.client` requires an account.");let s=BigInt(a.amount),c=a.currency,l=a.recipient,u=Ka({challengeId:n.id,clientId:r,serverId:n.realm}),d=await z.zone.getWithdrawalFee(i.client),[,p]=z.zone.requestWithdrawal.calls({amount:s,fallbackRecipient:o.address,memo:u,to:l,token:c}),h=await y(i.client,{account:o,calls:[z.token.approve.call({amount:s+d,spender:le.zoneOutbox,token:c}),p]}),g=await C(i.client,h);t.sent=!0;let _=f(g),v=await x(i.client,{serializedTransaction:g}).catch(e=>w(i.client,{hash:_,timeout:15e3}).catch(()=>{let t=Error(`Zone withdrawal outcome is unknown: transaction ${_} may have been sent. Retrying this challenge does not withdraw again.`);throw Object.defineProperty(t,"cause",{configurable:!0,value:e,writable:!0}),t}));if(v.status===`reverted`)throw t.sent=!1,Error(`Zone withdrawal transaction ${v.transactionHash} reverted.`);let[b]=m({abi:se.zoneOutbox,eventName:`WithdrawalRequested`,logs:v.logs});if(!b)throw Error("Zone withdrawal request did not emit `WithdrawalRequested`.");return ko({fallbackNonce:b.args.fallbackNonce,sender:b.args.sender,transactionHash:v.transactionHash})}function ns(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 h(e,t)}}function rs(e,t,n,r){let{amount:i,methodDetails:a,recipient:o}=n,s=a?.chainId;if(e.expectedChainId!==void 0&&s!==void 0&&s!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${s}.`);(s!==void 0||e.allowedChainIds?.length===0)&&Ua(e.allowedChainIds,s);let c=e.currencies?Oe(e.currencies,n.currency,{chainId:s??r??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),decimals:e.decimals}):void 0;if(e.currencies&&!c)throw Error(`Tempo charge currency is not allowed: ${n.currency}.`);if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase()));if(!o||!t.has(o.toLowerCase()))throw Error(`Unexpected primary recipient: ${o}`);let n=a?.splits;if(n){for(let e of n)if(!t.has(e.recipient.toLowerCase()))throw Error(`Unexpected split recipient: ${e.recipient}`)}}if(t.maxAtomicAmount!==void 0&&BigInt(i)>t.maxAtomicAmount)throw Error(`Tempo charge amount exceeds maxAtomicAmount.`);if(t.maxAmount!==void 0&&BigInt(i)>ns(t.maxAmount,c?.decimals))throw Error(`Tempo charge amount exceeds maxAmount.`)}const is=(1n<<96n)-1n;function as(e){return e>=0n&&e<=is}function os(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return as(t)?t:void 0}function ss(e){return cs(e),e}function cs(e){if(!as(e))throw Error(`Value ${e} is outside uint96 bounds.`)}const ls=new Set([`open`,`topUp`,`voucher`,`close`]);function us(e){return typeof e==`object`&&!!e}function ds(e){return typeof e==`string`&&ls.has(e)}function fs(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!ds(t.action))}function ps(e,t=`No session credential context available.`){if(!fs(e))throw Error(t);return e}function ms(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function hs(e){return us(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function gs(e){return us(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 _s(e){let t=D.toString(e),n=JSON.parse(t);if(!gs(n))throw Error(`Invalid session receipt.`);return n}function vs(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function ys(e){let t=`message`,n=[];for(let r of e.split(`
8
8
  `))r.startsWith(`event: `)?t=r.slice(7).trim():r.startsWith(`data: `)?n.push(r.slice(6)):r===`data:`&&n.push(``);if(n.length===0)return null;let r=n.join(`
9
- `);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=cs(r);return rs(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=cs(r);return is(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function cs(e){try{return JSON.parse(e)}catch{return null}}function ls(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function us(){return JSON.stringify({mpp:`payment-close-request`})}function ds(e){let t=fs(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`&&is(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`&&rs(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&is(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function fs(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}const ps=`0x4d50500000000000000000000000000000000000`;function ms(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function hs(e){let t=te.encode(te.from([`address payer`,`address payee`,`address operator`,`address token`,`bytes32 salt`,`address authorizedSigner`,`bytes32 expiringNonceHash`,`address escrow`,`uint256 chainId`]),[e.payer,e.payee,e.operator,e.token,e.salt,e.authorizedSigner,e.expiringNonceHash,e.escrow??`0x4d50500000000000000000000000000000000000`,BigInt(e.chainId)]);return k.keccak256(t)}function gs(e){return _e.encodeForSigning(e)}function _s(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function vs(e,t){return k.keccak256(A.concat(gs(e),t.sender))}const ys=[{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`}],bs=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],xs={name:`descriptor`,type:`tuple`,components:ys},Ss=[{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:[xs,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[xs,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[xs,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[xs],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[xs],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[xs],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:ys},{name:`state`,type:`tuple`,components:bs}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:bs}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:bs}]},{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 Cs(e,t){return{name:`TIP20 Channel Reserve`,version:`1`,chainId:t,verifyingContract:e}}const ws={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},Ts={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]};function Es(e,t,n){return s({domain:Cs(e,t),types:Ts,primaryType:`CloseAuthorization`,message:n})}function Ds(e,t){return me.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function Os(e,t,n){return e.toLowerCase()===me.address.toLowerCase()?Ds(t,n):s({domain:Cs(e,t),types:ws,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function ks(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function As(e){return e.source===`accessKey`&&`accessKeyAddress`in e}function js(e,t){return se.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function Ms(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===me.address.toLowerCase())try{return await js(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return w(e,{account:t,domain:Cs(r,i),types:ws,primaryType:`Voucher`,message:n})})(),o=B.from(a);if(!ks(o.type))throw Error(`TIP-1034 vouchers require a TIP-1020 primitive signature; received "${o.type}".`);return B.serialize(o)}async function Ns(e,t,n,r,i){let a=As(t)?await t.sign({hash:Es(r,i,n),raw:!0}):await w(e,{account:t,domain:Cs(r,i),types:Ts,primaryType:`CloseAuthorization`,message:n}),o=B.from(a);if(!ks(o.type))throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive signature; received "${o.type}".`);return B.serialize(o)}function Ps(e,t,n,r){try{let i=B.from(n.signature);if(!ks(i.type)||B.serialize(i).toLowerCase()!==n.signature.toLowerCase())return!1;let a=Os(e,t,n),o=B.extractAddress({payload:a,signature:i});return B.verify(i,{address:o,payload:a})&&Ha(o,r)}catch{return!1}}function Fs(e){return typeof e==`object`&&!!e}function Is(e){return typeof e==`string`&&l(e,{strict:!1})?e:void 0}function Ls(e){return Is(e.accessKeyAddress)}function Rs(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(A.random(8))%e)}function zs(e){return Ls(e)??e.address}async function Bs(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return v(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}})}async function Vs(e,t){return await C(e,t)}function Hs(e,t,n=!1){let r=e.request.methodDetails,i=Fs(r)?Is(r.escrowContract)??Is(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!Ws(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!Ws(i,a)?i:a}function Us(e,t,n,r){return jt({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}function Ws(e,t){return e.toLowerCase()===t.toLowerCase()}async function Gs(e,t,n,r,i,a=ps){let o=hs({...n,chainId:i,escrow:a}),s=Yo(r),c=await Ms(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function Ks(e,t,n,r,i,a=ps){let o=await Gs(e,t,n,r,i,a),s=await Ns(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 qs(e,t,n){let i=zs(t),a=n.escrow??`0x4d50500000000000000000000000000000000000`,o=n.operator??`0x0000000000000000000000000000000000000000`,s=A.random(32),c=Yo(n.deposit),l=Yo(n.initialAmount),u=r({abi:Ss,functionName:`open`,args:[n.payee,o,n.token,c,s,i]}),d=await Vs(e,await Bs(e,{account:t,calls:[...n.prefixCalls??[],{to:a,data:u}],feePayer:n.feePayer,feeToken:n.feeToken??n.token})),f=ue.deserialize(d),p={authorizedSigner:i,expiringNonceHash:vs(_s({...n.feePayer?{feePayer:!0}:{},transaction:f}),{sender:t.address}),operator:o,payee:n.payee,payer:t.address,salt:s,token:n.token},m=hs({...p,chainId:n.chainId,escrow:a});return{action:`open`,type:`transaction`,channelId:m,transaction:d,signature:await Ms(e,t,{channelId:m,cumulativeAmount:l},a,n.chainId),descriptor:p,cumulativeAmount:l.toString(),authorizedSigner:p.authorizedSigner}}async function Js(e,t,n,i,a,o,s=ps,c=[],l=n.token){let u=hs({...n,chainId:a,escrow:s}),d=Yo(i);return{action:`topUp`,type:`transaction`,channelId:u,transaction:await Vs(e,await Bs(e,{account:t,calls:[...c,{to:s,data:r({abi:Ss,functionName:`topUp`,args:[n,d]})}],feePayer:o,feeToken:l,validAfter:Rs()})),descriptor:n,additionalDeposit:d.toString()}}function Ys(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function Q(e){return Ys({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function Xs(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(Q(t),t)},delete(t){e.delete(t)}}}const Zs=new WeakMap,Qs=new WeakMap;function $s(e,t){Qs.set(e,Qs.get(t)??t)}async function ec(e,t,n){let r=Zs.get(e);r||(r=new Map,Zs.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 tc(e,t,n){return ec(Qs.get(e)??e,`funding:${t}`,n)}async function nc(e,t){await ec(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 rc(e,t){await ec(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}const ic=2n**96n-1n;function ac(e){if(e<0n||e>ic)throw new Y({reason:`amount exceeds uint96 range`})}async function oc(e,t,n=ps,r){return sc(await y(e,{address:n,abi:Ss,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function sc(e){return ac(e.settled),ac(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}const cc=U.custom(e=>typeof e==`string`&&l(e,{strict:!1})),lc=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),uc=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),dc=U.object({authorizedSigner:cc,expiringNonceHash:lc,operator:cc,payee:cc,payer:cc,salt:lc,token:cc}),fc=Vt(U.object({acceptedCumulative:U.string(),chainId:U.number(),channelId:lc,closeRequestedAt:U.optional(U.string()),deposit:U.string(),descriptor:dc,escrow:cc,highestVoucher:U.optional(U.object({channelId:lc,cumulativeAmount:U.string(),signature:uc})),requiredCumulative:U.string(),settled:U.string(),spent:U.string(),units:U.optional(U.number())}));function pc(e){return fc.encode(e)}function mc(e){return fc.decode(e)}const hc={status:`idle`};function gc(e){return{status:`active`,...e}}function _c(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:bc(e.challengeId,t.snapshot),effects:[]}:$(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:Nc({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:xc(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`?yc({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:xc(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:xc(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 vc(e,t){let n=_c(e.state,t);return e.state=n.state,n}function yc(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 bc(e,t){return gc({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function xc(e,t,n,r){return gc({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 Sc(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function Cc(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`);Sc({cumulativeAmount:i,maxVoucherCumulative:n}),Sc({cumulativeAmount:a,maxVoucherCumulative:n})}function wc(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;Cc({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function Tc(e,t){return typeof e==`bigint`?e:m(e,t)}function Ec(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 Dc(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;Sc({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){Sc({cumulativeAmount:e,maxVoucherCumulative:t??null})}function kc(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 Ac(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function jc(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!qo(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>Ac({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function Mc(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=Jo(r),s=Jo(a.spent);return o===void 0||s===void 0||!qo(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function Nc(e){return gc({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 Pc(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:hc}}function Fc(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=wc({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&vc(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function Ic(e,t){return gc({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function Lc(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=Jo(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 Rc(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 _c(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function zc(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 Bc(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 Vc(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(us()),e.waitForCloseReady()))(),a=BigInt(i.spent);jc({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=>Mc({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(ls(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}function Hc(e){return`cumulativeAmount`in e}function Uc(e){if(Hc(e))return BigInt(e.cumulativeAmount)}async function Wc(e,t){e.origin!==void 0&&(t={...t,origin:e.origin}),t.opened?await nc(e.store,t):await rc(e.store,Q(t)),e.notifyUpdate(t)}async function Gc(e,t,n){let r=Uc(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 Wc(e,i))}const Kc=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),qc=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),Jc=U.object({account:U.optional(U.custom()),autoSwap:U.optional(U.custom()),action:U.optional(U.enum([`open`,`topUp`,`voucher`,`close`])),channelId:U.optional(qc),cumulativeAmount:U.optional(W()),cumulativeAmountRaw:U.optional(U.string()),transaction:U.optional(Kc),descriptor:U.optional(U.custom()),additionalDeposit:U.optional(W()),additionalDepositRaw:U.optional(U.string()),depositRaw:U.optional(U.string())});function Yc(e){return e?.action!==void 0}function Xc(e){return Yc(e)&&e.descriptor!==void 0}function Zc(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 m(i,t)}function Qc(e,t,n,r){let i=Zc(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function $c(e){return typeof e==`object`&&!!e}function el(e){return typeof e==`string`&&l(e,{strict:!1})?e:void 0}function tl(e){let t=e.request.methodDetails;return $c(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:el(t.escrowContract),escrow:el(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:el(t.feeToken),operator:el(t.operator),sessionSnapshot:Ze(t,Ye.sessionSnapshot)}:{}}function nl(e,t){if(typeof e==`string`&&l(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function rl(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function il(e){return typeof e==`string`?e:void 0}async function al(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=tl(n);(o.chainId!==void 0||i?.length===0)&&La(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});Ia(c,s);let l=s??c.chain?.id;if(La(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=Hs(n,r,t),d=nl(n.request.recipient,`recipient`),f=nl(n.request.currency,`currency`);return{amount:rl(n.request.amount),challenge:n,chainId:l,client:c,escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:Ys({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:il(n.request.suggestedDeposit),token:f}}async function ol(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=oc}=e,o=hs({...r,chainId:i.chainId,escrow:i.escrow});sl({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 sl(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(!Ws(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!Ws(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!Ws(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!Ws(ms(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function cl(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function ll(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=Zc(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function ul(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(!Ps(i.escrow,i.chainId,{channelId:a.channelId,cumulativeAmount:s,signature:a.signature},ms(i.descriptor)))throw Error(`session snapshot highest voucher signature is invalid`);let f=await ol({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:zs(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 dl(e,t){return Ws(e.address,t.payer)?Ws(zs(e),ms(t)):!1}function fl(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(Yc(r)){if(!Xc(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=cl({context:r,snapshot:o.snapshot});return!n&&s&&dl(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&dl(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 pl(e,t,n=!1){switch(e.type){case`open`:return hl(e,t,n);case`recover`:return gl(e,t);case`voucher`:return _l(e,t);case`manual`:return vl(e,t,n)}}async function ml(e,t){if(e)return await Ga(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage,maxAmountIn:e.maxAmountIn})}async function hl(e,t,n){let{account:r,resolved:i}=e,a=Ec({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw}),o=await qs(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 ml(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await Wc(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function gl(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await ol({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:zs(n),token:o.token}}),l=ll({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 Gs(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await Wc(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 _l(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;Oc(a,e.maxDeposit);let o=await Gs(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await Wc(t,r),o}async function vl(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=hs({...s,chainId:o.chainId,escrow:o.escrow});sl({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:zs(r),token:o.token});let l=await yl({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await Gc(t,o.key,l),l}async function yl(e,t){switch(e.context.action){case`open`:return bl(e);case`topUp`:return xl(e,t);case`voucher`:return Sl(e);case`close`:return Cl(e)}}async function bl(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=Qc(r,i,`cumulativeAmount`,`open`),c=await Gs(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 xl(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=Qc(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:Js(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await ml(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken)}function Sl(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Gs(a.client,t,i,Qc(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function Cl(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Ks(a.client,t,i,Qc(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}const wl={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};function Tl(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=wl.CLOSED,r=null}if(a.type===`open`&&(i=wl.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 El(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function Dl(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=Tc(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:Ic(s,u)}:i?{channel:u,state:Nc({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function kl(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=El(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 Al(e){return e.method===qe.tempo&&e.intent===Je.session}function jl(e){return Al(e)&&Ze(e.request.methodDetails,Ye.sessionProtocol)===Xe.v2}function Ml(e){return Ze(e.request.methodDetails,Ye.sessionSnapshot)}function Nl(e,t,n,r){let i=e instanceof Request?e.headers:void 0;return ni({...t,redirect:`manual`,headers:{...Yi(i),...Yi(t?.headers)}},xt(r),n)}function Pl(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 Fl(e){try{let t=typeof location>`u`?void 0:location.href,n=Pl(e)?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function Il(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function Ll(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 Rl=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 zl(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 Bl({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 Rl&&(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(V.paymentReceipt);return i?as(i):void 0}async function Bl(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(Fl(e.input),{method:`POST`,signal:r.signal,redirect:`manual`,headers:uu(t,n,e.input,e.headers)}),s])}catch(t){throw e.context.action===`topUp`?new Rl(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=_t(n).find(jl);return r?t(r):n}async function Vl(e){let t=Hl({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,Nl(e.input,e.init,t,r))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(V.paymentReceipt)&&await l(),u}function Hl(e){let t=_t(e.response).find(jl);if(!t)return;let n=Ml(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=Pl(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?Fl(r):e.lastUrl,{...i,method:`POST`,redirect:`manual`,headers:uu(a,s,e.lastUrl,e.headers)})},o=await a(e.target.challenge);if(o.status===402){let t=_t(o).find(jl);t&&(e.setChallenge?.(t),o=await a(t,!0))}if(!o.ok){let e=await Ll(o),t=o.headers.get(V.wwwAuthenticate)??``;throw Error(`Close request failed with status ${o.status}${e?`: ${e}`:``}${t?` [${V.wwwAuthenticate}: ${t}]`:``}`)}let s=o.headers.get(V.paymentReceipt);if(!s)return;let c=as(s);if(!c.txHash||!A.validate(c.txHash,{strict:!0})||A.size(c.txHash)!==32||!Mc({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 Wl(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...Yi(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!os(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),Gl(e,c,{onReceipt:r,signal:o},n,s.headers)}function Gl(e,t,n,r,i){if(!os(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let a=r.getChallenge();return Kl({onNeedVoucher:t=>Zl({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*Kl(e){for await(let t of ql(e))t.data!==void 0&&(yield t.data)}async function*ql(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=Jl(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=ss(i.replace(/\r\n|\r/g,`
10
- `));if(!s){yield{raw:o};continue}switch(s.type){case`message`:yield{data:s.data,raw:o};break;case`payment-need-voucher`:await e.onNeedVoucher(s.data,e.signal);break;case`payment-receipt`:e.onReceipt(s.data)}}if(a)break}}finally{e.signal?.removeEventListener(`abort`,a),i||await t.cancel().catch(()=>void 0),t.releaseLock()}}function Jl(e,t){for(let n=0;n<e.length;n++){let r=Yl(e,n,t);if(!r)continue;let i=Yl(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function Yl(e,t,n){return e[t]===`
9
+ `);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=bs(r);return hs(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=bs(r);return gs(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function bs(e){try{return JSON.parse(e)}catch{return null}}function xs(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function Ss(){return JSON.stringify({mpp:`payment-close-request`})}function Cs(e){let t=ws(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`&&gs(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`&&hs(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&gs(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function ws(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}const Ts=`0x4d50500000000000000000000000000000000000`;function Es(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function Ds(e){let t=E.encode(E.from([`address payer`,`address payee`,`address operator`,`address token`,`bytes32 salt`,`address authorizedSigner`,`bytes32 expiringNonceHash`,`address escrow`,`uint256 chainId`]),[e.payer,e.payee,e.operator,e.token,e.salt,e.authorizedSigner,e.expiringNonceHash,e.escrow??`0x4d50500000000000000000000000000000000000`,BigInt(e.chainId)]);return k.keccak256(t)}function Os(e){return ve.encodeForSigning(e)}function ks(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function As(e,t){return k.keccak256(A.concat(Os(e),t.sender))}const js=[{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`}],Ms=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],Ns={name:`descriptor`,type:`tuple`,components:js},Ps=[{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:[Ns,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[Ns,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[Ns,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[Ns],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[Ns],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[Ns],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:js},{name:`state`,type:`tuple`,components:Ms}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:Ms}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:Ms}]},{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 Fs(e,t){return{name:`TIP20 Channel Reserve`,version:`1`,chainId:t,verifyingContract:e}}const Is={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},Ls={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]};function Rs(e,t,n){return c({domain:Fs(e,t),types:Ls,primaryType:`CloseAuthorization`,message:n})}function zs(e,t){return he.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function Bs(e,t,n){return e.toLowerCase()===he.address.toLowerCase()?zs(t,n):c({domain:Fs(e,t),types:Is,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function Vs(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function Hs(e){return e.source===`accessKey`&&`accessKeyAddress`in e}function Us(e,t){return ce.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function Ws(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===he.address.toLowerCase())try{return await Us(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return te(e,{account:t,domain:Fs(r,i),types:Is,primaryType:`Voucher`,message:n})})(),o=B.from(a);if(!Vs(o.type))throw Error(`TIP-1034 vouchers require a TIP-1020 primitive signature; received "${o.type}".`);return B.serialize(o)}async function Gs(e,t,n,r,i){let a=Hs(t)?await t.sign({hash:Rs(r,i,n),raw:!0}):await te(e,{account:t,domain:Fs(r,i),types:Ls,primaryType:`CloseAuthorization`,message:n}),o=B.from(a);if(!Vs(o.type))throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive signature; received "${o.type}".`);return B.serialize(o)}function Ks(e,t,n,r){try{let i=B.from(n.signature);if(!Vs(i.type)||B.serialize(i).toLowerCase()!==n.signature.toLowerCase())return!1;let a=Bs(e,t,n),o=B.extractAddress({payload:a,signature:i});return B.verify(i,{address:o,payload:a})&&Ja(o,r)}catch{return!1}}function qs(e){return typeof e==`object`&&!!e}function Js(e){return typeof e==`string`&&u(e,{strict:!1})?e:void 0}function Ys(e){return Js(e.accessKeyAddress)}function Xs(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(A.random(8))%e)}function Zs(e){return Ys(e)??e.address}async function Qs(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return y(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}})}async function $s(e,t){return await C(e,t)}function ec(e,t,n=!1){let r=e.request.methodDetails,i=qs(r)?Js(r.escrowContract)??Js(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!nc(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!nc(i,a)?i:a}function tc(e,t,n,r){return Ft({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}function nc(e,t){return e.toLowerCase()===t.toLowerCase()}async function rc(e,t,n,r,i,a=Ts){let o=Ds({...n,chainId:i,escrow:a}),s=ss(r),c=await Ws(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function ic(e,t,n,r,i,a=Ts){let o=await rc(e,t,n,r,i,a),s=await Gs(e,t,{channelId:o.channelId,cumulativeAmount:ss(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function ac(e,t,n){let i=Zs(t),a=n.escrow??`0x4d50500000000000000000000000000000000000`,o=n.operator??`0x0000000000000000000000000000000000000000`,s=A.random(32),c=ss(n.deposit),l=ss(n.initialAmount),u=r({abi:Ps,functionName:`open`,args:[n.payee,o,n.token,c,s,i]}),d=await $s(e,await Qs(e,{account:t,calls:[...n.prefixCalls??[],{to:a,data:u}],feePayer:n.feePayer,feeToken:n.feeToken??n.token})),f=de.deserialize(d),p={authorizedSigner:i,expiringNonceHash:As(ks({...n.feePayer?{feePayer:!0}:{},transaction:f}),{sender:t.address}),operator:o,payee:n.payee,payer:t.address,salt:s,token:n.token},m=Ds({...p,chainId:n.chainId,escrow:a});return{action:`open`,type:`transaction`,channelId:m,transaction:d,signature:await Ws(e,t,{channelId:m,cumulativeAmount:l},a,n.chainId),descriptor:p,cumulativeAmount:l.toString(),authorizedSigner:p.authorizedSigner}}async function oc(e,t,n,i,a,o,s=Ts,c=[],l=n.token){let u=Ds({...n,chainId:a,escrow:s}),d=ss(i);return{action:`topUp`,type:`transaction`,channelId:u,transaction:await $s(e,await Qs(e,{account:t,calls:[...c,{to:s,data:r({abi:Ps,functionName:`topUp`,args:[n,d]})}],feePayer:o,feeToken:l,validAfter:Xs()})),descriptor:n,additionalDeposit:d.toString()}}function sc(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function Q(e){return sc({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function cc(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(Q(t),t)},delete(t){e.delete(t)}}}const lc=new WeakMap,uc=new WeakMap;function dc(e,t){uc.set(e,uc.get(t)??t)}async function fc(e,t,n){let r=lc.get(e);r||(r=new Map,lc.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 pc(e,t,n){return fc(uc.get(e)??e,`funding:${t}`,n)}async function mc(e,t){await fc(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 hc(e,t){await fc(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}const gc=2n**96n-1n;function _c(e){if(e<0n||e>gc)throw new Y({reason:`amount exceeds uint96 range`})}async function vc(e,t,n=Ts,r){return yc(await b(e,{address:n,abi:Ps,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function yc(e){return _c(e.settled),_c(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}const bc=U.custom(e=>typeof e==`string`&&u(e,{strict:!1})),xc=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),Sc=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),Cc=U.object({authorizedSigner:bc,expiringNonceHash:xc,operator:bc,payee:bc,payer:bc,salt:xc,token:bc}),wc=qt(U.object({acceptedCumulative:U.string(),chainId:U.number(),channelId:xc,closeRequestedAt:U.optional(U.string()),deposit:U.string(),descriptor:Cc,escrow:bc,highestVoucher:U.optional(U.object({channelId:xc,cumulativeAmount:U.string(),signature:Sc})),requiredCumulative:U.string(),settled:U.string(),spent:U.string(),units:U.optional(U.number())}));function Tc(e){return wc.encode(e)}function Ec(e){return wc.decode(e)}const Dc={status:`idle`};function Oc(e){return{status:`active`,...e}}function kc(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:Mc(e.challengeId,t.snapshot),effects:[]}:$(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:Gc({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:Nc(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:$(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?$(e,t):{state:Jc(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?jc({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:Nc(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:Nc(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 Ac(e,t){let n=kc(e.state,t);return e.state=n.state,n}function jc(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 Mc(e,t){return Oc({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function Nc(e,t,n,r){return Oc({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 Pc(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function Fc(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`);Pc({cumulativeAmount:i,maxVoucherCumulative:n}),Pc({cumulativeAmount:a,maxVoucherCumulative:n})}function Ic(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;Fc({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function Lc(e,t){return typeof e==`bigint`?e:h(e,t)}function Rc(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(Bc(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 zc(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;Pc({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 Bc(e,t){Pc({cumulativeAmount:e,maxVoucherCumulative:t??null})}function Vc(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 Hc(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function Uc(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!as(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>Hc({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function Wc(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=os(r),s=os(a.spent);return o===void 0||s===void 0||!as(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function Gc(e){return Oc({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 Kc(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:Dc}}function qc(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=Ic({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&Ac(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function Jc(e,t){return Oc({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function Yc(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=os(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 Xc(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 kc(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function Zc(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 Qc(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 $c(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(Ss()),e.waitForCloseReady()))(),a=BigInt(i.spent);Uc({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=>Wc({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(xs(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}function el(e){return`cumulativeAmount`in e}function tl(e){if(el(e))return BigInt(e.cumulativeAmount)}async function nl(e,t){e.origin!==void 0&&(t={...t,origin:e.origin}),t.opened?await mc(e.store,t):await hc(e.store,Q(t)),e.notifyUpdate(t)}async function rl(e,t,n){let r=tl(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 nl(e,i))}const il=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),al=U.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),ol=U.object({account:U.optional(U.custom()),autoSwap:U.optional(U.custom()),action:U.optional(U.enum([`open`,`topUp`,`voucher`,`close`])),channelId:U.optional(al),cumulativeAmount:U.optional(W()),cumulativeAmountRaw:U.optional(U.string()),transaction:U.optional(il),descriptor:U.optional(U.custom()),additionalDeposit:U.optional(W()),additionalDepositRaw:U.optional(U.string()),depositRaw:U.optional(U.string())});function sl(e){return e?.action!==void 0}function cl(e){return sl(e)&&e.descriptor!==void 0}function ll(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 h(i,t)}function ul(e,t,n,r){let i=ll(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function dl(e){return typeof e==`object`&&!!e}function fl(e){return typeof e==`string`&&u(e,{strict:!1})?e:void 0}function pl(e){let t=e.request.methodDetails;return dl(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:fl(t.escrowContract),escrow:fl(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:fl(t.feeToken),operator:fl(t.operator),sessionSnapshot:tt(t,$e.sessionSnapshot)}:{}}function ml(e,t){if(typeof e==`string`&&u(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function hl(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function gl(e){return typeof e==`string`?e:void 0}async function _l(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=pl(n);(o.chainId!==void 0||i?.length===0)&&Ua(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});Ha(c,s);let l=s??c.chain?.id;if(Ua(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=ec(n,r,t),d=ml(n.request.recipient,`recipient`),f=ml(n.request.currency,`currency`);return{amount:hl(n.request.amount),challenge:n,chainId:l,client:c,escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:sc({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:gl(n.request.suggestedDeposit),token:f}}async function vl(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=vc}=e,o=Ds({...r,chainId:i.chainId,escrow:i.escrow});yl({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 yl(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(!nc(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!nc(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!nc(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!nc(Es(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function bl(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function xl(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=ll(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function Sl(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(!Ks(i.escrow,i.chainId,{channelId:a.channelId,cumulativeAmount:s,signature:a.signature},Es(i.descriptor)))throw Error(`session snapshot highest voucher signature is invalid`);let f=await vl({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:Zs(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 Cl(e,t){return nc(e.address,t.payer)?nc(Zs(e),Es(t)):!1}function wl(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(sl(r)){if(!cl(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=bl({context:r,snapshot:o.snapshot});return!n&&s&&Cl(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&Cl(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 Tl(e,t,n=!1){switch(e.type){case`open`:return Ol(e,t,n);case`recover`:return kl(e,t);case`voucher`:return Al(e,t);case`manual`:return jl(e,t,n)}}async function El(e,t){if(e)return await Za(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage,maxAmountIn:e.maxAmountIn})}async function Dl(e,t){let{account:n,amount:r,chainId:i,client:a,token:o}=t;if(e||!co({chainId:i,currency:o}))return;let s=await go(a,{account:n,amount:r,chainId:i});if(s)throw s}async function Ol(e,t,n){let{account:r,resolved:i}=e,a=Rc({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw});await Dl(n,{account:r.address,amount:a,chainId:i.chainId,client:i.client,token:i.token});let o=await ac(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 El(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await nl(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function kl(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await vl({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:Zs(n),token:o.token}}),l=xl({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`);Bc(l,a);let u=await rc(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await nl(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 Al(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;Bc(a,e.maxDeposit);let o=await rc(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await nl(t,r),o}async function jl(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=Ds({...s,chainId:o.chainId,escrow:o.escrow});yl({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:Zs(r),token:o.token});let l=await Ml({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await rl(t,o.key,l),l}async function Ml(e,t){switch(e.context.action){case`open`:return Nl(e);case`topUp`:return Pl(e,t);case`voucher`:return Fl(e);case`close`:return Il(e)}}async function Nl(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=ul(r,i,`cumulativeAmount`,`open`),c=await rc(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 Pl(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=ul(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:(await Dl(t,{account:n.address,amount:c,chainId:s.chainId,client:s.client,token:s.token}),oc(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await El(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken))}function Fl(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return rc(a.client,t,i,ul(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function Il(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return ic(a.client,t,i,ul(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}const Ll={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=Ll.CLOSED,r=null}if(a.type===`open`&&(i=Ll.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 zl(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function Bl(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=Lc(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 Vl(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:Jc(s,u)}:i?{channel:u,state:Gc({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function Hl(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=zl(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:ss(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function Ul(e){return e.method===Ze.tempo&&e.intent===Qe.session}function Wl(e){return Ul(e)&&tt(e.request.methodDetails,$e.sessionProtocol)===et.v2}function Gl(e){return tt(e.request.methodDetails,$e.sessionSnapshot)}function Kl(e,t,n,r){let i=e instanceof Request?e.headers:void 0;return ci({...t,redirect:`manual`,headers:{...ta(i),...ta(t?.headers)}},Tt(r),n)}function ql(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 Jl(e){try{let t=typeof location>`u`?void 0:location.href,n=ql(e)?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function Yl(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function Xl(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 Zl=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 Ql(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 $l({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 Zl&&(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(V.paymentReceipt);return i?_s(i):void 0}async function $l(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(Jl(e.input),{method:`POST`,signal:r.signal,redirect:`manual`,headers:Cu(t,n,e.input,e.headers)}),s])}catch(t){throw e.context.action===`topUp`?new Zl(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=xt(n).find(Wl);return r?t(r):n}async function eu(e){let t=tu({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,Kl(e.input,e.init,t,r))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(V.paymentReceipt)&&await l(),u}function tu(e){let t=xt(e.response).find(Wl);if(!t)return;let n=Gl(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function nu(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=ql(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?Jl(r):e.lastUrl,{...i,method:`POST`,redirect:`manual`,headers:Cu(a,s,e.lastUrl,e.headers)})},o=await a(e.target.challenge);if(o.status===402){let t=xt(o).find(Wl);t&&(e.setChallenge?.(t),o=await a(t,!0))}if(!o.ok){let e=await Xl(o),t=o.headers.get(V.wwwAuthenticate)??``;throw Error(`Close request failed with status ${o.status}${e?`: ${e}`:``}${t?` [${V.wwwAuthenticate}: ${t}]`:``}`)}let s=o.headers.get(V.paymentReceipt);if(!s)return;let c=_s(s);if(!c.txHash||!A.validate(c.txHash,{strict:!0})||A.size(c.txHash)!==32||!Wc({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 ru(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...ta(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!vs(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),iu(e,c,{onReceipt:r,signal:o},n,s.headers)}function iu(e,t,n,r,i){if(!vs(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let a=r.getChallenge();return au({onNeedVoucher:t=>uu({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*au(e){for await(let t of ou(e))t.data!==void 0&&(yield t.data)}async function*ou(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=su(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=ys(i.replace(/\r\n|\r/g,`
10
+ `));if(!s){yield{raw:o};continue}switch(s.type){case`message`:yield{data:s.data,raw:o};break;case`payment-need-voucher`:await e.onNeedVoucher(s.data,e.signal);break;case`payment-receipt`:e.onReceipt(s.data)}}if(a)break}}finally{e.signal?.removeEventListener(`abort`,a),i||await t.cancel().catch(()=>void 0),t.releaseLock()}}function su(e,t){for(let n=0;n<e.length;n++){let r=cu(e,n,t);if(!r)continue;let i=cu(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function cu(e,t,n){return e[t]===`
11
11
  `?1:e[t]===`\r`?e[t+1]===`
12
- `?2:t+1===e.length&&!n?0:1:0}function Xl(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=ql({...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 Zl(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await kl({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 Bl({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 Ql(e){let t=new URL(e.input.toString()),n=Il(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=_t(r).find(jl);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 $l(e){e.signal?.throwIfAborted();let t=await Ql(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function eu(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:Dt(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:ns(t)}}function tu(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function nu(e){if(!tu(e))return`received mismatched payment-close-ready frame`;let t=Jo(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 ru(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!tu(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!Mc({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function iu(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=eu({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=Tl(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===wl.CONNECTING||s.readyState===wl.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 ou({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await au(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(ls(n)),await e.waitForReceipt(),l.socket}function au(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 ou(e){let t=ds(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`:su(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 cu(e,t.data);return;case`payment-receipt`:lu(e,t.data);return}}function su(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=nu({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 cu(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 kl({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(ls(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function lu(e,t){let n=ru({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 uu(e,t,n,r){let i=xt(e),a=new Headers;if(i.toLowerCase()!==V.authorization.toLowerCase()){let e=new Headers(r).get(V.authorization)??(n instanceof Request?n.headers.get(V.authorization):null);e&&!e.startsWith(`${Ke.payment} `)&&a.set(V.authorization,e)}return a.set(i,t),a}const du=new WeakMap;async function fu(e,t){let n=du.get(e)??new Map;du.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 pu(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function mu(e,t,n){try{let r=e.response?.headers.get(V.paymentReceipt);if(r){let e=as(r);if(e.challengeId===t.id&&pu(n,e))return!0}}catch{}return e.challenges?.some(e=>jl(e)?pu(n,Ml(e)):!1)??!1}function hu(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:gu(i,n),maxAtomicAmount:a===void 0?void 0:BigInt(a)}}function gu(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 m(e,t)}}function _u(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 vu(e,t){try{return _u(e,t),!0}catch{return!1}}function yu(e){return typeof e==`object`&&!!e&&e.action===`close`}function bu(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:f}=e,p=hu(e),h=Fa({chain:ee,getClient:c,rpcUrl:Qn}),g=ja({account:t}),_=l===void 0?void 0:m(l,a),v=u===void 0?void 0:m(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??Xs(),x={store:b,notifyUpdate:e=>d?.(e)},S=async(e,t,n)=>{let r=g(e.client,t),i=t?.action?t.descriptor:n?.descriptor??cl({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:ms(i)}:{}}})??r},C=async(e,t,n)=>fl({account:await S(e,t,n),entry:n,context:t,decimals:a,maxDeposit:_,resolved:e}),w=Bt(No,{canHandleChallenge:({challenge:e,context:t})=>jl(e)&&(yu(t)||t===Fr||vu(p,e.request)),context:Jc,async createCredential(e){let{challenge:t,context:i}=e;i?.action!==`close`&&_u(p,t.request);let a=await al({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:h}),c=Mi(e),l=Li(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={...x,origin:l},d=()=>{};try{let e=!Yc(i)&&i?.descriptor===void 0;e&&(d=await fu(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 C(a,i,n);if(!e&&c&&o.type===`open`){d=await fu(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 C(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 Us(t,await pl(o,f,Ka(i?.autoSwap??r,Wa)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||mu(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 nc(b,e),x.notifyUpdate(e))}return!0}finally{d()}}}else d();return p}catch(e){throw d(),e}}});function T(e,t,n){let r={challenge:e,context:t};return Ii(r,xu(n)),w.createCredential(r)}let E=async({autoSwap:e,challenge:t,channel:n,deposit:r,fetch:i,input:a,requiredCumulative:o,signal:s})=>tc(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=Dc({deposit:l,maxDeposit:_,requiredCumulative:o,suggestedDeposit:t.request.suggestedDeposit===void 0?void 0:BigInt(t.request.suggestedDeposit),topUpAmount:v});u>0n&&await zl({autoSwap:e,additionalDeposit:u,challenge:t,channel:n,channelId:n.channelId,createSessionCredential:(e,t)=>T(e,t,a),onUncertainFunding:async e=>{let t=await b.get(Q(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};await nc(b,n),x.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 nc(b,m),x.notifyUpdate(m)});return xi(w,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!jl(e))return;let c=t===void 0?void 0:Jc.parse(t);if(Yc(c))return;_u(p,e.request);let l=await al({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:h}),u=await b.get(l.key);if(!u?.opened)return;let d=xu(i);if(u.origin!==d)throw Error(`Session channel origin mismatch`);let f=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,m=u.cumulativeAmount+ns(e),g=f?BigInt(f.requiredCumulative):m,_=g>m?g:m,v=f?BigInt(f.deposit):u.deposit,y=v>u.deposit?v:u.deposit;_<=y&&y===u.deposit||!dl(await S(l,c,u),u.descriptor)||await E({autoSwap:c?.autoSwap,challenge:e,channel:u,deposit:y,fetch:r,input:i,requiredCumulative:_,signal:a})}),ki(w,async({challenge:e,context:t,credential:r,fetch:i,headers:a,input:c,refetch:l,response:u,signal:d})=>{if(!jl(e))return u;if(!os(u))return ts(Dt(r).payload).action===`open`&&a.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await l?.()??u:u;let f=(await al({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:h})).key,p=await b.get(f),m={assertVoucherWithinLocalLimit:e=>Oc(e,_),createSessionCredential:(e,t)=>T(e,t,c),fetch:i,getChannel:()=>p??null,async topUpIfNeeded({deposit:n,requiredCumulative:r,signal:a}){p&&await E({autoSwap:t===void 0?void 0:Jc.parse(t).autoSwap,challenge:e,channel:p,deposit:p.deposit>n?p.deposit:n,fetch:i,input:c,requiredCumulative:r,signal:a})}};return Xl({onNeedVoucher:(t,n)=>Zl({challenge:e,driver:m,headers:a,input:c,signal:n},t),onReceipt(){},response:u,signal:d})})}function xu(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 Su=new WeakMap;function Cu(e,t){Su.set(e,t)}function wu(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 Tu(e){let t=wu(`close-ready`),n=wu(`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 Eu(e){return e.method===qe.tempo&&e.intent===Je.charge}function Du(e){if(!Eu(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={...Yi(Pl(e)?e.headers:void 0),...Yi(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===V.paymentSession.toLowerCase())?t:{...t,headers:{...r,[V.paymentSession]:n}}}function ku(e,t){return e===void 0?t:{...Jc.parse(e),...t}}function Au(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:m(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:m(e.topUpAmount,t),WebSocket:n}}function ju(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&La(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=Au(e),i;function a(e){let t=new URL(Pl(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=_a(r.fetch),s=va(r.fetch);r.fetch=async(e,t)=>{let n=a(e),r=await s(e,{...t,redirect:(t?.redirect??(Pl(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=Mr(c,o));let l=Fa({chain:ee,getClient:e.client?()=>e.client:e.getClient,rpcUrl:Qn}),u=ja({account:e.account}),d=Pc(),f=e.credentialContext===void 0?void 0:ku(e.credentialContext,{}),p=Tu({getSocketSession:()=>d.socketSession}),m=e.channelStore??Xs(),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,nc(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=>rc(m,e)};$s(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(rc(m,t)).catch(()=>void 0)}async function x(){let e=g;if(e?.created.size){for(let[t,n]of e.created){let e=await m.get(t);if(n.uncertainTopUp||e?.channelId===n.channelId&&e.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before discarding the channel.`);h.add(n.channelId),await Promise.resolve(rc(m,t)).catch(()=>void 0)}e.created.clear(),await z(e.committed??e.previous)}}function S(e){let t=Ze(e.request.methodDetails,Ye.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=zc({channel:d.channel,spent:d.spent,state:d.state}),!0;return!1}function C(e){return vc(d,e)}function w(){let e=d.state.status===`active`?d.state:g?.committed?.state??g?.previous.state;return e?.status===`active`?e.units:0}function T(e){let t=g,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit&&!e.uncertainTopUp||(t.resumed=void 0,t.committed=zc({channel:d.channel,spent:d.spent,state:d.state}))}let E=bu({account:e.account,allowCustomEscrow:n,autoSwap:e.autoSwap,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount,escrow:e.escrow,allowedChainIds:e.allowedChainIds,decimals:r.decimals,maxDeposit:e.maxDeposit,topUpAmount:e.topUpAmount,channelStore:y,onChannelUpdate(e){e.channelId!==d.channel?.channelId&&(d.spent=0n),d.channel=e,d.lastChallenge&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),T(e)}}),te=wi(E);te&&xi(E,e=>ie(()=>Promise.resolve(te(e)),e.signal)),Ai(E);let D=Io({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),O=Ji({trustedTempoProofRealms:e.trustedTempoProofRealms,fetch:c,identity:o,methods:[E],onChallenge:async(e,t)=>{if(!Al(e))return;let n=g,r=n&&n.challengesReceived>0&&e.id===d.lastChallenge?.id,i=r&&ct(e)===ct(d.lastChallenge);n&&n.challengesReceived++,!i&&(S(e)||(n?.created.size?await x():r&&await z(n.committed??n.previous)),d.lastChallenge=e,C({type:`challengeReceived`,challengeId:e.id}))}});function k(e,t){let n={challenge:e,context:ku(f,t)};return i&&Ii(n,i),E.createCredential(n)}function A(e){Fc({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:d})}function j(e=d.state.status===`active`?d.state.units:0){!d.channel||!d.lastChallenge||d.state.status!==`active`&&d.state.status!==`withdrawable`&&d.state.status!==`closeRequested`&&C({type:`activated`,challengeId:d.lastChallenge.id,entry:d.channel,spent:d.spent.toString(),units:e})}async function M(t){let n=t.headers.get(V.paymentSessionSnapshot);if(!n)return;let r=mc(n);La(e.allowedChainIds,r.chainId);let i=await l({chainId:r.chainId});Ia(i,r.chainId);let a=u(i),{entry:o,spent:s}=await ul({account:await e.resolveAccount?.({account:a,chainId:r.chainId,operation:{authority:ms(r.descriptor),kind:`authorizePaymentChannel`}})??a,client:i,snapshot:r});return R(o.cumulativeAmount),await Promise.resolve(y.set(o)).catch(()=>void 0),d.channel=o,d.spent=s,o}async function N(t,n){if(!e.bootstrap||d.channel?.opened)return;let i=Pl(t)?t.headers:void 0,{body:a,method:o,...s}=n??{},c=Pl(t)?t.url:t,l={...s,method:`HEAD`,headers:{...Yi(i),...Yi(n?.headers),[V.acceptPayment]:`${qe.tempo}/${Je.charge}`}};try{let t=await r.fetch(c,l);if(t.status!==402)return await M(t);let n=_t(t).find(Eu);if(!n||!Du(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;Ri(n,i,e.trustedTempoProofRealms);let a=await D.createCredential({challenge:n,context:{}}),o=await r.fetch(c,ni({...l,redirect:`manual`},xt(n),a));return o.ok?await M(o):void 0}catch{return}}function P(e,t){let n=d.socketSession;return Lc({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:d.channel?.channelId===t?d.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:d.spent,tickCost:n?.tickCost})}function F(e,t){let n=Ml(t);if(!n)return;if(hs({...n.descriptor,chainId:n.chainId,escrow:n.escrow}).toLowerCase()!==n.channelId.toLowerCase())throw Error(`close snapshot descriptor does not match its channel ID`);if(n.channelId.toLowerCase()!==e.channelId.toLowerCase())throw Error(`close snapshot channel ID does not match local session`);if(n.chainId!==e.chainId||n.escrow.toLowerCase()!==e.escrow.toLowerCase())throw Error(`close snapshot payment scope does not match local session`);let r=BigInt(n.acceptedCumulative),i=BigInt(n.spent);if(r<0n||i<0n)throw Error(`close snapshot amounts must not be negative`);if(i>r)throw Error(`close snapshot spent exceeds accepted cumulative amount`);if(r>e.cumulativeAmount)throw Error(`close snapshot accepted cumulative exceeds local voucher state`);return{acceptedCumulative:r,spent:i}}function I(e,t){let n=F(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(d.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>d.spent&&(d.spent=i),n}function L(e,t=e.challenge,n=!1){let r=(n?I(e,t):F(e.channel,t))?.acceptedCumulative??P(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return R(r),r.toString()}function R(e){Sc({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}let ne,re;async function ie(e,t){if(re)throw re;for(;;){let e=ne;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(),re)throw re;let n=e();ne=n;try{return await n}catch(e){throw e instanceof Rl&&(re=Error(`Session funding outcome is unknown; reconcile the pending payment before creating a new session manager.`)),e}finally{ne===n&&(ne=void 0)}}async function ae(e){if(!d.channel)throw Error(`Cannot top up session: no active channel`);return tc(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 zl({...n,channel:d.channel,createSessionCredential:k,fetch:r.fetch,onUncertainFunding:async e=>{let t=await y.get(Q(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};d.channel?.channelId===e.channelId&&(d.channel=n),await y.set(n),T(n)}});A(a);let o=d.channel,s=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,C({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:w()}),T(e)}return a})}async function oe(e){return ie(async()=>{e.signal?.throwIfAborted();let t=d.channel?.channelId===e.channelId?d.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=Dc({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 ae({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})},e.signal)}async function se(e,t){let n=Rc({channel:d.channel,channelId:e,challengeId:d.lastChallenge?.id,cumulativeAmount:t,spent:d.spent,state:d.state});n&&d.channel&&(C({type:`activated`,challengeId:n.challengeId,entry:d.channel,spent:n.spent,units:n.units}),await v(d.channel))}async function z(e){let t=Bc(e,d.channel);d.channel=t.channel,d.spent=t.spent,d.state=t.state,d.channel?.opened&&await v(d.channel)}function ce(e){let t=e.headers.get(V.paymentReceipt),n=t?as(t):null;return A(n),Object.assign(e,{receipt:n,challenge:d.lastChallenge,channelId:d.channel?.channelId??null,cumulative:d.channel?.cumulativeAmount??0n})}async function le(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=zc({channel:d.channel,spent:d.spent,state:d.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};g=i;try{await N(e,t),i.trackCreates=!0;let a=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 O(e,a)}catch(e){if(i.created.size?await x():await z(i.committed??n),await s())continue;throw e}let o=ce(t),c=!1;if(o.status===402){let t=await Vl({input:e,init:a,response:o,createSessionCredential:k,fetch:r.fetch,getChannel:()=>d.channel,restoreCumulative:se,setChallenge(e){d.lastChallenge=e},topUpIfNeeded:oe});t&&(c=!0,o=ce(t))}if(!c&&!o.ok&&!o.receipt){if(i.created.size?await x():await z(i.committed??n),await s())continue;return o}return o}}finally{g=void 0}}async function ue(e){let t=await Ul({createSessionCredential:k,fetch:r.fetch,getMinimumSpent:()=>d.spent,headers:d.lastHeaders,lastUrl:d.lastUrl,resolveSignedCloseAmount:t=>L(e,t,!0),signedCloseAmount:L(e),setChallenge(e){d.lastChallenge=e},target:e});return t&&(j(),C({type:`closeStarted`}),C({type:`closed`,receipt:t})),t}let de={createSessionCredential:k,doFetch:le,fetch:r.fetch,getChannel:()=>d.channel,getChallenge:()=>d.lastChallenge,assertVoucherWithinLocalLimit:R,acceptReceipt(e){A(e)},topUpIfNeeded:oe},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:le,async topUp(e){let t=Dl({amount:e,assertVoucherWithinLocalLimit:R,channel:d.channel,decimals:r.decimals,lastChallenge:d.lastChallenge,lastUrl:d.lastUrl});return ie(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=Dl({amount:e,assertVoucherWithinLocalLimit:R,channel:d.channel,decimals:r.decimals,lastChallenge:t.challenge,lastUrl:t.input});return ae({additionalDeposit:n.additionalDeposit,challenge:n.challenge,channelId:n.channelId,headers:d.lastHeaders,input:n.input})})},async sse(e,t){return Wl(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=Il(e);a(n);let i=t?.signal?{signal:t.signal}:void 0;await N(n,i);let o=d.channel?.opened?d.channel.channelId:void 0,{challenge:s,credential:c,httpUrl:l,wsUrl:u}=await $l({async createSessionCredential(e,i){return d.lastChallenge=e,await Ci(E,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),k(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){d.lastUrl=e.toString()},probeInit:Ou(n,i,o),signal:t?.signal});return d.lastChallenge=s,iu({challenge:s,credential:c,httpUrl:l,WebSocket:r.WebSocket,wsUrl:u,options:t,createSessionCredential:k,getChannel:()=>d.channel,setSocketSession(e){d.socketSession=e},async refreshChallenge(){let e=await Ql({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:R,acceptReceipt:A,rejectCloseReady:p.rejectCloseReady,rejectReceipt:p.rejectReceipt,settleCloseReady:p.settleCloseReady,settleReceipt:p.settleReceipt,topUpIfNeeded:oe,waitForReceipt:p.waitForReceipt})},async close(){let e=d.socketSession,t=kc({channel:d.channel,currentSocket:e,lastChallenge:d.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===wl.OPEN){let r=await Vc({activeSocket:n,createSessionCredential:k,currentSocket:e,spent:d.spent,target:t,waitForCloseReady:p.waitForCloseReady,waitForReceipt:p.waitForReceipt});return j(),C({type:`closeStarted`}),C({type:`closed`,receipt:r}),r}return ue(t)}};return Cu(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 Gl(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(!Al(t))throw Error(`Cannot restore session: challenge is not tempo/session.`);if(r<0n)throw Error(`Cannot restore session: spent must not be negative.`);if(r>e.cumulativeAmount)throw Error(`Cannot restore session: spent exceeds local voucher state.`);R(e.cumulativeAmount);let o=F(e,t),s=o&&o.spent>r?o.spent:r;d.lastUrl=n,d.lastChallenge=t,d.channel=e,d.spent=s,C({type:`challengeReceived`,challengeId:t.id}),C({type:`activated`,challengeId:t.id,entry:e,spent:s.toString(),units:0})}}),fe}(function(e){e.serializeSnapshot=pc,e.deserializeSnapshot=mc})(ju||={});const Mu=(1n<<64n)-1n,Nu={dev_second:1n,day:86400n,week:604800n};function Pu(e){return e instanceof Date?e:new Date(e)}function Fu(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 Iu(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new Y({reason:`periodCount is invalid`});let t=Nu[e.periodUnit];if(t===void 0)throw new Y({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>Mu)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 Lu(e){let{challengeExpires:t,request:n}=e;Iu(n);let r=Fu(Pu(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 Ru(e){return[{address:Zu(e.currency,`currency`),selector:`0x95777d59`,recipients:[Zu(e.recipient,`recipient`)]}]}function zu(e){try{let t=A.fromBytes(D.toBytes(e));if(A.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new Y({reason:`challenge id must encode 32 bytes`})}}async function Bu(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=Hu({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:he.getSignPayload(o)}),c=B.from(s);if(c.type===`keychain`||c.type===`multisig`)throw new Y({reason:`keyAuthorization must use a primitive signature`});return he.from(o,{signature:s})}function Vu(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=Uu(i.signature),s=Wu(o);if(Gu({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==zu(n))throw new Y({reason:`keyAuthorization challenge mismatch`});return Ku(o,a),Ju(qu(o),a),Yu(o.scopes,a),{authorization:o,source:{address:Xu(o,s),chainId:r}}}function Hu(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return he.from({address:Zu(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:Fu(Pu(i.subscriptionExpires)),limits:[{token:Zu(i.currency,`currency`),limit:BigInt(i.amount),period:Iu(i)}],scopes:Ru(i),type:t.keyType,witness:zu(n)})}function Uu(e){try{return he.deserialize(e)}catch(e){throw e instanceof he.InvalidSignatureTypeError?new Y({reason:`keyAuthorization must use a primitive signature`}):new Y({reason:`invalid keyAuthorization payload`})}}function Wu(e){let t=e.signature;if(!t)throw new Y({reason:`keyAuthorization must use a primitive signature`});return t}function Gu(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new Y({reason:`keyAuthorization chainId mismatch`});if(t){if(!u(n.address,Zu(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 Ku(e,t){if(Lu({request:t}),e.expiry!==Fu(Pu(t.subscriptionExpires)))throw new Y({reason:`keyAuthorization expiry mismatch`})}function qu(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 Ju(e,t){if(!u(e.token,Zu(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!==Iu(t))throw new Y({reason:`keyAuthorization period mismatch`})}function Yu(e,t){if(!e||e.length!==1)throw new Y({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=Zu(t.currency,`currency`),r=Zu(t.recipient,`recipient`),i=new Set;for(let t of e){if(!u(t.address,n))throw new Y({reason:`keyAuthorization call target mismatch`});let e=Qu(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||!u(t.recipients[0],r))throw new Y({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new Y({reason:`keyAuthorization must allow transferWithMemo`})}function Xu(e,t){let n=he.getSignPayload(e);try{let e=B.extractAddress({payload:n,signature:t});if(!B.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 Zu(e,t){if(!l(e))throw new Y({reason:`${t} must be an address`});return e.toLowerCase()}function Qu(e){return typeof e==`string`?e.toLowerCase():``}const $u=U.object({accessKey:U.optional(U.custom()),account:U.optional(U.custom())});function ed(e={}){let t=Fa({chain:R,getClient:e.getClient,rpcUrl:Qn}),n=ja({account:e.account});return Bt(Po,{context:$u,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.");nd(r.request),await e.validateRequest?.(r.request);let l=await td(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),d=Vu({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:he.serialize(l),type:`keyAuthorization`},request:r.request});if(!u(d.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return jt({challenge:r,payload:{signature:he.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function td(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await Bu({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:Fu(Pu(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:A.fromNumber(BigInt(o.amount)),period:Iu(o)}],scopes:Ru(o),witness:zu(i)}]});return he.fromRpc(c.keyAuthorization)}function nd(e){Iu(e),Fu(Pu(e.subscriptionExpires))}const rd=Object.assign(bu,{manager:ju});function id(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[Io(e),rd(n)]}(function(e){e.charge=Io,e.common=id,e.session=rd,e.subscription=ed})(id||={});const ad=L.union([L.boolean(),L.literal(`true`).transform(()=>!0),L.literal(`false`).transform(()=>!1)]);async function od(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}const sd=L.object({allowCustomEscrow:L.optional(ad),autoSwap:L.optional(ad),channel:L.optional(L.coerce.string()),deposit:L.optional(L.union([L.string(),L.number()])),payWith:L.optional(L.string()),slippage:L.optional(L.coerce.number()),tokenIn:L.optional(L.string())}),cd=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`];function ld(){let t;return vr({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:n,options:r,methodOpts:i}){let a=mr(r.account),o=n.request,s=o.currency,l=hd(i),u=yd({autoSwap:l.autoSwap??r.autoSwap,payWith:l.payWith??r.payWith,slippage:l.slippage??r.slippage,tokenIn:l.tokenIn}),d=s??``,f=o.decimals??6,p,m,h,g=!1,_=process.env.MPPX_PRIVATE_KEY?.trim()||(er(a)?void 0:await hr(a).get());if(!_&&er(a)&&Od()){g=!0;let t=Ed(a);if(t){let i=rr(r.rpcUrl,{network:r.network});h=e({chain:await ir({network:r.network,rpcUrl:i}),transport:c(i)}),_d({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let a=s?await sr(h,s,t.wallet_address).catch(()=>void 0):void 0;d=a?.symbol??s??``,f=a?.decimals??o.decimals??6}}else if(_)m=pe(_);else{let e=Ad();if(e){let t=await hr(e).get();t&&(m=pe(t))}if(!m)throw r.account?new qn({code:`ACCOUNT_NOT_FOUND`,message:`Account "${a}" not found.`,exitCode:69}):new qn({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!g&&m){let t=rr(r.rpcUrl,{network:r.network});h=e({chain:await ir({network:r.network,rpcUrl:t}),transport:c(t)}),_d({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let i=s?await sr(h,s,m.address).catch(()=>void 0):void 0;d=i?.symbol??s??``,f=i?.decimals??o.decimals??6}if(g)return{tokenSymbol:d,tokenDecimals:f,explorerUrl:p,methods:[],async createCredential(e){let t=e.headers.get(`www-authenticate`);if(!t)throw Error(`No WWW-Authenticate header in 402 response.`);return kd(t)}};if(!m||!h)throw new qn({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let v=id({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??(or(h.chain)?`10`:void 0);if(!t)throw new qn({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=xd(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 Ms(h,m,c,i,a);return jt({challenge:n,payload:{action:o,channelId:e,...o===`close`?{closeSignature:await Ns(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=Dt(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?``:`
12
+ `?2:t+1===e.length&&!n?0:1:0}function lu(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=ou({...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 uu(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await Hl({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 $l({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 du(e){let t=new URL(e.input.toString()),n=Yl(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=xt(r).find(Wl);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 fu(e){e.signal?.throwIfAborted();let t=await du(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function pu(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:jt(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:ms(t)}}function mu(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function hu(e){if(!mu(e))return`received mismatched payment-close-ready frame`;let t=os(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 gu(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!mu(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!Wc({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function _u(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=pu({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===Ll.CONNECTING||s.readyState===Ll.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 yu({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await vu(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(xs(n)),await e.waitForReceipt(),l.socket}function vu(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 yu(e){let t=Cs(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`:bu(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 xu(e,t.data);return;case`payment-receipt`:Su(e,t.data);return}}function bu(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=hu({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 xu(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 Hl({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(xs(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function Su(e,t){let n=gu({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 Cu(e,t,n,r){let i=Tt(e),a=new Headers;if(i.toLowerCase()!==V.authorization.toLowerCase()){let e=new Headers(r).get(V.authorization)??(n instanceof Request?n.headers.get(V.authorization):null);e&&!e.startsWith(`${Xe.payment} `)&&a.set(V.authorization,e)}return a.set(i,t),a}const wu=new WeakMap;async function Tu(e,t){let n=wu.get(e)??new Map;wu.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 Eu(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function Du(e,t,n){try{let r=e.response?.headers.get(V.paymentReceipt);if(r){let e=_s(r);if(e.challengeId===t.id&&Eu(n,e))return!0}}catch{}return e.challenges?.some(e=>Wl(e)?Eu(n,Gl(e)):!1)??!1}function Ou(e){let{allowedChainIds:t,currencies:n,decimals:r,expectedRecipients:i,maxAmount:a,maxAtomicAmount:o}=e;if((a!==void 0||o!==void 0)&&n===void 0)throw Error(`Tempo session maxAmount and maxAtomicAmount require currencies.`);for(let e of n??[])ku(a,typeof e==`string`?r:e.decimals);return{chainId:t?.length===1?t[0]:void 0,currencies:n,decimals:r,expectedRecipients:i?new Set(i.map(e=>e.toLowerCase())):void 0,maxAmount:a,maxAtomicAmount:o===void 0?void 0:BigInt(o)}}function ku(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 h(e,t)}}function Au(e,t,n){let r=e.currencies?Oe(e.currencies,t.currency,{chainId:t.methodDetails?.chainId??n??e.chainId,decimals:e.decimals}):void 0;if(e.currencies&&!r)throw Error(`Tempo session currency is not allowed: ${t.currency}.`);if(e.expectedRecipients&&(!t.recipient||!e.expectedRecipients.has(t.recipient.toLowerCase())))throw Error(`Unexpected session recipient: ${t.recipient}`);let i=BigInt(t.amount);if(e.maxAtomicAmount!==void 0&&i>e.maxAtomicAmount)throw Error(`Tempo session amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0&&i>ku(e.maxAmount,r?.decimals))throw Error(`Tempo session amount exceeds maxAmount.`)}function ju(e,t){try{return Au(e,t),!0}catch{return!1}}function Mu(e){return typeof e==`object`&&!!e&&e.action===`close`}function Nu(e={}){let{account:t,allowCustomEscrow:n=!1,autoSwap:r,channelStore:i,decimals:a,escrow:o,allowedChainIds:s,getClient:c,maxDeposit:l,topUpAmount:u,onChannelUpdate:d,resolveAccount:f}=e,p=Ou(e),m=Va({chain:ne,getClient:c,rpcUrl:ir}),g=La({account:t}),_=(e,t)=>{let n=(p.currencies?Oe(p.currencies,e.currency,{chainId:e.methodDetails?.chainId??t??p.chainId,decimals:a}):void 0)?.decimals??a??6;return{decimals:n,maxDeposit:l===void 0?void 0:h(l,n),topUpAmount:u===void 0?void 0:h(u,n)}};l!==void 0&&h(l,6),u!==void 0&&h(u,6);let v=e.origin===void 0?void 0:new URL(e.origin);if(v&&![`http:`,`https:`].includes(v.protocol))throw Error(`Session origins require HTTP or HTTPS`);let y=i??cc(),b={store:y,notifyUpdate:e=>d?.(e)},ee=async(e,t,n)=>{let r=g(e.client,t),i=t?.action?t.descriptor:n?.descriptor??bl({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:Es(i)}:{}}})??r},x=async(e,t,n)=>{let{decimals:r,maxDeposit:i}=_(e.challenge.request,e.chainId);return wl({account:await ee(e,t,n),entry:n,context:t,decimals:r,maxDeposit:i,resolved:e})},S=Kt(Wo,{canHandleChallenge:({challenge:e,context:t})=>Wl(e)&&(Mu(t)||t===Vr||ju(p,e.request)),context:ol,async createCredential(e){let{challenge:t,context:i}=e;i?.action!==`close`&&Au(p,t.request);let a=await _l({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:m});i?.action!==`close`&&t.request.methodDetails?.chainId===void 0&&Au(p,t.request,a.chainId);let c=Ri(e),l=Ui(e)??v?.origin;if(l!==void 0&&(l===`null`||![`http:`,`https:`].includes(new URL(l).protocol)))throw Error(`Session payments require an HTTP or HTTPS origin`);if(v&&l!==v.origin)throw Error(`Session channel origin mismatch`);let u={...b,origin:l},d=()=>{};try{let e=!sl(i)&&i?.descriptor===void 0;e&&(d=await Tu(y,a.key),c&&(await y.get(a.key))?.opened&&await c.prepare());let n=await y.get(a.key);if(n&&n.origin!==l)throw Error(`Session channel origin mismatch`);if(l&&!n&&a.snapshot&&!i?.descriptor&&!v)throw Error(`Session snapshot recovery requires an explicitly configured origin or descriptor`);let o=await x(a,i,n);if(!e&&c&&o.type===`open`){d=await Tu(y,a.key);let e=await y.get(a.key);if(e&&e.origin!==l)throw Error(`Session channel origin mismatch`);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await c.prepare(),n=await y.get(a.key)),o=await x(a,i,n))}let s,f=c&&o.type===`open`?{store:{get:e=>y.get(e),async set(e){s=l?{...e,origin:l}:e},delete:e=>y.delete(e)},notifyUpdate(){}}:u,p=await tc(t,await Tl(o,f,Qa(i?.autoSwap??r,Xa)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||Du(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await y.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await mc(y,e),b.notifyUpdate(e))}return!0}finally{d()}}}else d();return p}catch(e){throw d(),e}}});function C(e,t,n){let r={challenge:e,context:t};return Hi(r,Pu(n)),S.createCredential(r)}let te=async({autoSwap:e,challenge:t,channel:n,deposit:r,fetch:i,input:a,requiredCumulative:o,signal:s})=>pc(y,Q(n),async()=>{s?.throwIfAborted();let c=await y.get(Q(n));if(c?.channelId===n.channelId&&(n=c),n.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let l=n.deposit>r?n.deposit:r,{maxDeposit:u,topUpAmount:d}=_(t.request,n.chainId),f=zc({deposit:l,maxDeposit:u,requiredCumulative:o,suggestedDeposit:t.request.suggestedDeposit===void 0?void 0:BigInt(t.request.suggestedDeposit),topUpAmount:d});f>0n&&await Ql({autoSwap:e,additionalDeposit:f,challenge:t,channel:n,channelId:n.channelId,createSessionCredential:(e,t)=>C(e,t,a),onUncertainFunding:async e=>{let t=await y.get(Q(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};await mc(y,n),b.notifyUpdate(n)},fetch:i,input:a,signal:s});let p=l+f;if(p===n.deposit)return;let m=await y.get(Q(n)),h=m?.channelId.toLowerCase()===n.channelId.toLowerCase()?m:n,g={...h,deposit:h.deposit>p?h.deposit:p};await mc(y,g),b.notifyUpdate(g)});return Di(S,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!Wl(e))return;let c=t===void 0?void 0:ol.parse(t);if(sl(c))return;Au(p,e.request);let l=await _l({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m}),u=await y.get(l.key);if(!u?.opened)return;let d=Pu(i);if(u.origin!==d)throw Error(`Session channel origin mismatch`);let f=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,h=u.cumulativeAmount+ms(e),g=f?BigInt(f.requiredCumulative):h,_=g>h?g:h,v=f?BigInt(f.deposit):u.deposit,b=v>u.deposit?v:u.deposit;_<=b&&b===u.deposit||!Cl(await ee(l,c,u),u.descriptor)||await te({autoSwap:c?.autoSwap,challenge:e,channel:u,deposit:b,fetch:r,input:i,requiredCumulative:_,signal:a})}),Fi(S,async({challenge:e,context:t,credential:r,fetch:i,headers:a,input:c,refetch:l,response:u,signal:d})=>{if(!Wl(e))return u;if(!vs(u))return ps(jt(r).payload).action===`open`&&a.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await l?.()??u:u;let f=(await _l({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:m})).key,p=await y.get(f),h={assertVoucherWithinLocalLimit:t=>Bc(t,_(e.request,p?.chainId).maxDeposit),createSessionCredential:(e,t)=>C(e,t,c),fetch:i,getChannel:()=>p??null,async topUpIfNeeded({deposit:n,requiredCumulative:r,signal:a}){p&&await te({autoSwap:t===void 0?void 0:ol.parse(t).autoSwap,challenge:e,channel:p,deposit:p.deposit>n?p.deposit:n,fetch:i,input:c,requiredCumulative:r,signal:a})}};return lu({onNeedVoucher:(t,n)=>uu({challenge:e,driver:h,headers:a,input:c,signal:n},t),onReceipt(){},response:u,signal:d})})}function Pu(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 Fu=new WeakMap;function Iu(e,t){Fu.set(e,t)}function Lu(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=Lu(`close-ready`),n=Lu(`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 zu(e){return e.method===Ze.tempo&&e.intent===Qe.charge}function Bu(e){if(!zu(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function Vu(e,t,n){if(!n)return t;let r={...ta(ql(e)?e.headers:void 0),...ta(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===V.paymentSession.toLowerCase())?t:{...t,headers:{...r,[V.paymentSession]:n}}}function Hu(e,t){return e===void 0?t:{...ol.parse(e),...t}}function Uu(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:h(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:h(e.topUpAmount,t),WebSocket:n}}function Wu(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&Ua(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=Uu(e),i;function a(e){let t=new URL(ql(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=Ca(r.fetch),s=wa(r.fetch);r.fetch=async(e,t)=>{let n=a(e),r=await s(e,{...t,redirect:(t?.redirect??(ql(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=Rr(c,o));let l=Va({chain:ne,getClient:e.client?()=>e.client:e.getClient,rpcUrl:ir}),u=La({account:e.account}),d=Kc(),f=e.credentialContext===void 0?void 0:Hu(e.credentialContext,{}),p=Ru({getSocketSession:()=>d.socketSession}),m=e.channelStore??cc(),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,mc(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=>hc(m,e)};dc(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(hc(m,t)).catch(()=>void 0)}async function ee(){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(hc(m,t)).catch(()=>void 0)}e.created.clear(),await ce(e.committed??e.previous)}}function x(e){let t=tt(e.request.methodDetails,$e.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=Zc({channel:d.channel,spent:d.spent,state:d.state}),!0;return!1}function S(e){return Ac(d,e)}function C(){let e=d.state.status===`active`?d.state:g?.committed?.state??g?.previous.state;return e?.status===`active`?e.units:0}function te(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=Zc({channel:d.channel,spent:d.spent,state:d.state}))}let w=Nu({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&&S({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:C()}),te(e)}}),T=Ai(w);T&&Di(w,e=>ie(()=>Promise.resolve(T(e)),e.signal)),Ii(w);let E=qo({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),D=ea({trustedTempoProofRealms:e.trustedTempoProofRealms,fetch:c,identity:o,methods:[w],onChallenge:async(e,t)=>{if(!Ul(e))return;let n=g,r=n&&n.challengesReceived>0&&e.id===d.lastChallenge?.id,i=r&&ft(e)===ft(d.lastChallenge);n&&n.challengesReceived++,!i&&(x(e)||(n?.created.size?await ee():r&&await ce(n.committed??n.previous)),d.lastChallenge=e,S({type:`challengeReceived`,challengeId:e.id}))}});function O(e,t){let n={challenge:e,context:Hu(f,t)};return i&&Hi(n,i),w.createCredential(n)}function k(e){qc({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:d})}function A(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`&&S({type:`activated`,challengeId:d.lastChallenge.id,entry:d.channel,spent:d.spent.toString(),units:e})}async function j(t){let n=t.headers.get(V.paymentSessionSnapshot);if(!n)return;let r=Ec(n);Ua(e.allowedChainIds,r.chainId);let i=await l({chainId:r.chainId});Ha(i,r.chainId);let a=u(i),{entry:o,spent:s}=await Sl({account:await e.resolveAccount?.({account:a,chainId:r.chainId,operation:{authority:Es(r.descriptor),kind:`authorizePaymentChannel`}})??a,client:i,snapshot:r});return L(o.cumulativeAmount),await Promise.resolve(y.set(o)).catch(()=>void 0),d.channel=o,d.spent=s,o}async function M(t,n){if(!e.bootstrap||d.channel?.opened)return;let i=ql(t)?t.headers:void 0,{body:a,method:o,...s}=n??{},c=ql(t)?t.url:t,l={...s,method:`HEAD`,headers:{...ta(i),...ta(n?.headers),[V.acceptPayment]:`${Ze.tempo}/${Qe.charge}`}};try{let t=await r.fetch(c,l);if(t.status!==402)return await j(t);let n=xt(t).find(zu);if(!n||!Bu(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;Wi(n,i,e.trustedTempoProofRealms);let a=await E.createCredential({challenge:n,context:{}}),o=await r.fetch(c,ci({...l,redirect:`manual`},Tt(n),a));return o.ok?await j(o):void 0}catch{return}}function N(e,t){let n=d.socketSession;return Yc({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 P(e,t){let n=Gl(t);if(!n)return;if(Ds({...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 F(e,t){let n=P(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 I(e,t=e.challenge,n=!1){let r=(n?F(e,t):P(e.channel,t))?.acceptedCumulative??N(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return L(r),r.toString()}function L(e){Pc({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}let R,re;async function ie(e,t){if(re)throw re;for(;;){let e=R;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(),re)throw re;let n=e();R=n;try{return await n}catch(e){throw e instanceof Zl&&(re=Error(`Session funding outcome is unknown; reconcile the pending payment before creating a new session manager.`)),e}finally{R===n&&(R=void 0)}}async function ae(e){if(!d.channel)throw Error(`Cannot top up session: no active channel`);return pc(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 Ql({...n,channel:d.channel,createSessionCredential:O,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),te(n)}});k(a);let o=d.channel,s=Vl({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,S({type:`activated`,challengeId:d.lastChallenge.id,entry:e,spent:d.spent.toString(),units:C()}),te(e)}return a})}async function oe(e){return ie(async()=>{e.signal?.throwIfAborted();let t=d.channel?.channelId===e.channelId?d.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=zc({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 ae({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})},e.signal)}async function se(e,t){let n=Xc({channel:d.channel,channelId:e,challengeId:d.lastChallenge?.id,cumulativeAmount:t,spent:d.spent,state:d.state});n&&d.channel&&(S({type:`activated`,challengeId:n.challengeId,entry:d.channel,spent:n.spent,units:n.units}),await v(d.channel))}async function ce(e){let t=Qc(e,d.channel);d.channel=t.channel,d.spent=t.spent,d.state=t.state,d.channel?.opened&&await v(d.channel)}function z(e){let t=e.headers.get(V.paymentReceipt),n=t?_s(t):null;return k(n),Object.assign(e,{receipt:n,challenge:d.lastChallenge,channelId:d.channel?.channelId??null,cumulative:d.channel?.cumulativeAmount??0n})}async function le(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=Zc({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 M(e,t),i.trackCreates=!0;let a=Vu(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=Vu(e,t,void 0),!0)}for(;;){let t;try{t=await D(e,a)}catch(e){if(i.created.size?await ee():await ce(i.committed??n),await s())continue;throw e}let o=z(t),c=!1;if(o.status===402){let t=await eu({input:e,init:a,response:o,createSessionCredential:O,fetch:r.fetch,getChannel:()=>d.channel,restoreCumulative:se,setChallenge(e){d.lastChallenge=e},topUpIfNeeded:oe});t&&(c=!0,o=z(t))}if(!c&&!o.ok&&!o.receipt){if(i.created.size?await ee():await ce(i.committed??n),await s())continue;return o}return o}}finally{g=void 0}}async function ue(e){let t=await nu({createSessionCredential:O,fetch:r.fetch,getMinimumSpent:()=>d.spent,headers:d.lastHeaders,lastUrl:d.lastUrl,resolveSignedCloseAmount:t=>I(e,t,!0),signedCloseAmount:I(e),setChallenge(e){d.lastChallenge=e},target:e});return t&&(A(),S({type:`closeStarted`}),S({type:`closed`,receipt:t})),t}let de={createSessionCredential:O,doFetch:le,fetch:r.fetch,getChannel:()=>d.channel,getChallenge:()=>d.lastChallenge,assertVoucherWithinLocalLimit:L,acceptReceipt(e){k(e)},topUpIfNeeded:oe},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:le,async topUp(e){let t=Bl({amount:e,assertVoucherWithinLocalLimit:L,channel:d.channel,decimals:r.decimals,lastChallenge:d.lastChallenge,lastUrl:d.lastUrl});return ie(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=Bl({amount:e,assertVoucherWithinLocalLimit:L,channel:d.channel,decimals:r.decimals,lastChallenge:t.challenge,lastUrl:t.input});return ae({additionalDeposit:n.additionalDeposit,challenge:n.challenge,channelId:n.channelId,headers:d.lastHeaders,input:n.input})})},async sse(e,t){return ru(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=Yl(e);a(n);let i=t?.signal?{signal:t.signal}:void 0;await M(n,i);let o=d.channel?.opened?d.channel.channelId:void 0,{challenge:s,credential:c,httpUrl:l,wsUrl:u}=await fu({async createSessionCredential(e,i){return d.lastChallenge=e,await ki(w,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),O(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){d.lastUrl=e.toString()},probeInit:Vu(n,i,o),signal:t?.signal});return d.lastChallenge=s,_u({challenge:s,credential:c,httpUrl:l,WebSocket:r.WebSocket,wsUrl:u,options:t,createSessionCredential:O,getChannel:()=>d.channel,setSocketSession(e){d.socketSession=e},async refreshChallenge(){let e=await du({fetch:r.fetch,input:l,probeInit:Vu(l,i,d.channel?.opened?d.channel.channelId:void 0),signal:t?.signal});return d.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:L,acceptReceipt:k,rejectCloseReady:p.rejectCloseReady,rejectReceipt:p.rejectReceipt,settleCloseReady:p.settleCloseReady,settleReceipt:p.settleReceipt,topUpIfNeeded:oe,waitForReceipt:p.waitForReceipt})},async close(){let e=d.socketSession,t=Vc({channel:d.channel,currentSocket:e,lastChallenge:d.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===Ll.OPEN){let r=await $c({activeSocket:n,createSessionCredential:O,currentSocket:e,spent:d.spent,target:t,waitForCloseReady:p.waitForCloseReady,waitForReceipt:p.waitForReceipt});return A(),S({type:`closeStarted`}),S({type:`closed`,receipt:r}),r}return ue(t)}};return Iu(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 iu(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(!Ul(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.`);L(e.cumulativeAmount);let o=P(e,t),s=o&&o.spent>r?o.spent:r;d.lastUrl=n,d.lastChallenge=t,d.channel=e,d.spent=s,S({type:`challengeReceived`,challengeId:t.id}),S({type:`activated`,challengeId:t.id,entry:e,spent:s.toString(),units:0})}}),fe}(function(e){e.serializeSnapshot=Tc,e.deserializeSnapshot=Ec})(Wu||={});const Gu=(1n<<64n)-1n,Ku={dev_second:1n,day:86400n,week:604800n};function qu(e){return e instanceof Date?e:new Date(e)}function Ju(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 Yu(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new Y({reason:`periodCount is invalid`});let t=Ku[e.periodUnit];if(t===void 0)throw new Y({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>Gu)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 Xu(e){let{challengeExpires:t,request:n}=e;Yu(n);let r=Ju(qu(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 Zu(e){return[{address:ud(e.currency,`currency`),selector:`0x95777d59`,recipients:[ud(e.recipient,`recipient`)]}]}function Qu(e){try{let t=A.fromBytes(D.toBytes(e));if(A.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new Y({reason:`challenge id must encode 32 bytes`})}}async function $u(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=td({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:ge.getSignPayload(o)}),c=B.from(s);if(c.type===`keychain`||c.type===`configurable`)throw new Y({reason:`keyAuthorization must use a primitive signature`});return ge.from(o,{signature:s})}function ed(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=nd(i.signature),s=rd(o);if(id({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==Qu(n))throw new Y({reason:`keyAuthorization challenge mismatch`});return ad(o,a),sd(od(o),a),cd(o.scopes,a),{authorization:o,source:{address:ld(o,s),chainId:r}}}function td(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return ge.from({address:ud(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:Ju(qu(i.subscriptionExpires)),limits:[{token:ud(i.currency,`currency`),limit:BigInt(i.amount),period:Yu(i)}],scopes:Zu(i),type:t.keyType,witness:Qu(n)})}function nd(e){try{return ge.deserialize(e)}catch(e){throw e instanceof ge.InvalidSignatureTypeError?new Y({reason:`keyAuthorization must use a primitive signature`}):new Y({reason:`invalid keyAuthorization payload`})}}function rd(e){let t=e.signature;if(!t)throw new Y({reason:`keyAuthorization must use a primitive signature`});return t}function id(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new Y({reason:`keyAuthorization chainId mismatch`});if(t){if(!d(n.address,ud(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 ad(e,t){if(Xu({request:t}),e.expiry!==Ju(qu(t.subscriptionExpires)))throw new Y({reason:`keyAuthorization expiry mismatch`})}function od(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 sd(e,t){if(!d(e.token,ud(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!==Yu(t))throw new Y({reason:`keyAuthorization period mismatch`})}function cd(e,t){if(!e||e.length!==1)throw new Y({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=ud(t.currency,`currency`),r=ud(t.recipient,`recipient`),i=new Set;for(let t of e){if(!d(t.address,n))throw new Y({reason:`keyAuthorization call target mismatch`});let e=dd(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||!d(t.recipients[0],r))throw new Y({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new Y({reason:`keyAuthorization must allow transferWithMemo`})}function ld(e,t){let n=ge.getSignPayload(e);try{let e=B.extractAddress({payload:n,signature:t});if(!B.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 ud(e,t){if(!u(e))throw new Y({reason:`${t} must be an address`});return e.toLowerCase()}function dd(e){return typeof e==`string`?e.toLowerCase():``}const fd=U.object({accessKey:U.optional(U.custom()),account:U.optional(U.custom())});function pd(e={}){let t=Va({chain:R,getClient:e.getClient,rpcUrl:ir}),n=La({account:e.account});return Kt(Go,{context:fd,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.");hd(r.request),await e.validateRequest?.(r.request);let l=await md(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),u=ed({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:ge.serialize(l),type:`keyAuthorization`},request:r.request});if(!d(u.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return Ft({challenge:r,payload:{signature:ge.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function md(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await $u({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:Ju(qu(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:A.fromNumber(BigInt(o.amount)),period:Yu(o)}],scopes:Zu(o),witness:Qu(i)}]});return ge.fromRpc(c.keyAuthorization)}function hd(e){Yu(e),Ju(qu(e.subscriptionExpires))}const gd=Object.assign(Nu,{manager:Wu});function _d(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[qo(e),gd(n)]}(function(e){e.charge=qo,e.common=_d,e.session=gd,e.subscription=pd})(_d||={});const vd=L.union([L.boolean(),L.literal(`true`).transform(()=>!0),L.literal(`false`).transform(()=>!1)]);async function yd(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}const bd=L.object({allowCustomEscrow:L.optional(vd),autoSwap:L.optional(vd),channel:L.optional(L.coerce.string()),deposit:L.optional(L.union([L.string(),L.number()])),payWith:L.optional(L.string()),slippage:L.optional(L.coerce.number()),tokenIn:L.optional(L.string())}),xd=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`];function Sd(){let t;return wr({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:n,options:r,methodOpts:i}){let a=br(r.account),o=n.request,s=o.currency,c=Od(i),u=Md({autoSwap:c.autoSwap??r.autoSwap,payWith:c.payWith??r.payWith,slippage:c.slippage??r.slippage,tokenIn:c.tokenIn}),d=s??``,f=o.decimals??6,p,m,h,g=!1,_=process.env.MPPX_PRIVATE_KEY?.trim()||(or(a)?void 0:await xr(a).get());if(!_&&or(a)&&Vd()){g=!0;let t=zd(a);if(t){let i=lr(r.rpcUrl,{network:r.network});h=e({chain:await ur({network:r.network,rpcUrl:i}),transport:l(i)}),Ad({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let a=s?await pr(h,s,t.wallet_address).catch(()=>void 0):void 0;d=a?.symbol??s??``,f=a?.decimals??o.decimals??6}}else if(_)m=me(_);else{let e=Ud();if(e){let t=await xr(e).get();t&&(m=me(t))}if(!m)throw r.account?new $n({code:`ACCOUNT_NOT_FOUND`,message:`Account "${a}" not found.`,exitCode:69}):new $n({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!g&&m){let t=lr(r.rpcUrl,{network:r.network});h=e({chain:await ur({network:r.network,rpcUrl:t}),transport:l(t)}),Ad({challenge:n,clientChainId:h.chain?.id}),p=h.chain?.blockExplorers?.default?.url;let i=s?await pr(h,s,m.address).catch(()=>void 0):void 0;d=i?.symbol??s??``,f=i?.decimals??o.decimals??6}if(g)return{tokenSymbol:d,tokenDecimals:f,explorerUrl:p,methods:[],async createCredential(e){let t=e.headers.get(`www-authenticate`);if(!t)throw Error(`No WWW-Authenticate header in 402 response.`);return Hd(t)}};if(!m||!h)throw new $n({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let v=_d({account:m,...c.allowCustomEscrow===void 0?{}:{allowCustomEscrow:c.allowCustomEscrow},getClient:()=>h,...u===void 0?{}:{autoSwap:u},maxDeposit:(()=>{if(n.intent!==`session`)return;let e=n.request.suggestedDeposit,t=(c.deposit===void 0?void 0:String(c.deposit))??e??(fr(h.chain)?`10`:void 0);if(!t)throw new $n({code:`MISSING_DEPOSIT`,message:`Session payment requires a deposit. Use -M deposit=<amount> or connect to testnet.`,exitCode:2});return t})()}),y=(()=>{if(!c.channel)return;let e=c.channel,t=Pd(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 Ws(h,m,c,i,a);return Ft({challenge:n,payload:{action:o,channelId:e,...o===`close`?{closeSignature:await Gs(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=jt(r),g=n.request,_=g.methodDetails,v=h.payload.channelId,y=_?.escrowContract??_?.escrow??`0x4d50500000000000000000000000000000000000`,b=_?.chainId??0,ee=BigInt(g.amount),x=`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?``:`
13
13
  `}${Z.dim(`Channel opened ${h.payload.channelId}`)}${t}\n`)}else m(`${l?``:`
14
- `}${Z.dim(`Channel reused ${h.payload.channelId}`)}\n`)}let C=i;C.ok&&!C.headers.get(`Content-Type`)?.includes(`text/event-stream`)&&h.payload.action===`open`&&`cumulativeAmount`in h.payload&&(S=BigInt(h.payload.cumulativeAmount));let w=C.headers.get(V.paymentReceipt);if(w)try{let e=JSON.parse(D.toString(w));dd(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&Sd(v,S),s>=1&&ud(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
15
- `})}catch{}return(C.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await fd(C,{challenge:n,channelId:v,escrowContract:y,chainId:b,cumulativeAmount:S,tickCost:x,fetchUrl:a,fetchInit:o,session:t,info:m,verbose:s,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this}):(await od(C),v&&y&&b&&(l&&m(`
16
- `),l&&!await e.confirm(`Close channel?`,!0)?s>=1&&m(`${Z.dim(`Kept channel open.`)}\n`):await pd({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 ud(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(`(${tr(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,$n(`${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(`
17
- `)}function dd(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 fd(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 md():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:{[V.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{ud(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
14
+ `}${Z.dim(`Channel reused ${h.payload.channelId}`)}\n`)}let S=i;S.ok&&!S.headers.get(`Content-Type`)?.includes(`text/event-stream`)&&h.payload.action===`open`&&`cumulativeAmount`in h.payload&&(x=BigInt(h.payload.cumulativeAmount));let C=S.headers.get(V.paymentReceipt);if(C)try{let e=JSON.parse(D.toString(C));wd(e,x),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&Fd(v,x),s>=1&&Cd(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
15
+ `})}catch{}return(S.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await Td(S,{challenge:n,channelId:v,escrowContract:y,chainId:b,cumulativeAmount:x,tickCost:ee,fetchUrl:a,fetchInit:o,session:t,info:m,verbose:s,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this}):(await yd(S),v&&y&&b&&(l&&m(`
16
+ `),l&&!await e.confirm(`Close channel?`,!0)?s>=1&&m(`${Z.dim(`Kept channel open.`)}\n`):await Ed({channelId:v,cumulativeAmount:x,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 Cd(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(`(${sr(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,ar(`${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(`
17
+ `)}function wd(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 Td(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 Dd():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:{[V.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{Cd(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
18
18
 
19
19
  `})}catch{}o=``;continue}if(e.length===0)u(`
20
20
  `);else try{let t=JSON.parse(e);u(t.token??t.choices?.[0]?.delta?.content??e)}catch{u(e)}o=``}}};for(;;){let{done:e,value:t}=await r.read();if(e)break;a+=i.decode(t,{stream:!0});let n=a.split(`
21
- `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await pd({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 pd(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:{...Yi(e.fetchInit.headers),Authorization:t}});if(n.ok){if(Cd(e.channelId),e.verbose>=1){let t=n.headers.get(V.paymentReceipt),r;if(t)try{let e=JSON.parse(D.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${Z.dim($n(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${Z.dim(`Channel closed.`)} ${Z.dim(`Spent ${tr(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 md(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 hd(e){return gd(sd,e,cd)}function gd(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 _d(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 qn({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function vd(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function yd(e){let t=vd(e.tokenIn)??vd(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 bd(){return I.join(process.env.XDG_CONFIG_HOME||I.join(F.homedir(),`.config`),`mppx`,`channels`)}function xd(e){try{let t=P.readFileSync(I.join(bd(),e),`utf-8`).trim();return t?BigInt(t):void 0}catch{return}}function Sd(e,t){let n=bd();P.mkdirSync(n,{recursive:!0}),P.writeFileSync(I.join(n,e),t.toString(),`utf-8`)}function Cd(e){try{P.unlinkSync(I.join(bd(),e))}catch{}}function wd(){return F.platform()===`darwin`?I.join(F.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):I.join(process.env.XDG_DATA_HOME||I.join(F.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function Td(){try{let e=P.readFileSync(wd(),`utf-8`),t=[],n;for(let r of e.split(`
22
- `)){let e=r.trim();if(e===`[[keys]]`){n?.wallet_address&&t.push(n),n={wallet_type:`local`,wallet_address:``,chain_id:0};continue}if(!n)continue;let i=e.match(/^(\w+)\s*=\s*"?([^"]*)"?$/);if(!i)continue;let[,a,o]=i;a===`wallet_type`?n.wallet_type=o:a===`wallet_address`?n.wallet_address=o:a===`chain_id`&&(n.chain_id=Number.parseInt(o,10))}return n?.wallet_address&&t.push(n),t}catch{return[]}}function Ed(e){let t=Td();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 Dd;function Od(){if(Dd!==void 0)return Dd;try{N.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),Dd=!0}catch{Dd=!1}return Dd}async function kd(e){return new Promise((t,n)=>{N.execFile(`tempo`,[`mpp`,`sign`,`--challenge`,e],(e,r,i)=>{if(e){let t=i?.trim()||e.message;n(Error(`tempo mpp sign failed: ${t}`));return}let a=r.trim();if(!a){n(Error(`tempo mpp sign returned empty output`));return}t(a)})})}function Ad(){let e=pr();if(er(e.get())&&!Od()&&F.platform()===`darwin`)try{let t=N.execFileSync(`security`,[`dump-keychain`],{encoding:`utf-8`}),n=[];for(let e of t.split(`keychain:`)){let t=e.match(/"svce"<blob>="([^"]*)"/),r=e.match(/"acct"<blob>="([^"]*)"/);t?.[1]===`mppx`&&r?.[1]&&n.push(r[1])}if(n.length>0)return e.set(n[0]),n[0]}catch{}}const jd=[...Object.entries(Oe),...Object.entries(ke),...Object.entries(Ae),...Object.entries(je)];function Md(){return vr({method:`evm`,supports:Nd,async setup({challenge:e,options:t}){let n=e.request,r=n.network?Pd(Re(n.network)):void 0,i=n.network&&n.asset?jd.find(([,e])=>Ie(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`?Ee({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await _r(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...Gn({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function Nd(e){if(!On(e))return!1;let t=e.request,n=t.extra,r=n?.assetTransferMethod;return t.scheme===`exact`&&typeof t.asset==`string`&&typeof t.network==`string`&&typeof n?.name==`string`&&typeof n?.version==`string`&&(r===void 0||r===`eip3009`)}function Pd(e){return Object.values(E).find(t=>t.id===e)}export{vr as createPlugin,yr as evm,Or as stripe,ld as tempo,Md as x402};
21
+ `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await Ed({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 Ed(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:{...ta(e.fetchInit.headers),Authorization:t}});if(n.ok){if(Id(e.channelId),e.verbose>=1){let t=n.headers.get(V.paymentReceipt),r;if(t)try{let e=JSON.parse(D.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${Z.dim(ar(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${Z.dim(`Channel closed.`)} ${Z.dim(`Spent ${sr(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 Dd(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 Od(e){return kd(bd,e,xd)}function kd(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 Ad(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 $n({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function jd(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function Md(e){let t=jd(e.tokenIn)??jd(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 Nd(){return I.join(process.env.XDG_CONFIG_HOME||I.join(F.homedir(),`.config`),`mppx`,`channels`)}function Pd(e){try{let t=P.readFileSync(I.join(Nd(),e),`utf-8`).trim();return t?BigInt(t):void 0}catch{return}}function Fd(e,t){let n=Nd();P.mkdirSync(n,{recursive:!0}),P.writeFileSync(I.join(n,e),t.toString(),`utf-8`)}function Id(e){try{P.unlinkSync(I.join(Nd(),e))}catch{}}function Ld(){return F.platform()===`darwin`?I.join(F.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):I.join(process.env.XDG_DATA_HOME||I.join(F.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function Rd(){try{let e=P.readFileSync(Ld(),`utf-8`),t=[],n;for(let r of e.split(`
22
+ `)){let e=r.trim();if(e===`[[keys]]`){n?.wallet_address&&t.push(n),n={wallet_type:`local`,wallet_address:``,chain_id:0};continue}if(!n)continue;let i=e.match(/^(\w+)\s*=\s*"?([^"]*)"?$/);if(!i)continue;let[,a,o]=i;a===`wallet_type`?n.wallet_type=o:a===`wallet_address`?n.wallet_address=o:a===`chain_id`&&(n.chain_id=Number.parseInt(o,10))}return n?.wallet_address&&t.push(n),t}catch{return[]}}function zd(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 Bd;function Vd(){if(Bd!==void 0)return Bd;try{N.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),Bd=!0}catch{Bd=!1}return Bd}async function Hd(e){return new Promise((t,n)=>{N.execFile(`tempo`,[`mpp`,`sign`,`--challenge`,e],(e,r,i)=>{if(e){let t=i?.trim()||e.message;n(Error(`tempo mpp sign failed: ${t}`));return}let a=r.trim();if(!a){n(Error(`tempo mpp sign returned empty output`));return}t(a)})})}function Ud(){let e=yr();if(or(e.get())&&!Vd()&&F.platform()===`darwin`)try{let t=N.execFileSync(`security`,[`dump-keychain`],{encoding:`utf-8`}),n=[];for(let e of t.split(`keychain:`)){let t=e.match(/"svce"<blob>="([^"]*)"/),r=e.match(/"acct"<blob>="([^"]*)"/);t?.[1]===`mppx`&&r?.[1]&&n.push(r[1])}if(n.length>0)return e.set(n[0]),n[0]}catch{}}const Wd=[...Object.entries(Me),...Object.entries(Ne),...Object.entries(Pe),...Object.entries(Fe)];function Gd(){return wr({method:`evm`,supports:Kd,async setup({challenge:e,options:t}){let n=e.request,r=n.network?qd(He(n.network)):void 0,i=n.network&&n.asset?Wd.find(([,e])=>Be(e,n.asset,n.network)):void 0,a=n.extra?.name,o=n.extra?.version,s=n.asset&&n.network&&typeof a==`string`&&typeof o==`string`?Ae({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await Cr(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...Zn({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function Kd(e){if(!Pn(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 qd(e){return Object.values(T).find(t=>t.id===e)}export{wr as createPlugin,Tr as evm,Pr as stripe,Sd as tempo,Gd as x402};