@vleap/warps 3.0.0-alpha.99 → 3.0.0-beta.153

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.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var Hr=Object.create;var Q=Object.defineProperty;var Vr=Object.getOwnPropertyDescriptor;var Lr=Object.getOwnPropertyNames;var Fr=Object.getPrototypeOf,Or=Object.prototype.hasOwnProperty;var Dr=(n,r)=>{for(var t in r)Q(n,t,{get:r[t],enumerable:!0})},Ar=(n,r,t,e)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of Lr(r))!Or.call(n,a)&&a!==t&&Q(n,a,{get:()=>r[a],enumerable:!(e=Vr(r,a))||e.enumerable});return n};var X=(n,r,t)=>(t=n!=null?Hr(Fr(n)):{},Ar(r||!n||!n.__esModule?Q(t,"default",{value:n,enumerable:!0}):t,n)),jr=n=>Ar(Q({},"__esModule",{value:!0}),n);var ht={};Dr(ht,{BrowserCryptoProvider:()=>K,CacheTtl:()=>yr,NodeCryptoProvider:()=>Z,WarpBrandBuilder:()=>hr,WarpBuilder:()=>mr,WarpCache:()=>j,WarpCacheKey:()=>Wr,WarpChainName:()=>wr,WarpClient:()=>vr,WarpConfig:()=>w,WarpConstants:()=>p,WarpExecutor:()=>q,WarpFactory:()=>N,WarpIndex:()=>G,WarpInputTypes:()=>W,WarpInterpolator:()=>$,WarpLinkBuilder:()=>B,WarpLinkDetecter:()=>z,WarpLogger:()=>v,WarpProtocolVersions:()=>R,WarpSerializer:()=>A,WarpTypeRegistryImpl:()=>M,WarpValidator:()=>F,address:()=>ut,applyResultsToMessages:()=>cr,asset:()=>gr,biguint:()=>ct,boolean:()=>lt,buildNestedPayload:()=>dr,bytesToBase64:()=>qr,bytesToHex:()=>Cr,createAuthHeaders:()=>er,createAuthMessage:()=>tr,createCryptoProvider:()=>zr,createHttpAuthHeaders:()=>tt,createSignableMessage:()=>Sr,evaluateResultsCommon:()=>Pr,extractCollectResults:()=>fr,extractIdentifierInfoFromUrl:()=>U,findWarpAdapterByPrefix:()=>b,findWarpAdapterForChain:()=>g,findWarpExecutableAction:()=>or,getCryptoProvider:()=>ar,getLatestProtocolIdentifier:()=>V,getNextInfo:()=>ur,getProviderConfig:()=>_r,getProviderUrl:()=>Zr,getRandomBytes:()=>ir,getRandomHex:()=>sr,getWarpActionByIndex:()=>P,getWarpInfoFromIdentifier:()=>C,hasInputPrefix:()=>Qr,hex:()=>dt,mergeNestedPayload:()=>rr,parseResultsOutIndex:()=>Tr,parseSignedMessage:()=>nt,replacePlaceholders:()=>_,setCryptoProvider:()=>Mr,shiftBigintBy:()=>L,splitInput:()=>Y,string:()=>at,testCryptoAvailability:()=>Gr,toPreviewText:()=>pr,u16:()=>st,u32:()=>ot,u64:()=>pt,u8:()=>it,validateSignedMessage:()=>et});module.exports=jr(ht);var wr=(l=>(l.Multiversx="multiversx",l.Vibechain="vibechain",l.Sui="sui",l.Ethereum="ethereum",l.Base="base",l.Arbitrum="arbitrum",l.Somnia="somnia",l.Fastset="fastset",l))(wr||{}),p={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:[":","."],IdentifierParamSeparatorDefault:".",IdentifierChainDefault:"mvx",IdentifierType:{Alias:"alias",Hash:"hash"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.chain]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:n=>n.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"}},W={Option:"option",Optional:"optional",List:"list",Variadic:"variadic",Composite:"composite",String:"string",U8:"u8",U16:"u16",U32:"u32",U64:"u64",U128:"u128",U256:"u256",Biguint:"biguint",Boolean:"boolean",Address:"address",Asset:"asset",Hex:"hex"};var R={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},w={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${R.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${R.Brand}.schema.json`,DefaultClientUrl:n=>n==="devnet"?"https://devnet.usewarp.to":n==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",DefaultChainPrefix:"mvx",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 K=class{async getRandomBytes(r){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let t=new Uint8Array(r);return window.crypto.getRandomValues(t),t}},Z=class{async getRandomBytes(r){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let t=await import("crypto");return new Uint8Array(t.randomBytes(r))}catch(t){throw new Error(`Node.js crypto not available: ${t instanceof Error?t.message:"Unknown error"}`)}}},E=null;function ar(){if(E)return E;if(typeof window<"u"&&window.crypto)return E=new K,E;if(typeof process<"u"&&process.versions?.node)return E=new Z,E;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Mr(n){E=n}async function ir(n,r){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(r||ar()).getRandomBytes(n)}function Cr(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let r=new Array(n.length*2);for(let t=0;t<n.length;t++){let e=n[t];r[t*2]=(e>>>4).toString(16),r[t*2+1]=(e&15).toString(16)}return r.join("")}function qr(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 r=String.fromCharCode.apply(null,Array.from(n));return btoa(r)}else throw new Error("Base64 encoding not available in this environment")}async function sr(n,r){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let t=await ir(n/2,r);return Cr(t)}async function Gr(){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 ir(16),n.randomBytes=!0}catch{}return n}function zr(){return ar()}var g=(n,r)=>{let t=r.find(e=>e.chainInfo.name.toLowerCase()===n.toLowerCase());if(!t)throw new Error(`Adapter not found for chain: ${n}`);return t},b=(n,r)=>{let t=r.find(e=>e.prefix.toLowerCase()===n.toLowerCase());if(!t)throw new Error(`Adapter not found for prefix: ${n}`);return t},V=n=>{if(n==="warp")return`warp:${R.Warp}`;if(n==="brand")return`brand:${R.Brand}`;if(n==="abi")return`abi:${R.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},P=(n,r)=>n?.actions[r-1],or=n=>(n.actions.forEach((r,t)=>{if(r.type!=="link")return{action:r,actionIndex:t}}),{action:P(n,1),actionIndex:1}),L=(n,r)=>{let t=n.toString(),[e,a=""]=t.split("."),s=Math.abs(r);if(r>0)return BigInt(e+a.padEnd(s,"0"));if(r<0){let i=e+a;if(s>=i.length)return 0n;let o=i.slice(0,-s)||"0";return BigInt(o)}else return t.includes(".")?BigInt(t.split(".")[0]):BigInt(t)},pr=(n,r=100)=>{if(!n)return"";let t=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return t=t.startsWith("- ")?t.slice(2):t,t=t.length>r?t.substring(0,t.lastIndexOf(" ",r))+"...":t,t},_=(n,r)=>n.replace(/\{\{([^}]+)\}\}/g,(t,e)=>r[e]||""),cr=(n,r)=>{let t=Object.entries(n.messages||{}).map(([e,a])=>[e,_(a,r)]);return Object.fromEntries(t)};var kr=(n,r)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,Jr=n=>{let r=p.IdentifierParamSeparator,t=-1,e="";for(let a of r){let s=n.indexOf(a);s!==-1&&(t===-1||s<t)&&(t=s,e=a)}return t!==-1?{separator:e,index:t}:null},Ir=n=>{let r=Jr(n);if(!r)return[n];let{separator:t,index:e}=r,a=n.substring(0,e),s=n.substring(e+t.length),i=Ir(s);return[a,...i]},C=n=>{let r=decodeURIComponent(n).trim(),t=r.split("?")[0],e=Ir(t);if(t.length===64&&/^[a-fA-F0-9]+$/.test(t))return{chainPrefix:p.IdentifierChainDefault,type:p.IdentifierType.Hash,identifier:r,identifierBase:t};if(e.length===2&&/^[a-zA-Z0-9]{62}$/.test(e[0])&&/^[a-zA-Z0-9]{2}$/.test(e[1]))return null;if(e.length===3){let[a,s,i]=e;if(s===p.IdentifierType.Alias||s===p.IdentifierType.Hash){let o=r.includes("?")?i+r.substring(r.indexOf("?")):i;return{chainPrefix:a,type:s,identifier:o,identifierBase:i}}}if(e.length===2){let[a,s]=e;if(a===p.IdentifierType.Alias||a===p.IdentifierType.Hash){let i=r.includes("?")?s+r.substring(r.indexOf("?")):s;return{chainPrefix:p.IdentifierChainDefault,type:a,identifier:i,identifierBase:s}}}if(e.length===2){let[a,s]=e;if(a!==p.IdentifierType.Alias&&a!==p.IdentifierType.Hash){let i=r.includes("?")?s+r.substring(r.indexOf("?")):s,o=kr(s,a)?p.IdentifierType.Hash:p.IdentifierType.Alias;return{chainPrefix:a,type:o,identifier:i,identifierBase:s}}}return{chainPrefix:p.IdentifierChainDefault,type:p.IdentifierType.Alias,identifier:r,identifierBase:t}},U=n=>{let r=new URL(n),e=r.searchParams.get(p.IdentifierParamName);if(e||(e=r.pathname.split("/")[1]),!e)return null;let a=decodeURIComponent(e);return C(a)};var Y=n=>{let[r,...t]=n.split(/:(.*)/,2);return[r,t[0]||""]},Qr=n=>{let r=new Set(Object.values(W));if(!n.includes(p.ArgParamsSeparator))return!1;let t=Y(n)[0];return r.has(t)};var br=X(require("qr-code-styling"),1);var B=class{constructor(r,t){this.config=r;this.adapters=t}isValid(r){return r.startsWith(p.HttpProtocolPrefix)?!!U(r):!1}build(r,t,e){let a=this.config.clientUrl||w.DefaultClientUrl(this.config.env),s=g(r,this.adapters),i=t===p.IdentifierType.Alias?e:t+p.IdentifierParamSeparatorDefault+e,o=s.prefix+p.IdentifierParamSeparatorDefault+i,l=encodeURIComponent(o);return w.SuperClientUrls.includes(a)?`${a}/${l}`:`${a}?${p.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(r){let t=C(r);if(!t)return null;let e=b(t.chainPrefix,this.adapters);return e?this.build(e.chainInfo.name,t.type,t.identifierBase):null}generateQrCode(r,t,e,a=512,s="white",i="black",o="#23F7DD"){let l=g(r,this.adapters),c=this.build(l.chainInfo.name,t,e);return new br.default({type:"svg",width:a,height:a,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},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 Xr="https://",ur=(n,r,t,e,a)=>{let s=t.actions?.[e]?.next||t.next||null;if(!s)return null;if(s.startsWith(Xr))return[{identifier:null,url:s}];let[i,o]=s.split("?");if(!o)return[{identifier:i,url:lr(r,i,n)}];let l=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let h=_(o,{...t.vars,...a}),m=h?`${i}?${h}`:i;return[{identifier:m,url:lr(r,m,n)}]}let c=l[0];if(!c)return[];let u=c.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||a[d]===void 0)return[];let f=Array.isArray(a[d])?a[d]:[a[d]];if(f.length===0)return[];let y=l.filter(h=>h.includes(`{{${d}[]`)).map(h=>{let m=h.match(/\[\](\.[^}]+)?}}/),S=m&&m[1]||"";return{placeholder:h,field:S?S.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(h=>{let m=o;for(let{regex:nr,field:k}of y){let J=k?Kr(h,k):h;if(J==null)return null;m=m.replace(nr,J)}if(m.includes("{{")||m.includes("}}"))return null;let S=m?`${i}?${m}`:i;return{identifier:S,url:lr(r,S,n)}}).filter(h=>h!==null)},lr=(n,r,t)=>{let[e,a]=r.split("?"),s=C(e)||{chainPrefix:w.DefaultChainPrefix,type:"alias",identifier:e,identifierBase:e},i=b(s.chainPrefix,n);if(!i)throw new Error(`Adapter not found for chain ${s.chainPrefix}`);let o=new B(t,n).build(i.chainInfo.name,s.type,s.identifierBase);if(!a)return o;let l=new URL(o);return new URLSearchParams(a).forEach((c,u)=>l.searchParams.set(u,c)),l.toString().replace(/\/\?/,"?")},Kr=(n,r)=>r.split(".").reduce((t,e)=>t?.[e],n);function dr(n,r,t){return n.startsWith(p.Position.Payload)?n.slice(p.Position.Payload.length).split(".").reduceRight((e,a,s,i)=>({[a]:s===i.length-1?{[r]:t}:e}),{}):{[r]:t}}function rr(n,r){if(!n)return{...r};if(!r)return{...n};let t={...n};return Object.keys(r).forEach(e=>{t[e]&&typeof t[e]=="object"&&typeof r[e]=="object"?t[e]=rr(t[e],r[e]):t[e]=r[e]}),t}var Zr=(n,r,t,e)=>{let a=n.providers?.[r];return a?.[t]?a[t]:e},_r=(n,r)=>n.providers?.[r];var H=class H{static info(...r){H.isTestEnv||console.info(...r)}static warn(...r){H.isTestEnv||console.warn(...r)}static error(...r){H.isTestEnv||console.error(...r)}};H.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var v=H;var A=class{setTypeRegistry(r){this.typeRegistry=r}nativeToString(r,t){if(r==="asset"&&typeof t=="object"&&t&&"identifier"in t&&"amount"in t)return`${r}:${t.identifier}|${t.amount.toString()}`;if(this.typeRegistry?.hasType(r)){let e=this.typeRegistry.getHandler(r);if(e)return e.nativeToString(t)}return`${r}:${t?.toString()??""}`}stringToNative(r){let t=r.split(p.ArgParamsSeparator),e=t[0],a=t.slice(1).join(p.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[s,i]=a.split(p.ArgParamsSeparator);return[`option:${s}`,i||null]}else if(e==="optional"){let[s,i]=a.split(p.ArgParamsSeparator);return[`optional:${s}`,i||null]}else if(e==="list"){let s=a.split(p.ArgParamsSeparator),i=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`list:${i}`,c]}else if(e==="variadic"){let s=a.split(p.ArgParamsSeparator),i=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`variadic:${i}`,c]}else if(e.startsWith("composite")){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=a.split(p.ArgCompositeSeparator).map((l,c)=>this.stringToNative(`${s[c]}:${l}`)[1]);return[e,o]}else{if(e==="string")return[e,a];if(e==="uint8"||e==="uint16"||e==="uint32")return[e,Number(a)];if(e==="uint64"||e==="biguint")return[e,BigInt(a||0)];if(e==="bool")return[e,a==="true"];if(e==="address")return[e,a];if(e==="token")return[e,a];if(e==="hex")return[e,a];if(e==="codemeta")return[e,a];if(e==="asset"){let[s,i]=a.split(p.ArgCompositeSeparator),o={identifier:s,amount:BigInt(i)};return[e,o]}}if(this.typeRegistry?.hasType(e)){let s=this.typeRegistry.getHandler(e);if(s){let i=s.stringToNative(a);return[e,i]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}};var fr=async(n,r,t,e,a)=>{let s=[],i={};for(let[o,l]of Object.entries(n.results||{})){if(l.startsWith(p.Transform.Prefix))continue;let c=Tr(l);if(c!==null&&c!==t){i[o]=null;continue}let[u,...d]=l.split("."),f=(y,I)=>I.reduce((h,m)=>h&&h[m]!==void 0?h[m]:null,y);if(u==="out"||u.startsWith("out[")){let y=d.length===0?r?.data||r:f(r,d);s.push(y),i[o]=y}else i[o]=l}return{values:s,results:await Pr(n,i,t,e,a)}},Pr=async(n,r,t,e,a)=>{if(!n.results)return r;let s={...r};return s=Yr(s,n,t,e),s=await rt(n,s,a),s},Yr=(n,r,t,e)=>{let a={...n},s=P(r,t)?.inputs||[],i=new A;for(let[o,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("input.")){let c=l.split(".")[1],u=s.findIndex(f=>f.as===c||f.name===c),d=u!==-1?e[u]?.value:null;a[o]=d?i.stringToNative(d)[1]:null}return a},rt=async(n,r,t)=>{if(!n.results)return r;let e={...r},a=Object.entries(n.results).filter(([,s])=>s.startsWith(p.Transform.Prefix)).map(([s,i])=>({key:s,code:i.substring(p.Transform.Prefix.length)}));if(a.length>0&&(!t||typeof t.run!="function"))throw new Error("Transform results are defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:s,code:i}of a)try{e[s]=await t.run(i,e)}catch(o){v.error(`Transform error for result '${s}':`,o),e[s]=null}return e},Tr=n=>{if(n==="out")return 1;let r=n.match(/^out\[(\d+)\]/);return r?parseInt(r[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};async function Sr(n,r,t,e=5){let a=await sr(64,t),s=new Date(Date.now()+e*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:a,expiresAt:s,purpose:r}),nonce:a,expiresAt:s}}async function tr(n,r,t,e){let a=e||`prove-wallet-ownership for app "${r}"`;return Sr(n,a,t,5)}function er(n,r,t,e){return{"X-Signer-Wallet":n,"X-Signer-Signature":r,"X-Signer-Nonce":t,"X-Signer-ExpiresAt":e}}async function tt(n,r,t,e){let{message:a,nonce:s,expiresAt:i}=await tr(n,t,e),o=await r(a);return er(n,o,s,i)}function et(n){let r=new Date(n).getTime();return Date.now()<r}function nt(n){try{let r=JSON.parse(n);if(!r.wallet||!r.nonce||!r.expiresAt||!r.purpose)throw new Error("Invalid signed message: missing required fields");return r}catch(r){throw new Error(`Failed to parse signed message: ${r instanceof Error?r.message:"Unknown error"}`)}}var at=n=>W.String+p.ArgParamsSeparator+n,it=n=>W.U8+p.ArgParamsSeparator+n,st=n=>W.U16+p.ArgParamsSeparator+n,ot=n=>W.U32+p.ArgParamsSeparator+n,pt=n=>W.U64+p.ArgParamsSeparator+n,ct=n=>W.Biguint+p.ArgParamsSeparator+n,lt=n=>W.Boolean+p.ArgParamsSeparator+n,ut=n=>W.Address+p.ArgParamsSeparator+n,gr=n=>{let t=W.Asset+p.ArgParamsSeparator+n.identifier+p.ArgCompositeSeparator+n.amount;return n.decimals?t+p.ArgCompositeSeparator+n.decimals:t},dt=n=>W.Hex+p.ArgParamsSeparator+n;var Rr=X(require("ajv"),1);var hr=class{constructor(r){this.pendingBrand={protocol:V("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}setName(r){return this.pendingBrand.name=r,this}setDescription(r){return this.pendingBrand.description=r,this}setLogo(r){return this.pendingBrand.logo=r,this}setUrls(r){return this.pendingBrand.urls=r,this}setColors(r){return this.pendingBrand.colors=r,this}setCta(r){return this.pendingBrand.cta=r,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(r,t){if(!r)throw new Error(`Warp: ${t}`)}async ensureValidSchema(r){let t=this.config.schema?.brand||w.LatestBrandSchemaUrl,a=await(await fetch(t)).json(),s=new Rr.default,i=s.compile(a);if(!i(r))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(i.errors)}`)}};var Er=X(require("ajv"),1);var F=class{constructor(r){this.config=r;this.config=r}async validate(r){let t=[];return t.push(...this.validateMaxOneValuePosition(r)),t.push(...this.validateVariableNamesAndResultNamesUppercase(r)),t.push(...this.validateAbiIsSetIfApplicable(r)),t.push(...await this.validateSchema(r)),{valid:t.length===0,errors:t}}validateMaxOneValuePosition(r){return r.actions.filter(e=>e.inputs?e.inputs.some(a=>a.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let t=[],e=(a,s)=>{a&&Object.keys(a).forEach(i=>{i!==i.toUpperCase()&&t.push(`${s} name '${i}' must be uppercase`)})};return e(r.vars,"Variable"),e(r.results,"Result"),t}validateAbiIsSetIfApplicable(r){let t=r.actions.some(i=>i.type==="contract"),e=r.actions.some(i=>i.type==="query");if(!t&&!e)return[];let a=r.actions.some(i=>i.abi),s=Object.values(r.results||{}).some(i=>i.startsWith("out.")||i.startsWith("event."));return r.results&&!a&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let t=this.config.schema?.warp||w.LatestWarpSchemaUrl,a=await(await fetch(t)).json(),s=new Er.default({strict:!1}),i=s.compile(a);return i(r)?[]:[`Schema validation failed: ${s.errorsText(i.errors)}`]}catch(t){return[`Schema validation failed: ${t instanceof Error?t.message:String(t)}`]}}};var mr=class{constructor(r){this.config=r;this.pendingWarp={protocol:V("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.validate(e),e}async createFromUrl(r){return await(await fetch(r)).json()}setName(r){return this.pendingWarp.name=r,this}setTitle(r){return this.pendingWarp.title=r,this}setDescription(r){return this.pendingWarp.description=r,this}setPreview(r){return this.pendingWarp.preview=r,this}setActions(r){return this.pendingWarp.actions=r,this}addAction(r){return this.pendingWarp.actions.push(r),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(r,t=100){return pr(r,t)}ensure(r,t){if(!r)throw new Error(t)}async validate(r){let e=await new F(this.config).validate(r);if(!e.valid)throw new Error(e.errors.join(`
2
- `))}};var O=class{constructor(r="warp-cache"){this.prefix=r}getKey(r){return`${this.prefix}:${r}`}get(r){try{let t=localStorage.getItem(this.getKey(r));if(!t)return null;let e=JSON.parse(t,gt);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(r)),null):e.value}catch{return null}}set(r,t,e){let a={value:t,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(r),JSON.stringify(a,ft))}forget(r){localStorage.removeItem(this.getKey(r))}clear(){for(let r=0;r<localStorage.length;r++){let t=localStorage.key(r);t?.startsWith(this.prefix)&&localStorage.removeItem(t)}}},Br=new A,ft=(n,r)=>typeof r=="bigint"?Br.nativeToString("biguint",r):r,gt=(n,r)=>typeof r=="string"&&r.startsWith(W.Biguint+":")?Br.stringToNative(r)[1]:r;var T=class T{get(r){let t=T.cache.get(r);return t?Date.now()>t.expiresAt?(T.cache.delete(r),null):t.value:null}set(r,t,e){let a=Date.now()+e*1e3;T.cache.set(r,{value:t,expiresAt:a})}forget(r){T.cache.delete(r)}clear(){T.cache.clear()}};T.cache=new Map;var D=T;var yr={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},Wr={Warp:(n,r)=>`warp:${n}:${r}`,WarpAbi:(n,r)=>`warp-abi:${n}:${r}`,WarpExecutable:(n,r,t)=>`warp-exec:${n}:${r}:${t}`,RegistryInfo:(n,r)=>`registry-info:${n}:${r}`,Brand:(n,r)=>`brand:${n}:${r}`,Asset:(n,r,t)=>`asset:${n}:${r}:${t}`},j=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new O:r==="memory"?new D:typeof window<"u"&&window.localStorage?new O:new D}set(r,t,e){this.strategy.set(r,t,e)}get(r){return this.strategy.get(r)}forget(r){this.strategy.forget(r)}clear(){this.strategy.clear()}};var $=class{constructor(r,t){this.config=r;this.adapter=t}async apply(r,t,e){let a=this.applyVars(r,t,e);return await this.applyGlobals(r,a)}async applyGlobals(r,t){let e={...t};return e.actions=await Promise.all(e.actions.map(async a=>await this.applyActionGlobals(a))),e=await this.applyRootGlobals(e,r),e}applyVars(r,t,e){if(!t?.vars)return t;let a=JSON.stringify(t),s=(i,o)=>{a=a.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([i,o])=>{if(typeof o!="string")s(i,o);else if(o.startsWith(`${p.Vars.Query}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let l=o.split(`${p.Vars.Query}:`)[1],c=new URLSearchParams(r.currentUrl.split("?")[1]).get(l);c&&s(i,c)}else if(o.startsWith(`${p.Vars.Env}:`)){let l=o.split(`${p.Vars.Env}:`)[1],u={...r.vars,...e}?.[l];u&&s(i,u)}else if(o===p.Source.UserWallet&&r.user?.wallets?.[this.adapter.chainInfo.name]){let l=r.user.wallets[this.adapter.chainInfo.name];l&&s(i,l)}else s(i,o)}),JSON.parse(a)}async applyRootGlobals(r,t){let e=JSON.stringify(r),a={config:t,chain:this.adapter.chainInfo.name,chainInfo:this.adapter.chainInfo};return Object.values(p.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}async applyActionGlobals(r){let t=r.chain?this.adapter.chainInfo:this.adapter.chainInfo;if(!t)throw new Error(`Chain info not found for ${r.chain}`);let e=JSON.stringify(r),a={config:this.config,chain:this.adapter.chainInfo.name,chainInfo:t};return Object.values(p.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}};var M=class{constructor(){this.typeHandlers=new Map}registerType(r,t){this.typeHandlers.set(r,t)}hasType(r){return this.typeHandlers.has(r)}getHandler(r){return this.typeHandlers.get(r)}getRegisteredTypes(){return Array.from(this.typeHandlers.keys())}};var N=class{constructor(r,t){this.config=r;this.adapters=t;if(!r.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(r.currentUrl),this.serializer=new A,this.cache=new j(r.cache?.type);let e=new M;this.serializer.setTypeRegistry(e);for(let a of t)a.registerTypes&&a.registerTypes(e)}async createExecutable(r,t,e,a){let s=P(r,t);if(!s)throw new Error("WarpFactory: Action not found");let i=await this.getChainInfoForAction(s,e),o=g(i.name,this.adapters),l=await new $(this.config,o).apply(this.config,r,a),c=P(l,t),u=await this.getResolvedInputs(i.name,c,e),d=this.getModifiedInputs(u),f=d.find(x=>x.input.position==="receiver")?.value,y=this.getDestinationFromAction(c),I=f?this.serializer.stringToNative(f)[1]:y;if(!I)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let h=this.getPreparedArgs(c,d),m=d.find(x=>x.input.position==="value")?.value||null,S="value"in c?c.value:null,nr=BigInt(m?.split(":")[1]||S||0),k=d.filter(x=>x.input.position==="transfer"&&x.value).map(x=>x.value),$r=[...("transfers"in c?c.transfers:[])||[],...k||[]].map(x=>this.serializer.stringToNative(x)[1]),Nr=d.find(x=>x.input.position==="data")?.value,Ur="data"in c?c.data||"":null,xr={warp:l,chain:i,action:t,destination:I,args:h,value:nr,transfers:$r,data:Nr||Ur||null,resolvedInputs:d};return this.cache.set(Wr.WarpExecutable(this.config.env,l.meta?.hash||"",t),xr.resolvedInputs,yr.OneWeek),xr}async getChainInfoForAction(r,t){if(r.chain)return g(r.chain,this.adapters).chainInfo;if(t){let a=await this.tryGetChainFromInputs(r,t);if(a)return a}return this.adapters[0].chainInfo}async getResolvedInputs(r,t,e){let a=t.inputs||[],s=await Promise.all(e.map(o=>this.preprocessInput(r,o))),i=(o,l)=>{if(o.source==="query"){let c=this.url.searchParams.get(o.name);return c?this.serializer.nativeToString(o.type,c):null}else return o.source===p.Source.UserWallet?this.config.user?.wallets?.[r]?this.serializer.nativeToString("address",this.config.user.wallets[r]):null:o.source==="hidden"?o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null:s[l]||null};return a.map((o,l)=>{let c=i(o,l);return{input:o,value:c||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(r){return r.map((t,e)=>{if(t.input.modifier?.startsWith("scale:")){let[,a]=t.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(r.find(l=>l.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let i=t.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let o=L(i,+s);return{...t,value:`${t.input.type}:${o}`}}else{let s=t.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let i=L(s,+a);return{...t,value:`${t.input.type}:${i}`}}}else return t})}async preprocessInput(r,t){try{let[e,a]=Y(t),s=g(r,this.adapters);if(e==="asset"){let[i,o,l]=a.split(p.ArgCompositeSeparator);if(l)return t;let c=await s.dataLoader.getAsset(i);if(!c)throw new Error(`WarpFactory: Asset not found for asset ${i}`);if(typeof c.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${i}`);let u=L(o,c.decimals);return gr({...c,amount:u})}else return t}catch(e){throw v.warn("WarpFactory: Preprocess input failed",e),e}}getDestinationFromAction(r){return"address"in r&&r.address?r.address:"destination"in r&&r.destination?.url?r.destination.url:null}getPreparedArgs(r,t){let e="args"in r?r.args||[]:[];return t.forEach(({input:a,value:s})=>{if(!s||!a.position?.startsWith("arg:"))return;let i=Number(a.position.split(":")[1])-1;e.splice(i,0,s)}),e}async tryGetChainFromInputs(r,t){let e=r.inputs?.findIndex(l=>l.position==="chain");if(e===-1||e===void 0)return null;let a=t[e];if(!a)throw new Error("Chain input not found");let i=new A().stringToNative(a)[1];return g(i,this.adapters).chainInfo}};var q=class{constructor(r,t,e){this.config=r;this.adapters=t;this.handlers=e;this.handlers=e,this.factory=new N(r,t),this.serializer=new A}async execute(r,t,e){let{action:a,actionIndex:s}=or(r),i=await this.factory.createExecutable(r,s,t,e);if(a.type==="collect"){let c=await this.executeCollect(i);return c.success?this.handlers?.onExecuted?.(c):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null}}let o=g(i.chain.name,this.adapters);if(a.type==="query"){let c=await o.executor.executeQuery(i);return c.success?this.handlers?.onExecuted?.(c):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:i.chain}}return{tx:await o.executor.createTransaction(i),chain:i.chain}}async evaluateResults(r,t,e){let a=await g(t,this.adapters).results.getTransactionExecutionResults(r,e);this.handlers?.onExecuted?.(a)}async executeCollect(r,t){let e=this.config.user?.wallets?.[r.chain.name]||null,a=P(r.warp,r.action),s=u=>{if(!u.value)return null;let d=this.serializer.stringToNative(u.value)[1];if(u.input.type==="biguint")return d.toString();if(u.input.type==="asset"){let{identifier:f,amount:y}=d;return{identifier:f,amount:y.toString()}}else return d},i=new Headers;if(i.set("Content-Type","application/json"),i.set("Accept","application/json"),this.handlers?.onSignRequest){if(!e)throw new Error(`No wallet configured for chain ${r.chain.name}`);let{message:u,nonce:d,expiresAt:f}=await tr(e,`${r.chain.name}-adapter`),y=await this.handlers.onSignRequest({message:u,chain:r.chain}),I=er(e,y,d,f);Object.entries(I).forEach(([h,m])=>i.set(h,m))}Object.entries(a.destination.headers||{}).forEach(([u,d])=>{i.set(u,d)});let o={};r.resolvedInputs.forEach(u=>{let d=u.input.as||u.input.name,f=s(u);if(u.input.position&&u.input.position.startsWith(p.Position.Payload)){let y=dr(u.input.position,d,f);o=rr(o,y)}else o[d]=f});let l=a.destination.method||"GET",c=l==="GET"?void 0:JSON.stringify({...o,...t});v.info("Executing collect",{url:a.destination.url,method:l,headers:i,body:c});try{let u=await fetch(a.destination.url,{method:l,headers:i,body:c});v.info("Collect response",{response:u});let d=await u.json(),{values:f,results:y}=await fr(r.warp,d,r.action,r.resolvedInputs,this.config.transform?.runner),I=ur(this.config,this.adapters,r.warp,r.action,y);return{success:u.ok,warp:r.warp,action:r.action,user:this.config.user?.wallets?.[r.chain.name]||null,txHash:null,tx:null,next:I,values:f,valuesRaw:[],results:{...y,_DATA:d},messages:cr(r.warp,y)}}catch(u){return v.error("WarpActionExecutor: Error executing collect",u),{success:!1,warp:r.warp,action:r.action,user:e,txHash:null,tx:null,next:null,values:[],valuesRaw:[],results:{_DATA:u},messages:{}}}}};var G=class{constructor(r){this.config=r}async search(r,t,e){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let a=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"]:r,...t})});if(!a.ok)throw new Error(`WarpIndex: search failed with status ${a.status}`);return(await a.json()).hits}catch(a){throw v.error("WarpIndex: Error searching for warps: ",a),a}}};var z=class{constructor(r,t){this.config=r;this.adapters=t}isValid(r){return r.startsWith(p.HttpProtocolPrefix)?!!U(r):!1}async detectFromHtml(r){if(!r.length)return{match:!1,results:[]};let a=[...r.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),i=(await Promise.all(a)).filter(c=>c.match),o=i.length>0,l=i.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:l}}async detect(r,t){let e={match:!1,url:r,warp:null,chain:null,registryInfo:null,brand:null},a=r.startsWith(p.HttpProtocolPrefix)?U(r):C(r);if(!a)return e;try{let{type:s,identifierBase:i}=a,o=null,l=null,c=null,u=b(a.chainPrefix,this.adapters);if(s==="hash"){o=await u.builder().createFromTransactionHash(i,t);let f=await u.registry.getInfoByHash(i,t);l=f.registryInfo,c=f.brand}else if(s==="alias"){let f=await u.registry.getInfoByAlias(i,t);l=f.registryInfo,c=f.brand,f.registryInfo&&(o=await u.builder().createFromTransactionHash(f.registryInfo.hash,t))}let d=o?await new $(this.config,u).apply(this.config,o):null;return d?{match:!0,url:r,warp:d,chain:u.chainInfo.name,registryInfo:l,brand:c}:e}catch(s){return v.error("Error detecting warp link",s),e}}};var vr=class{constructor(r,t){this.config=r;this.adapters=t}getConfig(){return this.config}getAdapters(){return this.adapters}addAdapter(r){return this.adapters.push(r),this}createExecutor(r){return new q(this.config,this.adapters,r)}async detectWarp(r,t){return new z(this.config,this.adapters).detect(r,t)}async executeWarp(r,t,e,a={}){let s=typeof r=="object",i=!s&&r.startsWith("http")&&r.endsWith(".json"),o=s?r:null;if(!o&&i&&(o=await(await fetch(r)).json()),o||(o=(await this.detectWarp(r,a.cache)).warp),!o)throw new Error("Warp not found");let l=this.createExecutor(e),{tx:c,chain:u}=await l.execute(o,t);return{tx:c,chain:u,evaluateResults:async f=>{if(!u||!c||!o)throw new Error("Warp not found");await l.evaluateResults(o,u.name,f)}}}createInscriptionTransaction(r,t){return g(r,this.adapters).builder().createInscriptionTransaction(t)}async createFromTransaction(r,t,e=!1){return g(r,this.adapters).builder().createFromTransaction(t,e)}async createFromTransactionHash(r,t){let e=C(r);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return b(e.chainPrefix,this.adapters).builder().createFromTransactionHash(r,t)}async signMessage(r,t,e){if(!this.config.user?.wallets?.[r])throw new Error(`No wallet configured for chain ${r}`);return g(r,this.adapters).executor.signMessage(t,e)}getExplorer(r){return g(r,this.adapters).explorer}getResults(r){return g(r,this.adapters).results}async getRegistry(r){let t=g(r,this.adapters).registry;return await t.init(),t}getDataLoader(r){return g(r,this.adapters).dataLoader}get factory(){return new N(this.config,this.adapters)}get index(){return new G(this.config)}get linkBuilder(){return new B(this.config,this.adapters)}createBuilder(r){return g(r,this.adapters).builder()}createAbiBuilder(r){return g(r,this.adapters).abiBuilder()}createBrandBuilder(r){return g(r,this.adapters).brandBuilder()}};0&&(module.exports={BrowserCryptoProvider,CacheTtl,NodeCryptoProvider,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpTypeRegistryImpl,WarpValidator,address,applyResultsToMessages,asset,biguint,boolean,buildNestedPayload,bytesToBase64,bytesToHex,createAuthHeaders,createAuthMessage,createCryptoProvider,createHttpAuthHeaders,createSignableMessage,evaluateResultsCommon,extractCollectResults,extractIdentifierInfoFromUrl,findWarpAdapterByPrefix,findWarpAdapterForChain,findWarpExecutableAction,getCryptoProvider,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getProviderUrl,getRandomBytes,getRandomHex,getWarpActionByIndex,getWarpInfoFromIdentifier,hasInputPrefix,hex,mergeNestedPayload,parseResultsOutIndex,parseSignedMessage,replacePlaceholders,setCryptoProvider,shiftBigintBy,splitInput,string,testCryptoAvailability,toPreviewText,u16,u32,u64,u8,validateSignedMessage});
1
+ "use strict";var _t=Object.create;var _=Object.defineProperty;var Xt=Object.getOwnPropertyDescriptor;var Zt=Object.getOwnPropertyNames;var Yt=Object.getPrototypeOf,tr=Object.prototype.hasOwnProperty;var rr=(e,t)=>{for(var r in t)_(e,r,{get:t[r],enumerable:!0})},Pt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Zt(t))!tr.call(e,i)&&i!==r&&_(e,i,{get:()=>t[i],enumerable:!(n=Xt(t,i))||n.enumerable});return e};var X=(e,t,r)=>(r=e!=null?_t(Yt(e)):{},Pt(t||!e||!e.__esModule?_(r,"default",{value:e,enumerable:!0}):r,e)),er=e=>Pt(_({},"__esModule",{value:!0}),e);var qr={};rr(qr,{BrowserCryptoProvider:()=>Z,CacheTtl:()=>Ct,NodeCryptoProvider:()=>Y,WARP_LANGUAGES:()=>lr,WarpBrandBuilder:()=>xt,WarpBuilder:()=>vt,WarpCache:()=>z,WarpCacheKey:()=>wt,WarpChainName:()=>Et,WarpClient:()=>St,WarpConfig:()=>P,WarpConstants:()=>o,WarpExecutor:()=>G,WarpFactory:()=>U,WarpIndex:()=>J,WarpInputTypes:()=>d,WarpInterpolator:()=>b,WarpLinkBuilder:()=>$,WarpLinkDetecter:()=>Q,WarpLogger:()=>x,WarpProtocolVersions:()=>B,WarpSerializer:()=>A,WarpTypeRegistry:()=>It,WarpValidator:()=>q,address:()=>$r,applyOutputToMessages:()=>ht,asset:()=>At,biguint:()=>Br,bool:()=>Vr,buildNestedPayload:()=>yt,bytesToBase64:()=>sr,bytesToHex:()=>Rt,createAuthHeaders:()=>ot,createAuthMessage:()=>st,createCryptoProvider:()=>pr,createHttpAuthHeaders:()=>vr,createSignableMessage:()=>Ut,createWarpI18nText:()=>dr,createWarpIdentifier:()=>et,evaluateOutputCommon:()=>$t,extractCollectOutput:()=>at,extractIdentifierInfoFromUrl:()=>H,extractQueryStringFromIdentifier:()=>gt,extractQueryStringFromUrl:()=>ft,extractWarpSecrets:()=>cr,findWarpAdapterForChain:()=>h,getCryptoProvider:()=>ct,getEventNameFromWarp:()=>nr,getLatestProtocolIdentifier:()=>L,getNextInfo:()=>Wt,getProviderConfig:()=>yr,getRandomBytes:()=>lt,getRandomHex:()=>ut,getWarpActionByIndex:()=>I,getWarpBrandLogoUrl:()=>ir,getWarpInfoFromIdentifier:()=>T,getWarpPrimaryAction:()=>tt,getWarpWalletAddress:()=>Ot,getWarpWalletAddressFromConfig:()=>S,getWarpWalletMnemonic:()=>Ft,getWarpWalletMnemonicFromConfig:()=>Ir,getWarpWalletPrivateKey:()=>Ht,getWarpWalletPrivateKeyFromConfig:()=>Sr,hasInputPrefix:()=>hr,hex:()=>Nr,isWarpActionAutoExecute:()=>rt,isWarpI18nText:()=>ur,mergeNestedPayload:()=>it,option:()=>Ur,parseOutputOutIndex:()=>Nt,parseSignedMessage:()=>wr,replacePlaceholders:()=>E,resolveWarpText:()=>D,safeWindow:()=>pt,setCryptoProvider:()=>ar,shiftBigintBy:()=>j,splitInput:()=>nt,string:()=>Tr,struct:()=>Hr,testCryptoAvailability:()=>or,toPreviewText:()=>dt,tuple:()=>Or,uint16:()=>Pr,uint32:()=>Er,uint64:()=>Rr,uint8:()=>br,validateSignedMessage:()=>Cr,vector:()=>Fr});module.exports=er(qr);var Et=(l=>(l.Multiversx="multiversx",l.Vibechain="vibechain",l.Sui="sui",l.Ethereum="ethereum",l.Base="base",l.Arbitrum="arbitrum",l.Somnia="somnia",l.Fastset="fastset",l))(Et||{}),o={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:e=>e.config.user?.wallets?.[e.chain.name]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:e=>e.chain.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:e=>e.chain.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"},pt=typeof window<"u"?window:{open:()=>{}};var B={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},P={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${B.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${B.Brand}.schema.json`,DefaultClientUrl:e=>e==="devnet"?"https://devnet.usewarp.to":e==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",o.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 nr=(e,t)=>{let r=e.alerts?.[t];if(!r)return null;let n=o.Alerts.TriggerEventPrefix+o.ArgParamsSeparator;if(!r.trigger.startsWith(n))return null;let i=r.trigger.replace(n,"");return i||null};var ir=(e,t)=>typeof e.logo=="string"?e.logo:e.logo[t?.scheme??"light"];var Z=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}},Y=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 ct(){if(V)return V;if(typeof window<"u"&&window.crypto)return V=new Z,V;if(typeof process<"u"&&process.versions?.node)return V=new Y,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(e){V=e}async function lt(e,t){if(e<=0||!Number.isInteger(e))throw new Error("Size must be a positive integer");return(t||ct()).getRandomBytes(e)}function Rt(e){if(!(e instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(e.length*2);for(let r=0;r<e.length;r++){let n=e[r];t[r*2]=(n>>>4).toString(16),t[r*2+1]=(n&15).toString(16)}return t.join("")}function sr(e){if(!(e instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(e).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(e));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function ut(e,t){if(e<=0||e%2!==0)throw new Error("Length must be a positive even number");let r=await lt(e/2,t);return Rt(r)}async function or(){let e={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?e.environment="browser":typeof process<"u"&&process.versions?.node&&(e.environment="nodejs"),await lt(16),e.randomBytes=!0}catch{}return e}function pr(){return ct()}var cr=e=>Object.values(e.vars||{}).filter(t=>t.startsWith(`${o.Vars.Env}:`)).map(t=>{let r=t.replace(`${o.Vars.Env}:`,"").trim(),[n,i]=r.split(o.ArgCompositeSeparator);return{key:n,description:i||null}});var h=(e,t)=>{let r=t.find(n=>n.chainInfo.name.toLowerCase()===e.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${e}`);return r},L=e=>{if(e==="warp")return`warp:${B.Warp}`;if(e==="brand")return`brand:${B.Brand}`;if(e==="abi")return`abi:${B.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${e}`)},I=(e,t)=>e?.actions[t-1],tt=e=>{if(e.actions.length===0)throw new Error(`Warp has no primary action: ${e.meta?.identifier}`);let t=e.actions.find(s=>s.primary===!0);if(t)return{action:t,index:e.actions.indexOf(t)};let r=["transfer","contract","query","collect"],n=e.actions.find(s=>r.includes(s.type));return n?{action:n,index:e.actions.indexOf(n)}:{action:e.actions[0],index:0}},rt=(e,t)=>{if(e.auto===!1)return!1;if(e.type==="link"){if(e.auto===!0)return!0;let{action:r}=tt(t);return e===r}return!0},j=(e,t)=>{let r=e.toString(),[n,i=""]=r.split("."),s=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(s,"0"));if(t<0){let a=n+i;if(s>=a.length)return 0n;let p=a.slice(0,-s)||"0";return BigInt(p)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},dt=(e,t=100)=>{if(!e)return"";let r=e.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},E=(e,t)=>e.replace(/\{\{([^}]+)\}\}/g,(r,n)=>t[n]||"");var lr={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"},D=(e,t)=>{let r=t?.preferences?.locale||"en";if(typeof e=="string")return e;if(typeof e=="object"&&e!==null){if(r in e)return e[r];if("en"in e)return e.en;let n=Object.keys(e);if(n.length>0)return e[n[0]]}return""},ur=e=>typeof e=="object"&&e!==null&&Object.keys(e).length>0,dr=e=>e;var et=(e,t,r)=>{let n=r.startsWith(o.IdentifierAliasMarker)?r.replace(o.IdentifierAliasMarker,""):r;return t===o.IdentifierType.Alias?o.IdentifierAliasMarker+e+o.IdentifierParamSeparator+n:e+o.IdentifierParamSeparator+t+o.IdentifierParamSeparator+n},T=e=>{let r=decodeURIComponent(e).trim().replace(o.IdentifierAliasMarker,""),n=r.split("?")[0],i=Bt(n);if(n.length===64&&/^[a-fA-F0-9]+$/.test(n))return{chain:o.IdentifierChainDefault,type:o.IdentifierType.Hash,identifier:r,identifierBase:n};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[s,a,p]=i;if(a===o.IdentifierType.Alias||a===o.IdentifierType.Hash){let l=r.includes("?")?p+r.substring(r.indexOf("?")):p;return{chain:s,type:a,identifier:l,identifierBase:p}}}if(i.length===2){let[s,a]=i;if(s===o.IdentifierType.Alias||s===o.IdentifierType.Hash){let p=r.includes("?")?a+r.substring(r.indexOf("?")):a;return{chain:o.IdentifierChainDefault,type:s,identifier:p,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==o.IdentifierType.Alias&&s!==o.IdentifierType.Hash){let p=r.includes("?")?a+r.substring(r.indexOf("?")):a,l=fr(a,s)?o.IdentifierType.Hash:o.IdentifierType.Alias;return{chain:s,type:l,identifier:p,identifierBase:a}}}return{chain:o.IdentifierChainDefault,type:o.IdentifierType.Alias,identifier:r,identifierBase:n}},H=e=>{let t=new URL(e),n=t.searchParams.get(o.IdentifierParamName);if(n||(n=t.pathname.split("/")[1]),!n)return null;let i=decodeURIComponent(n);return T(i)},fr=(e,t)=>/^[a-fA-F0-9]+$/.test(e)&&e.length>32,gr=e=>{let t=o.IdentifierParamSeparator,r=e.indexOf(t);return r!==-1?{separator:t,index:r}:null},Bt=e=>{let t=gr(e);if(!t)return[e];let{separator:r,index:n}=t,i=e.substring(0,n),s=e.substring(n+r.length),a=Bt(s);return[i,...a]},ft=e=>{try{let t=new URL(e),r=new URLSearchParams(t.search);return r.delete(o.IdentifierParamName),r.toString()||null}catch{return null}},gt=e=>{let t=e.indexOf("?");if(t===-1||t===e.length-1)return null;let r=e.substring(t+1);return r.length>0?r:null};var nt=e=>{let[t,...r]=e.split(/:(.*)/,2);return[t,r[0]||""]},hr=e=>{let t=new Set(Object.values(d));if(!e.includes(o.ArgParamsSeparator))return!1;let r=nt(e)[0];return t.has(r)};var ht=(e,t,r)=>{let n=Object.entries(e.messages||{}).map(([i,s])=>{let a=D(s,r);return[i,E(a,t)]});return Object.fromEntries(n)};var Vt=X(require("qr-code-styling"),1);var $=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(o.HttpProtocolPrefix)?!!H(t):!1}build(t,r,n){let i=this.config.clientUrl||P.DefaultClientUrl(this.config.env),s=h(t,this.adapters),a=r===o.IdentifierType.Alias?n:r+o.IdentifierParamSeparator+n,p=s.chainInfo.name+o.IdentifierParamSeparator+a,l=encodeURIComponent(p);return P.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${o.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(t){let r=T(t);if(!r)return null;let n=h(r.chain,this.adapters);return n?this.build(n.chainInfo.name,r.type,r.identifierBase):null}generateQrCode(t,r,n,i=512,s="white",a="black",p="#23F7DD"){let l=h(t,this.adapters),c=this.build(l.chainInfo.name,r,n);return new Vt.default({type:"svg",width:i,height:i,data:String(c),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(p)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var mr="https://",Wt=(e,t,r,n,i)=>{let s=r.actions?.[n-1]?.next||r.next||null;if(!s)return null;if(s.startsWith(mr))return[{identifier:null,url:s}];let[a,p]=s.split("?");if(!p){let W=E(a,{...r.vars,...i});return[{identifier:W,url:mt(t,W,e)}]}let l=p.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let W=E(p,{...r.vars,...i}),y=W?`${a}?${W}`:a;return[{identifier:y,url:mt(t,y,e)}]}let c=l[0];if(!c)return[];let u=c.match(/{{([^[]+)\[\]/),f=u?u[1]:null;if(!f||i[f]===void 0)return[];let m=Array.isArray(i[f])?i[f]:[i[f]];if(m.length===0)return[];let g=l.filter(W=>W.includes(`{{${f}[]`)).map(W=>{let y=W.match(/\[\](\.[^}]+)?}}/),v=y&&y[1]||"";return{placeholder:W,field:v?v.slice(1):"",regex:new RegExp(W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return m.map(W=>{let y=p;for(let{regex:O,field:K}of g){let F=K?Wr(W,K):W;if(F==null)return null;y=y.replace(O,F)}if(y.includes("{{")||y.includes("}}"))return null;let v=y?`${a}?${y}`:a;return{identifier:v,url:mt(t,v,e)}}).filter(W=>W!==null)},mt=(e,t,r)=>{let[n,i]=t.split("?"),s=T(n)||{chain:o.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},a=h(s.chain,e);if(!a)throw new Error(`Adapter not found for chain ${s.chain}`);let p=new $(r,e).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return p;let l=new URL(p);return new URLSearchParams(i).forEach((c,u)=>l.searchParams.set(u,c)),l.toString().replace(/\/\?/,"?")},Wr=(e,t)=>t.split(".").reduce((r,n)=>r?.[n],e);function yt(e,t,r){return e.startsWith(o.Position.Payload)?e.slice(o.Position.Payload.length).split(".").reduceRight((n,i,s,a)=>({[i]:s===a.length-1?{[t]:r}:n}),{}):{[t]:r}}function it(e,t){if(!e)return{...t};if(!t)return{...e};let r={...e};return Object.keys(t).forEach(n=>{r[n]&&typeof r[n]=="object"&&typeof t[n]=="object"?r[n]=it(r[n],t[n]):r[n]=t[n]}),r}var yr=(e,t,r,n)=>{let i=e.preferences?.providers?.[t];return i?.[r]?typeof i[r]=="string"?{url:i[r]}:i[r]:{url:n}};var N=class N{static debug(...t){N.isTestEnv||console.debug(...t)}static info(...t){N.isTestEnv||console.info(...t)}static warn(...t){N.isTestEnv||console.warn(...t)}static error(...t){N.isTestEnv||console.error(...t)}};N.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var x=N;var at=async(e,t,r,n,i,s)=>{let a=[],p=[],l={};for(let[c,u]of Object.entries(e.output||{})){if(u.startsWith(o.Transform.Prefix))continue;let f=Nt(u);if(f!==null&&f!==r){l[c]=null;continue}let[m,...g]=u.split("."),w=(W,y)=>y.reduce((v,O)=>v&&v[O]!==void 0?v[O]:null,W);if(m==="out"||m.startsWith("out[")){let W=g.length===0?t?.data||t:w(t,g);a.push(String(W)),p.push(W),l[c]=W}else l[c]=u}return{values:{string:a,native:p},output:await $t(e,l,r,n,i,s)}},$t=async(e,t,r,n,i,s)=>{if(!e.output)return t;let a={...t};return a=Ar(a,e,r,n,i),a=await xr(e,a,s.transform?.runner||null),a},Ar=(e,t,r,n,i)=>{let s={...e},a=I(t,r)?.inputs||[];for(let[p,l]of Object.entries(s))if(typeof l=="string"&&l.startsWith("in.")){let c=l.split(".")[1],u=a.findIndex(m=>m.as===c||m.name===c),f=u!==-1?n[u]?.value:null;s[p]=f?i.stringToNative(f)[1]:null}return s},xr=async(e,t,r)=>{if(!e.output)return t;let n={...t},i=Object.entries(e.output).filter(([,s])=>s.startsWith(o.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(o.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{n[s]=await r.run(a,n)}catch(p){x.error(`Transform error for output '${s}':`,p),n[s]=null}return n},Nt=e=>{if(e==="out")return 1;let t=e.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(e.startsWith("out.")||e.startsWith("event."),null)};async function Ut(e,t,r,n=5){let i=await ut(64,r),s=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:e,nonce:i,expiresAt:s,purpose:t}),nonce:i,expiresAt:s}}async function st(e,t,r,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Ut(e,i,r,5)}function ot(e,t,r,n){return{"X-Signer-Wallet":e,"X-Signer-Signature":t,"X-Signer-Nonce":r,"X-Signer-ExpiresAt":n}}async function vr(e,t,r,n){let{message:i,nonce:s,expiresAt:a}=await st(e,r,n),p=await t(i);return ot(e,p,s,a)}function Cr(e){let t=new Date(e).getTime();return Date.now()<t}function wr(e){try{let t=JSON.parse(e);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 Ot=e=>e?typeof e=="string"?e:e.address:null,S=(e,t)=>Ot(e.user?.wallets?.[t]||null),Ht=e=>e?typeof e=="string"?e:e.privateKey:null,Ft=e=>e?typeof e=="string"?e:e.mnemonic:null,Sr=(e,t)=>Ht(e.user?.wallets?.[t]||null)?.trim()||null,Ir=(e,t)=>Ft(e.user?.wallets?.[t]||null)?.trim()||null;var A=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,r){if(t===d.Tuple&&Array.isArray(r)){if(r.length===0)return t+o.ArgParamsSeparator;if(r.every(n=>typeof n=="string"&&n.includes(o.ArgParamsSeparator))){let n=r.map(a=>this.getTypeAndValue(a)),i=n.map(([a])=>a),s=n.map(([,a])=>a);return`${t}(${i.join(o.ArgCompositeSeparator)})${o.ArgParamsSeparator}${s.join(o.ArgListSeparator)}`}return t+o.ArgParamsSeparator+r.join(o.ArgListSeparator)}if(t===d.Struct&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let n=r;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,s=Object.keys(n).filter(p=>p!=="_name");if(s.length===0)return`${t}(${i})${o.ArgParamsSeparator}`;let a=s.map(p=>{let[l,c]=this.getTypeAndValue(n[p]);return`(${p}${o.ArgParamsSeparator}${l})${c}`});return`${t}(${i})${o.ArgParamsSeparator}${a.join(o.ArgListSeparator)}`}if(t===d.Vector&&Array.isArray(r)){if(r.length===0)return`${t}${o.ArgParamsSeparator}`;if(r.every(n=>typeof n=="string"&&n.includes(o.ArgParamsSeparator))){let n=r[0],i=n.indexOf(o.ArgParamsSeparator),s=n.substring(0,i),a=r.map(l=>{let c=l.indexOf(o.ArgParamsSeparator),u=l.substring(c+1);return s.startsWith(d.Tuple)?u.replace(o.ArgListSeparator,o.ArgCompositeSeparator):u}),p=s.startsWith(d.Struct)?o.ArgStructSeparator:o.ArgListSeparator;return t+o.ArgParamsSeparator+s+o.ArgParamsSeparator+a.join(p)}return t+o.ArgParamsSeparator+r.join(o.ArgListSeparator)}if(t===d.Asset&&typeof r=="object"&&r&&"identifier"in r&&"amount"in r)return"decimals"in r?d.Asset+o.ArgParamsSeparator+r.identifier+o.ArgCompositeSeparator+String(r.amount)+o.ArgCompositeSeparator+String(r.decimals):d.Asset+o.ArgParamsSeparator+r.identifier+o.ArgCompositeSeparator+String(r.amount);if(this.typeRegistry){let n=this.typeRegistry.getHandler(t);if(n)return n.nativeToString(r);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,r)}return t+o.ArgParamsSeparator+(r?.toString()??"")}stringToNative(t){let r=t.split(o.ArgParamsSeparator),n=r[0],i=r.slice(1).join(o.ArgParamsSeparator);if(n==="null")return[n,null];if(n===d.Option){let[s,a]=i.split(o.ArgParamsSeparator);return[d.Option+o.ArgParamsSeparator+s,a||null]}if(n===d.Vector){let s=i.indexOf(o.ArgParamsSeparator),a=i.substring(0,s),p=i.substring(s+1),l=a.startsWith(d.Struct)?o.ArgStructSeparator:o.ArgListSeparator,u=(p?p.split(l):[]).map(f=>this.stringToNative(a+o.ArgParamsSeparator+f)[1]);return[d.Vector+o.ArgParamsSeparator+a,u]}else if(n.startsWith(d.Tuple)){let s=n.match(/\(([^)]+)\)/)?.[1]?.split(o.ArgCompositeSeparator),p=i.split(o.ArgCompositeSeparator).map((l,c)=>this.stringToNative(`${s[c]}${o.IdentifierParamSeparator}${l}`)[1]);return[n,p]}else if(n.startsWith(d.Struct)){let s=n.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let p={_name:s[1]};return i&&i.split(o.ArgListSeparator).forEach(l=>{let c=l.match(new RegExp(`^\\(([^${o.ArgParamsSeparator}]+)${o.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(c){let[,u,f,m]=c;p[u]=this.stringToNative(`${f}${o.IdentifierParamSeparator}${m}`)[1]}}),[n,p]}else{if(n===d.String)return[n,i];if(n===d.Uint8||n===d.Uint16||n===d.Uint32)return[n,Number(i)];if(n===d.Uint64||n===d.Uint128||n===d.Uint256||n===d.Biguint)return[n,BigInt(i||0)];if(n===d.Bool)return[n,i==="true"];if(n===d.Address)return[n,i];if(n===d.Hex)return[n,i];if(n===d.Asset){let[s,a]=i.split(o.ArgCompositeSeparator),p={identifier:s,amount:BigInt(a)};return[n,p]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(n);if(s){let p=s.stringToNative(i);return[n,p]}let a=this.typeRegistry.resolveType(n);if(a!==n){let[p,l]=this.stringToNative(`${a}:${i}`);return[n,l]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(o.ArgParamsSeparator)){let[r,n]=t.split(o.ArgParamsSeparator);return[r,n]}return typeof t=="number"?[d.Uint32,t]:typeof t=="bigint"?[d.Uint64,t]:typeof t=="boolean"?[d.Bool,t]:[typeof t,t]}};var Tr=e=>new A().nativeToString(d.String,e),br=e=>new A().nativeToString(d.Uint8,e),Pr=e=>new A().nativeToString(d.Uint16,e),Er=e=>new A().nativeToString(d.Uint32,e),Rr=e=>new A().nativeToString(d.Uint64,e),Br=e=>new A().nativeToString(d.Biguint,e),Vr=e=>new A().nativeToString(d.Bool,e),$r=e=>new A().nativeToString(d.Address,e),At=e=>new A().nativeToString(d.Asset,e),Nr=e=>new A().nativeToString(d.Hex,e),Ur=(e,t)=>{if(t===null)return d.Option+o.ArgParamsSeparator;let r=e(t),n=r.indexOf(o.ArgParamsSeparator),i=r.substring(0,n),s=r.substring(n+1);return d.Option+o.ArgParamsSeparator+i+o.ArgParamsSeparator+s},Or=(...e)=>new A().nativeToString(d.Tuple,e),Hr=e=>new A().nativeToString(d.Struct,e),Fr=e=>new A().nativeToString(d.Vector,e);var Lt=X(require("ajv"),1);var xt=class{constructor(t){this.pendingBrand={protocol:L("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,r=!0){let n=JSON.parse(t);return r&&await this.ensureValidSchema(n),n}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,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||P.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),s=new Lt.default,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};var jt=X(require("ajv"),1);var q=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}=tt(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(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],n=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&r.push(`${s} name '${a}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(a=>a.type==="contract"),n=t.actions.some(a=>a.type==="query");if(!r&&!n)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||P.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),s=new jt.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 vt=class{constructor(t){this.config=t;this.pendingWarp={protocol:L("warp"),chain:"",name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,r=!0){let n=JSON.parse(t);return r&&await this.validate(n),n}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}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 dt(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 n=await new q(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
+ `))}};var M=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 n=JSON.parse(r,jr);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,r,n){let i={value:r,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,Lr))}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)}}},Dt=new A,Lr=(e,t)=>typeof t=="bigint"?Dt.nativeToString("biguint",t):t,jr=(e,t)=>typeof t=="string"&&t.startsWith(d.Biguint+":")?Dt.stringToNative(t)[1]:t;var R=class R{get(t){let r=R.cache.get(t);return r?Date.now()>r.expiresAt?(R.cache.delete(t),null):r.value:null}set(t,r,n){let i=Date.now()+n*1e3;R.cache.set(t,{value:r,expiresAt:i})}forget(t){R.cache.delete(t)}clear(){R.cache.clear()}};R.cache=new Map;var k=R;var Ct={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},wt={Warp:(e,t)=>`warp:${e}:${t}`,WarpAbi:(e,t)=>`warp-abi:${e}:${t}`,WarpExecutable:(e,t,r)=>`warp-exec:${e}:${t}:${r}`,RegistryInfo:(e,t)=>`registry-info:${e}:${t}`,Brand:(e,t)=>`brand:${e}:${t}`,Asset:(e,t,r)=>`asset:${e}:${t}:${r}`},z=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new M:t==="memory"?new k:typeof window<"u"&&window.localStorage?new M:new k}set(t,r,n){this.strategy.set(t,r,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var b=class{constructor(t,r){this.config=t;this.adapter=r}async apply(t,r,n={}){let i=this.applyVars(t,r,n);return await this.applyGlobals(t,i)}async applyGlobals(t,r){let n={...r};return n.actions=await Promise.all(n.actions.map(async i=>await this.applyActionGlobals(i))),n=await this.applyRootGlobals(n,t),n}applyVars(t,r,n={}){if(!r?.vars)return r;let i=S(t,this.adapter.chainInfo.name),s=JSON.stringify(r),a=(p,l)=>{s=s.replace(new RegExp(`{{${p.toUpperCase()}}}`,"g"),l.toString())};return Object.entries(r.vars).forEach(([p,l])=>{if(typeof l!="string")a(p,l);else if(l.startsWith(o.Vars.Query+o.ArgParamsSeparator)){let c=l.slice(o.Vars.Query.length+1),[u,f]=c.split(o.ArgCompositeSeparator),m=t.currentUrl?new URLSearchParams(t.currentUrl.split("?")[1]).get(u):null,w=n.queries?.[u]||null||m;w&&a(p,w)}else if(l.startsWith(o.Vars.Env+o.ArgParamsSeparator)){let c=l.slice(o.Vars.Env.length+1),[u,f]=c.split(o.ArgCompositeSeparator),g={...t.vars,...n.envs}?.[u];g&&a(p,g)}else l===o.Source.UserWallet&&i?a(p,i):a(p,l)}),JSON.parse(s)}async applyRootGlobals(t,r){let n=JSON.stringify(t),i={config:r,chain:this.adapter.chainInfo};return Object.values(o.Globals).forEach(s=>{let a=s.Accessor(i);a!=null&&(n=n.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),a.toString()))}),JSON.parse(n)}async applyActionGlobals(t){let r=JSON.stringify(t),n={config:this.config,chain:this.adapter.chainInfo};return Object.values(o.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}applyInputs(t,r,n){if(!t||typeof t!="string")return t;let i={};return r.forEach(s=>{if(!s.value||!s.input.as)return;let a=s.input.as;if(a!==a.toUpperCase())return;let[,p]=n.stringToNative(s.value);i[a]=String(p)}),E(t,i)}};var U=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 A,this.cache=new z(t.cache?.type)}getSerializer(){return this.serializer}async createExecutable(t,r,n,i={}){let s=I(t,r);if(!s)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,n),p=h(a.name,this.adapters),l=new b(this.config,p),c=await l.apply(this.config,t,i),u=I(c,r),f=this.getStringTypedInputs(u,n),m=await this.getResolvedInputs(a.name,u,f),g=this.getModifiedInputs(m),w=g.find(C=>C.input.position==="receiver"||C.input.position==="destination")?.value,W=this.getDestinationFromAction(u),y=w?this.serializer.stringToNative(w)[1]:W;if(y&&(y=l.applyInputs(y,g,this.serializer)),!y&&s.type!=="collect")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let v=this.getPreparedArgs(u,g);v=v.map(C=>l.applyInputs(C,g,this.serializer));let O=g.find(C=>C.input.position==="value")?.value||null,K="value"in u?u.value:null,F=O?.split(o.ArgParamsSeparator)[1]||K||"0",qt=l.applyInputs(F,g,this.serializer),Mt=BigInt(qt),kt=g.filter(C=>C.input.position==="transfer"&&C.value).map(C=>C.value),zt=[...("transfers"in u?u.transfers:[])||[],...kt||[]].map(C=>{let Kt=l.applyInputs(C,g,this.serializer);return this.serializer.stringToNative(Kt)[1]}),Gt=g.find(C=>C.input.position==="data")?.value,Jt="data"in u?u.data||"":null,Tt=Gt||Jt||null,Qt=Tt?l.applyInputs(Tt,g,this.serializer):null,bt={warp:c,chain:a,action:r,destination:y,args:v,value:Mt,transfers:zt,data:Qt,resolvedInputs:g};return this.cache.set(wt.WarpExecutable(this.config.env,c.meta?.hash||"",r),bt.resolvedInputs,Ct.OneWeek),bt}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 n=t.inputs||[];return r.map((i,s)=>{let a=n[s];return!a||i.includes(o.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,r,n){let i=r.inputs||[],s=await Promise.all(n.map(p=>this.preprocessInput(t,p))),a=(p,l)=>{if(p.source==="query"){let c=this.url.searchParams.get(p.name);return c?this.serializer.nativeToString(p.type,c):null}else if(p.source===o.Source.UserWallet){let c=S(this.config,t);return c?this.serializer.nativeToString("address",c):null}else return p.source==="hidden"?p.default!==void 0?this.serializer.nativeToString(p.type,p.default):null:s[l]||null};return i.map((p,l)=>{let c=a(p,l);return{input:p,value:c||(p.default!==void 0?this.serializer.nativeToString(p.type,p.default):null)}})}getModifiedInputs(t){return t.map((r,n)=>{if(r.input.modifier?.startsWith("scale:")){let[,i]=r.input.modifier.split(":");if(isNaN(Number(i))){let s=Number(t.find(l=>l.input.name===i)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let a=r.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let p=j(a,+s);return{...r,value:`${r.input.type}:${p}`}}else{let s=r.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let a=j(s,+i);return{...r,value:`${r.input.type}:${a}`}}}else return r})}async preprocessInput(t,r){try{let[n,i]=nt(r),s=h(t,this.adapters);if(n==="asset"){let[a,p,l]=i.split(o.ArgCompositeSeparator);if(l)return r;let c=await s.dataLoader.getAsset(a);if(!c)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof c.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=j(p,c.decimals);return At({...c,amount:u})}else return r}catch(n){throw x.warn("WarpFactory: Preprocess input failed",n),n}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,r){let n="args"in t?t.args||[]:[];return r.forEach(({input:i,value:s})=>{if(!s||!i.position?.startsWith("arg:"))return;let a=Number(i.position.split(":")[1])-1;n.splice(a,0,s)}),n}async tryGetChainFromInputs(t,r){let n=t.actions.find(l=>l.inputs?.some(c=>c.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(l=>l.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 G=class{constructor(t,r,n){this.config=t;this.adapters=r;this.handlers=n;this.handlers=n,this.factory=new U(t,r)}async execute(t,r,n={}){let i=[],s=null,a=[];for(let p=1;p<=t.actions.length;p++){let l=I(t,p);if(!rt(l,t))continue;let{tx:c,chain:u,immediateExecution:f}=await this.executeAction(t,p,r,n);c&&i.push(c),u&&(s=u),f&&a.push(f)}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let p=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(p))}return{txs:i,chain:s,immediateExecutions:a}}async executeAction(t,r,n,i={}){let s=I(t,r);if(s.type==="link")return await this.callHandler(async()=>{let c=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(c):pt.open(c,"_blank")}),{tx:null,chain:null,immediateExecution:null};let a=await this.factory.createExecutable(t,r,n,i);if(s.type==="collect"){let c=await this.executeCollect(a);return c.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c}):c.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c}):(this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null,immediateExecution:null})}let p=h(a.chain.name,this.adapters);if(s.type==="query"){let c=await p.executor.executeQuery(a);return c.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:c,tx:null})):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:a.chain,immediateExecution:c}}return{tx:await p.executor.createTransaction(a),chain:a.chain,immediateExecution:null}}async evaluateOutput(t,r){if(r.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=h(n.name,this.adapters),s=(await Promise.all(t.actions.map(async(a,p)=>{if(!rt(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let l=r[p],c=p+1,u=await i.output.getActionExecution(t,c,l);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:c,chain:n,execution:u,tx:l})):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 n=S(this.config,t.chain.name),i=I(t.warp,t.action),s=c=>{if(!c.value)return null;let u=this.factory.getSerializer().stringToNative(c.value)[1];if(c.input.type==="biguint")return u.toString();if(c.input.type==="asset"){let{identifier:f,amount:m}=u;return{identifier:f,amount:m.toString()}}else return u},a={};if(t.resolvedInputs.forEach(c=>{let u=c.input.as||c.input.name,f=s(c);if(c.input.position&&c.input.position.startsWith(o.Position.Payload)){let m=yt(c.input.position,u,f);a=it(a,m)}else a[u]=f}),i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,n,a,r);let{values:p,output:l}=await at(t.warp,a,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,n,"unhandled",p,l)}async doHttpRequest(t,r,n,i,s){let a=new b(this.config,h(t.chain.name,this.adapters)),p=new Headers;if(p.set("Content-Type","application/json"),p.set("Accept","application/json"),this.handlers?.onSignRequest){if(!n)throw new Error(`No wallet configured for chain ${t.chain.name}`);let{message:f,nonce:m,expiresAt:g}=await st(n,`${t.chain.name}-adapter`),w=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:f,chain:t.chain}));if(w){let W=ot(n,w,m,g);Object.entries(W).forEach(([y,v])=>p.set(y,v))}}r.headers&&Object.entries(r.headers).forEach(([f,m])=>{let g=a.applyInputs(m,t.resolvedInputs,this.factory.getSerializer());p.set(f,g)});let l=r.method||"GET",c=l==="GET"?void 0:JSON.stringify({...i,...s}),u=a.applyInputs(r.url,t.resolvedInputs,this.factory.getSerializer());x.debug("WarpExecutor: Executing HTTP collect",{url:u,method:l,headers:p,body:c});try{let f=await fetch(u,{method:l,headers:p,body:c});x.debug("Collect response status",{status:f.status});let m=await f.json();x.debug("Collect response content",{content:m});let{values:g,output:w}=await at(t.warp,m,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),f.ok?"success":"error",g,w,m)}catch(f){return x.error("WarpActionExecutor: Error executing collect",f),{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[]},output:{_DATA:f},messages:{}}}}buildCollectResult(t,r,n,i,s,a){let p=Wt(this.config,this.adapters,t.warp,t.action,s);return{status:n,warp:t.warp,action:t.action,user:r||S(this.config,t.chain.name),txHash:null,tx:null,next:p,values:i,output:a?{...s,_DATA:a}:s,messages:ht(t.warp,s,this.config)}}async callHandler(t){if(t)return await t()}};var J=class{constructor(t){this.config=t}async search(t,r,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...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 x.error("WarpIndex: Error searching for warps: ",i),i}}};var Q=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(o.HttpProtocolPrefix)?!!H(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),a=(await Promise.all(i)).filter(c=>c.match),p=a.length>0,l=a.map(c=>({url:c.url,warp:c.warp}));return{match:p,output:l}}async detect(t,r){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(o.HttpProtocolPrefix)?H(t):T(t);if(!i)return n;try{let{type:s,identifierBase:a}=i,p=null,l=null,c=null,u=h(i.chain,this.adapters),f=t.startsWith(o.HttpProtocolPrefix)?ft(t):gt(i.identifier);if(s==="hash"){p=await u.builder().createFromTransactionHash(a,r);let g=await u.registry.getInfoByHash(a,r);l=g.registryInfo,c=g.brand}else if(s==="alias"){let g=await u.registry.getInfoByAlias(a,r);l=g.registryInfo,c=g.brand,g.registryInfo&&(p=await u.builder().createFromTransactionHash(g.registryInfo.hash,r))}p&&p.meta&&(Dr(p,u.chainInfo.name,l,i.identifier),p.meta.query=f);let m=p?await new b(this.config,u).apply(this.config,p):null;return m?{match:!0,url:t,warp:m,chain:u.chainInfo.name,registryInfo:l,brand:c}:n}catch(s){return x.error("Error detecting warp link",s),n}}},Dr=(e,t,r,n)=>{e.meta&&(e.meta.identifier=r?.alias?et(t,"alias",r.alias):et(t,"hash",r?.hash??n))};var St=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 G(this.config,this.adapters,t)}async detectWarp(t,r){return new Q(this.config,this.adapters).detect(t,r)}async executeWarp(t,r,n,i={}){let s=typeof t=="object",a=!s&&t.startsWith("http")&&t.endsWith(".json"),p=s?t:null;if(!p&&a){let g=await fetch(t);if(!g.ok)throw new Error("WarpClient: executeWarp - invalid url");p=await g.json()}if(p||(p=(await this.detectWarp(t,i.cache)).warp),!p)throw new Error("Warp not found");let l=this.createExecutor(n),{txs:c,chain:u,immediateExecutions:f}=await l.execute(p,r,{queries:i.queries});return{txs:c,chain:u,immediateExecutions:f,evaluateOutput:async g=>{await l.evaluateOutput(p,g)}}}async createInscriptionTransaction(t,r){return await h(t,this.adapters).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,n=!1){return h(t,this.adapters).builder().createFromTransaction(r,n)}async createFromTransactionHash(t,r){let n=T(t);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return h(n.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,n=!1){let i=this.getDataLoader(t);return(await Promise.all(r.map(async a=>i.getAction(a,n)))).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 U(this.config,this.adapters)}get index(){return new J(this.config)}get linkBuilder(){return new $(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 D(t,this.config)}};var It=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,buildNestedPayload,bytesToBase64,bytesToHex,createAuthHeaders,createAuthMessage,createCryptoProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,evaluateOutputCommon,extractCollectOutput,extractIdentifierInfoFromUrl,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,hasInputPrefix,hex,isWarpActionAutoExecute,isWarpI18nText,mergeNestedPayload,option,parseOutputOutIndex,parseSignedMessage,replacePlaceholders,resolveWarpText,safeWindow,setCryptoProvider,shiftBigintBy,splitInput,string,struct,testCryptoAvailability,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateSignedMessage,vector});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var Ir=(l=>(l.Multiversx="multiversx",l.Vibechain="vibechain",l.Sui="sui",l.Ethereum="ethereum",l.Base="base",l.Arbitrum="arbitrum",l.Somnia="somnia",l.Fastset="fastset",l))(Ir||{}),p={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:[":","."],IdentifierParamSeparatorDefault:".",IdentifierChainDefault:"mvx",IdentifierType:{Alias:"alias",Hash:"hash"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.chain]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:n=>n.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"}},W={Option:"option",Optional:"optional",List:"list",Variadic:"variadic",Composite:"composite",String:"string",U8:"u8",U16:"u16",U32:"u32",U64:"u64",U128:"u128",U256:"u256",Biguint:"biguint",Boolean:"boolean",Address:"address",Asset:"asset",Hex:"hex"};var E={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},C={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${E.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${E.Brand}.schema.json`,DefaultClientUrl:n=>n==="devnet"?"https://devnet.usewarp.to":n==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",DefaultChainPrefix:"mvx",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 X=class{async getRandomBytes(r){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let t=new Uint8Array(r);return window.crypto.getRandomValues(t),t}},K=class{async getRandomBytes(r){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let t=await import("crypto");return new Uint8Array(t.randomBytes(r))}catch(t){throw new Error(`Node.js crypto not available: ${t instanceof Error?t.message:"Unknown error"}`)}}},R=null;function ar(){if(R)return R;if(typeof window<"u"&&window.crypto)return R=new X,R;if(typeof process<"u"&&process.versions?.node)return R=new K,R;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function zr(n){R=n}async function ir(n,r){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(r||ar()).getRandomBytes(n)}function br(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let r=new Array(n.length*2);for(let t=0;t<n.length;t++){let e=n[t];r[t*2]=(e>>>4).toString(16),r[t*2+1]=(e&15).toString(16)}return r.join("")}function kr(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 r=String.fromCharCode.apply(null,Array.from(n));return btoa(r)}else throw new Error("Base64 encoding not available in this environment")}async function sr(n,r){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let t=await ir(n/2,r);return br(t)}async function Jr(){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 ir(16),n.randomBytes=!0}catch{}return n}function Qr(){return ar()}var g=(n,r)=>{let t=r.find(e=>e.chainInfo.name.toLowerCase()===n.toLowerCase());if(!t)throw new Error(`Adapter not found for chain: ${n}`);return t},b=(n,r)=>{let t=r.find(e=>e.prefix.toLowerCase()===n.toLowerCase());if(!t)throw new Error(`Adapter not found for prefix: ${n}`);return t},D=n=>{if(n==="warp")return`warp:${E.Warp}`;if(n==="brand")return`brand:${E.Brand}`;if(n==="abi")return`abi:${E.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},P=(n,r)=>n?.actions[r-1],or=n=>(n.actions.forEach((r,t)=>{if(r.type!=="link")return{action:r,actionIndex:t}}),{action:P(n,1),actionIndex:1}),j=(n,r)=>{let t=n.toString(),[e,a=""]=t.split("."),s=Math.abs(r);if(r>0)return BigInt(e+a.padEnd(s,"0"));if(r<0){let i=e+a;if(s>=i.length)return 0n;let o=i.slice(0,-s)||"0";return BigInt(o)}else return t.includes(".")?BigInt(t.split(".")[0]):BigInt(t)},pr=(n,r=100)=>{if(!n)return"";let t=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return t=t.startsWith("- ")?t.slice(2):t,t=t.length>r?t.substring(0,t.lastIndexOf(" ",r))+"...":t,t},Z=(n,r)=>n.replace(/\{\{([^}]+)\}\}/g,(t,e)=>r[e]||""),cr=(n,r)=>{let t=Object.entries(n.messages||{}).map(([e,a])=>[e,Z(a,r)]);return Object.fromEntries(t)};var Pr=(n,r)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,Tr=n=>{let r=p.IdentifierParamSeparator,t=-1,e="";for(let a of r){let s=n.indexOf(a);s!==-1&&(t===-1||s<t)&&(t=s,e=a)}return t!==-1?{separator:e,index:t}:null},lr=n=>{let r=Tr(n);if(!r)return[n];let{separator:t,index:e}=r,a=n.substring(0,e),s=n.substring(e+t.length),i=lr(s);return[a,...i]},I=n=>{let r=decodeURIComponent(n).trim(),t=r.split("?")[0],e=lr(t);if(t.length===64&&/^[a-fA-F0-9]+$/.test(t))return{chainPrefix:p.IdentifierChainDefault,type:p.IdentifierType.Hash,identifier:r,identifierBase:t};if(e.length===2&&/^[a-zA-Z0-9]{62}$/.test(e[0])&&/^[a-zA-Z0-9]{2}$/.test(e[1]))return null;if(e.length===3){let[a,s,i]=e;if(s===p.IdentifierType.Alias||s===p.IdentifierType.Hash){let o=r.includes("?")?i+r.substring(r.indexOf("?")):i;return{chainPrefix:a,type:s,identifier:o,identifierBase:i}}}if(e.length===2){let[a,s]=e;if(a===p.IdentifierType.Alias||a===p.IdentifierType.Hash){let i=r.includes("?")?s+r.substring(r.indexOf("?")):s;return{chainPrefix:p.IdentifierChainDefault,type:a,identifier:i,identifierBase:s}}}if(e.length===2){let[a,s]=e;if(a!==p.IdentifierType.Alias&&a!==p.IdentifierType.Hash){let i=r.includes("?")?s+r.substring(r.indexOf("?")):s,o=Pr(s,a)?p.IdentifierType.Hash:p.IdentifierType.Alias;return{chainPrefix:a,type:o,identifier:i,identifierBase:s}}}return{chainPrefix:p.IdentifierChainDefault,type:p.IdentifierType.Alias,identifier:r,identifierBase:t}},H=n=>{let r=new URL(n),e=r.searchParams.get(p.IdentifierParamName);if(e||(e=r.pathname.split("/")[1]),!e)return null;let a=decodeURIComponent(e);return I(a)};var _=n=>{let[r,...t]=n.split(/:(.*)/,2);return[r,t[0]||""]},tt=n=>{let r=new Set(Object.values(W));if(!n.includes(p.ArgParamsSeparator))return!1;let t=_(n)[0];return r.has(t)};import Sr from"qr-code-styling";var B=class{constructor(r,t){this.config=r;this.adapters=t}isValid(r){return r.startsWith(p.HttpProtocolPrefix)?!!H(r):!1}build(r,t,e){let a=this.config.clientUrl||C.DefaultClientUrl(this.config.env),s=g(r,this.adapters),i=t===p.IdentifierType.Alias?e:t+p.IdentifierParamSeparatorDefault+e,o=s.prefix+p.IdentifierParamSeparatorDefault+i,l=encodeURIComponent(o);return C.SuperClientUrls.includes(a)?`${a}/${l}`:`${a}?${p.IdentifierParamName}=${l}`}buildFromPrefixedIdentifier(r){let t=I(r);if(!t)return null;let e=b(t.chainPrefix,this.adapters);return e?this.build(e.chainInfo.name,t.type,t.identifierBase):null}generateQrCode(r,t,e,a=512,s="white",i="black",o="#23F7DD"){let l=g(r,this.adapters),c=this.build(l.chainInfo.name,t,e);return new Sr({type:"svg",width:a,height:a,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},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 Rr="https://",ur=(n,r,t,e,a)=>{let s=t.actions?.[e]?.next||t.next||null;if(!s)return null;if(s.startsWith(Rr))return[{identifier:null,url:s}];let[i,o]=s.split("?");if(!o)return[{identifier:i,url:Y(r,i,n)}];let l=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let h=Z(o,{...t.vars,...a}),m=h?`${i}?${h}`:i;return[{identifier:m,url:Y(r,m,n)}]}let c=l[0];if(!c)return[];let u=c.match(/{{([^[]+)\[\]/),d=u?u[1]:null;if(!d||a[d]===void 0)return[];let f=Array.isArray(a[d])?a[d]:[a[d]];if(f.length===0)return[];let y=l.filter(h=>h.includes(`{{${d}[]`)).map(h=>{let m=h.match(/\[\](\.[^}]+)?}}/),S=m&&m[1]||"";return{placeholder:h,field:S?S.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(h=>{let m=o;for(let{regex:Q,field:F}of y){let O=F?Er(h,F):h;if(O==null)return null;m=m.replace(Q,O)}if(m.includes("{{")||m.includes("}}"))return null;let S=m?`${i}?${m}`:i;return{identifier:S,url:Y(r,S,n)}}).filter(h=>h!==null)},Y=(n,r,t)=>{let[e,a]=r.split("?"),s=I(e)||{chainPrefix:C.DefaultChainPrefix,type:"alias",identifier:e,identifierBase:e},i=b(s.chainPrefix,n);if(!i)throw new Error(`Adapter not found for chain ${s.chainPrefix}`);let o=new B(t,n).build(i.chainInfo.name,s.type,s.identifierBase);if(!a)return o;let l=new URL(o);return new URLSearchParams(a).forEach((c,u)=>l.searchParams.set(u,c)),l.toString().replace(/\/\?/,"?")},Er=(n,r)=>r.split(".").reduce((t,e)=>t?.[e],n);function dr(n,r,t){return n.startsWith(p.Position.Payload)?n.slice(p.Position.Payload.length).split(".").reduceRight((e,a,s,i)=>({[a]:s===i.length-1?{[r]:t}:e}),{}):{[r]:t}}function rr(n,r){if(!n)return{...r};if(!r)return{...n};let t={...n};return Object.keys(r).forEach(e=>{t[e]&&typeof t[e]=="object"&&typeof r[e]=="object"?t[e]=rr(t[e],r[e]):t[e]=r[e]}),t}var mt=(n,r,t,e)=>{let a=n.providers?.[r];return a?.[t]?a[t]:e},yt=(n,r)=>n.providers?.[r];var $=class ${static info(...r){$.isTestEnv||console.info(...r)}static warn(...r){$.isTestEnv||console.warn(...r)}static error(...r){$.isTestEnv||console.error(...r)}};$.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var v=$;var A=class{setTypeRegistry(r){this.typeRegistry=r}nativeToString(r,t){if(r==="asset"&&typeof t=="object"&&t&&"identifier"in t&&"amount"in t)return`${r}:${t.identifier}|${t.amount.toString()}`;if(this.typeRegistry?.hasType(r)){let e=this.typeRegistry.getHandler(r);if(e)return e.nativeToString(t)}return`${r}:${t?.toString()??""}`}stringToNative(r){let t=r.split(p.ArgParamsSeparator),e=t[0],a=t.slice(1).join(p.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[s,i]=a.split(p.ArgParamsSeparator);return[`option:${s}`,i||null]}else if(e==="optional"){let[s,i]=a.split(p.ArgParamsSeparator);return[`optional:${s}`,i||null]}else if(e==="list"){let s=a.split(p.ArgParamsSeparator),i=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`list:${i}`,c]}else if(e==="variadic"){let s=a.split(p.ArgParamsSeparator),i=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`variadic:${i}`,c]}else if(e.startsWith("composite")){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=a.split(p.ArgCompositeSeparator).map((l,c)=>this.stringToNative(`${s[c]}:${l}`)[1]);return[e,o]}else{if(e==="string")return[e,a];if(e==="uint8"||e==="uint16"||e==="uint32")return[e,Number(a)];if(e==="uint64"||e==="biguint")return[e,BigInt(a||0)];if(e==="bool")return[e,a==="true"];if(e==="address")return[e,a];if(e==="token")return[e,a];if(e==="hex")return[e,a];if(e==="codemeta")return[e,a];if(e==="asset"){let[s,i]=a.split(p.ArgCompositeSeparator),o={identifier:s,amount:BigInt(i)};return[e,o]}}if(this.typeRegistry?.hasType(e)){let s=this.typeRegistry.getHandler(e);if(s){let i=s.stringToNative(a);return[e,i]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}};var fr=async(n,r,t,e,a)=>{let s=[],i={};for(let[o,l]of Object.entries(n.results||{})){if(l.startsWith(p.Transform.Prefix))continue;let c=Ur(l);if(c!==null&&c!==t){i[o]=null;continue}let[u,...d]=l.split("."),f=(y,w)=>w.reduce((h,m)=>h&&h[m]!==void 0?h[m]:null,y);if(u==="out"||u.startsWith("out[")){let y=d.length===0?r?.data||r:f(r,d);s.push(y),i[o]=y}else i[o]=l}return{values:s,results:await Br(n,i,t,e,a)}},Br=async(n,r,t,e,a)=>{if(!n.results)return r;let s={...r};return s=$r(s,n,t,e),s=await Nr(n,s,a),s},$r=(n,r,t,e)=>{let a={...n},s=P(r,t)?.inputs||[],i=new A;for(let[o,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("input.")){let c=l.split(".")[1],u=s.findIndex(f=>f.as===c||f.name===c),d=u!==-1?e[u]?.value:null;a[o]=d?i.stringToNative(d)[1]:null}return a},Nr=async(n,r,t)=>{if(!n.results)return r;let e={...r},a=Object.entries(n.results).filter(([,s])=>s.startsWith(p.Transform.Prefix)).map(([s,i])=>({key:s,code:i.substring(p.Transform.Prefix.length)}));if(a.length>0&&(!t||typeof t.run!="function"))throw new Error("Transform results are defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:s,code:i}of a)try{e[s]=await t.run(i,e)}catch(o){v.error(`Transform error for result '${s}':`,o),e[s]=null}return e},Ur=n=>{if(n==="out")return 1;let r=n.match(/^out\[(\d+)\]/);return r?parseInt(r[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};async function Hr(n,r,t,e=5){let a=await sr(64,t),s=new Date(Date.now()+e*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:a,expiresAt:s,purpose:r}),nonce:a,expiresAt:s}}async function tr(n,r,t,e){let a=e||`prove-wallet-ownership for app "${r}"`;return Hr(n,a,t,5)}function er(n,r,t,e){return{"X-Signer-Wallet":n,"X-Signer-Signature":r,"X-Signer-Nonce":t,"X-Signer-ExpiresAt":e}}async function Rt(n,r,t,e){let{message:a,nonce:s,expiresAt:i}=await tr(n,t,e),o=await r(a);return er(n,o,s,i)}function Et(n){let r=new Date(n).getTime();return Date.now()<r}function Bt(n){try{let r=JSON.parse(n);if(!r.wallet||!r.nonce||!r.expiresAt||!r.purpose)throw new Error("Invalid signed message: missing required fields");return r}catch(r){throw new Error(`Failed to parse signed message: ${r instanceof Error?r.message:"Unknown error"}`)}}var Ut=n=>W.String+p.ArgParamsSeparator+n,Ht=n=>W.U8+p.ArgParamsSeparator+n,Vt=n=>W.U16+p.ArgParamsSeparator+n,Lt=n=>W.U32+p.ArgParamsSeparator+n,Ft=n=>W.U64+p.ArgParamsSeparator+n,Ot=n=>W.Biguint+p.ArgParamsSeparator+n,Dt=n=>W.Boolean+p.ArgParamsSeparator+n,jt=n=>W.Address+p.ArgParamsSeparator+n,gr=n=>{let t=W.Asset+p.ArgParamsSeparator+n.identifier+p.ArgCompositeSeparator+n.amount;return n.decimals?t+p.ArgCompositeSeparator+n.decimals:t},Mt=n=>W.Hex+p.ArgParamsSeparator+n;import Vr from"ajv";var hr=class{constructor(r){this.pendingBrand={protocol:D("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}setName(r){return this.pendingBrand.name=r,this}setDescription(r){return this.pendingBrand.description=r,this}setLogo(r){return this.pendingBrand.logo=r,this}setUrls(r){return this.pendingBrand.urls=r,this}setColors(r){return this.pendingBrand.colors=r,this}setCta(r){return this.pendingBrand.cta=r,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(r,t){if(!r)throw new Error(`Warp: ${t}`)}async ensureValidSchema(r){let t=this.config.schema?.brand||C.LatestBrandSchemaUrl,a=await(await fetch(t)).json(),s=new Vr,i=s.compile(a);if(!i(r))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(i.errors)}`)}};import Lr from"ajv";var M=class{constructor(r){this.config=r;this.config=r}async validate(r){let t=[];return t.push(...this.validateMaxOneValuePosition(r)),t.push(...this.validateVariableNamesAndResultNamesUppercase(r)),t.push(...this.validateAbiIsSetIfApplicable(r)),t.push(...await this.validateSchema(r)),{valid:t.length===0,errors:t}}validateMaxOneValuePosition(r){return r.actions.filter(e=>e.inputs?e.inputs.some(a=>a.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let t=[],e=(a,s)=>{a&&Object.keys(a).forEach(i=>{i!==i.toUpperCase()&&t.push(`${s} name '${i}' must be uppercase`)})};return e(r.vars,"Variable"),e(r.results,"Result"),t}validateAbiIsSetIfApplicable(r){let t=r.actions.some(i=>i.type==="contract"),e=r.actions.some(i=>i.type==="query");if(!t&&!e)return[];let a=r.actions.some(i=>i.abi),s=Object.values(r.results||{}).some(i=>i.startsWith("out.")||i.startsWith("event."));return r.results&&!a&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let t=this.config.schema?.warp||C.LatestWarpSchemaUrl,a=await(await fetch(t)).json(),s=new Lr({strict:!1}),i=s.compile(a);return i(r)?[]:[`Schema validation failed: ${s.errorsText(i.errors)}`]}catch(t){return[`Schema validation failed: ${t instanceof Error?t.message:String(t)}`]}}};var mr=class{constructor(r){this.config=r;this.pendingWarp={protocol:D("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.validate(e),e}async createFromUrl(r){return await(await fetch(r)).json()}setName(r){return this.pendingWarp.name=r,this}setTitle(r){return this.pendingWarp.title=r,this}setDescription(r){return this.pendingWarp.description=r,this}setPreview(r){return this.pendingWarp.preview=r,this}setActions(r){return this.pendingWarp.actions=r,this}addAction(r){return this.pendingWarp.actions.push(r),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(r,t=100){return pr(r,t)}ensure(r,t){if(!r)throw new Error(t)}async validate(r){let e=await new M(this.config).validate(r);if(!e.valid)throw new Error(e.errors.join(`
2
- `))}};var V=class{constructor(r="warp-cache"){this.prefix=r}getKey(r){return`${this.prefix}:${r}`}get(r){try{let t=localStorage.getItem(this.getKey(r));if(!t)return null;let e=JSON.parse(t,Or);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(r)),null):e.value}catch{return null}}set(r,t,e){let a={value:t,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(r),JSON.stringify(a,Fr))}forget(r){localStorage.removeItem(this.getKey(r))}clear(){for(let r=0;r<localStorage.length;r++){let t=localStorage.key(r);t?.startsWith(this.prefix)&&localStorage.removeItem(t)}}},yr=new A,Fr=(n,r)=>typeof r=="bigint"?yr.nativeToString("biguint",r):r,Or=(n,r)=>typeof r=="string"&&r.startsWith(W.Biguint+":")?yr.stringToNative(r)[1]:r;var T=class T{get(r){let t=T.cache.get(r);return t?Date.now()>t.expiresAt?(T.cache.delete(r),null):t.value:null}set(r,t,e){let a=Date.now()+e*1e3;T.cache.set(r,{value:t,expiresAt:a})}forget(r){T.cache.delete(r)}clear(){T.cache.clear()}};T.cache=new Map;var L=T;var Wr={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},vr={Warp:(n,r)=>`warp:${n}:${r}`,WarpAbi:(n,r)=>`warp-abi:${n}:${r}`,WarpExecutable:(n,r,t)=>`warp-exec:${n}:${r}:${t}`,RegistryInfo:(n,r)=>`registry-info:${n}:${r}`,Brand:(n,r)=>`brand:${n}:${r}`,Asset:(n,r,t)=>`asset:${n}:${r}:${t}`},q=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new V:r==="memory"?new L:typeof window<"u"&&window.localStorage?new V:new L}set(r,t,e){this.strategy.set(r,t,e)}get(r){return this.strategy.get(r)}forget(r){this.strategy.forget(r)}clear(){this.strategy.clear()}};var N=class{constructor(r,t){this.config=r;this.adapter=t}async apply(r,t,e){let a=this.applyVars(r,t,e);return await this.applyGlobals(r,a)}async applyGlobals(r,t){let e={...t};return e.actions=await Promise.all(e.actions.map(async a=>await this.applyActionGlobals(a))),e=await this.applyRootGlobals(e,r),e}applyVars(r,t,e){if(!t?.vars)return t;let a=JSON.stringify(t),s=(i,o)=>{a=a.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([i,o])=>{if(typeof o!="string")s(i,o);else if(o.startsWith(`${p.Vars.Query}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let l=o.split(`${p.Vars.Query}:`)[1],c=new URLSearchParams(r.currentUrl.split("?")[1]).get(l);c&&s(i,c)}else if(o.startsWith(`${p.Vars.Env}:`)){let l=o.split(`${p.Vars.Env}:`)[1],u={...r.vars,...e}?.[l];u&&s(i,u)}else if(o===p.Source.UserWallet&&r.user?.wallets?.[this.adapter.chainInfo.name]){let l=r.user.wallets[this.adapter.chainInfo.name];l&&s(i,l)}else s(i,o)}),JSON.parse(a)}async applyRootGlobals(r,t){let e=JSON.stringify(r),a={config:t,chain:this.adapter.chainInfo.name,chainInfo:this.adapter.chainInfo};return Object.values(p.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}async applyActionGlobals(r){let t=r.chain?this.adapter.chainInfo:this.adapter.chainInfo;if(!t)throw new Error(`Chain info not found for ${r.chain}`);let e=JSON.stringify(r),a={config:this.config,chain:this.adapter.chainInfo.name,chainInfo:t};return Object.values(p.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}};var G=class{constructor(){this.typeHandlers=new Map}registerType(r,t){this.typeHandlers.set(r,t)}hasType(r){return this.typeHandlers.has(r)}getHandler(r){return this.typeHandlers.get(r)}getRegisteredTypes(){return Array.from(this.typeHandlers.keys())}};var U=class{constructor(r,t){this.config=r;this.adapters=t;if(!r.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(r.currentUrl),this.serializer=new A,this.cache=new q(r.cache?.type);let e=new G;this.serializer.setTypeRegistry(e);for(let a of t)a.registerTypes&&a.registerTypes(e)}async createExecutable(r,t,e,a){let s=P(r,t);if(!s)throw new Error("WarpFactory: Action not found");let i=await this.getChainInfoForAction(s,e),o=g(i.name,this.adapters),l=await new N(this.config,o).apply(this.config,r,a),c=P(l,t),u=await this.getResolvedInputs(i.name,c,e),d=this.getModifiedInputs(u),f=d.find(x=>x.input.position==="receiver")?.value,y=this.getDestinationFromAction(c),w=f?this.serializer.stringToNative(f)[1]:y;if(!w)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let h=this.getPreparedArgs(c,d),m=d.find(x=>x.input.position==="value")?.value||null,S="value"in c?c.value:null,Q=BigInt(m?.split(":")[1]||S||0),F=d.filter(x=>x.input.position==="transfer"&&x.value).map(x=>x.value),Ar=[...("transfers"in c?c.transfers:[])||[],...F||[]].map(x=>this.serializer.stringToNative(x)[1]),wr=d.find(x=>x.input.position==="data")?.value,Cr="data"in c?c.data||"":null,nr={warp:l,chain:i,action:t,destination:w,args:h,value:Q,transfers:Ar,data:wr||Cr||null,resolvedInputs:d};return this.cache.set(vr.WarpExecutable(this.config.env,l.meta?.hash||"",t),nr.resolvedInputs,Wr.OneWeek),nr}async getChainInfoForAction(r,t){if(r.chain)return g(r.chain,this.adapters).chainInfo;if(t){let a=await this.tryGetChainFromInputs(r,t);if(a)return a}return this.adapters[0].chainInfo}async getResolvedInputs(r,t,e){let a=t.inputs||[],s=await Promise.all(e.map(o=>this.preprocessInput(r,o))),i=(o,l)=>{if(o.source==="query"){let c=this.url.searchParams.get(o.name);return c?this.serializer.nativeToString(o.type,c):null}else return o.source===p.Source.UserWallet?this.config.user?.wallets?.[r]?this.serializer.nativeToString("address",this.config.user.wallets[r]):null:o.source==="hidden"?o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null:s[l]||null};return a.map((o,l)=>{let c=i(o,l);return{input:o,value:c||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(r){return r.map((t,e)=>{if(t.input.modifier?.startsWith("scale:")){let[,a]=t.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(r.find(l=>l.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let i=t.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let o=j(i,+s);return{...t,value:`${t.input.type}:${o}`}}else{let s=t.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let i=j(s,+a);return{...t,value:`${t.input.type}:${i}`}}}else return t})}async preprocessInput(r,t){try{let[e,a]=_(t),s=g(r,this.adapters);if(e==="asset"){let[i,o,l]=a.split(p.ArgCompositeSeparator);if(l)return t;let c=await s.dataLoader.getAsset(i);if(!c)throw new Error(`WarpFactory: Asset not found for asset ${i}`);if(typeof c.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${i}`);let u=j(o,c.decimals);return gr({...c,amount:u})}else return t}catch(e){throw v.warn("WarpFactory: Preprocess input failed",e),e}}getDestinationFromAction(r){return"address"in r&&r.address?r.address:"destination"in r&&r.destination?.url?r.destination.url:null}getPreparedArgs(r,t){let e="args"in r?r.args||[]:[];return t.forEach(({input:a,value:s})=>{if(!s||!a.position?.startsWith("arg:"))return;let i=Number(a.position.split(":")[1])-1;e.splice(i,0,s)}),e}async tryGetChainFromInputs(r,t){let e=r.inputs?.findIndex(l=>l.position==="chain");if(e===-1||e===void 0)return null;let a=t[e];if(!a)throw new Error("Chain input not found");let i=new A().stringToNative(a)[1];return g(i,this.adapters).chainInfo}};var z=class{constructor(r,t,e){this.config=r;this.adapters=t;this.handlers=e;this.handlers=e,this.factory=new U(r,t),this.serializer=new A}async execute(r,t,e){let{action:a,actionIndex:s}=or(r),i=await this.factory.createExecutable(r,s,t,e);if(a.type==="collect"){let c=await this.executeCollect(i);return c.success?this.handlers?.onExecuted?.(c):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null}}let o=g(i.chain.name,this.adapters);if(a.type==="query"){let c=await o.executor.executeQuery(i);return c.success?this.handlers?.onExecuted?.(c):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:i.chain}}return{tx:await o.executor.createTransaction(i),chain:i.chain}}async evaluateResults(r,t,e){let a=await g(t,this.adapters).results.getTransactionExecutionResults(r,e);this.handlers?.onExecuted?.(a)}async executeCollect(r,t){let e=this.config.user?.wallets?.[r.chain.name]||null,a=P(r.warp,r.action),s=u=>{if(!u.value)return null;let d=this.serializer.stringToNative(u.value)[1];if(u.input.type==="biguint")return d.toString();if(u.input.type==="asset"){let{identifier:f,amount:y}=d;return{identifier:f,amount:y.toString()}}else return d},i=new Headers;if(i.set("Content-Type","application/json"),i.set("Accept","application/json"),this.handlers?.onSignRequest){if(!e)throw new Error(`No wallet configured for chain ${r.chain.name}`);let{message:u,nonce:d,expiresAt:f}=await tr(e,`${r.chain.name}-adapter`),y=await this.handlers.onSignRequest({message:u,chain:r.chain}),w=er(e,y,d,f);Object.entries(w).forEach(([h,m])=>i.set(h,m))}Object.entries(a.destination.headers||{}).forEach(([u,d])=>{i.set(u,d)});let o={};r.resolvedInputs.forEach(u=>{let d=u.input.as||u.input.name,f=s(u);if(u.input.position&&u.input.position.startsWith(p.Position.Payload)){let y=dr(u.input.position,d,f);o=rr(o,y)}else o[d]=f});let l=a.destination.method||"GET",c=l==="GET"?void 0:JSON.stringify({...o,...t});v.info("Executing collect",{url:a.destination.url,method:l,headers:i,body:c});try{let u=await fetch(a.destination.url,{method:l,headers:i,body:c});v.info("Collect response",{response:u});let d=await u.json(),{values:f,results:y}=await fr(r.warp,d,r.action,r.resolvedInputs,this.config.transform?.runner),w=ur(this.config,this.adapters,r.warp,r.action,y);return{success:u.ok,warp:r.warp,action:r.action,user:this.config.user?.wallets?.[r.chain.name]||null,txHash:null,tx:null,next:w,values:f,valuesRaw:[],results:{...y,_DATA:d},messages:cr(r.warp,y)}}catch(u){return v.error("WarpActionExecutor: Error executing collect",u),{success:!1,warp:r.warp,action:r.action,user:e,txHash:null,tx:null,next:null,values:[],valuesRaw:[],results:{_DATA:u},messages:{}}}}};var k=class{constructor(r){this.config=r}async search(r,t,e){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let a=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"]:r,...t})});if(!a.ok)throw new Error(`WarpIndex: search failed with status ${a.status}`);return(await a.json()).hits}catch(a){throw v.error("WarpIndex: Error searching for warps: ",a),a}}};var J=class{constructor(r,t){this.config=r;this.adapters=t}isValid(r){return r.startsWith(p.HttpProtocolPrefix)?!!H(r):!1}async detectFromHtml(r){if(!r.length)return{match:!1,results:[]};let a=[...r.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),i=(await Promise.all(a)).filter(c=>c.match),o=i.length>0,l=i.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:l}}async detect(r,t){let e={match:!1,url:r,warp:null,chain:null,registryInfo:null,brand:null},a=r.startsWith(p.HttpProtocolPrefix)?H(r):I(r);if(!a)return e;try{let{type:s,identifierBase:i}=a,o=null,l=null,c=null,u=b(a.chainPrefix,this.adapters);if(s==="hash"){o=await u.builder().createFromTransactionHash(i,t);let f=await u.registry.getInfoByHash(i,t);l=f.registryInfo,c=f.brand}else if(s==="alias"){let f=await u.registry.getInfoByAlias(i,t);l=f.registryInfo,c=f.brand,f.registryInfo&&(o=await u.builder().createFromTransactionHash(f.registryInfo.hash,t))}let d=o?await new N(this.config,u).apply(this.config,o):null;return d?{match:!0,url:r,warp:d,chain:u.chainInfo.name,registryInfo:l,brand:c}:e}catch(s){return v.error("Error detecting warp link",s),e}}};var xr=class{constructor(r,t){this.config=r;this.adapters=t}getConfig(){return this.config}getAdapters(){return this.adapters}addAdapter(r){return this.adapters.push(r),this}createExecutor(r){return new z(this.config,this.adapters,r)}async detectWarp(r,t){return new J(this.config,this.adapters).detect(r,t)}async executeWarp(r,t,e,a={}){let s=typeof r=="object",i=!s&&r.startsWith("http")&&r.endsWith(".json"),o=s?r:null;if(!o&&i&&(o=await(await fetch(r)).json()),o||(o=(await this.detectWarp(r,a.cache)).warp),!o)throw new Error("Warp not found");let l=this.createExecutor(e),{tx:c,chain:u}=await l.execute(o,t);return{tx:c,chain:u,evaluateResults:async f=>{if(!u||!c||!o)throw new Error("Warp not found");await l.evaluateResults(o,u.name,f)}}}createInscriptionTransaction(r,t){return g(r,this.adapters).builder().createInscriptionTransaction(t)}async createFromTransaction(r,t,e=!1){return g(r,this.adapters).builder().createFromTransaction(t,e)}async createFromTransactionHash(r,t){let e=I(r);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return b(e.chainPrefix,this.adapters).builder().createFromTransactionHash(r,t)}async signMessage(r,t,e){if(!this.config.user?.wallets?.[r])throw new Error(`No wallet configured for chain ${r}`);return g(r,this.adapters).executor.signMessage(t,e)}getExplorer(r){return g(r,this.adapters).explorer}getResults(r){return g(r,this.adapters).results}async getRegistry(r){let t=g(r,this.adapters).registry;return await t.init(),t}getDataLoader(r){return g(r,this.adapters).dataLoader}get factory(){return new U(this.config,this.adapters)}get index(){return new k(this.config)}get linkBuilder(){return new B(this.config,this.adapters)}createBuilder(r){return g(r,this.adapters).builder()}createAbiBuilder(r){return g(r,this.adapters).abiBuilder()}createBrandBuilder(r){return g(r,this.adapters).brandBuilder()}};export{X as BrowserCryptoProvider,Wr as CacheTtl,K as NodeCryptoProvider,hr as WarpBrandBuilder,mr as WarpBuilder,q as WarpCache,vr as WarpCacheKey,Ir as WarpChainName,xr as WarpClient,C as WarpConfig,p as WarpConstants,z as WarpExecutor,U as WarpFactory,k as WarpIndex,W as WarpInputTypes,N as WarpInterpolator,B as WarpLinkBuilder,J as WarpLinkDetecter,v as WarpLogger,E as WarpProtocolVersions,A as WarpSerializer,G as WarpTypeRegistryImpl,M as WarpValidator,jt as address,cr as applyResultsToMessages,gr as asset,Ot as biguint,Dt as boolean,dr as buildNestedPayload,kr as bytesToBase64,br as bytesToHex,er as createAuthHeaders,tr as createAuthMessage,Qr as createCryptoProvider,Rt as createHttpAuthHeaders,Hr as createSignableMessage,Br as evaluateResultsCommon,fr as extractCollectResults,H as extractIdentifierInfoFromUrl,b as findWarpAdapterByPrefix,g as findWarpAdapterForChain,or as findWarpExecutableAction,ar as getCryptoProvider,D as getLatestProtocolIdentifier,ur as getNextInfo,yt as getProviderConfig,mt as getProviderUrl,ir as getRandomBytes,sr as getRandomHex,P as getWarpActionByIndex,I as getWarpInfoFromIdentifier,tt as hasInputPrefix,Mt as hex,rr as mergeNestedPayload,Ur as parseResultsOutIndex,Bt as parseSignedMessage,Z as replacePlaceholders,zr as setCryptoProvider,j as shiftBigintBy,_ as splitInput,Ut as string,Jr as testCryptoAvailability,pr as toPreviewText,Vt as u16,Lt as u32,Ft as u64,Ht as u8,Et as validateSignedMessage};
1
+ var Ot=(l=>(l.Multiversx="multiversx",l.Vibechain="vibechain",l.Sui="sui",l.Ethereum="ethereum",l.Base="base",l.Arbitrum="arbitrum",l.Somnia="somnia",l.Fastset="fastset",l))(Ot||{}),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.chain.name]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chain.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:n=>n.chain.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"},ct=typeof window<"u"?window:{open:()=>{}};var N={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},E={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${N.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${N.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 pr=(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 lr=(n,t)=>typeof n.logo=="string"?n.logo:n.logo[t?.scheme??"light"];var _=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}},X=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"}`)}}},R=null;function lt(){if(R)return R;if(typeof window<"u"&&window.crypto)return R=new _,R;if(typeof process<"u"&&process.versions?.node)return R=new X,R;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function dr(n){R=n}async function ut(n,t){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(t||lt()).getRandomBytes(n)}function Ht(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 fr(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 dt(n,t){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let r=await ut(n/2,t);return Ht(r)}async function gr(){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 ut(16),n.randomBytes=!0}catch{}return n}function hr(){return lt()}var yr=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},q=n=>{if(n==="warp")return`warp:${N.Warp}`;if(n==="brand")return`brand:${N.Brand}`;if(n==="abi")return`abi:${N.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},I=(n,t)=>n?.actions[t-1],Z=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}},Y=(n,t)=>{if(n.auto===!1)return!1;if(n.type==="link"){if(n.auto===!0)return!0;let{action:r}=Z(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)},ft=(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},B=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||"");var Cr={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"},k=(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""},wr=n=>typeof n=="object"&&n!==null&&Object.keys(n).length>0,Sr=n=>n;var tt=(n,t,r)=>{let e=r.startsWith(p.IdentifierAliasMarker)?r.replace(p.IdentifierAliasMarker,""):r;return t===p.IdentifierType.Alias?p.IdentifierAliasMarker+n+p.IdentifierParamSeparator+e:n+p.IdentifierParamSeparator+t+p.IdentifierParamSeparator+e},T=n=>{let r=decodeURIComponent(n).trim().replace(p.IdentifierAliasMarker,""),e=r.split("?")[0],i=gt(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 l=r.includes("?")?o+r.substring(r.indexOf("?")):o;return{chain:s,type:a,identifier:l,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,l=Ft(a,s)?p.IdentifierType.Hash:p.IdentifierType.Alias;return{chain:s,type:l,identifier:o,identifierBase:a}}}return{chain:p.IdentifierChainDefault,type:p.IdentifierType.Alias,identifier:r,identifierBase:e}},F=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)},Ft=(n,t)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,Lt=n=>{let t=p.IdentifierParamSeparator,r=n.indexOf(t);return r!==-1?{separator:t,index:r}:null},gt=n=>{let t=Lt(n);if(!t)return[n];let{separator:r,index:e}=t,i=n.substring(0,e),s=n.substring(e+r.length),a=gt(s);return[i,...a]},ht=n=>{try{let t=new URL(n),r=new URLSearchParams(t.search);return r.delete(p.IdentifierParamName),r.toString()||null}catch{return null}},mt=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 rt=n=>{let[t,...r]=n.split(/:(.*)/,2);return[t,r[0]||""]},Er=n=>{let t=new Set(Object.values(d));if(!n.includes(p.ArgParamsSeparator))return!1;let r=rt(n)[0];return t.has(r)};var Wt=(n,t,r)=>{let e=Object.entries(n.messages||{}).map(([i,s])=>{let a=k(s,r);return[i,B(a,t)]});return Object.fromEntries(e)};import jt from"qr-code-styling";var U=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!F(t):!1}build(t,r,e){let i=this.config.clientUrl||E.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,l=encodeURIComponent(o);return E.SuperClientUrls.includes(i)?`${i}/${l}`:`${i}?${p.IdentifierParamName}=${l}`}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 l=m(t,this.adapters),c=this.build(l.chainInfo.name,r,e);return new jt({type:"svg",width:i,height:i,data:String(c),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 Dt="https://",yt=(n,t,r,e,i)=>{let s=r.actions?.[e-1]?.next||r.next||null;if(!s)return null;if(s.startsWith(Dt))return[{identifier:null,url:s}];let[a,o]=s.split("?");if(!o){let W=B(a,{...r.vars,...i});return[{identifier:W,url:et(t,W,n)}]}let l=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(l.length===0){let W=B(o,{...r.vars,...i}),y=W?`${a}?${W}`:a;return[{identifier:y,url:et(t,y,n)}]}let c=l[0];if(!c)return[];let u=c.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 g=l.filter(W=>W.includes(`{{${f}[]`)).map(W=>{let y=W.match(/\[\](\.[^}]+)?}}/),x=y&&y[1]||"";return{placeholder:W,field:x?x.slice(1):"",regex:new RegExp(W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(W=>{let y=o;for(let{regex:$,field:D}of g){let H=D?qt(W,D):W;if(H==null)return null;y=y.replace($,H)}if(y.includes("{{")||y.includes("}}"))return null;let x=y?`${a}?${y}`:a;return{identifier:x,url:et(t,x,n)}}).filter(W=>W!==null)},et=(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 U(r,n).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return o;let l=new URL(o);return new URLSearchParams(i).forEach((c,u)=>l.searchParams.set(u,c)),l.toString().replace(/\/\?/,"?")},qt=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);function At(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 nt(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]=nt(r[e],t[e]):r[e]=t[e]}),r}var Jr=(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 V=class V{static debug(...t){V.isTestEnv||console.debug(...t)}static info(...t){V.isTestEnv||console.info(...t)}static warn(...t){V.isTestEnv||console.warn(...t)}static error(...t){V.isTestEnv||console.error(...t)}};V.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=V;var it=async(n,t,r,e,i,s)=>{let a=[],o=[],l={};for(let[c,u]of Object.entries(n.output||{})){if(u.startsWith(p.Transform.Prefix))continue;let f=Gt(u);if(f!==null&&f!==r){l[c]=null;continue}let[h,...g]=u.split("."),w=(W,y)=>y.reduce((x,$)=>x&&x[$]!==void 0?x[$]:null,W);if(h==="out"||h.startsWith("out[")){let W=g.length===0?t?.data||t:w(t,g);a.push(String(W)),o.push(W),l[c]=W}else l[c]=u}return{values:{string:a,native:o},output:await Mt(n,l,r,e,i,s)}},Mt=async(n,t,r,e,i,s)=>{if(!n.output)return t;let a={...t};return a=kt(a,n,r,e,i),a=await zt(n,a,s.transform?.runner||null),a},kt=(n,t,r,e,i)=>{let s={...n},a=I(t,r)?.inputs||[];for(let[o,l]of Object.entries(s))if(typeof l=="string"&&l.startsWith("in.")){let c=l.split(".")[1],u=a.findIndex(h=>h.as===c||h.name===c),f=u!==-1?e[u]?.value:null;s[o]=f?i.stringToNative(f)[1]:null}return s},zt=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},Gt=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 dt(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 at(n,t,r,e){let i=e||`prove-wallet-ownership for app "${t}"`;return Jt(n,i,r,5)}function st(n,t,r,e){return{"X-Signer-Wallet":n,"X-Signer-Signature":t,"X-Signer-Nonce":r,"X-Signer-ExpiresAt":e}}async function ee(n,t,r,e){let{message:i,nonce:s,expiresAt:a}=await at(n,r,e),o=await t(i);return st(n,o,s,a)}function ne(n){let t=new Date(n).getTime();return Date.now()<t}function ie(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 Qt=n=>n?typeof n=="string"?n:n.address:null,S=(n,t)=>Qt(n.user?.wallets?.[t]||null),Kt=n=>n?typeof n=="string"?n:n.privateKey:null,_t=n=>n?typeof n=="string"?n:n.mnemonic:null,se=(n,t)=>Kt(n.user?.wallets?.[t]||null)?.trim()||null,oe=(n,t)=>_t(n.user?.wallets?.[t]||null)?.trim()||null;var A=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[l,c]=this.getTypeAndValue(e[o]);return`(${o}${p.ArgParamsSeparator}${l})${c}`});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(l=>{let c=l.indexOf(p.ArgParamsSeparator),u=l.substring(c+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),l=a.startsWith(d.Struct)?p.ArgStructSeparator:p.ArgListSeparator,u=(o?o.split(l):[]).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((l,c)=>this.stringToNative(`${s[c]}${p.IdentifierParamSeparator}${l}`)[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(l=>{let c=l.match(new RegExp(`^\\(([^${p.ArgParamsSeparator}]+)${p.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(c){let[,u,f,h]=c;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,l]=this.stringToNative(`${a}:${i}`);return[e,l]}}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 fe=n=>new A().nativeToString(d.String,n),ge=n=>new A().nativeToString(d.Uint8,n),he=n=>new A().nativeToString(d.Uint16,n),me=n=>new A().nativeToString(d.Uint32,n),We=n=>new A().nativeToString(d.Uint64,n),ye=n=>new A().nativeToString(d.Biguint,n),Ae=n=>new A().nativeToString(d.Bool,n),xe=n=>new A().nativeToString(d.Address,n),xt=n=>new A().nativeToString(d.Asset,n),ve=n=>new A().nativeToString(d.Hex,n),Ce=(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},we=(...n)=>new A().nativeToString(d.Tuple,n),Se=n=>new A().nativeToString(d.Struct,n),Ie=n=>new A().nativeToString(d.Vector,n);import Xt from"ajv";var vt=class{constructor(t){this.pendingBrand={protocol:q("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||E.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),s=new Xt,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};import Zt from"ajv";var z=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}=Z(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||E.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),s=new Zt({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 Ct=class{constructor(t){this.config=t;this.pendingWarp={protocol:q("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 ft(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 z(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
2
+ `))}};var L=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,tr);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,Yt))}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)}}},wt=new A,Yt=(n,t)=>typeof t=="bigint"?wt.nativeToString("biguint",t):t,tr=(n,t)=>typeof t=="string"&&t.startsWith(d.Biguint+":")?wt.stringToNative(t)[1]:t;var b=class b{get(t){let r=b.cache.get(t);return r?Date.now()>r.expiresAt?(b.cache.delete(t),null):r.value:null}set(t,r,e){let i=Date.now()+e*1e3;b.cache.set(t,{value:r,expiresAt:i})}forget(t){b.cache.delete(t)}clear(){b.cache.clear()}};b.cache=new Map;var j=b;var St={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},It={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}`},G=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new L:t==="memory"?new j:typeof window<"u"&&window.localStorage?new L:new j}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,l)=>{s=s.replace(new RegExp(`{{${o.toUpperCase()}}}`,"g"),l.toString())};return Object.entries(r.vars).forEach(([o,l])=>{if(typeof l!="string")a(o,l);else if(l.startsWith(p.Vars.Query+p.ArgParamsSeparator)){let c=l.slice(p.Vars.Query.length+1),[u,f]=c.split(p.ArgCompositeSeparator),h=t.currentUrl?new URLSearchParams(t.currentUrl.split("?")[1]).get(u):null,w=e.queries?.[u]||null||h;w&&a(o,w)}else if(l.startsWith(p.Vars.Env+p.ArgParamsSeparator)){let c=l.slice(p.Vars.Env.length+1),[u,f]=c.split(p.ArgCompositeSeparator),g={...t.vars,...e.envs}?.[u];g&&a(o,g)}else l===p.Source.UserWallet&&i?a(o,i):a(o,l)}),JSON.parse(s)}async applyRootGlobals(t,r){let e=JSON.stringify(t),i={config:r,chain:this.adapter.chainInfo};return Object.values(p.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,chain:this.adapter.chainInfo};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){if(!t||typeof t!="string")return t;let i={};return r.forEach(s=>{if(!s.value||!s.input.as)return;let a=s.input.as;if(a!==a.toUpperCase())return;let[,o]=e.stringToNative(s.value);i[a]=String(o)}),B(t,i)}};var O=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 A,this.cache=new G(t.cache?.type)}getSerializer(){return this.serializer}async createExecutable(t,r,e,i={}){let s=I(t,r);if(!s)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,e),o=m(a.name,this.adapters),l=new P(this.config,o),c=await l.apply(this.config,t,i),u=I(c,r),f=this.getStringTypedInputs(u,e),h=await this.getResolvedInputs(a.name,u,f),g=this.getModifiedInputs(h),w=g.find(v=>v.input.position==="receiver"||v.input.position==="destination")?.value,W=this.getDestinationFromAction(u),y=w?this.serializer.stringToNative(w)[1]:W;if(y&&(y=l.applyInputs(y,g,this.serializer)),!y&&s.type!=="collect")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let x=this.getPreparedArgs(u,g);x=x.map(v=>l.applyInputs(v,g,this.serializer));let $=g.find(v=>v.input.position==="value")?.value||null,D="value"in u?u.value:null,H=$?.split(p.ArgParamsSeparator)[1]||D||"0",Pt=l.applyInputs(H,g,this.serializer),Et=BigInt(Pt),Rt=g.filter(v=>v.input.position==="transfer"&&v.value).map(v=>v.value),Bt=[...("transfers"in u?u.transfers:[])||[],...Rt||[]].map(v=>{let Ut=l.applyInputs(v,g,this.serializer);return this.serializer.stringToNative(Ut)[1]}),Vt=g.find(v=>v.input.position==="data")?.value,$t="data"in u?u.data||"":null,ot=Vt||$t||null,Nt=ot?l.applyInputs(ot,g,this.serializer):null,pt={warp:c,chain:a,action:r,destination:y,args:x,value:Et,transfers:Bt,data:Nt,resolvedInputs:g};return this.cache.set(It.WarpExecutable(this.config.env,c.meta?.hash||"",r),pt.resolvedInputs,St.OneWeek),pt}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){let i=r.inputs||[],s=await Promise.all(e.map(o=>this.preprocessInput(t,o))),a=(o,l)=>{if(o.source==="query"){let c=this.url.searchParams.get(o.name);return c?this.serializer.nativeToString(o.type,c):null}else if(o.source===p.Source.UserWallet){let c=S(this.config,t);return c?this.serializer.nativeToString("address",c):null}else return o.source==="hidden"?o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null:s[l]||null};return i.map((o,l)=>{let c=a(o,l);return{input:o,value:c||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(t){return t.map((r,e)=>{if(r.input.modifier?.startsWith("scale:")){let[,i]=r.input.modifier.split(":");if(isNaN(Number(i))){let s=Number(t.find(l=>l.input.name===i)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let a=r.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=M(a,+s);return{...r,value:`${r.input.type}:${o}`}}else{let s=r.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let a=M(s,+i);return{...r,value:`${r.input.type}:${a}`}}}else return r})}async preprocessInput(t,r){try{let[e,i]=rt(r),s=m(t,this.adapters);if(e==="asset"){let[a,o,l]=i.split(p.ArgCompositeSeparator);if(l)return r;let c=await s.dataLoader.getAsset(a);if(!c)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof c.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=M(o,c.decimals);return xt({...c,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||[]:[];return r.forEach(({input:i,value:s})=>{if(!s||!i.position?.startsWith("arg:"))return;let a=Number(i.position.split(":")[1])-1;e.splice(a,0,s)}),e}async tryGetChainFromInputs(t,r){let e=t.actions.find(l=>l.inputs?.some(c=>c.position==="chain"));if(!e)return null;let i=e.inputs?.findIndex(l=>l.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 J=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.handlers=e,this.factory=new O(t,r)}async execute(t,r,e={}){let i=[],s=null,a=[];for(let o=1;o<=t.actions.length;o++){let l=I(t,o);if(!Y(l,t))continue;let{tx:c,chain:u,immediateExecution:f}=await this.executeAction(t,o,r,e);c&&i.push(c),u&&(s=u),f&&a.push(f)}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let o=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(o))}return{txs:i,chain:s,immediateExecutions:a}}async executeAction(t,r,e,i={}){let s=I(t,r);if(s.type==="link")return await this.callHandler(async()=>{let c=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(c):ct.open(c,"_blank")}),{tx:null,chain:null,immediateExecution:null};let a=await this.factory.createExecutable(t,r,e,i);if(s.type==="collect"){let c=await this.executeCollect(a);return c.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c}):c.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:c,tx:null})),{tx:null,chain:null,immediateExecution:c}):(this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null,immediateExecution:null})}let o=m(a.chain.name,this.adapters);if(s.type==="query"){let c=await o.executor.executeQuery(a);return c.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:c,tx:null})):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:a.chain,immediateExecution:c}}return{tx:await o.executor.createTransaction(a),chain:a.chain,immediateExecution:null}}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(!Y(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let l=r[o],c=o+1,u=await i.output.getActionExecution(t,c,l);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:c,chain:e,execution:u,tx:l})):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=I(t.warp,t.action),s=c=>{if(!c.value)return null;let u=this.factory.getSerializer().stringToNative(c.value)[1];if(c.input.type==="biguint")return u.toString();if(c.input.type==="asset"){let{identifier:f,amount:h}=u;return{identifier:f,amount:h.toString()}}else return u},a={};if(t.resolvedInputs.forEach(c=>{let u=c.input.as||c.input.name,f=s(c);if(c.input.position&&c.input.position.startsWith(p.Position.Payload)){let h=At(c.input.position,u,f);a=nt(a,h)}else a[u]=f}),i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,e,a,r);let{values:o,output:l}=await it(t.warp,a,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,e,"unhandled",o,l)}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:g}=await at(e,`${t.chain.name}-adapter`),w=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:f,chain:t.chain}));if(w){let W=st(e,w,h,g);Object.entries(W).forEach(([y,x])=>o.set(y,x))}}r.headers&&Object.entries(r.headers).forEach(([f,h])=>{let g=a.applyInputs(h,t.resolvedInputs,this.factory.getSerializer());o.set(f,g)});let l=r.method||"GET",c=l==="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:l,headers:o,body:c});try{let f=await fetch(u,{method:l,headers:o,body:c});C.debug("Collect response status",{status:f.status});let h=await f.json();C.debug("Collect response content",{content:h});let{values:g,output:w}=await it(t.warp,h,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),f.ok?"success":"error",g,w,h)}catch(f){return C.error("WarpActionExecutor: Error executing collect",f),{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[]},output:{_DATA:f},messages:{}}}}buildCollectResult(t,r,e,i,s,a){let o=yt(this.config,this.adapters,t.warp,t.action,s);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:Wt(t.warp,s,this.config)}}async callHandler(t){if(t)return await t()}};var Q=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 K=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!F(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),a=(await Promise.all(i)).filter(c=>c.match),o=a.length>0,l=a.map(c=>({url:c.url,warp:c.warp}));return{match:o,output:l}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(p.HttpProtocolPrefix)?F(t):T(t);if(!i)return e;try{let{type:s,identifierBase:a}=i,o=null,l=null,c=null,u=m(i.chain,this.adapters),f=t.startsWith(p.HttpProtocolPrefix)?ht(t):mt(i.identifier);if(s==="hash"){o=await u.builder().createFromTransactionHash(a,r);let g=await u.registry.getInfoByHash(a,r);l=g.registryInfo,c=g.brand}else if(s==="alias"){let g=await u.registry.getInfoByAlias(a,r);l=g.registryInfo,c=g.brand,g.registryInfo&&(o=await u.builder().createFromTransactionHash(g.registryInfo.hash,r))}o&&o.meta&&(rr(o,u.chainInfo.name,l,i.identifier),o.meta.query=f);let h=o?await new P(this.config,u).apply(this.config,o):null;return h?{match:!0,url:t,warp:h,chain:u.chainInfo.name,registryInfo:l,brand:c}:e}catch(s){return C.error("Error detecting warp link",s),e}}},rr=(n,t,r,e)=>{n.meta&&(n.meta.identifier=r?.alias?tt(t,"alias",r.alias):tt(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 J(this.config,this.adapters,t)}async detectWarp(t,r){return new K(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 g=await fetch(t);if(!g.ok)throw new Error("WarpClient: executeWarp - invalid url");o=await g.json()}if(o||(o=(await this.detectWarp(t,i.cache)).warp),!o)throw new Error("Warp not found");let l=this.createExecutor(e),{txs:c,chain:u,immediateExecutions:f}=await l.execute(o,r,{queries:i.queries});return{txs:c,chain:u,immediateExecutions:f,evaluateOutput:async g=>{await l.evaluateOutput(o,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 O(this.config,this.adapters)}get index(){return new Q(this.config)}get linkBuilder(){return new U(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 k(t,this.config)}};var bt=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{_ as BrowserCryptoProvider,St as CacheTtl,X as NodeCryptoProvider,Cr as WARP_LANGUAGES,vt as WarpBrandBuilder,Ct as WarpBuilder,G as WarpCache,It as WarpCacheKey,Ot as WarpChainName,Tt as WarpClient,E as WarpConfig,p as WarpConstants,J as WarpExecutor,O as WarpFactory,Q as WarpIndex,d as WarpInputTypes,P as WarpInterpolator,U as WarpLinkBuilder,K as WarpLinkDetecter,C as WarpLogger,N as WarpProtocolVersions,A as WarpSerializer,bt as WarpTypeRegistry,z as WarpValidator,xe as address,Wt as applyOutputToMessages,xt as asset,ye as biguint,Ae as bool,At as buildNestedPayload,fr as bytesToBase64,Ht as bytesToHex,st as createAuthHeaders,at as createAuthMessage,hr as createCryptoProvider,ee as createHttpAuthHeaders,Jt as createSignableMessage,Sr as createWarpI18nText,tt as createWarpIdentifier,Mt as evaluateOutputCommon,it as extractCollectOutput,F as extractIdentifierInfoFromUrl,mt as extractQueryStringFromIdentifier,ht as extractQueryStringFromUrl,yr as extractWarpSecrets,m as findWarpAdapterForChain,lt as getCryptoProvider,pr as getEventNameFromWarp,q as getLatestProtocolIdentifier,yt as getNextInfo,Jr as getProviderConfig,ut as getRandomBytes,dt as getRandomHex,I as getWarpActionByIndex,lr as getWarpBrandLogoUrl,T as getWarpInfoFromIdentifier,Z as getWarpPrimaryAction,Qt as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,_t as getWarpWalletMnemonic,oe as getWarpWalletMnemonicFromConfig,Kt as getWarpWalletPrivateKey,se as getWarpWalletPrivateKeyFromConfig,Er as hasInputPrefix,ve as hex,Y as isWarpActionAutoExecute,wr as isWarpI18nText,nt as mergeNestedPayload,Ce as option,Gt as parseOutputOutIndex,ie as parseSignedMessage,B as replacePlaceholders,k as resolveWarpText,ct as safeWindow,dr as setCryptoProvider,M as shiftBigintBy,rt as splitInput,fe as string,Se as struct,gr as testCryptoAvailability,ft as toPreviewText,we as tuple,he as uint16,me as uint32,We as uint64,ge as uint8,ne as validateSignedMessage,Ie as vector};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "3.0.0-alpha.99",
3
+ "version": "3.0.0-beta.153",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",
@@ -27,12 +27,12 @@
27
27
  ],
28
28
  "devDependencies": {
29
29
  "@types/jest": "^30.0.0",
30
- "jest": "^30.1.3",
31
- "jest-environment-jsdom": "^30.1.2",
30
+ "jest": "^30.2.0",
31
+ "jest-environment-jsdom": "^30.2.0",
32
32
  "jest-fetch-mock": "^3.0.3",
33
- "ts-jest": "^29.4.1",
33
+ "ts-jest": "^29.4.5",
34
34
  "tsup": "^8.5.0",
35
- "typescript": "^5.9.2"
35
+ "typescript": "^5.9.3"
36
36
  },
37
37
  "publishConfig": {
38
38
  "access": "public"