mppx 0.8.1 → 0.8.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/dist/Errors.d.ts +13 -0
- package/dist/Errors.d.ts.map +1 -1
- package/dist/Errors.js +12 -0
- package/dist/Errors.js.map +1 -1
- package/dist/cli/cli.d.ts +2 -1
- package/dist/cli/cli.d.ts.map +1 -1
- package/dist/cli/cli.js +35 -4
- package/dist/cli/cli.js.map +1 -1
- package/dist/cli/plugins/tempo.d.ts +15 -0
- package/dist/cli/plugins/tempo.d.ts.map +1 -1
- package/dist/cli/plugins/tempo.js +125 -14
- package/dist/cli/plugins/tempo.js.map +1 -1
- package/dist/cli/utils.d.ts +2 -2
- package/dist/cli/utils.d.ts.map +1 -1
- package/dist/cli/utils.js +7 -1
- package/dist/cli/utils.js.map +1 -1
- package/dist/client/Mppx.d.ts +2 -0
- package/dist/client/Mppx.d.ts.map +1 -1
- package/dist/client/Mppx.js +2 -1
- package/dist/client/Mppx.js.map +1 -1
- package/dist/client/Transport.d.ts.map +1 -1
- package/dist/client/Transport.js +11 -12
- package/dist/client/Transport.js.map +1 -1
- package/dist/client/internal/Fetch.d.ts +2 -0
- package/dist/client/internal/Fetch.d.ts.map +1 -1
- package/dist/client/internal/Fetch.js +55 -50
- package/dist/client/internal/Fetch.js.map +1 -1
- package/dist/client/internal/protocols/Mcp.d.ts +6 -0
- package/dist/client/internal/protocols/Mcp.d.ts.map +1 -1
- package/dist/client/internal/protocols/Mcp.js +28 -10
- package/dist/client/internal/protocols/Mcp.js.map +1 -1
- package/dist/client/internal/protocols/X402.d.ts.map +1 -1
- package/dist/client/internal/protocols/X402.js +18 -12
- package/dist/client/internal/protocols/X402.js.map +1 -1
- package/dist/stripe/server/internal/html.gen.d.ts +1 -1
- package/dist/stripe/server/internal/html.gen.js +1 -1
- package/dist/tempo/client/Charge.d.ts.map +1 -1
- package/dist/tempo/client/Charge.js +7 -1
- package/dist/tempo/client/Charge.js.map +1 -1
- package/dist/tempo/internal/auto-swap.d.ts.map +1 -1
- package/dist/tempo/internal/auto-swap.js +15 -5
- package/dist/tempo/internal/auto-swap.js.map +1 -1
- package/dist/tempo/internal/fee-payer.d.ts.map +1 -1
- package/dist/tempo/internal/fee-payer.js +57 -1
- package/dist/tempo/internal/fee-payer.js.map +1 -1
- package/dist/tempo/internal/fee-token.js +1 -1
- package/dist/tempo/internal/fee-token.js.map +1 -1
- package/dist/tempo/server/internal/html.gen.d.ts +1 -1
- package/dist/tempo/server/internal/html.gen.d.ts.map +1 -1
- package/dist/tempo/server/internal/html.gen.js +1 -1
- package/dist/tempo/server/internal/html.gen.js.map +1 -1
- package/dist/tempo/session/client/SessionManager.d.ts.map +1 -1
- package/dist/tempo/session/client/SessionManager.js +47 -5
- package/dist/tempo/session/client/SessionManager.js.map +1 -1
- package/dist/x402/Header.d.ts +10 -1
- package/dist/x402/Header.d.ts.map +1 -1
- package/dist/x402/Header.js +27 -1
- package/dist/x402/Header.js.map +1 -1
- package/package.json +4 -4
- package/src/Errors.test.ts +28 -0
- package/src/Errors.ts +19 -0
- package/src/cli/cli.test.ts +194 -0
- package/src/cli/cli.ts +43 -7
- package/src/cli/plugins/tempo.ts +161 -17
- package/src/cli/utils.ts +14 -2
- package/src/client/Mppx.test-d.ts +9 -0
- package/src/client/Mppx.test.ts +41 -0
- package/src/client/Mppx.ts +4 -0
- package/src/client/Transport.test.ts +124 -0
- package/src/client/Transport.ts +11 -9
- package/src/client/internal/Fetch.test-d.ts +9 -0
- package/src/client/internal/Fetch.test.ts +186 -4
- package/src/client/internal/Fetch.ts +85 -76
- package/src/client/internal/protocols/Mcp.ts +39 -15
- package/src/client/internal/protocols/X402.ts +9 -5
- package/src/mcp/client/McpClient.integration.test.ts +12 -1
- package/src/server/Mppx.test.ts +3 -0
- package/src/stripe/server/internal/html.gen.ts +1 -1
- package/src/tempo/client/Charge.test.ts +56 -0
- package/src/tempo/client/Charge.ts +20 -2
- package/src/tempo/internal/auto-swap.test.ts +68 -1
- package/src/tempo/internal/auto-swap.ts +38 -5
- package/src/tempo/internal/fee-payer.test.ts +106 -0
- package/src/tempo/internal/fee-payer.ts +71 -1
- package/src/tempo/internal/fee-token.ts +1 -1
- package/src/tempo/server/Charge.test.ts +31 -16
- package/src/tempo/server/internal/html/package.json +2 -2
- package/src/tempo/server/internal/html.gen.ts +1 -1
- package/src/tempo/session/client/SessionManager.test.ts +57 -4
- package/src/tempo/session/client/SessionManager.ts +50 -6
- package/src/x402/Header.ts +45 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// Generated — do not edit.
|
|
2
|
-
export const html = "<script>(function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e=>{Object.defineProperty(e,\"__esModule\",{value:!0});function t(e){\"@babel/helpers - typeof\";return t=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},t(e)}var n=`dahlia`,r=function(e){return e===3?`v3`:e},i=`https://js.stripe.com`,a=`${i}/${n}/stripe.js`,o=/^https:\\/\\/js\\.stripe\\.com\\/v3\\/?(\\?.*)?$/,s=/^https:\\/\\/js\\.stripe\\.com\\/(v3|[a-z]+)\\/stripe\\.js(\\?.*)?$/,c=`loadStripe.setLoadParameters was called but an existing Stripe.js script already exists in the document; existing script parameters will be used`,l=function(e){return o.test(e)||s.test(e)},u=function(){for(var e=document.querySelectorAll(`script[src^=\"${i}\"]`),t=0;t<e.length;t++){var n=e[t];if(l(n.src))return n}return null},d=function(e){var t=e&&!e.advancedFraudSignals?`?advancedFraudSignals=false`:``,n=document.createElement(`script`);n.src=`${a}${t}`;var r=document.head||document.body;if(!r)throw Error(`Expected document.body not to be null. Stripe.js requires a <body> element.`);return r.appendChild(n),n},f=function(e,t){!e||!e._registerWrapper||e._registerWrapper({name:`stripe-js`,version:`9.8.0`,startTime:t})},p=null,m=null,h=null,ee=function(e){return function(t){e(Error(`Failed to load Stripe.js`,{cause:t}))}},g=function(e,t){return function(){window.Stripe?e(window.Stripe):t(Error(`Stripe.js not available`))}},_=function(e){return p===null?(p=new Promise(function(t,n){if(typeof window>`u`||typeof document>`u`){t(null);return}if(window.Stripe&&e&&console.warn(c),window.Stripe){t(window.Stripe);return}try{var r=u();if(r&&e)console.warn(c);else if(!r)r=d(e);else if(r&&h!==null&&m!==null){var i;r.removeEventListener(`load`,h),r.removeEventListener(`error`,m),(i=r.parentNode)==null||i.removeChild(r),r=d(e)}h=g(t,n),m=ee(n),r.addEventListener(`load`,h),r.addEventListener(`error`,m)}catch(e){n(e);return}}),p.catch(function(e){return p=null,Promise.reject(e)})):p},v=function(e,i,a){if(e===null)return null;var o=i[0];if(typeof o!=`string`)throw Error(`Expected publishable key to be of type string, got type ${t(o)} instead.`);var s=o.match(/^pk_test/),c=r(e.version),l=n;s&&c!==l&&console.warn(`Stripe.js@${c} was loaded on the page, but @stripe/stripe-js@9.8.0 expected Stripe.js@${l}. This may result in unexpected behavior. For more information, see https://docs.stripe.com/sdks/stripejs-versioning`);var u=e.apply(void 0,i);return f(u,a),u},y=function(e){var n=`invalid load parameters; expected object of shape\n\n {advancedFraudSignals: boolean}\n\nbut received\n\n ${JSON.stringify(e)}\n`;if(e===null||t(e)!==`object`)throw Error(n);if(Object.keys(e).length===1&&typeof e.advancedFraudSignals==`boolean`)return e;throw Error(n)},b,x=!1,S=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];x=!0;var r=Date.now();return _(b).then(function(e){return v(e,t,r)})};S.setLoadParameters=function(e){if(x&&b){var t=y(e);if(Object.keys(t).reduce(function(t,n){return t&&e[n]===b?.[n]},!0))return}if(x)throw Error(`You cannot change load parameters after calling loadStripe`);b=y(e)},e.loadStripe=S})),n=e(((e,n)=>{n.exports=t()}));function r(){return`0.1.1`}var i=class e extends Error{static setStaticOptions(t){e.prototype.docsOrigin=t.docsOrigin,e.prototype.showVersion=t.showVersion,e.prototype.version=t.version}constructor(t,n={}){let r=(()=>{if(n.cause instanceof e){if(n.cause.details)return n.cause.details;if(n.cause.shortMessage)return n.cause.shortMessage}return n.cause&&`details`in n.cause&&typeof n.cause.details==`string`?n.cause.details:n.cause?.message?n.cause.message:n.details})(),i=n.cause instanceof e&&n.cause.docsPath||n.docsPath,a=n.docsOrigin??e.prototype.docsOrigin,o=`${a}${i??``}`,s=!!(n.version??e.prototype.showVersion),c=n.version??e.prototype.version,l=[t||`An error occurred.`,...n.metaMessages?[``,...n.metaMessages]:[],...r||i||s?[``,r?`Details: ${r}`:void 0,i?`See: ${o}`:void 0,s?`Version: ${c}`:void 0]:[]].filter(e=>typeof e==`string`).join(`\n`);super(l,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,\"details\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"docs\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"docsOrigin\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"docsPath\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"shortMessage\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"showVersion\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"version\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"cause\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"name\",{enumerable:!0,configurable:!0,writable:!0,value:`BaseError`}),this.cause=n.cause,this.details=r,this.docs=o,this.docsOrigin=a,this.docsPath=i,this.shortMessage=t,this.showVersion=s,this.version=c}walk(e){return a(this,e)}};Object.defineProperty(i,\"defaultStaticOptions\",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:`https://oxlib.sh`,showVersion:!1,version:`ox@${r()}`}}),i.setStaticOptions(i.defaultStaticOptions);function a(e,t){return t?.(e)?e:e&&typeof e==`object`&&`cause`in e&&e.cause?a(e.cause,t):t?null:e}function o(e,t){if(p(e)>t)throw new m({givenSize:p(e),maxSize:t})}function s(e,t={}){let{dir:n,size:r=32}=t;if(r===0)return e;if(e.length>r)throw new h({size:e.length,targetSize:r,type:`Bytes`});let i=new Uint8Array(r);for(let t=0;t<r;t++){let a=n===`right`;i[a?t:r-t-1]=e[a?t:e.length-t-1]}return i}function c(e){if(e===null||typeof e==`boolean`||typeof e==`string`)return JSON.stringify(e);if(typeof e==`number`){if(!Number.isFinite(e))throw TypeError(`Cannot canonicalize non-finite number`);return Object.is(e,-0)?`0`:JSON.stringify(e)}if(typeof e==`bigint`)throw TypeError(`Cannot canonicalize bigint`);if(Array.isArray(e))return`[${e.map(e=>c(e)).join(`,`)}]`;if(typeof e==`object`)return`{${Object.keys(e).sort().reduce((t,n)=>{let r=e[n];return r!==void 0&&t.push(`${JSON.stringify(n)}:${c(r)}`),t},[]).join(`,`)}}`}function l(e,t){return JSON.parse(e,(e,n)=>{let r=n;return typeof r==`string`&&r.endsWith(`#__bigint`)?BigInt(r.slice(0,-9)):typeof t==`function`?t(e,r):r})}let u=new TextEncoder;function d(e,t={}){let{size:n}=t,r=u.encode(e);return typeof n==`number`?(o(r,n),f(r,n)):r}function f(e,t){return s(e,{dir:`right`,size:t})}function p(e){return e.length}var m=class extends i{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \\`${t}\\` bytes. Given size: \\`${e}\\` bytes.`),Object.defineProperty(this,\"name\",{enumerable:!0,configurable:!0,writable:!0,value:`Bytes.SizeOverflowError`})}},h=class extends i{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\\`${e}\\`) exceeds padding size (\\`${t}\\`).`),Object.defineProperty(this,\"name\",{enumerable:!0,configurable:!0,writable:!0,value:`Bytes.SizeExceedsPaddingSizeError`})}};let ee=new TextDecoder,g=Object.fromEntries(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`).map((e,t)=>[t,e.charCodeAt(0)]));({...Object.fromEntries(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`).map((e,t)=>[e.charCodeAt(0),t]))});function _(e,t={}){let{pad:n=!0,url:r=!1}=t,i=new Uint8Array(Math.ceil(e.length/3)*4);for(let t=0,n=0;n<e.length;t+=4,n+=3){let r=(e[n]<<16)+(e[n+1]<<8)+(e[n+2]|0);i[t]=g[r>>18],i[t+1]=g[r>>12&63],i[t+2]=g[r>>6&63],i[t+3]=g[r&63]}let a=e.length%3,o=Math.floor(e.length/3)*4+(a&&a+1),s=ee.decode(new Uint8Array(i.buffer,0,o));return n&&a===1&&(s+=`==`),n&&a===2&&(s+=`=`),r&&(s=s.replaceAll(`+`,`-`).replaceAll(`/`,`_`)),s}function v(e,t={}){return _(d(e),t)}let y={payment:`Payment`};function b(e){return v(c(e),{pad:!1,url:!0})}var x;function S(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,\"_zod\",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,\"name\",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,\"init\",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,\"name\",{value:e}),o}var C=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},te=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(x=globalThis).__zod_globalConfig??(x.__zod_globalConfig={});let w=globalThis.__zod_globalConfig;function T(e){return e&&Object.assign(w,e),w}function ne(e,t){return typeof t==`bigint`?t.toString():t}function re(e){return{get value(){{let t=e();return Object.defineProperty(this,\"value\",{value:t}),t}throw Error(`cached value already set`)}}}function ie(e){return e==null}function ae(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}let E=Symbol(`evaluating`);function D(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==E)return r===void 0&&(r=E,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}let O=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function k(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function oe(e){if(k(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return!(k(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function se(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function A(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error(\"Cannot specify both `message` and `error` params\");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function ce(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}-Number.MAX_VALUE,Number.MAX_VALUE;function j(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function le(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function M(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function N(e){return typeof e==`string`?e:e?.message}function P(e,t,n){let r=e.message?e.message:N(e.inst?._zod.def?.error?.(e))??N(t?.error?.(e))??N(n.customError?.(e))??N(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function ue(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}let de=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,\"_zod\",{value:e._zod,enumerable:!1}),Object.defineProperty(e,\"issues\",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ne,2),Object.defineProperty(e,\"toString\",{value:()=>e.message,enumerable:!1})},fe=S(`$ZodError`,de),F=S(`$ZodError`,de,{Parent:Error}),pe=(e=>(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new C;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>P(e,a,T())));throw O(t,i?.callee),t}return o.value})(F),me=(e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>P(e,a,T())));throw O(t,i?.callee),t}return o.value})(F),he=(e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new C;return a.issues.length?{success:!1,error:new(e??fe)(a.issues.map(e=>P(e,i,T())))}:{success:!0,data:a.value}})(F),ge=(e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>P(e,i,T())))}:{success:!0,data:a.value}})(F),_e=e=>{let t=e?`[\\\\s\\\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\\\s\\\\S]*`;return RegExp(`^${t}$`)},ve=/^-?\\d+(?:\\.\\d+)?$/,I=S(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),ye=S(`$ZodCheckMinLength`,(e,t)=>{var n;I.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!ie(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=ue(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),be=S(`$ZodCheckStringFormat`,(e,t)=>{var n,r;I.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),xe=S(`$ZodCheckRegex`,(e,t)=>{be.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Se={major:4,minor:4,patch:3},L=S(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Se;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=j(e),i;for(let a of t){if(a._zod.def.when){if(le(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new C;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=j(e,t))});else{if(e.issues.length===t)continue;r||=j(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(j(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new C;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new C;return o.then(e=>t(e,r,a))}return t(o,r,a)}}D(e,`~standard`,()=>({validate:t=>{try{let n=he(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return ge(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),Ce=S(`$ZodString`,(e,t)=>{L.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??_e(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),we=S(`$ZodNumber`,(e,t)=>{L.init(e,t),e._zod.pattern=e._zod.bag.pattern??ve,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}});function R(e,t,n){e.issues.length&&t.issues.push(...M(n,e.issues)),t.value[n]=e.value}let Te=S(`$ZodArray`,(e,t)=>{L.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>R(t,n,e))):R(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function z(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...M(n,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function Ee(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key \"${n}\": expected a Zod schema`);let n=ce(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function De(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>z(e,n,i,t,u,d))):z(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}let Oe=S(`$ZodObject`,(e,t)=>{if(L.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,\"shape\",{get:()=>{let n={...e};return Object.defineProperty(t,\"shape\",{value:n}),n}})}let n=re(()=>Ee(t));D(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=k,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>z(n,t,e,s,r,i))):z(a,t,e,s,r,i)}return i?De(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),ke=S(`$ZodRecord`,(e,t)=>{L.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!oe(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[],o=t.keyType._zod.values;if(o){n.value={};let s=new Set;for(let c of o)if(typeof c==`string`||typeof c==`number`||typeof c==`symbol`){s.add(typeof c==`number`?c.toString():c);let o=t.keyType._zod.run({value:c,issues:[]},r);if(o instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(o.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:o.issues.map(e=>P(e,r,T())),input:c,path:[c],inst:e});continue}let l=o.value,u=t.valueType._zod.run({value:i[c],issues:[]},r);u instanceof Promise?a.push(u.then(e=>{e.issues.length&&n.issues.push(...M(c,e.issues)),n.value[l]=e.value})):(u.issues.length&&n.issues.push(...M(c,u.issues)),n.value[l]=u.value)}let c;for(let e in i)s.has(e)||(c??=[],c.push(e));c&&c.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:c})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof o==`string`&&ve.test(o)&&s.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(s=e)}if(s.issues.length){t.mode===`loose`?n.value[o]=i[o]:n.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>P(e,r,T())),input:o,path:[o],inst:e});continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...M(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...M(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),Ae=S(`$ZodTransform`,(e,t)=>{L.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new te(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new C;return n.value=i,n.fallback=!0,n}});function B(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}let je=S(`$ZodOptional`,(e,t)=>{L.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,D(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),D(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${ae(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>B(e,r)):B(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),Me=S(`$ZodPipe`,(e,t)=>{L.init(e,t),D(e._zod,`values`,()=>t.in._zod.values),D(e._zod,`optin`,()=>t.in._zod.optin),D(e._zod,`optout`,()=>t.out._zod.optout),D(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>V(e,t.in,n)):V(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>V(e,t.out,n)):V(r,t.out,n)}});function V(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}function Ne(e,t){return new e({type:`string`,...A(t)})}function Pe(e,t){return new e({type:`number`,checks:[],...A(t)})}function Fe(e,t){return new ye({check:`min_length`,...A(t),minimum:e})}function Ie(e,t){return new xe({check:`string_format`,format:`regex`,...A(t),pattern:e})}let H=S(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);L.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>pe(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>he(e,t,n),e.parseAsync=async(t,n)=>me(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>ge(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>se(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),Le=S(`ZodMiniString`,(e,t)=>{Ce.init(e,t),H.init(e,t)});function U(e){return Ne(Le,e)}let Re=S(`ZodMiniNumber`,(e,t)=>{we.init(e,t),H.init(e,t)});function ze(e){return Pe(Re,e)}let Be=S(`ZodMiniArray`,(e,t)=>{Te.init(e,t),H.init(e,t)});function Ve(e,t){return new Be({type:`array`,element:e,...A(t)})}let He=S(`ZodMiniObject`,(e,t)=>{Oe.init(e,t),H.init(e,t),D(e,`shape`,()=>t.shape)});function W(e,t){return new He({type:`object`,shape:e??{},...A(t)})}let G=S(`ZodMiniRecord`,(e,t)=>{ke.init(e,t),H.init(e,t)});function Ue(e,t,n){return!t||!t._zod?new G({type:`record`,keyType:U(),valueType:e,...A(t)}):new G({type:`record`,keyType:e,valueType:t,...A(n)})}let We=S(`ZodMiniTransform`,(e,t)=>{Ae.init(e,t),H.init(e,t)});function Ge(e){return new We({type:`transform`,transform:e})}let Ke=S(`ZodMiniOptional`,(e,t)=>{je.init(e,t),H.init(e,t)});function K(e){return new Ke({type:`optional`,innerType:e})}let qe=S(`ZodMiniPipe`,(e,t)=>{Me.init(e,t),H.init(e,t)});function Je(e,t){return new qe({type:`pipe`,in:e,out:t})}function Ye(){return U().check(Ie(/^\\d+(\\.\\d+)?$/,`Invalid amount`))}function Xe(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:b(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:b(r)},payload:e.payload,...e.source&&{source:e.source}},s=v(JSON.stringify(o),{pad:!1,url:!0});return`${y.payment} ${s}`}function Ze(e){return e}function Qe(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}let q=`2.52.2`,J={getDocsUrl:({docsBaseUrl:e,docsPath:t=``,docsSlug:n})=>t?`${e??`https://viem.sh`}${t}${n?`#${n}`:``}`:void 0,version:`viem@${q}`};var $e=class e extends Error{constructor(t,n={}){let r=n.cause instanceof e?n.cause.details:n.cause?.message?n.cause.message:n.details,i=n.cause instanceof e&&n.cause.docsPath||n.docsPath,a=J.getDocsUrl?.({...n,docsPath:i}),o=[t||`An error occurred.`,``,...n.metaMessages?[...n.metaMessages,``]:[],...a?[`Docs: ${a}`]:[],...r?[`Details: ${r}`]:[],...J.version?[`Version: ${J.version}`]:[]].join(`\n`);super(o,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,\"details\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"docsPath\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"metaMessages\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"shortMessage\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"version\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"name\",{enumerable:!0,configurable:!0,writable:!0,value:`BaseError`}),this.details=r,this.docsPath=i,this.metaMessages=n.metaMessages,this.name=n.name??this.name,this.shortMessage=t,this.version=q}walk(e){return et(this,e)}};function et(e,t){return t?.(e)?e:e&&typeof e==`object`&&`cause`in e&&e.cause!==void 0?et(e.cause,t):t?null:e}var tt=class extends $e{constructor({value:e}){super(`Number \\`${e}\\` is not a valid decimal number.`,{name:`InvalidDecimalNumberError`})}};function nt(e,t){if(!/^(-?)([0-9]*)\\.?([0-9]*)$/.test(e))throw new tt({value:e});let[n,r=`0`]=e.split(`.`),i=n.startsWith(`-`);if(i&&(n=n.slice(1)),r=r.replace(/(0+)$/,``),t===0)Math.round(Number(`.${r}`))===1&&(n=`${BigInt(n)+1n}`),r=``;else if(r.length>t){let[e,i,a]=[r.slice(0,t-1),r.slice(t-1,t),r.slice(t)],o=Math.round(Number(`${i}.${a}`));r=o>9?`${BigInt(e)+BigInt(1)}0`.padStart(e.length+1,`0`):`${e}${o}`,r.length>t&&(r=r.slice(1),n=`${BigInt(n)+1n}`),r=r.slice(0,t)}else r=r.padEnd(t,`0`);return BigInt(`${i?`-`:``}${n}${r}`)}let rt=Ze({name:`stripe`,intent:`charge`,schema:{credential:{payload:W({externalId:K(U()),spt:U()})},request:Je(W({amount:Ye(),currency:U(),decimals:ze(),description:K(U()),externalId:K(U()),metadata:K(Ue(U(),U())),networkId:U(),paymentMethodTypes:Ve(U()).check(Fe(1)),recipient:K(U())}),Ge(({amount:e,decimals:t,metadata:n,networkId:r,paymentMethodTypes:i,...a})=>({...a,amount:nt(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:i,...n!==void 0&&{metadata:n}}})))}});function it(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return Qe(rt,{context:W({paymentMethod:K(U())}),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=await n({amount:s,challenge:e,client:t,currency:c,expiresAt:e.expires?Math.floor(new Date(e.expires).getTime()/1e3):Math.floor(Date.now()/1e3)+3600,metadata:d,networkId:u,paymentMethod:o}),p=l??r;return Xe({challenge:e,payload:{spt:f,...p===void 0?{}:{externalId:p}}})}})}function at(e){return[it(e)]}(function(e){e.charge=it})(at||={});var ot=n();let Y={data:`__MPPX_DATA__`,error:`root_error`,root:`root`},st={serviceWorker:`__mppx_worker`,tab:`__mppx_tab`},X={challengeId:`data-mppx-challenge-id`,remaining:`data-remaining`};var Z=class{name;constructor(e){this.name=`--mppx-${e}`}toString(){return`var(${this.name})`}};let ct={accent:new Z(`accent`),background:new Z(`background`),border:new Z(`border`),foreground:new Z(`foreground`),muted:new Z(`muted`),negative:new Z(`negative`),positive:new Z(`positive`),surface:new Z(`surface`),fontFamily:new Z(`font-family`),fontSizeBase:new Z(`font-size-base`),radius:new Z(`radius`),spacingUnit:new Z(`spacing-unit`)};String.raw`<style>\n *,\n ::after,\n ::before,\n ::backdrop,\n ::file-selector-button {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n border: 0 solid;\n border-color: ${ct.border};\n }\n html,\n :host {\n line-height: 1.5;\n -webkit-text-size-adjust: 100%;\n tab-size: 4;\n -webkit-tap-highlight-color: transparent;\n }\n h1,\n h2,\n h3,\n h4,\n h5,\n h6 {\n font-size: inherit;\n font-weight: inherit;\n }\n a {\n color: inherit;\n -webkit-text-decoration: inherit;\n text-decoration: inherit;\n }\n b,\n strong {\n font-weight: bolder;\n }\n code,\n kbd,\n samp,\n pre {\n font-family:\n ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New',\n monospace;\n font-size: 1em;\n }\n small {\n font-size: 80%;\n }\n ol,\n ul,\n menu {\n list-style: none;\n }\n img,\n svg,\n video,\n canvas,\n audio,\n iframe,\n embed,\n object {\n display: block;\n vertical-align: middle;\n }\n img,\n video {\n max-width: 100%;\n height: auto;\n }\n button,\n input,\n select,\n optgroup,\n textarea,\n ::file-selector-button {\n font: inherit;\n font-feature-settings: inherit;\n font-variation-settings: inherit;\n letter-spacing: inherit;\n color: inherit;\n border-radius: 0;\n background-color: transparent;\n opacity: 1;\n }\n ::file-selector-button {\n margin-inline-end: 4px;\n }\n ::placeholder {\n opacity: 1;\n }\n @supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) {\n ::placeholder {\n color: color-mix(in oklab, currentcolor 50%, transparent);\n }\n }\n textarea {\n resize: vertical;\n }\n ::-webkit-search-decoration {\n -webkit-appearance: none;\n }\n :-moz-ui-invalid {\n box-shadow: none;\n }\n button,\n input:where([type='button'], [type='reset'], [type='submit']),\n ::file-selector-button {\n appearance: button;\n }\n ::-webkit-inner-spin-button,\n ::-webkit-outer-spin-button {\n height: auto;\n }\n [hidden]:where(:not([hidden='until-found'])) {\n display: none !important;\n }\n</style>`;function lt(e,t){if(t==null)return e;if(!Q(e)||!Q(t))return t??e;let n={...e};for(let[e,r]of Object.entries(t)){if(r==null||r===``)continue;let t=n[e];n[e]=Q(t)&&Q(r)?lt(t,r):r}return n}function Q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function ut(e){let t=new URL(location.href);t.searchParams.set(st.serviceWorker,``);let n=await navigator.serviceWorker.register(t.pathname+t.search),r=await new Promise(e=>{let t=n.installing??n.waiting??n.active;if(t?.state===`activated`)return e(t);let r=t??n;r.addEventListener(`statechange`,function t(){let i=n.active;i?.state===`activated`&&(r.removeEventListener(`statechange`,t),e(i))})});await new Promise(t=>{let n=new MessageChannel;n.port1.onmessage=()=>t(),r.postMessage({credential:e},[n.port2])}),location.reload()}function dt(e){let t=document.getElementById(Y.data),n=l(t.textContent),r=t.getAttribute(X.remaining);!r||Number(r)<=1?t.remove():t.setAttribute(X.remaining,String(Number(r)-1));let i=document.currentScript,a=i?.getAttribute(X.challengeId),o=a?(i.removeAttribute(X.challengeId),n[a]):Object.values(n).find(t=>t.challenge.method===e);return{...o,error(e){if(!e){document.getElementById(Y.error)?.remove();return}let t=document.getElementById(Y.error);if(t){t.textContent=e;return}let n=document.createElement(`p`);n.id=Y.error,n.className=`mppx-error`,n.role=`alert`,n.textContent=e,document.getElementById(o.rootId)?.after(n)},root:document.getElementById(o.rootId),submit:ut,vars:ct}}let $=dt(`stripe`),ft=String.raw,pt=document.createElement(`style`);pt.textContent=ft`\n form {\n display: flex;\n flex-direction: column;\n gap: calc(${$.vars.spacingUnit} * 8);\n }\n button {\n background: ${$.vars.accent};\n border-radius: ${$.vars.radius};\n color: ${$.vars.background};\n cursor: pointer;\n font-weight: 500;\n padding: calc(${$.vars.spacingUnit} * 4) calc(${$.vars.spacingUnit} * 8);\n width: 100%;\n }\n button:hover:not(:disabled) {\n opacity: 0.85;\n }\n button:disabled {\n cursor: default;\n opacity: 0.5;\n }\n`,$.root.append(pt),(async()=>{let e=await(0,ot.loadStripe)($.config.publishableKey);if(!e)throw Error(`Failed to loadStripe`);let t=window.matchMedia(`(prefers-color-scheme: dark)`),n=()=>{let e=(()=>{if($.config.elements?.options?.appearance?.theme)return $.config.elements?.options?.appearance?.theme;switch($.theme.colorScheme){case`light dark`:return t.matches?`night`:`stripe`;case`light`:return`stripe`;case`dark`:return`night`}})(),n=+!!t.matches;return lt({disableAnimations:!0,theme:e,variables:{borderRadius:$.theme.radius,colorBackground:$.theme.surface[n],colorDanger:$.theme.negative[n],colorPrimary:$.theme.accent[n],colorText:$.theme.foreground[n],colorTextSecondary:$.theme.muted[n],fontSizeBase:$.theme.fontSizeBase,fontFamily:$.theme.fontFamily,spacingUnit:$.theme.spacingUnit}},$.config.elements?.options?.appearance??{})},r=e.elements({appearance:n(),...$.config.elements?.options,amount:Number($.challenge.request.amount),currency:$.challenge.request.currency,mode:`payment`,paymentMethodCreation:`manual`,paymentMethodTypes:$.challenge.request.methodDetails.paymentMethodTypes});t.addEventListener(`change`,()=>{r.update({appearance:n()})});let i=document.createElement(`form`);r.create(`payment`,$.config.elements?.paymentOptions).mount(i),$.root.appendChild(i);let a=document.createElement(`button`);a.textContent=$.text.pay,a.type=`submit`,i.appendChild(a),i.onsubmit=async t=>{t.preventDefault(),$.error(),a.disabled=!0;try{await r.submit();let{paymentMethod:t,error:n}=await e.createPaymentMethod({...$.config.elements?.createPaymentMethodOptions,elements:r});if(n||!t)throw n??Error(`Failed to create payment method`);let i=await at({client:e,createToken:mt})[0].createCredential({challenge:$.challenge,context:{paymentMethod:t.id}});await $.submit(i)}catch(e){$.error(e instanceof Error?e.message:`Payment failed`)}finally{a.disabled=!1}}})();async function mt(e){let t=new URL($.config.createTokenUrl,location.origin);if(t.origin!==location.origin)throw Error(`createTokenUrl must be same-origin`);let n=await fetch(t,{method:`POST`,headers:{\"Content-Type\":`application/json`},body:JSON.stringify(e)});if(!n.ok){let e=await n.text().catch(()=>`<response body unavailable>`);throw Error(`Failed to create SPT (${n.status}): ${e}`)}return(await n.json()).spt}})();</script>"
|
|
2
|
+
export const html = "<script>(function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e=>{Object.defineProperty(e,\"__esModule\",{value:!0});function t(e){\"@babel/helpers - typeof\";return t=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},t(e)}var n=`dahlia`,r=function(e){return e===3?`v3`:e},i=`https://js.stripe.com`,a=`${i}/${n}/stripe.js`,o=/^https:\\/\\/js\\.stripe\\.com\\/v3\\/?(\\?.*)?$/,s=/^https:\\/\\/js\\.stripe\\.com\\/(v3|[a-z]+)\\/stripe\\.js(\\?.*)?$/,c=`loadStripe.setLoadParameters was called but an existing Stripe.js script already exists in the document; existing script parameters will be used`,l=function(e){return o.test(e)||s.test(e)},u=function(){for(var e=document.querySelectorAll(`script[src^=\"${i}\"]`),t=0;t<e.length;t++){var n=e[t];if(l(n.src))return n}return null},d=function(e){var t=e&&!e.advancedFraudSignals?`?advancedFraudSignals=false`:``,n=document.createElement(`script`);n.src=`${a}${t}`;var r=document.head||document.body;if(!r)throw Error(`Expected document.body not to be null. Stripe.js requires a <body> element.`);return r.appendChild(n),n},f=function(e,t){!e||!e._registerWrapper||e._registerWrapper({name:`stripe-js`,version:`9.8.0`,startTime:t})},p=null,m=null,h=null,ee=function(e){return function(t){e(Error(`Failed to load Stripe.js`,{cause:t}))}},g=function(e,t){return function(){window.Stripe?e(window.Stripe):t(Error(`Stripe.js not available`))}},_=function(e){return p===null?(p=new Promise(function(t,n){if(typeof window>`u`||typeof document>`u`){t(null);return}if(window.Stripe&&e&&console.warn(c),window.Stripe){t(window.Stripe);return}try{var r=u();if(r&&e)console.warn(c);else if(!r)r=d(e);else if(r&&h!==null&&m!==null){var i;r.removeEventListener(`load`,h),r.removeEventListener(`error`,m),(i=r.parentNode)==null||i.removeChild(r),r=d(e)}h=g(t,n),m=ee(n),r.addEventListener(`load`,h),r.addEventListener(`error`,m)}catch(e){n(e);return}}),p.catch(function(e){return p=null,Promise.reject(e)})):p},v=function(e,i,a){if(e===null)return null;var o=i[0];if(typeof o!=`string`)throw Error(`Expected publishable key to be of type string, got type ${t(o)} instead.`);var s=o.match(/^pk_test/),c=r(e.version),l=n;s&&c!==l&&console.warn(`Stripe.js@${c} was loaded on the page, but @stripe/stripe-js@9.8.0 expected Stripe.js@${l}. This may result in unexpected behavior. For more information, see https://docs.stripe.com/sdks/stripejs-versioning`);var u=e.apply(void 0,i);return f(u,a),u},y=function(e){var n=`invalid load parameters; expected object of shape\n\n {advancedFraudSignals: boolean}\n\nbut received\n\n ${JSON.stringify(e)}\n`;if(e===null||t(e)!==`object`)throw Error(n);if(Object.keys(e).length===1&&typeof e.advancedFraudSignals==`boolean`)return e;throw Error(n)},b,x=!1,S=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];x=!0;var r=Date.now();return _(b).then(function(e){return v(e,t,r)})};S.setLoadParameters=function(e){if(x&&b){var t=y(e);if(Object.keys(t).reduce(function(t,n){return t&&e[n]===b?.[n]},!0))return}if(x)throw Error(`You cannot change load parameters after calling loadStripe`);b=y(e)},e.loadStripe=S})),n=e(((e,n)=>{n.exports=t()}));function r(){return`0.1.1`}var i=class e extends Error{static setStaticOptions(t){e.prototype.docsOrigin=t.docsOrigin,e.prototype.showVersion=t.showVersion,e.prototype.version=t.version}constructor(t,n={}){let r=(()=>{if(n.cause instanceof e){if(n.cause.details)return n.cause.details;if(n.cause.shortMessage)return n.cause.shortMessage}return n.cause&&`details`in n.cause&&typeof n.cause.details==`string`?n.cause.details:n.cause?.message?n.cause.message:n.details})(),i=n.cause instanceof e&&n.cause.docsPath||n.docsPath,a=n.docsOrigin??e.prototype.docsOrigin,o=`${a}${i??``}`,s=!!(n.version??e.prototype.showVersion),c=n.version??e.prototype.version,l=[t||`An error occurred.`,...n.metaMessages?[``,...n.metaMessages]:[],...r||i||s?[``,r?`Details: ${r}`:void 0,i?`See: ${o}`:void 0,s?`Version: ${c}`:void 0]:[]].filter(e=>typeof e==`string`).join(`\n`);super(l,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,\"details\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"docs\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"docsOrigin\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"docsPath\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"shortMessage\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"showVersion\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"version\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"cause\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"name\",{enumerable:!0,configurable:!0,writable:!0,value:`BaseError`}),this.cause=n.cause,this.details=r,this.docs=o,this.docsOrigin=a,this.docsPath=i,this.shortMessage=t,this.showVersion=s,this.version=c}walk(e){return a(this,e)}};Object.defineProperty(i,\"defaultStaticOptions\",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:`https://oxlib.sh`,showVersion:!1,version:`ox@${r()}`}}),i.setStaticOptions(i.defaultStaticOptions);function a(e,t){return t?.(e)?e:e&&typeof e==`object`&&`cause`in e&&e.cause?a(e.cause,t):t?null:e}function o(e,t){if(p(e)>t)throw new m({givenSize:p(e),maxSize:t})}function s(e,t={}){let{dir:n,size:r=32}=t;if(r===0)return e;if(e.length>r)throw new h({size:e.length,targetSize:r,type:`Bytes`});let i=new Uint8Array(r);for(let t=0;t<r;t++){let a=n===`right`;i[a?t:r-t-1]=e[a?t:e.length-t-1]}return i}function c(e){if(e===null||typeof e==`boolean`||typeof e==`string`)return JSON.stringify(e);if(typeof e==`number`){if(!Number.isFinite(e))throw TypeError(`Cannot canonicalize non-finite number`);return Object.is(e,-0)?`0`:JSON.stringify(e)}if(typeof e==`bigint`)throw TypeError(`Cannot canonicalize bigint`);if(Array.isArray(e))return`[${e.map(e=>c(e)).join(`,`)}]`;if(typeof e==`object`)return`{${Object.keys(e).sort().reduce((t,n)=>{let r=e[n];return r!==void 0&&t.push(`${JSON.stringify(n)}:${c(r)}`),t},[]).join(`,`)}}`}function l(e,t){return JSON.parse(e,(e,n)=>{let r=n;return typeof r==`string`&&r.endsWith(`#__bigint`)?BigInt(r.slice(0,-9)):typeof t==`function`?t(e,r):r})}let u=new TextEncoder;function d(e,t={}){let{size:n}=t,r=u.encode(e);return typeof n==`number`?(o(r,n),f(r,n)):r}function f(e,t){return s(e,{dir:`right`,size:t})}function p(e){return e.length}var m=class extends i{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \\`${t}\\` bytes. Given size: \\`${e}\\` bytes.`),Object.defineProperty(this,\"name\",{enumerable:!0,configurable:!0,writable:!0,value:`Bytes.SizeOverflowError`})}},h=class extends i{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\\`${e}\\`) exceeds padding size (\\`${t}\\`).`),Object.defineProperty(this,\"name\",{enumerable:!0,configurable:!0,writable:!0,value:`Bytes.SizeExceedsPaddingSizeError`})}};let ee=new TextDecoder,g=Object.fromEntries(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`).map((e,t)=>[t,e.charCodeAt(0)]));({...Object.fromEntries(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`).map((e,t)=>[e.charCodeAt(0),t]))});function _(e,t={}){let{pad:n=!0,url:r=!1}=t,i=new Uint8Array(Math.ceil(e.length/3)*4);for(let t=0,n=0;n<e.length;t+=4,n+=3){let r=(e[n]<<16)+(e[n+1]<<8)+(e[n+2]|0);i[t]=g[r>>18],i[t+1]=g[r>>12&63],i[t+2]=g[r>>6&63],i[t+3]=g[r&63]}let a=e.length%3,o=Math.floor(e.length/3)*4+(a&&a+1),s=ee.decode(new Uint8Array(i.buffer,0,o));return n&&a===1&&(s+=`==`),n&&a===2&&(s+=`=`),r&&(s=s.replaceAll(`+`,`-`).replaceAll(`/`,`_`)),s}function v(e,t={}){return _(d(e),t)}let y={payment:`Payment`};function b(e){return v(c(e),{pad:!1,url:!0})}var x;function S(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,\"_zod\",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,\"name\",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,\"init\",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,\"name\",{value:e}),o}var C=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},te=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(x=globalThis).__zod_globalConfig??(x.__zod_globalConfig={});let w=globalThis.__zod_globalConfig;function T(e){return e&&Object.assign(w,e),w}function ne(e,t){return typeof t==`bigint`?t.toString():t}function re(e){return{get value(){{let t=e();return Object.defineProperty(this,\"value\",{value:t}),t}throw Error(`cached value already set`)}}}function ie(e){return e==null}function ae(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}let E=Symbol(`evaluating`);function D(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==E)return r===void 0&&(r=E,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}let O=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function k(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function oe(e){if(k(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return!(k(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function se(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function A(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error(\"Cannot specify both `message` and `error` params\");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function ce(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}-Number.MAX_VALUE,Number.MAX_VALUE;function j(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function le(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function M(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function N(e){return typeof e==`string`?e:e?.message}function P(e,t,n){let r=e.message?e.message:N(e.inst?._zod.def?.error?.(e))??N(t?.error?.(e))??N(n.customError?.(e))??N(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function ue(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}let de=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,\"_zod\",{value:e._zod,enumerable:!1}),Object.defineProperty(e,\"issues\",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ne,2),Object.defineProperty(e,\"toString\",{value:()=>e.message,enumerable:!1})},fe=S(`$ZodError`,de),F=S(`$ZodError`,de,{Parent:Error}),pe=(e=>(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new C;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>P(e,a,T())));throw O(t,i?.callee),t}return o.value})(F),me=(e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>P(e,a,T())));throw O(t,i?.callee),t}return o.value})(F),he=(e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new C;return a.issues.length?{success:!1,error:new(e??fe)(a.issues.map(e=>P(e,i,T())))}:{success:!0,data:a.value}})(F),ge=(e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>P(e,i,T())))}:{success:!0,data:a.value}})(F),_e=e=>{let t=e?`[\\\\s\\\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\\\s\\\\S]*`;return RegExp(`^${t}$`)},ve=/^-?\\d+(?:\\.\\d+)?$/,I=S(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),ye=S(`$ZodCheckMinLength`,(e,t)=>{var n;I.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!ie(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=ue(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),be=S(`$ZodCheckStringFormat`,(e,t)=>{var n,r;I.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),xe=S(`$ZodCheckRegex`,(e,t)=>{be.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Se={major:4,minor:4,patch:3},L=S(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Se;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=j(e),i;for(let a of t){if(a._zod.def.when){if(le(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new C;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=j(e,t))});else{if(e.issues.length===t)continue;r||=j(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(j(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new C;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new C;return o.then(e=>t(e,r,a))}return t(o,r,a)}}D(e,`~standard`,()=>({validate:t=>{try{let n=he(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return ge(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),Ce=S(`$ZodString`,(e,t)=>{L.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??_e(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),we=S(`$ZodNumber`,(e,t)=>{L.init(e,t),e._zod.pattern=e._zod.bag.pattern??ve,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}});function R(e,t,n){e.issues.length&&t.issues.push(...M(n,e.issues)),t.value[n]=e.value}let Te=S(`$ZodArray`,(e,t)=>{L.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>R(t,n,e))):R(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function z(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...M(n,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function Ee(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key \"${n}\": expected a Zod schema`);let n=ce(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function De(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>z(e,n,i,t,u,d))):z(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}let Oe=S(`$ZodObject`,(e,t)=>{if(L.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,\"shape\",{get:()=>{let n={...e};return Object.defineProperty(t,\"shape\",{value:n}),n}})}let n=re(()=>Ee(t));D(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=k,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>z(n,t,e,s,r,i))):z(a,t,e,s,r,i)}return i?De(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),ke=S(`$ZodRecord`,(e,t)=>{L.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!oe(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[],o=t.keyType._zod.values;if(o){n.value={};let s=new Set;for(let c of o)if(typeof c==`string`||typeof c==`number`||typeof c==`symbol`){s.add(typeof c==`number`?c.toString():c);let o=t.keyType._zod.run({value:c,issues:[]},r);if(o instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(o.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:o.issues.map(e=>P(e,r,T())),input:c,path:[c],inst:e});continue}let l=o.value,u=t.valueType._zod.run({value:i[c],issues:[]},r);u instanceof Promise?a.push(u.then(e=>{e.issues.length&&n.issues.push(...M(c,e.issues)),n.value[l]=e.value})):(u.issues.length&&n.issues.push(...M(c,u.issues)),n.value[l]=u.value)}let c;for(let e in i)s.has(e)||(c??=[],c.push(e));c&&c.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:c})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof o==`string`&&ve.test(o)&&s.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(s=e)}if(s.issues.length){t.mode===`loose`?n.value[o]=i[o]:n.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>P(e,r,T())),input:o,path:[o],inst:e});continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...M(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...M(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),Ae=S(`$ZodTransform`,(e,t)=>{L.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new te(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new C;return n.value=i,n.fallback=!0,n}});function B(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}let je=S(`$ZodOptional`,(e,t)=>{L.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,D(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),D(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${ae(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>B(e,r)):B(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),Me=S(`$ZodPipe`,(e,t)=>{L.init(e,t),D(e._zod,`values`,()=>t.in._zod.values),D(e._zod,`optin`,()=>t.in._zod.optin),D(e._zod,`optout`,()=>t.out._zod.optout),D(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>V(e,t.in,n)):V(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>V(e,t.out,n)):V(r,t.out,n)}});function V(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}function Ne(e,t){return new e({type:`string`,...A(t)})}function Pe(e,t){return new e({type:`number`,checks:[],...A(t)})}function Fe(e,t){return new ye({check:`min_length`,...A(t),minimum:e})}function Ie(e,t){return new xe({check:`string_format`,format:`regex`,...A(t),pattern:e})}let H=S(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);L.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>pe(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>he(e,t,n),e.parseAsync=async(t,n)=>me(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>ge(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>se(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),Le=S(`ZodMiniString`,(e,t)=>{Ce.init(e,t),H.init(e,t)});function U(e){return Ne(Le,e)}let Re=S(`ZodMiniNumber`,(e,t)=>{we.init(e,t),H.init(e,t)});function ze(e){return Pe(Re,e)}let Be=S(`ZodMiniArray`,(e,t)=>{Te.init(e,t),H.init(e,t)});function Ve(e,t){return new Be({type:`array`,element:e,...A(t)})}let He=S(`ZodMiniObject`,(e,t)=>{Oe.init(e,t),H.init(e,t),D(e,`shape`,()=>t.shape)});function W(e,t){return new He({type:`object`,shape:e??{},...A(t)})}let G=S(`ZodMiniRecord`,(e,t)=>{ke.init(e,t),H.init(e,t)});function Ue(e,t,n){return!t||!t._zod?new G({type:`record`,keyType:U(),valueType:e,...A(t)}):new G({type:`record`,keyType:e,valueType:t,...A(n)})}let We=S(`ZodMiniTransform`,(e,t)=>{Ae.init(e,t),H.init(e,t)});function Ge(e){return new We({type:`transform`,transform:e})}let Ke=S(`ZodMiniOptional`,(e,t)=>{je.init(e,t),H.init(e,t)});function K(e){return new Ke({type:`optional`,innerType:e})}let qe=S(`ZodMiniPipe`,(e,t)=>{Me.init(e,t),H.init(e,t)});function Je(e,t){return new qe({type:`pipe`,in:e,out:t})}function Ye(){return U().check(Ie(/^\\d+(\\.\\d+)?$/,`Invalid amount`))}function Xe(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:b(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:b(r)},payload:e.payload,...e.source&&{source:e.source}},s=v(JSON.stringify(o),{pad:!1,url:!0});return`${y.payment} ${s}`}function Ze(e){return e}function Qe(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}let q=`2.54.1`,J={getDocsUrl:({docsBaseUrl:e,docsPath:t=``,docsSlug:n})=>t?`${e??`https://viem.sh`}${t}${n?`#${n}`:``}`:void 0,version:`viem@${q}`};var $e=class e extends Error{constructor(t,n={}){let r=n.cause instanceof e?n.cause.details:n.cause?.message?n.cause.message:n.details,i=n.cause instanceof e&&n.cause.docsPath||n.docsPath,a=J.getDocsUrl?.({...n,docsPath:i}),o=[t||`An error occurred.`,``,...n.metaMessages?[...n.metaMessages,``]:[],...a?[`Docs: ${a}`]:[],...r?[`Details: ${r}`]:[],...J.version?[`Version: ${J.version}`]:[]].join(`\n`);super(o,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,\"details\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"docsPath\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"metaMessages\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"shortMessage\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"version\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,\"name\",{enumerable:!0,configurable:!0,writable:!0,value:`BaseError`}),this.details=r,this.docsPath=i,this.metaMessages=n.metaMessages,this.name=n.name??this.name,this.shortMessage=t,this.version=q}walk(e){return et(this,e)}};function et(e,t){return t?.(e)?e:e&&typeof e==`object`&&`cause`in e&&e.cause!==void 0?et(e.cause,t):t?null:e}var tt=class extends $e{constructor({value:e}){super(`Number \\`${e}\\` is not a valid decimal number.`,{name:`InvalidDecimalNumberError`})}};function nt(e,t){if(!/^(-?)([0-9]*)\\.?([0-9]*)$/.test(e))throw new tt({value:e});let[n,r=`0`]=e.split(`.`),i=n.startsWith(`-`);if(i&&(n=n.slice(1)),r=r.replace(/(0+)$/,``),t===0)Math.round(Number(`.${r}`))===1&&(n=`${BigInt(n)+1n}`),r=``;else if(r.length>t){let[e,i,a]=[r.slice(0,t-1),r.slice(t-1,t),r.slice(t)],o=Math.round(Number(`${i}.${a}`));r=o>9?`${BigInt(e)+BigInt(1)}0`.padStart(e.length+1,`0`):`${e}${o}`,r.length>t&&(r=r.slice(1),n=`${BigInt(n)+1n}`),r=r.slice(0,t)}else r=r.padEnd(t,`0`);return BigInt(`${i?`-`:``}${n}${r}`)}let rt=Ze({name:`stripe`,intent:`charge`,schema:{credential:{payload:W({externalId:K(U()),spt:U()})},request:Je(W({amount:Ye(),currency:U(),decimals:ze(),description:K(U()),externalId:K(U()),metadata:K(Ue(U(),U())),networkId:U(),paymentMethodTypes:Ve(U()).check(Fe(1)),recipient:K(U())}),Ge(({amount:e,decimals:t,metadata:n,networkId:r,paymentMethodTypes:i,...a})=>({...a,amount:nt(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:i,...n!==void 0&&{metadata:n}}})))}});function it(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return Qe(rt,{context:W({paymentMethod:K(U())}),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=await n({amount:s,challenge:e,client:t,currency:c,expiresAt:e.expires?Math.floor(new Date(e.expires).getTime()/1e3):Math.floor(Date.now()/1e3)+3600,metadata:d,networkId:u,paymentMethod:o}),p=l??r;return Xe({challenge:e,payload:{spt:f,...p===void 0?{}:{externalId:p}}})}})}function at(e){return[it(e)]}(function(e){e.charge=it})(at||={});var ot=n();let Y={data:`__MPPX_DATA__`,error:`root_error`,root:`root`},st={serviceWorker:`__mppx_worker`,tab:`__mppx_tab`},X={challengeId:`data-mppx-challenge-id`,remaining:`data-remaining`};var Z=class{name;constructor(e){this.name=`--mppx-${e}`}toString(){return`var(${this.name})`}};let ct={accent:new Z(`accent`),background:new Z(`background`),border:new Z(`border`),foreground:new Z(`foreground`),muted:new Z(`muted`),negative:new Z(`negative`),positive:new Z(`positive`),surface:new Z(`surface`),fontFamily:new Z(`font-family`),fontSizeBase:new Z(`font-size-base`),radius:new Z(`radius`),spacingUnit:new Z(`spacing-unit`)};String.raw`<style>\n *,\n ::after,\n ::before,\n ::backdrop,\n ::file-selector-button {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n border: 0 solid;\n border-color: ${ct.border};\n }\n html,\n :host {\n line-height: 1.5;\n -webkit-text-size-adjust: 100%;\n tab-size: 4;\n -webkit-tap-highlight-color: transparent;\n }\n h1,\n h2,\n h3,\n h4,\n h5,\n h6 {\n font-size: inherit;\n font-weight: inherit;\n }\n a {\n color: inherit;\n -webkit-text-decoration: inherit;\n text-decoration: inherit;\n }\n b,\n strong {\n font-weight: bolder;\n }\n code,\n kbd,\n samp,\n pre {\n font-family:\n ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New',\n monospace;\n font-size: 1em;\n }\n small {\n font-size: 80%;\n }\n ol,\n ul,\n menu {\n list-style: none;\n }\n img,\n svg,\n video,\n canvas,\n audio,\n iframe,\n embed,\n object {\n display: block;\n vertical-align: middle;\n }\n img,\n video {\n max-width: 100%;\n height: auto;\n }\n button,\n input,\n select,\n optgroup,\n textarea,\n ::file-selector-button {\n font: inherit;\n font-feature-settings: inherit;\n font-variation-settings: inherit;\n letter-spacing: inherit;\n color: inherit;\n border-radius: 0;\n background-color: transparent;\n opacity: 1;\n }\n ::file-selector-button {\n margin-inline-end: 4px;\n }\n ::placeholder {\n opacity: 1;\n }\n @supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) {\n ::placeholder {\n color: color-mix(in oklab, currentcolor 50%, transparent);\n }\n }\n textarea {\n resize: vertical;\n }\n ::-webkit-search-decoration {\n -webkit-appearance: none;\n }\n :-moz-ui-invalid {\n box-shadow: none;\n }\n button,\n input:where([type='button'], [type='reset'], [type='submit']),\n ::file-selector-button {\n appearance: button;\n }\n ::-webkit-inner-spin-button,\n ::-webkit-outer-spin-button {\n height: auto;\n }\n [hidden]:where(:not([hidden='until-found'])) {\n display: none !important;\n }\n</style>`;function lt(e,t){if(t==null)return e;if(!Q(e)||!Q(t))return t??e;let n={...e};for(let[e,r]of Object.entries(t)){if(r==null||r===``)continue;let t=n[e];n[e]=Q(t)&&Q(r)?lt(t,r):r}return n}function Q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function ut(e){let t=new URL(location.href);t.searchParams.set(st.serviceWorker,``);let n=await navigator.serviceWorker.register(t.pathname+t.search),r=await new Promise(e=>{let t=n.installing??n.waiting??n.active;if(t?.state===`activated`)return e(t);let r=t??n;r.addEventListener(`statechange`,function t(){let i=n.active;i?.state===`activated`&&(r.removeEventListener(`statechange`,t),e(i))})});await new Promise(t=>{let n=new MessageChannel;n.port1.onmessage=()=>t(),r.postMessage({credential:e},[n.port2])}),location.reload()}function dt(e){let t=document.getElementById(Y.data),n=l(t.textContent),r=t.getAttribute(X.remaining);!r||Number(r)<=1?t.remove():t.setAttribute(X.remaining,String(Number(r)-1));let i=document.currentScript,a=i?.getAttribute(X.challengeId),o=a?(i.removeAttribute(X.challengeId),n[a]):Object.values(n).find(t=>t.challenge.method===e);return{...o,error(e){if(!e){document.getElementById(Y.error)?.remove();return}let t=document.getElementById(Y.error);if(t){t.textContent=e;return}let n=document.createElement(`p`);n.id=Y.error,n.className=`mppx-error`,n.role=`alert`,n.textContent=e,document.getElementById(o.rootId)?.after(n)},root:document.getElementById(o.rootId),submit:ut,vars:ct}}let $=dt(`stripe`),ft=String.raw,pt=document.createElement(`style`);pt.textContent=ft`\n form {\n display: flex;\n flex-direction: column;\n gap: calc(${$.vars.spacingUnit} * 8);\n }\n button {\n background: ${$.vars.accent};\n border-radius: ${$.vars.radius};\n color: ${$.vars.background};\n cursor: pointer;\n font-weight: 500;\n padding: calc(${$.vars.spacingUnit} * 4) calc(${$.vars.spacingUnit} * 8);\n width: 100%;\n }\n button:hover:not(:disabled) {\n opacity: 0.85;\n }\n button:disabled {\n cursor: default;\n opacity: 0.5;\n }\n`,$.root.append(pt),(async()=>{let e=await(0,ot.loadStripe)($.config.publishableKey);if(!e)throw Error(`Failed to loadStripe`);let t=window.matchMedia(`(prefers-color-scheme: dark)`),n=()=>{let e=(()=>{if($.config.elements?.options?.appearance?.theme)return $.config.elements?.options?.appearance?.theme;switch($.theme.colorScheme){case`light dark`:return t.matches?`night`:`stripe`;case`light`:return`stripe`;case`dark`:return`night`}})(),n=+!!t.matches;return lt({disableAnimations:!0,theme:e,variables:{borderRadius:$.theme.radius,colorBackground:$.theme.surface[n],colorDanger:$.theme.negative[n],colorPrimary:$.theme.accent[n],colorText:$.theme.foreground[n],colorTextSecondary:$.theme.muted[n],fontSizeBase:$.theme.fontSizeBase,fontFamily:$.theme.fontFamily,spacingUnit:$.theme.spacingUnit}},$.config.elements?.options?.appearance??{})},r=e.elements({appearance:n(),...$.config.elements?.options,amount:Number($.challenge.request.amount),currency:$.challenge.request.currency,mode:`payment`,paymentMethodCreation:`manual`,paymentMethodTypes:$.challenge.request.methodDetails.paymentMethodTypes});t.addEventListener(`change`,()=>{r.update({appearance:n()})});let i=document.createElement(`form`);r.create(`payment`,$.config.elements?.paymentOptions).mount(i),$.root.appendChild(i);let a=document.createElement(`button`);a.textContent=$.text.pay,a.type=`submit`,i.appendChild(a),i.onsubmit=async t=>{t.preventDefault(),$.error(),a.disabled=!0;try{await r.submit();let{paymentMethod:t,error:n}=await e.createPaymentMethod({...$.config.elements?.createPaymentMethodOptions,elements:r});if(n||!t)throw n??Error(`Failed to create payment method`);let i=await at({client:e,createToken:mt})[0].createCredential({challenge:$.challenge,context:{paymentMethod:t.id}});await $.submit(i)}catch(e){$.error(e instanceof Error?e.message:`Payment failed`)}finally{a.disabled=!1}}})();async function mt(e){let t=new URL($.config.createTokenUrl,location.origin);if(t.origin!==location.origin)throw Error(`createTokenUrl must be same-origin`);let n=await fetch(t,{method:`POST`,headers:{\"Content-Type\":`application/json`},body:JSON.stringify(e)});if(!n.ok){let e=await n.text().catch(()=>`<response body unavailable>`);throw Error(`Failed to create SPT (${n.status}): ${e}`)}return(await n.json()).spt}})();</script>"
|
|
@@ -84,6 +84,62 @@ describe('tempo.charge client', () => {
|
|
|
84
84
|
expect(credential.source).toBe(`did:pkh:eip155:${chainId}:${account.address}`)
|
|
85
85
|
})
|
|
86
86
|
|
|
87
|
+
test('passes the client to viem 2.54 Tempo transfer call builders', async () => {
|
|
88
|
+
vi.resetModules()
|
|
89
|
+
const chainId = 42431
|
|
90
|
+
const transferCalls: { client: unknown; parameters: Record<string, unknown> }[] = []
|
|
91
|
+
function transferCall(client: unknown, parameters: Record<string, unknown>) {
|
|
92
|
+
transferCalls.push({ client, parameters })
|
|
93
|
+
return { data: '0x', to: parameters.token }
|
|
94
|
+
}
|
|
95
|
+
const prepareTransactionRequest = vi.fn(async () => ({}))
|
|
96
|
+
const signTransaction = vi.fn(async () => '0xdeadbeef')
|
|
97
|
+
vi.doMock('viem/actions', () => ({
|
|
98
|
+
prepareTransactionRequest,
|
|
99
|
+
sendCallsSync: vi.fn(),
|
|
100
|
+
signTransaction,
|
|
101
|
+
signTypedData: vi.fn(),
|
|
102
|
+
}))
|
|
103
|
+
vi.doMock('viem/tempo', () => ({
|
|
104
|
+
Actions: { token: { transfer: { call: transferCall } } },
|
|
105
|
+
}))
|
|
106
|
+
|
|
107
|
+
try {
|
|
108
|
+
const { charge: chargeWithMockedTempo } = await import('./Charge.js')
|
|
109
|
+
const client = createClient({
|
|
110
|
+
account,
|
|
111
|
+
chain: tempoLocalnet,
|
|
112
|
+
transport: http('http://127.0.0.1'),
|
|
113
|
+
})
|
|
114
|
+
const method = chargeWithMockedTempo({
|
|
115
|
+
account,
|
|
116
|
+
getClient: () => client,
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
const credential = Credential.deserialize(
|
|
120
|
+
await method.createCredential({
|
|
121
|
+
challenge: createChallenge({ amount: '1', chainId, supportedModes: ['pull'] }),
|
|
122
|
+
context: {},
|
|
123
|
+
}),
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
expect(transferCalls).toHaveLength(1)
|
|
127
|
+
expect(transferCalls[0]!.client).toBe(client)
|
|
128
|
+
expect(transferCalls[0]!.parameters).toMatchObject({
|
|
129
|
+
amount: 1_000_000n,
|
|
130
|
+
to: recipient,
|
|
131
|
+
token: currency,
|
|
132
|
+
})
|
|
133
|
+
expect(prepareTransactionRequest).toHaveBeenCalledOnce()
|
|
134
|
+
expect(signTransaction).toHaveBeenCalledOnce()
|
|
135
|
+
expect(credential.payload).toEqual({ signature: '0xdeadbeef', type: 'transaction' })
|
|
136
|
+
} finally {
|
|
137
|
+
vi.doUnmock('viem/actions')
|
|
138
|
+
vi.doUnmock('viem/tempo')
|
|
139
|
+
vi.resetModules()
|
|
140
|
+
}
|
|
141
|
+
})
|
|
142
|
+
|
|
87
143
|
test('resolveAccount selects the transaction account from executable calls', async () => {
|
|
88
144
|
vi.resetModules()
|
|
89
145
|
const selectedAccount = privateKeyToAccount(
|
|
@@ -7,6 +7,7 @@ import {
|
|
|
7
7
|
signTransaction,
|
|
8
8
|
} from 'viem/actions'
|
|
9
9
|
import { Actions } from 'viem/tempo'
|
|
10
|
+
import type { token as viem_token } from 'viem/tempo/actions'
|
|
10
11
|
import { tempo as tempo_chain } from 'viem/tempo/chains'
|
|
11
12
|
|
|
12
13
|
import * as Credential from '../../Credential.js'
|
|
@@ -35,6 +36,23 @@ const chargeContextSchema = z.object({
|
|
|
35
36
|
mode: z.optional(z.enum(Methods.chargeModes)),
|
|
36
37
|
})
|
|
37
38
|
|
|
39
|
+
// TODO: Remove once the minimum viem version is >=2.54.0, which uses client-first Tempo call builders.
|
|
40
|
+
function getTransferCall(
|
|
41
|
+
client: unknown,
|
|
42
|
+
parameters: viem_token.transfer.Args,
|
|
43
|
+
): AccountResolution.ResolveAccountCall {
|
|
44
|
+
const call = Actions.token.transfer.call as unknown as {
|
|
45
|
+
length: number
|
|
46
|
+
(parameters: viem_token.transfer.Args): ReturnType<typeof viem_token.transfer.call>
|
|
47
|
+
(
|
|
48
|
+
client: unknown,
|
|
49
|
+
parameters: viem_token.transfer.Args,
|
|
50
|
+
): ReturnType<typeof viem_token.transfer.call>
|
|
51
|
+
}
|
|
52
|
+
const result = call.length >= 2 ? call(client, parameters) : call(parameters)
|
|
53
|
+
return result
|
|
54
|
+
}
|
|
55
|
+
|
|
38
56
|
/**
|
|
39
57
|
* Creates a Tempo charge method intent for usage on the client.
|
|
40
58
|
*
|
|
@@ -129,12 +147,12 @@ export function charge(parameters: charge.Parameters = {}) {
|
|
|
129
147
|
})
|
|
130
148
|
const transferCalls = transfers.map(
|
|
131
149
|
(transfer): AccountResolution.ResolveAccountCall =>
|
|
132
|
-
|
|
150
|
+
getTransferCall(client, {
|
|
133
151
|
amount: BigInt(transfer.amount),
|
|
134
152
|
...(transfer.memo && { memo: transfer.memo as Hex.Hex }),
|
|
135
153
|
to: transfer.recipient as Address,
|
|
136
154
|
token: currency,
|
|
137
|
-
})
|
|
155
|
+
}),
|
|
138
156
|
)
|
|
139
157
|
|
|
140
158
|
const autoSwap = AutoSwap.resolve(
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Address } from 'viem'
|
|
2
|
-
import { describe, expect, test } from 'vp/test'
|
|
2
|
+
import { describe, expect, test, vi } from 'vp/test'
|
|
3
3
|
|
|
4
4
|
import { defaultCurrencies, InsufficientFundsError, resolve } from './auto-swap.js'
|
|
5
5
|
|
|
@@ -102,6 +102,73 @@ describe('resolve', () => {
|
|
|
102
102
|
})
|
|
103
103
|
})
|
|
104
104
|
|
|
105
|
+
describe('findCalls', () => {
|
|
106
|
+
test('passes the client to viem 2.54 Tempo token call builders', async () => {
|
|
107
|
+
vi.resetModules()
|
|
108
|
+
const account = '0x1111111111111111111111111111111111111111' as Address
|
|
109
|
+
const tokenOut = '0x2222222222222222222222222222222222222222' as Address
|
|
110
|
+
const tokenIn = '0x3333333333333333333333333333333333333333' as Address
|
|
111
|
+
const client = { chain: { id: 42431 } }
|
|
112
|
+
const tokenCalls: { client: unknown; name: string; parameters: Record<string, unknown> }[] = []
|
|
113
|
+
|
|
114
|
+
function getBalanceCall(client: unknown, parameters: Record<string, unknown>) {
|
|
115
|
+
tokenCalls.push({ client, name: 'getBalance', parameters })
|
|
116
|
+
return { kind: parameters.token === tokenOut ? 'targetBalance' : 'candidateBalance' }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function approveCall(client: unknown, parameters: Record<string, unknown>) {
|
|
120
|
+
tokenCalls.push({ client, name: 'approve', parameters })
|
|
121
|
+
return { kind: 'approve' }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
vi.doMock('viem/actions', () => ({
|
|
125
|
+
readContract: vi.fn(async (_client, call: { kind: string }) =>
|
|
126
|
+
call.kind === 'targetBalance' ? 0n : 2_000_000n,
|
|
127
|
+
),
|
|
128
|
+
}))
|
|
129
|
+
vi.doMock('viem/tempo', () => ({
|
|
130
|
+
Actions: {
|
|
131
|
+
dex: {
|
|
132
|
+
buy: { call: vi.fn((parameters) => ({ kind: 'buy', parameters })) },
|
|
133
|
+
getBuyQuote: vi.fn(async () => 1_000_000n),
|
|
134
|
+
},
|
|
135
|
+
token: {
|
|
136
|
+
approve: { call: approveCall },
|
|
137
|
+
getBalance: { call: getBalanceCall },
|
|
138
|
+
},
|
|
139
|
+
},
|
|
140
|
+
Addresses: { stablecoinDex: '0x4444444444444444444444444444444444444444' },
|
|
141
|
+
}))
|
|
142
|
+
|
|
143
|
+
try {
|
|
144
|
+
const { findCalls } = await import('./auto-swap.js')
|
|
145
|
+
|
|
146
|
+
const calls = await findCalls(client as never, {
|
|
147
|
+
account,
|
|
148
|
+
amountOut: 1_000_000n,
|
|
149
|
+
slippage: 1,
|
|
150
|
+
tokenIn: [tokenIn],
|
|
151
|
+
tokenOut,
|
|
152
|
+
})
|
|
153
|
+
|
|
154
|
+
expect(calls).toHaveLength(2)
|
|
155
|
+
expect(tokenCalls.map((call) => call.client)).toEqual([client, client, client])
|
|
156
|
+
expect(tokenCalls.map((call) => call.name)).toEqual(['getBalance', 'getBalance', 'approve'])
|
|
157
|
+
expect(tokenCalls[0]!.parameters).toMatchObject({ account, token: tokenOut })
|
|
158
|
+
expect(tokenCalls[1]!.parameters).toMatchObject({ account, token: tokenIn })
|
|
159
|
+
expect(tokenCalls[2]!.parameters).toMatchObject({
|
|
160
|
+
amount: 1_010_000n,
|
|
161
|
+
spender: '0x4444444444444444444444444444444444444444',
|
|
162
|
+
token: tokenIn,
|
|
163
|
+
})
|
|
164
|
+
} finally {
|
|
165
|
+
vi.doUnmock('viem/actions')
|
|
166
|
+
vi.doUnmock('viem/tempo')
|
|
167
|
+
vi.resetModules()
|
|
168
|
+
}
|
|
169
|
+
})
|
|
170
|
+
})
|
|
171
|
+
|
|
105
172
|
describe('InsufficientFundsError', () => {
|
|
106
173
|
test('default', () => {
|
|
107
174
|
const error = new InsufficientFundsError({
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Address, Client } from 'viem'
|
|
2
2
|
import { readContract } from 'viem/actions'
|
|
3
3
|
import { Actions, Addresses } from 'viem/tempo'
|
|
4
|
+
import type { token as viem_token } from 'viem/tempo/actions'
|
|
4
5
|
|
|
5
6
|
import * as TempoAddress from './address.js'
|
|
6
7
|
import * as defaults from './defaults.js'
|
|
@@ -14,6 +15,38 @@ export const defaultCurrencies: readonly Address[] = [
|
|
|
14
15
|
defaults.tokens.usdc as Address,
|
|
15
16
|
]
|
|
16
17
|
|
|
18
|
+
// TODO: Remove once the minimum viem version is >=2.54.0, which uses client-first Tempo call builders.
|
|
19
|
+
function getBalanceCall(
|
|
20
|
+
client: Client,
|
|
21
|
+
parameters: viem_token.getBalance.Args,
|
|
22
|
+
): ReturnType<typeof viem_token.getBalance.call> {
|
|
23
|
+
const call = Actions.token.getBalance.call as unknown as {
|
|
24
|
+
length: number
|
|
25
|
+
(parameters: viem_token.getBalance.Args): ReturnType<typeof viem_token.getBalance.call>
|
|
26
|
+
(
|
|
27
|
+
client: Client,
|
|
28
|
+
parameters: viem_token.getBalance.Args,
|
|
29
|
+
): ReturnType<typeof viem_token.getBalance.call>
|
|
30
|
+
}
|
|
31
|
+
return call.length >= 2 ? call(client, parameters) : call(parameters)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// TODO: Remove once the minimum viem version is >=2.54.0, which uses client-first Tempo call builders.
|
|
35
|
+
function getApproveCall(
|
|
36
|
+
client: Client,
|
|
37
|
+
parameters: viem_token.approve.Args,
|
|
38
|
+
): ReturnType<typeof viem_token.approve.call> {
|
|
39
|
+
const call = Actions.token.approve.call as unknown as {
|
|
40
|
+
length: number
|
|
41
|
+
(parameters: viem_token.approve.Args): ReturnType<typeof viem_token.approve.call>
|
|
42
|
+
(
|
|
43
|
+
client: Client,
|
|
44
|
+
parameters: viem_token.approve.Args,
|
|
45
|
+
): ReturnType<typeof viem_token.approve.call>
|
|
46
|
+
}
|
|
47
|
+
return call.length >= 2 ? call(client, parameters) : call(parameters)
|
|
48
|
+
}
|
|
49
|
+
|
|
17
50
|
/**
|
|
18
51
|
* Finds the optimal swap calls to acquire `amountOut` of `tokenOut`,
|
|
19
52
|
* returning an approve + buy call sequence if a viable route is found.
|
|
@@ -30,9 +63,9 @@ export async function findCalls(
|
|
|
30
63
|
const candidates = tokenIn.filter((t) => !TempoAddress.isEqual(t, tokenOut))
|
|
31
64
|
|
|
32
65
|
const balanceResults = await Promise.allSettled([
|
|
33
|
-
readContract(client,
|
|
66
|
+
readContract(client, getBalanceCall(client, { account, token: tokenOut }) as never),
|
|
34
67
|
...candidates.map((t) =>
|
|
35
|
-
readContract(client,
|
|
68
|
+
readContract(client, getBalanceCall(client, { account, token: t }) as never),
|
|
36
69
|
),
|
|
37
70
|
])
|
|
38
71
|
|
|
@@ -62,10 +95,10 @@ export async function findCalls(
|
|
|
62
95
|
const maxAmountIn =
|
|
63
96
|
quotedAmountIn + (quotedAmountIn * BigInt(Math.round(slippage * 100))) / bps
|
|
64
97
|
return [
|
|
65
|
-
|
|
66
|
-
token: tokenIn,
|
|
67
|
-
spender: Addresses.stablecoinDex,
|
|
98
|
+
getApproveCall(client, {
|
|
68
99
|
amount: maxAmountIn,
|
|
100
|
+
spender: Addresses.stablecoinDex,
|
|
101
|
+
token: tokenIn,
|
|
69
102
|
}),
|
|
70
103
|
Actions.dex.buy.call({
|
|
71
104
|
tokenIn,
|
|
@@ -692,6 +692,47 @@ describe('fillHostedFeePayerTransaction', () => {
|
|
|
692
692
|
).rejects.toThrow('gas exceeds sponsor policy')
|
|
693
693
|
expect(fetchMock).not.toHaveBeenCalled()
|
|
694
694
|
})
|
|
695
|
+
|
|
696
|
+
test('error: rejects non-empty access lists before requesting hosted fill', async () => {
|
|
697
|
+
const fetchMock = vi.fn()
|
|
698
|
+
vi.stubGlobal('fetch', fetchMock)
|
|
699
|
+
|
|
700
|
+
await expect(
|
|
701
|
+
fillHostedFeePayerTransaction({
|
|
702
|
+
allowedFeeTokens: defaultAllowedFeeTokens(defaults.chainId.mainnet),
|
|
703
|
+
...hostedContext,
|
|
704
|
+
transaction: {
|
|
705
|
+
...hostedTransaction,
|
|
706
|
+
accessList: [{ address: bogus, storageKeys: [] }],
|
|
707
|
+
} as any,
|
|
708
|
+
url: 'https://sponsor.example/tp_key',
|
|
709
|
+
}),
|
|
710
|
+
).rejects.toThrow('accessList is not allowed')
|
|
711
|
+
expect(fetchMock).not.toHaveBeenCalled()
|
|
712
|
+
})
|
|
713
|
+
|
|
714
|
+
test('error: rejects padded calldata before requesting hosted fill', async () => {
|
|
715
|
+
const fetchMock = vi.fn()
|
|
716
|
+
vi.stubGlobal('fetch', fetchMock)
|
|
717
|
+
|
|
718
|
+
await expect(
|
|
719
|
+
fillHostedFeePayerTransaction({
|
|
720
|
+
allowedFeeTokens: defaultAllowedFeeTokens(defaults.chainId.mainnet),
|
|
721
|
+
...hostedContext,
|
|
722
|
+
transaction: {
|
|
723
|
+
...hostedTransaction,
|
|
724
|
+
calls: [
|
|
725
|
+
{
|
|
726
|
+
...hostedTransaction.calls[0],
|
|
727
|
+
data: `${hostedTransaction.calls[0]!.data}01`,
|
|
728
|
+
},
|
|
729
|
+
],
|
|
730
|
+
} as any,
|
|
731
|
+
url: 'https://sponsor.example/tp_key',
|
|
732
|
+
}),
|
|
733
|
+
).rejects.toThrow('calldata is not canonical')
|
|
734
|
+
expect(fetchMock).not.toHaveBeenCalled()
|
|
735
|
+
})
|
|
695
736
|
})
|
|
696
737
|
|
|
697
738
|
describe('simulationTransaction', () => {
|
|
@@ -972,4 +1013,69 @@ describe('prepareSponsoredTransaction', () => {
|
|
|
972
1013
|
}),
|
|
973
1014
|
).toThrow('validity window exceeds sponsor policy')
|
|
974
1015
|
})
|
|
1016
|
+
|
|
1017
|
+
test('error: rejects non-empty access lists', () => {
|
|
1018
|
+
expect(() =>
|
|
1019
|
+
prepareSponsoredTransaction({
|
|
1020
|
+
account: sponsor,
|
|
1021
|
+
chainId: 42431,
|
|
1022
|
+
details,
|
|
1023
|
+
allowedFeeTokens: [bogus],
|
|
1024
|
+
transaction: {
|
|
1025
|
+
...baseTransaction,
|
|
1026
|
+
accessList: [{ address: bogus, storageKeys: [] }],
|
|
1027
|
+
} as any,
|
|
1028
|
+
}),
|
|
1029
|
+
).toThrow('accessList is not allowed')
|
|
1030
|
+
})
|
|
1031
|
+
|
|
1032
|
+
test('error: rejects padded calldata', () => {
|
|
1033
|
+
expect(() =>
|
|
1034
|
+
prepareSponsoredTransaction({
|
|
1035
|
+
account: sponsor,
|
|
1036
|
+
chainId: 42431,
|
|
1037
|
+
details,
|
|
1038
|
+
allowedFeeTokens: [bogus],
|
|
1039
|
+
transaction: {
|
|
1040
|
+
...baseTransaction,
|
|
1041
|
+
calls: [
|
|
1042
|
+
{
|
|
1043
|
+
...baseTransaction.calls[0],
|
|
1044
|
+
data: `${baseTransaction.calls[0]!.data}01`,
|
|
1045
|
+
},
|
|
1046
|
+
],
|
|
1047
|
+
} as any,
|
|
1048
|
+
}),
|
|
1049
|
+
).toThrow('calldata is not canonical')
|
|
1050
|
+
})
|
|
1051
|
+
|
|
1052
|
+
test('error: rejects missing calls', () => {
|
|
1053
|
+
expect(() =>
|
|
1054
|
+
prepareSponsoredTransaction({
|
|
1055
|
+
account: sponsor,
|
|
1056
|
+
chainId: 42431,
|
|
1057
|
+
details,
|
|
1058
|
+
allowedFeeTokens: [bogus],
|
|
1059
|
+
transaction: {
|
|
1060
|
+
...baseTransaction,
|
|
1061
|
+
calls: undefined,
|
|
1062
|
+
} as any,
|
|
1063
|
+
}),
|
|
1064
|
+
).toThrow('must declare calls')
|
|
1065
|
+
})
|
|
1066
|
+
|
|
1067
|
+
test('error: rejects nonzero call value', () => {
|
|
1068
|
+
expect(() =>
|
|
1069
|
+
prepareSponsoredTransaction({
|
|
1070
|
+
account: sponsor,
|
|
1071
|
+
chainId: 42431,
|
|
1072
|
+
details,
|
|
1073
|
+
allowedFeeTokens: [bogus],
|
|
1074
|
+
transaction: {
|
|
1075
|
+
...baseTransaction,
|
|
1076
|
+
calls: [{ ...baseTransaction.calls[0], value: 1n }],
|
|
1077
|
+
} as any,
|
|
1078
|
+
}),
|
|
1079
|
+
).toThrow('call value is not allowed')
|
|
1080
|
+
})
|
|
975
1081
|
})
|
|
@@ -3,7 +3,7 @@ import type { TempoAddress } from 'ox/tempo'
|
|
|
3
3
|
import { TxEnvelopeTempo } from 'ox/tempo'
|
|
4
4
|
import type { Hex } from 'viem'
|
|
5
5
|
import type { Account } from 'viem'
|
|
6
|
-
import { decodeFunctionData, maxUint256, toHex } from 'viem'
|
|
6
|
+
import { decodeFunctionData, encodeFunctionData, maxUint256, toHex } from 'viem'
|
|
7
7
|
import { Abis, Addresses, Transaction } from 'viem/tempo'
|
|
8
8
|
|
|
9
9
|
import * as TempoAddress_internal from './address.js'
|
|
@@ -319,6 +319,74 @@ function isExpiringNonceKey(nonceKey: SponsoredTransaction['nonceKey']): boolean
|
|
|
319
319
|
return nonceKey === 'expiring' || nonceKey === maxUint256
|
|
320
320
|
}
|
|
321
321
|
|
|
322
|
+
const sponsoredCallAbi = [...Abis.tip20, ...Abis.stablecoinDex] as const
|
|
323
|
+
const sponsoredCallSelectors = new Set([
|
|
324
|
+
Selectors.approve,
|
|
325
|
+
Selectors.transfer,
|
|
326
|
+
Selectors.transferWithMemo,
|
|
327
|
+
Selectors.swapExactAmountOut,
|
|
328
|
+
])
|
|
329
|
+
|
|
330
|
+
function canonicalSponsoredCallData(
|
|
331
|
+
data: Hex,
|
|
332
|
+
call: string,
|
|
333
|
+
fail: (reason: string, extra?: Record<string, string>) => never,
|
|
334
|
+
) {
|
|
335
|
+
if (!sponsoredCallSelectors.has(data.slice(0, 10) as Hex)) return undefined
|
|
336
|
+
|
|
337
|
+
let decoded: ReturnType<typeof decodeFunctionData<typeof sponsoredCallAbi>>
|
|
338
|
+
try {
|
|
339
|
+
decoded = decodeFunctionData({ abi: sponsoredCallAbi, data })
|
|
340
|
+
} catch {
|
|
341
|
+
fail('fee-sponsored transaction call calldata is invalid', { call })
|
|
342
|
+
}
|
|
343
|
+
return encodeFunctionData({
|
|
344
|
+
abi: sponsoredCallAbi,
|
|
345
|
+
functionName: decoded.functionName,
|
|
346
|
+
args: decoded.args,
|
|
347
|
+
})
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Rejects sponsored transaction fields that increase intrinsic gas without
|
|
352
|
+
* changing the decoded payment intent.
|
|
353
|
+
*/
|
|
354
|
+
function assertCanonicalSponsoredTransaction(
|
|
355
|
+
transaction: SponsoredTransaction,
|
|
356
|
+
fail: (reason: string, extra?: Record<string, string>) => never,
|
|
357
|
+
) {
|
|
358
|
+
if (transaction.accessList !== undefined && transaction.accessList.length > 0)
|
|
359
|
+
fail('fee-sponsored transaction accessList is not allowed', {
|
|
360
|
+
accessListEntries: String(transaction.accessList.length),
|
|
361
|
+
})
|
|
362
|
+
|
|
363
|
+
const calls = transaction.calls
|
|
364
|
+
if (!Array.isArray(calls) || calls.length === 0)
|
|
365
|
+
fail('fee-sponsored transaction must declare calls')
|
|
366
|
+
|
|
367
|
+
for (const [index, call] of calls.entries()) {
|
|
368
|
+
const callIndex = String(index)
|
|
369
|
+
const value = call.value
|
|
370
|
+
if (value !== undefined && value !== 0n)
|
|
371
|
+
fail('fee-sponsored transaction call value is not allowed', {
|
|
372
|
+
call: callIndex,
|
|
373
|
+
value: value.toString(),
|
|
374
|
+
})
|
|
375
|
+
|
|
376
|
+
const data = call.data
|
|
377
|
+
if (!data)
|
|
378
|
+
fail('fee-sponsored transaction call is missing calldata', {
|
|
379
|
+
call: callIndex,
|
|
380
|
+
})
|
|
381
|
+
|
|
382
|
+
const canonical = canonicalSponsoredCallData(data, callIndex, fail)
|
|
383
|
+
if (canonical && data.toLowerCase() !== canonical.toLowerCase())
|
|
384
|
+
fail('fee-sponsored transaction call calldata is not canonical', {
|
|
385
|
+
call: callIndex,
|
|
386
|
+
})
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
322
390
|
/** Validates that a set of transaction calls matches an allowed fee-payer pattern. */
|
|
323
391
|
export function validateCalls(
|
|
324
392
|
calls: readonly { data?: `0x${string}` | undefined; to?: TempoAddress.Address | undefined }[],
|
|
@@ -486,6 +554,8 @@ export function assertTransactionPolicy(parameters: {
|
|
|
486
554
|
chainId: String(transactionChainId),
|
|
487
555
|
})
|
|
488
556
|
|
|
557
|
+
assertCanonicalSponsoredTransaction(transaction, fail)
|
|
558
|
+
|
|
489
559
|
if (gas === undefined || gas <= 0n) fail('fee-sponsored transaction must declare gas')
|
|
490
560
|
const gasLimit = gas
|
|
491
561
|
if (gasLimit > policy.maxGas)
|
|
@@ -12,7 +12,7 @@ function pushUnique(tokens: Address[], token: Address | undefined) {
|
|
|
12
12
|
|
|
13
13
|
async function hasBalance(client: Client, account: Address, token: Address): Promise<boolean> {
|
|
14
14
|
try {
|
|
15
|
-
return (await Actions.token.getBalance(client as never, { account, token })) > 0n
|
|
15
|
+
return (await Actions.token.getBalance(client as never, { account, token })).amount > 0n
|
|
16
16
|
} catch {
|
|
17
17
|
return false
|
|
18
18
|
}
|