@vleap/warps 3.0.0-alpha.58 → 3.0.0-alpha.59
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 +6 -2
- package/dist/index.d.ts +6 -2
- package/dist/index.js +3 -3
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -389,6 +389,10 @@ declare const WarpConfig: {
|
|
|
389
389
|
AvailableActionInputPositions: WarpActionInputPosition[];
|
|
390
390
|
};
|
|
391
391
|
|
|
392
|
+
declare enum WarpChainName {
|
|
393
|
+
Multiversx = "multiversx",
|
|
394
|
+
Sui = "sui"
|
|
395
|
+
}
|
|
392
396
|
declare const WarpConstants: {
|
|
393
397
|
HttpProtocolPrefix: string;
|
|
394
398
|
IdentifierParamName: string;
|
|
@@ -458,7 +462,7 @@ declare const findWarpExecutableAction: (warp: Warp) => {
|
|
|
458
462
|
actionIndex: WarpActionIndex;
|
|
459
463
|
};
|
|
460
464
|
declare const toTypedChainInfo: (chainInfo: any) => WarpChainInfo;
|
|
461
|
-
declare const shiftBigintBy: (value: bigint | string, decimals: number) => bigint;
|
|
465
|
+
declare const shiftBigintBy: (value: bigint | string | number, decimals: number) => bigint;
|
|
462
466
|
declare const toPreviewText: (text: string, maxChars?: number) => string;
|
|
463
467
|
declare const replacePlaceholders: (message: string, bag: Record<string, any>) => string;
|
|
464
468
|
declare const applyResultsToMessages: (warp: Warp, results: Record<string, any>) => Record<string, string>;
|
|
@@ -713,4 +717,4 @@ declare class WarpValidator {
|
|
|
713
717
|
private validateSchema;
|
|
714
718
|
}
|
|
715
719
|
|
|
716
|
-
export { type Adapter, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, type BaseWarpBuilder, CacheTtl, type CombinedWarpBuilder, 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, 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, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, biguint, boolean, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById, findWarpAdapterByPrefix, findWarpAdapterForChain, findWarpDefaultAdapter, findWarpExecutableAction, getLatestProtocolIdentifier, getMainChainInfo, getNextInfo, getWarpActionByIndex, getWarpInfoFromIdentifier, hex, parseResultsOutIndex, replacePlaceholders, shiftBigintBy, string, toPreviewText, toTypedChainInfo, u16, u32, u64, u8 };
|
|
720
|
+
export { type Adapter, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, type BaseWarpBuilder, CacheTtl, type CombinedWarpBuilder, 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, WarpChainName, 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, 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, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, biguint, boolean, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById, findWarpAdapterByPrefix, findWarpAdapterForChain, findWarpDefaultAdapter, findWarpExecutableAction, getLatestProtocolIdentifier, getMainChainInfo, getNextInfo, getWarpActionByIndex, getWarpInfoFromIdentifier, hex, parseResultsOutIndex, replacePlaceholders, shiftBigintBy, string, toPreviewText, toTypedChainInfo, u16, u32, u64, u8 };
|
package/dist/index.d.ts
CHANGED
|
@@ -389,6 +389,10 @@ declare const WarpConfig: {
|
|
|
389
389
|
AvailableActionInputPositions: WarpActionInputPosition[];
|
|
390
390
|
};
|
|
391
391
|
|
|
392
|
+
declare enum WarpChainName {
|
|
393
|
+
Multiversx = "multiversx",
|
|
394
|
+
Sui = "sui"
|
|
395
|
+
}
|
|
392
396
|
declare const WarpConstants: {
|
|
393
397
|
HttpProtocolPrefix: string;
|
|
394
398
|
IdentifierParamName: string;
|
|
@@ -458,7 +462,7 @@ declare const findWarpExecutableAction: (warp: Warp) => {
|
|
|
458
462
|
actionIndex: WarpActionIndex;
|
|
459
463
|
};
|
|
460
464
|
declare const toTypedChainInfo: (chainInfo: any) => WarpChainInfo;
|
|
461
|
-
declare const shiftBigintBy: (value: bigint | string, decimals: number) => bigint;
|
|
465
|
+
declare const shiftBigintBy: (value: bigint | string | number, decimals: number) => bigint;
|
|
462
466
|
declare const toPreviewText: (text: string, maxChars?: number) => string;
|
|
463
467
|
declare const replacePlaceholders: (message: string, bag: Record<string, any>) => string;
|
|
464
468
|
declare const applyResultsToMessages: (warp: Warp, results: Record<string, any>) => Record<string, string>;
|
|
@@ -713,4 +717,4 @@ declare class WarpValidator {
|
|
|
713
717
|
private validateSchema;
|
|
714
718
|
}
|
|
715
719
|
|
|
716
|
-
export { type Adapter, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, type BaseWarpBuilder, CacheTtl, type CombinedWarpBuilder, 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, 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, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, biguint, boolean, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById, findWarpAdapterByPrefix, findWarpAdapterForChain, findWarpDefaultAdapter, findWarpExecutableAction, getLatestProtocolIdentifier, getMainChainInfo, getNextInfo, getWarpActionByIndex, getWarpInfoFromIdentifier, hex, parseResultsOutIndex, replacePlaceholders, shiftBigintBy, string, toPreviewText, toTypedChainInfo, u16, u32, u64, u8 };
|
|
720
|
+
export { type Adapter, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, type BaseWarpBuilder, CacheTtl, type CombinedWarpBuilder, 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, WarpChainName, 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, 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, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, biguint, boolean, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById, findWarpAdapterByPrefix, findWarpAdapterForChain, findWarpDefaultAdapter, 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 Er=Object.create;var J=Object.defineProperty;var Tr=Object.getOwnPropertyDescriptor;var Pr=Object.getOwnPropertyNames;var Rr=Object.getPrototypeOf,Sr=Object.prototype.hasOwnProperty;var dr=(n,r)=>()=>(n&&(r=n(n=0)),r);var X=(n,r)=>{for(var t in r)J(n,t,{get:r[t],enumerable:!0})},fr=(n,r,t,e)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of Pr(r))!Sr.call(n,a)&&a!==t&&J(n,a,{get:()=>r[a],enumerable:!(e=Tr(r,a))||e.enumerable});return n};var Z=(n,r,t)=>(t=n!=null?Er(Rr(n)):{},fr(r||!n||!n.__esModule?J(t,"default",{value:n,enumerable:!0}):t,n)),Br=n=>fr(J({},"__esModule",{value:!0}),n);var Wr={};X(Wr,{runInVm:()=>Or});var Vr,Or,yr=dr(()=>{"use strict";Vr=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')}),Or=async(n,r)=>{let t;try{t=Vr("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 e=new t({timeout:2e3,sandbox:{result:r},eval:!1,wasm:!1});return n.trim().startsWith("(")&&n.includes("=>")?e.run(`(${n})(result)`):null}});var xr={};X(xr,{runInVm:()=>Dr});var Dr,vr=dr(()=>{"use strict";Dr=async(n,r)=>new Promise((t,e)=>{try{let a=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"}),s=URL.createObjectURL(a),i=new Worker(s);i.onmessage=function(o){o.data.error?e(new Error(o.data.error)):t(o.data.result),i.terminate(),URL.revokeObjectURL(s)},i.onerror=function(o){e(new Error(`Error in transform: ${o.message}`)),i.terminate(),URL.revokeObjectURL(s)},i.postMessage(r)}catch(a){return e(a)}})});var _r={};X(_r,{CacheTtl:()=>_,KnownTokens:()=>Ir,WarpBrandBuilder:()=>sr,WarpBuilder:()=>or,WarpCache:()=>j,WarpCacheKey:()=>pr,WarpClient:()=>lr,WarpConfig:()=>m,WarpConstants:()=>l,WarpExecutor:()=>q,WarpFactory:()=>U,WarpIndex:()=>G,WarpInputTypes:()=>I,WarpInterpolator:()=>N,WarpLinkBuilder:()=>$,WarpLinkDetecter:()=>z,WarpLogger:()=>x,WarpProtocolVersions:()=>S,WarpSerializer:()=>P,WarpValidator:()=>k,address:()=>Kr,applyResultsToMessages:()=>er,biguint:()=>zr,boolean:()=>Jr,evaluateResultsCommon:()=>vr,extractCollectResults:()=>ir,extractIdentifierInfoFromUrl:()=>O,findKnownTokenById:()=>kr,findWarpAdapterByPrefix:()=>B,findWarpAdapterForChain:()=>W,findWarpDefaultAdapter:()=>Y,findWarpExecutableAction:()=>rr,getLatestProtocolIdentifier:()=>F,getMainChainInfo:()=>V,getNextInfo:()=>ar,getWarpActionByIndex:()=>T,getWarpInfoFromIdentifier:()=>A,hex:()=>Qr,parseResultsOutIndex:()=>Cr,replacePlaceholders:()=>Q,shiftBigintBy:()=>K,string:()=>Hr,toPreviewText:()=>tr,toTypedChainInfo:()=>Br,u16:()=>jr,u32:()=>qr,u64:()=>Gr,u8:()=>Mr});module.exports=Sr(_r);var l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:[":","."],IdentifierParamSeparatorDefault:".",IdentifierChainDefault:"mvx",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.chain.name]},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 S={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${S.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${S.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"},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 Y=n=>{let r=n.find(t=>t.chain.toLowerCase()===m.MainChain.Name.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${m.MainChain.Name}`);return r},W=(n,r)=>{let t=r.find(e=>e.chain.toLowerCase()===n.toLowerCase());if(!t)throw new Error(`Adapter not found for chain: ${n}`);return t},B=(n,r)=>{let t=r.find(e=>e.prefix.toLowerCase()===n.toLowerCase());if(!t)throw new Error(`Adapter not found for prefix: ${n}`);return t},V=n=>({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}),F=n=>{if(n==="warp")return`warp:${S.Warp}`;if(n==="brand")return`brand:${S.Brand}`;if(n==="abi")return`abi:${S.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},T=(n,r)=>n?.actions[r-1],rr=n=>(n.actions.forEach((r,t)=>{if(r.type!=="link")return{action:r,actionIndex:t}}),{action:T(n,1),actionIndex:1}),Br=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()}),K=(n,r)=>{let t=n.toString(),[e,a=""]=t.split("."),s=Math.abs(r);if(r>0)return BigInt(e+a.padEnd(s,"0"));if(r<0){let i=e+a;if(s>=i.length)return 0n;let o=i.slice(0,-s)||"0";return BigInt(o)}else return t.includes(".")?BigInt(t.split(".")[0]):BigInt(t)},tr=(n,r=100)=>{if(!n)return"";let t=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return t=t.startsWith("- ")?t.slice(2):t,t=t.length>r?t.substring(0,t.lastIndexOf(" ",r))+"...":t,t},Q=(n,r)=>n.replace(/\{\{([^}]+)\}\}/g,(t,e)=>r[e]||""),er=(n,r)=>{let t=Object.entries(n.messages||{}).map(([e,a])=>[e,Q(a,r)]);return Object.fromEntries(t)};var $r=n=>{let r=l.IdentifierParamSeparator,t=-1,e="";for(let a of r){let s=n.indexOf(a);s!==-1&&(t===-1||s<t)&&(t=s,e=a)}return t!==-1?{separator:e,index:t}:null},hr=n=>{let r=$r(n);if(!r)return[n];let{separator:t,index:e}=r,a=n.substring(0,e),s=n.substring(e+t.length),i=hr(s);return[a,...i]},A=n=>{let r=decodeURIComponent(n).trim(),t=r.split("?")[0],e=hr(t);if(t.length===64&&/^[a-fA-F0-9]+$/.test(t))return{chainPrefix:l.IdentifierChainDefault,type:l.IdentifierType.Hash,identifier:r,identifierBase:t};if(e.length===2&&/^[a-zA-Z0-9]{62}$/.test(e[0])&&/^[a-zA-Z0-9]{2}$/.test(e[1]))return null;if(e.length===3){let[a,s,i]=e;if(s===l.IdentifierType.Alias||s===l.IdentifierType.Hash){let o=r.includes("?")?i+r.substring(r.indexOf("?")):i;return{chainPrefix:a,type:s,identifier:o,identifierBase:i}}}if(e.length===2){let[a,s]=e;if(a===l.IdentifierType.Alias||a===l.IdentifierType.Hash){let i=r.includes("?")?s+r.substring(r.indexOf("?")):s;return{chainPrefix:l.IdentifierChainDefault,type:a,identifier:i,identifierBase:s}}}if(e.length===2){let[a,s]=e;if(a!==l.IdentifierType.Alias&&a!==l.IdentifierType.Hash){let i=r.includes("?")?s+r.substring(r.indexOf("?")):s;return{chainPrefix:a,type:l.IdentifierType.Alias,identifier:i,identifierBase:s}}}return{chainPrefix:l.IdentifierChainDefault,type:l.IdentifierType.Alias,identifier:r,identifierBase:t}},O=n=>{let r=new URL(n),e=r.searchParams.get(l.IdentifierParamName);if(e||(e=r.pathname.split("/")[1]),!e)return null;let a=decodeURIComponent(e);return A(a)};var mr=Z(require("qr-code-styling"));var $=class{constructor(r,t){this.config=r;this.adapters=t}isValid(r){return r.startsWith(l.HttpProtocolPrefix)?!!O(r):!1}build(r,t,e){let a=this.config.clientUrl||m.DefaultClientUrl(this.config.env),s=W(r,this.adapters),i=t===l.IdentifierType.Alias?e:t+l.IdentifierParamSeparatorDefault+e,o=s.prefix+l.IdentifierParamSeparatorDefault+i,p=encodeURIComponent(o);return m.SuperClientUrls.includes(a)?`${a}/${p}`:`${a}?${l.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(r){let t=A(r);if(!t)return null;let e=B(t.chainPrefix,this.adapters);return e?this.build(e.chain,t.type,t.identifierBase):null}generateQrCode(r,t,e,a=512,s="white",i="black",o="#23F7DD"){let p=W(r,this.adapters),c=this.build(p.chain,t,e);return new mr.default({type:"svg",width:a,height:a,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Ur="https://",ar=(n,r,t,e,a)=>{let s=t.actions?.[e]?.next||t.next||null;if(!s)return null;if(s.startsWith(Ur))return[{identifier:null,url:s}];let[i,o]=s.split("?");if(!o)return[{identifier:i,url:nr(r,i,n)}];let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let h=Q(o,{...t.vars,...a}),y=h?`${i}?${h}`:i;return[{identifier:y,url:nr(r,y,n)}]}let c=p[0];if(!c)return[];let u=c.match(/{{([^[]+)\[\]/),g=u?u[1]:null;if(!g||a[g]===void 0)return[];let f=Array.isArray(a[g])?a[g]:[a[g]];if(f.length===0)return[];let v=p.filter(h=>h.includes(`{{${g}[]`)).map(h=>{let y=h.match(/\[\](\.[^}]+)?}}/),d=y&&y[1]||"";return{placeholder:h,field:d?d.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(h=>{let y=o;for(let{regex:C,field:L}of v){let b=L?Nr(h,L):h;if(b==null)return null;y=y.replace(C,b)}if(y.includes("{{")||y.includes("}}"))return null;let d=y?`${i}?${y}`:i;return{identifier:d,url:nr(r,d,n)}}).filter(h=>h!==null)},nr=(n,r,t)=>{let[e,a]=r.split("?"),s=A(e)||{type:"alias",identifier:e,identifierBase:e},i=new $(t,[n]).build(n.chain,s.type,s.identifierBase);if(!a)return i;let o=new URL(i);return new URLSearchParams(a).forEach((p,c)=>o.searchParams.set(c,p)),o.toString().replace(/\/\?/,"?")},Nr=(n,r)=>r.split(".").reduce((t,e)=>t?.[e],n);var D=class D{static info(...r){D.isTestEnv||console.info(...r)}static warn(...r){D.isTestEnv||console.warn(...r)}static error(...r){D.isTestEnv||console.error(...r)}};D.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var x=D;var P=class{nativeToString(r,t){return`${r}:${t?.toString()??""}`}stringToNative(r){let t=r.split(l.ArgParamsSeparator),e=t[0],a=t.slice(1).join(l.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[s,i]=a.split(l.ArgParamsSeparator);return[`option:${s}`,i||null]}else if(e==="optional"){let[s,i]=a.split(l.ArgParamsSeparator);return[`optional:${s}`,i||null]}else if(e==="list"){let s=a.split(l.ArgParamsSeparator),i=s.slice(0,-1).join(l.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`list:${i}`,c]}else if(e==="variadic"){let s=a.split(l.ArgParamsSeparator),i=s.slice(0,-1).join(l.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`variadic:${i}`,c]}else if(e.startsWith("composite")){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=a.split(l.ArgCompositeSeparator).map((p,c)=>this.stringToNative(`${s[c]}:${p}`)[1]);return[e,o]}else{if(e==="string")return[e,a];if(e==="uint8"||e==="uint16"||e==="uint32")return[e,Number(a)];if(e==="uint64"||e==="biguint")return[e,BigInt(a||0)];if(e==="bool")return[e,a==="true"];if(e==="address")return[e,a];if(e==="token")return[e,a];if(e==="hex")return[e,a];if(e==="codemeta")return[e,a];if(e==="esdt"){let[s,i,o]=a.split(l.ArgCompositeSeparator);return[e,`${s}|${i}|${o}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}};var ir=async(n,r,t,e)=>{let a=[],s={};for(let[i,o]of Object.entries(n.results||{})){if(o.startsWith(l.Transform.Prefix))continue;let p=Cr(o);if(p!==null&&p!==t){s[i]=null;continue}let[c,...u]=o.split("."),g=(f,v)=>v.reduce((E,h)=>E&&E[h]!==void 0?E[h]:null,f);if(c==="out"||c.startsWith("out[")){let f=u.length===0?r?.data||r:g(r,u);a.push(f),s[i]=f}else s[i]=o}return{values:a,results:await vr(n,s,t,e)}},vr=async(n,r,t,e)=>{if(!n.results)return r;let a={...r};return a=Dr(a,n,t,e),a=await Fr(n,a),a},Dr=(n,r,t,e)=>{let a={...n},s=T(r,t)?.inputs||[],i=new P;for(let[o,p]of Object.entries(a))if(typeof p=="string"&&p.startsWith("input.")){let c=p.split(".")[1],u=s.findIndex(f=>f.as===c||f.name===c),g=u!==-1?e[u]?.value:null;a[o]=g?i.stringToNative(g)[1]:null}return a},Fr=async(n,r)=>{if(!n.results)return r;let t={...r},e=Object.entries(n.results).filter(([,a])=>a.startsWith(l.Transform.Prefix)).map(([a,s])=>({key:a,code:s.substring(l.Transform.Prefix.length)}));for(let{key:a,code:s}of e)try{let i;typeof window>"u"?i=(await Promise.resolve().then(()=>(Wr(),gr))).runInVm:i=(await Promise.resolve().then(()=>(xr(),yr))).runInVm,t[a]=await i(s,t)}catch(i){x.error(`Transform error for result '${a}':`,i),t[a]=null}return t},Cr=n=>{if(n==="out")return 1;let r=n.match(/^out\[(\d+)\]/);return r?parseInt(r[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};var Ir=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],kr=n=>Ir.find(r=>r.id===n)||null;var Hr=n=>`${I.String}:${n}`,Mr=n=>`${I.U8}:${n}`,jr=n=>`${I.U16}:${n}`,qr=n=>`${I.U32}:${n}`,Gr=n=>`${I.U64}:${n}`,zr=n=>`${I.Biguint}:${n}`,Jr=n=>`${I.Boolean}:${n}`,Kr=n=>`${I.Address}:${n}`,Qr=n=>`${I.Hex}:${n}`;var wr=Z(require("ajv"));var sr=class{constructor(r){this.pendingBrand={protocol:F("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}setName(r){return this.pendingBrand.name=r,this}setDescription(r){return this.pendingBrand.description=r,this}setLogo(r){return this.pendingBrand.logo=r,this}setUrls(r){return this.pendingBrand.urls=r,this}setColors(r){return this.pendingBrand.colors=r,this}setCta(r){return this.pendingBrand.cta=r,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(r,t){if(!r)throw new Error(`Warp: ${t}`)}async ensureValidSchema(r){let t=this.config.schema?.brand||m.LatestBrandSchemaUrl,a=await(await fetch(t)).json(),s=new wr.default,i=s.compile(a);if(!i(r))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(i.errors)}`)}};var Ar=Z(require("ajv"));var k=class{constructor(r){this.config=r;this.config=r}async validate(r){let t=[];return t.push(...this.validateMaxOneValuePosition(r)),t.push(...this.validateVariableNamesAndResultNamesUppercase(r)),t.push(...this.validateAbiIsSetIfApplicable(r)),t.push(...await this.validateSchema(r)),{valid:t.length===0,errors:t}}validateMaxOneValuePosition(r){return r.actions.filter(e=>e.inputs?e.inputs.some(a=>a.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let t=[],e=(a,s)=>{a&&Object.keys(a).forEach(i=>{i!==i.toUpperCase()&&t.push(`${s} name '${i}' must be uppercase`)})};return e(r.vars,"Variable"),e(r.results,"Result"),t}validateAbiIsSetIfApplicable(r){let t=r.actions.some(i=>i.type==="contract"),e=r.actions.some(i=>i.type==="query");if(!t&&!e)return[];let a=r.actions.some(i=>i.abi),s=Object.values(r.results||{}).some(i=>i.startsWith("out.")||i.startsWith("event."));return r.results&&!a&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let t=this.config.schema?.warp||m.LatestWarpSchemaUrl,a=await(await fetch(t)).json(),s=new Ar.default({strict:!1}),i=s.compile(a);return i(r)?[]:[`Schema validation failed: ${s.errorsText(i.errors)}`]}catch(t){return[`Schema validation failed: ${t instanceof Error?t.message:String(t)}`]}}};var or=class{constructor(r){this.config=r;this.pendingWarp={protocol:F("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.validate(e),e}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 tr(r,t)}ensure(r,t){if(!r)throw new Error(t)}async validate(r){let e=await new k(this.config).validate(r);if(!e.valid)throw new Error(e.errors.join(`
|
|
12
|
-
`))}};var H=class{constructor(r="warp-cache"){this.prefix=r}getKey(r){return`${this.prefix}:${r}`}get(r){try{let t=localStorage.getItem(this.getKey(r));if(!t)return null;let e=JSON.parse(t);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(r)),null):e.value}catch{return null}}set(r,t,e){let a={value:t,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(r),JSON.stringify(a))}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 R=class R{get(r){let t=R.cache.get(r);return t?Date.now()>t.expiresAt?(R.cache.delete(r),null):t.value:null}set(r,t,e){let a=Date.now()+e*1e3;R.cache.set(r,{value:t,expiresAt:a})}forget(r){R.cache.delete(r)}clear(){R.cache.clear()}};R.cache=new Map;var M=R;var _={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},pr={Warp:(n,r)=>`warp:${n}:${r}`,WarpAbi:(n,r)=>`warp-abi:${n}:${r}`,WarpExecutable:(n,r,t)=>`warp-exec:${n}:${r}:${t}`,RegistryInfo:(n,r)=>`registry-info:${n}:${r}`,Brand:(n,r)=>`brand:${n}:${r}`,ChainInfo:(n,r)=>`chain:${n}:${r}`,ChainInfos:n=>`chains:${n}`},j=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new H:r==="memory"?new M:typeof window<"u"&&window.localStorage?new H:new M}set(r,t,e){this.strategy.set(r,t,e)}get(r){return this.strategy.get(r)}forget(r){this.strategy.forget(r)}clear(){this.strategy.clear()}};var U=class{constructor(r,t){this.config=r;this.adapters=t;if(!r.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(r.currentUrl),this.serializer=new P,this.cache=new j(r.cache?.type)}async createExecutable(r,t,e){let a=T(r,t);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForAction(a,e),i=await this.getResolvedInputs(s,a,e),o=this.getModifiedInputs(i),p=o.find(w=>w.input.position==="receiver")?.value,c="address"in a?a.address:null,u=p?.split(":")[1]||c;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let g=u,f=this.getPreparedArgs(a,o),v=o.find(w=>w.input.position==="value")?.value||null,E="value"in a?a.value:null,h=BigInt(v?.split(":")[1]||E||0),y=o.filter(w=>w.input.position==="transfer"&&w.value).map(w=>w.value),C=[...("transfers"in a?a.transfers:[])||[],...y||[]],L=o.find(w=>w.input.position==="data")?.value,b="data"in a?a.data||"":null,ur={warp:r,chain:s,action:t,destination:g,args:f,value:h,transfers:C,data:L||b||null,resolvedInputs:o};return this.cache.set(pr.WarpExecutable(this.config.env,r.meta?.hash||"",t),ur.resolvedInputs,_.OneWeek),ur}async getChainInfoForAction(r,t){if(t){let e=await this.tryGetChainFromInputs(r,t);if(e)return e}return this.getDefaultChainInfo(r)}async getResolvedInputs(r,t,e){let a=t.inputs||[],s=await Promise.all(e.map(o=>this.preprocessInput(r,o))),i=(o,p)=>{if(o.source==="query"){let c=this.url.searchParams.get(o.name);return c?this.serializer.nativeToString(o.type,c):null}else return o.source===l.Source.UserWallet?this.config.user?.wallets?.[r.name]?this.serializer.nativeToString("address",this.config.user.wallets[r.name]):null:s[p]||null};return a.map((o,p)=>{let c=i(o,p);return{input:o,value:c||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(r){return r.map((t,e)=>{if(t.input.modifier?.startsWith("scale:")){let[,a]=t.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(r.find(p=>p.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let i=t.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let o=K(i,+s);return{...t,value:`${t.input.type}:${o}`}}else{let s=t.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let i=K(s,+a);return{...t,value:`${t.input.type}:${i}`}}}else return t})}async preprocessInput(r,t){try{let[e,a]=t.split(l.ArgParamsSeparator,2);return W(r.name,this.adapters).executor.preprocessInput(r,t,e,a)}catch{return t}}getPreparedArgs(r,t){let e="args"in r?r.args||[]:[];return t.forEach(({input:a,value:s})=>{if(!s||!a.position?.startsWith("arg:"))return;let i=Number(a.position.split(":")[1])-1;e.splice(i,0,s)}),e}async tryGetChainFromInputs(r,t){let e=r.inputs?.findIndex(c=>c.position==="chain");if(e===-1||e===void 0)return null;let a=t[e];if(!a)throw new Error("WarpUtils: Chain input not found");let i=new P().stringToNative(a)[1],p=await W(i,this.adapters).registry.getChainInfo(i);if(!p)throw new Error(`WarpUtils: Chain info not found for ${i}`);return p}async getDefaultChainInfo(r){if(!r.chain)return V(this.config);let e=await Y(this.adapters).registry.getChainInfo(r.chain,{ttl:_.OneWeek});if(!e)throw new Error(`WarpUtils: Chain info not found for ${r.chain}`);return e}};var N=class{constructor(r,t){this.config=r;this.adapter=t}async apply(r,t){let e=this.applyVars(r,t);return await this.applyGlobals(r,e)}async applyGlobals(r,t){let e={...t};return e.actions=await Promise.all(e.actions.map(async a=>await this.applyActionGlobals(a))),e=await this.applyRootGlobals(e,r),e}applyVars(r,t){if(!t?.vars)return t;let e=JSON.stringify(t),a=(s,i)=>{e=e.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),i.toString())};return Object.entries(t.vars).forEach(([s,i])=>{if(typeof i!="string")a(s,i);else if(i.startsWith(`${l.Vars.Query}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=i.split(`${l.Vars.Query}:`)[1],p=new URLSearchParams(r.currentUrl.split("?")[1]).get(o);p&&a(s,p)}else if(i.startsWith(`${l.Vars.Env}:`)){let o=i.split(`${l.Vars.Env}:`)[1],p=r.vars?.[o];p&&a(s,p)}else if(i===l.Source.UserWallet&&r.user?.wallets?.[this.adapter.chain]){let o=r.user.wallets[this.adapter.chain];o&&a(s,o)}else a(s,i)}),JSON.parse(e)}async applyRootGlobals(r,t){let e=JSON.stringify(r),a={config:t,chain:V(t)};return Object.values(l.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}async applyActionGlobals(r){let t=r.chain?await this.adapter.registry.getChainInfo(r.chain):V(this.config);if(!t)throw new Error(`Chain info not found for ${r.chain}`);let e=JSON.stringify(r),a={config:this.config,chain:t};return Object.values(l.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}};var q=class{constructor(r,t,e){this.config=r;this.adapters=t;this.handlers=e;this.factory=new U(r,t),this.handlers=e}async execute(r,t){let{action:e,actionIndex:a}=rr(r);if(e.type==="collect"){let c=await this.executeCollect(r,a,t);return c.success?this.handlers?.onExecuted?.(c):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null}}let s=await this.factory.createExecutable(r,a,t),i=s.chain.name.toLowerCase(),o=this.adapters.find(c=>c.chain.toLowerCase()===i);if(!o)throw new Error(`No adapter registered for chain: ${i}`);return{tx:await o.executor.createTransaction(s),chain:s.chain}}async evaluateResults(r,t,e){let a=this.adapters.find(i=>i.chain.toLowerCase()===t.name.toLowerCase());if(!a)throw new Error(`No adapter registered for chain: ${t.name}`);let s=await a.results.getTransactionExecutionResults(r,e);this.handlers?.onExecuted?.(s)}async executeCollect(r,t,e,a){let s=T(r,t);if(!s)throw new Error("WarpActionExecutor: Action not found");let i=await this.factory.getChainInfoForAction(s),o=W(i.name,this.adapters),p=await new N(this.config,o).apply(this.config,r),c=await this.factory.getResolvedInputs(i,s,e),u=this.factory.getModifiedInputs(c),g=this.factory.serializer,f=d=>{if(!d.value)return null;let C=g.stringToNative(d.value)[1];return d.input.type==="biguint"?C.toString():d.input.type==="esdt"?{}:C},v=new Headers;v.set("Content-Type","application/json"),v.set("Accept","application/json"),Object.entries(s.destination.headers||{}).forEach(([d,C])=>{v.set(d,C)});let E=Object.fromEntries(u.map(d=>[d.input.as||d.input.name,f(d)])),h=s.destination.method||"GET",y=h==="GET"?void 0:JSON.stringify({...E,...a});x.info("Executing collect",{url:s.destination.url,method:h,headers:v,body:y});try{let d=await fetch(s.destination.url,{method:h,headers:v,body:y}),C=await d.json(),{values:L,results:b}=await ir(p,C,t,u),cr=ar(this.config,o,p,t,b);return{success:d.ok,warp:p,action:t,user:this.config.user?.wallets?.[i.name]||null,txHash:null,next:cr,values:L,results:{...b,_DATA:C},messages:er(p,b)}}catch(d){return x.error("WarpActionExecutor: Error executing collect",d),{success:!1,warp:p,action:t,user:this.config.user?.wallets?.[i.name]||null,txHash:null,next:null,values:[],results:{_DATA:d},messages:{}}}}};var G=class{constructor(r){this.config=r}async search(r,t,e){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let a=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...e},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:r,...t})});if(!a.ok)throw new Error(`WarpIndex: search failed with status ${a.status}`);return(await a.json()).hits}catch(a){throw x.error("WarpIndex: Error searching for warps: ",a),a}}};var z=class{constructor(r,t){this.config=r;this.adapters=t}isValid(r){return r.startsWith(l.HttpProtocolPrefix)?!!O(r):!1}async detectFromHtml(r){if(!r.length)return{match:!1,results:[]};let a=[...r.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),i=(await Promise.all(a)).filter(c=>c.match),o=i.length>0,p=i.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:p}}async detect(r,t){let e={match:!1,url:r,warp:null,chain:null,registryInfo:null,brand:null},a=r.startsWith(l.HttpProtocolPrefix)?O(r):A(r);if(!a)return e;try{let{type:s,identifierBase:i}=a,o=null,p=null,c=null,u=B(a.chainPrefix,this.adapters);if(s==="hash"){o=await u.builder().createFromTransactionHash(i,t);let f=await u.registry.getInfoByHash(i,t);p=f.registryInfo,c=f.brand}else if(s==="alias"){let f=await u.registry.getInfoByAlias(i,t);p=f.registryInfo,c=f.brand,f.registryInfo&&(o=await u.builder().createFromTransactionHash(f.registryInfo.hash,t))}let g=o?await new N(this.config,u).apply(this.config,o):null;return g?{match:!0,url:r,warp:g,chain:u.chain,registryInfo:p,brand:c}:e}catch(s){return x.error("Error detecting warp link",s),e}}};var lr=class{constructor(r,t){this.config=r;this.adapters=t}getConfig(){return this.config}setConfig(r){return this.config=r,this}getAdapters(){return this.adapters}addAdapter(r){return this.adapters.push(r),this}createExecutor(r){return new q(this.config,this.adapters,r)}async detectWarp(r,t){return new z(this.config,this.adapters).detect(r,t)}async executeWarp(r,t,e,a={}){let s=await this.detectWarp(r,a.cache);if(!s.match||!s.warp)throw new Error("Warp not found");let i=this.createExecutor(e),{tx:o,chain:p}=await i.execute(s.warp,t);return{tx:o,chain:p,evaluateResults:async u=>{if(!p||!o||!s.warp)throw new Error("Warp not found");await i.evaluateResults(s.warp,p,u)}}}createInscriptionTransaction(r,t){return W(r,this.adapters).builder().createInscriptionTransaction(t)}async createFromTransaction(r,t,e=!1){return W(r,this.adapters).builder().createFromTransaction(t,e)}async createFromTransactionHash(r,t){let e=A(r);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return B(e.chainPrefix,this.adapters).builder().createFromTransactionHash(r,t)}getExplorer(r){return W(r.name,this.adapters).explorer(r)}getResults(r){return W(r.name,this.adapters).results}async getRegistry(r){let t=W(r,this.adapters).registry;return await t.init(),t}get factory(){return new U(this.config,this.adapters)}get index(){return new G(this.config)}get linkBuilder(){return new $(this.config,this.adapters)}createBuilder(r){return W(r,this.adapters).builder()}createAbiBuilder(r){return W(r,this.adapters).abiBuilder()}createBrandBuilder(r){return W(r,this.adapters).brandBuilder()}};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,findWarpAdapterByPrefix,findWarpAdapterForChain,findWarpDefaultAdapter,findWarpExecutableAction,getLatestProtocolIdentifier,getMainChainInfo,getNextInfo,getWarpActionByIndex,getWarpInfoFromIdentifier,hex,parseResultsOutIndex,replacePlaceholders,shiftBigintBy,string,toPreviewText,toTypedChainInfo,u16,u32,u64,u8});
|
|
11
|
+
`],{type:"application/javascript"}),s=URL.createObjectURL(a),i=new Worker(s);i.onmessage=function(o){o.data.error?e(new Error(o.data.error)):t(o.data.result),i.terminate(),URL.revokeObjectURL(s)},i.onerror=function(o){e(new Error(`Error in transform: ${o.message}`)),i.terminate(),URL.revokeObjectURL(s)},i.postMessage(r)}catch(a){return e(a)}})});var Xr={};X(Xr,{CacheTtl:()=>_,KnownTokens:()=>wr,WarpBrandBuilder:()=>sr,WarpBuilder:()=>or,WarpCache:()=>j,WarpCacheKey:()=>pr,WarpChainName:()=>hr,WarpClient:()=>lr,WarpConfig:()=>m,WarpConstants:()=>l,WarpExecutor:()=>q,WarpFactory:()=>U,WarpIndex:()=>G,WarpInputTypes:()=>I,WarpInterpolator:()=>N,WarpLinkBuilder:()=>$,WarpLinkDetecter:()=>z,WarpLogger:()=>x,WarpProtocolVersions:()=>S,WarpSerializer:()=>P,WarpValidator:()=>k,address:()=>Qr,applyResultsToMessages:()=>er,biguint:()=>Jr,boolean:()=>Kr,evaluateResultsCommon:()=>Cr,extractCollectResults:()=>ir,extractIdentifierInfoFromUrl:()=>O,findKnownTokenById:()=>Hr,findWarpAdapterByPrefix:()=>B,findWarpAdapterForChain:()=>W,findWarpDefaultAdapter:()=>Y,findWarpExecutableAction:()=>rr,getLatestProtocolIdentifier:()=>F,getMainChainInfo:()=>V,getNextInfo:()=>ar,getWarpActionByIndex:()=>T,getWarpInfoFromIdentifier:()=>A,hex:()=>_r,parseResultsOutIndex:()=>Ir,replacePlaceholders:()=>Q,shiftBigintBy:()=>K,string:()=>Mr,toPreviewText:()=>tr,toTypedChainInfo:()=>$r,u16:()=>qr,u32:()=>Gr,u64:()=>zr,u8:()=>jr});module.exports=Br(Xr);var hr=(t=>(t.Multiversx="multiversx",t.Sui="sui",t))(hr||{}),l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:[":","."],IdentifierParamSeparatorDefault:".",IdentifierChainDefault:"mvx",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.chain.name]},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 S={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${S.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${S.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"},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 Y=n=>{let r=n.find(t=>t.chain.toLowerCase()===m.MainChain.Name.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${m.MainChain.Name}`);return r},W=(n,r)=>{let t=r.find(e=>e.chain.toLowerCase()===n.toLowerCase());if(!t)throw new Error(`Adapter not found for chain: ${n}`);return t},B=(n,r)=>{let t=r.find(e=>e.prefix.toLowerCase()===n.toLowerCase());if(!t)throw new Error(`Adapter not found for prefix: ${n}`);return t},V=n=>({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}),F=n=>{if(n==="warp")return`warp:${S.Warp}`;if(n==="brand")return`brand:${S.Brand}`;if(n==="abi")return`abi:${S.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},T=(n,r)=>n?.actions[r-1],rr=n=>(n.actions.forEach((r,t)=>{if(r.type!=="link")return{action:r,actionIndex:t}}),{action:T(n,1),actionIndex:1}),$r=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()}),K=(n,r)=>{let t=n.toString(),[e,a=""]=t.split("."),s=Math.abs(r);if(r>0)return BigInt(e+a.padEnd(s,"0"));if(r<0){let i=e+a;if(s>=i.length)return 0n;let o=i.slice(0,-s)||"0";return BigInt(o)}else return t.includes(".")?BigInt(t.split(".")[0]):BigInt(t)},tr=(n,r=100)=>{if(!n)return"";let t=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return t=t.startsWith("- ")?t.slice(2):t,t=t.length>r?t.substring(0,t.lastIndexOf(" ",r))+"...":t,t},Q=(n,r)=>n.replace(/\{\{([^}]+)\}\}/g,(t,e)=>r[e]||""),er=(n,r)=>{let t=Object.entries(n.messages||{}).map(([e,a])=>[e,Q(a,r)]);return Object.fromEntries(t)};var Ur=n=>{let r=l.IdentifierParamSeparator,t=-1,e="";for(let a of r){let s=n.indexOf(a);s!==-1&&(t===-1||s<t)&&(t=s,e=a)}return t!==-1?{separator:e,index:t}:null},mr=n=>{let r=Ur(n);if(!r)return[n];let{separator:t,index:e}=r,a=n.substring(0,e),s=n.substring(e+t.length),i=mr(s);return[a,...i]},A=n=>{let r=decodeURIComponent(n).trim(),t=r.split("?")[0],e=mr(t);if(t.length===64&&/^[a-fA-F0-9]+$/.test(t))return{chainPrefix:l.IdentifierChainDefault,type:l.IdentifierType.Hash,identifier:r,identifierBase:t};if(e.length===2&&/^[a-zA-Z0-9]{62}$/.test(e[0])&&/^[a-zA-Z0-9]{2}$/.test(e[1]))return null;if(e.length===3){let[a,s,i]=e;if(s===l.IdentifierType.Alias||s===l.IdentifierType.Hash){let o=r.includes("?")?i+r.substring(r.indexOf("?")):i;return{chainPrefix:a,type:s,identifier:o,identifierBase:i}}}if(e.length===2){let[a,s]=e;if(a===l.IdentifierType.Alias||a===l.IdentifierType.Hash){let i=r.includes("?")?s+r.substring(r.indexOf("?")):s;return{chainPrefix:l.IdentifierChainDefault,type:a,identifier:i,identifierBase:s}}}if(e.length===2){let[a,s]=e;if(a!==l.IdentifierType.Alias&&a!==l.IdentifierType.Hash){let i=r.includes("?")?s+r.substring(r.indexOf("?")):s;return{chainPrefix:a,type:l.IdentifierType.Alias,identifier:i,identifierBase:s}}}return{chainPrefix:l.IdentifierChainDefault,type:l.IdentifierType.Alias,identifier:r,identifierBase:t}},O=n=>{let r=new URL(n),e=r.searchParams.get(l.IdentifierParamName);if(e||(e=r.pathname.split("/")[1]),!e)return null;let a=decodeURIComponent(e);return A(a)};var gr=Z(require("qr-code-styling"));var $=class{constructor(r,t){this.config=r;this.adapters=t}isValid(r){return r.startsWith(l.HttpProtocolPrefix)?!!O(r):!1}build(r,t,e){let a=this.config.clientUrl||m.DefaultClientUrl(this.config.env),s=W(r,this.adapters),i=t===l.IdentifierType.Alias?e:t+l.IdentifierParamSeparatorDefault+e,o=s.prefix+l.IdentifierParamSeparatorDefault+i,p=encodeURIComponent(o);return m.SuperClientUrls.includes(a)?`${a}/${p}`:`${a}?${l.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(r){let t=A(r);if(!t)return null;let e=B(t.chainPrefix,this.adapters);return e?this.build(e.chain,t.type,t.identifierBase):null}generateQrCode(r,t,e,a=512,s="white",i="black",o="#23F7DD"){let p=W(r,this.adapters),c=this.build(p.chain,t,e);return new gr.default({type:"svg",width:a,height:a,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Nr="https://",ar=(n,r,t,e,a)=>{let s=t.actions?.[e]?.next||t.next||null;if(!s)return null;if(s.startsWith(Nr))return[{identifier:null,url:s}];let[i,o]=s.split("?");if(!o)return[{identifier:i,url:nr(r,i,n)}];let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let h=Q(o,{...t.vars,...a}),y=h?`${i}?${h}`:i;return[{identifier:y,url:nr(r,y,n)}]}let c=p[0];if(!c)return[];let u=c.match(/{{([^[]+)\[\]/),g=u?u[1]:null;if(!g||a[g]===void 0)return[];let f=Array.isArray(a[g])?a[g]:[a[g]];if(f.length===0)return[];let v=p.filter(h=>h.includes(`{{${g}[]`)).map(h=>{let y=h.match(/\[\](\.[^}]+)?}}/),d=y&&y[1]||"";return{placeholder:h,field:d?d.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(h=>{let y=o;for(let{regex:C,field:L}of v){let b=L?Lr(h,L):h;if(b==null)return null;y=y.replace(C,b)}if(y.includes("{{")||y.includes("}}"))return null;let d=y?`${i}?${y}`:i;return{identifier:d,url:nr(r,d,n)}}).filter(h=>h!==null)},nr=(n,r,t)=>{let[e,a]=r.split("?"),s=A(e)||{type:"alias",identifier:e,identifierBase:e},i=new $(t,[n]).build(n.chain,s.type,s.identifierBase);if(!a)return i;let o=new URL(i);return new URLSearchParams(a).forEach((p,c)=>o.searchParams.set(c,p)),o.toString().replace(/\/\?/,"?")},Lr=(n,r)=>r.split(".").reduce((t,e)=>t?.[e],n);var D=class D{static info(...r){D.isTestEnv||console.info(...r)}static warn(...r){D.isTestEnv||console.warn(...r)}static error(...r){D.isTestEnv||console.error(...r)}};D.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var x=D;var P=class{nativeToString(r,t){return`${r}:${t?.toString()??""}`}stringToNative(r){let t=r.split(l.ArgParamsSeparator),e=t[0],a=t.slice(1).join(l.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[s,i]=a.split(l.ArgParamsSeparator);return[`option:${s}`,i||null]}else if(e==="optional"){let[s,i]=a.split(l.ArgParamsSeparator);return[`optional:${s}`,i||null]}else if(e==="list"){let s=a.split(l.ArgParamsSeparator),i=s.slice(0,-1).join(l.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`list:${i}`,c]}else if(e==="variadic"){let s=a.split(l.ArgParamsSeparator),i=s.slice(0,-1).join(l.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`variadic:${i}`,c]}else if(e.startsWith("composite")){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=a.split(l.ArgCompositeSeparator).map((p,c)=>this.stringToNative(`${s[c]}:${p}`)[1]);return[e,o]}else{if(e==="string")return[e,a];if(e==="uint8"||e==="uint16"||e==="uint32")return[e,Number(a)];if(e==="uint64"||e==="biguint")return[e,BigInt(a||0)];if(e==="bool")return[e,a==="true"];if(e==="address")return[e,a];if(e==="token")return[e,a];if(e==="hex")return[e,a];if(e==="codemeta")return[e,a];if(e==="esdt"){let[s,i,o]=a.split(l.ArgCompositeSeparator);return[e,`${s}|${i}|${o}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}};var ir=async(n,r,t,e)=>{let a=[],s={};for(let[i,o]of Object.entries(n.results||{})){if(o.startsWith(l.Transform.Prefix))continue;let p=Ir(o);if(p!==null&&p!==t){s[i]=null;continue}let[c,...u]=o.split("."),g=(f,v)=>v.reduce((E,h)=>E&&E[h]!==void 0?E[h]:null,f);if(c==="out"||c.startsWith("out[")){let f=u.length===0?r?.data||r:g(r,u);a.push(f),s[i]=f}else s[i]=o}return{values:a,results:await Cr(n,s,t,e)}},Cr=async(n,r,t,e)=>{if(!n.results)return r;let a={...r};return a=Fr(a,n,t,e),a=await kr(n,a),a},Fr=(n,r,t,e)=>{let a={...n},s=T(r,t)?.inputs||[],i=new P;for(let[o,p]of Object.entries(a))if(typeof p=="string"&&p.startsWith("input.")){let c=p.split(".")[1],u=s.findIndex(f=>f.as===c||f.name===c),g=u!==-1?e[u]?.value:null;a[o]=g?i.stringToNative(g)[1]:null}return a},kr=async(n,r)=>{if(!n.results)return r;let t={...r},e=Object.entries(n.results).filter(([,a])=>a.startsWith(l.Transform.Prefix)).map(([a,s])=>({key:a,code:s.substring(l.Transform.Prefix.length)}));for(let{key:a,code:s}of e)try{let i;typeof window>"u"?i=(await Promise.resolve().then(()=>(yr(),Wr))).runInVm:i=(await Promise.resolve().then(()=>(vr(),xr))).runInVm,t[a]=await i(s,t)}catch(i){x.error(`Transform error for result '${a}':`,i),t[a]=null}return t},Ir=n=>{if(n==="out")return 1;let r=n.match(/^out\[(\d+)\]/);return r?parseInt(r[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};var wr=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Hr=n=>wr.find(r=>r.id===n)||null;var Mr=n=>`${I.String}:${n}`,jr=n=>`${I.U8}:${n}`,qr=n=>`${I.U16}:${n}`,Gr=n=>`${I.U32}:${n}`,zr=n=>`${I.U64}:${n}`,Jr=n=>`${I.Biguint}:${n}`,Kr=n=>`${I.Boolean}:${n}`,Qr=n=>`${I.Address}:${n}`,_r=n=>`${I.Hex}:${n}`;var Ar=Z(require("ajv"));var sr=class{constructor(r){this.pendingBrand={protocol:F("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}setName(r){return this.pendingBrand.name=r,this}setDescription(r){return this.pendingBrand.description=r,this}setLogo(r){return this.pendingBrand.logo=r,this}setUrls(r){return this.pendingBrand.urls=r,this}setColors(r){return this.pendingBrand.colors=r,this}setCta(r){return this.pendingBrand.cta=r,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(r,t){if(!r)throw new Error(`Warp: ${t}`)}async ensureValidSchema(r){let t=this.config.schema?.brand||m.LatestBrandSchemaUrl,a=await(await fetch(t)).json(),s=new Ar.default,i=s.compile(a);if(!i(r))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(i.errors)}`)}};var br=Z(require("ajv"));var k=class{constructor(r){this.config=r;this.config=r}async validate(r){let t=[];return t.push(...this.validateMaxOneValuePosition(r)),t.push(...this.validateVariableNamesAndResultNamesUppercase(r)),t.push(...this.validateAbiIsSetIfApplicable(r)),t.push(...await this.validateSchema(r)),{valid:t.length===0,errors:t}}validateMaxOneValuePosition(r){return r.actions.filter(e=>e.inputs?e.inputs.some(a=>a.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let t=[],e=(a,s)=>{a&&Object.keys(a).forEach(i=>{i!==i.toUpperCase()&&t.push(`${s} name '${i}' must be uppercase`)})};return e(r.vars,"Variable"),e(r.results,"Result"),t}validateAbiIsSetIfApplicable(r){let t=r.actions.some(i=>i.type==="contract"),e=r.actions.some(i=>i.type==="query");if(!t&&!e)return[];let a=r.actions.some(i=>i.abi),s=Object.values(r.results||{}).some(i=>i.startsWith("out.")||i.startsWith("event."));return r.results&&!a&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let t=this.config.schema?.warp||m.LatestWarpSchemaUrl,a=await(await fetch(t)).json(),s=new br.default({strict:!1}),i=s.compile(a);return i(r)?[]:[`Schema validation failed: ${s.errorsText(i.errors)}`]}catch(t){return[`Schema validation failed: ${t instanceof Error?t.message:String(t)}`]}}};var or=class{constructor(r){this.config=r;this.pendingWarp={protocol:F("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.validate(e),e}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 tr(r,t)}ensure(r,t){if(!r)throw new Error(t)}async validate(r){let e=await new k(this.config).validate(r);if(!e.valid)throw new Error(e.errors.join(`
|
|
12
|
+
`))}};var H=class{constructor(r="warp-cache"){this.prefix=r}getKey(r){return`${this.prefix}:${r}`}get(r){try{let t=localStorage.getItem(this.getKey(r));if(!t)return null;let e=JSON.parse(t);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(r)),null):e.value}catch{return null}}set(r,t,e){let a={value:t,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(r),JSON.stringify(a))}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 R=class R{get(r){let t=R.cache.get(r);return t?Date.now()>t.expiresAt?(R.cache.delete(r),null):t.value:null}set(r,t,e){let a=Date.now()+e*1e3;R.cache.set(r,{value:t,expiresAt:a})}forget(r){R.cache.delete(r)}clear(){R.cache.clear()}};R.cache=new Map;var M=R;var _={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},pr={Warp:(n,r)=>`warp:${n}:${r}`,WarpAbi:(n,r)=>`warp-abi:${n}:${r}`,WarpExecutable:(n,r,t)=>`warp-exec:${n}:${r}:${t}`,RegistryInfo:(n,r)=>`registry-info:${n}:${r}`,Brand:(n,r)=>`brand:${n}:${r}`,ChainInfo:(n,r)=>`chain:${n}:${r}`,ChainInfos:n=>`chains:${n}`},j=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new H:r==="memory"?new M:typeof window<"u"&&window.localStorage?new H:new M}set(r,t,e){this.strategy.set(r,t,e)}get(r){return this.strategy.get(r)}forget(r){this.strategy.forget(r)}clear(){this.strategy.clear()}};var U=class{constructor(r,t){this.config=r;this.adapters=t;if(!r.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(r.currentUrl),this.serializer=new P,this.cache=new j(r.cache?.type)}async createExecutable(r,t,e){let a=T(r,t);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForAction(a,e),i=await this.getResolvedInputs(s,a,e),o=this.getModifiedInputs(i),p=o.find(w=>w.input.position==="receiver")?.value,c="address"in a?a.address:null,u=p?.split(":")[1]||c;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let g=u,f=this.getPreparedArgs(a,o),v=o.find(w=>w.input.position==="value")?.value||null,E="value"in a?a.value:null,h=BigInt(v?.split(":")[1]||E||0),y=o.filter(w=>w.input.position==="transfer"&&w.value).map(w=>w.value),C=[...("transfers"in a?a.transfers:[])||[],...y||[]],L=o.find(w=>w.input.position==="data")?.value,b="data"in a?a.data||"":null,ur={warp:r,chain:s,action:t,destination:g,args:f,value:h,transfers:C,data:L||b||null,resolvedInputs:o};return this.cache.set(pr.WarpExecutable(this.config.env,r.meta?.hash||"",t),ur.resolvedInputs,_.OneWeek),ur}async getChainInfoForAction(r,t){if(t){let e=await this.tryGetChainFromInputs(r,t);if(e)return e}return this.getDefaultChainInfo(r)}async getResolvedInputs(r,t,e){let a=t.inputs||[],s=await Promise.all(e.map(o=>this.preprocessInput(r,o))),i=(o,p)=>{if(o.source==="query"){let c=this.url.searchParams.get(o.name);return c?this.serializer.nativeToString(o.type,c):null}else return o.source===l.Source.UserWallet?this.config.user?.wallets?.[r.name]?this.serializer.nativeToString("address",this.config.user.wallets[r.name]):null:s[p]||null};return a.map((o,p)=>{let c=i(o,p);return{input:o,value:c||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(r){return r.map((t,e)=>{if(t.input.modifier?.startsWith("scale:")){let[,a]=t.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(r.find(p=>p.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let i=t.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let o=K(i,+s);return{...t,value:`${t.input.type}:${o}`}}else{let s=t.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let i=K(s,+a);return{...t,value:`${t.input.type}:${i}`}}}else return t})}async preprocessInput(r,t){try{let[e,a]=t.split(l.ArgParamsSeparator,2);return W(r.name,this.adapters).executor.preprocessInput(r,t,e,a)}catch{return t}}getPreparedArgs(r,t){let e="args"in r?r.args||[]:[];return t.forEach(({input:a,value:s})=>{if(!s||!a.position?.startsWith("arg:"))return;let i=Number(a.position.split(":")[1])-1;e.splice(i,0,s)}),e}async tryGetChainFromInputs(r,t){let e=r.inputs?.findIndex(c=>c.position==="chain");if(e===-1||e===void 0)return null;let a=t[e];if(!a)throw new Error("WarpUtils: Chain input not found");let i=new P().stringToNative(a)[1],p=await W(i,this.adapters).registry.getChainInfo(i);if(!p)throw new Error(`WarpUtils: Chain info not found for ${i}`);return p}async getDefaultChainInfo(r){if(!r.chain)return V(this.config);let e=await Y(this.adapters).registry.getChainInfo(r.chain,{ttl:_.OneWeek});if(!e)throw new Error(`WarpUtils: Chain info not found for ${r.chain}`);return e}};var N=class{constructor(r,t){this.config=r;this.adapter=t}async apply(r,t){let e=this.applyVars(r,t);return await this.applyGlobals(r,e)}async applyGlobals(r,t){let e={...t};return e.actions=await Promise.all(e.actions.map(async a=>await this.applyActionGlobals(a))),e=await this.applyRootGlobals(e,r),e}applyVars(r,t){if(!t?.vars)return t;let e=JSON.stringify(t),a=(s,i)=>{e=e.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),i.toString())};return Object.entries(t.vars).forEach(([s,i])=>{if(typeof i!="string")a(s,i);else if(i.startsWith(`${l.Vars.Query}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=i.split(`${l.Vars.Query}:`)[1],p=new URLSearchParams(r.currentUrl.split("?")[1]).get(o);p&&a(s,p)}else if(i.startsWith(`${l.Vars.Env}:`)){let o=i.split(`${l.Vars.Env}:`)[1],p=r.vars?.[o];p&&a(s,p)}else if(i===l.Source.UserWallet&&r.user?.wallets?.[this.adapter.chain]){let o=r.user.wallets[this.adapter.chain];o&&a(s,o)}else a(s,i)}),JSON.parse(e)}async applyRootGlobals(r,t){let e=JSON.stringify(r),a={config:t,chain:V(t)};return Object.values(l.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}async applyActionGlobals(r){let t=r.chain?await this.adapter.registry.getChainInfo(r.chain):V(this.config);if(!t)throw new Error(`Chain info not found for ${r.chain}`);let e=JSON.stringify(r),a={config:this.config,chain:t};return Object.values(l.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}};var q=class{constructor(r,t,e){this.config=r;this.adapters=t;this.handlers=e;this.factory=new U(r,t),this.handlers=e}async execute(r,t){let{action:e,actionIndex:a}=rr(r);if(e.type==="collect"){let c=await this.executeCollect(r,a,t);return c.success?this.handlers?.onExecuted?.(c):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null}}let s=await this.factory.createExecutable(r,a,t),i=s.chain.name.toLowerCase(),o=this.adapters.find(c=>c.chain.toLowerCase()===i);if(!o)throw new Error(`No adapter registered for chain: ${i}`);return{tx:await o.executor.createTransaction(s),chain:s.chain}}async evaluateResults(r,t,e){let a=this.adapters.find(i=>i.chain.toLowerCase()===t.name.toLowerCase());if(!a)throw new Error(`No adapter registered for chain: ${t.name}`);let s=await a.results.getTransactionExecutionResults(r,e);this.handlers?.onExecuted?.(s)}async executeCollect(r,t,e,a){let s=T(r,t);if(!s)throw new Error("WarpActionExecutor: Action not found");let i=await this.factory.getChainInfoForAction(s),o=W(i.name,this.adapters),p=await new N(this.config,o).apply(this.config,r),c=await this.factory.getResolvedInputs(i,s,e),u=this.factory.getModifiedInputs(c),g=this.factory.serializer,f=d=>{if(!d.value)return null;let C=g.stringToNative(d.value)[1];return d.input.type==="biguint"?C.toString():d.input.type==="esdt"?{}:C},v=new Headers;v.set("Content-Type","application/json"),v.set("Accept","application/json"),Object.entries(s.destination.headers||{}).forEach(([d,C])=>{v.set(d,C)});let E=Object.fromEntries(u.map(d=>[d.input.as||d.input.name,f(d)])),h=s.destination.method||"GET",y=h==="GET"?void 0:JSON.stringify({...E,...a});x.info("Executing collect",{url:s.destination.url,method:h,headers:v,body:y});try{let d=await fetch(s.destination.url,{method:h,headers:v,body:y}),C=await d.json(),{values:L,results:b}=await ir(p,C,t,u),cr=ar(this.config,o,p,t,b);return{success:d.ok,warp:p,action:t,user:this.config.user?.wallets?.[i.name]||null,txHash:null,next:cr,values:L,results:{...b,_DATA:C},messages:er(p,b)}}catch(d){return x.error("WarpActionExecutor: Error executing collect",d),{success:!1,warp:p,action:t,user:this.config.user?.wallets?.[i.name]||null,txHash:null,next:null,values:[],results:{_DATA:d},messages:{}}}}};var G=class{constructor(r){this.config=r}async search(r,t,e){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let a=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...e},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:r,...t})});if(!a.ok)throw new Error(`WarpIndex: search failed with status ${a.status}`);return(await a.json()).hits}catch(a){throw x.error("WarpIndex: Error searching for warps: ",a),a}}};var z=class{constructor(r,t){this.config=r;this.adapters=t}isValid(r){return r.startsWith(l.HttpProtocolPrefix)?!!O(r):!1}async detectFromHtml(r){if(!r.length)return{match:!1,results:[]};let a=[...r.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),i=(await Promise.all(a)).filter(c=>c.match),o=i.length>0,p=i.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:p}}async detect(r,t){let e={match:!1,url:r,warp:null,chain:null,registryInfo:null,brand:null},a=r.startsWith(l.HttpProtocolPrefix)?O(r):A(r);if(!a)return e;try{let{type:s,identifierBase:i}=a,o=null,p=null,c=null,u=B(a.chainPrefix,this.adapters);if(s==="hash"){o=await u.builder().createFromTransactionHash(i,t);let f=await u.registry.getInfoByHash(i,t);p=f.registryInfo,c=f.brand}else if(s==="alias"){let f=await u.registry.getInfoByAlias(i,t);p=f.registryInfo,c=f.brand,f.registryInfo&&(o=await u.builder().createFromTransactionHash(f.registryInfo.hash,t))}let g=o?await new N(this.config,u).apply(this.config,o):null;return g?{match:!0,url:r,warp:g,chain:u.chain,registryInfo:p,brand:c}:e}catch(s){return x.error("Error detecting warp link",s),e}}};var lr=class{constructor(r,t){this.config=r;this.adapters=t}getConfig(){return this.config}setConfig(r){return this.config=r,this}getAdapters(){return this.adapters}addAdapter(r){return this.adapters.push(r),this}createExecutor(r){return new q(this.config,this.adapters,r)}async detectWarp(r,t){return new z(this.config,this.adapters).detect(r,t)}async executeWarp(r,t,e,a={}){let s=await this.detectWarp(r,a.cache);if(!s.match||!s.warp)throw new Error("Warp not found");let i=this.createExecutor(e),{tx:o,chain:p}=await i.execute(s.warp,t);return{tx:o,chain:p,evaluateResults:async u=>{if(!p||!o||!s.warp)throw new Error("Warp not found");await i.evaluateResults(s.warp,p,u)}}}createInscriptionTransaction(r,t){return W(r,this.adapters).builder().createInscriptionTransaction(t)}async createFromTransaction(r,t,e=!1){return W(r,this.adapters).builder().createFromTransaction(t,e)}async createFromTransactionHash(r,t){let e=A(r);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return B(e.chainPrefix,this.adapters).builder().createFromTransactionHash(r,t)}getExplorer(r){return W(r.name,this.adapters).explorer(r)}getResults(r){return W(r.name,this.adapters).results}async getRegistry(r){let t=W(r,this.adapters).registry;return await t.init(),t}get factory(){return new U(this.config,this.adapters)}get index(){return new G(this.config)}get linkBuilder(){return new $(this.config,this.adapters)}createBuilder(r){return W(r,this.adapters).builder()}createAbiBuilder(r){return W(r,this.adapters).abiBuilder()}createBrandBuilder(r){return W(r,this.adapters).brandBuilder()}};0&&(module.exports={CacheTtl,KnownTokens,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpValidator,address,applyResultsToMessages,biguint,boolean,evaluateResultsCommon,extractCollectResults,extractIdentifierInfoFromUrl,findKnownTokenById,findWarpAdapterByPrefix,findWarpAdapterForChain,findWarpDefaultAdapter,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:[":","."],IdentifierParamSeparatorDefault:".",IdentifierChainDefault:"mvx",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:a=>a.config.user?.wallets?.[a.chain.name]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:a=>a.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:a=>a.chain.explorerUrl},ChainAddressHrp:{Placeholder:"chain.addressHrp",Accessor:a=>a.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},A={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 B={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${B.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${B.Brand}.schema.json`,DefaultClientUrl:a=>a==="devnet"?"https://devnet.usewarp.to":a==="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:a=>a==="devnet"?"https://devnet-api.multiversx.com":a==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:a=>a==="devnet"?"https://devnet-explorer.multiversx.com":a==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:a=>6e3,AddressHrp:"erd",ChainId:a=>a==="devnet"?"D":a==="testnet"?"T":"1",NativeToken:"EGLD"},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 Y=a=>{let t=a.find(r=>r.chain.toLowerCase()===m.MainChain.Name.toLowerCase());if(!t)throw new Error(`Adapter not found for chain: ${m.MainChain.Name}`);return t},y=(a,t)=>{let r=t.find(e=>e.chain.toLowerCase()===a.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${a}`);return r},$=(a,t)=>{let r=t.find(e=>e.prefix.toLowerCase()===a.toLowerCase());if(!r)throw new Error(`Adapter not found for prefix: ${a}`);return r},O=a=>({name:m.MainChain.Name,displayName:m.MainChain.DisplayName,chainId:m.MainChain.ChainId(a.env),blockTime:m.MainChain.BlockTime(a.env),addressHrp:m.MainChain.AddressHrp,apiUrl:m.MainChain.ApiUrl(a.env),explorerUrl:m.MainChain.ExplorerUrl(a.env),nativeToken:m.MainChain.NativeToken}),k=a=>{if(a==="warp")return`warp:${B.Warp}`;if(a==="brand")return`brand:${B.Brand}`;if(a==="abi")return`abi:${B.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${a}`)},P=(a,t)=>a?.actions[t-1],tt=a=>(a.actions.forEach((t,r)=>{if(t.type!=="link")return{action:t,actionIndex:r}}),{action:P(a,1),actionIndex:1}),bt=a=>({name:a.name.toString(),displayName:a.display_name.toString(),chainId:a.chain_id.toString(),blockTime:a.block_time.toNumber(),addressHrp:a.address_hrp.toString(),apiUrl:a.api_url.toString(),explorerUrl:a.explorer_url.toString(),nativeToken:a.native_token.toString()}),J=(a,t)=>{let r=a.toString(),[e,n=""]=r.split("."),i=Math.abs(t);if(t>0)return BigInt(e+n.padEnd(i,"0"));if(t<0){let s=e+n;if(i>=s.length)return 0n;let o=s.slice(0,-i)||"0";return BigInt(o)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},rt=(a,t=100)=>{if(!a)return"";let r=a.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=(a,t)=>a.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),et=(a,t)=>{let r=Object.entries(a.messages||{}).map(([e,n])=>[e,K(n,t)]);return Object.fromEntries(r)};var ct=a=>{let t=l.IdentifierParamSeparator,r=-1,e="";for(let n of t){let i=a.indexOf(n);i!==-1&&(r===-1||i<r)&&(r=i,e=n)}return r!==-1?{separator:e,index:r}:null},nt=a=>{let t=ct(a);if(!t)return[a];let{separator:r,index:e}=t,n=a.substring(0,e),i=a.substring(e+r.length),s=nt(i);return[n,...s]},b=a=>{let t=decodeURIComponent(a).trim(),r=t.split("?")[0],e=nt(r);if(r.length===64&&/^[a-fA-F0-9]+$/.test(r))return{chainPrefix:l.IdentifierChainDefault,type:l.IdentifierType.Hash,identifier:t,identifierBase:r};if(e.length===2&&/^[a-zA-Z0-9]{62}$/.test(e[0])&&/^[a-zA-Z0-9]{2}$/.test(e[1]))return null;if(e.length===3){let[n,i,s]=e;if(i===l.IdentifierType.Alias||i===l.IdentifierType.Hash){let o=t.includes("?")?s+t.substring(t.indexOf("?")):s;return{chainPrefix:n,type:i,identifier:o,identifierBase:s}}}if(e.length===2){let[n,i]=e;if(n===l.IdentifierType.Alias||n===l.IdentifierType.Hash){let s=t.includes("?")?i+t.substring(t.indexOf("?")):i;return{chainPrefix:l.IdentifierChainDefault,type:n,identifier:s,identifierBase:i}}}if(e.length===2){let[n,i]=e;if(n!==l.IdentifierType.Alias&&n!==l.IdentifierType.Hash){let s=t.includes("?")?i+t.substring(t.indexOf("?")):i;return{chainPrefix:n,type:l.IdentifierType.Alias,identifier:s,identifierBase:i}}}return{chainPrefix:l.IdentifierChainDefault,type:l.IdentifierType.Alias,identifier:t,identifierBase:r}},D=a=>{let t=new URL(a),e=t.searchParams.get(l.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let n=decodeURIComponent(e);return b(n)};import ut from"qr-code-styling";var N=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!D(t):!1}build(t,r,e){let n=this.config.clientUrl||m.DefaultClientUrl(this.config.env),i=y(t,this.adapters),s=r===l.IdentifierType.Alias?e:r+l.IdentifierParamSeparatorDefault+e,o=i.prefix+l.IdentifierParamSeparatorDefault+s,p=encodeURIComponent(o);return m.SuperClientUrls.includes(n)?`${n}/${p}`:`${n}?${l.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(t){let r=b(t);if(!r)return null;let e=$(r.chainPrefix,this.adapters);return e?this.build(e.chain,r.type,r.identifierBase):null}generateQrCode(t,r,e,n=512,i="white",s="black",o="#23F7DD"){let p=y(t,this.adapters),c=this.build(p.chain,r,e);return new ut({type:"svg",width:n,height:n,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var dt="https://",at=(a,t,r,e,n)=>{let i=r.actions?.[e]?.next||r.next||null;if(!i)return null;if(i.startsWith(dt))return[{identifier:null,url:i}];let[s,o]=i.split("?");if(!o)return[{identifier:s,url:Q(t,s,a)}];let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let h=K(o,{...r.vars,...n}),W=h?`${s}?${h}`:s;return[{identifier:W,url:Q(t,W,a)}]}let c=p[0];if(!c)return[];let u=c.match(/{{([^[]+)\[\]/),g=u?u[1]:null;if(!g||n[g]===void 0)return[];let f=Array.isArray(n[g])?n[g]:[n[g]];if(f.length===0)return[];let x=p.filter(h=>h.includes(`{{${g}[]`)).map(h=>{let W=h.match(/\[\](\.[^}]+)?}}/),d=W&&W[1]||"";return{placeholder:h,field:d?d.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(h=>{let W=o;for(let{regex:v,field:S}of x){let w=S?ft(h,S):h;if(w==null)return null;W=W.replace(v,w)}if(W.includes("{{")||W.includes("}}"))return null;let d=W?`${s}?${W}`:s;return{identifier:d,url:Q(t,d,a)}}).filter(h=>h!==null)},Q=(a,t,r)=>{let[e,n]=t.split("?"),i=b(e)||{type:"alias",identifier:e,identifierBase:e},s=new N(r,[a]).build(a.chain,i.type,i.identifierBase);if(!n)return s;let o=new URL(s);return new URLSearchParams(n).forEach((p,c)=>o.searchParams.set(c,p)),o.toString().replace(/\/\?/,"?")},ft=(a,t)=>t.split(".").reduce((r,e)=>r?.[e],a);var U=class U{static info(...t){U.isTestEnv||console.info(...t)}static warn(...t){U.isTestEnv||console.warn(...t)}static error(...t){U.isTestEnv||console.error(...t)}};U.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=U;var R=class{nativeToString(t,r){return`${t}:${r?.toString()??""}`}stringToNative(t){let r=t.split(l.ArgParamsSeparator),e=r[0],n=r.slice(1).join(l.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[i,s]=n.split(l.ArgParamsSeparator);return[`option:${i}`,s||null]}else if(e==="optional"){let[i,s]=n.split(l.ArgParamsSeparator);return[`optional:${i}`,s||null]}else if(e==="list"){let i=n.split(l.ArgParamsSeparator),s=i.slice(0,-1).join(l.ArgParamsSeparator),o=i[i.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${s}:${u}`)[1]);return[`list:${s}`,c]}else if(e==="variadic"){let i=n.split(l.ArgParamsSeparator),s=i.slice(0,-1).join(l.ArgParamsSeparator),o=i[i.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${s}:${u}`)[1]);return[`variadic:${s}`,c]}else if(e.startsWith("composite")){let i=e.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=n.split(l.ArgCompositeSeparator).map((p,c)=>this.stringToNative(`${i[c]}:${p}`)[1]);return[e,o]}else{if(e==="string")return[e,n];if(e==="uint8"||e==="uint16"||e==="uint32")return[e,Number(n)];if(e==="uint64"||e==="biguint")return[e,BigInt(n||0)];if(e==="bool")return[e,n==="true"];if(e==="address")return[e,n];if(e==="token")return[e,n];if(e==="hex")return[e,n];if(e==="codemeta")return[e,n];if(e==="esdt"){let[i,s,o]=n.split(l.ArgCompositeSeparator);return[e,`${i}|${s}|${o}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}};var it=async(a,t,r,e)=>{let n=[],i={};for(let[s,o]of Object.entries(a.results||{})){if(o.startsWith(l.Transform.Prefix))continue;let p=Wt(o);if(p!==null&&p!==r){i[s]=null;continue}let[c,...u]=o.split("."),g=(f,x)=>x.reduce((E,h)=>E&&E[h]!==void 0?E[h]:null,f);if(c==="out"||c.startsWith("out[")){let f=u.length===0?t?.data||t:g(t,u);n.push(f),i[s]=f}else i[s]=o}return{values:n,results:await ht(a,i,r,e)}},ht=async(a,t,r,e)=>{if(!a.results)return t;let n={...t};return n=gt(n,a,r,e),n=await mt(a,n),n},gt=(a,t,r,e)=>{let n={...a},i=P(t,r)?.inputs||[],s=new R;for(let[o,p]of Object.entries(n))if(typeof p=="string"&&p.startsWith("input.")){let c=p.split(".")[1],u=i.findIndex(f=>f.as===c||f.name===c),g=u!==-1?e[u]?.value:null;n[o]=g?s.stringToNative(g)[1]:null}return n},mt=async(a,t)=>{if(!a.results)return t;let r={...t},e=Object.entries(a.results).filter(([,n])=>n.startsWith(l.Transform.Prefix)).map(([n,i])=>({key:n,code:i.substring(l.Transform.Prefix.length)}));for(let{key:n,code:i}of e)try{let s;typeof window>"u"?s=(await import("./runInVm-BFUZVHHD.mjs")).runInVm:s=(await import("./runInVm-5YQ766M3.mjs")).runInVm,r[n]=await s(i,r)}catch(s){C.error(`Transform error for result '${n}':`,s),r[n]=null}return r},Wt=a=>{if(a==="out")return 1;let t=a.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(a.startsWith("out.")||a.startsWith("event."),null)};var yt=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Zt=a=>yt.find(t=>t.id===a)||null;var cr=a=>`${A.String}:${a}`,ur=a=>`${A.U8}:${a}`,dr=a=>`${A.U16}:${a}`,fr=a=>`${A.U32}:${a}`,hr=a=>`${A.U64}:${a}`,gr=a=>`${A.Biguint}:${a}`,mr=a=>`${A.Boolean}:${a}`,Wr=a=>`${A.Address}:${a}`,yr=a=>`${A.Hex}:${a}`;import xt from"ajv";var st=class{constructor(t){this.pendingBrand={protocol:k("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),e}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.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,n=await(await fetch(r)).json(),i=new xt,s=i.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};import vt from"ajv";var M=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(n=>n.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(n,i)=>{n&&Object.keys(n).forEach(s=>{s!==s.toUpperCase()&&r.push(`${i} name '${s}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.results,"Result"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(s=>s.type==="contract"),e=t.actions.some(s=>s.type==="query");if(!r&&!e)return[];let n=t.actions.some(s=>s.abi),i=Object.values(t.results||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.results&&!n&&i?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||m.LatestWarpSchemaUrl,n=await(await fetch(r)).json(),i=new vt({strict:!1}),s=i.compile(n);return s(t)?[]:[`Schema validation failed: ${i.errorsText(s.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var ot=class{constructor(t){this.config=t;this.pendingWarp={protocol:k("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 rt(t,r)}ensure(t,r){if(!t)throw new Error(r)}async validate(t){let e=await new M(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
|
|
2
|
-
`))}};var F=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 n={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(n))}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 T=class T{get(t){let r=T.cache.get(t);return r?Date.now()>r.expiresAt?(T.cache.delete(t),null):r.value:null}set(t,r,e){let n=Date.now()+e*1e3;T.cache.set(t,{value:r,expiresAt:n})}forget(t){T.cache.delete(t)}clear(){T.cache.clear()}};T.cache=new Map;var H=T;var _={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},pt={Warp:(a,t)=>`warp:${a}:${t}`,WarpAbi:(a,t)=>`warp-abi:${a}:${t}`,WarpExecutable:(a,t,r)=>`warp-exec:${a}:${t}:${r}`,RegistryInfo:(a,t)=>`registry-info:${a}:${t}`,Brand:(a,t)=>`brand:${a}:${t}`,ChainInfo:(a,t)=>`chain:${a}:${t}`,ChainInfos:a=>`chains:${a}`},G=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new F:t==="memory"?new H:typeof window<"u"&&window.localStorage?new F:new H}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 V=class{constructor(t,r){this.config=t;this.adapters=r;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new R,this.cache=new G(t.cache?.type)}async createExecutable(t,r,e){let n=P(t,r);if(!n)throw new Error("WarpFactory: Action not found");let i=await this.getChainInfoForAction(n,e),s=await this.getResolvedInputs(i,n,e),o=this.getModifiedInputs(s),p=o.find(I=>I.input.position==="receiver")?.value,c="address"in n?n.address:null,u=p?.split(":")[1]||c;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let g=u,f=this.getPreparedArgs(n,o),x=o.find(I=>I.input.position==="value")?.value||null,E="value"in n?n.value:null,h=BigInt(x?.split(":")[1]||E||0),W=o.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),v=[...("transfers"in n?n.transfers:[])||[],...W||[]],S=o.find(I=>I.input.position==="data")?.value,w="data"in n?n.data||"":null,Z={warp:t,chain:i,action:r,destination:g,args:f,value:h,transfers:v,data:S||w||null,resolvedInputs:o};return this.cache.set(pt.WarpExecutable(this.config.env,t.meta?.hash||"",r),Z.resolvedInputs,_.OneWeek),Z}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 n=r.inputs||[],i=await Promise.all(e.map(o=>this.preprocessInput(t,o))),s=(o,p)=>{if(o.source==="query"){let c=this.url.searchParams.get(o.name);return c?this.serializer.nativeToString(o.type,c):null}else return o.source===l.Source.UserWallet?this.config.user?.wallets?.[t.name]?this.serializer.nativeToString("address",this.config.user.wallets[t.name]):null:i[p]||null};return n.map((o,p)=>{let c=s(o,p);return{input:o,value:c||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(t){return t.map((r,e)=>{if(r.input.modifier?.startsWith("scale:")){let[,n]=r.input.modifier.split(":");if(isNaN(Number(n))){let i=Number(t.find(p=>p.input.name===n)?.value?.split(":")[1]);if(!i)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let s=r.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=J(s,+i);return{...r,value:`${r.input.type}:${o}`}}else{let i=r.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let s=J(i,+n);return{...r,value:`${r.input.type}:${s}`}}}else return r})}async preprocessInput(t,r){try{let[e,n]=r.split(l.ArgParamsSeparator,2);return y(t.name,this.adapters).executor.preprocessInput(t,r,e,n)}catch{return r}}getPreparedArgs(t,r){let e="args"in t?t.args||[]:[];return r.forEach(({input:n,value:i})=>{if(!i||!n.position?.startsWith("arg:"))return;let s=Number(n.position.split(":")[1])-1;e.splice(s,0,i)}),e}async tryGetChainFromInputs(t,r){let e=t.inputs?.findIndex(c=>c.position==="chain");if(e===-1||e===void 0)return null;let n=r[e];if(!n)throw new Error("WarpUtils: Chain input not found");let s=new R().stringToNative(n)[1],p=await y(s,this.adapters).registry.getChainInfo(s);if(!p)throw new Error(`WarpUtils: Chain info not found for ${s}`);return p}async getDefaultChainInfo(t){if(!t.chain)return O(this.config);let e=await Y(this.adapters).registry.getChainInfo(t.chain,{ttl:_.OneWeek});if(!e)throw new Error(`WarpUtils: Chain info not found for ${t.chain}`);return e}};var L=class{constructor(t,r){this.config=t;this.adapter=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 n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e,t),e}applyVars(t,r){if(!r?.vars)return r;let e=JSON.stringify(r),n=(i,s)=>{e=e.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(r.vars).forEach(([i,s])=>{if(typeof s!="string")n(i,s);else if(s.startsWith(`${l.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${l.Vars.Query}:`)[1],p=new URLSearchParams(t.currentUrl.split("?")[1]).get(o);p&&n(i,p)}else if(s.startsWith(`${l.Vars.Env}:`)){let o=s.split(`${l.Vars.Env}:`)[1],p=t.vars?.[o];p&&n(i,p)}else if(s===l.Source.UserWallet&&t.user?.wallets?.[this.adapter.chain]){let o=t.user.wallets[this.adapter.chain];o&&n(i,o)}else n(i,s)}),JSON.parse(e)}async applyRootGlobals(t,r){let e=JSON.stringify(t),n={config:r,chain:O(r)};return Object.values(l.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(e)}async applyActionGlobals(t){let r=t.chain?await this.adapter.registry.getChainInfo(t.chain):O(this.config);if(!r)throw new Error(`Chain info not found for ${t.chain}`);let e=JSON.stringify(t),n={config:this.config,chain:r};return Object.values(l.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(e)}};var j=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.factory=new V(t,r),this.handlers=e}async execute(t,r){let{action:e,actionIndex:n}=tt(t);if(e.type==="collect"){let c=await this.executeCollect(t,n,r);return c.success?this.handlers?.onExecuted?.(c):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null}}let i=await this.factory.createExecutable(t,n,r),s=i.chain.name.toLowerCase(),o=this.adapters.find(c=>c.chain.toLowerCase()===s);if(!o)throw new Error(`No adapter registered for chain: ${s}`);return{tx:await o.executor.createTransaction(i),chain:i.chain}}async evaluateResults(t,r,e){let n=this.adapters.find(s=>s.chain.toLowerCase()===r.name.toLowerCase());if(!n)throw new Error(`No adapter registered for chain: ${r.name}`);let i=await n.results.getTransactionExecutionResults(t,e);this.handlers?.onExecuted?.(i)}async executeCollect(t,r,e,n){let i=P(t,r);if(!i)throw new Error("WarpActionExecutor: Action not found");let s=await this.factory.getChainInfoForAction(i),o=y(s.name,this.adapters),p=await new L(this.config,o).apply(this.config,t),c=await this.factory.getResolvedInputs(s,i,e),u=this.factory.getModifiedInputs(c),g=this.factory.serializer,f=d=>{if(!d.value)return null;let v=g.stringToNative(d.value)[1];return d.input.type==="biguint"?v.toString():d.input.type==="esdt"?{}:v},x=new Headers;x.set("Content-Type","application/json"),x.set("Accept","application/json"),Object.entries(i.destination.headers||{}).forEach(([d,v])=>{x.set(d,v)});let E=Object.fromEntries(u.map(d=>[d.input.as||d.input.name,f(d)])),h=i.destination.method||"GET",W=h==="GET"?void 0:JSON.stringify({...E,...n});C.info("Executing collect",{url:i.destination.url,method:h,headers:x,body:W});try{let d=await fetch(i.destination.url,{method:h,headers:x,body:W}),v=await d.json(),{values:S,results:w}=await it(p,v,r,u),X=at(this.config,o,p,r,w);return{success:d.ok,warp:p,action:r,user:this.config.user?.wallets?.[s.name]||null,txHash:null,next:X,values:S,results:{...w,_DATA:v},messages:et(p,w)}}catch(d){return C.error("WarpActionExecutor: Error executing collect",d),{success:!1,warp:p,action:r,user:this.config.user?.wallets?.[s.name]||null,txHash:null,next:null,values:[],results:{_DATA:d},messages:{}}}}};var q=class{constructor(t){this.config=t}async search(t,r,e){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let n=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(!n.ok)throw new Error(`WarpIndex: search failed with status ${n.status}`);return(await n.json()).hits}catch(n){throw C.error("WarpIndex: Error searching for warps: ",n),n}}};var z=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!D(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),s=(await Promise.all(n)).filter(c=>c.match),o=s.length>0,p=s.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:p}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},n=t.startsWith(l.HttpProtocolPrefix)?D(t):b(t);if(!n)return e;try{let{type:i,identifierBase:s}=n,o=null,p=null,c=null,u=$(n.chainPrefix,this.adapters);if(i==="hash"){o=await u.builder().createFromTransactionHash(s,r);let f=await u.registry.getInfoByHash(s,r);p=f.registryInfo,c=f.brand}else if(i==="alias"){let f=await u.registry.getInfoByAlias(s,r);p=f.registryInfo,c=f.brand,f.registryInfo&&(o=await u.builder().createFromTransactionHash(f.registryInfo.hash,r))}let g=o?await new L(this.config,u).apply(this.config,o):null;return g?{match:!0,url:t,warp:g,chain:u.chain,registryInfo:p,brand:c}:e}catch(i){return C.error("Error detecting warp link",i),e}}};var lt=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}setConfig(t){return this.config=t,this}getAdapters(){return this.adapters}addAdapter(t){return this.adapters.push(t),this}createExecutor(t){return new j(this.config,this.adapters,t)}async detectWarp(t,r){return new z(this.config,this.adapters).detect(t,r)}async executeWarp(t,r,e,n={}){let i=await this.detectWarp(t,n.cache);if(!i.match||!i.warp)throw new Error("Warp not found");let s=this.createExecutor(e),{tx:o,chain:p}=await s.execute(i.warp,r);return{tx:o,chain:p,evaluateResults:async u=>{if(!p||!o||!i.warp)throw new Error("Warp not found");await s.evaluateResults(i.warp,p,u)}}}createInscriptionTransaction(t,r){return y(t,this.adapters).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return y(t,this.adapters).builder().createFromTransaction(r,e)}async createFromTransactionHash(t,r){let e=b(t);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return $(e.chainPrefix,this.adapters).builder().createFromTransactionHash(t,r)}getExplorer(t){return y(t.name,this.adapters).explorer(t)}getResults(t){return y(t.name,this.adapters).results}async getRegistry(t){let r=y(t,this.adapters).registry;return await r.init(),r}get factory(){return new V(this.config,this.adapters)}get index(){return new q(this.config)}get linkBuilder(){return new N(this.config,this.adapters)}createBuilder(t){return y(t,this.adapters).builder()}createAbiBuilder(t){return y(t,this.adapters).abiBuilder()}createBrandBuilder(t){return y(t,this.adapters).brandBuilder()}};export{_ as CacheTtl,yt as KnownTokens,st as WarpBrandBuilder,ot as WarpBuilder,G as WarpCache,pt as WarpCacheKey,lt as WarpClient,m as WarpConfig,l as WarpConstants,j as WarpExecutor,V as WarpFactory,q as WarpIndex,A as WarpInputTypes,L as WarpInterpolator,N as WarpLinkBuilder,z as WarpLinkDetecter,C as WarpLogger,B as WarpProtocolVersions,R as WarpSerializer,M as WarpValidator,Wr as address,et as applyResultsToMessages,gr as biguint,mr as boolean,ht as evaluateResultsCommon,it as extractCollectResults,D as extractIdentifierInfoFromUrl,Zt as findKnownTokenById,$ as findWarpAdapterByPrefix,y as findWarpAdapterForChain,Y as findWarpDefaultAdapter,tt as findWarpExecutableAction,k as getLatestProtocolIdentifier,O as getMainChainInfo,at as getNextInfo,P as getWarpActionByIndex,b as getWarpInfoFromIdentifier,yr as hex,Wt as parseResultsOutIndex,K as replacePlaceholders,J as shiftBigintBy,cr as string,rt as toPreviewText,bt as toTypedChainInfo,dr as u16,fr as u32,hr as u64,ur as u8};
|
|
1
|
+
import"./chunk-3SAEGOMQ.mjs";var ct=(r=>(r.Multiversx="multiversx",r.Sui="sui",r))(ct||{}),l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:[":","."],IdentifierParamSeparatorDefault:".",IdentifierChainDefault:"mvx",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:a=>a.config.user?.wallets?.[a.chain.name]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:a=>a.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:a=>a.chain.explorerUrl},ChainAddressHrp:{Placeholder:"chain.addressHrp",Accessor:a=>a.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},A={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 B={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},g={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${B.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${B.Brand}.schema.json`,DefaultClientUrl:a=>a==="devnet"?"https://devnet.usewarp.to":a==="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:a=>a==="devnet"?"https://devnet-api.multiversx.com":a==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:a=>a==="devnet"?"https://devnet-explorer.multiversx.com":a==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:a=>6e3,AddressHrp:"erd",ChainId:a=>a==="devnet"?"D":a==="testnet"?"T":"1",NativeToken:"EGLD"},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 Y=a=>{let t=a.find(r=>r.chain.toLowerCase()===g.MainChain.Name.toLowerCase());if(!t)throw new Error(`Adapter not found for chain: ${g.MainChain.Name}`);return t},y=(a,t)=>{let r=t.find(e=>e.chain.toLowerCase()===a.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${a}`);return r},$=(a,t)=>{let r=t.find(e=>e.prefix.toLowerCase()===a.toLowerCase());if(!r)throw new Error(`Adapter not found for prefix: ${a}`);return r},O=a=>({name:g.MainChain.Name,displayName:g.MainChain.DisplayName,chainId:g.MainChain.ChainId(a.env),blockTime:g.MainChain.BlockTime(a.env),addressHrp:g.MainChain.AddressHrp,apiUrl:g.MainChain.ApiUrl(a.env),explorerUrl:g.MainChain.ExplorerUrl(a.env),nativeToken:g.MainChain.NativeToken}),k=a=>{if(a==="warp")return`warp:${B.Warp}`;if(a==="brand")return`brand:${B.Brand}`;if(a==="abi")return`abi:${B.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${a}`)},P=(a,t)=>a?.actions[t-1],tt=a=>(a.actions.forEach((t,r)=>{if(t.type!=="link")return{action:t,actionIndex:r}}),{action:P(a,1),actionIndex:1}),Et=a=>({name:a.name.toString(),displayName:a.display_name.toString(),chainId:a.chain_id.toString(),blockTime:a.block_time.toNumber(),addressHrp:a.address_hrp.toString(),apiUrl:a.api_url.toString(),explorerUrl:a.explorer_url.toString(),nativeToken:a.native_token.toString()}),J=(a,t)=>{let r=a.toString(),[e,n=""]=r.split("."),i=Math.abs(t);if(t>0)return BigInt(e+n.padEnd(i,"0"));if(t<0){let s=e+n;if(i>=s.length)return 0n;let o=s.slice(0,-i)||"0";return BigInt(o)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},rt=(a,t=100)=>{if(!a)return"";let r=a.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=(a,t)=>a.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),et=(a,t)=>{let r=Object.entries(a.messages||{}).map(([e,n])=>[e,K(n,t)]);return Object.fromEntries(r)};var ut=a=>{let t=l.IdentifierParamSeparator,r=-1,e="";for(let n of t){let i=a.indexOf(n);i!==-1&&(r===-1||i<r)&&(r=i,e=n)}return r!==-1?{separator:e,index:r}:null},nt=a=>{let t=ut(a);if(!t)return[a];let{separator:r,index:e}=t,n=a.substring(0,e),i=a.substring(e+r.length),s=nt(i);return[n,...s]},b=a=>{let t=decodeURIComponent(a).trim(),r=t.split("?")[0],e=nt(r);if(r.length===64&&/^[a-fA-F0-9]+$/.test(r))return{chainPrefix:l.IdentifierChainDefault,type:l.IdentifierType.Hash,identifier:t,identifierBase:r};if(e.length===2&&/^[a-zA-Z0-9]{62}$/.test(e[0])&&/^[a-zA-Z0-9]{2}$/.test(e[1]))return null;if(e.length===3){let[n,i,s]=e;if(i===l.IdentifierType.Alias||i===l.IdentifierType.Hash){let o=t.includes("?")?s+t.substring(t.indexOf("?")):s;return{chainPrefix:n,type:i,identifier:o,identifierBase:s}}}if(e.length===2){let[n,i]=e;if(n===l.IdentifierType.Alias||n===l.IdentifierType.Hash){let s=t.includes("?")?i+t.substring(t.indexOf("?")):i;return{chainPrefix:l.IdentifierChainDefault,type:n,identifier:s,identifierBase:i}}}if(e.length===2){let[n,i]=e;if(n!==l.IdentifierType.Alias&&n!==l.IdentifierType.Hash){let s=t.includes("?")?i+t.substring(t.indexOf("?")):i;return{chainPrefix:n,type:l.IdentifierType.Alias,identifier:s,identifierBase:i}}}return{chainPrefix:l.IdentifierChainDefault,type:l.IdentifierType.Alias,identifier:t,identifierBase:r}},D=a=>{let t=new URL(a),e=t.searchParams.get(l.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let n=decodeURIComponent(e);return b(n)};import dt from"qr-code-styling";var N=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!D(t):!1}build(t,r,e){let n=this.config.clientUrl||g.DefaultClientUrl(this.config.env),i=y(t,this.adapters),s=r===l.IdentifierType.Alias?e:r+l.IdentifierParamSeparatorDefault+e,o=i.prefix+l.IdentifierParamSeparatorDefault+s,p=encodeURIComponent(o);return g.SuperClientUrls.includes(n)?`${n}/${p}`:`${n}?${l.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(t){let r=b(t);if(!r)return null;let e=$(r.chainPrefix,this.adapters);return e?this.build(e.chain,r.type,r.identifierBase):null}generateQrCode(t,r,e,n=512,i="white",s="black",o="#23F7DD"){let p=y(t,this.adapters),c=this.build(p.chain,r,e);return new dt({type:"svg",width:n,height:n,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},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 ft="https://",at=(a,t,r,e,n)=>{let i=r.actions?.[e]?.next||r.next||null;if(!i)return null;if(i.startsWith(ft))return[{identifier:null,url:i}];let[s,o]=i.split("?");if(!o)return[{identifier:s,url:Q(t,s,a)}];let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let h=K(o,{...r.vars,...n}),W=h?`${s}?${h}`:s;return[{identifier:W,url:Q(t,W,a)}]}let c=p[0];if(!c)return[];let u=c.match(/{{([^[]+)\[\]/),m=u?u[1]:null;if(!m||n[m]===void 0)return[];let f=Array.isArray(n[m])?n[m]:[n[m]];if(f.length===0)return[];let x=p.filter(h=>h.includes(`{{${m}[]`)).map(h=>{let W=h.match(/\[\](\.[^}]+)?}}/),d=W&&W[1]||"";return{placeholder:h,field:d?d.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(h=>{let W=o;for(let{regex:v,field:R}of x){let w=R?ht(h,R):h;if(w==null)return null;W=W.replace(v,w)}if(W.includes("{{")||W.includes("}}"))return null;let d=W?`${s}?${W}`:s;return{identifier:d,url:Q(t,d,a)}}).filter(h=>h!==null)},Q=(a,t,r)=>{let[e,n]=t.split("?"),i=b(e)||{type:"alias",identifier:e,identifierBase:e},s=new N(r,[a]).build(a.chain,i.type,i.identifierBase);if(!n)return s;let o=new URL(s);return new URLSearchParams(n).forEach((p,c)=>o.searchParams.set(c,p)),o.toString().replace(/\/\?/,"?")},ht=(a,t)=>t.split(".").reduce((r,e)=>r?.[e],a);var U=class U{static info(...t){U.isTestEnv||console.info(...t)}static warn(...t){U.isTestEnv||console.warn(...t)}static error(...t){U.isTestEnv||console.error(...t)}};U.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=U;var S=class{nativeToString(t,r){return`${t}:${r?.toString()??""}`}stringToNative(t){let r=t.split(l.ArgParamsSeparator),e=r[0],n=r.slice(1).join(l.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[i,s]=n.split(l.ArgParamsSeparator);return[`option:${i}`,s||null]}else if(e==="optional"){let[i,s]=n.split(l.ArgParamsSeparator);return[`optional:${i}`,s||null]}else if(e==="list"){let i=n.split(l.ArgParamsSeparator),s=i.slice(0,-1).join(l.ArgParamsSeparator),o=i[i.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${s}:${u}`)[1]);return[`list:${s}`,c]}else if(e==="variadic"){let i=n.split(l.ArgParamsSeparator),s=i.slice(0,-1).join(l.ArgParamsSeparator),o=i[i.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${s}:${u}`)[1]);return[`variadic:${s}`,c]}else if(e.startsWith("composite")){let i=e.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=n.split(l.ArgCompositeSeparator).map((p,c)=>this.stringToNative(`${i[c]}:${p}`)[1]);return[e,o]}else{if(e==="string")return[e,n];if(e==="uint8"||e==="uint16"||e==="uint32")return[e,Number(n)];if(e==="uint64"||e==="biguint")return[e,BigInt(n||0)];if(e==="bool")return[e,n==="true"];if(e==="address")return[e,n];if(e==="token")return[e,n];if(e==="hex")return[e,n];if(e==="codemeta")return[e,n];if(e==="esdt"){let[i,s,o]=n.split(l.ArgCompositeSeparator);return[e,`${i}|${s}|${o}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}};var it=async(a,t,r,e)=>{let n=[],i={};for(let[s,o]of Object.entries(a.results||{})){if(o.startsWith(l.Transform.Prefix))continue;let p=yt(o);if(p!==null&&p!==r){i[s]=null;continue}let[c,...u]=o.split("."),m=(f,x)=>x.reduce((E,h)=>E&&E[h]!==void 0?E[h]:null,f);if(c==="out"||c.startsWith("out[")){let f=u.length===0?t?.data||t:m(t,u);n.push(f),i[s]=f}else i[s]=o}return{values:n,results:await mt(a,i,r,e)}},mt=async(a,t,r,e)=>{if(!a.results)return t;let n={...t};return n=gt(n,a,r,e),n=await Wt(a,n),n},gt=(a,t,r,e)=>{let n={...a},i=P(t,r)?.inputs||[],s=new S;for(let[o,p]of Object.entries(n))if(typeof p=="string"&&p.startsWith("input.")){let c=p.split(".")[1],u=i.findIndex(f=>f.as===c||f.name===c),m=u!==-1?e[u]?.value:null;n[o]=m?s.stringToNative(m)[1]:null}return n},Wt=async(a,t)=>{if(!a.results)return t;let r={...t},e=Object.entries(a.results).filter(([,n])=>n.startsWith(l.Transform.Prefix)).map(([n,i])=>({key:n,code:i.substring(l.Transform.Prefix.length)}));for(let{key:n,code:i}of e)try{let s;typeof window>"u"?s=(await import("./runInVm-BFUZVHHD.mjs")).runInVm:s=(await import("./runInVm-5YQ766M3.mjs")).runInVm,r[n]=await s(i,r)}catch(s){C.error(`Transform error for result '${n}':`,s),r[n]=null}return r},yt=a=>{if(a==="out")return 1;let t=a.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(a.startsWith("out.")||a.startsWith("event."),null)};var xt=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Yt=a=>xt.find(t=>t.id===a)||null;var ur=a=>`${A.String}:${a}`,dr=a=>`${A.U8}:${a}`,fr=a=>`${A.U16}:${a}`,hr=a=>`${A.U32}:${a}`,mr=a=>`${A.U64}:${a}`,gr=a=>`${A.Biguint}:${a}`,Wr=a=>`${A.Boolean}:${a}`,yr=a=>`${A.Address}:${a}`,xr=a=>`${A.Hex}:${a}`;import vt from"ajv";var st=class{constructor(t){this.pendingBrand={protocol:k("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),e}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.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||g.LatestBrandSchemaUrl,n=await(await fetch(r)).json(),i=new vt,s=i.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};import Ct from"ajv";var M=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(n=>n.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(n,i)=>{n&&Object.keys(n).forEach(s=>{s!==s.toUpperCase()&&r.push(`${i} name '${s}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.results,"Result"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(s=>s.type==="contract"),e=t.actions.some(s=>s.type==="query");if(!r&&!e)return[];let n=t.actions.some(s=>s.abi),i=Object.values(t.results||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.results&&!n&&i?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||g.LatestWarpSchemaUrl,n=await(await fetch(r)).json(),i=new Ct({strict:!1}),s=i.compile(n);return s(t)?[]:[`Schema validation failed: ${i.errorsText(s.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var ot=class{constructor(t){this.config=t;this.pendingWarp={protocol:k("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 rt(t,r)}ensure(t,r){if(!t)throw new Error(r)}async validate(t){let e=await new M(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
|
|
2
|
+
`))}};var F=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 n={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(n))}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 T=class T{get(t){let r=T.cache.get(t);return r?Date.now()>r.expiresAt?(T.cache.delete(t),null):r.value:null}set(t,r,e){let n=Date.now()+e*1e3;T.cache.set(t,{value:r,expiresAt:n})}forget(t){T.cache.delete(t)}clear(){T.cache.clear()}};T.cache=new Map;var H=T;var _={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},pt={Warp:(a,t)=>`warp:${a}:${t}`,WarpAbi:(a,t)=>`warp-abi:${a}:${t}`,WarpExecutable:(a,t,r)=>`warp-exec:${a}:${t}:${r}`,RegistryInfo:(a,t)=>`registry-info:${a}:${t}`,Brand:(a,t)=>`brand:${a}:${t}`,ChainInfo:(a,t)=>`chain:${a}:${t}`,ChainInfos:a=>`chains:${a}`},G=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new F:t==="memory"?new H:typeof window<"u"&&window.localStorage?new F:new H}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 V=class{constructor(t,r){this.config=t;this.adapters=r;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new S,this.cache=new G(t.cache?.type)}async createExecutable(t,r,e){let n=P(t,r);if(!n)throw new Error("WarpFactory: Action not found");let i=await this.getChainInfoForAction(n,e),s=await this.getResolvedInputs(i,n,e),o=this.getModifiedInputs(s),p=o.find(I=>I.input.position==="receiver")?.value,c="address"in n?n.address:null,u=p?.split(":")[1]||c;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let m=u,f=this.getPreparedArgs(n,o),x=o.find(I=>I.input.position==="value")?.value||null,E="value"in n?n.value:null,h=BigInt(x?.split(":")[1]||E||0),W=o.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),v=[...("transfers"in n?n.transfers:[])||[],...W||[]],R=o.find(I=>I.input.position==="data")?.value,w="data"in n?n.data||"":null,Z={warp:t,chain:i,action:r,destination:m,args:f,value:h,transfers:v,data:R||w||null,resolvedInputs:o};return this.cache.set(pt.WarpExecutable(this.config.env,t.meta?.hash||"",r),Z.resolvedInputs,_.OneWeek),Z}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 n=r.inputs||[],i=await Promise.all(e.map(o=>this.preprocessInput(t,o))),s=(o,p)=>{if(o.source==="query"){let c=this.url.searchParams.get(o.name);return c?this.serializer.nativeToString(o.type,c):null}else return o.source===l.Source.UserWallet?this.config.user?.wallets?.[t.name]?this.serializer.nativeToString("address",this.config.user.wallets[t.name]):null:i[p]||null};return n.map((o,p)=>{let c=s(o,p);return{input:o,value:c||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(t){return t.map((r,e)=>{if(r.input.modifier?.startsWith("scale:")){let[,n]=r.input.modifier.split(":");if(isNaN(Number(n))){let i=Number(t.find(p=>p.input.name===n)?.value?.split(":")[1]);if(!i)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let s=r.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=J(s,+i);return{...r,value:`${r.input.type}:${o}`}}else{let i=r.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let s=J(i,+n);return{...r,value:`${r.input.type}:${s}`}}}else return r})}async preprocessInput(t,r){try{let[e,n]=r.split(l.ArgParamsSeparator,2);return y(t.name,this.adapters).executor.preprocessInput(t,r,e,n)}catch{return r}}getPreparedArgs(t,r){let e="args"in t?t.args||[]:[];return r.forEach(({input:n,value:i})=>{if(!i||!n.position?.startsWith("arg:"))return;let s=Number(n.position.split(":")[1])-1;e.splice(s,0,i)}),e}async tryGetChainFromInputs(t,r){let e=t.inputs?.findIndex(c=>c.position==="chain");if(e===-1||e===void 0)return null;let n=r[e];if(!n)throw new Error("WarpUtils: Chain input not found");let s=new S().stringToNative(n)[1],p=await y(s,this.adapters).registry.getChainInfo(s);if(!p)throw new Error(`WarpUtils: Chain info not found for ${s}`);return p}async getDefaultChainInfo(t){if(!t.chain)return O(this.config);let e=await Y(this.adapters).registry.getChainInfo(t.chain,{ttl:_.OneWeek});if(!e)throw new Error(`WarpUtils: Chain info not found for ${t.chain}`);return e}};var L=class{constructor(t,r){this.config=t;this.adapter=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 n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e,t),e}applyVars(t,r){if(!r?.vars)return r;let e=JSON.stringify(r),n=(i,s)=>{e=e.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(r.vars).forEach(([i,s])=>{if(typeof s!="string")n(i,s);else if(s.startsWith(`${l.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${l.Vars.Query}:`)[1],p=new URLSearchParams(t.currentUrl.split("?")[1]).get(o);p&&n(i,p)}else if(s.startsWith(`${l.Vars.Env}:`)){let o=s.split(`${l.Vars.Env}:`)[1],p=t.vars?.[o];p&&n(i,p)}else if(s===l.Source.UserWallet&&t.user?.wallets?.[this.adapter.chain]){let o=t.user.wallets[this.adapter.chain];o&&n(i,o)}else n(i,s)}),JSON.parse(e)}async applyRootGlobals(t,r){let e=JSON.stringify(t),n={config:r,chain:O(r)};return Object.values(l.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(e)}async applyActionGlobals(t){let r=t.chain?await this.adapter.registry.getChainInfo(t.chain):O(this.config);if(!r)throw new Error(`Chain info not found for ${t.chain}`);let e=JSON.stringify(t),n={config:this.config,chain:r};return Object.values(l.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(e)}};var j=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.factory=new V(t,r),this.handlers=e}async execute(t,r){let{action:e,actionIndex:n}=tt(t);if(e.type==="collect"){let c=await this.executeCollect(t,n,r);return c.success?this.handlers?.onExecuted?.(c):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null}}let i=await this.factory.createExecutable(t,n,r),s=i.chain.name.toLowerCase(),o=this.adapters.find(c=>c.chain.toLowerCase()===s);if(!o)throw new Error(`No adapter registered for chain: ${s}`);return{tx:await o.executor.createTransaction(i),chain:i.chain}}async evaluateResults(t,r,e){let n=this.adapters.find(s=>s.chain.toLowerCase()===r.name.toLowerCase());if(!n)throw new Error(`No adapter registered for chain: ${r.name}`);let i=await n.results.getTransactionExecutionResults(t,e);this.handlers?.onExecuted?.(i)}async executeCollect(t,r,e,n){let i=P(t,r);if(!i)throw new Error("WarpActionExecutor: Action not found");let s=await this.factory.getChainInfoForAction(i),o=y(s.name,this.adapters),p=await new L(this.config,o).apply(this.config,t),c=await this.factory.getResolvedInputs(s,i,e),u=this.factory.getModifiedInputs(c),m=this.factory.serializer,f=d=>{if(!d.value)return null;let v=m.stringToNative(d.value)[1];return d.input.type==="biguint"?v.toString():d.input.type==="esdt"?{}:v},x=new Headers;x.set("Content-Type","application/json"),x.set("Accept","application/json"),Object.entries(i.destination.headers||{}).forEach(([d,v])=>{x.set(d,v)});let E=Object.fromEntries(u.map(d=>[d.input.as||d.input.name,f(d)])),h=i.destination.method||"GET",W=h==="GET"?void 0:JSON.stringify({...E,...n});C.info("Executing collect",{url:i.destination.url,method:h,headers:x,body:W});try{let d=await fetch(i.destination.url,{method:h,headers:x,body:W}),v=await d.json(),{values:R,results:w}=await it(p,v,r,u),X=at(this.config,o,p,r,w);return{success:d.ok,warp:p,action:r,user:this.config.user?.wallets?.[s.name]||null,txHash:null,next:X,values:R,results:{...w,_DATA:v},messages:et(p,w)}}catch(d){return C.error("WarpActionExecutor: Error executing collect",d),{success:!1,warp:p,action:r,user:this.config.user?.wallets?.[s.name]||null,txHash:null,next:null,values:[],results:{_DATA:d},messages:{}}}}};var q=class{constructor(t){this.config=t}async search(t,r,e){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let n=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(!n.ok)throw new Error(`WarpIndex: search failed with status ${n.status}`);return(await n.json()).hits}catch(n){throw C.error("WarpIndex: Error searching for warps: ",n),n}}};var z=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!D(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),s=(await Promise.all(n)).filter(c=>c.match),o=s.length>0,p=s.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:p}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},n=t.startsWith(l.HttpProtocolPrefix)?D(t):b(t);if(!n)return e;try{let{type:i,identifierBase:s}=n,o=null,p=null,c=null,u=$(n.chainPrefix,this.adapters);if(i==="hash"){o=await u.builder().createFromTransactionHash(s,r);let f=await u.registry.getInfoByHash(s,r);p=f.registryInfo,c=f.brand}else if(i==="alias"){let f=await u.registry.getInfoByAlias(s,r);p=f.registryInfo,c=f.brand,f.registryInfo&&(o=await u.builder().createFromTransactionHash(f.registryInfo.hash,r))}let m=o?await new L(this.config,u).apply(this.config,o):null;return m?{match:!0,url:t,warp:m,chain:u.chain,registryInfo:p,brand:c}:e}catch(i){return C.error("Error detecting warp link",i),e}}};var lt=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}setConfig(t){return this.config=t,this}getAdapters(){return this.adapters}addAdapter(t){return this.adapters.push(t),this}createExecutor(t){return new j(this.config,this.adapters,t)}async detectWarp(t,r){return new z(this.config,this.adapters).detect(t,r)}async executeWarp(t,r,e,n={}){let i=await this.detectWarp(t,n.cache);if(!i.match||!i.warp)throw new Error("Warp not found");let s=this.createExecutor(e),{tx:o,chain:p}=await s.execute(i.warp,r);return{tx:o,chain:p,evaluateResults:async u=>{if(!p||!o||!i.warp)throw new Error("Warp not found");await s.evaluateResults(i.warp,p,u)}}}createInscriptionTransaction(t,r){return y(t,this.adapters).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return y(t,this.adapters).builder().createFromTransaction(r,e)}async createFromTransactionHash(t,r){let e=b(t);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return $(e.chainPrefix,this.adapters).builder().createFromTransactionHash(t,r)}getExplorer(t){return y(t.name,this.adapters).explorer(t)}getResults(t){return y(t.name,this.adapters).results}async getRegistry(t){let r=y(t,this.adapters).registry;return await r.init(),r}get factory(){return new V(this.config,this.adapters)}get index(){return new q(this.config)}get linkBuilder(){return new N(this.config,this.adapters)}createBuilder(t){return y(t,this.adapters).builder()}createAbiBuilder(t){return y(t,this.adapters).abiBuilder()}createBrandBuilder(t){return y(t,this.adapters).brandBuilder()}};export{_ as CacheTtl,xt as KnownTokens,st as WarpBrandBuilder,ot as WarpBuilder,G as WarpCache,pt as WarpCacheKey,ct as WarpChainName,lt as WarpClient,g as WarpConfig,l as WarpConstants,j as WarpExecutor,V as WarpFactory,q as WarpIndex,A as WarpInputTypes,L as WarpInterpolator,N as WarpLinkBuilder,z as WarpLinkDetecter,C as WarpLogger,B as WarpProtocolVersions,S as WarpSerializer,M as WarpValidator,yr as address,et as applyResultsToMessages,gr as biguint,Wr as boolean,mt as evaluateResultsCommon,it as extractCollectResults,D as extractIdentifierInfoFromUrl,Yt as findKnownTokenById,$ as findWarpAdapterByPrefix,y as findWarpAdapterForChain,Y as findWarpDefaultAdapter,tt as findWarpExecutableAction,k as getLatestProtocolIdentifier,O as getMainChainInfo,at as getNextInfo,P as getWarpActionByIndex,b as getWarpInfoFromIdentifier,xr as hex,yt as parseResultsOutIndex,K as replacePlaceholders,J as shiftBigintBy,ur as string,rt as toPreviewText,Et as toTypedChainInfo,fr as u16,hr as u32,mr as u64,dr as u8};
|