@vleap/warps 3.0.0-beta.191 → 3.0.0-beta.192

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/dist/index.d.cts CHANGED
@@ -996,8 +996,7 @@ declare const WarpCacheKey: {
996
996
  };
997
997
  declare class WarpCache {
998
998
  private strategy;
999
- private path?;
1000
- constructor(type?: WarpCacheType, path?: string);
999
+ constructor(env: WarpChainEnv, config?: ClientCacheConfig);
1001
1000
  private selectStrategy;
1002
1001
  set<T>(key: string, value: T, ttl: number): void;
1003
1002
  get<T>(key: string): T | null;
package/dist/index.d.ts CHANGED
@@ -996,8 +996,7 @@ declare const WarpCacheKey: {
996
996
  };
997
997
  declare class WarpCache {
998
998
  private strategy;
999
- private path?;
1000
- constructor(type?: WarpCacheType, path?: string);
999
+ constructor(env: WarpChainEnv, config?: ClientCacheConfig);
1001
1000
  private selectStrategy;
1002
1001
  set<T>(key: string, value: T, ttl: number): void;
1003
1002
  get<T>(key: string): T | null;
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var Pe=Object.create;var dt=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var be=Object.getOwnPropertyNames;var Ee=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var Ne=(r,t)=>{for(var e in t)dt(r,e,{get:t[e],enumerable:!0})},Zt=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of be(t))!Re.call(r,i)&&i!==e&&dt(r,i,{get:()=>t[i],enumerable:!(n=Te(t,i))||n.enumerable});return r};var G=(r,t,e)=>(e=r!=null?Pe(Ee(r)):{},Zt(t||!r||!r.__esModule?dt(e,"default",{value:r,enumerable:!0}):e,r)),Be=r=>Zt(dt({},"__esModule",{value:!0}),r);var Br={};Ne(Br,{BrowserCryptoProvider:()=>ft,CacheTtl:()=>zt,NodeCryptoProvider:()=>gt,WARP_LANGUAGES:()=>qe,WarpBrandBuilder:()=>Lt,WarpBuilder:()=>Mt,WarpCache:()=>ot,WarpCacheKey:()=>St,WarpChainName:()=>Yt,WarpClient:()=>Jt,WarpConfig:()=>F,WarpConstants:()=>l,WarpExecutor:()=>ct,WarpFactory:()=>q,WarpIndex:()=>lt,WarpInputTypes:()=>g,WarpInterpolator:()=>E,WarpLinkBuilder:()=>L,WarpLinkDetecter:()=>ut,WarpLogger:()=>C,WarpProtocolVersions:()=>D,WarpSerializer:()=>w,WarpTypeRegistry:()=>Qt,WarpValidator:()=>it,address:()=>Cr,applyOutputToMessages:()=>Wt,asset:()=>jt,biguint:()=>Ar,bool:()=>xr,buildMappedOutput:()=>rt,buildNestedPayload:()=>ne,bytesToBase64:()=>De,bytesToHex:()=>te,cleanWarpIdentifier:()=>et,createAuthHeaders:()=>xt,createAuthMessage:()=>At,createCryptoProvider:()=>Le,createDefaultWalletProvider:()=>dr,createHttpAuthHeaders:()=>er,createSignableMessage:()=>oe,createWarpI18nText:()=>ke,createWarpIdentifier:()=>mt,evaluateOutputCommon:()=>ae,evaluateWhenCondition:()=>Bt,extractCollectOutput:()=>nt,extractIdentifierInfoFromUrl:()=>_,extractQueryStringFromIdentifier:()=>Ht,extractQueryStringFromUrl:()=>$t,extractResolvedInputValues:()=>B,extractWarpSecrets:()=>Me,findWarpAdapterForChain:()=>v,getCryptoProvider:()=>Tt,getEventNameFromWarp:()=>He,getLatestProtocolIdentifier:()=>Z,getNextInfo:()=>vt,getProviderConfig:()=>tr,getRandomBytes:()=>bt,getRandomHex:()=>Et,getWalletFromConfigOrFail:()=>ir,getWarpActionByIndex:()=>b,getWarpBrandLogoUrl:()=>Oe,getWarpChainAssetLogoUrl:()=>Fe,getWarpChainInfoLogoUrl:()=>Ve,getWarpInfoFromIdentifier:()=>H,getWarpPrimaryAction:()=>$,getWarpWalletAddress:()=>pe,getWarpWalletAddressFromConfig:()=>P,getWarpWalletExternalId:()=>ue,getWarpWalletExternalIdFromConfig:()=>de,getWarpWalletExternalIdFromConfigOrFail:()=>or,getWarpWalletMnemonic:()=>le,getWarpWalletMnemonicFromConfig:()=>sr,getWarpWalletPrivateKey:()=>ce,getWarpWalletPrivateKeyFromConfig:()=>ar,handleX402Payment:()=>Dt,hasInputPrefix:()=>Qe,hex:()=>wr,initializeWalletCache:()=>ur,isEqualWarpIdentifier:()=>Ge,isWarpActionAutoExecute:()=>ht,isWarpI18nText:()=>ze,isWarpWalletReadOnly:()=>pr,mergeNestedPayload:()=>Ft,normalizeAndValidateMnemonic:()=>lr,normalizeMnemonic:()=>fe,option:()=>Ir,parseOutputOutIndex:()=>se,parseSignedMessage:()=>nr,replacePlaceholders:()=>V,replacePlaceholdersInWhenExpression:()=>Nt,resolveWarpText:()=>tt,safeWindow:()=>Pt,setCryptoProvider:()=>Ue,setWarpWalletInConfig:()=>cr,shiftBigintBy:()=>Y,splitInput:()=>yt,string:()=>hr,struct:()=>Pr,testCryptoAvailability:()=>je,toInputPayloadValue:()=>ie,toPreviewText:()=>Rt,tuple:()=>Sr,uint16:()=>yr,uint32:()=>Wr,uint64:()=>vr,uint8:()=>mr,validateMnemonicLength:()=>ge,validateSignedMessage:()=>rr,vector:()=>Tr,withAdapterFallback:()=>$e});module.exports=Be(Br);var Yt=(d=>(d.Multiversx="multiversx",d.Vibechain="vibechain",d.Sui="sui",d.Ethereum="ethereum",d.Base="base",d.Arbitrum="arbitrum",d.Polygon="polygon",d.Somnia="somnia",d.Fastset="fastset",d.Solana="solana",d.Near="near",d))(Yt||{}),l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>r.config.user?.wallets?.[r.adapter.chainInfo.name]},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:r=>{if(!r.adapter.wallet)return null;try{return r.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:r=>r.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:r=>r.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},g={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},Pt=typeof window<"u"?window:{open:()=>{}};var D={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},F={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${D.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${D.Brand}.schema.json`,DefaultClientUrl:r=>r==="devnet"?"https://devnet.usewarp.to":r==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",l.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var $e=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var He=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=l.Alerts.TriggerEventPrefix+l.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var Oe=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},Fe=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]},Ve=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var ft=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(t);return window.crypto.getRandomValues(e),e}},gt=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(t))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},j=null;function Tt(){if(j)return j;if(typeof window<"u"&&window.crypto)return j=new ft,j;if(typeof process<"u"&&process.versions?.node)return j=new gt,j;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Ue(r){j=r}async function bt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Tt()).getRandomBytes(r)}function te(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(r.length*2);for(let e=0;e<r.length;e++){let n=r[e];t[e*2]=(n>>>4).toString(16),t[e*2+1]=(n&15).toString(16)}return t.join("")}function De(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(r).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(r));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function Et(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await bt(r/2,t);return te(e)}async function je(){let r={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?r.environment="browser":typeof process<"u"&&process.versions?.node&&(r.environment="nodejs"),await bt(16),r.randomBytes=!0}catch{}return r}function Le(){return Tt()}var Me=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${l.Vars.Env}:`)).map(t=>{let e=t.replace(`${l.Vars.Env}:`,"").trim(),[n,i]=e.split(l.ArgCompositeSeparator);return{key:n,description:i||null}});var v=(r,t)=>{let e=t.find(n=>n.chainInfo.name.toLowerCase()===r.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${r}`);return e},Z=r=>{if(r==="warp")return`warp:${D.Warp}`;if(r==="brand")return`brand:${D.Brand}`;if(r==="abi")return`abi:${D.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},b=(r,t)=>r?.actions[t-1],$=r=>{if(r.actions.length===0)throw new Error(`Warp has no primary action: ${r.meta?.identifier}`);let t=r.actions.find(a=>a.primary===!0);if(t)return{action:t,index:r.actions.indexOf(t)};let e=["transfer","contract","query","collect","mcp"],n=r.actions.find(a=>e.includes(a.type));return n?{action:n,index:r.actions.indexOf(n)}:{action:r.actions[0],index:0}},ht=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=$(t);return r===e}return!0},Y=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(a,"0"));if(t<0){let s=n+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},Rt=(r,t=100)=>{if(!r)return"";let e=r.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},V=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>t[n]||""),Nt=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Bt=r=>{if(!r||typeof r!="string")return!0;try{return!!new Function(`return ${r}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${r}. Error: ${t}`)}};var qe={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},tt=(r,t)=>{let e=t?.preferences?.locale||"en";if(typeof r=="string")return r;if(typeof r=="object"&&r!==null){if(e in r)return r[e];if("en"in r)return r.en;let n=Object.keys(r);if(n.length>0)return r[n[0]]}return""},ze=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,ke=r=>r;var et=r=>r.startsWith(l.IdentifierAliasMarker)?r.replace(l.IdentifierAliasMarker,""):r,Ge=(r,t)=>!r||!t?!1:et(r)===et(t),mt=(r,t,e)=>{let n=et(e);return t===l.IdentifierType.Alias?l.IdentifierAliasMarker+r+l.IdentifierParamSeparator+n:r+l.IdentifierParamSeparator+t+l.IdentifierParamSeparator+n},H=r=>{let t=decodeURIComponent(r).trim(),e=et(t),n=e.split("?")[0],i=ee(n);if(n.length===64&&/^[a-fA-F0-9]+$/.test(n))return{chain:l.IdentifierChainDefault,type:l.IdentifierType.Hash,identifier:e,identifierBase:n};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[a,s,p]=i;if(s===l.IdentifierType.Alias||s===l.IdentifierType.Hash){let c=e.includes("?")?p+e.substring(e.indexOf("?")):p;return{chain:a,type:s,identifier:c,identifierBase:p}}}if(i.length===2){let[a,s]=i;if(a===l.IdentifierType.Alias||a===l.IdentifierType.Hash){let p=e.includes("?")?s+e.substring(e.indexOf("?")):s;return{chain:l.IdentifierChainDefault,type:a,identifier:p,identifierBase:s}}}if(i.length===2){let[a,s]=i;if(a!==l.IdentifierType.Alias&&a!==l.IdentifierType.Hash){let p=e.includes("?")?s+e.substring(e.indexOf("?")):s,c=_e(s,a)?l.IdentifierType.Hash:l.IdentifierType.Alias;return{chain:a,type:c,identifier:p,identifierBase:s}}}return{chain:l.IdentifierChainDefault,type:l.IdentifierType.Alias,identifier:e,identifierBase:n}},_=r=>{let t=new URL(r),n=t.searchParams.get(l.IdentifierParamName);if(n||(n=t.pathname.split("/")[1]),!n)return null;let i=decodeURIComponent(n);return H(i)},_e=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Je=r=>{let t=l.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},ee=r=>{let t=Je(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=ee(a);return[i,...s]},$t=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(l.IdentifierParamName),e.toString()||null}catch{return null}},Ht=r=>{let t=r.indexOf("?");if(t===-1||t===r.length-1)return null;let e=r.substring(t+1);return e.length>0?e:null};var yt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},Qe=r=>{let t=new Set(Object.values(g));if(!r.includes(l.ArgParamsSeparator))return!1;let e=yt(r)[0];return t.has(e)};var Wt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=tt(a,e);return[i,V(s,t)]});return Object.fromEntries(n)};var re=G(require("qr-code-styling"),1);var L=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!_(t):!1}build(t,e,n){let i=this.config.clientUrl||F.DefaultClientUrl(this.config.env),a=v(t,this.adapters),s=e===l.IdentifierType.Alias?n:e+l.IdentifierParamSeparator+n,p=a.chainInfo.name+l.IdentifierParamSeparator+s,c=encodeURIComponent(p);return F.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${l.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let e=H(t);if(!e)return null;let n=v(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,a="white",s="black",p="#23F7DD"){let c=v(t,this.adapters),o=this.build(c.chainInfo.name,e,n);return new re.default({type:"svg",width:i,height:i,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(p)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Ke="https://",vt=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith(Ke))return[{identifier:null,url:a}];let[s,p]=a.split("?");if(!p){let f=V(s,{...e.vars,...i});return[{identifier:f,url:Ot(t,f,r)}]}let c=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let f=V(p,{...e.vars,...i}),y=f?`${s}?${f}`:s;return[{identifier:y,url:Ot(t,y,r)}]}let o=c[0];if(!o)return[];let u=o.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let h=Array.isArray(i[d])?i[d]:[i[d]];if(h.length===0)return[];let m=c.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let y=f.match(/\[\](\.[^}]+)?}}/),A=y&&y[1]||"";return{placeholder:f,field:A?A.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let y=p;for(let{regex:T,field:R}of m){let x=R?Xe(f,R):f;if(x==null)return null;y=y.replace(T,x)}if(y.includes("{{")||y.includes("}}"))return null;let A=y?`${s}?${y}`:s;return{identifier:A,url:Ot(t,A,r)}}).filter(f=>f!==null)},Ot=(r,t,e)=>{let[n,i]=t.split("?"),a=H(n)||{chain:l.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},s=v(a.chain,r);if(!s)throw new Error(`Adapter not found for chain ${a.chain}`);let p=new L(e,r).build(s.chainInfo.name,a.type,a.identifierBase);if(!i)return p;let c=new URL(p);return new URLSearchParams(i).forEach((o,u)=>c.searchParams.set(u,o)),c.toString().replace(/\/\?/,"?")},Xe=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var M=class M{static debug(...t){M.isTestEnv||console.debug(...t)}static info(...t){M.isTestEnv||console.info(...t)}static warn(...t){M.isTestEnv||console.warn(...t)}static error(...t){M.isTestEnv||console.error(...t)}};M.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=M;function ne(r,t,e){return r.startsWith(l.Position.Payload)?r.slice(l.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function Ft(r,t){if(!r)return{...t};if(!t)return{...r};let e={...r};return Object.keys(t).forEach(n=>{e[n]&&typeof e[n]=="object"&&typeof t[n]=="object"?e[n]=Ft(e[n],t[n]):e[n]=t[n]}),e}function ie(r,t){if(!r.value)return null;let e=t.stringToNative(r.value)[1];if(r.input.type==="biguint")return e.toString();if(r.input.type==="asset"){let{identifier:n,amount:i}=e;return{identifier:n,amount:i.toString()}}else return e}function B(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function rt(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,a=ie(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(l.Position.Payload)){let s=ne(n.input.position,i,a);e=Ft(e,s)}else e[i]=a}),e}var nt=async(r,t,e,n,i,a)=>{let s=[],p=[],c={};for(let[u,d]of Object.entries(r.output||{})){if(d.startsWith(l.Transform.Prefix))continue;let h=se(d);if(h!==null&&h!==e){c[u]=null;continue}let[m,...W]=d.split("."),f=(y,A)=>A.reduce((T,R)=>T&&T[R]!==void 0?T[R]:null,y);if(m==="out"||m.startsWith("out[")){let y=W.length===0?t?.data||t:f(t,W);s.push(String(y)),p.push(y),c[u]=y}else c[u]=d}let o=rt(n,i);return{values:{string:s,native:p,mapped:o},output:await ae(r,c,e,n,i,a)}},ae=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t};return s=Ze(s,r,e,n,i),s=await Ye(r,s,a.transform?.runner||null),s},Ze=(r,t,e,n,i)=>{let a={...r},s=b(t,e)?.inputs||[];for(let[p,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("in.")){let o=c.split(".")[1],u=s.findIndex(h=>h.as===o||h.name===o),d=u!==-1?n[u]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},Ye=async(r,t,e)=>{if(!r.output)return t;let n={...t},i=Object.entries(r.output).filter(([,a])=>a.startsWith(l.Transform.Prefix)).map(([a,s])=>({key:a,code:s.substring(l.Transform.Prefix.length)}));if(i.length>0&&(!e||typeof e.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:a,code:s}of i)try{n[a]=await e.run(s,n)}catch(p){C.error(`Transform error for output '${a}':`,p),n[a]=null}return n},se=r=>{if(r==="out")return 1;let t=r.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(r.startsWith("out.")||r.startsWith("event."),null)};var tr=(r,t,e,n)=>{let i=r.preferences?.providers?.[t];return i?.[e]?typeof i[e]=="string"?{url:i[e]}:i[e]:{url:n}};async function oe(r,t,e,n=5){let i=await Et(64,e),a=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:r,nonce:i,expiresAt:a,purpose:t}),nonce:i,expiresAt:a}}async function At(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return oe(r,i,e,5)}function xt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function er(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await At(r,e,n),p=await t(i);return xt(r,p,a,s)}function rr(r){let t=new Date(r).getTime();return Date.now()<t}function nr(r){try{let t=JSON.parse(r);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var ir=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},pe=r=>r?typeof r=="string"?r:r.address:null,P=(r,t)=>pe(r.user?.wallets?.[t]||null),ce=r=>r?typeof r=="string"?r:r.privateKey||null:null,le=r=>r?typeof r=="string"?r:r.mnemonic||null:null,ue=r=>r?typeof r=="string"?r:r.externalId||null:null,ar=(r,t)=>ce(r.user?.wallets?.[t]||null)?.trim()||null,sr=(r,t)=>le(r.user?.wallets?.[t]||null)?.trim()||null,de=(r,t)=>ue(r.user?.wallets?.[t]||null)?.trim()||null,or=(r,t)=>{let e=de(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},pr=r=>typeof r=="string",cr=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},fe=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},ge=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},lr=(r,t=24)=>{let e=fe(r);return ge(e,t),e};async function ur(r){let t={address:null,publicKey:null};if(!r)return t;try{t.address=await r.getAddress()}catch{}try{t.publicKey=await r.getPublicKey()}catch{}return t}function dr(r,t,e){return null}var Vt=require("@x402/core/client"),Ut=require("@x402/core/http");async function Dt(r,t,e,n,i){let a=await fr(r,i);if(!a)return r;let s=new Headers;n&&s.set("Content-Type","application/json"),s.set("Accept","application/json"),Object.entries(a).forEach(([c,o])=>{s.set(c,o)}),C.debug("WarpExecutor: Retrying request with payment headers");let p=await fetch(t,{method:e,headers:s,body:n});return C.debug("WarpExecutor: Payment processed, new response status",{status:p.status}),p}var fr=async(r,t)=>{let e=await gr(r),i=new Ut.x402HTTPClient(new Vt.x402Client).getPaymentRequiredResponse(a=>r.headers.get(a),e);if(!i?.accepts?.length)return null;for(let a of t)if(a.wallet.registerX402Handlers)try{let s=new Vt.x402Client,p=await a.wallet.registerX402Handlers(s),c=i.accepts.find(h=>h?.network&&p[h.network]);if(!c?.network)continue;p[c.network]();let o=new Ut.x402HTTPClient(s),u=await o.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=o.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return C.debug(`WarpExecutor: x402 payment processed with ${a.chainInfo.name} adapter using ${c.network} scheme`),d}catch{continue}return null},gr=async r=>{try{let t=await r.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===g.Tuple&&Array.isArray(e)){if(e.length===0)return t+l.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(l.ArgCompositeSeparator)})${l.ArgParamsSeparator}${a.join(l.ArgListSeparator)}`}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===g.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,a=Object.keys(n).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${l.ArgParamsSeparator}`;let s=a.map(p=>{let[c,o]=this.getTypeAndValue(n[p]);return`(${p}${l.ArgParamsSeparator}${c})${o}`});return`${t}(${i})${l.ArgParamsSeparator}${s.join(l.ArgListSeparator)}`}if(t===g.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${l.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e[0],i=n.indexOf(l.ArgParamsSeparator),a=n.substring(0,i),s=e.map(c=>{let o=c.indexOf(l.ArgParamsSeparator),u=c.substring(o+1);return a.startsWith(g.Tuple)?u.replace(l.ArgListSeparator,l.ArgCompositeSeparator):u}),p=a.startsWith(g.Struct)?l.ArgStructSeparator:l.ArgListSeparator;return t+l.ArgParamsSeparator+a+l.ArgParamsSeparator+s.join(p)}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===g.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?g.Asset+l.ArgParamsSeparator+e.identifier+l.ArgCompositeSeparator+String(e.amount)+l.ArgCompositeSeparator+String(e.decimals):g.Asset+l.ArgParamsSeparator+e.identifier+l.ArgCompositeSeparator+String(e.amount);if(this.typeRegistry){let n=this.typeRegistry.getHandler(t);if(n)return n.nativeToString(e);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,e)}return t+l.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(l.ArgParamsSeparator),n=e[0],i=e.slice(1).join(l.ArgParamsSeparator);if(n==="null")return[n,null];if(n===g.Option){let[a,s]=i.split(l.ArgParamsSeparator);return[g.Option+l.ArgParamsSeparator+a,s||null]}if(n===g.Vector){let a=i.indexOf(l.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),c=s.startsWith(g.Struct)?l.ArgStructSeparator:l.ArgListSeparator,u=(p?p.split(c):[]).map(d=>this.stringToNative(s+l.ArgParamsSeparator+d)[1]);return[g.Vector+l.ArgParamsSeparator+s,u]}else if(n.startsWith(g.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),p=i.split(l.ArgCompositeSeparator).map((c,o)=>this.stringToNative(`${a[o]}${l.IdentifierParamSeparator}${c}`)[1]);return[n,p]}else if(n.startsWith(g.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:a[1]};return i&&i.split(l.ArgListSeparator).forEach(c=>{let o=c.match(new RegExp(`^\\(([^${l.ArgParamsSeparator}]+)${l.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,h]=o;p[u]=this.stringToNative(`${d}${l.IdentifierParamSeparator}${h}`)[1]}}),[n,p]}else{if(n===g.String)return[n,i];if(n===g.Uint8||n===g.Uint16||n===g.Uint32)return[n,Number(i)];if(n===g.Uint64||n===g.Uint128||n===g.Uint256||n===g.Biguint)return[n,BigInt(i||0)];if(n===g.Bool)return[n,i==="true"];if(n===g.Address)return[n,i];if(n===g.Hex)return[n,i];if(n===g.Asset){let[a,s]=i.split(l.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[n,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let p=a.stringToNative(i);return[n,p]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[p,c]=this.stringToNative(`${s}:${i}`);return[n,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(l.ArgParamsSeparator)){let[e,n]=t.split(l.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[g.Uint32,t]:typeof t=="bigint"?[g.Uint64,t]:typeof t=="boolean"?[g.Bool,t]:[typeof t,t]}};var hr=r=>new w().nativeToString(g.String,r),mr=r=>new w().nativeToString(g.Uint8,r),yr=r=>new w().nativeToString(g.Uint16,r),Wr=r=>new w().nativeToString(g.Uint32,r),vr=r=>new w().nativeToString(g.Uint64,r),Ar=r=>new w().nativeToString(g.Biguint,r),xr=r=>new w().nativeToString(g.Bool,r),Cr=r=>new w().nativeToString(g.Address,r),jt=r=>new w().nativeToString(g.Asset,r),wr=r=>new w().nativeToString(g.Hex,r),Ir=(r,t)=>{if(t===null)return g.Option+l.ArgParamsSeparator;let e=r(t),n=e.indexOf(l.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return g.Option+l.ArgParamsSeparator+i+l.ArgParamsSeparator+a},Sr=(...r)=>new w().nativeToString(g.Tuple,r),Pr=r=>new w().nativeToString(g.Struct,r),Tr=r=>new w().nativeToString(g.Vector,r);var he=G(require("ajv"),1);var Lt=class{constructor(t){this.pendingBrand={protocol:Z("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.ensureValidSchema(n),n}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}ensureWarpText(t,e){if(!t)throw new Error(`Warp: ${e}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||F.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new he.default,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var me=G(require("ajv"),1);var it=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validatePrimaryAction(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validatePrimaryAction(t){try{let{action:e}=$(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,a)=>{i&&Object.keys(i).forEach(s=>{s!==s.toUpperCase()&&e.push(`${a} name '${s}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(s=>s.type==="contract"),n=t.actions.some(s=>s.type==="query");if(!e&&!n)return[];let i=t.actions.some(s=>s.abi),a=Object.values(t.output||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.output&&!i&&a?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||F.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new me.default({strict:!1}),s=a.compile(i);return s(t)?[]:[`Schema validation failed: ${a.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var Mt=class{constructor(t){this.config=t;this.pendingWarp={protocol:Z("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.validate(n),n}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}setOutput(t){return this.pendingWarp.output=t??void 0,this}async build(t=!0){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),t&&await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return Rt(t,e)}ensure(t,e){if(!t)throw new Error(e)}ensureWarpText(t,e){if(!t)throw new Error(e);if(typeof t=="object"&&!t.en)throw new Error(e)}async validate(t){let n=await new it(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
- `))}};var I=require("fs"),K=require("path");var ye=new w,J=(r,t)=>typeof t=="bigint"?ye.nativeToString("biguint",t):t,Q=(r,t)=>typeof t=="string"&&t.startsWith(g.Biguint+":")?ye.stringToNative(t)[1]:t;var Ct=class{constructor(t){this.cacheDir=t?(0,K.resolve)(t):(0,K.resolve)(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){(0,I.existsSync)(this.cacheDir)||(0,I.mkdirSync)(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return(0,K.join)(this.cacheDir,`${e}.json`)}get(t){try{let e=this.getFilePath(t);if(!(0,I.existsSync)(e))return null;let n=(0,I.readFileSync)(e,"utf-8"),i=JSON.parse(n,Q);return Date.now()>i.expiresAt?((0,I.unlinkSync)(e),null):i.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3},a=this.getFilePath(t);(0,I.writeFileSync)(a,JSON.stringify(i,J),"utf-8")}forget(t){try{let e=this.getFilePath(t);(0,I.existsSync)(e)&&(0,I.unlinkSync)(e)}catch{}}clear(){try{(0,I.readdirSync)(this.cacheDir).forEach(e=>{e.endsWith(".json")&&(0,I.unlinkSync)((0,K.join)(this.cacheDir,e))})}catch{}}};var at=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,Q);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,J))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var U=class U{get(t){let e=U.cache.get(t);return e?Date.now()>e.expiresAt?(U.cache.delete(t),null):e.value:null}set(t,e,n){let i=Date.now()+n*1e3;U.cache.set(t,{value:e,expiresAt:i})}forget(t){U.cache.delete(t)}clear(){U.cache.clear()}};U.cache=new Map;var st=U;var It=require("fs"),qt=require("path");var wt=class{constructor(t){this.manifestPath=t?(0,qt.resolve)(t):(0,qt.resolve)(process.cwd(),"warps-manifest.json"),console.log("StaticCacheStrategy path",t),console.log("StaticCacheStrategy manifestPath",this.manifestPath),console.log("StaticCacheStrategy process.cwd()",process.cwd()),this.cache=this.loadManifest()}loadManifest(){try{let t=(0,It.readFileSync)(this.manifestPath,"utf-8");return new Map(Object.entries(JSON.parse(t,Q)))}catch{return new Map}}saveManifest(){let t=JSON.stringify(Object.fromEntries(this.cache.entries()),J);(0,It.writeFileSync)(this.manifestPath,t,"utf-8")}get(t){let e=this.cache.get(t);return!e||Date.now()>e.expiresAt?(e&&(this.cache.delete(t),this.saveManifest()),null):e.value}set(t,e,n){let i=Date.now()+n*1e3,a={value:e,expiresAt:i};this.cache.set(t,a),this.saveManifest()}forget(t){this.cache.delete(t)&&this.saveManifest()}clear(){this.cache.clear(),this.saveManifest()}};var zt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},St={Warp:(r,t)=>`warp:${r}:${t}`,WarpAbi:(r,t)=>`warp-abi:${r}:${t}`,WarpExecutable:(r,t,e)=>`warp-exec:${r}:${t}:${e}`,RegistryInfo:(r,t)=>`registry-info:${r}:${t}`,Brand:(r,t)=>`brand:${r}:${t}`,Asset:(r,t,e)=>`asset:${r}:${t}:${e}`},ot=class{constructor(t,e){this.path=e,this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new at:t==="memory"?new st:t==="static"?new wt(this.path):t==="filesystem"?new Ct(this.path):typeof window<"u"&&window.localStorage?new at:new st}set(t,e,n){this.strategy.set(t,e,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var pt={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},kt={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},Gt=(r,t,e)=>{let n=r.find(a=>a.input.as===t||a.input.name===t);if(!n?.value)return null;let[,i]=e.stringToNative(n.value);return typeof i=="string"?i:String(i)},_t=r=>{try{return JSON.parse(r)}catch{return null}},br=async(r,t,e,n,i,a)=>{let s=new Headers;if(s.set("Content-Type","application/json"),s.set("Accept","application/json"),a&&n){let{message:c,nonce:o,expiresAt:u}=await At(n,`${e.chain.name}-adapter`),d=await a({message:c,chain:e.chain});d&&Object.entries(xt(n,d,o,u)).forEach(([h,m])=>s.set(h,m))}let p=Gt(e.resolvedInputs,pt.Headers,i);if(p){let c=_t(p);c&&typeof c=="object"&&Object.entries(c).forEach(([o,u])=>typeof u=="string"&&s.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([c,o])=>{s.set(c,r.applyInputs(o,e.resolvedInputs,i))});return s},Er=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===kt.Get){let s=Gt(e.resolvedInputs,pt.Queries,i);if(s){let p=_t(s);if(p&&typeof p=="object"){let c=new URL(a);Object.entries(p).forEach(([o,u])=>u!=null&&c.searchParams.set(o,String(u))),a=c.toString()}}}return a},Rr=(r,t,e,n,i)=>{if(r===kt.Get)return;let a=Gt(t.resolvedInputs,pt.Payload,n);if(a&&_t(a)!==null)return a;let{[pt.Payload]:s,[pt.Queries]:p,...c}=e;return JSON.stringify({...c,...i})},We=async(r,t,e,n,i,a,s,p)=>{let c=t.method||kt.Get,o=await br(r,t,e,n,a,p),u=Er(r,t,e,c,a),d=Rr(c,e,i,a,s);return{url:u,method:c,headers:o,body:d}};var E=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e);return await this.applyGlobals(n)}async applyGlobals(t){let e={...t};return e.actions=await Promise.all((e.actions||[]).map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e),e}applyVars(t,e={}){if(!t?.vars)return t;let n=P(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,p)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(t.vars).forEach(([s,p])=>{if(typeof p!="string")a(s,p);else if(p.startsWith(l.Vars.Query+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Query.length+1),[o,u]=c.split(l.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,m=e.queries?.[o]||null||d;m&&a(s,m)}else if(p.startsWith(l.Vars.Env+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Env.length+1),[o,u]=c.split(l.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h&&a(s,h)}else p===l.Source.UserWallet&&n?a(s,n):a(s,p)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(l.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}async applyActionGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(l.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}applyInputs(t,e,n,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let a=this.applyGlobalsToText(t),s=this.buildInputBag(e,n,i);return V(a,s)}applyGlobalsToText(t){if(!Object.values(l.Globals).map(s=>s.Placeholder).some(s=>t.includes(`{{${s}}}`)||t.includes(`{{${s}:`)))return t;let i={config:this.config,adapter:this.adapter},a=t;return Object.values(l.Globals).forEach(s=>{let p=s.Accessor(i);p!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),p.toString())),a=this.replacePlaceholdersWithChain(a,s.Placeholder,i,s.Accessor)}),a}replacePlaceholdersWithChain(t,e,n,i){let a=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(a,(s,p)=>{let c=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=v(c,this.adapters),u={config:this.config,adapter:o},d=i(u);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e,n){let i={};return t.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);i[s]=String(p)}),n&&n.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);if(i[`primary.${s}`]=String(p),a.input.type==="asset"&&typeof a.input.position=="object"){let c=p;c&&typeof c=="object"&&"identifier"in c&&"amount"in c&&(i[`primary.${s}.token`]=String(c.identifier),i[`primary.${s}.amount`]=String(c.amount))}}),i}};var q=class{constructor(t,e){this.config=t;this.adapters=e;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new w,this.cache=new ot(t.cache?.type,t.cache?.path)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,e,n){let i=this.cache.get(St.WarpExecutable(t,e||"",n))||[];return B(i)}async createExecutable(t,e,n,i={}){let a=b(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=v(s.name,this.adapters),c=new E(this.config,p,this.adapters),o=await c.apply(t,i),u=b(o,e),{action:d,index:h}=$(o),m=this.getStringTypedInputs(d,n),W=await this.getResolvedInputs(s.name,d,m,c),f=await this.getModifiedInputs(W),y=[],A=[];h===e-1?(y=W,A=f):this.requiresPayloadInputs(u)&&(y=await this.resolveActionInputs(s.name,u,n,c),A=await this.getModifiedInputs(y));let T=A.find(S=>S.input.position==="receiver"||S.input.position==="destination")?.value,R=this.getDestinationFromAction(u),x=T?this.serializer.stringToNative(T)[1]:R;if(x&&(x=c.applyInputs(x,A,this.serializer,f)),!x&&a.type!=="collect"&&a.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let z=this.getPreparedArgs(u,A);z=z.map(S=>c.applyInputs(S,A,this.serializer,f));let k=A.find(S=>S.input.position==="value")?.value||null,N="value"in u?u.value:null,O=k?.split(l.ArgParamsSeparator)[1]||N||"0",X=c.applyInputs(O,A,this.serializer,f),ve=BigInt(X),Ae=A.filter(S=>S.input.position==="transfer"&&S.value).map(S=>S.value),xe=[...("transfers"in u?u.transfers:[])||[],...Ae||[]].map(S=>{let Se=c.applyInputs(S,A,this.serializer,f);return this.serializer.stringToNative(Se)[1]}),Ce=A.find(S=>S.input.position==="data")?.value,we="data"in u?u.data||"":null,Kt=Ce||we||null,Ie=Kt?c.applyInputs(Kt,A,this.serializer,f):null,Xt={adapter:p,warp:o,chain:s,action:e,destination:x,args:z,value:ve,transfers:xe,data:Ie,resolvedInputs:A};return this.cache.set(St.WarpExecutable(this.config.env,o.meta?.hash||"",e),Xt.resolvedInputs,zt.OneWeek),Xt}async getChainInfoForWarp(t,e){if(t.chain)return v(t.chain,this.adapters).chainInfo;if(e){let i=await this.tryGetChainFromInputs(t,e);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,e){let n=t.inputs||[];return e.map((i,a)=>{let s=n[a];return!s||i.includes(l.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i){let a=e.inputs||[],s=await Promise.all(n.map(c=>this.preprocessInput(t,c))),p=(c,o)=>{if(c.source==="query"){let u=this.url.searchParams.get(c.name);return u?this.serializer.nativeToString(c.type,u):null}else if(c.source===l.Source.UserWallet){let u=P(this.config,t);return u?this.serializer.nativeToString("address",u):null}else if(c.source==="hidden"){if(c.default===void 0)return null;let u=i?i.applyInputs(String(c.default),[],this.serializer):String(c.default);return this.serializer.nativeToString(c.type,u)}else return s[o]||null};return a.map((c,o)=>{let u=p(c,o),d=c.default!==void 0?i?i.applyInputs(String(c.default),[],this.serializer):String(c.default):void 0;return{input:c,value:u||(d!==void 0?this.serializer.nativeToString(c.type,d):null)}})}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,n,i){let a=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,a,i)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,a]=i.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(t.find(o=>o.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let c=Y(p,+s);e.push({...i,value:`${i.input.type}:${c}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=Y(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(l.Transform.Prefix)){let a=i.input.modifier.substring(l.Transform.Prefix.length),s=this.config.transform?.runner;if(!s||typeof s.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=this.buildInputContext(t,n,i),c=await s.run(a,p);if(c==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,c);e.push({...i,value:o})}}else e.push(i)}return e}buildInputContext(t,e,n){let i={};for(let a=0;a<e;a++){let s=t[a];if(!s.value)continue;let p=s.input.as||s.input.name,[,c]=this.serializer.stringToNative(s.value);if(i[p]=c,s.input.type==="asset"&&typeof c=="object"&&c!==null){let o=c;"identifier"in o&&"amount"in o&&(i[`${p}.token`]=String(o.identifier),i[`${p}.amount`]=String(o.amount),i[`${p}.identifier`]=String(o.identifier))}}if(n&&n.value){let a=n.input.as||n.input.name,[,s]=this.serializer.stringToNative(n.value);if(i[a]=s,n.input.type==="asset"&&typeof s=="object"&&s!==null){let p=s;"identifier"in p&&"amount"in p&&(i[`${a}.token`]=String(p.identifier),i[`${a}.amount`]=String(p.amount),i[`${a}.identifier`]=String(p.identifier))}}return i}async preprocessInput(t,e){try{let[n,i]=yt(e),a=v(t,this.adapters);if(n==="asset"){let[s,p,c]=i.split(l.ArgCompositeSeparator);if(c)return e;let o=await a.dataLoader.getAsset(s);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let u=Y(p,o.decimals);return jt({...o,amount:u})}else return e}catch(n){throw C.warn("WarpFactory: Preprocess input failed",n),n}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,e){let n="args"in t?t.args||[]:[],i=[];return e.forEach(({input:a,value:s})=>{if(!(!s||!a.position)){if(typeof a.position=="object"){if(a.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${a.name}" has type "${a.type}"`);if(!a.position.token?.startsWith("arg:")||!a.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${a.name}"`);let[p,c]=this.serializer.stringToNative(s),o=c;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let u=Number(a.position.token.split(":")[1])-1,d=Number(a.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",o.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",o.amount)})}else if(a.position.startsWith("arg:")){let p=Number(a.position.split(":")[1])-1;i.push({index:p,value:s})}}}),i.forEach(({index:a,value:s})=>{for(;n.length<=a;)n.push(void 0);n[a]=s}),n.filter(a=>a!==void 0)}async tryGetChainFromInputs(t,e){let n=t.actions.find(c=>c.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(c=>c.position==="chain");if(i===-1||i===void 0)return null;let a=e[i];if(!a)throw new Error("Chain input not found");let s=this.serializer.stringToNative(a)[1];return v(s,this.adapters).chainInfo}};var ct=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new q(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],{action:c,index:o}=$(t);for(let u=1;u<=t.actions.length;u++){let d=b(t,u);if(!ht(d,t))continue;let{tx:h,chain:m,immediateExecution:W,executable:f}=await this.executeAction(t,u,e,n);h&&i.push(h),m&&(a=m),W&&s.push(W),f&&u===o+1&&f.resolvedInputs&&(p=B(f.resolvedInputs))}if(!a&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&s.length>0){let u=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(u))}return{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p}}async executeAction(t,e,n,i={}){let a=b(t,e);if(a.type==="link")return a.when&&!await this.evaluateWhenCondition(t,a,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):Pt.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let o=await this.executePrompt(t,a,e,n,i);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:null};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,executable:null}}}let s=await this.factory.createExecutable(t,e,n,i);if(a.when&&!await this.evaluateWhenCondition(t,a,n,i,s.resolvedInputs,s.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="collect"){let o=await this.executeCollect(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="mcp"){let o=await this.executeMcp(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,executable:s}}}let p=v(s.chain.name,this.adapters);if(a.type==="query"){let o=await p.executor.executeQuery(s);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.chain,execution:o,tx:null}));else{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,result:o})}return{tx:null,chain:s.chain,immediateExecution:o,executable:s}}return{tx:await p.executor.createTransaction(s),chain:s.chain,immediateExecution:null,executable:s}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=v(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!ht(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let c=e[p],o=p+1;if(!c){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),h={status:"error",warp:t,action:o,user:P(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,o,c);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:u,tx:c})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).filter(s=>s!==null);if(a.every(s=>s.status==="success")){let s=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(s))}else{let s=a.find(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let n=P(this.config,t.chain.name),i=b(t.warp,t.action),a=this.factory.getSerializer(),s=rt(t.resolvedInputs,a);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,n,s,e);let{values:p,output:c}=await nt(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,c)}async doHttpRequest(t,e,n,i,a){let s=new E(this.config,v(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:c,method:o,headers:u,body:d}=await We(s,e,t,n,i,p,a,async h=>await this.callHandler(()=>this.handlers?.onSignRequest?.(h)));C.debug("WarpExecutor: Executing HTTP collect",{url:c,method:o,headers:u,body:d});try{let m=await fetch(c,{method:o,headers:u,body:d});C.debug("Collect response status",{status:m.status}),m.status===402&&(m=await Dt(m,c,o,d,this.adapters));let W=await m.json();C.debug("Collect response content",{content:W});let{values:f,output:y}=await nt(t.warp,W,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,P(this.config,t.chain.name),m.ok?"success":"error",f,y,W)}catch(h){C.error("WarpActionExecutor: Error executing collect",h);let m=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:h},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=P(this.config,t.chain.name),i=b(t.warp,t.action);if(!i.destination){let m=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let W=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("Please install @modelcontextprotocol/sdk to execute MCP warps or mcp actions")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}let p=this.factory.getSerializer(),c=new E(this.config,v(t.chain.name,this.adapters),this.adapters),o=i.destination,u=c.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=c.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([m,W])=>{let f=c.applyInputs(W,t.resolvedInputs,this.factory.getSerializer());h[m]=f}),C.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:h});try{let m=new s(new URL(u),{requestInit:{headers:h}}),W=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await W.connect(m);let f={};t.resolvedInputs.forEach(({input:x,value:z})=>{if(z&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let k=x.position.replace("payload:",""),[N,O]=p.stringToNative(z);if(N==="string")f[k]=String(O);else if(N==="bool")f[k]=!!O;else if(N==="uint8"||N==="uint16"||N==="uint32"||N==="uint64"||N==="uint128"||N==="uint256"||N==="biguint"){let X=Number(O);f[k]=(Number.isInteger(X),X)}else f[k]=O}}),e&&Object.assign(f,e);let y=await W.callTool({name:d,arguments:f});await W.close();let A;if(y.content&&y.content.length>0){let x=y.content[0];if(x.type==="text")try{A=JSON.parse(x.text)}catch{A=x.text}else x.type,A=x}else A=y;let{values:T,output:R}=await nt(t.warp,A,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",T,R,y)}catch(m){C.error("WarpExecutor: Error executing MCP",m);let W=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:m},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}}buildCollectResult(t,e,n,i,a,s){let p=vt(this.config,this.adapters,t.warp,t.action,a),c=B(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||P(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:Wt(t.warp,a,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:c}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=v(s.name,this.adapters),c=new E(this.config,p,this.adapters),o=await c.apply(t,a),u=b(o,n),{action:d}=$(o),h=this.factory.getStringTypedInputs(d,i),m=await this.factory.getResolvedInputs(s.name,d,h,c),W=await this.factory.getModifiedInputs(m),f=W;if(e.inputs&&e.inputs.length>0){let R=this.factory.getStringTypedInputs(e,i),x=await this.factory.getResolvedInputs(s.name,e,R,c);f=await this.factory.getModifiedInputs(x)}let y=c.applyInputs(u.prompt,f,this.factory.getSerializer(),W),A=B(f),T=P(this.config,s.name);return{status:"success",warp:o,action:n,user:T,txHash:null,tx:null,next:vt(this.config,this.adapters,o,n,{prompt:y}),values:{string:[y],native:[y],mapped:{prompt:y}},output:{prompt:y},messages:Wt(o,{prompt:y},this.config),destination:null,resolvedInputs:A}}catch(s){return C.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:s},messages:{},destination:null,resolvedInputs:[]}}}async evaluateWhenCondition(t,e,n,i,a,s){if(!e.when)return!0;let p=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),c=v(p.name,this.adapters),o=new E(this.config,c,this.adapters),{action:u}=$(t),d=this.factory.getStringTypedInputs(u,n),h=await this.factory.getResolvedInputs(p.name,u,d,o),m=await this.factory.getModifiedInputs(h),W;if(a)W=a;else{let A=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o);W=await this.factory.getModifiedInputs(A)}let f=o.buildInputBag(W,this.factory.getSerializer(),m),y=Nt(e.when,f);return Bt(y)}};var lt=class{constructor(t){this.config=t}async search(t,e,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw C.error("WarpIndex: Error searching for warps: ",i),i}}};var ut=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!_(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(o=>o[0]).filter(o=>this.isValid(o)).map(o=>this.detect(o)),s=(await Promise.all(i)).filter(o=>o.match),p=s.length>0,c=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:c}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?_(t):H(t);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,c=null,o=null,u=v(i.chain,this.adapters),d=t.startsWith(l.HttpProtocolPrefix)?$t(t):Ht(i.identifier);if(a==="hash"){p=await u.builder().createFromTransactionHash(s,e);let f=await u.registry.getInfoByHash(s,e);c=f.registryInfo,o=f.brand}else if(a==="alias"){let f=await u.registry.getInfoByAlias(s,e);c=f.registryInfo,o=f.brand,f.registryInfo&&(p=await u.builder().createFromTransactionHash(f.registryInfo.hash,e))}if(p&&p.meta&&(Nr(p,u.chainInfo.name,c,i.identifier),p.meta.query=d),!p)return n;let h=p.chain||u.chainInfo.name,m=v(h,this.adapters),W=await new E(this.config,m,this.adapters).apply(p);return{match:!0,url:t,warp:W,chain:h,registryInfo:c,brand:o}}catch(a){return C.error("Error detecting warp link",a),n}}},Nr=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?mt(t,"alias",e.alias):mt(t,"hash",e?.hash??n))};var Jt=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config))}getConfig(){return this.config}createExecutor(t){return new ct(this.config,this.chains,t)}async detectWarp(t,e){return new ut(this.config,this.chains).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),p=a?t:null;if(!p&&s){let W=await fetch(t);if(!W.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await W.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let c=this.createExecutor(n),{txs:o,chain:u,immediateExecutions:d,resolvedInputs:h}=await c.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async W=>{await c.evaluateOutput(p,W)},resolvedInputs:h}}async createInscriptionTransaction(t,e){return await v(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return v(t,this.chains).builder().createFromTransaction(e,n)}async createFromTransactionHash(t,e){let n=H(t);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return v(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!P(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return v(t,this.chains).wallet.signMessage(e)}async getActions(t,e,n=!1){let i=this.getDataLoader(t);return(await Promise.all(e.map(async s=>i.getAction(s,n)))).filter(s=>s!==null)}getExplorer(t){return v(t,this.chains).explorer}getOutput(t){return v(t,this.chains).output}async getRegistry(t){let e=v(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return v(t,this.chains).dataLoader}getWallet(t){return v(t,this.chains).wallet}get factory(){return new q(this.config,this.chains)}get index(){return new lt(this.config)}get linkBuilder(){return new L(this.config,this.chains)}createBuilder(t){return v(t,this.chains).builder()}createAbiBuilder(t){return v(t,this.chains).abiBuilder()}createBrandBuilder(t){return v(t,this.chains).brandBuilder()}createSerializer(t){return v(t,this.chains).serializer}resolveText(t){return tt(t,this.config)}};var Qt=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};0&&(module.exports={BrowserCryptoProvider,CacheTtl,NodeCryptoProvider,WARP_LANGUAGES,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createDefaultWalletProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpChainAssetLogoUrl,getWarpChainInfoLogoUrl,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletExternalId,getWarpWalletExternalIdFromConfig,getWarpWalletExternalIdFromConfigOrFail,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,handleX402Payment,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isWarpActionAutoExecute,isWarpI18nText,isWarpWalletReadOnly,mergeNestedPayload,normalizeAndValidateMnemonic,normalizeMnemonic,option,parseOutputOutIndex,parseSignedMessage,replacePlaceholders,replacePlaceholdersInWhenExpression,resolveWarpText,safeWindow,setCryptoProvider,setWarpWalletInConfig,shiftBigintBy,splitInput,string,struct,testCryptoAvailability,toInputPayloadValue,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateMnemonicLength,validateSignedMessage,vector,withAdapterFallback});
1
+ "use strict";var Pe=Object.create;var ft=Object.defineProperty;var be=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var Ee=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var Ne=(r,t)=>{for(var e in t)ft(r,e,{get:t[e],enumerable:!0})},Zt=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Te(t))!Re.call(r,i)&&i!==e&&ft(r,i,{get:()=>t[i],enumerable:!(n=be(t,i))||n.enumerable});return r};var G=(r,t,e)=>(e=r!=null?Pe(Ee(r)):{},Zt(t||!r||!r.__esModule?ft(e,"default",{value:r,enumerable:!0}):e,r)),Be=r=>Zt(ft({},"__esModule",{value:!0}),r);var Br={};Ne(Br,{BrowserCryptoProvider:()=>gt,CacheTtl:()=>zt,NodeCryptoProvider:()=>ht,WARP_LANGUAGES:()=>qe,WarpBrandBuilder:()=>Mt,WarpBuilder:()=>qt,WarpCache:()=>pt,WarpCacheKey:()=>Pt,WarpChainName:()=>Yt,WarpClient:()=>Jt,WarpConfig:()=>F,WarpConstants:()=>l,WarpExecutor:()=>lt,WarpFactory:()=>q,WarpIndex:()=>ut,WarpInputTypes:()=>g,WarpInterpolator:()=>E,WarpLinkBuilder:()=>L,WarpLinkDetecter:()=>dt,WarpLogger:()=>x,WarpProtocolVersions:()=>D,WarpSerializer:()=>w,WarpTypeRegistry:()=>Qt,WarpValidator:()=>it,address:()=>xr,applyOutputToMessages:()=>vt,asset:()=>Lt,biguint:()=>Ar,bool:()=>Cr,buildMappedOutput:()=>rt,buildNestedPayload:()=>ne,bytesToBase64:()=>De,bytesToHex:()=>te,cleanWarpIdentifier:()=>et,createAuthHeaders:()=>xt,createAuthMessage:()=>Ct,createCryptoProvider:()=>Le,createDefaultWalletProvider:()=>dr,createHttpAuthHeaders:()=>er,createSignableMessage:()=>oe,createWarpI18nText:()=>ke,createWarpIdentifier:()=>yt,evaluateOutputCommon:()=>ae,evaluateWhenCondition:()=>$t,extractCollectOutput:()=>nt,extractIdentifierInfoFromUrl:()=>_,extractQueryStringFromIdentifier:()=>Ot,extractQueryStringFromUrl:()=>Ht,extractResolvedInputValues:()=>B,extractWarpSecrets:()=>Me,findWarpAdapterForChain:()=>v,getCryptoProvider:()=>Tt,getEventNameFromWarp:()=>He,getLatestProtocolIdentifier:()=>Z,getNextInfo:()=>At,getProviderConfig:()=>tr,getRandomBytes:()=>Et,getRandomHex:()=>Rt,getWalletFromConfigOrFail:()=>ir,getWarpActionByIndex:()=>T,getWarpBrandLogoUrl:()=>Oe,getWarpChainAssetLogoUrl:()=>Fe,getWarpChainInfoLogoUrl:()=>Ve,getWarpInfoFromIdentifier:()=>H,getWarpPrimaryAction:()=>$,getWarpWalletAddress:()=>pe,getWarpWalletAddressFromConfig:()=>P,getWarpWalletExternalId:()=>ue,getWarpWalletExternalIdFromConfig:()=>de,getWarpWalletExternalIdFromConfigOrFail:()=>or,getWarpWalletMnemonic:()=>le,getWarpWalletMnemonicFromConfig:()=>sr,getWarpWalletPrivateKey:()=>ce,getWarpWalletPrivateKeyFromConfig:()=>ar,handleX402Payment:()=>jt,hasInputPrefix:()=>Qe,hex:()=>wr,initializeWalletCache:()=>ur,isEqualWarpIdentifier:()=>Ge,isWarpActionAutoExecute:()=>mt,isWarpI18nText:()=>ze,isWarpWalletReadOnly:()=>pr,mergeNestedPayload:()=>Vt,normalizeAndValidateMnemonic:()=>lr,normalizeMnemonic:()=>fe,option:()=>Ir,parseOutputOutIndex:()=>se,parseSignedMessage:()=>nr,replacePlaceholders:()=>V,replacePlaceholdersInWhenExpression:()=>Bt,resolveWarpText:()=>tt,safeWindow:()=>bt,setCryptoProvider:()=>Ue,setWarpWalletInConfig:()=>cr,shiftBigintBy:()=>Y,splitInput:()=>Wt,string:()=>hr,struct:()=>Pr,testCryptoAvailability:()=>je,toInputPayloadValue:()=>ie,toPreviewText:()=>Nt,tuple:()=>Sr,uint16:()=>yr,uint32:()=>Wr,uint64:()=>vr,uint8:()=>mr,validateMnemonicLength:()=>ge,validateSignedMessage:()=>rr,vector:()=>br,withAdapterFallback:()=>$e});module.exports=Be(Br);var Yt=(d=>(d.Multiversx="multiversx",d.Vibechain="vibechain",d.Sui="sui",d.Ethereum="ethereum",d.Base="base",d.Arbitrum="arbitrum",d.Polygon="polygon",d.Somnia="somnia",d.Fastset="fastset",d.Solana="solana",d.Near="near",d))(Yt||{}),l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>r.config.user?.wallets?.[r.adapter.chainInfo.name]},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:r=>{if(!r.adapter.wallet)return null;try{return r.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:r=>r.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:r=>r.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},g={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},bt=typeof window<"u"?window:{open:()=>{}};var D={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},F={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${D.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${D.Brand}.schema.json`,DefaultClientUrl:r=>r==="devnet"?"https://devnet.usewarp.to":r==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",l.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var $e=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var He=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=l.Alerts.TriggerEventPrefix+l.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var Oe=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},Fe=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]},Ve=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var gt=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(t);return window.crypto.getRandomValues(e),e}},ht=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(t))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},j=null;function Tt(){if(j)return j;if(typeof window<"u"&&window.crypto)return j=new gt,j;if(typeof process<"u"&&process.versions?.node)return j=new ht,j;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Ue(r){j=r}async function Et(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Tt()).getRandomBytes(r)}function te(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(r.length*2);for(let e=0;e<r.length;e++){let n=r[e];t[e*2]=(n>>>4).toString(16),t[e*2+1]=(n&15).toString(16)}return t.join("")}function De(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(r).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(r));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function Rt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Et(r/2,t);return te(e)}async function je(){let r={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?r.environment="browser":typeof process<"u"&&process.versions?.node&&(r.environment="nodejs"),await Et(16),r.randomBytes=!0}catch{}return r}function Le(){return Tt()}var Me=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${l.Vars.Env}:`)).map(t=>{let e=t.replace(`${l.Vars.Env}:`,"").trim(),[n,i]=e.split(l.ArgCompositeSeparator);return{key:n,description:i||null}});var v=(r,t)=>{let e=t.find(n=>n.chainInfo.name.toLowerCase()===r.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${r}`);return e},Z=r=>{if(r==="warp")return`warp:${D.Warp}`;if(r==="brand")return`brand:${D.Brand}`;if(r==="abi")return`abi:${D.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},T=(r,t)=>r?.actions[t-1],$=r=>{if(r.actions.length===0)throw new Error(`Warp has no primary action: ${r.meta?.identifier}`);let t=r.actions.find(a=>a.primary===!0);if(t)return{action:t,index:r.actions.indexOf(t)};let e=["transfer","contract","query","collect","mcp"],n=r.actions.find(a=>e.includes(a.type));return n?{action:n,index:r.actions.indexOf(n)}:{action:r.actions[0],index:0}},mt=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=$(t);return r===e}return!0},Y=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(a,"0"));if(t<0){let s=n+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},Nt=(r,t=100)=>{if(!r)return"";let e=r.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},V=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>t[n]||""),Bt=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),$t=r=>{if(!r||typeof r!="string")return!0;try{return!!new Function(`return ${r}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${r}. Error: ${t}`)}};var qe={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},tt=(r,t)=>{let e=t?.preferences?.locale||"en";if(typeof r=="string")return r;if(typeof r=="object"&&r!==null){if(e in r)return r[e];if("en"in r)return r.en;let n=Object.keys(r);if(n.length>0)return r[n[0]]}return""},ze=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,ke=r=>r;var et=r=>r.startsWith(l.IdentifierAliasMarker)?r.replace(l.IdentifierAliasMarker,""):r,Ge=(r,t)=>!r||!t?!1:et(r)===et(t),yt=(r,t,e)=>{let n=et(e);return t===l.IdentifierType.Alias?l.IdentifierAliasMarker+r+l.IdentifierParamSeparator+n:r+l.IdentifierParamSeparator+t+l.IdentifierParamSeparator+n},H=r=>{let t=decodeURIComponent(r).trim(),e=et(t),n=e.split("?")[0],i=ee(n);if(n.length===64&&/^[a-fA-F0-9]+$/.test(n))return{chain:l.IdentifierChainDefault,type:l.IdentifierType.Hash,identifier:e,identifierBase:n};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[a,s,p]=i;if(s===l.IdentifierType.Alias||s===l.IdentifierType.Hash){let c=e.includes("?")?p+e.substring(e.indexOf("?")):p;return{chain:a,type:s,identifier:c,identifierBase:p}}}if(i.length===2){let[a,s]=i;if(a===l.IdentifierType.Alias||a===l.IdentifierType.Hash){let p=e.includes("?")?s+e.substring(e.indexOf("?")):s;return{chain:l.IdentifierChainDefault,type:a,identifier:p,identifierBase:s}}}if(i.length===2){let[a,s]=i;if(a!==l.IdentifierType.Alias&&a!==l.IdentifierType.Hash){let p=e.includes("?")?s+e.substring(e.indexOf("?")):s,c=_e(s,a)?l.IdentifierType.Hash:l.IdentifierType.Alias;return{chain:a,type:c,identifier:p,identifierBase:s}}}return{chain:l.IdentifierChainDefault,type:l.IdentifierType.Alias,identifier:e,identifierBase:n}},_=r=>{let t=new URL(r),n=t.searchParams.get(l.IdentifierParamName);if(n||(n=t.pathname.split("/")[1]),!n)return null;let i=decodeURIComponent(n);return H(i)},_e=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,Je=r=>{let t=l.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},ee=r=>{let t=Je(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=ee(a);return[i,...s]},Ht=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(l.IdentifierParamName),e.toString()||null}catch{return null}},Ot=r=>{let t=r.indexOf("?");if(t===-1||t===r.length-1)return null;let e=r.substring(t+1);return e.length>0?e:null};var Wt=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},Qe=r=>{let t=new Set(Object.values(g));if(!r.includes(l.ArgParamsSeparator))return!1;let e=Wt(r)[0];return t.has(e)};var vt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=tt(a,e);return[i,V(s,t)]});return Object.fromEntries(n)};var re=G(require("qr-code-styling"),1);var L=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!_(t):!1}build(t,e,n){let i=this.config.clientUrl||F.DefaultClientUrl(this.config.env),a=v(t,this.adapters),s=e===l.IdentifierType.Alias?n:e+l.IdentifierParamSeparator+n,p=a.chainInfo.name+l.IdentifierParamSeparator+s,c=encodeURIComponent(p);return F.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${l.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let e=H(t);if(!e)return null;let n=v(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,a="white",s="black",p="#23F7DD"){let c=v(t,this.adapters),o=this.build(c.chainInfo.name,e,n);return new re.default({type:"svg",width:i,height:i,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(p)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Ke="https://",At=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith(Ke))return[{identifier:null,url:a}];let[s,p]=a.split("?");if(!p){let f=V(s,{...e.vars,...i});return[{identifier:f,url:Ft(t,f,r)}]}let c=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let f=V(p,{...e.vars,...i}),y=f?`${s}?${f}`:s;return[{identifier:y,url:Ft(t,y,r)}]}let o=c[0];if(!o)return[];let u=o.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let h=Array.isArray(i[d])?i[d]:[i[d]];if(h.length===0)return[];let m=c.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let y=f.match(/\[\](\.[^}]+)?}}/),A=y&&y[1]||"";return{placeholder:f,field:A?A.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let y=p;for(let{regex:b,field:R}of m){let C=R?Xe(f,R):f;if(C==null)return null;y=y.replace(b,C)}if(y.includes("{{")||y.includes("}}"))return null;let A=y?`${s}?${y}`:s;return{identifier:A,url:Ft(t,A,r)}}).filter(f=>f!==null)},Ft=(r,t,e)=>{let[n,i]=t.split("?"),a=H(n)||{chain:l.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},s=v(a.chain,r);if(!s)throw new Error(`Adapter not found for chain ${a.chain}`);let p=new L(e,r).build(s.chainInfo.name,a.type,a.identifierBase);if(!i)return p;let c=new URL(p);return new URLSearchParams(i).forEach((o,u)=>c.searchParams.set(u,o)),c.toString().replace(/\/\?/,"?")},Xe=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var M=class M{static debug(...t){M.isTestEnv||console.debug(...t)}static info(...t){M.isTestEnv||console.info(...t)}static warn(...t){M.isTestEnv||console.warn(...t)}static error(...t){M.isTestEnv||console.error(...t)}};M.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var x=M;function ne(r,t,e){return r.startsWith(l.Position.Payload)?r.slice(l.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function Vt(r,t){if(!r)return{...t};if(!t)return{...r};let e={...r};return Object.keys(t).forEach(n=>{e[n]&&typeof e[n]=="object"&&typeof t[n]=="object"?e[n]=Vt(e[n],t[n]):e[n]=t[n]}),e}function ie(r,t){if(!r.value)return null;let e=t.stringToNative(r.value)[1];if(r.input.type==="biguint")return e.toString();if(r.input.type==="asset"){let{identifier:n,amount:i}=e;return{identifier:n,amount:i.toString()}}else return e}function B(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function rt(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,a=ie(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(l.Position.Payload)){let s=ne(n.input.position,i,a);e=Vt(e,s)}else e[i]=a}),e}var nt=async(r,t,e,n,i,a)=>{let s=[],p=[],c={};for(let[u,d]of Object.entries(r.output||{})){if(d.startsWith(l.Transform.Prefix))continue;let h=se(d);if(h!==null&&h!==e){c[u]=null;continue}let[m,...W]=d.split("."),f=(y,A)=>A.reduce((b,R)=>b&&b[R]!==void 0?b[R]:null,y);if(m==="out"||m.startsWith("out[")){let y=W.length===0?t?.data||t:f(t,W);s.push(String(y)),p.push(y),c[u]=y}else c[u]=d}let o=rt(n,i);return{values:{string:s,native:p,mapped:o},output:await ae(r,c,e,n,i,a)}},ae=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t};return s=Ze(s,r,e,n,i),s=await Ye(r,s,a.transform?.runner||null),s},Ze=(r,t,e,n,i)=>{let a={...r},s=T(t,e)?.inputs||[];for(let[p,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("in.")){let o=c.split(".")[1],u=s.findIndex(h=>h.as===o||h.name===o),d=u!==-1?n[u]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},Ye=async(r,t,e)=>{if(!r.output)return t;let n={...t},i=Object.entries(r.output).filter(([,a])=>a.startsWith(l.Transform.Prefix)).map(([a,s])=>({key:a,code:s.substring(l.Transform.Prefix.length)}));if(i.length>0&&(!e||typeof e.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:a,code:s}of i)try{n[a]=await e.run(s,n)}catch(p){x.error(`Transform error for output '${a}':`,p),n[a]=null}return n},se=r=>{if(r==="out")return 1;let t=r.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(r.startsWith("out.")||r.startsWith("event."),null)};var tr=(r,t,e,n)=>{let i=r.preferences?.providers?.[t];return i?.[e]?typeof i[e]=="string"?{url:i[e]}:i[e]:{url:n}};async function oe(r,t,e,n=5){let i=await Rt(64,e),a=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:r,nonce:i,expiresAt:a,purpose:t}),nonce:i,expiresAt:a}}async function Ct(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return oe(r,i,e,5)}function xt(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function er(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await Ct(r,e,n),p=await t(i);return xt(r,p,a,s)}function rr(r){let t=new Date(r).getTime();return Date.now()<t}function nr(r){try{let t=JSON.parse(r);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var ir=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},pe=r=>r?typeof r=="string"?r:r.address:null,P=(r,t)=>pe(r.user?.wallets?.[t]||null),ce=r=>r?typeof r=="string"?r:r.privateKey||null:null,le=r=>r?typeof r=="string"?r:r.mnemonic||null:null,ue=r=>r?typeof r=="string"?r:r.externalId||null:null,ar=(r,t)=>ce(r.user?.wallets?.[t]||null)?.trim()||null,sr=(r,t)=>le(r.user?.wallets?.[t]||null)?.trim()||null,de=(r,t)=>ue(r.user?.wallets?.[t]||null)?.trim()||null,or=(r,t)=>{let e=de(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},pr=r=>typeof r=="string",cr=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},fe=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},ge=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},lr=(r,t=24)=>{let e=fe(r);return ge(e,t),e};async function ur(r){let t={address:null,publicKey:null};if(!r)return t;try{t.address=await r.getAddress()}catch{}try{t.publicKey=await r.getPublicKey()}catch{}return t}function dr(r,t,e){return null}var Ut=require("@x402/core/client"),Dt=require("@x402/core/http");async function jt(r,t,e,n,i){let a=await fr(r,i);if(!a)return r;let s=new Headers;n&&s.set("Content-Type","application/json"),s.set("Accept","application/json"),Object.entries(a).forEach(([c,o])=>{s.set(c,o)}),x.debug("WarpExecutor: Retrying request with payment headers");let p=await fetch(t,{method:e,headers:s,body:n});return x.debug("WarpExecutor: Payment processed, new response status",{status:p.status}),p}var fr=async(r,t)=>{let e=await gr(r),i=new Dt.x402HTTPClient(new Ut.x402Client).getPaymentRequiredResponse(a=>r.headers.get(a),e);if(!i?.accepts?.length)return null;for(let a of t)if(a.wallet.registerX402Handlers)try{let s=new Ut.x402Client,p=await a.wallet.registerX402Handlers(s),c=i.accepts.find(h=>h?.network&&p[h.network]);if(!c?.network)continue;p[c.network]();let o=new Dt.x402HTTPClient(s),u=await o.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=o.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return x.debug(`WarpExecutor: x402 payment processed with ${a.chainInfo.name} adapter using ${c.network} scheme`),d}catch{continue}return null},gr=async r=>{try{let t=await r.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===g.Tuple&&Array.isArray(e)){if(e.length===0)return t+l.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(l.ArgCompositeSeparator)})${l.ArgParamsSeparator}${a.join(l.ArgListSeparator)}`}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===g.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,a=Object.keys(n).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${l.ArgParamsSeparator}`;let s=a.map(p=>{let[c,o]=this.getTypeAndValue(n[p]);return`(${p}${l.ArgParamsSeparator}${c})${o}`});return`${t}(${i})${l.ArgParamsSeparator}${s.join(l.ArgListSeparator)}`}if(t===g.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${l.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e[0],i=n.indexOf(l.ArgParamsSeparator),a=n.substring(0,i),s=e.map(c=>{let o=c.indexOf(l.ArgParamsSeparator),u=c.substring(o+1);return a.startsWith(g.Tuple)?u.replace(l.ArgListSeparator,l.ArgCompositeSeparator):u}),p=a.startsWith(g.Struct)?l.ArgStructSeparator:l.ArgListSeparator;return t+l.ArgParamsSeparator+a+l.ArgParamsSeparator+s.join(p)}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===g.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?g.Asset+l.ArgParamsSeparator+e.identifier+l.ArgCompositeSeparator+String(e.amount)+l.ArgCompositeSeparator+String(e.decimals):g.Asset+l.ArgParamsSeparator+e.identifier+l.ArgCompositeSeparator+String(e.amount);if(this.typeRegistry){let n=this.typeRegistry.getHandler(t);if(n)return n.nativeToString(e);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,e)}return t+l.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(l.ArgParamsSeparator),n=e[0],i=e.slice(1).join(l.ArgParamsSeparator);if(n==="null")return[n,null];if(n===g.Option){let[a,s]=i.split(l.ArgParamsSeparator);return[g.Option+l.ArgParamsSeparator+a,s||null]}if(n===g.Vector){let a=i.indexOf(l.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),c=s.startsWith(g.Struct)?l.ArgStructSeparator:l.ArgListSeparator,u=(p?p.split(c):[]).map(d=>this.stringToNative(s+l.ArgParamsSeparator+d)[1]);return[g.Vector+l.ArgParamsSeparator+s,u]}else if(n.startsWith(g.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),p=i.split(l.ArgCompositeSeparator).map((c,o)=>this.stringToNative(`${a[o]}${l.IdentifierParamSeparator}${c}`)[1]);return[n,p]}else if(n.startsWith(g.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:a[1]};return i&&i.split(l.ArgListSeparator).forEach(c=>{let o=c.match(new RegExp(`^\\(([^${l.ArgParamsSeparator}]+)${l.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,h]=o;p[u]=this.stringToNative(`${d}${l.IdentifierParamSeparator}${h}`)[1]}}),[n,p]}else{if(n===g.String)return[n,i];if(n===g.Uint8||n===g.Uint16||n===g.Uint32)return[n,Number(i)];if(n===g.Uint64||n===g.Uint128||n===g.Uint256||n===g.Biguint)return[n,BigInt(i||0)];if(n===g.Bool)return[n,i==="true"];if(n===g.Address)return[n,i];if(n===g.Hex)return[n,i];if(n===g.Asset){let[a,s]=i.split(l.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[n,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let p=a.stringToNative(i);return[n,p]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[p,c]=this.stringToNative(`${s}:${i}`);return[n,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(l.ArgParamsSeparator)){let[e,n]=t.split(l.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[g.Uint32,t]:typeof t=="bigint"?[g.Uint64,t]:typeof t=="boolean"?[g.Bool,t]:[typeof t,t]}};var hr=r=>new w().nativeToString(g.String,r),mr=r=>new w().nativeToString(g.Uint8,r),yr=r=>new w().nativeToString(g.Uint16,r),Wr=r=>new w().nativeToString(g.Uint32,r),vr=r=>new w().nativeToString(g.Uint64,r),Ar=r=>new w().nativeToString(g.Biguint,r),Cr=r=>new w().nativeToString(g.Bool,r),xr=r=>new w().nativeToString(g.Address,r),Lt=r=>new w().nativeToString(g.Asset,r),wr=r=>new w().nativeToString(g.Hex,r),Ir=(r,t)=>{if(t===null)return g.Option+l.ArgParamsSeparator;let e=r(t),n=e.indexOf(l.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return g.Option+l.ArgParamsSeparator+i+l.ArgParamsSeparator+a},Sr=(...r)=>new w().nativeToString(g.Tuple,r),Pr=r=>new w().nativeToString(g.Struct,r),br=r=>new w().nativeToString(g.Vector,r);var he=G(require("ajv"),1);var Mt=class{constructor(t){this.pendingBrand={protocol:Z("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.ensureValidSchema(n),n}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}ensureWarpText(t,e){if(!t)throw new Error(`Warp: ${e}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||F.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new he.default,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};var me=G(require("ajv"),1);var it=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validatePrimaryAction(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validatePrimaryAction(t){try{let{action:e}=$(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,a)=>{i&&Object.keys(i).forEach(s=>{s!==s.toUpperCase()&&e.push(`${a} name '${s}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(s=>s.type==="contract"),n=t.actions.some(s=>s.type==="query");if(!e&&!n)return[];let i=t.actions.some(s=>s.abi),a=Object.values(t.output||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.output&&!i&&a?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||F.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new me.default({strict:!1}),s=a.compile(i);return s(t)?[]:[`Schema validation failed: ${a.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var qt=class{constructor(t){this.config=t;this.pendingWarp={protocol:Z("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.validate(n),n}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}setOutput(t){return this.pendingWarp.output=t??void 0,this}async build(t=!0){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),t&&await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return Nt(t,e)}ensure(t,e){if(!t)throw new Error(e)}ensureWarpText(t,e){if(!t)throw new Error(e);if(typeof t=="object"&&!t.en)throw new Error(e)}async validate(t){let n=await new it(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
+ `))}};var I=require("fs"),K=require("path");var ye=new w,J=(r,t)=>typeof t=="bigint"?ye.nativeToString("biguint",t):t,Q=(r,t)=>typeof t=="string"&&t.startsWith(g.Biguint+":")?ye.stringToNative(t)[1]:t;var wt=class{constructor(t,e){let n=e?.path;this.cacheDir=n?(0,K.resolve)(n):(0,K.resolve)(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){(0,I.existsSync)(this.cacheDir)||(0,I.mkdirSync)(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return(0,K.join)(this.cacheDir,`${e}.json`)}get(t){try{let e=this.getFilePath(t);if(!(0,I.existsSync)(e))return null;let n=(0,I.readFileSync)(e,"utf-8"),i=JSON.parse(n,Q);return Date.now()>i.expiresAt?((0,I.unlinkSync)(e),null):i.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3},a=this.getFilePath(t);(0,I.writeFileSync)(a,JSON.stringify(i,J),"utf-8")}forget(t){try{let e=this.getFilePath(t);(0,I.existsSync)(e)&&(0,I.unlinkSync)(e)}catch{}}clear(){try{(0,I.readdirSync)(this.cacheDir).forEach(e=>{e.endsWith(".json")&&(0,I.unlinkSync)((0,K.join)(this.cacheDir,e))})}catch{}}};var at=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,Q);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,J))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var U=class U{constructor(t,e){}get(t){let e=U.cache.get(t);return e?Date.now()>e.expiresAt?(U.cache.delete(t),null):e.value:null}set(t,e,n){let i=Date.now()+n*1e3;U.cache.set(t,{value:e,expiresAt:i})}forget(t){U.cache.delete(t)}clear(){U.cache.clear()}};U.cache=new Map;var st=U;var St=require("fs"),ot=require("path");var It=class{constructor(t,e){this.manifestPath=this.resolveManifestPath(t,e),this.cache=this.loadManifest()}loadManifest(){try{let t=(0,St.readFileSync)(this.manifestPath,"utf-8");return new Map(Object.entries(JSON.parse(t,Q)))}catch{return new Map}}saveManifest(){let t=JSON.stringify(Object.fromEntries(this.cache.entries()),J);(0,St.writeFileSync)(this.manifestPath,t,"utf-8")}get(t){let e=this.cache.get(t);return!e||Date.now()>e.expiresAt?(e&&(this.cache.delete(t),this.saveManifest()),null):e.value}set(t,e,n){let i=Date.now()+n*1e3,a={value:e,expiresAt:i};this.cache.set(t,a),this.saveManifest()}forget(t){this.cache.delete(t)&&this.saveManifest()}clear(){this.cache.clear(),this.saveManifest()}resolveManifestPath(t,e){let n=e?.path;if(n){let i=(0,ot.resolve)(n),a=(0,ot.extname)(i);return`${a?i.slice(0,-a.length):i}-${t}${a||".json"}`}return(0,ot.resolve)(process.cwd(),`warps-manifest-${t}.json`)}};var zt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},Pt={Warp:(r,t)=>`warp:${r}:${t}`,WarpAbi:(r,t)=>`warp-abi:${r}:${t}`,WarpExecutable:(r,t,e)=>`warp-exec:${r}:${t}:${e}`,RegistryInfo:(r,t)=>`registry-info:${r}:${t}`,Brand:(r,t)=>`brand:${r}:${t}`,Asset:(r,t,e)=>`asset:${r}:${t}:${e}`},pt=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.type==="localStorage"?new at(t,e):e?.type==="memory"?new st(t,e):e?.type==="static"?new It(t,e):e?.type==="filesystem"?new wt(t,e):typeof window<"u"&&window.localStorage?new at(t,e):new st(t,e)}set(t,e,n){this.strategy.set(t,e,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var ct={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},kt={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},Gt=(r,t,e)=>{let n=r.find(a=>a.input.as===t||a.input.name===t);if(!n?.value)return null;let[,i]=e.stringToNative(n.value);return typeof i=="string"?i:String(i)},_t=r=>{try{return JSON.parse(r)}catch{return null}},Tr=async(r,t,e,n,i,a)=>{let s=new Headers;if(s.set("Content-Type","application/json"),s.set("Accept","application/json"),a&&n){let{message:c,nonce:o,expiresAt:u}=await Ct(n,`${e.chain.name}-adapter`),d=await a({message:c,chain:e.chain});d&&Object.entries(xt(n,d,o,u)).forEach(([h,m])=>s.set(h,m))}let p=Gt(e.resolvedInputs,ct.Headers,i);if(p){let c=_t(p);c&&typeof c=="object"&&Object.entries(c).forEach(([o,u])=>typeof u=="string"&&s.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([c,o])=>{s.set(c,r.applyInputs(o,e.resolvedInputs,i))});return s},Er=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===kt.Get){let s=Gt(e.resolvedInputs,ct.Queries,i);if(s){let p=_t(s);if(p&&typeof p=="object"){let c=new URL(a);Object.entries(p).forEach(([o,u])=>u!=null&&c.searchParams.set(o,String(u))),a=c.toString()}}}return a},Rr=(r,t,e,n,i)=>{if(r===kt.Get)return;let a=Gt(t.resolvedInputs,ct.Payload,n);if(a&&_t(a)!==null)return a;let{[ct.Payload]:s,[ct.Queries]:p,...c}=e;return JSON.stringify({...c,...i})},We=async(r,t,e,n,i,a,s,p)=>{let c=t.method||kt.Get,o=await Tr(r,t,e,n,a,p),u=Er(r,t,e,c,a),d=Rr(c,e,i,a,s);return{url:u,method:c,headers:o,body:d}};var E=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e);return await this.applyGlobals(n)}async applyGlobals(t){let e={...t};return e.actions=await Promise.all((e.actions||[]).map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e),e}applyVars(t,e={}){if(!t?.vars)return t;let n=P(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,p)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(t.vars).forEach(([s,p])=>{if(typeof p!="string")a(s,p);else if(p.startsWith(l.Vars.Query+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Query.length+1),[o,u]=c.split(l.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,m=e.queries?.[o]||null||d;m&&a(s,m)}else if(p.startsWith(l.Vars.Env+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Env.length+1),[o,u]=c.split(l.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h&&a(s,h)}else p===l.Source.UserWallet&&n?a(s,n):a(s,p)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(l.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}async applyActionGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(l.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}applyInputs(t,e,n,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let a=this.applyGlobalsToText(t),s=this.buildInputBag(e,n,i);return V(a,s)}applyGlobalsToText(t){if(!Object.values(l.Globals).map(s=>s.Placeholder).some(s=>t.includes(`{{${s}}}`)||t.includes(`{{${s}:`)))return t;let i={config:this.config,adapter:this.adapter},a=t;return Object.values(l.Globals).forEach(s=>{let p=s.Accessor(i);p!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),p.toString())),a=this.replacePlaceholdersWithChain(a,s.Placeholder,i,s.Accessor)}),a}replacePlaceholdersWithChain(t,e,n,i){let a=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(a,(s,p)=>{let c=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=v(c,this.adapters),u={config:this.config,adapter:o},d=i(u);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e,n){let i={};return t.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);i[s]=String(p)}),n&&n.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);if(i[`primary.${s}`]=String(p),a.input.type==="asset"&&typeof a.input.position=="object"){let c=p;c&&typeof c=="object"&&"identifier"in c&&"amount"in c&&(i[`primary.${s}.token`]=String(c.identifier),i[`primary.${s}.amount`]=String(c.amount))}}),i}};var q=class{constructor(t,e){this.config=t;this.adapters=e;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new w,this.cache=new pt(t.env,t.cache)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,e,n){let i=this.cache.get(Pt.WarpExecutable(t,e||"",n))||[];return B(i)}async createExecutable(t,e,n,i={}){let a=T(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=v(s.name,this.adapters),c=new E(this.config,p,this.adapters),o=await c.apply(t,i),u=T(o,e),{action:d,index:h}=$(o),m=this.getStringTypedInputs(d,n),W=await this.getResolvedInputs(s.name,d,m,c),f=await this.getModifiedInputs(W),y=[],A=[];h===e-1?(y=W,A=f):this.requiresPayloadInputs(u)&&(y=await this.resolveActionInputs(s.name,u,n,c),A=await this.getModifiedInputs(y));let b=A.find(S=>S.input.position==="receiver"||S.input.position==="destination")?.value,R=this.getDestinationFromAction(u),C=b?this.serializer.stringToNative(b)[1]:R;if(C&&(C=c.applyInputs(C,A,this.serializer,f)),!C&&a.type!=="collect"&&a.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let z=this.getPreparedArgs(u,A);z=z.map(S=>c.applyInputs(S,A,this.serializer,f));let k=A.find(S=>S.input.position==="value")?.value||null,N="value"in u?u.value:null,O=k?.split(l.ArgParamsSeparator)[1]||N||"0",X=c.applyInputs(O,A,this.serializer,f),ve=BigInt(X),Ae=A.filter(S=>S.input.position==="transfer"&&S.value).map(S=>S.value),Ce=[...("transfers"in u?u.transfers:[])||[],...Ae||[]].map(S=>{let Se=c.applyInputs(S,A,this.serializer,f);return this.serializer.stringToNative(Se)[1]}),xe=A.find(S=>S.input.position==="data")?.value,we="data"in u?u.data||"":null,Kt=xe||we||null,Ie=Kt?c.applyInputs(Kt,A,this.serializer,f):null,Xt={adapter:p,warp:o,chain:s,action:e,destination:C,args:z,value:ve,transfers:Ce,data:Ie,resolvedInputs:A};return this.cache.set(Pt.WarpExecutable(this.config.env,o.meta?.hash||"",e),Xt.resolvedInputs,zt.OneWeek),Xt}async getChainInfoForWarp(t,e){if(t.chain)return v(t.chain,this.adapters).chainInfo;if(e){let i=await this.tryGetChainFromInputs(t,e);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,e){let n=t.inputs||[];return e.map((i,a)=>{let s=n[a];return!s||i.includes(l.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i){let a=e.inputs||[],s=await Promise.all(n.map(c=>this.preprocessInput(t,c))),p=(c,o)=>{if(c.source==="query"){let u=this.url.searchParams.get(c.name);return u?this.serializer.nativeToString(c.type,u):null}else if(c.source===l.Source.UserWallet){let u=P(this.config,t);return u?this.serializer.nativeToString("address",u):null}else if(c.source==="hidden"){if(c.default===void 0)return null;let u=i?i.applyInputs(String(c.default),[],this.serializer):String(c.default);return this.serializer.nativeToString(c.type,u)}else return s[o]||null};return a.map((c,o)=>{let u=p(c,o),d=c.default!==void 0?i?i.applyInputs(String(c.default),[],this.serializer):String(c.default):void 0;return{input:c,value:u||(d!==void 0?this.serializer.nativeToString(c.type,d):null)}})}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,n,i){let a=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,a,i)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,a]=i.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(t.find(o=>o.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let c=Y(p,+s);e.push({...i,value:`${i.input.type}:${c}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=Y(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(l.Transform.Prefix)){let a=i.input.modifier.substring(l.Transform.Prefix.length),s=this.config.transform?.runner;if(!s||typeof s.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=this.buildInputContext(t,n,i),c=await s.run(a,p);if(c==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,c);e.push({...i,value:o})}}else e.push(i)}return e}buildInputContext(t,e,n){let i={};for(let a=0;a<e;a++){let s=t[a];if(!s.value)continue;let p=s.input.as||s.input.name,[,c]=this.serializer.stringToNative(s.value);if(i[p]=c,s.input.type==="asset"&&typeof c=="object"&&c!==null){let o=c;"identifier"in o&&"amount"in o&&(i[`${p}.token`]=String(o.identifier),i[`${p}.amount`]=String(o.amount),i[`${p}.identifier`]=String(o.identifier))}}if(n&&n.value){let a=n.input.as||n.input.name,[,s]=this.serializer.stringToNative(n.value);if(i[a]=s,n.input.type==="asset"&&typeof s=="object"&&s!==null){let p=s;"identifier"in p&&"amount"in p&&(i[`${a}.token`]=String(p.identifier),i[`${a}.amount`]=String(p.amount),i[`${a}.identifier`]=String(p.identifier))}}return i}async preprocessInput(t,e){try{let[n,i]=Wt(e),a=v(t,this.adapters);if(n==="asset"){let[s,p,c]=i.split(l.ArgCompositeSeparator);if(c)return e;let o=await a.dataLoader.getAsset(s);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let u=Y(p,o.decimals);return Lt({...o,amount:u})}else return e}catch(n){throw x.warn("WarpFactory: Preprocess input failed",n),n}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,e){let n="args"in t?t.args||[]:[],i=[];return e.forEach(({input:a,value:s})=>{if(!(!s||!a.position)){if(typeof a.position=="object"){if(a.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${a.name}" has type "${a.type}"`);if(!a.position.token?.startsWith("arg:")||!a.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${a.name}"`);let[p,c]=this.serializer.stringToNative(s),o=c;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let u=Number(a.position.token.split(":")[1])-1,d=Number(a.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",o.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",o.amount)})}else if(a.position.startsWith("arg:")){let p=Number(a.position.split(":")[1])-1;i.push({index:p,value:s})}}}),i.forEach(({index:a,value:s})=>{for(;n.length<=a;)n.push(void 0);n[a]=s}),n.filter(a=>a!==void 0)}async tryGetChainFromInputs(t,e){let n=t.actions.find(c=>c.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(c=>c.position==="chain");if(i===-1||i===void 0)return null;let a=e[i];if(!a)throw new Error("Chain input not found");let s=this.serializer.stringToNative(a)[1];return v(s,this.adapters).chainInfo}};var lt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new q(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],{action:c,index:o}=$(t);for(let u=1;u<=t.actions.length;u++){let d=T(t,u);if(!mt(d,t))continue;let{tx:h,chain:m,immediateExecution:W,executable:f}=await this.executeAction(t,u,e,n);h&&i.push(h),m&&(a=m),W&&s.push(W),f&&u===o+1&&f.resolvedInputs&&(p=B(f.resolvedInputs))}if(!a&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&s.length>0){let u=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(u))}return{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p}}async executeAction(t,e,n,i={}){let a=T(t,e);if(a.type==="link")return a.when&&!await this.evaluateWhenCondition(t,a,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):bt.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let o=await this.executePrompt(t,a,e,n,i);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:null};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,executable:null}}}let s=await this.factory.createExecutable(t,e,n,i);if(a.when&&!await this.evaluateWhenCondition(t,a,n,i,s.resolvedInputs,s.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="collect"){let o=await this.executeCollect(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="mcp"){let o=await this.executeMcp(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,executable:s}}}let p=v(s.chain.name,this.adapters);if(a.type==="query"){let o=await p.executor.executeQuery(s);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.chain,execution:o,tx:null}));else{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,result:o})}return{tx:null,chain:s.chain,immediateExecution:o,executable:s}}return{tx:await p.executor.createTransaction(s),chain:s.chain,immediateExecution:null,executable:s}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=v(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!mt(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let c=e[p],o=p+1;if(!c){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),h={status:"error",warp:t,action:o,user:P(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,o,c);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:u,tx:c})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).filter(s=>s!==null);if(a.every(s=>s.status==="success")){let s=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(s))}else{let s=a.find(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let n=P(this.config,t.chain.name),i=T(t.warp,t.action),a=this.factory.getSerializer(),s=rt(t.resolvedInputs,a);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,n,s,e);let{values:p,output:c}=await nt(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,c)}async doHttpRequest(t,e,n,i,a){let s=new E(this.config,v(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:c,method:o,headers:u,body:d}=await We(s,e,t,n,i,p,a,async h=>await this.callHandler(()=>this.handlers?.onSignRequest?.(h)));x.debug("WarpExecutor: Executing HTTP collect",{url:c,method:o,headers:u,body:d});try{let m=await fetch(c,{method:o,headers:u,body:d});x.debug("Collect response status",{status:m.status}),m.status===402&&(m=await jt(m,c,o,d,this.adapters));let W=await m.json();x.debug("Collect response content",{content:W});let{values:f,output:y}=await nt(t.warp,W,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,P(this.config,t.chain.name),m.ok?"success":"error",f,y,W)}catch(h){x.error("WarpActionExecutor: Error executing collect",h);let m=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:h},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=P(this.config,t.chain.name),i=T(t.warp,t.action);if(!i.destination){let m=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let W=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("Please install @modelcontextprotocol/sdk to execute MCP warps or mcp actions")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}let p=this.factory.getSerializer(),c=new E(this.config,v(t.chain.name,this.adapters),this.adapters),o=i.destination,u=c.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=c.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([m,W])=>{let f=c.applyInputs(W,t.resolvedInputs,this.factory.getSerializer());h[m]=f}),x.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:h});try{let m=new s(new URL(u),{requestInit:{headers:h}}),W=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await W.connect(m);let f={};t.resolvedInputs.forEach(({input:C,value:z})=>{if(z&&C.position&&typeof C.position=="string"&&C.position.startsWith("payload:")){let k=C.position.replace("payload:",""),[N,O]=p.stringToNative(z);if(N==="string")f[k]=String(O);else if(N==="bool")f[k]=!!O;else if(N==="uint8"||N==="uint16"||N==="uint32"||N==="uint64"||N==="uint128"||N==="uint256"||N==="biguint"){let X=Number(O);f[k]=(Number.isInteger(X),X)}else f[k]=O}}),e&&Object.assign(f,e);let y=await W.callTool({name:d,arguments:f});await W.close();let A;if(y.content&&y.content.length>0){let C=y.content[0];if(C.type==="text")try{A=JSON.parse(C.text)}catch{A=C.text}else C.type,A=C}else A=y;let{values:b,output:R}=await nt(t.warp,A,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",b,R,y)}catch(m){x.error("WarpExecutor: Error executing MCP",m);let W=B(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:m},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}}buildCollectResult(t,e,n,i,a,s){let p=At(this.config,this.adapters,t.warp,t.action,a),c=B(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||P(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:vt(t.warp,a,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:c}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=v(s.name,this.adapters),c=new E(this.config,p,this.adapters),o=await c.apply(t,a),u=T(o,n),{action:d}=$(o),h=this.factory.getStringTypedInputs(d,i),m=await this.factory.getResolvedInputs(s.name,d,h,c),W=await this.factory.getModifiedInputs(m),f=W;if(e.inputs&&e.inputs.length>0){let R=this.factory.getStringTypedInputs(e,i),C=await this.factory.getResolvedInputs(s.name,e,R,c);f=await this.factory.getModifiedInputs(C)}let y=c.applyInputs(u.prompt,f,this.factory.getSerializer(),W),A=B(f),b=P(this.config,s.name);return{status:"success",warp:o,action:n,user:b,txHash:null,tx:null,next:At(this.config,this.adapters,o,n,{prompt:y}),values:{string:[y],native:[y],mapped:{prompt:y}},output:{prompt:y},messages:vt(o,{prompt:y},this.config),destination:null,resolvedInputs:A}}catch(s){return x.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:s},messages:{},destination:null,resolvedInputs:[]}}}async evaluateWhenCondition(t,e,n,i,a,s){if(!e.when)return!0;let p=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),c=v(p.name,this.adapters),o=new E(this.config,c,this.adapters),{action:u}=$(t),d=this.factory.getStringTypedInputs(u,n),h=await this.factory.getResolvedInputs(p.name,u,d,o),m=await this.factory.getModifiedInputs(h),W;if(a)W=a;else{let A=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o);W=await this.factory.getModifiedInputs(A)}let f=o.buildInputBag(W,this.factory.getSerializer(),m),y=Bt(e.when,f);return $t(y)}};var ut=class{constructor(t){this.config=t}async search(t,e,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw x.error("WarpIndex: Error searching for warps: ",i),i}}};var dt=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!_(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(o=>o[0]).filter(o=>this.isValid(o)).map(o=>this.detect(o)),s=(await Promise.all(i)).filter(o=>o.match),p=s.length>0,c=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:c}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?_(t):H(t);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,c=null,o=null,u=v(i.chain,this.adapters),d=t.startsWith(l.HttpProtocolPrefix)?Ht(t):Ot(i.identifier);if(a==="hash"){p=await u.builder().createFromTransactionHash(s,e);let f=await u.registry.getInfoByHash(s,e);c=f.registryInfo,o=f.brand}else if(a==="alias"){let f=await u.registry.getInfoByAlias(s,e);c=f.registryInfo,o=f.brand,f.registryInfo&&(p=await u.builder().createFromTransactionHash(f.registryInfo.hash,e))}if(p&&p.meta&&(Nr(p,u.chainInfo.name,c,i.identifier),p.meta.query=d),!p)return n;let h=p.chain||u.chainInfo.name,m=v(h,this.adapters),W=await new E(this.config,m,this.adapters).apply(p);return{match:!0,url:t,warp:W,chain:h,registryInfo:c,brand:o}}catch(a){return x.error("Error detecting warp link",a),n}}},Nr=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?yt(t,"alias",e.alias):yt(t,"hash",e?.hash??n))};var Jt=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config))}getConfig(){return this.config}createExecutor(t){return new lt(this.config,this.chains,t)}async detectWarp(t,e){return new dt(this.config,this.chains).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),p=a?t:null;if(!p&&s){let W=await fetch(t);if(!W.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await W.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let c=this.createExecutor(n),{txs:o,chain:u,immediateExecutions:d,resolvedInputs:h}=await c.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async W=>{await c.evaluateOutput(p,W)},resolvedInputs:h}}async createInscriptionTransaction(t,e){return await v(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return v(t,this.chains).builder().createFromTransaction(e,n)}async createFromTransactionHash(t,e){let n=H(t);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return v(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!P(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return v(t,this.chains).wallet.signMessage(e)}async getActions(t,e,n=!1){let i=this.getDataLoader(t);return(await Promise.all(e.map(async s=>i.getAction(s,n)))).filter(s=>s!==null)}getExplorer(t){return v(t,this.chains).explorer}getOutput(t){return v(t,this.chains).output}async getRegistry(t){let e=v(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return v(t,this.chains).dataLoader}getWallet(t){return v(t,this.chains).wallet}get factory(){return new q(this.config,this.chains)}get index(){return new ut(this.config)}get linkBuilder(){return new L(this.config,this.chains)}createBuilder(t){return v(t,this.chains).builder()}createAbiBuilder(t){return v(t,this.chains).abiBuilder()}createBrandBuilder(t){return v(t,this.chains).brandBuilder()}createSerializer(t){return v(t,this.chains).serializer}resolveText(t){return tt(t,this.config)}};var Qt=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};0&&(module.exports={BrowserCryptoProvider,CacheTtl,NodeCryptoProvider,WARP_LANGUAGES,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createDefaultWalletProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,evaluateOutputCommon,evaluateWhenCondition,extractCollectOutput,extractIdentifierInfoFromUrl,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getWalletFromConfigOrFail,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpChainAssetLogoUrl,getWarpChainInfoLogoUrl,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletExternalId,getWarpWalletExternalIdFromConfig,getWarpWalletExternalIdFromConfigOrFail,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,handleX402Payment,hasInputPrefix,hex,initializeWalletCache,isEqualWarpIdentifier,isWarpActionAutoExecute,isWarpI18nText,isWarpWalletReadOnly,mergeNestedPayload,normalizeAndValidateMnemonic,normalizeMnemonic,option,parseOutputOutIndex,parseSignedMessage,replacePlaceholders,replacePlaceholdersInWhenExpression,resolveWarpText,safeWindow,setCryptoProvider,setWarpWalletInConfig,shiftBigintBy,splitInput,string,struct,testCryptoAvailability,toInputPayloadValue,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateMnemonicLength,validateSignedMessage,vector,withAdapterFallback});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var oe=(d=>(d.Multiversx="multiversx",d.Vibechain="vibechain",d.Sui="sui",d.Ethereum="ethereum",d.Base="base",d.Arbitrum="arbitrum",d.Polygon="polygon",d.Somnia="somnia",d.Fastset="fastset",d.Solana="solana",d.Near="near",d))(oe||{}),l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:r=>r.config.user?.wallets?.[r.adapter.chainInfo.name]},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:r=>{if(!r.adapter.wallet)return null;try{return r.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:r=>r.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:r=>r.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},g={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},Et=typeof window<"u"?window:{open:()=>{}};var M={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},F={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${M.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${M.Brand}.schema.json`,DefaultClientUrl:r=>r==="devnet"?"https://devnet.usewarp.to":r==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",l.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var _e=(r,t)=>(e,n)=>{let i=t(e,n);return r(e,i)};var Ke=(r,t)=>{let e=r.alerts?.[t];if(!e)return null;let n=l.Alerts.TriggerEventPrefix+l.ArgParamsSeparator;if(!e.trigger.startsWith(n))return null;let i=e.trigger.replace(n,"");return i||null};var Ze=(r,t)=>{let e=t?.preferences?.theme??"light";return typeof r.logo=="string"?r.logo:r.logo[e]},Ye=(r,t)=>{if(!r.logoUrl)return null;if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]},tr=(r,t)=>{if(typeof r.logoUrl=="string")return r.logoUrl;let e=t?.preferences?.theme??"light";return r.logoUrl[e]};var ut=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(t);return window.crypto.getRandomValues(e),e}},dt=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(t))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},V=null;function Rt(){if(V)return V;if(typeof window<"u"&&window.crypto)return V=new ut,V;if(typeof process<"u"&&process.versions?.node)return V=new dt,V;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function rr(r){V=r}async function Nt(r,t){if(r<=0||!Number.isInteger(r))throw new Error("Size must be a positive integer");return(t||Rt()).getRandomBytes(r)}function pe(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(r.length*2);for(let e=0;e<r.length;e++){let n=r[e];t[e*2]=(n>>>4).toString(16),t[e*2+1]=(n&15).toString(16)}return t.join("")}function nr(r){if(!(r instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(r).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(r));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function Bt(r,t){if(r<=0||r%2!==0)throw new Error("Length must be a positive even number");let e=await Nt(r/2,t);return pe(e)}async function ir(){let r={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?r.environment="browser":typeof process<"u"&&process.versions?.node&&(r.environment="nodejs"),await Nt(16),r.randomBytes=!0}catch{}return r}function ar(){return Rt()}var pr=r=>Object.values(r.vars||{}).filter(t=>t.startsWith(`${l.Vars.Env}:`)).map(t=>{let e=t.replace(`${l.Vars.Env}:`,"").trim(),[n,i]=e.split(l.ArgCompositeSeparator);return{key:n,description:i||null}});var v=(r,t)=>{let e=t.find(n=>n.chainInfo.name.toLowerCase()===r.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${r}`);return e},Z=r=>{if(r==="warp")return`warp:${M.Warp}`;if(r==="brand")return`brand:${M.Brand}`;if(r==="abi")return`abi:${M.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${r}`)},E=(r,t)=>r?.actions[t-1],B=r=>{if(r.actions.length===0)throw new Error(`Warp has no primary action: ${r.meta?.identifier}`);let t=r.actions.find(a=>a.primary===!0);if(t)return{action:t,index:r.actions.indexOf(t)};let e=["transfer","contract","query","collect","mcp"],n=r.actions.find(a=>e.includes(a.type));return n?{action:n,index:r.actions.indexOf(n)}:{action:r.actions[0],index:0}},ft=(r,t)=>{if(r.auto===!1)return!1;if(r.type==="link"){if(r.auto===!0)return!0;let{action:e}=B(t);return r===e}return!0},Y=(r,t)=>{let e=r.toString(),[n,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(a,"0"));if(t<0){let s=n+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},$t=(r,t=100)=>{if(!r)return"";let e=r.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},U=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>t[n]||""),Ht=(r,t)=>r.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=t[n];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Ot=r=>{if(!r||typeof r!="string")return!0;try{return!!new Function(`return ${r}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${r}. Error: ${t}`)}};var dr={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},tt=(r,t)=>{let e=t?.preferences?.locale||"en";if(typeof r=="string")return r;if(typeof r=="object"&&r!==null){if(e in r)return r[e];if("en"in r)return r.en;let n=Object.keys(r);if(n.length>0)return r[n[0]]}return""},fr=r=>typeof r=="object"&&r!==null&&Object.keys(r).length>0,gr=r=>r;var et=r=>r.startsWith(l.IdentifierAliasMarker)?r.replace(l.IdentifierAliasMarker,""):r,Wr=(r,t)=>!r||!t?!1:et(r)===et(t),gt=(r,t,e)=>{let n=et(e);return t===l.IdentifierType.Alias?l.IdentifierAliasMarker+r+l.IdentifierParamSeparator+n:r+l.IdentifierParamSeparator+t+l.IdentifierParamSeparator+n},$=r=>{let t=decodeURIComponent(r).trim(),e=et(t),n=e.split("?")[0],i=Ft(n);if(n.length===64&&/^[a-fA-F0-9]+$/.test(n))return{chain:l.IdentifierChainDefault,type:l.IdentifierType.Hash,identifier:e,identifierBase:n};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[a,s,p]=i;if(s===l.IdentifierType.Alias||s===l.IdentifierType.Hash){let c=e.includes("?")?p+e.substring(e.indexOf("?")):p;return{chain:a,type:s,identifier:c,identifierBase:p}}}if(i.length===2){let[a,s]=i;if(a===l.IdentifierType.Alias||a===l.IdentifierType.Hash){let p=e.includes("?")?s+e.substring(e.indexOf("?")):s;return{chain:l.IdentifierChainDefault,type:a,identifier:p,identifierBase:s}}}if(i.length===2){let[a,s]=i;if(a!==l.IdentifierType.Alias&&a!==l.IdentifierType.Hash){let p=e.includes("?")?s+e.substring(e.indexOf("?")):s,c=ce(s,a)?l.IdentifierType.Hash:l.IdentifierType.Alias;return{chain:a,type:c,identifier:p,identifierBase:s}}}return{chain:l.IdentifierChainDefault,type:l.IdentifierType.Alias,identifier:e,identifierBase:n}},J=r=>{let t=new URL(r),n=t.searchParams.get(l.IdentifierParamName);if(n||(n=t.pathname.split("/")[1]),!n)return null;let i=decodeURIComponent(n);return $(i)},ce=(r,t)=>/^[a-fA-F0-9]+$/.test(r)&&r.length>32,le=r=>{let t=l.IdentifierParamSeparator,e=r.indexOf(t);return e!==-1?{separator:t,index:e}:null},Ft=r=>{let t=le(r);if(!t)return[r];let{separator:e,index:n}=t,i=r.substring(0,n),a=r.substring(n+e.length),s=Ft(a);return[i,...s]},Vt=r=>{try{let t=new URL(r),e=new URLSearchParams(t.search);return e.delete(l.IdentifierParamName),e.toString()||null}catch{return null}},Ut=r=>{let t=r.indexOf("?");if(t===-1||t===r.length-1)return null;let e=r.substring(t+1);return e.length>0?e:null};var ht=r=>{let[t,...e]=r.split(/:(.*)/,2);return[t,e[0]||""]},xr=r=>{let t=new Set(Object.values(g));if(!r.includes(l.ArgParamsSeparator))return!1;let e=ht(r)[0];return t.has(e)};var mt=(r,t,e)=>{let n=Object.entries(r.messages||{}).map(([i,a])=>{let s=tt(a,e);return[i,U(s,t)]});return Object.fromEntries(n)};import ue from"qr-code-styling";var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!J(t):!1}build(t,e,n){let i=this.config.clientUrl||F.DefaultClientUrl(this.config.env),a=v(t,this.adapters),s=e===l.IdentifierType.Alias?n:e+l.IdentifierParamSeparator+n,p=a.chainInfo.name+l.IdentifierParamSeparator+s,c=encodeURIComponent(p);return F.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${l.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let e=$(t);if(!e)return null;let n=v(e.chain,this.adapters);return n?this.build(n.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,n,i=512,a="white",s="black",p="#23F7DD"){let c=v(t,this.adapters),o=this.build(c.chainInfo.name,e,n);return new ue({type:"svg",width:i,height:i,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(p)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var de="https://",Wt=(r,t,e,n,i)=>{let a=e.actions?.[n-1]?.next||e.next||null;if(!a)return null;if(a.startsWith(de))return[{identifier:null,url:a}];let[s,p]=a.split("?");if(!p){let f=U(s,{...e.vars,...i});return[{identifier:f,url:yt(t,f,r)}]}let c=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let f=U(p,{...e.vars,...i}),y=f?`${s}?${f}`:s;return[{identifier:y,url:yt(t,y,r)}]}let o=c[0];if(!o)return[];let u=o.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let h=Array.isArray(i[d])?i[d]:[i[d]];if(h.length===0)return[];let m=c.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let y=f.match(/\[\](\.[^}]+)?}}/),A=y&&y[1]||"";return{placeholder:f,field:A?A.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let y=p;for(let{regex:P,field:T}of m){let x=T?fe(f,T):f;if(x==null)return null;y=y.replace(P,x)}if(y.includes("{{")||y.includes("}}"))return null;let A=y?`${s}?${y}`:s;return{identifier:A,url:yt(t,A,r)}}).filter(f=>f!==null)},yt=(r,t,e)=>{let[n,i]=t.split("?"),a=$(n)||{chain:l.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},s=v(a.chain,r);if(!s)throw new Error(`Adapter not found for chain ${a.chain}`);let p=new q(e,r).build(s.chainInfo.name,a.type,a.identifierBase);if(!i)return p;let c=new URL(p);return new URLSearchParams(i).forEach((o,u)=>c.searchParams.set(u,o)),c.toString().replace(/\/\?/,"?")},fe=(r,t)=>t.split(".").reduce((e,n)=>e?.[n],r);var D=class D{static debug(...t){D.isTestEnv||console.debug(...t)}static info(...t){D.isTestEnv||console.info(...t)}static warn(...t){D.isTestEnv||console.warn(...t)}static error(...t){D.isTestEnv||console.error(...t)}};D.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=D;function ge(r,t,e){return r.startsWith(l.Position.Payload)?r.slice(l.Position.Payload.length).split(".").reduceRight((n,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:n}),{}):{[t]:e}}function Dt(r,t){if(!r)return{...t};if(!t)return{...r};let e={...r};return Object.keys(t).forEach(n=>{e[n]&&typeof e[n]=="object"&&typeof t[n]=="object"?e[n]=Dt(e[n],t[n]):e[n]=t[n]}),e}function he(r,t){if(!r.value)return null;let e=t.stringToNative(r.value)[1];if(r.input.type==="biguint")return e.toString();if(r.input.type==="asset"){let{identifier:n,amount:i}=e;return{identifier:n,amount:i.toString()}}else return e}function N(r){return r.map(t=>t.value).filter(t=>t!=null&&t!=="")}function rt(r,t){let e={};return r.forEach(n=>{let i=n.input.as||n.input.name,a=he(n,t);if(n.input.position&&typeof n.input.position=="string"&&n.input.position.startsWith(l.Position.Payload)){let s=ge(n.input.position,i,a);e=Dt(e,s)}else e[i]=a}),e}var nt=async(r,t,e,n,i,a)=>{let s=[],p=[],c={};for(let[u,d]of Object.entries(r.output||{})){if(d.startsWith(l.Transform.Prefix))continue;let h=ve(d);if(h!==null&&h!==e){c[u]=null;continue}let[m,...W]=d.split("."),f=(y,A)=>A.reduce((P,T)=>P&&P[T]!==void 0?P[T]:null,y);if(m==="out"||m.startsWith("out[")){let y=W.length===0?t?.data||t:f(t,W);s.push(String(y)),p.push(y),c[u]=y}else c[u]=d}let o=rt(n,i);return{values:{string:s,native:p,mapped:o},output:await me(r,c,e,n,i,a)}},me=async(r,t,e,n,i,a)=>{if(!r.output)return t;let s={...t};return s=ye(s,r,e,n,i),s=await We(r,s,a.transform?.runner||null),s},ye=(r,t,e,n,i)=>{let a={...r},s=E(t,e)?.inputs||[];for(let[p,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("in.")){let o=c.split(".")[1],u=s.findIndex(h=>h.as===o||h.name===o),d=u!==-1?n[u]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},We=async(r,t,e)=>{if(!r.output)return t;let n={...t},i=Object.entries(r.output).filter(([,a])=>a.startsWith(l.Transform.Prefix)).map(([a,s])=>({key:a,code:s.substring(l.Transform.Prefix.length)}));if(i.length>0&&(!e||typeof e.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:a,code:s}of i)try{n[a]=await e.run(s,n)}catch(p){C.error(`Transform error for output '${a}':`,p),n[a]=null}return n},ve=r=>{if(r==="out")return 1;let t=r.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(r.startsWith("out.")||r.startsWith("event."),null)};var _r=(r,t,e,n)=>{let i=r.preferences?.providers?.[t];return i?.[e]?typeof i[e]=="string"?{url:i[e]}:i[e]:{url:n}};async function Ae(r,t,e,n=5){let i=await Bt(64,e),a=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:r,nonce:i,expiresAt:a,purpose:t}),nonce:i,expiresAt:a}}async function vt(r,t,e,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Ae(r,i,e,5)}function At(r,t,e,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":n}}async function Xr(r,t,e,n){let{message:i,nonce:a,expiresAt:s}=await vt(r,e,n),p=await t(i);return At(r,p,a,s)}function Zr(r){let t=new Date(r).getTime();return Date.now()<t}function Yr(r){try{let t=JSON.parse(r);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var en=(r,t)=>{let e=r.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},xe=r=>r?typeof r=="string"?r:r.address:null,S=(r,t)=>xe(r.user?.wallets?.[t]||null),Ce=r=>r?typeof r=="string"?r:r.privateKey||null:null,we=r=>r?typeof r=="string"?r:r.mnemonic||null:null,Ie=r=>r?typeof r=="string"?r:r.externalId||null:null,rn=(r,t)=>Ce(r.user?.wallets?.[t]||null)?.trim()||null,nn=(r,t)=>we(r.user?.wallets?.[t]||null)?.trim()||null,Se=(r,t)=>Ie(r.user?.wallets?.[t]||null)?.trim()||null,an=(r,t)=>{let e=Se(r,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},sn=r=>typeof r=="string",on=(r,t,e)=>{r.user||(r.user={}),r.user.wallets||(r.user.wallets={}),r.user.wallets[t]=e},Pe=r=>{if(!r)throw new Error("Mnemonic is required");return typeof r=="string"?r.trim():String(r).trim()},Te=(r,t=24)=>{let e=r.split(/\s+/).filter(n=>n.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},pn=(r,t=24)=>{let e=Pe(r);return Te(e,t),e};async function ln(r){let t={address:null,publicKey:null};if(!r)return t;try{t.address=await r.getAddress()}catch{}try{t.publicKey=await r.getPublicKey()}catch{}return t}function dn(r,t,e){return null}import{x402Client as jt}from"@x402/core/client";import{x402HTTPClient as Lt}from"@x402/core/http";async function Mt(r,t,e,n,i){let a=await be(r,i);if(!a)return r;let s=new Headers;n&&s.set("Content-Type","application/json"),s.set("Accept","application/json"),Object.entries(a).forEach(([c,o])=>{s.set(c,o)}),C.debug("WarpExecutor: Retrying request with payment headers");let p=await fetch(t,{method:e,headers:s,body:n});return C.debug("WarpExecutor: Payment processed, new response status",{status:p.status}),p}var be=async(r,t)=>{let e=await Ee(r),i=new Lt(new jt).getPaymentRequiredResponse(a=>r.headers.get(a),e);if(!i?.accepts?.length)return null;for(let a of t)if(a.wallet.registerX402Handlers)try{let s=new jt,p=await a.wallet.registerX402Handlers(s),c=i.accepts.find(h=>h?.network&&p[h.network]);if(!c?.network)continue;p[c.network]();let o=new Lt(s),u=await o.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=o.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return C.debug(`WarpExecutor: x402 payment processed with ${a.chainInfo.name} adapter using ${c.network} scheme`),d}catch{continue}return null},Ee=async r=>{try{let t=await r.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===g.Tuple&&Array.isArray(e)){if(e.length===0)return t+l.ArgParamsSeparator;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e.map(s=>this.getTypeAndValue(s)),i=n.map(([s])=>s),a=n.map(([,s])=>s);return`${t}(${i.join(l.ArgCompositeSeparator)})${l.ArgParamsSeparator}${a.join(l.ArgListSeparator)}`}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===g.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let n=e;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,a=Object.keys(n).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${l.ArgParamsSeparator}`;let s=a.map(p=>{let[c,o]=this.getTypeAndValue(n[p]);return`(${p}${l.ArgParamsSeparator}${c})${o}`});return`${t}(${i})${l.ArgParamsSeparator}${s.join(l.ArgListSeparator)}`}if(t===g.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${l.ArgParamsSeparator}`;if(e.every(n=>typeof n=="string"&&n.includes(l.ArgParamsSeparator))){let n=e[0],i=n.indexOf(l.ArgParamsSeparator),a=n.substring(0,i),s=e.map(c=>{let o=c.indexOf(l.ArgParamsSeparator),u=c.substring(o+1);return a.startsWith(g.Tuple)?u.replace(l.ArgListSeparator,l.ArgCompositeSeparator):u}),p=a.startsWith(g.Struct)?l.ArgStructSeparator:l.ArgListSeparator;return t+l.ArgParamsSeparator+a+l.ArgParamsSeparator+s.join(p)}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===g.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?g.Asset+l.ArgParamsSeparator+e.identifier+l.ArgCompositeSeparator+String(e.amount)+l.ArgCompositeSeparator+String(e.decimals):g.Asset+l.ArgParamsSeparator+e.identifier+l.ArgCompositeSeparator+String(e.amount);if(this.typeRegistry){let n=this.typeRegistry.getHandler(t);if(n)return n.nativeToString(e);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,e)}return t+l.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(l.ArgParamsSeparator),n=e[0],i=e.slice(1).join(l.ArgParamsSeparator);if(n==="null")return[n,null];if(n===g.Option){let[a,s]=i.split(l.ArgParamsSeparator);return[g.Option+l.ArgParamsSeparator+a,s||null]}if(n===g.Vector){let a=i.indexOf(l.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),c=s.startsWith(g.Struct)?l.ArgStructSeparator:l.ArgListSeparator,u=(p?p.split(c):[]).map(d=>this.stringToNative(s+l.ArgParamsSeparator+d)[1]);return[g.Vector+l.ArgParamsSeparator+s,u]}else if(n.startsWith(g.Tuple)){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),p=i.split(l.ArgCompositeSeparator).map((c,o)=>this.stringToNative(`${a[o]}${l.IdentifierParamSeparator}${c}`)[1]);return[n,p]}else if(n.startsWith(g.Struct)){let a=n.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:a[1]};return i&&i.split(l.ArgListSeparator).forEach(c=>{let o=c.match(new RegExp(`^\\(([^${l.ArgParamsSeparator}]+)${l.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,h]=o;p[u]=this.stringToNative(`${d}${l.IdentifierParamSeparator}${h}`)[1]}}),[n,p]}else{if(n===g.String)return[n,i];if(n===g.Uint8||n===g.Uint16||n===g.Uint32)return[n,Number(i)];if(n===g.Uint64||n===g.Uint128||n===g.Uint256||n===g.Biguint)return[n,BigInt(i||0)];if(n===g.Bool)return[n,i==="true"];if(n===g.Address)return[n,i];if(n===g.Hex)return[n,i];if(n===g.Asset){let[a,s]=i.split(l.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[n,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(n);if(a){let p=a.stringToNative(i);return[n,p]}let s=this.typeRegistry.resolveType(n);if(s!==n){let[p,c]=this.stringToNative(`${s}:${i}`);return[n,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(l.ArgParamsSeparator)){let[e,n]=t.split(l.ArgParamsSeparator);return[e,n]}return typeof t=="number"?[g.Uint32,t]:typeof t=="bigint"?[g.Uint64,t]:typeof t=="boolean"?[g.Bool,t]:[typeof t,t]}};var Cn=r=>new w().nativeToString(g.String,r),wn=r=>new w().nativeToString(g.Uint8,r),In=r=>new w().nativeToString(g.Uint16,r),Sn=r=>new w().nativeToString(g.Uint32,r),Pn=r=>new w().nativeToString(g.Uint64,r),Tn=r=>new w().nativeToString(g.Biguint,r),bn=r=>new w().nativeToString(g.Bool,r),En=r=>new w().nativeToString(g.Address,r),qt=r=>new w().nativeToString(g.Asset,r),Rn=r=>new w().nativeToString(g.Hex,r),Nn=(r,t)=>{if(t===null)return g.Option+l.ArgParamsSeparator;let e=r(t),n=e.indexOf(l.ArgParamsSeparator),i=e.substring(0,n),a=e.substring(n+1);return g.Option+l.ArgParamsSeparator+i+l.ArgParamsSeparator+a},Bn=(...r)=>new w().nativeToString(g.Tuple,r),$n=r=>new w().nativeToString(g.Struct,r),Hn=r=>new w().nativeToString(g.Vector,r);import Re from"ajv";var zt=class{constructor(t){this.pendingBrand={protocol:Z("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.ensureValidSchema(n),n}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}ensureWarpText(t,e){if(!t)throw new Error(`Warp: ${e}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||F.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new Re,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import Ne from"ajv";var it=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validatePrimaryAction(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validatePrimaryAction(t){try{let{action:e}=B(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],n=(i,a)=>{i&&Object.keys(i).forEach(s=>{s!==s.toUpperCase()&&e.push(`${a} name '${s}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(s=>s.type==="contract"),n=t.actions.some(s=>s.type==="query");if(!e&&!n)return[];let i=t.actions.some(s=>s.abi),a=Object.values(t.output||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.output&&!i&&a?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||F.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new Ne({strict:!1}),s=a.compile(i);return s(t)?[]:[`Schema validation failed: ${a.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var kt=class{constructor(t){this.config=t;this.pendingWarp={protocol:Z("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,e=!0){let n=JSON.parse(t);return e&&await this.validate(n),n}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}setOutput(t){return this.pendingWarp.output=t??void 0,this}async build(t=!0){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),t&&await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return $t(t,e)}ensure(t,e){if(!t)throw new Error(e)}ensureWarpText(t,e){if(!t)throw new Error(e);if(typeof t=="object"&&!t.en)throw new Error(e)}async validate(t){let n=await new it(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
- `))}};import{existsSync as xt,mkdirSync as Be,readdirSync as $e,readFileSync as He,unlinkSync as Ct,writeFileSync as Oe}from"fs";import{join as _t,resolve as Jt}from"path";var Gt=new w,z=(r,t)=>typeof t=="bigint"?Gt.nativeToString("biguint",t):t,k=(r,t)=>typeof t=="string"&&t.startsWith(g.Biguint+":")?Gt.stringToNative(t)[1]:t;var at=class{constructor(t){this.cacheDir=t?Jt(t):Jt(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){xt(this.cacheDir)||Be(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return _t(this.cacheDir,`${e}.json`)}get(t){try{let e=this.getFilePath(t);if(!xt(e))return null;let n=He(e,"utf-8"),i=JSON.parse(n,k);return Date.now()>i.expiresAt?(Ct(e),null):i.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3},a=this.getFilePath(t);Oe(a,JSON.stringify(i,z),"utf-8")}forget(t){try{let e=this.getFilePath(t);xt(e)&&Ct(e)}catch{}}clear(){try{$e(this.cacheDir).forEach(e=>{e.endsWith(".json")&&Ct(_t(this.cacheDir,e))})}catch{}}};var Q=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let n=JSON.parse(e,k);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,e,n){let i={value:e,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,z))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var O=class O{get(t){let e=O.cache.get(t);return e?Date.now()>e.expiresAt?(O.cache.delete(t),null):e.value:null}set(t,e,n){let i=Date.now()+n*1e3;O.cache.set(t,{value:e,expiresAt:i})}forget(t){O.cache.delete(t)}clear(){O.cache.clear()}};O.cache=new Map;var K=O;import{readFileSync as Fe,writeFileSync as Ve}from"fs";import{resolve as Qt}from"path";var st=class{constructor(t){this.manifestPath=t?Qt(t):Qt(process.cwd(),"warps-manifest.json"),console.log("StaticCacheStrategy path",t),console.log("StaticCacheStrategy manifestPath",this.manifestPath),console.log("StaticCacheStrategy process.cwd()",process.cwd()),this.cache=this.loadManifest()}loadManifest(){try{let t=Fe(this.manifestPath,"utf-8");return new Map(Object.entries(JSON.parse(t,k)))}catch{return new Map}}saveManifest(){let t=JSON.stringify(Object.fromEntries(this.cache.entries()),z);Ve(this.manifestPath,t,"utf-8")}get(t){let e=this.cache.get(t);return!e||Date.now()>e.expiresAt?(e&&(this.cache.delete(t),this.saveManifest()),null):e.value}set(t,e,n){let i=Date.now()+n*1e3,a={value:e,expiresAt:i};this.cache.set(t,a),this.saveManifest()}forget(t){this.cache.delete(t)&&this.saveManifest()}clear(){this.cache.clear(),this.saveManifest()}};var Kt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},wt={Warp:(r,t)=>`warp:${r}:${t}`,WarpAbi:(r,t)=>`warp-abi:${r}:${t}`,WarpExecutable:(r,t,e)=>`warp-exec:${r}:${t}:${e}`,RegistryInfo:(r,t)=>`registry-info:${r}:${t}`,Brand:(r,t)=>`brand:${r}:${t}`,Asset:(r,t,e)=>`asset:${r}:${t}:${e}`},ot=class{constructor(t,e){this.path=e,this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new Q:t==="memory"?new K:t==="static"?new st(this.path):t==="filesystem"?new at(this.path):typeof window<"u"&&window.localStorage?new Q:new K}set(t,e,n){this.strategy.set(t,e,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var X={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},It={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},St=(r,t,e)=>{let n=r.find(a=>a.input.as===t||a.input.name===t);if(!n?.value)return null;let[,i]=e.stringToNative(n.value);return typeof i=="string"?i:String(i)},Pt=r=>{try{return JSON.parse(r)}catch{return null}},Ue=async(r,t,e,n,i,a)=>{let s=new Headers;if(s.set("Content-Type","application/json"),s.set("Accept","application/json"),a&&n){let{message:c,nonce:o,expiresAt:u}=await vt(n,`${e.chain.name}-adapter`),d=await a({message:c,chain:e.chain});d&&Object.entries(At(n,d,o,u)).forEach(([h,m])=>s.set(h,m))}let p=St(e.resolvedInputs,X.Headers,i);if(p){let c=Pt(p);c&&typeof c=="object"&&Object.entries(c).forEach(([o,u])=>typeof u=="string"&&s.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([c,o])=>{s.set(c,r.applyInputs(o,e.resolvedInputs,i))});return s},De=(r,t,e,n,i)=>{let a=r.applyInputs(t.url,e.resolvedInputs,i);if(n===It.Get){let s=St(e.resolvedInputs,X.Queries,i);if(s){let p=Pt(s);if(p&&typeof p=="object"){let c=new URL(a);Object.entries(p).forEach(([o,u])=>u!=null&&c.searchParams.set(o,String(u))),a=c.toString()}}}return a},je=(r,t,e,n,i)=>{if(r===It.Get)return;let a=St(t.resolvedInputs,X.Payload,n);if(a&&Pt(a)!==null)return a;let{[X.Payload]:s,[X.Queries]:p,...c}=e;return JSON.stringify({...c,...i})},Xt=async(r,t,e,n,i,a,s,p)=>{let c=t.method||It.Get,o=await Ue(r,t,e,n,a,p),u=De(r,t,e,c,a),d=je(c,e,i,a,s);return{url:u,method:c,headers:o,body:d}};var R=class{constructor(t,e,n){this.config=t;this.adapter=e;this.adapters=n}async apply(t,e={}){let n=this.applyVars(t,e);return await this.applyGlobals(n)}async applyGlobals(t){let e={...t};return e.actions=await Promise.all((e.actions||[]).map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e),e}applyVars(t,e={}){if(!t?.vars)return t;let n=S(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,p)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(t.vars).forEach(([s,p])=>{if(typeof p!="string")a(s,p);else if(p.startsWith(l.Vars.Query+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Query.length+1),[o,u]=c.split(l.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,m=e.queries?.[o]||null||d;m&&a(s,m)}else if(p.startsWith(l.Vars.Env+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Env.length+1),[o,u]=c.split(l.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h&&a(s,h)}else p===l.Source.UserWallet&&n?a(s,n):a(s,p)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(l.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}async applyActionGlobals(t){let e=JSON.stringify(t),n={config:this.config,adapter:this.adapter};return Object.values(l.Globals).forEach(i=>{let a=i.Accessor(n);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,n,i.Accessor)}),JSON.parse(e)}applyInputs(t,e,n,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let a=this.applyGlobalsToText(t),s=this.buildInputBag(e,n,i);return U(a,s)}applyGlobalsToText(t){if(!Object.values(l.Globals).map(s=>s.Placeholder).some(s=>t.includes(`{{${s}}}`)||t.includes(`{{${s}:`)))return t;let i={config:this.config,adapter:this.adapter},a=t;return Object.values(l.Globals).forEach(s=>{let p=s.Accessor(i);p!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),p.toString())),a=this.replacePlaceholdersWithChain(a,s.Placeholder,i,s.Accessor)}),a}replacePlaceholdersWithChain(t,e,n,i){let a=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(a,(s,p)=>{let c=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=v(c,this.adapters),u={config:this.config,adapter:o},d=i(u);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e,n){let i={};return t.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);i[s]=String(p)}),n&&n.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);if(i[`primary.${s}`]=String(p),a.input.type==="asset"&&typeof a.input.position=="object"){let c=p;c&&typeof c=="object"&&"identifier"in c&&"amount"in c&&(i[`primary.${s}.token`]=String(c.identifier),i[`primary.${s}.amount`]=String(c.amount))}}),i}};var G=class{constructor(t,e){this.config=t;this.adapters=e;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new w,this.cache=new ot(t.cache?.type,t.cache?.path)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,e,n){let i=this.cache.get(wt.WarpExecutable(t,e||"",n))||[];return N(i)}async createExecutable(t,e,n,i={}){let a=E(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,n),p=v(s.name,this.adapters),c=new R(this.config,p,this.adapters),o=await c.apply(t,i),u=E(o,e),{action:d,index:h}=B(o),m=this.getStringTypedInputs(d,n),W=await this.getResolvedInputs(s.name,d,m,c),f=await this.getModifiedInputs(W),y=[],A=[];h===e-1?(y=W,A=f):this.requiresPayloadInputs(u)&&(y=await this.resolveActionInputs(s.name,u,n,c),A=await this.getModifiedInputs(y));let P=A.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,T=this.getDestinationFromAction(u),x=P?this.serializer.stringToNative(P)[1]:T;if(x&&(x=c.applyInputs(x,A,this.serializer,f)),!x&&a.type!=="collect"&&a.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let j=this.getPreparedArgs(u,A);j=j.map(I=>c.applyInputs(I,A,this.serializer,f));let L=A.find(I=>I.input.position==="value")?.value||null,b="value"in u?u.value:null,H=L?.split(l.ArgParamsSeparator)[1]||b||"0",_=c.applyInputs(H,A,this.serializer,f),te=BigInt(_),ee=A.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),re=[...("transfers"in u?u.transfers:[])||[],...ee||[]].map(I=>{let se=c.applyInputs(I,A,this.serializer,f);return this.serializer.stringToNative(se)[1]}),ne=A.find(I=>I.input.position==="data")?.value,ie="data"in u?u.data||"":null,Tt=ne||ie||null,ae=Tt?c.applyInputs(Tt,A,this.serializer,f):null,bt={adapter:p,warp:o,chain:s,action:e,destination:x,args:j,value:te,transfers:re,data:ae,resolvedInputs:A};return this.cache.set(wt.WarpExecutable(this.config.env,o.meta?.hash||"",e),bt.resolvedInputs,Kt.OneWeek),bt}async getChainInfoForWarp(t,e){if(t.chain)return v(t.chain,this.adapters).chainInfo;if(e){let i=await this.tryGetChainFromInputs(t,e);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,e){let n=t.inputs||[];return e.map((i,a)=>{let s=n[a];return!s||i.includes(l.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,n,i){let a=e.inputs||[],s=await Promise.all(n.map(c=>this.preprocessInput(t,c))),p=(c,o)=>{if(c.source==="query"){let u=this.url.searchParams.get(c.name);return u?this.serializer.nativeToString(c.type,u):null}else if(c.source===l.Source.UserWallet){let u=S(this.config,t);return u?this.serializer.nativeToString("address",u):null}else if(c.source==="hidden"){if(c.default===void 0)return null;let u=i?i.applyInputs(String(c.default),[],this.serializer):String(c.default);return this.serializer.nativeToString(c.type,u)}else return s[o]||null};return a.map((c,o)=>{let u=p(c,o),d=c.default!==void 0?i?i.applyInputs(String(c.default),[],this.serializer):String(c.default):void 0;return{input:c,value:u||(d!==void 0?this.serializer.nativeToString(c.type,d):null)}})}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,n,i){let a=this.getStringTypedInputs(e,n);return await this.getResolvedInputs(t,e,a,i)}async getModifiedInputs(t){let e=[];for(let n=0;n<t.length;n++){let i=t[n];if(i.input.modifier?.startsWith("scale:")){let[,a]=i.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(t.find(o=>o.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let c=Y(p,+s);e.push({...i,value:`${i.input.type}:${c}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=Y(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(l.Transform.Prefix)){let a=i.input.modifier.substring(l.Transform.Prefix.length),s=this.config.transform?.runner;if(!s||typeof s.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=this.buildInputContext(t,n,i),c=await s.run(a,p);if(c==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,c);e.push({...i,value:o})}}else e.push(i)}return e}buildInputContext(t,e,n){let i={};for(let a=0;a<e;a++){let s=t[a];if(!s.value)continue;let p=s.input.as||s.input.name,[,c]=this.serializer.stringToNative(s.value);if(i[p]=c,s.input.type==="asset"&&typeof c=="object"&&c!==null){let o=c;"identifier"in o&&"amount"in o&&(i[`${p}.token`]=String(o.identifier),i[`${p}.amount`]=String(o.amount),i[`${p}.identifier`]=String(o.identifier))}}if(n&&n.value){let a=n.input.as||n.input.name,[,s]=this.serializer.stringToNative(n.value);if(i[a]=s,n.input.type==="asset"&&typeof s=="object"&&s!==null){let p=s;"identifier"in p&&"amount"in p&&(i[`${a}.token`]=String(p.identifier),i[`${a}.amount`]=String(p.amount),i[`${a}.identifier`]=String(p.identifier))}}return i}async preprocessInput(t,e){try{let[n,i]=ht(e),a=v(t,this.adapters);if(n==="asset"){let[s,p,c]=i.split(l.ArgCompositeSeparator);if(c)return e;let o=await a.dataLoader.getAsset(s);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let u=Y(p,o.decimals);return qt({...o,amount:u})}else return e}catch(n){throw C.warn("WarpFactory: Preprocess input failed",n),n}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,e){let n="args"in t?t.args||[]:[],i=[];return e.forEach(({input:a,value:s})=>{if(!(!s||!a.position)){if(typeof a.position=="object"){if(a.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${a.name}" has type "${a.type}"`);if(!a.position.token?.startsWith("arg:")||!a.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${a.name}"`);let[p,c]=this.serializer.stringToNative(s),o=c;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let u=Number(a.position.token.split(":")[1])-1,d=Number(a.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",o.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",o.amount)})}else if(a.position.startsWith("arg:")){let p=Number(a.position.split(":")[1])-1;i.push({index:p,value:s})}}}),i.forEach(({index:a,value:s})=>{for(;n.length<=a;)n.push(void 0);n[a]=s}),n.filter(a=>a!==void 0)}async tryGetChainFromInputs(t,e){let n=t.actions.find(c=>c.inputs?.some(o=>o.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(c=>c.position==="chain");if(i===-1||i===void 0)return null;let a=e[i];if(!a)throw new Error("Chain input not found");let s=this.serializer.stringToNative(a)[1];return v(s,this.adapters).chainInfo}};var pt=class{constructor(t,e,n){this.config=t;this.adapters=e;this.handlers=n;this.handlers=n,this.factory=new G(t,e)}async execute(t,e,n={}){let i=[],a=null,s=[],p=[],{action:c,index:o}=B(t);for(let u=1;u<=t.actions.length;u++){let d=E(t,u);if(!ft(d,t))continue;let{tx:h,chain:m,immediateExecution:W,executable:f}=await this.executeAction(t,u,e,n);h&&i.push(h),m&&(a=m),W&&s.push(W),f&&u===o+1&&f.resolvedInputs&&(p=N(f.resolvedInputs))}if(!a&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&s.length>0){let u=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(u))}return{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p}}async executeAction(t,e,n,i={}){let a=E(t,e);if(a.type==="link")return a.when&&!await this.evaluateWhenCondition(t,a,n,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):Et.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let o=await this.executePrompt(t,a,e,n,i);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:null};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,executable:null}}}let s=await this.factory.createExecutable(t,e,n,i);if(a.when&&!await this.evaluateWhenCondition(t,a,n,i,s.resolvedInputs,s.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="collect"){let o=await this.executeCollect(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="mcp"){let o=await this.executeMcp(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,executable:s}}}let p=v(s.chain.name,this.adapters);if(a.type==="query"){let o=await p.executor.executeQuery(s);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.chain,execution:o,tx:null}));else{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,result:o})}return{tx:null,chain:s.chain,immediateExecution:o,executable:s}}return{tx:await p.executor.createTransaction(s),chain:s.chain,immediateExecution:null,executable:s}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=v(n.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!ft(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let c=e[p],o=p+1;if(!c){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),h={status:"error",warp:t,action:o,user:S(this.config,n.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,o,c);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:n,execution:u,tx:c})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).filter(s=>s!==null);if(a.every(s=>s.status==="success")){let s=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(s))}else{let s=a.find(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let n=S(this.config,t.chain.name),i=E(t.warp,t.action),a=this.factory.getSerializer(),s=rt(t.resolvedInputs,a);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,n,s,e);let{values:p,output:c}=await nt(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,n,"unhandled",p,c)}async doHttpRequest(t,e,n,i,a){let s=new R(this.config,v(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:c,method:o,headers:u,body:d}=await Xt(s,e,t,n,i,p,a,async h=>await this.callHandler(()=>this.handlers?.onSignRequest?.(h)));C.debug("WarpExecutor: Executing HTTP collect",{url:c,method:o,headers:u,body:d});try{let m=await fetch(c,{method:o,headers:u,body:d});C.debug("Collect response status",{status:m.status}),m.status===402&&(m=await Mt(m,c,o,d,this.adapters));let W=await m.json();C.debug("Collect response content",{content:W});let{values:f,output:y}=await nt(t.warp,W,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),m.ok?"success":"error",f,y,W)}catch(h){C.error("WarpActionExecutor: Error executing collect",h);let m=N(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:h},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let n=S(this.config,t.chain.name),i=E(t.warp,t.action);if(!i.destination){let m=N(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let W=N(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("Please install @modelcontextprotocol/sdk to execute MCP warps or mcp actions")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}let p=this.factory.getSerializer(),c=new R(this.config,v(t.chain.name,this.adapters),this.adapters),o=i.destination,u=c.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=c.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([m,W])=>{let f=c.applyInputs(W,t.resolvedInputs,this.factory.getSerializer());h[m]=f}),C.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:h});try{let m=new s(new URL(u),{requestInit:{headers:h}}),W=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await W.connect(m);let f={};t.resolvedInputs.forEach(({input:x,value:j})=>{if(j&&x.position&&typeof x.position=="string"&&x.position.startsWith("payload:")){let L=x.position.replace("payload:",""),[b,H]=p.stringToNative(j);if(b==="string")f[L]=String(H);else if(b==="bool")f[L]=!!H;else if(b==="uint8"||b==="uint16"||b==="uint32"||b==="uint64"||b==="uint128"||b==="uint256"||b==="biguint"){let _=Number(H);f[L]=(Number.isInteger(_),_)}else f[L]=H}}),e&&Object.assign(f,e);let y=await W.callTool({name:d,arguments:f});await W.close();let A;if(y.content&&y.content.length>0){let x=y.content[0];if(x.type==="text")try{A=JSON.parse(x.text)}catch{A=x.text}else x.type,A=x}else A=y;let{values:P,output:T}=await nt(t.warp,A,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,n,"success",P,T,y)}catch(m){C.error("WarpExecutor: Error executing MCP",m);let W=N(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:m},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}}buildCollectResult(t,e,n,i,a,s){let p=Wt(this.config,this.adapters,t.warp,t.action,a),c=N(t.resolvedInputs);return{status:n,warp:t.warp,action:t.action,user:e||S(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:mt(t.warp,a,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:c}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,n,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=v(s.name,this.adapters),c=new R(this.config,p,this.adapters),o=await c.apply(t,a),u=E(o,n),{action:d}=B(o),h=this.factory.getStringTypedInputs(d,i),m=await this.factory.getResolvedInputs(s.name,d,h,c),W=await this.factory.getModifiedInputs(m),f=W;if(e.inputs&&e.inputs.length>0){let T=this.factory.getStringTypedInputs(e,i),x=await this.factory.getResolvedInputs(s.name,e,T,c);f=await this.factory.getModifiedInputs(x)}let y=c.applyInputs(u.prompt,f,this.factory.getSerializer(),W),A=N(f),P=S(this.config,s.name);return{status:"success",warp:o,action:n,user:P,txHash:null,tx:null,next:Wt(this.config,this.adapters,o,n,{prompt:y}),values:{string:[y],native:[y],mapped:{prompt:y}},output:{prompt:y},messages:mt(o,{prompt:y},this.config),destination:null,resolvedInputs:A}}catch(s){return C.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:n,user:null,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:s},messages:{},destination:null,resolvedInputs:[]}}}async evaluateWhenCondition(t,e,n,i,a,s){if(!e.when)return!0;let p=s?{name:s}:await this.factory.getChainInfoForWarp(t,n),c=v(p.name,this.adapters),o=new R(this.config,c,this.adapters),{action:u}=B(t),d=this.factory.getStringTypedInputs(u,n),h=await this.factory.getResolvedInputs(p.name,u,d,o),m=await this.factory.getModifiedInputs(h),W;if(a)W=a;else{let A=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,n),o);W=await this.factory.getModifiedInputs(A)}let f=o.buildInputBag(W,this.factory.getSerializer(),m),y=Ht(e.when,f);return Ot(y)}};var ct=class{constructor(t){this.config=t}async search(t,e,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw C.error("WarpIndex: Error searching for warps: ",i),i}}};var lt=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!J(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(o=>o[0]).filter(o=>this.isValid(o)).map(o=>this.detect(o)),s=(await Promise.all(i)).filter(o=>o.match),p=s.length>0,c=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:c}}async detect(t,e){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?J(t):$(t);if(!i)return n;try{let{type:a,identifierBase:s}=i,p=null,c=null,o=null,u=v(i.chain,this.adapters),d=t.startsWith(l.HttpProtocolPrefix)?Vt(t):Ut(i.identifier);if(a==="hash"){p=await u.builder().createFromTransactionHash(s,e);let f=await u.registry.getInfoByHash(s,e);c=f.registryInfo,o=f.brand}else if(a==="alias"){let f=await u.registry.getInfoByAlias(s,e);c=f.registryInfo,o=f.brand,f.registryInfo&&(p=await u.builder().createFromTransactionHash(f.registryInfo.hash,e))}if(p&&p.meta&&(Le(p,u.chainInfo.name,c,i.identifier),p.meta.query=d),!p)return n;let h=p.chain||u.chainInfo.name,m=v(h,this.adapters),W=await new R(this.config,m,this.adapters).apply(p);return{match:!0,url:t,warp:W,chain:h,registryInfo:c,brand:o}}catch(a){return C.error("Error detecting warp link",a),n}}},Le=(r,t,e,n)=>{r.meta&&(r.meta.identifier=e?.alias?gt(t,"alias",e.alias):gt(t,"hash",e?.hash??n))};var Zt=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(n=>n(this.config))}getConfig(){return this.config}createExecutor(t){return new pt(this.config,this.chains,t)}async detectWarp(t,e){return new lt(this.config,this.chains).detect(t,e)}async executeWarp(t,e,n,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),p=a?t:null;if(!p&&s){let W=await fetch(t);if(!W.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await W.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let c=this.createExecutor(n),{txs:o,chain:u,immediateExecutions:d,resolvedInputs:h}=await c.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async W=>{await c.evaluateOutput(p,W)},resolvedInputs:h}}async createInscriptionTransaction(t,e){return await v(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,n=!1){return v(t,this.chains).builder().createFromTransaction(e,n)}async createFromTransactionHash(t,e){let n=$(t);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return v(n.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return v(t,this.chains).wallet.signMessage(e)}async getActions(t,e,n=!1){let i=this.getDataLoader(t);return(await Promise.all(e.map(async s=>i.getAction(s,n)))).filter(s=>s!==null)}getExplorer(t){return v(t,this.chains).explorer}getOutput(t){return v(t,this.chains).output}async getRegistry(t){let e=v(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return v(t,this.chains).dataLoader}getWallet(t){return v(t,this.chains).wallet}get factory(){return new G(this.config,this.chains)}get index(){return new ct(this.config)}get linkBuilder(){return new q(this.config,this.chains)}createBuilder(t){return v(t,this.chains).builder()}createAbiBuilder(t){return v(t,this.chains).abiBuilder()}createBrandBuilder(t){return v(t,this.chains).brandBuilder()}createSerializer(t){return v(t,this.chains).serializer}resolveText(t){return tt(t,this.config)}};var Yt=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};export{ut as BrowserCryptoProvider,Kt as CacheTtl,dt as NodeCryptoProvider,dr as WARP_LANGUAGES,zt as WarpBrandBuilder,kt as WarpBuilder,ot as WarpCache,wt as WarpCacheKey,oe as WarpChainName,Zt as WarpClient,F as WarpConfig,l as WarpConstants,pt as WarpExecutor,G as WarpFactory,ct as WarpIndex,g as WarpInputTypes,R as WarpInterpolator,q as WarpLinkBuilder,lt as WarpLinkDetecter,C as WarpLogger,M as WarpProtocolVersions,w as WarpSerializer,Yt as WarpTypeRegistry,it as WarpValidator,En as address,mt as applyOutputToMessages,qt as asset,Tn as biguint,bn as bool,rt as buildMappedOutput,ge as buildNestedPayload,nr as bytesToBase64,pe as bytesToHex,et as cleanWarpIdentifier,At as createAuthHeaders,vt as createAuthMessage,ar as createCryptoProvider,dn as createDefaultWalletProvider,Xr as createHttpAuthHeaders,Ae as createSignableMessage,gr as createWarpI18nText,gt as createWarpIdentifier,me as evaluateOutputCommon,Ot as evaluateWhenCondition,nt as extractCollectOutput,J as extractIdentifierInfoFromUrl,Ut as extractQueryStringFromIdentifier,Vt as extractQueryStringFromUrl,N as extractResolvedInputValues,pr as extractWarpSecrets,v as findWarpAdapterForChain,Rt as getCryptoProvider,Ke as getEventNameFromWarp,Z as getLatestProtocolIdentifier,Wt as getNextInfo,_r as getProviderConfig,Nt as getRandomBytes,Bt as getRandomHex,en as getWalletFromConfigOrFail,E as getWarpActionByIndex,Ze as getWarpBrandLogoUrl,Ye as getWarpChainAssetLogoUrl,tr as getWarpChainInfoLogoUrl,$ as getWarpInfoFromIdentifier,B as getWarpPrimaryAction,xe as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,Ie as getWarpWalletExternalId,Se as getWarpWalletExternalIdFromConfig,an as getWarpWalletExternalIdFromConfigOrFail,we as getWarpWalletMnemonic,nn as getWarpWalletMnemonicFromConfig,Ce as getWarpWalletPrivateKey,rn as getWarpWalletPrivateKeyFromConfig,Mt as handleX402Payment,xr as hasInputPrefix,Rn as hex,ln as initializeWalletCache,Wr as isEqualWarpIdentifier,ft as isWarpActionAutoExecute,fr as isWarpI18nText,sn as isWarpWalletReadOnly,Dt as mergeNestedPayload,pn as normalizeAndValidateMnemonic,Pe as normalizeMnemonic,Nn as option,ve as parseOutputOutIndex,Yr as parseSignedMessage,U as replacePlaceholders,Ht as replacePlaceholdersInWhenExpression,tt as resolveWarpText,Et as safeWindow,rr as setCryptoProvider,on as setWarpWalletInConfig,Y as shiftBigintBy,ht as splitInput,Cn as string,$n as struct,ir as testCryptoAvailability,he as toInputPayloadValue,$t as toPreviewText,Bn as tuple,In as uint16,Sn as uint32,Pn as uint64,wn as uint8,Te as validateMnemonicLength,Zr as validateSignedMessage,Hn as vector,_e as withAdapterFallback};
1
+ var oe=(d=>(d.Multiversx="multiversx",d.Vibechain="vibechain",d.Sui="sui",d.Ethereum="ethereum",d.Base="base",d.Arbitrum="arbitrum",d.Polygon="polygon",d.Somnia="somnia",d.Fastset="fastset",d.Solana="solana",d.Near="near",d))(oe||{}),l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.adapter.chainInfo.name]},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:n=>{if(!n.adapter.wallet)return null;try{return n.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:n=>n.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},g={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},Et=typeof window<"u"?window:{open:()=>{}};var M={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},F={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${M.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${M.Brand}.schema.json`,DefaultClientUrl:n=>n==="devnet"?"https://devnet.usewarp.to":n==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",l.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var Je=(n,t)=>(e,r)=>{let i=t(e,r);return n(e,i)};var Xe=(n,t)=>{let e=n.alerts?.[t];if(!e)return null;let r=l.Alerts.TriggerEventPrefix+l.ArgParamsSeparator;if(!e.trigger.startsWith(r))return null;let i=e.trigger.replace(r,"");return i||null};var Ye=(n,t)=>{let e=t?.preferences?.theme??"light";return typeof n.logo=="string"?n.logo:n.logo[e]},tr=(n,t)=>{if(!n.logoUrl)return null;if(typeof n.logoUrl=="string")return n.logoUrl;let e=t?.preferences?.theme??"light";return n.logoUrl[e]},er=(n,t)=>{if(typeof n.logoUrl=="string")return n.logoUrl;let e=t?.preferences?.theme??"light";return n.logoUrl[e]};var ut=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let e=new Uint8Array(t);return window.crypto.getRandomValues(e),e}},dt=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let e=await import("crypto");return new Uint8Array(e.randomBytes(t))}catch(e){throw new Error(`Node.js crypto not available: ${e instanceof Error?e.message:"Unknown error"}`)}}},V=null;function Rt(){if(V)return V;if(typeof window<"u"&&window.crypto)return V=new ut,V;if(typeof process<"u"&&process.versions?.node)return V=new dt,V;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function nr(n){V=n}async function Nt(n,t){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(t||Rt()).getRandomBytes(n)}function pe(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(n.length*2);for(let e=0;e<n.length;e++){let r=n[e];t[e*2]=(r>>>4).toString(16),t[e*2+1]=(r&15).toString(16)}return t.join("")}function ir(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(n).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(n));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function Bt(n,t){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let e=await Nt(n/2,t);return pe(e)}async function ar(){let n={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?n.environment="browser":typeof process<"u"&&process.versions?.node&&(n.environment="nodejs"),await Nt(16),n.randomBytes=!0}catch{}return n}function sr(){return Rt()}var cr=n=>Object.values(n.vars||{}).filter(t=>t.startsWith(`${l.Vars.Env}:`)).map(t=>{let e=t.replace(`${l.Vars.Env}:`,"").trim(),[r,i]=e.split(l.ArgCompositeSeparator);return{key:r,description:i||null}});var v=(n,t)=>{let e=t.find(r=>r.chainInfo.name.toLowerCase()===n.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${n}`);return e},Z=n=>{if(n==="warp")return`warp:${M.Warp}`;if(n==="brand")return`brand:${M.Brand}`;if(n==="abi")return`abi:${M.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},E=(n,t)=>n?.actions[t-1],B=n=>{if(n.actions.length===0)throw new Error(`Warp has no primary action: ${n.meta?.identifier}`);let t=n.actions.find(a=>a.primary===!0);if(t)return{action:t,index:n.actions.indexOf(t)};let e=["transfer","contract","query","collect","mcp"],r=n.actions.find(a=>e.includes(a.type));return r?{action:r,index:n.actions.indexOf(r)}:{action:n.actions[0],index:0}},ft=(n,t)=>{if(n.auto===!1)return!1;if(n.type==="link"){if(n.auto===!0)return!0;let{action:e}=B(t);return n===e}return!0},Y=(n,t)=>{let e=n.toString(),[r,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(r+i.padEnd(a,"0"));if(t<0){let s=r+i;if(a>=s.length)return 0n;let p=s.slice(0,-a)||"0";return BigInt(p)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},$t=(n,t=100)=>{if(!n)return"";let e=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},U=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(e,r)=>t[r]||""),Ht=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(e,r)=>{let i=t[r];return i==null?"":typeof i=="string"?`'${i.replace(/'/g,"\\'")}'`:String(i)}),Ot=n=>{if(!n||typeof n!="string")return!0;try{return!!new Function(`return ${n}`)()}catch(t){throw new Error(`Failed to evaluate 'when' condition: ${n}. Error: ${t}`)}};var fr={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},tt=(n,t)=>{let e=t?.preferences?.locale||"en";if(typeof n=="string")return n;if(typeof n=="object"&&n!==null){if(e in n)return n[e];if("en"in n)return n.en;let r=Object.keys(n);if(r.length>0)return n[r[0]]}return""},gr=n=>typeof n=="object"&&n!==null&&Object.keys(n).length>0,hr=n=>n;var et=n=>n.startsWith(l.IdentifierAliasMarker)?n.replace(l.IdentifierAliasMarker,""):n,vr=(n,t)=>!n||!t?!1:et(n)===et(t),gt=(n,t,e)=>{let r=et(e);return t===l.IdentifierType.Alias?l.IdentifierAliasMarker+n+l.IdentifierParamSeparator+r:n+l.IdentifierParamSeparator+t+l.IdentifierParamSeparator+r},$=n=>{let t=decodeURIComponent(n).trim(),e=et(t),r=e.split("?")[0],i=Ft(r);if(r.length===64&&/^[a-fA-F0-9]+$/.test(r))return{chain:l.IdentifierChainDefault,type:l.IdentifierType.Hash,identifier:e,identifierBase:r};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[a,s,p]=i;if(s===l.IdentifierType.Alias||s===l.IdentifierType.Hash){let c=e.includes("?")?p+e.substring(e.indexOf("?")):p;return{chain:a,type:s,identifier:c,identifierBase:p}}}if(i.length===2){let[a,s]=i;if(a===l.IdentifierType.Alias||a===l.IdentifierType.Hash){let p=e.includes("?")?s+e.substring(e.indexOf("?")):s;return{chain:l.IdentifierChainDefault,type:a,identifier:p,identifierBase:s}}}if(i.length===2){let[a,s]=i;if(a!==l.IdentifierType.Alias&&a!==l.IdentifierType.Hash){let p=e.includes("?")?s+e.substring(e.indexOf("?")):s,c=ce(s,a)?l.IdentifierType.Hash:l.IdentifierType.Alias;return{chain:a,type:c,identifier:p,identifierBase:s}}}return{chain:l.IdentifierChainDefault,type:l.IdentifierType.Alias,identifier:e,identifierBase:r}},J=n=>{let t=new URL(n),r=t.searchParams.get(l.IdentifierParamName);if(r||(r=t.pathname.split("/")[1]),!r)return null;let i=decodeURIComponent(r);return $(i)},ce=(n,t)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,le=n=>{let t=l.IdentifierParamSeparator,e=n.indexOf(t);return e!==-1?{separator:t,index:e}:null},Ft=n=>{let t=le(n);if(!t)return[n];let{separator:e,index:r}=t,i=n.substring(0,r),a=n.substring(r+e.length),s=Ft(a);return[i,...s]},Vt=n=>{try{let t=new URL(n),e=new URLSearchParams(t.search);return e.delete(l.IdentifierParamName),e.toString()||null}catch{return null}},Ut=n=>{let t=n.indexOf("?");if(t===-1||t===n.length-1)return null;let e=n.substring(t+1);return e.length>0?e:null};var ht=n=>{let[t,...e]=n.split(/:(.*)/,2);return[t,e[0]||""]},xr=n=>{let t=new Set(Object.values(g));if(!n.includes(l.ArgParamsSeparator))return!1;let e=ht(n)[0];return t.has(e)};var mt=(n,t,e)=>{let r=Object.entries(n.messages||{}).map(([i,a])=>{let s=tt(a,e);return[i,U(s,t)]});return Object.fromEntries(r)};import ue from"qr-code-styling";var q=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!J(t):!1}build(t,e,r){let i=this.config.clientUrl||F.DefaultClientUrl(this.config.env),a=v(t,this.adapters),s=e===l.IdentifierType.Alias?r:e+l.IdentifierParamSeparator+r,p=a.chainInfo.name+l.IdentifierParamSeparator+s,c=encodeURIComponent(p);return F.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${l.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let e=$(t);if(!e)return null;let r=v(e.chain,this.adapters);return r?this.build(r.chainInfo.name,e.type,e.identifierBase):null}generateQrCode(t,e,r,i=512,a="white",s="black",p="#23F7DD"){let c=v(t,this.adapters),o=this.build(c.chainInfo.name,e,r);return new ue({type:"svg",width:i,height:i,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(p)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var de="https://",Wt=(n,t,e,r,i)=>{let a=e.actions?.[r-1]?.next||e.next||null;if(!a)return null;if(a.startsWith(de))return[{identifier:null,url:a}];let[s,p]=a.split("?");if(!p){let f=U(s,{...e.vars,...i});return[{identifier:f,url:yt(t,f,n)}]}let c=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let f=U(p,{...e.vars,...i}),y=f?`${s}?${f}`:s;return[{identifier:y,url:yt(t,y,n)}]}let o=c[0];if(!o)return[];let u=o.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||i[d]===void 0)return[];let h=Array.isArray(i[d])?i[d]:[i[d]];if(h.length===0)return[];let m=c.filter(f=>f.includes(`{{${d}[]`)).map(f=>{let y=f.match(/\[\](\.[^}]+)?}}/),A=y&&y[1]||"";return{placeholder:f,field:A?A.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let y=p;for(let{regex:P,field:b}of m){let C=b?fe(f,b):f;if(C==null)return null;y=y.replace(P,C)}if(y.includes("{{")||y.includes("}}"))return null;let A=y?`${s}?${y}`:s;return{identifier:A,url:yt(t,A,n)}}).filter(f=>f!==null)},yt=(n,t,e)=>{let[r,i]=t.split("?"),a=$(r)||{chain:l.IdentifierChainDefault,type:"alias",identifier:r,identifierBase:r},s=v(a.chain,n);if(!s)throw new Error(`Adapter not found for chain ${a.chain}`);let p=new q(e,n).build(s.chainInfo.name,a.type,a.identifierBase);if(!i)return p;let c=new URL(p);return new URLSearchParams(i).forEach((o,u)=>c.searchParams.set(u,o)),c.toString().replace(/\/\?/,"?")},fe=(n,t)=>t.split(".").reduce((e,r)=>e?.[r],n);var D=class D{static debug(...t){D.isTestEnv||console.debug(...t)}static info(...t){D.isTestEnv||console.info(...t)}static warn(...t){D.isTestEnv||console.warn(...t)}static error(...t){D.isTestEnv||console.error(...t)}};D.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var x=D;function ge(n,t,e){return n.startsWith(l.Position.Payload)?n.slice(l.Position.Payload.length).split(".").reduceRight((r,i,a,s)=>({[i]:a===s.length-1?{[t]:e}:r}),{}):{[t]:e}}function Dt(n,t){if(!n)return{...t};if(!t)return{...n};let e={...n};return Object.keys(t).forEach(r=>{e[r]&&typeof e[r]=="object"&&typeof t[r]=="object"?e[r]=Dt(e[r],t[r]):e[r]=t[r]}),e}function he(n,t){if(!n.value)return null;let e=t.stringToNative(n.value)[1];if(n.input.type==="biguint")return e.toString();if(n.input.type==="asset"){let{identifier:r,amount:i}=e;return{identifier:r,amount:i.toString()}}else return e}function N(n){return n.map(t=>t.value).filter(t=>t!=null&&t!=="")}function rt(n,t){let e={};return n.forEach(r=>{let i=r.input.as||r.input.name,a=he(r,t);if(r.input.position&&typeof r.input.position=="string"&&r.input.position.startsWith(l.Position.Payload)){let s=ge(r.input.position,i,a);e=Dt(e,s)}else e[i]=a}),e}var nt=async(n,t,e,r,i,a)=>{let s=[],p=[],c={};for(let[u,d]of Object.entries(n.output||{})){if(d.startsWith(l.Transform.Prefix))continue;let h=ve(d);if(h!==null&&h!==e){c[u]=null;continue}let[m,...W]=d.split("."),f=(y,A)=>A.reduce((P,b)=>P&&P[b]!==void 0?P[b]:null,y);if(m==="out"||m.startsWith("out[")){let y=W.length===0?t?.data||t:f(t,W);s.push(String(y)),p.push(y),c[u]=y}else c[u]=d}let o=rt(r,i);return{values:{string:s,native:p,mapped:o},output:await me(n,c,e,r,i,a)}},me=async(n,t,e,r,i,a)=>{if(!n.output)return t;let s={...t};return s=ye(s,n,e,r,i),s=await We(n,s,a.transform?.runner||null),s},ye=(n,t,e,r,i)=>{let a={...n},s=E(t,e)?.inputs||[];for(let[p,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("in.")){let o=c.split(".")[1],u=s.findIndex(h=>h.as===o||h.name===o),d=u!==-1?r[u]?.value:null;a[p]=d?i.stringToNative(d)[1]:null}return a},We=async(n,t,e)=>{if(!n.output)return t;let r={...t},i=Object.entries(n.output).filter(([,a])=>a.startsWith(l.Transform.Prefix)).map(([a,s])=>({key:a,code:s.substring(l.Transform.Prefix.length)}));if(i.length>0&&(!e||typeof e.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:a,code:s}of i)try{r[a]=await e.run(s,r)}catch(p){x.error(`Transform error for output '${a}':`,p),r[a]=null}return r},ve=n=>{if(n==="out")return 1;let t=n.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};var Jr=(n,t,e,r)=>{let i=n.preferences?.providers?.[t];return i?.[e]?typeof i[e]=="string"?{url:i[e]}:i[e]:{url:r}};async function Ae(n,t,e,r=5){let i=await Bt(64,e),a=new Date(Date.now()+r*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:i,expiresAt:a,purpose:t}),nonce:i,expiresAt:a}}async function vt(n,t,e,r){let i=r||`prove-wallet-ownership for app "${t}"`;return Ae(n,i,e,5)}function At(n,t,e,r){return{"X-Signer-Wallet":n,"X-Signer-Signature":t,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":r}}async function Zr(n,t,e,r){let{message:i,nonce:a,expiresAt:s}=await vt(n,e,r),p=await t(i);return At(n,p,a,s)}function Yr(n){let t=new Date(n).getTime();return Date.now()<t}function tn(n){try{let t=JSON.parse(n);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var rn=(n,t)=>{let e=n.user?.wallets?.[t]||null;if(!e)throw new Error(`No wallet configured for chain ${t}`);return e},Ce=n=>n?typeof n=="string"?n:n.address:null,S=(n,t)=>Ce(n.user?.wallets?.[t]||null),xe=n=>n?typeof n=="string"?n:n.privateKey||null:null,we=n=>n?typeof n=="string"?n:n.mnemonic||null:null,Ie=n=>n?typeof n=="string"?n:n.externalId||null:null,nn=(n,t)=>xe(n.user?.wallets?.[t]||null)?.trim()||null,an=(n,t)=>we(n.user?.wallets?.[t]||null)?.trim()||null,Se=(n,t)=>Ie(n.user?.wallets?.[t]||null)?.trim()||null,sn=(n,t)=>{let e=Se(n,t);if(!e)throw new Error(`No external ID configured for wallet onchain ${t}`);return e},on=n=>typeof n=="string",pn=(n,t,e)=>{n.user||(n.user={}),n.user.wallets||(n.user.wallets={}),n.user.wallets[t]=e},Pe=n=>{if(!n)throw new Error("Mnemonic is required");return typeof n=="string"?n.trim():String(n).trim()},be=(n,t=24)=>{let e=n.split(/\s+/).filter(r=>r.length>0);if(e.length!==t)throw new Error(`Mnemonic must be ${t} words. Got ${e.length} words`)},cn=(n,t=24)=>{let e=Pe(n);return be(e,t),e};async function un(n){let t={address:null,publicKey:null};if(!n)return t;try{t.address=await n.getAddress()}catch{}try{t.publicKey=await n.getPublicKey()}catch{}return t}function fn(n,t,e){return null}import{x402Client as jt}from"@x402/core/client";import{x402HTTPClient as Lt}from"@x402/core/http";async function Mt(n,t,e,r,i){let a=await Te(n,i);if(!a)return n;let s=new Headers;r&&s.set("Content-Type","application/json"),s.set("Accept","application/json"),Object.entries(a).forEach(([c,o])=>{s.set(c,o)}),x.debug("WarpExecutor: Retrying request with payment headers");let p=await fetch(t,{method:e,headers:s,body:r});return x.debug("WarpExecutor: Payment processed, new response status",{status:p.status}),p}var Te=async(n,t)=>{let e=await Ee(n),i=new Lt(new jt).getPaymentRequiredResponse(a=>n.headers.get(a),e);if(!i?.accepts?.length)return null;for(let a of t)if(a.wallet.registerX402Handlers)try{let s=new jt,p=await a.wallet.registerX402Handlers(s),c=i.accepts.find(h=>h?.network&&p[h.network]);if(!c?.network)continue;p[c.network]();let o=new Lt(s),u=await o.createPaymentPayload(i);if(!u||typeof u!="object")continue;let d=o.encodePaymentSignatureHeader(u);if(!d||typeof d!="object")continue;return x.debug(`WarpExecutor: x402 payment processed with ${a.chainInfo.name} adapter using ${c.network} scheme`),d}catch{continue}return null},Ee=async n=>{try{let t=await n.clone().text();return t?JSON.parse(t):{}}catch{return{}}};var w=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,e){if(t===g.Tuple&&Array.isArray(e)){if(e.length===0)return t+l.ArgParamsSeparator;if(e.every(r=>typeof r=="string"&&r.includes(l.ArgParamsSeparator))){let r=e.map(s=>this.getTypeAndValue(s)),i=r.map(([s])=>s),a=r.map(([,s])=>s);return`${t}(${i.join(l.ArgCompositeSeparator)})${l.ArgParamsSeparator}${a.join(l.ArgListSeparator)}`}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===g.Struct&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let r=e;if(!r._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=r._name,a=Object.keys(r).filter(p=>p!=="_name");if(a.length===0)return`${t}(${i})${l.ArgParamsSeparator}`;let s=a.map(p=>{let[c,o]=this.getTypeAndValue(r[p]);return`(${p}${l.ArgParamsSeparator}${c})${o}`});return`${t}(${i})${l.ArgParamsSeparator}${s.join(l.ArgListSeparator)}`}if(t===g.Vector&&Array.isArray(e)){if(e.length===0)return`${t}${l.ArgParamsSeparator}`;if(e.every(r=>typeof r=="string"&&r.includes(l.ArgParamsSeparator))){let r=e[0],i=r.indexOf(l.ArgParamsSeparator),a=r.substring(0,i),s=e.map(c=>{let o=c.indexOf(l.ArgParamsSeparator),u=c.substring(o+1);return a.startsWith(g.Tuple)?u.replace(l.ArgListSeparator,l.ArgCompositeSeparator):u}),p=a.startsWith(g.Struct)?l.ArgStructSeparator:l.ArgListSeparator;return t+l.ArgParamsSeparator+a+l.ArgParamsSeparator+s.join(p)}return t+l.ArgParamsSeparator+e.join(l.ArgListSeparator)}if(t===g.Asset&&typeof e=="object"&&e&&"identifier"in e&&"amount"in e)return"decimals"in e?g.Asset+l.ArgParamsSeparator+e.identifier+l.ArgCompositeSeparator+String(e.amount)+l.ArgCompositeSeparator+String(e.decimals):g.Asset+l.ArgParamsSeparator+e.identifier+l.ArgCompositeSeparator+String(e.amount);if(this.typeRegistry){let r=this.typeRegistry.getHandler(t);if(r)return r.nativeToString(e);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,e)}return t+l.ArgParamsSeparator+(e?.toString()??"")}stringToNative(t){let e=t.split(l.ArgParamsSeparator),r=e[0],i=e.slice(1).join(l.ArgParamsSeparator);if(r==="null")return[r,null];if(r===g.Option){let[a,s]=i.split(l.ArgParamsSeparator);return[g.Option+l.ArgParamsSeparator+a,s||null]}if(r===g.Vector){let a=i.indexOf(l.ArgParamsSeparator),s=i.substring(0,a),p=i.substring(a+1),c=s.startsWith(g.Struct)?l.ArgStructSeparator:l.ArgListSeparator,u=(p?p.split(c):[]).map(d=>this.stringToNative(s+l.ArgParamsSeparator+d)[1]);return[g.Vector+l.ArgParamsSeparator+s,u]}else if(r.startsWith(g.Tuple)){let a=r.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),p=i.split(l.ArgCompositeSeparator).map((c,o)=>this.stringToNative(`${a[o]}${l.IdentifierParamSeparator}${c}`)[1]);return[r,p]}else if(r.startsWith(g.Struct)){let a=r.match(/\(([^)]+)\)/);if(!a)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:a[1]};return i&&i.split(l.ArgListSeparator).forEach(c=>{let o=c.match(new RegExp(`^\\(([^${l.ArgParamsSeparator}]+)${l.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(o){let[,u,d,h]=o;p[u]=this.stringToNative(`${d}${l.IdentifierParamSeparator}${h}`)[1]}}),[r,p]}else{if(r===g.String)return[r,i];if(r===g.Uint8||r===g.Uint16||r===g.Uint32)return[r,Number(i)];if(r===g.Uint64||r===g.Uint128||r===g.Uint256||r===g.Biguint)return[r,BigInt(i||0)];if(r===g.Bool)return[r,i==="true"];if(r===g.Address)return[r,i];if(r===g.Hex)return[r,i];if(r===g.Asset){let[a,s]=i.split(l.ArgCompositeSeparator),p={identifier:a,amount:BigInt(s)};return[r,p]}}if(this.typeRegistry){let a=this.typeRegistry.getHandler(r);if(a){let p=a.stringToNative(i);return[r,p]}let s=this.typeRegistry.resolveType(r);if(s!==r){let[p,c]=this.stringToNative(`${s}:${i}`);return[r,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(l.ArgParamsSeparator)){let[e,r]=t.split(l.ArgParamsSeparator);return[e,r]}return typeof t=="number"?[g.Uint32,t]:typeof t=="bigint"?[g.Uint64,t]:typeof t=="boolean"?[g.Bool,t]:[typeof t,t]}};var wn=n=>new w().nativeToString(g.String,n),In=n=>new w().nativeToString(g.Uint8,n),Sn=n=>new w().nativeToString(g.Uint16,n),Pn=n=>new w().nativeToString(g.Uint32,n),bn=n=>new w().nativeToString(g.Uint64,n),Tn=n=>new w().nativeToString(g.Biguint,n),En=n=>new w().nativeToString(g.Bool,n),Rn=n=>new w().nativeToString(g.Address,n),qt=n=>new w().nativeToString(g.Asset,n),Nn=n=>new w().nativeToString(g.Hex,n),Bn=(n,t)=>{if(t===null)return g.Option+l.ArgParamsSeparator;let e=n(t),r=e.indexOf(l.ArgParamsSeparator),i=e.substring(0,r),a=e.substring(r+1);return g.Option+l.ArgParamsSeparator+i+l.ArgParamsSeparator+a},$n=(...n)=>new w().nativeToString(g.Tuple,n),Hn=n=>new w().nativeToString(g.Struct,n),On=n=>new w().nativeToString(g.Vector,n);import Re from"ajv";var zt=class{constructor(t){this.pendingBrand={protocol:Z("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.ensureValidSchema(r),r}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}ensureWarpText(t,e){if(!t)throw new Error(`Warp: ${e}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||F.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),a=new Re,s=a.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(s.errors)}`)}};import Ne from"ajv";var it=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validatePrimaryAction(t)),e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validatePrimaryAction(t){try{let{action:e}=B(t);return e?[]:["Primary action is required"]}catch(e){return[e instanceof Error?e.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(r=>r.inputs?r.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],r=(i,a)=>{i&&Object.keys(i).forEach(s=>{s!==s.toUpperCase()&&e.push(`${a} name '${s}' must be uppercase`)})};return r(t.vars,"Variable"),r(t.output,"Output"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(s=>s.type==="contract"),r=t.actions.some(s=>s.type==="query");if(!e&&!r)return[];let i=t.actions.some(s=>s.abi),a=Object.values(t.output||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.output&&!i&&a?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||F.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new Ne({strict:!1}),s=a.compile(i);return s(t)?[]:[`Schema validation failed: ${a.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var kt=class{constructor(t){this.config=t;this.pendingWarp={protocol:Z("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.validate(r),r}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}setOutput(t){return this.pendingWarp.output=t??void 0,this}async build(t=!0){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),t&&await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return $t(t,e)}ensure(t,e){if(!t)throw new Error(e)}ensureWarpText(t,e){if(!t)throw new Error(e);if(typeof t=="object"&&!t.en)throw new Error(e)}async validate(t){let r=await new it(this.config).validate(t);if(!r.valid)throw new Error(r.errors.join(`
2
+ `))}};import{existsSync as Ct,mkdirSync as Be,readdirSync as $e,readFileSync as He,unlinkSync as xt,writeFileSync as Oe}from"fs";import{join as _t,resolve as Jt}from"path";var Gt=new w,z=(n,t)=>typeof t=="bigint"?Gt.nativeToString("biguint",t):t,k=(n,t)=>typeof t=="string"&&t.startsWith(g.Biguint+":")?Gt.stringToNative(t)[1]:t;var at=class{constructor(t,e){let r=e?.path;this.cacheDir=r?Jt(r):Jt(process.cwd(),".warp-cache"),this.ensureCacheDir()}ensureCacheDir(){Ct(this.cacheDir)||Be(this.cacheDir,{recursive:!0})}getFilePath(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return _t(this.cacheDir,`${e}.json`)}get(t){try{let e=this.getFilePath(t);if(!Ct(e))return null;let r=He(e,"utf-8"),i=JSON.parse(r,k);return Date.now()>i.expiresAt?(xt(e),null):i.value}catch{return null}}set(t,e,r){let i={value:e,expiresAt:Date.now()+r*1e3},a=this.getFilePath(t);Oe(a,JSON.stringify(i,z),"utf-8")}forget(t){try{let e=this.getFilePath(t);Ct(e)&&xt(e)}catch{}}clear(){try{$e(this.cacheDir).forEach(e=>{e.endsWith(".json")&&xt(_t(this.cacheDir,e))})}catch{}}};var Q=class{constructor(t,e){this.prefix="warp-cache"}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let r=JSON.parse(e,k);return Date.now()>r.expiresAt?(localStorage.removeItem(this.getKey(t)),null):r.value}catch{return null}}set(t,e,r){let i={value:e,expiresAt:Date.now()+r*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,z))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var O=class O{constructor(t,e){}get(t){let e=O.cache.get(t);return e?Date.now()>e.expiresAt?(O.cache.delete(t),null):e.value:null}set(t,e,r){let i=Date.now()+r*1e3;O.cache.set(t,{value:e,expiresAt:i})}forget(t){O.cache.delete(t)}clear(){O.cache.clear()}};O.cache=new Map;var K=O;import{readFileSync as Fe,writeFileSync as Ve}from"fs";import{extname as Ue,resolve as Qt}from"path";var st=class{constructor(t,e){this.manifestPath=this.resolveManifestPath(t,e),this.cache=this.loadManifest()}loadManifest(){try{let t=Fe(this.manifestPath,"utf-8");return new Map(Object.entries(JSON.parse(t,k)))}catch{return new Map}}saveManifest(){let t=JSON.stringify(Object.fromEntries(this.cache.entries()),z);Ve(this.manifestPath,t,"utf-8")}get(t){let e=this.cache.get(t);return!e||Date.now()>e.expiresAt?(e&&(this.cache.delete(t),this.saveManifest()),null):e.value}set(t,e,r){let i=Date.now()+r*1e3,a={value:e,expiresAt:i};this.cache.set(t,a),this.saveManifest()}forget(t){this.cache.delete(t)&&this.saveManifest()}clear(){this.cache.clear(),this.saveManifest()}resolveManifestPath(t,e){let r=e?.path;if(r){let i=Qt(r),a=Ue(i);return`${a?i.slice(0,-a.length):i}-${t}${a||".json"}`}return Qt(process.cwd(),`warps-manifest-${t}.json`)}};var Kt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},wt={Warp:(n,t)=>`warp:${n}:${t}`,WarpAbi:(n,t)=>`warp-abi:${n}:${t}`,WarpExecutable:(n,t,e)=>`warp-exec:${n}:${t}:${e}`,RegistryInfo:(n,t)=>`registry-info:${n}:${t}`,Brand:(n,t)=>`brand:${n}:${t}`,Asset:(n,t,e)=>`asset:${n}:${t}:${e}`},ot=class{constructor(t,e){this.strategy=this.selectStrategy(t,e)}selectStrategy(t,e){return e?.type==="localStorage"?new Q(t,e):e?.type==="memory"?new K(t,e):e?.type==="static"?new st(t,e):e?.type==="filesystem"?new at(t,e):typeof window<"u"&&window.localStorage?new Q(t,e):new K(t,e)}set(t,e,r){this.strategy.set(t,e,r)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var X={Queries:"QUERIES",Payload:"PAYLOAD",Headers:"HEADERS"},It={Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE"},St=(n,t,e)=>{let r=n.find(a=>a.input.as===t||a.input.name===t);if(!r?.value)return null;let[,i]=e.stringToNative(r.value);return typeof i=="string"?i:String(i)},Pt=n=>{try{return JSON.parse(n)}catch{return null}},De=async(n,t,e,r,i,a)=>{let s=new Headers;if(s.set("Content-Type","application/json"),s.set("Accept","application/json"),a&&r){let{message:c,nonce:o,expiresAt:u}=await vt(r,`${e.chain.name}-adapter`),d=await a({message:c,chain:e.chain});d&&Object.entries(At(r,d,o,u)).forEach(([h,m])=>s.set(h,m))}let p=St(e.resolvedInputs,X.Headers,i);if(p){let c=Pt(p);c&&typeof c=="object"&&Object.entries(c).forEach(([o,u])=>typeof u=="string"&&s.set(o,u))}else t.headers&&Object.entries(t.headers).forEach(([c,o])=>{s.set(c,n.applyInputs(o,e.resolvedInputs,i))});return s},je=(n,t,e,r,i)=>{let a=n.applyInputs(t.url,e.resolvedInputs,i);if(r===It.Get){let s=St(e.resolvedInputs,X.Queries,i);if(s){let p=Pt(s);if(p&&typeof p=="object"){let c=new URL(a);Object.entries(p).forEach(([o,u])=>u!=null&&c.searchParams.set(o,String(u))),a=c.toString()}}}return a},Le=(n,t,e,r,i)=>{if(n===It.Get)return;let a=St(t.resolvedInputs,X.Payload,r);if(a&&Pt(a)!==null)return a;let{[X.Payload]:s,[X.Queries]:p,...c}=e;return JSON.stringify({...c,...i})},Xt=async(n,t,e,r,i,a,s,p)=>{let c=t.method||It.Get,o=await De(n,t,e,r,a,p),u=je(n,t,e,c,a),d=Le(c,e,i,a,s);return{url:u,method:c,headers:o,body:d}};var R=class{constructor(t,e,r){this.config=t;this.adapter=e;this.adapters=r}async apply(t,e={}){let r=this.applyVars(t,e);return await this.applyGlobals(r)}async applyGlobals(t){let e={...t};return e.actions=await Promise.all((e.actions||[]).map(async r=>await this.applyActionGlobals(r))),e=await this.applyRootGlobals(e),e}applyVars(t,e={}){if(!t?.vars)return t;let r=S(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),a=(s,p)=>{i=i.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(t.vars).forEach(([s,p])=>{if(typeof p!="string")a(s,p);else if(p.startsWith(l.Vars.Query+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Query.length+1),[o,u]=c.split(l.ArgCompositeSeparator),d=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(o):null,m=e.queries?.[o]||null||d;m&&a(s,m)}else if(p.startsWith(l.Vars.Env+l.ArgParamsSeparator)){let c=p.slice(l.Vars.Env.length+1),[o,u]=c.split(l.ArgCompositeSeparator),h={...this.config.vars,...e.envs}?.[o];h&&a(s,h)}else p===l.Source.UserWallet&&r?a(s,r):a(s,p)}),JSON.parse(i)}async applyRootGlobals(t){let e=JSON.stringify(t),r={config:this.config,adapter:this.adapter};return Object.values(l.Globals).forEach(i=>{let a=i.Accessor(r);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,r,i.Accessor)}),JSON.parse(e)}async applyActionGlobals(t){let e=JSON.stringify(t),r={config:this.config,adapter:this.adapter};return Object.values(l.Globals).forEach(i=>{let a=i.Accessor(r);a!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),a.toString())),e=this.replacePlaceholdersWithChain(e,i.Placeholder,r,i.Accessor)}),JSON.parse(e)}applyInputs(t,e,r,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let a=this.applyGlobalsToText(t),s=this.buildInputBag(e,r,i);return U(a,s)}applyGlobalsToText(t){if(!Object.values(l.Globals).map(s=>s.Placeholder).some(s=>t.includes(`{{${s}}}`)||t.includes(`{{${s}:`)))return t;let i={config:this.config,adapter:this.adapter},a=t;return Object.values(l.Globals).forEach(s=>{let p=s.Accessor(i);p!=null&&(a=a.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),p.toString())),a=this.replacePlaceholdersWithChain(a,s.Placeholder,i,s.Accessor)}),a}replacePlaceholdersWithChain(t,e,r,i){let a=new RegExp(`\\{\\{${e}:([^}]+)\\}\\}`,"g");return t.replace(a,(s,p)=>{let c=p.trim().toLowerCase();if(!this.adapters)return s;try{let o=v(c,this.adapters),u={config:this.config,adapter:o},d=i(u);return d!=null?d.toString():s}catch{return s}})}buildInputBag(t,e,r){let i={};return t.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);i[s]=String(p)}),r&&r.forEach(a=>{if(!a.value)return;let s=a.input.as||a.input.name,[,p]=e.stringToNative(a.value);if(i[`primary.${s}`]=String(p),a.input.type==="asset"&&typeof a.input.position=="object"){let c=p;c&&typeof c=="object"&&"identifier"in c&&"amount"in c&&(i[`primary.${s}.token`]=String(c.identifier),i[`primary.${s}.amount`]=String(c.amount))}}),i}};var G=class{constructor(t,e){this.config=t;this.adapters=e;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new w,this.cache=new ot(t.env,t.cache)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,e,r){let i=this.cache.get(wt.WarpExecutable(t,e||"",r))||[];return N(i)}async createExecutable(t,e,r,i={}){let a=E(t,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForWarp(t,r),p=v(s.name,this.adapters),c=new R(this.config,p,this.adapters),o=await c.apply(t,i),u=E(o,e),{action:d,index:h}=B(o),m=this.getStringTypedInputs(d,r),W=await this.getResolvedInputs(s.name,d,m,c),f=await this.getModifiedInputs(W),y=[],A=[];h===e-1?(y=W,A=f):this.requiresPayloadInputs(u)&&(y=await this.resolveActionInputs(s.name,u,r,c),A=await this.getModifiedInputs(y));let P=A.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,b=this.getDestinationFromAction(u),C=P?this.serializer.stringToNative(P)[1]:b;if(C&&(C=c.applyInputs(C,A,this.serializer,f)),!C&&a.type!=="collect"&&a.type!=="mcp")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let j=this.getPreparedArgs(u,A);j=j.map(I=>c.applyInputs(I,A,this.serializer,f));let L=A.find(I=>I.input.position==="value")?.value||null,T="value"in u?u.value:null,H=L?.split(l.ArgParamsSeparator)[1]||T||"0",_=c.applyInputs(H,A,this.serializer,f),te=BigInt(_),ee=A.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),re=[...("transfers"in u?u.transfers:[])||[],...ee||[]].map(I=>{let se=c.applyInputs(I,A,this.serializer,f);return this.serializer.stringToNative(se)[1]}),ne=A.find(I=>I.input.position==="data")?.value,ie="data"in u?u.data||"":null,bt=ne||ie||null,ae=bt?c.applyInputs(bt,A,this.serializer,f):null,Tt={adapter:p,warp:o,chain:s,action:e,destination:C,args:j,value:te,transfers:re,data:ae,resolvedInputs:A};return this.cache.set(wt.WarpExecutable(this.config.env,o.meta?.hash||"",e),Tt.resolvedInputs,Kt.OneWeek),Tt}async getChainInfoForWarp(t,e){if(t.chain)return v(t.chain,this.adapters).chainInfo;if(e){let i=await this.tryGetChainFromInputs(t,e);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,e){let r=t.inputs||[];return e.map((i,a)=>{let s=r[a];return!s||i.includes(l.ArgParamsSeparator)?i:this.serializer.nativeToString(s.type,i)})}async getResolvedInputs(t,e,r,i){let a=e.inputs||[],s=await Promise.all(r.map(c=>this.preprocessInput(t,c))),p=(c,o)=>{if(c.source==="query"){let u=this.url.searchParams.get(c.name);return u?this.serializer.nativeToString(c.type,u):null}else if(c.source===l.Source.UserWallet){let u=S(this.config,t);return u?this.serializer.nativeToString("address",u):null}else if(c.source==="hidden"){if(c.default===void 0)return null;let u=i?i.applyInputs(String(c.default),[],this.serializer):String(c.default);return this.serializer.nativeToString(c.type,u)}else return s[o]||null};return a.map((c,o)=>{let u=p(c,o),d=c.default!==void 0?i?i.applyInputs(String(c.default),[],this.serializer):String(c.default):void 0;return{input:c,value:u||(d!==void 0?this.serializer.nativeToString(c.type,d):null)}})}requiresPayloadInputs(t){return t.inputs?.some(e=>typeof e.position=="string"&&e.position.startsWith("payload:"))??!1}async resolveActionInputs(t,e,r,i){let a=this.getStringTypedInputs(e,r);return await this.getResolvedInputs(t,e,a,i)}async getModifiedInputs(t){let e=[];for(let r=0;r<t.length;r++){let i=t[r];if(i.input.modifier?.startsWith("scale:")){let[,a]=i.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(t.find(o=>o.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let p=i.value?.split(":")[1];if(!p)throw new Error("WarpActionExecutor: Scalable value not found");let c=Y(p,+s);e.push({...i,value:`${i.input.type}:${c}`})}else{let s=i.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let p=Y(s,+a);e.push({...i,value:`${i.input.type}:${p}`})}}else if(i.input.modifier?.startsWith(l.Transform.Prefix)){let a=i.input.modifier.substring(l.Transform.Prefix.length),s=this.config.transform?.runner;if(!s||typeof s.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let p=this.buildInputContext(t,r,i),c=await s.run(a,p);if(c==null)e.push(i);else{let o=this.serializer.nativeToString(i.input.type,c);e.push({...i,value:o})}}else e.push(i)}return e}buildInputContext(t,e,r){let i={};for(let a=0;a<e;a++){let s=t[a];if(!s.value)continue;let p=s.input.as||s.input.name,[,c]=this.serializer.stringToNative(s.value);if(i[p]=c,s.input.type==="asset"&&typeof c=="object"&&c!==null){let o=c;"identifier"in o&&"amount"in o&&(i[`${p}.token`]=String(o.identifier),i[`${p}.amount`]=String(o.amount),i[`${p}.identifier`]=String(o.identifier))}}if(r&&r.value){let a=r.input.as||r.input.name,[,s]=this.serializer.stringToNative(r.value);if(i[a]=s,r.input.type==="asset"&&typeof s=="object"&&s!==null){let p=s;"identifier"in p&&"amount"in p&&(i[`${a}.token`]=String(p.identifier),i[`${a}.amount`]=String(p.amount),i[`${a}.identifier`]=String(p.identifier))}}return i}async preprocessInput(t,e){try{let[r,i]=ht(e),a=v(t,this.adapters);if(r==="asset"){let[s,p,c]=i.split(l.ArgCompositeSeparator);if(c)return e;let o=await a.dataLoader.getAsset(s);if(!o)throw new Error(`WarpFactory: Asset not found for asset ${s}`);if(typeof o.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${s}`);let u=Y(p,o.decimals);return qt({...o,amount:u})}else return e}catch(r){throw x.warn("WarpFactory: Preprocess input failed",r),r}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,e){let r="args"in t?t.args||[]:[],i=[];return e.forEach(({input:a,value:s})=>{if(!(!s||!a.position)){if(typeof a.position=="object"){if(a.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${a.name}" has type "${a.type}"`);if(!a.position.token?.startsWith("arg:")||!a.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${a.name}"`);let[p,c]=this.serializer.stringToNative(s),o=c;if(!o||typeof o!="object"||!("identifier"in o)||!("amount"in o))throw new Error(`WarpFactory: Invalid asset value for input "${a.name}"`);let u=Number(a.position.token.split(":")[1])-1,d=Number(a.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",o.identifier)}),i.push({index:d,value:this.serializer.nativeToString("uint256",o.amount)})}else if(a.position.startsWith("arg:")){let p=Number(a.position.split(":")[1])-1;i.push({index:p,value:s})}}}),i.forEach(({index:a,value:s})=>{for(;r.length<=a;)r.push(void 0);r[a]=s}),r.filter(a=>a!==void 0)}async tryGetChainFromInputs(t,e){let r=t.actions.find(c=>c.inputs?.some(o=>o.position==="chain"));if(!r)return null;let i=r.inputs?.findIndex(c=>c.position==="chain");if(i===-1||i===void 0)return null;let a=e[i];if(!a)throw new Error("Chain input not found");let s=this.serializer.stringToNative(a)[1];return v(s,this.adapters).chainInfo}};var pt=class{constructor(t,e,r){this.config=t;this.adapters=e;this.handlers=r;this.handlers=r,this.factory=new G(t,e)}async execute(t,e,r={}){let i=[],a=null,s=[],p=[],{action:c,index:o}=B(t);for(let u=1;u<=t.actions.length;u++){let d=E(t,u);if(!ft(d,t))continue;let{tx:h,chain:m,immediateExecution:W,executable:f}=await this.executeAction(t,u,e,r);h&&i.push(h),m&&(a=m),W&&s.push(W),f&&u===o+1&&f.resolvedInputs&&(p=N(f.resolvedInputs))}if(!a&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&s.length>0){let u=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(u))}return{txs:i,chain:a,immediateExecutions:s,resolvedInputs:p}}async executeAction(t,e,r,i={}){let a=E(t,e);if(a.type==="link")return a.when&&!await this.evaluateWhenCondition(t,a,r,i)?{tx:null,chain:null,immediateExecution:null,executable:null}:(await this.callHandler(async()=>{let o=a.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(o):Et.open(o,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null});if(a.type==="prompt"){let o=await this.executePrompt(t,a,e,r,i);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:null};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,executable:null}}}let s=await this.factory.createExecutable(t,e,r,i);if(a.when&&!await this.evaluateWhenCondition(t,a,r,i,s.resolvedInputs,s.chain.name))return{tx:null,chain:null,immediateExecution:null,executable:null};if(a.type==="collect"){let o=await this.executeCollect(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,result:o})}return{tx:null,chain:null,immediateExecution:null,executable:s}}if(a.type==="mcp"){let o=await this.executeMcp(s);if(o.status==="success")return await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};if(o.status==="unhandled")return await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:e,chain:null,execution:o,tx:null})),{tx:null,chain:null,immediateExecution:o,executable:s};{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);return this.handlers?.onError?.({message:u,result:o}),{tx:null,chain:null,immediateExecution:o,executable:s}}}let p=v(s.chain.name,this.adapters);if(a.type==="query"){let o=await p.executor.executeQuery(s);if(o.status==="success")await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:e,chain:s.chain,execution:o,tx:null}));else{let u=o.output._DATA instanceof Error?o.output._DATA.message:JSON.stringify(o.output._DATA);this.handlers?.onError?.({message:u,result:o})}return{tx:null,chain:s.chain,immediateExecution:o,executable:s}}return{tx:await p.executor.createTransaction(s),chain:s.chain,immediateExecution:null,executable:s}}async evaluateOutput(t,e){if(e.length===0||t.actions.length===0||!this.handlers)return;let r=await this.factory.getChainInfoForWarp(t),i=v(r.name,this.adapters),a=(await Promise.all(t.actions.map(async(s,p)=>{if(!ft(s,t)||s.type!=="transfer"&&s.type!=="contract")return null;let c=e[p],o=p+1;if(!c){let d=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,o),h={status:"error",warp:t,action:o,user:S(this.config,r.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:d};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${o} failed: Transaction not found`,result:h})),h}let u=await i.output.getActionExecution(t,o,c);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:o,chain:r,execution:u,tx:c})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values),result:u})),u}))).filter(s=>s!==null);if(a.every(s=>s.status==="success")){let s=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(s))}else{let s=a.find(p=>p.status!=="success");await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(a)}`,result:s}))}}async executeCollect(t,e){let r=S(this.config,t.chain.name),i=E(t.warp,t.action),a=this.factory.getSerializer(),s=rt(t.resolvedInputs,a);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,r,s,e);let{values:p,output:c}=await nt(t.warp,s,t.action,t.resolvedInputs,a,this.config);return this.buildCollectResult(t,r,"unhandled",p,c)}async doHttpRequest(t,e,r,i,a){let s=new R(this.config,v(t.chain.name,this.adapters),this.adapters),p=this.factory.getSerializer(),{url:c,method:o,headers:u,body:d}=await Xt(s,e,t,r,i,p,a,async h=>await this.callHandler(()=>this.handlers?.onSignRequest?.(h)));x.debug("WarpExecutor: Executing HTTP collect",{url:c,method:o,headers:u,body:d});try{let m=await fetch(c,{method:o,headers:u,body:d});x.debug("Collect response status",{status:m.status}),m.status===402&&(m=await Mt(m,c,o,d,this.adapters));let W=await m.json();x.debug("Collect response content",{content:W});let{values:f,output:y}=await nt(t.warp,W,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),m.ok?"success":"error",f,y,W)}catch(h){x.error("WarpActionExecutor: Error executing collect",h);let m=N(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:r,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:h},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(r=>r.input.position==="receiver"||r.input.position==="destination")?.value||t.destination}async executeMcp(t,e){let r=S(this.config,t.chain.name),i=E(t.warp,t.action);if(!i.destination){let m=N(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:r,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("WarpExecutor: MCP action requires destination")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:m}}let a,s;try{a=(await import("@modelcontextprotocol/sdk/client/index.js")).Client,s=(await import("@modelcontextprotocol/sdk/client/streamableHttp.js")).StreamableHTTPClientTransport}catch{let W=N(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:r,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:new Error("Please install @modelcontextprotocol/sdk to execute MCP warps or mcp actions")},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}let p=this.factory.getSerializer(),c=new R(this.config,v(t.chain.name,this.adapters),this.adapters),o=i.destination,u=c.applyInputs(o.url,t.resolvedInputs,this.factory.getSerializer()),d=c.applyInputs(o.tool,t.resolvedInputs,this.factory.getSerializer()),h={};o.headers&&Object.entries(o.headers).forEach(([m,W])=>{let f=c.applyInputs(W,t.resolvedInputs,this.factory.getSerializer());h[m]=f}),x.debug("WarpExecutor: Executing MCP",{url:u,tool:d,headers:h});try{let m=new s(new URL(u),{requestInit:{headers:h}}),W=new a({name:"warps-mcp-client",version:"1.0.0"},{capabilities:{}});await W.connect(m);let f={};t.resolvedInputs.forEach(({input:C,value:j})=>{if(j&&C.position&&typeof C.position=="string"&&C.position.startsWith("payload:")){let L=C.position.replace("payload:",""),[T,H]=p.stringToNative(j);if(T==="string")f[L]=String(H);else if(T==="bool")f[L]=!!H;else if(T==="uint8"||T==="uint16"||T==="uint32"||T==="uint64"||T==="uint128"||T==="uint256"||T==="biguint"){let _=Number(H);f[L]=(Number.isInteger(_),_)}else f[L]=H}}),e&&Object.assign(f,e);let y=await W.callTool({name:d,arguments:f});await W.close();let A;if(y.content&&y.content.length>0){let C=y.content[0];if(C.type==="text")try{A=JSON.parse(C.text)}catch{A=C.text}else C.type,A=C}else A=y;let{values:P,output:b}=await nt(t.warp,A,t.action,t.resolvedInputs,p,this.config);return this.buildCollectResult(t,r,"success",P,b,y)}catch(m){x.error("WarpExecutor: Error executing MCP",m);let W=N(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:r,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:m},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:W}}}buildCollectResult(t,e,r,i,a,s){let p=Wt(this.config,this.adapters,t.warp,t.action,a),c=N(t.resolvedInputs);return{status:r,warp:t.warp,action:t.action,user:e||S(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:s?{...a,_DATA:s}:a,messages:mt(t.warp,a,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:c}}async callHandler(t){if(t)return await t()}async executePrompt(t,e,r,i,a={}){try{let s=await this.factory.getChainInfoForWarp(t,i),p=v(s.name,this.adapters),c=new R(this.config,p,this.adapters),o=await c.apply(t,a),u=E(o,r),{action:d}=B(o),h=this.factory.getStringTypedInputs(d,i),m=await this.factory.getResolvedInputs(s.name,d,h,c),W=await this.factory.getModifiedInputs(m),f=W;if(e.inputs&&e.inputs.length>0){let b=this.factory.getStringTypedInputs(e,i),C=await this.factory.getResolvedInputs(s.name,e,b,c);f=await this.factory.getModifiedInputs(C)}let y=c.applyInputs(u.prompt,f,this.factory.getSerializer(),W),A=N(f),P=S(this.config,s.name);return{status:"success",warp:o,action:r,user:P,txHash:null,tx:null,next:Wt(this.config,this.adapters,o,r,{prompt:y}),values:{string:[y],native:[y],mapped:{prompt:y}},output:{prompt:y},messages:mt(o,{prompt:y},this.config),destination:null,resolvedInputs:A}}catch(s){return x.error("WarpExecutor: Error executing prompt action",s),{status:"error",warp:t,action:r,user:null,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:s},messages:{},destination:null,resolvedInputs:[]}}}async evaluateWhenCondition(t,e,r,i,a,s){if(!e.when)return!0;let p=s?{name:s}:await this.factory.getChainInfoForWarp(t,r),c=v(p.name,this.adapters),o=new R(this.config,c,this.adapters),{action:u}=B(t),d=this.factory.getStringTypedInputs(u,r),h=await this.factory.getResolvedInputs(p.name,u,d,o),m=await this.factory.getModifiedInputs(h),W;if(a)W=a;else{let A=await this.factory.getResolvedInputs(p.name,e,this.factory.getStringTypedInputs(e,r),o);W=await this.factory.getModifiedInputs(A)}let f=o.buildInputBag(W,this.factory.getSerializer(),m),y=Ht(e.when,f);return Ot(y)}};var ct=class{constructor(t){this.config=t}async search(t,e,r){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...r},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw x.error("WarpIndex: Error searching for warps: ",i),i}}};var lt=class{constructor(t,e){this.config=t;this.adapters=e}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!J(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(o=>o[0]).filter(o=>this.isValid(o)).map(o=>this.detect(o)),s=(await Promise.all(i)).filter(o=>o.match),p=s.length>0,c=s.map(o=>({url:o.url,warp:o.warp}));return{match:p,output:c}}async detect(t,e){let r={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?J(t):$(t);if(!i)return r;try{let{type:a,identifierBase:s}=i,p=null,c=null,o=null,u=v(i.chain,this.adapters),d=t.startsWith(l.HttpProtocolPrefix)?Vt(t):Ut(i.identifier);if(a==="hash"){p=await u.builder().createFromTransactionHash(s,e);let f=await u.registry.getInfoByHash(s,e);c=f.registryInfo,o=f.brand}else if(a==="alias"){let f=await u.registry.getInfoByAlias(s,e);c=f.registryInfo,o=f.brand,f.registryInfo&&(p=await u.builder().createFromTransactionHash(f.registryInfo.hash,e))}if(p&&p.meta&&(Me(p,u.chainInfo.name,c,i.identifier),p.meta.query=d),!p)return r;let h=p.chain||u.chainInfo.name,m=v(h,this.adapters),W=await new R(this.config,m,this.adapters).apply(p);return{match:!0,url:t,warp:W,chain:h,registryInfo:c,brand:o}}catch(a){return x.error("Error detecting warp link",a),r}}},Me=(n,t,e,r)=>{n.meta&&(n.meta.identifier=e?.alias?gt(t,"alias",e.alias):gt(t,"hash",e?.hash??r))};var Zt=class{constructor(t,e){this.config=t;this.options=e;this.chains=e.chains.map(r=>r(this.config))}getConfig(){return this.config}createExecutor(t){return new pt(this.config,this.chains,t)}async detectWarp(t,e){return new lt(this.config,this.chains).detect(t,e)}async executeWarp(t,e,r,i={}){let a=typeof t=="object",s=!a&&t.startsWith("http")&&t.endsWith(".json"),p=a?t:null;if(!p&&s){let W=await fetch(t);if(!W.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await W.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let c=this.createExecutor(r),{txs:o,chain:u,immediateExecutions:d,resolvedInputs:h}=await c.execute(p,e,{queries:i.queries});return{txs:o,chain:u,immediateExecutions:d,evaluateOutput:async W=>{await c.evaluateOutput(p,W)},resolvedInputs:h}}async createInscriptionTransaction(t,e){return await v(t,this.chains).builder().createInscriptionTransaction(e)}async createFromTransaction(t,e,r=!1){return v(t,this.chains).builder().createFromTransaction(e,r)}async createFromTransactionHash(t,e){let r=$(t);if(!r)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return v(r.chain,this.chains).builder().createFromTransactionHash(t,e)}async signMessage(t,e){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return v(t,this.chains).wallet.signMessage(e)}async getActions(t,e,r=!1){let i=this.getDataLoader(t);return(await Promise.all(e.map(async s=>i.getAction(s,r)))).filter(s=>s!==null)}getExplorer(t){return v(t,this.chains).explorer}getOutput(t){return v(t,this.chains).output}async getRegistry(t){let e=v(t,this.chains).registry;return await e.init(),e}getDataLoader(t){return v(t,this.chains).dataLoader}getWallet(t){return v(t,this.chains).wallet}get factory(){return new G(this.config,this.chains)}get index(){return new ct(this.config)}get linkBuilder(){return new q(this.config,this.chains)}createBuilder(t){return v(t,this.chains).builder()}createAbiBuilder(t){return v(t,this.chains).abiBuilder()}createBrandBuilder(t){return v(t,this.chains).brandBuilder()}createSerializer(t){return v(t,this.chains).serializer}resolveText(t){return tt(t,this.config)}};var Yt=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,e){this.typeHandlers.set(t,e)}registerTypeAlias(t,e){this.typeAliases.set(t,e)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let e=this.typeAliases.get(t);return e?this.getHandler(e):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let e=this.typeAliases.get(t);return e?this.resolveType(e):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};export{ut as BrowserCryptoProvider,Kt as CacheTtl,dt as NodeCryptoProvider,fr as WARP_LANGUAGES,zt as WarpBrandBuilder,kt as WarpBuilder,ot as WarpCache,wt as WarpCacheKey,oe as WarpChainName,Zt as WarpClient,F as WarpConfig,l as WarpConstants,pt as WarpExecutor,G as WarpFactory,ct as WarpIndex,g as WarpInputTypes,R as WarpInterpolator,q as WarpLinkBuilder,lt as WarpLinkDetecter,x as WarpLogger,M as WarpProtocolVersions,w as WarpSerializer,Yt as WarpTypeRegistry,it as WarpValidator,Rn as address,mt as applyOutputToMessages,qt as asset,Tn as biguint,En as bool,rt as buildMappedOutput,ge as buildNestedPayload,ir as bytesToBase64,pe as bytesToHex,et as cleanWarpIdentifier,At as createAuthHeaders,vt as createAuthMessage,sr as createCryptoProvider,fn as createDefaultWalletProvider,Zr as createHttpAuthHeaders,Ae as createSignableMessage,hr as createWarpI18nText,gt as createWarpIdentifier,me as evaluateOutputCommon,Ot as evaluateWhenCondition,nt as extractCollectOutput,J as extractIdentifierInfoFromUrl,Ut as extractQueryStringFromIdentifier,Vt as extractQueryStringFromUrl,N as extractResolvedInputValues,cr as extractWarpSecrets,v as findWarpAdapterForChain,Rt as getCryptoProvider,Xe as getEventNameFromWarp,Z as getLatestProtocolIdentifier,Wt as getNextInfo,Jr as getProviderConfig,Nt as getRandomBytes,Bt as getRandomHex,rn as getWalletFromConfigOrFail,E as getWarpActionByIndex,Ye as getWarpBrandLogoUrl,tr as getWarpChainAssetLogoUrl,er as getWarpChainInfoLogoUrl,$ as getWarpInfoFromIdentifier,B as getWarpPrimaryAction,Ce as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,Ie as getWarpWalletExternalId,Se as getWarpWalletExternalIdFromConfig,sn as getWarpWalletExternalIdFromConfigOrFail,we as getWarpWalletMnemonic,an as getWarpWalletMnemonicFromConfig,xe as getWarpWalletPrivateKey,nn as getWarpWalletPrivateKeyFromConfig,Mt as handleX402Payment,xr as hasInputPrefix,Nn as hex,un as initializeWalletCache,vr as isEqualWarpIdentifier,ft as isWarpActionAutoExecute,gr as isWarpI18nText,on as isWarpWalletReadOnly,Dt as mergeNestedPayload,cn as normalizeAndValidateMnemonic,Pe as normalizeMnemonic,Bn as option,ve as parseOutputOutIndex,tn as parseSignedMessage,U as replacePlaceholders,Ht as replacePlaceholdersInWhenExpression,tt as resolveWarpText,Et as safeWindow,nr as setCryptoProvider,pn as setWarpWalletInConfig,Y as shiftBigintBy,ht as splitInput,wn as string,Hn as struct,ar as testCryptoAvailability,he as toInputPayloadValue,$t as toPreviewText,$n as tuple,Sn as uint16,Pn as uint32,bn as uint64,In as uint8,be as validateMnemonicLength,Yr as validateSignedMessage,On as vector,Je as withAdapterFallback};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "3.0.0-beta.191",
3
+ "version": "3.0.0-beta.192",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",