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