@vleap/warps 3.0.0-beta.162 → 3.0.0-beta.164

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
@@ -976,12 +976,12 @@ declare class WarpInterpolator {
976
976
  private config;
977
977
  private adapter;
978
978
  constructor(config: WarpClientConfig, adapter: Adapter);
979
- apply(config: WarpClientConfig, warp: Warp, meta?: {
979
+ apply(warp: Warp, meta?: {
980
980
  envs?: Record<string, any>;
981
981
  queries?: Record<string, any>;
982
982
  }): Promise<Warp>;
983
- applyGlobals(config: WarpClientConfig, warp: Warp): Promise<Warp>;
984
- applyVars(config: WarpClientConfig, warp: Warp, meta?: {
983
+ applyGlobals(warp: Warp): Promise<Warp>;
984
+ applyVars(warp: Warp, meta?: {
985
985
  envs?: Record<string, any>;
986
986
  queries?: Record<string, any>;
987
987
  }): Warp;
package/dist/index.d.ts CHANGED
@@ -976,12 +976,12 @@ declare class WarpInterpolator {
976
976
  private config;
977
977
  private adapter;
978
978
  constructor(config: WarpClientConfig, adapter: Adapter);
979
- apply(config: WarpClientConfig, warp: Warp, meta?: {
979
+ apply(warp: Warp, meta?: {
980
980
  envs?: Record<string, any>;
981
981
  queries?: Record<string, any>;
982
982
  }): Promise<Warp>;
983
- applyGlobals(config: WarpClientConfig, warp: Warp): Promise<Warp>;
984
- applyVars(config: WarpClientConfig, warp: Warp, meta?: {
983
+ applyGlobals(warp: Warp): Promise<Warp>;
984
+ applyVars(warp: Warp, meta?: {
985
985
  envs?: Record<string, any>;
986
986
  queries?: Record<string, any>;
987
987
  }): Warp;
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var ir=Object.create;var tt=Object.defineProperty;var ar=Object.getOwnPropertyDescriptor;var sr=Object.getOwnPropertyNames;var or=Object.getPrototypeOf,pr=Object.prototype.hasOwnProperty;var cr=(n,t)=>{for(var r in t)tt(n,r,{get:t[r],enumerable:!0})},Bt=(n,t,r,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of sr(t))!pr.call(n,i)&&i!==r&&tt(n,i,{get:()=>t[i],enumerable:!(e=ar(t,i))||e.enumerable});return n};var rt=(n,t,r)=>(r=n!=null?ir(or(n)):{},Bt(t||!n||!n.__esModule?tt(r,"default",{value:n,enumerable:!0}):r,n)),lr=n=>Bt(tt({},"__esModule",{value:!0}),n);var Xr={};cr(Xr,{BrowserCryptoProvider:()=>et,CacheTtl:()=>bt,NodeCryptoProvider:()=>nt,WARP_LANGUAGES:()=>yr,WarpBrandBuilder:()=>St,WarpBuilder:()=>wt,WarpCache:()=>_,WarpCacheKey:()=>lt,WarpChainName:()=>$t,WarpClient:()=>Tt,WarpConfig:()=>R,WarpConstants:()=>c,WarpExecutor:()=>X,WarpFactory:()=>j,WarpIndex:()=>Z,WarpInputTypes:()=>d,WarpInterpolator:()=>P,WarpLinkBuilder:()=>F,WarpLinkDetecter:()=>Y,WarpLogger:()=>C,WarpProtocolVersions:()=>O,WarpSerializer:()=>x,WarpTypeRegistry:()=>Pt,WarpValidator:()=>J,address:()=>kr,applyOutputToMessages:()=>vt,asset:()=>It,biguint:()=>jr,bool:()=>Dr,buildMappedOutput:()=>G,buildNestedPayload:()=>Ut,bytesToBase64:()=>gr,bytesToHex:()=>Vt,cleanWarpIdentifier:()=>M,createAuthHeaders:()=>ct,createAuthMessage:()=>pt,createCryptoProvider:()=>mr,createHttpAuthHeaders:()=>Rr,createSignableMessage:()=>jt,createWarpI18nText:()=>Ar,createWarpIdentifier:()=>at,evaluateOutputCommon:()=>Ht,extractCollectOutput:()=>ot,extractIdentifierInfoFromUrl:()=>D,extractQueryStringFromIdentifier:()=>yt,extractQueryStringFromUrl:()=>Wt,extractResolvedInputValues:()=>H,extractWarpSecrets:()=>Wr,findWarpAdapterForChain:()=>h,getCryptoProvider:()=>ft,getEventNameFromWarp:()=>ur,getLatestProtocolIdentifier:()=>k,getNextInfo:()=>xt,getProviderConfig:()=>Tr,getRandomBytes:()=>gt,getRandomHex:()=>ht,getWarpActionByIndex:()=>w,getWarpBrandLogoUrl:()=>dr,getWarpInfoFromIdentifier:()=>b,getWarpPrimaryAction:()=>B,getWarpWalletAddress:()=>Dt,getWarpWalletAddressFromConfig:()=>S,getWarpWalletMnemonic:()=>qt,getWarpWalletMnemonicFromConfig:()=>Nr,getWarpWalletPrivateKey:()=>kt,getWarpWalletPrivateKeyFromConfig:()=>Vr,hasInputPrefix:()=>Sr,hex:()=>qr,isEqualWarpIdentifier:()=>xr,isWarpActionAutoExecute:()=>it,isWarpI18nText:()=>vr,mergeNestedPayload:()=>Ct,option:()=>zr,parseOutputOutIndex:()=>Lt,parseSignedMessage:()=>$r,replacePlaceholders:()=>$,resolveWarpText:()=>z,safeWindow:()=>dt,setCryptoProvider:()=>fr,shiftBigintBy:()=>q,splitInput:()=>st,string:()=>Or,struct:()=>Gr,testCryptoAvailability:()=>hr,toInputPayloadValue:()=>Ft,toPreviewText:()=>mt,tuple:()=>Mr,uint16:()=>Fr,uint32:()=>Hr,uint64:()=>Lr,uint8:()=>Ur,validateSignedMessage:()=>Br,vector:()=>Jr});module.exports=lr(Xr);var $t=(p=>(p.Multiversx="multiversx",p.Vibechain="vibechain",p.Sui="sui",p.Ethereum="ethereum",p.Base="base",p.Arbitrum="arbitrum",p.Somnia="somnia",p.Fastset="fastset",p))($t||{}),c={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"}},d={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"},dt=typeof window<"u"?window:{open:()=>{}};var O={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},R={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${O.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${O.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",c.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 ur=(n,t)=>{let r=n.alerts?.[t];if(!r)return null;let e=c.Alerts.TriggerEventPrefix+c.ArgParamsSeparator;if(!r.trigger.startsWith(e))return null;let i=r.trigger.replace(e,"");return i||null};var dr=(n,t)=>typeof n.logo=="string"?n.logo:n.logo[t?.scheme??"light"];var et=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let r=new Uint8Array(t);return window.crypto.getRandomValues(r),r}},nt=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let r=await import("crypto");return new Uint8Array(r.randomBytes(t))}catch(r){throw new Error(`Node.js crypto not available: ${r instanceof Error?r.message:"Unknown error"}`)}}},U=null;function ft(){if(U)return U;if(typeof window<"u"&&window.crypto)return U=new et,U;if(typeof process<"u"&&process.versions?.node)return U=new nt,U;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function fr(n){U=n}async function gt(n,t){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(t||ft()).getRandomBytes(n)}function Vt(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(n.length*2);for(let r=0;r<n.length;r++){let e=n[r];t[r*2]=(e>>>4).toString(16),t[r*2+1]=(e&15).toString(16)}return t.join("")}function gr(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 ht(n,t){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let r=await gt(n/2,t);return Vt(r)}async function hr(){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 gt(16),n.randomBytes=!0}catch{}return n}function mr(){return ft()}var Wr=n=>Object.values(n.vars||{}).filter(t=>t.startsWith(`${c.Vars.Env}:`)).map(t=>{let r=t.replace(`${c.Vars.Env}:`,"").trim(),[e,i]=r.split(c.ArgCompositeSeparator);return{key:e,description:i||null}});var h=(n,t)=>{let r=t.find(e=>e.chainInfo.name.toLowerCase()===n.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${n}`);return r},k=n=>{if(n==="warp")return`warp:${O.Warp}`;if(n==="brand")return`brand:${O.Brand}`;if(n==="abi")return`abi:${O.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},w=(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(s=>s.primary===!0);if(t)return{action:t,index:n.actions.indexOf(t)};let r=["transfer","contract","query","collect"],e=n.actions.find(s=>r.includes(s.type));return e?{action:e,index:n.actions.indexOf(e)}:{action:n.actions[0],index:0}},it=(n,t)=>{if(n.auto===!1)return!1;if(n.type==="link"){if(n.auto===!0)return!0;let{action:r}=B(t);return n===r}return!0},q=(n,t)=>{let r=n.toString(),[e,i=""]=r.split("."),s=Math.abs(t);if(t>0)return BigInt(e+i.padEnd(s,"0"));if(t<0){let a=e+i;if(s>=a.length)return 0n;let o=a.slice(0,-s)||"0";return BigInt(o)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},mt=(n,t=100)=>{if(!n)return"";let r=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r},$=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||"");var yr={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"},z=(n,t)=>{let r=t?.preferences?.locale||"en";if(typeof n=="string")return n;if(typeof n=="object"&&n!==null){if(r in n)return n[r];if("en"in n)return n.en;let e=Object.keys(n);if(e.length>0)return n[e[0]]}return""},vr=n=>typeof n=="object"&&n!==null&&Object.keys(n).length>0,Ar=n=>n;var M=n=>n.startsWith(c.IdentifierAliasMarker)?n.replace(c.IdentifierAliasMarker,""):n,xr=(n,t)=>!n||!t?!1:M(n)===M(t),at=(n,t,r)=>{let e=M(r);return t===c.IdentifierType.Alias?c.IdentifierAliasMarker+n+c.IdentifierParamSeparator+e:n+c.IdentifierParamSeparator+t+c.IdentifierParamSeparator+e},b=n=>{let t=decodeURIComponent(n).trim(),r=M(t),e=r.split("?")[0],i=Nt(e);if(e.length===64&&/^[a-fA-F0-9]+$/.test(e))return{chain:c.IdentifierChainDefault,type:c.IdentifierType.Hash,identifier:r,identifierBase:e};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[s,a,o]=i;if(a===c.IdentifierType.Alias||a===c.IdentifierType.Hash){let p=r.includes("?")?o+r.substring(r.indexOf("?")):o;return{chain:s,type:a,identifier:p,identifierBase:o}}}if(i.length===2){let[s,a]=i;if(s===c.IdentifierType.Alias||s===c.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a;return{chain:c.IdentifierChainDefault,type:s,identifier:o,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==c.IdentifierType.Alias&&s!==c.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a,p=Cr(a,s)?c.IdentifierType.Hash:c.IdentifierType.Alias;return{chain:s,type:p,identifier:o,identifierBase:a}}}return{chain:c.IdentifierChainDefault,type:c.IdentifierType.Alias,identifier:r,identifierBase:e}},D=n=>{let t=new URL(n),e=t.searchParams.get(c.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let i=decodeURIComponent(e);return b(i)},Cr=(n,t)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,Ir=n=>{let t=c.IdentifierParamSeparator,r=n.indexOf(t);return r!==-1?{separator:t,index:r}:null},Nt=n=>{let t=Ir(n);if(!t)return[n];let{separator:r,index:e}=t,i=n.substring(0,e),s=n.substring(e+r.length),a=Nt(s);return[i,...a]},Wt=n=>{try{let t=new URL(n),r=new URLSearchParams(t.search);return r.delete(c.IdentifierParamName),r.toString()||null}catch{return null}},yt=n=>{let t=n.indexOf("?");if(t===-1||t===n.length-1)return null;let r=n.substring(t+1);return r.length>0?r:null};var st=n=>{let[t,...r]=n.split(/:(.*)/,2);return[t,r[0]||""]},Sr=n=>{let t=new Set(Object.values(d));if(!n.includes(c.ArgParamsSeparator))return!1;let r=st(n)[0];return t.has(r)};var vt=(n,t,r)=>{let e=Object.entries(n.messages||{}).map(([i,s])=>{let a=z(s,r);return[i,$(a,t)]});return Object.fromEntries(e)};var Ot=rt(require("qr-code-styling"),1);var F=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!D(t):!1}build(t,r,e){let i=this.config.clientUrl||R.DefaultClientUrl(this.config.env),s=h(t,this.adapters),a=r===c.IdentifierType.Alias?e:r+c.IdentifierParamSeparator+e,o=s.chainInfo.name+c.IdentifierParamSeparator+a,p=encodeURIComponent(o);return R.SuperClientUrls.includes(i)?`${i}/${p}`:`${i}?${c.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(t){let r=b(t);if(!r)return null;let e=h(r.chain,this.adapters);return e?this.build(e.chainInfo.name,r.type,r.identifierBase):null}generateQrCode(t,r,e,i=512,s="white",a="black",o="#23F7DD"){let p=h(t,this.adapters),l=this.build(p.chainInfo.name,r,e);return new Ot.default({type:"svg",width:i,height:i,data:String(l),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},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(o)}" 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 wr="https://",xt=(n,t,r,e,i)=>{let s=r.actions?.[e-1]?.next||r.next||null;if(!s)return null;if(s.startsWith(wr))return[{identifier:null,url:s}];let[a,o]=s.split("?");if(!o){let m=$(a,{...r.vars,...i});return[{identifier:m,url:At(t,m,n)}]}let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let m=$(o,{...r.vars,...i}),v=m?`${a}?${m}`:a;return[{identifier:v,url:At(t,v,n)}]}let l=p[0];if(!l)return[];let u=l.match(/{{([^[]+)\[\]/),f=u?u[1]:null;if(!f||i[f]===void 0)return[];let g=Array.isArray(i[f])?i[f]:[i[f]];if(g.length===0)return[];let W=p.filter(m=>m.includes(`{{${f}[]`)).map(m=>{let v=m.match(/\[\](\.[^}]+)?}}/),A=v&&v[1]||"";return{placeholder:m,field:A?A.slice(1):"",regex:new RegExp(m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return g.map(m=>{let v=o;for(let{regex:E,field:N}of W){let T=N?br(m,N):m;if(T==null)return null;v=v.replace(E,T)}if(v.includes("{{")||v.includes("}}"))return null;let A=v?`${a}?${v}`:a;return{identifier:A,url:At(t,A,n)}}).filter(m=>m!==null)},At=(n,t,r)=>{let[e,i]=t.split("?"),s=b(e)||{chain:c.IdentifierChainDefault,type:"alias",identifier:e,identifierBase:e},a=h(s.chain,n);if(!a)throw new Error(`Adapter not found for chain ${s.chain}`);let o=new F(r,n).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return o;let p=new URL(o);return new URLSearchParams(i).forEach((l,u)=>p.searchParams.set(u,l)),p.toString().replace(/\/\?/,"?")},br=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);function Ut(n,t,r){return n.startsWith(c.Position.Payload)?n.slice(c.Position.Payload.length).split(".").reduceRight((e,i,s,a)=>({[i]:s===a.length-1?{[t]:r}:e}),{}):{[t]:r}}function Ct(n,t){if(!n)return{...t};if(!t)return{...n};let r={...n};return Object.keys(t).forEach(e=>{r[e]&&typeof r[e]=="object"&&typeof t[e]=="object"?r[e]=Ct(r[e],t[e]):r[e]=t[e]}),r}function Ft(n,t){if(!n.value)return null;let r=t.stringToNative(n.value)[1];if(n.input.type==="biguint")return r.toString();if(n.input.type==="asset"){let{identifier:e,amount:i}=r;return{identifier:e,amount:i.toString()}}else return r}function H(n){return n.map(t=>t.value).filter(t=>t!=null&&t!=="")}function G(n,t){let r={};return n.forEach(e=>{let i=e.input.as||e.input.name,s=Ft(e,t);if(e.input.position&&typeof e.input.position=="string"&&e.input.position.startsWith(c.Position.Payload)){let a=Ut(e.input.position,i,s);r=Ct(r,a)}else r[i]=s}),r}var Tr=(n,t,r,e)=>{let i=n.preferences?.providers?.[t];return i?.[r]?typeof i[r]=="string"?{url:i[r]}:i[r]:{url:e}};var L=class L{static debug(...t){L.isTestEnv||console.debug(...t)}static info(...t){L.isTestEnv||console.info(...t)}static warn(...t){L.isTestEnv||console.warn(...t)}static error(...t){L.isTestEnv||console.error(...t)}};L.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=L;var ot=async(n,t,r,e,i,s)=>{let a=[],o=[],p={};for(let[u,f]of Object.entries(n.output||{})){if(f.startsWith(c.Transform.Prefix))continue;let g=Lt(f);if(g!==null&&g!==r){p[u]=null;continue}let[W,...y]=f.split("."),m=(v,A)=>A.reduce((E,N)=>E&&E[N]!==void 0?E[N]:null,v);if(W==="out"||W.startsWith("out[")){let v=y.length===0?t?.data||t:m(t,y);a.push(String(v)),o.push(v),p[u]=v}else p[u]=f}let l=G(e,i);return{values:{string:a,native:o,mapped:l},output:await Ht(n,p,r,e,i,s)}},Ht=async(n,t,r,e,i,s)=>{if(!n.output)return t;let a={...t};return a=Pr(a,n,r,e,i),a=await Er(n,a,s.transform?.runner||null),a},Pr=(n,t,r,e,i)=>{let s={...n},a=w(t,r)?.inputs||[];for(let[o,p]of Object.entries(s))if(typeof p=="string"&&p.startsWith("in.")){let l=p.split(".")[1],u=a.findIndex(g=>g.as===l||g.name===l),f=u!==-1?e[u]?.value:null;s[o]=f?i.stringToNative(f)[1]:null}return s},Er=async(n,t,r)=>{if(!n.output)return t;let e={...t},i=Object.entries(n.output).filter(([,s])=>s.startsWith(c.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(c.Transform.Prefix.length)}));if(i.length>0&&(!r||typeof r.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:s,code:a}of i)try{e[s]=await r.run(a,e)}catch(o){C.error(`Transform error for output '${s}':`,o),e[s]=null}return e},Lt=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)};async function jt(n,t,r,e=5){let i=await ht(64,r),s=new Date(Date.now()+e*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:i,expiresAt:s,purpose:t}),nonce:i,expiresAt:s}}async function pt(n,t,r,e){let i=e||`prove-wallet-ownership for app "${t}"`;return jt(n,i,r,5)}function ct(n,t,r,e){return{"X-Signer-Wallet":n,"X-Signer-Signature":t,"X-Signer-Nonce":r,"X-Signer-ExpiresAt":e}}async function Rr(n,t,r,e){let{message:i,nonce:s,expiresAt:a}=await pt(n,r,e),o=await t(i);return ct(n,o,s,a)}function Br(n){let t=new Date(n).getTime();return Date.now()<t}function $r(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 Dt=n=>n?typeof n=="string"?n:n.address:null,S=(n,t)=>Dt(n.user?.wallets?.[t]||null),kt=n=>n?typeof n=="string"?n:n.privateKey:null,qt=n=>n?typeof n=="string"?n:n.mnemonic:null,Vr=(n,t)=>kt(n.user?.wallets?.[t]||null)?.trim()||null,Nr=(n,t)=>qt(n.user?.wallets?.[t]||null)?.trim()||null;var x=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,r){if(t===d.Tuple&&Array.isArray(r)){if(r.length===0)return t+c.ArgParamsSeparator;if(r.every(e=>typeof e=="string"&&e.includes(c.ArgParamsSeparator))){let e=r.map(a=>this.getTypeAndValue(a)),i=e.map(([a])=>a),s=e.map(([,a])=>a);return`${t}(${i.join(c.ArgCompositeSeparator)})${c.ArgParamsSeparator}${s.join(c.ArgListSeparator)}`}return t+c.ArgParamsSeparator+r.join(c.ArgListSeparator)}if(t===d.Struct&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let e=r;if(!e._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=e._name,s=Object.keys(e).filter(o=>o!=="_name");if(s.length===0)return`${t}(${i})${c.ArgParamsSeparator}`;let a=s.map(o=>{let[p,l]=this.getTypeAndValue(e[o]);return`(${o}${c.ArgParamsSeparator}${p})${l}`});return`${t}(${i})${c.ArgParamsSeparator}${a.join(c.ArgListSeparator)}`}if(t===d.Vector&&Array.isArray(r)){if(r.length===0)return`${t}${c.ArgParamsSeparator}`;if(r.every(e=>typeof e=="string"&&e.includes(c.ArgParamsSeparator))){let e=r[0],i=e.indexOf(c.ArgParamsSeparator),s=e.substring(0,i),a=r.map(p=>{let l=p.indexOf(c.ArgParamsSeparator),u=p.substring(l+1);return s.startsWith(d.Tuple)?u.replace(c.ArgListSeparator,c.ArgCompositeSeparator):u}),o=s.startsWith(d.Struct)?c.ArgStructSeparator:c.ArgListSeparator;return t+c.ArgParamsSeparator+s+c.ArgParamsSeparator+a.join(o)}return t+c.ArgParamsSeparator+r.join(c.ArgListSeparator)}if(t===d.Asset&&typeof r=="object"&&r&&"identifier"in r&&"amount"in r)return"decimals"in r?d.Asset+c.ArgParamsSeparator+r.identifier+c.ArgCompositeSeparator+String(r.amount)+c.ArgCompositeSeparator+String(r.decimals):d.Asset+c.ArgParamsSeparator+r.identifier+c.ArgCompositeSeparator+String(r.amount);if(this.typeRegistry){let e=this.typeRegistry.getHandler(t);if(e)return e.nativeToString(r);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,r)}return t+c.ArgParamsSeparator+(r?.toString()??"")}stringToNative(t){let r=t.split(c.ArgParamsSeparator),e=r[0],i=r.slice(1).join(c.ArgParamsSeparator);if(e==="null")return[e,null];if(e===d.Option){let[s,a]=i.split(c.ArgParamsSeparator);return[d.Option+c.ArgParamsSeparator+s,a||null]}if(e===d.Vector){let s=i.indexOf(c.ArgParamsSeparator),a=i.substring(0,s),o=i.substring(s+1),p=a.startsWith(d.Struct)?c.ArgStructSeparator:c.ArgListSeparator,u=(o?o.split(p):[]).map(f=>this.stringToNative(a+c.ArgParamsSeparator+f)[1]);return[d.Vector+c.ArgParamsSeparator+a,u]}else if(e.startsWith(d.Tuple)){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(c.ArgCompositeSeparator),o=i.split(c.ArgCompositeSeparator).map((p,l)=>this.stringToNative(`${s[l]}${c.IdentifierParamSeparator}${p}`)[1]);return[e,o]}else if(e.startsWith(d.Struct)){let s=e.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let o={_name:s[1]};return i&&i.split(c.ArgListSeparator).forEach(p=>{let l=p.match(new RegExp(`^\\(([^${c.ArgParamsSeparator}]+)${c.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(l){let[,u,f,g]=l;o[u]=this.stringToNative(`${f}${c.IdentifierParamSeparator}${g}`)[1]}}),[e,o]}else{if(e===d.String)return[e,i];if(e===d.Uint8||e===d.Uint16||e===d.Uint32)return[e,Number(i)];if(e===d.Uint64||e===d.Uint128||e===d.Uint256||e===d.Biguint)return[e,BigInt(i||0)];if(e===d.Bool)return[e,i==="true"];if(e===d.Address)return[e,i];if(e===d.Hex)return[e,i];if(e===d.Asset){let[s,a]=i.split(c.ArgCompositeSeparator),o={identifier:s,amount:BigInt(a)};return[e,o]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(e);if(s){let o=s.stringToNative(i);return[e,o]}let a=this.typeRegistry.resolveType(e);if(a!==e){let[o,p]=this.stringToNative(`${a}:${i}`);return[e,p]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(c.ArgParamsSeparator)){let[r,e]=t.split(c.ArgParamsSeparator);return[r,e]}return typeof t=="number"?[d.Uint32,t]:typeof t=="bigint"?[d.Uint64,t]:typeof t=="boolean"?[d.Bool,t]:[typeof t,t]}};var Or=n=>new x().nativeToString(d.String,n),Ur=n=>new x().nativeToString(d.Uint8,n),Fr=n=>new x().nativeToString(d.Uint16,n),Hr=n=>new x().nativeToString(d.Uint32,n),Lr=n=>new x().nativeToString(d.Uint64,n),jr=n=>new x().nativeToString(d.Biguint,n),Dr=n=>new x().nativeToString(d.Bool,n),kr=n=>new x().nativeToString(d.Address,n),It=n=>new x().nativeToString(d.Asset,n),qr=n=>new x().nativeToString(d.Hex,n),zr=(n,t)=>{if(t===null)return d.Option+c.ArgParamsSeparator;let r=n(t),e=r.indexOf(c.ArgParamsSeparator),i=r.substring(0,e),s=r.substring(e+1);return d.Option+c.ArgParamsSeparator+i+c.ArgParamsSeparator+s},Mr=(...n)=>new x().nativeToString(d.Tuple,n),Gr=n=>new x().nativeToString(d.Struct,n),Jr=n=>new x().nativeToString(d.Vector,n);var zt=rt(require("ajv"),1);var St=class{constructor(t){this.pendingBrand={protocol:k("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),e}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,r){if(!t)throw new Error(`Warp: ${r}`)}ensureWarpText(t,r){if(!t)throw new Error(`Warp: ${r}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.schema?.brand||R.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),s=new zt.default,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};var Mt=rt(require("ajv"),1);var J=class{constructor(t){this.config=t;this.config=t}async validate(t){let r=[];return r.push(...this.validatePrimaryAction(t)),r.push(...this.validateMaxOneValuePosition(t)),r.push(...this.validateVariableNamesAndResultNamesUppercase(t)),r.push(...this.validateAbiIsSetIfApplicable(t)),r.push(...await this.validateSchema(t)),{valid:r.length===0,errors:r}}validatePrimaryAction(t){try{let{action:r}=B(t);return r?[]:["Primary action is required"]}catch(r){return[r instanceof Error?r.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(e=>e.inputs?e.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&r.push(`${s} name '${a}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.output,"Output"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(a=>a.type==="contract"),e=t.actions.some(a=>a.type==="query");if(!r&&!e)return[];let i=t.actions.some(a=>a.abi),s=Object.values(t.output||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.output&&!i&&s?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||R.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),s=new Mt.default({strict:!1}),a=s.compile(i);return a(t)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var wt=class{constructor(t){this.config=t;this.pendingWarp={protocol:k("warp"),chain:"",name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.validate(e),e}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}async build(){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"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,r=100){return mt(t,r)}ensure(t,r){if(!t)throw new Error(r)}ensureWarpText(t,r){if(!t)throw new Error(r);if(typeof t=="object"&&!t.en)throw new Error(r)}async validate(t){let e=await new J(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
2
- `))}};var Q=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let r=localStorage.getItem(this.getKey(t));if(!r)return null;let e=JSON.parse(r,Kr);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(t)),null):e.value}catch{return null}}set(t,r,e){let i={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,Qr))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r?.startsWith(this.prefix)&&localStorage.removeItem(r)}}},Gt=new x,Qr=(n,t)=>typeof t=="bigint"?Gt.nativeToString("biguint",t):t,Kr=(n,t)=>typeof t=="string"&&t.startsWith(d.Biguint+":")?Gt.stringToNative(t)[1]:t;var V=class V{get(t){let r=V.cache.get(t);return r?Date.now()>r.expiresAt?(V.cache.delete(t),null):r.value:null}set(t,r,e){let i=Date.now()+e*1e3;V.cache.set(t,{value:r,expiresAt:i})}forget(t){V.cache.delete(t)}clear(){V.cache.clear()}};V.cache=new Map;var K=V;var bt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},lt={Warp:(n,t)=>`warp:${n}:${t}`,WarpAbi:(n,t)=>`warp-abi:${n}:${t}`,WarpExecutable:(n,t,r)=>`warp-exec:${n}:${t}:${r}`,RegistryInfo:(n,t)=>`registry-info:${n}:${t}`,Brand:(n,t)=>`brand:${n}:${t}`,Asset:(n,t,r)=>`asset:${n}:${t}:${r}`},_=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new Q:t==="memory"?new K:typeof window<"u"&&window.localStorage?new Q:new K}set(t,r,e){this.strategy.set(t,r,e)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var P=class{constructor(t,r){this.config=t;this.adapter=r}async apply(t,r,e={}){let i=this.applyVars(t,r,e);return await this.applyGlobals(t,i)}async applyGlobals(t,r){let e={...r};return e.actions=await Promise.all(e.actions.map(async i=>await this.applyActionGlobals(i))),e=await this.applyRootGlobals(e,t),e}applyVars(t,r,e={}){if(!r?.vars)return r;let i=S(t,this.adapter.chainInfo.name),s=JSON.stringify(r),a=(o,p)=>{s=s.replace(new RegExp(`{{${o.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(r.vars).forEach(([o,p])=>{if(typeof p!="string")a(o,p);else if(p.startsWith(c.Vars.Query+c.ArgParamsSeparator)){let l=p.slice(c.Vars.Query.length+1),[u,f]=l.split(c.ArgCompositeSeparator),g=t.currentUrl?new URLSearchParams(t.currentUrl.split("?")[1]).get(u):null,y=e.queries?.[u]||null||g;y&&a(o,y)}else if(p.startsWith(c.Vars.Env+c.ArgParamsSeparator)){let l=p.slice(c.Vars.Env.length+1),[u,f]=l.split(c.ArgCompositeSeparator),W={...t.vars,...e.envs}?.[u];W&&a(o,W)}else p===c.Source.UserWallet&&i?a(o,i):a(o,p)}),JSON.parse(s)}async applyRootGlobals(t,r){let e=JSON.stringify(t),i={config:r,adapter:this.adapter};return Object.values(c.Globals).forEach(s=>{let a=s.Accessor(i);a!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),a.toString()))}),JSON.parse(e)}async applyActionGlobals(t){let r=JSON.stringify(t),e={config:this.config,adapter:this.adapter};return Object.values(c.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}applyInputs(t,r,e,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let s=this.applyGlobalsToText(t),a=this.buildInputBag(r,e,i);return $(s,a)}applyGlobalsToText(t){if(!Object.values(c.Globals).map(a=>a.Placeholder).some(a=>t.includes(`{{${a}}}`)))return t;let i={config:this.config,adapter:this.adapter},s=t;return Object.values(c.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(s=s.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString()))}),s}buildInputBag(t,r,e){let i={};return t.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,o]=r.stringToNative(s.value);i[a]=String(o)}),e&&e.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,o]=r.stringToNative(s.value);if(i[`primary.${a}`]=String(o),s.input.type==="asset"&&typeof s.input.position=="object"){let p=o;p&&typeof p=="object"&&"identifier"in p&&"amount"in p&&(i[`primary.${a}.token`]=String(p.identifier),i[`primary.${a}.amount`]=String(p.amount))}}),i}};var j=class{constructor(t,r){this.config=t;this.adapters=r;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new x,this.cache=new _(t.cache?.type)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,r,e){let i=this.cache.get(lt.WarpExecutable(t,r||"",e))||[];return H(i)}async createExecutable(t,r,e,i={}){let s=w(t,r);if(!s)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,e),o=h(a.name,this.adapters),p=new P(this.config,o),l=await p.apply(this.config,t,i),u=w(l,r),{action:f,index:g}=B(l),W=this.getStringTypedInputs(f,e),y=await this.getResolvedInputs(a.name,f,W,p),m=await this.getModifiedInputs(y),v=[],A=[];g===r-1&&(v=y,A=m);let E=A.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,N=this.getDestinationFromAction(u),T=E?this.serializer.stringToNative(E)[1]:N;if(T&&(T=p.applyInputs(T,A,this.serializer,m)),!T&&s.type!=="collect")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let ut=this.getPreparedArgs(u,A);ut=ut.map(I=>p.applyInputs(I,A,this.serializer,m));let Jt=A.find(I=>I.input.position==="value")?.value||null,Qt="value"in u?u.value:null,Kt=Jt?.split(c.ArgParamsSeparator)[1]||Qt||"0",_t=p.applyInputs(Kt,A,this.serializer,m),Xt=BigInt(_t),Zt=A.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),Yt=[...("transfers"in u?u.transfers:[])||[],...Zt||[]].map(I=>{let nr=p.applyInputs(I,A,this.serializer,m);return this.serializer.stringToNative(nr)[1]}),tr=A.find(I=>I.input.position==="data")?.value,rr="data"in u?u.data||"":null,Et=tr||rr||null,er=Et?p.applyInputs(Et,A,this.serializer,m):null,Rt={warp:l,chain:a,action:r,destination:T,args:ut,value:Xt,transfers:Yt,data:er,resolvedInputs:A};return this.cache.set(lt.WarpExecutable(this.config.env,l.meta?.hash||"",r),Rt.resolvedInputs,bt.OneWeek),Rt}async getChainInfoForWarp(t,r){if(t.chain)return h(t.chain,this.adapters).chainInfo;if(r){let i=await this.tryGetChainFromInputs(t,r);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,r){let e=t.inputs||[];return r.map((i,s)=>{let a=e[s];return!a||i.includes(c.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,r,e,i){let s=r.inputs||[],a=await Promise.all(e.map(p=>this.preprocessInput(t,p))),o=(p,l)=>{if(p.source==="query"){let u=this.url.searchParams.get(p.name);return u?this.serializer.nativeToString(p.type,u):null}else if(p.source===c.Source.UserWallet){let u=S(this.config,t);return u?this.serializer.nativeToString("address",u):null}else if(p.source==="hidden"){if(p.default===void 0)return null;let u=i?i.applyInputs(String(p.default),[],this.serializer):String(p.default);return this.serializer.nativeToString(p.type,u)}else return a[l]||null};return s.map((p,l)=>{let u=o(p,l),f=p.default!==void 0?i?i.applyInputs(String(p.default),[],this.serializer):String(p.default):void 0;return{input:p,value:u||(f!==void 0?this.serializer.nativeToString(p.type,f):null)}})}async getModifiedInputs(t){let r=[];for(let e=0;e<t.length;e++){let i=t[e];if(i.input.modifier?.startsWith("scale:")){let[,s]=i.input.modifier.split(":");if(isNaN(Number(s))){let a=Number(t.find(l=>l.input.name===s)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${s}`);let o=i.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let p=q(o,+a);r.push({...i,value:`${i.input.type}:${p}`})}else{let a=i.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=q(a,+s);r.push({...i,value:`${i.input.type}:${o}`})}}else if(i.input.modifier?.startsWith(c.Transform.Prefix)){let s=i.input.modifier.substring(c.Transform.Prefix.length),a=this.config.transform?.runner;if(!a||typeof a.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let o=this.buildInputContext(t,e,i),p=await a.run(s,o);if(p==null)r.push(i);else{let l=this.serializer.nativeToString(i.input.type,p);r.push({...i,value:l})}}else r.push(i)}return r}buildInputContext(t,r,e){let i={};for(let s=0;s<r;s++){let a=t[s];if(!a.value)continue;let o=a.input.as||a.input.name,[,p]=this.serializer.stringToNative(a.value);if(i[o]=p,a.input.type==="asset"&&typeof p=="object"&&p!==null){let l=p;"identifier"in l&&"amount"in l&&(i[`${o}.token`]=String(l.identifier),i[`${o}.amount`]=String(l.amount),i[`${o}.identifier`]=String(l.identifier))}}if(e&&e.value){let s=e.input.as||e.input.name,[,a]=this.serializer.stringToNative(e.value);if(i[s]=a,e.input.type==="asset"&&typeof a=="object"&&a!==null){let o=a;"identifier"in o&&"amount"in o&&(i[`${s}.token`]=String(o.identifier),i[`${s}.amount`]=String(o.amount),i[`${s}.identifier`]=String(o.identifier))}}return i}async preprocessInput(t,r){try{let[e,i]=st(r),s=h(t,this.adapters);if(e==="asset"){let[a,o,p]=i.split(c.ArgCompositeSeparator);if(p)return r;let l=await s.dataLoader.getAsset(a);if(!l)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof l.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=q(o,l.decimals);return It({...l,amount:u})}else return r}catch(e){throw C.warn("WarpFactory: Preprocess input failed",e),e}}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,r){let e="args"in t?t.args||[]:[],i=[];return r.forEach(({input:s,value:a})=>{if(!(!a||!s.position)){if(typeof s.position=="object"){if(s.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${s.name}" has type "${s.type}"`);if(!s.position.token?.startsWith("arg:")||!s.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${s.name}"`);let[o,p]=this.serializer.stringToNative(a),l=p;if(!l||typeof l!="object"||!("identifier"in l)||!("amount"in l))throw new Error(`WarpFactory: Invalid asset value for input "${s.name}"`);let u=Number(s.position.token.split(":")[1])-1,f=Number(s.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",l.identifier)}),i.push({index:f,value:this.serializer.nativeToString("uint256",l.amount)})}else if(s.position.startsWith("arg:")){let o=Number(s.position.split(":")[1])-1;i.push({index:o,value:a})}}}),i.forEach(({index:s,value:a})=>{for(;e.length<=s;)e.push(void 0);e[s]=a}),e.filter(s=>s!==void 0)}async tryGetChainFromInputs(t,r){let e=t.actions.find(p=>p.inputs?.some(l=>l.position==="chain"));if(!e)return null;let i=e.inputs?.findIndex(p=>p.position==="chain");if(i===-1||i===void 0)return null;let s=r[i];if(!s)throw new Error("Chain input not found");let a=this.serializer.stringToNative(s)[1];return h(a,this.adapters).chainInfo}};var X=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.handlers=e,this.factory=new j(t,r)}async execute(t,r,e={}){let i=[],s=null,a=[],o=[],{action:p,index:l}=B(t);for(let u=1;u<=t.actions.length;u++){let f=w(t,u);if(!it(f,t))continue;let{tx:g,chain:W,immediateExecution:y,executable:m}=await this.executeAction(t,u,r,e);g&&i.push(g),W&&(s=W),y&&a.push(y),m&&u===l+1&&m.resolvedInputs&&(o=H(m.resolvedInputs))}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let u=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(u))}return{txs:i,chain:s,immediateExecutions:a,resolvedInputs:o}}async executeAction(t,r,e,i={}){let s=w(t,r);if(s.type==="link")return await this.callHandler(async()=>{let l=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(l):dt.open(l,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null};let a=await this.factory.createExecutable(t,r,e,i);if(s.type==="collect"){let l=await this.executeCollect(a);return l.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):l.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(l.values)}),{tx:null,chain:null,immediateExecution:null,executable:a})}let o=h(a.chain.name,this.adapters);if(s.type==="query"){let l=await o.executor.executeQuery(a);return l.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:l,tx:null})):this.handlers?.onError?.({message:JSON.stringify(l.values)}),{tx:null,chain:a.chain,immediateExecution:l,executable:a}}return{tx:await o.executor.createTransaction(a),chain:a.chain,immediateExecution:null,executable:a}}async evaluateOutput(t,r){if(r.length===0||t.actions.length===0||!this.handlers)return;let e=await this.factory.getChainInfoForWarp(t),i=h(e.name,this.adapters),s=(await Promise.all(t.actions.map(async(a,o)=>{if(!it(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let p=r[o],l=o+1;if(!p){let f=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,l),g={status:"error",warp:t,action:l,user:S(this.config,e.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:f};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${l} failed: Transaction not found`})),g}let u=await i.output.getActionExecution(t,l,p);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:l,chain:e,execution:u,tx:p})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values)})),u}))).filter(a=>a!==null);if(s.every(a=>a.status==="success")){let a=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(a))}else await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(s.map(a=>a.values))}`}))}async executeCollect(t,r){let e=S(this.config,t.chain.name),i=w(t.warp,t.action),s=this.factory.getSerializer(),a=G(t.resolvedInputs,s);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,e,a,r);let{values:o,output:p}=await ot(t.warp,a,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,e,"unhandled",o,p)}async doHttpRequest(t,r,e,i,s){let a=new P(this.config,h(t.chain.name,this.adapters)),o=new Headers;if(o.set("Content-Type","application/json"),o.set("Accept","application/json"),this.handlers?.onSignRequest){if(!e)throw new Error(`No wallet configured for chain ${t.chain.name}`);let{message:f,nonce:g,expiresAt:W}=await pt(e,`${t.chain.name}-adapter`),y=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:f,chain:t.chain}));if(y){let m=ct(e,y,g,W);Object.entries(m).forEach(([v,A])=>o.set(v,A))}}r.headers&&Object.entries(r.headers).forEach(([f,g])=>{let W=a.applyInputs(g,t.resolvedInputs,this.factory.getSerializer());o.set(f,W)});let p=r.method||"GET",l=p==="GET"?void 0:JSON.stringify({...i,...s}),u=a.applyInputs(r.url,t.resolvedInputs,this.factory.getSerializer());C.debug("WarpExecutor: Executing HTTP collect",{url:u,method:p,headers:o,body:l});try{let f=await fetch(u,{method:p,headers:o,body:l});C.debug("Collect response status",{status:f.status});let g=await f.json();C.debug("Collect response content",{content:g});let{values:W,output:y}=await ot(t.warp,g,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),f.ok?"success":"error",W,y,g)}catch(f){C.error("WarpActionExecutor: Error executing collect",f);let g=H(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:g}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(e=>e.input.position==="receiver"||e.input.position==="destination")?.value||t.destination}buildCollectResult(t,r,e,i,s,a){let o=xt(this.config,this.adapters,t.warp,t.action,s),p=H(t.resolvedInputs);return{status:e,warp:t.warp,action:t.action,user:r||S(this.config,t.chain.name),txHash:null,tx:null,next:o,values:i,output:a?{...s,_DATA:a}:s,messages:vt(t.warp,s,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:p}}async callHandler(t){if(t)return await t()}};var Z=class{constructor(t){this.config=t}async search(t,r,e){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}`,...e},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...r})});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 Y=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!D(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),a=(await Promise.all(i)).filter(l=>l.match),o=a.length>0,p=a.map(l=>({url:l.url,warp:l.warp}));return{match:o,output:p}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(c.HttpProtocolPrefix)?D(t):b(t);if(!i)return e;try{let{type:s,identifierBase:a}=i,o=null,p=null,l=null,u=h(i.chain,this.adapters),f=t.startsWith(c.HttpProtocolPrefix)?Wt(t):yt(i.identifier);if(s==="hash"){o=await u.builder().createFromTransactionHash(a,r);let W=await u.registry.getInfoByHash(a,r);p=W.registryInfo,l=W.brand}else if(s==="alias"){let W=await u.registry.getInfoByAlias(a,r);p=W.registryInfo,l=W.brand,W.registryInfo&&(o=await u.builder().createFromTransactionHash(W.registryInfo.hash,r))}o&&o.meta&&(_r(o,u.chainInfo.name,p,i.identifier),o.meta.query=f);let g=o?await new P(this.config,u).apply(this.config,o):null;return g?{match:!0,url:t,warp:g,chain:u.chainInfo.name,registryInfo:p,brand:l}:e}catch(s){return C.error("Error detecting warp link",s),e}}},_r=(n,t,r,e)=>{n.meta&&(n.meta.identifier=r?.alias?at(t,"alias",r.alias):at(t,"hash",r?.hash??e))};var Tt=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}getAdapters(){return this.adapters}addAdapter(t){return this.adapters.push(t),this}createExecutor(t){return new X(this.config,this.adapters,t)}async detectWarp(t,r){return new Y(this.config,this.adapters).detect(t,r)}async executeWarp(t,r,e,i={}){let s=typeof t=="object",a=!s&&t.startsWith("http")&&t.endsWith(".json"),o=s?t:null;if(!o&&a){let y=await fetch(t);if(!y.ok)throw new Error("WarpClient: executeWarp - invalid url");o=await y.json()}if(o||(o=(await this.detectWarp(t,i.cache)).warp),!o)throw new Error("Warp not found");let p=this.createExecutor(e),{txs:l,chain:u,immediateExecutions:f,resolvedInputs:g}=await p.execute(o,r,{queries:i.queries});return{txs:l,chain:u,immediateExecutions:f,evaluateOutput:async y=>{await p.evaluateOutput(o,y)},resolvedInputs:g}}async createInscriptionTransaction(t,r){return await h(t,this.adapters).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return h(t,this.adapters).builder().createFromTransaction(r,e)}async createFromTransactionHash(t,r){let e=b(t);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return h(e.chain,this.adapters).builder().createFromTransactionHash(t,r)}async signMessage(t,r){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return h(t,this.adapters).wallet.signMessage(r)}async getActions(t,r,e=!1){let i=this.getDataLoader(t);return(await Promise.all(r.map(async a=>i.getAction(a,e)))).filter(a=>a!==null)}getExplorer(t){return h(t,this.adapters).explorer}getOutput(t){return h(t,this.adapters).output}async getRegistry(t){let r=h(t,this.adapters).registry;return await r.init(),r}getDataLoader(t){return h(t,this.adapters).dataLoader}getWallet(t){return h(t,this.adapters).wallet}get factory(){return new j(this.config,this.adapters)}get index(){return new Z(this.config)}get linkBuilder(){return new F(this.config,this.adapters)}createBuilder(t){return h(t,this.adapters).builder()}createAbiBuilder(t){return h(t,this.adapters).abiBuilder()}createBrandBuilder(t){return h(t,this.adapters).brandBuilder()}createSerializer(t){return h(t,this.adapters).serializer}resolveText(t){return z(t,this.config)}};var Pt=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,r){this.typeHandlers.set(t,r)}registerTypeAlias(t,r){this.typeAliases.set(t,r)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let r=this.typeAliases.get(t);return r?this.getHandler(r):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let r=this.typeAliases.get(t);return r?this.resolveType(r):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,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,evaluateOutputCommon,extractCollectOutput,extractIdentifierInfoFromUrl,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,hasInputPrefix,hex,isEqualWarpIdentifier,isWarpActionAutoExecute,isWarpI18nText,mergeNestedPayload,option,parseOutputOutIndex,parseSignedMessage,replacePlaceholders,resolveWarpText,safeWindow,setCryptoProvider,shiftBigintBy,splitInput,string,struct,testCryptoAvailability,toInputPayloadValue,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateSignedMessage,vector});
1
+ "use strict";var ir=Object.create;var tt=Object.defineProperty;var ar=Object.getOwnPropertyDescriptor;var sr=Object.getOwnPropertyNames;var or=Object.getPrototypeOf,pr=Object.prototype.hasOwnProperty;var cr=(n,t)=>{for(var r in t)tt(n,r,{get:t[r],enumerable:!0})},Bt=(n,t,r,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of sr(t))!pr.call(n,i)&&i!==r&&tt(n,i,{get:()=>t[i],enumerable:!(e=ar(t,i))||e.enumerable});return n};var rt=(n,t,r)=>(r=n!=null?ir(or(n)):{},Bt(t||!n||!n.__esModule?tt(r,"default",{value:n,enumerable:!0}):r,n)),lr=n=>Bt(tt({},"__esModule",{value:!0}),n);var Xr={};cr(Xr,{BrowserCryptoProvider:()=>et,CacheTtl:()=>bt,NodeCryptoProvider:()=>nt,WARP_LANGUAGES:()=>yr,WarpBrandBuilder:()=>wt,WarpBuilder:()=>St,WarpCache:()=>_,WarpCacheKey:()=>lt,WarpChainName:()=>$t,WarpClient:()=>Tt,WarpConfig:()=>R,WarpConstants:()=>p,WarpExecutor:()=>X,WarpFactory:()=>j,WarpIndex:()=>Z,WarpInputTypes:()=>d,WarpInterpolator:()=>P,WarpLinkBuilder:()=>F,WarpLinkDetecter:()=>Y,WarpLogger:()=>C,WarpProtocolVersions:()=>O,WarpSerializer:()=>x,WarpTypeRegistry:()=>Pt,WarpValidator:()=>J,address:()=>kr,applyOutputToMessages:()=>vt,asset:()=>It,biguint:()=>jr,bool:()=>Dr,buildMappedOutput:()=>G,buildNestedPayload:()=>Ut,bytesToBase64:()=>gr,bytesToHex:()=>Vt,cleanWarpIdentifier:()=>M,createAuthHeaders:()=>ct,createAuthMessage:()=>pt,createCryptoProvider:()=>mr,createHttpAuthHeaders:()=>Rr,createSignableMessage:()=>jt,createWarpI18nText:()=>Ar,createWarpIdentifier:()=>at,evaluateOutputCommon:()=>Ht,extractCollectOutput:()=>ot,extractIdentifierInfoFromUrl:()=>D,extractQueryStringFromIdentifier:()=>yt,extractQueryStringFromUrl:()=>Wt,extractResolvedInputValues:()=>H,extractWarpSecrets:()=>Wr,findWarpAdapterForChain:()=>m,getCryptoProvider:()=>ft,getEventNameFromWarp:()=>ur,getLatestProtocolIdentifier:()=>k,getNextInfo:()=>xt,getProviderConfig:()=>Tr,getRandomBytes:()=>gt,getRandomHex:()=>ht,getWarpActionByIndex:()=>S,getWarpBrandLogoUrl:()=>dr,getWarpInfoFromIdentifier:()=>b,getWarpPrimaryAction:()=>B,getWarpWalletAddress:()=>Dt,getWarpWalletAddressFromConfig:()=>w,getWarpWalletMnemonic:()=>qt,getWarpWalletMnemonicFromConfig:()=>Nr,getWarpWalletPrivateKey:()=>kt,getWarpWalletPrivateKeyFromConfig:()=>Vr,hasInputPrefix:()=>wr,hex:()=>qr,isEqualWarpIdentifier:()=>xr,isWarpActionAutoExecute:()=>it,isWarpI18nText:()=>vr,mergeNestedPayload:()=>Ct,option:()=>zr,parseOutputOutIndex:()=>Lt,parseSignedMessage:()=>$r,replacePlaceholders:()=>$,resolveWarpText:()=>z,safeWindow:()=>dt,setCryptoProvider:()=>fr,shiftBigintBy:()=>q,splitInput:()=>st,string:()=>Or,struct:()=>Gr,testCryptoAvailability:()=>hr,toInputPayloadValue:()=>Ft,toPreviewText:()=>mt,tuple:()=>Mr,uint16:()=>Fr,uint32:()=>Hr,uint64:()=>Lr,uint8:()=>Ur,validateSignedMessage:()=>Br,vector:()=>Jr});module.exports=lr(Xr);var $t=(c=>(c.Multiversx="multiversx",c.Vibechain="vibechain",c.Sui="sui",c.Ethereum="ethereum",c.Base="base",c.Arbitrum="arbitrum",c.Somnia="somnia",c.Fastset="fastset",c))($t||{}),p={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"}},d={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"},dt=typeof window<"u"?window:{open:()=>{}};var O={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},R={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${O.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${O.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",p.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 ur=(n,t)=>{let r=n.alerts?.[t];if(!r)return null;let e=p.Alerts.TriggerEventPrefix+p.ArgParamsSeparator;if(!r.trigger.startsWith(e))return null;let i=r.trigger.replace(e,"");return i||null};var dr=(n,t)=>typeof n.logo=="string"?n.logo:n.logo[t?.scheme??"light"];var et=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let r=new Uint8Array(t);return window.crypto.getRandomValues(r),r}},nt=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let r=await import("crypto");return new Uint8Array(r.randomBytes(t))}catch(r){throw new Error(`Node.js crypto not available: ${r instanceof Error?r.message:"Unknown error"}`)}}},U=null;function ft(){if(U)return U;if(typeof window<"u"&&window.crypto)return U=new et,U;if(typeof process<"u"&&process.versions?.node)return U=new nt,U;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function fr(n){U=n}async function gt(n,t){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(t||ft()).getRandomBytes(n)}function Vt(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(n.length*2);for(let r=0;r<n.length;r++){let e=n[r];t[r*2]=(e>>>4).toString(16),t[r*2+1]=(e&15).toString(16)}return t.join("")}function gr(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 ht(n,t){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let r=await gt(n/2,t);return Vt(r)}async function hr(){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 gt(16),n.randomBytes=!0}catch{}return n}function mr(){return ft()}var Wr=n=>Object.values(n.vars||{}).filter(t=>t.startsWith(`${p.Vars.Env}:`)).map(t=>{let r=t.replace(`${p.Vars.Env}:`,"").trim(),[e,i]=r.split(p.ArgCompositeSeparator);return{key:e,description:i||null}});var m=(n,t)=>{let r=t.find(e=>e.chainInfo.name.toLowerCase()===n.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${n}`);return r},k=n=>{if(n==="warp")return`warp:${O.Warp}`;if(n==="brand")return`brand:${O.Brand}`;if(n==="abi")return`abi:${O.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},S=(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(s=>s.primary===!0);if(t)return{action:t,index:n.actions.indexOf(t)};let r=["transfer","contract","query","collect"],e=n.actions.find(s=>r.includes(s.type));return e?{action:e,index:n.actions.indexOf(e)}:{action:n.actions[0],index:0}},it=(n,t)=>{if(n.auto===!1)return!1;if(n.type==="link"){if(n.auto===!0)return!0;let{action:r}=B(t);return n===r}return!0},q=(n,t)=>{let r=n.toString(),[e,i=""]=r.split("."),s=Math.abs(t);if(t>0)return BigInt(e+i.padEnd(s,"0"));if(t<0){let a=e+i;if(s>=a.length)return 0n;let o=a.slice(0,-s)||"0";return BigInt(o)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},mt=(n,t=100)=>{if(!n)return"";let r=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r},$=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||"");var yr={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"},z=(n,t)=>{let r=t?.preferences?.locale||"en";if(typeof n=="string")return n;if(typeof n=="object"&&n!==null){if(r in n)return n[r];if("en"in n)return n.en;let e=Object.keys(n);if(e.length>0)return n[e[0]]}return""},vr=n=>typeof n=="object"&&n!==null&&Object.keys(n).length>0,Ar=n=>n;var M=n=>n.startsWith(p.IdentifierAliasMarker)?n.replace(p.IdentifierAliasMarker,""):n,xr=(n,t)=>!n||!t?!1:M(n)===M(t),at=(n,t,r)=>{let e=M(r);return t===p.IdentifierType.Alias?p.IdentifierAliasMarker+n+p.IdentifierParamSeparator+e:n+p.IdentifierParamSeparator+t+p.IdentifierParamSeparator+e},b=n=>{let t=decodeURIComponent(n).trim(),r=M(t),e=r.split("?")[0],i=Nt(e);if(e.length===64&&/^[a-fA-F0-9]+$/.test(e))return{chain:p.IdentifierChainDefault,type:p.IdentifierType.Hash,identifier:r,identifierBase:e};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[s,a,o]=i;if(a===p.IdentifierType.Alias||a===p.IdentifierType.Hash){let c=r.includes("?")?o+r.substring(r.indexOf("?")):o;return{chain:s,type:a,identifier:c,identifierBase:o}}}if(i.length===2){let[s,a]=i;if(s===p.IdentifierType.Alias||s===p.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a;return{chain:p.IdentifierChainDefault,type:s,identifier:o,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==p.IdentifierType.Alias&&s!==p.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a,c=Cr(a,s)?p.IdentifierType.Hash:p.IdentifierType.Alias;return{chain:s,type:c,identifier:o,identifierBase:a}}}return{chain:p.IdentifierChainDefault,type:p.IdentifierType.Alias,identifier:r,identifierBase:e}},D=n=>{let t=new URL(n),e=t.searchParams.get(p.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let i=decodeURIComponent(e);return b(i)},Cr=(n,t)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,Ir=n=>{let t=p.IdentifierParamSeparator,r=n.indexOf(t);return r!==-1?{separator:t,index:r}:null},Nt=n=>{let t=Ir(n);if(!t)return[n];let{separator:r,index:e}=t,i=n.substring(0,e),s=n.substring(e+r.length),a=Nt(s);return[i,...a]},Wt=n=>{try{let t=new URL(n),r=new URLSearchParams(t.search);return r.delete(p.IdentifierParamName),r.toString()||null}catch{return null}},yt=n=>{let t=n.indexOf("?");if(t===-1||t===n.length-1)return null;let r=n.substring(t+1);return r.length>0?r:null};var st=n=>{let[t,...r]=n.split(/:(.*)/,2);return[t,r[0]||""]},wr=n=>{let t=new Set(Object.values(d));if(!n.includes(p.ArgParamsSeparator))return!1;let r=st(n)[0];return t.has(r)};var vt=(n,t,r)=>{let e=Object.entries(n.messages||{}).map(([i,s])=>{let a=z(s,r);return[i,$(a,t)]});return Object.fromEntries(e)};var Ot=rt(require("qr-code-styling"),1);var F=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!D(t):!1}build(t,r,e){let i=this.config.clientUrl||R.DefaultClientUrl(this.config.env),s=m(t,this.adapters),a=r===p.IdentifierType.Alias?e:r+p.IdentifierParamSeparator+e,o=s.chainInfo.name+p.IdentifierParamSeparator+a,c=encodeURIComponent(o);return R.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${p.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let r=b(t);if(!r)return null;let e=m(r.chain,this.adapters);return e?this.build(e.chainInfo.name,r.type,r.identifierBase):null}generateQrCode(t,r,e,i=512,s="white",a="black",o="#23F7DD"){let c=m(t,this.adapters),l=this.build(c.chainInfo.name,r,e);return new Ot.default({type:"svg",width:i,height:i,data:String(l),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},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(o)}" 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 Sr="https://",xt=(n,t,r,e,i)=>{let s=r.actions?.[e-1]?.next||r.next||null;if(!s)return null;if(s.startsWith(Sr))return[{identifier:null,url:s}];let[a,o]=s.split("?");if(!o){let g=$(a,{...r.vars,...i});return[{identifier:g,url:At(t,g,n)}]}let c=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let g=$(o,{...r.vars,...i}),W=g?`${a}?${g}`:a;return[{identifier:W,url:At(t,W,n)}]}let l=c[0];if(!l)return[];let u=l.match(/{{([^[]+)\[\]/),f=u?u[1]:null;if(!f||i[f]===void 0)return[];let h=Array.isArray(i[f])?i[f]:[i[f]];if(h.length===0)return[];let v=c.filter(g=>g.includes(`{{${f}[]`)).map(g=>{let W=g.match(/\[\](\.[^}]+)?}}/),y=W&&W[1]||"";return{placeholder:g,field:y?y.slice(1):"",regex:new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(g=>{let W=o;for(let{regex:E,field:N}of v){let T=N?br(g,N):g;if(T==null)return null;W=W.replace(E,T)}if(W.includes("{{")||W.includes("}}"))return null;let y=W?`${a}?${W}`:a;return{identifier:y,url:At(t,y,n)}}).filter(g=>g!==null)},At=(n,t,r)=>{let[e,i]=t.split("?"),s=b(e)||{chain:p.IdentifierChainDefault,type:"alias",identifier:e,identifierBase:e},a=m(s.chain,n);if(!a)throw new Error(`Adapter not found for chain ${s.chain}`);let o=new F(r,n).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return o;let c=new URL(o);return new URLSearchParams(i).forEach((l,u)=>c.searchParams.set(u,l)),c.toString().replace(/\/\?/,"?")},br=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);function Ut(n,t,r){return n.startsWith(p.Position.Payload)?n.slice(p.Position.Payload.length).split(".").reduceRight((e,i,s,a)=>({[i]:s===a.length-1?{[t]:r}:e}),{}):{[t]:r}}function Ct(n,t){if(!n)return{...t};if(!t)return{...n};let r={...n};return Object.keys(t).forEach(e=>{r[e]&&typeof r[e]=="object"&&typeof t[e]=="object"?r[e]=Ct(r[e],t[e]):r[e]=t[e]}),r}function Ft(n,t){if(!n.value)return null;let r=t.stringToNative(n.value)[1];if(n.input.type==="biguint")return r.toString();if(n.input.type==="asset"){let{identifier:e,amount:i}=r;return{identifier:e,amount:i.toString()}}else return r}function H(n){return n.map(t=>t.value).filter(t=>t!=null&&t!=="")}function G(n,t){let r={};return n.forEach(e=>{let i=e.input.as||e.input.name,s=Ft(e,t);if(e.input.position&&typeof e.input.position=="string"&&e.input.position.startsWith(p.Position.Payload)){let a=Ut(e.input.position,i,s);r=Ct(r,a)}else r[i]=s}),r}var Tr=(n,t,r,e)=>{let i=n.preferences?.providers?.[t];return i?.[r]?typeof i[r]=="string"?{url:i[r]}:i[r]:{url:e}};var L=class L{static debug(...t){L.isTestEnv||console.debug(...t)}static info(...t){L.isTestEnv||console.info(...t)}static warn(...t){L.isTestEnv||console.warn(...t)}static error(...t){L.isTestEnv||console.error(...t)}};L.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=L;var ot=async(n,t,r,e,i,s)=>{let a=[],o=[],c={};for(let[u,f]of Object.entries(n.output||{})){if(f.startsWith(p.Transform.Prefix))continue;let h=Lt(f);if(h!==null&&h!==r){c[u]=null;continue}let[v,...A]=f.split("."),g=(W,y)=>y.reduce((E,N)=>E&&E[N]!==void 0?E[N]:null,W);if(v==="out"||v.startsWith("out[")){let W=A.length===0?t?.data||t:g(t,A);a.push(String(W)),o.push(W),c[u]=W}else c[u]=f}let l=G(e,i);return{values:{string:a,native:o,mapped:l},output:await Ht(n,c,r,e,i,s)}},Ht=async(n,t,r,e,i,s)=>{if(!n.output)return t;let a={...t};return a=Pr(a,n,r,e,i),a=await Er(n,a,s.transform?.runner||null),a},Pr=(n,t,r,e,i)=>{let s={...n},a=S(t,r)?.inputs||[];for(let[o,c]of Object.entries(s))if(typeof c=="string"&&c.startsWith("in.")){let l=c.split(".")[1],u=a.findIndex(h=>h.as===l||h.name===l),f=u!==-1?e[u]?.value:null;s[o]=f?i.stringToNative(f)[1]:null}return s},Er=async(n,t,r)=>{if(!n.output)return t;let e={...t},i=Object.entries(n.output).filter(([,s])=>s.startsWith(p.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(p.Transform.Prefix.length)}));if(i.length>0&&(!r||typeof r.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:s,code:a}of i)try{e[s]=await r.run(a,e)}catch(o){C.error(`Transform error for output '${s}':`,o),e[s]=null}return e},Lt=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)};async function jt(n,t,r,e=5){let i=await ht(64,r),s=new Date(Date.now()+e*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:i,expiresAt:s,purpose:t}),nonce:i,expiresAt:s}}async function pt(n,t,r,e){let i=e||`prove-wallet-ownership for app "${t}"`;return jt(n,i,r,5)}function ct(n,t,r,e){return{"X-Signer-Wallet":n,"X-Signer-Signature":t,"X-Signer-Nonce":r,"X-Signer-ExpiresAt":e}}async function Rr(n,t,r,e){let{message:i,nonce:s,expiresAt:a}=await pt(n,r,e),o=await t(i);return ct(n,o,s,a)}function Br(n){let t=new Date(n).getTime();return Date.now()<t}function $r(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 Dt=n=>n?typeof n=="string"?n:n.address:null,w=(n,t)=>Dt(n.user?.wallets?.[t]||null),kt=n=>n?typeof n=="string"?n:n.privateKey:null,qt=n=>n?typeof n=="string"?n:n.mnemonic:null,Vr=(n,t)=>kt(n.user?.wallets?.[t]||null)?.trim()||null,Nr=(n,t)=>qt(n.user?.wallets?.[t]||null)?.trim()||null;var x=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,r){if(t===d.Tuple&&Array.isArray(r)){if(r.length===0)return t+p.ArgParamsSeparator;if(r.every(e=>typeof e=="string"&&e.includes(p.ArgParamsSeparator))){let e=r.map(a=>this.getTypeAndValue(a)),i=e.map(([a])=>a),s=e.map(([,a])=>a);return`${t}(${i.join(p.ArgCompositeSeparator)})${p.ArgParamsSeparator}${s.join(p.ArgListSeparator)}`}return t+p.ArgParamsSeparator+r.join(p.ArgListSeparator)}if(t===d.Struct&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let e=r;if(!e._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=e._name,s=Object.keys(e).filter(o=>o!=="_name");if(s.length===0)return`${t}(${i})${p.ArgParamsSeparator}`;let a=s.map(o=>{let[c,l]=this.getTypeAndValue(e[o]);return`(${o}${p.ArgParamsSeparator}${c})${l}`});return`${t}(${i})${p.ArgParamsSeparator}${a.join(p.ArgListSeparator)}`}if(t===d.Vector&&Array.isArray(r)){if(r.length===0)return`${t}${p.ArgParamsSeparator}`;if(r.every(e=>typeof e=="string"&&e.includes(p.ArgParamsSeparator))){let e=r[0],i=e.indexOf(p.ArgParamsSeparator),s=e.substring(0,i),a=r.map(c=>{let l=c.indexOf(p.ArgParamsSeparator),u=c.substring(l+1);return s.startsWith(d.Tuple)?u.replace(p.ArgListSeparator,p.ArgCompositeSeparator):u}),o=s.startsWith(d.Struct)?p.ArgStructSeparator:p.ArgListSeparator;return t+p.ArgParamsSeparator+s+p.ArgParamsSeparator+a.join(o)}return t+p.ArgParamsSeparator+r.join(p.ArgListSeparator)}if(t===d.Asset&&typeof r=="object"&&r&&"identifier"in r&&"amount"in r)return"decimals"in r?d.Asset+p.ArgParamsSeparator+r.identifier+p.ArgCompositeSeparator+String(r.amount)+p.ArgCompositeSeparator+String(r.decimals):d.Asset+p.ArgParamsSeparator+r.identifier+p.ArgCompositeSeparator+String(r.amount);if(this.typeRegistry){let e=this.typeRegistry.getHandler(t);if(e)return e.nativeToString(r);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,r)}return t+p.ArgParamsSeparator+(r?.toString()??"")}stringToNative(t){let r=t.split(p.ArgParamsSeparator),e=r[0],i=r.slice(1).join(p.ArgParamsSeparator);if(e==="null")return[e,null];if(e===d.Option){let[s,a]=i.split(p.ArgParamsSeparator);return[d.Option+p.ArgParamsSeparator+s,a||null]}if(e===d.Vector){let s=i.indexOf(p.ArgParamsSeparator),a=i.substring(0,s),o=i.substring(s+1),c=a.startsWith(d.Struct)?p.ArgStructSeparator:p.ArgListSeparator,u=(o?o.split(c):[]).map(f=>this.stringToNative(a+p.ArgParamsSeparator+f)[1]);return[d.Vector+p.ArgParamsSeparator+a,u]}else if(e.startsWith(d.Tuple)){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=i.split(p.ArgCompositeSeparator).map((c,l)=>this.stringToNative(`${s[l]}${p.IdentifierParamSeparator}${c}`)[1]);return[e,o]}else if(e.startsWith(d.Struct)){let s=e.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let o={_name:s[1]};return i&&i.split(p.ArgListSeparator).forEach(c=>{let l=c.match(new RegExp(`^\\(([^${p.ArgParamsSeparator}]+)${p.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(l){let[,u,f,h]=l;o[u]=this.stringToNative(`${f}${p.IdentifierParamSeparator}${h}`)[1]}}),[e,o]}else{if(e===d.String)return[e,i];if(e===d.Uint8||e===d.Uint16||e===d.Uint32)return[e,Number(i)];if(e===d.Uint64||e===d.Uint128||e===d.Uint256||e===d.Biguint)return[e,BigInt(i||0)];if(e===d.Bool)return[e,i==="true"];if(e===d.Address)return[e,i];if(e===d.Hex)return[e,i];if(e===d.Asset){let[s,a]=i.split(p.ArgCompositeSeparator),o={identifier:s,amount:BigInt(a)};return[e,o]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(e);if(s){let o=s.stringToNative(i);return[e,o]}let a=this.typeRegistry.resolveType(e);if(a!==e){let[o,c]=this.stringToNative(`${a}:${i}`);return[e,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(p.ArgParamsSeparator)){let[r,e]=t.split(p.ArgParamsSeparator);return[r,e]}return typeof t=="number"?[d.Uint32,t]:typeof t=="bigint"?[d.Uint64,t]:typeof t=="boolean"?[d.Bool,t]:[typeof t,t]}};var Or=n=>new x().nativeToString(d.String,n),Ur=n=>new x().nativeToString(d.Uint8,n),Fr=n=>new x().nativeToString(d.Uint16,n),Hr=n=>new x().nativeToString(d.Uint32,n),Lr=n=>new x().nativeToString(d.Uint64,n),jr=n=>new x().nativeToString(d.Biguint,n),Dr=n=>new x().nativeToString(d.Bool,n),kr=n=>new x().nativeToString(d.Address,n),It=n=>new x().nativeToString(d.Asset,n),qr=n=>new x().nativeToString(d.Hex,n),zr=(n,t)=>{if(t===null)return d.Option+p.ArgParamsSeparator;let r=n(t),e=r.indexOf(p.ArgParamsSeparator),i=r.substring(0,e),s=r.substring(e+1);return d.Option+p.ArgParamsSeparator+i+p.ArgParamsSeparator+s},Mr=(...n)=>new x().nativeToString(d.Tuple,n),Gr=n=>new x().nativeToString(d.Struct,n),Jr=n=>new x().nativeToString(d.Vector,n);var zt=rt(require("ajv"),1);var wt=class{constructor(t){this.pendingBrand={protocol:k("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),e}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,r){if(!t)throw new Error(`Warp: ${r}`)}ensureWarpText(t,r){if(!t)throw new Error(`Warp: ${r}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.schema?.brand||R.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),s=new zt.default,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};var Mt=rt(require("ajv"),1);var J=class{constructor(t){this.config=t;this.config=t}async validate(t){let r=[];return r.push(...this.validatePrimaryAction(t)),r.push(...this.validateMaxOneValuePosition(t)),r.push(...this.validateVariableNamesAndResultNamesUppercase(t)),r.push(...this.validateAbiIsSetIfApplicable(t)),r.push(...await this.validateSchema(t)),{valid:r.length===0,errors:r}}validatePrimaryAction(t){try{let{action:r}=B(t);return r?[]:["Primary action is required"]}catch(r){return[r instanceof Error?r.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(e=>e.inputs?e.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&r.push(`${s} name '${a}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.output,"Output"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(a=>a.type==="contract"),e=t.actions.some(a=>a.type==="query");if(!r&&!e)return[];let i=t.actions.some(a=>a.abi),s=Object.values(t.output||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.output&&!i&&s?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||R.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),s=new Mt.default({strict:!1}),a=s.compile(i);return a(t)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var St=class{constructor(t){this.config=t;this.pendingWarp={protocol:k("warp"),chain:"",name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.validate(e),e}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}async build(){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"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,r=100){return mt(t,r)}ensure(t,r){if(!t)throw new Error(r)}ensureWarpText(t,r){if(!t)throw new Error(r);if(typeof t=="object"&&!t.en)throw new Error(r)}async validate(t){let e=await new J(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
2
+ `))}};var Q=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let r=localStorage.getItem(this.getKey(t));if(!r)return null;let e=JSON.parse(r,Kr);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(t)),null):e.value}catch{return null}}set(t,r,e){let i={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,Qr))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r?.startsWith(this.prefix)&&localStorage.removeItem(r)}}},Gt=new x,Qr=(n,t)=>typeof t=="bigint"?Gt.nativeToString("biguint",t):t,Kr=(n,t)=>typeof t=="string"&&t.startsWith(d.Biguint+":")?Gt.stringToNative(t)[1]:t;var V=class V{get(t){let r=V.cache.get(t);return r?Date.now()>r.expiresAt?(V.cache.delete(t),null):r.value:null}set(t,r,e){let i=Date.now()+e*1e3;V.cache.set(t,{value:r,expiresAt:i})}forget(t){V.cache.delete(t)}clear(){V.cache.clear()}};V.cache=new Map;var K=V;var bt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},lt={Warp:(n,t)=>`warp:${n}:${t}`,WarpAbi:(n,t)=>`warp-abi:${n}:${t}`,WarpExecutable:(n,t,r)=>`warp-exec:${n}:${t}:${r}`,RegistryInfo:(n,t)=>`registry-info:${n}:${t}`,Brand:(n,t)=>`brand:${n}:${t}`,Asset:(n,t,r)=>`asset:${n}:${t}:${r}`},_=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new Q:t==="memory"?new K:typeof window<"u"&&window.localStorage?new Q:new K}set(t,r,e){this.strategy.set(t,r,e)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var P=class{constructor(t,r){this.config=t;this.adapter=r}async apply(t,r={}){let e=this.applyVars(t,r);return await this.applyGlobals(e)}async applyGlobals(t){let r={...t};return r.actions=await Promise.all((r.actions||[]).map(async e=>await this.applyActionGlobals(e))),r=await this.applyRootGlobals(r),r}applyVars(t,r={}){if(!t?.vars)return t;let e=w(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),s=(a,o)=>{i=i.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([a,o])=>{if(typeof o!="string")s(a,o);else if(o.startsWith(p.Vars.Query+p.ArgParamsSeparator)){let c=o.slice(p.Vars.Query.length+1),[l,u]=c.split(p.ArgCompositeSeparator),f=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(l):null,v=r.queries?.[l]||null||f;v&&s(a,v)}else if(o.startsWith(p.Vars.Env+p.ArgParamsSeparator)){let c=o.slice(p.Vars.Env.length+1),[l,u]=c.split(p.ArgCompositeSeparator),h={...this.config.vars,...r.envs}?.[l];h&&s(a,h)}else o===p.Source.UserWallet&&e?s(a,e):s(a,o)}),JSON.parse(i)}async applyRootGlobals(t){let r=JSON.stringify(t),e={config:this.config,adapter:this.adapter};return Object.values(p.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}async applyActionGlobals(t){let r=JSON.stringify(t),e={config:this.config,adapter:this.adapter};return Object.values(p.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}applyInputs(t,r,e,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let s=this.applyGlobalsToText(t),a=this.buildInputBag(r,e,i);return $(s,a)}applyGlobalsToText(t){if(!Object.values(p.Globals).map(a=>a.Placeholder).some(a=>t.includes(`{{${a}}}`)))return t;let i={config:this.config,adapter:this.adapter},s=t;return Object.values(p.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(s=s.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString()))}),s}buildInputBag(t,r,e){let i={};return t.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,o]=r.stringToNative(s.value);i[a]=String(o)}),e&&e.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,o]=r.stringToNative(s.value);if(i[`primary.${a}`]=String(o),s.input.type==="asset"&&typeof s.input.position=="object"){let c=o;c&&typeof c=="object"&&"identifier"in c&&"amount"in c&&(i[`primary.${a}.token`]=String(c.identifier),i[`primary.${a}.amount`]=String(c.amount))}}),i}};var j=class{constructor(t,r){this.config=t;this.adapters=r;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new x,this.cache=new _(t.cache?.type)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,r,e){let i=this.cache.get(lt.WarpExecutable(t,r||"",e))||[];return H(i)}async createExecutable(t,r,e,i={}){let s=S(t,r);if(!s)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,e),o=m(a.name,this.adapters),c=new P(this.config,o),l=await c.apply(t,i),u=S(l,r),{action:f,index:h}=B(l),v=this.getStringTypedInputs(f,e),A=await this.getResolvedInputs(a.name,f,v,c),g=await this.getModifiedInputs(A),W=[],y=[];h===r-1&&(W=A,y=g);let E=y.find(I=>I.input.position==="receiver"||I.input.position==="destination")?.value,N=this.getDestinationFromAction(u),T=E?this.serializer.stringToNative(E)[1]:N;if(T&&(T=c.applyInputs(T,y,this.serializer,g)),!T&&s.type!=="collect")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let ut=this.getPreparedArgs(u,y);ut=ut.map(I=>c.applyInputs(I,y,this.serializer,g));let Jt=y.find(I=>I.input.position==="value")?.value||null,Qt="value"in u?u.value:null,Kt=Jt?.split(p.ArgParamsSeparator)[1]||Qt||"0",_t=c.applyInputs(Kt,y,this.serializer,g),Xt=BigInt(_t),Zt=y.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),Yt=[...("transfers"in u?u.transfers:[])||[],...Zt||[]].map(I=>{let nr=c.applyInputs(I,y,this.serializer,g);return this.serializer.stringToNative(nr)[1]}),tr=y.find(I=>I.input.position==="data")?.value,rr="data"in u?u.data||"":null,Et=tr||rr||null,er=Et?c.applyInputs(Et,y,this.serializer,g):null,Rt={warp:l,chain:a,action:r,destination:T,args:ut,value:Xt,transfers:Yt,data:er,resolvedInputs:y};return this.cache.set(lt.WarpExecutable(this.config.env,l.meta?.hash||"",r),Rt.resolvedInputs,bt.OneWeek),Rt}async getChainInfoForWarp(t,r){if(t.chain)return m(t.chain,this.adapters).chainInfo;if(r){let i=await this.tryGetChainFromInputs(t,r);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,r){let e=t.inputs||[];return r.map((i,s)=>{let a=e[s];return!a||i.includes(p.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,r,e,i){let s=r.inputs||[],a=await Promise.all(e.map(c=>this.preprocessInput(t,c))),o=(c,l)=>{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===p.Source.UserWallet){let u=w(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 a[l]||null};return s.map((c,l)=>{let u=o(c,l),f=c.default!==void 0?i?i.applyInputs(String(c.default),[],this.serializer):String(c.default):void 0;return{input:c,value:u||(f!==void 0?this.serializer.nativeToString(c.type,f):null)}})}async getModifiedInputs(t){let r=[];for(let e=0;e<t.length;e++){let i=t[e];if(i.input.modifier?.startsWith("scale:")){let[,s]=i.input.modifier.split(":");if(isNaN(Number(s))){let a=Number(t.find(l=>l.input.name===s)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${s}`);let o=i.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let c=q(o,+a);r.push({...i,value:`${i.input.type}:${c}`})}else{let a=i.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=q(a,+s);r.push({...i,value:`${i.input.type}:${o}`})}}else if(i.input.modifier?.startsWith(p.Transform.Prefix)){let s=i.input.modifier.substring(p.Transform.Prefix.length),a=this.config.transform?.runner;if(!a||typeof a.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let o=this.buildInputContext(t,e,i),c=await a.run(s,o);if(c==null)r.push(i);else{let l=this.serializer.nativeToString(i.input.type,c);r.push({...i,value:l})}}else r.push(i)}return r}buildInputContext(t,r,e){let i={};for(let s=0;s<r;s++){let a=t[s];if(!a.value)continue;let o=a.input.as||a.input.name,[,c]=this.serializer.stringToNative(a.value);if(i[o]=c,a.input.type==="asset"&&typeof c=="object"&&c!==null){let l=c;"identifier"in l&&"amount"in l&&(i[`${o}.token`]=String(l.identifier),i[`${o}.amount`]=String(l.amount),i[`${o}.identifier`]=String(l.identifier))}}if(e&&e.value){let s=e.input.as||e.input.name,[,a]=this.serializer.stringToNative(e.value);if(i[s]=a,e.input.type==="asset"&&typeof a=="object"&&a!==null){let o=a;"identifier"in o&&"amount"in o&&(i[`${s}.token`]=String(o.identifier),i[`${s}.amount`]=String(o.amount),i[`${s}.identifier`]=String(o.identifier))}}return i}async preprocessInput(t,r){try{let[e,i]=st(r),s=m(t,this.adapters);if(e==="asset"){let[a,o,c]=i.split(p.ArgCompositeSeparator);if(c)return r;let l=await s.dataLoader.getAsset(a);if(!l)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof l.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=q(o,l.decimals);return It({...l,amount:u})}else return r}catch(e){throw C.warn("WarpFactory: Preprocess input failed",e),e}}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,r){let e="args"in t?t.args||[]:[],i=[];return r.forEach(({input:s,value:a})=>{if(!(!a||!s.position)){if(typeof s.position=="object"){if(s.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${s.name}" has type "${s.type}"`);if(!s.position.token?.startsWith("arg:")||!s.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${s.name}"`);let[o,c]=this.serializer.stringToNative(a),l=c;if(!l||typeof l!="object"||!("identifier"in l)||!("amount"in l))throw new Error(`WarpFactory: Invalid asset value for input "${s.name}"`);let u=Number(s.position.token.split(":")[1])-1,f=Number(s.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",l.identifier)}),i.push({index:f,value:this.serializer.nativeToString("uint256",l.amount)})}else if(s.position.startsWith("arg:")){let o=Number(s.position.split(":")[1])-1;i.push({index:o,value:a})}}}),i.forEach(({index:s,value:a})=>{for(;e.length<=s;)e.push(void 0);e[s]=a}),e.filter(s=>s!==void 0)}async tryGetChainFromInputs(t,r){let e=t.actions.find(c=>c.inputs?.some(l=>l.position==="chain"));if(!e)return null;let i=e.inputs?.findIndex(c=>c.position==="chain");if(i===-1||i===void 0)return null;let s=r[i];if(!s)throw new Error("Chain input not found");let a=this.serializer.stringToNative(s)[1];return m(a,this.adapters).chainInfo}};var X=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.handlers=e,this.factory=new j(t,r)}async execute(t,r,e={}){let i=[],s=null,a=[],o=[],{action:c,index:l}=B(t);for(let u=1;u<=t.actions.length;u++){let f=S(t,u);if(!it(f,t))continue;let{tx:h,chain:v,immediateExecution:A,executable:g}=await this.executeAction(t,u,r,e);h&&i.push(h),v&&(s=v),A&&a.push(A),g&&u===l+1&&g.resolvedInputs&&(o=H(g.resolvedInputs))}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let u=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(u))}return{txs:i,chain:s,immediateExecutions:a,resolvedInputs:o}}async executeAction(t,r,e,i={}){let s=S(t,r);if(s.type==="link")return await this.callHandler(async()=>{let l=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(l):dt.open(l,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null};let a=await this.factory.createExecutable(t,r,e,i);if(s.type==="collect"){let l=await this.executeCollect(a);return l.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):l.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(l.values)}),{tx:null,chain:null,immediateExecution:null,executable:a})}let o=m(a.chain.name,this.adapters);if(s.type==="query"){let l=await o.executor.executeQuery(a);return l.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:l,tx:null})):this.handlers?.onError?.({message:JSON.stringify(l.values)}),{tx:null,chain:a.chain,immediateExecution:l,executable:a}}return{tx:await o.executor.createTransaction(a),chain:a.chain,immediateExecution:null,executable:a}}async evaluateOutput(t,r){if(r.length===0||t.actions.length===0||!this.handlers)return;let e=await this.factory.getChainInfoForWarp(t),i=m(e.name,this.adapters),s=(await Promise.all(t.actions.map(async(a,o)=>{if(!it(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let c=r[o],l=o+1;if(!c){let f=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,l),h={status:"error",warp:t,action:l,user:w(this.config,e.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:f};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${l} failed: Transaction not found`})),h}let u=await i.output.getActionExecution(t,l,c);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:l,chain:e,execution:u,tx:c})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values)})),u}))).filter(a=>a!==null);if(s.every(a=>a.status==="success")){let a=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(a))}else await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(s.map(a=>a.values))}`}))}async executeCollect(t,r){let e=w(this.config,t.chain.name),i=S(t.warp,t.action),s=this.factory.getSerializer(),a=G(t.resolvedInputs,s);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,e,a,r);let{values:o,output:c}=await ot(t.warp,a,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,e,"unhandled",o,c)}async doHttpRequest(t,r,e,i,s){let a=new P(this.config,m(t.chain.name,this.adapters)),o=new Headers;if(o.set("Content-Type","application/json"),o.set("Accept","application/json"),this.handlers?.onSignRequest){if(!e)throw new Error(`No wallet configured for chain ${t.chain.name}`);let{message:f,nonce:h,expiresAt:v}=await pt(e,`${t.chain.name}-adapter`),A=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:f,chain:t.chain}));if(A){let g=ct(e,A,h,v);Object.entries(g).forEach(([W,y])=>o.set(W,y))}}r.headers&&Object.entries(r.headers).forEach(([f,h])=>{let v=a.applyInputs(h,t.resolvedInputs,this.factory.getSerializer());o.set(f,v)});let c=r.method||"GET",l=c==="GET"?void 0:JSON.stringify({...i,...s}),u=a.applyInputs(r.url,t.resolvedInputs,this.factory.getSerializer());C.debug("WarpExecutor: Executing HTTP collect",{url:u,method:c,headers:o,body:l});try{let f=await fetch(u,{method:c,headers:o,body:l});C.debug("Collect response status",{status:f.status});let h=await f.json();C.debug("Collect response content",{content:h});let{values:v,output:A}=await ot(t.warp,h,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,w(this.config,t.chain.name),f.ok?"success":"error",v,A,h)}catch(f){C.error("WarpActionExecutor: Error executing collect",f);let h=H(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(e=>e.input.position==="receiver"||e.input.position==="destination")?.value||t.destination}buildCollectResult(t,r,e,i,s,a){let o=xt(this.config,this.adapters,t.warp,t.action,s),c=H(t.resolvedInputs);return{status:e,warp:t.warp,action:t.action,user:r||w(this.config,t.chain.name),txHash:null,tx:null,next:o,values:i,output:a?{...s,_DATA:a}:s,messages:vt(t.warp,s,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:c}}async callHandler(t){if(t)return await t()}};var Z=class{constructor(t){this.config=t}async search(t,r,e){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}`,...e},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...r})});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 Y=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!D(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),a=(await Promise.all(i)).filter(l=>l.match),o=a.length>0,c=a.map(l=>({url:l.url,warp:l.warp}));return{match:o,output:c}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(p.HttpProtocolPrefix)?D(t):b(t);if(!i)return e;try{let{type:s,identifierBase:a}=i,o=null,c=null,l=null,u=m(i.chain,this.adapters),f=t.startsWith(p.HttpProtocolPrefix)?Wt(t):yt(i.identifier);if(s==="hash"){o=await u.builder().createFromTransactionHash(a,r);let g=await u.registry.getInfoByHash(a,r);c=g.registryInfo,l=g.brand}else if(s==="alias"){let g=await u.registry.getInfoByAlias(a,r);c=g.registryInfo,l=g.brand,g.registryInfo&&(o=await u.builder().createFromTransactionHash(g.registryInfo.hash,r))}if(o&&o.meta&&(_r(o,u.chainInfo.name,c,i.identifier),o.meta.query=f),!o)return e;let h=o.chain||u.chainInfo.name,v=m(h,this.adapters),A=await new P(this.config,v).apply(o);return{match:!0,url:t,warp:A,chain:h,registryInfo:c,brand:l}}catch(s){return C.error("Error detecting warp link",s),e}}},_r=(n,t,r,e)=>{n.meta&&(n.meta.identifier=r?.alias?at(t,"alias",r.alias):at(t,"hash",r?.hash??e))};var Tt=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}getAdapters(){return this.adapters}addAdapter(t){return this.adapters.push(t),this}createExecutor(t){return new X(this.config,this.adapters,t)}async detectWarp(t,r){return new Y(this.config,this.adapters).detect(t,r)}async executeWarp(t,r,e,i={}){let s=typeof t=="object",a=!s&&t.startsWith("http")&&t.endsWith(".json"),o=s?t:null;if(!o&&a){let A=await fetch(t);if(!A.ok)throw new Error("WarpClient: executeWarp - invalid url");o=await A.json()}if(o||(o=(await this.detectWarp(t,i.cache)).warp),!o)throw new Error("Warp not found");let c=this.createExecutor(e),{txs:l,chain:u,immediateExecutions:f,resolvedInputs:h}=await c.execute(o,r,{queries:i.queries});return{txs:l,chain:u,immediateExecutions:f,evaluateOutput:async A=>{await c.evaluateOutput(o,A)},resolvedInputs:h}}async createInscriptionTransaction(t,r){return await m(t,this.adapters).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return m(t,this.adapters).builder().createFromTransaction(r,e)}async createFromTransactionHash(t,r){let e=b(t);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return m(e.chain,this.adapters).builder().createFromTransactionHash(t,r)}async signMessage(t,r){if(!w(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return m(t,this.adapters).wallet.signMessage(r)}async getActions(t,r,e=!1){let i=this.getDataLoader(t);return(await Promise.all(r.map(async a=>i.getAction(a,e)))).filter(a=>a!==null)}getExplorer(t){return m(t,this.adapters).explorer}getOutput(t){return m(t,this.adapters).output}async getRegistry(t){let r=m(t,this.adapters).registry;return await r.init(),r}getDataLoader(t){return m(t,this.adapters).dataLoader}getWallet(t){return m(t,this.adapters).wallet}get factory(){return new j(this.config,this.adapters)}get index(){return new Z(this.config)}get linkBuilder(){return new F(this.config,this.adapters)}createBuilder(t){return m(t,this.adapters).builder()}createAbiBuilder(t){return m(t,this.adapters).abiBuilder()}createBrandBuilder(t){return m(t,this.adapters).brandBuilder()}createSerializer(t){return m(t,this.adapters).serializer}resolveText(t){return z(t,this.config)}};var Pt=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,r){this.typeHandlers.set(t,r)}registerTypeAlias(t,r){this.typeAliases.set(t,r)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let r=this.typeAliases.get(t);return r?this.getHandler(r):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let r=this.typeAliases.get(t);return r?this.resolveType(r):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,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,evaluateOutputCommon,extractCollectOutput,extractIdentifierInfoFromUrl,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractResolvedInputValues,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,hasInputPrefix,hex,isEqualWarpIdentifier,isWarpActionAutoExecute,isWarpI18nText,mergeNestedPayload,option,parseOutputOutIndex,parseSignedMessage,replacePlaceholders,resolveWarpText,safeWindow,setCryptoProvider,shiftBigintBy,splitInput,string,struct,testCryptoAvailability,toInputPayloadValue,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateSignedMessage,vector});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var kt=(p=>(p.Multiversx="multiversx",p.Vibechain="vibechain",p.Sui="sui",p.Ethereum="ethereum",p.Base="base",p.Arbitrum="arbitrum",p.Somnia="somnia",p.Fastset="fastset",p))(kt||{}),c={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"}},d={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"},ft=typeof window<"u"?window:{open:()=>{}};var F={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},$={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${F.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${F.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",c.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 mr=(n,t)=>{let r=n.alerts?.[t];if(!r)return null;let e=c.Alerts.TriggerEventPrefix+c.ArgParamsSeparator;if(!r.trigger.startsWith(e))return null;let i=r.trigger.replace(e,"");return i||null};var yr=(n,t)=>typeof n.logo=="string"?n.logo:n.logo[t?.scheme??"light"];var rt=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let r=new Uint8Array(t);return window.crypto.getRandomValues(r),r}},et=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let r=await import("crypto");return new Uint8Array(r.randomBytes(t))}catch(r){throw new Error(`Node.js crypto not available: ${r instanceof Error?r.message:"Unknown error"}`)}}},V=null;function gt(){if(V)return V;if(typeof window<"u"&&window.crypto)return V=new rt,V;if(typeof process<"u"&&process.versions?.node)return V=new et,V;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Ar(n){V=n}async function ht(n,t){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(t||gt()).getRandomBytes(n)}function qt(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(n.length*2);for(let r=0;r<n.length;r++){let e=n[r];t[r*2]=(e>>>4).toString(16),t[r*2+1]=(e&15).toString(16)}return t.join("")}function xr(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 mt(n,t){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let r=await ht(n/2,t);return qt(r)}async function Cr(){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 ht(16),n.randomBytes=!0}catch{}return n}function Ir(){return gt()}var br=n=>Object.values(n.vars||{}).filter(t=>t.startsWith(`${c.Vars.Env}:`)).map(t=>{let r=t.replace(`${c.Vars.Env}:`,"").trim(),[e,i]=r.split(c.ArgCompositeSeparator);return{key:e,description:i||null}});var m=(n,t)=>{let r=t.find(e=>e.chainInfo.name.toLowerCase()===n.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${n}`);return r},z=n=>{if(n==="warp")return`warp:${F.Warp}`;if(n==="brand")return`brand:${F.Brand}`;if(n==="abi")return`abi:${F.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},b=(n,t)=>n?.actions[t-1],N=n=>{if(n.actions.length===0)throw new Error(`Warp has no primary action: ${n.meta?.identifier}`);let t=n.actions.find(s=>s.primary===!0);if(t)return{action:t,index:n.actions.indexOf(t)};let r=["transfer","contract","query","collect"],e=n.actions.find(s=>r.includes(s.type));return e?{action:e,index:n.actions.indexOf(e)}:{action:n.actions[0],index:0}},nt=(n,t)=>{if(n.auto===!1)return!1;if(n.type==="link"){if(n.auto===!0)return!0;let{action:r}=N(t);return n===r}return!0},M=(n,t)=>{let r=n.toString(),[e,i=""]=r.split("."),s=Math.abs(t);if(t>0)return BigInt(e+i.padEnd(s,"0"));if(t<0){let a=e+i;if(s>=a.length)return 0n;let o=a.slice(0,-s)||"0";return BigInt(o)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},Wt=(n,t=100)=>{if(!n)return"";let r=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r},O=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||"");var Rr={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"},G=(n,t)=>{let r=t?.preferences?.locale||"en";if(typeof n=="string")return n;if(typeof n=="object"&&n!==null){if(r in n)return n[r];if("en"in n)return n.en;let e=Object.keys(n);if(e.length>0)return n[e[0]]}return""},Br=n=>typeof n=="object"&&n!==null&&Object.keys(n).length>0,$r=n=>n;var J=n=>n.startsWith(c.IdentifierAliasMarker)?n.replace(c.IdentifierAliasMarker,""):n,Or=(n,t)=>!n||!t?!1:J(n)===J(t),it=(n,t,r)=>{let e=J(r);return t===c.IdentifierType.Alias?c.IdentifierAliasMarker+n+c.IdentifierParamSeparator+e:n+c.IdentifierParamSeparator+t+c.IdentifierParamSeparator+e},T=n=>{let t=decodeURIComponent(n).trim(),r=J(t),e=r.split("?")[0],i=yt(e);if(e.length===64&&/^[a-fA-F0-9]+$/.test(e))return{chain:c.IdentifierChainDefault,type:c.IdentifierType.Hash,identifier:r,identifierBase:e};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[s,a,o]=i;if(a===c.IdentifierType.Alias||a===c.IdentifierType.Hash){let p=r.includes("?")?o+r.substring(r.indexOf("?")):o;return{chain:s,type:a,identifier:p,identifierBase:o}}}if(i.length===2){let[s,a]=i;if(s===c.IdentifierType.Alias||s===c.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a;return{chain:c.IdentifierChainDefault,type:s,identifier:o,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==c.IdentifierType.Alias&&s!==c.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a,p=zt(a,s)?c.IdentifierType.Hash:c.IdentifierType.Alias;return{chain:s,type:p,identifier:o,identifierBase:a}}}return{chain:c.IdentifierChainDefault,type:c.IdentifierType.Alias,identifier:r,identifierBase:e}},D=n=>{let t=new URL(n),e=t.searchParams.get(c.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let i=decodeURIComponent(e);return T(i)},zt=(n,t)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,Mt=n=>{let t=c.IdentifierParamSeparator,r=n.indexOf(t);return r!==-1?{separator:t,index:r}:null},yt=n=>{let t=Mt(n);if(!t)return[n];let{separator:r,index:e}=t,i=n.substring(0,e),s=n.substring(e+r.length),a=yt(s);return[i,...a]},vt=n=>{try{let t=new URL(n),r=new URLSearchParams(t.search);return r.delete(c.IdentifierParamName),r.toString()||null}catch{return null}},At=n=>{let t=n.indexOf("?");if(t===-1||t===n.length-1)return null;let r=n.substring(t+1);return r.length>0?r:null};var at=n=>{let[t,...r]=n.split(/:(.*)/,2);return[t,r[0]||""]},Hr=n=>{let t=new Set(Object.values(d));if(!n.includes(c.ArgParamsSeparator))return!1;let r=at(n)[0];return t.has(r)};var xt=(n,t,r)=>{let e=Object.entries(n.messages||{}).map(([i,s])=>{let a=G(s,r);return[i,O(a,t)]});return Object.fromEntries(e)};import Gt from"qr-code-styling";var H=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!D(t):!1}build(t,r,e){let i=this.config.clientUrl||$.DefaultClientUrl(this.config.env),s=m(t,this.adapters),a=r===c.IdentifierType.Alias?e:r+c.IdentifierParamSeparator+e,o=s.chainInfo.name+c.IdentifierParamSeparator+a,p=encodeURIComponent(o);return $.SuperClientUrls.includes(i)?`${i}/${p}`:`${i}?${c.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(t){let r=T(t);if(!r)return null;let e=m(r.chain,this.adapters);return e?this.build(e.chainInfo.name,r.type,r.identifierBase):null}generateQrCode(t,r,e,i=512,s="white",a="black",o="#23F7DD"){let p=m(t,this.adapters),l=this.build(p.chainInfo.name,r,e);return new Gt({type:"svg",width:i,height:i,data:String(l),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},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(o)}" 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 Jt="https://",Ct=(n,t,r,e,i)=>{let s=r.actions?.[e-1]?.next||r.next||null;if(!s)return null;if(s.startsWith(Jt))return[{identifier:null,url:s}];let[a,o]=s.split("?");if(!o){let h=O(a,{...r.vars,...i});return[{identifier:h,url:st(t,h,n)}]}let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let h=O(o,{...r.vars,...i}),v=h?`${a}?${h}`:a;return[{identifier:v,url:st(t,v,n)}]}let l=p[0];if(!l)return[];let u=l.match(/{{([^[]+)\[\]/),f=u?u[1]:null;if(!f||i[f]===void 0)return[];let g=Array.isArray(i[f])?i[f]:[i[f]];if(g.length===0)return[];let W=p.filter(h=>h.includes(`{{${f}[]`)).map(h=>{let v=h.match(/\[\](\.[^}]+)?}}/),A=v&&v[1]||"";return{placeholder:h,field:A?A.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return g.map(h=>{let v=o;for(let{regex:P,field:B}of W){let w=B?Qt(h,B):h;if(w==null)return null;v=v.replace(P,w)}if(v.includes("{{")||v.includes("}}"))return null;let A=v?`${a}?${v}`:a;return{identifier:A,url:st(t,A,n)}}).filter(h=>h!==null)},st=(n,t,r)=>{let[e,i]=t.split("?"),s=T(e)||{chain:c.IdentifierChainDefault,type:"alias",identifier:e,identifierBase:e},a=m(s.chain,n);if(!a)throw new Error(`Adapter not found for chain ${s.chain}`);let o=new H(r,n).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return o;let p=new URL(o);return new URLSearchParams(i).forEach((l,u)=>p.searchParams.set(u,l)),p.toString().replace(/\/\?/,"?")},Qt=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);function Kt(n,t,r){return n.startsWith(c.Position.Payload)?n.slice(c.Position.Payload.length).split(".").reduceRight((e,i,s,a)=>({[i]:s===a.length-1?{[t]:r}:e}),{}):{[t]:r}}function It(n,t){if(!n)return{...t};if(!t)return{...n};let r={...n};return Object.keys(t).forEach(e=>{r[e]&&typeof r[e]=="object"&&typeof t[e]=="object"?r[e]=It(r[e],t[e]):r[e]=t[e]}),r}function _t(n,t){if(!n.value)return null;let r=t.stringToNative(n.value)[1];if(n.input.type==="biguint")return r.toString();if(n.input.type==="asset"){let{identifier:e,amount:i}=r;return{identifier:e,amount:i.toString()}}else return r}function L(n){return n.map(t=>t.value).filter(t=>t!=null&&t!=="")}function Q(n,t){let r={};return n.forEach(e=>{let i=e.input.as||e.input.name,s=_t(e,t);if(e.input.position&&typeof e.input.position=="string"&&e.input.position.startsWith(c.Position.Payload)){let a=Kt(e.input.position,i,s);r=It(r,a)}else r[i]=s}),r}var ee=(n,t,r,e)=>{let i=n.preferences?.providers?.[t];return i?.[r]?typeof i[r]=="string"?{url:i[r]}:i[r]:{url:e}};var U=class U{static debug(...t){U.isTestEnv||console.debug(...t)}static info(...t){U.isTestEnv||console.info(...t)}static warn(...t){U.isTestEnv||console.warn(...t)}static error(...t){U.isTestEnv||console.error(...t)}};U.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var I=U;var ot=async(n,t,r,e,i,s)=>{let a=[],o=[],p={};for(let[u,f]of Object.entries(n.output||{})){if(f.startsWith(c.Transform.Prefix))continue;let g=tr(f);if(g!==null&&g!==r){p[u]=null;continue}let[W,...y]=f.split("."),h=(v,A)=>A.reduce((P,B)=>P&&P[B]!==void 0?P[B]:null,v);if(W==="out"||W.startsWith("out[")){let v=y.length===0?t?.data||t:h(t,y);a.push(String(v)),o.push(v),p[u]=v}else p[u]=f}let l=Q(e,i);return{values:{string:a,native:o,mapped:l},output:await Xt(n,p,r,e,i,s)}},Xt=async(n,t,r,e,i,s)=>{if(!n.output)return t;let a={...t};return a=Zt(a,n,r,e,i),a=await Yt(n,a,s.transform?.runner||null),a},Zt=(n,t,r,e,i)=>{let s={...n},a=b(t,r)?.inputs||[];for(let[o,p]of Object.entries(s))if(typeof p=="string"&&p.startsWith("in.")){let l=p.split(".")[1],u=a.findIndex(g=>g.as===l||g.name===l),f=u!==-1?e[u]?.value:null;s[o]=f?i.stringToNative(f)[1]:null}return s},Yt=async(n,t,r)=>{if(!n.output)return t;let e={...t},i=Object.entries(n.output).filter(([,s])=>s.startsWith(c.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(c.Transform.Prefix.length)}));if(i.length>0&&(!r||typeof r.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:s,code:a}of i)try{e[s]=await r.run(a,e)}catch(o){I.error(`Transform error for output '${s}':`,o),e[s]=null}return e},tr=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)};async function rr(n,t,r,e=5){let i=await mt(64,r),s=new Date(Date.now()+e*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:i,expiresAt:s,purpose:t}),nonce:i,expiresAt:s}}async function pt(n,t,r,e){let i=e||`prove-wallet-ownership for app "${t}"`;return rr(n,i,r,5)}function ct(n,t,r,e){return{"X-Signer-Wallet":n,"X-Signer-Signature":t,"X-Signer-Nonce":r,"X-Signer-ExpiresAt":e}}async function de(n,t,r,e){let{message:i,nonce:s,expiresAt:a}=await pt(n,r,e),o=await t(i);return ct(n,o,s,a)}function fe(n){let t=new Date(n).getTime();return Date.now()<t}function ge(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 er=n=>n?typeof n=="string"?n:n.address:null,S=(n,t)=>er(n.user?.wallets?.[t]||null),nr=n=>n?typeof n=="string"?n:n.privateKey:null,ir=n=>n?typeof n=="string"?n:n.mnemonic:null,me=(n,t)=>nr(n.user?.wallets?.[t]||null)?.trim()||null,We=(n,t)=>ir(n.user?.wallets?.[t]||null)?.trim()||null;var x=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,r){if(t===d.Tuple&&Array.isArray(r)){if(r.length===0)return t+c.ArgParamsSeparator;if(r.every(e=>typeof e=="string"&&e.includes(c.ArgParamsSeparator))){let e=r.map(a=>this.getTypeAndValue(a)),i=e.map(([a])=>a),s=e.map(([,a])=>a);return`${t}(${i.join(c.ArgCompositeSeparator)})${c.ArgParamsSeparator}${s.join(c.ArgListSeparator)}`}return t+c.ArgParamsSeparator+r.join(c.ArgListSeparator)}if(t===d.Struct&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let e=r;if(!e._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=e._name,s=Object.keys(e).filter(o=>o!=="_name");if(s.length===0)return`${t}(${i})${c.ArgParamsSeparator}`;let a=s.map(o=>{let[p,l]=this.getTypeAndValue(e[o]);return`(${o}${c.ArgParamsSeparator}${p})${l}`});return`${t}(${i})${c.ArgParamsSeparator}${a.join(c.ArgListSeparator)}`}if(t===d.Vector&&Array.isArray(r)){if(r.length===0)return`${t}${c.ArgParamsSeparator}`;if(r.every(e=>typeof e=="string"&&e.includes(c.ArgParamsSeparator))){let e=r[0],i=e.indexOf(c.ArgParamsSeparator),s=e.substring(0,i),a=r.map(p=>{let l=p.indexOf(c.ArgParamsSeparator),u=p.substring(l+1);return s.startsWith(d.Tuple)?u.replace(c.ArgListSeparator,c.ArgCompositeSeparator):u}),o=s.startsWith(d.Struct)?c.ArgStructSeparator:c.ArgListSeparator;return t+c.ArgParamsSeparator+s+c.ArgParamsSeparator+a.join(o)}return t+c.ArgParamsSeparator+r.join(c.ArgListSeparator)}if(t===d.Asset&&typeof r=="object"&&r&&"identifier"in r&&"amount"in r)return"decimals"in r?d.Asset+c.ArgParamsSeparator+r.identifier+c.ArgCompositeSeparator+String(r.amount)+c.ArgCompositeSeparator+String(r.decimals):d.Asset+c.ArgParamsSeparator+r.identifier+c.ArgCompositeSeparator+String(r.amount);if(this.typeRegistry){let e=this.typeRegistry.getHandler(t);if(e)return e.nativeToString(r);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,r)}return t+c.ArgParamsSeparator+(r?.toString()??"")}stringToNative(t){let r=t.split(c.ArgParamsSeparator),e=r[0],i=r.slice(1).join(c.ArgParamsSeparator);if(e==="null")return[e,null];if(e===d.Option){let[s,a]=i.split(c.ArgParamsSeparator);return[d.Option+c.ArgParamsSeparator+s,a||null]}if(e===d.Vector){let s=i.indexOf(c.ArgParamsSeparator),a=i.substring(0,s),o=i.substring(s+1),p=a.startsWith(d.Struct)?c.ArgStructSeparator:c.ArgListSeparator,u=(o?o.split(p):[]).map(f=>this.stringToNative(a+c.ArgParamsSeparator+f)[1]);return[d.Vector+c.ArgParamsSeparator+a,u]}else if(e.startsWith(d.Tuple)){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(c.ArgCompositeSeparator),o=i.split(c.ArgCompositeSeparator).map((p,l)=>this.stringToNative(`${s[l]}${c.IdentifierParamSeparator}${p}`)[1]);return[e,o]}else if(e.startsWith(d.Struct)){let s=e.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let o={_name:s[1]};return i&&i.split(c.ArgListSeparator).forEach(p=>{let l=p.match(new RegExp(`^\\(([^${c.ArgParamsSeparator}]+)${c.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(l){let[,u,f,g]=l;o[u]=this.stringToNative(`${f}${c.IdentifierParamSeparator}${g}`)[1]}}),[e,o]}else{if(e===d.String)return[e,i];if(e===d.Uint8||e===d.Uint16||e===d.Uint32)return[e,Number(i)];if(e===d.Uint64||e===d.Uint128||e===d.Uint256||e===d.Biguint)return[e,BigInt(i||0)];if(e===d.Bool)return[e,i==="true"];if(e===d.Address)return[e,i];if(e===d.Hex)return[e,i];if(e===d.Asset){let[s,a]=i.split(c.ArgCompositeSeparator),o={identifier:s,amount:BigInt(a)};return[e,o]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(e);if(s){let o=s.stringToNative(i);return[e,o]}let a=this.typeRegistry.resolveType(e);if(a!==e){let[o,p]=this.stringToNative(`${a}:${i}`);return[e,p]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(c.ArgParamsSeparator)){let[r,e]=t.split(c.ArgParamsSeparator);return[r,e]}return typeof t=="number"?[d.Uint32,t]:typeof t=="bigint"?[d.Uint64,t]:typeof t=="boolean"?[d.Bool,t]:[typeof t,t]}};var Ie=n=>new x().nativeToString(d.String,n),Se=n=>new x().nativeToString(d.Uint8,n),we=n=>new x().nativeToString(d.Uint16,n),be=n=>new x().nativeToString(d.Uint32,n),Te=n=>new x().nativeToString(d.Uint64,n),Pe=n=>new x().nativeToString(d.Biguint,n),Ee=n=>new x().nativeToString(d.Bool,n),Re=n=>new x().nativeToString(d.Address,n),St=n=>new x().nativeToString(d.Asset,n),Be=n=>new x().nativeToString(d.Hex,n),$e=(n,t)=>{if(t===null)return d.Option+c.ArgParamsSeparator;let r=n(t),e=r.indexOf(c.ArgParamsSeparator),i=r.substring(0,e),s=r.substring(e+1);return d.Option+c.ArgParamsSeparator+i+c.ArgParamsSeparator+s},Ve=(...n)=>new x().nativeToString(d.Tuple,n),Ne=n=>new x().nativeToString(d.Struct,n),Oe=n=>new x().nativeToString(d.Vector,n);import ar from"ajv";var wt=class{constructor(t){this.pendingBrand={protocol:z("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),e}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,r){if(!t)throw new Error(`Warp: ${r}`)}ensureWarpText(t,r){if(!t)throw new Error(`Warp: ${r}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.schema?.brand||$.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),s=new ar,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};import sr from"ajv";var K=class{constructor(t){this.config=t;this.config=t}async validate(t){let r=[];return r.push(...this.validatePrimaryAction(t)),r.push(...this.validateMaxOneValuePosition(t)),r.push(...this.validateVariableNamesAndResultNamesUppercase(t)),r.push(...this.validateAbiIsSetIfApplicable(t)),r.push(...await this.validateSchema(t)),{valid:r.length===0,errors:r}}validatePrimaryAction(t){try{let{action:r}=N(t);return r?[]:["Primary action is required"]}catch(r){return[r instanceof Error?r.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(e=>e.inputs?e.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&r.push(`${s} name '${a}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.output,"Output"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(a=>a.type==="contract"),e=t.actions.some(a=>a.type==="query");if(!r&&!e)return[];let i=t.actions.some(a=>a.abi),s=Object.values(t.output||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.output&&!i&&s?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||$.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),s=new sr({strict:!1}),a=s.compile(i);return a(t)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var bt=class{constructor(t){this.config=t;this.pendingWarp={protocol:z("warp"),chain:"",name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.validate(e),e}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}async build(){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"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,r=100){return Wt(t,r)}ensure(t,r){if(!t)throw new Error(r)}ensureWarpText(t,r){if(!t)throw new Error(r);if(typeof t=="object"&&!t.en)throw new Error(r)}async validate(t){let e=await new K(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
2
- `))}};var k=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let r=localStorage.getItem(this.getKey(t));if(!r)return null;let e=JSON.parse(r,pr);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(t)),null):e.value}catch{return null}}set(t,r,e){let i={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,or))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r?.startsWith(this.prefix)&&localStorage.removeItem(r)}}},Tt=new x,or=(n,t)=>typeof t=="bigint"?Tt.nativeToString("biguint",t):t,pr=(n,t)=>typeof t=="string"&&t.startsWith(d.Biguint+":")?Tt.stringToNative(t)[1]:t;var E=class E{get(t){let r=E.cache.get(t);return r?Date.now()>r.expiresAt?(E.cache.delete(t),null):r.value:null}set(t,r,e){let i=Date.now()+e*1e3;E.cache.set(t,{value:r,expiresAt:i})}forget(t){E.cache.delete(t)}clear(){E.cache.clear()}};E.cache=new Map;var q=E;var Pt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},lt={Warp:(n,t)=>`warp:${n}:${t}`,WarpAbi:(n,t)=>`warp-abi:${n}:${t}`,WarpExecutable:(n,t,r)=>`warp-exec:${n}:${t}:${r}`,RegistryInfo:(n,t)=>`registry-info:${n}:${t}`,Brand:(n,t)=>`brand:${n}:${t}`,Asset:(n,t,r)=>`asset:${n}:${t}:${r}`},_=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new k:t==="memory"?new q:typeof window<"u"&&window.localStorage?new k:new q}set(t,r,e){this.strategy.set(t,r,e)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var R=class{constructor(t,r){this.config=t;this.adapter=r}async apply(t,r,e={}){let i=this.applyVars(t,r,e);return await this.applyGlobals(t,i)}async applyGlobals(t,r){let e={...r};return e.actions=await Promise.all(e.actions.map(async i=>await this.applyActionGlobals(i))),e=await this.applyRootGlobals(e,t),e}applyVars(t,r,e={}){if(!r?.vars)return r;let i=S(t,this.adapter.chainInfo.name),s=JSON.stringify(r),a=(o,p)=>{s=s.replace(new RegExp(`{{${o.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(r.vars).forEach(([o,p])=>{if(typeof p!="string")a(o,p);else if(p.startsWith(c.Vars.Query+c.ArgParamsSeparator)){let l=p.slice(c.Vars.Query.length+1),[u,f]=l.split(c.ArgCompositeSeparator),g=t.currentUrl?new URLSearchParams(t.currentUrl.split("?")[1]).get(u):null,y=e.queries?.[u]||null||g;y&&a(o,y)}else if(p.startsWith(c.Vars.Env+c.ArgParamsSeparator)){let l=p.slice(c.Vars.Env.length+1),[u,f]=l.split(c.ArgCompositeSeparator),W={...t.vars,...e.envs}?.[u];W&&a(o,W)}else p===c.Source.UserWallet&&i?a(o,i):a(o,p)}),JSON.parse(s)}async applyRootGlobals(t,r){let e=JSON.stringify(t),i={config:r,adapter:this.adapter};return Object.values(c.Globals).forEach(s=>{let a=s.Accessor(i);a!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),a.toString()))}),JSON.parse(e)}async applyActionGlobals(t){let r=JSON.stringify(t),e={config:this.config,adapter:this.adapter};return Object.values(c.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}applyInputs(t,r,e,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let s=this.applyGlobalsToText(t),a=this.buildInputBag(r,e,i);return O(s,a)}applyGlobalsToText(t){if(!Object.values(c.Globals).map(a=>a.Placeholder).some(a=>t.includes(`{{${a}}}`)))return t;let i={config:this.config,adapter:this.adapter},s=t;return Object.values(c.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(s=s.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString()))}),s}buildInputBag(t,r,e){let i={};return t.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,o]=r.stringToNative(s.value);i[a]=String(o)}),e&&e.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,o]=r.stringToNative(s.value);if(i[`primary.${a}`]=String(o),s.input.type==="asset"&&typeof s.input.position=="object"){let p=o;p&&typeof p=="object"&&"identifier"in p&&"amount"in p&&(i[`primary.${a}.token`]=String(p.identifier),i[`primary.${a}.amount`]=String(p.amount))}}),i}};var j=class{constructor(t,r){this.config=t;this.adapters=r;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new x,this.cache=new _(t.cache?.type)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,r,e){let i=this.cache.get(lt.WarpExecutable(t,r||"",e))||[];return L(i)}async createExecutable(t,r,e,i={}){let s=b(t,r);if(!s)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,e),o=m(a.name,this.adapters),p=new R(this.config,o),l=await p.apply(this.config,t,i),u=b(l,r),{action:f,index:g}=N(l),W=this.getStringTypedInputs(f,e),y=await this.getResolvedInputs(a.name,f,W,p),h=await this.getModifiedInputs(y),v=[],A=[];g===r-1&&(v=y,A=h);let P=A.find(C=>C.input.position==="receiver"||C.input.position==="destination")?.value,B=this.getDestinationFromAction(u),w=P?this.serializer.stringToNative(P)[1]:B;if(w&&(w=p.applyInputs(w,A,this.serializer,h)),!w&&s.type!=="collect")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let tt=this.getPreparedArgs(u,A);tt=tt.map(C=>p.applyInputs(C,A,this.serializer,h));let Bt=A.find(C=>C.input.position==="value")?.value||null,$t="value"in u?u.value:null,Vt=Bt?.split(c.ArgParamsSeparator)[1]||$t||"0",Nt=p.applyInputs(Vt,A,this.serializer,h),Ot=BigInt(Nt),Ut=A.filter(C=>C.input.position==="transfer"&&C.value).map(C=>C.value),Ft=[...("transfers"in u?u.transfers:[])||[],...Ut||[]].map(C=>{let Dt=p.applyInputs(C,A,this.serializer,h);return this.serializer.stringToNative(Dt)[1]}),Ht=A.find(C=>C.input.position==="data")?.value,Lt="data"in u?u.data||"":null,ut=Ht||Lt||null,jt=ut?p.applyInputs(ut,A,this.serializer,h):null,dt={warp:l,chain:a,action:r,destination:w,args:tt,value:Ot,transfers:Ft,data:jt,resolvedInputs:A};return this.cache.set(lt.WarpExecutable(this.config.env,l.meta?.hash||"",r),dt.resolvedInputs,Pt.OneWeek),dt}async getChainInfoForWarp(t,r){if(t.chain)return m(t.chain,this.adapters).chainInfo;if(r){let i=await this.tryGetChainFromInputs(t,r);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,r){let e=t.inputs||[];return r.map((i,s)=>{let a=e[s];return!a||i.includes(c.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,r,e,i){let s=r.inputs||[],a=await Promise.all(e.map(p=>this.preprocessInput(t,p))),o=(p,l)=>{if(p.source==="query"){let u=this.url.searchParams.get(p.name);return u?this.serializer.nativeToString(p.type,u):null}else if(p.source===c.Source.UserWallet){let u=S(this.config,t);return u?this.serializer.nativeToString("address",u):null}else if(p.source==="hidden"){if(p.default===void 0)return null;let u=i?i.applyInputs(String(p.default),[],this.serializer):String(p.default);return this.serializer.nativeToString(p.type,u)}else return a[l]||null};return s.map((p,l)=>{let u=o(p,l),f=p.default!==void 0?i?i.applyInputs(String(p.default),[],this.serializer):String(p.default):void 0;return{input:p,value:u||(f!==void 0?this.serializer.nativeToString(p.type,f):null)}})}async getModifiedInputs(t){let r=[];for(let e=0;e<t.length;e++){let i=t[e];if(i.input.modifier?.startsWith("scale:")){let[,s]=i.input.modifier.split(":");if(isNaN(Number(s))){let a=Number(t.find(l=>l.input.name===s)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${s}`);let o=i.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let p=M(o,+a);r.push({...i,value:`${i.input.type}:${p}`})}else{let a=i.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=M(a,+s);r.push({...i,value:`${i.input.type}:${o}`})}}else if(i.input.modifier?.startsWith(c.Transform.Prefix)){let s=i.input.modifier.substring(c.Transform.Prefix.length),a=this.config.transform?.runner;if(!a||typeof a.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let o=this.buildInputContext(t,e,i),p=await a.run(s,o);if(p==null)r.push(i);else{let l=this.serializer.nativeToString(i.input.type,p);r.push({...i,value:l})}}else r.push(i)}return r}buildInputContext(t,r,e){let i={};for(let s=0;s<r;s++){let a=t[s];if(!a.value)continue;let o=a.input.as||a.input.name,[,p]=this.serializer.stringToNative(a.value);if(i[o]=p,a.input.type==="asset"&&typeof p=="object"&&p!==null){let l=p;"identifier"in l&&"amount"in l&&(i[`${o}.token`]=String(l.identifier),i[`${o}.amount`]=String(l.amount),i[`${o}.identifier`]=String(l.identifier))}}if(e&&e.value){let s=e.input.as||e.input.name,[,a]=this.serializer.stringToNative(e.value);if(i[s]=a,e.input.type==="asset"&&typeof a=="object"&&a!==null){let o=a;"identifier"in o&&"amount"in o&&(i[`${s}.token`]=String(o.identifier),i[`${s}.amount`]=String(o.amount),i[`${s}.identifier`]=String(o.identifier))}}return i}async preprocessInput(t,r){try{let[e,i]=at(r),s=m(t,this.adapters);if(e==="asset"){let[a,o,p]=i.split(c.ArgCompositeSeparator);if(p)return r;let l=await s.dataLoader.getAsset(a);if(!l)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof l.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=M(o,l.decimals);return St({...l,amount:u})}else return r}catch(e){throw I.warn("WarpFactory: Preprocess input failed",e),e}}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,r){let e="args"in t?t.args||[]:[],i=[];return r.forEach(({input:s,value:a})=>{if(!(!a||!s.position)){if(typeof s.position=="object"){if(s.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${s.name}" has type "${s.type}"`);if(!s.position.token?.startsWith("arg:")||!s.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${s.name}"`);let[o,p]=this.serializer.stringToNative(a),l=p;if(!l||typeof l!="object"||!("identifier"in l)||!("amount"in l))throw new Error(`WarpFactory: Invalid asset value for input "${s.name}"`);let u=Number(s.position.token.split(":")[1])-1,f=Number(s.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",l.identifier)}),i.push({index:f,value:this.serializer.nativeToString("uint256",l.amount)})}else if(s.position.startsWith("arg:")){let o=Number(s.position.split(":")[1])-1;i.push({index:o,value:a})}}}),i.forEach(({index:s,value:a})=>{for(;e.length<=s;)e.push(void 0);e[s]=a}),e.filter(s=>s!==void 0)}async tryGetChainFromInputs(t,r){let e=t.actions.find(p=>p.inputs?.some(l=>l.position==="chain"));if(!e)return null;let i=e.inputs?.findIndex(p=>p.position==="chain");if(i===-1||i===void 0)return null;let s=r[i];if(!s)throw new Error("Chain input not found");let a=this.serializer.stringToNative(s)[1];return m(a,this.adapters).chainInfo}};var X=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.handlers=e,this.factory=new j(t,r)}async execute(t,r,e={}){let i=[],s=null,a=[],o=[],{action:p,index:l}=N(t);for(let u=1;u<=t.actions.length;u++){let f=b(t,u);if(!nt(f,t))continue;let{tx:g,chain:W,immediateExecution:y,executable:h}=await this.executeAction(t,u,r,e);g&&i.push(g),W&&(s=W),y&&a.push(y),h&&u===l+1&&h.resolvedInputs&&(o=L(h.resolvedInputs))}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let u=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(u))}return{txs:i,chain:s,immediateExecutions:a,resolvedInputs:o}}async executeAction(t,r,e,i={}){let s=b(t,r);if(s.type==="link")return await this.callHandler(async()=>{let l=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(l):ft.open(l,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null};let a=await this.factory.createExecutable(t,r,e,i);if(s.type==="collect"){let l=await this.executeCollect(a);return l.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):l.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(l.values)}),{tx:null,chain:null,immediateExecution:null,executable:a})}let o=m(a.chain.name,this.adapters);if(s.type==="query"){let l=await o.executor.executeQuery(a);return l.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:l,tx:null})):this.handlers?.onError?.({message:JSON.stringify(l.values)}),{tx:null,chain:a.chain,immediateExecution:l,executable:a}}return{tx:await o.executor.createTransaction(a),chain:a.chain,immediateExecution:null,executable:a}}async evaluateOutput(t,r){if(r.length===0||t.actions.length===0||!this.handlers)return;let e=await this.factory.getChainInfoForWarp(t),i=m(e.name,this.adapters),s=(await Promise.all(t.actions.map(async(a,o)=>{if(!nt(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let p=r[o],l=o+1;if(!p){let f=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,l),g={status:"error",warp:t,action:l,user:S(this.config,e.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:f};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${l} failed: Transaction not found`})),g}let u=await i.output.getActionExecution(t,l,p);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:l,chain:e,execution:u,tx:p})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values)})),u}))).filter(a=>a!==null);if(s.every(a=>a.status==="success")){let a=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(a))}else await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(s.map(a=>a.values))}`}))}async executeCollect(t,r){let e=S(this.config,t.chain.name),i=b(t.warp,t.action),s=this.factory.getSerializer(),a=Q(t.resolvedInputs,s);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,e,a,r);let{values:o,output:p}=await ot(t.warp,a,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,e,"unhandled",o,p)}async doHttpRequest(t,r,e,i,s){let a=new R(this.config,m(t.chain.name,this.adapters)),o=new Headers;if(o.set("Content-Type","application/json"),o.set("Accept","application/json"),this.handlers?.onSignRequest){if(!e)throw new Error(`No wallet configured for chain ${t.chain.name}`);let{message:f,nonce:g,expiresAt:W}=await pt(e,`${t.chain.name}-adapter`),y=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:f,chain:t.chain}));if(y){let h=ct(e,y,g,W);Object.entries(h).forEach(([v,A])=>o.set(v,A))}}r.headers&&Object.entries(r.headers).forEach(([f,g])=>{let W=a.applyInputs(g,t.resolvedInputs,this.factory.getSerializer());o.set(f,W)});let p=r.method||"GET",l=p==="GET"?void 0:JSON.stringify({...i,...s}),u=a.applyInputs(r.url,t.resolvedInputs,this.factory.getSerializer());I.debug("WarpExecutor: Executing HTTP collect",{url:u,method:p,headers:o,body:l});try{let f=await fetch(u,{method:p,headers:o,body:l});I.debug("Collect response status",{status:f.status});let g=await f.json();I.debug("Collect response content",{content:g});let{values:W,output:y}=await ot(t.warp,g,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),f.ok?"success":"error",W,y,g)}catch(f){I.error("WarpActionExecutor: Error executing collect",f);let g=L(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:g}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(e=>e.input.position==="receiver"||e.input.position==="destination")?.value||t.destination}buildCollectResult(t,r,e,i,s,a){let o=Ct(this.config,this.adapters,t.warp,t.action,s),p=L(t.resolvedInputs);return{status:e,warp:t.warp,action:t.action,user:r||S(this.config,t.chain.name),txHash:null,tx:null,next:o,values:i,output:a?{...s,_DATA:a}:s,messages:xt(t.warp,s,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:p}}async callHandler(t){if(t)return await t()}};var Z=class{constructor(t){this.config=t}async search(t,r,e){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}`,...e},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...r})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw I.error("WarpIndex: Error searching for warps: ",i),i}}};var Y=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(c.HttpProtocolPrefix)?!!D(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),a=(await Promise.all(i)).filter(l=>l.match),o=a.length>0,p=a.map(l=>({url:l.url,warp:l.warp}));return{match:o,output:p}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(c.HttpProtocolPrefix)?D(t):T(t);if(!i)return e;try{let{type:s,identifierBase:a}=i,o=null,p=null,l=null,u=m(i.chain,this.adapters),f=t.startsWith(c.HttpProtocolPrefix)?vt(t):At(i.identifier);if(s==="hash"){o=await u.builder().createFromTransactionHash(a,r);let W=await u.registry.getInfoByHash(a,r);p=W.registryInfo,l=W.brand}else if(s==="alias"){let W=await u.registry.getInfoByAlias(a,r);p=W.registryInfo,l=W.brand,W.registryInfo&&(o=await u.builder().createFromTransactionHash(W.registryInfo.hash,r))}o&&o.meta&&(cr(o,u.chainInfo.name,p,i.identifier),o.meta.query=f);let g=o?await new R(this.config,u).apply(this.config,o):null;return g?{match:!0,url:t,warp:g,chain:u.chainInfo.name,registryInfo:p,brand:l}:e}catch(s){return I.error("Error detecting warp link",s),e}}},cr=(n,t,r,e)=>{n.meta&&(n.meta.identifier=r?.alias?it(t,"alias",r.alias):it(t,"hash",r?.hash??e))};var Et=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}getAdapters(){return this.adapters}addAdapter(t){return this.adapters.push(t),this}createExecutor(t){return new X(this.config,this.adapters,t)}async detectWarp(t,r){return new Y(this.config,this.adapters).detect(t,r)}async executeWarp(t,r,e,i={}){let s=typeof t=="object",a=!s&&t.startsWith("http")&&t.endsWith(".json"),o=s?t:null;if(!o&&a){let y=await fetch(t);if(!y.ok)throw new Error("WarpClient: executeWarp - invalid url");o=await y.json()}if(o||(o=(await this.detectWarp(t,i.cache)).warp),!o)throw new Error("Warp not found");let p=this.createExecutor(e),{txs:l,chain:u,immediateExecutions:f,resolvedInputs:g}=await p.execute(o,r,{queries:i.queries});return{txs:l,chain:u,immediateExecutions:f,evaluateOutput:async y=>{await p.evaluateOutput(o,y)},resolvedInputs:g}}async createInscriptionTransaction(t,r){return await m(t,this.adapters).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return m(t,this.adapters).builder().createFromTransaction(r,e)}async createFromTransactionHash(t,r){let e=T(t);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return m(e.chain,this.adapters).builder().createFromTransactionHash(t,r)}async signMessage(t,r){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return m(t,this.adapters).wallet.signMessage(r)}async getActions(t,r,e=!1){let i=this.getDataLoader(t);return(await Promise.all(r.map(async a=>i.getAction(a,e)))).filter(a=>a!==null)}getExplorer(t){return m(t,this.adapters).explorer}getOutput(t){return m(t,this.adapters).output}async getRegistry(t){let r=m(t,this.adapters).registry;return await r.init(),r}getDataLoader(t){return m(t,this.adapters).dataLoader}getWallet(t){return m(t,this.adapters).wallet}get factory(){return new j(this.config,this.adapters)}get index(){return new Z(this.config)}get linkBuilder(){return new H(this.config,this.adapters)}createBuilder(t){return m(t,this.adapters).builder()}createAbiBuilder(t){return m(t,this.adapters).abiBuilder()}createBrandBuilder(t){return m(t,this.adapters).brandBuilder()}createSerializer(t){return m(t,this.adapters).serializer}resolveText(t){return G(t,this.config)}};var Rt=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,r){this.typeHandlers.set(t,r)}registerTypeAlias(t,r){this.typeAliases.set(t,r)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let r=this.typeAliases.get(t);return r?this.getHandler(r):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let r=this.typeAliases.get(t);return r?this.resolveType(r):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};export{rt as BrowserCryptoProvider,Pt as CacheTtl,et as NodeCryptoProvider,Rr as WARP_LANGUAGES,wt as WarpBrandBuilder,bt as WarpBuilder,_ as WarpCache,lt as WarpCacheKey,kt as WarpChainName,Et as WarpClient,$ as WarpConfig,c as WarpConstants,X as WarpExecutor,j as WarpFactory,Z as WarpIndex,d as WarpInputTypes,R as WarpInterpolator,H as WarpLinkBuilder,Y as WarpLinkDetecter,I as WarpLogger,F as WarpProtocolVersions,x as WarpSerializer,Rt as WarpTypeRegistry,K as WarpValidator,Re as address,xt as applyOutputToMessages,St as asset,Pe as biguint,Ee as bool,Q as buildMappedOutput,Kt as buildNestedPayload,xr as bytesToBase64,qt as bytesToHex,J as cleanWarpIdentifier,ct as createAuthHeaders,pt as createAuthMessage,Ir as createCryptoProvider,de as createHttpAuthHeaders,rr as createSignableMessage,$r as createWarpI18nText,it as createWarpIdentifier,Xt as evaluateOutputCommon,ot as extractCollectOutput,D as extractIdentifierInfoFromUrl,At as extractQueryStringFromIdentifier,vt as extractQueryStringFromUrl,L as extractResolvedInputValues,br as extractWarpSecrets,m as findWarpAdapterForChain,gt as getCryptoProvider,mr as getEventNameFromWarp,z as getLatestProtocolIdentifier,Ct as getNextInfo,ee as getProviderConfig,ht as getRandomBytes,mt as getRandomHex,b as getWarpActionByIndex,yr as getWarpBrandLogoUrl,T as getWarpInfoFromIdentifier,N as getWarpPrimaryAction,er as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,ir as getWarpWalletMnemonic,We as getWarpWalletMnemonicFromConfig,nr as getWarpWalletPrivateKey,me as getWarpWalletPrivateKeyFromConfig,Hr as hasInputPrefix,Be as hex,Or as isEqualWarpIdentifier,nt as isWarpActionAutoExecute,Br as isWarpI18nText,It as mergeNestedPayload,$e as option,tr as parseOutputOutIndex,ge as parseSignedMessage,O as replacePlaceholders,G as resolveWarpText,ft as safeWindow,Ar as setCryptoProvider,M as shiftBigintBy,at as splitInput,Ie as string,Ne as struct,Cr as testCryptoAvailability,_t as toInputPayloadValue,Wt as toPreviewText,Ve as tuple,we as uint16,be as uint32,Te as uint64,Se as uint8,fe as validateSignedMessage,Oe as vector};
1
+ var kt=(c=>(c.Multiversx="multiversx",c.Vibechain="vibechain",c.Sui="sui",c.Ethereum="ethereum",c.Base="base",c.Arbitrum="arbitrum",c.Somnia="somnia",c.Fastset="fastset",c))(kt||{}),p={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"}},d={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"},ft=typeof window<"u"?window:{open:()=>{}};var F={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},$={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${F.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${F.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",p.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 mr=(n,t)=>{let r=n.alerts?.[t];if(!r)return null;let e=p.Alerts.TriggerEventPrefix+p.ArgParamsSeparator;if(!r.trigger.startsWith(e))return null;let i=r.trigger.replace(e,"");return i||null};var yr=(n,t)=>typeof n.logo=="string"?n.logo:n.logo[t?.scheme??"light"];var rt=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let r=new Uint8Array(t);return window.crypto.getRandomValues(r),r}},et=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let r=await import("crypto");return new Uint8Array(r.randomBytes(t))}catch(r){throw new Error(`Node.js crypto not available: ${r instanceof Error?r.message:"Unknown error"}`)}}},V=null;function gt(){if(V)return V;if(typeof window<"u"&&window.crypto)return V=new rt,V;if(typeof process<"u"&&process.versions?.node)return V=new et,V;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Ar(n){V=n}async function ht(n,t){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(t||gt()).getRandomBytes(n)}function qt(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(n.length*2);for(let r=0;r<n.length;r++){let e=n[r];t[r*2]=(e>>>4).toString(16),t[r*2+1]=(e&15).toString(16)}return t.join("")}function xr(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 mt(n,t){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let r=await ht(n/2,t);return qt(r)}async function Cr(){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 ht(16),n.randomBytes=!0}catch{}return n}function Ir(){return gt()}var br=n=>Object.values(n.vars||{}).filter(t=>t.startsWith(`${p.Vars.Env}:`)).map(t=>{let r=t.replace(`${p.Vars.Env}:`,"").trim(),[e,i]=r.split(p.ArgCompositeSeparator);return{key:e,description:i||null}});var m=(n,t)=>{let r=t.find(e=>e.chainInfo.name.toLowerCase()===n.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${n}`);return r},z=n=>{if(n==="warp")return`warp:${F.Warp}`;if(n==="brand")return`brand:${F.Brand}`;if(n==="abi")return`abi:${F.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},b=(n,t)=>n?.actions[t-1],N=n=>{if(n.actions.length===0)throw new Error(`Warp has no primary action: ${n.meta?.identifier}`);let t=n.actions.find(s=>s.primary===!0);if(t)return{action:t,index:n.actions.indexOf(t)};let r=["transfer","contract","query","collect"],e=n.actions.find(s=>r.includes(s.type));return e?{action:e,index:n.actions.indexOf(e)}:{action:n.actions[0],index:0}},nt=(n,t)=>{if(n.auto===!1)return!1;if(n.type==="link"){if(n.auto===!0)return!0;let{action:r}=N(t);return n===r}return!0},M=(n,t)=>{let r=n.toString(),[e,i=""]=r.split("."),s=Math.abs(t);if(t>0)return BigInt(e+i.padEnd(s,"0"));if(t<0){let a=e+i;if(s>=a.length)return 0n;let o=a.slice(0,-s)||"0";return BigInt(o)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},Wt=(n,t=100)=>{if(!n)return"";let r=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r},O=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||"");var Rr={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"},G=(n,t)=>{let r=t?.preferences?.locale||"en";if(typeof n=="string")return n;if(typeof n=="object"&&n!==null){if(r in n)return n[r];if("en"in n)return n.en;let e=Object.keys(n);if(e.length>0)return n[e[0]]}return""},Br=n=>typeof n=="object"&&n!==null&&Object.keys(n).length>0,$r=n=>n;var J=n=>n.startsWith(p.IdentifierAliasMarker)?n.replace(p.IdentifierAliasMarker,""):n,Or=(n,t)=>!n||!t?!1:J(n)===J(t),it=(n,t,r)=>{let e=J(r);return t===p.IdentifierType.Alias?p.IdentifierAliasMarker+n+p.IdentifierParamSeparator+e:n+p.IdentifierParamSeparator+t+p.IdentifierParamSeparator+e},T=n=>{let t=decodeURIComponent(n).trim(),r=J(t),e=r.split("?")[0],i=yt(e);if(e.length===64&&/^[a-fA-F0-9]+$/.test(e))return{chain:p.IdentifierChainDefault,type:p.IdentifierType.Hash,identifier:r,identifierBase:e};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[s,a,o]=i;if(a===p.IdentifierType.Alias||a===p.IdentifierType.Hash){let c=r.includes("?")?o+r.substring(r.indexOf("?")):o;return{chain:s,type:a,identifier:c,identifierBase:o}}}if(i.length===2){let[s,a]=i;if(s===p.IdentifierType.Alias||s===p.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a;return{chain:p.IdentifierChainDefault,type:s,identifier:o,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==p.IdentifierType.Alias&&s!==p.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a,c=zt(a,s)?p.IdentifierType.Hash:p.IdentifierType.Alias;return{chain:s,type:c,identifier:o,identifierBase:a}}}return{chain:p.IdentifierChainDefault,type:p.IdentifierType.Alias,identifier:r,identifierBase:e}},D=n=>{let t=new URL(n),e=t.searchParams.get(p.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let i=decodeURIComponent(e);return T(i)},zt=(n,t)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,Mt=n=>{let t=p.IdentifierParamSeparator,r=n.indexOf(t);return r!==-1?{separator:t,index:r}:null},yt=n=>{let t=Mt(n);if(!t)return[n];let{separator:r,index:e}=t,i=n.substring(0,e),s=n.substring(e+r.length),a=yt(s);return[i,...a]},vt=n=>{try{let t=new URL(n),r=new URLSearchParams(t.search);return r.delete(p.IdentifierParamName),r.toString()||null}catch{return null}},At=n=>{let t=n.indexOf("?");if(t===-1||t===n.length-1)return null;let r=n.substring(t+1);return r.length>0?r:null};var at=n=>{let[t,...r]=n.split(/:(.*)/,2);return[t,r[0]||""]},Hr=n=>{let t=new Set(Object.values(d));if(!n.includes(p.ArgParamsSeparator))return!1;let r=at(n)[0];return t.has(r)};var xt=(n,t,r)=>{let e=Object.entries(n.messages||{}).map(([i,s])=>{let a=G(s,r);return[i,O(a,t)]});return Object.fromEntries(e)};import Gt from"qr-code-styling";var H=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!D(t):!1}build(t,r,e){let i=this.config.clientUrl||$.DefaultClientUrl(this.config.env),s=m(t,this.adapters),a=r===p.IdentifierType.Alias?e:r+p.IdentifierParamSeparator+e,o=s.chainInfo.name+p.IdentifierParamSeparator+a,c=encodeURIComponent(o);return $.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${p.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let r=T(t);if(!r)return null;let e=m(r.chain,this.adapters);return e?this.build(e.chainInfo.name,r.type,r.identifierBase):null}generateQrCode(t,r,e,i=512,s="white",a="black",o="#23F7DD"){let c=m(t,this.adapters),l=this.build(c.chainInfo.name,r,e);return new Gt({type:"svg",width:i,height:i,data:String(l),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},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(o)}" 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 Jt="https://",Ct=(n,t,r,e,i)=>{let s=r.actions?.[e-1]?.next||r.next||null;if(!s)return null;if(s.startsWith(Jt))return[{identifier:null,url:s}];let[a,o]=s.split("?");if(!o){let g=O(a,{...r.vars,...i});return[{identifier:g,url:st(t,g,n)}]}let c=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let g=O(o,{...r.vars,...i}),W=g?`${a}?${g}`:a;return[{identifier:W,url:st(t,W,n)}]}let l=c[0];if(!l)return[];let u=l.match(/{{([^[]+)\[\]/),f=u?u[1]:null;if(!f||i[f]===void 0)return[];let h=Array.isArray(i[f])?i[f]:[i[f]];if(h.length===0)return[];let v=c.filter(g=>g.includes(`{{${f}[]`)).map(g=>{let W=g.match(/\[\](\.[^}]+)?}}/),y=W&&W[1]||"";return{placeholder:g,field:y?y.slice(1):"",regex:new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(g=>{let W=o;for(let{regex:P,field:B}of v){let S=B?Qt(g,B):g;if(S==null)return null;W=W.replace(P,S)}if(W.includes("{{")||W.includes("}}"))return null;let y=W?`${a}?${W}`:a;return{identifier:y,url:st(t,y,n)}}).filter(g=>g!==null)},st=(n,t,r)=>{let[e,i]=t.split("?"),s=T(e)||{chain:p.IdentifierChainDefault,type:"alias",identifier:e,identifierBase:e},a=m(s.chain,n);if(!a)throw new Error(`Adapter not found for chain ${s.chain}`);let o=new H(r,n).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return o;let c=new URL(o);return new URLSearchParams(i).forEach((l,u)=>c.searchParams.set(u,l)),c.toString().replace(/\/\?/,"?")},Qt=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);function Kt(n,t,r){return n.startsWith(p.Position.Payload)?n.slice(p.Position.Payload.length).split(".").reduceRight((e,i,s,a)=>({[i]:s===a.length-1?{[t]:r}:e}),{}):{[t]:r}}function It(n,t){if(!n)return{...t};if(!t)return{...n};let r={...n};return Object.keys(t).forEach(e=>{r[e]&&typeof r[e]=="object"&&typeof t[e]=="object"?r[e]=It(r[e],t[e]):r[e]=t[e]}),r}function _t(n,t){if(!n.value)return null;let r=t.stringToNative(n.value)[1];if(n.input.type==="biguint")return r.toString();if(n.input.type==="asset"){let{identifier:e,amount:i}=r;return{identifier:e,amount:i.toString()}}else return r}function L(n){return n.map(t=>t.value).filter(t=>t!=null&&t!=="")}function Q(n,t){let r={};return n.forEach(e=>{let i=e.input.as||e.input.name,s=_t(e,t);if(e.input.position&&typeof e.input.position=="string"&&e.input.position.startsWith(p.Position.Payload)){let a=Kt(e.input.position,i,s);r=It(r,a)}else r[i]=s}),r}var ee=(n,t,r,e)=>{let i=n.preferences?.providers?.[t];return i?.[r]?typeof i[r]=="string"?{url:i[r]}:i[r]:{url:e}};var U=class U{static debug(...t){U.isTestEnv||console.debug(...t)}static info(...t){U.isTestEnv||console.info(...t)}static warn(...t){U.isTestEnv||console.warn(...t)}static error(...t){U.isTestEnv||console.error(...t)}};U.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var I=U;var ot=async(n,t,r,e,i,s)=>{let a=[],o=[],c={};for(let[u,f]of Object.entries(n.output||{})){if(f.startsWith(p.Transform.Prefix))continue;let h=tr(f);if(h!==null&&h!==r){c[u]=null;continue}let[v,...A]=f.split("."),g=(W,y)=>y.reduce((P,B)=>P&&P[B]!==void 0?P[B]:null,W);if(v==="out"||v.startsWith("out[")){let W=A.length===0?t?.data||t:g(t,A);a.push(String(W)),o.push(W),c[u]=W}else c[u]=f}let l=Q(e,i);return{values:{string:a,native:o,mapped:l},output:await Xt(n,c,r,e,i,s)}},Xt=async(n,t,r,e,i,s)=>{if(!n.output)return t;let a={...t};return a=Zt(a,n,r,e,i),a=await Yt(n,a,s.transform?.runner||null),a},Zt=(n,t,r,e,i)=>{let s={...n},a=b(t,r)?.inputs||[];for(let[o,c]of Object.entries(s))if(typeof c=="string"&&c.startsWith("in.")){let l=c.split(".")[1],u=a.findIndex(h=>h.as===l||h.name===l),f=u!==-1?e[u]?.value:null;s[o]=f?i.stringToNative(f)[1]:null}return s},Yt=async(n,t,r)=>{if(!n.output)return t;let e={...t},i=Object.entries(n.output).filter(([,s])=>s.startsWith(p.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(p.Transform.Prefix.length)}));if(i.length>0&&(!r||typeof r.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:s,code:a}of i)try{e[s]=await r.run(a,e)}catch(o){I.error(`Transform error for output '${s}':`,o),e[s]=null}return e},tr=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)};async function rr(n,t,r,e=5){let i=await mt(64,r),s=new Date(Date.now()+e*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:i,expiresAt:s,purpose:t}),nonce:i,expiresAt:s}}async function pt(n,t,r,e){let i=e||`prove-wallet-ownership for app "${t}"`;return rr(n,i,r,5)}function ct(n,t,r,e){return{"X-Signer-Wallet":n,"X-Signer-Signature":t,"X-Signer-Nonce":r,"X-Signer-ExpiresAt":e}}async function de(n,t,r,e){let{message:i,nonce:s,expiresAt:a}=await pt(n,r,e),o=await t(i);return ct(n,o,s,a)}function fe(n){let t=new Date(n).getTime();return Date.now()<t}function ge(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 er=n=>n?typeof n=="string"?n:n.address:null,w=(n,t)=>er(n.user?.wallets?.[t]||null),nr=n=>n?typeof n=="string"?n:n.privateKey:null,ir=n=>n?typeof n=="string"?n:n.mnemonic:null,me=(n,t)=>nr(n.user?.wallets?.[t]||null)?.trim()||null,We=(n,t)=>ir(n.user?.wallets?.[t]||null)?.trim()||null;var x=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,r){if(t===d.Tuple&&Array.isArray(r)){if(r.length===0)return t+p.ArgParamsSeparator;if(r.every(e=>typeof e=="string"&&e.includes(p.ArgParamsSeparator))){let e=r.map(a=>this.getTypeAndValue(a)),i=e.map(([a])=>a),s=e.map(([,a])=>a);return`${t}(${i.join(p.ArgCompositeSeparator)})${p.ArgParamsSeparator}${s.join(p.ArgListSeparator)}`}return t+p.ArgParamsSeparator+r.join(p.ArgListSeparator)}if(t===d.Struct&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let e=r;if(!e._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=e._name,s=Object.keys(e).filter(o=>o!=="_name");if(s.length===0)return`${t}(${i})${p.ArgParamsSeparator}`;let a=s.map(o=>{let[c,l]=this.getTypeAndValue(e[o]);return`(${o}${p.ArgParamsSeparator}${c})${l}`});return`${t}(${i})${p.ArgParamsSeparator}${a.join(p.ArgListSeparator)}`}if(t===d.Vector&&Array.isArray(r)){if(r.length===0)return`${t}${p.ArgParamsSeparator}`;if(r.every(e=>typeof e=="string"&&e.includes(p.ArgParamsSeparator))){let e=r[0],i=e.indexOf(p.ArgParamsSeparator),s=e.substring(0,i),a=r.map(c=>{let l=c.indexOf(p.ArgParamsSeparator),u=c.substring(l+1);return s.startsWith(d.Tuple)?u.replace(p.ArgListSeparator,p.ArgCompositeSeparator):u}),o=s.startsWith(d.Struct)?p.ArgStructSeparator:p.ArgListSeparator;return t+p.ArgParamsSeparator+s+p.ArgParamsSeparator+a.join(o)}return t+p.ArgParamsSeparator+r.join(p.ArgListSeparator)}if(t===d.Asset&&typeof r=="object"&&r&&"identifier"in r&&"amount"in r)return"decimals"in r?d.Asset+p.ArgParamsSeparator+r.identifier+p.ArgCompositeSeparator+String(r.amount)+p.ArgCompositeSeparator+String(r.decimals):d.Asset+p.ArgParamsSeparator+r.identifier+p.ArgCompositeSeparator+String(r.amount);if(this.typeRegistry){let e=this.typeRegistry.getHandler(t);if(e)return e.nativeToString(r);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,r)}return t+p.ArgParamsSeparator+(r?.toString()??"")}stringToNative(t){let r=t.split(p.ArgParamsSeparator),e=r[0],i=r.slice(1).join(p.ArgParamsSeparator);if(e==="null")return[e,null];if(e===d.Option){let[s,a]=i.split(p.ArgParamsSeparator);return[d.Option+p.ArgParamsSeparator+s,a||null]}if(e===d.Vector){let s=i.indexOf(p.ArgParamsSeparator),a=i.substring(0,s),o=i.substring(s+1),c=a.startsWith(d.Struct)?p.ArgStructSeparator:p.ArgListSeparator,u=(o?o.split(c):[]).map(f=>this.stringToNative(a+p.ArgParamsSeparator+f)[1]);return[d.Vector+p.ArgParamsSeparator+a,u]}else if(e.startsWith(d.Tuple)){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=i.split(p.ArgCompositeSeparator).map((c,l)=>this.stringToNative(`${s[l]}${p.IdentifierParamSeparator}${c}`)[1]);return[e,o]}else if(e.startsWith(d.Struct)){let s=e.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let o={_name:s[1]};return i&&i.split(p.ArgListSeparator).forEach(c=>{let l=c.match(new RegExp(`^\\(([^${p.ArgParamsSeparator}]+)${p.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(l){let[,u,f,h]=l;o[u]=this.stringToNative(`${f}${p.IdentifierParamSeparator}${h}`)[1]}}),[e,o]}else{if(e===d.String)return[e,i];if(e===d.Uint8||e===d.Uint16||e===d.Uint32)return[e,Number(i)];if(e===d.Uint64||e===d.Uint128||e===d.Uint256||e===d.Biguint)return[e,BigInt(i||0)];if(e===d.Bool)return[e,i==="true"];if(e===d.Address)return[e,i];if(e===d.Hex)return[e,i];if(e===d.Asset){let[s,a]=i.split(p.ArgCompositeSeparator),o={identifier:s,amount:BigInt(a)};return[e,o]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(e);if(s){let o=s.stringToNative(i);return[e,o]}let a=this.typeRegistry.resolveType(e);if(a!==e){let[o,c]=this.stringToNative(`${a}:${i}`);return[e,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(p.ArgParamsSeparator)){let[r,e]=t.split(p.ArgParamsSeparator);return[r,e]}return typeof t=="number"?[d.Uint32,t]:typeof t=="bigint"?[d.Uint64,t]:typeof t=="boolean"?[d.Bool,t]:[typeof t,t]}};var Ie=n=>new x().nativeToString(d.String,n),we=n=>new x().nativeToString(d.Uint8,n),Se=n=>new x().nativeToString(d.Uint16,n),be=n=>new x().nativeToString(d.Uint32,n),Te=n=>new x().nativeToString(d.Uint64,n),Pe=n=>new x().nativeToString(d.Biguint,n),Ee=n=>new x().nativeToString(d.Bool,n),Re=n=>new x().nativeToString(d.Address,n),wt=n=>new x().nativeToString(d.Asset,n),Be=n=>new x().nativeToString(d.Hex,n),$e=(n,t)=>{if(t===null)return d.Option+p.ArgParamsSeparator;let r=n(t),e=r.indexOf(p.ArgParamsSeparator),i=r.substring(0,e),s=r.substring(e+1);return d.Option+p.ArgParamsSeparator+i+p.ArgParamsSeparator+s},Ve=(...n)=>new x().nativeToString(d.Tuple,n),Ne=n=>new x().nativeToString(d.Struct,n),Oe=n=>new x().nativeToString(d.Vector,n);import ar from"ajv";var St=class{constructor(t){this.pendingBrand={protocol:z("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),e}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,r){if(!t)throw new Error(`Warp: ${r}`)}ensureWarpText(t,r){if(!t)throw new Error(`Warp: ${r}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.schema?.brand||$.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),s=new ar,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};import sr from"ajv";var K=class{constructor(t){this.config=t;this.config=t}async validate(t){let r=[];return r.push(...this.validatePrimaryAction(t)),r.push(...this.validateMaxOneValuePosition(t)),r.push(...this.validateVariableNamesAndResultNamesUppercase(t)),r.push(...this.validateAbiIsSetIfApplicable(t)),r.push(...await this.validateSchema(t)),{valid:r.length===0,errors:r}}validatePrimaryAction(t){try{let{action:r}=N(t);return r?[]:["Primary action is required"]}catch(r){return[r instanceof Error?r.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(e=>e.inputs?e.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&r.push(`${s} name '${a}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.output,"Output"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(a=>a.type==="contract"),e=t.actions.some(a=>a.type==="query");if(!r&&!e)return[];let i=t.actions.some(a=>a.abi),s=Object.values(t.output||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.output&&!i&&s?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||$.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),s=new sr({strict:!1}),a=s.compile(i);return a(t)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var bt=class{constructor(t){this.config=t;this.pendingWarp={protocol:z("warp"),chain:"",name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.validate(e),e}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}async build(){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"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,r=100){return Wt(t,r)}ensure(t,r){if(!t)throw new Error(r)}ensureWarpText(t,r){if(!t)throw new Error(r);if(typeof t=="object"&&!t.en)throw new Error(r)}async validate(t){let e=await new K(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
2
+ `))}};var k=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let r=localStorage.getItem(this.getKey(t));if(!r)return null;let e=JSON.parse(r,pr);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(t)),null):e.value}catch{return null}}set(t,r,e){let i={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,or))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r?.startsWith(this.prefix)&&localStorage.removeItem(r)}}},Tt=new x,or=(n,t)=>typeof t=="bigint"?Tt.nativeToString("biguint",t):t,pr=(n,t)=>typeof t=="string"&&t.startsWith(d.Biguint+":")?Tt.stringToNative(t)[1]:t;var E=class E{get(t){let r=E.cache.get(t);return r?Date.now()>r.expiresAt?(E.cache.delete(t),null):r.value:null}set(t,r,e){let i=Date.now()+e*1e3;E.cache.set(t,{value:r,expiresAt:i})}forget(t){E.cache.delete(t)}clear(){E.cache.clear()}};E.cache=new Map;var q=E;var Pt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},lt={Warp:(n,t)=>`warp:${n}:${t}`,WarpAbi:(n,t)=>`warp-abi:${n}:${t}`,WarpExecutable:(n,t,r)=>`warp-exec:${n}:${t}:${r}`,RegistryInfo:(n,t)=>`registry-info:${n}:${t}`,Brand:(n,t)=>`brand:${n}:${t}`,Asset:(n,t,r)=>`asset:${n}:${t}:${r}`},_=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new k:t==="memory"?new q:typeof window<"u"&&window.localStorage?new k:new q}set(t,r,e){this.strategy.set(t,r,e)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var R=class{constructor(t,r){this.config=t;this.adapter=r}async apply(t,r={}){let e=this.applyVars(t,r);return await this.applyGlobals(e)}async applyGlobals(t){let r={...t};return r.actions=await Promise.all((r.actions||[]).map(async e=>await this.applyActionGlobals(e))),r=await this.applyRootGlobals(r),r}applyVars(t,r={}){if(!t?.vars)return t;let e=w(this.config,this.adapter.chainInfo.name),i=JSON.stringify(t),s=(a,o)=>{i=i.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([a,o])=>{if(typeof o!="string")s(a,o);else if(o.startsWith(p.Vars.Query+p.ArgParamsSeparator)){let c=o.slice(p.Vars.Query.length+1),[l,u]=c.split(p.ArgCompositeSeparator),f=this.config.currentUrl?new URLSearchParams(this.config.currentUrl.split("?")[1]).get(l):null,v=r.queries?.[l]||null||f;v&&s(a,v)}else if(o.startsWith(p.Vars.Env+p.ArgParamsSeparator)){let c=o.slice(p.Vars.Env.length+1),[l,u]=c.split(p.ArgCompositeSeparator),h={...this.config.vars,...r.envs}?.[l];h&&s(a,h)}else o===p.Source.UserWallet&&e?s(a,e):s(a,o)}),JSON.parse(i)}async applyRootGlobals(t){let r=JSON.stringify(t),e={config:this.config,adapter:this.adapter};return Object.values(p.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}async applyActionGlobals(t){let r=JSON.stringify(t),e={config:this.config,adapter:this.adapter};return Object.values(p.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}applyInputs(t,r,e,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let s=this.applyGlobalsToText(t),a=this.buildInputBag(r,e,i);return O(s,a)}applyGlobalsToText(t){if(!Object.values(p.Globals).map(a=>a.Placeholder).some(a=>t.includes(`{{${a}}}`)))return t;let i={config:this.config,adapter:this.adapter},s=t;return Object.values(p.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(s=s.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString()))}),s}buildInputBag(t,r,e){let i={};return t.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,o]=r.stringToNative(s.value);i[a]=String(o)}),e&&e.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,o]=r.stringToNative(s.value);if(i[`primary.${a}`]=String(o),s.input.type==="asset"&&typeof s.input.position=="object"){let c=o;c&&typeof c=="object"&&"identifier"in c&&"amount"in c&&(i[`primary.${a}.token`]=String(c.identifier),i[`primary.${a}.amount`]=String(c.amount))}}),i}};var j=class{constructor(t,r){this.config=t;this.adapters=r;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new x,this.cache=new _(t.cache?.type)}getSerializer(){return this.serializer}getResolvedInputsFromCache(t,r,e){let i=this.cache.get(lt.WarpExecutable(t,r||"",e))||[];return L(i)}async createExecutable(t,r,e,i={}){let s=b(t,r);if(!s)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,e),o=m(a.name,this.adapters),c=new R(this.config,o),l=await c.apply(t,i),u=b(l,r),{action:f,index:h}=N(l),v=this.getStringTypedInputs(f,e),A=await this.getResolvedInputs(a.name,f,v,c),g=await this.getModifiedInputs(A),W=[],y=[];h===r-1&&(W=A,y=g);let P=y.find(C=>C.input.position==="receiver"||C.input.position==="destination")?.value,B=this.getDestinationFromAction(u),S=P?this.serializer.stringToNative(P)[1]:B;if(S&&(S=c.applyInputs(S,y,this.serializer,g)),!S&&s.type!=="collect")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let tt=this.getPreparedArgs(u,y);tt=tt.map(C=>c.applyInputs(C,y,this.serializer,g));let Bt=y.find(C=>C.input.position==="value")?.value||null,$t="value"in u?u.value:null,Vt=Bt?.split(p.ArgParamsSeparator)[1]||$t||"0",Nt=c.applyInputs(Vt,y,this.serializer,g),Ot=BigInt(Nt),Ut=y.filter(C=>C.input.position==="transfer"&&C.value).map(C=>C.value),Ft=[...("transfers"in u?u.transfers:[])||[],...Ut||[]].map(C=>{let Dt=c.applyInputs(C,y,this.serializer,g);return this.serializer.stringToNative(Dt)[1]}),Ht=y.find(C=>C.input.position==="data")?.value,Lt="data"in u?u.data||"":null,ut=Ht||Lt||null,jt=ut?c.applyInputs(ut,y,this.serializer,g):null,dt={warp:l,chain:a,action:r,destination:S,args:tt,value:Ot,transfers:Ft,data:jt,resolvedInputs:y};return this.cache.set(lt.WarpExecutable(this.config.env,l.meta?.hash||"",r),dt.resolvedInputs,Pt.OneWeek),dt}async getChainInfoForWarp(t,r){if(t.chain)return m(t.chain,this.adapters).chainInfo;if(r){let i=await this.tryGetChainFromInputs(t,r);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,r){let e=t.inputs||[];return r.map((i,s)=>{let a=e[s];return!a||i.includes(p.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,r,e,i){let s=r.inputs||[],a=await Promise.all(e.map(c=>this.preprocessInput(t,c))),o=(c,l)=>{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===p.Source.UserWallet){let u=w(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 a[l]||null};return s.map((c,l)=>{let u=o(c,l),f=c.default!==void 0?i?i.applyInputs(String(c.default),[],this.serializer):String(c.default):void 0;return{input:c,value:u||(f!==void 0?this.serializer.nativeToString(c.type,f):null)}})}async getModifiedInputs(t){let r=[];for(let e=0;e<t.length;e++){let i=t[e];if(i.input.modifier?.startsWith("scale:")){let[,s]=i.input.modifier.split(":");if(isNaN(Number(s))){let a=Number(t.find(l=>l.input.name===s)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${s}`);let o=i.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let c=M(o,+a);r.push({...i,value:`${i.input.type}:${c}`})}else{let a=i.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=M(a,+s);r.push({...i,value:`${i.input.type}:${o}`})}}else if(i.input.modifier?.startsWith(p.Transform.Prefix)){let s=i.input.modifier.substring(p.Transform.Prefix.length),a=this.config.transform?.runner;if(!a||typeof a.run!="function")throw new Error("Transform modifier is defined but no transform runner is configured. Provide a runner via config.transform.runner.");let o=this.buildInputContext(t,e,i),c=await a.run(s,o);if(c==null)r.push(i);else{let l=this.serializer.nativeToString(i.input.type,c);r.push({...i,value:l})}}else r.push(i)}return r}buildInputContext(t,r,e){let i={};for(let s=0;s<r;s++){let a=t[s];if(!a.value)continue;let o=a.input.as||a.input.name,[,c]=this.serializer.stringToNative(a.value);if(i[o]=c,a.input.type==="asset"&&typeof c=="object"&&c!==null){let l=c;"identifier"in l&&"amount"in l&&(i[`${o}.token`]=String(l.identifier),i[`${o}.amount`]=String(l.amount),i[`${o}.identifier`]=String(l.identifier))}}if(e&&e.value){let s=e.input.as||e.input.name,[,a]=this.serializer.stringToNative(e.value);if(i[s]=a,e.input.type==="asset"&&typeof a=="object"&&a!==null){let o=a;"identifier"in o&&"amount"in o&&(i[`${s}.token`]=String(o.identifier),i[`${s}.amount`]=String(o.amount),i[`${s}.identifier`]=String(o.identifier))}}return i}async preprocessInput(t,r){try{let[e,i]=at(r),s=m(t,this.adapters);if(e==="asset"){let[a,o,c]=i.split(p.ArgCompositeSeparator);if(c)return r;let l=await s.dataLoader.getAsset(a);if(!l)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof l.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=M(o,l.decimals);return wt({...l,amount:u})}else return r}catch(e){throw I.warn("WarpFactory: Preprocess input failed",e),e}}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,r){let e="args"in t?t.args||[]:[],i=[];return r.forEach(({input:s,value:a})=>{if(!(!a||!s.position)){if(typeof s.position=="object"){if(s.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${s.name}" has type "${s.type}"`);if(!s.position.token?.startsWith("arg:")||!s.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${s.name}"`);let[o,c]=this.serializer.stringToNative(a),l=c;if(!l||typeof l!="object"||!("identifier"in l)||!("amount"in l))throw new Error(`WarpFactory: Invalid asset value for input "${s.name}"`);let u=Number(s.position.token.split(":")[1])-1,f=Number(s.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",l.identifier)}),i.push({index:f,value:this.serializer.nativeToString("uint256",l.amount)})}else if(s.position.startsWith("arg:")){let o=Number(s.position.split(":")[1])-1;i.push({index:o,value:a})}}}),i.forEach(({index:s,value:a})=>{for(;e.length<=s;)e.push(void 0);e[s]=a}),e.filter(s=>s!==void 0)}async tryGetChainFromInputs(t,r){let e=t.actions.find(c=>c.inputs?.some(l=>l.position==="chain"));if(!e)return null;let i=e.inputs?.findIndex(c=>c.position==="chain");if(i===-1||i===void 0)return null;let s=r[i];if(!s)throw new Error("Chain input not found");let a=this.serializer.stringToNative(s)[1];return m(a,this.adapters).chainInfo}};var X=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.handlers=e,this.factory=new j(t,r)}async execute(t,r,e={}){let i=[],s=null,a=[],o=[],{action:c,index:l}=N(t);for(let u=1;u<=t.actions.length;u++){let f=b(t,u);if(!nt(f,t))continue;let{tx:h,chain:v,immediateExecution:A,executable:g}=await this.executeAction(t,u,r,e);h&&i.push(h),v&&(s=v),A&&a.push(A),g&&u===l+1&&g.resolvedInputs&&(o=L(g.resolvedInputs))}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let u=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(u))}return{txs:i,chain:s,immediateExecutions:a,resolvedInputs:o}}async executeAction(t,r,e,i={}){let s=b(t,r);if(s.type==="link")return await this.callHandler(async()=>{let l=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(l):ft.open(l,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null};let a=await this.factory.createExecutable(t,r,e,i);if(s.type==="collect"){let l=await this.executeCollect(a);return l.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):l.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(l.values)}),{tx:null,chain:null,immediateExecution:null,executable:a})}let o=m(a.chain.name,this.adapters);if(s.type==="query"){let l=await o.executor.executeQuery(a);return l.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:l,tx:null})):this.handlers?.onError?.({message:JSON.stringify(l.values)}),{tx:null,chain:a.chain,immediateExecution:l,executable:a}}return{tx:await o.executor.createTransaction(a),chain:a.chain,immediateExecution:null,executable:a}}async evaluateOutput(t,r){if(r.length===0||t.actions.length===0||!this.handlers)return;let e=await this.factory.getChainInfoForWarp(t),i=m(e.name,this.adapters),s=(await Promise.all(t.actions.map(async(a,o)=>{if(!nt(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let c=r[o],l=o+1;if(!c){let f=this.factory.getResolvedInputsFromCache(this.config.env,t.meta?.hash,l),h={status:"error",warp:t,action:l,user:w(this.config,e.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null,resolvedInputs:f};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${l} failed: Transaction not found`})),h}let u=await i.output.getActionExecution(t,l,c);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:l,chain:e,execution:u,tx:c})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values)})),u}))).filter(a=>a!==null);if(s.every(a=>a.status==="success")){let a=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(a))}else await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(s.map(a=>a.values))}`}))}async executeCollect(t,r){let e=w(this.config,t.chain.name),i=b(t.warp,t.action),s=this.factory.getSerializer(),a=Q(t.resolvedInputs,s);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,e,a,r);let{values:o,output:c}=await ot(t.warp,a,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,e,"unhandled",o,c)}async doHttpRequest(t,r,e,i,s){let a=new R(this.config,m(t.chain.name,this.adapters)),o=new Headers;if(o.set("Content-Type","application/json"),o.set("Accept","application/json"),this.handlers?.onSignRequest){if(!e)throw new Error(`No wallet configured for chain ${t.chain.name}`);let{message:f,nonce:h,expiresAt:v}=await pt(e,`${t.chain.name}-adapter`),A=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:f,chain:t.chain}));if(A){let g=ct(e,A,h,v);Object.entries(g).forEach(([W,y])=>o.set(W,y))}}r.headers&&Object.entries(r.headers).forEach(([f,h])=>{let v=a.applyInputs(h,t.resolvedInputs,this.factory.getSerializer());o.set(f,v)});let c=r.method||"GET",l=c==="GET"?void 0:JSON.stringify({...i,...s}),u=a.applyInputs(r.url,t.resolvedInputs,this.factory.getSerializer());I.debug("WarpExecutor: Executing HTTP collect",{url:u,method:c,headers:o,body:l});try{let f=await fetch(u,{method:c,headers:o,body:l});I.debug("Collect response status",{status:f.status});let h=await f.json();I.debug("Collect response content",{content:h});let{values:v,output:A}=await ot(t.warp,h,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,w(this.config,t.chain.name),f.ok?"success":"error",v,A,h)}catch(f){I.error("WarpActionExecutor: Error executing collect",f);let h=L(t.resolvedInputs);return{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:h}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(e=>e.input.position==="receiver"||e.input.position==="destination")?.value||t.destination}buildCollectResult(t,r,e,i,s,a){let o=Ct(this.config,this.adapters,t.warp,t.action,s),c=L(t.resolvedInputs);return{status:e,warp:t.warp,action:t.action,user:r||w(this.config,t.chain.name),txHash:null,tx:null,next:o,values:i,output:a?{...s,_DATA:a}:s,messages:xt(t.warp,s,this.config),destination:this.getDestinationFromResolvedInputs(t),resolvedInputs:c}}async callHandler(t){if(t)return await t()}};var Z=class{constructor(t){this.config=t}async search(t,r,e){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}`,...e},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...r})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw I.error("WarpIndex: Error searching for warps: ",i),i}}};var Y=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!D(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),a=(await Promise.all(i)).filter(l=>l.match),o=a.length>0,c=a.map(l=>({url:l.url,warp:l.warp}));return{match:o,output:c}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(p.HttpProtocolPrefix)?D(t):T(t);if(!i)return e;try{let{type:s,identifierBase:a}=i,o=null,c=null,l=null,u=m(i.chain,this.adapters),f=t.startsWith(p.HttpProtocolPrefix)?vt(t):At(i.identifier);if(s==="hash"){o=await u.builder().createFromTransactionHash(a,r);let g=await u.registry.getInfoByHash(a,r);c=g.registryInfo,l=g.brand}else if(s==="alias"){let g=await u.registry.getInfoByAlias(a,r);c=g.registryInfo,l=g.brand,g.registryInfo&&(o=await u.builder().createFromTransactionHash(g.registryInfo.hash,r))}if(o&&o.meta&&(cr(o,u.chainInfo.name,c,i.identifier),o.meta.query=f),!o)return e;let h=o.chain||u.chainInfo.name,v=m(h,this.adapters),A=await new R(this.config,v).apply(o);return{match:!0,url:t,warp:A,chain:h,registryInfo:c,brand:l}}catch(s){return I.error("Error detecting warp link",s),e}}},cr=(n,t,r,e)=>{n.meta&&(n.meta.identifier=r?.alias?it(t,"alias",r.alias):it(t,"hash",r?.hash??e))};var Et=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}getAdapters(){return this.adapters}addAdapter(t){return this.adapters.push(t),this}createExecutor(t){return new X(this.config,this.adapters,t)}async detectWarp(t,r){return new Y(this.config,this.adapters).detect(t,r)}async executeWarp(t,r,e,i={}){let s=typeof t=="object",a=!s&&t.startsWith("http")&&t.endsWith(".json"),o=s?t:null;if(!o&&a){let A=await fetch(t);if(!A.ok)throw new Error("WarpClient: executeWarp - invalid url");o=await A.json()}if(o||(o=(await this.detectWarp(t,i.cache)).warp),!o)throw new Error("Warp not found");let c=this.createExecutor(e),{txs:l,chain:u,immediateExecutions:f,resolvedInputs:h}=await c.execute(o,r,{queries:i.queries});return{txs:l,chain:u,immediateExecutions:f,evaluateOutput:async A=>{await c.evaluateOutput(o,A)},resolvedInputs:h}}async createInscriptionTransaction(t,r){return await m(t,this.adapters).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return m(t,this.adapters).builder().createFromTransaction(r,e)}async createFromTransactionHash(t,r){let e=T(t);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return m(e.chain,this.adapters).builder().createFromTransactionHash(t,r)}async signMessage(t,r){if(!w(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return m(t,this.adapters).wallet.signMessage(r)}async getActions(t,r,e=!1){let i=this.getDataLoader(t);return(await Promise.all(r.map(async a=>i.getAction(a,e)))).filter(a=>a!==null)}getExplorer(t){return m(t,this.adapters).explorer}getOutput(t){return m(t,this.adapters).output}async getRegistry(t){let r=m(t,this.adapters).registry;return await r.init(),r}getDataLoader(t){return m(t,this.adapters).dataLoader}getWallet(t){return m(t,this.adapters).wallet}get factory(){return new j(this.config,this.adapters)}get index(){return new Z(this.config)}get linkBuilder(){return new H(this.config,this.adapters)}createBuilder(t){return m(t,this.adapters).builder()}createAbiBuilder(t){return m(t,this.adapters).abiBuilder()}createBrandBuilder(t){return m(t,this.adapters).brandBuilder()}createSerializer(t){return m(t,this.adapters).serializer}resolveText(t){return G(t,this.config)}};var Rt=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,r){this.typeHandlers.set(t,r)}registerTypeAlias(t,r){this.typeAliases.set(t,r)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let r=this.typeAliases.get(t);return r?this.getHandler(r):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let r=this.typeAliases.get(t);return r?this.resolveType(r):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};export{rt as BrowserCryptoProvider,Pt as CacheTtl,et as NodeCryptoProvider,Rr as WARP_LANGUAGES,St as WarpBrandBuilder,bt as WarpBuilder,_ as WarpCache,lt as WarpCacheKey,kt as WarpChainName,Et as WarpClient,$ as WarpConfig,p as WarpConstants,X as WarpExecutor,j as WarpFactory,Z as WarpIndex,d as WarpInputTypes,R as WarpInterpolator,H as WarpLinkBuilder,Y as WarpLinkDetecter,I as WarpLogger,F as WarpProtocolVersions,x as WarpSerializer,Rt as WarpTypeRegistry,K as WarpValidator,Re as address,xt as applyOutputToMessages,wt as asset,Pe as biguint,Ee as bool,Q as buildMappedOutput,Kt as buildNestedPayload,xr as bytesToBase64,qt as bytesToHex,J as cleanWarpIdentifier,ct as createAuthHeaders,pt as createAuthMessage,Ir as createCryptoProvider,de as createHttpAuthHeaders,rr as createSignableMessage,$r as createWarpI18nText,it as createWarpIdentifier,Xt as evaluateOutputCommon,ot as extractCollectOutput,D as extractIdentifierInfoFromUrl,At as extractQueryStringFromIdentifier,vt as extractQueryStringFromUrl,L as extractResolvedInputValues,br as extractWarpSecrets,m as findWarpAdapterForChain,gt as getCryptoProvider,mr as getEventNameFromWarp,z as getLatestProtocolIdentifier,Ct as getNextInfo,ee as getProviderConfig,ht as getRandomBytes,mt as getRandomHex,b as getWarpActionByIndex,yr as getWarpBrandLogoUrl,T as getWarpInfoFromIdentifier,N as getWarpPrimaryAction,er as getWarpWalletAddress,w as getWarpWalletAddressFromConfig,ir as getWarpWalletMnemonic,We as getWarpWalletMnemonicFromConfig,nr as getWarpWalletPrivateKey,me as getWarpWalletPrivateKeyFromConfig,Hr as hasInputPrefix,Be as hex,Or as isEqualWarpIdentifier,nt as isWarpActionAutoExecute,Br as isWarpI18nText,It as mergeNestedPayload,$e as option,tr as parseOutputOutIndex,ge as parseSignedMessage,O as replacePlaceholders,G as resolveWarpText,ft as safeWindow,Ar as setCryptoProvider,M as shiftBigintBy,at as splitInput,Ie as string,Ne as struct,Cr as testCryptoAvailability,_t as toInputPayloadValue,Wt as toPreviewText,Ve as tuple,Se as uint16,be as uint32,Te as uint64,we as uint8,fe as validateSignedMessage,Oe as vector};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "3.0.0-beta.162",
3
+ "version": "3.0.0-beta.164",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",