@vleap/warps 3.0.0-alpha.59 → 3.0.0-alpha.60

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.
@@ -0,0 +1 @@
1
+ import{randomBytes as o}from"crypto";function c(r,e,t=5){let n=o(32).toString("hex"),s=new Date(Date.now()+t*60*1e3).toISOString();return{message:JSON.stringify({wallet:r,nonce:n,expiresAt:s,purpose:e}),nonce:n,expiresAt:s}}function l(r,e,t){let n=t||`prove-wallet-ownership for app "${e}"`;return c(r,n,5)}function p(r,e,t,n){return{"X-Signer-Wallet":r,"X-Signer-Signature":e,"X-Signer-Nonce":t,"X-Signer-ExpiresAt":n}}async function m(r,e,t){let{createAuthMessage:n}=await Promise.resolve().then(()=>require_signing()),{message:s,nonce:i,expiresAt:g}=n(r,t),a=await e(s);return p(r,a,i,g)}function S(r){let e=new Date(r).getTime();return Date.now()<e}function x(r){try{let e=JSON.parse(r);if(!e.wallet||!e.nonce||!e.expiresAt||!e.purpose)throw new Error("Invalid signed message: missing required fields");return e}catch(e){throw new Error(`Failed to parse signed message: ${e instanceof Error?e.message:"Unknown error"}`)}}export{c as a,l as b,p as c,m as d,S as e,x as f};
package/dist/index.d.mts CHANGED
@@ -257,6 +257,7 @@ type WarpClientConfig = {
257
257
  type WarpCacheConfig = {
258
258
  ttl?: number;
259
259
  };
260
+ type AdapterFactory = (config: WarpClientConfig, fallback?: Adapter) => Adapter;
260
261
  type Adapter = {
261
262
  chain: WarpChain;
262
263
  prefix: string;
@@ -301,6 +302,7 @@ interface AdapterWarpBrandBuilder {
301
302
  interface AdapterWarpExecutor {
302
303
  createTransaction(executable: WarpExecutable): Promise<WarpAdapterGenericTransaction>;
303
304
  preprocessInput(chain: WarpChainInfo, input: string, type: WarpActionInputType, value: string): Promise<string>;
305
+ signMessage(message: string, privateKey: string): Promise<string>;
304
306
  }
305
307
  interface AdapterWarpResults {
306
308
  getTransactionExecutionResults(warp: Warp, tx: WarpAdapterGenericRemoteTransaction): Promise<WarpExecution>;
@@ -391,7 +393,8 @@ declare const WarpConfig: {
391
393
 
392
394
  declare enum WarpChainName {
393
395
  Multiversx = "multiversx",
394
- Sui = "sui"
396
+ Sui = "sui",
397
+ Evm = "evm"
395
398
  }
396
399
  declare const WarpConstants: {
397
400
  HttpProtocolPrefix: string;
@@ -493,6 +496,53 @@ declare const evaluateResultsCommon: (warp: Warp, baseResults: WarpExecutionResu
493
496
  */
494
497
  declare const parseResultsOutIndex: (resultPath: string) => number | null;
495
498
 
499
+ interface SignableMessage {
500
+ wallet: string;
501
+ nonce: string;
502
+ expiresAt: string;
503
+ purpose: string;
504
+ }
505
+ type HttpAuthHeaders = Record<string, string> & {
506
+ 'X-Signer-Wallet': string;
507
+ 'X-Signer-Signature': string;
508
+ 'X-Signer-Nonce': string;
509
+ 'X-Signer-ExpiresAt': string;
510
+ };
511
+ /**
512
+ * Creates a signable message with standard security fields
513
+ * This can be used for any type of proof or authentication
514
+ */
515
+ declare function createSignableMessage(walletAddress: string, purpose: string, expiresInMinutes?: number): {
516
+ message: string;
517
+ nonce: string;
518
+ expiresAt: string;
519
+ };
520
+ /**
521
+ * Creates a signable message for HTTP authentication
522
+ * This is a convenience function that uses the standard format
523
+ */
524
+ declare function createAuthMessage(walletAddress: string, appName: string, purpose?: string): {
525
+ message: string;
526
+ nonce: string;
527
+ expiresAt: string;
528
+ };
529
+ /**
530
+ * Creates HTTP authentication headers from a signature
531
+ */
532
+ declare function createAuthHeaders(walletAddress: string, signature: string, nonce: string, expiresAt: string): HttpAuthHeaders;
533
+ /**
534
+ * Creates HTTP authentication headers for a wallet using the provided signing function
535
+ */
536
+ declare function createHttpAuthHeaders(walletAddress: string, signMessage: (message: string) => Promise<string>, appName: string): Promise<HttpAuthHeaders>;
537
+ /**
538
+ * Validates a signed message by checking expiration
539
+ */
540
+ declare function validateSignedMessage(expiresAt: string): boolean;
541
+ /**
542
+ * Parses a signed message to extract its components
543
+ */
544
+ declare function parseSignedMessage(message: string): SignableMessage;
545
+
496
546
  type KnownToken = {
497
547
  id: string;
498
548
  name: string;
@@ -576,12 +626,17 @@ type ExecutionHandlers = {
576
626
  onError?: (params: {
577
627
  message: string;
578
628
  }) => void;
629
+ onSignRequest?: (params: {
630
+ message: string;
631
+ chain: WarpChainInfo;
632
+ }) => Promise<string>;
579
633
  };
580
634
  declare class WarpExecutor {
581
635
  private config;
582
636
  private adapters;
583
637
  private handlers?;
584
638
  private factory;
639
+ private serializer;
585
640
  constructor(config: WarpClientConfig, adapters: Adapter[], handlers?: ExecutionHandlers | undefined);
586
641
  execute(warp: Warp, inputs: string[]): Promise<{
587
642
  tx: WarpAdapterGenericTransaction | null;
@@ -668,6 +723,7 @@ declare class WarpClient {
668
723
  createInscriptionTransaction(chain: WarpChain, warp: Warp): WarpAdapterGenericTransaction;
669
724
  createFromTransaction(chain: WarpChain, tx: WarpAdapterGenericRemoteTransaction, validate?: boolean): Promise<Warp>;
670
725
  createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
726
+ signMessage(chain: WarpChain, message: string, privateKey: string): Promise<string>;
671
727
  getExplorer(chain: WarpChainInfo): AdapterWarpExplorer;
672
728
  getResults(chain: WarpChainInfo): AdapterWarpResults;
673
729
  getRegistry(chain: WarpChain): Promise<AdapterWarpRegistry>;
@@ -717,4 +773,4 @@ declare class WarpValidator {
717
773
  private validateSchema;
718
774
  }
719
775
 
720
- export { type Adapter, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, type BaseWarpBuilder, CacheTtl, type CombinedWarpBuilder, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type InterpolationBag, type KnownToken, KnownTokens, type ProtocolName, type ResolvedInput, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandMeta, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainEnv, type WarpChainInfo, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpExecutable, type WarpExecution, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, WarpFactory, type WarpIdType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, WarpSerializer, type WarpTransferAction, type WarpTrustStatus, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, biguint, boolean, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById, findWarpAdapterByPrefix, findWarpAdapterForChain, findWarpDefaultAdapter, findWarpExecutableAction, getLatestProtocolIdentifier, getMainChainInfo, getNextInfo, getWarpActionByIndex, getWarpInfoFromIdentifier, hex, parseResultsOutIndex, replacePlaceholders, shiftBigintBy, string, toPreviewText, toTypedChainInfo, u16, u32, u64, u8 };
776
+ export { type Adapter, type AdapterFactory, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, type BaseWarpBuilder, CacheTtl, type CombinedWarpBuilder, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, type KnownToken, KnownTokens, type ProtocolName, type ResolvedInput, type SignableMessage, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandMeta, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainEnv, type WarpChainInfo, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpExecutable, type WarpExecution, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, WarpFactory, type WarpIdType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, WarpSerializer, type WarpTransferAction, type WarpTrustStatus, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, biguint, boolean, createAuthHeaders, createAuthMessage, createHttpAuthHeaders, createSignableMessage, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById, findWarpAdapterByPrefix, findWarpAdapterForChain, findWarpDefaultAdapter, findWarpExecutableAction, getLatestProtocolIdentifier, getMainChainInfo, getNextInfo, getWarpActionByIndex, getWarpInfoFromIdentifier, hex, parseResultsOutIndex, parseSignedMessage, replacePlaceholders, shiftBigintBy, string, toPreviewText, toTypedChainInfo, u16, u32, u64, u8, validateSignedMessage };
package/dist/index.d.ts CHANGED
@@ -257,6 +257,7 @@ type WarpClientConfig = {
257
257
  type WarpCacheConfig = {
258
258
  ttl?: number;
259
259
  };
260
+ type AdapterFactory = (config: WarpClientConfig, fallback?: Adapter) => Adapter;
260
261
  type Adapter = {
261
262
  chain: WarpChain;
262
263
  prefix: string;
@@ -301,6 +302,7 @@ interface AdapterWarpBrandBuilder {
301
302
  interface AdapterWarpExecutor {
302
303
  createTransaction(executable: WarpExecutable): Promise<WarpAdapterGenericTransaction>;
303
304
  preprocessInput(chain: WarpChainInfo, input: string, type: WarpActionInputType, value: string): Promise<string>;
305
+ signMessage(message: string, privateKey: string): Promise<string>;
304
306
  }
305
307
  interface AdapterWarpResults {
306
308
  getTransactionExecutionResults(warp: Warp, tx: WarpAdapterGenericRemoteTransaction): Promise<WarpExecution>;
@@ -391,7 +393,8 @@ declare const WarpConfig: {
391
393
 
392
394
  declare enum WarpChainName {
393
395
  Multiversx = "multiversx",
394
- Sui = "sui"
396
+ Sui = "sui",
397
+ Evm = "evm"
395
398
  }
396
399
  declare const WarpConstants: {
397
400
  HttpProtocolPrefix: string;
@@ -493,6 +496,53 @@ declare const evaluateResultsCommon: (warp: Warp, baseResults: WarpExecutionResu
493
496
  */
494
497
  declare const parseResultsOutIndex: (resultPath: string) => number | null;
495
498
 
499
+ interface SignableMessage {
500
+ wallet: string;
501
+ nonce: string;
502
+ expiresAt: string;
503
+ purpose: string;
504
+ }
505
+ type HttpAuthHeaders = Record<string, string> & {
506
+ 'X-Signer-Wallet': string;
507
+ 'X-Signer-Signature': string;
508
+ 'X-Signer-Nonce': string;
509
+ 'X-Signer-ExpiresAt': string;
510
+ };
511
+ /**
512
+ * Creates a signable message with standard security fields
513
+ * This can be used for any type of proof or authentication
514
+ */
515
+ declare function createSignableMessage(walletAddress: string, purpose: string, expiresInMinutes?: number): {
516
+ message: string;
517
+ nonce: string;
518
+ expiresAt: string;
519
+ };
520
+ /**
521
+ * Creates a signable message for HTTP authentication
522
+ * This is a convenience function that uses the standard format
523
+ */
524
+ declare function createAuthMessage(walletAddress: string, appName: string, purpose?: string): {
525
+ message: string;
526
+ nonce: string;
527
+ expiresAt: string;
528
+ };
529
+ /**
530
+ * Creates HTTP authentication headers from a signature
531
+ */
532
+ declare function createAuthHeaders(walletAddress: string, signature: string, nonce: string, expiresAt: string): HttpAuthHeaders;
533
+ /**
534
+ * Creates HTTP authentication headers for a wallet using the provided signing function
535
+ */
536
+ declare function createHttpAuthHeaders(walletAddress: string, signMessage: (message: string) => Promise<string>, appName: string): Promise<HttpAuthHeaders>;
537
+ /**
538
+ * Validates a signed message by checking expiration
539
+ */
540
+ declare function validateSignedMessage(expiresAt: string): boolean;
541
+ /**
542
+ * Parses a signed message to extract its components
543
+ */
544
+ declare function parseSignedMessage(message: string): SignableMessage;
545
+
496
546
  type KnownToken = {
497
547
  id: string;
498
548
  name: string;
@@ -576,12 +626,17 @@ type ExecutionHandlers = {
576
626
  onError?: (params: {
577
627
  message: string;
578
628
  }) => void;
629
+ onSignRequest?: (params: {
630
+ message: string;
631
+ chain: WarpChainInfo;
632
+ }) => Promise<string>;
579
633
  };
580
634
  declare class WarpExecutor {
581
635
  private config;
582
636
  private adapters;
583
637
  private handlers?;
584
638
  private factory;
639
+ private serializer;
585
640
  constructor(config: WarpClientConfig, adapters: Adapter[], handlers?: ExecutionHandlers | undefined);
586
641
  execute(warp: Warp, inputs: string[]): Promise<{
587
642
  tx: WarpAdapterGenericTransaction | null;
@@ -668,6 +723,7 @@ declare class WarpClient {
668
723
  createInscriptionTransaction(chain: WarpChain, warp: Warp): WarpAdapterGenericTransaction;
669
724
  createFromTransaction(chain: WarpChain, tx: WarpAdapterGenericRemoteTransaction, validate?: boolean): Promise<Warp>;
670
725
  createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
726
+ signMessage(chain: WarpChain, message: string, privateKey: string): Promise<string>;
671
727
  getExplorer(chain: WarpChainInfo): AdapterWarpExplorer;
672
728
  getResults(chain: WarpChainInfo): AdapterWarpResults;
673
729
  getRegistry(chain: WarpChain): Promise<AdapterWarpRegistry>;
@@ -717,4 +773,4 @@ declare class WarpValidator {
717
773
  private validateSchema;
718
774
  }
719
775
 
720
- export { type Adapter, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, type BaseWarpBuilder, CacheTtl, type CombinedWarpBuilder, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type InterpolationBag, type KnownToken, KnownTokens, type ProtocolName, type ResolvedInput, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandMeta, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainEnv, type WarpChainInfo, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpExecutable, type WarpExecution, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, WarpFactory, type WarpIdType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, WarpSerializer, type WarpTransferAction, type WarpTrustStatus, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, biguint, boolean, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById, findWarpAdapterByPrefix, findWarpAdapterForChain, findWarpDefaultAdapter, findWarpExecutableAction, getLatestProtocolIdentifier, getMainChainInfo, getNextInfo, getWarpActionByIndex, getWarpInfoFromIdentifier, hex, parseResultsOutIndex, replacePlaceholders, shiftBigintBy, string, toPreviewText, toTypedChainInfo, u16, u32, u64, u8 };
776
+ export { type Adapter, type AdapterFactory, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpRegistry, type AdapterWarpResults, type AdapterWarpSerializer, type BaseWarpActionInputType, type BaseWarpBuilder, CacheTtl, type CombinedWarpBuilder, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, type KnownToken, KnownTokens, type ProtocolName, type ResolvedInput, type SignableMessage, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandMeta, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainEnv, type WarpChainInfo, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpExecutable, type WarpExecution, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionResults, WarpExecutor, WarpFactory, type WarpIdType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, WarpSerializer, type WarpTransferAction, type WarpTrustStatus, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, address, applyResultsToMessages, biguint, boolean, createAuthHeaders, createAuthMessage, createHttpAuthHeaders, createSignableMessage, evaluateResultsCommon, extractCollectResults, extractIdentifierInfoFromUrl, findKnownTokenById, findWarpAdapterByPrefix, findWarpAdapterForChain, findWarpDefaultAdapter, findWarpExecutableAction, getLatestProtocolIdentifier, getMainChainInfo, getNextInfo, getWarpActionByIndex, getWarpInfoFromIdentifier, hex, parseResultsOutIndex, parseSignedMessage, replacePlaceholders, shiftBigintBy, string, toPreviewText, toTypedChainInfo, u16, u32, u64, u8, validateSignedMessage };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Er=Object.create;var J=Object.defineProperty;var Tr=Object.getOwnPropertyDescriptor;var Pr=Object.getOwnPropertyNames;var Rr=Object.getPrototypeOf,Sr=Object.prototype.hasOwnProperty;var dr=(n,r)=>()=>(n&&(r=n(n=0)),r);var X=(n,r)=>{for(var t in r)J(n,t,{get:r[t],enumerable:!0})},fr=(n,r,t,e)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of Pr(r))!Sr.call(n,a)&&a!==t&&J(n,a,{get:()=>r[a],enumerable:!(e=Tr(r,a))||e.enumerable});return n};var Z=(n,r,t)=>(t=n!=null?Er(Rr(n)):{},fr(r||!n||!n.__esModule?J(t,"default",{value:n,enumerable:!0}):t,n)),Br=n=>fr(J({},"__esModule",{value:!0}),n);var Wr={};X(Wr,{runInVm:()=>Or});var Vr,Or,yr=dr(()=>{"use strict";Vr=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')}),Or=async(n,r)=>{let t;try{t=Vr("vm2").VM}catch{throw new Error('The optional dependency "vm2" is not installed. To use runInVm in Node.js, please install vm2: npm install vm2 --save.')}let e=new t({timeout:2e3,sandbox:{result:r},eval:!1,wasm:!1});return n.trim().startsWith("(")&&n.includes("=>")?e.run(`(${n})(result)`):null}});var xr={};X(xr,{runInVm:()=>Dr});var Dr,vr=dr(()=>{"use strict";Dr=async(n,r)=>new Promise((t,e)=>{try{let a=new Blob([`
1
+ "use strict";var Lr=Object.create;var Q=Object.defineProperty;var Vr=Object.getOwnPropertyDescriptor;var Or=Object.getOwnPropertyNames;var Hr=Object.getPrototypeOf,Mr=Object.prototype.hasOwnProperty;var tr=(n,r)=>()=>(n&&(r=n(n=0)),r);var X=(n,r)=>{for(var e in r)Q(n,e,{get:r[e],enumerable:!0})},Wr=(n,r,e,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of Or(r))!Mr.call(n,a)&&a!==e&&Q(n,a,{get:()=>r[a],enumerable:!(t=Vr(r,a))||t.enumerable});return n};var nr=(n,r,e)=>(e=n!=null?Lr(Hr(n)):{},Wr(r||!n||!n.__esModule?Q(e,"default",{value:n,enumerable:!0}):e,n)),Dr=n=>Wr(Q({},"__esModule",{value:!0}),n);var Cr={};X(Cr,{runInVm:()=>zr});var Gr,zr,wr=tr(()=>{"use strict";Gr=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(r,e)=>(typeof require<"u"?require:r)[e]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')}),zr=async(n,r)=>{let e;try{e=Gr("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 t=new e({timeout:2e3,sandbox:{result:r},eval:!1,wasm:!1});return n.trim().startsWith("(")&&n.includes("=>")?t.run(`(${n})(result)`):null}});var Ir={};X(Ir,{runInVm:()=>Jr});var Jr,Ar=tr(()=>{"use strict";Jr=async(n,r)=>new Promise((e,t)=>{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 Xr={};X(Xr,{CacheTtl:()=>_,KnownTokens:()=>wr,WarpBrandBuilder:()=>sr,WarpBuilder:()=>or,WarpCache:()=>j,WarpCacheKey:()=>pr,WarpChainName:()=>hr,WarpClient:()=>lr,WarpConfig:()=>m,WarpConstants:()=>l,WarpExecutor:()=>q,WarpFactory:()=>U,WarpIndex:()=>G,WarpInputTypes:()=>I,WarpInterpolator:()=>N,WarpLinkBuilder:()=>$,WarpLinkDetecter:()=>z,WarpLogger:()=>x,WarpProtocolVersions:()=>S,WarpSerializer:()=>P,WarpValidator:()=>k,address:()=>Qr,applyResultsToMessages:()=>er,biguint:()=>Jr,boolean:()=>Kr,evaluateResultsCommon:()=>Cr,extractCollectResults:()=>ir,extractIdentifierInfoFromUrl:()=>O,findKnownTokenById:()=>Hr,findWarpAdapterByPrefix:()=>B,findWarpAdapterForChain:()=>W,findWarpDefaultAdapter:()=>Y,findWarpExecutableAction:()=>rr,getLatestProtocolIdentifier:()=>F,getMainChainInfo:()=>V,getNextInfo:()=>ar,getWarpActionByIndex:()=>T,getWarpInfoFromIdentifier:()=>A,hex:()=>_r,parseResultsOutIndex:()=>Ir,replacePlaceholders:()=>Q,shiftBigintBy:()=>K,string:()=>Mr,toPreviewText:()=>tr,toTypedChainInfo:()=>$r,u16:()=>qr,u32:()=>Gr,u64:()=>zr,u8:()=>jr});module.exports=Br(Xr);var hr=(t=>(t.Multiversx="multiversx",t.Sui="sui",t))(hr||{}),l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:[":","."],IdentifierParamSeparatorDefault:".",IdentifierChainDefault:"mvx",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.chain.name]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:n=>n.chain.explorerUrl},ChainAddressHrp:{Placeholder:"chain.addressHrp",Accessor:n=>n.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},I={Option:"option",Optional:"optional",List:"list",Variadic:"variadic",Composite:"composite",String:"string",U8:"u8",U16:"u16",U32:"u32",U64:"u64",Biguint:"biguint",Boolean:"boolean",Address:"address",Hex:"hex"};var S={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},m={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${S.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${S.Brand}.schema.json`,DefaultClientUrl:n=>n==="devnet"?"https://devnet.usewarp.to":n==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],MainChain:{Name:"multiversx",DisplayName:"MultiversX",ApiUrl:n=>n==="devnet"?"https://devnet-api.multiversx.com":n==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:n=>n==="devnet"?"https://devnet-explorer.multiversx.com":n==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:n=>6e3,AddressHrp:"erd",ChainId:n=>n==="devnet"?"D":n==="testnet"?"T":"1",NativeToken:"EGLD"},AvailableActionInputSources:["field","query",l.Source.UserWallet],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var Y=n=>{let r=n.find(t=>t.chain.toLowerCase()===m.MainChain.Name.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${m.MainChain.Name}`);return r},W=(n,r)=>{let t=r.find(e=>e.chain.toLowerCase()===n.toLowerCase());if(!t)throw new Error(`Adapter not found for chain: ${n}`);return t},B=(n,r)=>{let t=r.find(e=>e.prefix.toLowerCase()===n.toLowerCase());if(!t)throw new Error(`Adapter not found for prefix: ${n}`);return t},V=n=>({name:m.MainChain.Name,displayName:m.MainChain.DisplayName,chainId:m.MainChain.ChainId(n.env),blockTime:m.MainChain.BlockTime(n.env),addressHrp:m.MainChain.AddressHrp,apiUrl:m.MainChain.ApiUrl(n.env),explorerUrl:m.MainChain.ExplorerUrl(n.env),nativeToken:m.MainChain.NativeToken}),F=n=>{if(n==="warp")return`warp:${S.Warp}`;if(n==="brand")return`brand:${S.Brand}`;if(n==="abi")return`abi:${S.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},T=(n,r)=>n?.actions[r-1],rr=n=>(n.actions.forEach((r,t)=>{if(r.type!=="link")return{action:r,actionIndex:t}}),{action:T(n,1),actionIndex:1}),$r=n=>({name:n.name.toString(),displayName:n.display_name.toString(),chainId:n.chain_id.toString(),blockTime:n.block_time.toNumber(),addressHrp:n.address_hrp.toString(),apiUrl:n.api_url.toString(),explorerUrl:n.explorer_url.toString(),nativeToken:n.native_token.toString()}),K=(n,r)=>{let t=n.toString(),[e,a=""]=t.split("."),s=Math.abs(r);if(r>0)return BigInt(e+a.padEnd(s,"0"));if(r<0){let i=e+a;if(s>=i.length)return 0n;let o=i.slice(0,-s)||"0";return BigInt(o)}else return t.includes(".")?BigInt(t.split(".")[0]):BigInt(t)},tr=(n,r=100)=>{if(!n)return"";let t=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return t=t.startsWith("- ")?t.slice(2):t,t=t.length>r?t.substring(0,t.lastIndexOf(" ",r))+"...":t,t},Q=(n,r)=>n.replace(/\{\{([^}]+)\}\}/g,(t,e)=>r[e]||""),er=(n,r)=>{let t=Object.entries(n.messages||{}).map(([e,a])=>[e,Q(a,r)]);return Object.fromEntries(t)};var Ur=n=>{let r=l.IdentifierParamSeparator,t=-1,e="";for(let a of r){let s=n.indexOf(a);s!==-1&&(t===-1||s<t)&&(t=s,e=a)}return t!==-1?{separator:e,index:t}:null},mr=n=>{let r=Ur(n);if(!r)return[n];let{separator:t,index:e}=r,a=n.substring(0,e),s=n.substring(e+t.length),i=mr(s);return[a,...i]},A=n=>{let r=decodeURIComponent(n).trim(),t=r.split("?")[0],e=mr(t);if(t.length===64&&/^[a-fA-F0-9]+$/.test(t))return{chainPrefix:l.IdentifierChainDefault,type:l.IdentifierType.Hash,identifier:r,identifierBase:t};if(e.length===2&&/^[a-zA-Z0-9]{62}$/.test(e[0])&&/^[a-zA-Z0-9]{2}$/.test(e[1]))return null;if(e.length===3){let[a,s,i]=e;if(s===l.IdentifierType.Alias||s===l.IdentifierType.Hash){let o=r.includes("?")?i+r.substring(r.indexOf("?")):i;return{chainPrefix:a,type:s,identifier:o,identifierBase:i}}}if(e.length===2){let[a,s]=e;if(a===l.IdentifierType.Alias||a===l.IdentifierType.Hash){let i=r.includes("?")?s+r.substring(r.indexOf("?")):s;return{chainPrefix:l.IdentifierChainDefault,type:a,identifier:i,identifierBase:s}}}if(e.length===2){let[a,s]=e;if(a!==l.IdentifierType.Alias&&a!==l.IdentifierType.Hash){let i=r.includes("?")?s+r.substring(r.indexOf("?")):s;return{chainPrefix:a,type:l.IdentifierType.Alias,identifier:i,identifierBase:s}}}return{chainPrefix:l.IdentifierChainDefault,type:l.IdentifierType.Alias,identifier:r,identifierBase:t}},O=n=>{let r=new URL(n),e=r.searchParams.get(l.IdentifierParamName);if(e||(e=r.pathname.split("/")[1]),!e)return null;let a=decodeURIComponent(e);return A(a)};var gr=Z(require("qr-code-styling"));var $=class{constructor(r,t){this.config=r;this.adapters=t}isValid(r){return r.startsWith(l.HttpProtocolPrefix)?!!O(r):!1}build(r,t,e){let a=this.config.clientUrl||m.DefaultClientUrl(this.config.env),s=W(r,this.adapters),i=t===l.IdentifierType.Alias?e:t+l.IdentifierParamSeparatorDefault+e,o=s.prefix+l.IdentifierParamSeparatorDefault+i,p=encodeURIComponent(o);return m.SuperClientUrls.includes(a)?`${a}/${p}`:`${a}?${l.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(r){let t=A(r);if(!t)return null;let e=B(t.chainPrefix,this.adapters);return e?this.build(e.chain,t.type,t.identifierBase):null}generateQrCode(r,t,e,a=512,s="white",i="black",o="#23F7DD"){let p=W(r,this.adapters),c=this.build(p.chain,t,e);return new gr.default({type:"svg",width:a,height:a,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Nr="https://",ar=(n,r,t,e,a)=>{let s=t.actions?.[e]?.next||t.next||null;if(!s)return null;if(s.startsWith(Nr))return[{identifier:null,url:s}];let[i,o]=s.split("?");if(!o)return[{identifier:i,url:nr(r,i,n)}];let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let h=Q(o,{...t.vars,...a}),y=h?`${i}?${h}`:i;return[{identifier:y,url:nr(r,y,n)}]}let c=p[0];if(!c)return[];let u=c.match(/{{([^[]+)\[\]/),g=u?u[1]:null;if(!g||a[g]===void 0)return[];let f=Array.isArray(a[g])?a[g]:[a[g]];if(f.length===0)return[];let v=p.filter(h=>h.includes(`{{${g}[]`)).map(h=>{let y=h.match(/\[\](\.[^}]+)?}}/),d=y&&y[1]||"";return{placeholder:h,field:d?d.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(h=>{let y=o;for(let{regex:C,field:L}of v){let b=L?Lr(h,L):h;if(b==null)return null;y=y.replace(C,b)}if(y.includes("{{")||y.includes("}}"))return null;let d=y?`${i}?${y}`:i;return{identifier:d,url:nr(r,d,n)}}).filter(h=>h!==null)},nr=(n,r,t)=>{let[e,a]=r.split("?"),s=A(e)||{type:"alias",identifier:e,identifierBase:e},i=new $(t,[n]).build(n.chain,s.type,s.identifierBase);if(!a)return i;let o=new URL(i);return new URLSearchParams(a).forEach((p,c)=>o.searchParams.set(c,p)),o.toString().replace(/\/\?/,"?")},Lr=(n,r)=>r.split(".").reduce((t,e)=>t?.[e],n);var D=class D{static info(...r){D.isTestEnv||console.info(...r)}static warn(...r){D.isTestEnv||console.warn(...r)}static error(...r){D.isTestEnv||console.error(...r)}};D.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var x=D;var P=class{nativeToString(r,t){return`${r}:${t?.toString()??""}`}stringToNative(r){let t=r.split(l.ArgParamsSeparator),e=t[0],a=t.slice(1).join(l.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[s,i]=a.split(l.ArgParamsSeparator);return[`option:${s}`,i||null]}else if(e==="optional"){let[s,i]=a.split(l.ArgParamsSeparator);return[`optional:${s}`,i||null]}else if(e==="list"){let s=a.split(l.ArgParamsSeparator),i=s.slice(0,-1).join(l.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`list:${i}`,c]}else if(e==="variadic"){let s=a.split(l.ArgParamsSeparator),i=s.slice(0,-1).join(l.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`variadic:${i}`,c]}else if(e.startsWith("composite")){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=a.split(l.ArgCompositeSeparator).map((p,c)=>this.stringToNative(`${s[c]}:${p}`)[1]);return[e,o]}else{if(e==="string")return[e,a];if(e==="uint8"||e==="uint16"||e==="uint32")return[e,Number(a)];if(e==="uint64"||e==="biguint")return[e,BigInt(a||0)];if(e==="bool")return[e,a==="true"];if(e==="address")return[e,a];if(e==="token")return[e,a];if(e==="hex")return[e,a];if(e==="codemeta")return[e,a];if(e==="esdt"){let[s,i,o]=a.split(l.ArgCompositeSeparator);return[e,`${s}|${i}|${o}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}};var ir=async(n,r,t,e)=>{let a=[],s={};for(let[i,o]of Object.entries(n.results||{})){if(o.startsWith(l.Transform.Prefix))continue;let p=Ir(o);if(p!==null&&p!==t){s[i]=null;continue}let[c,...u]=o.split("."),g=(f,v)=>v.reduce((E,h)=>E&&E[h]!==void 0?E[h]:null,f);if(c==="out"||c.startsWith("out[")){let f=u.length===0?r?.data||r:g(r,u);a.push(f),s[i]=f}else s[i]=o}return{values:a,results:await Cr(n,s,t,e)}},Cr=async(n,r,t,e)=>{if(!n.results)return r;let a={...r};return a=Fr(a,n,t,e),a=await kr(n,a),a},Fr=(n,r,t,e)=>{let a={...n},s=T(r,t)?.inputs||[],i=new P;for(let[o,p]of Object.entries(a))if(typeof p=="string"&&p.startsWith("input.")){let c=p.split(".")[1],u=s.findIndex(f=>f.as===c||f.name===c),g=u!==-1?e[u]?.value:null;a[o]=g?i.stringToNative(g)[1]:null}return a},kr=async(n,r)=>{if(!n.results)return r;let t={...r},e=Object.entries(n.results).filter(([,a])=>a.startsWith(l.Transform.Prefix)).map(([a,s])=>({key:a,code:s.substring(l.Transform.Prefix.length)}));for(let{key:a,code:s}of e)try{let i;typeof window>"u"?i=(await Promise.resolve().then(()=>(yr(),Wr))).runInVm:i=(await Promise.resolve().then(()=>(vr(),xr))).runInVm,t[a]=await i(s,t)}catch(i){x.error(`Transform error for result '${a}':`,i),t[a]=null}return t},Ir=n=>{if(n==="out")return 1;let r=n.match(/^out\[(\d+)\]/);return r?parseInt(r[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};var wr=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Hr=n=>wr.find(r=>r.id===n)||null;var Mr=n=>`${I.String}:${n}`,jr=n=>`${I.U8}:${n}`,qr=n=>`${I.U16}:${n}`,Gr=n=>`${I.U32}:${n}`,zr=n=>`${I.U64}:${n}`,Jr=n=>`${I.Biguint}:${n}`,Kr=n=>`${I.Boolean}:${n}`,Qr=n=>`${I.Address}:${n}`,_r=n=>`${I.Hex}:${n}`;var Ar=Z(require("ajv"));var sr=class{constructor(r){this.pendingBrand={protocol:F("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}setName(r){return this.pendingBrand.name=r,this}setDescription(r){return this.pendingBrand.description=r,this}setLogo(r){return this.pendingBrand.logo=r,this}setUrls(r){return this.pendingBrand.urls=r,this}setColors(r){return this.pendingBrand.colors=r,this}setCta(r){return this.pendingBrand.cta=r,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(r,t){if(!r)throw new Error(`Warp: ${t}`)}async ensureValidSchema(r){let t=this.config.schema?.brand||m.LatestBrandSchemaUrl,a=await(await fetch(t)).json(),s=new Ar.default,i=s.compile(a);if(!i(r))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(i.errors)}`)}};var br=Z(require("ajv"));var k=class{constructor(r){this.config=r;this.config=r}async validate(r){let t=[];return t.push(...this.validateMaxOneValuePosition(r)),t.push(...this.validateVariableNamesAndResultNamesUppercase(r)),t.push(...this.validateAbiIsSetIfApplicable(r)),t.push(...await this.validateSchema(r)),{valid:t.length===0,errors:t}}validateMaxOneValuePosition(r){return r.actions.filter(e=>e.inputs?e.inputs.some(a=>a.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let t=[],e=(a,s)=>{a&&Object.keys(a).forEach(i=>{i!==i.toUpperCase()&&t.push(`${s} name '${i}' must be uppercase`)})};return e(r.vars,"Variable"),e(r.results,"Result"),t}validateAbiIsSetIfApplicable(r){let t=r.actions.some(i=>i.type==="contract"),e=r.actions.some(i=>i.type==="query");if(!t&&!e)return[];let a=r.actions.some(i=>i.abi),s=Object.values(r.results||{}).some(i=>i.startsWith("out.")||i.startsWith("event."));return r.results&&!a&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let t=this.config.schema?.warp||m.LatestWarpSchemaUrl,a=await(await fetch(t)).json(),s=new br.default({strict:!1}),i=s.compile(a);return i(r)?[]:[`Schema validation failed: ${s.errorsText(i.errors)}`]}catch(t){return[`Schema validation failed: ${t instanceof Error?t.message:String(t)}`]}}};var or=class{constructor(r){this.config=r;this.pendingWarp={protocol:F("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.validate(e),e}setName(r){return this.pendingWarp.name=r,this}setTitle(r){return this.pendingWarp.title=r,this}setDescription(r){return this.pendingWarp.description=r,this}setPreview(r){return this.pendingWarp.preview=r,this}setActions(r){return this.pendingWarp.actions=r,this}addAction(r){return this.pendingWarp.actions.push(r),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(r,t=100){return tr(r,t)}ensure(r,t){if(!r)throw new Error(t)}async validate(r){let e=await new k(this.config).validate(r);if(!e.valid)throw new Error(e.errors.join(`
12
- `))}};var H=class{constructor(r="warp-cache"){this.prefix=r}getKey(r){return`${this.prefix}:${r}`}get(r){try{let t=localStorage.getItem(this.getKey(r));if(!t)return null;let e=JSON.parse(t);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(r)),null):e.value}catch{return null}}set(r,t,e){let a={value:t,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(r),JSON.stringify(a))}forget(r){localStorage.removeItem(this.getKey(r))}clear(){for(let r=0;r<localStorage.length;r++){let t=localStorage.key(r);t?.startsWith(this.prefix)&&localStorage.removeItem(t)}}};var R=class R{get(r){let t=R.cache.get(r);return t?Date.now()>t.expiresAt?(R.cache.delete(r),null):t.value:null}set(r,t,e){let a=Date.now()+e*1e3;R.cache.set(r,{value:t,expiresAt:a})}forget(r){R.cache.delete(r)}clear(){R.cache.clear()}};R.cache=new Map;var M=R;var _={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},pr={Warp:(n,r)=>`warp:${n}:${r}`,WarpAbi:(n,r)=>`warp-abi:${n}:${r}`,WarpExecutable:(n,r,t)=>`warp-exec:${n}:${r}:${t}`,RegistryInfo:(n,r)=>`registry-info:${n}:${r}`,Brand:(n,r)=>`brand:${n}:${r}`,ChainInfo:(n,r)=>`chain:${n}:${r}`,ChainInfos:n=>`chains:${n}`},j=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new H:r==="memory"?new M:typeof window<"u"&&window.localStorage?new H:new M}set(r,t,e){this.strategy.set(r,t,e)}get(r){return this.strategy.get(r)}forget(r){this.strategy.forget(r)}clear(){this.strategy.clear()}};var U=class{constructor(r,t){this.config=r;this.adapters=t;if(!r.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(r.currentUrl),this.serializer=new P,this.cache=new j(r.cache?.type)}async createExecutable(r,t,e){let a=T(r,t);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForAction(a,e),i=await this.getResolvedInputs(s,a,e),o=this.getModifiedInputs(i),p=o.find(w=>w.input.position==="receiver")?.value,c="address"in a?a.address:null,u=p?.split(":")[1]||c;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let g=u,f=this.getPreparedArgs(a,o),v=o.find(w=>w.input.position==="value")?.value||null,E="value"in a?a.value:null,h=BigInt(v?.split(":")[1]||E||0),y=o.filter(w=>w.input.position==="transfer"&&w.value).map(w=>w.value),C=[...("transfers"in a?a.transfers:[])||[],...y||[]],L=o.find(w=>w.input.position==="data")?.value,b="data"in a?a.data||"":null,ur={warp:r,chain:s,action:t,destination:g,args:f,value:h,transfers:C,data:L||b||null,resolvedInputs:o};return this.cache.set(pr.WarpExecutable(this.config.env,r.meta?.hash||"",t),ur.resolvedInputs,_.OneWeek),ur}async getChainInfoForAction(r,t){if(t){let e=await this.tryGetChainFromInputs(r,t);if(e)return e}return this.getDefaultChainInfo(r)}async getResolvedInputs(r,t,e){let a=t.inputs||[],s=await Promise.all(e.map(o=>this.preprocessInput(r,o))),i=(o,p)=>{if(o.source==="query"){let c=this.url.searchParams.get(o.name);return c?this.serializer.nativeToString(o.type,c):null}else return o.source===l.Source.UserWallet?this.config.user?.wallets?.[r.name]?this.serializer.nativeToString("address",this.config.user.wallets[r.name]):null:s[p]||null};return a.map((o,p)=>{let c=i(o,p);return{input:o,value:c||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(r){return r.map((t,e)=>{if(t.input.modifier?.startsWith("scale:")){let[,a]=t.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(r.find(p=>p.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let i=t.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let o=K(i,+s);return{...t,value:`${t.input.type}:${o}`}}else{let s=t.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let i=K(s,+a);return{...t,value:`${t.input.type}:${i}`}}}else return t})}async preprocessInput(r,t){try{let[e,a]=t.split(l.ArgParamsSeparator,2);return W(r.name,this.adapters).executor.preprocessInput(r,t,e,a)}catch{return t}}getPreparedArgs(r,t){let e="args"in r?r.args||[]:[];return t.forEach(({input:a,value:s})=>{if(!s||!a.position?.startsWith("arg:"))return;let i=Number(a.position.split(":")[1])-1;e.splice(i,0,s)}),e}async tryGetChainFromInputs(r,t){let e=r.inputs?.findIndex(c=>c.position==="chain");if(e===-1||e===void 0)return null;let a=t[e];if(!a)throw new Error("WarpUtils: Chain input not found");let i=new P().stringToNative(a)[1],p=await W(i,this.adapters).registry.getChainInfo(i);if(!p)throw new Error(`WarpUtils: Chain info not found for ${i}`);return p}async getDefaultChainInfo(r){if(!r.chain)return V(this.config);let e=await Y(this.adapters).registry.getChainInfo(r.chain,{ttl:_.OneWeek});if(!e)throw new Error(`WarpUtils: Chain info not found for ${r.chain}`);return e}};var N=class{constructor(r,t){this.config=r;this.adapter=t}async apply(r,t){let e=this.applyVars(r,t);return await this.applyGlobals(r,e)}async applyGlobals(r,t){let e={...t};return e.actions=await Promise.all(e.actions.map(async a=>await this.applyActionGlobals(a))),e=await this.applyRootGlobals(e,r),e}applyVars(r,t){if(!t?.vars)return t;let e=JSON.stringify(t),a=(s,i)=>{e=e.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),i.toString())};return Object.entries(t.vars).forEach(([s,i])=>{if(typeof i!="string")a(s,i);else if(i.startsWith(`${l.Vars.Query}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=i.split(`${l.Vars.Query}:`)[1],p=new URLSearchParams(r.currentUrl.split("?")[1]).get(o);p&&a(s,p)}else if(i.startsWith(`${l.Vars.Env}:`)){let o=i.split(`${l.Vars.Env}:`)[1],p=r.vars?.[o];p&&a(s,p)}else if(i===l.Source.UserWallet&&r.user?.wallets?.[this.adapter.chain]){let o=r.user.wallets[this.adapter.chain];o&&a(s,o)}else a(s,i)}),JSON.parse(e)}async applyRootGlobals(r,t){let e=JSON.stringify(r),a={config:t,chain:V(t)};return Object.values(l.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}async applyActionGlobals(r){let t=r.chain?await this.adapter.registry.getChainInfo(r.chain):V(this.config);if(!t)throw new Error(`Chain info not found for ${r.chain}`);let e=JSON.stringify(r),a={config:this.config,chain:t};return Object.values(l.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}};var q=class{constructor(r,t,e){this.config=r;this.adapters=t;this.handlers=e;this.factory=new U(r,t),this.handlers=e}async execute(r,t){let{action:e,actionIndex:a}=rr(r);if(e.type==="collect"){let c=await this.executeCollect(r,a,t);return c.success?this.handlers?.onExecuted?.(c):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null}}let s=await this.factory.createExecutable(r,a,t),i=s.chain.name.toLowerCase(),o=this.adapters.find(c=>c.chain.toLowerCase()===i);if(!o)throw new Error(`No adapter registered for chain: ${i}`);return{tx:await o.executor.createTransaction(s),chain:s.chain}}async evaluateResults(r,t,e){let a=this.adapters.find(i=>i.chain.toLowerCase()===t.name.toLowerCase());if(!a)throw new Error(`No adapter registered for chain: ${t.name}`);let s=await a.results.getTransactionExecutionResults(r,e);this.handlers?.onExecuted?.(s)}async executeCollect(r,t,e,a){let s=T(r,t);if(!s)throw new Error("WarpActionExecutor: Action not found");let i=await this.factory.getChainInfoForAction(s),o=W(i.name,this.adapters),p=await new N(this.config,o).apply(this.config,r),c=await this.factory.getResolvedInputs(i,s,e),u=this.factory.getModifiedInputs(c),g=this.factory.serializer,f=d=>{if(!d.value)return null;let C=g.stringToNative(d.value)[1];return d.input.type==="biguint"?C.toString():d.input.type==="esdt"?{}:C},v=new Headers;v.set("Content-Type","application/json"),v.set("Accept","application/json"),Object.entries(s.destination.headers||{}).forEach(([d,C])=>{v.set(d,C)});let E=Object.fromEntries(u.map(d=>[d.input.as||d.input.name,f(d)])),h=s.destination.method||"GET",y=h==="GET"?void 0:JSON.stringify({...E,...a});x.info("Executing collect",{url:s.destination.url,method:h,headers:v,body:y});try{let d=await fetch(s.destination.url,{method:h,headers:v,body:y}),C=await d.json(),{values:L,results:b}=await ir(p,C,t,u),cr=ar(this.config,o,p,t,b);return{success:d.ok,warp:p,action:t,user:this.config.user?.wallets?.[i.name]||null,txHash:null,next:cr,values:L,results:{...b,_DATA:C},messages:er(p,b)}}catch(d){return x.error("WarpActionExecutor: Error executing collect",d),{success:!1,warp:p,action:t,user:this.config.user?.wallets?.[i.name]||null,txHash:null,next:null,values:[],results:{_DATA:d},messages:{}}}}};var G=class{constructor(r){this.config=r}async search(r,t,e){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let a=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...e},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:r,...t})});if(!a.ok)throw new Error(`WarpIndex: search failed with status ${a.status}`);return(await a.json()).hits}catch(a){throw x.error("WarpIndex: Error searching for warps: ",a),a}}};var z=class{constructor(r,t){this.config=r;this.adapters=t}isValid(r){return r.startsWith(l.HttpProtocolPrefix)?!!O(r):!1}async detectFromHtml(r){if(!r.length)return{match:!1,results:[]};let a=[...r.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),i=(await Promise.all(a)).filter(c=>c.match),o=i.length>0,p=i.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:p}}async detect(r,t){let e={match:!1,url:r,warp:null,chain:null,registryInfo:null,brand:null},a=r.startsWith(l.HttpProtocolPrefix)?O(r):A(r);if(!a)return e;try{let{type:s,identifierBase:i}=a,o=null,p=null,c=null,u=B(a.chainPrefix,this.adapters);if(s==="hash"){o=await u.builder().createFromTransactionHash(i,t);let f=await u.registry.getInfoByHash(i,t);p=f.registryInfo,c=f.brand}else if(s==="alias"){let f=await u.registry.getInfoByAlias(i,t);p=f.registryInfo,c=f.brand,f.registryInfo&&(o=await u.builder().createFromTransactionHash(f.registryInfo.hash,t))}let g=o?await new N(this.config,u).apply(this.config,o):null;return g?{match:!0,url:r,warp:g,chain:u.chain,registryInfo:p,brand:c}:e}catch(s){return x.error("Error detecting warp link",s),e}}};var lr=class{constructor(r,t){this.config=r;this.adapters=t}getConfig(){return this.config}setConfig(r){return this.config=r,this}getAdapters(){return this.adapters}addAdapter(r){return this.adapters.push(r),this}createExecutor(r){return new q(this.config,this.adapters,r)}async detectWarp(r,t){return new z(this.config,this.adapters).detect(r,t)}async executeWarp(r,t,e,a={}){let s=await this.detectWarp(r,a.cache);if(!s.match||!s.warp)throw new Error("Warp not found");let i=this.createExecutor(e),{tx:o,chain:p}=await i.execute(s.warp,t);return{tx:o,chain:p,evaluateResults:async u=>{if(!p||!o||!s.warp)throw new Error("Warp not found");await i.evaluateResults(s.warp,p,u)}}}createInscriptionTransaction(r,t){return W(r,this.adapters).builder().createInscriptionTransaction(t)}async createFromTransaction(r,t,e=!1){return W(r,this.adapters).builder().createFromTransaction(t,e)}async createFromTransactionHash(r,t){let e=A(r);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return B(e.chainPrefix,this.adapters).builder().createFromTransactionHash(r,t)}getExplorer(r){return W(r.name,this.adapters).explorer(r)}getResults(r){return W(r.name,this.adapters).results}async getRegistry(r){let t=W(r,this.adapters).registry;return await t.init(),t}get factory(){return new U(this.config,this.adapters)}get index(){return new G(this.config)}get linkBuilder(){return new $(this.config,this.adapters)}createBuilder(r){return W(r,this.adapters).builder()}createAbiBuilder(r){return W(r,this.adapters).abiBuilder()}createBrandBuilder(r){return W(r,this.adapters).brandBuilder()}};0&&(module.exports={CacheTtl,KnownTokens,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpValidator,address,applyResultsToMessages,biguint,boolean,evaluateResultsCommon,extractCollectResults,extractIdentifierInfoFromUrl,findKnownTokenById,findWarpAdapterByPrefix,findWarpAdapterForChain,findWarpDefaultAdapter,findWarpExecutableAction,getLatestProtocolIdentifier,getMainChainInfo,getNextInfo,getWarpActionByIndex,getWarpInfoFromIdentifier,hex,parseResultsOutIndex,replacePlaceholders,shiftBigintBy,string,toPreviewText,toTypedChainInfo,u16,u32,u64,u8});
11
+ `],{type:"application/javascript"}),s=URL.createObjectURL(a),i=new Worker(s);i.onmessage=function(o){o.data.error?t(new Error(o.data.error)):e(o.data.result),i.terminate(),URL.revokeObjectURL(s)},i.onerror=function(o){t(new Error(`Error in transform: ${o.message}`)),i.terminate(),URL.revokeObjectURL(s)},i.postMessage(r)}catch(a){return t(a)}})});var Br={};X(Br,{createAuthHeaders:()=>D,createAuthMessage:()=>Y,createHttpAuthHeaders:()=>Sr,createSignableMessage:()=>ur,parseSignedMessage:()=>Rr,validateSignedMessage:()=>Pr});function ur(n,r,e=5){let t=(0,Tr.randomBytes)(32).toString("hex"),a=new Date(Date.now()+e*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:t,expiresAt:a,purpose:r}),nonce:t,expiresAt:a}}function Y(n,r,e){let t=e||`prove-wallet-ownership for app "${r}"`;return ur(n,t,5)}function D(n,r,e,t){return{"X-Signer-Wallet":n,"X-Signer-Signature":r,"X-Signer-Nonce":e,"X-Signer-ExpiresAt":t}}async function Sr(n,r,e){let{createAuthMessage:t}=await Promise.resolve().then(()=>(rr(),Br)),{message:a,nonce:s,expiresAt:i}=t(n,e),o=await r(a);return D(n,o,s,i)}function Pr(n){let r=new Date(n).getTime();return Date.now()<r}function Rr(n){try{let r=JSON.parse(n);if(!r.wallet||!r.nonce||!r.expiresAt||!r.purpose)throw new Error("Invalid signed message: missing required fields");return r}catch(r){throw new Error(`Failed to parse signed message: ${r instanceof Error?r.message:"Unknown error"}`)}}var Tr,rr=tr(()=>{"use strict";Tr=require("crypto")});var se={};X(se,{CacheTtl:()=>er,KnownTokens:()=>$r,WarpBrandBuilder:()=>dr,WarpBuilder:()=>fr,WarpCache:()=>q,WarpCacheKey:()=>gr,WarpChainName:()=>yr,WarpClient:()=>hr,WarpConfig:()=>h,WarpConstants:()=>c,WarpExecutor:()=>G,WarpFactory:()=>U,WarpIndex:()=>z,WarpInputTypes:()=>C,WarpInterpolator:()=>L,WarpLinkBuilder:()=>N,WarpLinkDetecter:()=>J,WarpLogger:()=>v,WarpProtocolVersions:()=>B,WarpSerializer:()=>b,WarpValidator:()=>F,address:()=>ae,applyResultsToMessages:()=>or,biguint:()=>te,boolean:()=>ne,createAuthHeaders:()=>D,createAuthMessage:()=>Y,createHttpAuthHeaders:()=>Sr,createSignableMessage:()=>ur,evaluateResultsCommon:()=>br,extractCollectResults:()=>lr,extractIdentifierInfoFromUrl:()=>O,findKnownTokenById:()=>Xr,findWarpAdapterByPrefix:()=>$,findWarpAdapterForChain:()=>m,findWarpDefaultAdapter:()=>ar,findWarpExecutableAction:()=>ir,getLatestProtocolIdentifier:()=>M,getMainChainInfo:()=>V,getNextInfo:()=>cr,getWarpActionByIndex:()=>T,getWarpInfoFromIdentifier:()=>A,hex:()=>ie,parseResultsOutIndex:()=>Er,parseSignedMessage:()=>Rr,replacePlaceholders:()=>Z,shiftBigintBy:()=>_,string:()=>_r,toPreviewText:()=>sr,toTypedChainInfo:()=>Fr,u16:()=>Yr,u32:()=>re,u64:()=>ee,u8:()=>Zr,validateSignedMessage:()=>Pr});module.exports=Dr(se);var yr=(t=>(t.Multiversx="multiversx",t.Sui="sui",t.Evm="evm",t))(yr||{}),c={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:[":","."],IdentifierParamSeparatorDefault:".",IdentifierChainDefault:"mvx",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.chain.name]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:n=>n.chain.explorerUrl},ChainAddressHrp:{Placeholder:"chain.addressHrp",Accessor:n=>n.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},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 B={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},h={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${B.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${B.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",c.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 ar=n=>{let r=n.find(e=>e.chain.toLowerCase()===h.MainChain.Name.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${h.MainChain.Name}`);return r},m=(n,r)=>{let e=r.find(t=>t.chain.toLowerCase()===n.toLowerCase());if(!e)throw new Error(`Adapter not found for chain: ${n}`);return e},$=(n,r)=>{let e=r.find(t=>t.prefix.toLowerCase()===n.toLowerCase());if(!e)throw new Error(`Adapter not found for prefix: ${n}`);return e},V=n=>({name:h.MainChain.Name,displayName:h.MainChain.DisplayName,chainId:h.MainChain.ChainId(n.env),blockTime:h.MainChain.BlockTime(n.env),addressHrp:h.MainChain.AddressHrp,apiUrl:h.MainChain.ApiUrl(n.env),explorerUrl:h.MainChain.ExplorerUrl(n.env),nativeToken:h.MainChain.NativeToken}),M=n=>{if(n==="warp")return`warp:${B.Warp}`;if(n==="brand")return`brand:${B.Brand}`;if(n==="abi")return`abi:${B.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},T=(n,r)=>n?.actions[r-1],ir=n=>(n.actions.forEach((r,e)=>{if(r.type!=="link")return{action:r,actionIndex:e}}),{action:T(n,1),actionIndex:1}),Fr=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()}),_=(n,r)=>{let e=n.toString(),[t,a=""]=e.split("."),s=Math.abs(r);if(r>0)return BigInt(t+a.padEnd(s,"0"));if(r<0){let i=t+a;if(s>=i.length)return 0n;let o=i.slice(0,-s)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},sr=(n,r=100)=>{if(!n)return"";let e=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>r?e.substring(0,e.lastIndexOf(" ",r))+"...":e,e},Z=(n,r)=>n.replace(/\{\{([^}]+)\}\}/g,(e,t)=>r[t]||""),or=(n,r)=>{let e=Object.entries(n.messages||{}).map(([t,a])=>[t,Z(a,r)]);return Object.fromEntries(e)};var kr=n=>{let r=c.IdentifierParamSeparator,e=-1,t="";for(let a of r){let s=n.indexOf(a);s!==-1&&(e===-1||s<e)&&(e=s,t=a)}return e!==-1?{separator:t,index:e}:null},xr=n=>{let r=kr(n);if(!r)return[n];let{separator:e,index:t}=r,a=n.substring(0,t),s=n.substring(t+e.length),i=xr(s);return[a,...i]},A=n=>{let r=decodeURIComponent(n).trim(),e=r.split("?")[0],t=xr(e);if(e.length===64&&/^[a-fA-F0-9]+$/.test(e))return{chainPrefix:c.IdentifierChainDefault,type:c.IdentifierType.Hash,identifier:r,identifierBase:e};if(t.length===2&&/^[a-zA-Z0-9]{62}$/.test(t[0])&&/^[a-zA-Z0-9]{2}$/.test(t[1]))return null;if(t.length===3){let[a,s,i]=t;if(s===c.IdentifierType.Alias||s===c.IdentifierType.Hash){let o=r.includes("?")?i+r.substring(r.indexOf("?")):i;return{chainPrefix:a,type:s,identifier:o,identifierBase:i}}}if(t.length===2){let[a,s]=t;if(a===c.IdentifierType.Alias||a===c.IdentifierType.Hash){let i=r.includes("?")?s+r.substring(r.indexOf("?")):s;return{chainPrefix:c.IdentifierChainDefault,type:a,identifier:i,identifierBase:s}}}if(t.length===2){let[a,s]=t;if(a!==c.IdentifierType.Alias&&a!==c.IdentifierType.Hash){let i=r.includes("?")?s+r.substring(r.indexOf("?")):s;return{chainPrefix:a,type:c.IdentifierType.Alias,identifier:i,identifierBase:s}}}return{chainPrefix:c.IdentifierChainDefault,type:c.IdentifierType.Alias,identifier:r,identifierBase:e}},O=n=>{let r=new URL(n),t=r.searchParams.get(c.IdentifierParamName);if(t||(t=r.pathname.split("/")[1]),!t)return null;let a=decodeURIComponent(t);return A(a)};var vr=nr(require("qr-code-styling"));var N=class{constructor(r,e){this.config=r;this.adapters=e}isValid(r){return r.startsWith(c.HttpProtocolPrefix)?!!O(r):!1}build(r,e,t){let a=this.config.clientUrl||h.DefaultClientUrl(this.config.env),s=m(r,this.adapters),i=e===c.IdentifierType.Alias?t:e+c.IdentifierParamSeparatorDefault+t,o=s.prefix+c.IdentifierParamSeparatorDefault+i,p=encodeURIComponent(o);return h.SuperClientUrls.includes(a)?`${a}/${p}`:`${a}?${c.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(r){let e=A(r);if(!e)return null;let t=$(e.chainPrefix,this.adapters);return t?this.build(t.chain,e.type,e.identifierBase):null}generateQrCode(r,e,t,a=512,s="white",i="black",o="#23F7DD"){let p=m(r,this.adapters),l=this.build(p.chain,e,t);return new vr.default({type:"svg",width:a,height:a,data:String(l),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var jr="https://",cr=(n,r,e,t,a)=>{let s=e.actions?.[t]?.next||e.next||null;if(!s)return null;if(s.startsWith(jr))return[{identifier:null,url:s}];let[i,o]=s.split("?");if(!o)return[{identifier:i,url:pr(r,i,n)}];let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let g=Z(o,{...e.vars,...a}),u=g?`${i}?${g}`:i;return[{identifier:u,url:pr(r,u,n)}]}let l=p[0];if(!l)return[];let d=l.match(/{{([^[]+)\[\]/),W=d?d[1]:null;if(!W||a[W]===void 0)return[];let f=Array.isArray(a[W])?a[W]:[a[W]];if(f.length===0)return[];let P=p.filter(g=>g.includes(`{{${W}[]`)).map(g=>{let u=g.match(/\[\](\.[^}]+)?}}/),y=u&&u[1]||"";return{placeholder:g,field:y?y.slice(1):"",regex:new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(g=>{let u=o;for(let{regex:R,field:I}of P){let E=I?qr(g,I):g;if(E==null)return null;u=u.replace(R,E)}if(u.includes("{{")||u.includes("}}"))return null;let y=u?`${i}?${u}`:i;return{identifier:y,url:pr(r,y,n)}}).filter(g=>g!==null)},pr=(n,r,e)=>{let[t,a]=r.split("?"),s=A(t)||{type:"alias",identifier:t,identifierBase:t},i=new N(e,[n]).build(n.chain,s.type,s.identifierBase);if(!a)return i;let o=new URL(i);return new URLSearchParams(a).forEach((p,l)=>o.searchParams.set(l,p)),o.toString().replace(/\/\?/,"?")},qr=(n,r)=>r.split(".").reduce((e,t)=>e?.[t],n);var H=class H{static info(...r){H.isTestEnv||console.info(...r)}static warn(...r){H.isTestEnv||console.warn(...r)}static error(...r){H.isTestEnv||console.error(...r)}};H.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var v=H;var b=class{nativeToString(r,e){return`${r}:${e?.toString()??""}`}stringToNative(r){let e=r.split(c.ArgParamsSeparator),t=e[0],a=e.slice(1).join(c.ArgParamsSeparator);if(t==="null")return[t,null];if(t==="option"){let[s,i]=a.split(c.ArgParamsSeparator);return[`option:${s}`,i||null]}else if(t==="optional"){let[s,i]=a.split(c.ArgParamsSeparator);return[`optional:${s}`,i||null]}else if(t==="list"){let s=a.split(c.ArgParamsSeparator),i=s.slice(0,-1).join(c.ArgParamsSeparator),o=s[s.length-1],l=(o?o.split(","):[]).map(d=>this.stringToNative(`${i}:${d}`)[1]);return[`list:${i}`,l]}else if(t==="variadic"){let s=a.split(c.ArgParamsSeparator),i=s.slice(0,-1).join(c.ArgParamsSeparator),o=s[s.length-1],l=(o?o.split(","):[]).map(d=>this.stringToNative(`${i}:${d}`)[1]);return[`variadic:${i}`,l]}else if(t.startsWith("composite")){let s=t.match(/\(([^)]+)\)/)?.[1]?.split(c.ArgCompositeSeparator),o=a.split(c.ArgCompositeSeparator).map((p,l)=>this.stringToNative(`${s[l]}:${p}`)[1]);return[t,o]}else{if(t==="string")return[t,a];if(t==="uint8"||t==="uint16"||t==="uint32")return[t,Number(a)];if(t==="uint64"||t==="biguint")return[t,BigInt(a||0)];if(t==="bool")return[t,a==="true"];if(t==="address")return[t,a];if(t==="token")return[t,a];if(t==="hex")return[t,a];if(t==="codemeta")return[t,a];if(t==="esdt"){let[s,i,o]=a.split(c.ArgCompositeSeparator);return[t,`${s}|${i}|${o}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${t}`)}};var lr=async(n,r,e,t)=>{let a=[],s={};for(let[i,o]of Object.entries(n.results||{})){if(o.startsWith(c.Transform.Prefix))continue;let p=Er(o);if(p!==null&&p!==e){s[i]=null;continue}let[l,...d]=o.split("."),W=(f,P)=>P.reduce((w,g)=>w&&w[g]!==void 0?w[g]:null,f);if(l==="out"||l.startsWith("out[")){let f=d.length===0?r?.data||r:W(r,d);a.push(f),s[i]=f}else s[i]=o}return{values:a,results:await br(n,s,e,t)}},br=async(n,r,e,t)=>{if(!n.results)return r;let a={...r};return a=Kr(a,n,e,t),a=await Qr(n,a),a},Kr=(n,r,e,t)=>{let a={...n},s=T(r,e)?.inputs||[],i=new b;for(let[o,p]of Object.entries(a))if(typeof p=="string"&&p.startsWith("input.")){let l=p.split(".")[1],d=s.findIndex(f=>f.as===l||f.name===l),W=d!==-1?t[d]?.value:null;a[o]=W?i.stringToNative(W)[1]:null}return a},Qr=async(n,r)=>{if(!n.results)return r;let e={...r},t=Object.entries(n.results).filter(([,a])=>a.startsWith(c.Transform.Prefix)).map(([a,s])=>({key:a,code:s.substring(c.Transform.Prefix.length)}));for(let{key:a,code:s}of t)try{let i;typeof window>"u"?i=(await Promise.resolve().then(()=>(wr(),Cr))).runInVm:i=(await Promise.resolve().then(()=>(Ar(),Ir))).runInVm,e[a]=await i(s,e)}catch(i){v.error(`Transform error for result '${a}':`,i),e[a]=null}return e},Er=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)};rr();var $r=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Xr=n=>$r.find(r=>r.id===n)||null;var _r=n=>`${C.String}:${n}`,Zr=n=>`${C.U8}:${n}`,Yr=n=>`${C.U16}:${n}`,re=n=>`${C.U32}:${n}`,ee=n=>`${C.U64}:${n}`,te=n=>`${C.Biguint}:${n}`,ne=n=>`${C.Boolean}:${n}`,ae=n=>`${C.Address}:${n}`,ie=n=>`${C.Hex}:${n}`;var Nr=nr(require("ajv"));var dr=class{constructor(r){this.pendingBrand={protocol:M("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,e=!0){let t=JSON.parse(r);return e&&await this.ensureValidSchema(t),t}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,e){if(!r)throw new Error(`Warp: ${e}`)}async ensureValidSchema(r){let e=this.config.schema?.brand||h.LatestBrandSchemaUrl,a=await(await fetch(e)).json(),s=new Nr.default,i=s.compile(a);if(!i(r))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(i.errors)}`)}};var Ur=nr(require("ajv"));var F=class{constructor(r){this.config=r;this.config=r}async validate(r){let e=[];return e.push(...this.validateMaxOneValuePosition(r)),e.push(...this.validateVariableNamesAndResultNamesUppercase(r)),e.push(...this.validateAbiIsSetIfApplicable(r)),e.push(...await this.validateSchema(r)),{valid:e.length===0,errors:e}}validateMaxOneValuePosition(r){return r.actions.filter(t=>t.inputs?t.inputs.some(a=>a.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let e=[],t=(a,s)=>{a&&Object.keys(a).forEach(i=>{i!==i.toUpperCase()&&e.push(`${s} name '${i}' must be uppercase`)})};return t(r.vars,"Variable"),t(r.results,"Result"),e}validateAbiIsSetIfApplicable(r){let e=r.actions.some(i=>i.type==="contract"),t=r.actions.some(i=>i.type==="query");if(!e&&!t)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 e=this.config.schema?.warp||h.LatestWarpSchemaUrl,a=await(await fetch(e)).json(),s=new Ur.default({strict:!1}),i=s.compile(a);return i(r)?[]:[`Schema validation failed: ${s.errorsText(i.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var fr=class{constructor(r){this.config=r;this.pendingWarp={protocol:M("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(r,e=!0){let t=JSON.parse(r);return e&&await this.validate(t),t}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,e=100){return sr(r,e)}ensure(r,e){if(!r)throw new Error(e)}async validate(r){let t=await new F(this.config).validate(r);if(!t.valid)throw new Error(t.errors.join(`
12
+ `))}};var k=class{constructor(r="warp-cache"){this.prefix=r}getKey(r){return`${this.prefix}:${r}`}get(r){try{let e=localStorage.getItem(this.getKey(r));if(!e)return null;let t=JSON.parse(e);return Date.now()>t.expiresAt?(localStorage.removeItem(this.getKey(r)),null):t.value}catch{return null}}set(r,e,t){let a={value:e,expiresAt:Date.now()+t*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 e=localStorage.key(r);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var S=class S{get(r){let e=S.cache.get(r);return e?Date.now()>e.expiresAt?(S.cache.delete(r),null):e.value:null}set(r,e,t){let a=Date.now()+t*1e3;S.cache.set(r,{value:e,expiresAt:a})}forget(r){S.cache.delete(r)}clear(){S.cache.clear()}};S.cache=new Map;var j=S;var er={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},gr={Warp:(n,r)=>`warp:${n}:${r}`,WarpAbi:(n,r)=>`warp-abi:${n}:${r}`,WarpExecutable:(n,r,e)=>`warp-exec:${n}:${r}:${e}`,RegistryInfo:(n,r)=>`registry-info:${n}:${r}`,Brand:(n,r)=>`brand:${n}:${r}`,ChainInfo:(n,r)=>`chain:${n}:${r}`,ChainInfos:n=>`chains:${n}`},q=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new k:r==="memory"?new j:typeof window<"u"&&window.localStorage?new k:new j}set(r,e,t){this.strategy.set(r,e,t)}get(r){return this.strategy.get(r)}forget(r){this.strategy.forget(r)}clear(){this.strategy.clear()}};rr();var U=class{constructor(r,e){this.config=r;this.adapters=e;if(!r.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(r.currentUrl),this.serializer=new b,this.cache=new q(r.cache?.type)}async createExecutable(r,e,t){let a=T(r,e);if(!a)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForAction(a,t),i=await this.getResolvedInputs(s,a,t),o=this.getModifiedInputs(i),p=o.find(x=>x.input.position==="receiver")?.value,l="address"in a?a.address:null,d=p?.split(":")[1]||l;if(!d)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let W=d,f=this.getPreparedArgs(a,o),P=o.find(x=>x.input.position==="value")?.value||null,w="value"in a?a.value:null,g=BigInt(P?.split(":")[1]||w||0),u=o.filter(x=>x.input.position==="transfer"&&x.value).map(x=>x.value),R=[...("transfers"in a?a.transfers:[])||[],...u||[]],I=o.find(x=>x.input.position==="data")?.value,E="data"in a?a.data||"":null,K={warp:r,chain:s,action:e,destination:W,args:f,value:g,transfers:R,data:I||E||null,resolvedInputs:o};return this.cache.set(gr.WarpExecutable(this.config.env,r.meta?.hash||"",e),K.resolvedInputs,er.OneWeek),K}async getChainInfoForAction(r,e){if(e){let t=await this.tryGetChainFromInputs(r,e);if(t)return t}return this.getDefaultChainInfo(r)}async getResolvedInputs(r,e,t){let a=e.inputs||[],s=await Promise.all(t.map(o=>this.preprocessInput(r,o))),i=(o,p)=>{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===c.Source.UserWallet?this.config.user?.wallets?.[r.name]?this.serializer.nativeToString("address",this.config.user.wallets[r.name]):null:s[p]||null};return a.map((o,p)=>{let l=i(o,p);return{input:o,value:l||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(r){return r.map((e,t)=>{if(e.input.modifier?.startsWith("scale:")){let[,a]=e.input.modifier.split(":");if(isNaN(Number(a))){let s=Number(r.find(p=>p.input.name===a)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${a}`);let i=e.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let o=_(i,+s);return{...e,value:`${e.input.type}:${o}`}}else{let s=e.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let i=_(s,+a);return{...e,value:`${e.input.type}:${i}`}}}else return e})}async preprocessInput(r,e){try{let[t,a]=e.split(c.ArgParamsSeparator,2);return m(r.name,this.adapters).executor.preprocessInput(r,e,t,a)}catch{return e}}getPreparedArgs(r,e){let t="args"in r?r.args||[]:[];return e.forEach(({input:a,value:s})=>{if(!s||!a.position?.startsWith("arg:"))return;let i=Number(a.position.split(":")[1])-1;t.splice(i,0,s)}),t}async tryGetChainFromInputs(r,e){let t=r.inputs?.findIndex(l=>l.position==="chain");if(t===-1||t===void 0)return null;let a=e[t];if(!a)throw new Error("WarpUtils: Chain input not found");let i=new b().stringToNative(a)[1],p=await m(i,this.adapters).registry.getChainInfo(i);if(!p)throw new Error(`WarpUtils: Chain info not found for ${i}`);return p}async getDefaultChainInfo(r){if(!r.chain)return V(this.config);let t=await ar(this.adapters).registry.getChainInfo(r.chain,{ttl:er.OneWeek});if(!t)throw new Error(`WarpUtils: Chain info not found for ${r.chain}`);return t}};var L=class{constructor(r,e){this.config=r;this.adapter=e}async apply(r,e){let t=this.applyVars(r,e);return await this.applyGlobals(r,t)}async applyGlobals(r,e){let t={...e};return t.actions=await Promise.all(t.actions.map(async a=>await this.applyActionGlobals(a))),t=await this.applyRootGlobals(t,r),t}applyVars(r,e){if(!e?.vars)return e;let t=JSON.stringify(e),a=(s,i)=>{t=t.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),i.toString())};return Object.entries(e.vars).forEach(([s,i])=>{if(typeof i!="string")a(s,i);else if(i.startsWith(`${c.Vars.Query}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=i.split(`${c.Vars.Query}:`)[1],p=new URLSearchParams(r.currentUrl.split("?")[1]).get(o);p&&a(s,p)}else if(i.startsWith(`${c.Vars.Env}:`)){let o=i.split(`${c.Vars.Env}:`)[1],p=r.vars?.[o];p&&a(s,p)}else if(i===c.Source.UserWallet&&r.user?.wallets?.[this.adapter.chain]){let o=r.user.wallets[this.adapter.chain];o&&a(s,o)}else a(s,i)}),JSON.parse(t)}async applyRootGlobals(r,e){let t=JSON.stringify(r),a={config:e,chain:V(e)};return Object.values(c.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(t=t.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(t)}async applyActionGlobals(r){let e=r.chain?await this.adapter.registry.getChainInfo(r.chain):V(this.config);if(!e)throw new Error(`Chain info not found for ${r.chain}`);let t=JSON.stringify(r),a={config:this.config,chain:e};return Object.values(c.Globals).forEach(s=>{let i=s.Accessor(a);i!=null&&(t=t.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(t)}};var G=class{constructor(r,e,t){this.config=r;this.adapters=e;this.handlers=t;this.handlers=t,this.factory=new U(r,e),this.serializer=new b}async execute(r,e){let{action:t,actionIndex:a}=ir(r);if(t.type==="collect"){let l=await this.executeCollect(r,a,e);return l.success?this.handlers?.onExecuted?.(l):this.handlers?.onError?.({message:JSON.stringify(l.values)}),{tx:null,chain:null}}let s=await this.factory.createExecutable(r,a,e),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{tx:await o.executor.createTransaction(s),chain:s.chain}}async evaluateResults(r,e,t){let a=this.adapters.find(i=>i.chain.toLowerCase()===e.name.toLowerCase());if(!a)throw new Error(`No adapter registered for chain: ${e.name}`);let s=await a.results.getTransactionExecutionResults(r,t);this.handlers?.onExecuted?.(s)}async executeCollect(r,e,t,a){let s=T(r,e);if(!s)throw new Error("WarpActionExecutor: Action not found");let i=await this.factory.getChainInfoForAction(s),o=m(i.name,this.adapters),p=await new L(this.config,o).apply(this.config,r),l=await this.factory.getResolvedInputs(i,s,t),d=this.factory.getModifiedInputs(l),W=u=>{if(!u.value)return null;let y=this.serializer.stringToNative(u.value)[1];return u.input.type==="biguint"?y.toString():u.input.type==="esdt"?{}:y},f=new Headers;if(f.set("Content-Type","application/json"),f.set("Accept","application/json"),this.handlers?.onSignRequest){let u=this.config.user?.wallets?.[i.name];if(!u)throw new Error(`No wallet configured for chain ${i.name}`);let{message:y,nonce:R,expiresAt:I}=Y(u,`${i.name}-adapter`),E=await this.handlers.onSignRequest({message:y,chain:i}),mr=D(u,E,R,I);Object.entries(mr).forEach(([K,x])=>f.set(K,x))}Object.entries(s.destination.headers||{}).forEach(([u,y])=>{f.set(u,y)});let P=Object.fromEntries(d.map(u=>[u.input.as||u.input.name,W(u)])),w=s.destination.method||"GET",g=w==="GET"?void 0:JSON.stringify({...P,...a});v.info("Executing collect",{url:s.destination.url,method:w,headers:f,body:g});try{let u=await fetch(s.destination.url,{method:w,headers:f,body:g}),y=await u.json(),{values:R,results:I}=await lr(p,y,e,d),E=cr(this.config,o,p,e,I);return{success:u.ok,warp:p,action:e,user:this.config.user?.wallets?.[i.name]||null,txHash:null,next:E,values:R,results:{...I,_DATA:y},messages:or(p,I)}}catch(u){return v.error("WarpActionExecutor: Error executing collect",u),{success:!1,warp:p,action:e,user:this.config.user?.wallets?.[i.name]||null,txHash:null,next:null,values:[],results:{_DATA:u},messages:{}}}}};var z=class{constructor(r){this.config=r}async search(r,e,t){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}`,...t},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:r,...e})});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}}};var J=class{constructor(r,e){this.config=r;this.adapters=e}isValid(r){return r.startsWith(c.HttpProtocolPrefix)?!!O(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,p=i.map(l=>({url:l.url,warp:l.warp}));return{match:o,results:p}}async detect(r,e){let t={match:!1,url:r,warp:null,chain:null,registryInfo:null,brand:null},a=r.startsWith(c.HttpProtocolPrefix)?O(r):A(r);if(!a)return t;try{let{type:s,identifierBase:i}=a,o=null,p=null,l=null,d=$(a.chainPrefix,this.adapters);if(s==="hash"){o=await d.builder().createFromTransactionHash(i,e);let f=await d.registry.getInfoByHash(i,e);p=f.registryInfo,l=f.brand}else if(s==="alias"){let f=await d.registry.getInfoByAlias(i,e);p=f.registryInfo,l=f.brand,f.registryInfo&&(o=await d.builder().createFromTransactionHash(f.registryInfo.hash,e))}let W=o?await new L(this.config,d).apply(this.config,o):null;return W?{match:!0,url:r,warp:W,chain:d.chain,registryInfo:p,brand:l}:t}catch(s){return v.error("Error detecting warp link",s),t}}};var hr=class{constructor(r,e){this.config=r;this.adapters=e}getConfig(){return this.config}setConfig(r){return this.config=r,this}getAdapters(){return this.adapters}addAdapter(r){return this.adapters.push(r),this}createExecutor(r){return new G(this.config,this.adapters,r)}async detectWarp(r,e){return new J(this.config,this.adapters).detect(r,e)}async executeWarp(r,e,t,a={}){let s=await this.detectWarp(r,a.cache);if(!s.match||!s.warp)throw new Error("Warp not found");let i=this.createExecutor(t),{tx:o,chain:p}=await i.execute(s.warp,e);return{tx:o,chain:p,evaluateResults:async d=>{if(!p||!o||!s.warp)throw new Error("Warp not found");await i.evaluateResults(s.warp,p,d)}}}createInscriptionTransaction(r,e){return m(r,this.adapters).builder().createInscriptionTransaction(e)}async createFromTransaction(r,e,t=!1){return m(r,this.adapters).builder().createFromTransaction(e,t)}async createFromTransactionHash(r,e){let t=A(r);if(!t)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return $(t.chainPrefix,this.adapters).builder().createFromTransactionHash(r,e)}async signMessage(r,e,t){if(!this.config.user?.wallets?.[r])throw new Error(`No wallet configured for chain ${r}`);return m(r,this.adapters).executor.signMessage(e,t)}getExplorer(r){return m(r.name,this.adapters).explorer(r)}getResults(r){return m(r.name,this.adapters).results}async getRegistry(r){let e=m(r,this.adapters).registry;return await e.init(),e}get factory(){return new U(this.config,this.adapters)}get index(){return new z(this.config)}get linkBuilder(){return new N(this.config,this.adapters)}createBuilder(r){return m(r,this.adapters).builder()}createAbiBuilder(r){return m(r,this.adapters).abiBuilder()}createBrandBuilder(r){return m(r,this.adapters).brandBuilder()}};0&&(module.exports={CacheTtl,KnownTokens,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpValidator,address,applyResultsToMessages,biguint,boolean,createAuthHeaders,createAuthMessage,createHttpAuthHeaders,createSignableMessage,evaluateResultsCommon,extractCollectResults,extractIdentifierInfoFromUrl,findKnownTokenById,findWarpAdapterByPrefix,findWarpAdapterForChain,findWarpDefaultAdapter,findWarpExecutableAction,getLatestProtocolIdentifier,getMainChainInfo,getNextInfo,getWarpActionByIndex,getWarpInfoFromIdentifier,hex,parseResultsOutIndex,parseSignedMessage,replacePlaceholders,shiftBigintBy,string,toPreviewText,toTypedChainInfo,u16,u32,u64,u8,validateSignedMessage});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import"./chunk-3SAEGOMQ.mjs";var ct=(r=>(r.Multiversx="multiversx",r.Sui="sui",r))(ct||{}),l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:[":","."],IdentifierParamSeparatorDefault:".",IdentifierChainDefault:"mvx",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:a=>a.config.user?.wallets?.[a.chain.name]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:a=>a.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:a=>a.chain.explorerUrl},ChainAddressHrp:{Placeholder:"chain.addressHrp",Accessor:a=>a.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},A={Option:"option",Optional:"optional",List:"list",Variadic:"variadic",Composite:"composite",String:"string",U8:"u8",U16:"u16",U32:"u32",U64:"u64",Biguint:"biguint",Boolean:"boolean",Address:"address",Hex:"hex"};var B={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},g={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${B.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${B.Brand}.schema.json`,DefaultClientUrl:a=>a==="devnet"?"https://devnet.usewarp.to":a==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],MainChain:{Name:"multiversx",DisplayName:"MultiversX",ApiUrl:a=>a==="devnet"?"https://devnet-api.multiversx.com":a==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:a=>a==="devnet"?"https://devnet-explorer.multiversx.com":a==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:a=>6e3,AddressHrp:"erd",ChainId:a=>a==="devnet"?"D":a==="testnet"?"T":"1",NativeToken:"EGLD"},AvailableActionInputSources:["field","query",l.Source.UserWallet],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var Y=a=>{let t=a.find(r=>r.chain.toLowerCase()===g.MainChain.Name.toLowerCase());if(!t)throw new Error(`Adapter not found for chain: ${g.MainChain.Name}`);return t},y=(a,t)=>{let r=t.find(e=>e.chain.toLowerCase()===a.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${a}`);return r},$=(a,t)=>{let r=t.find(e=>e.prefix.toLowerCase()===a.toLowerCase());if(!r)throw new Error(`Adapter not found for prefix: ${a}`);return r},O=a=>({name:g.MainChain.Name,displayName:g.MainChain.DisplayName,chainId:g.MainChain.ChainId(a.env),blockTime:g.MainChain.BlockTime(a.env),addressHrp:g.MainChain.AddressHrp,apiUrl:g.MainChain.ApiUrl(a.env),explorerUrl:g.MainChain.ExplorerUrl(a.env),nativeToken:g.MainChain.NativeToken}),k=a=>{if(a==="warp")return`warp:${B.Warp}`;if(a==="brand")return`brand:${B.Brand}`;if(a==="abi")return`abi:${B.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${a}`)},P=(a,t)=>a?.actions[t-1],tt=a=>(a.actions.forEach((t,r)=>{if(t.type!=="link")return{action:t,actionIndex:r}}),{action:P(a,1),actionIndex:1}),Et=a=>({name:a.name.toString(),displayName:a.display_name.toString(),chainId:a.chain_id.toString(),blockTime:a.block_time.toNumber(),addressHrp:a.address_hrp.toString(),apiUrl:a.api_url.toString(),explorerUrl:a.explorer_url.toString(),nativeToken:a.native_token.toString()}),J=(a,t)=>{let r=a.toString(),[e,n=""]=r.split("."),i=Math.abs(t);if(t>0)return BigInt(e+n.padEnd(i,"0"));if(t<0){let s=e+n;if(i>=s.length)return 0n;let o=s.slice(0,-i)||"0";return BigInt(o)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},rt=(a,t=100)=>{if(!a)return"";let r=a.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r},K=(a,t)=>a.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||""),et=(a,t)=>{let r=Object.entries(a.messages||{}).map(([e,n])=>[e,K(n,t)]);return Object.fromEntries(r)};var ut=a=>{let t=l.IdentifierParamSeparator,r=-1,e="";for(let n of t){let i=a.indexOf(n);i!==-1&&(r===-1||i<r)&&(r=i,e=n)}return r!==-1?{separator:e,index:r}:null},nt=a=>{let t=ut(a);if(!t)return[a];let{separator:r,index:e}=t,n=a.substring(0,e),i=a.substring(e+r.length),s=nt(i);return[n,...s]},b=a=>{let t=decodeURIComponent(a).trim(),r=t.split("?")[0],e=nt(r);if(r.length===64&&/^[a-fA-F0-9]+$/.test(r))return{chainPrefix:l.IdentifierChainDefault,type:l.IdentifierType.Hash,identifier:t,identifierBase:r};if(e.length===2&&/^[a-zA-Z0-9]{62}$/.test(e[0])&&/^[a-zA-Z0-9]{2}$/.test(e[1]))return null;if(e.length===3){let[n,i,s]=e;if(i===l.IdentifierType.Alias||i===l.IdentifierType.Hash){let o=t.includes("?")?s+t.substring(t.indexOf("?")):s;return{chainPrefix:n,type:i,identifier:o,identifierBase:s}}}if(e.length===2){let[n,i]=e;if(n===l.IdentifierType.Alias||n===l.IdentifierType.Hash){let s=t.includes("?")?i+t.substring(t.indexOf("?")):i;return{chainPrefix:l.IdentifierChainDefault,type:n,identifier:s,identifierBase:i}}}if(e.length===2){let[n,i]=e;if(n!==l.IdentifierType.Alias&&n!==l.IdentifierType.Hash){let s=t.includes("?")?i+t.substring(t.indexOf("?")):i;return{chainPrefix:n,type:l.IdentifierType.Alias,identifier:s,identifierBase:i}}}return{chainPrefix:l.IdentifierChainDefault,type:l.IdentifierType.Alias,identifier:t,identifierBase:r}},D=a=>{let t=new URL(a),e=t.searchParams.get(l.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let n=decodeURIComponent(e);return b(n)};import dt from"qr-code-styling";var N=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!D(t):!1}build(t,r,e){let n=this.config.clientUrl||g.DefaultClientUrl(this.config.env),i=y(t,this.adapters),s=r===l.IdentifierType.Alias?e:r+l.IdentifierParamSeparatorDefault+e,o=i.prefix+l.IdentifierParamSeparatorDefault+s,p=encodeURIComponent(o);return g.SuperClientUrls.includes(n)?`${n}/${p}`:`${n}?${l.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(t){let r=b(t);if(!r)return null;let e=$(r.chainPrefix,this.adapters);return e?this.build(e.chain,r.type,r.identifierBase):null}generateQrCode(t,r,e,n=512,i="white",s="black",o="#23F7DD"){let p=y(t,this.adapters),c=this.build(p.chain,r,e);return new dt({type:"svg",width:n,height:n,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var ft="https://",at=(a,t,r,e,n)=>{let i=r.actions?.[e]?.next||r.next||null;if(!i)return null;if(i.startsWith(ft))return[{identifier:null,url:i}];let[s,o]=i.split("?");if(!o)return[{identifier:s,url:Q(t,s,a)}];let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let h=K(o,{...r.vars,...n}),W=h?`${s}?${h}`:s;return[{identifier:W,url:Q(t,W,a)}]}let c=p[0];if(!c)return[];let u=c.match(/{{([^[]+)\[\]/),m=u?u[1]:null;if(!m||n[m]===void 0)return[];let f=Array.isArray(n[m])?n[m]:[n[m]];if(f.length===0)return[];let x=p.filter(h=>h.includes(`{{${m}[]`)).map(h=>{let W=h.match(/\[\](\.[^}]+)?}}/),d=W&&W[1]||"";return{placeholder:h,field:d?d.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(h=>{let W=o;for(let{regex:v,field:R}of x){let w=R?ht(h,R):h;if(w==null)return null;W=W.replace(v,w)}if(W.includes("{{")||W.includes("}}"))return null;let d=W?`${s}?${W}`:s;return{identifier:d,url:Q(t,d,a)}}).filter(h=>h!==null)},Q=(a,t,r)=>{let[e,n]=t.split("?"),i=b(e)||{type:"alias",identifier:e,identifierBase:e},s=new N(r,[a]).build(a.chain,i.type,i.identifierBase);if(!n)return s;let o=new URL(s);return new URLSearchParams(n).forEach((p,c)=>o.searchParams.set(c,p)),o.toString().replace(/\/\?/,"?")},ht=(a,t)=>t.split(".").reduce((r,e)=>r?.[e],a);var U=class U{static info(...t){U.isTestEnv||console.info(...t)}static warn(...t){U.isTestEnv||console.warn(...t)}static error(...t){U.isTestEnv||console.error(...t)}};U.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=U;var S=class{nativeToString(t,r){return`${t}:${r?.toString()??""}`}stringToNative(t){let r=t.split(l.ArgParamsSeparator),e=r[0],n=r.slice(1).join(l.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[i,s]=n.split(l.ArgParamsSeparator);return[`option:${i}`,s||null]}else if(e==="optional"){let[i,s]=n.split(l.ArgParamsSeparator);return[`optional:${i}`,s||null]}else if(e==="list"){let i=n.split(l.ArgParamsSeparator),s=i.slice(0,-1).join(l.ArgParamsSeparator),o=i[i.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${s}:${u}`)[1]);return[`list:${s}`,c]}else if(e==="variadic"){let i=n.split(l.ArgParamsSeparator),s=i.slice(0,-1).join(l.ArgParamsSeparator),o=i[i.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${s}:${u}`)[1]);return[`variadic:${s}`,c]}else if(e.startsWith("composite")){let i=e.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=n.split(l.ArgCompositeSeparator).map((p,c)=>this.stringToNative(`${i[c]}:${p}`)[1]);return[e,o]}else{if(e==="string")return[e,n];if(e==="uint8"||e==="uint16"||e==="uint32")return[e,Number(n)];if(e==="uint64"||e==="biguint")return[e,BigInt(n||0)];if(e==="bool")return[e,n==="true"];if(e==="address")return[e,n];if(e==="token")return[e,n];if(e==="hex")return[e,n];if(e==="codemeta")return[e,n];if(e==="esdt"){let[i,s,o]=n.split(l.ArgCompositeSeparator);return[e,`${i}|${s}|${o}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}};var it=async(a,t,r,e)=>{let n=[],i={};for(let[s,o]of Object.entries(a.results||{})){if(o.startsWith(l.Transform.Prefix))continue;let p=yt(o);if(p!==null&&p!==r){i[s]=null;continue}let[c,...u]=o.split("."),m=(f,x)=>x.reduce((E,h)=>E&&E[h]!==void 0?E[h]:null,f);if(c==="out"||c.startsWith("out[")){let f=u.length===0?t?.data||t:m(t,u);n.push(f),i[s]=f}else i[s]=o}return{values:n,results:await mt(a,i,r,e)}},mt=async(a,t,r,e)=>{if(!a.results)return t;let n={...t};return n=gt(n,a,r,e),n=await Wt(a,n),n},gt=(a,t,r,e)=>{let n={...a},i=P(t,r)?.inputs||[],s=new S;for(let[o,p]of Object.entries(n))if(typeof p=="string"&&p.startsWith("input.")){let c=p.split(".")[1],u=i.findIndex(f=>f.as===c||f.name===c),m=u!==-1?e[u]?.value:null;n[o]=m?s.stringToNative(m)[1]:null}return n},Wt=async(a,t)=>{if(!a.results)return t;let r={...t},e=Object.entries(a.results).filter(([,n])=>n.startsWith(l.Transform.Prefix)).map(([n,i])=>({key:n,code:i.substring(l.Transform.Prefix.length)}));for(let{key:n,code:i}of e)try{let s;typeof window>"u"?s=(await import("./runInVm-BFUZVHHD.mjs")).runInVm:s=(await import("./runInVm-5YQ766M3.mjs")).runInVm,r[n]=await s(i,r)}catch(s){C.error(`Transform error for result '${n}':`,s),r[n]=null}return r},yt=a=>{if(a==="out")return 1;let t=a.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(a.startsWith("out.")||a.startsWith("event."),null)};var xt=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18},{id:"VIBE-000000",name:"VIBE",decimals:18}],Yt=a=>xt.find(t=>t.id===a)||null;var ur=a=>`${A.String}:${a}`,dr=a=>`${A.U8}:${a}`,fr=a=>`${A.U16}:${a}`,hr=a=>`${A.U32}:${a}`,mr=a=>`${A.U64}:${a}`,gr=a=>`${A.Biguint}:${a}`,Wr=a=>`${A.Boolean}:${a}`,yr=a=>`${A.Address}:${a}`,xr=a=>`${A.Hex}:${a}`;import vt from"ajv";var st=class{constructor(t){this.pendingBrand={protocol:k("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),e}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,r){if(!t)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.schema?.brand||g.LatestBrandSchemaUrl,n=await(await fetch(r)).json(),i=new vt,s=i.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};import Ct from"ajv";var M=class{constructor(t){this.config=t;this.config=t}async validate(t){let r=[];return r.push(...this.validateMaxOneValuePosition(t)),r.push(...this.validateVariableNamesAndResultNamesUppercase(t)),r.push(...this.validateAbiIsSetIfApplicable(t)),r.push(...await this.validateSchema(t)),{valid:r.length===0,errors:r}}validateMaxOneValuePosition(t){return t.actions.filter(e=>e.inputs?e.inputs.some(n=>n.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(n,i)=>{n&&Object.keys(n).forEach(s=>{s!==s.toUpperCase()&&r.push(`${i} name '${s}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.results,"Result"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(s=>s.type==="contract"),e=t.actions.some(s=>s.type==="query");if(!r&&!e)return[];let n=t.actions.some(s=>s.abi),i=Object.values(t.results||{}).some(s=>s.startsWith("out.")||s.startsWith("event."));return t.results&&!n&&i?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||g.LatestWarpSchemaUrl,n=await(await fetch(r)).json(),i=new Ct({strict:!1}),s=i.compile(n);return s(t)?[]:[`Schema validation failed: ${i.errorsText(s.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var ot=class{constructor(t){this.config=t;this.pendingWarp={protocol:k("warp"),name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.validate(e),e}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,r=100){return rt(t,r)}ensure(t,r){if(!t)throw new Error(r)}async validate(t){let e=await new M(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
2
- `))}};var F=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let r=localStorage.getItem(this.getKey(t));if(!r)return null;let e=JSON.parse(r);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(t)),null):e.value}catch{return null}}set(t,r,e){let n={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(n))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r?.startsWith(this.prefix)&&localStorage.removeItem(r)}}};var T=class T{get(t){let r=T.cache.get(t);return r?Date.now()>r.expiresAt?(T.cache.delete(t),null):r.value:null}set(t,r,e){let n=Date.now()+e*1e3;T.cache.set(t,{value:r,expiresAt:n})}forget(t){T.cache.delete(t)}clear(){T.cache.clear()}};T.cache=new Map;var H=T;var _={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},pt={Warp:(a,t)=>`warp:${a}:${t}`,WarpAbi:(a,t)=>`warp-abi:${a}:${t}`,WarpExecutable:(a,t,r)=>`warp-exec:${a}:${t}:${r}`,RegistryInfo:(a,t)=>`registry-info:${a}:${t}`,Brand:(a,t)=>`brand:${a}:${t}`,ChainInfo:(a,t)=>`chain:${a}:${t}`,ChainInfos:a=>`chains:${a}`},G=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new F:t==="memory"?new H:typeof window<"u"&&window.localStorage?new F:new H}set(t,r,e){this.strategy.set(t,r,e)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var V=class{constructor(t,r){this.config=t;this.adapters=r;if(!t.currentUrl)throw new Error("WarpFactory: currentUrl config not set");this.url=new URL(t.currentUrl),this.serializer=new S,this.cache=new G(t.cache?.type)}async createExecutable(t,r,e){let n=P(t,r);if(!n)throw new Error("WarpFactory: Action not found");let i=await this.getChainInfoForAction(n,e),s=await this.getResolvedInputs(i,n,e),o=this.getModifiedInputs(s),p=o.find(I=>I.input.position==="receiver")?.value,c="address"in n?n.address:null,u=p?.split(":")[1]||c;if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let m=u,f=this.getPreparedArgs(n,o),x=o.find(I=>I.input.position==="value")?.value||null,E="value"in n?n.value:null,h=BigInt(x?.split(":")[1]||E||0),W=o.filter(I=>I.input.position==="transfer"&&I.value).map(I=>I.value),v=[...("transfers"in n?n.transfers:[])||[],...W||[]],R=o.find(I=>I.input.position==="data")?.value,w="data"in n?n.data||"":null,Z={warp:t,chain:i,action:r,destination:m,args:f,value:h,transfers:v,data:R||w||null,resolvedInputs:o};return this.cache.set(pt.WarpExecutable(this.config.env,t.meta?.hash||"",r),Z.resolvedInputs,_.OneWeek),Z}async getChainInfoForAction(t,r){if(r){let e=await this.tryGetChainFromInputs(t,r);if(e)return e}return this.getDefaultChainInfo(t)}async getResolvedInputs(t,r,e){let n=r.inputs||[],i=await Promise.all(e.map(o=>this.preprocessInput(t,o))),s=(o,p)=>{if(o.source==="query"){let c=this.url.searchParams.get(o.name);return c?this.serializer.nativeToString(o.type,c):null}else return o.source===l.Source.UserWallet?this.config.user?.wallets?.[t.name]?this.serializer.nativeToString("address",this.config.user.wallets[t.name]):null:i[p]||null};return n.map((o,p)=>{let c=s(o,p);return{input:o,value:c||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(t){return t.map((r,e)=>{if(r.input.modifier?.startsWith("scale:")){let[,n]=r.input.modifier.split(":");if(isNaN(Number(n))){let i=Number(t.find(p=>p.input.name===n)?.value?.split(":")[1]);if(!i)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let s=r.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=J(s,+i);return{...r,value:`${r.input.type}:${o}`}}else{let i=r.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let s=J(i,+n);return{...r,value:`${r.input.type}:${s}`}}}else return r})}async preprocessInput(t,r){try{let[e,n]=r.split(l.ArgParamsSeparator,2);return y(t.name,this.adapters).executor.preprocessInput(t,r,e,n)}catch{return r}}getPreparedArgs(t,r){let e="args"in t?t.args||[]:[];return r.forEach(({input:n,value:i})=>{if(!i||!n.position?.startsWith("arg:"))return;let s=Number(n.position.split(":")[1])-1;e.splice(s,0,i)}),e}async tryGetChainFromInputs(t,r){let e=t.inputs?.findIndex(c=>c.position==="chain");if(e===-1||e===void 0)return null;let n=r[e];if(!n)throw new Error("WarpUtils: Chain input not found");let s=new S().stringToNative(n)[1],p=await y(s,this.adapters).registry.getChainInfo(s);if(!p)throw new Error(`WarpUtils: Chain info not found for ${s}`);return p}async getDefaultChainInfo(t){if(!t.chain)return O(this.config);let e=await Y(this.adapters).registry.getChainInfo(t.chain,{ttl:_.OneWeek});if(!e)throw new Error(`WarpUtils: Chain info not found for ${t.chain}`);return e}};var L=class{constructor(t,r){this.config=t;this.adapter=r}async apply(t,r){let e=this.applyVars(t,r);return await this.applyGlobals(t,e)}async applyGlobals(t,r){let e={...r};return e.actions=await Promise.all(e.actions.map(async n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e,t),e}applyVars(t,r){if(!r?.vars)return r;let e=JSON.stringify(r),n=(i,s)=>{e=e.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(r.vars).forEach(([i,s])=>{if(typeof s!="string")n(i,s);else if(s.startsWith(`${l.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${l.Vars.Query}:`)[1],p=new URLSearchParams(t.currentUrl.split("?")[1]).get(o);p&&n(i,p)}else if(s.startsWith(`${l.Vars.Env}:`)){let o=s.split(`${l.Vars.Env}:`)[1],p=t.vars?.[o];p&&n(i,p)}else if(s===l.Source.UserWallet&&t.user?.wallets?.[this.adapter.chain]){let o=t.user.wallets[this.adapter.chain];o&&n(i,o)}else n(i,s)}),JSON.parse(e)}async applyRootGlobals(t,r){let e=JSON.stringify(t),n={config:r,chain:O(r)};return Object.values(l.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(e)}async applyActionGlobals(t){let r=t.chain?await this.adapter.registry.getChainInfo(t.chain):O(this.config);if(!r)throw new Error(`Chain info not found for ${t.chain}`);let e=JSON.stringify(t),n={config:this.config,chain:r};return Object.values(l.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(e=e.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(e)}};var j=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.factory=new V(t,r),this.handlers=e}async execute(t,r){let{action:e,actionIndex:n}=tt(t);if(e.type==="collect"){let c=await this.executeCollect(t,n,r);return c.success?this.handlers?.onExecuted?.(c):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null}}let i=await this.factory.createExecutable(t,n,r),s=i.chain.name.toLowerCase(),o=this.adapters.find(c=>c.chain.toLowerCase()===s);if(!o)throw new Error(`No adapter registered for chain: ${s}`);return{tx:await o.executor.createTransaction(i),chain:i.chain}}async evaluateResults(t,r,e){let n=this.adapters.find(s=>s.chain.toLowerCase()===r.name.toLowerCase());if(!n)throw new Error(`No adapter registered for chain: ${r.name}`);let i=await n.results.getTransactionExecutionResults(t,e);this.handlers?.onExecuted?.(i)}async executeCollect(t,r,e,n){let i=P(t,r);if(!i)throw new Error("WarpActionExecutor: Action not found");let s=await this.factory.getChainInfoForAction(i),o=y(s.name,this.adapters),p=await new L(this.config,o).apply(this.config,t),c=await this.factory.getResolvedInputs(s,i,e),u=this.factory.getModifiedInputs(c),m=this.factory.serializer,f=d=>{if(!d.value)return null;let v=m.stringToNative(d.value)[1];return d.input.type==="biguint"?v.toString():d.input.type==="esdt"?{}:v},x=new Headers;x.set("Content-Type","application/json"),x.set("Accept","application/json"),Object.entries(i.destination.headers||{}).forEach(([d,v])=>{x.set(d,v)});let E=Object.fromEntries(u.map(d=>[d.input.as||d.input.name,f(d)])),h=i.destination.method||"GET",W=h==="GET"?void 0:JSON.stringify({...E,...n});C.info("Executing collect",{url:i.destination.url,method:h,headers:x,body:W});try{let d=await fetch(i.destination.url,{method:h,headers:x,body:W}),v=await d.json(),{values:R,results:w}=await it(p,v,r,u),X=at(this.config,o,p,r,w);return{success:d.ok,warp:p,action:r,user:this.config.user?.wallets?.[s.name]||null,txHash:null,next:X,values:R,results:{...w,_DATA:v},messages:et(p,w)}}catch(d){return C.error("WarpActionExecutor: Error executing collect",d),{success:!1,warp:p,action:r,user:this.config.user?.wallets?.[s.name]||null,txHash:null,next:null,values:[],results:{_DATA:d},messages:{}}}}};var q=class{constructor(t){this.config=t}async search(t,r,e){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let n=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...e},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...r})});if(!n.ok)throw new Error(`WarpIndex: search failed with status ${n.status}`);return(await n.json()).hits}catch(n){throw C.error("WarpIndex: Error searching for warps: ",n),n}}};var z=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(l.HttpProtocolPrefix)?!!D(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),s=(await Promise.all(n)).filter(c=>c.match),o=s.length>0,p=s.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:p}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},n=t.startsWith(l.HttpProtocolPrefix)?D(t):b(t);if(!n)return e;try{let{type:i,identifierBase:s}=n,o=null,p=null,c=null,u=$(n.chainPrefix,this.adapters);if(i==="hash"){o=await u.builder().createFromTransactionHash(s,r);let f=await u.registry.getInfoByHash(s,r);p=f.registryInfo,c=f.brand}else if(i==="alias"){let f=await u.registry.getInfoByAlias(s,r);p=f.registryInfo,c=f.brand,f.registryInfo&&(o=await u.builder().createFromTransactionHash(f.registryInfo.hash,r))}let m=o?await new L(this.config,u).apply(this.config,o):null;return m?{match:!0,url:t,warp:m,chain:u.chain,registryInfo:p,brand:c}:e}catch(i){return C.error("Error detecting warp link",i),e}}};var lt=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}setConfig(t){return this.config=t,this}getAdapters(){return this.adapters}addAdapter(t){return this.adapters.push(t),this}createExecutor(t){return new j(this.config,this.adapters,t)}async detectWarp(t,r){return new z(this.config,this.adapters).detect(t,r)}async executeWarp(t,r,e,n={}){let i=await this.detectWarp(t,n.cache);if(!i.match||!i.warp)throw new Error("Warp not found");let s=this.createExecutor(e),{tx:o,chain:p}=await s.execute(i.warp,r);return{tx:o,chain:p,evaluateResults:async u=>{if(!p||!o||!i.warp)throw new Error("Warp not found");await s.evaluateResults(i.warp,p,u)}}}createInscriptionTransaction(t,r){return y(t,this.adapters).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return y(t,this.adapters).builder().createFromTransaction(r,e)}async createFromTransactionHash(t,r){let e=b(t);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return $(e.chainPrefix,this.adapters).builder().createFromTransactionHash(t,r)}getExplorer(t){return y(t.name,this.adapters).explorer(t)}getResults(t){return y(t.name,this.adapters).results}async getRegistry(t){let r=y(t,this.adapters).registry;return await r.init(),r}get factory(){return new V(this.config,this.adapters)}get index(){return new q(this.config)}get linkBuilder(){return new N(this.config,this.adapters)}createBuilder(t){return y(t,this.adapters).builder()}createAbiBuilder(t){return y(t,this.adapters).abiBuilder()}createBrandBuilder(t){return y(t,this.adapters).brandBuilder()}};export{_ as CacheTtl,xt as KnownTokens,st as WarpBrandBuilder,ot as WarpBuilder,G as WarpCache,pt as WarpCacheKey,ct as WarpChainName,lt as WarpClient,g as WarpConfig,l as WarpConstants,j as WarpExecutor,V as WarpFactory,q as WarpIndex,A as WarpInputTypes,L as WarpInterpolator,N as WarpLinkBuilder,z as WarpLinkDetecter,C as WarpLogger,B as WarpProtocolVersions,S as WarpSerializer,M as WarpValidator,yr as address,et as applyResultsToMessages,gr as biguint,Wr as boolean,mt as evaluateResultsCommon,it as extractCollectResults,D as extractIdentifierInfoFromUrl,Yt as findKnownTokenById,$ as findWarpAdapterByPrefix,y as findWarpAdapterForChain,Y as findWarpDefaultAdapter,tt as findWarpExecutableAction,k as getLatestProtocolIdentifier,O as getMainChainInfo,at as getNextInfo,P as getWarpActionByIndex,b as getWarpInfoFromIdentifier,xr as hex,yt as parseResultsOutIndex,K as replacePlaceholders,J as shiftBigintBy,ur as string,rt as toPreviewText,Et as toTypedChainInfo,fr as u16,hr as u32,mr as u64,dr as u8};
1
+ import{a as Ar,b as Y,c as rr,d as br,e as Er,f as Tr}from"./chunk-SGF3YQCF.mjs";import"./chunk-3SAEGOMQ.mjs";var dr=(e=>(e.Multiversx="multiversx",e.Sui="sui",e.Evm="evm",e))(dr||{}),l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:[":","."],IdentifierParamSeparatorDefault:".",IdentifierChainDefault:"mvx",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:a=>a.config.user?.wallets?.[a.chain.name]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:a=>a.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:a=>a.chain.explorerUrl},ChainAddressHrp:{Placeholder:"chain.addressHrp",Accessor:a=>a.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"}},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 B={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},m={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${B.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${B.Brand}.schema.json`,DefaultClientUrl:a=>a==="devnet"?"https://devnet.usewarp.to":a==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],MainChain:{Name:"multiversx",DisplayName:"MultiversX",ApiUrl:a=>a==="devnet"?"https://devnet-api.multiversx.com":a==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:a=>a==="devnet"?"https://devnet-explorer.multiversx.com":a==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:a=>6e3,AddressHrp:"erd",ChainId:a=>a==="devnet"?"D":a==="testnet"?"T":"1",NativeToken:"EGLD"},AvailableActionInputSources:["field","query",l.Source.UserWallet],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var tr=a=>{let r=a.find(t=>t.chain.toLowerCase()===m.MainChain.Name.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${m.MainChain.Name}`);return r},W=(a,r)=>{let t=r.find(e=>e.chain.toLowerCase()===a.toLowerCase());if(!t)throw new Error(`Adapter not found for chain: ${a}`);return t},$=(a,r)=>{let t=r.find(e=>e.prefix.toLowerCase()===a.toLowerCase());if(!t)throw new Error(`Adapter not found for prefix: ${a}`);return t},O=a=>({name:m.MainChain.Name,displayName:m.MainChain.DisplayName,chainId:m.MainChain.ChainId(a.env),blockTime:m.MainChain.BlockTime(a.env),addressHrp:m.MainChain.AddressHrp,apiUrl:m.MainChain.ApiUrl(a.env),explorerUrl:m.MainChain.ExplorerUrl(a.env),nativeToken:m.MainChain.NativeToken}),M=a=>{if(a==="warp")return`warp:${B.Warp}`;if(a==="brand")return`brand:${B.Brand}`;if(a==="abi")return`abi:${B.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${a}`)},R=(a,r)=>a?.actions[r-1],er=a=>(a.actions.forEach((r,t)=>{if(r.type!=="link")return{action:r,actionIndex:t}}),{action:R(a,1),actionIndex:1}),$r=a=>({name:a.name.toString(),displayName:a.display_name.toString(),chainId:a.chain_id.toString(),blockTime:a.block_time.toNumber(),addressHrp:a.address_hrp.toString(),apiUrl:a.api_url.toString(),explorerUrl:a.explorer_url.toString(),nativeToken:a.native_token.toString()}),K=(a,r)=>{let t=a.toString(),[e,n=""]=t.split("."),s=Math.abs(r);if(r>0)return BigInt(e+n.padEnd(s,"0"));if(r<0){let i=e+n;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)},nr=(a,r=100)=>{if(!a)return"";let t=a.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return t=t.startsWith("- ")?t.slice(2):t,t=t.length>r?t.substring(0,t.lastIndexOf(" ",r))+"...":t,t},Q=(a,r)=>a.replace(/\{\{([^}]+)\}\}/g,(t,e)=>r[e]||""),ar=(a,r)=>{let t=Object.entries(a.messages||{}).map(([e,n])=>[e,Q(n,r)]);return Object.fromEntries(t)};var fr=a=>{let r=l.IdentifierParamSeparator,t=-1,e="";for(let n of r){let s=a.indexOf(n);s!==-1&&(t===-1||s<t)&&(t=s,e=n)}return t!==-1?{separator:e,index:t}:null},ir=a=>{let r=fr(a);if(!r)return[a];let{separator:t,index:e}=r,n=a.substring(0,e),s=a.substring(e+t.length),i=ir(s);return[n,...i]},b=a=>{let r=decodeURIComponent(a).trim(),t=r.split("?")[0],e=ir(t);if(t.length===64&&/^[a-fA-F0-9]+$/.test(t))return{chainPrefix:l.IdentifierChainDefault,type:l.IdentifierType.Hash,identifier:r,identifierBase:t};if(e.length===2&&/^[a-zA-Z0-9]{62}$/.test(e[0])&&/^[a-zA-Z0-9]{2}$/.test(e[1]))return null;if(e.length===3){let[n,s,i]=e;if(s===l.IdentifierType.Alias||s===l.IdentifierType.Hash){let o=r.includes("?")?i+r.substring(r.indexOf("?")):i;return{chainPrefix:n,type:s,identifier:o,identifierBase:i}}}if(e.length===2){let[n,s]=e;if(n===l.IdentifierType.Alias||n===l.IdentifierType.Hash){let i=r.includes("?")?s+r.substring(r.indexOf("?")):s;return{chainPrefix:l.IdentifierChainDefault,type:n,identifier:i,identifierBase:s}}}if(e.length===2){let[n,s]=e;if(n!==l.IdentifierType.Alias&&n!==l.IdentifierType.Hash){let i=r.includes("?")?s+r.substring(r.indexOf("?")):s;return{chainPrefix:n,type:l.IdentifierType.Alias,identifier:i,identifierBase:s}}}return{chainPrefix:l.IdentifierChainDefault,type:l.IdentifierType.Alias,identifier:r,identifierBase:t}},D=a=>{let r=new URL(a),e=r.searchParams.get(l.IdentifierParamName);if(e||(e=r.pathname.split("/")[1]),!e)return null;let n=decodeURIComponent(e);return b(n)};import hr from"qr-code-styling";var N=class{constructor(r,t){this.config=r;this.adapters=t}isValid(r){return r.startsWith(l.HttpProtocolPrefix)?!!D(r):!1}build(r,t,e){let n=this.config.clientUrl||m.DefaultClientUrl(this.config.env),s=W(r,this.adapters),i=t===l.IdentifierType.Alias?e:t+l.IdentifierParamSeparatorDefault+e,o=s.prefix+l.IdentifierParamSeparatorDefault+i,p=encodeURIComponent(o);return m.SuperClientUrls.includes(n)?`${n}/${p}`:`${n}?${l.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(r){let t=b(r);if(!t)return null;let e=$(t.chainPrefix,this.adapters);return e?this.build(e.chain,t.type,t.identifierBase):null}generateQrCode(r,t,e,n=512,s="white",i="black",o="#23F7DD"){let p=W(r,this.adapters),c=this.build(p.chain,t,e);return new hr({type:"svg",width:n,height:n,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var gr="https://",sr=(a,r,t,e,n)=>{let s=t.actions?.[e]?.next||t.next||null;if(!s)return null;if(s.startsWith(gr))return[{identifier:null,url:s}];let[i,o]=s.split("?");if(!o)return[{identifier:i,url:_(r,i,a)}];let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let h=Q(o,{...t.vars,...n}),u=h?`${i}?${h}`:i;return[{identifier:u,url:_(r,u,a)}]}let c=p[0];if(!c)return[];let d=c.match(/{{([^[]+)\[\]/),g=d?d[1]:null;if(!g||n[g]===void 0)return[];let f=Array.isArray(n[g])?n[g]:[n[g]];if(f.length===0)return[];let P=p.filter(h=>h.includes(`{{${g}[]`)).map(h=>{let u=h.match(/\[\](\.[^}]+)?}}/),y=u&&u[1]||"";return{placeholder:h,field:y?y.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return f.map(h=>{let u=o;for(let{regex:S,field:I}of P){let A=I?mr(h,I):h;if(A==null)return null;u=u.replace(S,A)}if(u.includes("{{")||u.includes("}}"))return null;let y=u?`${i}?${u}`:i;return{identifier:y,url:_(r,y,a)}}).filter(h=>h!==null)},_=(a,r,t)=>{let[e,n]=r.split("?"),s=b(e)||{type:"alias",identifier:e,identifierBase:e},i=new N(t,[a]).build(a.chain,s.type,s.identifierBase);if(!n)return i;let o=new URL(i);return new URLSearchParams(n).forEach((p,c)=>o.searchParams.set(c,p)),o.toString().replace(/\/\?/,"?")},mr=(a,r)=>r.split(".").reduce((t,e)=>t?.[e],a);var U=class U{static info(...r){U.isTestEnv||console.info(...r)}static warn(...r){U.isTestEnv||console.warn(...r)}static error(...r){U.isTestEnv||console.error(...r)}};U.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var v=U;var E=class{nativeToString(r,t){return`${r}:${t?.toString()??""}`}stringToNative(r){let t=r.split(l.ArgParamsSeparator),e=t[0],n=t.slice(1).join(l.ArgParamsSeparator);if(e==="null")return[e,null];if(e==="option"){let[s,i]=n.split(l.ArgParamsSeparator);return[`option:${s}`,i||null]}else if(e==="optional"){let[s,i]=n.split(l.ArgParamsSeparator);return[`optional:${s}`,i||null]}else if(e==="list"){let s=n.split(l.ArgParamsSeparator),i=s.slice(0,-1).join(l.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(d=>this.stringToNative(`${i}:${d}`)[1]);return[`list:${i}`,c]}else if(e==="variadic"){let s=n.split(l.ArgParamsSeparator),i=s.slice(0,-1).join(l.ArgParamsSeparator),o=s[s.length-1],c=(o?o.split(","):[]).map(d=>this.stringToNative(`${i}:${d}`)[1]);return[`variadic:${i}`,c]}else if(e.startsWith("composite")){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=n.split(l.ArgCompositeSeparator).map((p,c)=>this.stringToNative(`${s[c]}:${p}`)[1]);return[e,o]}else{if(e==="string")return[e,n];if(e==="uint8"||e==="uint16"||e==="uint32")return[e,Number(n)];if(e==="uint64"||e==="biguint")return[e,BigInt(n||0)];if(e==="bool")return[e,n==="true"];if(e==="address")return[e,n];if(e==="token")return[e,n];if(e==="hex")return[e,n];if(e==="codemeta")return[e,n];if(e==="esdt"){let[s,i,o]=n.split(l.ArgCompositeSeparator);return[e,`${s}|${i}|${o}`]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}};var or=async(a,r,t,e)=>{let n=[],s={};for(let[i,o]of Object.entries(a.results||{})){if(o.startsWith(l.Transform.Prefix))continue;let p=vr(o);if(p!==null&&p!==t){s[i]=null;continue}let[c,...d]=o.split("."),g=(f,P)=>P.reduce((C,h)=>C&&C[h]!==void 0?C[h]:null,f);if(c==="out"||c.startsWith("out[")){let f=d.length===0?r?.data||r:g(r,d);n.push(f),s[i]=f}else s[i]=o}return{values:n,results:await Wr(a,s,t,e)}},Wr=async(a,r,t,e)=>{if(!a.results)return r;let n={...r};return n=yr(n,a,t,e),n=await xr(a,n),n},yr=(a,r,t,e)=>{let n={...a},s=R(r,t)?.inputs||[],i=new E;for(let[o,p]of Object.entries(n))if(typeof p=="string"&&p.startsWith("input.")){let c=p.split(".")[1],d=s.findIndex(f=>f.as===c||f.name===c),g=d!==-1?e[d]?.value:null;n[o]=g?i.stringToNative(g)[1]:null}return n},xr=async(a,r)=>{if(!a.results)return r;let t={...r},e=Object.entries(a.results).filter(([,n])=>n.startsWith(l.Transform.Prefix)).map(([n,s])=>({key:n,code:s.substring(l.Transform.Prefix.length)}));for(let{key:n,code:s}of e)try{let i;typeof window>"u"?i=(await import("./runInVm-BFUZVHHD.mjs")).runInVm:i=(await import("./runInVm-5YQ766M3.mjs")).runInVm,t[n]=await i(s,t)}catch(i){v.error(`Transform error for result '${n}':`,i),t[n]=null}return t},vr=a=>{if(a==="out")return 1;let r=a.match(/^out\[(\d+)\]/);return r?parseInt(r[1],10):(a.startsWith("out.")||a.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}],st=a=>Cr.find(r=>r.id===a)||null;var yt=a=>`${w.String}:${a}`,xt=a=>`${w.U8}:${a}`,vt=a=>`${w.U16}:${a}`,Ct=a=>`${w.U32}:${a}`,It=a=>`${w.U64}:${a}`,wt=a=>`${w.Biguint}:${a}`,At=a=>`${w.Boolean}:${a}`,bt=a=>`${w.Address}:${a}`,Et=a=>`${w.Hex}:${a}`;import Ir from"ajv";var pr=class{constructor(r){this.pendingBrand={protocol:M("brand"),name:"",description:"",logo:""};this.config=r}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}setName(r){return this.pendingBrand.name=r,this}setDescription(r){return this.pendingBrand.description=r,this}setLogo(r){return this.pendingBrand.logo=r,this}setUrls(r){return this.pendingBrand.urls=r,this}setColors(r){return this.pendingBrand.colors=r,this}setCta(r){return this.pendingBrand.cta=r,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(r,t){if(!r)throw new Error(`Warp: ${t}`)}async ensureValidSchema(r){let t=this.config.schema?.brand||m.LatestBrandSchemaUrl,n=await(await fetch(t)).json(),s=new Ir,i=s.compile(n);if(!i(r))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(i.errors)}`)}};import wr from"ajv";var j=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(n=>n.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(r){let t=[],e=(n,s)=>{n&&Object.keys(n).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 n=r.actions.some(i=>i.abi),s=Object.values(r.results||{}).some(i=>i.startsWith("out.")||i.startsWith("event."));return r.results&&!n&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(r){try{let t=this.config.schema?.warp||m.LatestWarpSchemaUrl,n=await(await fetch(t)).json(),s=new wr({strict:!1}),i=s.compile(n);return i(r)?[]:[`Schema validation failed: ${s.errorsText(i.errors)}`]}catch(t){return[`Schema validation failed: ${t instanceof Error?t.message:String(t)}`]}}};var lr=class{constructor(r){this.config=r;this.pendingWarp={protocol:M("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 nr(r,t)}ensure(r,t){if(!r)throw new Error(t)}async validate(r){let e=await new j(this.config).validate(r);if(!e.valid)throw new Error(e.errors.join(`
2
+ `))}};var F=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 n={value:t,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(r),JSON.stringify(n))}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 T=class T{get(r){let t=T.cache.get(r);return t?Date.now()>t.expiresAt?(T.cache.delete(r),null):t.value:null}set(r,t,e){let n=Date.now()+e*1e3;T.cache.set(r,{value:t,expiresAt:n})}forget(r){T.cache.delete(r)}clear(){T.cache.clear()}};T.cache=new Map;var H=T;var X={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},cr={Warp:(a,r)=>`warp:${a}:${r}`,WarpAbi:(a,r)=>`warp-abi:${a}:${r}`,WarpExecutable:(a,r,t)=>`warp-exec:${a}:${r}:${t}`,RegistryInfo:(a,r)=>`registry-info:${a}:${r}`,Brand:(a,r)=>`brand:${a}:${r}`,ChainInfo:(a,r)=>`chain:${a}:${r}`,ChainInfos:a=>`chains:${a}`},G=class{constructor(r){this.strategy=this.selectStrategy(r)}selectStrategy(r){return r==="localStorage"?new F:r==="memory"?new H:typeof window<"u"&&window.localStorage?new F: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 V=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 E,this.cache=new G(r.cache?.type)}async createExecutable(r,t,e){let n=R(r,t);if(!n)throw new Error("WarpFactory: Action not found");let s=await this.getChainInfoForAction(n,e),i=await this.getResolvedInputs(s,n,e),o=this.getModifiedInputs(i),p=o.find(x=>x.input.position==="receiver")?.value,c="address"in n?n.address:null,d=p?.split(":")[1]||c;if(!d)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let g=d,f=this.getPreparedArgs(n,o),P=o.find(x=>x.input.position==="value")?.value||null,C="value"in n?n.value:null,h=BigInt(P?.split(":")[1]||C||0),u=o.filter(x=>x.input.position==="transfer"&&x.value).map(x=>x.value),S=[...("transfers"in n?n.transfers:[])||[],...u||[]],I=o.find(x=>x.input.position==="data")?.value,A="data"in n?n.data||"":null,k={warp:r,chain:s,action:t,destination:g,args:f,value:h,transfers:S,data:I||A||null,resolvedInputs:o};return this.cache.set(cr.WarpExecutable(this.config.env,r.meta?.hash||"",t),k.resolvedInputs,X.OneWeek),k}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 n=t.inputs||[],s=await Promise.all(e.map(o=>this.preprocessInput(r,o))),i=(o,p)=>{if(o.source==="query"){let c=this.url.searchParams.get(o.name);return c?this.serializer.nativeToString(o.type,c):null}else return o.source===l.Source.UserWallet?this.config.user?.wallets?.[r.name]?this.serializer.nativeToString("address",this.config.user.wallets[r.name]):null:s[p]||null};return n.map((o,p)=>{let c=i(o,p);return{input:o,value:c||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(r){return r.map((t,e)=>{if(t.input.modifier?.startsWith("scale:")){let[,n]=t.input.modifier.split(":");if(isNaN(Number(n))){let s=Number(r.find(p=>p.input.name===n)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);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,+n);return{...t,value:`${t.input.type}:${i}`}}}else return t})}async preprocessInput(r,t){try{let[e,n]=t.split(l.ArgParamsSeparator,2);return W(r.name,this.adapters).executor.preprocessInput(r,t,e,n)}catch{return t}}getPreparedArgs(r,t){let e="args"in r?r.args||[]:[];return t.forEach(({input:n,value:s})=>{if(!s||!n.position?.startsWith("arg:"))return;let i=Number(n.position.split(":")[1])-1;e.splice(i,0,s)}),e}async tryGetChainFromInputs(r,t){let e=r.inputs?.findIndex(c=>c.position==="chain");if(e===-1||e===void 0)return null;let n=t[e];if(!n)throw new Error("WarpUtils: Chain input not found");let i=new E().stringToNative(n)[1],p=await W(i,this.adapters).registry.getChainInfo(i);if(!p)throw new Error(`WarpUtils: Chain info not found for ${i}`);return p}async getDefaultChainInfo(r){if(!r.chain)return O(this.config);let e=await tr(this.adapters).registry.getChainInfo(r.chain,{ttl:X.OneWeek});if(!e)throw new Error(`WarpUtils: Chain info not found for ${r.chain}`);return e}};var L=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 n=>await this.applyActionGlobals(n))),e=await this.applyRootGlobals(e,r),e}applyVars(r,t){if(!t?.vars)return t;let e=JSON.stringify(t),n=(s,i)=>{e=e.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),i.toString())};return Object.entries(t.vars).forEach(([s,i])=>{if(typeof i!="string")n(s,i);else if(i.startsWith(`${l.Vars.Query}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=i.split(`${l.Vars.Query}:`)[1],p=new URLSearchParams(r.currentUrl.split("?")[1]).get(o);p&&n(s,p)}else if(i.startsWith(`${l.Vars.Env}:`)){let o=i.split(`${l.Vars.Env}:`)[1],p=r.vars?.[o];p&&n(s,p)}else if(i===l.Source.UserWallet&&r.user?.wallets?.[this.adapter.chain]){let o=r.user.wallets[this.adapter.chain];o&&n(s,o)}else n(s,i)}),JSON.parse(e)}async applyRootGlobals(r,t){let e=JSON.stringify(r),n={config:t,chain:O(t)};return Object.values(l.Globals).forEach(s=>{let i=s.Accessor(n);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):O(this.config);if(!t)throw new Error(`Chain info not found for ${r.chain}`);let e=JSON.stringify(r),n={config:this.config,chain:t};return Object.values(l.Globals).forEach(s=>{let i=s.Accessor(n);i!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(e)}};var q=class{constructor(r,t,e){this.config=r;this.adapters=t;this.handlers=e;this.handlers=e,this.factory=new V(r,t),this.serializer=new E}async execute(r,t){let{action:e,actionIndex:n}=er(r);if(e.type==="collect"){let c=await this.executeCollect(r,n,t);return c.success?this.handlers?.onExecuted?.(c):this.handlers?.onError?.({message:JSON.stringify(c.values)}),{tx:null,chain:null}}let s=await this.factory.createExecutable(r,n,t),i=s.chain.name.toLowerCase(),o=this.adapters.find(c=>c.chain.toLowerCase()===i);if(!o)throw new Error(`No adapter registered for chain: ${i}`);return{tx:await o.executor.createTransaction(s),chain:s.chain}}async evaluateResults(r,t,e){let n=this.adapters.find(i=>i.chain.toLowerCase()===t.name.toLowerCase());if(!n)throw new Error(`No adapter registered for chain: ${t.name}`);let s=await n.results.getTransactionExecutionResults(r,e);this.handlers?.onExecuted?.(s)}async executeCollect(r,t,e,n){let s=R(r,t);if(!s)throw new Error("WarpActionExecutor: Action not found");let i=await this.factory.getChainInfoForAction(s),o=W(i.name,this.adapters),p=await new L(this.config,o).apply(this.config,r),c=await this.factory.getResolvedInputs(i,s,e),d=this.factory.getModifiedInputs(c),g=u=>{if(!u.value)return null;let y=this.serializer.stringToNative(u.value)[1];return u.input.type==="biguint"?y.toString():u.input.type==="esdt"?{}:y},f=new Headers;if(f.set("Content-Type","application/json"),f.set("Accept","application/json"),this.handlers?.onSignRequest){let u=this.config.user?.wallets?.[i.name];if(!u)throw new Error(`No wallet configured for chain ${i.name}`);let{message:y,nonce:S,expiresAt:I}=Y(u,`${i.name}-adapter`),A=await this.handlers.onSignRequest({message:y,chain:i}),Z=rr(u,A,S,I);Object.entries(Z).forEach(([k,x])=>f.set(k,x))}Object.entries(s.destination.headers||{}).forEach(([u,y])=>{f.set(u,y)});let P=Object.fromEntries(d.map(u=>[u.input.as||u.input.name,g(u)])),C=s.destination.method||"GET",h=C==="GET"?void 0:JSON.stringify({...P,...n});v.info("Executing collect",{url:s.destination.url,method:C,headers:f,body:h});try{let u=await fetch(s.destination.url,{method:C,headers:f,body:h}),y=await u.json(),{values:S,results:I}=await or(p,y,t,d),A=sr(this.config,o,p,t,I);return{success:u.ok,warp:p,action:t,user:this.config.user?.wallets?.[i.name]||null,txHash:null,next:A,values:S,results:{...I,_DATA:y},messages:ar(p,I)}}catch(u){return v.error("WarpActionExecutor: Error executing collect",u),{success:!1,warp:p,action:t,user:this.config.user?.wallets?.[i.name]||null,txHash:null,next:null,values:[],results:{_DATA:u},messages:{}}}}};var z=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 n=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...e},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:r,...t})});if(!n.ok)throw new Error(`WarpIndex: search failed with status ${n.status}`);return(await n.json()).hits}catch(n){throw v.error("WarpIndex: Error searching for warps: ",n),n}}};var J=class{constructor(r,t){this.config=r;this.adapters=t}isValid(r){return r.startsWith(l.HttpProtocolPrefix)?!!D(r):!1}async detectFromHtml(r){if(!r.length)return{match:!1,results:[]};let n=[...r.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),i=(await Promise.all(n)).filter(c=>c.match),o=i.length>0,p=i.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:p}}async detect(r,t){let e={match:!1,url:r,warp:null,chain:null,registryInfo:null,brand:null},n=r.startsWith(l.HttpProtocolPrefix)?D(r):b(r);if(!n)return e;try{let{type:s,identifierBase:i}=n,o=null,p=null,c=null,d=$(n.chainPrefix,this.adapters);if(s==="hash"){o=await d.builder().createFromTransactionHash(i,t);let f=await d.registry.getInfoByHash(i,t);p=f.registryInfo,c=f.brand}else if(s==="alias"){let f=await d.registry.getInfoByAlias(i,t);p=f.registryInfo,c=f.brand,f.registryInfo&&(o=await d.builder().createFromTransactionHash(f.registryInfo.hash,t))}let g=o?await new L(this.config,d).apply(this.config,o):null;return g?{match:!0,url:r,warp:g,chain:d.chain,registryInfo:p,brand:c}:e}catch(s){return v.error("Error detecting warp link",s),e}}};var ur=class{constructor(r,t){this.config=r;this.adapters=t}getConfig(){return this.config}setConfig(r){return this.config=r,this}getAdapters(){return this.adapters}addAdapter(r){return this.adapters.push(r),this}createExecutor(r){return new q(this.config,this.adapters,r)}async detectWarp(r,t){return new J(this.config,this.adapters).detect(r,t)}async executeWarp(r,t,e,n={}){let s=await this.detectWarp(r,n.cache);if(!s.match||!s.warp)throw new Error("Warp not found");let i=this.createExecutor(e),{tx:o,chain:p}=await i.execute(s.warp,t);return{tx:o,chain:p,evaluateResults:async d=>{if(!p||!o||!s.warp)throw new Error("Warp not found");await i.evaluateResults(s.warp,p,d)}}}createInscriptionTransaction(r,t){return W(r,this.adapters).builder().createInscriptionTransaction(t)}async createFromTransaction(r,t,e=!1){return W(r,this.adapters).builder().createFromTransaction(t,e)}async createFromTransactionHash(r,t){let e=b(r);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return $(e.chainPrefix,this.adapters).builder().createFromTransactionHash(r,t)}async signMessage(r,t,e){if(!this.config.user?.wallets?.[r])throw new Error(`No wallet configured for chain ${r}`);return W(r,this.adapters).executor.signMessage(t,e)}getExplorer(r){return W(r.name,this.adapters).explorer(r)}getResults(r){return W(r.name,this.adapters).results}async getRegistry(r){let t=W(r,this.adapters).registry;return await t.init(),t}get factory(){return new V(this.config,this.adapters)}get index(){return new z(this.config)}get linkBuilder(){return new N(this.config,this.adapters)}createBuilder(r){return W(r,this.adapters).builder()}createAbiBuilder(r){return W(r,this.adapters).abiBuilder()}createBrandBuilder(r){return W(r,this.adapters).brandBuilder()}};export{X as CacheTtl,Cr as KnownTokens,pr as WarpBrandBuilder,lr as WarpBuilder,G as WarpCache,cr as WarpCacheKey,dr as WarpChainName,ur as WarpClient,m as WarpConfig,l as WarpConstants,q as WarpExecutor,V as WarpFactory,z as WarpIndex,w as WarpInputTypes,L as WarpInterpolator,N as WarpLinkBuilder,J as WarpLinkDetecter,v as WarpLogger,B as WarpProtocolVersions,E as WarpSerializer,j as WarpValidator,bt as address,ar as applyResultsToMessages,wt as biguint,At as boolean,rr as createAuthHeaders,Y as createAuthMessage,br as createHttpAuthHeaders,Ar as createSignableMessage,Wr as evaluateResultsCommon,or as extractCollectResults,D as extractIdentifierInfoFromUrl,st as findKnownTokenById,$ as findWarpAdapterByPrefix,W as findWarpAdapterForChain,tr as findWarpDefaultAdapter,er as findWarpExecutableAction,M as getLatestProtocolIdentifier,O as getMainChainInfo,sr as getNextInfo,R as getWarpActionByIndex,b as getWarpInfoFromIdentifier,Et as hex,vr as parseResultsOutIndex,Tr as parseSignedMessage,Q as replacePlaceholders,K as shiftBigintBy,yt as string,nr as toPreviewText,$r as toTypedChainInfo,vt as u16,Ct as u32,It as u64,xt as u8,Er as validateSignedMessage};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e,f}from"./chunk-SGF3YQCF.mjs";import"./chunk-3SAEGOMQ.mjs";export{c as createAuthHeaders,b as createAuthMessage,d as createHttpAuthHeaders,a as createSignableMessage,f as parseSignedMessage,e as validateSignedMessage};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "3.0.0-alpha.59",
3
+ "version": "3.0.0-alpha.60",
4
4
  "description": "",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",