@vleap/warps 3.0.0-alpha.46 → 3.0.0-alpha.48

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 CHANGED
@@ -230,13 +230,14 @@ type WarpExecutionNextInfo = {
230
230
  type WarpExecutionResults = Record<WarpResultName, any | null>;
231
231
  type WarpExecutionMessages = Record<WarpMessageName, string | null>;
232
232
 
233
+ type WarpUserWallets = Record<WarpChain, string | null>;
233
234
  type WarpClientConfig = {
234
235
  env: WarpChainEnv;
235
236
  clientUrl?: string;
236
237
  currentUrl?: string;
237
238
  vars?: Record<string, string | number>;
238
239
  user?: {
239
- wallet?: string;
240
+ wallets?: WarpUserWallets;
240
241
  };
241
242
  schema?: {
242
243
  warp?: string;
@@ -246,9 +247,6 @@ type WarpClientConfig = {
246
247
  ttl?: number;
247
248
  type?: WarpCacheType;
248
249
  };
249
- registry?: {
250
- contract?: string;
251
- };
252
250
  index?: {
253
251
  url?: string;
254
252
  apiKey?: string;
@@ -361,9 +359,6 @@ declare const WarpConfig: {
361
359
  ChainId: (env: WarpChainEnv) => "D" | "T" | "1";
362
360
  NativeToken: string;
363
361
  };
364
- Registry: {
365
- Contract: (env: WarpChainEnv) => "erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36" | "####" | "erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe";
366
- };
367
362
  AvailableActionInputSources: WarpActionInputSource[];
368
363
  AvailableActionInputTypes: WarpActionInputType[];
369
364
  AvailableActionInputPositions: WarpActionInputPosition[];
@@ -384,7 +379,7 @@ declare const WarpConstants: {
384
379
  Globals: {
385
380
  UserWallet: {
386
381
  Placeholder: string;
387
- Accessor: (bag: InterpolationBag) => string | undefined;
382
+ Accessor: (bag: InterpolationBag) => string | null | undefined;
388
383
  };
389
384
  ChainApiUrl: {
390
385
  Placeholder: string;
@@ -552,7 +547,10 @@ declare class WarpExecutor {
552
547
  private handlers?;
553
548
  private factory;
554
549
  constructor(config: WarpClientConfig, adapters: Adapter[], handlers?: ExecutionHandlers | undefined);
555
- execute(warp: Warp, inputs: string[]): Promise<[WarpAdapterGenericTransaction | null, WarpChainInfo | null]>;
550
+ execute(warp: Warp, inputs: string[]): Promise<{
551
+ tx: WarpAdapterGenericTransaction | null;
552
+ chain: WarpChainInfo | null;
553
+ }>;
556
554
  evaluateResults(warp: Warp, chain: WarpChainInfo, tx: WarpAdapterGenericRemoteTransaction): Promise<void>;
557
555
  private executeCollect;
558
556
  }
@@ -606,7 +604,14 @@ declare class WarpClient {
606
604
  addAdapter(adapter: Adapter): WarpClient;
607
605
  createBuilder(): WarpBuilder;
608
606
  createExecutor(handlers?: ExecutionHandlers): WarpExecutor;
609
- detectWarp(url: string, cache?: WarpCacheConfig): Promise<DetectionResult>;
607
+ detectWarp(urlOrId: string, cache?: WarpCacheConfig): Promise<DetectionResult>;
608
+ executeWarp(identifier: string, inputs: string[], handlers?: ExecutionHandlers, options?: {
609
+ cache?: WarpCacheConfig;
610
+ }): Promise<{
611
+ tx: WarpAdapterGenericTransaction | null;
612
+ chain: WarpChainInfo | null;
613
+ evaluateResults: (remoteTx: WarpAdapterGenericRemoteTransaction) => Promise<void>;
614
+ }>;
610
615
  createInscriptionTransaction(chain: WarpChain, warp: Warp): WarpAdapterGenericTransaction;
611
616
  createFromTransaction(chain: WarpChain, tx: WarpAdapterGenericRemoteTransaction, validate?: boolean): Promise<Warp>;
612
617
  createFromTransactionHash(chain: WarpChain, hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
@@ -669,4 +674,4 @@ declare class WarpValidator {
669
674
  private validateSchema;
670
675
  }
671
676
 
672
- export { type Adapter, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, CacheTtl, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type InterpolationBag, type KnownToken, KnownTokens, type ProtocolName, type ResolvedInput, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandMeta, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainEnv, type WarpChainInfo, WarpClient, type WarpClientConfig, type WarpCollectAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpExecutable, type WarpExecution, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, WarpFactory, type WarpIdType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, WarpSerializer, type WarpTransferAction, type WarpTrustStatus, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, biguint, boolean, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById, findWarpAdapterByPrefix, findWarpAdapterForChain, findWarpDefaultAdapter, findWarpExecutableAction, getLatestProtocolIdentifier, getMainChainInfo, getNextInfo, getWarpActionByIndex, getWarpInfoFromIdentifier, hex, parseResultsOutIndex, replacePlaceholders, shiftBigintBy, string, toPreviewText, toTypedChainInfo, u16, u32, u64, u8 };
677
+ export { type Adapter, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, CacheTtl, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type InterpolationBag, type KnownToken, KnownTokens, type ProtocolName, type ResolvedInput, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandMeta, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainEnv, type WarpChainInfo, WarpClient, type WarpClientConfig, type WarpCollectAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpExecutable, type WarpExecution, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, WarpFactory, type WarpIdType, WarpIndex, 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
@@ -230,13 +230,14 @@ type WarpExecutionNextInfo = {
230
230
  type WarpExecutionResults = Record<WarpResultName, any | null>;
231
231
  type WarpExecutionMessages = Record<WarpMessageName, string | null>;
232
232
 
233
+ type WarpUserWallets = Record<WarpChain, string | null>;
233
234
  type WarpClientConfig = {
234
235
  env: WarpChainEnv;
235
236
  clientUrl?: string;
236
237
  currentUrl?: string;
237
238
  vars?: Record<string, string | number>;
238
239
  user?: {
239
- wallet?: string;
240
+ wallets?: WarpUserWallets;
240
241
  };
241
242
  schema?: {
242
243
  warp?: string;
@@ -246,9 +247,6 @@ type WarpClientConfig = {
246
247
  ttl?: number;
247
248
  type?: WarpCacheType;
248
249
  };
249
- registry?: {
250
- contract?: string;
251
- };
252
250
  index?: {
253
251
  url?: string;
254
252
  apiKey?: string;
@@ -361,9 +359,6 @@ declare const WarpConfig: {
361
359
  ChainId: (env: WarpChainEnv) => "D" | "T" | "1";
362
360
  NativeToken: string;
363
361
  };
364
- Registry: {
365
- Contract: (env: WarpChainEnv) => "erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36" | "####" | "erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe";
366
- };
367
362
  AvailableActionInputSources: WarpActionInputSource[];
368
363
  AvailableActionInputTypes: WarpActionInputType[];
369
364
  AvailableActionInputPositions: WarpActionInputPosition[];
@@ -384,7 +379,7 @@ declare const WarpConstants: {
384
379
  Globals: {
385
380
  UserWallet: {
386
381
  Placeholder: string;
387
- Accessor: (bag: InterpolationBag) => string | undefined;
382
+ Accessor: (bag: InterpolationBag) => string | null | undefined;
388
383
  };
389
384
  ChainApiUrl: {
390
385
  Placeholder: string;
@@ -552,7 +547,10 @@ declare class WarpExecutor {
552
547
  private handlers?;
553
548
  private factory;
554
549
  constructor(config: WarpClientConfig, adapters: Adapter[], handlers?: ExecutionHandlers | undefined);
555
- execute(warp: Warp, inputs: string[]): Promise<[WarpAdapterGenericTransaction | null, WarpChainInfo | null]>;
550
+ execute(warp: Warp, inputs: string[]): Promise<{
551
+ tx: WarpAdapterGenericTransaction | null;
552
+ chain: WarpChainInfo | null;
553
+ }>;
556
554
  evaluateResults(warp: Warp, chain: WarpChainInfo, tx: WarpAdapterGenericRemoteTransaction): Promise<void>;
557
555
  private executeCollect;
558
556
  }
@@ -606,7 +604,14 @@ declare class WarpClient {
606
604
  addAdapter(adapter: Adapter): WarpClient;
607
605
  createBuilder(): WarpBuilder;
608
606
  createExecutor(handlers?: ExecutionHandlers): WarpExecutor;
609
- detectWarp(url: string, cache?: WarpCacheConfig): Promise<DetectionResult>;
607
+ detectWarp(urlOrId: string, cache?: WarpCacheConfig): Promise<DetectionResult>;
608
+ executeWarp(identifier: string, inputs: string[], handlers?: ExecutionHandlers, options?: {
609
+ cache?: WarpCacheConfig;
610
+ }): Promise<{
611
+ tx: WarpAdapterGenericTransaction | null;
612
+ chain: WarpChainInfo | null;
613
+ evaluateResults: (remoteTx: WarpAdapterGenericRemoteTransaction) => Promise<void>;
614
+ }>;
610
615
  createInscriptionTransaction(chain: WarpChain, warp: Warp): WarpAdapterGenericTransaction;
611
616
  createFromTransaction(chain: WarpChain, tx: WarpAdapterGenericRemoteTransaction, validate?: boolean): Promise<Warp>;
612
617
  createFromTransactionHash(chain: WarpChain, hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
@@ -669,4 +674,4 @@ declare class WarpValidator {
669
674
  private validateSchema;
670
675
  }
671
676
 
672
- export { type Adapter, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, CacheTtl, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type InterpolationBag, type KnownToken, KnownTokens, type ProtocolName, type ResolvedInput, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandMeta, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainEnv, type WarpChainInfo, WarpClient, type WarpClientConfig, type WarpCollectAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpExecutable, type WarpExecution, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, WarpFactory, type WarpIdType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, WarpSerializer, type WarpTransferAction, type WarpTrustStatus, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, biguint, boolean, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById, findWarpAdapterByPrefix, findWarpAdapterForChain, findWarpDefaultAdapter, findWarpExecutableAction, getLatestProtocolIdentifier, getMainChainInfo, getNextInfo, getWarpActionByIndex, getWarpInfoFromIdentifier, hex, parseResultsOutIndex, replacePlaceholders, shiftBigintBy, string, toPreviewText, toTypedChainInfo, u16, u32, u64, u8 };
677
+ export { type Adapter, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, CacheTtl, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type InterpolationBag, type KnownToken, KnownTokens, type ProtocolName, type ResolvedInput, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandMeta, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainEnv, type WarpChainInfo, WarpClient, type WarpClientConfig, type WarpCollectAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpExecutable, type WarpExecution, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, WarpFactory, type WarpIdType, WarpIndex, 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 Ar=Object.create;var z=Object.defineProperty;var br=Object.getOwnPropertyDescriptor;var Er=Object.getOwnPropertyNames;var Tr=Object.getPrototypeOf,Pr=Object.prototype.hasOwnProperty;var dr=(n,r)=>()=>(n&&(r=n(n=0)),r);var _=(n,r)=>{for(var t in r)z(n,t,{get:r[t],enumerable:!0})},fr=(n,r,t,e)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of Er(r))!Pr.call(n,a)&&a!==t&&z(n,a,{get:()=>r[a],enumerable:!(e=br(r,a))||e.enumerable});return n};var X=(n,r,t)=>(t=n!=null?Ar(Tr(n)):{},fr(r||!n||!n.__esModule?z(t,"default",{value:n,enumerable:!0}):t,n)),Rr=n=>fr(z({},"__esModule",{value:!0}),n);var mr={};_(mr,{runInVm:()=>Nr});var Ur,Nr,gr=dr(()=>{"use strict";Ur=(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')}),Nr=async(n,r)=>{let t;try{t=Ur("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 Wr={};_(Wr,{runInVm:()=>Vr});var Vr,yr=dr(()=>{"use strict";Vr=async(n,r)=>new Promise((t,e)=>{try{let a=new Blob([`
1
+ "use strict";var At=Object.create;var z=Object.defineProperty;var bt=Object.getOwnPropertyDescriptor;var Et=Object.getOwnPropertyNames;var Tt=Object.getPrototypeOf,Rt=Object.prototype.hasOwnProperty;var dt=(n,t)=>()=>(n&&(t=n(n=0)),t);var _=(n,t)=>{for(var r in t)z(n,r,{get:t[r],enumerable:!0})},ft=(n,t,r,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Et(t))!Rt.call(n,a)&&a!==r&&z(n,a,{get:()=>t[a],enumerable:!(e=bt(t,a))||e.enumerable});return n};var X=(n,t,r)=>(r=n!=null?At(Tt(n)):{},ft(t||!n||!n.__esModule?z(r,"default",{value:n,enumerable:!0}):r,n)),Pt=n=>ft(z({},"__esModule",{value:!0}),n);var mt={};_(mt,{runInVm:()=>Nt});var Ut,Nt,gt=dt(()=>{"use strict";Ut=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')}),Nt=async(n,t)=>{let r;try{r=Ut("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 r({timeout:2e3,sandbox:{result:t},eval:!1,wasm:!1});return n.trim().startsWith("(")&&n.includes("=>")?e.run(`(${n})(result)`):null}});var Wt={};_(Wt,{runInVm:()=>Vt});var Vt,yt=dt(()=>{"use strict";Vt=async(n,t)=>new Promise((r,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 Jr={};_(Jr,{CacheTtl:()=>Q,KnownTokens:()=>Cr,WarpBrandBuilder:()=>sr,WarpBuilder:()=>D,WarpCache:()=>F,WarpCacheKey:()=>or,WarpClient:()=>pr,WarpConfig:()=>g,WarpConstants:()=>p,WarpExecutor:()=>M,WarpFactory:()=>B,WarpIndex:()=>lr,WarpInputTypes:()=>C,WarpInterpolator:()=>$,WarpLinkBuilder:()=>O,WarpLinkDetecter:()=>G,WarpLogger:()=>x,WarpProtocolVersions:()=>S,WarpSerializer:()=>T,WarpValidator:()=>k,address:()=>zr,applyResultsToMessages:()=>er,biguint:()=>Mr,boolean:()=>Gr,evaluateResultsCommon:()=>vr,extractCollectResults:()=>ir,extractIdentifierInfoFromUrl:()=>N,findKnownTokenById:()=>Or,findWarpAdapterByPrefix:()=>Y,findWarpAdapterForChain:()=>y,findWarpDefaultAdapter:()=>Z,findWarpExecutableAction:()=>rr,getLatestProtocolIdentifier:()=>q,getMainChainInfo:()=>U,getNextInfo:()=>ar,getWarpActionByIndex:()=>b,getWarpInfoFromIdentifier:()=>E,hex:()=>Kr,parseResultsOutIndex:()=>xr,replacePlaceholders:()=>J,shiftBigintBy:()=>K,string:()=>kr,toPreviewText:()=>tr,toTypedChainInfo:()=>Sr,u16:()=>jr,u32:()=>Hr,u64:()=>Fr,u8:()=>Dr});module.exports=Rr(Jr);var p={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"mvx",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:n=>n.chain.explorerUrl},ChainAddressHrp:{Placeholder:"chain.addressHrp",Accessor:n=>n.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},C={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"},g={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"},Registry:{Contract:n=>n==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":n==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query",p.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 Z=n=>{let r=n.find(t=>t.chain.toLowerCase()===g.MainChain.Name.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${g.MainChain.Name}`);return r},y=(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},Y=(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},U=n=>({name:g.MainChain.Name,displayName:g.MainChain.DisplayName,chainId:g.MainChain.ChainId(n.env),blockTime:g.MainChain.BlockTime(n.env),addressHrp:g.MainChain.AddressHrp,apiUrl:g.MainChain.ApiUrl(n.env),explorerUrl:g.MainChain.ExplorerUrl(n.env),nativeToken:g.MainChain.NativeToken}),q=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}`)},b=(n,r)=>n?.actions[r-1],rr=n=>(n.actions.forEach((r,t)=>{if(r.type!=="link")return[r,t]}),[b(n,1),1]),Sr=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},J=(n,r)=>n.replace(/\{\{([^}]+)\}\}/g,(t,e)=>r[e]||""),er=(n,r)=>{let t=Object.entries(n.messages||{}).map(([e,a])=>[e,J(a,r)]);return Object.fromEntries(t)};var E=n=>{let r=decodeURIComponent(n).trim(),t=r.split(p.IdentifierParamSeparator),e=r.split("?")[0];return t.length===3&&(t[1]===p.IdentifierType.Alias||t[1]===p.IdentifierType.Hash)?{chainPrefix:t[0],type:t[1],identifier:t[2],identifierBase:t[2].split("?")[0]}:t.length===2&&(t[0]===p.IdentifierType.Alias||t[0]===p.IdentifierType.Hash)?{chainPrefix:p.IdentifierChainDefault,type:t[0],identifier:t[1],identifierBase:t[1].split("?")[0]}:t.length===2&&/^[a-zA-Z0-9]{62}$/.test(t[0])&&/^[a-zA-Z0-9]{2}$/.test(t[1])?null:t.length===2&&t[0]!==p.IdentifierType.Alias&&t[0]!==p.IdentifierType.Hash?{chainPrefix:t[0],type:p.IdentifierType.Alias,identifier:t[1],identifierBase:t[1].split("?")[0]}:e.length===64?{chainPrefix:p.IdentifierChainDefault,type:p.IdentifierType.Hash,identifier:r,identifierBase:e}:{chainPrefix:p.IdentifierChainDefault,type:p.IdentifierType.Alias,identifier:r,identifierBase:e}},N=n=>{let r=new URL(n),e=r.searchParams.get(p.IdentifierParamName);if(e||(e=r.pathname.split("/")[1]),!e)return null;let a=decodeURIComponent(e);return E(a)};var hr=X(require("qr-code-styling"));var O=class{constructor(r){this.config=r;this.config=r}isValid(r){return r.startsWith(p.HttpProtocolPrefix)?!!N(r):!1}build(r,t){let e=this.config.clientUrl||g.DefaultClientUrl(this.config.env),a=r===p.IdentifierType.Alias?encodeURIComponent(t):encodeURIComponent(r+p.IdentifierParamSeparator+t);return g.SuperClientUrls.includes(e)?`${e}/${a}`:`${e}?${p.IdentifierParamName}=${a}`}buildFromPrefixedIdentifier(r){let t=E(r);return t?this.build(t.type,t.identifierBase):""}generateQrCode(r,t,e=512,a="white",s="black",i="#23F7DD"){let o=this.build(r,t);return new hr.default({type:"svg",width:e,height:e,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},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(i)}" 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 Br="https://",ar=(n,r,t,e)=>{let a=r.actions?.[t]?.next||r.next||null;if(!a)return null;if(a.startsWith(Br))return[{identifier:null,url:a}];let[s,i]=a.split("?");if(!i)return[{identifier:s,url:nr(s,n)}];let o=i.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(o.length===0){let f=J(i,{...r.vars,...e}),h=f?`${s}?${f}`:s;return[{identifier:h,url:nr(h,n)}]}let c=o[0];if(!c)return[];let l=c.match(/{{([^[]+)\[\]/),u=l?l[1]:null;if(!u||e[u]===void 0)return[];let W=Array.isArray(e[u])?e[u]:[e[u]];if(W.length===0)return[];let d=o.filter(f=>f.includes(`{{${u}[]`)).map(f=>{let h=f.match(/\[\](\.[^}]+)?}}/),w=h&&h[1]||"";return{placeholder:f,field:w?w.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return W.map(f=>{let h=i;for(let{regex:m,field:v}of d){let R=v?$r(f,v):f;if(R==null)return null;h=h.replace(m,R)}if(h.includes("{{")||h.includes("}}"))return null;let w=h?`${s}?${h}`:s;return{identifier:w,url:nr(w,n)}}).filter(f=>f!==null)},nr=(n,r)=>{let[t,e]=n.split("?"),a=E(t)||{type:"alias",identifier:t,identifierBase:t},i=new O(r).build(a.type,a.identifierBase);if(!e)return i;let o=new URL(i);return new URLSearchParams(e).forEach((c,l)=>o.searchParams.set(l,c)),o.toString().replace(/\/\?/,"?")},$r=(n,r)=>r.split(".").reduce((t,e)=>t?.[e],n);var V=class V{static info(...r){V.isTestEnv||console.info(...r)}static warn(...r){V.isTestEnv||console.warn(...r)}static error(...r){V.isTestEnv||console.error(...r)}};V.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var x=V;var T=class{nativeToString(r,t){return`${r}:${t?.toString()??""}`}stringToNative(r){let t=r.split(p.ArgParamsSeparator),e=t[0],a=t.slice(1).join(p.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[s,i]=a.split(p.ArgParamsSeparator);return[`option:${s}`,i||null]}else if(e==="optional"){let[s,i]=a.split(p.ArgParamsSeparator);return[`optional:${s}`,i||null]}else if(e==="list"){let s=a.split(p.ArgParamsSeparator),i=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],l=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`list:${i}`,l]}else if(e==="variadic"){let s=a.split(p.ArgParamsSeparator),i=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],l=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`variadic:${i}`,l]}else if(e.startsWith("composite")){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=a.split(p.ArgCompositeSeparator).map((c,l)=>this.stringToNative(`${s[l]}:${c}`)[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(p.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(p.Transform.Prefix))continue;let c=xr(o);if(c!==null&&c!==t){s[i]=null;continue}let[l,...u]=o.split("."),W=(d,I)=>I.reduce((f,h)=>f&&f[h]!==void 0?f[h]:null,d);if(l==="out"||l.startsWith("out[")){let d=u.length===0?r?.data||r:W(r,u);a.push(d),s[i]=d}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=Lr(a,n,t,e),a=await qr(n,a),a},Lr=(n,r,t,e)=>{let a={...n},s=b(r,t)?.inputs||[],i=new T;for(let[o,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("input.")){let l=c.split(".")[1],u=s.findIndex(d=>d.as===l||d.name===l),W=u!==-1?e[u]?.value:null;a[o]=W?i.stringToNative(W)[1]:null}return a},qr=async(n,r)=>{if(!n.results)return r;let t={...r},e=Object.entries(n.results).filter(([,a])=>a.startsWith(p.Transform.Prefix)).map(([a,s])=>({key:a,code:s.substring(p.Transform.Prefix.length)}));for(let{key:a,code:s}of e)try{let i;typeof window>"u"?i=(await Promise.resolve().then(()=>(gr(),mr))).runInVm:i=(await Promise.resolve().then(()=>(yr(),Wr))).runInVm,t[a]=await i(s,t)}catch(i){x.error(`Transform error for result '${a}':`,i),t[a]=null}return t},xr=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 Cr=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Or=n=>Cr.find(r=>r.id===n)||null;var kr=n=>`${C.String}:${n}`,Dr=n=>`${C.U8}:${n}`,jr=n=>`${C.U16}:${n}`,Hr=n=>`${C.U32}:${n}`,Fr=n=>`${C.U64}:${n}`,Mr=n=>`${C.Biguint}:${n}`,Gr=n=>`${C.Boolean}:${n}`,zr=n=>`${C.Address}:${n}`,Kr=n=>`${C.Hex}:${n}`;var Ir=X(require("ajv"));var sr=class{constructor(r){this.pendingBrand={protocol:q("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||g.LatestBrandSchemaUrl,a=await(await fetch(t)).json(),s=new Ir.default,i=s.compile(a);if(!i(r))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(i.errors)}`)}};var wr=X(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||g.LatestWarpSchemaUrl,a=await(await fetch(t)).json(),s=new wr.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 D=class{constructor(r){this.config=r;this.pendingWarp={protocol:q("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 j=class{constructor(r="warp-cache"){this.prefix=r}getKey(r){return`${this.prefix}:${r}`}get(r){try{let t=localStorage.getItem(this.getKey(r));if(!t)return null;let e=JSON.parse(t);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 P=class P{get(r){let t=P.cache.get(r);return t?Date.now()>t.expiresAt?(P.cache.delete(r),null):t.value:null}set(r,t,e){let a=Date.now()+e*1e3;P.cache.set(r,{value:t,expiresAt:a})}forget(r){P.cache.delete(r)}clear(){P.cache.clear()}};P.cache=new Map;var H=P;var Q={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},or={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}`},F=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new j:r==="memory"?new H:typeof window<"u"&&window.localStorage?new j:new H}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 B=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 T,this.cache=new F(r.cache?.type)}async createExecutable(r,t,e){let a=b(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),c=o.find(A=>A.input.position==="receiver")?.value,l="address"in a?a.address:null,u=c?.split(":")[1]||l;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let W=u,d=this.getPreparedArgs(a,o),I=o.find(A=>A.input.position==="value")?.value||null,f="value"in a?a.value:null,h=BigInt(I?.split(":")[1]||f||0),w=o.filter(A=>A.input.position==="transfer"&&A.value).map(A=>A.value),v=[...("transfers"in a?a.transfers:[])||[],...w||[]],R=o.find(A=>A.input.position==="data")?.value,L="data"in a?a.data||"":null,ur={warp:r,chain:s,action:t,destination:W,args:d,value:h,transfers:v,data:R||L||null,resolvedInputs:o};return this.cache.set(or.WarpExecutable(this.config.env,r.meta?.hash||"",t),ur.resolvedInputs,Q.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,c)=>{if(o.source==="query"){let l=this.url.searchParams.get(o.name);return l?this.serializer.nativeToString(o.type,l):null}else return o.source===p.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:s[c]||null};return a.map((o,c)=>{let l=i(o,c);return{input:o,value:l||(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(c=>c.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(p.ArgParamsSeparator,2);return y(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(l=>l.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 T().stringToNative(a)[1],c=await y(i,this.adapters).registry.getChainInfo(i);if(!c)throw new Error(`WarpUtils: Chain info not found for ${i}`);return c}async getDefaultChainInfo(r){if(!r.chain)return U(this.config);let e=await Z(this.adapters).registry.getChainInfo(r.chain,{ttl:Q.OneWeek});if(!e)throw new Error(`WarpUtils: Chain info not found for ${r.chain}`);return e}};var $=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(`${p.Vars.Query}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=i.split(`${p.Vars.Query}:`)[1],c=new URLSearchParams(r.currentUrl.split("?")[1]).get(o);c&&a(s,c)}else if(i.startsWith(`${p.Vars.Env}:`)){let o=i.split(`${p.Vars.Env}:`)[1],c=r.vars?.[o];c&&a(s,c)}else i===p.Source.UserWallet&&r.user?.wallet?a(s,r.user.wallet):a(s,i)}),JSON.parse(e)}async applyRootGlobals(r,t){let e=JSON.stringify(r),a={config:t,chain:U(t)};return Object.values(p.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}async applyActionGlobals(r){let t=r.chain?await this.adapter.registry.getChainInfo(r.chain):U(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(p.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}};var M=class{constructor(r,t,e){this.config=r;this.adapters=t;this.handlers=e;this.factory=new B(r,t),this.handlers=e}async execute(r,t){let[e,a]=rr(r);if(e.type==="collect"){let l=await this.executeCollect(r,a,t);return this.handlers?.onExecuted?.(l),[null,null]}let s=await this.factory.createExecutable(r,a,t),i=s.chain.name.toLowerCase(),o=this.adapters.find(l=>l.chain.toLowerCase()===i);if(!o)throw new Error(`No adapter registered for chain: ${i}`);return[await o.executor.createTransaction(s),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=b(r,t);if(!s)throw new Error("WarpActionExecutor: Action not found");let i=await this.factory.getChainInfoForAction(s),o=y(i.name,this.adapters),c=await new $(this.config,o).apply(this.config,r),l=await this.factory.getResolvedInputs(i,s,e),u=this.factory.getModifiedInputs(l),W=this.factory.serializer,d=m=>{if(!m.value)return null;let v=W.stringToNative(m.value)[1];return m.input.type==="biguint"?v.toString():m.input.type==="esdt"?{}:v},I=new Headers;I.set("Content-Type","application/json"),I.set("Accept","application/json"),Object.entries(s.destination.headers||{}).forEach(([m,v])=>{I.set(m,v)});let f=Object.fromEntries(u.map(m=>[m.input.as||m.input.name,d(m)])),h=s.destination.method||"GET",w=h==="GET"?void 0:JSON.stringify({...f,...a});x.info("Executing collect",{url:s.destination.url,method:h,headers:I,body:w});try{let m=await fetch(s.destination.url,{method:h,headers:I,body:w}),v=await m.json(),{values:R,results:L}=await ir(c,v,t,u),cr=ar(this.config,c,t,L);return{success:m.ok,warp:c,action:t,user:this.config.user?.wallet||null,txHash:null,next:cr,values:R,results:{...L,_DATA:v},messages:er(c,L)}}catch(m){return x.error("WarpActionExecutor: Error executing collect",m),{success:!1,warp:c,action:t,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{_DATA:m},messages:{}}}}};var G=class{constructor(r,t){this.config=r;this.adapters=t}isValid(r){return r.startsWith(p.HttpProtocolPrefix)?!!N(r):!1}async detectFromHtml(r){if(!r.length)return{match:!1,results:[]};let a=[...r.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),i=(await Promise.all(a)).filter(l=>l.match),o=i.length>0,c=i.map(l=>({url:l.url,warp:l.warp}));return{match:o,results:c}}async detect(r,t){let e={match:!1,url:r,warp:null,registryInfo:null,brand:null},a=r.startsWith(p.HttpProtocolPrefix)?N(r):E(r);if(!a)return e;try{let{type:s,identifierBase:i}=a,o=null,c=null,l=null,u=Y(a.chainPrefix,this.adapters);if(s==="hash"){o=await u.builder.createFromTransactionHash(i,t);let d=await u.registry.getInfoByHash(i,t);c=d.registryInfo,l=d.brand}else if(s==="alias"){let d=await u.registry.getInfoByAlias(i,t);c=d.registryInfo,l=d.brand,d.registryInfo&&(o=await u.builder.createFromTransactionHash(d.registryInfo.hash,t))}let W=o?await new $(this.config,u).apply(this.config,o):null;return W?{match:!0,url:r,warp:W,registryInfo:c,brand:l}:e}catch(s){return x.error("Error detecting warp link",s),e}}};var pr=class{constructor(r,t){this.config=r;this.adapters=t}getConfig(){return this.config}setConfig(r){return this.config=r,this}addAdapter(r){return this.adapters.push(r),this}createBuilder(){return new D(this.config)}createExecutor(r){return new M(this.config,this.adapters,r)}async detectWarp(r,t){return new G(this.config,this.adapters).detect(r,t)}createInscriptionTransaction(r,t){return y(r,this.adapters).builder.createInscriptionTransaction(t)}async createFromTransaction(r,t,e=!1){return y(r,this.adapters).builder.createFromTransaction(t,e)}async createFromTransactionHash(r,t,e){return y(r,this.adapters).builder.createFromTransactionHash(t,e)}getExplorer(r){return y(r.name,this.adapters).explorer(r)}getResults(r){return y(r.name,this.adapters).results}getRegistry(r){return y(r,this.adapters).registry}get factory(){return new B(this.config,this.adapters)}};var lr=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}}};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)):r(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(t)}catch(a){return e(a)}})});var Jt={};_(Jt,{CacheTtl:()=>Q,KnownTokens:()=>Ct,WarpBrandBuilder:()=>st,WarpBuilder:()=>H,WarpCache:()=>j,WarpCacheKey:()=>ot,WarpClient:()=>pt,WarpConfig:()=>g,WarpConstants:()=>p,WarpExecutor:()=>q,WarpFactory:()=>B,WarpIndex:()=>lt,WarpInputTypes:()=>C,WarpInterpolator:()=>$,WarpLinkBuilder:()=>D,WarpLinkDetecter:()=>G,WarpLogger:()=>x,WarpProtocolVersions:()=>S,WarpSerializer:()=>T,WarpValidator:()=>k,address:()=>zt,applyResultsToMessages:()=>et,biguint:()=>qt,boolean:()=>Gt,evaluateResultsCommon:()=>vt,extractCollectResults:()=>it,extractIdentifierInfoFromUrl:()=>N,findKnownTokenById:()=>Dt,findWarpAdapterByPrefix:()=>Y,findWarpAdapterForChain:()=>y,findWarpDefaultAdapter:()=>Z,findWarpExecutableAction:()=>tt,getLatestProtocolIdentifier:()=>O,getMainChainInfo:()=>U,getNextInfo:()=>at,getWarpActionByIndex:()=>b,getWarpInfoFromIdentifier:()=>E,hex:()=>Kt,parseResultsOutIndex:()=>xt,replacePlaceholders:()=>J,shiftBigintBy:()=>K,string:()=>kt,toPreviewText:()=>rt,toTypedChainInfo:()=>St,u16:()=>Ft,u32:()=>Mt,u64:()=>jt,u8:()=>Ht});module.exports=Pt(Jt);var p={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",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:"}},C={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"},g={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",p.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 Z=n=>{let t=n.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=(n,t)=>{let r=t.find(e=>e.chain.toLowerCase()===n.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${n}`);return r},Y=(n,t)=>{let r=t.find(e=>e.prefix.toLowerCase()===n.toLowerCase());if(!r)throw new Error(`Adapter not found for prefix: ${n}`);return r},U=n=>({name:g.MainChain.Name,displayName:g.MainChain.DisplayName,chainId:g.MainChain.ChainId(n.env),blockTime:g.MainChain.BlockTime(n.env),addressHrp:g.MainChain.AddressHrp,apiUrl:g.MainChain.ApiUrl(n.env),explorerUrl:g.MainChain.ExplorerUrl(n.env),nativeToken:g.MainChain.NativeToken}),O=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}`)},b=(n,t)=>n?.actions[t-1],tt=n=>(n.actions.forEach((t,r)=>{if(t.type!=="link")return[t,r]}),[b(n,1),1]),St=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,t)=>{let r=n.toString(),[e,a=""]=r.split("."),s=Math.abs(t);if(t>0)return BigInt(e+a.padEnd(s,"0"));if(t<0){let i=e+a;if(s>=i.length)return 0n;let o=i.slice(0,-s)||"0";return BigInt(o)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},rt=(n,t=100)=>{if(!n)return"";let r=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r},J=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),et=(n,t)=>{let r=Object.entries(n.messages||{}).map(([e,a])=>[e,J(a,t)]);return Object.fromEntries(r)};var E=n=>{let t=decodeURIComponent(n).trim(),r=t.split(p.IdentifierParamSeparator),e=t.split("?")[0];return r.length===3&&(r[1]===p.IdentifierType.Alias||r[1]===p.IdentifierType.Hash)?{chainPrefix:r[0],type:r[1],identifier:r[2],identifierBase:r[2].split("?")[0]}:r.length===2&&(r[0]===p.IdentifierType.Alias||r[0]===p.IdentifierType.Hash)?{chainPrefix:p.IdentifierChainDefault,type:r[0],identifier:r[1],identifierBase:r[1].split("?")[0]}:r.length===2&&/^[a-zA-Z0-9]{62}$/.test(r[0])&&/^[a-zA-Z0-9]{2}$/.test(r[1])?null:r.length===2&&r[0]!==p.IdentifierType.Alias&&r[0]!==p.IdentifierType.Hash?{chainPrefix:r[0],type:p.IdentifierType.Alias,identifier:r[1],identifierBase:r[1].split("?")[0]}:e.length===64?{chainPrefix:p.IdentifierChainDefault,type:p.IdentifierType.Hash,identifier:t,identifierBase:e}:{chainPrefix:p.IdentifierChainDefault,type:p.IdentifierType.Alias,identifier:t,identifierBase:e}},N=n=>{let t=new URL(n),e=t.searchParams.get(p.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let a=decodeURIComponent(e);return E(a)};var ht=X(require("qr-code-styling"));var D=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!N(t):!1}build(t,r){let e=this.config.clientUrl||g.DefaultClientUrl(this.config.env),a=t===p.IdentifierType.Alias?encodeURIComponent(r):encodeURIComponent(t+p.IdentifierParamSeparator+r);return g.SuperClientUrls.includes(e)?`${e}/${a}`:`${e}?${p.IdentifierParamName}=${a}`}buildFromPrefixedIdentifier(t){let r=E(t);return r?this.build(r.type,r.identifierBase):""}generateQrCode(t,r,e=512,a="white",s="black",i="#23F7DD"){let o=this.build(t,r);return new ht.default({type:"svg",width:e,height:e,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},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(i)}" 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 Bt="https://",at=(n,t,r,e)=>{let a=t.actions?.[r]?.next||t.next||null;if(!a)return null;if(a.startsWith(Bt))return[{identifier:null,url:a}];let[s,i]=a.split("?");if(!i)return[{identifier:s,url:nt(s,n)}];let o=i.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(o.length===0){let f=J(i,{...t.vars,...e}),h=f?`${s}?${f}`:s;return[{identifier:h,url:nt(h,n)}]}let l=o[0];if(!l)return[];let c=l.match(/{{([^[]+)\[\]/),u=c?c[1]:null;if(!u||e[u]===void 0)return[];let W=Array.isArray(e[u])?e[u]:[e[u]];if(W.length===0)return[];let d=o.filter(f=>f.includes(`{{${u}[]`)).map(f=>{let h=f.match(/\[\](\.[^}]+)?}}/),w=h&&h[1]||"";return{placeholder:f,field:w?w.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return W.map(f=>{let h=i;for(let{regex:m,field:v}of d){let P=v?$t(f,v):f;if(P==null)return null;h=h.replace(m,P)}if(h.includes("{{")||h.includes("}}"))return null;let w=h?`${s}?${h}`:s;return{identifier:w,url:nt(w,n)}}).filter(f=>f!==null)},nt=(n,t)=>{let[r,e]=n.split("?"),a=E(r)||{type:"alias",identifier:r,identifierBase:r},i=new D(t).build(a.type,a.identifierBase);if(!e)return i;let o=new URL(i);return new URLSearchParams(e).forEach((l,c)=>o.searchParams.set(c,l)),o.toString().replace(/\/\?/,"?")},$t=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);var V=class V{static info(...t){V.isTestEnv||console.info(...t)}static warn(...t){V.isTestEnv||console.warn(...t)}static error(...t){V.isTestEnv||console.error(...t)}};V.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var x=V;var T=class{nativeToString(t,r){return`${t}:${r?.toString()??""}`}stringToNative(t){let r=t.split(p.ArgParamsSeparator),e=r[0],a=r.slice(1).join(p.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[s,i]=a.split(p.ArgParamsSeparator);return[`option:${s}`,i||null]}else if(e==="optional"){let[s,i]=a.split(p.ArgParamsSeparator);return[`optional:${s}`,i||null]}else if(e==="list"){let s=a.split(p.ArgParamsSeparator),i=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`list:${i}`,c]}else if(e==="variadic"){let s=a.split(p.ArgParamsSeparator),i=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`variadic:${i}`,c]}else if(e.startsWith("composite")){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=a.split(p.ArgCompositeSeparator).map((l,c)=>this.stringToNative(`${s[c]}:${l}`)[1]);return[e,o]}else{if(e==="string")return[e,a];if(e==="uint8"||e==="uint16"||e==="uint32")return[e,Number(a)];if(e==="uint64"||e==="biguint")return[e,BigInt(a||0)];if(e==="bool")return[e,a==="true"];if(e==="address")return[e,a];if(e==="token")return[e,a];if(e==="hex")return[e,a];if(e==="codemeta")return[e,a];if(e==="esdt"){let[s,i,o]=a.split(p.ArgCompositeSeparator);return[e,`${s}|${i}|${o}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}};var it=async(n,t,r,e)=>{let a=[],s={};for(let[i,o]of Object.entries(n.results||{})){if(o.startsWith(p.Transform.Prefix))continue;let l=xt(o);if(l!==null&&l!==r){s[i]=null;continue}let[c,...u]=o.split("."),W=(d,I)=>I.reduce((f,h)=>f&&f[h]!==void 0?f[h]:null,d);if(c==="out"||c.startsWith("out[")){let d=u.length===0?t?.data||t:W(t,u);a.push(d),s[i]=d}else s[i]=o}return{values:a,results:await vt(n,s,r,e)}},vt=async(n,t,r,e)=>{if(!n.results)return t;let a={...t};return a=Lt(a,n,r,e),a=await Ot(n,a),a},Lt=(n,t,r,e)=>{let a={...n},s=b(t,r)?.inputs||[],i=new T;for(let[o,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("input.")){let c=l.split(".")[1],u=s.findIndex(d=>d.as===c||d.name===c),W=u!==-1?e[u]?.value:null;a[o]=W?i.stringToNative(W)[1]:null}return a},Ot=async(n,t)=>{if(!n.results)return t;let r={...t},e=Object.entries(n.results).filter(([,a])=>a.startsWith(p.Transform.Prefix)).map(([a,s])=>({key:a,code:s.substring(p.Transform.Prefix.length)}));for(let{key:a,code:s}of e)try{let i;typeof window>"u"?i=(await Promise.resolve().then(()=>(gt(),mt))).runInVm:i=(await Promise.resolve().then(()=>(yt(),Wt))).runInVm,r[a]=await i(s,r)}catch(i){x.error(`Transform error for result '${a}':`,i),r[a]=null}return r},xt=n=>{if(n==="out")return 1;let t=n.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};var Ct=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Dt=n=>Ct.find(t=>t.id===n)||null;var kt=n=>`${C.String}:${n}`,Ht=n=>`${C.U8}:${n}`,Ft=n=>`${C.U16}:${n}`,Mt=n=>`${C.U32}:${n}`,jt=n=>`${C.U64}:${n}`,qt=n=>`${C.Biguint}:${n}`,Gt=n=>`${C.Boolean}:${n}`,zt=n=>`${C.Address}:${n}`,Kt=n=>`${C.Hex}:${n}`;var It=X(require("ajv"));var st=class{constructor(t){this.pendingBrand={protocol:O("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,a=await(await fetch(r)).json(),s=new It.default,i=s.compile(a);if(!i(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(i.errors)}`)}};var wt=X(require("ajv"));var k=class{constructor(t){this.config=t;this.config=t}async validate(t){let r=[];return r.push(...this.validateMaxOneValuePosition(t)),r.push(...this.validateVariableNamesAndResultNamesUppercase(t)),r.push(...this.validateAbiIsSetIfApplicable(t)),r.push(...await this.validateSchema(t)),{valid:r.length===0,errors:r}}validateMaxOneValuePosition(t){return t.actions.filter(e=>e.inputs?e.inputs.some(a=>a.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(a,s)=>{a&&Object.keys(a).forEach(i=>{i!==i.toUpperCase()&&r.push(`${s} name '${i}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.results,"Result"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(i=>i.type==="contract"),e=t.actions.some(i=>i.type==="query");if(!r&&!e)return[];let a=t.actions.some(i=>i.abi),s=Object.values(t.results||{}).some(i=>i.startsWith("out.")||i.startsWith("event."));return t.results&&!a&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||g.LatestWarpSchemaUrl,a=await(await fetch(r)).json(),s=new wt.default({strict:!1}),i=s.compile(a);return i(t)?[]:[`Schema validation failed: ${s.errorsText(i.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var H=class{constructor(t){this.config=t;this.pendingWarp={protocol:O("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 k(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
12
+ `))}};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 a={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(a))}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 R=class R{get(t){let r=R.cache.get(t);return r?Date.now()>r.expiresAt?(R.cache.delete(t),null):r.value:null}set(t,r,e){let a=Date.now()+e*1e3;R.cache.set(t,{value:r,expiresAt:a})}forget(t){R.cache.delete(t)}clear(){R.cache.clear()}};R.cache=new Map;var M=R;var Q={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},ot={Warp:(n,t)=>`warp:${n}:${t}`,WarpAbi:(n,t)=>`warp-abi:${n}:${t}`,WarpExecutable:(n,t,r)=>`warp-exec:${n}:${t}:${r}`,RegistryInfo:(n,t)=>`registry-info:${n}:${t}`,Brand:(n,t)=>`brand:${n}:${t}`,ChainInfo:(n,t)=>`chain:${n}:${t}`,ChainInfos:n=>`chains:${n}`},j=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new F:t==="memory"?new M:typeof window<"u"&&window.localStorage?new F:new M}set(t,r,e){this.strategy.set(t,r,e)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var B=class{constructor(t,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 T,this.cache=new j(t.cache?.type)}async createExecutable(t,r,e){let a=b(t,r);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),l=o.find(A=>A.input.position==="receiver")?.value,c="address"in a?a.address:null,u=l?.split(":")[1]||c;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let W=u,d=this.getPreparedArgs(a,o),I=o.find(A=>A.input.position==="value")?.value||null,f="value"in a?a.value:null,h=BigInt(I?.split(":")[1]||f||0),w=o.filter(A=>A.input.position==="transfer"&&A.value).map(A=>A.value),v=[...("transfers"in a?a.transfers:[])||[],...w||[]],P=o.find(A=>A.input.position==="data")?.value,L="data"in a?a.data||"":null,ut={warp:t,chain:s,action:r,destination:W,args:d,value:h,transfers:v,data:P||L||null,resolvedInputs:o};return this.cache.set(ot.WarpExecutable(this.config.env,t.meta?.hash||"",r),ut.resolvedInputs,Q.OneWeek),ut}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 a=r.inputs||[],s=await Promise.all(e.map(o=>this.preprocessInput(t,o))),i=(o,l)=>{if(o.source==="query"){let c=this.url.searchParams.get(o.name);return c?this.serializer.nativeToString(o.type,c):null}else return o.source===p.Source.UserWallet?this.config.user?.wallets?.[t.name]?this.serializer.nativeToString("address",this.config.user.wallets[t.name]):null:s[l]||null};return a.map((o,l)=>{let c=i(o,l);return{input:o,value:c||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(t){return t.map((r,e)=>{if(r.input.modifier?.startsWith("scale:")){let[,a]=r.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(t.find(l=>l.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let i=r.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let o=K(i,+s);return{...r,value:`${r.input.type}:${o}`}}else{let s=r.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let i=K(s,+a);return{...r,value:`${r.input.type}:${i}`}}}else return r})}async preprocessInput(t,r){try{let[e,a]=r.split(p.ArgParamsSeparator,2);return y(t.name,this.adapters).executor.preprocessInput(t,r,e,a)}catch{return r}}getPreparedArgs(t,r){let e="args"in t?t.args||[]:[];return r.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(t,r){let e=t.inputs?.findIndex(c=>c.position==="chain");if(e===-1||e===void 0)return null;let a=r[e];if(!a)throw new Error("WarpUtils: Chain input not found");let i=new T().stringToNative(a)[1],l=await y(i,this.adapters).registry.getChainInfo(i);if(!l)throw new Error(`WarpUtils: Chain info not found for ${i}`);return l}async getDefaultChainInfo(t){if(!t.chain)return U(this.config);let e=await Z(this.adapters).registry.getChainInfo(t.chain,{ttl:Q.OneWeek});if(!e)throw new Error(`WarpUtils: Chain info not found for ${t.chain}`);return e}};var $=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 a=>await this.applyActionGlobals(a))),e=await this.applyRootGlobals(e,t),e}applyVars(t,r){if(!r?.vars)return r;let e=JSON.stringify(r),a=(s,i)=>{e=e.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),i.toString())};return Object.entries(r.vars).forEach(([s,i])=>{if(typeof i!="string")a(s,i);else if(i.startsWith(`${p.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=i.split(`${p.Vars.Query}:`)[1],l=new URLSearchParams(t.currentUrl.split("?")[1]).get(o);l&&a(s,l)}else if(i.startsWith(`${p.Vars.Env}:`)){let o=i.split(`${p.Vars.Env}:`)[1],l=t.vars?.[o];l&&a(s,l)}else if(i===p.Source.UserWallet&&t.user?.wallets?.[this.adapter.chain]){let o=t.user.wallets[this.adapter.chain];o&&a(s,o)}else a(s,i)}),JSON.parse(e)}async applyRootGlobals(t,r){let e=JSON.stringify(t),a={config:r,chain:U(r)};return Object.values(p.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}async applyActionGlobals(t){let r=t.chain?await this.adapter.registry.getChainInfo(t.chain):U(this.config);if(!r)throw new Error(`Chain info not found for ${t.chain}`);let e=JSON.stringify(t),a={config:this.config,chain:r};return Object.values(p.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}};var q=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.factory=new B(t,r),this.handlers=e}async execute(t,r){let[e,a]=tt(t);if(e.type==="collect"){let c=await this.executeCollect(t,a,r);return this.handlers?.onExecuted?.(c),{tx:null,chain:null}}let s=await this.factory.createExecutable(t,a,r),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(t,r,e){let a=this.adapters.find(i=>i.chain.toLowerCase()===r.name.toLowerCase());if(!a)throw new Error(`No adapter registered for chain: ${r.name}`);let s=await a.results.getTransactionExecutionResults(t,e);this.handlers?.onExecuted?.(s)}async executeCollect(t,r,e,a){let s=b(t,r);if(!s)throw new Error("WarpActionExecutor: Action not found");let i=await this.factory.getChainInfoForAction(s),o=y(i.name,this.adapters),l=await new $(this.config,o).apply(this.config,t),c=await this.factory.getResolvedInputs(i,s,e),u=this.factory.getModifiedInputs(c),W=this.factory.serializer,d=m=>{if(!m.value)return null;let v=W.stringToNative(m.value)[1];return m.input.type==="biguint"?v.toString():m.input.type==="esdt"?{}:v},I=new Headers;I.set("Content-Type","application/json"),I.set("Accept","application/json"),Object.entries(s.destination.headers||{}).forEach(([m,v])=>{I.set(m,v)});let f=Object.fromEntries(u.map(m=>[m.input.as||m.input.name,d(m)])),h=s.destination.method||"GET",w=h==="GET"?void 0:JSON.stringify({...f,...a});x.info("Executing collect",{url:s.destination.url,method:h,headers:I,body:w});try{let m=await fetch(s.destination.url,{method:h,headers:I,body:w}),v=await m.json(),{values:P,results:L}=await it(l,v,r,u),ct=at(this.config,l,r,L);return{success:m.ok,warp:l,action:r,user:this.config.user?.wallets?.[i.name]||null,txHash:null,next:ct,values:P,results:{...L,_DATA:v},messages:et(l,L)}}catch(m){return x.error("WarpActionExecutor: Error executing collect",m),{success:!1,warp:l,action:r,user:this.config.user?.wallets?.[i.name]||null,txHash:null,next:null,values:[],results:{_DATA:m},messages:{}}}}};var G=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!N(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let a=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),i=(await Promise.all(a)).filter(c=>c.match),o=i.length>0,l=i.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:l}}async detect(t,r){let e={match:!1,url:t,warp:null,registryInfo:null,brand:null},a=t.startsWith(p.HttpProtocolPrefix)?N(t):E(t);if(!a)return e;try{let{type:s,identifierBase:i}=a,o=null,l=null,c=null,u=Y(a.chainPrefix,this.adapters);if(s==="hash"){o=await u.builder.createFromTransactionHash(i,r);let d=await u.registry.getInfoByHash(i,r);l=d.registryInfo,c=d.brand}else if(s==="alias"){let d=await u.registry.getInfoByAlias(i,r);l=d.registryInfo,c=d.brand,d.registryInfo&&(o=await u.builder.createFromTransactionHash(d.registryInfo.hash,r))}let W=o?await new $(this.config,u).apply(this.config,o):null;return W?{match:!0,url:t,warp:W,registryInfo:l,brand:c}:e}catch(s){return x.error("Error detecting warp link",s),e}}};var pt=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}setConfig(t){return this.config=t,this}addAdapter(t){return this.adapters.push(t),this}createBuilder(){return new H(this.config)}createExecutor(t){return new q(this.config,this.adapters,t)}async detectWarp(t,r){return new G(this.config,this.adapters).detect(t,r)}async executeWarp(t,r,e,a={}){let s=await this.detectWarp(t,a.cache);if(!s.match||!s.warp)throw new Error("Warp not found");let i=this.createExecutor(e),{tx:o,chain:l}=await i.execute(s.warp,r);return{tx:o,chain:l,evaluateResults:async u=>{if(!l||!o||!s.warp)throw new Error("Warp not found");await i.evaluateResults(s.warp,l,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,e){return y(t,this.adapters).builder.createFromTransactionHash(r,e)}getExplorer(t){return y(t.name,this.adapters).explorer(t)}getResults(t){return y(t.name,this.adapters).results}getRegistry(t){return y(t,this.adapters).registry}get factory(){return new B(this.config,this.adapters)}};var lt=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 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"]:t,...r})});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}}};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});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import"./chunk-3SAEGOMQ.mjs";var p={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"mvx",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:n=>n.chain.explorerUrl},ChainAddressHrp:{Placeholder:"chain.addressHrp",Accessor:n=>n.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},w={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"},Registry:{Contract:n=>n==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":n==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query",p.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 Z=n=>{let t=n.find(r=>r.chain.toLowerCase()===m.MainChain.Name.toLowerCase());if(!t)throw new Error(`Adapter not found for chain: ${m.MainChain.Name}`);return t},v=(n,t)=>{let r=t.find(e=>e.chain.toLowerCase()===n.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${n}`);return r},Y=(n,t)=>{let r=t.find(e=>e.prefix.toLowerCase()===n.toLowerCase());if(!r)throw new Error(`Adapter not found for prefix: ${n}`);return r},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}),D=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,t)=>n?.actions[t-1],tt=n=>(n.actions.forEach((t,r)=>{if(t.type!=="link")return[t,r]}),[T(n,1),1]),At=n=>({name:n.name.toString(),displayName:n.display_name.toString(),chainId:n.chain_id.toString(),blockTime:n.block_time.toNumber(),addressHrp:n.address_hrp.toString(),apiUrl:n.api_url.toString(),explorerUrl:n.explorer_url.toString(),nativeToken:n.native_token.toString()}),z=(n,t)=>{let r=n.toString(),[e,a=""]=r.split("."),s=Math.abs(t);if(t>0)return BigInt(e+a.padEnd(s,"0"));if(t<0){let i=e+a;if(s>=i.length)return 0n;let o=i.slice(0,-s)||"0";return BigInt(o)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},rt=(n,t=100)=>{if(!n)return"";let r=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r},K=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),et=(n,t)=>{let r=Object.entries(n.messages||{}).map(([e,a])=>[e,K(a,t)]);return Object.fromEntries(r)};var P=n=>{let t=decodeURIComponent(n).trim(),r=t.split(p.IdentifierParamSeparator),e=t.split("?")[0];return r.length===3&&(r[1]===p.IdentifierType.Alias||r[1]===p.IdentifierType.Hash)?{chainPrefix:r[0],type:r[1],identifier:r[2],identifierBase:r[2].split("?")[0]}:r.length===2&&(r[0]===p.IdentifierType.Alias||r[0]===p.IdentifierType.Hash)?{chainPrefix:p.IdentifierChainDefault,type:r[0],identifier:r[1],identifierBase:r[1].split("?")[0]}:r.length===2&&/^[a-zA-Z0-9]{62}$/.test(r[0])&&/^[a-zA-Z0-9]{2}$/.test(r[1])?null:r.length===2&&r[0]!==p.IdentifierType.Alias&&r[0]!==p.IdentifierType.Hash?{chainPrefix:r[0],type:p.IdentifierType.Alias,identifier:r[1],identifierBase:r[1].split("?")[0]}:e.length===64?{chainPrefix:p.IdentifierChainDefault,type:p.IdentifierType.Hash,identifier:t,identifierBase:e}:{chainPrefix:p.IdentifierChainDefault,type:p.IdentifierType.Alias,identifier:t,identifierBase:e}},L=n=>{let t=new URL(n),e=t.searchParams.get(p.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let a=decodeURIComponent(e);return P(a)};import lt from"qr-code-styling";var k=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!L(t):!1}build(t,r){let e=this.config.clientUrl||m.DefaultClientUrl(this.config.env),a=t===p.IdentifierType.Alias?encodeURIComponent(r):encodeURIComponent(t+p.IdentifierParamSeparator+r);return m.SuperClientUrls.includes(e)?`${e}/${a}`:`${e}?${p.IdentifierParamName}=${a}`}buildFromPrefixedIdentifier(t){let r=P(t);return r?this.build(r.type,r.identifierBase):""}generateQrCode(t,r,e=512,a="white",s="black",i="#23F7DD"){let o=this.build(t,r);return new lt({type:"svg",width:e,height:e,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},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(i)}" 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 ct="https://",nt=(n,t,r,e)=>{let a=t.actions?.[r]?.next||t.next||null;if(!a)return null;if(a.startsWith(ct))return[{identifier:null,url:a}];let[s,i]=a.split("?");if(!i)return[{identifier:s,url:J(s,n)}];let o=i.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(o.length===0){let f=K(i,{...t.vars,...e}),h=f?`${s}?${f}`:s;return[{identifier:h,url:J(h,n)}]}let c=o[0];if(!c)return[];let l=c.match(/{{([^[]+)\[\]/),u=l?l[1]:null;if(!u||e[u]===void 0)return[];let W=Array.isArray(e[u])?e[u]:[e[u]];if(W.length===0)return[];let d=o.filter(f=>f.includes(`{{${u}[]`)).map(f=>{let h=f.match(/\[\](\.[^}]+)?}}/),I=h&&h[1]||"";return{placeholder:f,field:I?I.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return W.map(f=>{let h=i;for(let{regex:g,field:y}of d){let E=y?ut(f,y):f;if(E==null)return null;h=h.replace(g,E)}if(h.includes("{{")||h.includes("}}"))return null;let I=h?`${s}?${h}`:s;return{identifier:I,url:J(I,n)}}).filter(f=>f!==null)},J=(n,t)=>{let[r,e]=n.split("?"),a=P(r)||{type:"alias",identifier:r,identifierBase:r},i=new k(t).build(a.type,a.identifierBase);if(!e)return i;let o=new URL(i);return new URLSearchParams(e).forEach((c,l)=>o.searchParams.set(l,c)),o.toString().replace(/\/\?/,"?")},ut=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);var B=class B{static info(...t){B.isTestEnv||console.info(...t)}static warn(...t){B.isTestEnv||console.warn(...t)}static error(...t){B.isTestEnv||console.error(...t)}};B.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var x=B;var R=class{nativeToString(t,r){return`${t}:${r?.toString()??""}`}stringToNative(t){let r=t.split(p.ArgParamsSeparator),e=r[0],a=r.slice(1).join(p.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[s,i]=a.split(p.ArgParamsSeparator);return[`option:${s}`,i||null]}else if(e==="optional"){let[s,i]=a.split(p.ArgParamsSeparator);return[`optional:${s}`,i||null]}else if(e==="list"){let s=a.split(p.ArgParamsSeparator),i=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],l=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`list:${i}`,l]}else if(e==="variadic"){let s=a.split(p.ArgParamsSeparator),i=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],l=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`variadic:${i}`,l]}else if(e.startsWith("composite")){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=a.split(p.ArgCompositeSeparator).map((c,l)=>this.stringToNative(`${s[l]}:${c}`)[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(p.ArgCompositeSeparator);return[e,`${s}|${i}|${o}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}};var at=async(n,t,r,e)=>{let a=[],s={};for(let[i,o]of Object.entries(n.results||{})){if(o.startsWith(p.Transform.Prefix))continue;let c=gt(o);if(c!==null&&c!==r){s[i]=null;continue}let[l,...u]=o.split("."),W=(d,C)=>C.reduce((f,h)=>f&&f[h]!==void 0?f[h]:null,d);if(l==="out"||l.startsWith("out[")){let d=u.length===0?t?.data||t:W(t,u);a.push(d),s[i]=d}else s[i]=o}return{values:a,results:await dt(n,s,r,e)}},dt=async(n,t,r,e)=>{if(!n.results)return t;let a={...t};return a=ft(a,n,r,e),a=await ht(n,a),a},ft=(n,t,r,e)=>{let a={...n},s=T(t,r)?.inputs||[],i=new R;for(let[o,c]of Object.entries(a))if(typeof c=="string"&&c.startsWith("input.")){let l=c.split(".")[1],u=s.findIndex(d=>d.as===l||d.name===l),W=u!==-1?e[u]?.value:null;a[o]=W?i.stringToNative(W)[1]:null}return a},ht=async(n,t)=>{if(!n.results)return t;let r={...t},e=Object.entries(n.results).filter(([,a])=>a.startsWith(p.Transform.Prefix)).map(([a,s])=>({key:a,code:s.substring(p.Transform.Prefix.length)}));for(let{key:a,code:s}of e)try{let i;typeof window>"u"?i=(await import("./runInVm-BFUZVHHD.mjs")).runInVm:i=(await import("./runInVm-5YQ766M3.mjs")).runInVm,r[a]=await i(s,r)}catch(i){x.error(`Transform error for result '${a}':`,i),r[a]=null}return r},gt=n=>{if(n==="out")return 1;let t=n.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};var mt=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Qt=n=>mt.find(t=>t.id===n)||null;var or=n=>`${w.String}:${n}`,pr=n=>`${w.U8}:${n}`,lr=n=>`${w.U16}:${n}`,cr=n=>`${w.U32}:${n}`,ur=n=>`${w.U64}:${n}`,dr=n=>`${w.Biguint}:${n}`,fr=n=>`${w.Boolean}:${n}`,hr=n=>`${w.Address}:${n}`,gr=n=>`${w.Hex}:${n}`;import Wt from"ajv";var it=class{constructor(t){this.pendingBrand={protocol:D("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,a=await(await fetch(r)).json(),s=new Wt,i=s.compile(a);if(!i(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(i.errors)}`)}};import yt from"ajv";var H=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(a=>a.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(a,s)=>{a&&Object.keys(a).forEach(i=>{i!==i.toUpperCase()&&r.push(`${s} name '${i}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.results,"Result"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(i=>i.type==="contract"),e=t.actions.some(i=>i.type==="query");if(!r&&!e)return[];let a=t.actions.some(i=>i.abi),s=Object.values(t.results||{}).some(i=>i.startsWith("out.")||i.startsWith("event."));return t.results&&!a&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||m.LatestWarpSchemaUrl,a=await(await fetch(r)).json(),s=new yt({strict:!1}),i=s.compile(a);return i(t)?[]:[`Schema validation failed: ${s.errorsText(i.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var F=class{constructor(t){this.config=t;this.pendingWarp={protocol:D("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 H(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
2
- `))}};var q=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let r=localStorage.getItem(this.getKey(t));if(!r)return null;let 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 a={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(a))}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 b=class b{get(t){let r=b.cache.get(t);return r?Date.now()>r.expiresAt?(b.cache.delete(t),null):r.value:null}set(t,r,e){let a=Date.now()+e*1e3;b.cache.set(t,{value:r,expiresAt:a})}forget(t){b.cache.delete(t)}clear(){b.cache.clear()}};b.cache=new Map;var O=b;var Q={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},st={Warp:(n,t)=>`warp:${n}:${t}`,WarpAbi:(n,t)=>`warp-abi:${n}:${t}`,WarpExecutable:(n,t,r)=>`warp-exec:${n}:${t}:${r}`,RegistryInfo:(n,t)=>`registry-info:${n}:${t}`,Brand:(n,t)=>`brand:${n}:${t}`,ChainInfo:(n,t)=>`chain:${n}:${t}`,ChainInfos:n=>`chains:${n}`},j=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new q:t==="memory"?new O:typeof window<"u"&&window.localStorage?new q:new O}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 $=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 j(t.cache?.type)}async createExecutable(t,r,e){let a=T(t,r);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),c=o.find(A=>A.input.position==="receiver")?.value,l="address"in a?a.address:null,u=c?.split(":")[1]||l;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let W=u,d=this.getPreparedArgs(a,o),C=o.find(A=>A.input.position==="value")?.value||null,f="value"in a?a.value:null,h=BigInt(C?.split(":")[1]||f||0),I=o.filter(A=>A.input.position==="transfer"&&A.value).map(A=>A.value),y=[...("transfers"in a?a.transfers:[])||[],...I||[]],E=o.find(A=>A.input.position==="data")?.value,U="data"in a?a.data||"":null,X={warp:t,chain:s,action:r,destination:W,args:d,value:h,transfers:y,data:E||U||null,resolvedInputs:o};return this.cache.set(st.WarpExecutable(this.config.env,t.meta?.hash||"",r),X.resolvedInputs,Q.OneWeek),X}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 a=r.inputs||[],s=await Promise.all(e.map(o=>this.preprocessInput(t,o))),i=(o,c)=>{if(o.source==="query"){let l=this.url.searchParams.get(o.name);return l?this.serializer.nativeToString(o.type,l):null}else return o.source===p.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:s[c]||null};return a.map((o,c)=>{let l=i(o,c);return{input:o,value:l||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(t){return t.map((r,e)=>{if(r.input.modifier?.startsWith("scale:")){let[,a]=r.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(t.find(c=>c.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let i=r.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let o=z(i,+s);return{...r,value:`${r.input.type}:${o}`}}else{let s=r.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let i=z(s,+a);return{...r,value:`${r.input.type}:${i}`}}}else return r})}async preprocessInput(t,r){try{let[e,a]=r.split(p.ArgParamsSeparator,2);return v(t.name,this.adapters).executor.preprocessInput(t,r,e,a)}catch{return r}}getPreparedArgs(t,r){let e="args"in t?t.args||[]:[];return r.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(t,r){let e=t.inputs?.findIndex(l=>l.position==="chain");if(e===-1||e===void 0)return null;let a=r[e];if(!a)throw new Error("WarpUtils: Chain input not found");let i=new R().stringToNative(a)[1],c=await v(i,this.adapters).registry.getChainInfo(i);if(!c)throw new Error(`WarpUtils: Chain info not found for ${i}`);return c}async getDefaultChainInfo(t){if(!t.chain)return V(this.config);let e=await Z(this.adapters).registry.getChainInfo(t.chain,{ttl:Q.OneWeek});if(!e)throw new Error(`WarpUtils: Chain info not found for ${t.chain}`);return e}};var N=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 a=>await this.applyActionGlobals(a))),e=await this.applyRootGlobals(e,t),e}applyVars(t,r){if(!r?.vars)return r;let e=JSON.stringify(r),a=(s,i)=>{e=e.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),i.toString())};return Object.entries(r.vars).forEach(([s,i])=>{if(typeof i!="string")a(s,i);else if(i.startsWith(`${p.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=i.split(`${p.Vars.Query}:`)[1],c=new URLSearchParams(t.currentUrl.split("?")[1]).get(o);c&&a(s,c)}else if(i.startsWith(`${p.Vars.Env}:`)){let o=i.split(`${p.Vars.Env}:`)[1],c=t.vars?.[o];c&&a(s,c)}else i===p.Source.UserWallet&&t.user?.wallet?a(s,t.user.wallet):a(s,i)}),JSON.parse(e)}async applyRootGlobals(t,r){let e=JSON.stringify(t),a={config:r,chain:V(r)};return Object.values(p.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}async applyActionGlobals(t){let r=t.chain?await this.adapter.registry.getChainInfo(t.chain):V(this.config);if(!r)throw new Error(`Chain info not found for ${t.chain}`);let e=JSON.stringify(t),a={config:this.config,chain:r};return Object.values(p.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}};var M=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.factory=new $(t,r),this.handlers=e}async execute(t,r){let[e,a]=tt(t);if(e.type==="collect"){let l=await this.executeCollect(t,a,r);return this.handlers?.onExecuted?.(l),[null,null]}let s=await this.factory.createExecutable(t,a,r),i=s.chain.name.toLowerCase(),o=this.adapters.find(l=>l.chain.toLowerCase()===i);if(!o)throw new Error(`No adapter registered for chain: ${i}`);return[await o.executor.createTransaction(s),s.chain]}async evaluateResults(t,r,e){let a=this.adapters.find(i=>i.chain.toLowerCase()===r.name.toLowerCase());if(!a)throw new Error(`No adapter registered for chain: ${r.name}`);let s=await a.results.getTransactionExecutionResults(t,e);this.handlers?.onExecuted?.(s)}async executeCollect(t,r,e,a){let s=T(t,r);if(!s)throw new Error("WarpActionExecutor: Action not found");let i=await this.factory.getChainInfoForAction(s),o=v(i.name,this.adapters),c=await new N(this.config,o).apply(this.config,t),l=await this.factory.getResolvedInputs(i,s,e),u=this.factory.getModifiedInputs(l),W=this.factory.serializer,d=g=>{if(!g.value)return null;let y=W.stringToNative(g.value)[1];return g.input.type==="biguint"?y.toString():g.input.type==="esdt"?{}:y},C=new Headers;C.set("Content-Type","application/json"),C.set("Accept","application/json"),Object.entries(s.destination.headers||{}).forEach(([g,y])=>{C.set(g,y)});let f=Object.fromEntries(u.map(g=>[g.input.as||g.input.name,d(g)])),h=s.destination.method||"GET",I=h==="GET"?void 0:JSON.stringify({...f,...a});x.info("Executing collect",{url:s.destination.url,method:h,headers:C,body:I});try{let g=await fetch(s.destination.url,{method:h,headers:C,body:I}),y=await g.json(),{values:E,results:U}=await at(c,y,r,u),_=nt(this.config,c,r,U);return{success:g.ok,warp:c,action:r,user:this.config.user?.wallet||null,txHash:null,next:_,values:E,results:{...U,_DATA:y},messages:et(c,U)}}catch(g){return x.error("WarpActionExecutor: Error executing collect",g),{success:!1,warp:c,action:r,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{_DATA:g},messages:{}}}}};var G=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!L(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let a=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),i=(await Promise.all(a)).filter(l=>l.match),o=i.length>0,c=i.map(l=>({url:l.url,warp:l.warp}));return{match:o,results:c}}async detect(t,r){let e={match:!1,url:t,warp:null,registryInfo:null,brand:null},a=t.startsWith(p.HttpProtocolPrefix)?L(t):P(t);if(!a)return e;try{let{type:s,identifierBase:i}=a,o=null,c=null,l=null,u=Y(a.chainPrefix,this.adapters);if(s==="hash"){o=await u.builder.createFromTransactionHash(i,r);let d=await u.registry.getInfoByHash(i,r);c=d.registryInfo,l=d.brand}else if(s==="alias"){let d=await u.registry.getInfoByAlias(i,r);c=d.registryInfo,l=d.brand,d.registryInfo&&(o=await u.builder.createFromTransactionHash(d.registryInfo.hash,r))}let W=o?await new N(this.config,u).apply(this.config,o):null;return W?{match:!0,url:t,warp:W,registryInfo:c,brand:l}:e}catch(s){return x.error("Error detecting warp link",s),e}}};var ot=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}setConfig(t){return this.config=t,this}addAdapter(t){return this.adapters.push(t),this}createBuilder(){return new F(this.config)}createExecutor(t){return new M(this.config,this.adapters,t)}async detectWarp(t,r){return new G(this.config,this.adapters).detect(t,r)}createInscriptionTransaction(t,r){return v(t,this.adapters).builder.createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return v(t,this.adapters).builder.createFromTransaction(r,e)}async createFromTransactionHash(t,r,e){return v(t,this.adapters).builder.createFromTransactionHash(r,e)}getExplorer(t){return v(t.name,this.adapters).explorer(t)}getResults(t){return v(t.name,this.adapters).results}getRegistry(t){return v(t,this.adapters).registry}get factory(){return new $(this.config,this.adapters)}};var pt=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 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"]:t,...r})});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}}};export{Q as CacheTtl,mt as KnownTokens,it as WarpBrandBuilder,F as WarpBuilder,j as WarpCache,st as WarpCacheKey,ot as WarpClient,m as WarpConfig,p as WarpConstants,M as WarpExecutor,$ as WarpFactory,pt as WarpIndex,w as WarpInputTypes,N as WarpInterpolator,k as WarpLinkBuilder,G as WarpLinkDetecter,x as WarpLogger,S as WarpProtocolVersions,R as WarpSerializer,H as WarpValidator,hr as address,et as applyResultsToMessages,dr as biguint,fr as boolean,dt as evaluateResultsCommon,at as extractCollectResults,L as extractIdentifierInfoFromUrl,Qt as findKnownTokenById,Y as findWarpAdapterByPrefix,v as findWarpAdapterForChain,Z as findWarpDefaultAdapter,tt as findWarpExecutableAction,D as getLatestProtocolIdentifier,V as getMainChainInfo,nt as getNextInfo,T as getWarpActionByIndex,P as getWarpInfoFromIdentifier,gr as hex,gt as parseResultsOutIndex,K as replacePlaceholders,z as shiftBigintBy,or as string,rt as toPreviewText,At as toTypedChainInfo,lr as u16,cr as u32,ur as u64,pr as u8};
1
+ import"./chunk-3SAEGOMQ.mjs";var p={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",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:"}},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 S={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${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",p.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 Z=n=>{let t=n.find(r=>r.chain.toLowerCase()===g.MainChain.Name.toLowerCase());if(!t)throw new Error(`Adapter not found for chain: ${g.MainChain.Name}`);return t},x=(n,t)=>{let r=t.find(e=>e.chain.toLowerCase()===n.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${n}`);return r},Y=(n,t)=>{let r=t.find(e=>e.prefix.toLowerCase()===n.toLowerCase());if(!r)throw new Error(`Adapter not found for prefix: ${n}`);return r},V=n=>({name:g.MainChain.Name,displayName:g.MainChain.DisplayName,chainId:g.MainChain.ChainId(n.env),blockTime:g.MainChain.BlockTime(n.env),addressHrp:g.MainChain.AddressHrp,apiUrl:g.MainChain.ApiUrl(n.env),explorerUrl:g.MainChain.ExplorerUrl(n.env),nativeToken:g.MainChain.NativeToken}),H=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}`)},E=(n,t)=>n?.actions[t-1],tt=n=>(n.actions.forEach((t,r)=>{if(t.type!=="link")return[t,r]}),[E(n,1),1]),wt=n=>({name:n.name.toString(),displayName:n.display_name.toString(),chainId:n.chain_id.toString(),blockTime:n.block_time.toNumber(),addressHrp:n.address_hrp.toString(),apiUrl:n.api_url.toString(),explorerUrl:n.explorer_url.toString(),nativeToken:n.native_token.toString()}),z=(n,t)=>{let r=n.toString(),[e,a=""]=r.split("."),s=Math.abs(t);if(t>0)return BigInt(e+a.padEnd(s,"0"));if(t<0){let i=e+a;if(s>=i.length)return 0n;let o=i.slice(0,-s)||"0";return BigInt(o)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},rt=(n,t=100)=>{if(!n)return"";let r=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r},K=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),et=(n,t)=>{let r=Object.entries(n.messages||{}).map(([e,a])=>[e,K(a,t)]);return Object.fromEntries(r)};var P=n=>{let t=decodeURIComponent(n).trim(),r=t.split(p.IdentifierParamSeparator),e=t.split("?")[0];return r.length===3&&(r[1]===p.IdentifierType.Alias||r[1]===p.IdentifierType.Hash)?{chainPrefix:r[0],type:r[1],identifier:r[2],identifierBase:r[2].split("?")[0]}:r.length===2&&(r[0]===p.IdentifierType.Alias||r[0]===p.IdentifierType.Hash)?{chainPrefix:p.IdentifierChainDefault,type:r[0],identifier:r[1],identifierBase:r[1].split("?")[0]}:r.length===2&&/^[a-zA-Z0-9]{62}$/.test(r[0])&&/^[a-zA-Z0-9]{2}$/.test(r[1])?null:r.length===2&&r[0]!==p.IdentifierType.Alias&&r[0]!==p.IdentifierType.Hash?{chainPrefix:r[0],type:p.IdentifierType.Alias,identifier:r[1],identifierBase:r[1].split("?")[0]}:e.length===64?{chainPrefix:p.IdentifierChainDefault,type:p.IdentifierType.Hash,identifier:t,identifierBase:e}:{chainPrefix:p.IdentifierChainDefault,type:p.IdentifierType.Alias,identifier:t,identifierBase:e}},L=n=>{let t=new URL(n),e=t.searchParams.get(p.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let a=decodeURIComponent(e);return P(a)};import lt from"qr-code-styling";var F=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!L(t):!1}build(t,r){let e=this.config.clientUrl||g.DefaultClientUrl(this.config.env),a=t===p.IdentifierType.Alias?encodeURIComponent(r):encodeURIComponent(t+p.IdentifierParamSeparator+r);return g.SuperClientUrls.includes(e)?`${e}/${a}`:`${e}?${p.IdentifierParamName}=${a}`}buildFromPrefixedIdentifier(t){let r=P(t);return r?this.build(r.type,r.identifierBase):""}generateQrCode(t,r,e=512,a="white",s="black",i="#23F7DD"){let o=this.build(t,r);return new lt({type:"svg",width:e,height:e,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},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(i)}" 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 ct="https://",nt=(n,t,r,e)=>{let a=t.actions?.[r]?.next||t.next||null;if(!a)return null;if(a.startsWith(ct))return[{identifier:null,url:a}];let[s,i]=a.split("?");if(!i)return[{identifier:s,url:J(s,n)}];let o=i.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(o.length===0){let f=K(i,{...t.vars,...e}),h=f?`${s}?${f}`:s;return[{identifier:h,url:J(h,n)}]}let l=o[0];if(!l)return[];let c=l.match(/{{([^[]+)\[\]/),u=c?c[1]:null;if(!u||e[u]===void 0)return[];let W=Array.isArray(e[u])?e[u]:[e[u]];if(W.length===0)return[];let d=o.filter(f=>f.includes(`{{${u}[]`)).map(f=>{let h=f.match(/\[\](\.[^}]+)?}}/),I=h&&h[1]||"";return{placeholder:f,field:I?I.slice(1):"",regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return W.map(f=>{let h=i;for(let{regex:m,field:y}of d){let T=y?ut(f,y):f;if(T==null)return null;h=h.replace(m,T)}if(h.includes("{{")||h.includes("}}"))return null;let I=h?`${s}?${h}`:s;return{identifier:I,url:J(I,n)}}).filter(f=>f!==null)},J=(n,t)=>{let[r,e]=n.split("?"),a=P(r)||{type:"alias",identifier:r,identifierBase:r},i=new F(t).build(a.type,a.identifierBase);if(!e)return i;let o=new URL(i);return new URLSearchParams(e).forEach((l,c)=>o.searchParams.set(c,l)),o.toString().replace(/\/\?/,"?")},ut=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);var B=class B{static info(...t){B.isTestEnv||console.info(...t)}static warn(...t){B.isTestEnv||console.warn(...t)}static error(...t){B.isTestEnv||console.error(...t)}};B.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var v=B;var R=class{nativeToString(t,r){return`${t}:${r?.toString()??""}`}stringToNative(t){let r=t.split(p.ArgParamsSeparator),e=r[0],a=r.slice(1).join(p.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[s,i]=a.split(p.ArgParamsSeparator);return[`option:${s}`,i||null]}else if(e==="optional"){let[s,i]=a.split(p.ArgParamsSeparator);return[`optional:${s}`,i||null]}else if(e==="list"){let s=a.split(p.ArgParamsSeparator),i=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`list:${i}`,c]}else if(e==="variadic"){let s=a.split(p.ArgParamsSeparator),i=s.slice(0,-1).join(p.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`variadic:${i}`,c]}else if(e.startsWith("composite")){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=a.split(p.ArgCompositeSeparator).map((l,c)=>this.stringToNative(`${s[c]}:${l}`)[1]);return[e,o]}else{if(e==="string")return[e,a];if(e==="uint8"||e==="uint16"||e==="uint32")return[e,Number(a)];if(e==="uint64"||e==="biguint")return[e,BigInt(a||0)];if(e==="bool")return[e,a==="true"];if(e==="address")return[e,a];if(e==="token")return[e,a];if(e==="hex")return[e,a];if(e==="codemeta")return[e,a];if(e==="esdt"){let[s,i,o]=a.split(p.ArgCompositeSeparator);return[e,`${s}|${i}|${o}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}};var at=async(n,t,r,e)=>{let a=[],s={};for(let[i,o]of Object.entries(n.results||{})){if(o.startsWith(p.Transform.Prefix))continue;let l=mt(o);if(l!==null&&l!==r){s[i]=null;continue}let[c,...u]=o.split("."),W=(d,C)=>C.reduce((f,h)=>f&&f[h]!==void 0?f[h]:null,d);if(c==="out"||c.startsWith("out[")){let d=u.length===0?t?.data||t:W(t,u);a.push(d),s[i]=d}else s[i]=o}return{values:a,results:await dt(n,s,r,e)}},dt=async(n,t,r,e)=>{if(!n.results)return t;let a={...t};return a=ft(a,n,r,e),a=await ht(n,a),a},ft=(n,t,r,e)=>{let a={...n},s=E(t,r)?.inputs||[],i=new R;for(let[o,l]of Object.entries(a))if(typeof l=="string"&&l.startsWith("input.")){let c=l.split(".")[1],u=s.findIndex(d=>d.as===c||d.name===c),W=u!==-1?e[u]?.value:null;a[o]=W?i.stringToNative(W)[1]:null}return a},ht=async(n,t)=>{if(!n.results)return t;let r={...t},e=Object.entries(n.results).filter(([,a])=>a.startsWith(p.Transform.Prefix)).map(([a,s])=>({key:a,code:s.substring(p.Transform.Prefix.length)}));for(let{key:a,code:s}of e)try{let i;typeof window>"u"?i=(await import("./runInVm-BFUZVHHD.mjs")).runInVm:i=(await import("./runInVm-5YQ766M3.mjs")).runInVm,r[a]=await i(s,r)}catch(i){v.error(`Transform error for result '${a}':`,i),r[a]=null}return r},mt=n=>{if(n==="out")return 1;let t=n.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};var gt=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Qt=n=>gt.find(t=>t.id===n)||null;var or=n=>`${A.String}:${n}`,pr=n=>`${A.U8}:${n}`,lr=n=>`${A.U16}:${n}`,cr=n=>`${A.U32}:${n}`,ur=n=>`${A.U64}:${n}`,dr=n=>`${A.Biguint}:${n}`,fr=n=>`${A.Boolean}:${n}`,hr=n=>`${A.Address}:${n}`,mr=n=>`${A.Hex}:${n}`;import Wt from"ajv";var it=class{constructor(t){this.pendingBrand={protocol:H("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,a=await(await fetch(r)).json(),s=new Wt,i=s.compile(a);if(!i(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(i.errors)}`)}};import yt from"ajv";var k=class{constructor(t){this.config=t;this.config=t}async validate(t){let r=[];return r.push(...this.validateMaxOneValuePosition(t)),r.push(...this.validateVariableNamesAndResultNamesUppercase(t)),r.push(...this.validateAbiIsSetIfApplicable(t)),r.push(...await this.validateSchema(t)),{valid:r.length===0,errors:r}}validateMaxOneValuePosition(t){return t.actions.filter(e=>e.inputs?e.inputs.some(a=>a.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(a,s)=>{a&&Object.keys(a).forEach(i=>{i!==i.toUpperCase()&&r.push(`${s} name '${i}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.results,"Result"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(i=>i.type==="contract"),e=t.actions.some(i=>i.type==="query");if(!r&&!e)return[];let a=t.actions.some(i=>i.abi),s=Object.values(t.results||{}).some(i=>i.startsWith("out.")||i.startsWith("event."));return t.results&&!a&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||g.LatestWarpSchemaUrl,a=await(await fetch(r)).json(),s=new yt({strict:!1}),i=s.compile(a);return i(t)?[]:[`Schema validation failed: ${s.errorsText(i.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var M=class{constructor(t){this.config=t;this.pendingWarp={protocol:H("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 k(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
2
+ `))}};var O=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 a={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(a))}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 b=class b{get(t){let r=b.cache.get(t);return r?Date.now()>r.expiresAt?(b.cache.delete(t),null):r.value:null}set(t,r,e){let a=Date.now()+e*1e3;b.cache.set(t,{value:r,expiresAt:a})}forget(t){b.cache.delete(t)}clear(){b.cache.clear()}};b.cache=new Map;var D=b;var Q={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},st={Warp:(n,t)=>`warp:${n}:${t}`,WarpAbi:(n,t)=>`warp-abi:${n}:${t}`,WarpExecutable:(n,t,r)=>`warp-exec:${n}:${t}:${r}`,RegistryInfo:(n,t)=>`registry-info:${n}:${t}`,Brand:(n,t)=>`brand:${n}:${t}`,ChainInfo:(n,t)=>`chain:${n}:${t}`,ChainInfos:n=>`chains:${n}`},G=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new O:t==="memory"?new D:typeof window<"u"&&window.localStorage?new O:new D}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 $=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 a=E(t,r);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),l=o.find(w=>w.input.position==="receiver")?.value,c="address"in a?a.address:null,u=l?.split(":")[1]||c;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let W=u,d=this.getPreparedArgs(a,o),C=o.find(w=>w.input.position==="value")?.value||null,f="value"in a?a.value:null,h=BigInt(C?.split(":")[1]||f||0),I=o.filter(w=>w.input.position==="transfer"&&w.value).map(w=>w.value),y=[...("transfers"in a?a.transfers:[])||[],...I||[]],T=o.find(w=>w.input.position==="data")?.value,U="data"in a?a.data||"":null,X={warp:t,chain:s,action:r,destination:W,args:d,value:h,transfers:y,data:T||U||null,resolvedInputs:o};return this.cache.set(st.WarpExecutable(this.config.env,t.meta?.hash||"",r),X.resolvedInputs,Q.OneWeek),X}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 a=r.inputs||[],s=await Promise.all(e.map(o=>this.preprocessInput(t,o))),i=(o,l)=>{if(o.source==="query"){let c=this.url.searchParams.get(o.name);return c?this.serializer.nativeToString(o.type,c):null}else return o.source===p.Source.UserWallet?this.config.user?.wallets?.[t.name]?this.serializer.nativeToString("address",this.config.user.wallets[t.name]):null:s[l]||null};return a.map((o,l)=>{let c=i(o,l);return{input:o,value:c||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(t){return t.map((r,e)=>{if(r.input.modifier?.startsWith("scale:")){let[,a]=r.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(t.find(l=>l.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let i=r.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let o=z(i,+s);return{...r,value:`${r.input.type}:${o}`}}else{let s=r.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let i=z(s,+a);return{...r,value:`${r.input.type}:${i}`}}}else return r})}async preprocessInput(t,r){try{let[e,a]=r.split(p.ArgParamsSeparator,2);return x(t.name,this.adapters).executor.preprocessInput(t,r,e,a)}catch{return r}}getPreparedArgs(t,r){let e="args"in t?t.args||[]:[];return r.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(t,r){let e=t.inputs?.findIndex(c=>c.position==="chain");if(e===-1||e===void 0)return null;let a=r[e];if(!a)throw new Error("WarpUtils: Chain input not found");let i=new R().stringToNative(a)[1],l=await x(i,this.adapters).registry.getChainInfo(i);if(!l)throw new Error(`WarpUtils: Chain info not found for ${i}`);return l}async getDefaultChainInfo(t){if(!t.chain)return V(this.config);let e=await Z(this.adapters).registry.getChainInfo(t.chain,{ttl:Q.OneWeek});if(!e)throw new Error(`WarpUtils: Chain info not found for ${t.chain}`);return e}};var N=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 a=>await this.applyActionGlobals(a))),e=await this.applyRootGlobals(e,t),e}applyVars(t,r){if(!r?.vars)return r;let e=JSON.stringify(r),a=(s,i)=>{e=e.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),i.toString())};return Object.entries(r.vars).forEach(([s,i])=>{if(typeof i!="string")a(s,i);else if(i.startsWith(`${p.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=i.split(`${p.Vars.Query}:`)[1],l=new URLSearchParams(t.currentUrl.split("?")[1]).get(o);l&&a(s,l)}else if(i.startsWith(`${p.Vars.Env}:`)){let o=i.split(`${p.Vars.Env}:`)[1],l=t.vars?.[o];l&&a(s,l)}else if(i===p.Source.UserWallet&&t.user?.wallets?.[this.adapter.chain]){let o=t.user.wallets[this.adapter.chain];o&&a(s,o)}else a(s,i)}),JSON.parse(e)}async applyRootGlobals(t,r){let e=JSON.stringify(t),a={config:r,chain:V(r)};return Object.values(p.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}async applyActionGlobals(t){let r=t.chain?await this.adapter.registry.getChainInfo(t.chain):V(this.config);if(!r)throw new Error(`Chain info not found for ${t.chain}`);let e=JSON.stringify(t),a={config:this.config,chain:r};return Object.values(p.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}};var j=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.factory=new $(t,r),this.handlers=e}async execute(t,r){let[e,a]=tt(t);if(e.type==="collect"){let c=await this.executeCollect(t,a,r);return this.handlers?.onExecuted?.(c),{tx:null,chain:null}}let s=await this.factory.createExecutable(t,a,r),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(t,r,e){let a=this.adapters.find(i=>i.chain.toLowerCase()===r.name.toLowerCase());if(!a)throw new Error(`No adapter registered for chain: ${r.name}`);let s=await a.results.getTransactionExecutionResults(t,e);this.handlers?.onExecuted?.(s)}async executeCollect(t,r,e,a){let s=E(t,r);if(!s)throw new Error("WarpActionExecutor: Action not found");let i=await this.factory.getChainInfoForAction(s),o=x(i.name,this.adapters),l=await new N(this.config,o).apply(this.config,t),c=await this.factory.getResolvedInputs(i,s,e),u=this.factory.getModifiedInputs(c),W=this.factory.serializer,d=m=>{if(!m.value)return null;let y=W.stringToNative(m.value)[1];return m.input.type==="biguint"?y.toString():m.input.type==="esdt"?{}:y},C=new Headers;C.set("Content-Type","application/json"),C.set("Accept","application/json"),Object.entries(s.destination.headers||{}).forEach(([m,y])=>{C.set(m,y)});let f=Object.fromEntries(u.map(m=>[m.input.as||m.input.name,d(m)])),h=s.destination.method||"GET",I=h==="GET"?void 0:JSON.stringify({...f,...a});v.info("Executing collect",{url:s.destination.url,method:h,headers:C,body:I});try{let m=await fetch(s.destination.url,{method:h,headers:C,body:I}),y=await m.json(),{values:T,results:U}=await at(l,y,r,u),_=nt(this.config,l,r,U);return{success:m.ok,warp:l,action:r,user:this.config.user?.wallets?.[i.name]||null,txHash:null,next:_,values:T,results:{...U,_DATA:y},messages:et(l,U)}}catch(m){return v.error("WarpActionExecutor: Error executing collect",m),{success:!1,warp:l,action:r,user:this.config.user?.wallets?.[i.name]||null,txHash:null,next:null,values:[],results:{_DATA:m},messages:{}}}}};var q=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!L(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let a=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),i=(await Promise.all(a)).filter(c=>c.match),o=i.length>0,l=i.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:l}}async detect(t,r){let e={match:!1,url:t,warp:null,registryInfo:null,brand:null},a=t.startsWith(p.HttpProtocolPrefix)?L(t):P(t);if(!a)return e;try{let{type:s,identifierBase:i}=a,o=null,l=null,c=null,u=Y(a.chainPrefix,this.adapters);if(s==="hash"){o=await u.builder.createFromTransactionHash(i,r);let d=await u.registry.getInfoByHash(i,r);l=d.registryInfo,c=d.brand}else if(s==="alias"){let d=await u.registry.getInfoByAlias(i,r);l=d.registryInfo,c=d.brand,d.registryInfo&&(o=await u.builder.createFromTransactionHash(d.registryInfo.hash,r))}let W=o?await new N(this.config,u).apply(this.config,o):null;return W?{match:!0,url:t,warp:W,registryInfo:l,brand:c}:e}catch(s){return v.error("Error detecting warp link",s),e}}};var ot=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}setConfig(t){return this.config=t,this}addAdapter(t){return this.adapters.push(t),this}createBuilder(){return new M(this.config)}createExecutor(t){return new j(this.config,this.adapters,t)}async detectWarp(t,r){return new q(this.config,this.adapters).detect(t,r)}async executeWarp(t,r,e,a={}){let s=await this.detectWarp(t,a.cache);if(!s.match||!s.warp)throw new Error("Warp not found");let i=this.createExecutor(e),{tx:o,chain:l}=await i.execute(s.warp,r);return{tx:o,chain:l,evaluateResults:async u=>{if(!l||!o||!s.warp)throw new Error("Warp not found");await i.evaluateResults(s.warp,l,u)}}}createInscriptionTransaction(t,r){return x(t,this.adapters).builder.createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return x(t,this.adapters).builder.createFromTransaction(r,e)}async createFromTransactionHash(t,r,e){return x(t,this.adapters).builder.createFromTransactionHash(r,e)}getExplorer(t){return x(t.name,this.adapters).explorer(t)}getResults(t){return x(t.name,this.adapters).results}getRegistry(t){return x(t,this.adapters).registry}get factory(){return new $(this.config,this.adapters)}};var pt=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 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"]:t,...r})});if(!a.ok)throw new Error(`WarpIndex: search failed with status ${a.status}`);return(await a.json()).hits}catch(a){throw v.error("WarpIndex: Error searching for warps: ",a),a}}};export{Q as CacheTtl,gt as KnownTokens,it as WarpBrandBuilder,M as WarpBuilder,G as WarpCache,st as WarpCacheKey,ot as WarpClient,g as WarpConfig,p as WarpConstants,j as WarpExecutor,$ as WarpFactory,pt as WarpIndex,A as WarpInputTypes,N as WarpInterpolator,F as WarpLinkBuilder,q as WarpLinkDetecter,v as WarpLogger,S as WarpProtocolVersions,R as WarpSerializer,k as WarpValidator,hr as address,et as applyResultsToMessages,dr as biguint,fr as boolean,dt as evaluateResultsCommon,at as extractCollectResults,L as extractIdentifierInfoFromUrl,Qt as findKnownTokenById,Y as findWarpAdapterByPrefix,x as findWarpAdapterForChain,Z as findWarpDefaultAdapter,tt as findWarpExecutableAction,H as getLatestProtocolIdentifier,V as getMainChainInfo,nt as getNextInfo,E as getWarpActionByIndex,P as getWarpInfoFromIdentifier,mr as hex,mt as parseResultsOutIndex,K as replacePlaceholders,z as shiftBigintBy,or as string,rt as toPreviewText,wt as toTypedChainInfo,lr as u16,cr as u32,ur as u64,pr as u8};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "3.0.0-alpha.46",
3
+ "version": "3.0.0-alpha.48",
4
4
  "description": "",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",