@vleap/warps 3.0.0-alpha.44 → 3.0.0-alpha.45
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +9 -3
- package/dist/index.d.ts +9 -3
- package/dist/index.js +3 -3
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -269,6 +269,7 @@ type Adapter = {
|
|
|
269
269
|
results: AdapterWarpResults;
|
|
270
270
|
serializer: AdapterWarpSerializer;
|
|
271
271
|
registry: AdapterWarpRegistry;
|
|
272
|
+
explorer: (chainInfo: WarpChainInfo) => AdapterWarpExplorer;
|
|
272
273
|
};
|
|
273
274
|
type WarpAdapterGenericTransaction = any;
|
|
274
275
|
type WarpAdapterGenericRemoteTransaction = any;
|
|
@@ -318,6 +319,10 @@ interface AdapterWarpRegistry {
|
|
|
318
319
|
removeChain(chain: WarpChain): Promise<WarpAdapterGenericTransaction>;
|
|
319
320
|
fetchBrand(hash: string, cache?: WarpCacheConfig): Promise<WarpBrand | null>;
|
|
320
321
|
}
|
|
322
|
+
interface AdapterWarpExplorer {
|
|
323
|
+
getAccountUrl(address: string): string;
|
|
324
|
+
getTransactionUrl(hash: string): string;
|
|
325
|
+
}
|
|
321
326
|
|
|
322
327
|
type InterpolationBag = {
|
|
323
328
|
config: WarpInitConfig;
|
|
@@ -423,8 +428,8 @@ declare const WarpInputTypes: {
|
|
|
423
428
|
Hex: string;
|
|
424
429
|
};
|
|
425
430
|
|
|
431
|
+
declare const findWarpAdapter: (config: WarpClientConfig, chainInfo: WarpChainInfo) => Adapter;
|
|
426
432
|
declare const getMainChainInfo: (config: WarpInitConfig) => WarpChainInfo;
|
|
427
|
-
declare const getChainExplorerUrl: (chain: WarpChainInfo, path?: string) => string;
|
|
428
433
|
declare const getLatestProtocolIdentifier: (name: ProtocolName) => string;
|
|
429
434
|
declare const getWarpActionByIndex: (warp: Warp, index: number) => WarpAction;
|
|
430
435
|
declare const findWarpExecutableAction: (warp: Warp) => [WarpAction, WarpActionIndex];
|
|
@@ -601,8 +606,9 @@ declare class WarpClient {
|
|
|
601
606
|
createInscriptionTransaction(warp: Warp): WarpAdapterGenericTransaction;
|
|
602
607
|
createFromTransaction(tx: WarpAdapterGenericRemoteTransaction, validate?: boolean): Promise<Warp>;
|
|
603
608
|
createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
|
|
609
|
+
getExplorer(chain: WarpChainInfo): AdapterWarpExplorer;
|
|
610
|
+
getResults(chain: WarpChainInfo): AdapterWarpResults;
|
|
604
611
|
get factory(): WarpFactory;
|
|
605
|
-
get results(): AdapterWarpResults;
|
|
606
612
|
get registry(): AdapterWarpRegistry;
|
|
607
613
|
}
|
|
608
614
|
|
|
@@ -659,4 +665,4 @@ declare class WarpValidator {
|
|
|
659
665
|
private validateSchema;
|
|
660
666
|
}
|
|
661
667
|
|
|
662
|
-
export { type Adapter, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, CacheTtl, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type InterpolationBag, type KnownToken, KnownTokens, type ProtocolName, type ResolvedInput, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandMeta, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainEnv, type WarpChainInfo, WarpClient, type WarpClientConfig, type WarpCollectAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpExecutable, type WarpExecution, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, WarpFactory, type WarpIdType, WarpIndex, type WarpInitConfig, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, WarpSerializer, type WarpTransferAction, type WarpTrustStatus, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, biguint, boolean, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById,
|
|
668
|
+
export { type Adapter, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, CacheTtl, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type InterpolationBag, type KnownToken, KnownTokens, type ProtocolName, type ResolvedInput, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandMeta, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainEnv, type WarpChainInfo, WarpClient, type WarpClientConfig, type WarpCollectAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpExecutable, type WarpExecution, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, WarpFactory, type WarpIdType, WarpIndex, type WarpInitConfig, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, WarpSerializer, type WarpTransferAction, type WarpTrustStatus, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, biguint, boolean, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById, findWarpAdapter, findWarpExecutableAction, getLatestProtocolIdentifier, getMainChainInfo, getNextInfo, getWarpActionByIndex, getWarpInfoFromIdentifier, hex, parseResultsOutIndex, replacePlaceholders, shiftBigintBy, string, toPreviewText, toTypedChainInfo, u16, u32, u64, u8 };
|
package/dist/index.d.ts
CHANGED
|
@@ -269,6 +269,7 @@ type Adapter = {
|
|
|
269
269
|
results: AdapterWarpResults;
|
|
270
270
|
serializer: AdapterWarpSerializer;
|
|
271
271
|
registry: AdapterWarpRegistry;
|
|
272
|
+
explorer: (chainInfo: WarpChainInfo) => AdapterWarpExplorer;
|
|
272
273
|
};
|
|
273
274
|
type WarpAdapterGenericTransaction = any;
|
|
274
275
|
type WarpAdapterGenericRemoteTransaction = any;
|
|
@@ -318,6 +319,10 @@ interface AdapterWarpRegistry {
|
|
|
318
319
|
removeChain(chain: WarpChain): Promise<WarpAdapterGenericTransaction>;
|
|
319
320
|
fetchBrand(hash: string, cache?: WarpCacheConfig): Promise<WarpBrand | null>;
|
|
320
321
|
}
|
|
322
|
+
interface AdapterWarpExplorer {
|
|
323
|
+
getAccountUrl(address: string): string;
|
|
324
|
+
getTransactionUrl(hash: string): string;
|
|
325
|
+
}
|
|
321
326
|
|
|
322
327
|
type InterpolationBag = {
|
|
323
328
|
config: WarpInitConfig;
|
|
@@ -423,8 +428,8 @@ declare const WarpInputTypes: {
|
|
|
423
428
|
Hex: string;
|
|
424
429
|
};
|
|
425
430
|
|
|
431
|
+
declare const findWarpAdapter: (config: WarpClientConfig, chainInfo: WarpChainInfo) => Adapter;
|
|
426
432
|
declare const getMainChainInfo: (config: WarpInitConfig) => WarpChainInfo;
|
|
427
|
-
declare const getChainExplorerUrl: (chain: WarpChainInfo, path?: string) => string;
|
|
428
433
|
declare const getLatestProtocolIdentifier: (name: ProtocolName) => string;
|
|
429
434
|
declare const getWarpActionByIndex: (warp: Warp, index: number) => WarpAction;
|
|
430
435
|
declare const findWarpExecutableAction: (warp: Warp) => [WarpAction, WarpActionIndex];
|
|
@@ -601,8 +606,9 @@ declare class WarpClient {
|
|
|
601
606
|
createInscriptionTransaction(warp: Warp): WarpAdapterGenericTransaction;
|
|
602
607
|
createFromTransaction(tx: WarpAdapterGenericRemoteTransaction, validate?: boolean): Promise<Warp>;
|
|
603
608
|
createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
|
|
609
|
+
getExplorer(chain: WarpChainInfo): AdapterWarpExplorer;
|
|
610
|
+
getResults(chain: WarpChainInfo): AdapterWarpResults;
|
|
604
611
|
get factory(): WarpFactory;
|
|
605
|
-
get results(): AdapterWarpResults;
|
|
606
612
|
get registry(): AdapterWarpRegistry;
|
|
607
613
|
}
|
|
608
614
|
|
|
@@ -659,4 +665,4 @@ declare class WarpValidator {
|
|
|
659
665
|
private validateSchema;
|
|
660
666
|
}
|
|
661
667
|
|
|
662
|
-
export { type Adapter, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, CacheTtl, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type InterpolationBag, type KnownToken, KnownTokens, type ProtocolName, type ResolvedInput, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandMeta, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainEnv, type WarpChainInfo, WarpClient, type WarpClientConfig, type WarpCollectAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpExecutable, type WarpExecution, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, WarpFactory, type WarpIdType, WarpIndex, type WarpInitConfig, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, WarpSerializer, type WarpTransferAction, type WarpTrustStatus, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, biguint, boolean, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById,
|
|
668
|
+
export { type Adapter, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, CacheTtl, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type InterpolationBag, type KnownToken, KnownTokens, type ProtocolName, type ResolvedInput, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandMeta, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainEnv, type WarpChainInfo, WarpClient, type WarpClientConfig, type WarpCollectAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpExecutable, type WarpExecution, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, WarpFactory, type WarpIdType, WarpIndex, type WarpInitConfig, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, WarpSerializer, type WarpTransferAction, type WarpTrustStatus, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, biguint, boolean, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById, findWarpAdapter, findWarpExecutableAction, getLatestProtocolIdentifier, getMainChainInfo, getNextInfo, getWarpActionByIndex, getWarpInfoFromIdentifier, hex, parseResultsOutIndex, replacePlaceholders, shiftBigintBy, string, toPreviewText, toTypedChainInfo, u16, u32, u64, u8 };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Ir=Object.create;var F=Object.defineProperty;var Cr=Object.getOwnPropertyDescriptor;var wr=Object.getOwnPropertyNames;var Ar=Object.getPrototypeOf,br=Object.prototype.hasOwnProperty;var lr=(e,r)=>()=>(e&&(r=e(e=0)),r);var _=(e,r)=>{for(var t in r)F(e,t,{get:r[t],enumerable:!0})},cr=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of wr(r))!br.call(e,i)&&i!==t&&F(e,i,{get:()=>r[i],enumerable:!(n=Cr(r,i))||n.enumerable});return e};var X=(e,r,t)=>(t=e!=null?Ir(Ar(e)):{},cr(r||!e||!e.__esModule?F(t,"default",{value:e,enumerable:!0}):t,e)),Er=e=>cr(F({},"__esModule",{value:!0}),e);var dr={};_(dr,{runInVm:()=>Br});var Pr,Br,fr=lr(()=>{"use strict";Pr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Br=async(e,r)=>{let t;try{t=Pr("vm2").VM}catch{throw new Error('The optional dependency "vm2" is not installed. To use runInVm in Node.js, please install vm2: npm install vm2 --save.')}let n=new t({timeout:2e3,sandbox:{result:r},eval:!1,wasm:!1});return e.trim().startsWith("(")&&e.includes("=>")?n.run(`(${e})(result)`):null}});var gr={};_(gr,{runInVm:()=>$r});var $r,mr=lr(()=>{"use strict";$r=async(e,r)=>new Promise((t,n)=>{try{let i=new Blob([`
|
|
2
2
|
self.onmessage = function(e) {
|
|
3
3
|
try {
|
|
4
4
|
const result = e.data;
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
self.postMessage({ error: error.toString() });
|
|
9
9
|
}
|
|
10
10
|
};
|
|
11
|
-
`],{type:"application/javascript"}),a=URL.createObjectURL(i),o=new Worker(a);o.onmessage=function(s){s.data.error?n(new Error(s.data.error)):t(s.data.result),o.terminate(),URL.revokeObjectURL(a)},o.onerror=function(s){n(new Error(`Error in transform: ${s.message}`)),o.terminate(),URL.revokeObjectURL(a)},o.postMessage(r)}catch(i){return n(i)}})});var Gr={};Q(Gr,{CacheTtl:()=>K,KnownTokens:()=>Wr,WarpBrandBuilder:()=>nr,WarpBuilder:()=>O,WarpCache:()=>D,WarpCacheKey:()=>ir,WarpClient:()=>ar,WarpConfig:()=>h,WarpConstants:()=>l,WarpExecutor:()=>H,WarpFactory:()=>R,WarpIndex:()=>or,WarpInputTypes:()=>v,WarpInterpolator:()=>S,WarpLinkBuilder:()=>q,WarpLinkDetecter:()=>M,WarpLogger:()=>y,WarpProtocolVersions:()=>T,WarpSerializer:()=>b,WarpValidator:()=>L,address:()=>Mr,applyResultsToMessages:()=>Z,biguint:()=>Dr,boolean:()=>Hr,evaluateResultsCommon:()=>mr,extractCollectResults:()=>er,extractIdentifierInfoFromUrl:()=>U,findKnownTokenById:()=>Vr,findWarpExecutableAction:()=>X,getChainExplorerUrl:()=>Er,getLatestProtocolIdentifier:()=>V,getMainChainInfo:()=>$,getNextInfo:()=>tr,getWarpActionByIndex:()=>w,getWarpInfoFromIdentifier:()=>A,hex:()=>Fr,parseResultsOutIndex:()=>hr,replacePlaceholders:()=>z,shiftBigintBy:()=>G,string:()=>qr,toPreviewText:()=>Y,toTypedChainInfo:()=>Tr,u16:()=>Or,u32:()=>kr,u64:()=>jr,u8:()=>Lr});module.exports=br(Gr);var l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:e=>e.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:e=>e.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:e=>e.chain.explorerUrl},ChainAddressHrp:{Placeholder:"chain.addressHrp",Accessor:e=>e.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},v={Option:"option",Optional:"optional",List:"list",Variadic:"variadic",Composite:"composite",String:"string",U8:"u8",U16:"u16",U32:"u32",U64:"u64",Biguint:"biguint",Boolean:"boolean",Address:"address",Hex:"hex"};var T={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},h={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${T.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${T.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"],MainChain:{Name:"multiversx",DisplayName:"MultiversX",ApiUrl:e=>e==="devnet"?"https://devnet-api.multiversx.com":e==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:e=>e==="devnet"?"https://devnet-explorer.multiversx.com":e==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:e=>6e3,AddressHrp:"erd",ChainId:e=>e==="devnet"?"D":e==="testnet"?"T":"1",NativeToken:"EGLD"},Registry:{Contract:e=>e==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":e==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query",l.Source.UserWallet],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var $=e=>({name:h.MainChain.Name,displayName:h.MainChain.DisplayName,chainId:h.MainChain.ChainId(e.env),blockTime:h.MainChain.BlockTime(e.env),addressHrp:h.MainChain.AddressHrp,apiUrl:h.MainChain.ApiUrl(e.env),explorerUrl:h.MainChain.ExplorerUrl(e.env),nativeToken:h.MainChain.NativeToken}),Er=(e,r)=>e.explorerUrl+(r?"/"+r:""),V=e=>{if(e==="warp")return`warp:${T.Warp}`;if(e==="brand")return`brand:${T.Brand}`;if(e==="abi")return`abi:${T.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${e}`)},w=(e,r)=>e?.actions[r-1],X=e=>(e.actions.forEach((r,t)=>{if(r.type!=="link")return[r,t]}),[w(e,1),1]),Tr=e=>({name:e.name.toString(),displayName:e.display_name.toString(),chainId:e.chain_id.toString(),blockTime:e.block_time.toNumber(),addressHrp:e.address_hrp.toString(),apiUrl:e.api_url.toString(),explorerUrl:e.explorer_url.toString(),nativeToken:e.native_token.toString()}),G=(e,r)=>{let t=e.toString(),[n,i=""]=t.split("."),a=Math.abs(r);if(r>0)return BigInt(n+i.padEnd(a,"0"));if(r<0){let o=n+i;if(a>=o.length)return 0n;let s=o.slice(0,-a)||"0";return BigInt(s)}else return t.includes(".")?BigInt(t.split(".")[0]):BigInt(t)},Y=(e,r=100)=>{if(!e)return"";let t=e.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return t=t.startsWith("- ")?t.slice(2):t,t=t.length>r?t.substring(0,t.lastIndexOf(" ",r))+"...":t,t},z=(e,r)=>e.replace(/\{\{([^}]+)\}\}/g,(t,n)=>r[n]||""),Z=(e,r)=>{let t=Object.entries(e.messages||{}).map(([n,i])=>[n,z(i,r)]);return Object.fromEntries(t)};var A=e=>{let r=decodeURIComponent(e);if(r.includes(l.IdentifierParamSeparator)){let[n,i]=r.split(l.IdentifierParamSeparator),a=i.split("?")[0];return{type:n,identifier:i,identifierBase:a}}let t=r.split("?")[0];return t.length===64?{type:l.IdentifierType.Hash,identifier:r,identifierBase:t}:{type:l.IdentifierType.Alias,identifier:r,identifierBase:t}},U=e=>{let r=new URL(e),t=h.SuperClientUrls.includes(r.origin),n=r.searchParams.get(l.IdentifierParamName),i=t&&!n?r.pathname.split("/")[1]:n;if(!i)return null;let a=decodeURIComponent(i);return A(a)};var cr=_(require("qr-code-styling"));var q=class{constructor(r){this.config=r;this.config=r}isValid(r){return r.startsWith(l.HttpProtocolPrefix)?!!U(r):!1}build(r,t){let n=this.config.clientUrl||h.DefaultClientUrl(this.config.env),i=r===l.IdentifierType.Alias?encodeURIComponent(t):encodeURIComponent(r+l.IdentifierParamSeparator+t);return h.SuperClientUrls.includes(n)?`${n}/${i}`:`${n}?${l.IdentifierParamName}=${i}`}buildFromPrefixedIdentifier(r){let t=A(r);return t?this.build(t.type,t.identifierBase):""}generateQrCode(r,t,n=512,i="white",a="black",o="#23F7DD"){let s=this.build(r,t);return new cr.default({type:"svg",width:n,height:n,data:String(s),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},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 Rr="https://",tr=(e,r,t,n)=>{let i=r.actions?.[t]?.next||r.next||null;if(!i)return null;if(i.startsWith(Rr))return[{identifier:null,url:i}];let[a,o]=i.split("?");if(!o)return[{identifier:a,url:rr(a,e)}];let s=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(s.length===0){let f=z(o,{...r.vars,...n}),g=f?`${a}?${f}`:a;return[{identifier:g,url:rr(g,e)}]}let c=s[0];if(!c)return[];let p=c.match(/{{([^[]+)\[\]/),u=p?p[1]:null;if(!u||n[u]===void 0)return[];let m=Array.isArray(n[u])?n[u]:[n[u]];if(m.length===0)return[];let W=s.filter(f=>f.includes(`{{${u}[]`)).map(f=>{let g=f.match(/\[\](\.[^}]+)?}}/),d=g&&g[1]||"";return{placeholder:f,field:d?d.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return m.map(f=>{let g=o;for(let{regex:x,field:B}of W){let C=B?Sr(f,B):f;if(C==null)return null;g=g.replace(x,C)}if(g.includes("{{")||g.includes("}}"))return null;let d=g?`${a}?${g}`:a;return{identifier:d,url:rr(d,e)}}).filter(f=>f!==null)},rr=(e,r)=>{let[t,n]=e.split("?"),i=A(t)||{type:"alias",identifier:t,identifierBase:t},o=new q(r).build(i.type,i.identifierBase);if(!n)return o;let s=new URL(o);return new URLSearchParams(n).forEach((c,p)=>s.searchParams.set(p,c)),s.toString().replace(/\/\?/,"?")},Sr=(e,r)=>r.split(".").reduce((t,n)=>t?.[n],e);var N=class N{static info(...r){N.isTestEnv||console.info(...r)}static warn(...r){N.isTestEnv||console.warn(...r)}static error(...r){N.isTestEnv||console.error(...r)}};N.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var y=N;var b=class{nativeToString(r,t){return`${r}:${t?.toString()??""}`}stringToNative(r){let t=r.split(l.ArgParamsSeparator),n=t[0],i=t.slice(1).join(l.ArgParamsSeparator);if(n==="null")return[n,null];if(n==="option"){let[a,o]=i.split(l.ArgParamsSeparator);return[`option:${a}`,o||null]}else if(n==="optional"){let[a,o]=i.split(l.ArgParamsSeparator);return[`optional:${a}`,o||null]}else if(n==="list"){let a=i.split(l.ArgParamsSeparator),o=a.slice(0,-1).join(l.ArgParamsSeparator),s=a[a.length-1],p=(s?s.split(","):[]).map(u=>this.stringToNative(`${o}:${u}`)[1]);return[`list:${o}`,p]}else if(n==="variadic"){let a=i.split(l.ArgParamsSeparator),o=a.slice(0,-1).join(l.ArgParamsSeparator),s=a[a.length-1],p=(s?s.split(","):[]).map(u=>this.stringToNative(`${o}:${u}`)[1]);return[`variadic:${o}`,p]}else if(n.startsWith("composite")){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),s=i.split(l.ArgCompositeSeparator).map((c,p)=>this.stringToNative(`${a[p]}:${c}`)[1]);return[n,s]}else{if(n==="string")return[n,i];if(n==="uint8"||n==="uint16"||n==="uint32")return[n,Number(i)];if(n==="uint64"||n==="biguint")return[n,BigInt(i||0)];if(n==="bool")return[n,i==="true"];if(n==="address")return[n,i];if(n==="token")return[n,i];if(n==="hex")return[n,i];if(n==="codemeta")return[n,i];if(n==="esdt"){let[a,o,s]=i.split(l.ArgCompositeSeparator);return[n,`${a}|${o}|${s}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}};var er=async(e,r,t,n)=>{let i=[],a={};for(let[o,s]of Object.entries(e.results||{})){if(s.startsWith(l.Transform.Prefix))continue;let c=hr(s);if(c!==null&&c!==t){a[o]=null;continue}let[p,...u]=s.split("."),m=(W,P)=>P.reduce((f,g)=>f&&f[g]!==void 0?f[g]:null,W);if(p==="out"||p.startsWith("out[")){let W=u.length===0?r?.data||r:m(r,u);i.push(W),a[o]=W}else a[o]=s}return{values:i,results:await mr(e,a,t,n)}},mr=async(e,r,t,n)=>{if(!e.results)return r;let i={...r};return i=Ur(i,e,t,n),i=await Nr(e,i),i},Ur=(e,r,t,n)=>{let i={...e},a=w(r,t)?.inputs||[],o=new b;for(let[s,c]of Object.entries(i))if(typeof c=="string"&&c.startsWith("input.")){let p=c.split(".")[1],u=a.findIndex(W=>W.as===p||W.name===p),m=u!==-1?n[u]?.value:null;i[s]=m?o.stringToNative(m)[1]:null}return i},Nr=async(e,r)=>{if(!e.results)return r;let t={...r},n=Object.entries(e.results).filter(([,i])=>i.startsWith(l.Transform.Prefix)).map(([i,a])=>({key:i,code:a.substring(l.Transform.Prefix.length)}));for(let{key:i,code:a}of n)try{let o;typeof window>"u"?o=(await Promise.resolve().then(()=>(dr(),ur))).runInVm:o=(await Promise.resolve().then(()=>(gr(),fr))).runInVm,t[i]=await o(a,t)}catch(o){y.error(`Transform error for result '${i}':`,o),t[i]=null}return t},hr=e=>{if(e==="out")return 1;let r=e.match(/^out\[(\d+)\]/);return r?parseInt(r[1],10):(e.startsWith("out.")||e.startsWith("event."),null)};var Wr=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Vr=e=>Wr.find(r=>r.id===e)||null;var qr=e=>`${v.String}:${e}`,Lr=e=>`${v.U8}:${e}`,Or=e=>`${v.U16}:${e}`,kr=e=>`${v.U32}:${e}`,jr=e=>`${v.U64}:${e}`,Dr=e=>`${v.Biguint}:${e}`,Hr=e=>`${v.Boolean}:${e}`,Mr=e=>`${v.Address}:${e}`,Fr=e=>`${v.Hex}:${e}`;var yr=_(require("ajv"));var nr=class{constructor(r){this.pendingBrand={protocol:V("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,t=!0){let n=JSON.parse(r);return t&&await this.ensureValidSchema(n),n}setName(r){return this.pendingBrand.name=r,this}setDescription(r){return this.pendingBrand.description=r,this}setLogo(r){return this.pendingBrand.logo=r,this}setUrls(r){return this.pendingBrand.urls=r,this}setColors(r){return this.pendingBrand.colors=r,this}setCta(r){return this.pendingBrand.cta=r,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(r,t){if(!r)throw new Error(`Warp: ${t}`)}async ensureValidSchema(r){let t=this.config.schema?.brand||h.LatestBrandSchemaUrl,i=await(await fetch(t)).json(),a=new yr.default,o=a.compile(i);if(!o(r))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(o.errors)}`)}};var vr=_(require("ajv"));var L=class{constructor(r){this.config=r;this.config=r}async validate(r){let t=[];return t.push(...this.validateMaxOneValuePosition(r)),t.push(...this.validateVariableNamesAndResultNamesUppercase(r)),t.push(...this.validateAbiIsSetIfApplicable(r)),t.push(...await this.validateSchema(r)),{valid:t.length===0,errors:t}}validateMaxOneValuePosition(r){return r.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let t=[],n=(i,a)=>{i&&Object.keys(i).forEach(o=>{o!==o.toUpperCase()&&t.push(`${a} name '${o}' must be uppercase`)})};return n(r.vars,"Variable"),n(r.results,"Result"),t}validateAbiIsSetIfApplicable(r){let t=r.actions.some(o=>o.type==="contract"),n=r.actions.some(o=>o.type==="query");if(!t&&!n)return[];let i=r.actions.some(o=>o.abi),a=Object.values(r.results||{}).some(o=>o.startsWith("out.")||o.startsWith("event."));return r.results&&!i&&a?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let t=this.config.schema?.warp||h.LatestWarpSchemaUrl,i=await(await fetch(t)).json(),a=new vr.default({strict:!1}),o=a.compile(i);return o(r)?[]:[`Schema validation failed: ${a.errorsText(o.errors)}`]}catch(t){return[`Schema validation failed: ${t instanceof Error?t.message:String(t)}`]}}};var O=class{constructor(r){this.config=r;this.pendingWarp={protocol:V("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(r,t=!0){let n=JSON.parse(r);return t&&await this.validate(n),n}setName(r){return this.pendingWarp.name=r,this}setTitle(r){return this.pendingWarp.title=r,this}setDescription(r){return this.pendingWarp.description=r,this}setPreview(r){return this.pendingWarp.preview=r,this}setActions(r){return this.pendingWarp.actions=r,this}addAction(r){return this.pendingWarp.actions.push(r),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(r,t=100){return Y(r,t)}ensure(r,t){if(!r)throw new Error(t)}async validate(r){let n=await new L(this.config).validate(r);if(!n.valid)throw new Error(n.errors.join(`
|
|
12
|
-
`))}};var k=class{constructor(r="warp-cache"){this.prefix=r}getKey(r){return`${this.prefix}:${r}`}get(r){try{let t=localStorage.getItem(this.getKey(r));if(!t)return null;let n=JSON.parse(t);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(r)),null):n.value}catch{return null}}set(r,t,n){let i={value:t,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(r),JSON.stringify(i))}forget(r){localStorage.removeItem(this.getKey(r))}clear(){for(let r=0;r<localStorage.length;r++){let t=localStorage.key(r);t?.startsWith(this.prefix)&&localStorage.removeItem(t)}}};var E=class E{get(r){let t=E.cache.get(r);return t?Date.now()>t.expiresAt?(E.cache.delete(r),null):t.value:null}set(r,t,n){let i=Date.now()+n*1e3;E.cache.set(r,{value:t,expiresAt:i})}forget(r){E.cache.delete(r)}clear(){E.cache.clear()}};E.cache=new Map;var j=E;var K={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},ir={Warp:(e,r)=>`warp:${e}:${r}`,WarpAbi:(e,r)=>`warp-abi:${e}:${r}`,WarpExecutable:(e,r,t)=>`warp-exec:${e}:${r}:${t}`,RegistryInfo:(e,r)=>`registry-info:${e}:${r}`,Brand:(e,r)=>`brand:${e}:${r}`,ChainInfo:(e,r)=>`chain:${e}:${r}`,ChainInfos:e=>`chains:${e}`},D=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new k:r==="memory"?new j:typeof window<"u"&&window.localStorage?new k:new j}set(r,t,n){this.strategy.set(r,t,n)}get(r){return this.strategy.get(r)}forget(r){this.strategy.forget(r)}clear(){this.strategy.clear()}};var R=class{constructor(r){this.config=r;if(!r.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(r.currentUrl),this.serializer=new b,this.cache=new D(r.cache?.type)}async createExecutable(r,t,n){let i=w(r,t);if(!i)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForAction(i,n),o=await this.getResolvedInputs(a,i,n),s=this.getModifiedInputs(o),c=s.find(I=>I.input.position==="receiver")?.value,p="address"in i?i.address:null,u=c?.split(":")[1]||p;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let m=u,W=this.getPreparedArgs(i,s),P=s.find(I=>I.input.position==="value")?.value||null,f="value"in i?i.value:null,g=BigInt(P?.split(":")[1]||f||0),d=s.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),B=[...("transfers"in i?i.transfers:[])||[],...d||[]],C=s.find(I=>I.input.position==="data")?.value,J="data"in i?i.data||"":null,sr={warp:r,chain:a,action:t,destination:m,args:W,value:g,transfers:B,data:C||J||null,resolvedInputs:s};return this.cache.set(ir.WarpExecutable(this.config.env,r.meta?.hash||"",t),sr.resolvedInputs,K.OneWeek),sr}async getChainInfoForAction(r,t){if(t){let n=await this.tryGetChainFromInputs(r,t);if(n)return n}return this.getDefaultChainInfo(r)}async getResolvedInputs(r,t,n){let i=t.inputs||[],a=await Promise.all(n.map(s=>this.preprocessInput(r,s))),o=(s,c)=>{if(s.source==="query"){let p=this.url.searchParams.get(s.name);return p?this.serializer.nativeToString(s.type,p):null}else return s.source===l.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:a[c]||null};return i.map((s,c)=>{let p=o(s,c);return{input:s,value:p||(s.default!==void 0?this.serializer.nativeToString(s.type,s.default):null)}})}getModifiedInputs(r){return r.map((t,n)=>{if(t.input.modifier?.startsWith("scale:")){let[,i]=t.input.modifier.split(":");if(isNaN(Number(i))){let a=Number(r.find(c=>c.input.name===i)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let o=t.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let s=G(o,+a);return{...t,value:`${t.input.type}:${s}`}}else{let a=t.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=G(a,+i);return{...t,value:`${t.input.type}:${o}`}}}else return t})}async preprocessInput(r,t){try{let[n,i]=t.split(l.ArgParamsSeparator,2),a=this.config.adapters.find(o=>o.chain===r.name)?.executor;return a?a.preprocessInput(r,t,n,i):t}catch{return t}}getPreparedArgs(r,t){let n="args"in r?r.args||[]:[];return t.forEach(({input:i,value:a})=>{if(!a||!i.position?.startsWith("arg:"))return;let o=Number(i.position.split(":")[1])-1;n.splice(o,0,a)}),n}async tryGetChainFromInputs(r,t){let n=r.inputs?.findIndex(c=>c.position==="chain");if(n===-1||n===void 0)return null;let i=t[n];if(!i)throw new Error("WarpUtils: Chain input not found");let o=new b().stringToNative(i)[1],s=await this.config.repository.registry.getChainInfo(o);if(!s)throw new Error(`WarpUtils: Chain info not found for ${o}`);return s}async getDefaultChainInfo(r){if(!r.chain)return $(this.config);let t=await this.config.repository.registry.getChainInfo(r.chain,{ttl:K.OneWeek});if(!t)throw new Error(`WarpUtils: Chain info not found for ${r.chain}`);return t}};var S=class{constructor(r,t){this.config=r;this.repository=t}async apply(r,t){let n=this.applyVars(r,t);return await this.applyGlobals(r,n)}async applyGlobals(r,t){let n={...t};return n.actions=await Promise.all(n.actions.map(async i=>await this.applyActionGlobals(i))),n=await this.applyRootGlobals(n,r),n}applyVars(r,t){if(!t?.vars)return t;let n=JSON.stringify(t),i=(a,o)=>{n=n.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([a,o])=>{if(typeof o!="string")i(a,o);else if(o.startsWith(`${l.Vars.Query}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let s=o.split(`${l.Vars.Query}:`)[1],c=new URLSearchParams(r.currentUrl.split("?")[1]).get(s);c&&i(a,c)}else if(o.startsWith(`${l.Vars.Env}:`)){let s=o.split(`${l.Vars.Env}:`)[1],c=r.vars?.[s];c&&i(a,c)}else o===l.Source.UserWallet&&r.user?.wallet?i(a,r.user.wallet):i(a,o)}),JSON.parse(n)}async applyRootGlobals(r,t){let n=JSON.stringify(r),i={config:t,chain:$(t)};return Object.values(l.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(n=n.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(n)}async applyActionGlobals(r){let t=r.chain?await this.repository.registry.getChainInfo(r.chain):$(this.config);if(!t)throw new Error(`Chain info not found for ${r.chain}`);let n=JSON.stringify(r),i={config:this.config,chain:t};return Object.values(l.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(n=n.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(n)}};var H=class{constructor(r,t){this.config=r;this.handlers=t;this.factory=new R(r),this.interpolator=new S(r,r.repository),this.handlers=t}async execute(r,t){let[n,i]=X(r);if(n.type==="collect"){let p=await this.executeCollect(r,i,t);return this.handlers?.onExecuted?.(p),[null,null]}let a=await this.factory.createExecutable(r,i,t),o=a.chain.name.toLowerCase(),s=this.config.adapters.find(p=>p.chain.toLowerCase()===o);if(!s)throw new Error(`No adapter registered for chain: ${o}`);return[await s.executor.createTransaction(a),a.chain]}async evaluateResults(r,t,n){let i=this.config.adapters.find(o=>o.chain.toLowerCase()===t.name.toLowerCase());if(!i)throw new Error(`No adapter registered for chain: ${t.name}`);let a=await i.results.getTransactionExecutionResults(r,n);this.handlers?.onExecuted?.(a)}async executeCollect(r,t,n,i){let a=w(r,t);if(!a)throw new Error("WarpActionExecutor: Action not found");let o=await this.factory.getChainInfoForAction(a),s=await this.interpolator.apply(this.config,r),c=await this.factory.getResolvedInputs(o,a,n),p=this.factory.getModifiedInputs(c),u=this.factory.serializer,m=d=>{if(!d.value)return null;let x=u.stringToNative(d.value)[1];return d.input.type==="biguint"?x.toString():d.input.type==="esdt"?{}:x},W=new Headers;W.set("Content-Type","application/json"),W.set("Accept","application/json"),Object.entries(a.destination.headers||{}).forEach(([d,x])=>{W.set(d,x)});let P=Object.fromEntries(p.map(d=>[d.input.as||d.input.name,m(d)])),f=a.destination.method||"GET",g=f==="GET"?void 0:JSON.stringify({...P,...i});y.info("Executing collect",{url:a.destination.url,method:f,headers:W,body:g});try{let d=await fetch(a.destination.url,{method:f,headers:W,body:g}),x=await d.json(),{values:B,results:C}=await er(s,x,t,p),J=tr(this.config,s,t,C);return{success:d.ok,warp:s,action:t,user:this.config.user?.wallet||null,txHash:null,next:J,values:B,results:{...C,_DATA:x},messages:Z(s,C)}}catch(d){return y.error("WarpActionExecutor: Error executing collect",d),{success:!1,warp:s,action:t,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{_DATA:d},messages:{}}}}};var M=class{constructor(r,t){this.config=r;this.repository=t;this.interpolator=new S(r,t)}isValid(r){return r.startsWith(l.HttpProtocolPrefix)?!!U(r):!1}async detectFromHtml(r){if(!r.length)return{match:!1,results:[]};let i=[...r.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),o=(await Promise.all(i)).filter(p=>p.match),s=o.length>0,c=o.map(p=>({url:p.url,warp:p.warp}));return{match:s,results:c}}async detect(r,t){let n={match:!1,url:r,warp:null,registryInfo:null,brand:null},i=r.startsWith(l.HttpProtocolPrefix)?U(r):A(r);if(!i)return n;try{let{type:a,identifierBase:o}=i,s=null,c=null,p=null;if(a==="hash"){s=await this.repository.builder.createFromTransactionHash(o,t);let m=await this.repository.registry.getInfoByHash(o,t);c=m.registryInfo,p=m.brand}else if(a==="alias"){let m=await this.repository.registry.getInfoByAlias(o,t);c=m.registryInfo,p=m.brand,m.registryInfo&&(s=await this.repository.builder.createFromTransactionHash(m.registryInfo.hash,t))}let u=s?await this.interpolator.apply(this.config,s):null;return u?{match:!0,url:r,warp:u,registryInfo:c,brand:p}:n}catch(a){return y.error("Error detecting warp link",a),n}}};var ar=class{constructor(r){this.config=r}getConfig(){return this.config}setConfig(r){return this.config=r,this}createBuilder(){return new O(this.config)}createExecutor(r){return new H(this.config,r)}async detectWarp(r,t){return new M(this.config,this.config.repository).detect(r,t)}createInscriptionTransaction(r){return this.config.repository.builder.createInscriptionTransaction(r)}async createFromTransaction(r,t=!1){return this.config.repository.builder.createFromTransaction(r,t)}async createFromTransactionHash(r,t){return this.config.repository.builder.createFromTransactionHash(r,t)}get factory(){return new R(this.config)}get results(){return this.config.repository.results}get registry(){return this.config.repository.registry}};var or=class{constructor(r){this.config=r}async search(r,t,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:r,...t})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}`);return(await i.json()).hits}catch(i){throw y.error("WarpIndex: Error searching for warps: ",i),i}}};0&&(module.exports={CacheTtl,KnownTokens,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpValidator,address,applyResultsToMessages,biguint,boolean,evaluateResultsCommon,extractCollectResults,extractIdentifierInfoFromUrl,findKnownTokenById,findWarpExecutableAction,getChainExplorerUrl,getLatestProtocolIdentifier,getMainChainInfo,getNextInfo,getWarpActionByIndex,getWarpInfoFromIdentifier,hex,parseResultsOutIndex,replacePlaceholders,shiftBigintBy,string,toPreviewText,toTypedChainInfo,u16,u32,u64,u8});
|
|
11
|
+
`],{type:"application/javascript"}),a=URL.createObjectURL(i),o=new Worker(a);o.onmessage=function(s){s.data.error?n(new Error(s.data.error)):t(s.data.result),o.terminate(),URL.revokeObjectURL(a)},o.onerror=function(s){n(new Error(`Error in transform: ${s.message}`)),o.terminate(),URL.revokeObjectURL(a)},o.postMessage(r)}catch(i){return n(i)}})});var Gr={};_(Gr,{CacheTtl:()=>J,KnownTokens:()=>yr,WarpBrandBuilder:()=>ir,WarpBuilder:()=>O,WarpCache:()=>D,WarpCacheKey:()=>ar,WarpClient:()=>or,WarpConfig:()=>h,WarpConstants:()=>l,WarpExecutor:()=>H,WarpFactory:()=>R,WarpIndex:()=>sr,WarpInputTypes:()=>v,WarpInterpolator:()=>S,WarpLinkBuilder:()=>q,WarpLinkDetecter:()=>M,WarpLogger:()=>y,WarpProtocolVersions:()=>T,WarpSerializer:()=>b,WarpValidator:()=>L,address:()=>Mr,applyResultsToMessages:()=>rr,biguint:()=>Dr,boolean:()=>Hr,evaluateResultsCommon:()=>hr,extractCollectResults:()=>nr,extractIdentifierInfoFromUrl:()=>U,findKnownTokenById:()=>Vr,findWarpAdapter:()=>G,findWarpExecutableAction:()=>Y,getLatestProtocolIdentifier:()=>V,getMainChainInfo:()=>$,getNextInfo:()=>er,getWarpActionByIndex:()=>w,getWarpInfoFromIdentifier:()=>A,hex:()=>Fr,parseResultsOutIndex:()=>Wr,replacePlaceholders:()=>K,shiftBigintBy:()=>z,string:()=>qr,toPreviewText:()=>Z,toTypedChainInfo:()=>Tr,u16:()=>Or,u32:()=>kr,u64:()=>jr,u8:()=>Lr});module.exports=Er(Gr);var l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:e=>e.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:e=>e.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:e=>e.chain.explorerUrl},ChainAddressHrp:{Placeholder:"chain.addressHrp",Accessor:e=>e.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},v={Option:"option",Optional:"optional",List:"list",Variadic:"variadic",Composite:"composite",String:"string",U8:"u8",U16:"u16",U32:"u32",U64:"u64",Biguint:"biguint",Boolean:"boolean",Address:"address",Hex:"hex"};var T={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},h={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${T.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${T.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"],MainChain:{Name:"multiversx",DisplayName:"MultiversX",ApiUrl:e=>e==="devnet"?"https://devnet-api.multiversx.com":e==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:e=>e==="devnet"?"https://devnet-explorer.multiversx.com":e==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:e=>6e3,AddressHrp:"erd",ChainId:e=>e==="devnet"?"D":e==="testnet"?"T":"1",NativeToken:"EGLD"},Registry:{Contract:e=>e==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":e==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query",l.Source.UserWallet],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 G=(e,r)=>e.adapters.find(n=>n.chain.toLowerCase()===r.name.toLowerCase())||e.adapters[0],$=e=>({name:h.MainChain.Name,displayName:h.MainChain.DisplayName,chainId:h.MainChain.ChainId(e.env),blockTime:h.MainChain.BlockTime(e.env),addressHrp:h.MainChain.AddressHrp,apiUrl:h.MainChain.ApiUrl(e.env),explorerUrl:h.MainChain.ExplorerUrl(e.env),nativeToken:h.MainChain.NativeToken}),V=e=>{if(e==="warp")return`warp:${T.Warp}`;if(e==="brand")return`brand:${T.Brand}`;if(e==="abi")return`abi:${T.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${e}`)},w=(e,r)=>e?.actions[r-1],Y=e=>(e.actions.forEach((r,t)=>{if(r.type!=="link")return[r,t]}),[w(e,1),1]),Tr=e=>({name:e.name.toString(),displayName:e.display_name.toString(),chainId:e.chain_id.toString(),blockTime:e.block_time.toNumber(),addressHrp:e.address_hrp.toString(),apiUrl:e.api_url.toString(),explorerUrl:e.explorer_url.toString(),nativeToken:e.native_token.toString()}),z=(e,r)=>{let t=e.toString(),[n,i=""]=t.split("."),a=Math.abs(r);if(r>0)return BigInt(n+i.padEnd(a,"0"));if(r<0){let o=n+i;if(a>=o.length)return 0n;let s=o.slice(0,-a)||"0";return BigInt(s)}else return t.includes(".")?BigInt(t.split(".")[0]):BigInt(t)},Z=(e,r=100)=>{if(!e)return"";let t=e.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return t=t.startsWith("- ")?t.slice(2):t,t=t.length>r?t.substring(0,t.lastIndexOf(" ",r))+"...":t,t},K=(e,r)=>e.replace(/\{\{([^}]+)\}\}/g,(t,n)=>r[n]||""),rr=(e,r)=>{let t=Object.entries(e.messages||{}).map(([n,i])=>[n,K(i,r)]);return Object.fromEntries(t)};var A=e=>{let r=decodeURIComponent(e);if(r.includes(l.IdentifierParamSeparator)){let[n,i]=r.split(l.IdentifierParamSeparator),a=i.split("?")[0];return{type:n,identifier:i,identifierBase:a}}let t=r.split("?")[0];return t.length===64?{type:l.IdentifierType.Hash,identifier:r,identifierBase:t}:{type:l.IdentifierType.Alias,identifier:r,identifierBase:t}},U=e=>{let r=new URL(e),t=h.SuperClientUrls.includes(r.origin),n=r.searchParams.get(l.IdentifierParamName),i=t&&!n?r.pathname.split("/")[1]:n;if(!i)return null;let a=decodeURIComponent(i);return A(a)};var ur=X(require("qr-code-styling"));var q=class{constructor(r){this.config=r;this.config=r}isValid(r){return r.startsWith(l.HttpProtocolPrefix)?!!U(r):!1}build(r,t){let n=this.config.clientUrl||h.DefaultClientUrl(this.config.env),i=r===l.IdentifierType.Alias?encodeURIComponent(t):encodeURIComponent(r+l.IdentifierParamSeparator+t);return h.SuperClientUrls.includes(n)?`${n}/${i}`:`${n}?${l.IdentifierParamName}=${i}`}buildFromPrefixedIdentifier(r){let t=A(r);return t?this.build(t.type,t.identifierBase):""}generateQrCode(r,t,n=512,i="white",a="black",o="#23F7DD"){let s=this.build(r,t);return new ur.default({type:"svg",width:n,height:n,data:String(s),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},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 Rr="https://",er=(e,r,t,n)=>{let i=r.actions?.[t]?.next||r.next||null;if(!i)return null;if(i.startsWith(Rr))return[{identifier:null,url:i}];let[a,o]=i.split("?");if(!o)return[{identifier:a,url:tr(a,e)}];let s=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(s.length===0){let f=K(o,{...r.vars,...n}),g=f?`${a}?${f}`:a;return[{identifier:g,url:tr(g,e)}]}let c=s[0];if(!c)return[];let p=c.match(/{{([^[]+)\[\]/),u=p?p[1]:null;if(!u||n[u]===void 0)return[];let m=Array.isArray(n[u])?n[u]:[n[u]];if(m.length===0)return[];let W=s.filter(f=>f.includes(`{{${u}[]`)).map(f=>{let g=f.match(/\[\](\.[^}]+)?}}/),d=g&&g[1]||"";return{placeholder:f,field:d?d.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return m.map(f=>{let g=o;for(let{regex:x,field:B}of W){let C=B?Sr(f,B):f;if(C==null)return null;g=g.replace(x,C)}if(g.includes("{{")||g.includes("}}"))return null;let d=g?`${a}?${g}`:a;return{identifier:d,url:tr(d,e)}}).filter(f=>f!==null)},tr=(e,r)=>{let[t,n]=e.split("?"),i=A(t)||{type:"alias",identifier:t,identifierBase:t},o=new q(r).build(i.type,i.identifierBase);if(!n)return o;let s=new URL(o);return new URLSearchParams(n).forEach((c,p)=>s.searchParams.set(p,c)),s.toString().replace(/\/\?/,"?")},Sr=(e,r)=>r.split(".").reduce((t,n)=>t?.[n],e);var N=class N{static info(...r){N.isTestEnv||console.info(...r)}static warn(...r){N.isTestEnv||console.warn(...r)}static error(...r){N.isTestEnv||console.error(...r)}};N.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var y=N;var b=class{nativeToString(r,t){return`${r}:${t?.toString()??""}`}stringToNative(r){let t=r.split(l.ArgParamsSeparator),n=t[0],i=t.slice(1).join(l.ArgParamsSeparator);if(n==="null")return[n,null];if(n==="option"){let[a,o]=i.split(l.ArgParamsSeparator);return[`option:${a}`,o||null]}else if(n==="optional"){let[a,o]=i.split(l.ArgParamsSeparator);return[`optional:${a}`,o||null]}else if(n==="list"){let a=i.split(l.ArgParamsSeparator),o=a.slice(0,-1).join(l.ArgParamsSeparator),s=a[a.length-1],p=(s?s.split(","):[]).map(u=>this.stringToNative(`${o}:${u}`)[1]);return[`list:${o}`,p]}else if(n==="variadic"){let a=i.split(l.ArgParamsSeparator),o=a.slice(0,-1).join(l.ArgParamsSeparator),s=a[a.length-1],p=(s?s.split(","):[]).map(u=>this.stringToNative(`${o}:${u}`)[1]);return[`variadic:${o}`,p]}else if(n.startsWith("composite")){let a=n.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),s=i.split(l.ArgCompositeSeparator).map((c,p)=>this.stringToNative(`${a[p]}:${c}`)[1]);return[n,s]}else{if(n==="string")return[n,i];if(n==="uint8"||n==="uint16"||n==="uint32")return[n,Number(i)];if(n==="uint64"||n==="biguint")return[n,BigInt(i||0)];if(n==="bool")return[n,i==="true"];if(n==="address")return[n,i];if(n==="token")return[n,i];if(n==="hex")return[n,i];if(n==="codemeta")return[n,i];if(n==="esdt"){let[a,o,s]=i.split(l.ArgCompositeSeparator);return[n,`${a}|${o}|${s}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}};var nr=async(e,r,t,n)=>{let i=[],a={};for(let[o,s]of Object.entries(e.results||{})){if(s.startsWith(l.Transform.Prefix))continue;let c=Wr(s);if(c!==null&&c!==t){a[o]=null;continue}let[p,...u]=s.split("."),m=(W,P)=>P.reduce((f,g)=>f&&f[g]!==void 0?f[g]:null,W);if(p==="out"||p.startsWith("out[")){let W=u.length===0?r?.data||r:m(r,u);i.push(W),a[o]=W}else a[o]=s}return{values:i,results:await hr(e,a,t,n)}},hr=async(e,r,t,n)=>{if(!e.results)return r;let i={...r};return i=Ur(i,e,t,n),i=await Nr(e,i),i},Ur=(e,r,t,n)=>{let i={...e},a=w(r,t)?.inputs||[],o=new b;for(let[s,c]of Object.entries(i))if(typeof c=="string"&&c.startsWith("input.")){let p=c.split(".")[1],u=a.findIndex(W=>W.as===p||W.name===p),m=u!==-1?n[u]?.value:null;i[s]=m?o.stringToNative(m)[1]:null}return i},Nr=async(e,r)=>{if(!e.results)return r;let t={...r},n=Object.entries(e.results).filter(([,i])=>i.startsWith(l.Transform.Prefix)).map(([i,a])=>({key:i,code:a.substring(l.Transform.Prefix.length)}));for(let{key:i,code:a}of n)try{let o;typeof window>"u"?o=(await Promise.resolve().then(()=>(fr(),dr))).runInVm:o=(await Promise.resolve().then(()=>(mr(),gr))).runInVm,t[i]=await o(a,t)}catch(o){y.error(`Transform error for result '${i}':`,o),t[i]=null}return t},Wr=e=>{if(e==="out")return 1;let r=e.match(/^out\[(\d+)\]/);return r?parseInt(r[1],10):(e.startsWith("out.")||e.startsWith("event."),null)};var yr=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Vr=e=>yr.find(r=>r.id===e)||null;var qr=e=>`${v.String}:${e}`,Lr=e=>`${v.U8}:${e}`,Or=e=>`${v.U16}:${e}`,kr=e=>`${v.U32}:${e}`,jr=e=>`${v.U64}:${e}`,Dr=e=>`${v.Biguint}:${e}`,Hr=e=>`${v.Boolean}:${e}`,Mr=e=>`${v.Address}:${e}`,Fr=e=>`${v.Hex}:${e}`;var vr=X(require("ajv"));var ir=class{constructor(r){this.pendingBrand={protocol:V("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,t=!0){let n=JSON.parse(r);return t&&await this.ensureValidSchema(n),n}setName(r){return this.pendingBrand.name=r,this}setDescription(r){return this.pendingBrand.description=r,this}setLogo(r){return this.pendingBrand.logo=r,this}setUrls(r){return this.pendingBrand.urls=r,this}setColors(r){return this.pendingBrand.colors=r,this}setCta(r){return this.pendingBrand.cta=r,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(r,t){if(!r)throw new Error(`Warp: ${t}`)}async ensureValidSchema(r){let t=this.config.schema?.brand||h.LatestBrandSchemaUrl,i=await(await fetch(t)).json(),a=new vr.default,o=a.compile(i);if(!o(r))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(o.errors)}`)}};var xr=X(require("ajv"));var L=class{constructor(r){this.config=r;this.config=r}async validate(r){let t=[];return t.push(...this.validateMaxOneValuePosition(r)),t.push(...this.validateVariableNamesAndResultNamesUppercase(r)),t.push(...this.validateAbiIsSetIfApplicable(r)),t.push(...await this.validateSchema(r)),{valid:t.length===0,errors:t}}validateMaxOneValuePosition(r){return r.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let t=[],n=(i,a)=>{i&&Object.keys(i).forEach(o=>{o!==o.toUpperCase()&&t.push(`${a} name '${o}' must be uppercase`)})};return n(r.vars,"Variable"),n(r.results,"Result"),t}validateAbiIsSetIfApplicable(r){let t=r.actions.some(o=>o.type==="contract"),n=r.actions.some(o=>o.type==="query");if(!t&&!n)return[];let i=r.actions.some(o=>o.abi),a=Object.values(r.results||{}).some(o=>o.startsWith("out.")||o.startsWith("event."));return r.results&&!i&&a?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let t=this.config.schema?.warp||h.LatestWarpSchemaUrl,i=await(await fetch(t)).json(),a=new xr.default({strict:!1}),o=a.compile(i);return o(r)?[]:[`Schema validation failed: ${a.errorsText(o.errors)}`]}catch(t){return[`Schema validation failed: ${t instanceof Error?t.message:String(t)}`]}}};var O=class{constructor(r){this.config=r;this.pendingWarp={protocol:V("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(r,t=!0){let n=JSON.parse(r);return t&&await this.validate(n),n}setName(r){return this.pendingWarp.name=r,this}setTitle(r){return this.pendingWarp.title=r,this}setDescription(r){return this.pendingWarp.description=r,this}setPreview(r){return this.pendingWarp.preview=r,this}setActions(r){return this.pendingWarp.actions=r,this}addAction(r){return this.pendingWarp.actions.push(r),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(r,t=100){return Z(r,t)}ensure(r,t){if(!r)throw new Error(t)}async validate(r){let n=await new L(this.config).validate(r);if(!n.valid)throw new Error(n.errors.join(`
|
|
12
|
+
`))}};var k=class{constructor(r="warp-cache"){this.prefix=r}getKey(r){return`${this.prefix}:${r}`}get(r){try{let t=localStorage.getItem(this.getKey(r));if(!t)return null;let n=JSON.parse(t);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(r)),null):n.value}catch{return null}}set(r,t,n){let i={value:t,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(r),JSON.stringify(i))}forget(r){localStorage.removeItem(this.getKey(r))}clear(){for(let r=0;r<localStorage.length;r++){let t=localStorage.key(r);t?.startsWith(this.prefix)&&localStorage.removeItem(t)}}};var E=class E{get(r){let t=E.cache.get(r);return t?Date.now()>t.expiresAt?(E.cache.delete(r),null):t.value:null}set(r,t,n){let i=Date.now()+n*1e3;E.cache.set(r,{value:t,expiresAt:i})}forget(r){E.cache.delete(r)}clear(){E.cache.clear()}};E.cache=new Map;var j=E;var J={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},ar={Warp:(e,r)=>`warp:${e}:${r}`,WarpAbi:(e,r)=>`warp-abi:${e}:${r}`,WarpExecutable:(e,r,t)=>`warp-exec:${e}:${r}:${t}`,RegistryInfo:(e,r)=>`registry-info:${e}:${r}`,Brand:(e,r)=>`brand:${e}:${r}`,ChainInfo:(e,r)=>`chain:${e}:${r}`,ChainInfos:e=>`chains:${e}`},D=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new k:r==="memory"?new j:typeof window<"u"&&window.localStorage?new k:new j}set(r,t,n){this.strategy.set(r,t,n)}get(r){return this.strategy.get(r)}forget(r){this.strategy.forget(r)}clear(){this.strategy.clear()}};var R=class{constructor(r){this.config=r;if(!r.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(r.currentUrl),this.serializer=new b,this.cache=new D(r.cache?.type)}async createExecutable(r,t,n){let i=w(r,t);if(!i)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForAction(i,n),o=await this.getResolvedInputs(a,i,n),s=this.getModifiedInputs(o),c=s.find(I=>I.input.position==="receiver")?.value,p="address"in i?i.address:null,u=c?.split(":")[1]||p;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let m=u,W=this.getPreparedArgs(i,s),P=s.find(I=>I.input.position==="value")?.value||null,f="value"in i?i.value:null,g=BigInt(P?.split(":")[1]||f||0),d=s.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),B=[...("transfers"in i?i.transfers:[])||[],...d||[]],C=s.find(I=>I.input.position==="data")?.value,Q="data"in i?i.data||"":null,pr={warp:r,chain:a,action:t,destination:m,args:W,value:g,transfers:B,data:C||Q||null,resolvedInputs:s};return this.cache.set(ar.WarpExecutable(this.config.env,r.meta?.hash||"",t),pr.resolvedInputs,J.OneWeek),pr}async getChainInfoForAction(r,t){if(t){let n=await this.tryGetChainFromInputs(r,t);if(n)return n}return this.getDefaultChainInfo(r)}async getResolvedInputs(r,t,n){let i=t.inputs||[],a=await Promise.all(n.map(s=>this.preprocessInput(r,s))),o=(s,c)=>{if(s.source==="query"){let p=this.url.searchParams.get(s.name);return p?this.serializer.nativeToString(s.type,p):null}else return s.source===l.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:a[c]||null};return i.map((s,c)=>{let p=o(s,c);return{input:s,value:p||(s.default!==void 0?this.serializer.nativeToString(s.type,s.default):null)}})}getModifiedInputs(r){return r.map((t,n)=>{if(t.input.modifier?.startsWith("scale:")){let[,i]=t.input.modifier.split(":");if(isNaN(Number(i))){let a=Number(r.find(c=>c.input.name===i)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let o=t.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let s=z(o,+a);return{...t,value:`${t.input.type}:${s}`}}else{let a=t.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=z(a,+i);return{...t,value:`${t.input.type}:${o}`}}}else return t})}async preprocessInput(r,t){try{let[n,i]=t.split(l.ArgParamsSeparator,2),a=this.config.adapters.find(o=>o.chain===r.name)?.executor;return a?a.preprocessInput(r,t,n,i):t}catch{return t}}getPreparedArgs(r,t){let n="args"in r?r.args||[]:[];return t.forEach(({input:i,value:a})=>{if(!a||!i.position?.startsWith("arg:"))return;let o=Number(i.position.split(":")[1])-1;n.splice(o,0,a)}),n}async tryGetChainFromInputs(r,t){let n=r.inputs?.findIndex(c=>c.position==="chain");if(n===-1||n===void 0)return null;let i=t[n];if(!i)throw new Error("WarpUtils: Chain input not found");let o=new b().stringToNative(i)[1],s=await this.config.repository.registry.getChainInfo(o);if(!s)throw new Error(`WarpUtils: Chain info not found for ${o}`);return s}async getDefaultChainInfo(r){if(!r.chain)return $(this.config);let t=await this.config.repository.registry.getChainInfo(r.chain,{ttl:J.OneWeek});if(!t)throw new Error(`WarpUtils: Chain info not found for ${r.chain}`);return t}};var S=class{constructor(r,t){this.config=r;this.repository=t}async apply(r,t){let n=this.applyVars(r,t);return await this.applyGlobals(r,n)}async applyGlobals(r,t){let n={...t};return n.actions=await Promise.all(n.actions.map(async i=>await this.applyActionGlobals(i))),n=await this.applyRootGlobals(n,r),n}applyVars(r,t){if(!t?.vars)return t;let n=JSON.stringify(t),i=(a,o)=>{n=n.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([a,o])=>{if(typeof o!="string")i(a,o);else if(o.startsWith(`${l.Vars.Query}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let s=o.split(`${l.Vars.Query}:`)[1],c=new URLSearchParams(r.currentUrl.split("?")[1]).get(s);c&&i(a,c)}else if(o.startsWith(`${l.Vars.Env}:`)){let s=o.split(`${l.Vars.Env}:`)[1],c=r.vars?.[s];c&&i(a,c)}else o===l.Source.UserWallet&&r.user?.wallet?i(a,r.user.wallet):i(a,o)}),JSON.parse(n)}async applyRootGlobals(r,t){let n=JSON.stringify(r),i={config:t,chain:$(t)};return Object.values(l.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(n=n.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(n)}async applyActionGlobals(r){let t=r.chain?await this.repository.registry.getChainInfo(r.chain):$(this.config);if(!t)throw new Error(`Chain info not found for ${r.chain}`);let n=JSON.stringify(r),i={config:this.config,chain:t};return Object.values(l.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(n=n.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(n)}};var H=class{constructor(r,t){this.config=r;this.handlers=t;this.factory=new R(r),this.interpolator=new S(r,r.repository),this.handlers=t}async execute(r,t){let[n,i]=Y(r);if(n.type==="collect"){let p=await this.executeCollect(r,i,t);return this.handlers?.onExecuted?.(p),[null,null]}let a=await this.factory.createExecutable(r,i,t),o=a.chain.name.toLowerCase(),s=this.config.adapters.find(p=>p.chain.toLowerCase()===o);if(!s)throw new Error(`No adapter registered for chain: ${o}`);return[await s.executor.createTransaction(a),a.chain]}async evaluateResults(r,t,n){let i=this.config.adapters.find(o=>o.chain.toLowerCase()===t.name.toLowerCase());if(!i)throw new Error(`No adapter registered for chain: ${t.name}`);let a=await i.results.getTransactionExecutionResults(r,n);this.handlers?.onExecuted?.(a)}async executeCollect(r,t,n,i){let a=w(r,t);if(!a)throw new Error("WarpActionExecutor: Action not found");let o=await this.factory.getChainInfoForAction(a),s=await this.interpolator.apply(this.config,r),c=await this.factory.getResolvedInputs(o,a,n),p=this.factory.getModifiedInputs(c),u=this.factory.serializer,m=d=>{if(!d.value)return null;let x=u.stringToNative(d.value)[1];return d.input.type==="biguint"?x.toString():d.input.type==="esdt"?{}:x},W=new Headers;W.set("Content-Type","application/json"),W.set("Accept","application/json"),Object.entries(a.destination.headers||{}).forEach(([d,x])=>{W.set(d,x)});let P=Object.fromEntries(p.map(d=>[d.input.as||d.input.name,m(d)])),f=a.destination.method||"GET",g=f==="GET"?void 0:JSON.stringify({...P,...i});y.info("Executing collect",{url:a.destination.url,method:f,headers:W,body:g});try{let d=await fetch(a.destination.url,{method:f,headers:W,body:g}),x=await d.json(),{values:B,results:C}=await nr(s,x,t,p),Q=er(this.config,s,t,C);return{success:d.ok,warp:s,action:t,user:this.config.user?.wallet||null,txHash:null,next:Q,values:B,results:{...C,_DATA:x},messages:rr(s,C)}}catch(d){return y.error("WarpActionExecutor: Error executing collect",d),{success:!1,warp:s,action:t,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{_DATA:d},messages:{}}}}};var M=class{constructor(r,t){this.config=r;this.repository=t;this.interpolator=new S(r,t)}isValid(r){return r.startsWith(l.HttpProtocolPrefix)?!!U(r):!1}async detectFromHtml(r){if(!r.length)return{match:!1,results:[]};let i=[...r.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),o=(await Promise.all(i)).filter(p=>p.match),s=o.length>0,c=o.map(p=>({url:p.url,warp:p.warp}));return{match:s,results:c}}async detect(r,t){let n={match:!1,url:r,warp:null,registryInfo:null,brand:null},i=r.startsWith(l.HttpProtocolPrefix)?U(r):A(r);if(!i)return n;try{let{type:a,identifierBase:o}=i,s=null,c=null,p=null;if(a==="hash"){s=await this.repository.builder.createFromTransactionHash(o,t);let m=await this.repository.registry.getInfoByHash(o,t);c=m.registryInfo,p=m.brand}else if(a==="alias"){let m=await this.repository.registry.getInfoByAlias(o,t);c=m.registryInfo,p=m.brand,m.registryInfo&&(s=await this.repository.builder.createFromTransactionHash(m.registryInfo.hash,t))}let u=s?await this.interpolator.apply(this.config,s):null;return u?{match:!0,url:r,warp:u,registryInfo:c,brand:p}:n}catch(a){return y.error("Error detecting warp link",a),n}}};var or=class{constructor(r){this.config=r}getConfig(){return this.config}setConfig(r){return this.config=r,this}createBuilder(){return new O(this.config)}createExecutor(r){return new H(this.config,r)}async detectWarp(r,t){return new M(this.config,this.config.repository).detect(r,t)}createInscriptionTransaction(r){return this.config.repository.builder.createInscriptionTransaction(r)}async createFromTransaction(r,t=!1){return this.config.repository.builder.createFromTransaction(r,t)}async createFromTransactionHash(r,t){return this.config.repository.builder.createFromTransactionHash(r,t)}getExplorer(r){return G(this.config,r).explorer(r)}getResults(r){return G(this.config,r).results}get factory(){return new R(this.config)}get registry(){return this.config.repository.registry}};var sr=class{constructor(r){this.config=r}async search(r,t,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:r,...t})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}`);return(await i.json()).hits}catch(i){throw y.error("WarpIndex: Error searching for warps: ",i),i}}};0&&(module.exports={CacheTtl,KnownTokens,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpValidator,address,applyResultsToMessages,biguint,boolean,evaluateResultsCommon,extractCollectResults,extractIdentifierInfoFromUrl,findKnownTokenById,findWarpAdapter,findWarpExecutableAction,getLatestProtocolIdentifier,getMainChainInfo,getNextInfo,getWarpActionByIndex,getWarpInfoFromIdentifier,hex,parseResultsOutIndex,replacePlaceholders,shiftBigintBy,string,toPreviewText,toTypedChainInfo,u16,u32,u64,u8});
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"./chunk-3SAEGOMQ.mjs";var l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:n=>n.chain.explorerUrl},ChainAddressHrp:{Placeholder:"chain.addressHrp",Accessor:n=>n.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},I={Option:"option",Optional:"optional",List:"list",Variadic:"variadic",Composite:"composite",String:"string",U8:"u8",U16:"u16",U32:"u32",U64:"u64",Biguint:"biguint",Boolean:"boolean",Address:"address",Hex:"hex"};var R={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},m={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${R.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${R.Brand}.schema.json`,DefaultClientUrl:n=>n==="devnet"?"https://devnet.usewarp.to":n==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],MainChain:{Name:"multiversx",DisplayName:"MultiversX",ApiUrl:n=>n==="devnet"?"https://devnet-api.multiversx.com":n==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:n=>n==="devnet"?"https://devnet-explorer.multiversx.com":n==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:n=>6e3,AddressHrp:"erd",ChainId:n=>n==="devnet"?"D":n==="testnet"?"T":"1",NativeToken:"EGLD"},Registry:{Contract:n=>n==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":n==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query",l.Source.UserWallet],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 U=n=>({name:m.MainChain.Name,displayName:m.MainChain.DisplayName,chainId:m.MainChain.ChainId(n.env),blockTime:m.MainChain.BlockTime(n.env),addressHrp:m.MainChain.AddressHrp,apiUrl:m.MainChain.ApiUrl(n.env),explorerUrl:m.MainChain.ExplorerUrl(n.env),nativeToken:m.MainChain.NativeToken}),xt=(n,t)=>n.explorerUrl+(t?"/"+t:""),L=n=>{if(n==="warp")return`warp:${R.Warp}`;if(n==="brand")return`brand:${R.Brand}`;if(n==="abi")return`abi:${R.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},A=(n,t)=>n?.actions[t-1],_=n=>(n.actions.forEach((t,r)=>{if(t.type!=="link")return[t,r]}),[A(n,1),1]),It=n=>({name:n.name.toString(),displayName:n.display_name.toString(),chainId:n.chain_id.toString(),blockTime:n.block_time.toNumber(),addressHrp:n.address_hrp.toString(),apiUrl:n.api_url.toString(),explorerUrl:n.explorer_url.toString(),nativeToken:n.native_token.toString()}),G=(n,t)=>{let r=n.toString(),[e,i=""]=r.split("."),a=Math.abs(t);if(t>0)return BigInt(e+i.padEnd(a,"0"));if(t<0){let o=e+i;if(a>=o.length)return 0n;let s=o.slice(0,-a)||"0";return BigInt(s)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},X=(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},z=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),Y=(n,t)=>{let r=Object.entries(n.messages||{}).map(([e,i])=>[e,z(i,t)]);return Object.fromEntries(r)};var b=n=>{let t=decodeURIComponent(n);if(t.includes(l.IdentifierParamSeparator)){let[e,i]=t.split(l.IdentifierParamSeparator),a=i.split("?")[0];return{type:e,identifier:i,identifierBase:a}}let r=t.split("?")[0];return r.length===64?{type:l.IdentifierType.Hash,identifier:t,identifierBase:r}:{type:l.IdentifierType.Alias,identifier:t,identifierBase:r}},N=n=>{let t=new URL(n),r=m.SuperClientUrls.includes(t.origin),e=t.searchParams.get(l.IdentifierParamName),i=r&&!e?t.pathname.split("/")[1]:e;if(!i)return null;let a=decodeURIComponent(i);return b(a)};import at from"qr-code-styling";var O=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!N(t):!1}build(t,r){let e=this.config.clientUrl||m.DefaultClientUrl(this.config.env),i=t===l.IdentifierType.Alias?encodeURIComponent(r):encodeURIComponent(t+l.IdentifierParamSeparator+r);return m.SuperClientUrls.includes(e)?`${e}/${i}`:`${e}?${l.IdentifierParamName}=${i}`}buildFromPrefixedIdentifier(t){let r=b(t);return r?this.build(r.type,r.identifierBase):""}generateQrCode(t,r,e=512,i="white",a="black",o="#23F7DD"){let s=this.build(t,r);return new at({type:"svg",width:e,height:e,data:String(s),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},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 ot="https://",Z=(n,t,r,e)=>{let i=t.actions?.[r]?.next||t.next||null;if(!i)return null;if(i.startsWith(ot))return[{identifier:null,url:i}];let[a,o]=i.split("?");if(!o)return[{identifier:a,url:K(a,n)}];let s=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(s.length===0){let f=z(o,{...t.vars,...e}),g=f?`${a}?${f}`:a;return[{identifier:g,url:K(g,n)}]}let c=s[0];if(!c)return[];let p=c.match(/{{([^[]+)\[\]/),u=p?p[1]:null;if(!u||e[u]===void 0)return[];let h=Array.isArray(e[u])?e[u]:[e[u]];if(h.length===0)return[];let W=s.filter(f=>f.includes(`{{${u}[]`)).map(f=>{let g=f.match(/\[\](\.[^}]+)?}}/),d=g&&g[1]||"";return{placeholder:f,field:d?d.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let g=o;for(let{regex:v,field:S}of W){let C=S?st(f,S):f;if(C==null)return null;g=g.replace(v,C)}if(g.includes("{{")||g.includes("}}"))return null;let d=g?`${a}?${g}`:a;return{identifier:d,url:K(d,n)}}).filter(f=>f!==null)},K=(n,t)=>{let[r,e]=n.split("?"),i=b(r)||{type:"alias",identifier:r,identifierBase:r},o=new O(t).build(i.type,i.identifierBase);if(!e)return o;let s=new URL(o);return new URLSearchParams(e).forEach((c,p)=>s.searchParams.set(p,c)),s.toString().replace(/\/\?/,"?")},st=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);var P=class P{static info(...t){P.isTestEnv||console.info(...t)}static warn(...t){P.isTestEnv||console.warn(...t)}static error(...t){P.isTestEnv||console.error(...t)}};P.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var y=P;var E=class{nativeToString(t,r){return`${t}:${r?.toString()??""}`}stringToNative(t){let r=t.split(l.ArgParamsSeparator),e=r[0],i=r.slice(1).join(l.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[a,o]=i.split(l.ArgParamsSeparator);return[`option:${a}`,o||null]}else if(e==="optional"){let[a,o]=i.split(l.ArgParamsSeparator);return[`optional:${a}`,o||null]}else if(e==="list"){let a=i.split(l.ArgParamsSeparator),o=a.slice(0,-1).join(l.ArgParamsSeparator),s=a[a.length-1],p=(s?s.split(","):[]).map(u=>this.stringToNative(`${o}:${u}`)[1]);return[`list:${o}`,p]}else if(e==="variadic"){let a=i.split(l.ArgParamsSeparator),o=a.slice(0,-1).join(l.ArgParamsSeparator),s=a[a.length-1],p=(s?s.split(","):[]).map(u=>this.stringToNative(`${o}:${u}`)[1]);return[`variadic:${o}`,p]}else if(e.startsWith("composite")){let a=e.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),s=i.split(l.ArgCompositeSeparator).map((c,p)=>this.stringToNative(`${a[p]}:${c}`)[1]);return[e,s]}else{if(e==="string")return[e,i];if(e==="uint8"||e==="uint16"||e==="uint32")return[e,Number(i)];if(e==="uint64"||e==="biguint")return[e,BigInt(i||0)];if(e==="bool")return[e,i==="true"];if(e==="address")return[e,i];if(e==="token")return[e,i];if(e==="hex")return[e,i];if(e==="codemeta")return[e,i];if(e==="esdt"){let[a,o,s]=i.split(l.ArgCompositeSeparator);return[e,`${a}|${o}|${s}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}};var tt=async(n,t,r,e)=>{let i=[],a={};for(let[o,s]of Object.entries(n.results||{})){if(s.startsWith(l.Transform.Prefix))continue;let c=ut(s);if(c!==null&&c!==r){a[o]=null;continue}let[p,...u]=s.split("."),h=(W,T)=>T.reduce((f,g)=>f&&f[g]!==void 0?f[g]:null,W);if(p==="out"||p.startsWith("out[")){let W=u.length===0?t?.data||t:h(t,u);i.push(W),a[o]=W}else a[o]=s}return{values:i,results:await pt(n,a,r,e)}},pt=async(n,t,r,e)=>{if(!n.results)return t;let i={...t};return i=lt(i,n,r,e),i=await ct(n,i),i},lt=(n,t,r,e)=>{let i={...n},a=A(t,r)?.inputs||[],o=new E;for(let[s,c]of Object.entries(i))if(typeof c=="string"&&c.startsWith("input.")){let p=c.split(".")[1],u=a.findIndex(W=>W.as===p||W.name===p),h=u!==-1?e[u]?.value:null;i[s]=h?o.stringToNative(h)[1]:null}return i},ct=async(n,t)=>{if(!n.results)return t;let r={...t},e=Object.entries(n.results).filter(([,i])=>i.startsWith(l.Transform.Prefix)).map(([i,a])=>({key:i,code:a.substring(l.Transform.Prefix.length)}));for(let{key:i,code:a}of e)try{let o;typeof window>"u"?o=(await import("./runInVm-BFUZVHHD.mjs")).runInVm:o=(await import("./runInVm-5YQ766M3.mjs")).runInVm,r[i]=await o(a,r)}catch(o){y.error(`Transform error for result '${i}':`,o),r[i]=null}return r},ut=n=>{if(n==="out")return 1;let t=n.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};var dt=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Jt=n=>dt.find(t=>t.id===n)||null;var or=n=>`${I.String}:${n}`,sr=n=>`${I.U8}:${n}`,pr=n=>`${I.U16}:${n}`,lr=n=>`${I.U32}:${n}`,cr=n=>`${I.U64}:${n}`,ur=n=>`${I.Biguint}:${n}`,dr=n=>`${I.Boolean}:${n}`,fr=n=>`${I.Address}:${n}`,gr=n=>`${I.Hex}:${n}`;import ft from"ajv";var rt=class{constructor(t){this.pendingBrand={protocol:L("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.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,r){if(!t)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.schema?.brand||m.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),a=new ft,o=a.compile(i);if(!o(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(o.errors)}`)}};import gt from"ajv";var k=class{constructor(t){this.config=t;this.config=t}async validate(t){let r=[];return 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}}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,a)=>{i&&Object.keys(i).forEach(o=>{o!==o.toUpperCase()&&r.push(`${a} name '${o}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.results,"Result"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(o=>o.type==="contract"),e=t.actions.some(o=>o.type==="query");if(!r&&!e)return[];let i=t.actions.some(o=>o.abi),a=Object.values(t.results||{}).some(o=>o.startsWith("out.")||o.startsWith("event."));return t.results&&!i&&a?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||m.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),a=new gt({strict:!1}),o=a.compile(i);return o(t)?[]:[`Schema validation failed: ${a.errorsText(o.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var H=class{constructor(t){this.config=t;this.pendingWarp={protocol:L("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.validate(e),e}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.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,r=100){return X(t,r)}ensure(t,r){if(!t)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 V=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);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))}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)}}};var w=class w{get(t){let r=w.cache.get(t);return r?Date.now()>r.expiresAt?(w.cache.delete(t),null):r.value:null}set(t,r,e){let i=Date.now()+e*1e3;w.cache.set(t,{value:r,expiresAt:i})}forget(t){w.cache.delete(t)}clear(){w.cache.clear()}};w.cache=new Map;var q=w;var J={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},et={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}`,ChainInfo:(n,t)=>`chain:${n}:${t}`,ChainInfos:n=>`chains:${n}`},D=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new V:t==="memory"?new q:typeof window<"u"&&window.localStorage?new V:new q}set(t,r,e){this.strategy.set(t,r,e)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var B=class{constructor(t){this.config=t;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new E,this.cache=new D(t.cache?.type)}async createExecutable(t,r,e){let i=A(t,r);if(!i)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForAction(i,e),o=await this.getResolvedInputs(a,i,e),s=this.getModifiedInputs(o),c=s.find(x=>x.input.position==="receiver")?.value,p="address"in i?i.address:null,u=c?.split(":")[1]||p;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let h=u,W=this.getPreparedArgs(i,s),T=s.find(x=>x.input.position==="value")?.value||null,f="value"in i?i.value:null,g=BigInt(T?.split(":")[1]||f||0),d=s.filter(x=>x.input.position==="transfer"&&x.value).map(x=>x.value),S=[...("transfers"in i?i.transfers:[])||[],...d||[]],C=s.find(x=>x.input.position==="data")?.value,M="data"in i?i.data||"":null,Q={warp:t,chain:a,action:r,destination:h,args:W,value:g,transfers:S,data:C||M||null,resolvedInputs:s};return this.cache.set(et.WarpExecutable(this.config.env,t.meta?.hash||"",r),Q.resolvedInputs,J.OneWeek),Q}async getChainInfoForAction(t,r){if(r){let e=await this.tryGetChainFromInputs(t,r);if(e)return e}return this.getDefaultChainInfo(t)}async getResolvedInputs(t,r,e){let i=r.inputs||[],a=await Promise.all(e.map(s=>this.preprocessInput(t,s))),o=(s,c)=>{if(s.source==="query"){let p=this.url.searchParams.get(s.name);return p?this.serializer.nativeToString(s.type,p):null}else return s.source===l.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:a[c]||null};return i.map((s,c)=>{let p=o(s,c);return{input:s,value:p||(s.default!==void 0?this.serializer.nativeToString(s.type,s.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 a=Number(t.find(c=>c.input.name===i)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let o=r.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let s=G(o,+a);return{...r,value:`${r.input.type}:${s}`}}else{let a=r.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=G(a,+i);return{...r,value:`${r.input.type}:${o}`}}}else return r})}async preprocessInput(t,r){try{let[e,i]=r.split(l.ArgParamsSeparator,2),a=this.config.adapters.find(o=>o.chain===t.name)?.executor;return a?a.preprocessInput(t,r,e,i):r}catch{return r}}getPreparedArgs(t,r){let e="args"in t?t.args||[]:[];return r.forEach(({input:i,value:a})=>{if(!a||!i.position?.startsWith("arg:"))return;let o=Number(i.position.split(":")[1])-1;e.splice(o,0,a)}),e}async tryGetChainFromInputs(t,r){let e=t.inputs?.findIndex(c=>c.position==="chain");if(e===-1||e===void 0)return null;let i=r[e];if(!i)throw new Error("WarpUtils: Chain input not found");let o=new E().stringToNative(i)[1],s=await this.config.repository.registry.getChainInfo(o);if(!s)throw new Error(`WarpUtils: Chain info not found for ${o}`);return s}async getDefaultChainInfo(t){if(!t.chain)return U(this.config);let r=await this.config.repository.registry.getChainInfo(t.chain,{ttl:J.OneWeek});if(!r)throw new Error(`WarpUtils: Chain info not found for ${t.chain}`);return r}};var $=class{constructor(t,r){this.config=t;this.repository=r}async apply(t,r){let e=this.applyVars(t,r);return await this.applyGlobals(t,e)}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){if(!r?.vars)return r;let e=JSON.stringify(r),i=(a,o)=>{e=e.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(r.vars).forEach(([a,o])=>{if(typeof o!="string")i(a,o);else if(o.startsWith(`${l.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let s=o.split(`${l.Vars.Query}:`)[1],c=new URLSearchParams(t.currentUrl.split("?")[1]).get(s);c&&i(a,c)}else if(o.startsWith(`${l.Vars.Env}:`)){let s=o.split(`${l.Vars.Env}:`)[1],c=t.vars?.[s];c&&i(a,c)}else o===l.Source.UserWallet&&t.user?.wallet?i(a,t.user.wallet):i(a,o)}),JSON.parse(e)}async applyRootGlobals(t,r){let e=JSON.stringify(t),i={config:r,chain:U(r)};return Object.values(l.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(e=e.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(e)}async applyActionGlobals(t){let r=t.chain?await this.repository.registry.getChainInfo(t.chain):U(this.config);if(!r)throw new Error(`Chain info not found for ${t.chain}`);let e=JSON.stringify(t),i={config:this.config,chain:r};return Object.values(l.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(e=e.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(e)}};var j=class{constructor(t,r){this.config=t;this.handlers=r;this.factory=new B(t),this.interpolator=new $(t,t.repository),this.handlers=r}async execute(t,r){let[e,i]=_(t);if(e.type==="collect"){let p=await this.executeCollect(t,i,r);return this.handlers?.onExecuted?.(p),[null,null]}let a=await this.factory.createExecutable(t,i,r),o=a.chain.name.toLowerCase(),s=this.config.adapters.find(p=>p.chain.toLowerCase()===o);if(!s)throw new Error(`No adapter registered for chain: ${o}`);return[await s.executor.createTransaction(a),a.chain]}async evaluateResults(t,r,e){let i=this.config.adapters.find(o=>o.chain.toLowerCase()===r.name.toLowerCase());if(!i)throw new Error(`No adapter registered for chain: ${r.name}`);let a=await i.results.getTransactionExecutionResults(t,e);this.handlers?.onExecuted?.(a)}async executeCollect(t,r,e,i){let a=A(t,r);if(!a)throw new Error("WarpActionExecutor: Action not found");let o=await this.factory.getChainInfoForAction(a),s=await this.interpolator.apply(this.config,t),c=await this.factory.getResolvedInputs(o,a,e),p=this.factory.getModifiedInputs(c),u=this.factory.serializer,h=d=>{if(!d.value)return null;let v=u.stringToNative(d.value)[1];return d.input.type==="biguint"?v.toString():d.input.type==="esdt"?{}:v},W=new Headers;W.set("Content-Type","application/json"),W.set("Accept","application/json"),Object.entries(a.destination.headers||{}).forEach(([d,v])=>{W.set(d,v)});let T=Object.fromEntries(p.map(d=>[d.input.as||d.input.name,h(d)])),f=a.destination.method||"GET",g=f==="GET"?void 0:JSON.stringify({...T,...i});y.info("Executing collect",{url:a.destination.url,method:f,headers:W,body:g});try{let d=await fetch(a.destination.url,{method:f,headers:W,body:g}),v=await d.json(),{values:S,results:C}=await tt(s,v,r,p),M=Z(this.config,s,r,C);return{success:d.ok,warp:s,action:r,user:this.config.user?.wallet||null,txHash:null,next:M,values:S,results:{...C,_DATA:v},messages:Y(s,C)}}catch(d){return y.error("WarpActionExecutor: Error executing collect",d),{success:!1,warp:s,action:r,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{_DATA:d},messages:{}}}}};var F=class{constructor(t,r){this.config=t;this.repository=r;this.interpolator=new $(t,r)}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!N(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),o=(await Promise.all(i)).filter(p=>p.match),s=o.length>0,c=o.map(p=>({url:p.url,warp:p.warp}));return{match:s,results:c}}async detect(t,r){let e={match:!1,url:t,warp:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?N(t):b(t);if(!i)return e;try{let{type:a,identifierBase:o}=i,s=null,c=null,p=null;if(a==="hash"){s=await this.repository.builder.createFromTransactionHash(o,r);let h=await this.repository.registry.getInfoByHash(o,r);c=h.registryInfo,p=h.brand}else if(a==="alias"){let h=await this.repository.registry.getInfoByAlias(o,r);c=h.registryInfo,p=h.brand,h.registryInfo&&(s=await this.repository.builder.createFromTransactionHash(h.registryInfo.hash,r))}let u=s?await this.interpolator.apply(this.config,s):null;return u?{match:!0,url:t,warp:u,registryInfo:c,brand:p}:e}catch(a){return y.error("Error detecting warp link",a),e}}};var nt=class{constructor(t){this.config=t}getConfig(){return this.config}setConfig(t){return this.config=t,this}createBuilder(){return new H(this.config)}createExecutor(t){return new j(this.config,t)}async detectWarp(t,r){return new F(this.config,this.config.repository).detect(t,r)}createInscriptionTransaction(t){return this.config.repository.builder.createInscriptionTransaction(t)}async createFromTransaction(t,r=!1){return this.config.repository.builder.createFromTransaction(t,r)}async createFromTransactionHash(t,r){return this.config.repository.builder.createFromTransactionHash(t,r)}get factory(){return new B(this.config)}get results(){return this.config.repository.results}get registry(){return this.config.repository.registry}};var it=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}`);return(await i.json()).hits}catch(i){throw y.error("WarpIndex: Error searching for warps: ",i),i}}};export{J as CacheTtl,dt as KnownTokens,rt as WarpBrandBuilder,H as WarpBuilder,D as WarpCache,et as WarpCacheKey,nt as WarpClient,m as WarpConfig,l as WarpConstants,j as WarpExecutor,B as WarpFactory,it as WarpIndex,I as WarpInputTypes,$ as WarpInterpolator,O as WarpLinkBuilder,F as WarpLinkDetecter,y as WarpLogger,R as WarpProtocolVersions,E as WarpSerializer,k as WarpValidator,fr as address,Y as applyResultsToMessages,ur as biguint,dr as boolean,pt as evaluateResultsCommon,tt as extractCollectResults,N as extractIdentifierInfoFromUrl,Jt as findKnownTokenById,_ as findWarpExecutableAction,xt as getChainExplorerUrl,L as getLatestProtocolIdentifier,U as getMainChainInfo,Z as getNextInfo,A as getWarpActionByIndex,b as getWarpInfoFromIdentifier,gr as hex,ut as parseResultsOutIndex,z as replacePlaceholders,G as shiftBigintBy,or as string,X as toPreviewText,It as toTypedChainInfo,pr as u16,lr as u32,cr as u64,sr as u8};
|
|
1
|
+
import"./chunk-3SAEGOMQ.mjs";var l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:n=>n.chain.explorerUrl},ChainAddressHrp:{Placeholder:"chain.addressHrp",Accessor:n=>n.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},I={Option:"option",Optional:"optional",List:"list",Variadic:"variadic",Composite:"composite",String:"string",U8:"u8",U16:"u16",U32:"u32",U64:"u64",Biguint:"biguint",Boolean:"boolean",Address:"address",Hex:"hex"};var R={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},m={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${R.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${R.Brand}.schema.json`,DefaultClientUrl:n=>n==="devnet"?"https://devnet.usewarp.to":n==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],MainChain:{Name:"multiversx",DisplayName:"MultiversX",ApiUrl:n=>n==="devnet"?"https://devnet-api.multiversx.com":n==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:n=>n==="devnet"?"https://devnet-explorer.multiversx.com":n==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:n=>6e3,AddressHrp:"erd",ChainId:n=>n==="devnet"?"D":n==="testnet"?"T":"1",NativeToken:"EGLD"},Registry:{Contract:n=>n==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":n==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query",l.Source.UserWallet],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 G=(n,t)=>n.adapters.find(e=>e.chain.toLowerCase()===t.name.toLowerCase())||n.adapters[0],U=n=>({name:m.MainChain.Name,displayName:m.MainChain.DisplayName,chainId:m.MainChain.ChainId(n.env),blockTime:m.MainChain.BlockTime(n.env),addressHrp:m.MainChain.AddressHrp,apiUrl:m.MainChain.ApiUrl(n.env),explorerUrl:m.MainChain.ExplorerUrl(n.env),nativeToken:m.MainChain.NativeToken}),q=n=>{if(n==="warp")return`warp:${R.Warp}`;if(n==="brand")return`brand:${R.Brand}`;if(n==="abi")return`abi:${R.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},A=(n,t)=>n?.actions[t-1],X=n=>(n.actions.forEach((t,r)=>{if(t.type!=="link")return[t,r]}),[A(n,1),1]),It=n=>({name:n.name.toString(),displayName:n.display_name.toString(),chainId:n.chain_id.toString(),blockTime:n.block_time.toNumber(),addressHrp:n.address_hrp.toString(),apiUrl:n.api_url.toString(),explorerUrl:n.explorer_url.toString(),nativeToken:n.native_token.toString()}),z=(n,t)=>{let r=n.toString(),[e,i=""]=r.split("."),a=Math.abs(t);if(t>0)return BigInt(e+i.padEnd(a,"0"));if(t<0){let o=e+i;if(a>=o.length)return 0n;let s=o.slice(0,-a)||"0";return BigInt(s)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},Y=(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},K=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),Z=(n,t)=>{let r=Object.entries(n.messages||{}).map(([e,i])=>[e,K(i,t)]);return Object.fromEntries(r)};var b=n=>{let t=decodeURIComponent(n);if(t.includes(l.IdentifierParamSeparator)){let[e,i]=t.split(l.IdentifierParamSeparator),a=i.split("?")[0];return{type:e,identifier:i,identifierBase:a}}let r=t.split("?")[0];return r.length===64?{type:l.IdentifierType.Hash,identifier:t,identifierBase:r}:{type:l.IdentifierType.Alias,identifier:t,identifierBase:r}},N=n=>{let t=new URL(n),r=m.SuperClientUrls.includes(t.origin),e=t.searchParams.get(l.IdentifierParamName),i=r&&!e?t.pathname.split("/")[1]:e;if(!i)return null;let a=decodeURIComponent(i);return b(a)};import ot from"qr-code-styling";var O=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!N(t):!1}build(t,r){let e=this.config.clientUrl||m.DefaultClientUrl(this.config.env),i=t===l.IdentifierType.Alias?encodeURIComponent(r):encodeURIComponent(t+l.IdentifierParamSeparator+r);return m.SuperClientUrls.includes(e)?`${e}/${i}`:`${e}?${l.IdentifierParamName}=${i}`}buildFromPrefixedIdentifier(t){let r=b(t);return r?this.build(r.type,r.identifierBase):""}generateQrCode(t,r,e=512,i="white",a="black",o="#23F7DD"){let s=this.build(t,r);return new ot({type:"svg",width:e,height:e,data:String(s),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},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 st="https://",tt=(n,t,r,e)=>{let i=t.actions?.[r]?.next||t.next||null;if(!i)return null;if(i.startsWith(st))return[{identifier:null,url:i}];let[a,o]=i.split("?");if(!o)return[{identifier:a,url:J(a,n)}];let s=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(s.length===0){let f=K(o,{...t.vars,...e}),g=f?`${a}?${f}`:a;return[{identifier:g,url:J(g,n)}]}let c=s[0];if(!c)return[];let p=c.match(/{{([^[]+)\[\]/),u=p?p[1]:null;if(!u||e[u]===void 0)return[];let h=Array.isArray(e[u])?e[u]:[e[u]];if(h.length===0)return[];let W=s.filter(f=>f.includes(`{{${u}[]`)).map(f=>{let g=f.match(/\[\](\.[^}]+)?}}/),d=g&&g[1]||"";return{placeholder:f,field:d?d.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(f=>{let g=o;for(let{regex:v,field:S}of W){let C=S?pt(f,S):f;if(C==null)return null;g=g.replace(v,C)}if(g.includes("{{")||g.includes("}}"))return null;let d=g?`${a}?${g}`:a;return{identifier:d,url:J(d,n)}}).filter(f=>f!==null)},J=(n,t)=>{let[r,e]=n.split("?"),i=b(r)||{type:"alias",identifier:r,identifierBase:r},o=new O(t).build(i.type,i.identifierBase);if(!e)return o;let s=new URL(o);return new URLSearchParams(e).forEach((c,p)=>s.searchParams.set(p,c)),s.toString().replace(/\/\?/,"?")},pt=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);var P=class P{static info(...t){P.isTestEnv||console.info(...t)}static warn(...t){P.isTestEnv||console.warn(...t)}static error(...t){P.isTestEnv||console.error(...t)}};P.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var y=P;var E=class{nativeToString(t,r){return`${t}:${r?.toString()??""}`}stringToNative(t){let r=t.split(l.ArgParamsSeparator),e=r[0],i=r.slice(1).join(l.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[a,o]=i.split(l.ArgParamsSeparator);return[`option:${a}`,o||null]}else if(e==="optional"){let[a,o]=i.split(l.ArgParamsSeparator);return[`optional:${a}`,o||null]}else if(e==="list"){let a=i.split(l.ArgParamsSeparator),o=a.slice(0,-1).join(l.ArgParamsSeparator),s=a[a.length-1],p=(s?s.split(","):[]).map(u=>this.stringToNative(`${o}:${u}`)[1]);return[`list:${o}`,p]}else if(e==="variadic"){let a=i.split(l.ArgParamsSeparator),o=a.slice(0,-1).join(l.ArgParamsSeparator),s=a[a.length-1],p=(s?s.split(","):[]).map(u=>this.stringToNative(`${o}:${u}`)[1]);return[`variadic:${o}`,p]}else if(e.startsWith("composite")){let a=e.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),s=i.split(l.ArgCompositeSeparator).map((c,p)=>this.stringToNative(`${a[p]}:${c}`)[1]);return[e,s]}else{if(e==="string")return[e,i];if(e==="uint8"||e==="uint16"||e==="uint32")return[e,Number(i)];if(e==="uint64"||e==="biguint")return[e,BigInt(i||0)];if(e==="bool")return[e,i==="true"];if(e==="address")return[e,i];if(e==="token")return[e,i];if(e==="hex")return[e,i];if(e==="codemeta")return[e,i];if(e==="esdt"){let[a,o,s]=i.split(l.ArgCompositeSeparator);return[e,`${a}|${o}|${s}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}};var rt=async(n,t,r,e)=>{let i=[],a={};for(let[o,s]of Object.entries(n.results||{})){if(s.startsWith(l.Transform.Prefix))continue;let c=dt(s);if(c!==null&&c!==r){a[o]=null;continue}let[p,...u]=s.split("."),h=(W,T)=>T.reduce((f,g)=>f&&f[g]!==void 0?f[g]:null,W);if(p==="out"||p.startsWith("out[")){let W=u.length===0?t?.data||t:h(t,u);i.push(W),a[o]=W}else a[o]=s}return{values:i,results:await lt(n,a,r,e)}},lt=async(n,t,r,e)=>{if(!n.results)return t;let i={...t};return i=ct(i,n,r,e),i=await ut(n,i),i},ct=(n,t,r,e)=>{let i={...n},a=A(t,r)?.inputs||[],o=new E;for(let[s,c]of Object.entries(i))if(typeof c=="string"&&c.startsWith("input.")){let p=c.split(".")[1],u=a.findIndex(W=>W.as===p||W.name===p),h=u!==-1?e[u]?.value:null;i[s]=h?o.stringToNative(h)[1]:null}return i},ut=async(n,t)=>{if(!n.results)return t;let r={...t},e=Object.entries(n.results).filter(([,i])=>i.startsWith(l.Transform.Prefix)).map(([i,a])=>({key:i,code:a.substring(l.Transform.Prefix.length)}));for(let{key:i,code:a}of e)try{let o;typeof window>"u"?o=(await import("./runInVm-BFUZVHHD.mjs")).runInVm:o=(await import("./runInVm-5YQ766M3.mjs")).runInVm,r[i]=await o(a,r)}catch(o){y.error(`Transform error for result '${i}':`,o),r[i]=null}return r},dt=n=>{if(n==="out")return 1;let t=n.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};var ft=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Jt=n=>ft.find(t=>t.id===n)||null;var or=n=>`${I.String}:${n}`,sr=n=>`${I.U8}:${n}`,pr=n=>`${I.U16}:${n}`,lr=n=>`${I.U32}:${n}`,cr=n=>`${I.U64}:${n}`,ur=n=>`${I.Biguint}:${n}`,dr=n=>`${I.Boolean}:${n}`,fr=n=>`${I.Address}:${n}`,gr=n=>`${I.Hex}:${n}`;import gt from"ajv";var et=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.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,r){if(!t)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.schema?.brand||m.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),a=new gt,o=a.compile(i);if(!o(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(o.errors)}`)}};import ht from"ajv";var k=class{constructor(t){this.config=t;this.config=t}async validate(t){let r=[];return 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}}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,a)=>{i&&Object.keys(i).forEach(o=>{o!==o.toUpperCase()&&r.push(`${a} name '${o}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.results,"Result"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(o=>o.type==="contract"),e=t.actions.some(o=>o.type==="query");if(!r&&!e)return[];let i=t.actions.some(o=>o.abi),a=Object.values(t.results||{}).some(o=>o.startsWith("out.")||o.startsWith("event."));return t.results&&!i&&a?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||m.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),a=new ht({strict:!1}),o=a.compile(i);return o(t)?[]:[`Schema validation failed: ${a.errorsText(o.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var H=class{constructor(t){this.config=t;this.pendingWarp={protocol:q("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.validate(e),e}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.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,r=100){return Y(t,r)}ensure(t,r){if(!t)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 V=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);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))}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)}}};var w=class w{get(t){let r=w.cache.get(t);return r?Date.now()>r.expiresAt?(w.cache.delete(t),null):r.value:null}set(t,r,e){let i=Date.now()+e*1e3;w.cache.set(t,{value:r,expiresAt:i})}forget(t){w.cache.delete(t)}clear(){w.cache.clear()}};w.cache=new Map;var L=w;var Q={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},nt={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}`,ChainInfo:(n,t)=>`chain:${n}:${t}`,ChainInfos:n=>`chains:${n}`},D=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new V:t==="memory"?new L:typeof window<"u"&&window.localStorage?new V:new L}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 B=class{constructor(t){this.config=t;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new E,this.cache=new D(t.cache?.type)}async createExecutable(t,r,e){let i=A(t,r);if(!i)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForAction(i,e),o=await this.getResolvedInputs(a,i,e),s=this.getModifiedInputs(o),c=s.find(x=>x.input.position==="receiver")?.value,p="address"in i?i.address:null,u=c?.split(":")[1]||p;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let h=u,W=this.getPreparedArgs(i,s),T=s.find(x=>x.input.position==="value")?.value||null,f="value"in i?i.value:null,g=BigInt(T?.split(":")[1]||f||0),d=s.filter(x=>x.input.position==="transfer"&&x.value).map(x=>x.value),S=[...("transfers"in i?i.transfers:[])||[],...d||[]],C=s.find(x=>x.input.position==="data")?.value,M="data"in i?i.data||"":null,_={warp:t,chain:a,action:r,destination:h,args:W,value:g,transfers:S,data:C||M||null,resolvedInputs:s};return this.cache.set(nt.WarpExecutable(this.config.env,t.meta?.hash||"",r),_.resolvedInputs,Q.OneWeek),_}async getChainInfoForAction(t,r){if(r){let e=await this.tryGetChainFromInputs(t,r);if(e)return e}return this.getDefaultChainInfo(t)}async getResolvedInputs(t,r,e){let i=r.inputs||[],a=await Promise.all(e.map(s=>this.preprocessInput(t,s))),o=(s,c)=>{if(s.source==="query"){let p=this.url.searchParams.get(s.name);return p?this.serializer.nativeToString(s.type,p):null}else return s.source===l.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:a[c]||null};return i.map((s,c)=>{let p=o(s,c);return{input:s,value:p||(s.default!==void 0?this.serializer.nativeToString(s.type,s.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 a=Number(t.find(c=>c.input.name===i)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let o=r.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let s=z(o,+a);return{...r,value:`${r.input.type}:${s}`}}else{let a=r.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=z(a,+i);return{...r,value:`${r.input.type}:${o}`}}}else return r})}async preprocessInput(t,r){try{let[e,i]=r.split(l.ArgParamsSeparator,2),a=this.config.adapters.find(o=>o.chain===t.name)?.executor;return a?a.preprocessInput(t,r,e,i):r}catch{return r}}getPreparedArgs(t,r){let e="args"in t?t.args||[]:[];return r.forEach(({input:i,value:a})=>{if(!a||!i.position?.startsWith("arg:"))return;let o=Number(i.position.split(":")[1])-1;e.splice(o,0,a)}),e}async tryGetChainFromInputs(t,r){let e=t.inputs?.findIndex(c=>c.position==="chain");if(e===-1||e===void 0)return null;let i=r[e];if(!i)throw new Error("WarpUtils: Chain input not found");let o=new E().stringToNative(i)[1],s=await this.config.repository.registry.getChainInfo(o);if(!s)throw new Error(`WarpUtils: Chain info not found for ${o}`);return s}async getDefaultChainInfo(t){if(!t.chain)return U(this.config);let r=await this.config.repository.registry.getChainInfo(t.chain,{ttl:Q.OneWeek});if(!r)throw new Error(`WarpUtils: Chain info not found for ${t.chain}`);return r}};var $=class{constructor(t,r){this.config=t;this.repository=r}async apply(t,r){let e=this.applyVars(t,r);return await this.applyGlobals(t,e)}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){if(!r?.vars)return r;let e=JSON.stringify(r),i=(a,o)=>{e=e.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(r.vars).forEach(([a,o])=>{if(typeof o!="string")i(a,o);else if(o.startsWith(`${l.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let s=o.split(`${l.Vars.Query}:`)[1],c=new URLSearchParams(t.currentUrl.split("?")[1]).get(s);c&&i(a,c)}else if(o.startsWith(`${l.Vars.Env}:`)){let s=o.split(`${l.Vars.Env}:`)[1],c=t.vars?.[s];c&&i(a,c)}else o===l.Source.UserWallet&&t.user?.wallet?i(a,t.user.wallet):i(a,o)}),JSON.parse(e)}async applyRootGlobals(t,r){let e=JSON.stringify(t),i={config:r,chain:U(r)};return Object.values(l.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(e=e.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(e)}async applyActionGlobals(t){let r=t.chain?await this.repository.registry.getChainInfo(t.chain):U(this.config);if(!r)throw new Error(`Chain info not found for ${t.chain}`);let e=JSON.stringify(t),i={config:this.config,chain:r};return Object.values(l.Globals).forEach(a=>{let o=a.Accessor(i);o!=null&&(e=e.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(e)}};var j=class{constructor(t,r){this.config=t;this.handlers=r;this.factory=new B(t),this.interpolator=new $(t,t.repository),this.handlers=r}async execute(t,r){let[e,i]=X(t);if(e.type==="collect"){let p=await this.executeCollect(t,i,r);return this.handlers?.onExecuted?.(p),[null,null]}let a=await this.factory.createExecutable(t,i,r),o=a.chain.name.toLowerCase(),s=this.config.adapters.find(p=>p.chain.toLowerCase()===o);if(!s)throw new Error(`No adapter registered for chain: ${o}`);return[await s.executor.createTransaction(a),a.chain]}async evaluateResults(t,r,e){let i=this.config.adapters.find(o=>o.chain.toLowerCase()===r.name.toLowerCase());if(!i)throw new Error(`No adapter registered for chain: ${r.name}`);let a=await i.results.getTransactionExecutionResults(t,e);this.handlers?.onExecuted?.(a)}async executeCollect(t,r,e,i){let a=A(t,r);if(!a)throw new Error("WarpActionExecutor: Action not found");let o=await this.factory.getChainInfoForAction(a),s=await this.interpolator.apply(this.config,t),c=await this.factory.getResolvedInputs(o,a,e),p=this.factory.getModifiedInputs(c),u=this.factory.serializer,h=d=>{if(!d.value)return null;let v=u.stringToNative(d.value)[1];return d.input.type==="biguint"?v.toString():d.input.type==="esdt"?{}:v},W=new Headers;W.set("Content-Type","application/json"),W.set("Accept","application/json"),Object.entries(a.destination.headers||{}).forEach(([d,v])=>{W.set(d,v)});let T=Object.fromEntries(p.map(d=>[d.input.as||d.input.name,h(d)])),f=a.destination.method||"GET",g=f==="GET"?void 0:JSON.stringify({...T,...i});y.info("Executing collect",{url:a.destination.url,method:f,headers:W,body:g});try{let d=await fetch(a.destination.url,{method:f,headers:W,body:g}),v=await d.json(),{values:S,results:C}=await rt(s,v,r,p),M=tt(this.config,s,r,C);return{success:d.ok,warp:s,action:r,user:this.config.user?.wallet||null,txHash:null,next:M,values:S,results:{...C,_DATA:v},messages:Z(s,C)}}catch(d){return y.error("WarpActionExecutor: Error executing collect",d),{success:!1,warp:s,action:r,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{_DATA:d},messages:{}}}}};var F=class{constructor(t,r){this.config=t;this.repository=r;this.interpolator=new $(t,r)}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!N(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),o=(await Promise.all(i)).filter(p=>p.match),s=o.length>0,c=o.map(p=>({url:p.url,warp:p.warp}));return{match:s,results:c}}async detect(t,r){let e={match:!1,url:t,warp:null,registryInfo:null,brand:null},i=t.startsWith(l.HttpProtocolPrefix)?N(t):b(t);if(!i)return e;try{let{type:a,identifierBase:o}=i,s=null,c=null,p=null;if(a==="hash"){s=await this.repository.builder.createFromTransactionHash(o,r);let h=await this.repository.registry.getInfoByHash(o,r);c=h.registryInfo,p=h.brand}else if(a==="alias"){let h=await this.repository.registry.getInfoByAlias(o,r);c=h.registryInfo,p=h.brand,h.registryInfo&&(s=await this.repository.builder.createFromTransactionHash(h.registryInfo.hash,r))}let u=s?await this.interpolator.apply(this.config,s):null;return u?{match:!0,url:t,warp:u,registryInfo:c,brand:p}:e}catch(a){return y.error("Error detecting warp link",a),e}}};var it=class{constructor(t){this.config=t}getConfig(){return this.config}setConfig(t){return this.config=t,this}createBuilder(){return new H(this.config)}createExecutor(t){return new j(this.config,t)}async detectWarp(t,r){return new F(this.config,this.config.repository).detect(t,r)}createInscriptionTransaction(t){return this.config.repository.builder.createInscriptionTransaction(t)}async createFromTransaction(t,r=!1){return this.config.repository.builder.createFromTransaction(t,r)}async createFromTransactionHash(t,r){return this.config.repository.builder.createFromTransactionHash(t,r)}getExplorer(t){return G(this.config,t).explorer(t)}getResults(t){return G(this.config,t).results}get factory(){return new B(this.config)}get registry(){return this.config.repository.registry}};var at=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}`);return(await i.json()).hits}catch(i){throw y.error("WarpIndex: Error searching for warps: ",i),i}}};export{Q as CacheTtl,ft as KnownTokens,et as WarpBrandBuilder,H as WarpBuilder,D as WarpCache,nt as WarpCacheKey,it as WarpClient,m as WarpConfig,l as WarpConstants,j as WarpExecutor,B as WarpFactory,at as WarpIndex,I as WarpInputTypes,$ as WarpInterpolator,O as WarpLinkBuilder,F as WarpLinkDetecter,y as WarpLogger,R as WarpProtocolVersions,E as WarpSerializer,k as WarpValidator,fr as address,Z as applyResultsToMessages,ur as biguint,dr as boolean,lt as evaluateResultsCommon,rt as extractCollectResults,N as extractIdentifierInfoFromUrl,Jt as findKnownTokenById,G as findWarpAdapter,X as findWarpExecutableAction,q as getLatestProtocolIdentifier,U as getMainChainInfo,tt as getNextInfo,A as getWarpActionByIndex,b as getWarpInfoFromIdentifier,gr as hex,dt as parseResultsOutIndex,K as replacePlaceholders,z as shiftBigintBy,or as string,Y as toPreviewText,It as toTypedChainInfo,pr as u16,lr as u32,cr as u64,sr as u8};
|