@vleap/warps 3.0.0-beta.158 → 3.0.0-beta.160

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -54,22 +54,6 @@ type WarpCacheType = 'memory' | 'localStorage';
54
54
  type WarpChainEnv = 'mainnet' | 'testnet' | 'devnet';
55
55
  type ProtocolName = 'warp' | 'brand' | 'abi';
56
56
 
57
- type WarpTrustStatus = 'unverified' | 'verified' | 'blacklisted';
58
- type WarpRegistryInfo = {
59
- hash: string;
60
- alias: string | null;
61
- trust: WarpTrustStatus;
62
- owner: string;
63
- createdAt: number;
64
- upgradedAt: number;
65
- brand: string | null;
66
- upgrade: string | null;
67
- };
68
- type WarpRegistryConfigInfo = {
69
- unitPrice: bigint;
70
- admins: string[];
71
- };
72
-
73
57
  type WarpActionExecutionStatus = 'success' | 'error' | 'unhandled';
74
58
  type WarpActionExecutionResult = {
75
59
  status: WarpActionExecutionStatus;
@@ -95,6 +79,22 @@ type WarpExecutionNextInfo = {
95
79
  type WarpExecutionOutput = Record<WarpOutputName, any | null>;
96
80
  type WarpExecutionMessages = Record<WarpMessageName, string | null>;
97
81
 
82
+ type WarpTrustStatus = 'unverified' | 'verified' | 'blacklisted';
83
+ type WarpRegistryInfo = {
84
+ hash: string;
85
+ alias: string | null;
86
+ trust: WarpTrustStatus;
87
+ owner: string;
88
+ createdAt: number;
89
+ upgradedAt: number;
90
+ brand: string | null;
91
+ upgrade: string | null;
92
+ };
93
+ type WarpRegistryConfigInfo = {
94
+ unitPrice: bigint;
95
+ admins: string[];
96
+ };
97
+
98
98
  type ClientIndexConfig = {
99
99
  url?: string;
100
100
  apiKey?: string;
@@ -282,6 +282,7 @@ interface AdapterWarpWallet {
282
282
  create(mnemonic: string): WarpWalletDetails;
283
283
  generate(): WarpWalletDetails;
284
284
  getAddress(): string | null;
285
+ getPublicKey(): string | null;
285
286
  }
286
287
 
287
288
  type WarpChainAccount = {
@@ -437,7 +438,11 @@ interface WarpStructValue {
437
438
  [key: string]: WarpNativeValue;
438
439
  }
439
440
  type WarpNativeValue = string | number | bigint | boolean | WarpChainAssetValue | null | WarpNativeValue[] | WarpStructValue;
440
- type WarpActionInputPosition = 'receiver' | 'value' | 'transfer' | `arg:${1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10}` | 'data' | 'chain' | `payload:${string}` | 'destination';
441
+ type WarpActionInputPosition = 'receiver' | 'value' | 'transfer' | `arg:${1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10}` | 'data' | 'chain' | `payload:${string}` | 'destination' | WarpActionInputPositionAssetObject;
442
+ type WarpActionInputPositionAssetObject = {
443
+ token: `arg:${string}`;
444
+ amount: `arg:${string}`;
445
+ };
441
446
  type WarpActionInputModifier = 'scale';
442
447
  type WarpActionInput = {
443
448
  name: string;
@@ -505,7 +510,7 @@ type WarpSecret = {
505
510
 
506
511
  type InterpolationBag = {
507
512
  config: WarpClientConfig;
508
- chain: WarpChainInfo;
513
+ adapter: Adapter;
509
514
  };
510
515
 
511
516
  declare const WarpProtocolVersions: {
@@ -548,6 +553,10 @@ declare const WarpConstants: {
548
553
  Placeholder: string;
549
554
  Accessor: (bag: InterpolationBag) => string | WarpWalletDetails | null | undefined;
550
555
  };
556
+ UserWalletPublicKey: {
557
+ Placeholder: string;
558
+ Accessor: (bag: InterpolationBag) => string | null;
559
+ };
551
560
  ChainApiUrl: {
552
561
  Placeholder: string;
553
562
  Accessor: (bag: InterpolationBag) => string;
@@ -936,6 +945,7 @@ declare class WarpExecutor {
936
945
  txs: WarpAdapterGenericTransaction[];
937
946
  chain: WarpChainInfo | null;
938
947
  immediateExecutions: WarpActionExecutionResult[];
948
+ resolvedInputs: string[];
939
949
  }>;
940
950
  executeAction(warp: Warp, actionIndex: WarpActionIndex, inputs: string[], meta?: {
941
951
  envs?: Record<string, any>;
@@ -944,6 +954,7 @@ declare class WarpExecutor {
944
954
  tx: WarpAdapterGenericTransaction | null;
945
955
  chain: WarpChainInfo | null;
946
956
  immediateExecution: WarpActionExecutionResult | null;
957
+ executable: WarpExecutable | null;
947
958
  }>;
948
959
  evaluateOutput(warp: Warp, actions: WarpChainAction[]): Promise<void>;
949
960
  private executeCollect;
@@ -953,6 +964,26 @@ declare class WarpExecutor {
953
964
  private callHandler;
954
965
  }
955
966
 
967
+ declare class WarpInterpolator {
968
+ private config;
969
+ private adapter;
970
+ constructor(config: WarpClientConfig, adapter: Adapter);
971
+ apply(config: WarpClientConfig, warp: Warp, meta?: {
972
+ envs?: Record<string, any>;
973
+ queries?: Record<string, any>;
974
+ }): Promise<Warp>;
975
+ applyGlobals(config: WarpClientConfig, warp: Warp): Promise<Warp>;
976
+ applyVars(config: WarpClientConfig, warp: Warp, meta?: {
977
+ envs?: Record<string, any>;
978
+ queries?: Record<string, any>;
979
+ }): Warp;
980
+ private applyRootGlobals;
981
+ private applyActionGlobals;
982
+ applyInputs(text: string, resolvedInputs: ResolvedInput[], serializer: WarpSerializer, primaryInputs?: ResolvedInput[]): string;
983
+ private applyGlobalsToText;
984
+ private buildInputBag;
985
+ }
986
+
956
987
  declare class WarpFactory {
957
988
  private config;
958
989
  private adapters;
@@ -967,7 +998,7 @@ declare class WarpFactory {
967
998
  }): Promise<WarpExecutable>;
968
999
  getChainInfoForWarp(warp: Warp, inputs?: string[]): Promise<WarpChainInfo>;
969
1000
  getStringTypedInputs(action: WarpAction, inputs: string[]): string[];
970
- getResolvedInputs(chain: WarpChain, action: WarpAction, inputArgs: string[]): Promise<ResolvedInput[]>;
1001
+ getResolvedInputs(chain: WarpChain, action: WarpAction, inputArgs: string[], interpolator?: WarpInterpolator): Promise<ResolvedInput[]>;
971
1002
  getModifiedInputs(inputs: ResolvedInput[]): ResolvedInput[];
972
1003
  preprocessInput(chain: WarpChain, input: string): Promise<string>;
973
1004
  private getDestinationFromAction;
@@ -1032,6 +1063,7 @@ declare class WarpClient {
1032
1063
  chain: WarpChainInfo | null;
1033
1064
  immediateExecutions: WarpActionExecutionResult[];
1034
1065
  evaluateOutput: (remoteTxs: WarpAdapterGenericRemoteTransaction[]) => Promise<void>;
1066
+ resolvedInputs: string[];
1035
1067
  }>;
1036
1068
  createInscriptionTransaction(chain: WarpChain, warp: Warp): Promise<WarpAdapterGenericTransaction>;
1037
1069
  createFromTransaction(chain: WarpChain, tx: WarpAdapterGenericRemoteTransaction, validate?: boolean): Promise<Warp>;
@@ -1053,24 +1085,6 @@ declare class WarpClient {
1053
1085
  resolveText(warpText: WarpText): string;
1054
1086
  }
1055
1087
 
1056
- declare class WarpInterpolator {
1057
- private config;
1058
- private adapter;
1059
- constructor(config: WarpClientConfig, adapter: Adapter);
1060
- apply(config: WarpClientConfig, warp: Warp, meta?: {
1061
- envs?: Record<string, any>;
1062
- queries?: Record<string, any>;
1063
- }): Promise<Warp>;
1064
- applyGlobals(config: WarpClientConfig, warp: Warp): Promise<Warp>;
1065
- applyVars(config: WarpClientConfig, warp: Warp, meta?: {
1066
- envs?: Record<string, any>;
1067
- queries?: Record<string, any>;
1068
- }): Warp;
1069
- private applyRootGlobals;
1070
- private applyActionGlobals;
1071
- applyInputs(text: string, resolvedInputs: ResolvedInput[], serializer: WarpSerializer, primaryInputs?: ResolvedInput[]): string;
1072
- }
1073
-
1074
1088
  declare class WarpLogger {
1075
1089
  private static isTestEnv;
1076
1090
  static debug(...args: any[]): void;
@@ -1107,4 +1121,4 @@ declare class WarpValidator {
1107
1121
  private validateSchema;
1108
1122
  }
1109
1123
 
1110
- export { type Adapter, type AdapterFactory, type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, extractCollectOutput, extractIdentifierInfoFromUrl, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, isEqualWarpIdentifier, isWarpActionAutoExecute, isWarpI18nText, mergeNestedPayload, option, parseOutputOutIndex, parseSignedMessage, replacePlaceholders, resolveWarpText, safeWindow, setCryptoProvider, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateSignedMessage, vector };
1124
+ export { type Adapter, type AdapterFactory, type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, extractCollectOutput, extractIdentifierInfoFromUrl, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, isEqualWarpIdentifier, isWarpActionAutoExecute, isWarpI18nText, mergeNestedPayload, option, parseOutputOutIndex, parseSignedMessage, replacePlaceholders, resolveWarpText, safeWindow, setCryptoProvider, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateSignedMessage, vector };
package/dist/index.d.ts CHANGED
@@ -54,22 +54,6 @@ type WarpCacheType = 'memory' | 'localStorage';
54
54
  type WarpChainEnv = 'mainnet' | 'testnet' | 'devnet';
55
55
  type ProtocolName = 'warp' | 'brand' | 'abi';
56
56
 
57
- type WarpTrustStatus = 'unverified' | 'verified' | 'blacklisted';
58
- type WarpRegistryInfo = {
59
- hash: string;
60
- alias: string | null;
61
- trust: WarpTrustStatus;
62
- owner: string;
63
- createdAt: number;
64
- upgradedAt: number;
65
- brand: string | null;
66
- upgrade: string | null;
67
- };
68
- type WarpRegistryConfigInfo = {
69
- unitPrice: bigint;
70
- admins: string[];
71
- };
72
-
73
57
  type WarpActionExecutionStatus = 'success' | 'error' | 'unhandled';
74
58
  type WarpActionExecutionResult = {
75
59
  status: WarpActionExecutionStatus;
@@ -95,6 +79,22 @@ type WarpExecutionNextInfo = {
95
79
  type WarpExecutionOutput = Record<WarpOutputName, any | null>;
96
80
  type WarpExecutionMessages = Record<WarpMessageName, string | null>;
97
81
 
82
+ type WarpTrustStatus = 'unverified' | 'verified' | 'blacklisted';
83
+ type WarpRegistryInfo = {
84
+ hash: string;
85
+ alias: string | null;
86
+ trust: WarpTrustStatus;
87
+ owner: string;
88
+ createdAt: number;
89
+ upgradedAt: number;
90
+ brand: string | null;
91
+ upgrade: string | null;
92
+ };
93
+ type WarpRegistryConfigInfo = {
94
+ unitPrice: bigint;
95
+ admins: string[];
96
+ };
97
+
98
98
  type ClientIndexConfig = {
99
99
  url?: string;
100
100
  apiKey?: string;
@@ -282,6 +282,7 @@ interface AdapterWarpWallet {
282
282
  create(mnemonic: string): WarpWalletDetails;
283
283
  generate(): WarpWalletDetails;
284
284
  getAddress(): string | null;
285
+ getPublicKey(): string | null;
285
286
  }
286
287
 
287
288
  type WarpChainAccount = {
@@ -437,7 +438,11 @@ interface WarpStructValue {
437
438
  [key: string]: WarpNativeValue;
438
439
  }
439
440
  type WarpNativeValue = string | number | bigint | boolean | WarpChainAssetValue | null | WarpNativeValue[] | WarpStructValue;
440
- type WarpActionInputPosition = 'receiver' | 'value' | 'transfer' | `arg:${1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10}` | 'data' | 'chain' | `payload:${string}` | 'destination';
441
+ type WarpActionInputPosition = 'receiver' | 'value' | 'transfer' | `arg:${1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10}` | 'data' | 'chain' | `payload:${string}` | 'destination' | WarpActionInputPositionAssetObject;
442
+ type WarpActionInputPositionAssetObject = {
443
+ token: `arg:${string}`;
444
+ amount: `arg:${string}`;
445
+ };
441
446
  type WarpActionInputModifier = 'scale';
442
447
  type WarpActionInput = {
443
448
  name: string;
@@ -505,7 +510,7 @@ type WarpSecret = {
505
510
 
506
511
  type InterpolationBag = {
507
512
  config: WarpClientConfig;
508
- chain: WarpChainInfo;
513
+ adapter: Adapter;
509
514
  };
510
515
 
511
516
  declare const WarpProtocolVersions: {
@@ -548,6 +553,10 @@ declare const WarpConstants: {
548
553
  Placeholder: string;
549
554
  Accessor: (bag: InterpolationBag) => string | WarpWalletDetails | null | undefined;
550
555
  };
556
+ UserWalletPublicKey: {
557
+ Placeholder: string;
558
+ Accessor: (bag: InterpolationBag) => string | null;
559
+ };
551
560
  ChainApiUrl: {
552
561
  Placeholder: string;
553
562
  Accessor: (bag: InterpolationBag) => string;
@@ -936,6 +945,7 @@ declare class WarpExecutor {
936
945
  txs: WarpAdapterGenericTransaction[];
937
946
  chain: WarpChainInfo | null;
938
947
  immediateExecutions: WarpActionExecutionResult[];
948
+ resolvedInputs: string[];
939
949
  }>;
940
950
  executeAction(warp: Warp, actionIndex: WarpActionIndex, inputs: string[], meta?: {
941
951
  envs?: Record<string, any>;
@@ -944,6 +954,7 @@ declare class WarpExecutor {
944
954
  tx: WarpAdapterGenericTransaction | null;
945
955
  chain: WarpChainInfo | null;
946
956
  immediateExecution: WarpActionExecutionResult | null;
957
+ executable: WarpExecutable | null;
947
958
  }>;
948
959
  evaluateOutput(warp: Warp, actions: WarpChainAction[]): Promise<void>;
949
960
  private executeCollect;
@@ -953,6 +964,26 @@ declare class WarpExecutor {
953
964
  private callHandler;
954
965
  }
955
966
 
967
+ declare class WarpInterpolator {
968
+ private config;
969
+ private adapter;
970
+ constructor(config: WarpClientConfig, adapter: Adapter);
971
+ apply(config: WarpClientConfig, warp: Warp, meta?: {
972
+ envs?: Record<string, any>;
973
+ queries?: Record<string, any>;
974
+ }): Promise<Warp>;
975
+ applyGlobals(config: WarpClientConfig, warp: Warp): Promise<Warp>;
976
+ applyVars(config: WarpClientConfig, warp: Warp, meta?: {
977
+ envs?: Record<string, any>;
978
+ queries?: Record<string, any>;
979
+ }): Warp;
980
+ private applyRootGlobals;
981
+ private applyActionGlobals;
982
+ applyInputs(text: string, resolvedInputs: ResolvedInput[], serializer: WarpSerializer, primaryInputs?: ResolvedInput[]): string;
983
+ private applyGlobalsToText;
984
+ private buildInputBag;
985
+ }
986
+
956
987
  declare class WarpFactory {
957
988
  private config;
958
989
  private adapters;
@@ -967,7 +998,7 @@ declare class WarpFactory {
967
998
  }): Promise<WarpExecutable>;
968
999
  getChainInfoForWarp(warp: Warp, inputs?: string[]): Promise<WarpChainInfo>;
969
1000
  getStringTypedInputs(action: WarpAction, inputs: string[]): string[];
970
- getResolvedInputs(chain: WarpChain, action: WarpAction, inputArgs: string[]): Promise<ResolvedInput[]>;
1001
+ getResolvedInputs(chain: WarpChain, action: WarpAction, inputArgs: string[], interpolator?: WarpInterpolator): Promise<ResolvedInput[]>;
971
1002
  getModifiedInputs(inputs: ResolvedInput[]): ResolvedInput[];
972
1003
  preprocessInput(chain: WarpChain, input: string): Promise<string>;
973
1004
  private getDestinationFromAction;
@@ -1032,6 +1063,7 @@ declare class WarpClient {
1032
1063
  chain: WarpChainInfo | null;
1033
1064
  immediateExecutions: WarpActionExecutionResult[];
1034
1065
  evaluateOutput: (remoteTxs: WarpAdapterGenericRemoteTransaction[]) => Promise<void>;
1066
+ resolvedInputs: string[];
1035
1067
  }>;
1036
1068
  createInscriptionTransaction(chain: WarpChain, warp: Warp): Promise<WarpAdapterGenericTransaction>;
1037
1069
  createFromTransaction(chain: WarpChain, tx: WarpAdapterGenericRemoteTransaction, validate?: boolean): Promise<Warp>;
@@ -1053,24 +1085,6 @@ declare class WarpClient {
1053
1085
  resolveText(warpText: WarpText): string;
1054
1086
  }
1055
1087
 
1056
- declare class WarpInterpolator {
1057
- private config;
1058
- private adapter;
1059
- constructor(config: WarpClientConfig, adapter: Adapter);
1060
- apply(config: WarpClientConfig, warp: Warp, meta?: {
1061
- envs?: Record<string, any>;
1062
- queries?: Record<string, any>;
1063
- }): Promise<Warp>;
1064
- applyGlobals(config: WarpClientConfig, warp: Warp): Promise<Warp>;
1065
- applyVars(config: WarpClientConfig, warp: Warp, meta?: {
1066
- envs?: Record<string, any>;
1067
- queries?: Record<string, any>;
1068
- }): Warp;
1069
- private applyRootGlobals;
1070
- private applyActionGlobals;
1071
- applyInputs(text: string, resolvedInputs: ResolvedInput[], serializer: WarpSerializer, primaryInputs?: ResolvedInput[]): string;
1072
- }
1073
-
1074
1088
  declare class WarpLogger {
1075
1089
  private static isTestEnv;
1076
1090
  static debug(...args: any[]): void;
@@ -1107,4 +1121,4 @@ declare class WarpValidator {
1107
1121
  private validateSchema;
1108
1122
  }
1109
1123
 
1110
- export { type Adapter, type AdapterFactory, type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, extractCollectOutput, extractIdentifierInfoFromUrl, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, isEqualWarpIdentifier, isWarpActionAutoExecute, isWarpI18nText, mergeNestedPayload, option, parseOutputOutIndex, parseSignedMessage, replacePlaceholders, resolveWarpText, safeWindow, setCryptoProvider, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateSignedMessage, vector };
1124
+ export { type Adapter, type AdapterFactory, type AdapterTypeRegistry, type AdapterWarpAbiBuilder, type AdapterWarpBrandBuilder, type AdapterWarpBuilder, type AdapterWarpDataLoader, type AdapterWarpExecutor, type AdapterWarpExplorer, type AdapterWarpOutput, type AdapterWarpRegistry, type AdapterWarpSerializer, type AdapterWarpWallet, type BaseWarpActionInputType, type BaseWarpBuilder, BrowserCryptoProvider, CacheTtl, type ClientIndexConfig, type ClientTransformConfig, type CodecFunc, type CombinedWarpBuilder, type CryptoProvider, type DetectionResult, type DetectionResultFromHtml, type ExecutionHandlers, type HttpAuthHeaders, type InterpolationBag, NodeCryptoProvider, type ProtocolName, type ResolvedInput, type SignableMessage, type TransformRunner, WARP_LANGUAGES, type Warp, type WarpAbi, type WarpAbiContents, type WarpAction, type WarpActionExecutionResult, type WarpActionExecutionStatus, type WarpActionIndex, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputPositionAssetObject, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, type WarpAdapterGenericRemoteTransaction, type WarpAdapterGenericTransaction, type WarpAdapterGenericType, type WarpAdapterGenericValue, type WarpAlert, type WarpAlertName, type WarpAlerts, type WarpBrand, WarpBrandBuilder, type WarpBrandColors, type WarpBrandCta, type WarpBrandLogo, type WarpBrandLogoThemed, type WarpBrandUrls, WarpBuilder, WarpCache, type WarpCacheConfig, WarpCacheKey, type WarpChain, type WarpChainAccount, type WarpChainAction, type WarpChainActionStatus, type WarpChainAsset, type WarpChainAssetValue, type WarpChainEnv, type WarpChainInfo, WarpChainName, WarpClient, type WarpClientConfig, type WarpCollectAction, type WarpCollectDestination, type WarpCollectDestinationHttp, WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractVerification, type WarpDataLoaderOptions, type WarpExecutable, type WarpExecutionMessages, type WarpExecutionNextInfo, type WarpExecutionOutput, WarpExecutor, type WarpExplorerName, WarpFactory, type WarpI18nText, type WarpIdentifierType, WarpIndex, WarpInputTypes, WarpInterpolator, type WarpLinkAction, WarpLinkBuilder, WarpLinkDetecter, type WarpLocale, WarpLogger, type WarpMessageName, type WarpMeta, type WarpNativeValue, type WarpOutputName, WarpProtocolVersions, type WarpProviderConfig, type WarpProviderPreferences, type WarpQueryAction, type WarpRegistryConfigInfo, type WarpRegistryInfo, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpSecret, WarpSerializer, type WarpStructValue, type WarpText, type WarpTransferAction, type WarpTrustStatus, type WarpTypeHandler, WarpTypeRegistry, type WarpUserWallets, WarpValidator, type WarpVarPlaceholder, type WarpWalletDetails, address, applyOutputToMessages, asset, biguint, bool, buildMappedOutput, buildNestedPayload, bytesToBase64, bytesToHex, cleanWarpIdentifier, createAuthHeaders, createAuthMessage, createCryptoProvider, createHttpAuthHeaders, createSignableMessage, createWarpI18nText, createWarpIdentifier, evaluateOutputCommon, extractCollectOutput, extractIdentifierInfoFromUrl, extractQueryStringFromIdentifier, extractQueryStringFromUrl, extractWarpSecrets, findWarpAdapterForChain, getCryptoProvider, getEventNameFromWarp, getLatestProtocolIdentifier, getNextInfo, getProviderConfig, getRandomBytes, getRandomHex, getWarpActionByIndex, getWarpBrandLogoUrl, getWarpInfoFromIdentifier, getWarpPrimaryAction, getWarpWalletAddress, getWarpWalletAddressFromConfig, getWarpWalletMnemonic, getWarpWalletMnemonicFromConfig, getWarpWalletPrivateKey, getWarpWalletPrivateKeyFromConfig, hasInputPrefix, hex, isEqualWarpIdentifier, isWarpActionAutoExecute, isWarpI18nText, mergeNestedPayload, option, parseOutputOutIndex, parseSignedMessage, replacePlaceholders, resolveWarpText, safeWindow, setCryptoProvider, shiftBigintBy, splitInput, string, struct, testCryptoAvailability, toInputPayloadValue, toPreviewText, tuple, uint16, uint32, uint64, uint8, validateSignedMessage, vector };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var nr=Object.create;var Y=Object.defineProperty;var ir=Object.getOwnPropertyDescriptor;var ar=Object.getOwnPropertyNames;var sr=Object.getPrototypeOf,or=Object.prototype.hasOwnProperty;var pr=(e,t)=>{for(var r in t)Y(e,r,{get:t[r],enumerable:!0})},Rt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ar(t))!or.call(e,i)&&i!==r&&Y(e,i,{get:()=>t[i],enumerable:!(n=ir(t,i))||n.enumerable});return e};var tt=(e,t,r)=>(r=e!=null?nr(sr(e)):{},Rt(t||!e||!e.__esModule?Y(r,"default",{value:e,enumerable:!0}):r,e)),cr=e=>Rt(Y({},"__esModule",{value:!0}),e);var _r={};pr(_r,{BrowserCryptoProvider:()=>rt,CacheTtl:()=>St,NodeCryptoProvider:()=>et,WARP_LANGUAGES:()=>Wr,WarpBrandBuilder:()=>Ct,WarpBuilder:()=>wt,WarpCache:()=>K,WarpCacheKey:()=>It,WarpChainName:()=>Bt,WarpClient:()=>Tt,WarpConfig:()=>R,WarpConstants:()=>p,WarpExecutor:()=>_,WarpFactory:()=>F,WarpIndex:()=>X,WarpInputTypes:()=>d,WarpInterpolator:()=>P,WarpLinkBuilder:()=>U,WarpLinkDetecter:()=>Z,WarpLogger:()=>v,WarpProtocolVersions:()=>O,WarpSerializer:()=>x,WarpTypeRegistry:()=>bt,WarpValidator:()=>G,address:()=>Dr,applyOutputToMessages:()=>Wt,asset:()=>vt,biguint:()=>Lr,bool:()=>jr,buildMappedOutput:()=>z,buildNestedPayload:()=>Nt,bytesToBase64:()=>fr,bytesToHex:()=>Vt,cleanWarpIdentifier:()=>k,createAuthHeaders:()=>pt,createAuthMessage:()=>ot,createCryptoProvider:()=>hr,createHttpAuthHeaders:()=>Er,createSignableMessage:()=>Lt,createWarpI18nText:()=>Ar,createWarpIdentifier:()=>it,evaluateOutputCommon:()=>Ht,extractCollectOutput:()=>st,extractIdentifierInfoFromUrl:()=>j,extractQueryStringFromIdentifier:()=>mt,extractQueryStringFromUrl:()=>ht,extractWarpSecrets:()=>mr,findWarpAdapterForChain:()=>g,getCryptoProvider:()=>ut,getEventNameFromWarp:()=>lr,getLatestProtocolIdentifier:()=>D,getNextInfo:()=>At,getProviderConfig:()=>Tr,getRandomBytes:()=>dt,getRandomHex:()=>ft,getWarpActionByIndex:()=>I,getWarpBrandLogoUrl:()=>ur,getWarpInfoFromIdentifier:()=>T,getWarpPrimaryAction:()=>L,getWarpWalletAddress:()=>jt,getWarpWalletAddressFromConfig:()=>S,getWarpWalletMnemonic:()=>qt,getWarpWalletMnemonicFromConfig:()=>$r,getWarpWalletPrivateKey:()=>Dt,getWarpWalletPrivateKeyFromConfig:()=>Vr,hasInputPrefix:()=>wr,hex:()=>qr,isEqualWarpIdentifier:()=>xr,isWarpActionAutoExecute:()=>nt,isWarpI18nText:()=>yr,mergeNestedPayload:()=>xt,option:()=>Mr,parseOutputOutIndex:()=>Ft,parseSignedMessage:()=>Br,replacePlaceholders:()=>B,resolveWarpText:()=>M,safeWindow:()=>lt,setCryptoProvider:()=>dr,shiftBigintBy:()=>q,splitInput:()=>at,string:()=>Or,struct:()=>zr,testCryptoAvailability:()=>gr,toInputPayloadValue:()=>Ut,toPreviewText:()=>gt,tuple:()=>kr,uint16:()=>Ur,uint32:()=>Hr,uint64:()=>Fr,uint8:()=>Nr,validateSignedMessage:()=>Rr,vector:()=>Gr});module.exports=cr(_r);var Bt=(c=>(c.Multiversx="multiversx",c.Vibechain="vibechain",c.Sui="sui",c.Ethereum="ethereum",c.Base="base",c.Arbitrum="arbitrum",c.Somnia="somnia",c.Fastset="fastset",c))(Bt||{}),p={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:e=>e.config.user?.wallets?.[e.chain.name]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:e=>e.chain.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:e=>e.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},d={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},lt=typeof window<"u"?window:{open:()=>{}};var O={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},R={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${O.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${O.Brand}.schema.json`,DefaultClientUrl:e=>e==="devnet"?"https://devnet.usewarp.to":e==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",p.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var lr=(e,t)=>{let r=e.alerts?.[t];if(!r)return null;let n=p.Alerts.TriggerEventPrefix+p.ArgParamsSeparator;if(!r.trigger.startsWith(n))return null;let i=r.trigger.replace(n,"");return i||null};var ur=(e,t)=>typeof e.logo=="string"?e.logo:e.logo[t?.scheme??"light"];var rt=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let r=new Uint8Array(t);return window.crypto.getRandomValues(r),r}},et=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let r=await import("crypto");return new Uint8Array(r.randomBytes(t))}catch(r){throw new Error(`Node.js crypto not available: ${r instanceof Error?r.message:"Unknown error"}`)}}},N=null;function ut(){if(N)return N;if(typeof window<"u"&&window.crypto)return N=new rt,N;if(typeof process<"u"&&process.versions?.node)return N=new et,N;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function dr(e){N=e}async function dt(e,t){if(e<=0||!Number.isInteger(e))throw new Error("Size must be a positive integer");return(t||ut()).getRandomBytes(e)}function Vt(e){if(!(e instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(e.length*2);for(let r=0;r<e.length;r++){let n=e[r];t[r*2]=(n>>>4).toString(16),t[r*2+1]=(n&15).toString(16)}return t.join("")}function fr(e){if(!(e instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(e).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(e));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function ft(e,t){if(e<=0||e%2!==0)throw new Error("Length must be a positive even number");let r=await dt(e/2,t);return Vt(r)}async function gr(){let e={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?e.environment="browser":typeof process<"u"&&process.versions?.node&&(e.environment="nodejs"),await dt(16),e.randomBytes=!0}catch{}return e}function hr(){return ut()}var mr=e=>Object.values(e.vars||{}).filter(t=>t.startsWith(`${p.Vars.Env}:`)).map(t=>{let r=t.replace(`${p.Vars.Env}:`,"").trim(),[n,i]=r.split(p.ArgCompositeSeparator);return{key:n,description:i||null}});var g=(e,t)=>{let r=t.find(n=>n.chainInfo.name.toLowerCase()===e.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${e}`);return r},D=e=>{if(e==="warp")return`warp:${O.Warp}`;if(e==="brand")return`brand:${O.Brand}`;if(e==="abi")return`abi:${O.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${e}`)},I=(e,t)=>e?.actions[t-1],L=e=>{if(e.actions.length===0)throw new Error(`Warp has no primary action: ${e.meta?.identifier}`);let t=e.actions.find(s=>s.primary===!0);if(t)return{action:t,index:e.actions.indexOf(t)};let r=["transfer","contract","query","collect"],n=e.actions.find(s=>r.includes(s.type));return n?{action:n,index:e.actions.indexOf(n)}:{action:e.actions[0],index:0}},nt=(e,t)=>{if(e.auto===!1)return!1;if(e.type==="link"){if(e.auto===!0)return!0;let{action:r}=L(t);return e===r}return!0},q=(e,t)=>{let r=e.toString(),[n,i=""]=r.split("."),s=Math.abs(t);if(t>0)return BigInt(n+i.padEnd(s,"0"));if(t<0){let a=n+i;if(s>=a.length)return 0n;let o=a.slice(0,-s)||"0";return BigInt(o)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},gt=(e,t=100)=>{if(!e)return"";let r=e.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r},B=(e,t)=>e.replace(/\{\{([^}]+)\}\}/g,(r,n)=>t[n]||"");var Wr={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},M=(e,t)=>{let r=t?.preferences?.locale||"en";if(typeof e=="string")return e;if(typeof e=="object"&&e!==null){if(r in e)return e[r];if("en"in e)return e.en;let n=Object.keys(e);if(n.length>0)return e[n[0]]}return""},yr=e=>typeof e=="object"&&e!==null&&Object.keys(e).length>0,Ar=e=>e;var k=e=>e.startsWith(p.IdentifierAliasMarker)?e.replace(p.IdentifierAliasMarker,""):e,xr=(e,t)=>!e||!t?!1:k(e)===k(t),it=(e,t,r)=>{let n=k(r);return t===p.IdentifierType.Alias?p.IdentifierAliasMarker+e+p.IdentifierParamSeparator+n:e+p.IdentifierParamSeparator+t+p.IdentifierParamSeparator+n},T=e=>{let t=decodeURIComponent(e).trim(),r=k(t),n=r.split("?")[0],i=$t(n);if(n.length===64&&/^[a-fA-F0-9]+$/.test(n))return{chain:p.IdentifierChainDefault,type:p.IdentifierType.Hash,identifier:r,identifierBase:n};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[s,a,o]=i;if(a===p.IdentifierType.Alias||a===p.IdentifierType.Hash){let c=r.includes("?")?o+r.substring(r.indexOf("?")):o;return{chain:s,type:a,identifier:c,identifierBase:o}}}if(i.length===2){let[s,a]=i;if(s===p.IdentifierType.Alias||s===p.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a;return{chain:p.IdentifierChainDefault,type:s,identifier:o,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==p.IdentifierType.Alias&&s!==p.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a,c=vr(a,s)?p.IdentifierType.Hash:p.IdentifierType.Alias;return{chain:s,type:c,identifier:o,identifierBase:a}}}return{chain:p.IdentifierChainDefault,type:p.IdentifierType.Alias,identifier:r,identifierBase:n}},j=e=>{let t=new URL(e),n=t.searchParams.get(p.IdentifierParamName);if(n||(n=t.pathname.split("/")[1]),!n)return null;let i=decodeURIComponent(n);return T(i)},vr=(e,t)=>/^[a-fA-F0-9]+$/.test(e)&&e.length>32,Cr=e=>{let t=p.IdentifierParamSeparator,r=e.indexOf(t);return r!==-1?{separator:t,index:r}:null},$t=e=>{let t=Cr(e);if(!t)return[e];let{separator:r,index:n}=t,i=e.substring(0,n),s=e.substring(n+r.length),a=$t(s);return[i,...a]},ht=e=>{try{let t=new URL(e),r=new URLSearchParams(t.search);return r.delete(p.IdentifierParamName),r.toString()||null}catch{return null}},mt=e=>{let t=e.indexOf("?");if(t===-1||t===e.length-1)return null;let r=e.substring(t+1);return r.length>0?r:null};var at=e=>{let[t,...r]=e.split(/:(.*)/,2);return[t,r[0]||""]},wr=e=>{let t=new Set(Object.values(d));if(!e.includes(p.ArgParamsSeparator))return!1;let r=at(e)[0];return t.has(r)};var Wt=(e,t,r)=>{let n=Object.entries(e.messages||{}).map(([i,s])=>{let a=M(s,r);return[i,B(a,t)]});return Object.fromEntries(n)};var Ot=tt(require("qr-code-styling"),1);var U=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!j(t):!1}build(t,r,n){let i=this.config.clientUrl||R.DefaultClientUrl(this.config.env),s=g(t,this.adapters),a=r===p.IdentifierType.Alias?n:r+p.IdentifierParamSeparator+n,o=s.chainInfo.name+p.IdentifierParamSeparator+a,c=encodeURIComponent(o);return R.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${p.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let r=T(t);if(!r)return null;let n=g(r.chain,this.adapters);return n?this.build(n.chainInfo.name,r.type,r.identifierBase):null}generateQrCode(t,r,n,i=512,s="white",a="black",o="#23F7DD"){let c=g(t,this.adapters),l=this.build(c.chainInfo.name,r,n);return new Ot.default({type:"svg",width:i,height:i,data:String(l),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Sr="https://",At=(e,t,r,n,i)=>{let s=r.actions?.[n-1]?.next||r.next||null;if(!s)return null;if(s.startsWith(Sr))return[{identifier:null,url:s}];let[a,o]=s.split("?");if(!o){let W=B(a,{...r.vars,...i});return[{identifier:W,url:yt(t,W,e)}]}let c=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let W=B(o,{...r.vars,...i}),y=W?`${a}?${W}`:a;return[{identifier:y,url:yt(t,y,e)}]}let l=c[0];if(!l)return[];let u=l.match(/{{([^[]+)\[\]/),f=u?u[1]:null;if(!f||i[f]===void 0)return[];let m=Array.isArray(i[f])?i[f]:[i[f]];if(m.length===0)return[];let h=c.filter(W=>W.includes(`{{${f}[]`)).map(W=>{let y=W.match(/\[\](\.[^}]+)?}}/),A=y&&y[1]||"";return{placeholder:W,field:A?A.slice(1):"",regex:new RegExp(W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return m.map(W=>{let y=o;for(let{regex:E,field:$}of h){let b=$?Ir(W,$):W;if(b==null)return null;y=y.replace(E,b)}if(y.includes("{{")||y.includes("}}"))return null;let A=y?`${a}?${y}`:a;return{identifier:A,url:yt(t,A,e)}}).filter(W=>W!==null)},yt=(e,t,r)=>{let[n,i]=t.split("?"),s=T(n)||{chain:p.IdentifierChainDefault,type:"alias",identifier:n,identifierBase:n},a=g(s.chain,e);if(!a)throw new Error(`Adapter not found for chain ${s.chain}`);let o=new U(r,e).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return o;let c=new URL(o);return new URLSearchParams(i).forEach((l,u)=>c.searchParams.set(u,l)),c.toString().replace(/\/\?/,"?")},Ir=(e,t)=>t.split(".").reduce((r,n)=>r?.[n],e);function Nt(e,t,r){return e.startsWith(p.Position.Payload)?e.slice(p.Position.Payload.length).split(".").reduceRight((n,i,s,a)=>({[i]:s===a.length-1?{[t]:r}:n}),{}):{[t]:r}}function xt(e,t){if(!e)return{...t};if(!t)return{...e};let r={...e};return Object.keys(t).forEach(n=>{r[n]&&typeof r[n]=="object"&&typeof t[n]=="object"?r[n]=xt(r[n],t[n]):r[n]=t[n]}),r}function Ut(e,t){if(!e.value)return null;let r=t.stringToNative(e.value)[1];if(e.input.type==="biguint")return r.toString();if(e.input.type==="asset"){let{identifier:n,amount:i}=r;return{identifier:n,amount:i.toString()}}else return r}function z(e,t){let r={};return e.forEach(n=>{let i=n.input.as||n.input.name,s=Ut(n,t);if(n.input.position&&n.input.position.startsWith(p.Position.Payload)){let a=Nt(n.input.position,i,s);r=xt(r,a)}else r[i]=s}),r}var Tr=(e,t,r,n)=>{let i=e.preferences?.providers?.[t];return i?.[r]?typeof i[r]=="string"?{url:i[r]}:i[r]:{url:n}};var H=class H{static debug(...t){H.isTestEnv||console.debug(...t)}static info(...t){H.isTestEnv||console.info(...t)}static warn(...t){H.isTestEnv||console.warn(...t)}static error(...t){H.isTestEnv||console.error(...t)}};H.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var v=H;var st=async(e,t,r,n,i,s)=>{let a=[],o=[],c={};for(let[u,f]of Object.entries(e.output||{})){if(f.startsWith(p.Transform.Prefix))continue;let m=Ft(f);if(m!==null&&m!==r){c[u]=null;continue}let[h,...w]=f.split("."),W=(y,A)=>A.reduce((E,$)=>E&&E[$]!==void 0?E[$]:null,y);if(h==="out"||h.startsWith("out[")){let y=w.length===0?t?.data||t:W(t,w);a.push(String(y)),o.push(y),c[u]=y}else c[u]=f}let l=z(n,i);return{values:{string:a,native:o,mapped:l},output:await Ht(e,c,r,n,i,s)}},Ht=async(e,t,r,n,i,s)=>{if(!e.output)return t;let a={...t};return a=br(a,e,r,n,i),a=await Pr(e,a,s.transform?.runner||null),a},br=(e,t,r,n,i)=>{let s={...e},a=I(t,r)?.inputs||[];for(let[o,c]of Object.entries(s))if(typeof c=="string"&&c.startsWith("in.")){let l=c.split(".")[1],u=a.findIndex(m=>m.as===l||m.name===l),f=u!==-1?n[u]?.value:null;s[o]=f?i.stringToNative(f)[1]:null}return s},Pr=async(e,t,r)=>{if(!e.output)return t;let n={...t},i=Object.entries(e.output).filter(([,s])=>s.startsWith(p.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(p.Transform.Prefix.length)}));if(i.length>0&&(!r||typeof r.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:s,code:a}of i)try{n[s]=await r.run(a,n)}catch(o){v.error(`Transform error for output '${s}':`,o),n[s]=null}return n},Ft=e=>{if(e==="out")return 1;let t=e.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(e.startsWith("out.")||e.startsWith("event."),null)};async function Lt(e,t,r,n=5){let i=await ft(64,r),s=new Date(Date.now()+n*60*1e3).toISOString();return{message:JSON.stringify({wallet:e,nonce:i,expiresAt:s,purpose:t}),nonce:i,expiresAt:s}}async function ot(e,t,r,n){let i=n||`prove-wallet-ownership for app "${t}"`;return Lt(e,i,r,5)}function pt(e,t,r,n){return{"X-Signer-Wallet":e,"X-Signer-Signature":t,"X-Signer-Nonce":r,"X-Signer-ExpiresAt":n}}async function Er(e,t,r,n){let{message:i,nonce:s,expiresAt:a}=await ot(e,r,n),o=await t(i);return pt(e,o,s,a)}function Rr(e){let t=new Date(e).getTime();return Date.now()<t}function Br(e){try{let t=JSON.parse(e);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var jt=e=>e?typeof e=="string"?e:e.address:null,S=(e,t)=>jt(e.user?.wallets?.[t]||null),Dt=e=>e?typeof e=="string"?e:e.privateKey:null,qt=e=>e?typeof e=="string"?e:e.mnemonic:null,Vr=(e,t)=>Dt(e.user?.wallets?.[t]||null)?.trim()||null,$r=(e,t)=>qt(e.user?.wallets?.[t]||null)?.trim()||null;var x=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,r){if(t===d.Tuple&&Array.isArray(r)){if(r.length===0)return t+p.ArgParamsSeparator;if(r.every(n=>typeof n=="string"&&n.includes(p.ArgParamsSeparator))){let n=r.map(a=>this.getTypeAndValue(a)),i=n.map(([a])=>a),s=n.map(([,a])=>a);return`${t}(${i.join(p.ArgCompositeSeparator)})${p.ArgParamsSeparator}${s.join(p.ArgListSeparator)}`}return t+p.ArgParamsSeparator+r.join(p.ArgListSeparator)}if(t===d.Struct&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let n=r;if(!n._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=n._name,s=Object.keys(n).filter(o=>o!=="_name");if(s.length===0)return`${t}(${i})${p.ArgParamsSeparator}`;let a=s.map(o=>{let[c,l]=this.getTypeAndValue(n[o]);return`(${o}${p.ArgParamsSeparator}${c})${l}`});return`${t}(${i})${p.ArgParamsSeparator}${a.join(p.ArgListSeparator)}`}if(t===d.Vector&&Array.isArray(r)){if(r.length===0)return`${t}${p.ArgParamsSeparator}`;if(r.every(n=>typeof n=="string"&&n.includes(p.ArgParamsSeparator))){let n=r[0],i=n.indexOf(p.ArgParamsSeparator),s=n.substring(0,i),a=r.map(c=>{let l=c.indexOf(p.ArgParamsSeparator),u=c.substring(l+1);return s.startsWith(d.Tuple)?u.replace(p.ArgListSeparator,p.ArgCompositeSeparator):u}),o=s.startsWith(d.Struct)?p.ArgStructSeparator:p.ArgListSeparator;return t+p.ArgParamsSeparator+s+p.ArgParamsSeparator+a.join(o)}return t+p.ArgParamsSeparator+r.join(p.ArgListSeparator)}if(t===d.Asset&&typeof r=="object"&&r&&"identifier"in r&&"amount"in r)return"decimals"in r?d.Asset+p.ArgParamsSeparator+r.identifier+p.ArgCompositeSeparator+String(r.amount)+p.ArgCompositeSeparator+String(r.decimals):d.Asset+p.ArgParamsSeparator+r.identifier+p.ArgCompositeSeparator+String(r.amount);if(this.typeRegistry){let n=this.typeRegistry.getHandler(t);if(n)return n.nativeToString(r);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,r)}return t+p.ArgParamsSeparator+(r?.toString()??"")}stringToNative(t){let r=t.split(p.ArgParamsSeparator),n=r[0],i=r.slice(1).join(p.ArgParamsSeparator);if(n==="null")return[n,null];if(n===d.Option){let[s,a]=i.split(p.ArgParamsSeparator);return[d.Option+p.ArgParamsSeparator+s,a||null]}if(n===d.Vector){let s=i.indexOf(p.ArgParamsSeparator),a=i.substring(0,s),o=i.substring(s+1),c=a.startsWith(d.Struct)?p.ArgStructSeparator:p.ArgListSeparator,u=(o?o.split(c):[]).map(f=>this.stringToNative(a+p.ArgParamsSeparator+f)[1]);return[d.Vector+p.ArgParamsSeparator+a,u]}else if(n.startsWith(d.Tuple)){let s=n.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=i.split(p.ArgCompositeSeparator).map((c,l)=>this.stringToNative(`${s[l]}${p.IdentifierParamSeparator}${c}`)[1]);return[n,o]}else if(n.startsWith(d.Struct)){let s=n.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let o={_name:s[1]};return i&&i.split(p.ArgListSeparator).forEach(c=>{let l=c.match(new RegExp(`^\\(([^${p.ArgParamsSeparator}]+)${p.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(l){let[,u,f,m]=l;o[u]=this.stringToNative(`${f}${p.IdentifierParamSeparator}${m}`)[1]}}),[n,o]}else{if(n===d.String)return[n,i];if(n===d.Uint8||n===d.Uint16||n===d.Uint32)return[n,Number(i)];if(n===d.Uint64||n===d.Uint128||n===d.Uint256||n===d.Biguint)return[n,BigInt(i||0)];if(n===d.Bool)return[n,i==="true"];if(n===d.Address)return[n,i];if(n===d.Hex)return[n,i];if(n===d.Asset){let[s,a]=i.split(p.ArgCompositeSeparator),o={identifier:s,amount:BigInt(a)};return[n,o]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(n);if(s){let o=s.stringToNative(i);return[n,o]}let a=this.typeRegistry.resolveType(n);if(a!==n){let[o,c]=this.stringToNative(`${a}:${i}`);return[n,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${n}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(p.ArgParamsSeparator)){let[r,n]=t.split(p.ArgParamsSeparator);return[r,n]}return typeof t=="number"?[d.Uint32,t]:typeof t=="bigint"?[d.Uint64,t]:typeof t=="boolean"?[d.Bool,t]:[typeof t,t]}};var Or=e=>new x().nativeToString(d.String,e),Nr=e=>new x().nativeToString(d.Uint8,e),Ur=e=>new x().nativeToString(d.Uint16,e),Hr=e=>new x().nativeToString(d.Uint32,e),Fr=e=>new x().nativeToString(d.Uint64,e),Lr=e=>new x().nativeToString(d.Biguint,e),jr=e=>new x().nativeToString(d.Bool,e),Dr=e=>new x().nativeToString(d.Address,e),vt=e=>new x().nativeToString(d.Asset,e),qr=e=>new x().nativeToString(d.Hex,e),Mr=(e,t)=>{if(t===null)return d.Option+p.ArgParamsSeparator;let r=e(t),n=r.indexOf(p.ArgParamsSeparator),i=r.substring(0,n),s=r.substring(n+1);return d.Option+p.ArgParamsSeparator+i+p.ArgParamsSeparator+s},kr=(...e)=>new x().nativeToString(d.Tuple,e),zr=e=>new x().nativeToString(d.Struct,e),Gr=e=>new x().nativeToString(d.Vector,e);var Mt=tt(require("ajv"),1);var Ct=class{constructor(t){this.pendingBrand={protocol:D("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,r=!0){let n=JSON.parse(t);return r&&await this.ensureValidSchema(n),n}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,r){if(!t)throw new Error(`Warp: ${r}`)}ensureWarpText(t,r){if(!t)throw new Error(`Warp: ${r}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.schema?.brand||R.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),s=new Mt.default,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};var kt=tt(require("ajv"),1);var G=class{constructor(t){this.config=t;this.config=t}async validate(t){let r=[];return r.push(...this.validatePrimaryAction(t)),r.push(...this.validateMaxOneValuePosition(t)),r.push(...this.validateVariableNamesAndResultNamesUppercase(t)),r.push(...this.validateAbiIsSetIfApplicable(t)),r.push(...await this.validateSchema(t)),{valid:r.length===0,errors:r}}validatePrimaryAction(t){try{let{action:r}=L(t);return r?[]:["Primary action is required"]}catch(r){return[r instanceof Error?r.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(n=>n.inputs?n.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],n=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&r.push(`${s} name '${a}' must be uppercase`)})};return n(t.vars,"Variable"),n(t.output,"Output"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(a=>a.type==="contract"),n=t.actions.some(a=>a.type==="query");if(!r&&!n)return[];let i=t.actions.some(a=>a.abi),s=Object.values(t.output||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.output&&!i&&s?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||R.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),s=new kt.default({strict:!1}),a=s.compile(i);return a(t)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var wt=class{constructor(t){this.config=t;this.pendingWarp={protocol:D("warp"),chain:"",name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,r=!0){let n=JSON.parse(t);return r&&await this.validate(n),n}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,r=100){return gt(t,r)}ensure(t,r){if(!t)throw new Error(r)}ensureWarpText(t,r){if(!t)throw new Error(r);if(typeof t=="object"&&!t.en)throw new Error(r)}async validate(t){let n=await new G(this.config).validate(t);if(!n.valid)throw new Error(n.errors.join(`
2
- `))}};var J=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let r=localStorage.getItem(this.getKey(t));if(!r)return null;let n=JSON.parse(r,Qr);return Date.now()>n.expiresAt?(localStorage.removeItem(this.getKey(t)),null):n.value}catch{return null}}set(t,r,n){let i={value:r,expiresAt:Date.now()+n*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,Jr))}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)}}},zt=new x,Jr=(e,t)=>typeof t=="bigint"?zt.nativeToString("biguint",t):t,Qr=(e,t)=>typeof t=="string"&&t.startsWith(d.Biguint+":")?zt.stringToNative(t)[1]:t;var V=class V{get(t){let r=V.cache.get(t);return r?Date.now()>r.expiresAt?(V.cache.delete(t),null):r.value:null}set(t,r,n){let i=Date.now()+n*1e3;V.cache.set(t,{value:r,expiresAt:i})}forget(t){V.cache.delete(t)}clear(){V.cache.clear()}};V.cache=new Map;var Q=V;var St={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},It={Warp:(e,t)=>`warp:${e}:${t}`,WarpAbi:(e,t)=>`warp-abi:${e}:${t}`,WarpExecutable:(e,t,r)=>`warp-exec:${e}:${t}:${r}`,RegistryInfo:(e,t)=>`registry-info:${e}:${t}`,Brand:(e,t)=>`brand:${e}:${t}`,Asset:(e,t,r)=>`asset:${e}:${t}:${r}`},K=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new J:t==="memory"?new Q:typeof window<"u"&&window.localStorage?new J:new Q}set(t,r,n){this.strategy.set(t,r,n)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var P=class{constructor(t,r){this.config=t;this.adapter=r}async apply(t,r,n={}){let i=this.applyVars(t,r,n);return await this.applyGlobals(t,i)}async applyGlobals(t,r){let n={...r};return n.actions=await Promise.all(n.actions.map(async i=>await this.applyActionGlobals(i))),n=await this.applyRootGlobals(n,t),n}applyVars(t,r,n={}){if(!r?.vars)return r;let i=S(t,this.adapter.chainInfo.name),s=JSON.stringify(r),a=(o,c)=>{s=s.replace(new RegExp(`{{${o.toUpperCase()}}}`,"g"),c.toString())};return Object.entries(r.vars).forEach(([o,c])=>{if(typeof c!="string")a(o,c);else if(c.startsWith(p.Vars.Query+p.ArgParamsSeparator)){let l=c.slice(p.Vars.Query.length+1),[u,f]=l.split(p.ArgCompositeSeparator),m=t.currentUrl?new URLSearchParams(t.currentUrl.split("?")[1]).get(u):null,w=n.queries?.[u]||null||m;w&&a(o,w)}else if(c.startsWith(p.Vars.Env+p.ArgParamsSeparator)){let l=c.slice(p.Vars.Env.length+1),[u,f]=l.split(p.ArgCompositeSeparator),h={...t.vars,...n.envs}?.[u];h&&a(o,h)}else c===p.Source.UserWallet&&i?a(o,i):a(o,c)}),JSON.parse(s)}async applyRootGlobals(t,r){let n=JSON.stringify(t),i={config:r,chain:this.adapter.chainInfo};return Object.values(p.Globals).forEach(s=>{let a=s.Accessor(i);a!=null&&(n=n.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),a.toString()))}),JSON.parse(n)}async applyActionGlobals(t){let r=JSON.stringify(t),n={config:this.config,chain:this.adapter.chainInfo};return Object.values(p.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}applyInputs(t,r,n,i){if(!t||typeof t!="string")return t;let s={};return r.forEach(a=>{if(!a.value)return;let o=a.input.as||a.input.name,[,c]=n.stringToNative(a.value);s[o]=String(c)}),i&&i.forEach(a=>{if(!a.value)return;let o=a.input.as||a.input.name,[,c]=n.stringToNative(a.value);s[`primary.${o}`]=String(c)}),B(t,s)}};var F=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 x,this.cache=new K(t.cache?.type)}getSerializer(){return this.serializer}async createExecutable(t,r,n,i={}){let s=I(t,r);if(!s)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,n),o=g(a.name,this.adapters),c=new P(this.config,o),l=await c.apply(this.config,t,i),u=I(l,r),{action:f,index:m}=L(l),h=this.getStringTypedInputs(f,n),w=await this.getResolvedInputs(a.name,f,h),W=this.getModifiedInputs(w),y=[],A=[];m===r-1&&(y=w,A=W);let E=A.find(C=>C.input.position==="receiver"||C.input.position==="destination")?.value,$=this.getDestinationFromAction(u),b=E?this.serializer.stringToNative(E)[1]:$;if(b&&(b=c.applyInputs(b,A,this.serializer,W)),!b&&s.type!=="collect")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let ct=this.getPreparedArgs(u,A);ct=ct.map(C=>c.applyInputs(C,A,this.serializer,W));let Gt=A.find(C=>C.input.position==="value")?.value||null,Jt="value"in u?u.value:null,Qt=Gt?.split(p.ArgParamsSeparator)[1]||Jt||"0",Kt=c.applyInputs(Qt,A,this.serializer,W),_t=BigInt(Kt),Xt=A.filter(C=>C.input.position==="transfer"&&C.value).map(C=>C.value),Zt=[...("transfers"in u?u.transfers:[])||[],...Xt||[]].map(C=>{let er=c.applyInputs(C,A,this.serializer,W);return this.serializer.stringToNative(er)[1]}),Yt=A.find(C=>C.input.position==="data")?.value,tr="data"in u?u.data||"":null,Pt=Yt||tr||null,rr=Pt?c.applyInputs(Pt,A,this.serializer,W):null,Et={warp:l,chain:a,action:r,destination:b,args:ct,value:_t,transfers:Zt,data:rr,resolvedInputs:A};return this.cache.set(It.WarpExecutable(this.config.env,l.meta?.hash||"",r),Et.resolvedInputs,St.OneWeek),Et}async getChainInfoForWarp(t,r){if(t.chain)return g(t.chain,this.adapters).chainInfo;if(r){let i=await this.tryGetChainFromInputs(t,r);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,r){let n=t.inputs||[];return r.map((i,s)=>{let a=n[s];return!a||i.includes(p.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,r,n){let i=r.inputs||[],s=await Promise.all(n.map(o=>this.preprocessInput(t,o))),a=(o,c)=>{if(o.source==="query"){let l=this.url.searchParams.get(o.name);return l?this.serializer.nativeToString(o.type,l):null}else if(o.source===p.Source.UserWallet){let l=S(this.config,t);return l?this.serializer.nativeToString("address",l):null}else return o.source==="hidden"?o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null:s[c]||null};return i.map((o,c)=>{let l=a(o,c);return{input:o,value:l||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(t){return t.map((r,n)=>{if(r.input.modifier?.startsWith("scale:")){let[,i]=r.input.modifier.split(":");if(isNaN(Number(i))){let s=Number(t.find(c=>c.input.name===i)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let a=r.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=q(a,+s);return{...r,value:`${r.input.type}:${o}`}}else{let s=r.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let a=q(s,+i);return{...r,value:`${r.input.type}:${a}`}}}else return r})}async preprocessInput(t,r){try{let[n,i]=at(r),s=g(t,this.adapters);if(n==="asset"){let[a,o,c]=i.split(p.ArgCompositeSeparator);if(c)return r;let l=await s.dataLoader.getAsset(a);if(!l)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof l.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=q(o,l.decimals);return vt({...l,amount:u})}else return r}catch(n){throw v.warn("WarpFactory: Preprocess input failed",n),n}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,r){let n="args"in t?t.args||[]:[];return r.forEach(({input:i,value:s})=>{if(!s||!i.position?.startsWith("arg:"))return;let a=Number(i.position.split(":")[1])-1;n.splice(a,0,s)}),n}async tryGetChainFromInputs(t,r){let n=t.actions.find(c=>c.inputs?.some(l=>l.position==="chain"));if(!n)return null;let i=n.inputs?.findIndex(c=>c.position==="chain");if(i===-1||i===void 0)return null;let s=r[i];if(!s)throw new Error("Chain input not found");let a=this.serializer.stringToNative(s)[1];return g(a,this.adapters).chainInfo}};var _=class{constructor(t,r,n){this.config=t;this.adapters=r;this.handlers=n;this.handlers=n,this.factory=new F(t,r)}async execute(t,r,n={}){let i=[],s=null,a=[];for(let o=1;o<=t.actions.length;o++){let c=I(t,o);if(!nt(c,t))continue;let{tx:l,chain:u,immediateExecution:f}=await this.executeAction(t,o,r,n);l&&i.push(l),u&&(s=u),f&&a.push(f)}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let o=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(o))}return{txs:i,chain:s,immediateExecutions:a}}async executeAction(t,r,n,i={}){let s=I(t,r);if(s.type==="link")return await this.callHandler(async()=>{let l=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(l):lt.open(l,"_blank")}),{tx:null,chain:null,immediateExecution:null};let a=await this.factory.createExecutable(t,r,n,i);if(s.type==="collect"){let l=await this.executeCollect(a);return l.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l}):l.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l}):(this.handlers?.onError?.({message:JSON.stringify(l.values)}),{tx:null,chain:null,immediateExecution:null})}let o=g(a.chain.name,this.adapters);if(s.type==="query"){let l=await o.executor.executeQuery(a);return l.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:l,tx:null})):this.handlers?.onError?.({message:JSON.stringify(l.values)}),{tx:null,chain:a.chain,immediateExecution:l}}return{tx:await o.executor.createTransaction(a),chain:a.chain,immediateExecution:null}}async evaluateOutput(t,r){if(r.length===0||t.actions.length===0||!this.handlers)return;let n=await this.factory.getChainInfoForWarp(t),i=g(n.name,this.adapters),s=(await Promise.all(t.actions.map(async(a,o)=>{if(!nt(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let c=r[o],l=o+1,u=await i.output.getActionExecution(t,l,c);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:l,chain:n,execution:u,tx:c})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values)})),u}))).filter(a=>a!==null);if(s.every(a=>a.status==="success")){let a=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(a))}else await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(s.map(a=>a.values))}`}))}async executeCollect(t,r){let n=S(this.config,t.chain.name),i=I(t.warp,t.action),s=this.factory.getSerializer(),a=z(t.resolvedInputs,s);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,n,a,r);let{values:o,output:c}=await st(t.warp,a,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,n,"unhandled",o,c)}async doHttpRequest(t,r,n,i,s){let a=new P(this.config,g(t.chain.name,this.adapters)),o=new Headers;if(o.set("Content-Type","application/json"),o.set("Accept","application/json"),this.handlers?.onSignRequest){if(!n)throw new Error(`No wallet configured for chain ${t.chain.name}`);let{message:f,nonce:m,expiresAt:h}=await ot(n,`${t.chain.name}-adapter`),w=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:f,chain:t.chain}));if(w){let W=pt(n,w,m,h);Object.entries(W).forEach(([y,A])=>o.set(y,A))}}r.headers&&Object.entries(r.headers).forEach(([f,m])=>{let h=a.applyInputs(m,t.resolvedInputs,this.factory.getSerializer());o.set(f,h)});let c=r.method||"GET",l=c==="GET"?void 0:JSON.stringify({...i,...s}),u=a.applyInputs(r.url,t.resolvedInputs,this.factory.getSerializer());v.debug("WarpExecutor: Executing HTTP collect",{url:u,method:c,headers:o,body:l});try{let f=await fetch(u,{method:c,headers:o,body:l});v.debug("Collect response status",{status:f.status});let m=await f.json();v.debug("Collect response content",{content:m});let{values:h,output:w}=await st(t.warp,m,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),f.ok?"success":"error",h,w,m)}catch(f){return v.error("WarpActionExecutor: Error executing collect",f),{status:"error",warp:t.warp,action:t.action,user:n,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t)}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(n=>n.input.position==="receiver"||n.input.position==="destination")?.value||t.destination}buildCollectResult(t,r,n,i,s,a){let o=At(this.config,this.adapters,t.warp,t.action,s);return{status:n,warp:t.warp,action:t.action,user:r||S(this.config,t.chain.name),txHash:null,tx:null,next:o,values:i,output:a?{...s,_DATA:a}:s,messages:Wt(t.warp,s,this.config),destination:this.getDestinationFromResolvedInputs(t)}}async callHandler(t){if(t)return await t()}};var X=class{constructor(t){this.config=t}async search(t,r,n){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...n},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...r})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw v.error("WarpIndex: Error searching for warps: ",i),i}}};var Z=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!j(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),a=(await Promise.all(i)).filter(l=>l.match),o=a.length>0,c=a.map(l=>({url:l.url,warp:l.warp}));return{match:o,output:c}}async detect(t,r){let n={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(p.HttpProtocolPrefix)?j(t):T(t);if(!i)return n;try{let{type:s,identifierBase:a}=i,o=null,c=null,l=null,u=g(i.chain,this.adapters),f=t.startsWith(p.HttpProtocolPrefix)?ht(t):mt(i.identifier);if(s==="hash"){o=await u.builder().createFromTransactionHash(a,r);let h=await u.registry.getInfoByHash(a,r);c=h.registryInfo,l=h.brand}else if(s==="alias"){let h=await u.registry.getInfoByAlias(a,r);c=h.registryInfo,l=h.brand,h.registryInfo&&(o=await u.builder().createFromTransactionHash(h.registryInfo.hash,r))}o&&o.meta&&(Kr(o,u.chainInfo.name,c,i.identifier),o.meta.query=f);let m=o?await new P(this.config,u).apply(this.config,o):null;return m?{match:!0,url:t,warp:m,chain:u.chainInfo.name,registryInfo:c,brand:l}:n}catch(s){return v.error("Error detecting warp link",s),n}}},Kr=(e,t,r,n)=>{e.meta&&(e.meta.identifier=r?.alias?it(t,"alias",r.alias):it(t,"hash",r?.hash??n))};var Tt=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}getAdapters(){return this.adapters}addAdapter(t){return this.adapters.push(t),this}createExecutor(t){return new _(this.config,this.adapters,t)}async detectWarp(t,r){return new Z(this.config,this.adapters).detect(t,r)}async executeWarp(t,r,n,i={}){let s=typeof t=="object",a=!s&&t.startsWith("http")&&t.endsWith(".json"),o=s?t:null;if(!o&&a){let h=await fetch(t);if(!h.ok)throw new Error("WarpClient: executeWarp - invalid url");o=await h.json()}if(o||(o=(await this.detectWarp(t,i.cache)).warp),!o)throw new Error("Warp not found");let c=this.createExecutor(n),{txs:l,chain:u,immediateExecutions:f}=await c.execute(o,r,{queries:i.queries});return{txs:l,chain:u,immediateExecutions:f,evaluateOutput:async h=>{await c.evaluateOutput(o,h)}}}async createInscriptionTransaction(t,r){return await g(t,this.adapters).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,n=!1){return g(t,this.adapters).builder().createFromTransaction(r,n)}async createFromTransactionHash(t,r){let n=T(t);if(!n)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return g(n.chain,this.adapters).builder().createFromTransactionHash(t,r)}async signMessage(t,r){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return g(t,this.adapters).wallet.signMessage(r)}async getActions(t,r,n=!1){let i=this.getDataLoader(t);return(await Promise.all(r.map(async a=>i.getAction(a,n)))).filter(a=>a!==null)}getExplorer(t){return g(t,this.adapters).explorer}getOutput(t){return g(t,this.adapters).output}async getRegistry(t){let r=g(t,this.adapters).registry;return await r.init(),r}getDataLoader(t){return g(t,this.adapters).dataLoader}getWallet(t){return g(t,this.adapters).wallet}get factory(){return new F(this.config,this.adapters)}get index(){return new X(this.config)}get linkBuilder(){return new U(this.config,this.adapters)}createBuilder(t){return g(t,this.adapters).builder()}createAbiBuilder(t){return g(t,this.adapters).abiBuilder()}createBrandBuilder(t){return g(t,this.adapters).brandBuilder()}createSerializer(t){return g(t,this.adapters).serializer}resolveText(t){return M(t,this.config)}};var bt=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,r){this.typeHandlers.set(t,r)}registerTypeAlias(t,r){this.typeAliases.set(t,r)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let r=this.typeAliases.get(t);return r?this.getHandler(r):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let r=this.typeAliases.get(t);return r?this.resolveType(r):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};0&&(module.exports={BrowserCryptoProvider,CacheTtl,NodeCryptoProvider,WARP_LANGUAGES,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,evaluateOutputCommon,extractCollectOutput,extractIdentifierInfoFromUrl,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,hasInputPrefix,hex,isEqualWarpIdentifier,isWarpActionAutoExecute,isWarpI18nText,mergeNestedPayload,option,parseOutputOutIndex,parseSignedMessage,replacePlaceholders,resolveWarpText,safeWindow,setCryptoProvider,shiftBigintBy,splitInput,string,struct,testCryptoAvailability,toInputPayloadValue,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateSignedMessage,vector});
1
+ "use strict";var nr=Object.create;var Y=Object.defineProperty;var ir=Object.getOwnPropertyDescriptor;var ar=Object.getOwnPropertyNames;var sr=Object.getPrototypeOf,or=Object.prototype.hasOwnProperty;var pr=(n,t)=>{for(var r in t)Y(n,r,{get:t[r],enumerable:!0})},Rt=(n,t,r,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ar(t))!or.call(n,i)&&i!==r&&Y(n,i,{get:()=>t[i],enumerable:!(e=ir(t,i))||e.enumerable});return n};var tt=(n,t,r)=>(r=n!=null?nr(sr(n)):{},Rt(t||!n||!n.__esModule?Y(r,"default",{value:n,enumerable:!0}):r,n)),cr=n=>Rt(Y({},"__esModule",{value:!0}),n);var _r={};pr(_r,{BrowserCryptoProvider:()=>rt,CacheTtl:()=>St,NodeCryptoProvider:()=>et,WARP_LANGUAGES:()=>Wr,WarpBrandBuilder:()=>Ct,WarpBuilder:()=>wt,WarpCache:()=>K,WarpCacheKey:()=>It,WarpChainName:()=>Bt,WarpClient:()=>bt,WarpConfig:()=>R,WarpConstants:()=>o,WarpExecutor:()=>_,WarpFactory:()=>L,WarpIndex:()=>X,WarpInputTypes:()=>d,WarpInterpolator:()=>P,WarpLinkBuilder:()=>H,WarpLinkDetecter:()=>Z,WarpLogger:()=>C,WarpProtocolVersions:()=>N,WarpSerializer:()=>v,WarpTypeRegistry:()=>Tt,WarpValidator:()=>G,address:()=>Dr,applyOutputToMessages:()=>Wt,asset:()=>vt,biguint:()=>Lr,bool:()=>jr,buildMappedOutput:()=>M,buildNestedPayload:()=>Nt,bytesToBase64:()=>fr,bytesToHex:()=>$t,cleanWarpIdentifier:()=>z,createAuthHeaders:()=>pt,createAuthMessage:()=>ot,createCryptoProvider:()=>hr,createHttpAuthHeaders:()=>Er,createSignableMessage:()=>Lt,createWarpI18nText:()=>Ar,createWarpIdentifier:()=>it,evaluateOutputCommon:()=>Ht,extractCollectOutput:()=>st,extractIdentifierInfoFromUrl:()=>j,extractQueryStringFromIdentifier:()=>mt,extractQueryStringFromUrl:()=>ht,extractWarpSecrets:()=>mr,findWarpAdapterForChain:()=>g,getCryptoProvider:()=>ut,getEventNameFromWarp:()=>lr,getLatestProtocolIdentifier:()=>D,getNextInfo:()=>At,getProviderConfig:()=>br,getRandomBytes:()=>dt,getRandomHex:()=>ft,getWarpActionByIndex:()=>I,getWarpBrandLogoUrl:()=>ur,getWarpInfoFromIdentifier:()=>b,getWarpPrimaryAction:()=>B,getWarpWalletAddress:()=>jt,getWarpWalletAddressFromConfig:()=>S,getWarpWalletMnemonic:()=>qt,getWarpWalletMnemonicFromConfig:()=>Vr,getWarpWalletPrivateKey:()=>Dt,getWarpWalletPrivateKeyFromConfig:()=>$r,hasInputPrefix:()=>wr,hex:()=>qr,isEqualWarpIdentifier:()=>xr,isWarpActionAutoExecute:()=>nt,isWarpI18nText:()=>yr,mergeNestedPayload:()=>xt,option:()=>kr,parseOutputOutIndex:()=>Ft,parseSignedMessage:()=>Br,replacePlaceholders:()=>$,resolveWarpText:()=>k,safeWindow:()=>lt,setCryptoProvider:()=>dr,shiftBigintBy:()=>q,splitInput:()=>at,string:()=>Or,struct:()=>Mr,testCryptoAvailability:()=>gr,toInputPayloadValue:()=>Ut,toPreviewText:()=>gt,tuple:()=>zr,uint16:()=>Ur,uint32:()=>Hr,uint64:()=>Fr,uint8:()=>Nr,validateSignedMessage:()=>Rr,vector:()=>Gr});module.exports=cr(_r);var Bt=(p=>(p.Multiversx="multiversx",p.Vibechain="vibechain",p.Sui="sui",p.Ethereum="ethereum",p.Base="base",p.Arbitrum="arbitrum",p.Somnia="somnia",p.Fastset="fastset",p))(Bt||{}),o={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.adapter.chainInfo.name]},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:n=>{if(!n.adapter.wallet)return null;try{return n.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:n=>n.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},d={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},lt=typeof window<"u"?window:{open:()=>{}};var N={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},R={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${N.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${N.Brand}.schema.json`,DefaultClientUrl:n=>n==="devnet"?"https://devnet.usewarp.to":n==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",o.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var lr=(n,t)=>{let r=n.alerts?.[t];if(!r)return null;let e=o.Alerts.TriggerEventPrefix+o.ArgParamsSeparator;if(!r.trigger.startsWith(e))return null;let i=r.trigger.replace(e,"");return i||null};var ur=(n,t)=>typeof n.logo=="string"?n.logo:n.logo[t?.scheme??"light"];var rt=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let r=new Uint8Array(t);return window.crypto.getRandomValues(r),r}},et=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let r=await import("crypto");return new Uint8Array(r.randomBytes(t))}catch(r){throw new Error(`Node.js crypto not available: ${r instanceof Error?r.message:"Unknown error"}`)}}},U=null;function ut(){if(U)return U;if(typeof window<"u"&&window.crypto)return U=new rt,U;if(typeof process<"u"&&process.versions?.node)return U=new et,U;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function dr(n){U=n}async function dt(n,t){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(t||ut()).getRandomBytes(n)}function $t(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(n.length*2);for(let r=0;r<n.length;r++){let e=n[r];t[r*2]=(e>>>4).toString(16),t[r*2+1]=(e&15).toString(16)}return t.join("")}function fr(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(n).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(n));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function ft(n,t){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let r=await dt(n/2,t);return $t(r)}async function gr(){let n={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?n.environment="browser":typeof process<"u"&&process.versions?.node&&(n.environment="nodejs"),await dt(16),n.randomBytes=!0}catch{}return n}function hr(){return ut()}var mr=n=>Object.values(n.vars||{}).filter(t=>t.startsWith(`${o.Vars.Env}:`)).map(t=>{let r=t.replace(`${o.Vars.Env}:`,"").trim(),[e,i]=r.split(o.ArgCompositeSeparator);return{key:e,description:i||null}});var g=(n,t)=>{let r=t.find(e=>e.chainInfo.name.toLowerCase()===n.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${n}`);return r},D=n=>{if(n==="warp")return`warp:${N.Warp}`;if(n==="brand")return`brand:${N.Brand}`;if(n==="abi")return`abi:${N.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},I=(n,t)=>n?.actions[t-1],B=n=>{if(n.actions.length===0)throw new Error(`Warp has no primary action: ${n.meta?.identifier}`);let t=n.actions.find(s=>s.primary===!0);if(t)return{action:t,index:n.actions.indexOf(t)};let r=["transfer","contract","query","collect"],e=n.actions.find(s=>r.includes(s.type));return e?{action:e,index:n.actions.indexOf(e)}:{action:n.actions[0],index:0}},nt=(n,t)=>{if(n.auto===!1)return!1;if(n.type==="link"){if(n.auto===!0)return!0;let{action:r}=B(t);return n===r}return!0},q=(n,t)=>{let r=n.toString(),[e,i=""]=r.split("."),s=Math.abs(t);if(t>0)return BigInt(e+i.padEnd(s,"0"));if(t<0){let a=e+i;if(s>=a.length)return 0n;let c=a.slice(0,-s)||"0";return BigInt(c)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},gt=(n,t=100)=>{if(!n)return"";let r=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r},$=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||"");var Wr={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},k=(n,t)=>{let r=t?.preferences?.locale||"en";if(typeof n=="string")return n;if(typeof n=="object"&&n!==null){if(r in n)return n[r];if("en"in n)return n.en;let e=Object.keys(n);if(e.length>0)return n[e[0]]}return""},yr=n=>typeof n=="object"&&n!==null&&Object.keys(n).length>0,Ar=n=>n;var z=n=>n.startsWith(o.IdentifierAliasMarker)?n.replace(o.IdentifierAliasMarker,""):n,xr=(n,t)=>!n||!t?!1:z(n)===z(t),it=(n,t,r)=>{let e=z(r);return t===o.IdentifierType.Alias?o.IdentifierAliasMarker+n+o.IdentifierParamSeparator+e:n+o.IdentifierParamSeparator+t+o.IdentifierParamSeparator+e},b=n=>{let t=decodeURIComponent(n).trim(),r=z(t),e=r.split("?")[0],i=Vt(e);if(e.length===64&&/^[a-fA-F0-9]+$/.test(e))return{chain:o.IdentifierChainDefault,type:o.IdentifierType.Hash,identifier:r,identifierBase:e};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[s,a,c]=i;if(a===o.IdentifierType.Alias||a===o.IdentifierType.Hash){let p=r.includes("?")?c+r.substring(r.indexOf("?")):c;return{chain:s,type:a,identifier:p,identifierBase:c}}}if(i.length===2){let[s,a]=i;if(s===o.IdentifierType.Alias||s===o.IdentifierType.Hash){let c=r.includes("?")?a+r.substring(r.indexOf("?")):a;return{chain:o.IdentifierChainDefault,type:s,identifier:c,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==o.IdentifierType.Alias&&s!==o.IdentifierType.Hash){let c=r.includes("?")?a+r.substring(r.indexOf("?")):a,p=vr(a,s)?o.IdentifierType.Hash:o.IdentifierType.Alias;return{chain:s,type:p,identifier:c,identifierBase:a}}}return{chain:o.IdentifierChainDefault,type:o.IdentifierType.Alias,identifier:r,identifierBase:e}},j=n=>{let t=new URL(n),e=t.searchParams.get(o.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let i=decodeURIComponent(e);return b(i)},vr=(n,t)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,Cr=n=>{let t=o.IdentifierParamSeparator,r=n.indexOf(t);return r!==-1?{separator:t,index:r}:null},Vt=n=>{let t=Cr(n);if(!t)return[n];let{separator:r,index:e}=t,i=n.substring(0,e),s=n.substring(e+r.length),a=Vt(s);return[i,...a]},ht=n=>{try{let t=new URL(n),r=new URLSearchParams(t.search);return r.delete(o.IdentifierParamName),r.toString()||null}catch{return null}},mt=n=>{let t=n.indexOf("?");if(t===-1||t===n.length-1)return null;let r=n.substring(t+1);return r.length>0?r:null};var at=n=>{let[t,...r]=n.split(/:(.*)/,2);return[t,r[0]||""]},wr=n=>{let t=new Set(Object.values(d));if(!n.includes(o.ArgParamsSeparator))return!1;let r=at(n)[0];return t.has(r)};var Wt=(n,t,r)=>{let e=Object.entries(n.messages||{}).map(([i,s])=>{let a=k(s,r);return[i,$(a,t)]});return Object.fromEntries(e)};var Ot=tt(require("qr-code-styling"),1);var H=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(o.HttpProtocolPrefix)?!!j(t):!1}build(t,r,e){let i=this.config.clientUrl||R.DefaultClientUrl(this.config.env),s=g(t,this.adapters),a=r===o.IdentifierType.Alias?e:r+o.IdentifierParamSeparator+e,c=s.chainInfo.name+o.IdentifierParamSeparator+a,p=encodeURIComponent(c);return R.SuperClientUrls.includes(i)?`${i}/${p}`:`${i}?${o.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(t){let r=b(t);if(!r)return null;let e=g(r.chain,this.adapters);return e?this.build(e.chainInfo.name,r.type,r.identifierBase):null}generateQrCode(t,r,e,i=512,s="white",a="black",c="#23F7DD"){let p=g(t,this.adapters),l=this.build(p.chainInfo.name,r,e);return new Ot.default({type:"svg",width:i,height:i,data:String(l),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(c)}" 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 Sr="https://",At=(n,t,r,e,i)=>{let s=r.actions?.[e-1]?.next||r.next||null;if(!s)return null;if(s.startsWith(Sr))return[{identifier:null,url:s}];let[a,c]=s.split("?");if(!c){let m=$(a,{...r.vars,...i});return[{identifier:m,url:yt(t,m,n)}]}let p=c.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let m=$(c,{...r.vars,...i}),y=m?`${a}?${m}`:a;return[{identifier:y,url:yt(t,y,n)}]}let l=p[0];if(!l)return[];let u=l.match(/{{([^[]+)\[\]/),f=u?u[1]:null;if(!f||i[f]===void 0)return[];let h=Array.isArray(i[f])?i[f]:[i[f]];if(h.length===0)return[];let W=p.filter(m=>m.includes(`{{${f}[]`)).map(m=>{let y=m.match(/\[\](\.[^}]+)?}}/),x=y&&y[1]||"";return{placeholder:m,field:x?x.slice(1):"",regex:new RegExp(m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(m=>{let y=c;for(let{regex:E,field:O}of W){let T=O?Ir(m,O):m;if(T==null)return null;y=y.replace(E,T)}if(y.includes("{{")||y.includes("}}"))return null;let x=y?`${a}?${y}`:a;return{identifier:x,url:yt(t,x,n)}}).filter(m=>m!==null)},yt=(n,t,r)=>{let[e,i]=t.split("?"),s=b(e)||{chain:o.IdentifierChainDefault,type:"alias",identifier:e,identifierBase:e},a=g(s.chain,n);if(!a)throw new Error(`Adapter not found for chain ${s.chain}`);let c=new H(r,n).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return c;let p=new URL(c);return new URLSearchParams(i).forEach((l,u)=>p.searchParams.set(u,l)),p.toString().replace(/\/\?/,"?")},Ir=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);function Nt(n,t,r){return n.startsWith(o.Position.Payload)?n.slice(o.Position.Payload.length).split(".").reduceRight((e,i,s,a)=>({[i]:s===a.length-1?{[t]:r}:e}),{}):{[t]:r}}function xt(n,t){if(!n)return{...t};if(!t)return{...n};let r={...n};return Object.keys(t).forEach(e=>{r[e]&&typeof r[e]=="object"&&typeof t[e]=="object"?r[e]=xt(r[e],t[e]):r[e]=t[e]}),r}function Ut(n,t){if(!n.value)return null;let r=t.stringToNative(n.value)[1];if(n.input.type==="biguint")return r.toString();if(n.input.type==="asset"){let{identifier:e,amount:i}=r;return{identifier:e,amount:i.toString()}}else return r}function M(n,t){let r={};return n.forEach(e=>{let i=e.input.as||e.input.name,s=Ut(e,t);if(e.input.position&&typeof e.input.position=="string"&&e.input.position.startsWith(o.Position.Payload)){let a=Nt(e.input.position,i,s);r=xt(r,a)}else r[i]=s}),r}var br=(n,t,r,e)=>{let i=n.preferences?.providers?.[t];return i?.[r]?typeof i[r]=="string"?{url:i[r]}:i[r]:{url:e}};var F=class F{static debug(...t){F.isTestEnv||console.debug(...t)}static info(...t){F.isTestEnv||console.info(...t)}static warn(...t){F.isTestEnv||console.warn(...t)}static error(...t){F.isTestEnv||console.error(...t)}};F.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=F;var st=async(n,t,r,e,i,s)=>{let a=[],c=[],p={};for(let[u,f]of Object.entries(n.output||{})){if(f.startsWith(o.Transform.Prefix))continue;let h=Ft(f);if(h!==null&&h!==r){p[u]=null;continue}let[W,...A]=f.split("."),m=(y,x)=>x.reduce((E,O)=>E&&E[O]!==void 0?E[O]:null,y);if(W==="out"||W.startsWith("out[")){let y=A.length===0?t?.data||t:m(t,A);a.push(String(y)),c.push(y),p[u]=y}else p[u]=f}let l=M(e,i);return{values:{string:a,native:c,mapped:l},output:await Ht(n,p,r,e,i,s)}},Ht=async(n,t,r,e,i,s)=>{if(!n.output)return t;let a={...t};return a=Tr(a,n,r,e,i),a=await Pr(n,a,s.transform?.runner||null),a},Tr=(n,t,r,e,i)=>{let s={...n},a=I(t,r)?.inputs||[];for(let[c,p]of Object.entries(s))if(typeof p=="string"&&p.startsWith("in.")){let l=p.split(".")[1],u=a.findIndex(h=>h.as===l||h.name===l),f=u!==-1?e[u]?.value:null;s[c]=f?i.stringToNative(f)[1]:null}return s},Pr=async(n,t,r)=>{if(!n.output)return t;let e={...t},i=Object.entries(n.output).filter(([,s])=>s.startsWith(o.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(o.Transform.Prefix.length)}));if(i.length>0&&(!r||typeof r.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:s,code:a}of i)try{e[s]=await r.run(a,e)}catch(c){C.error(`Transform error for output '${s}':`,c),e[s]=null}return e},Ft=n=>{if(n==="out")return 1;let t=n.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};async function Lt(n,t,r,e=5){let i=await ft(64,r),s=new Date(Date.now()+e*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:i,expiresAt:s,purpose:t}),nonce:i,expiresAt:s}}async function ot(n,t,r,e){let i=e||`prove-wallet-ownership for app "${t}"`;return Lt(n,i,r,5)}function pt(n,t,r,e){return{"X-Signer-Wallet":n,"X-Signer-Signature":t,"X-Signer-Nonce":r,"X-Signer-ExpiresAt":e}}async function Er(n,t,r,e){let{message:i,nonce:s,expiresAt:a}=await ot(n,r,e),c=await t(i);return pt(n,c,s,a)}function Rr(n){let t=new Date(n).getTime();return Date.now()<t}function Br(n){try{let t=JSON.parse(n);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var jt=n=>n?typeof n=="string"?n:n.address:null,S=(n,t)=>jt(n.user?.wallets?.[t]||null),Dt=n=>n?typeof n=="string"?n:n.privateKey:null,qt=n=>n?typeof n=="string"?n:n.mnemonic:null,$r=(n,t)=>Dt(n.user?.wallets?.[t]||null)?.trim()||null,Vr=(n,t)=>qt(n.user?.wallets?.[t]||null)?.trim()||null;var v=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,r){if(t===d.Tuple&&Array.isArray(r)){if(r.length===0)return t+o.ArgParamsSeparator;if(r.every(e=>typeof e=="string"&&e.includes(o.ArgParamsSeparator))){let e=r.map(a=>this.getTypeAndValue(a)),i=e.map(([a])=>a),s=e.map(([,a])=>a);return`${t}(${i.join(o.ArgCompositeSeparator)})${o.ArgParamsSeparator}${s.join(o.ArgListSeparator)}`}return t+o.ArgParamsSeparator+r.join(o.ArgListSeparator)}if(t===d.Struct&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let e=r;if(!e._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=e._name,s=Object.keys(e).filter(c=>c!=="_name");if(s.length===0)return`${t}(${i})${o.ArgParamsSeparator}`;let a=s.map(c=>{let[p,l]=this.getTypeAndValue(e[c]);return`(${c}${o.ArgParamsSeparator}${p})${l}`});return`${t}(${i})${o.ArgParamsSeparator}${a.join(o.ArgListSeparator)}`}if(t===d.Vector&&Array.isArray(r)){if(r.length===0)return`${t}${o.ArgParamsSeparator}`;if(r.every(e=>typeof e=="string"&&e.includes(o.ArgParamsSeparator))){let e=r[0],i=e.indexOf(o.ArgParamsSeparator),s=e.substring(0,i),a=r.map(p=>{let l=p.indexOf(o.ArgParamsSeparator),u=p.substring(l+1);return s.startsWith(d.Tuple)?u.replace(o.ArgListSeparator,o.ArgCompositeSeparator):u}),c=s.startsWith(d.Struct)?o.ArgStructSeparator:o.ArgListSeparator;return t+o.ArgParamsSeparator+s+o.ArgParamsSeparator+a.join(c)}return t+o.ArgParamsSeparator+r.join(o.ArgListSeparator)}if(t===d.Asset&&typeof r=="object"&&r&&"identifier"in r&&"amount"in r)return"decimals"in r?d.Asset+o.ArgParamsSeparator+r.identifier+o.ArgCompositeSeparator+String(r.amount)+o.ArgCompositeSeparator+String(r.decimals):d.Asset+o.ArgParamsSeparator+r.identifier+o.ArgCompositeSeparator+String(r.amount);if(this.typeRegistry){let e=this.typeRegistry.getHandler(t);if(e)return e.nativeToString(r);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,r)}return t+o.ArgParamsSeparator+(r?.toString()??"")}stringToNative(t){let r=t.split(o.ArgParamsSeparator),e=r[0],i=r.slice(1).join(o.ArgParamsSeparator);if(e==="null")return[e,null];if(e===d.Option){let[s,a]=i.split(o.ArgParamsSeparator);return[d.Option+o.ArgParamsSeparator+s,a||null]}if(e===d.Vector){let s=i.indexOf(o.ArgParamsSeparator),a=i.substring(0,s),c=i.substring(s+1),p=a.startsWith(d.Struct)?o.ArgStructSeparator:o.ArgListSeparator,u=(c?c.split(p):[]).map(f=>this.stringToNative(a+o.ArgParamsSeparator+f)[1]);return[d.Vector+o.ArgParamsSeparator+a,u]}else if(e.startsWith(d.Tuple)){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(o.ArgCompositeSeparator),c=i.split(o.ArgCompositeSeparator).map((p,l)=>this.stringToNative(`${s[l]}${o.IdentifierParamSeparator}${p}`)[1]);return[e,c]}else if(e.startsWith(d.Struct)){let s=e.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let c={_name:s[1]};return i&&i.split(o.ArgListSeparator).forEach(p=>{let l=p.match(new RegExp(`^\\(([^${o.ArgParamsSeparator}]+)${o.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(l){let[,u,f,h]=l;c[u]=this.stringToNative(`${f}${o.IdentifierParamSeparator}${h}`)[1]}}),[e,c]}else{if(e===d.String)return[e,i];if(e===d.Uint8||e===d.Uint16||e===d.Uint32)return[e,Number(i)];if(e===d.Uint64||e===d.Uint128||e===d.Uint256||e===d.Biguint)return[e,BigInt(i||0)];if(e===d.Bool)return[e,i==="true"];if(e===d.Address)return[e,i];if(e===d.Hex)return[e,i];if(e===d.Asset){let[s,a]=i.split(o.ArgCompositeSeparator),c={identifier:s,amount:BigInt(a)};return[e,c]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(e);if(s){let c=s.stringToNative(i);return[e,c]}let a=this.typeRegistry.resolveType(e);if(a!==e){let[c,p]=this.stringToNative(`${a}:${i}`);return[e,p]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(o.ArgParamsSeparator)){let[r,e]=t.split(o.ArgParamsSeparator);return[r,e]}return typeof t=="number"?[d.Uint32,t]:typeof t=="bigint"?[d.Uint64,t]:typeof t=="boolean"?[d.Bool,t]:[typeof t,t]}};var Or=n=>new v().nativeToString(d.String,n),Nr=n=>new v().nativeToString(d.Uint8,n),Ur=n=>new v().nativeToString(d.Uint16,n),Hr=n=>new v().nativeToString(d.Uint32,n),Fr=n=>new v().nativeToString(d.Uint64,n),Lr=n=>new v().nativeToString(d.Biguint,n),jr=n=>new v().nativeToString(d.Bool,n),Dr=n=>new v().nativeToString(d.Address,n),vt=n=>new v().nativeToString(d.Asset,n),qr=n=>new v().nativeToString(d.Hex,n),kr=(n,t)=>{if(t===null)return d.Option+o.ArgParamsSeparator;let r=n(t),e=r.indexOf(o.ArgParamsSeparator),i=r.substring(0,e),s=r.substring(e+1);return d.Option+o.ArgParamsSeparator+i+o.ArgParamsSeparator+s},zr=(...n)=>new v().nativeToString(d.Tuple,n),Mr=n=>new v().nativeToString(d.Struct,n),Gr=n=>new v().nativeToString(d.Vector,n);var kt=tt(require("ajv"),1);var Ct=class{constructor(t){this.pendingBrand={protocol:D("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),e}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,r){if(!t)throw new Error(`Warp: ${r}`)}ensureWarpText(t,r){if(!t)throw new Error(`Warp: ${r}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.schema?.brand||R.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),s=new kt.default,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};var zt=tt(require("ajv"),1);var G=class{constructor(t){this.config=t;this.config=t}async validate(t){let r=[];return r.push(...this.validatePrimaryAction(t)),r.push(...this.validateMaxOneValuePosition(t)),r.push(...this.validateVariableNamesAndResultNamesUppercase(t)),r.push(...this.validateAbiIsSetIfApplicable(t)),r.push(...await this.validateSchema(t)),{valid:r.length===0,errors:r}}validatePrimaryAction(t){try{let{action:r}=B(t);return r?[]:["Primary action is required"]}catch(r){return[r instanceof Error?r.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(e=>e.inputs?e.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&r.push(`${s} name '${a}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.output,"Output"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(a=>a.type==="contract"),e=t.actions.some(a=>a.type==="query");if(!r&&!e)return[];let i=t.actions.some(a=>a.abi),s=Object.values(t.output||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.output&&!i&&s?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||R.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),s=new zt.default({strict:!1}),a=s.compile(i);return a(t)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var wt=class{constructor(t){this.config=t;this.pendingWarp={protocol:D("warp"),chain:"",name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.validate(e),e}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,r=100){return gt(t,r)}ensure(t,r){if(!t)throw new Error(r)}ensureWarpText(t,r){if(!t)throw new Error(r);if(typeof t=="object"&&!t.en)throw new Error(r)}async validate(t){let e=await new G(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
2
+ `))}};var J=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,Qr);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(t)),null):e.value}catch{return null}}set(t,r,e){let i={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,Jr))}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)}}},Mt=new v,Jr=(n,t)=>typeof t=="bigint"?Mt.nativeToString("biguint",t):t,Qr=(n,t)=>typeof t=="string"&&t.startsWith(d.Biguint+":")?Mt.stringToNative(t)[1]:t;var V=class V{get(t){let r=V.cache.get(t);return r?Date.now()>r.expiresAt?(V.cache.delete(t),null):r.value:null}set(t,r,e){let i=Date.now()+e*1e3;V.cache.set(t,{value:r,expiresAt:i})}forget(t){V.cache.delete(t)}clear(){V.cache.clear()}};V.cache=new Map;var Q=V;var St={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},It={Warp:(n,t)=>`warp:${n}:${t}`,WarpAbi:(n,t)=>`warp-abi:${n}:${t}`,WarpExecutable:(n,t,r)=>`warp-exec:${n}:${t}:${r}`,RegistryInfo:(n,t)=>`registry-info:${n}:${t}`,Brand:(n,t)=>`brand:${n}:${t}`,Asset:(n,t,r)=>`asset:${n}:${t}:${r}`},K=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new J:t==="memory"?new Q:typeof window<"u"&&window.localStorage?new J:new Q}set(t,r,e){this.strategy.set(t,r,e)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var P=class{constructor(t,r){this.config=t;this.adapter=r}async apply(t,r,e={}){let i=this.applyVars(t,r,e);return await this.applyGlobals(t,i)}async applyGlobals(t,r){let e={...r};return e.actions=await Promise.all(e.actions.map(async i=>await this.applyActionGlobals(i))),e=await this.applyRootGlobals(e,t),e}applyVars(t,r,e={}){if(!r?.vars)return r;let i=S(t,this.adapter.chainInfo.name),s=JSON.stringify(r),a=(c,p)=>{s=s.replace(new RegExp(`{{${c.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(r.vars).forEach(([c,p])=>{if(typeof p!="string")a(c,p);else if(p.startsWith(o.Vars.Query+o.ArgParamsSeparator)){let l=p.slice(o.Vars.Query.length+1),[u,f]=l.split(o.ArgCompositeSeparator),h=t.currentUrl?new URLSearchParams(t.currentUrl.split("?")[1]).get(u):null,A=e.queries?.[u]||null||h;A&&a(c,A)}else if(p.startsWith(o.Vars.Env+o.ArgParamsSeparator)){let l=p.slice(o.Vars.Env.length+1),[u,f]=l.split(o.ArgCompositeSeparator),W={...t.vars,...e.envs}?.[u];W&&a(c,W)}else p===o.Source.UserWallet&&i?a(c,i):a(c,p)}),JSON.parse(s)}async applyRootGlobals(t,r){let e=JSON.stringify(t),i={config:r,adapter:this.adapter};return Object.values(o.Globals).forEach(s=>{let a=s.Accessor(i);a!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),a.toString()))}),JSON.parse(e)}async applyActionGlobals(t){let r=JSON.stringify(t),e={config:this.config,adapter:this.adapter};return Object.values(o.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}applyInputs(t,r,e,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let s=this.applyGlobalsToText(t),a=this.buildInputBag(r,e,i);return $(s,a)}applyGlobalsToText(t){if(!Object.values(o.Globals).map(a=>a.Placeholder).some(a=>t.includes(`{{${a}}}`)))return t;let i={config:this.config,adapter:this.adapter},s=t;return Object.values(o.Globals).forEach(a=>{let c=a.Accessor(i);c!=null&&(s=s.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),c.toString()))}),s}buildInputBag(t,r,e){let i={};return t.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,c]=r.stringToNative(s.value);i[a]=String(c)}),e&&e.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,c]=r.stringToNative(s.value);if(i[`primary.${a}`]=String(c),s.input.type==="asset"&&typeof s.input.position=="object"){let p=c;p&&typeof p=="object"&&"identifier"in p&&"amount"in p&&(i[`primary.${a}.token`]=String(p.identifier),i[`primary.${a}.amount`]=String(p.amount))}}),i}};var L=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 v,this.cache=new K(t.cache?.type)}getSerializer(){return this.serializer}async createExecutable(t,r,e,i={}){let s=I(t,r);if(!s)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,e),c=g(a.name,this.adapters),p=new P(this.config,c),l=await p.apply(this.config,t,i),u=I(l,r),{action:f,index:h}=B(l),W=this.getStringTypedInputs(f,e),A=await this.getResolvedInputs(a.name,f,W,p),m=this.getModifiedInputs(A),y=[],x=[];h===r-1&&(y=A,x=m);let E=x.find(w=>w.input.position==="receiver"||w.input.position==="destination")?.value,O=this.getDestinationFromAction(u),T=E?this.serializer.stringToNative(E)[1]:O;if(T&&(T=p.applyInputs(T,x,this.serializer,m)),!T&&s.type!=="collect")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let ct=this.getPreparedArgs(u,x);ct=ct.map(w=>p.applyInputs(w,x,this.serializer,m));let Gt=x.find(w=>w.input.position==="value")?.value||null,Jt="value"in u?u.value:null,Qt=Gt?.split(o.ArgParamsSeparator)[1]||Jt||"0",Kt=p.applyInputs(Qt,x,this.serializer,m),_t=BigInt(Kt),Xt=x.filter(w=>w.input.position==="transfer"&&w.value).map(w=>w.value),Zt=[...("transfers"in u?u.transfers:[])||[],...Xt||[]].map(w=>{let er=p.applyInputs(w,x,this.serializer,m);return this.serializer.stringToNative(er)[1]}),Yt=x.find(w=>w.input.position==="data")?.value,tr="data"in u?u.data||"":null,Pt=Yt||tr||null,rr=Pt?p.applyInputs(Pt,x,this.serializer,m):null,Et={warp:l,chain:a,action:r,destination:T,args:ct,value:_t,transfers:Zt,data:rr,resolvedInputs:x};return this.cache.set(It.WarpExecutable(this.config.env,l.meta?.hash||"",r),Et.resolvedInputs,St.OneWeek),Et}async getChainInfoForWarp(t,r){if(t.chain)return g(t.chain,this.adapters).chainInfo;if(r){let i=await this.tryGetChainFromInputs(t,r);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,r){let e=t.inputs||[];return r.map((i,s)=>{let a=e[s];return!a||i.includes(o.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,r,e,i){let s=r.inputs||[],a=await Promise.all(e.map(p=>this.preprocessInput(t,p))),c=(p,l)=>{if(p.source==="query"){let u=this.url.searchParams.get(p.name);return u?this.serializer.nativeToString(p.type,u):null}else if(p.source===o.Source.UserWallet){let u=S(this.config,t);return u?this.serializer.nativeToString("address",u):null}else if(p.source==="hidden"){if(p.default===void 0)return null;let u=i?i.applyInputs(String(p.default),[],this.serializer):String(p.default);return this.serializer.nativeToString(p.type,u)}else return a[l]||null};return s.map((p,l)=>{let u=c(p,l),f=p.default!==void 0?i?i.applyInputs(String(p.default),[],this.serializer):String(p.default):void 0;return{input:p,value:u||(f!==void 0?this.serializer.nativeToString(p.type,f):null)}})}getModifiedInputs(t){return t.map((r,e)=>{if(r.input.modifier?.startsWith("scale:")){let[,i]=r.input.modifier.split(":");if(isNaN(Number(i))){let s=Number(t.find(p=>p.input.name===i)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let a=r.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let c=q(a,+s);return{...r,value:`${r.input.type}:${c}`}}else{let s=r.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let a=q(s,+i);return{...r,value:`${r.input.type}:${a}`}}}else return r})}async preprocessInput(t,r){try{let[e,i]=at(r),s=g(t,this.adapters);if(e==="asset"){let[a,c,p]=i.split(o.ArgCompositeSeparator);if(p)return r;let l=await s.dataLoader.getAsset(a);if(!l)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof l.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=q(c,l.decimals);return vt({...l,amount:u})}else return r}catch(e){throw C.warn("WarpFactory: Preprocess input failed",e),e}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,r){let e="args"in t?t.args||[]:[],i=[];return r.forEach(({input:s,value:a})=>{if(!(!a||!s.position)){if(typeof s.position=="object"){if(s.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${s.name}" has type "${s.type}"`);if(!s.position.token?.startsWith("arg:")||!s.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${s.name}"`);let[c,p]=this.serializer.stringToNative(a),l=p;if(!l||typeof l!="object"||!("identifier"in l)||!("amount"in l))throw new Error(`WarpFactory: Invalid asset value for input "${s.name}"`);let u=Number(s.position.token.split(":")[1])-1,f=Number(s.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",l.identifier)}),i.push({index:f,value:this.serializer.nativeToString("uint256",l.amount)})}else if(s.position.startsWith("arg:")){let c=Number(s.position.split(":")[1])-1;i.push({index:c,value:a})}}}),i.forEach(({index:s,value:a})=>{for(;e.length<=s;)e.push(void 0);e[s]=a}),e.filter(s=>s!==void 0)}async tryGetChainFromInputs(t,r){let e=t.actions.find(p=>p.inputs?.some(l=>l.position==="chain"));if(!e)return null;let i=e.inputs?.findIndex(p=>p.position==="chain");if(i===-1||i===void 0)return null;let s=r[i];if(!s)throw new Error("Chain input not found");let a=this.serializer.stringToNative(s)[1];return g(a,this.adapters).chainInfo}};var _=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.handlers=e,this.factory=new L(t,r)}async execute(t,r,e={}){let i=[],s=null,a=[],c=[],{action:p,index:l}=B(t);for(let u=1;u<=t.actions.length;u++){let f=I(t,u);if(!nt(f,t))continue;let{tx:h,chain:W,immediateExecution:A,executable:m}=await this.executeAction(t,u,r,e);h&&i.push(h),W&&(s=W),A&&a.push(A),m&&u===l+1&&m.resolvedInputs&&(c=m.resolvedInputs.map(y=>y.value||"").filter(y=>y!==""))}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let u=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(u))}return{txs:i,chain:s,immediateExecutions:a,resolvedInputs:c}}async executeAction(t,r,e,i={}){let s=I(t,r);if(s.type==="link")return await this.callHandler(async()=>{let l=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(l):lt.open(l,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null};let a=await this.factory.createExecutable(t,r,e,i);if(s.type==="collect"){let l=await this.executeCollect(a);return l.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):l.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(l.values)}),{tx:null,chain:null,immediateExecution:null,executable:a})}let c=g(a.chain.name,this.adapters);if(s.type==="query"){let l=await c.executor.executeQuery(a);return l.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:l,tx:null})):this.handlers?.onError?.({message:JSON.stringify(l.values)}),{tx:null,chain:a.chain,immediateExecution:l,executable:a}}return{tx:await c.executor.createTransaction(a),chain:a.chain,immediateExecution:null,executable:a}}async evaluateOutput(t,r){if(r.length===0||t.actions.length===0||!this.handlers)return;let e=await this.factory.getChainInfoForWarp(t),i=g(e.name,this.adapters),s=(await Promise.all(t.actions.map(async(a,c)=>{if(!nt(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let p=r[c],l=c+1;if(!p){let f={status:"error",warp:t,action:l,user:S(this.config,e.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${l} failed: Transaction not found`})),f}let u=await i.output.getActionExecution(t,l,p);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:l,chain:e,execution:u,tx:p})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values)})),u}))).filter(a=>a!==null);if(s.every(a=>a.status==="success")){let a=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(a))}else await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(s.map(a=>a.values))}`}))}async executeCollect(t,r){let e=S(this.config,t.chain.name),i=I(t.warp,t.action),s=this.factory.getSerializer(),a=M(t.resolvedInputs,s);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,e,a,r);let{values:c,output:p}=await st(t.warp,a,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,e,"unhandled",c,p)}async doHttpRequest(t,r,e,i,s){let a=new P(this.config,g(t.chain.name,this.adapters)),c=new Headers;if(c.set("Content-Type","application/json"),c.set("Accept","application/json"),this.handlers?.onSignRequest){if(!e)throw new Error(`No wallet configured for chain ${t.chain.name}`);let{message:f,nonce:h,expiresAt:W}=await ot(e,`${t.chain.name}-adapter`),A=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:f,chain:t.chain}));if(A){let m=pt(e,A,h,W);Object.entries(m).forEach(([y,x])=>c.set(y,x))}}r.headers&&Object.entries(r.headers).forEach(([f,h])=>{let W=a.applyInputs(h,t.resolvedInputs,this.factory.getSerializer());c.set(f,W)});let p=r.method||"GET",l=p==="GET"?void 0:JSON.stringify({...i,...s}),u=a.applyInputs(r.url,t.resolvedInputs,this.factory.getSerializer());C.debug("WarpExecutor: Executing HTTP collect",{url:u,method:p,headers:c,body:l});try{let f=await fetch(u,{method:p,headers:c,body:l});C.debug("Collect response status",{status:f.status});let h=await f.json();C.debug("Collect response content",{content:h});let{values:W,output:A}=await st(t.warp,h,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),f.ok?"success":"error",W,A,h)}catch(f){return C.error("WarpActionExecutor: Error executing collect",f),{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t)}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(e=>e.input.position==="receiver"||e.input.position==="destination")?.value||t.destination}buildCollectResult(t,r,e,i,s,a){let c=At(this.config,this.adapters,t.warp,t.action,s);return{status:e,warp:t.warp,action:t.action,user:r||S(this.config,t.chain.name),txHash:null,tx:null,next:c,values:i,output:a?{...s,_DATA:a}:s,messages:Wt(t.warp,s,this.config),destination:this.getDestinationFromResolvedInputs(t)}}async callHandler(t){if(t)return await t()}};var X=class{constructor(t){this.config=t}async search(t,r,e){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...e},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...r})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw C.error("WarpIndex: Error searching for warps: ",i),i}}};var Z=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(o.HttpProtocolPrefix)?!!j(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),a=(await Promise.all(i)).filter(l=>l.match),c=a.length>0,p=a.map(l=>({url:l.url,warp:l.warp}));return{match:c,output:p}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(o.HttpProtocolPrefix)?j(t):b(t);if(!i)return e;try{let{type:s,identifierBase:a}=i,c=null,p=null,l=null,u=g(i.chain,this.adapters),f=t.startsWith(o.HttpProtocolPrefix)?ht(t):mt(i.identifier);if(s==="hash"){c=await u.builder().createFromTransactionHash(a,r);let W=await u.registry.getInfoByHash(a,r);p=W.registryInfo,l=W.brand}else if(s==="alias"){let W=await u.registry.getInfoByAlias(a,r);p=W.registryInfo,l=W.brand,W.registryInfo&&(c=await u.builder().createFromTransactionHash(W.registryInfo.hash,r))}c&&c.meta&&(Kr(c,u.chainInfo.name,p,i.identifier),c.meta.query=f);let h=c?await new P(this.config,u).apply(this.config,c):null;return h?{match:!0,url:t,warp:h,chain:u.chainInfo.name,registryInfo:p,brand:l}:e}catch(s){return C.error("Error detecting warp link",s),e}}},Kr=(n,t,r,e)=>{n.meta&&(n.meta.identifier=r?.alias?it(t,"alias",r.alias):it(t,"hash",r?.hash??e))};var bt=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}getAdapters(){return this.adapters}addAdapter(t){return this.adapters.push(t),this}createExecutor(t){return new _(this.config,this.adapters,t)}async detectWarp(t,r){return new Z(this.config,this.adapters).detect(t,r)}async executeWarp(t,r,e,i={}){let s=typeof t=="object",a=!s&&t.startsWith("http")&&t.endsWith(".json"),c=s?t:null;if(!c&&a){let A=await fetch(t);if(!A.ok)throw new Error("WarpClient: executeWarp - invalid url");c=await A.json()}if(c||(c=(await this.detectWarp(t,i.cache)).warp),!c)throw new Error("Warp not found");let p=this.createExecutor(e),{txs:l,chain:u,immediateExecutions:f,resolvedInputs:h}=await p.execute(c,r,{queries:i.queries});return{txs:l,chain:u,immediateExecutions:f,evaluateOutput:async A=>{await p.evaluateOutput(c,A)},resolvedInputs:h}}async createInscriptionTransaction(t,r){return await g(t,this.adapters).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return g(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 g(e.chain,this.adapters).builder().createFromTransactionHash(t,r)}async signMessage(t,r){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return g(t,this.adapters).wallet.signMessage(r)}async getActions(t,r,e=!1){let i=this.getDataLoader(t);return(await Promise.all(r.map(async a=>i.getAction(a,e)))).filter(a=>a!==null)}getExplorer(t){return g(t,this.adapters).explorer}getOutput(t){return g(t,this.adapters).output}async getRegistry(t){let r=g(t,this.adapters).registry;return await r.init(),r}getDataLoader(t){return g(t,this.adapters).dataLoader}getWallet(t){return g(t,this.adapters).wallet}get factory(){return new L(this.config,this.adapters)}get index(){return new X(this.config)}get linkBuilder(){return new H(this.config,this.adapters)}createBuilder(t){return g(t,this.adapters).builder()}createAbiBuilder(t){return g(t,this.adapters).abiBuilder()}createBrandBuilder(t){return g(t,this.adapters).brandBuilder()}createSerializer(t){return g(t,this.adapters).serializer}resolveText(t){return k(t,this.config)}};var Tt=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,r){this.typeHandlers.set(t,r)}registerTypeAlias(t,r){this.typeAliases.set(t,r)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let r=this.typeAliases.get(t);return r?this.getHandler(r):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let r=this.typeAliases.get(t);return r?this.resolveType(r):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};0&&(module.exports={BrowserCryptoProvider,CacheTtl,NodeCryptoProvider,WARP_LANGUAGES,WarpBrandBuilder,WarpBuilder,WarpCache,WarpCacheKey,WarpChainName,WarpClient,WarpConfig,WarpConstants,WarpExecutor,WarpFactory,WarpIndex,WarpInputTypes,WarpInterpolator,WarpLinkBuilder,WarpLinkDetecter,WarpLogger,WarpProtocolVersions,WarpSerializer,WarpTypeRegistry,WarpValidator,address,applyOutputToMessages,asset,biguint,bool,buildMappedOutput,buildNestedPayload,bytesToBase64,bytesToHex,cleanWarpIdentifier,createAuthHeaders,createAuthMessage,createCryptoProvider,createHttpAuthHeaders,createSignableMessage,createWarpI18nText,createWarpIdentifier,evaluateOutputCommon,extractCollectOutput,extractIdentifierInfoFromUrl,extractQueryStringFromIdentifier,extractQueryStringFromUrl,extractWarpSecrets,findWarpAdapterForChain,getCryptoProvider,getEventNameFromWarp,getLatestProtocolIdentifier,getNextInfo,getProviderConfig,getRandomBytes,getRandomHex,getWarpActionByIndex,getWarpBrandLogoUrl,getWarpInfoFromIdentifier,getWarpPrimaryAction,getWarpWalletAddress,getWarpWalletAddressFromConfig,getWarpWalletMnemonic,getWarpWalletMnemonicFromConfig,getWarpWalletPrivateKey,getWarpWalletPrivateKeyFromConfig,hasInputPrefix,hex,isEqualWarpIdentifier,isWarpActionAutoExecute,isWarpI18nText,mergeNestedPayload,option,parseOutputOutIndex,parseSignedMessage,replacePlaceholders,resolveWarpText,safeWindow,setCryptoProvider,shiftBigintBy,splitInput,string,struct,testCryptoAvailability,toInputPayloadValue,toPreviewText,tuple,uint16,uint32,uint64,uint8,validateSignedMessage,vector});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var Dt=(c=>(c.Multiversx="multiversx",c.Vibechain="vibechain",c.Sui="sui",c.Ethereum="ethereum",c.Base="base",c.Arbitrum="arbitrum",c.Somnia="somnia",c.Fastset="fastset",c))(Dt||{}),p={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.chain.name]},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.chain.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:n=>n.chain.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},d={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},ut=typeof window<"u"?window:{open:()=>{}};var U={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},V={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${U.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${U.Brand}.schema.json`,DefaultClientUrl:n=>n==="devnet"?"https://devnet.usewarp.to":n==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",p.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var hr=(n,t)=>{let r=n.alerts?.[t];if(!r)return null;let e=p.Alerts.TriggerEventPrefix+p.ArgParamsSeparator;if(!r.trigger.startsWith(e))return null;let i=r.trigger.replace(e,"");return i||null};var Wr=(n,t)=>typeof n.logo=="string"?n.logo:n.logo[t?.scheme??"light"];var tt=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let r=new Uint8Array(t);return window.crypto.getRandomValues(r),r}},rt=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let r=await import("crypto");return new Uint8Array(r.randomBytes(t))}catch(r){throw new Error(`Node.js crypto not available: ${r instanceof Error?r.message:"Unknown error"}`)}}},$=null;function dt(){if($)return $;if(typeof window<"u"&&window.crypto)return $=new tt,$;if(typeof process<"u"&&process.versions?.node)return $=new rt,$;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Ar(n){$=n}async function ft(n,t){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(t||dt()).getRandomBytes(n)}function qt(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(n.length*2);for(let r=0;r<n.length;r++){let e=n[r];t[r*2]=(e>>>4).toString(16),t[r*2+1]=(e&15).toString(16)}return t.join("")}function xr(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(n).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(n));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function gt(n,t){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let r=await ft(n/2,t);return qt(r)}async function vr(){let n={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?n.environment="browser":typeof process<"u"&&process.versions?.node&&(n.environment="nodejs"),await ft(16),n.randomBytes=!0}catch{}return n}function Cr(){return dt()}var Ir=n=>Object.values(n.vars||{}).filter(t=>t.startsWith(`${p.Vars.Env}:`)).map(t=>{let r=t.replace(`${p.Vars.Env}:`,"").trim(),[e,i]=r.split(p.ArgCompositeSeparator);return{key:e,description:i||null}});var g=(n,t)=>{let r=t.find(e=>e.chainInfo.name.toLowerCase()===n.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${n}`);return r},M=n=>{if(n==="warp")return`warp:${U.Warp}`;if(n==="brand")return`brand:${U.Brand}`;if(n==="abi")return`abi:${U.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},T=(n,t)=>n?.actions[t-1],L=n=>{if(n.actions.length===0)throw new Error(`Warp has no primary action: ${n.meta?.identifier}`);let t=n.actions.find(s=>s.primary===!0);if(t)return{action:t,index:n.actions.indexOf(t)};let r=["transfer","contract","query","collect"],e=n.actions.find(s=>r.includes(s.type));return e?{action:e,index:n.actions.indexOf(e)}:{action:n.actions[0],index:0}},et=(n,t)=>{if(n.auto===!1)return!1;if(n.type==="link"){if(n.auto===!0)return!0;let{action:r}=L(t);return n===r}return!0},k=(n,t)=>{let r=n.toString(),[e,i=""]=r.split("."),s=Math.abs(t);if(t>0)return BigInt(e+i.padEnd(s,"0"));if(t<0){let a=e+i;if(s>=a.length)return 0n;let o=a.slice(0,-s)||"0";return BigInt(o)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},ht=(n,t=100)=>{if(!n)return"";let r=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r},O=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||"");var Er={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},z=(n,t)=>{let r=t?.preferences?.locale||"en";if(typeof n=="string")return n;if(typeof n=="object"&&n!==null){if(r in n)return n[r];if("en"in n)return n.en;let e=Object.keys(n);if(e.length>0)return n[e[0]]}return""},Rr=n=>typeof n=="object"&&n!==null&&Object.keys(n).length>0,Br=n=>n;var G=n=>n.startsWith(p.IdentifierAliasMarker)?n.replace(p.IdentifierAliasMarker,""):n,Or=(n,t)=>!n||!t?!1:G(n)===G(t),nt=(n,t,r)=>{let e=G(r);return t===p.IdentifierType.Alias?p.IdentifierAliasMarker+n+p.IdentifierParamSeparator+e:n+p.IdentifierParamSeparator+t+p.IdentifierParamSeparator+e},b=n=>{let t=decodeURIComponent(n).trim(),r=G(t),e=r.split("?")[0],i=mt(e);if(e.length===64&&/^[a-fA-F0-9]+$/.test(e))return{chain:p.IdentifierChainDefault,type:p.IdentifierType.Hash,identifier:r,identifierBase:e};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[s,a,o]=i;if(a===p.IdentifierType.Alias||a===p.IdentifierType.Hash){let c=r.includes("?")?o+r.substring(r.indexOf("?")):o;return{chain:s,type:a,identifier:c,identifierBase:o}}}if(i.length===2){let[s,a]=i;if(s===p.IdentifierType.Alias||s===p.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a;return{chain:p.IdentifierChainDefault,type:s,identifier:o,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==p.IdentifierType.Alias&&s!==p.IdentifierType.Hash){let o=r.includes("?")?a+r.substring(r.indexOf("?")):a,c=Mt(a,s)?p.IdentifierType.Hash:p.IdentifierType.Alias;return{chain:s,type:c,identifier:o,identifierBase:a}}}return{chain:p.IdentifierChainDefault,type:p.IdentifierType.Alias,identifier:r,identifierBase:e}},j=n=>{let t=new URL(n),e=t.searchParams.get(p.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let i=decodeURIComponent(e);return b(i)},Mt=(n,t)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,kt=n=>{let t=p.IdentifierParamSeparator,r=n.indexOf(t);return r!==-1?{separator:t,index:r}:null},mt=n=>{let t=kt(n);if(!t)return[n];let{separator:r,index:e}=t,i=n.substring(0,e),s=n.substring(e+r.length),a=mt(s);return[i,...a]},Wt=n=>{try{let t=new URL(n),r=new URLSearchParams(t.search);return r.delete(p.IdentifierParamName),r.toString()||null}catch{return null}},yt=n=>{let t=n.indexOf("?");if(t===-1||t===n.length-1)return null;let r=n.substring(t+1);return r.length>0?r:null};var it=n=>{let[t,...r]=n.split(/:(.*)/,2);return[t,r[0]||""]},Hr=n=>{let t=new Set(Object.values(d));if(!n.includes(p.ArgParamsSeparator))return!1;let r=it(n)[0];return t.has(r)};var At=(n,t,r)=>{let e=Object.entries(n.messages||{}).map(([i,s])=>{let a=z(s,r);return[i,O(a,t)]});return Object.fromEntries(e)};import zt from"qr-code-styling";var H=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!j(t):!1}build(t,r,e){let i=this.config.clientUrl||V.DefaultClientUrl(this.config.env),s=g(t,this.adapters),a=r===p.IdentifierType.Alias?e:r+p.IdentifierParamSeparator+e,o=s.chainInfo.name+p.IdentifierParamSeparator+a,c=encodeURIComponent(o);return V.SuperClientUrls.includes(i)?`${i}/${c}`:`${i}?${p.IdentifierParamName}=${c}`}buildFromPrefixedIdentifier(t){let r=b(t);if(!r)return null;let e=g(r.chain,this.adapters);return e?this.build(e.chainInfo.name,r.type,r.identifierBase):null}generateQrCode(t,r,e,i=512,s="white",a="black",o="#23F7DD"){let c=g(t,this.adapters),l=this.build(c.chainInfo.name,r,e);return new zt({type:"svg",width:i,height:i,data:String(l),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};var Gt="https://",xt=(n,t,r,e,i)=>{let s=r.actions?.[e-1]?.next||r.next||null;if(!s)return null;if(s.startsWith(Gt))return[{identifier:null,url:s}];let[a,o]=s.split("?");if(!o){let W=O(a,{...r.vars,...i});return[{identifier:W,url:at(t,W,n)}]}let c=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let W=O(o,{...r.vars,...i}),y=W?`${a}?${W}`:a;return[{identifier:y,url:at(t,y,n)}]}let l=c[0];if(!l)return[];let u=l.match(/{{([^[]+)\[\]/),f=u?u[1]:null;if(!f||i[f]===void 0)return[];let m=Array.isArray(i[f])?i[f]:[i[f]];if(m.length===0)return[];let h=c.filter(W=>W.includes(`{{${f}[]`)).map(W=>{let y=W.match(/\[\](\.[^}]+)?}}/),A=y&&y[1]||"";return{placeholder:W,field:A?A.slice(1):"",regex:new RegExp(W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return m.map(W=>{let y=o;for(let{regex:P,field:B}of h){let I=B?Jt(W,B):W;if(I==null)return null;y=y.replace(P,I)}if(y.includes("{{")||y.includes("}}"))return null;let A=y?`${a}?${y}`:a;return{identifier:A,url:at(t,A,n)}}).filter(W=>W!==null)},at=(n,t,r)=>{let[e,i]=t.split("?"),s=b(e)||{chain:p.IdentifierChainDefault,type:"alias",identifier:e,identifierBase:e},a=g(s.chain,n);if(!a)throw new Error(`Adapter not found for chain ${s.chain}`);let o=new H(r,n).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return o;let c=new URL(o);return new URLSearchParams(i).forEach((l,u)=>c.searchParams.set(u,l)),c.toString().replace(/\/\?/,"?")},Jt=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);function Qt(n,t,r){return n.startsWith(p.Position.Payload)?n.slice(p.Position.Payload.length).split(".").reduceRight((e,i,s,a)=>({[i]:s===a.length-1?{[t]:r}:e}),{}):{[t]:r}}function vt(n,t){if(!n)return{...t};if(!t)return{...n};let r={...n};return Object.keys(t).forEach(e=>{r[e]&&typeof r[e]=="object"&&typeof t[e]=="object"?r[e]=vt(r[e],t[e]):r[e]=t[e]}),r}function Kt(n,t){if(!n.value)return null;let r=t.stringToNative(n.value)[1];if(n.input.type==="biguint")return r.toString();if(n.input.type==="asset"){let{identifier:e,amount:i}=r;return{identifier:e,amount:i.toString()}}else return r}function J(n,t){let r={};return n.forEach(e=>{let i=e.input.as||e.input.name,s=Kt(e,t);if(e.input.position&&e.input.position.startsWith(p.Position.Payload)){let a=Qt(e.input.position,i,s);r=vt(r,a)}else r[i]=s}),r}var re=(n,t,r,e)=>{let i=n.preferences?.providers?.[t];return i?.[r]?typeof i[r]=="string"?{url:i[r]}:i[r]:{url:e}};var N=class N{static debug(...t){N.isTestEnv||console.debug(...t)}static info(...t){N.isTestEnv||console.info(...t)}static warn(...t){N.isTestEnv||console.warn(...t)}static error(...t){N.isTestEnv||console.error(...t)}};N.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=N;var st=async(n,t,r,e,i,s)=>{let a=[],o=[],c={};for(let[u,f]of Object.entries(n.output||{})){if(f.startsWith(p.Transform.Prefix))continue;let m=Yt(f);if(m!==null&&m!==r){c[u]=null;continue}let[h,...w]=f.split("."),W=(y,A)=>A.reduce((P,B)=>P&&P[B]!==void 0?P[B]:null,y);if(h==="out"||h.startsWith("out[")){let y=w.length===0?t?.data||t:W(t,w);a.push(String(y)),o.push(y),c[u]=y}else c[u]=f}let l=J(e,i);return{values:{string:a,native:o,mapped:l},output:await _t(n,c,r,e,i,s)}},_t=async(n,t,r,e,i,s)=>{if(!n.output)return t;let a={...t};return a=Xt(a,n,r,e,i),a=await Zt(n,a,s.transform?.runner||null),a},Xt=(n,t,r,e,i)=>{let s={...n},a=T(t,r)?.inputs||[];for(let[o,c]of Object.entries(s))if(typeof c=="string"&&c.startsWith("in.")){let l=c.split(".")[1],u=a.findIndex(m=>m.as===l||m.name===l),f=u!==-1?e[u]?.value:null;s[o]=f?i.stringToNative(f)[1]:null}return s},Zt=async(n,t,r)=>{if(!n.output)return t;let e={...t},i=Object.entries(n.output).filter(([,s])=>s.startsWith(p.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(p.Transform.Prefix.length)}));if(i.length>0&&(!r||typeof r.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:s,code:a}of i)try{e[s]=await r.run(a,e)}catch(o){C.error(`Transform error for output '${s}':`,o),e[s]=null}return e},Yt=n=>{if(n==="out")return 1;let t=n.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};async function tr(n,t,r,e=5){let i=await gt(64,r),s=new Date(Date.now()+e*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:i,expiresAt:s,purpose:t}),nonce:i,expiresAt:s}}async function ot(n,t,r,e){let i=e||`prove-wallet-ownership for app "${t}"`;return tr(n,i,r,5)}function pt(n,t,r,e){return{"X-Signer-Wallet":n,"X-Signer-Signature":t,"X-Signer-Nonce":r,"X-Signer-ExpiresAt":e}}async function ue(n,t,r,e){let{message:i,nonce:s,expiresAt:a}=await ot(n,r,e),o=await t(i);return pt(n,o,s,a)}function de(n){let t=new Date(n).getTime();return Date.now()<t}function fe(n){try{let t=JSON.parse(n);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var rr=n=>n?typeof n=="string"?n:n.address:null,S=(n,t)=>rr(n.user?.wallets?.[t]||null),er=n=>n?typeof n=="string"?n:n.privateKey:null,nr=n=>n?typeof n=="string"?n:n.mnemonic:null,he=(n,t)=>er(n.user?.wallets?.[t]||null)?.trim()||null,me=(n,t)=>nr(n.user?.wallets?.[t]||null)?.trim()||null;var x=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,r){if(t===d.Tuple&&Array.isArray(r)){if(r.length===0)return t+p.ArgParamsSeparator;if(r.every(e=>typeof e=="string"&&e.includes(p.ArgParamsSeparator))){let e=r.map(a=>this.getTypeAndValue(a)),i=e.map(([a])=>a),s=e.map(([,a])=>a);return`${t}(${i.join(p.ArgCompositeSeparator)})${p.ArgParamsSeparator}${s.join(p.ArgListSeparator)}`}return t+p.ArgParamsSeparator+r.join(p.ArgListSeparator)}if(t===d.Struct&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let e=r;if(!e._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=e._name,s=Object.keys(e).filter(o=>o!=="_name");if(s.length===0)return`${t}(${i})${p.ArgParamsSeparator}`;let a=s.map(o=>{let[c,l]=this.getTypeAndValue(e[o]);return`(${o}${p.ArgParamsSeparator}${c})${l}`});return`${t}(${i})${p.ArgParamsSeparator}${a.join(p.ArgListSeparator)}`}if(t===d.Vector&&Array.isArray(r)){if(r.length===0)return`${t}${p.ArgParamsSeparator}`;if(r.every(e=>typeof e=="string"&&e.includes(p.ArgParamsSeparator))){let e=r[0],i=e.indexOf(p.ArgParamsSeparator),s=e.substring(0,i),a=r.map(c=>{let l=c.indexOf(p.ArgParamsSeparator),u=c.substring(l+1);return s.startsWith(d.Tuple)?u.replace(p.ArgListSeparator,p.ArgCompositeSeparator):u}),o=s.startsWith(d.Struct)?p.ArgStructSeparator:p.ArgListSeparator;return t+p.ArgParamsSeparator+s+p.ArgParamsSeparator+a.join(o)}return t+p.ArgParamsSeparator+r.join(p.ArgListSeparator)}if(t===d.Asset&&typeof r=="object"&&r&&"identifier"in r&&"amount"in r)return"decimals"in r?d.Asset+p.ArgParamsSeparator+r.identifier+p.ArgCompositeSeparator+String(r.amount)+p.ArgCompositeSeparator+String(r.decimals):d.Asset+p.ArgParamsSeparator+r.identifier+p.ArgCompositeSeparator+String(r.amount);if(this.typeRegistry){let e=this.typeRegistry.getHandler(t);if(e)return e.nativeToString(r);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,r)}return t+p.ArgParamsSeparator+(r?.toString()??"")}stringToNative(t){let r=t.split(p.ArgParamsSeparator),e=r[0],i=r.slice(1).join(p.ArgParamsSeparator);if(e==="null")return[e,null];if(e===d.Option){let[s,a]=i.split(p.ArgParamsSeparator);return[d.Option+p.ArgParamsSeparator+s,a||null]}if(e===d.Vector){let s=i.indexOf(p.ArgParamsSeparator),a=i.substring(0,s),o=i.substring(s+1),c=a.startsWith(d.Struct)?p.ArgStructSeparator:p.ArgListSeparator,u=(o?o.split(c):[]).map(f=>this.stringToNative(a+p.ArgParamsSeparator+f)[1]);return[d.Vector+p.ArgParamsSeparator+a,u]}else if(e.startsWith(d.Tuple)){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=i.split(p.ArgCompositeSeparator).map((c,l)=>this.stringToNative(`${s[l]}${p.IdentifierParamSeparator}${c}`)[1]);return[e,o]}else if(e.startsWith(d.Struct)){let s=e.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let o={_name:s[1]};return i&&i.split(p.ArgListSeparator).forEach(c=>{let l=c.match(new RegExp(`^\\(([^${p.ArgParamsSeparator}]+)${p.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(l){let[,u,f,m]=l;o[u]=this.stringToNative(`${f}${p.IdentifierParamSeparator}${m}`)[1]}}),[e,o]}else{if(e===d.String)return[e,i];if(e===d.Uint8||e===d.Uint16||e===d.Uint32)return[e,Number(i)];if(e===d.Uint64||e===d.Uint128||e===d.Uint256||e===d.Biguint)return[e,BigInt(i||0)];if(e===d.Bool)return[e,i==="true"];if(e===d.Address)return[e,i];if(e===d.Hex)return[e,i];if(e===d.Asset){let[s,a]=i.split(p.ArgCompositeSeparator),o={identifier:s,amount:BigInt(a)};return[e,o]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(e);if(s){let o=s.stringToNative(i);return[e,o]}let a=this.typeRegistry.resolveType(e);if(a!==e){let[o,c]=this.stringToNative(`${a}:${i}`);return[e,c]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(p.ArgParamsSeparator)){let[r,e]=t.split(p.ArgParamsSeparator);return[r,e]}return typeof t=="number"?[d.Uint32,t]:typeof t=="bigint"?[d.Uint64,t]:typeof t=="boolean"?[d.Bool,t]:[typeof t,t]}};var Ce=n=>new x().nativeToString(d.String,n),we=n=>new x().nativeToString(d.Uint8,n),Se=n=>new x().nativeToString(d.Uint16,n),Ie=n=>new x().nativeToString(d.Uint32,n),Te=n=>new x().nativeToString(d.Uint64,n),be=n=>new x().nativeToString(d.Biguint,n),Pe=n=>new x().nativeToString(d.Bool,n),Ee=n=>new x().nativeToString(d.Address,n),Ct=n=>new x().nativeToString(d.Asset,n),Re=n=>new x().nativeToString(d.Hex,n),Be=(n,t)=>{if(t===null)return d.Option+p.ArgParamsSeparator;let r=n(t),e=r.indexOf(p.ArgParamsSeparator),i=r.substring(0,e),s=r.substring(e+1);return d.Option+p.ArgParamsSeparator+i+p.ArgParamsSeparator+s},Ve=(...n)=>new x().nativeToString(d.Tuple,n),$e=n=>new x().nativeToString(d.Struct,n),Oe=n=>new x().nativeToString(d.Vector,n);import ir from"ajv";var wt=class{constructor(t){this.pendingBrand={protocol:M("brand"),name:"",description:"",logo:""};this.config=t}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),e}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,r){if(!t)throw new Error(`Warp: ${r}`)}ensureWarpText(t,r){if(!t)throw new Error(`Warp: ${r}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.schema?.brand||V.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),s=new ir,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};import ar from"ajv";var Q=class{constructor(t){this.config=t;this.config=t}async validate(t){let r=[];return r.push(...this.validatePrimaryAction(t)),r.push(...this.validateMaxOneValuePosition(t)),r.push(...this.validateVariableNamesAndResultNamesUppercase(t)),r.push(...this.validateAbiIsSetIfApplicable(t)),r.push(...await this.validateSchema(t)),{valid:r.length===0,errors:r}}validatePrimaryAction(t){try{let{action:r}=L(t);return r?[]:["Primary action is required"]}catch(r){return[r instanceof Error?r.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(e=>e.inputs?e.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&r.push(`${s} name '${a}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.output,"Output"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(a=>a.type==="contract"),e=t.actions.some(a=>a.type==="query");if(!r&&!e)return[];let i=t.actions.some(a=>a.abi),s=Object.values(t.output||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.output&&!i&&s?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||V.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),s=new ar({strict:!1}),a=s.compile(i);return a(t)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var St=class{constructor(t){this.config=t;this.pendingWarp={protocol:M("warp"),chain:"",name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.validate(e),e}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,r=100){return ht(t,r)}ensure(t,r){if(!t)throw new Error(r)}ensureWarpText(t,r){if(!t)throw new Error(r);if(typeof t=="object"&&!t.en)throw new Error(r)}async validate(t){let e=await new Q(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
2
- `))}};var D=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,or);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(t)),null):e.value}catch{return null}}set(t,r,e){let i={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,sr))}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)}}},It=new x,sr=(n,t)=>typeof t=="bigint"?It.nativeToString("biguint",t):t,or=(n,t)=>typeof t=="string"&&t.startsWith(d.Biguint+":")?It.stringToNative(t)[1]:t;var E=class E{get(t){let r=E.cache.get(t);return r?Date.now()>r.expiresAt?(E.cache.delete(t),null):r.value:null}set(t,r,e){let i=Date.now()+e*1e3;E.cache.set(t,{value:r,expiresAt:i})}forget(t){E.cache.delete(t)}clear(){E.cache.clear()}};E.cache=new Map;var q=E;var Tt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},bt={Warp:(n,t)=>`warp:${n}:${t}`,WarpAbi:(n,t)=>`warp-abi:${n}:${t}`,WarpExecutable:(n,t,r)=>`warp-exec:${n}:${t}:${r}`,RegistryInfo:(n,t)=>`registry-info:${n}:${t}`,Brand:(n,t)=>`brand:${n}:${t}`,Asset:(n,t,r)=>`asset:${n}:${t}:${r}`},K=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new D:t==="memory"?new q:typeof window<"u"&&window.localStorage?new D:new q}set(t,r,e){this.strategy.set(t,r,e)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var R=class{constructor(t,r){this.config=t;this.adapter=r}async apply(t,r,e={}){let i=this.applyVars(t,r,e);return await this.applyGlobals(t,i)}async applyGlobals(t,r){let e={...r};return e.actions=await Promise.all(e.actions.map(async i=>await this.applyActionGlobals(i))),e=await this.applyRootGlobals(e,t),e}applyVars(t,r,e={}){if(!r?.vars)return r;let i=S(t,this.adapter.chainInfo.name),s=JSON.stringify(r),a=(o,c)=>{s=s.replace(new RegExp(`{{${o.toUpperCase()}}}`,"g"),c.toString())};return Object.entries(r.vars).forEach(([o,c])=>{if(typeof c!="string")a(o,c);else if(c.startsWith(p.Vars.Query+p.ArgParamsSeparator)){let l=c.slice(p.Vars.Query.length+1),[u,f]=l.split(p.ArgCompositeSeparator),m=t.currentUrl?new URLSearchParams(t.currentUrl.split("?")[1]).get(u):null,w=e.queries?.[u]||null||m;w&&a(o,w)}else if(c.startsWith(p.Vars.Env+p.ArgParamsSeparator)){let l=c.slice(p.Vars.Env.length+1),[u,f]=l.split(p.ArgCompositeSeparator),h={...t.vars,...e.envs}?.[u];h&&a(o,h)}else c===p.Source.UserWallet&&i?a(o,i):a(o,c)}),JSON.parse(s)}async applyRootGlobals(t,r){let e=JSON.stringify(t),i={config:r,chain:this.adapter.chainInfo};return Object.values(p.Globals).forEach(s=>{let a=s.Accessor(i);a!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),a.toString()))}),JSON.parse(e)}async applyActionGlobals(t){let r=JSON.stringify(t),e={config:this.config,chain:this.adapter.chainInfo};return Object.values(p.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}applyInputs(t,r,e,i){if(!t||typeof t!="string")return t;let s={};return r.forEach(a=>{if(!a.value)return;let o=a.input.as||a.input.name,[,c]=e.stringToNative(a.value);s[o]=String(c)}),i&&i.forEach(a=>{if(!a.value)return;let o=a.input.as||a.input.name,[,c]=e.stringToNative(a.value);s[`primary.${o}`]=String(c)}),O(t,s)}};var F=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 x,this.cache=new K(t.cache?.type)}getSerializer(){return this.serializer}async createExecutable(t,r,e,i={}){let s=T(t,r);if(!s)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,e),o=g(a.name,this.adapters),c=new R(this.config,o),l=await c.apply(this.config,t,i),u=T(l,r),{action:f,index:m}=L(l),h=this.getStringTypedInputs(f,e),w=await this.getResolvedInputs(a.name,f,h),W=this.getModifiedInputs(w),y=[],A=[];m===r-1&&(y=w,A=W);let P=A.find(v=>v.input.position==="receiver"||v.input.position==="destination")?.value,B=this.getDestinationFromAction(u),I=P?this.serializer.stringToNative(P)[1]:B;if(I&&(I=c.applyInputs(I,A,this.serializer,W)),!I&&s.type!=="collect")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let Y=this.getPreparedArgs(u,A);Y=Y.map(v=>c.applyInputs(v,A,this.serializer,W));let Rt=A.find(v=>v.input.position==="value")?.value||null,Bt="value"in u?u.value:null,Vt=Rt?.split(p.ArgParamsSeparator)[1]||Bt||"0",$t=c.applyInputs(Vt,A,this.serializer,W),Ot=BigInt($t),Nt=A.filter(v=>v.input.position==="transfer"&&v.value).map(v=>v.value),Ut=[...("transfers"in u?u.transfers:[])||[],...Nt||[]].map(v=>{let jt=c.applyInputs(v,A,this.serializer,W);return this.serializer.stringToNative(jt)[1]}),Ht=A.find(v=>v.input.position==="data")?.value,Ft="data"in u?u.data||"":null,ct=Ht||Ft||null,Lt=ct?c.applyInputs(ct,A,this.serializer,W):null,lt={warp:l,chain:a,action:r,destination:I,args:Y,value:Ot,transfers:Ut,data:Lt,resolvedInputs:A};return this.cache.set(bt.WarpExecutable(this.config.env,l.meta?.hash||"",r),lt.resolvedInputs,Tt.OneWeek),lt}async getChainInfoForWarp(t,r){if(t.chain)return g(t.chain,this.adapters).chainInfo;if(r){let i=await this.tryGetChainFromInputs(t,r);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,r){let e=t.inputs||[];return r.map((i,s)=>{let a=e[s];return!a||i.includes(p.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,r,e){let i=r.inputs||[],s=await Promise.all(e.map(o=>this.preprocessInput(t,o))),a=(o,c)=>{if(o.source==="query"){let l=this.url.searchParams.get(o.name);return l?this.serializer.nativeToString(o.type,l):null}else if(o.source===p.Source.UserWallet){let l=S(this.config,t);return l?this.serializer.nativeToString("address",l):null}else return o.source==="hidden"?o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null:s[c]||null};return i.map((o,c)=>{let l=a(o,c);return{input:o,value:l||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(t){return t.map((r,e)=>{if(r.input.modifier?.startsWith("scale:")){let[,i]=r.input.modifier.split(":");if(isNaN(Number(i))){let s=Number(t.find(c=>c.input.name===i)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let a=r.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=k(a,+s);return{...r,value:`${r.input.type}:${o}`}}else{let s=r.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let a=k(s,+i);return{...r,value:`${r.input.type}:${a}`}}}else return r})}async preprocessInput(t,r){try{let[e,i]=it(r),s=g(t,this.adapters);if(e==="asset"){let[a,o,c]=i.split(p.ArgCompositeSeparator);if(c)return r;let l=await s.dataLoader.getAsset(a);if(!l)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof l.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=k(o,l.decimals);return Ct({...l,amount:u})}else return r}catch(e){throw C.warn("WarpFactory: Preprocess input failed",e),e}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,r){let e="args"in t?t.args||[]:[];return r.forEach(({input:i,value:s})=>{if(!s||!i.position?.startsWith("arg:"))return;let a=Number(i.position.split(":")[1])-1;e.splice(a,0,s)}),e}async tryGetChainFromInputs(t,r){let e=t.actions.find(c=>c.inputs?.some(l=>l.position==="chain"));if(!e)return null;let i=e.inputs?.findIndex(c=>c.position==="chain");if(i===-1||i===void 0)return null;let s=r[i];if(!s)throw new Error("Chain input not found");let a=this.serializer.stringToNative(s)[1];return g(a,this.adapters).chainInfo}};var _=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.handlers=e,this.factory=new F(t,r)}async execute(t,r,e={}){let i=[],s=null,a=[];for(let o=1;o<=t.actions.length;o++){let c=T(t,o);if(!et(c,t))continue;let{tx:l,chain:u,immediateExecution:f}=await this.executeAction(t,o,r,e);l&&i.push(l),u&&(s=u),f&&a.push(f)}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let o=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(o))}return{txs:i,chain:s,immediateExecutions:a}}async executeAction(t,r,e,i={}){let s=T(t,r);if(s.type==="link")return await this.callHandler(async()=>{let l=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(l):ut.open(l,"_blank")}),{tx:null,chain:null,immediateExecution:null};let a=await this.factory.createExecutable(t,r,e,i);if(s.type==="collect"){let l=await this.executeCollect(a);return l.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l}):l.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l}):(this.handlers?.onError?.({message:JSON.stringify(l.values)}),{tx:null,chain:null,immediateExecution:null})}let o=g(a.chain.name,this.adapters);if(s.type==="query"){let l=await o.executor.executeQuery(a);return l.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:l,tx:null})):this.handlers?.onError?.({message:JSON.stringify(l.values)}),{tx:null,chain:a.chain,immediateExecution:l}}return{tx:await o.executor.createTransaction(a),chain:a.chain,immediateExecution:null}}async evaluateOutput(t,r){if(r.length===0||t.actions.length===0||!this.handlers)return;let e=await this.factory.getChainInfoForWarp(t),i=g(e.name,this.adapters),s=(await Promise.all(t.actions.map(async(a,o)=>{if(!et(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let c=r[o],l=o+1,u=await i.output.getActionExecution(t,l,c);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:l,chain:e,execution:u,tx:c})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values)})),u}))).filter(a=>a!==null);if(s.every(a=>a.status==="success")){let a=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(a))}else await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(s.map(a=>a.values))}`}))}async executeCollect(t,r){let e=S(this.config,t.chain.name),i=T(t.warp,t.action),s=this.factory.getSerializer(),a=J(t.resolvedInputs,s);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,e,a,r);let{values:o,output:c}=await st(t.warp,a,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,e,"unhandled",o,c)}async doHttpRequest(t,r,e,i,s){let a=new R(this.config,g(t.chain.name,this.adapters)),o=new Headers;if(o.set("Content-Type","application/json"),o.set("Accept","application/json"),this.handlers?.onSignRequest){if(!e)throw new Error(`No wallet configured for chain ${t.chain.name}`);let{message:f,nonce:m,expiresAt:h}=await ot(e,`${t.chain.name}-adapter`),w=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:f,chain:t.chain}));if(w){let W=pt(e,w,m,h);Object.entries(W).forEach(([y,A])=>o.set(y,A))}}r.headers&&Object.entries(r.headers).forEach(([f,m])=>{let h=a.applyInputs(m,t.resolvedInputs,this.factory.getSerializer());o.set(f,h)});let c=r.method||"GET",l=c==="GET"?void 0:JSON.stringify({...i,...s}),u=a.applyInputs(r.url,t.resolvedInputs,this.factory.getSerializer());C.debug("WarpExecutor: Executing HTTP collect",{url:u,method:c,headers:o,body:l});try{let f=await fetch(u,{method:c,headers:o,body:l});C.debug("Collect response status",{status:f.status});let m=await f.json();C.debug("Collect response content",{content:m});let{values:h,output:w}=await st(t.warp,m,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),f.ok?"success":"error",h,w,m)}catch(f){return C.error("WarpActionExecutor: Error executing collect",f),{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t)}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(e=>e.input.position==="receiver"||e.input.position==="destination")?.value||t.destination}buildCollectResult(t,r,e,i,s,a){let o=xt(this.config,this.adapters,t.warp,t.action,s);return{status:e,warp:t.warp,action:t.action,user:r||S(this.config,t.chain.name),txHash:null,tx:null,next:o,values:i,output:a?{...s,_DATA:a}:s,messages:At(t.warp,s,this.config),destination:this.getDestinationFromResolvedInputs(t)}}async callHandler(t){if(t)return await t()}};var X=class{constructor(t){this.config=t}async search(t,r,e){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...e},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...r})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw C.error("WarpIndex: Error searching for warps: ",i),i}}};var Z=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(p.HttpProtocolPrefix)?!!j(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),a=(await Promise.all(i)).filter(l=>l.match),o=a.length>0,c=a.map(l=>({url:l.url,warp:l.warp}));return{match:o,output:c}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(p.HttpProtocolPrefix)?j(t):b(t);if(!i)return e;try{let{type:s,identifierBase:a}=i,o=null,c=null,l=null,u=g(i.chain,this.adapters),f=t.startsWith(p.HttpProtocolPrefix)?Wt(t):yt(i.identifier);if(s==="hash"){o=await u.builder().createFromTransactionHash(a,r);let h=await u.registry.getInfoByHash(a,r);c=h.registryInfo,l=h.brand}else if(s==="alias"){let h=await u.registry.getInfoByAlias(a,r);c=h.registryInfo,l=h.brand,h.registryInfo&&(o=await u.builder().createFromTransactionHash(h.registryInfo.hash,r))}o&&o.meta&&(pr(o,u.chainInfo.name,c,i.identifier),o.meta.query=f);let m=o?await new R(this.config,u).apply(this.config,o):null;return m?{match:!0,url:t,warp:m,chain:u.chainInfo.name,registryInfo:c,brand:l}:e}catch(s){return C.error("Error detecting warp link",s),e}}},pr=(n,t,r,e)=>{n.meta&&(n.meta.identifier=r?.alias?nt(t,"alias",r.alias):nt(t,"hash",r?.hash??e))};var Pt=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}getAdapters(){return this.adapters}addAdapter(t){return this.adapters.push(t),this}createExecutor(t){return new _(this.config,this.adapters,t)}async detectWarp(t,r){return new Z(this.config,this.adapters).detect(t,r)}async executeWarp(t,r,e,i={}){let s=typeof t=="object",a=!s&&t.startsWith("http")&&t.endsWith(".json"),o=s?t:null;if(!o&&a){let h=await fetch(t);if(!h.ok)throw new Error("WarpClient: executeWarp - invalid url");o=await h.json()}if(o||(o=(await this.detectWarp(t,i.cache)).warp),!o)throw new Error("Warp not found");let c=this.createExecutor(e),{txs:l,chain:u,immediateExecutions:f}=await c.execute(o,r,{queries:i.queries});return{txs:l,chain:u,immediateExecutions:f,evaluateOutput:async h=>{await c.evaluateOutput(o,h)}}}async createInscriptionTransaction(t,r){return await g(t,this.adapters).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return g(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 g(e.chain,this.adapters).builder().createFromTransactionHash(t,r)}async signMessage(t,r){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return g(t,this.adapters).wallet.signMessage(r)}async getActions(t,r,e=!1){let i=this.getDataLoader(t);return(await Promise.all(r.map(async a=>i.getAction(a,e)))).filter(a=>a!==null)}getExplorer(t){return g(t,this.adapters).explorer}getOutput(t){return g(t,this.adapters).output}async getRegistry(t){let r=g(t,this.adapters).registry;return await r.init(),r}getDataLoader(t){return g(t,this.adapters).dataLoader}getWallet(t){return g(t,this.adapters).wallet}get factory(){return new F(this.config,this.adapters)}get index(){return new X(this.config)}get linkBuilder(){return new H(this.config,this.adapters)}createBuilder(t){return g(t,this.adapters).builder()}createAbiBuilder(t){return g(t,this.adapters).abiBuilder()}createBrandBuilder(t){return g(t,this.adapters).brandBuilder()}createSerializer(t){return g(t,this.adapters).serializer}resolveText(t){return z(t,this.config)}};var Et=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,r){this.typeHandlers.set(t,r)}registerTypeAlias(t,r){this.typeAliases.set(t,r)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let r=this.typeAliases.get(t);return r?this.getHandler(r):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let r=this.typeAliases.get(t);return r?this.resolveType(r):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};export{tt as BrowserCryptoProvider,Tt as CacheTtl,rt as NodeCryptoProvider,Er as WARP_LANGUAGES,wt as WarpBrandBuilder,St as WarpBuilder,K as WarpCache,bt as WarpCacheKey,Dt as WarpChainName,Pt as WarpClient,V as WarpConfig,p as WarpConstants,_ as WarpExecutor,F as WarpFactory,X as WarpIndex,d as WarpInputTypes,R as WarpInterpolator,H as WarpLinkBuilder,Z as WarpLinkDetecter,C as WarpLogger,U as WarpProtocolVersions,x as WarpSerializer,Et as WarpTypeRegistry,Q as WarpValidator,Ee as address,At as applyOutputToMessages,Ct as asset,be as biguint,Pe as bool,J as buildMappedOutput,Qt as buildNestedPayload,xr as bytesToBase64,qt as bytesToHex,G as cleanWarpIdentifier,pt as createAuthHeaders,ot as createAuthMessage,Cr as createCryptoProvider,ue as createHttpAuthHeaders,tr as createSignableMessage,Br as createWarpI18nText,nt as createWarpIdentifier,_t as evaluateOutputCommon,st as extractCollectOutput,j as extractIdentifierInfoFromUrl,yt as extractQueryStringFromIdentifier,Wt as extractQueryStringFromUrl,Ir as extractWarpSecrets,g as findWarpAdapterForChain,dt as getCryptoProvider,hr as getEventNameFromWarp,M as getLatestProtocolIdentifier,xt as getNextInfo,re as getProviderConfig,ft as getRandomBytes,gt as getRandomHex,T as getWarpActionByIndex,Wr as getWarpBrandLogoUrl,b as getWarpInfoFromIdentifier,L as getWarpPrimaryAction,rr as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,nr as getWarpWalletMnemonic,me as getWarpWalletMnemonicFromConfig,er as getWarpWalletPrivateKey,he as getWarpWalletPrivateKeyFromConfig,Hr as hasInputPrefix,Re as hex,Or as isEqualWarpIdentifier,et as isWarpActionAutoExecute,Rr as isWarpI18nText,vt as mergeNestedPayload,Be as option,Yt as parseOutputOutIndex,fe as parseSignedMessage,O as replacePlaceholders,z as resolveWarpText,ut as safeWindow,Ar as setCryptoProvider,k as shiftBigintBy,it as splitInput,Ce as string,$e as struct,vr as testCryptoAvailability,Kt as toInputPayloadValue,ht as toPreviewText,Ve as tuple,Se as uint16,Ie as uint32,Te as uint64,we as uint8,de as validateSignedMessage,Oe as vector};
1
+ var Dt=(p=>(p.Multiversx="multiversx",p.Vibechain="vibechain",p.Sui="sui",p.Ethereum="ethereum",p.Base="base",p.Arbitrum="arbitrum",p.Somnia="somnia",p.Fastset="fastset",p))(Dt||{}),o={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:n=>n.config.user?.wallets?.[n.adapter.chainInfo.name]},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:n=>{if(!n.adapter.wallet)return null;try{return n.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:n=>n.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:n=>n.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},d={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"},ut=typeof window<"u"?window:{open:()=>{}};var H={Warp:"3.0.0",Brand:"0.2.0",Abi:"0.1.0"},$={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${H.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${H.Brand}.schema.json`,DefaultClientUrl:n=>n==="devnet"?"https://devnet.usewarp.to":n==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],AvailableActionInputSources:["field","query",o.Source.UserWallet,"hidden"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var hr=(n,t)=>{let r=n.alerts?.[t];if(!r)return null;let e=o.Alerts.TriggerEventPrefix+o.ArgParamsSeparator;if(!r.trigger.startsWith(e))return null;let i=r.trigger.replace(e,"");return i||null};var Wr=(n,t)=>typeof n.logo=="string"?n.logo:n.logo[t?.scheme??"light"];var tt=class{async getRandomBytes(t){if(typeof window>"u"||!window.crypto)throw new Error("Web Crypto API not available");let r=new Uint8Array(t);return window.crypto.getRandomValues(r),r}},rt=class{async getRandomBytes(t){if(typeof process>"u"||!process.versions?.node)throw new Error("Node.js environment not detected");try{let r=await import("crypto");return new Uint8Array(r.randomBytes(t))}catch(r){throw new Error(`Node.js crypto not available: ${r instanceof Error?r.message:"Unknown error"}`)}}},V=null;function dt(){if(V)return V;if(typeof window<"u"&&window.crypto)return V=new tt,V;if(typeof process<"u"&&process.versions?.node)return V=new rt,V;throw new Error("No compatible crypto provider found. Please provide a crypto provider using setCryptoProvider() or ensure Web Crypto API is available.")}function Ar(n){V=n}async function ft(n,t){if(n<=0||!Number.isInteger(n))throw new Error("Size must be a positive integer");return(t||dt()).getRandomBytes(n)}function qt(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");let t=new Array(n.length*2);for(let r=0;r<n.length;r++){let e=n[r];t[r*2]=(e>>>4).toString(16),t[r*2+1]=(e&15).toString(16)}return t.join("")}function xr(n){if(!(n instanceof Uint8Array))throw new Error("Input must be a Uint8Array");if(typeof Buffer<"u")return Buffer.from(n).toString("base64");if(typeof btoa<"u"){let t=String.fromCharCode.apply(null,Array.from(n));return btoa(t)}else throw new Error("Base64 encoding not available in this environment")}async function gt(n,t){if(n<=0||n%2!==0)throw new Error("Length must be a positive even number");let r=await ft(n/2,t);return qt(r)}async function vr(){let n={randomBytes:!1,environment:"unknown"};try{typeof window<"u"&&window.crypto?n.environment="browser":typeof process<"u"&&process.versions?.node&&(n.environment="nodejs"),await ft(16),n.randomBytes=!0}catch{}return n}function Cr(){return dt()}var Ir=n=>Object.values(n.vars||{}).filter(t=>t.startsWith(`${o.Vars.Env}:`)).map(t=>{let r=t.replace(`${o.Vars.Env}:`,"").trim(),[e,i]=r.split(o.ArgCompositeSeparator);return{key:e,description:i||null}});var m=(n,t)=>{let r=t.find(e=>e.chainInfo.name.toLowerCase()===n.toLowerCase());if(!r)throw new Error(`Adapter not found for chain: ${n}`);return r},k=n=>{if(n==="warp")return`warp:${H.Warp}`;if(n==="brand")return`brand:${H.Brand}`;if(n==="abi")return`abi:${H.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${n}`)},b=(n,t)=>n?.actions[t-1],O=n=>{if(n.actions.length===0)throw new Error(`Warp has no primary action: ${n.meta?.identifier}`);let t=n.actions.find(s=>s.primary===!0);if(t)return{action:t,index:n.actions.indexOf(t)};let r=["transfer","contract","query","collect"],e=n.actions.find(s=>r.includes(s.type));return e?{action:e,index:n.actions.indexOf(e)}:{action:n.actions[0],index:0}},et=(n,t)=>{if(n.auto===!1)return!1;if(n.type==="link"){if(n.auto===!0)return!0;let{action:r}=O(t);return n===r}return!0},z=(n,t)=>{let r=n.toString(),[e,i=""]=r.split("."),s=Math.abs(t);if(t>0)return BigInt(e+i.padEnd(s,"0"));if(t<0){let a=e+i;if(s>=a.length)return 0n;let c=a.slice(0,-s)||"0";return BigInt(c)}else return r.includes(".")?BigInt(r.split(".")[0]):BigInt(r)},ht=(n,t=100)=>{if(!n)return"";let r=n.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r},N=(n,t)=>n.replace(/\{\{([^}]+)\}\}/g,(r,e)=>t[e]||"");var Er={de:"German",en:"English",es:"Spanish",fr:"French",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",ar:"Arabic",hi:"Hindi",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",pl:"Polish",tr:"Turkish",el:"Greek",he:"Hebrew",th:"Thai",vi:"Vietnamese",id:"Indonesian",ms:"Malay",tl:"Tagalog"},M=(n,t)=>{let r=t?.preferences?.locale||"en";if(typeof n=="string")return n;if(typeof n=="object"&&n!==null){if(r in n)return n[r];if("en"in n)return n.en;let e=Object.keys(n);if(e.length>0)return n[e[0]]}return""},Rr=n=>typeof n=="object"&&n!==null&&Object.keys(n).length>0,Br=n=>n;var G=n=>n.startsWith(o.IdentifierAliasMarker)?n.replace(o.IdentifierAliasMarker,""):n,Or=(n,t)=>!n||!t?!1:G(n)===G(t),nt=(n,t,r)=>{let e=G(r);return t===o.IdentifierType.Alias?o.IdentifierAliasMarker+n+o.IdentifierParamSeparator+e:n+o.IdentifierParamSeparator+t+o.IdentifierParamSeparator+e},T=n=>{let t=decodeURIComponent(n).trim(),r=G(t),e=r.split("?")[0],i=mt(e);if(e.length===64&&/^[a-fA-F0-9]+$/.test(e))return{chain:o.IdentifierChainDefault,type:o.IdentifierType.Hash,identifier:r,identifierBase:e};if(i.length===2&&/^[a-zA-Z0-9]{62}$/.test(i[0])&&/^[a-zA-Z0-9]{2}$/.test(i[1]))return null;if(i.length===3){let[s,a,c]=i;if(a===o.IdentifierType.Alias||a===o.IdentifierType.Hash){let p=r.includes("?")?c+r.substring(r.indexOf("?")):c;return{chain:s,type:a,identifier:p,identifierBase:c}}}if(i.length===2){let[s,a]=i;if(s===o.IdentifierType.Alias||s===o.IdentifierType.Hash){let c=r.includes("?")?a+r.substring(r.indexOf("?")):a;return{chain:o.IdentifierChainDefault,type:s,identifier:c,identifierBase:a}}}if(i.length===2){let[s,a]=i;if(s!==o.IdentifierType.Alias&&s!==o.IdentifierType.Hash){let c=r.includes("?")?a+r.substring(r.indexOf("?")):a,p=kt(a,s)?o.IdentifierType.Hash:o.IdentifierType.Alias;return{chain:s,type:p,identifier:c,identifierBase:a}}}return{chain:o.IdentifierChainDefault,type:o.IdentifierType.Alias,identifier:r,identifierBase:e}},j=n=>{let t=new URL(n),e=t.searchParams.get(o.IdentifierParamName);if(e||(e=t.pathname.split("/")[1]),!e)return null;let i=decodeURIComponent(e);return T(i)},kt=(n,t)=>/^[a-fA-F0-9]+$/.test(n)&&n.length>32,zt=n=>{let t=o.IdentifierParamSeparator,r=n.indexOf(t);return r!==-1?{separator:t,index:r}:null},mt=n=>{let t=zt(n);if(!t)return[n];let{separator:r,index:e}=t,i=n.substring(0,e),s=n.substring(e+r.length),a=mt(s);return[i,...a]},Wt=n=>{try{let t=new URL(n),r=new URLSearchParams(t.search);return r.delete(o.IdentifierParamName),r.toString()||null}catch{return null}},yt=n=>{let t=n.indexOf("?");if(t===-1||t===n.length-1)return null;let r=n.substring(t+1);return r.length>0?r:null};var it=n=>{let[t,...r]=n.split(/:(.*)/,2);return[t,r[0]||""]},Hr=n=>{let t=new Set(Object.values(d));if(!n.includes(o.ArgParamsSeparator))return!1;let r=it(n)[0];return t.has(r)};var At=(n,t,r)=>{let e=Object.entries(n.messages||{}).map(([i,s])=>{let a=M(s,r);return[i,N(a,t)]});return Object.fromEntries(e)};import Mt from"qr-code-styling";var F=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(o.HttpProtocolPrefix)?!!j(t):!1}build(t,r,e){let i=this.config.clientUrl||$.DefaultClientUrl(this.config.env),s=m(t,this.adapters),a=r===o.IdentifierType.Alias?e:r+o.IdentifierParamSeparator+e,c=s.chainInfo.name+o.IdentifierParamSeparator+a,p=encodeURIComponent(c);return $.SuperClientUrls.includes(i)?`${i}/${p}`:`${i}?${o.IdentifierParamName}=${p}`}buildFromPrefixedIdentifier(t){let r=T(t);if(!r)return null;let e=m(r.chain,this.adapters);return e?this.build(e.chainInfo.name,r.type,r.identifierBase):null}generateQrCode(t,r,e,i=512,s="white",a="black",c="#23F7DD"){let p=m(t,this.adapters),l=this.build(p.chainInfo.name,r,e);return new Mt({type:"svg",width:i,height:i,data:String(l),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(c)}" 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 Gt="https://",xt=(n,t,r,e,i)=>{let s=r.actions?.[e-1]?.next||r.next||null;if(!s)return null;if(s.startsWith(Gt))return[{identifier:null,url:s}];let[a,c]=s.split("?");if(!c){let h=N(a,{...r.vars,...i});return[{identifier:h,url:at(t,h,n)}]}let p=c.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let h=N(c,{...r.vars,...i}),y=h?`${a}?${h}`:a;return[{identifier:y,url:at(t,y,n)}]}let l=p[0];if(!l)return[];let u=l.match(/{{([^[]+)\[\]/),f=u?u[1]:null;if(!f||i[f]===void 0)return[];let g=Array.isArray(i[f])?i[f]:[i[f]];if(g.length===0)return[];let W=p.filter(h=>h.includes(`{{${f}[]`)).map(h=>{let y=h.match(/\[\](\.[^}]+)?}}/),x=y&&y[1]||"";return{placeholder:h,field:x?x.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return g.map(h=>{let y=c;for(let{regex:P,field:B}of W){let I=B?Jt(h,B):h;if(I==null)return null;y=y.replace(P,I)}if(y.includes("{{")||y.includes("}}"))return null;let x=y?`${a}?${y}`:a;return{identifier:x,url:at(t,x,n)}}).filter(h=>h!==null)},at=(n,t,r)=>{let[e,i]=t.split("?"),s=T(e)||{chain:o.IdentifierChainDefault,type:"alias",identifier:e,identifierBase:e},a=m(s.chain,n);if(!a)throw new Error(`Adapter not found for chain ${s.chain}`);let c=new F(r,n).build(a.chainInfo.name,s.type,s.identifierBase);if(!i)return c;let p=new URL(c);return new URLSearchParams(i).forEach((l,u)=>p.searchParams.set(u,l)),p.toString().replace(/\/\?/,"?")},Jt=(n,t)=>t.split(".").reduce((r,e)=>r?.[e],n);function Qt(n,t,r){return n.startsWith(o.Position.Payload)?n.slice(o.Position.Payload.length).split(".").reduceRight((e,i,s,a)=>({[i]:s===a.length-1?{[t]:r}:e}),{}):{[t]:r}}function vt(n,t){if(!n)return{...t};if(!t)return{...n};let r={...n};return Object.keys(t).forEach(e=>{r[e]&&typeof r[e]=="object"&&typeof t[e]=="object"?r[e]=vt(r[e],t[e]):r[e]=t[e]}),r}function Kt(n,t){if(!n.value)return null;let r=t.stringToNative(n.value)[1];if(n.input.type==="biguint")return r.toString();if(n.input.type==="asset"){let{identifier:e,amount:i}=r;return{identifier:e,amount:i.toString()}}else return r}function J(n,t){let r={};return n.forEach(e=>{let i=e.input.as||e.input.name,s=Kt(e,t);if(e.input.position&&typeof e.input.position=="string"&&e.input.position.startsWith(o.Position.Payload)){let a=Qt(e.input.position,i,s);r=vt(r,a)}else r[i]=s}),r}var re=(n,t,r,e)=>{let i=n.preferences?.providers?.[t];return i?.[r]?typeof i[r]=="string"?{url:i[r]}:i[r]:{url:e}};var U=class U{static debug(...t){U.isTestEnv||console.debug(...t)}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 w=U;var st=async(n,t,r,e,i,s)=>{let a=[],c=[],p={};for(let[u,f]of Object.entries(n.output||{})){if(f.startsWith(o.Transform.Prefix))continue;let g=Yt(f);if(g!==null&&g!==r){p[u]=null;continue}let[W,...A]=f.split("."),h=(y,x)=>x.reduce((P,B)=>P&&P[B]!==void 0?P[B]:null,y);if(W==="out"||W.startsWith("out[")){let y=A.length===0?t?.data||t:h(t,A);a.push(String(y)),c.push(y),p[u]=y}else p[u]=f}let l=J(e,i);return{values:{string:a,native:c,mapped:l},output:await _t(n,p,r,e,i,s)}},_t=async(n,t,r,e,i,s)=>{if(!n.output)return t;let a={...t};return a=Xt(a,n,r,e,i),a=await Zt(n,a,s.transform?.runner||null),a},Xt=(n,t,r,e,i)=>{let s={...n},a=b(t,r)?.inputs||[];for(let[c,p]of Object.entries(s))if(typeof p=="string"&&p.startsWith("in.")){let l=p.split(".")[1],u=a.findIndex(g=>g.as===l||g.name===l),f=u!==-1?e[u]?.value:null;s[c]=f?i.stringToNative(f)[1]:null}return s},Zt=async(n,t,r)=>{if(!n.output)return t;let e={...t},i=Object.entries(n.output).filter(([,s])=>s.startsWith(o.Transform.Prefix)).map(([s,a])=>({key:s,code:a.substring(o.Transform.Prefix.length)}));if(i.length>0&&(!r||typeof r.run!="function"))throw new Error("Transform output is defined but no transform runner is configured. Provide a runner via config.transform.runner.");for(let{key:s,code:a}of i)try{e[s]=await r.run(a,e)}catch(c){w.error(`Transform error for output '${s}':`,c),e[s]=null}return e},Yt=n=>{if(n==="out")return 1;let t=n.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(n.startsWith("out.")||n.startsWith("event."),null)};async function tr(n,t,r,e=5){let i=await gt(64,r),s=new Date(Date.now()+e*60*1e3).toISOString();return{message:JSON.stringify({wallet:n,nonce:i,expiresAt:s,purpose:t}),nonce:i,expiresAt:s}}async function ot(n,t,r,e){let i=e||`prove-wallet-ownership for app "${t}"`;return tr(n,i,r,5)}function pt(n,t,r,e){return{"X-Signer-Wallet":n,"X-Signer-Signature":t,"X-Signer-Nonce":r,"X-Signer-ExpiresAt":e}}async function ue(n,t,r,e){let{message:i,nonce:s,expiresAt:a}=await ot(n,r,e),c=await t(i);return pt(n,c,s,a)}function de(n){let t=new Date(n).getTime();return Date.now()<t}function fe(n){try{let t=JSON.parse(n);if(!t.wallet||!t.nonce||!t.expiresAt||!t.purpose)throw new Error("Invalid signed message: missing required fields");return t}catch(t){throw new Error(`Failed to parse signed message: ${t instanceof Error?t.message:"Unknown error"}`)}}var rr=n=>n?typeof n=="string"?n:n.address:null,S=(n,t)=>rr(n.user?.wallets?.[t]||null),er=n=>n?typeof n=="string"?n:n.privateKey:null,nr=n=>n?typeof n=="string"?n:n.mnemonic:null,he=(n,t)=>er(n.user?.wallets?.[t]||null)?.trim()||null,me=(n,t)=>nr(n.user?.wallets?.[t]||null)?.trim()||null;var v=class{constructor(t){this.typeRegistry=t?.typeRegistry}nativeToString(t,r){if(t===d.Tuple&&Array.isArray(r)){if(r.length===0)return t+o.ArgParamsSeparator;if(r.every(e=>typeof e=="string"&&e.includes(o.ArgParamsSeparator))){let e=r.map(a=>this.getTypeAndValue(a)),i=e.map(([a])=>a),s=e.map(([,a])=>a);return`${t}(${i.join(o.ArgCompositeSeparator)})${o.ArgParamsSeparator}${s.join(o.ArgListSeparator)}`}return t+o.ArgParamsSeparator+r.join(o.ArgListSeparator)}if(t===d.Struct&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let e=r;if(!e._name)throw new Error("Struct objects must have a _name property to specify the struct name");let i=e._name,s=Object.keys(e).filter(c=>c!=="_name");if(s.length===0)return`${t}(${i})${o.ArgParamsSeparator}`;let a=s.map(c=>{let[p,l]=this.getTypeAndValue(e[c]);return`(${c}${o.ArgParamsSeparator}${p})${l}`});return`${t}(${i})${o.ArgParamsSeparator}${a.join(o.ArgListSeparator)}`}if(t===d.Vector&&Array.isArray(r)){if(r.length===0)return`${t}${o.ArgParamsSeparator}`;if(r.every(e=>typeof e=="string"&&e.includes(o.ArgParamsSeparator))){let e=r[0],i=e.indexOf(o.ArgParamsSeparator),s=e.substring(0,i),a=r.map(p=>{let l=p.indexOf(o.ArgParamsSeparator),u=p.substring(l+1);return s.startsWith(d.Tuple)?u.replace(o.ArgListSeparator,o.ArgCompositeSeparator):u}),c=s.startsWith(d.Struct)?o.ArgStructSeparator:o.ArgListSeparator;return t+o.ArgParamsSeparator+s+o.ArgParamsSeparator+a.join(c)}return t+o.ArgParamsSeparator+r.join(o.ArgListSeparator)}if(t===d.Asset&&typeof r=="object"&&r&&"identifier"in r&&"amount"in r)return"decimals"in r?d.Asset+o.ArgParamsSeparator+r.identifier+o.ArgCompositeSeparator+String(r.amount)+o.ArgCompositeSeparator+String(r.decimals):d.Asset+o.ArgParamsSeparator+r.identifier+o.ArgCompositeSeparator+String(r.amount);if(this.typeRegistry){let e=this.typeRegistry.getHandler(t);if(e)return e.nativeToString(r);let i=this.typeRegistry.resolveType(t);if(i!==t)return this.nativeToString(i,r)}return t+o.ArgParamsSeparator+(r?.toString()??"")}stringToNative(t){let r=t.split(o.ArgParamsSeparator),e=r[0],i=r.slice(1).join(o.ArgParamsSeparator);if(e==="null")return[e,null];if(e===d.Option){let[s,a]=i.split(o.ArgParamsSeparator);return[d.Option+o.ArgParamsSeparator+s,a||null]}if(e===d.Vector){let s=i.indexOf(o.ArgParamsSeparator),a=i.substring(0,s),c=i.substring(s+1),p=a.startsWith(d.Struct)?o.ArgStructSeparator:o.ArgListSeparator,u=(c?c.split(p):[]).map(f=>this.stringToNative(a+o.ArgParamsSeparator+f)[1]);return[d.Vector+o.ArgParamsSeparator+a,u]}else if(e.startsWith(d.Tuple)){let s=e.match(/\(([^)]+)\)/)?.[1]?.split(o.ArgCompositeSeparator),c=i.split(o.ArgCompositeSeparator).map((p,l)=>this.stringToNative(`${s[l]}${o.IdentifierParamSeparator}${p}`)[1]);return[e,c]}else if(e.startsWith(d.Struct)){let s=e.match(/\(([^)]+)\)/);if(!s)throw new Error("Struct type must include a name in the format struct(Name)");let c={_name:s[1]};return i&&i.split(o.ArgListSeparator).forEach(p=>{let l=p.match(new RegExp(`^\\(([^${o.ArgParamsSeparator}]+)${o.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(l){let[,u,f,g]=l;c[u]=this.stringToNative(`${f}${o.IdentifierParamSeparator}${g}`)[1]}}),[e,c]}else{if(e===d.String)return[e,i];if(e===d.Uint8||e===d.Uint16||e===d.Uint32)return[e,Number(i)];if(e===d.Uint64||e===d.Uint128||e===d.Uint256||e===d.Biguint)return[e,BigInt(i||0)];if(e===d.Bool)return[e,i==="true"];if(e===d.Address)return[e,i];if(e===d.Hex)return[e,i];if(e===d.Asset){let[s,a]=i.split(o.ArgCompositeSeparator),c={identifier:s,amount:BigInt(a)};return[e,c]}}if(this.typeRegistry){let s=this.typeRegistry.getHandler(e);if(s){let c=s.stringToNative(i);return[e,c]}let a=this.typeRegistry.resolveType(e);if(a!==e){let[c,p]=this.stringToNative(`${a}:${i}`);return[e,p]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${e}`)}getTypeAndValue(t){if(typeof t=="string"&&t.includes(o.ArgParamsSeparator)){let[r,e]=t.split(o.ArgParamsSeparator);return[r,e]}return typeof t=="number"?[d.Uint32,t]:typeof t=="bigint"?[d.Uint64,t]:typeof t=="boolean"?[d.Bool,t]:[typeof t,t]}};var Ce=n=>new v().nativeToString(d.String,n),we=n=>new v().nativeToString(d.Uint8,n),Se=n=>new v().nativeToString(d.Uint16,n),Ie=n=>new v().nativeToString(d.Uint32,n),be=n=>new v().nativeToString(d.Uint64,n),Te=n=>new v().nativeToString(d.Biguint,n),Pe=n=>new v().nativeToString(d.Bool,n),Ee=n=>new v().nativeToString(d.Address,n),Ct=n=>new v().nativeToString(d.Asset,n),Re=n=>new v().nativeToString(d.Hex,n),Be=(n,t)=>{if(t===null)return d.Option+o.ArgParamsSeparator;let r=n(t),e=r.indexOf(o.ArgParamsSeparator),i=r.substring(0,e),s=r.substring(e+1);return d.Option+o.ArgParamsSeparator+i+o.ArgParamsSeparator+s},$e=(...n)=>new v().nativeToString(d.Tuple,n),Ve=n=>new v().nativeToString(d.Struct,n),Oe=n=>new v().nativeToString(d.Vector,n);import ir from"ajv";var wt=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.ensureWarpText(this.pendingBrand.name,"name is required"),this.ensureWarpText(this.pendingBrand.description,"description is required"),typeof this.pendingBrand.logo=="string"&&this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,r){if(!t)throw new Error(`Warp: ${r}`)}ensureWarpText(t,r){if(!t)throw new Error(`Warp: ${r}`);if(typeof t=="object"&&Object.keys(t).length===0)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.schema?.brand||$.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),s=new ir,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};import ar from"ajv";var Q=class{constructor(t){this.config=t;this.config=t}async validate(t){let r=[];return r.push(...this.validatePrimaryAction(t)),r.push(...this.validateMaxOneValuePosition(t)),r.push(...this.validateVariableNamesAndResultNamesUppercase(t)),r.push(...this.validateAbiIsSetIfApplicable(t)),r.push(...await this.validateSchema(t)),{valid:r.length===0,errors:r}}validatePrimaryAction(t){try{let{action:r}=O(t);return r?[]:["Primary action is required"]}catch(r){return[r instanceof Error?r.message:"Primary action is required"]}}validateMaxOneValuePosition(t){return t.actions.filter(e=>e.inputs?e.inputs.some(i=>i.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let r=[],e=(i,s)=>{i&&Object.keys(i).forEach(a=>{a!==a.toUpperCase()&&r.push(`${s} name '${a}' must be uppercase`)})};return e(t.vars,"Variable"),e(t.output,"Output"),r}validateAbiIsSetIfApplicable(t){let r=t.actions.some(a=>a.type==="contract"),e=t.actions.some(a=>a.type==="query");if(!r&&!e)return[];let i=t.actions.some(a=>a.abi),s=Object.values(t.output||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.output&&!i&&s?["ABI is required when output is present for contract or query actions"]:[]}async validateSchema(t){try{let r=this.config.schema?.warp||$.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),s=new ar({strict:!1}),a=s.compile(i);return a(t)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(r){return[`Schema validation failed: ${r instanceof Error?r.message:String(r)}`]}}};var St=class{constructor(t){this.config=t;this.pendingWarp={protocol:k("warp"),chain:"",name:"",title:"",description:null,preview:"",actions:[]}}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.validate(e),e}async createFromUrl(t){return await(await fetch(t)).json()}setChain(t){return this.pendingWarp.chain=t,this}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensureWarpText(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,r=100){return ht(t,r)}ensure(t,r){if(!t)throw new Error(r)}ensureWarpText(t,r){if(!t)throw new Error(r);if(typeof t=="object"&&!t.en)throw new Error(r)}async validate(t){let e=await new Q(this.config).validate(t);if(!e.valid)throw new Error(e.errors.join(`
2
+ `))}};var D=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,or);return Date.now()>e.expiresAt?(localStorage.removeItem(this.getKey(t)),null):e.value}catch{return null}}set(t,r,e){let i={value:r,expiresAt:Date.now()+e*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(i,sr))}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)}}},It=new v,sr=(n,t)=>typeof t=="bigint"?It.nativeToString("biguint",t):t,or=(n,t)=>typeof t=="string"&&t.startsWith(d.Biguint+":")?It.stringToNative(t)[1]:t;var E=class E{get(t){let r=E.cache.get(t);return r?Date.now()>r.expiresAt?(E.cache.delete(t),null):r.value:null}set(t,r,e){let i=Date.now()+e*1e3;E.cache.set(t,{value:r,expiresAt:i})}forget(t){E.cache.delete(t)}clear(){E.cache.clear()}};E.cache=new Map;var q=E;var bt={OneMinute:60,OneHour:3600,OneDay:3600*24,OneWeek:3600*24*7,OneMonth:3600*24*30,OneYear:3600*24*365},Tt={Warp:(n,t)=>`warp:${n}:${t}`,WarpAbi:(n,t)=>`warp-abi:${n}:${t}`,WarpExecutable:(n,t,r)=>`warp-exec:${n}:${t}:${r}`,RegistryInfo:(n,t)=>`registry-info:${n}:${t}`,Brand:(n,t)=>`brand:${n}:${t}`,Asset:(n,t,r)=>`asset:${n}:${t}:${r}`},K=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new D:t==="memory"?new q:typeof window<"u"&&window.localStorage?new D:new q}set(t,r,e){this.strategy.set(t,r,e)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var R=class{constructor(t,r){this.config=t;this.adapter=r}async apply(t,r,e={}){let i=this.applyVars(t,r,e);return await this.applyGlobals(t,i)}async applyGlobals(t,r){let e={...r};return e.actions=await Promise.all(e.actions.map(async i=>await this.applyActionGlobals(i))),e=await this.applyRootGlobals(e,t),e}applyVars(t,r,e={}){if(!r?.vars)return r;let i=S(t,this.adapter.chainInfo.name),s=JSON.stringify(r),a=(c,p)=>{s=s.replace(new RegExp(`{{${c.toUpperCase()}}}`,"g"),p.toString())};return Object.entries(r.vars).forEach(([c,p])=>{if(typeof p!="string")a(c,p);else if(p.startsWith(o.Vars.Query+o.ArgParamsSeparator)){let l=p.slice(o.Vars.Query.length+1),[u,f]=l.split(o.ArgCompositeSeparator),g=t.currentUrl?new URLSearchParams(t.currentUrl.split("?")[1]).get(u):null,A=e.queries?.[u]||null||g;A&&a(c,A)}else if(p.startsWith(o.Vars.Env+o.ArgParamsSeparator)){let l=p.slice(o.Vars.Env.length+1),[u,f]=l.split(o.ArgCompositeSeparator),W={...t.vars,...e.envs}?.[u];W&&a(c,W)}else p===o.Source.UserWallet&&i?a(c,i):a(c,p)}),JSON.parse(s)}async applyRootGlobals(t,r){let e=JSON.stringify(t),i={config:r,adapter:this.adapter};return Object.values(o.Globals).forEach(s=>{let a=s.Accessor(i);a!=null&&(e=e.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),a.toString()))}),JSON.parse(e)}async applyActionGlobals(t){let r=JSON.stringify(t),e={config:this.config,adapter:this.adapter};return Object.values(o.Globals).forEach(i=>{let s=i.Accessor(e);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}applyInputs(t,r,e,i){if(!t||typeof t!="string"||!t.includes("{{"))return t;let s=this.applyGlobalsToText(t),a=this.buildInputBag(r,e,i);return N(s,a)}applyGlobalsToText(t){if(!Object.values(o.Globals).map(a=>a.Placeholder).some(a=>t.includes(`{{${a}}}`)))return t;let i={config:this.config,adapter:this.adapter},s=t;return Object.values(o.Globals).forEach(a=>{let c=a.Accessor(i);c!=null&&(s=s.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),c.toString()))}),s}buildInputBag(t,r,e){let i={};return t.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,c]=r.stringToNative(s.value);i[a]=String(c)}),e&&e.forEach(s=>{if(!s.value)return;let a=s.input.as||s.input.name,[,c]=r.stringToNative(s.value);if(i[`primary.${a}`]=String(c),s.input.type==="asset"&&typeof s.input.position=="object"){let p=c;p&&typeof p=="object"&&"identifier"in p&&"amount"in p&&(i[`primary.${a}.token`]=String(p.identifier),i[`primary.${a}.amount`]=String(p.amount))}}),i}};var L=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 v,this.cache=new K(t.cache?.type)}getSerializer(){return this.serializer}async createExecutable(t,r,e,i={}){let s=b(t,r);if(!s)throw new Error("WarpFactory: Action not found");let a=await this.getChainInfoForWarp(t,e),c=m(a.name,this.adapters),p=new R(this.config,c),l=await p.apply(this.config,t,i),u=b(l,r),{action:f,index:g}=O(l),W=this.getStringTypedInputs(f,e),A=await this.getResolvedInputs(a.name,f,W,p),h=this.getModifiedInputs(A),y=[],x=[];g===r-1&&(y=A,x=h);let P=x.find(C=>C.input.position==="receiver"||C.input.position==="destination")?.value,B=this.getDestinationFromAction(u),I=P?this.serializer.stringToNative(P)[1]:B;if(I&&(I=p.applyInputs(I,x,this.serializer,h)),!I&&s.type!=="collect")throw new Error("WarpActionExecutor: Destination/Receiver not provided");let Y=this.getPreparedArgs(u,x);Y=Y.map(C=>p.applyInputs(C,x,this.serializer,h));let Rt=x.find(C=>C.input.position==="value")?.value||null,Bt="value"in u?u.value:null,$t=Rt?.split(o.ArgParamsSeparator)[1]||Bt||"0",Vt=p.applyInputs($t,x,this.serializer,h),Ot=BigInt(Vt),Nt=x.filter(C=>C.input.position==="transfer"&&C.value).map(C=>C.value),Ut=[...("transfers"in u?u.transfers:[])||[],...Nt||[]].map(C=>{let jt=p.applyInputs(C,x,this.serializer,h);return this.serializer.stringToNative(jt)[1]}),Ht=x.find(C=>C.input.position==="data")?.value,Ft="data"in u?u.data||"":null,ct=Ht||Ft||null,Lt=ct?p.applyInputs(ct,x,this.serializer,h):null,lt={warp:l,chain:a,action:r,destination:I,args:Y,value:Ot,transfers:Ut,data:Lt,resolvedInputs:x};return this.cache.set(Tt.WarpExecutable(this.config.env,l.meta?.hash||"",r),lt.resolvedInputs,bt.OneWeek),lt}async getChainInfoForWarp(t,r){if(t.chain)return m(t.chain,this.adapters).chainInfo;if(r){let i=await this.tryGetChainFromInputs(t,r);if(i)return i}return this.adapters[0].chainInfo}getStringTypedInputs(t,r){let e=t.inputs||[];return r.map((i,s)=>{let a=e[s];return!a||i.includes(o.ArgParamsSeparator)?i:this.serializer.nativeToString(a.type,i)})}async getResolvedInputs(t,r,e,i){let s=r.inputs||[],a=await Promise.all(e.map(p=>this.preprocessInput(t,p))),c=(p,l)=>{if(p.source==="query"){let u=this.url.searchParams.get(p.name);return u?this.serializer.nativeToString(p.type,u):null}else if(p.source===o.Source.UserWallet){let u=S(this.config,t);return u?this.serializer.nativeToString("address",u):null}else if(p.source==="hidden"){if(p.default===void 0)return null;let u=i?i.applyInputs(String(p.default),[],this.serializer):String(p.default);return this.serializer.nativeToString(p.type,u)}else return a[l]||null};return s.map((p,l)=>{let u=c(p,l),f=p.default!==void 0?i?i.applyInputs(String(p.default),[],this.serializer):String(p.default):void 0;return{input:p,value:u||(f!==void 0?this.serializer.nativeToString(p.type,f):null)}})}getModifiedInputs(t){return t.map((r,e)=>{if(r.input.modifier?.startsWith("scale:")){let[,i]=r.input.modifier.split(":");if(isNaN(Number(i))){let s=Number(t.find(p=>p.input.name===i)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let a=r.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let c=z(a,+s);return{...r,value:`${r.input.type}:${c}`}}else{let s=r.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let a=z(s,+i);return{...r,value:`${r.input.type}:${a}`}}}else return r})}async preprocessInput(t,r){try{let[e,i]=it(r),s=m(t,this.adapters);if(e==="asset"){let[a,c,p]=i.split(o.ArgCompositeSeparator);if(p)return r;let l=await s.dataLoader.getAsset(a);if(!l)throw new Error(`WarpFactory: Asset not found for asset ${a}`);if(typeof l.decimals!="number")throw new Error(`WarpFactory: Decimals not found for asset ${a}`);let u=z(c,l.decimals);return Ct({...l,amount:u})}else return r}catch(e){throw w.warn("WarpFactory: Preprocess input failed",e),e}}getDestinationFromAction(t){if("address"in t&&t.address)return t.address;if("destination"in t&&t.destination){if(typeof t.destination=="string")return t.destination;if(typeof t.destination=="object"&&"url"in t.destination)return t.destination.url}return null}getPreparedArgs(t,r){let e="args"in t?t.args||[]:[],i=[];return r.forEach(({input:s,value:a})=>{if(!(!a||!s.position)){if(typeof s.position=="object"){if(s.type!=="asset")throw new Error(`WarpFactory: Object position is only supported for asset type. Input "${s.name}" has type "${s.type}"`);if(!s.position.token?.startsWith("arg:")||!s.position.amount?.startsWith("arg:"))throw new Error(`WarpFactory: Object position must have token and amount as arg:N. Input "${s.name}"`);let[c,p]=this.serializer.stringToNative(a),l=p;if(!l||typeof l!="object"||!("identifier"in l)||!("amount"in l))throw new Error(`WarpFactory: Invalid asset value for input "${s.name}"`);let u=Number(s.position.token.split(":")[1])-1,f=Number(s.position.amount.split(":")[1])-1;i.push({index:u,value:this.serializer.nativeToString("address",l.identifier)}),i.push({index:f,value:this.serializer.nativeToString("uint256",l.amount)})}else if(s.position.startsWith("arg:")){let c=Number(s.position.split(":")[1])-1;i.push({index:c,value:a})}}}),i.forEach(({index:s,value:a})=>{for(;e.length<=s;)e.push(void 0);e[s]=a}),e.filter(s=>s!==void 0)}async tryGetChainFromInputs(t,r){let e=t.actions.find(p=>p.inputs?.some(l=>l.position==="chain"));if(!e)return null;let i=e.inputs?.findIndex(p=>p.position==="chain");if(i===-1||i===void 0)return null;let s=r[i];if(!s)throw new Error("Chain input not found");let a=this.serializer.stringToNative(s)[1];return m(a,this.adapters).chainInfo}};var _=class{constructor(t,r,e){this.config=t;this.adapters=r;this.handlers=e;this.handlers=e,this.factory=new L(t,r)}async execute(t,r,e={}){let i=[],s=null,a=[],c=[],{action:p,index:l}=O(t);for(let u=1;u<=t.actions.length;u++){let f=b(t,u);if(!et(f,t))continue;let{tx:g,chain:W,immediateExecution:A,executable:h}=await this.executeAction(t,u,r,e);g&&i.push(g),W&&(s=W),A&&a.push(A),h&&u===l+1&&h.resolvedInputs&&(c=h.resolvedInputs.map(y=>y.value||"").filter(y=>y!==""))}if(!s&&i.length>0)throw new Error(`WarpExecutor: Chain not found for ${i.length} transactions`);if(i.length===0&&a.length>0){let u=a[a.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(u))}return{txs:i,chain:s,immediateExecutions:a,resolvedInputs:c}}async executeAction(t,r,e,i={}){let s=b(t,r);if(s.type==="link")return await this.callHandler(async()=>{let l=s.url;this.config.interceptors?.openLink?await this.config.interceptors.openLink(l):ut.open(l,"_blank")}),{tx:null,chain:null,immediateExecution:null,executable:null};let a=await this.factory.createExecutable(t,r,e,i);if(s.type==="collect"){let l=await this.executeCollect(a);return l.status==="success"?(await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):l.status==="unhandled"?(await this.callHandler(()=>this.handlers?.onActionUnhandled?.({action:r,chain:null,execution:l,tx:null})),{tx:null,chain:null,immediateExecution:l,executable:a}):(this.handlers?.onError?.({message:JSON.stringify(l.values)}),{tx:null,chain:null,immediateExecution:null,executable:a})}let c=m(a.chain.name,this.adapters);if(s.type==="query"){let l=await c.executor.executeQuery(a);return l.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:r,chain:a.chain,execution:l,tx:null})):this.handlers?.onError?.({message:JSON.stringify(l.values)}),{tx:null,chain:a.chain,immediateExecution:l,executable:a}}return{tx:await c.executor.createTransaction(a),chain:a.chain,immediateExecution:null,executable:a}}async evaluateOutput(t,r){if(r.length===0||t.actions.length===0||!this.handlers)return;let e=await this.factory.getChainInfoForWarp(t),i=m(e.name,this.adapters),s=(await Promise.all(t.actions.map(async(a,c)=>{if(!et(a,t)||a.type!=="transfer"&&a.type!=="contract")return null;let p=r[c],l=c+1;if(!p){let f={status:"error",warp:t,action:l,user:S(this.config,e.name),txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{},messages:{},destination:null};return await this.callHandler(()=>this.handlers?.onError?.({message:`Action ${l} failed: Transaction not found`})),f}let u=await i.output.getActionExecution(t,l,p);return u.status==="success"?await this.callHandler(()=>this.handlers?.onActionExecuted?.({action:l,chain:e,execution:u,tx:p})):await this.callHandler(()=>this.handlers?.onError?.({message:"Action failed: "+JSON.stringify(u.values)})),u}))).filter(a=>a!==null);if(s.every(a=>a.status==="success")){let a=s[s.length-1];await this.callHandler(()=>this.handlers?.onExecuted?.(a))}else await this.callHandler(()=>this.handlers?.onError?.({message:`Warp failed: ${JSON.stringify(s.map(a=>a.values))}`}))}async executeCollect(t,r){let e=S(this.config,t.chain.name),i=b(t.warp,t.action),s=this.factory.getSerializer(),a=J(t.resolvedInputs,s);if(i.destination&&typeof i.destination=="object"&&"url"in i.destination)return await this.doHttpRequest(t,i.destination,e,a,r);let{values:c,output:p}=await st(t.warp,a,t.action,t.resolvedInputs,s,this.config);return this.buildCollectResult(t,e,"unhandled",c,p)}async doHttpRequest(t,r,e,i,s){let a=new R(this.config,m(t.chain.name,this.adapters)),c=new Headers;if(c.set("Content-Type","application/json"),c.set("Accept","application/json"),this.handlers?.onSignRequest){if(!e)throw new Error(`No wallet configured for chain ${t.chain.name}`);let{message:f,nonce:g,expiresAt:W}=await ot(e,`${t.chain.name}-adapter`),A=await this.callHandler(()=>this.handlers?.onSignRequest?.({message:f,chain:t.chain}));if(A){let h=pt(e,A,g,W);Object.entries(h).forEach(([y,x])=>c.set(y,x))}}r.headers&&Object.entries(r.headers).forEach(([f,g])=>{let W=a.applyInputs(g,t.resolvedInputs,this.factory.getSerializer());c.set(f,W)});let p=r.method||"GET",l=p==="GET"?void 0:JSON.stringify({...i,...s}),u=a.applyInputs(r.url,t.resolvedInputs,this.factory.getSerializer());w.debug("WarpExecutor: Executing HTTP collect",{url:u,method:p,headers:c,body:l});try{let f=await fetch(u,{method:p,headers:c,body:l});w.debug("Collect response status",{status:f.status});let g=await f.json();w.debug("Collect response content",{content:g});let{values:W,output:A}=await st(t.warp,g,t.action,t.resolvedInputs,this.factory.getSerializer(),this.config);return this.buildCollectResult(t,S(this.config,t.chain.name),f.ok?"success":"error",W,A,g)}catch(f){return w.error("WarpActionExecutor: Error executing collect",f),{status:"error",warp:t.warp,action:t.action,user:e,txHash:null,tx:null,next:null,values:{string:[],native:[],mapped:{}},output:{_DATA:f},messages:{},destination:this.getDestinationFromResolvedInputs(t)}}}getDestinationFromResolvedInputs(t){return t.resolvedInputs.find(e=>e.input.position==="receiver"||e.input.position==="destination")?.value||t.destination}buildCollectResult(t,r,e,i,s,a){let c=xt(this.config,this.adapters,t.warp,t.action,s);return{status:e,warp:t.warp,action:t.action,user:r||S(this.config,t.chain.name),txHash:null,tx:null,next:c,values:i,output:a?{...s,_DATA:a}:s,messages:At(t.warp,s,this.config),destination:this.getDestinationFromResolvedInputs(t)}}async callHandler(t){if(t)return await t()}};var X=class{constructor(t){this.config=t}async search(t,r,e){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let i=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...e},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...r})});if(!i.ok)throw new Error(`WarpIndex: search failed with status ${i.status}: ${await i.text()}`);return(await i.json()).hits}catch(i){throw w.error("WarpIndex: Error searching for warps: ",i),i}}};var Z=class{constructor(t,r){this.config=t;this.adapters=r}isValid(t){return t.startsWith(o.HttpProtocolPrefix)?!!j(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,output:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),a=(await Promise.all(i)).filter(l=>l.match),c=a.length>0,p=a.map(l=>({url:l.url,warp:l.warp}));return{match:c,output:p}}async detect(t,r){let e={match:!1,url:t,warp:null,chain:null,registryInfo:null,brand:null},i=t.startsWith(o.HttpProtocolPrefix)?j(t):T(t);if(!i)return e;try{let{type:s,identifierBase:a}=i,c=null,p=null,l=null,u=m(i.chain,this.adapters),f=t.startsWith(o.HttpProtocolPrefix)?Wt(t):yt(i.identifier);if(s==="hash"){c=await u.builder().createFromTransactionHash(a,r);let W=await u.registry.getInfoByHash(a,r);p=W.registryInfo,l=W.brand}else if(s==="alias"){let W=await u.registry.getInfoByAlias(a,r);p=W.registryInfo,l=W.brand,W.registryInfo&&(c=await u.builder().createFromTransactionHash(W.registryInfo.hash,r))}c&&c.meta&&(pr(c,u.chainInfo.name,p,i.identifier),c.meta.query=f);let g=c?await new R(this.config,u).apply(this.config,c):null;return g?{match:!0,url:t,warp:g,chain:u.chainInfo.name,registryInfo:p,brand:l}:e}catch(s){return w.error("Error detecting warp link",s),e}}},pr=(n,t,r,e)=>{n.meta&&(n.meta.identifier=r?.alias?nt(t,"alias",r.alias):nt(t,"hash",r?.hash??e))};var Pt=class{constructor(t,r){this.config=t;this.adapters=r}getConfig(){return this.config}getAdapters(){return this.adapters}addAdapter(t){return this.adapters.push(t),this}createExecutor(t){return new _(this.config,this.adapters,t)}async detectWarp(t,r){return new Z(this.config,this.adapters).detect(t,r)}async executeWarp(t,r,e,i={}){let s=typeof t=="object",a=!s&&t.startsWith("http")&&t.endsWith(".json"),c=s?t:null;if(!c&&a){let A=await fetch(t);if(!A.ok)throw new Error("WarpClient: executeWarp - invalid url");c=await A.json()}if(c||(c=(await this.detectWarp(t,i.cache)).warp),!c)throw new Error("Warp not found");let p=this.createExecutor(e),{txs:l,chain:u,immediateExecutions:f,resolvedInputs:g}=await p.execute(c,r,{queries:i.queries});return{txs:l,chain:u,immediateExecutions:f,evaluateOutput:async A=>{await p.evaluateOutput(c,A)},resolvedInputs:g}}async createInscriptionTransaction(t,r){return await m(t,this.adapters).builder().createInscriptionTransaction(r)}async createFromTransaction(t,r,e=!1){return m(t,this.adapters).builder().createFromTransaction(r,e)}async createFromTransactionHash(t,r){let e=T(t);if(!e)throw new Error("WarpClient: createFromTransactionHash - invalid hash");return m(e.chain,this.adapters).builder().createFromTransactionHash(t,r)}async signMessage(t,r){if(!S(this.config,t))throw new Error(`No wallet configured for chain ${t}`);return m(t,this.adapters).wallet.signMessage(r)}async getActions(t,r,e=!1){let i=this.getDataLoader(t);return(await Promise.all(r.map(async a=>i.getAction(a,e)))).filter(a=>a!==null)}getExplorer(t){return m(t,this.adapters).explorer}getOutput(t){return m(t,this.adapters).output}async getRegistry(t){let r=m(t,this.adapters).registry;return await r.init(),r}getDataLoader(t){return m(t,this.adapters).dataLoader}getWallet(t){return m(t,this.adapters).wallet}get factory(){return new L(this.config,this.adapters)}get index(){return new X(this.config)}get linkBuilder(){return new F(this.config,this.adapters)}createBuilder(t){return m(t,this.adapters).builder()}createAbiBuilder(t){return m(t,this.adapters).abiBuilder()}createBrandBuilder(t){return m(t,this.adapters).brandBuilder()}createSerializer(t){return m(t,this.adapters).serializer}resolveText(t){return M(t,this.config)}};var Et=class{constructor(){this.typeHandlers=new Map;this.typeAliases=new Map}registerType(t,r){this.typeHandlers.set(t,r)}registerTypeAlias(t,r){this.typeAliases.set(t,r)}hasType(t){return this.typeHandlers.has(t)||this.typeAliases.has(t)}getHandler(t){let r=this.typeAliases.get(t);return r?this.getHandler(r):this.typeHandlers.get(t)}getAlias(t){return this.typeAliases.get(t)}resolveType(t){let r=this.typeAliases.get(t);return r?this.resolveType(r):t}getRegisteredTypes(){return Array.from(new Set([...this.typeHandlers.keys(),...this.typeAliases.keys()]))}};export{tt as BrowserCryptoProvider,bt as CacheTtl,rt as NodeCryptoProvider,Er as WARP_LANGUAGES,wt as WarpBrandBuilder,St as WarpBuilder,K as WarpCache,Tt as WarpCacheKey,Dt as WarpChainName,Pt as WarpClient,$ as WarpConfig,o as WarpConstants,_ as WarpExecutor,L as WarpFactory,X as WarpIndex,d as WarpInputTypes,R as WarpInterpolator,F as WarpLinkBuilder,Z as WarpLinkDetecter,w as WarpLogger,H as WarpProtocolVersions,v as WarpSerializer,Et as WarpTypeRegistry,Q as WarpValidator,Ee as address,At as applyOutputToMessages,Ct as asset,Te as biguint,Pe as bool,J as buildMappedOutput,Qt as buildNestedPayload,xr as bytesToBase64,qt as bytesToHex,G as cleanWarpIdentifier,pt as createAuthHeaders,ot as createAuthMessage,Cr as createCryptoProvider,ue as createHttpAuthHeaders,tr as createSignableMessage,Br as createWarpI18nText,nt as createWarpIdentifier,_t as evaluateOutputCommon,st as extractCollectOutput,j as extractIdentifierInfoFromUrl,yt as extractQueryStringFromIdentifier,Wt as extractQueryStringFromUrl,Ir as extractWarpSecrets,m as findWarpAdapterForChain,dt as getCryptoProvider,hr as getEventNameFromWarp,k as getLatestProtocolIdentifier,xt as getNextInfo,re as getProviderConfig,ft as getRandomBytes,gt as getRandomHex,b as getWarpActionByIndex,Wr as getWarpBrandLogoUrl,T as getWarpInfoFromIdentifier,O as getWarpPrimaryAction,rr as getWarpWalletAddress,S as getWarpWalletAddressFromConfig,nr as getWarpWalletMnemonic,me as getWarpWalletMnemonicFromConfig,er as getWarpWalletPrivateKey,he as getWarpWalletPrivateKeyFromConfig,Hr as hasInputPrefix,Re as hex,Or as isEqualWarpIdentifier,et as isWarpActionAutoExecute,Rr as isWarpI18nText,vt as mergeNestedPayload,Be as option,Yt as parseOutputOutIndex,fe as parseSignedMessage,N as replacePlaceholders,M as resolveWarpText,ut as safeWindow,Ar as setCryptoProvider,z as shiftBigintBy,it as splitInput,Ce as string,Ve as struct,vr as testCryptoAvailability,Kt as toInputPayloadValue,ht as toPreviewText,$e as tuple,Se as uint16,Ie as uint32,be as uint64,we as uint8,de as validateSignedMessage,Oe as vector};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "3.0.0-beta.158",
3
+ "version": "3.0.0-beta.160",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",