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