@vleap/warps 2.0.0-alpha.4 → 2.0.0-alpha.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +10 -7
- package/dist/index.d.ts +10 -7
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Transaction, TransactionOnNetwork, Address, TokenTransfer as TokenTransfer$1, AbiRegistry, NetworkEntrypoint
|
|
1
|
+
import { Transaction, TransactionOnNetwork, Address, TokenTransfer as TokenTransfer$1, AbiRegistry, NetworkEntrypoint } from '@multiversx/sdk-core';
|
|
2
2
|
import { TypedValue, Type, OptionValue, OptionalValue, List, VariadicValue, CompositeValue, StringValue, U8Value, U16Value, U32Value, U64Value, BigUIntValue, BooleanValue, AddressValue, TokenIdentifierValue, BytesValue, TokenTransfer, Struct, CodeMetadataValue, NothingValue, Transaction as Transaction$1, Address as Address$1 } from '@multiversx/sdk-core/out';
|
|
3
3
|
import QRCodeStyling from 'qr-code-styling';
|
|
4
4
|
|
|
@@ -29,6 +29,7 @@ type WarpConfig = {
|
|
|
29
29
|
currentUrl?: string;
|
|
30
30
|
userAddress?: string;
|
|
31
31
|
chainApiUrl?: string;
|
|
32
|
+
chainExplorerUrl?: string;
|
|
32
33
|
warpSchemaUrl?: string;
|
|
33
34
|
brandSchemaUrl?: string;
|
|
34
35
|
cacheTtl?: number;
|
|
@@ -44,7 +45,9 @@ type WarpCacheConfig = {
|
|
|
44
45
|
};
|
|
45
46
|
type ChainInfo = {
|
|
46
47
|
chainId: string;
|
|
48
|
+
blockTime: number;
|
|
47
49
|
apiUrl: string;
|
|
50
|
+
explorerUrl: string;
|
|
48
51
|
};
|
|
49
52
|
type WarpIdType = 'hash' | 'alias';
|
|
50
53
|
type WarpVarPlaceholder = string;
|
|
@@ -278,8 +281,9 @@ declare const Config: {
|
|
|
278
281
|
LatestBrandSchemaUrl: string;
|
|
279
282
|
DefaultClientUrl: (env: ChainEnv) => "https://usewarp.to" | "https://testnet.usewarp.to" | "https://devnet.usewarp.to";
|
|
280
283
|
SuperClientUrls: string[];
|
|
281
|
-
|
|
284
|
+
MainChain: {
|
|
282
285
|
ApiUrl: (env: ChainEnv) => "https://devnet-api.multiversx.com" | "https://testnet-api.multiversx.com" | "https://api.multiversx.com";
|
|
286
|
+
ExplorerUrl: (env: ChainEnv) => "https://devnet-explorer.multiversx.com" | "https://testnet-explorer.multiversx.com" | "https://explorer.multiversx.com";
|
|
283
287
|
};
|
|
284
288
|
Registry: {
|
|
285
289
|
Contract: (env: ChainEnv) => "erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36" | "####" | "erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe";
|
|
@@ -307,7 +311,7 @@ declare const WarpConstants: {
|
|
|
307
311
|
};
|
|
308
312
|
|
|
309
313
|
declare const getChainId: (env: ChainEnv) => string;
|
|
310
|
-
declare const
|
|
314
|
+
declare const getMainChainInfo: (config: WarpConfig) => ChainInfo;
|
|
311
315
|
declare const getLatestProtocolIdentifier: (name: ProtocolName) => string;
|
|
312
316
|
declare const getWarpActionByIndex: (warp: Warp, index: number) => WarpAction;
|
|
313
317
|
declare const toTypedRegistryInfo: (registryInfo: any) => RegistryInfo;
|
|
@@ -411,8 +415,8 @@ declare class WarpBuilder {
|
|
|
411
415
|
declare class WarpContractLoader {
|
|
412
416
|
private readonly config;
|
|
413
417
|
constructor(config: WarpConfig);
|
|
414
|
-
getContract(address: string): Promise<WarpContract | null>;
|
|
415
|
-
getVerificationInfo(address: string): Promise<WarpContractVerification | null>;
|
|
418
|
+
getContract(address: string, chain: ChainInfo): Promise<WarpContract | null>;
|
|
419
|
+
getVerificationInfo(address: string, chain: ChainInfo): Promise<WarpContractVerification | null>;
|
|
416
420
|
}
|
|
417
421
|
|
|
418
422
|
declare class WarpIndex {
|
|
@@ -486,7 +490,6 @@ declare class WarpUtils {
|
|
|
486
490
|
static getNextStepUrl(warp: Warp, actionIndex: number, config: WarpConfig): string | null;
|
|
487
491
|
static getChainInfoForAction(action: WarpTransferAction | WarpContractAction | WarpQueryAction, config: WarpConfig): Promise<ChainInfo>;
|
|
488
492
|
static getChainEntrypoint(chainInfo: ChainInfo, env: ChainEnv): NetworkEntrypoint;
|
|
489
|
-
static getConfiguredChainApi(config: WarpConfig): ApiNetworkProvider;
|
|
490
493
|
}
|
|
491
494
|
|
|
492
495
|
declare class WarpValidator {
|
|
@@ -500,4 +503,4 @@ declare class WarpValidator {
|
|
|
500
503
|
private throwUnless;
|
|
501
504
|
}
|
|
502
505
|
|
|
503
|
-
export { type AbiContents, type BaseWarpActionInputType, type Brand, BrandBuilder, type BrandColors, type BrandCta, type BrandMeta, type BrandUrls, CacheKey, type CacheType, type ChainEnv, type ChainInfo, Config, type ProtocolName, type RegistryInfo, type TrustStatus, type Warp, type WarpAbi, WarpAbiBuilder, type WarpAction, WarpActionExecutor, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, WarpArgSerializer, WarpBuilder, WarpCache, type WarpCacheConfig, type WarpChain, type WarpCollectAction, type WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractActionTransfer, WarpContractLoader, type WarpContractVerification, type WarpExecutionMessages, type WarpExecutionResult, type WarpExecutionResults, type WarpIdType, WarpIndex, WarpLink, type WarpLinkAction, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpQueryAction, WarpRegistry, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpTransferAction, WarpUtils, WarpValidator, type WarpVarPlaceholder, address, biguint, boolean, codemeta, composite, esdt, getChainId,
|
|
506
|
+
export { type AbiContents, type BaseWarpActionInputType, type Brand, BrandBuilder, type BrandColors, type BrandCta, type BrandMeta, type BrandUrls, CacheKey, type CacheType, type ChainEnv, type ChainInfo, Config, type ProtocolName, type RegistryInfo, type TrustStatus, type Warp, type WarpAbi, WarpAbiBuilder, type WarpAction, WarpActionExecutor, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, WarpArgSerializer, WarpBuilder, WarpCache, type WarpCacheConfig, type WarpChain, type WarpCollectAction, type WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractActionTransfer, WarpContractLoader, type WarpContractVerification, type WarpExecutionMessages, type WarpExecutionResult, type WarpExecutionResults, type WarpIdType, WarpIndex, WarpLink, type WarpLinkAction, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpQueryAction, WarpRegistry, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpTransferAction, WarpUtils, WarpValidator, type WarpVarPlaceholder, address, biguint, boolean, codemeta, composite, esdt, getChainId, getLatestProtocolIdentifier, getMainChainInfo, getWarpActionByIndex, hex, list, nothing, option, optional, shiftBigintBy, string, toPreviewText, toTypedChainInfo, toTypedRegistryInfo, token, u16, u32, u64, u8, variadic };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Transaction, TransactionOnNetwork, Address, TokenTransfer as TokenTransfer$1, AbiRegistry, NetworkEntrypoint
|
|
1
|
+
import { Transaction, TransactionOnNetwork, Address, TokenTransfer as TokenTransfer$1, AbiRegistry, NetworkEntrypoint } from '@multiversx/sdk-core';
|
|
2
2
|
import { TypedValue, Type, OptionValue, OptionalValue, List, VariadicValue, CompositeValue, StringValue, U8Value, U16Value, U32Value, U64Value, BigUIntValue, BooleanValue, AddressValue, TokenIdentifierValue, BytesValue, TokenTransfer, Struct, CodeMetadataValue, NothingValue, Transaction as Transaction$1, Address as Address$1 } from '@multiversx/sdk-core/out';
|
|
3
3
|
import QRCodeStyling from 'qr-code-styling';
|
|
4
4
|
|
|
@@ -29,6 +29,7 @@ type WarpConfig = {
|
|
|
29
29
|
currentUrl?: string;
|
|
30
30
|
userAddress?: string;
|
|
31
31
|
chainApiUrl?: string;
|
|
32
|
+
chainExplorerUrl?: string;
|
|
32
33
|
warpSchemaUrl?: string;
|
|
33
34
|
brandSchemaUrl?: string;
|
|
34
35
|
cacheTtl?: number;
|
|
@@ -44,7 +45,9 @@ type WarpCacheConfig = {
|
|
|
44
45
|
};
|
|
45
46
|
type ChainInfo = {
|
|
46
47
|
chainId: string;
|
|
48
|
+
blockTime: number;
|
|
47
49
|
apiUrl: string;
|
|
50
|
+
explorerUrl: string;
|
|
48
51
|
};
|
|
49
52
|
type WarpIdType = 'hash' | 'alias';
|
|
50
53
|
type WarpVarPlaceholder = string;
|
|
@@ -278,8 +281,9 @@ declare const Config: {
|
|
|
278
281
|
LatestBrandSchemaUrl: string;
|
|
279
282
|
DefaultClientUrl: (env: ChainEnv) => "https://usewarp.to" | "https://testnet.usewarp.to" | "https://devnet.usewarp.to";
|
|
280
283
|
SuperClientUrls: string[];
|
|
281
|
-
|
|
284
|
+
MainChain: {
|
|
282
285
|
ApiUrl: (env: ChainEnv) => "https://devnet-api.multiversx.com" | "https://testnet-api.multiversx.com" | "https://api.multiversx.com";
|
|
286
|
+
ExplorerUrl: (env: ChainEnv) => "https://devnet-explorer.multiversx.com" | "https://testnet-explorer.multiversx.com" | "https://explorer.multiversx.com";
|
|
283
287
|
};
|
|
284
288
|
Registry: {
|
|
285
289
|
Contract: (env: ChainEnv) => "erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36" | "####" | "erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe";
|
|
@@ -307,7 +311,7 @@ declare const WarpConstants: {
|
|
|
307
311
|
};
|
|
308
312
|
|
|
309
313
|
declare const getChainId: (env: ChainEnv) => string;
|
|
310
|
-
declare const
|
|
314
|
+
declare const getMainChainInfo: (config: WarpConfig) => ChainInfo;
|
|
311
315
|
declare const getLatestProtocolIdentifier: (name: ProtocolName) => string;
|
|
312
316
|
declare const getWarpActionByIndex: (warp: Warp, index: number) => WarpAction;
|
|
313
317
|
declare const toTypedRegistryInfo: (registryInfo: any) => RegistryInfo;
|
|
@@ -411,8 +415,8 @@ declare class WarpBuilder {
|
|
|
411
415
|
declare class WarpContractLoader {
|
|
412
416
|
private readonly config;
|
|
413
417
|
constructor(config: WarpConfig);
|
|
414
|
-
getContract(address: string): Promise<WarpContract | null>;
|
|
415
|
-
getVerificationInfo(address: string): Promise<WarpContractVerification | null>;
|
|
418
|
+
getContract(address: string, chain: ChainInfo): Promise<WarpContract | null>;
|
|
419
|
+
getVerificationInfo(address: string, chain: ChainInfo): Promise<WarpContractVerification | null>;
|
|
416
420
|
}
|
|
417
421
|
|
|
418
422
|
declare class WarpIndex {
|
|
@@ -486,7 +490,6 @@ declare class WarpUtils {
|
|
|
486
490
|
static getNextStepUrl(warp: Warp, actionIndex: number, config: WarpConfig): string | null;
|
|
487
491
|
static getChainInfoForAction(action: WarpTransferAction | WarpContractAction | WarpQueryAction, config: WarpConfig): Promise<ChainInfo>;
|
|
488
492
|
static getChainEntrypoint(chainInfo: ChainInfo, env: ChainEnv): NetworkEntrypoint;
|
|
489
|
-
static getConfiguredChainApi(config: WarpConfig): ApiNetworkProvider;
|
|
490
493
|
}
|
|
491
494
|
|
|
492
495
|
declare class WarpValidator {
|
|
@@ -500,4 +503,4 @@ declare class WarpValidator {
|
|
|
500
503
|
private throwUnless;
|
|
501
504
|
}
|
|
502
505
|
|
|
503
|
-
export { type AbiContents, type BaseWarpActionInputType, type Brand, BrandBuilder, type BrandColors, type BrandCta, type BrandMeta, type BrandUrls, CacheKey, type CacheType, type ChainEnv, type ChainInfo, Config, type ProtocolName, type RegistryInfo, type TrustStatus, type Warp, type WarpAbi, WarpAbiBuilder, type WarpAction, WarpActionExecutor, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, WarpArgSerializer, WarpBuilder, WarpCache, type WarpCacheConfig, type WarpChain, type WarpCollectAction, type WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractActionTransfer, WarpContractLoader, type WarpContractVerification, type WarpExecutionMessages, type WarpExecutionResult, type WarpExecutionResults, type WarpIdType, WarpIndex, WarpLink, type WarpLinkAction, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpQueryAction, WarpRegistry, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpTransferAction, WarpUtils, WarpValidator, type WarpVarPlaceholder, address, biguint, boolean, codemeta, composite, esdt, getChainId,
|
|
506
|
+
export { type AbiContents, type BaseWarpActionInputType, type Brand, BrandBuilder, type BrandColors, type BrandCta, type BrandMeta, type BrandUrls, CacheKey, type CacheType, type ChainEnv, type ChainInfo, Config, type ProtocolName, type RegistryInfo, type TrustStatus, type Warp, type WarpAbi, WarpAbiBuilder, type WarpAction, WarpActionExecutor, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, WarpArgSerializer, WarpBuilder, WarpCache, type WarpCacheConfig, type WarpChain, type WarpCollectAction, type WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractActionTransfer, WarpContractLoader, type WarpContractVerification, type WarpExecutionMessages, type WarpExecutionResult, type WarpExecutionResults, type WarpIdType, WarpIndex, WarpLink, type WarpLinkAction, type WarpMessageName, type WarpMeta, type WarpNativeValue, WarpProtocolVersions, type WarpQueryAction, WarpRegistry, type WarpResultName, type WarpResulutionPath, type WarpSearchHit, type WarpSearchResult, type WarpTransferAction, WarpUtils, WarpValidator, type WarpVarPlaceholder, address, biguint, boolean, codemeta, composite, esdt, getChainId, getLatestProtocolIdentifier, getMainChainInfo, getWarpActionByIndex, hex, list, nothing, option, optional, shiftBigintBy, string, toPreviewText, toTypedChainInfo, toTypedRegistryInfo, token, u16, u32, u64, u8, variadic };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var wt=Object.create;var Y=Object.defineProperty;var Tt=Object.getOwnPropertyDescriptor;var Wt=Object.getOwnPropertyNames;var Ct=Object.getPrototypeOf,At=Object.prototype.hasOwnProperty;var It=(o,t)=>{for(var e in t)Y(o,e,{get:t[e],enumerable:!0})},ot=(o,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Wt(t))!At.call(o,n)&&n!==e&&Y(o,n,{get:()=>t[n],enumerable:!(r=Tt(t,n))||r.enumerable});return o};var tt=(o,t,e)=>(e=o!=null?wt(Ct(o)):{},ot(t||!o||!o.__esModule?Y(e,"default",{value:o,enumerable:!0}):e,o)),bt=o=>ot(Y({},"__esModule",{value:!0}),o);var Mt={};It(Mt,{BrandBuilder:()=>it,CacheKey:()=>v,Config:()=>W,WarpAbiBuilder:()=>J,WarpActionExecutor:()=>st,WarpArgSerializer:()=>N,WarpBuilder:()=>K,WarpCache:()=>x,WarpConstants:()=>f,WarpContractLoader:()=>Z,WarpIndex:()=>at,WarpLink:()=>G,WarpProtocolVersions:()=>R,WarpRegistry:()=>B,WarpUtils:()=>h,WarpValidator:()=>k,address:()=>Lt,biguint:()=>$t,boolean:()=>Ot,codemeta:()=>Ht,composite:()=>Rt,esdt:()=>_t,getChainId:()=>b,getDefaultChainInfo:()=>_,getLatestProtocolIdentifier:()=>E,getWarpActionByIndex:()=>H,hex:()=>Dt,list:()=>Vt,nothing:()=>jt,option:()=>Bt,optional:()=>St,shiftBigintBy:()=>Q,string:()=>Et,toPreviewText:()=>rt,toTypedChainInfo:()=>et,toTypedRegistryInfo:()=>j,token:()=>qt,u16:()=>Ft,u32:()=>Nt,u64:()=>kt,u8:()=>Ut,variadic:()=>Pt});module.exports=bt(Mt);var F=require("@multiversx/sdk-core"),dt=tt(require("ajv"));var R={Warp:"1.3.0",Brand:"0.1.0",Abi:"0.1.0"},W={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${R.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${R.Brand}.schema.json`,DefaultClientUrl:o=>o==="devnet"?"https://devnet.usewarp.to":o==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],Chain:{ApiUrl:o=>o==="devnet"?"https://devnet-api.multiversx.com":o==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:o=>o==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":o==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var b=o=>o==="devnet"?"D":o==="testnet"?"T":"1",_=o=>({chainId:b(o.env),apiUrl:o.chainApiUrl||W.Chain.ApiUrl(o.env)}),E=o=>{if(o==="warp")return`warp:${R.Warp}`;if(o==="brand")return`brand:${R.Brand}`;if(o==="abi")return`abi:${R.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${o}`)},H=(o,t)=>o?.actions[t-1],j=o=>({hash:o.hash.toString("hex"),alias:o.alias?.toString()||null,trust:o.trust.toString(),creator:o.creator.toString(),createdAt:o.created_at.toNumber(),brand:o.brand?.toString("hex")||null,upgrade:o.upgrade?.toString("hex")||null}),et=o=>({chainId:o.chain_id.toString(),apiUrl:o.api_url.toString()}),Q=(o,t)=>{let e=o.toString(),[r,n=""]=e.split("."),i=Math.abs(t);if(t>0)return BigInt(r+n.padEnd(i,"0"));if(t<0){let a=r+n;if(i>=a.length)return 0n;let c=a.slice(0,-i)||"0";return BigInt(c)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},rt=(o,t=100)=>{if(!o)return"";let e=o.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e};var V=require("@multiversx/sdk-core");var f={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};var pt=tt(require("qr-code-styling"));var U=require("@multiversx/sdk-core");var M=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let r=JSON.parse(e);return Date.now()>r.expiresAt?(localStorage.removeItem(this.getKey(t)),null):r.value}catch{return null}}set(t,e,r){let n={value:e,expiresAt:Date.now()+r*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(n))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var z=class{constructor(){this.cache=new Map}get(t){let e=this.cache.get(t);return e?Date.now()>e.expiresAt?(this.cache.delete(t),null):e.value:null}set(t,e,r){let n=Date.now()+r*1e3;this.cache.set(t,{value:e,expiresAt:n})}clear(){this.cache.clear()}};var v={Warp:o=>`warp:${o}`,WarpAbi:o=>`warp-abi:${o}`,RegistryInfo:o=>`registry-info:${o}`,Brand:o=>`brand:${o}`,ChainInfo:o=>`chain:${o}`},x=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new M:t==="memory"?new z:typeof window<"u"&&window.localStorage?new M:new z}set(t,e,r){this.strategy.set(t,e,r)}get(t){return this.strategy.get(t)}clear(){this.strategy.clear()}};var ct=tt(require("ajv"));var k=class{constructor(t){this.config=t;this.config=t}async validate(t){this.ensureMaxOneValuePosition(t),this.ensureVariableNamesAndResultNamesUppercase(t),this.ensureAbiIsSetIfApplicable(t),await this.ensureValidSchema(t)}ensureMaxOneValuePosition(t){if(t.actions.filter(r=>r.inputs?r.inputs.some(n=>n.position==="value"):!1).length>1)throw new Error("WarpBuilder: only one value position action is allowed")}ensureVariableNamesAndResultNamesUppercase(t){let e=r=>{r&&Object.keys(r).forEach(n=>{if(n!==n.toUpperCase())throw new Error(`WarpValidator: variable/result name '${n}' must be uppercase`)})};e(t.vars),e(t.results)}ensureAbiIsSetIfApplicable(t){let e=t.actions.some(n=>n.type==="contract"),r=t.actions.some(n=>n.type==="query");!e&&!r||this.throwUnless(!!t.results,"results are required if there are contract or query actions")}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||W.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),i=new ct.default,a=i.compile(n);this.throwUnless(a(t),`WarpValidator: schema validation failed: ${i.errorsText(a.errors)}`)}throwUnless(t,e){if(!t)throw new Error(`WarpValidator: ${e}`)}};var K=class{constructor(t){this.pendingWarp={protocol:E("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t,this.cache=new x(t.cacheType)}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new U.TransactionsFactoryConfig({chainID:b(this.config.env)}),r=new U.TransferTransactionsFactory({config:e}),n=U.Address.newFromBech32(this.config.userAddress),i=JSON.stringify(t),a=r.createTransactionForTransfer(n,{receiver:U.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))});return a.gasLimit=a.gasLimit+BigInt(2e6),a}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await new k(this.config).validate(r),h.prepareVars(r,this.config)}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=v.Warp(t);if(e){let i=this.cache.get(r);if(i)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),i}let n=h.getConfiguredChainApi(this.config);try{let i=await n.getTransaction(t),a=await this.createFromTransaction(i);return e&&e.ttl&&a&&this.cache.set(r,a,e.ttl),a}catch(i){return console.error("WarpBuilder: Error creating from transaction hash",i),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await new k(this.config).validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return rt(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}};var m=require("@multiversx/sdk-core/out");var nt={buildInfo:{rustc:{version:"1.80.0-nightly",commitHash:"791adf759cc065316f054961875052d5bc03e16c",commitDate:"2024-05-21",channel:"Nightly",short:"rustc 1.80.0-nightly (791adf759 2024-05-21)"},contractCrate:{name:"registry",version:"0.0.1"},framework:{name:"multiversx-sc",version:"0.51.1"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"},{name:"vault",type:"Address"}],outputs:[]},upgradeConstructor:{inputs:[],outputs:[]},endpoints:[{name:"registerWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias_opt",type:"optional<bytes>",multi_arg:!0},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],outputs:[],allow_multiple_var_args:!0},{name:"unregisterWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"upgradeWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"alias",type:"bytes"},{name:"new_warp",type:"bytes"}],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"verifyWarp",onlyOwner:!0,mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<InfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"setVault",onlyOwner:!0,mutability:"mutable",inputs:[{name:"vault",type:"Address"}],outputs:[]},{name:"setUnitPrice",onlyOwner:!0,mutability:"mutable",inputs:[{name:"amount",type:"BigUint"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"BigUint"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0}]},{identifier:"warpVerified",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"creator",type:"Address"},{name:"created_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var B=class{constructor(t){this.config=t,this.cache=new x(t.cacheType),this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(this.config.userAddress),n=e?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:n,arguments:e?[m.BytesValue.fromHex(t),m.BytesValue.fromUTF8(e)]:[m.BytesValue.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=m.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[m.BytesValue.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.BytesValue.fromUTF8(t),m.BytesValue.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.BytesValue.fromHex(t),m.BytesValue.fromUTF8(e)]})}createWarpVerifyTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=m.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[m.BytesValue.fromHex(t)]})}createBrandRegisterTransaction(t){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=m.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.BytesValue.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.BytesValue.fromHex(t),m.BytesValue.fromHex(e)]})}async getInfoByAlias(t,e){let r=v.RegistryInfo(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),a=this.getController(),c=a.createQuery({contract:i,function:"getInfoByAlias",arguments:[m.BytesValue.fromUTF8(t)]}),u=await a.runQuery(c),[l]=a.parseQueryResponse(u),d=l?j(l):null,g=d?.brand?await this.fetchBrand(d.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:d,brand:g},e.ttl),{registryInfo:d,brand:g}}async getInfoByHash(t,e){let r=v.RegistryInfo(t);if(e){let g=this.cache.get(r);if(g)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),g}let n=this.getRegistryContractAddress(),i=this.getController(),a=i.createQuery({contract:n,function:"getInfoByHash",arguments:[m.BytesValue.fromHex(t)]}),c=await i.runQuery(a),[u]=i.parseQueryResponse(c),l=u?j(u):null,d=l?.brand?await this.fetchBrand(l.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:l,brand:d},e.ttl),{registryInfo:l,brand:d}}async getUserWarpRegistryInfos(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getUserWarps",arguments:[new m.AddressValue(new m.Address(e))]}),a=await n.runQuery(i),[c]=n.parseQueryResponse(a);return c.map(j)}async getUserBrands(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getUserBrands",arguments:[new m.AddressValue(new m.Address(e))]}),a=await n.runQuery(i),[c]=n.parseQueryResponse(a),u=c.map(g=>g.toString("hex")),l={ttl:365*24*60*60};return(await Promise.all(u.map(g=>this.fetchBrand(g,l)))).filter(g=>g!==null)}async getChainInfo(t,e){let r=v.ChainInfo(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),a=this.getController(),c=a.createQuery({contract:i,function:"getChain",arguments:[m.BytesValue.fromUTF8(t)]}),u=await a.runQuery(c),[l]=a.parseQueryResponse(u),d=l?et(l):null;return d&&e?.ttl&&this.cache.set(r,d,e.ttl),d}async fetchBrand(t,e){let r=v.Brand(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let i=h.getConfiguredChainApi(this.config);try{let a=await i.getTransaction(t),c=JSON.parse(a.data.toString());return c.meta={hash:a.hash,creator:a.sender.bech32(),createdAt:new Date(a.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,c,e.ttl),c}catch(a){return console.error("WarpRegistry: Error fetching brand from transaction hash",a),null}}getRegistryContractAddress(){return m.Address.newFromBech32(this.config.registryContract||W.Registry.Contract(this.config.env))}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),[r]=await e.query({contract:t,function:"getConfig",arguments:[]}),n=BigInt(r.toString());this.unitPrice=n}getFactory(){let t=new m.TransactionsFactoryConfig({chainID:b(this.config.env)}),e=m.AbiRegistry.create(nt);return new m.SmartContractTransactionsFactory({config:t,abi:e})}getController(){let t=_(this.config),e=h.getChainEntrypoint(t,this.config.env),r=m.AbiRegistry.create(nt);return e.createSmartContractController(r)}};var G=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(f.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),a=(await Promise.all(n)).filter(l=>l.match),c=a.length>0,u=a.map(l=>({url:l.url,warp:l.warp}));return{match:c,results:u}}async detect(t){let e=t.startsWith(f.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):h.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:n}=e,i=new K(this.config),a=new B(this.config),c=null,u=null,l=null;if(r==="hash"){c=await i.createFromTransactionHash(n);try{let{registryInfo:d,brand:g}=await a.getInfoByHash(n);u=d,l=g}catch{}}else if(r==="alias"){let{registryInfo:d,brand:g}=await a.getInfoByAlias(n);u=d,l=g,d&&(c=await i.createFromTransactionHash(d.hash))}return c?{match:!0,url:t,warp:c,registryInfo:u,brand:l}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||W.DefaultClientUrl(this.config.env),n=t===f.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+f.IdentifierParamSeparator+e);return W.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${f.IdentifierParamName}=${n}`}generateQrCode(t,e,r=512,n="white",i="black",a="#23F7DD"){let c=this.build(t,e);return new pt.default({type:"svg",width:r,height:r,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:n},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(a)}" 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>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=W.SuperClientUrls.includes(e.origin),n=e.searchParams.get(f.IdentifierParamName),i=r&&!n?e.pathname.split("/")[1]:n;if(!i)return null;let a=decodeURIComponent(i);return h.getInfoFromPrefixedIdentifier(a)}};var xt="https://",ut="query",lt="env",h=class o{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),n=(i,a)=>{r=r.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),a.toString())};return Object.entries(t.vars).forEach(([i,a])=>{if(typeof a=="string"&&a.startsWith(`${ut}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let c=a.split(`${ut}:`)[1],u=new URL(e.currentUrl).searchParams.get(c);u&&n(i,u)}else if(typeof a=="string"&&a.startsWith(`${lt}:`)){let c=a.split(`${lt}:`)[1],u=e.vars?.[c];u&&n(i,u)}else n(i,a)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(f.IdentifierParamSeparator)?e:`${f.IdentifierType.Alias}${f.IdentifierParamSeparator}${e}`,[n,i]=r.split(f.IdentifierParamSeparator);return{type:n,id:i}}static getNextStepUrl(t,e,r){let n=t.next||t.actions?.[e]?.next||null;if(!n)return null;if(n.startsWith(xt))return n;{let i=new G(r),a=o.getInfoFromPrefixedIdentifier(n);return a?i.build(a.type,a.id):null}}static async getChainInfoForAction(t,e){if(!t.chain)return _(e);let r=await new B(e).getChainInfo(t.chain);if(!r)throw new Error(`WarpActionExecutor: Chain info not found for ${t.chain}`);return r}static getChainEntrypoint(t,e){let r="warp-sdk",n="api";return e==="devnet"?new V.DevnetEntrypoint(t.apiUrl,n,r):e==="testnet"?new V.TestnetEntrypoint(t.apiUrl,n,r):new V.MainnetEntrypoint(t.apiUrl,n,r)}static getConfiguredChainApi(t){let e=t.chainApiUrl||W.Chain.ApiUrl(t.env);if(!e)throw new Error("WarpUtils: Chain API URL not configured");return new V.ApiNetworkProvider(e,{timeout:3e4,clientName:"warp-sdk"})}};var it=class{constructor(t){this.pendingBrand={protocol:E("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let e=new F.TransactionsFactoryConfig({chainID:b(this.config.env)}),r=new F.TransferTransactionsFactory({config:e}),n=F.Address.newFromBech32(this.config.userAddress),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer(n,{receiver:F.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))})}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.ensureValidSchema(r),r}async createFromTransaction(t,e=!1){return await this.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=h.getConfiguredChainApi(this.config);try{let r=await e.getTransaction(t);return this.createFromTransaction(r)}catch(r){return console.error("BrandBuilder: Error creating from transaction hash",r),null}}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.brandSchemaUrl||W.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),i=new dt.default,a=i.compile(n);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(a.errors)}`)}};var p=require("@multiversx/sdk-core/out"),Bt=(o,t)=>o?p.OptionValue.newProvided(o):t?p.OptionValue.newMissingTyped(t):p.OptionValue.newMissing(),St=(o,t)=>o?new p.OptionalValue(o.getType(),o):t?new p.OptionalValue(t):p.OptionalValue.newMissing(),Vt=o=>{if(o.length===0)throw new Error("Cannot create a list from an empty array");let t=o[0].getType();return new p.List(t,o)},Pt=o=>p.VariadicValue.fromItems(...o),Rt=o=>{let t=o.map(e=>e.getType());return new p.CompositeValue(new p.CompositeType(...t),o)},Et=o=>p.StringValue.fromUTF8(o),Ut=o=>new p.U8Value(o),Ft=o=>new p.U16Value(o),Nt=o=>new p.U32Value(o),kt=o=>new p.U64Value(o),$t=o=>new p.BigUIntValue(BigInt(o)),Ot=o=>new p.BooleanValue(o),Lt=o=>new p.AddressValue(p.Address.newFromBech32(o)),qt=o=>new p.TokenIdentifierValue(o),Dt=o=>p.BytesValue.fromHex(o),_t=o=>new p.Struct(new p.StructType("EsdtTokenPayment",[new p.FieldDefinition("token_identifier","",new p.TokenIdentifierType),new p.FieldDefinition("token_nonce","",new p.U64Type),new p.FieldDefinition("amount","",new p.BigUIntType)]),[new p.Field(new p.TokenIdentifierValue(o.token.identifier),"token_identifier"),new p.Field(new p.U64Value(BigInt(o.token.nonce)),"token_nonce"),new p.Field(new p.BigUIntValue(BigInt(o.amount)),"amount")]),Ht=o=>new p.CodeMetadataValue(p.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(o,"hex")))),jt=()=>new p.NothingValue;var $=require("@multiversx/sdk-core");var J=class{constructor(t){this.cache=new x;this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new $.TransactionsFactoryConfig({chainID:b(this.config.env)}),r=new $.TransferTransactionsFactory({config:e}),n={protocol:E("abi"),content:t},i=$.Address.newFromBech32(this.config.userAddress),a=JSON.stringify(n),c=r.createTransactionForTransfer(i,{receiver:i,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(a))});return c.gasLimit=c.gasLimit+BigInt(2e6),c}async createFromRaw(t){return JSON.parse(t)}async createFromTransaction(t){let e=await this.createFromRaw(t.data.toString());return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,e){let r=v.WarpAbi(t);if(e){let i=this.cache.get(r);if(i)return console.log(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),i}let n=h.getConfiguredChainApi(this.config);try{let i=await n.getTransaction(t),a=await this.createFromTransaction(i);return e&&e.ttl&&a&&this.cache.set(r,a,e.ttl),a}catch(i){return console.error("WarpAbiBuilder: Error creating from transaction hash",i),null}}};var y=require("@multiversx/sdk-core");var O=require("@multiversx/sdk-core/out");var s=require("@multiversx/sdk-core/out");var gt=new RegExp(`${f.ArgParamsSeparator}(.*)`),N=class{nativeToString(t,e){return t==="esdt"&&e instanceof s.TokenTransfer?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(s.OptionValue.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(s.OptionalValue.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(s.List.ClassName)){let e=t.getItems(),n=e.map(a=>this.typedToString(a).split(f.ArgParamsSeparator)[0])[0],i=e.map(a=>this.typedToString(a).split(f.ArgParamsSeparator)[1]);return`list:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(s.VariadicValue.ClassName)){let e=t.getItems(),n=e.map(a=>this.typedToString(a).split(f.ArgParamsSeparator)[0])[0],i=e.map(a=>this.typedToString(a).split(f.ArgParamsSeparator)[1]);return`variadic:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(s.CompositeValue.ClassName)){let e=t.getItems(),r=e.map(c=>this.typedToString(c).split(f.ArgParamsSeparator)[0]),n=e.map(c=>this.typedToString(c).split(f.ArgParamsSeparator)[1]),i=r.join(f.ArgCompositeSeparator),a=n.join(f.ArgCompositeSeparator);return`composite(${i}):${a}`}if(t.hasClassOrSuperclass(s.BigUIntValue.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(s.U8Value.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(s.U16Value.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(s.U32Value.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(s.U64Value.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(s.StringValue.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(s.BooleanValue.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(s.AddressValue.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(s.TokenIdentifierValue.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(s.BytesValue.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(s.CodeMetadataValue.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),n=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${n}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.stringToNative(e)}nativeToTyped(t,e){let r=this.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new s.CompositeType(...e.split(f.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new s.StringType;if(t==="uint8")return new s.U8Type;if(t==="uint16")return new s.U16Type;if(t==="uint32")return new s.U32Type;if(t==="uint64")return new s.U64Type;if(t==="biguint")return new s.BigUIntType;if(t==="bool")return new s.BooleanType;if(t==="address")return new s.AddressType;if(t==="token")return new s.TokenIdentifierType;if(t==="hex")return new s.BytesType;if(t==="codemeta")return new s.CodeMetadataType;if(t==="esdt"||t==="nft")return new s.StructType("EsdtTokenPayment",[new s.FieldDefinition("token_identifier","",new s.TokenIdentifierType),new s.FieldDefinition("token_nonce","",new s.U64Type),new s.FieldDefinition("amount","",new s.BigUIntType)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(f.ArgParamsSeparator),r=e[0],n=e.slice(1).join(f.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[i,a]=n.split(f.ArgParamsSeparator);return[`option:${i}`,a||null]}else if(r==="optional"){let[i,a]=n.split(f.ArgParamsSeparator);return[`optional:${i}`,a||null]}else if(r==="list"){let i=n.split(f.ArgParamsSeparator),a=i.slice(0,-1).join(f.ArgParamsSeparator),c=i[i.length-1],l=(c?c.split(","):[]).map(d=>this.stringToNative(`${a}:${d}`)[1]);return[`list:${a}`,l]}else if(r==="variadic"){let i=n.split(f.ArgParamsSeparator),a=i.slice(0,-1).join(f.ArgParamsSeparator),c=i[i.length-1],l=(c?c.split(","):[]).map(d=>this.stringToNative(`${a}:${d}`)[1]);return[`variadic:${a}`,l]}else if(r.startsWith("composite")){let i=r.match(/\(([^)]+)\)/)?.[1]?.split(f.ArgCompositeSeparator),c=n.split(f.ArgCompositeSeparator).map((u,l)=>this.stringToNative(`${i[l]}:${u}`)[1]);return[r,c]}else{if(r==="string")return[r,n];if(r==="uint8"||r==="uint16"||r==="uint32")return[r,Number(n)];if(r==="uint64"||r==="biguint")return[r,BigInt(n||0)];if(r==="bool")return[r,n==="true"];if(r==="address")return[r,n];if(r==="token")return[r,n];if(r==="hex")return[r,n];if(r==="codemeta")return[r,n];if(r==="esdt"){let[i,a,c]=n.split(f.ArgCompositeSeparator);return[r,new s.TokenTransfer({token:new s.Token({identifier:i,nonce:BigInt(a)}),amount:BigInt(c)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new s.NothingValue;if(e==="option"){let n=this.stringToTyped(r);return n instanceof s.NothingValue?s.OptionValue.newMissingTyped(n.getType()):s.OptionValue.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof s.NothingValue?s.OptionalValue.newMissing():new s.OptionalValue(n.getType(),n)}if(e==="list"){let[n,i]=r.split(gt,2),c=i.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new s.List(this.nativeToType(n),c)}if(e==="variadic"){let[n,i]=r.split(gt,2),c=i.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new s.VariadicValue(new s.VariadicType(this.nativeToType(n)),c)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],i=r.split(f.ArgCompositeSeparator),a=n.split(f.ArgCompositeSeparator),c=i.map((l,d)=>this.stringToTyped(`${a[d]}:${l}`)),u=c.map(l=>l.getType());return new s.CompositeValue(new s.CompositeType(...u),c)}if(e==="string")return r?s.StringValue.fromUTF8(r):new s.NothingValue;if(e==="uint8")return r?new s.U8Value(Number(r)):new s.NothingValue;if(e==="uint16")return r?new s.U16Value(Number(r)):new s.NothingValue;if(e==="uint32")return r?new s.U32Value(Number(r)):new s.NothingValue;if(e==="uint64")return r?new s.U64Value(BigInt(r)):new s.NothingValue;if(e==="biguint")return r?new s.BigUIntValue(BigInt(r)):new s.NothingValue;if(e==="bool")return r?new s.BooleanValue(typeof r=="boolean"?r:r==="true"):new s.NothingValue;if(e==="address")return r?new s.AddressValue(s.Address.newFromBech32(r)):new s.NothingValue;if(e==="token")return r?new s.TokenIdentifierValue(r):new s.NothingValue;if(e==="hex")return r?s.BytesValue.fromHex(r):new s.NothingValue;if(e==="codemeta")return new s.CodeMetadataValue(s.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(f.ArgCompositeSeparator);return new s.Struct(this.nativeToType("esdt"),[new s.Field(new s.TokenIdentifierValue(n[0]),"token_identifier"),new s.Field(new s.U64Value(BigInt(n[1])),"token_nonce"),new s.Field(new s.BigUIntValue(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof s.OptionType)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof s.OptionalType)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof s.ListType)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof s.VariadicType)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof s.StringType)return"string";if(t instanceof s.U8Type)return"uint8";if(t instanceof s.U16Type)return"uint16";if(t instanceof s.U32Type)return"uint32";if(t instanceof s.U64Type)return"uint64";if(t instanceof s.BigUIntType)return"biguint";if(t instanceof s.BooleanType)return"bool";if(t instanceof s.AddressType)return"address";if(t instanceof s.TokenIdentifierType)return"token";if(t instanceof s.BytesType)return"hex";if(t instanceof s.CodeMetadataType)return"codemeta";if(t instanceof s.StructType&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var ft=async(o,t,e,r)=>{let n=[],i={};if(!t.results||!e.abi||e.type!=="contract")return{values:n,results:i};let a=await o.getAbiForAction(e),c=new O.TransactionEventsParser({abi:a}),l=new O.SmartContractTransactionsOutcomeParser({abi:a}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[d,g]of Object.entries(t.results)){let[T,w,A]=g.split(".");if(T==="event"){if(!w||isNaN(Number(A)))continue;let P=Number(A),I=(0,O.findEventsByFirstTopic)(r,w),L=c.parseEvents({events:I})[0],S=Object.values(L)[P]||null;n.push(S),i[d]=S&&S.valueOf()}else if(T==="out"){if(!w)continue;let P=Number(w),I=l.values[P-1]||null;n.push(I),i[d]=I&&I.valueOf()}}return{values:n,results:i}},mt=async(o,t)=>{let e=new N,r=t.map(c=>e.typedToString(c)),n=t.map(c=>e.typedToNative(c)[1]),i={};if(!o.results)return{values:r,results:i};let a=c=>{let u=c.split(".").slice(1).map(d=>parseInt(d)-1);if(u.length===0)return;let l=n[u[0]];for(let d=1;d<u.length;d++){if(l==null)return;l=l[u[d]]}return l};return Object.entries(o.results).forEach(([c,u])=>{if(u.startsWith("out.")){let l=a(u);i[c]=l||null}}),{values:r,results:i}},ht=async(o,t)=>{let e=[],r={};for(let[n,i]of Object.entries(o.results||{})){let[a,...c]=i.split(".");if(a!=="out"||!c.length)continue;let u=c.reduce((l,d)=>l?.[d],t);e.push(u),r[n]=u}return{values:e,results:r}};var Qt=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],yt=o=>Qt.find(t=>t.id===o)||null;var Z=class{constructor(t){this.config=t}async getContract(t){try{let r=await h.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{address:t,owner:r.ownerAddress,verified:r.isVerified}}catch(e){return console.error("WarpContractLoader: getContract error",e),null}}async getVerificationInfo(t){try{let r=await h.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{codeHash:r.codeHash,abi:r.source.abi}}catch(e){return console.error("WarpContractLoader: getVerificationInfo error",e),null}}};var st=class{constructor(t){if(!t.currentUrl)throw new Error("WarpActionExecutor: currentUrl config not set");this.config=t,this.url=new URL(t.currentUrl),this.serializer=new N,this.contractLoader=new Z(t),this.registry=new B(t)}async createTransactionForExecute(t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let r=y.Address.newFromBech32(this.config.userAddress),n=await h.getChainInfoForAction(t,this.config),i=new y.TransactionsFactoryConfig({chainID:n.chainId}),{destination:a,args:c,value:u,transfers:l,data:d}=await this.getTxComponentsFromInputs(t,e,r),g=c.map(T=>this.serializer.stringToTyped(T));if(t.type==="transfer")return new y.TransferTransactionsFactory({config:i}).createTransactionForTransfer(r,{receiver:a,nativeAmount:u,tokenTransfers:l,data:d?new Uint8Array(d):void 0});if(t.type==="contract"&&a.isSmartContract())return new y.SmartContractTransactionsFactory({config:i}).createTransactionForExecute(r,{contract:a,function:"func"in t&&t.func||"",gasLimit:"gasLimit"in t?BigInt(t.gasLimit||0):0n,arguments:g,tokenTransfers:l,nativeTransferAmount:u});throw t.type==="query"?new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead"):t.type==="collect"?new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead"):new Error(`WarpActionExecutor: Invalid action type (${t.type})`)}async getTransactionExecutionResults(t,e,r){let n=H(t,e),i=h.getNextStepUrl(t,e,this.config),{values:a,results:c}=await ft(this,t,n,r),u=this.getPreparedMessages(t,c);return{success:r.status.isSuccessful(),warp:t,action:e,user:this.config.userAddress||null,txHash:r.hash,redirectUrl:i,values:a,results:c,messages:u}}async executeQuery(t,e,r){let n=H(t,e);if(!n)throw new Error("WarpActionExecutor: Action not found");if(!n.func)throw new Error("WarpActionExecutor: Function not found");let i=await h.getChainInfoForAction(n,this.config),a=await this.getAbiForAction(n),{args:c}=await this.getTxComponentsFromInputs(n,r),u=c.map(D=>this.serializer.stringToTyped(D)),l=h.getChainEntrypoint(i,this.config.env),d=y.Address.newFromBech32(n.address),g=l.createSmartContractController(a),T=g.createQuery({contract:d,function:n.func,arguments:u}),w=await g.runQuery(T),A=w.returnCode==="ok",P=new y.ArgSerializer,I=a.getEndpoint(w.function),L=w.returnDataParts.map(D=>Buffer.from(D)),S=P.buffersToValues(L,I.output),{values:X,results:q}=await mt(t,S);return{success:A,warp:t,action:e,user:this.config.userAddress||null,txHash:null,redirectUrl:n.next||null,values:X,results:q,messages:this.getPreparedMessages(t,q)}}async executeCollect(t,e,r,n){let i=H(t,e);if(!i)throw new Error("WarpActionExecutor: Action not found");let a=await this.getResolvedInputs(i,r),c=this.getModifiedInputs(a),u=g=>{if(!g.value)return null;let T=this.serializer.stringToNative(g.value)[1];if(g.input.type==="biguint")return T.toString();if(g.input.type==="esdt"){let w=T;return{token:w.token.identifier,nonce:w.token.nonce.toString(),amount:w.amount.toString()}}else return T},l=Object.fromEntries(c.map(g=>[g.input.as||g.input.name,u(g)])),d=new Headers;d.set("Content-Type","application/json"),d.set("Accept","application/json"),Object.entries(i.destination.headers).forEach(([g,T])=>{d.set(g,T)});try{let g=await fetch(i.destination.url,{method:i.destination.method,headers:d,body:JSON.stringify({inputs:l,meta:n})}),T=await g.json(),{values:w,results:A}=await ht(t,T);return{success:g.ok,warp:t,action:e,user:this.config.userAddress||null,txHash:null,redirectUrl:i.next||null,values:w,results:A,messages:this.getPreparedMessages(t,A)}}catch(g){return console.error(g),{success:!1,warp:t,action:e,user:this.config.userAddress||null,txHash:null,redirectUrl:null,values:[],results:{},messages:{}}}}async getTxComponentsFromInputs(t,e,r){let n=await this.getResolvedInputs(t,e),i=this.getModifiedInputs(n),a=i.find(C=>C.input.position==="receiver")?.value,c="address"in t?t.address:null,u=a?.split(":")[1]||c||r?.toBech32();if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let l=y.Address.newFromBech32(u),d=this.getPreparedArgs(t,i),g=i.find(C=>C.input.position==="value")?.value||null,T="value"in t?t.value:null,w=BigInt(g?.split(":")[1]||T||0),A=i.filter(C=>C.input.position==="transfer"&&C.value).map(C=>C.value),I=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...A?.map(C=>this.serializer.stringToNative(C)[1])||[]],L=i.find(C=>C.input.position==="data")?.value,S="data"in t?t.data||"":null,X=L||S||null,q=X?this.serializer.stringToTyped(X).valueOf():null,D=q?Buffer.from(q):null;return{destination:l,args:d,value:w,transfers:I,data:D}}async getResolvedInputs(t,e){let r=t.inputs||[],n=await Promise.all(e.map(a=>this.preprocessInput(a))),i=(a,c)=>{if(a.source==="query"){let u=this.url.searchParams.get(a.name);return u?this.serializer.nativeToString(a.type,u):null}else return a.source==="user_wallet"?this.config.userAddress?this.serializer.nativeToString("address",this.config.userAddress):null:n[c]||null};return r.map((a,c)=>({input:a,value:i(a,c)}))}getModifiedInputs(t){return t.map((e,r)=>{if(e.input.modifier?.startsWith("scale:")){let[,n]=e.input.modifier.split(":");if(isNaN(Number(n))){let i=Number(t.find(u=>u.input.name===n)?.value?.split(":")[1]);if(!i)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let a=e.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let c=Q(a,+i);return{...e,value:`${e.input.type}:${c}`}}else{let i=e.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let a=Q(i,+n);return{...e,value:`${e.input.type}:${a}`}}}else return e})}async preprocessInput(t){try{let[e,r]=t.split(f.ArgParamsSeparator,2);if(e==="esdt"){let[n,i,a,c]=r.split(f.ArgCompositeSeparator);if(c)return t;let u=new y.Token({identifier:n,nonce:BigInt(i)});if(!new y.TokenComputer().isFungible(u))return t;let g=yt(n)?.decimals;if(!g){let w=this.config.chainApiUrl||W.Chain.ApiUrl(this.config.env);g=(await(await fetch(`${w}/tokens/${n}`)).json()).decimals}if(!g)throw new Error(`WarpActionExecutor: Decimals not found for token ${n}`);let T=new y.TokenTransfer({token:u,amount:Q(a,g)});return this.serializer.nativeToString(e,T)+f.ArgCompositeSeparator+g}return t}catch{return t}}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=await this.contractLoader.getVerificationInfo(t.address);if(!e)throw new Error("WarpActionExecutor: Verification info not found");return y.AbiRegistry.create(e.abi)}getPreparedArgs(t,e){let r="args"in t?t.args||[]:[];return e.forEach(({input:n,value:i})=>{if(!i||!n.position.startsWith("arg:"))return;let a=Number(n.position.split(":")[1])-1;r.splice(a,0,i)}),r}getPreparedMessages(t,e){let r=Object.entries(t.messages||{}).map(([n,i])=>[n,i.replace(/\{\{([^}]+)\}\}/g,(a,c)=>e[c]||"")]);return Object.fromEntries(r)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(f.IdentifierType.Hash)){let e=new J(this.config),r=t.abi.split(f.IdentifierParamSeparator)[1],n=await e.createFromTransactionHash(r);if(!n)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return y.AbiRegistry.create(n.content)}else{let r=await(await fetch(t.abi)).json();return y.AbiRegistry.create(r)}}toTypedTransfer(t){return new y.TokenTransfer({token:new y.Token({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var at=class{constructor(t){this.config=t}async search(t,e,r){if(!this.config.indexUrl)throw new Error("WarpIndex: Index URL is not set");try{let n=await fetch(this.config.indexUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.indexApiKey}`,...r},body:JSON.stringify({[this.config.indexSearchParamName||"search"]:t,...e})});if(!n.ok)throw new Error(`WarpIndex: search failed with status ${n.status}`);return(await n.json()).hits}catch(n){throw console.error("WarpIndex: Error searching for warps: ",n),n}}};0&&(module.exports={BrandBuilder,CacheKey,Config,WarpAbiBuilder,WarpActionExecutor,WarpArgSerializer,WarpBuilder,WarpCache,WarpConstants,WarpContractLoader,WarpIndex,WarpLink,WarpProtocolVersions,WarpRegistry,WarpUtils,WarpValidator,address,biguint,boolean,codemeta,composite,esdt,getChainId,getDefaultChainInfo,getLatestProtocolIdentifier,getWarpActionByIndex,hex,list,nothing,option,optional,shiftBigintBy,string,toPreviewText,toTypedChainInfo,toTypedRegistryInfo,token,u16,u32,u64,u8,variadic});
|
|
1
|
+
"use strict";var wt=Object.create;var Y=Object.defineProperty;var Tt=Object.getOwnPropertyDescriptor;var Wt=Object.getOwnPropertyNames;var Ct=Object.getPrototypeOf,At=Object.prototype.hasOwnProperty;var It=(a,t)=>{for(var e in t)Y(a,e,{get:t[e],enumerable:!0})},ot=(a,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Wt(t))!At.call(a,n)&&n!==e&&Y(a,n,{get:()=>t[n],enumerable:!(r=Tt(t,n))||r.enumerable});return a};var tt=(a,t,e)=>(e=a!=null?wt(Ct(a)):{},ot(t||!a||!a.__esModule?Y(e,"default",{value:a,enumerable:!0}):e,a)),bt=a=>ot(Y({},"__esModule",{value:!0}),a);var Qt={};It(Qt,{BrandBuilder:()=>it,CacheKey:()=>x,Config:()=>W,WarpAbiBuilder:()=>J,WarpActionExecutor:()=>st,WarpArgSerializer:()=>F,WarpBuilder:()=>K,WarpCache:()=>B,WarpConstants:()=>f,WarpContractLoader:()=>Z,WarpIndex:()=>at,WarpLink:()=>G,WarpProtocolVersions:()=>V,WarpRegistry:()=>S,WarpUtils:()=>h,WarpValidator:()=>k,address:()=>Lt,biguint:()=>$t,boolean:()=>Ot,codemeta:()=>Ht,composite:()=>Vt,esdt:()=>_t,getChainId:()=>v,getLatestProtocolIdentifier:()=>R,getMainChainInfo:()=>C,getWarpActionByIndex:()=>H,hex:()=>Dt,list:()=>Pt,nothing:()=>Mt,option:()=>Bt,optional:()=>St,shiftBigintBy:()=>j,string:()=>Rt,toPreviewText:()=>rt,toTypedChainInfo:()=>et,toTypedRegistryInfo:()=>M,token:()=>qt,u16:()=>Nt,u32:()=>Ft,u64:()=>kt,u8:()=>Ut,variadic:()=>Et});module.exports=bt(Qt);var N=require("@multiversx/sdk-core"),dt=tt(require("ajv"));var V={Warp:"1.3.0",Brand:"0.1.0",Abi:"0.1.0"},W={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${V.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${V.Brand}.schema.json`,DefaultClientUrl:a=>a==="devnet"?"https://devnet.usewarp.to":a==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],MainChain:{ApiUrl:a=>a==="devnet"?"https://devnet-api.multiversx.com":a==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:a=>a==="devnet"?"https://devnet-explorer.multiversx.com":a==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com"},Registry:{Contract:a=>a==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":a==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var v=a=>a==="devnet"?"D":a==="testnet"?"T":"1",C=a=>({chainId:v(a.env),apiUrl:a.chainApiUrl||W.MainChain.ApiUrl(a.env),blockTime:6e3,explorerUrl:a.chainExplorerUrl||W.MainChain.ExplorerUrl(a.env)}),R=a=>{if(a==="warp")return`warp:${V.Warp}`;if(a==="brand")return`brand:${V.Brand}`;if(a==="abi")return`abi:${V.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${a}`)},H=(a,t)=>a?.actions[t-1],M=a=>({hash:a.hash.toString("hex"),alias:a.alias?.toString()||null,trust:a.trust.toString(),creator:a.creator.toString(),createdAt:a.created_at.toNumber(),brand:a.brand?.toString("hex")||null,upgrade:a.upgrade?.toString("hex")||null}),et=a=>({chainId:a.chain_id.toString(),apiUrl:a.api_url.toString(),explorerUrl:a.explorer_url.toString(),blockTime:a.block_time.toNumber()}),j=(a,t)=>{let e=a.toString(),[r,n=""]=e.split("."),i=Math.abs(t);if(t>0)return BigInt(r+n.padEnd(i,"0"));if(t<0){let o=r+n;if(i>=o.length)return 0n;let c=o.slice(0,-i)||"0";return BigInt(c)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},rt=(a,t=100)=>{if(!a)return"";let e=a.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e};var $=require("@multiversx/sdk-core");var f={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};var pt=tt(require("qr-code-styling"));var U=require("@multiversx/sdk-core");var Q=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let r=JSON.parse(e);return Date.now()>r.expiresAt?(localStorage.removeItem(this.getKey(t)),null):r.value}catch{return null}}set(t,e,r){let n={value:e,expiresAt:Date.now()+r*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(n))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var z=class{constructor(){this.cache=new Map}get(t){let e=this.cache.get(t);return e?Date.now()>e.expiresAt?(this.cache.delete(t),null):e.value:null}set(t,e,r){let n=Date.now()+r*1e3;this.cache.set(t,{value:e,expiresAt:n})}clear(){this.cache.clear()}};var x={Warp:a=>`warp:${a}`,WarpAbi:a=>`warp-abi:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`,ChainInfo:a=>`chain:${a}`},B=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new Q:t==="memory"?new z:typeof window<"u"&&window.localStorage?new Q:new z}set(t,e,r){this.strategy.set(t,e,r)}get(t){return this.strategy.get(t)}clear(){this.strategy.clear()}};var ct=tt(require("ajv"));var k=class{constructor(t){this.config=t;this.config=t}async validate(t){this.ensureMaxOneValuePosition(t),this.ensureVariableNamesAndResultNamesUppercase(t),this.ensureAbiIsSetIfApplicable(t),await this.ensureValidSchema(t)}ensureMaxOneValuePosition(t){if(t.actions.filter(r=>r.inputs?r.inputs.some(n=>n.position==="value"):!1).length>1)throw new Error("WarpBuilder: only one value position action is allowed")}ensureVariableNamesAndResultNamesUppercase(t){let e=r=>{r&&Object.keys(r).forEach(n=>{if(n!==n.toUpperCase())throw new Error(`WarpValidator: variable/result name '${n}' must be uppercase`)})};e(t.vars),e(t.results)}ensureAbiIsSetIfApplicable(t){let e=t.actions.some(n=>n.type==="contract"),r=t.actions.some(n=>n.type==="query");!e&&!r||this.throwUnless(!!t.results,"results are required if there are contract or query actions")}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||W.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),i=new ct.default,o=i.compile(n);this.throwUnless(o(t),`WarpValidator: schema validation failed: ${i.errorsText(o.errors)}`)}throwUnless(t,e){if(!t)throw new Error(`WarpValidator: ${e}`)}};var K=class{constructor(t){this.pendingWarp={protocol:R("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t,this.cache=new B(t.cacheType)}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new U.TransactionsFactoryConfig({chainID:v(this.config.env)}),r=new U.TransferTransactionsFactory({config:e}),n=U.Address.newFromBech32(this.config.userAddress),i=JSON.stringify(t),o=r.createTransactionForTransfer(n,{receiver:U.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))});return o.gasLimit=o.gasLimit+BigInt(2e6),o}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await new k(this.config).validate(r),h.prepareVars(r,this.config)}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=x.Warp(t);if(e){let c=this.cache.get(r);if(c)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),c}let n=C(this.config),o=h.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let c=await o.getTransaction(t),p=await this.createFromTransaction(c);return e&&e.ttl&&p&&this.cache.set(r,p,e.ttl),p}catch(c){return console.error("WarpBuilder: Error creating from transaction hash",c),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await new k(this.config).validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return rt(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}};var m=require("@multiversx/sdk-core/out");var nt={buildInfo:{rustc:{version:"1.80.0-nightly",commitHash:"791adf759cc065316f054961875052d5bc03e16c",commitDate:"2024-05-21",channel:"Nightly",short:"rustc 1.80.0-nightly (791adf759 2024-05-21)"},contractCrate:{name:"registry",version:"0.0.1"},framework:{name:"multiversx-sc",version:"0.51.1"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"},{name:"vault",type:"Address"}],outputs:[]},upgradeConstructor:{inputs:[],outputs:[]},endpoints:[{name:"registerWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias_opt",type:"optional<bytes>",multi_arg:!0},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],outputs:[],allow_multiple_var_args:!0},{name:"unregisterWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"upgradeWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"alias",type:"bytes"},{name:"new_warp",type:"bytes"}],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"verifyWarp",onlyOwner:!0,mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<InfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"setVault",onlyOwner:!0,mutability:"mutable",inputs:[{name:"vault",type:"Address"}],outputs:[]},{name:"setUnitPrice",onlyOwner:!0,mutability:"mutable",inputs:[{name:"amount",type:"BigUint"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"BigUint"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0}]},{identifier:"warpVerified",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"creator",type:"Address"},{name:"created_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var S=class{constructor(t){this.config=t,this.cache=new B(t.cacheType),this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(this.config.userAddress),n=e?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:n,arguments:e?[m.BytesValue.fromHex(t),m.BytesValue.fromUTF8(e)]:[m.BytesValue.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=m.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[m.BytesValue.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.BytesValue.fromUTF8(t),m.BytesValue.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.BytesValue.fromHex(t),m.BytesValue.fromUTF8(e)]})}createWarpVerifyTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=m.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[m.BytesValue.fromHex(t)]})}createBrandRegisterTransaction(t){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=m.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.BytesValue.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.BytesValue.fromHex(t),m.BytesValue.fromHex(e)]})}async getInfoByAlias(t,e){let r=x.RegistryInfo(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),o=this.getController(),c=o.createQuery({contract:i,function:"getInfoByAlias",arguments:[m.BytesValue.fromUTF8(t)]}),p=await o.runQuery(c),[l]=o.parseQueryResponse(p),d=l?M(l):null,g=d?.brand?await this.fetchBrand(d.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:d,brand:g},e.ttl),{registryInfo:d,brand:g}}async getInfoByHash(t,e){let r=x.RegistryInfo(t);if(e){let g=this.cache.get(r);if(g)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),g}let n=this.getRegistryContractAddress(),i=this.getController(),o=i.createQuery({contract:n,function:"getInfoByHash",arguments:[m.BytesValue.fromHex(t)]}),c=await i.runQuery(o),[p]=i.parseQueryResponse(c),l=p?M(p):null,d=l?.brand?await this.fetchBrand(l.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:l,brand:d},e.ttl),{registryInfo:l,brand:d}}async getUserWarpRegistryInfos(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getUserWarps",arguments:[new m.AddressValue(new m.Address(e))]}),o=await n.runQuery(i),[c]=n.parseQueryResponse(o);return c.map(M)}async getUserBrands(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getUserBrands",arguments:[new m.AddressValue(new m.Address(e))]}),o=await n.runQuery(i),[c]=n.parseQueryResponse(o),p=c.map(g=>g.toString("hex")),l={ttl:365*24*60*60};return(await Promise.all(p.map(g=>this.fetchBrand(g,l)))).filter(g=>g!==null)}async getChainInfo(t,e){let r=x.ChainInfo(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),o=this.getController(),c=o.createQuery({contract:i,function:"getChain",arguments:[m.BytesValue.fromUTF8(t)]}),p=await o.runQuery(c),[l]=o.parseQueryResponse(p),d=l?et(l):null;return d&&e?.ttl&&this.cache.set(r,d,e.ttl),d}async fetchBrand(t,e){let r=x.Brand(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let i=C(this.config),c=h.getChainEntrypoint(i,this.config.env).createNetworkProvider();try{let p=await c.getTransaction(t),l=JSON.parse(p.data.toString());return l.meta={hash:p.hash,creator:p.sender.bech32(),createdAt:new Date(p.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,l,e.ttl),l}catch(p){return console.error("WarpRegistry: Error fetching brand from transaction hash",p),null}}getRegistryContractAddress(){return m.Address.newFromBech32(this.config.registryContract||W.Registry.Contract(this.config.env))}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),[r]=await e.query({contract:t,function:"getConfig",arguments:[]}),n=BigInt(r.toString());this.unitPrice=n}getFactory(){let t=new m.TransactionsFactoryConfig({chainID:v(this.config.env)}),e=m.AbiRegistry.create(nt);return new m.SmartContractTransactionsFactory({config:t,abi:e})}getController(){let t=C(this.config),e=h.getChainEntrypoint(t,this.config.env),r=m.AbiRegistry.create(nt);return e.createSmartContractController(r)}};var G=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(f.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),o=(await Promise.all(n)).filter(l=>l.match),c=o.length>0,p=o.map(l=>({url:l.url,warp:l.warp}));return{match:c,results:p}}async detect(t){let e=t.startsWith(f.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):h.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:n}=e,i=new K(this.config),o=new S(this.config),c=null,p=null,l=null;if(r==="hash"){c=await i.createFromTransactionHash(n);try{let{registryInfo:d,brand:g}=await o.getInfoByHash(n);p=d,l=g}catch{}}else if(r==="alias"){let{registryInfo:d,brand:g}=await o.getInfoByAlias(n);p=d,l=g,d&&(c=await i.createFromTransactionHash(d.hash))}return c?{match:!0,url:t,warp:c,registryInfo:p,brand:l}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||W.DefaultClientUrl(this.config.env),n=t===f.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+f.IdentifierParamSeparator+e);return W.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${f.IdentifierParamName}=${n}`}generateQrCode(t,e,r=512,n="white",i="black",o="#23F7DD"){let c=this.build(t,e);return new pt.default({type:"svg",width:r,height:r,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:n},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=W.SuperClientUrls.includes(e.origin),n=e.searchParams.get(f.IdentifierParamName),i=r&&!n?e.pathname.split("/")[1]:n;if(!i)return null;let o=decodeURIComponent(i);return h.getInfoFromPrefixedIdentifier(o)}};var xt="https://",ut="query",lt="env",h=class a{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),n=(i,o)=>{r=r.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([i,o])=>{if(typeof o=="string"&&o.startsWith(`${ut}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let c=o.split(`${ut}:`)[1],p=new URL(e.currentUrl).searchParams.get(c);p&&n(i,p)}else if(typeof o=="string"&&o.startsWith(`${lt}:`)){let c=o.split(`${lt}:`)[1],p=e.vars?.[c];p&&n(i,p)}else n(i,o)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(f.IdentifierParamSeparator)?e:`${f.IdentifierType.Alias}${f.IdentifierParamSeparator}${e}`,[n,i]=r.split(f.IdentifierParamSeparator);return{type:n,id:i}}static getNextStepUrl(t,e,r){let n=t.next||t.actions?.[e]?.next||null;if(!n)return null;if(n.startsWith(xt))return n;{let i=new G(r),o=a.getInfoFromPrefixedIdentifier(n);return o?i.build(o.type,o.id):null}}static async getChainInfoForAction(t,e){if(!t.chain)return C(e);let r=await new S(e).getChainInfo(t.chain);if(!r)throw new Error(`WarpActionExecutor: Chain info not found for ${t.chain}`);return r}static getChainEntrypoint(t,e){let r="warp-sdk",n="api";return e==="devnet"?new $.DevnetEntrypoint(t.apiUrl,n,r):e==="testnet"?new $.TestnetEntrypoint(t.apiUrl,n,r):new $.MainnetEntrypoint(t.apiUrl,n,r)}};var it=class{constructor(t){this.pendingBrand={protocol:R("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let e=new N.TransactionsFactoryConfig({chainID:v(this.config.env)}),r=new N.TransferTransactionsFactory({config:e}),n=N.Address.newFromBech32(this.config.userAddress),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer(n,{receiver:N.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))})}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.ensureValidSchema(r),r}async createFromTransaction(t,e=!1){return await this.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=C(this.config),n=h.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let i=await n.getTransaction(t);return this.createFromTransaction(i)}catch(i){return console.error("BrandBuilder: Error creating from transaction hash",i),null}}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.brandSchemaUrl||W.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),i=new dt.default,o=i.compile(n);if(!o(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(o.errors)}`)}};var u=require("@multiversx/sdk-core/out"),Bt=(a,t)=>a?u.OptionValue.newProvided(a):t?u.OptionValue.newMissingTyped(t):u.OptionValue.newMissing(),St=(a,t)=>a?new u.OptionalValue(a.getType(),a):t?new u.OptionalValue(t):u.OptionalValue.newMissing(),Pt=a=>{if(a.length===0)throw new Error("Cannot create a list from an empty array");let t=a[0].getType();return new u.List(t,a)},Et=a=>u.VariadicValue.fromItems(...a),Vt=a=>{let t=a.map(e=>e.getType());return new u.CompositeValue(new u.CompositeType(...t),a)},Rt=a=>u.StringValue.fromUTF8(a),Ut=a=>new u.U8Value(a),Nt=a=>new u.U16Value(a),Ft=a=>new u.U32Value(a),kt=a=>new u.U64Value(a),$t=a=>new u.BigUIntValue(BigInt(a)),Ot=a=>new u.BooleanValue(a),Lt=a=>new u.AddressValue(u.Address.newFromBech32(a)),qt=a=>new u.TokenIdentifierValue(a),Dt=a=>u.BytesValue.fromHex(a),_t=a=>new u.Struct(new u.StructType("EsdtTokenPayment",[new u.FieldDefinition("token_identifier","",new u.TokenIdentifierType),new u.FieldDefinition("token_nonce","",new u.U64Type),new u.FieldDefinition("amount","",new u.BigUIntType)]),[new u.Field(new u.TokenIdentifierValue(a.token.identifier),"token_identifier"),new u.Field(new u.U64Value(BigInt(a.token.nonce)),"token_nonce"),new u.Field(new u.BigUIntValue(BigInt(a.amount)),"amount")]),Ht=a=>new u.CodeMetadataValue(u.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(a,"hex")))),Mt=()=>new u.NothingValue;var O=require("@multiversx/sdk-core");var J=class{constructor(t){this.cache=new B;this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new O.TransactionsFactoryConfig({chainID:v(this.config.env)}),r=new O.TransferTransactionsFactory({config:e}),n={protocol:R("abi"),content:t},i=O.Address.newFromBech32(this.config.userAddress),o=JSON.stringify(n),c=r.createTransactionForTransfer(i,{receiver:i,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(o))});return c.gasLimit=c.gasLimit+BigInt(2e6),c}async createFromRaw(t){return JSON.parse(t)}async createFromTransaction(t){let e=await this.createFromRaw(t.data.toString());return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,e){let r=x.WarpAbi(t);if(e){let c=this.cache.get(r);if(c)return console.log(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),c}let n=C(this.config),o=h.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let c=await o.getTransaction(t),p=await this.createFromTransaction(c);return e&&e.ttl&&p&&this.cache.set(r,p,e.ttl),p}catch(c){return console.error("WarpAbiBuilder: Error creating from transaction hash",c),null}}};var y=require("@multiversx/sdk-core");var L=require("@multiversx/sdk-core/out");var s=require("@multiversx/sdk-core/out");var gt=new RegExp(`${f.ArgParamsSeparator}(.*)`),F=class{nativeToString(t,e){return t==="esdt"&&e instanceof s.TokenTransfer?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(s.OptionValue.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(s.OptionalValue.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(s.List.ClassName)){let e=t.getItems(),n=e.map(o=>this.typedToString(o).split(f.ArgParamsSeparator)[0])[0],i=e.map(o=>this.typedToString(o).split(f.ArgParamsSeparator)[1]);return`list:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(s.VariadicValue.ClassName)){let e=t.getItems(),n=e.map(o=>this.typedToString(o).split(f.ArgParamsSeparator)[0])[0],i=e.map(o=>this.typedToString(o).split(f.ArgParamsSeparator)[1]);return`variadic:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(s.CompositeValue.ClassName)){let e=t.getItems(),r=e.map(c=>this.typedToString(c).split(f.ArgParamsSeparator)[0]),n=e.map(c=>this.typedToString(c).split(f.ArgParamsSeparator)[1]),i=r.join(f.ArgCompositeSeparator),o=n.join(f.ArgCompositeSeparator);return`composite(${i}):${o}`}if(t.hasClassOrSuperclass(s.BigUIntValue.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(s.U8Value.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(s.U16Value.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(s.U32Value.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(s.U64Value.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(s.StringValue.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(s.BooleanValue.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(s.AddressValue.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(s.TokenIdentifierValue.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(s.BytesValue.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(s.CodeMetadataValue.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),n=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${n}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.stringToNative(e)}nativeToTyped(t,e){let r=this.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new s.CompositeType(...e.split(f.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new s.StringType;if(t==="uint8")return new s.U8Type;if(t==="uint16")return new s.U16Type;if(t==="uint32")return new s.U32Type;if(t==="uint64")return new s.U64Type;if(t==="biguint")return new s.BigUIntType;if(t==="bool")return new s.BooleanType;if(t==="address")return new s.AddressType;if(t==="token")return new s.TokenIdentifierType;if(t==="hex")return new s.BytesType;if(t==="codemeta")return new s.CodeMetadataType;if(t==="esdt"||t==="nft")return new s.StructType("EsdtTokenPayment",[new s.FieldDefinition("token_identifier","",new s.TokenIdentifierType),new s.FieldDefinition("token_nonce","",new s.U64Type),new s.FieldDefinition("amount","",new s.BigUIntType)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(f.ArgParamsSeparator),r=e[0],n=e.slice(1).join(f.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[i,o]=n.split(f.ArgParamsSeparator);return[`option:${i}`,o||null]}else if(r==="optional"){let[i,o]=n.split(f.ArgParamsSeparator);return[`optional:${i}`,o||null]}else if(r==="list"){let i=n.split(f.ArgParamsSeparator),o=i.slice(0,-1).join(f.ArgParamsSeparator),c=i[i.length-1],l=(c?c.split(","):[]).map(d=>this.stringToNative(`${o}:${d}`)[1]);return[`list:${o}`,l]}else if(r==="variadic"){let i=n.split(f.ArgParamsSeparator),o=i.slice(0,-1).join(f.ArgParamsSeparator),c=i[i.length-1],l=(c?c.split(","):[]).map(d=>this.stringToNative(`${o}:${d}`)[1]);return[`variadic:${o}`,l]}else if(r.startsWith("composite")){let i=r.match(/\(([^)]+)\)/)?.[1]?.split(f.ArgCompositeSeparator),c=n.split(f.ArgCompositeSeparator).map((p,l)=>this.stringToNative(`${i[l]}:${p}`)[1]);return[r,c]}else{if(r==="string")return[r,n];if(r==="uint8"||r==="uint16"||r==="uint32")return[r,Number(n)];if(r==="uint64"||r==="biguint")return[r,BigInt(n||0)];if(r==="bool")return[r,n==="true"];if(r==="address")return[r,n];if(r==="token")return[r,n];if(r==="hex")return[r,n];if(r==="codemeta")return[r,n];if(r==="esdt"){let[i,o,c]=n.split(f.ArgCompositeSeparator);return[r,new s.TokenTransfer({token:new s.Token({identifier:i,nonce:BigInt(o)}),amount:BigInt(c)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new s.NothingValue;if(e==="option"){let n=this.stringToTyped(r);return n instanceof s.NothingValue?s.OptionValue.newMissingTyped(n.getType()):s.OptionValue.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof s.NothingValue?s.OptionalValue.newMissing():new s.OptionalValue(n.getType(),n)}if(e==="list"){let[n,i]=r.split(gt,2),c=i.split(",").map(p=>this.stringToTyped(`${n}:${p}`));return new s.List(this.nativeToType(n),c)}if(e==="variadic"){let[n,i]=r.split(gt,2),c=i.split(",").map(p=>this.stringToTyped(`${n}:${p}`));return new s.VariadicValue(new s.VariadicType(this.nativeToType(n)),c)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],i=r.split(f.ArgCompositeSeparator),o=n.split(f.ArgCompositeSeparator),c=i.map((l,d)=>this.stringToTyped(`${o[d]}:${l}`)),p=c.map(l=>l.getType());return new s.CompositeValue(new s.CompositeType(...p),c)}if(e==="string")return r?s.StringValue.fromUTF8(r):new s.NothingValue;if(e==="uint8")return r?new s.U8Value(Number(r)):new s.NothingValue;if(e==="uint16")return r?new s.U16Value(Number(r)):new s.NothingValue;if(e==="uint32")return r?new s.U32Value(Number(r)):new s.NothingValue;if(e==="uint64")return r?new s.U64Value(BigInt(r)):new s.NothingValue;if(e==="biguint")return r?new s.BigUIntValue(BigInt(r)):new s.NothingValue;if(e==="bool")return r?new s.BooleanValue(typeof r=="boolean"?r:r==="true"):new s.NothingValue;if(e==="address")return r?new s.AddressValue(s.Address.newFromBech32(r)):new s.NothingValue;if(e==="token")return r?new s.TokenIdentifierValue(r):new s.NothingValue;if(e==="hex")return r?s.BytesValue.fromHex(r):new s.NothingValue;if(e==="codemeta")return new s.CodeMetadataValue(s.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(f.ArgCompositeSeparator);return new s.Struct(this.nativeToType("esdt"),[new s.Field(new s.TokenIdentifierValue(n[0]),"token_identifier"),new s.Field(new s.U64Value(BigInt(n[1])),"token_nonce"),new s.Field(new s.BigUIntValue(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof s.OptionType)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof s.OptionalType)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof s.ListType)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof s.VariadicType)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof s.StringType)return"string";if(t instanceof s.U8Type)return"uint8";if(t instanceof s.U16Type)return"uint16";if(t instanceof s.U32Type)return"uint32";if(t instanceof s.U64Type)return"uint64";if(t instanceof s.BigUIntType)return"biguint";if(t instanceof s.BooleanType)return"bool";if(t instanceof s.AddressType)return"address";if(t instanceof s.TokenIdentifierType)return"token";if(t instanceof s.BytesType)return"hex";if(t instanceof s.CodeMetadataType)return"codemeta";if(t instanceof s.StructType&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var ft=async(a,t,e,r)=>{let n=[],i={};if(!t.results||!e.abi||e.type!=="contract")return{values:n,results:i};let o=await a.getAbiForAction(e),c=new L.TransactionEventsParser({abi:o}),l=new L.SmartContractTransactionsOutcomeParser({abi:o}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[d,g]of Object.entries(t.results)){let[T,w,I]=g.split(".");if(T==="event"){if(!w||isNaN(Number(I)))continue;let E=Number(I),b=(0,L.findEventsByFirstTopic)(r,w),q=c.parseEvents({events:b})[0],P=Object.values(q)[E]||null;n.push(P),i[d]=P&&P.valueOf()}else if(T==="out"){if(!w)continue;let E=Number(w),b=l.values[E-1]||null;n.push(b),i[d]=b&&b.valueOf()}}return{values:n,results:i}},mt=async(a,t)=>{let e=new F,r=t.map(c=>e.typedToString(c)),n=t.map(c=>e.typedToNative(c)[1]),i={};if(!a.results)return{values:r,results:i};let o=c=>{let p=c.split(".").slice(1).map(d=>parseInt(d)-1);if(p.length===0)return;let l=n[p[0]];for(let d=1;d<p.length;d++){if(l==null)return;l=l[p[d]]}return l};return Object.entries(a.results).forEach(([c,p])=>{if(p.startsWith("out.")){let l=o(p);i[c]=l||null}}),{values:r,results:i}},ht=async(a,t)=>{let e=[],r={};for(let[n,i]of Object.entries(a.results||{})){let[o,...c]=i.split(".");if(o!=="out"||!c.length)continue;let p=c.reduce((l,d)=>l?.[d],t);e.push(p),r[n]=p}return{values:e,results:r}};var jt=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],yt=a=>jt.find(t=>t.id===a)||null;var Z=class{constructor(t){this.config=t}async getContract(t,e){try{let i=await h.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}`);return{address:t,owner:i.ownerAddress,verified:i.isVerified||!1}}catch(r){return console.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t,e){try{let i=await h.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}/verification`);return{codeHash:i.codeHash,abi:i.source.abi}}catch(r){return console.error("WarpContractLoader: getVerificationInfo error",r),null}}};var st=class{constructor(t){if(!t.currentUrl)throw new Error("WarpActionExecutor: currentUrl config not set");this.config=t,this.url=new URL(t.currentUrl),this.serializer=new F,this.contractLoader=new Z(t),this.registry=new S(t)}async createTransactionForExecute(t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let r=y.Address.newFromBech32(this.config.userAddress),n=await h.getChainInfoForAction(t,this.config),i=new y.TransactionsFactoryConfig({chainID:n.chainId}),{destination:o,args:c,value:p,transfers:l,data:d}=await this.getTxComponentsFromInputs(t,e,r),g=c.map(T=>this.serializer.stringToTyped(T));if(t.type==="transfer")return new y.TransferTransactionsFactory({config:i}).createTransactionForTransfer(r,{receiver:o,nativeAmount:p,tokenTransfers:l,data:d?new Uint8Array(d):void 0});if(t.type==="contract"&&o.isSmartContract())return new y.SmartContractTransactionsFactory({config:i}).createTransactionForExecute(r,{contract:o,function:"func"in t&&t.func||"",gasLimit:"gasLimit"in t?BigInt(t.gasLimit||0):0n,arguments:g,tokenTransfers:l,nativeTransferAmount:p});throw t.type==="query"?new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead"):t.type==="collect"?new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead"):new Error(`WarpActionExecutor: Invalid action type (${t.type})`)}async getTransactionExecutionResults(t,e,r){let n=H(t,e),i=h.getNextStepUrl(t,e,this.config),{values:o,results:c}=await ft(this,t,n,r),p=this.getPreparedMessages(t,c);return{success:r.status.isSuccessful(),warp:t,action:e,user:this.config.userAddress||null,txHash:r.hash,redirectUrl:i,values:o,results:c,messages:p}}async executeQuery(t,e,r){let n=H(t,e);if(!n)throw new Error("WarpActionExecutor: Action not found");if(!n.func)throw new Error("WarpActionExecutor: Function not found");let i=await h.getChainInfoForAction(n,this.config),o=await this.getAbiForAction(n),{args:c}=await this.getTxComponentsFromInputs(n,r),p=c.map(_=>this.serializer.stringToTyped(_)),l=h.getChainEntrypoint(i,this.config.env),d=y.Address.newFromBech32(n.address),g=l.createSmartContractController(o),T=g.createQuery({contract:d,function:n.func,arguments:p}),w=await g.runQuery(T),I=w.returnCode==="ok",E=new y.ArgSerializer,b=o.getEndpoint(w.function),q=w.returnDataParts.map(_=>Buffer.from(_)),P=E.buffersToValues(q,b.output),{values:X,results:D}=await mt(t,P);return{success:I,warp:t,action:e,user:this.config.userAddress||null,txHash:null,redirectUrl:n.next||null,values:X,results:D,messages:this.getPreparedMessages(t,D)}}async executeCollect(t,e,r,n){let i=H(t,e);if(!i)throw new Error("WarpActionExecutor: Action not found");let o=await this.getResolvedInputs(i,r),c=this.getModifiedInputs(o),p=g=>{if(!g.value)return null;let T=this.serializer.stringToNative(g.value)[1];if(g.input.type==="biguint")return T.toString();if(g.input.type==="esdt"){let w=T;return{token:w.token.identifier,nonce:w.token.nonce.toString(),amount:w.amount.toString()}}else return T},l=Object.fromEntries(c.map(g=>[g.input.as||g.input.name,p(g)])),d=new Headers;d.set("Content-Type","application/json"),d.set("Accept","application/json"),Object.entries(i.destination.headers).forEach(([g,T])=>{d.set(g,T)});try{let g=await fetch(i.destination.url,{method:i.destination.method,headers:d,body:JSON.stringify({inputs:l,meta:n})}),T=await g.json(),{values:w,results:I}=await ht(t,T);return{success:g.ok,warp:t,action:e,user:this.config.userAddress||null,txHash:null,redirectUrl:i.next||null,values:w,results:I,messages:this.getPreparedMessages(t,I)}}catch(g){return console.error(g),{success:!1,warp:t,action:e,user:this.config.userAddress||null,txHash:null,redirectUrl:null,values:[],results:{},messages:{}}}}async getTxComponentsFromInputs(t,e,r){let n=await this.getResolvedInputs(t,e),i=this.getModifiedInputs(n),o=i.find(A=>A.input.position==="receiver")?.value,c="address"in t?t.address:null,p=o?.split(":")[1]||c||r?.toBech32();if(!p)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let l=y.Address.newFromBech32(p),d=this.getPreparedArgs(t,i),g=i.find(A=>A.input.position==="value")?.value||null,T="value"in t?t.value:null,w=BigInt(g?.split(":")[1]||T||0),I=i.filter(A=>A.input.position==="transfer"&&A.value).map(A=>A.value),b=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...I?.map(A=>this.serializer.stringToNative(A)[1])||[]],q=i.find(A=>A.input.position==="data")?.value,P="data"in t?t.data||"":null,X=q||P||null,D=X?this.serializer.stringToTyped(X).valueOf():null,_=D?Buffer.from(D):null;return{destination:l,args:d,value:w,transfers:b,data:_}}async getResolvedInputs(t,e){let r=t.inputs||[],n=await Promise.all(e.map(o=>this.preprocessInput(o))),i=(o,c)=>{if(o.source==="query"){let p=this.url.searchParams.get(o.name);return p?this.serializer.nativeToString(o.type,p):null}else return o.source==="user_wallet"?this.config.userAddress?this.serializer.nativeToString("address",this.config.userAddress):null:n[c]||null};return r.map((o,c)=>({input:o,value:i(o,c)}))}getModifiedInputs(t){return t.map((e,r)=>{if(e.input.modifier?.startsWith("scale:")){let[,n]=e.input.modifier.split(":");if(isNaN(Number(n))){let i=Number(t.find(p=>p.input.name===n)?.value?.split(":")[1]);if(!i)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let o=e.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let c=j(o,+i);return{...e,value:`${e.input.type}:${c}`}}else{let i=e.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let o=j(i,+n);return{...e,value:`${e.input.type}:${o}`}}}else return e})}async preprocessInput(t){try{let[e,r]=t.split(f.ArgParamsSeparator,2);if(e==="esdt"){let[n,i,o,c]=r.split(f.ArgCompositeSeparator);if(c)return t;let p=new y.Token({identifier:n,nonce:BigInt(i)});if(!new y.TokenComputer().isFungible(p))return t;let g=yt(n)?.decimals;if(!g){let w=this.config.chainApiUrl||W.MainChain.ApiUrl(this.config.env);g=(await(await fetch(`${w}/tokens/${n}`)).json()).decimals}if(!g)throw new Error(`WarpActionExecutor: Decimals not found for token ${n}`);let T=new y.TokenTransfer({token:p,amount:j(o,g)});return this.serializer.nativeToString(e,T)+f.ArgCompositeSeparator+g}return t}catch{return t}}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=C(this.config),r=await this.contractLoader.getVerificationInfo(t.address,e);if(!r)throw new Error("WarpActionExecutor: Verification info not found");return y.AbiRegistry.create(r.abi)}getPreparedArgs(t,e){let r="args"in t?t.args||[]:[];return e.forEach(({input:n,value:i})=>{if(!i||!n.position.startsWith("arg:"))return;let o=Number(n.position.split(":")[1])-1;r.splice(o,0,i)}),r}getPreparedMessages(t,e){let r=Object.entries(t.messages||{}).map(([n,i])=>[n,i.replace(/\{\{([^}]+)\}\}/g,(o,c)=>e[c]||"")]);return Object.fromEntries(r)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(f.IdentifierType.Hash)){let e=new J(this.config),r=t.abi.split(f.IdentifierParamSeparator)[1],n=await e.createFromTransactionHash(r);if(!n)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return y.AbiRegistry.create(n.content)}else{let r=await(await fetch(t.abi)).json();return y.AbiRegistry.create(r)}}toTypedTransfer(t){return new y.TokenTransfer({token:new y.Token({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var at=class{constructor(t){this.config=t}async search(t,e,r){if(!this.config.indexUrl)throw new Error("WarpIndex: Index URL is not set");try{let n=await fetch(this.config.indexUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.indexApiKey}`,...r},body:JSON.stringify({[this.config.indexSearchParamName||"search"]:t,...e})});if(!n.ok)throw new Error(`WarpIndex: search failed with status ${n.status}`);return(await n.json()).hits}catch(n){throw console.error("WarpIndex: Error searching for warps: ",n),n}}};0&&(module.exports={BrandBuilder,CacheKey,Config,WarpAbiBuilder,WarpActionExecutor,WarpArgSerializer,WarpBuilder,WarpCache,WarpConstants,WarpContractLoader,WarpIndex,WarpLink,WarpProtocolVersions,WarpRegistry,WarpUtils,WarpValidator,address,biguint,boolean,codemeta,composite,esdt,getChainId,getLatestProtocolIdentifier,getMainChainInfo,getWarpActionByIndex,hex,list,nothing,option,optional,shiftBigintBy,string,toPreviewText,toTypedChainInfo,toTypedRegistryInfo,token,u16,u32,u64,u8,variadic});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Address as yt,TransactionsFactoryConfig as de,TransferTransactionsFactory as ge}from"@multiversx/sdk-core";import fe from"ajv";var V={Warp:"1.3.0",Brand:"0.1.0",Abi:"0.1.0"},h={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${V.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${V.Brand}.schema.json`,DefaultClientUrl:a=>a==="devnet"?"https://devnet.usewarp.to":a==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],Chain:{ApiUrl:a=>a==="devnet"?"https://devnet-api.multiversx.com":a==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:a=>a==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":a==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var I=a=>a==="devnet"?"D":a==="testnet"?"T":"1",L=a=>({chainId:I(a.env),apiUrl:a.chainApiUrl||h.Chain.ApiUrl(a.env)}),P=a=>{if(a==="warp")return`warp:${V.Warp}`;if(a==="brand")return`brand:${V.Brand}`;if(a==="abi")return`abi:${V.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${a}`)},q=(a,t)=>a?.actions[t-1],D=a=>({hash:a.hash.toString("hex"),alias:a.alias?.toString()||null,trust:a.trust.toString(),creator:a.creator.toString(),createdAt:a.created_at.toNumber(),brand:a.brand?.toString("hex")||null,upgrade:a.upgrade?.toString("hex")||null}),ut=a=>({chainId:a.chain_id.toString(),apiUrl:a.api_url.toString()}),_=(a,t)=>{let e=a.toString(),[r,n=""]=e.split("."),i=Math.abs(t);if(t>0)return BigInt(r+n.padEnd(i,"0"));if(t<0){let s=r+n;if(i>=s.length)return 0n;let o=s.slice(0,-i)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},lt=(a,t=100)=>{if(!a)return"";let e=a.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e};import{ApiNetworkProvider as oe,DevnetEntrypoint as ce,MainnetEntrypoint as pe,TestnetEntrypoint as ue}from"@multiversx/sdk-core";var d={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};import ae from"qr-code-styling";import{Address as dt,TransactionsFactoryConfig as ee,TransferTransactionsFactory as re}from"@multiversx/sdk-core";var N=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let r=JSON.parse(e);return Date.now()>r.expiresAt?(localStorage.removeItem(this.getKey(t)),null):r.value}catch{return null}}set(t,e,r){let n={value:e,expiresAt:Date.now()+r*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(n))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var k=class{constructor(){this.cache=new Map}get(t){let e=this.cache.get(t);return e?Date.now()>e.expiresAt?(this.cache.delete(t),null):e.value:null}set(t,e,r){let n=Date.now()+r*1e3;this.cache.set(t,{value:e,expiresAt:n})}clear(){this.cache.clear()}};var b={Warp:a=>`warp:${a}`,WarpAbi:a=>`warp-abi:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`,ChainInfo:a=>`chain:${a}`},x=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new N:t==="memory"?new k:typeof window<"u"&&window.localStorage?new N:new k}set(t,e,r){this.strategy.set(t,e,r)}get(t){return this.strategy.get(t)}clear(){this.strategy.clear()}};import te from"ajv";var $=class{constructor(t){this.config=t;this.config=t}async validate(t){this.ensureMaxOneValuePosition(t),this.ensureVariableNamesAndResultNamesUppercase(t),this.ensureAbiIsSetIfApplicable(t),await this.ensureValidSchema(t)}ensureMaxOneValuePosition(t){if(t.actions.filter(r=>r.inputs?r.inputs.some(n=>n.position==="value"):!1).length>1)throw new Error("WarpBuilder: only one value position action is allowed")}ensureVariableNamesAndResultNamesUppercase(t){let e=r=>{r&&Object.keys(r).forEach(n=>{if(n!==n.toUpperCase())throw new Error(`WarpValidator: variable/result name '${n}' must be uppercase`)})};e(t.vars),e(t.results)}ensureAbiIsSetIfApplicable(t){let e=t.actions.some(n=>n.type==="contract"),r=t.actions.some(n=>n.type==="query");!e&&!r||this.throwUnless(!!t.results,"results are required if there are contract or query actions")}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||h.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),i=new te,s=i.compile(n);this.throwUnless(s(t),`WarpValidator: schema validation failed: ${i.errorsText(s.errors)}`)}throwUnless(t,e){if(!t)throw new Error(`WarpValidator: ${e}`)}};var H=class{constructor(t){this.pendingWarp={protocol:P("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t,this.cache=new x(t.cacheType)}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new ee({chainID:I(this.config.env)}),r=new re({config:e}),n=dt.newFromBech32(this.config.userAddress),i=JSON.stringify(t),s=r.createTransactionForTransfer(n,{receiver:dt.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))});return s.gasLimit=s.gasLimit+BigInt(2e6),s}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await new $(this.config).validate(r),g.prepareVars(r,this.config)}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=b.Warp(t);if(e){let i=this.cache.get(r);if(i)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),i}let n=g.getConfiguredChainApi(this.config);try{let i=await n.getTransaction(t),s=await this.createFromTransaction(i);return e&&e.ttl&&s&&this.cache.set(r,s,e.ttl),s}catch(i){return console.error("WarpBuilder: Error creating from transaction hash",i),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await new $(this.config).validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return lt(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}};import{AbiRegistry as gt,Address as A,AddressValue as ft,BytesValue as y,SmartContractTransactionsFactory as ie,TransactionsFactoryConfig as se}from"@multiversx/sdk-core/out";var z={buildInfo:{rustc:{version:"1.80.0-nightly",commitHash:"791adf759cc065316f054961875052d5bc03e16c",commitDate:"2024-05-21",channel:"Nightly",short:"rustc 1.80.0-nightly (791adf759 2024-05-21)"},contractCrate:{name:"registry",version:"0.0.1"},framework:{name:"multiversx-sc",version:"0.51.1"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"},{name:"vault",type:"Address"}],outputs:[]},upgradeConstructor:{inputs:[],outputs:[]},endpoints:[{name:"registerWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias_opt",type:"optional<bytes>",multi_arg:!0},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],outputs:[],allow_multiple_var_args:!0},{name:"unregisterWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"upgradeWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"alias",type:"bytes"},{name:"new_warp",type:"bytes"}],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"verifyWarp",onlyOwner:!0,mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<InfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"setVault",onlyOwner:!0,mutability:"mutable",inputs:[{name:"vault",type:"Address"}],outputs:[]},{name:"setUnitPrice",onlyOwner:!0,mutability:"mutable",inputs:[{name:"amount",type:"BigUint"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"BigUint"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0}]},{identifier:"warpVerified",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"creator",type:"Address"},{name:"created_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var B=class{constructor(t){this.config=t,this.cache=new x(t.cacheType),this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=A.newFromBech32(this.config.userAddress),n=e?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:n,arguments:e?[y.fromHex(t),y.fromUTF8(e)]:[y.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=A.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[y.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=A.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromUTF8(t),y.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=A.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromHex(t),y.fromUTF8(e)]})}createWarpVerifyTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=A.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[y.fromHex(t)]})}createBrandRegisterTransaction(t){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=A.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=A.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromHex(t),y.fromHex(e)]})}async getInfoByAlias(t,e){let r=b.RegistryInfo(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:i,function:"getInfoByAlias",arguments:[y.fromUTF8(t)]}),c=await s.runQuery(o),[p]=s.parseQueryResponse(c),u=p?D(p):null,l=u?.brand?await this.fetchBrand(u.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:u,brand:l},e.ttl),{registryInfo:u,brand:l}}async getInfoByHash(t,e){let r=b.RegistryInfo(t);if(e){let l=this.cache.get(r);if(l)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),l}let n=this.getRegistryContractAddress(),i=this.getController(),s=i.createQuery({contract:n,function:"getInfoByHash",arguments:[y.fromHex(t)]}),o=await i.runQuery(s),[c]=i.parseQueryResponse(o),p=c?D(c):null,u=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:u},e.ttl),{registryInfo:p,brand:u}}async getUserWarpRegistryInfos(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getUserWarps",arguments:[new ft(new A(e))]}),s=await n.runQuery(i),[o]=n.parseQueryResponse(s);return o.map(D)}async getUserBrands(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getUserBrands",arguments:[new ft(new A(e))]}),s=await n.runQuery(i),[o]=n.parseQueryResponse(s),c=o.map(l=>l.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(c.map(l=>this.fetchBrand(l,p)))).filter(l=>l!==null)}async getChainInfo(t,e){let r=b.ChainInfo(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:i,function:"getChain",arguments:[y.fromUTF8(t)]}),c=await s.runQuery(o),[p]=s.parseQueryResponse(c),u=p?ut(p):null;return u&&e?.ttl&&this.cache.set(r,u,e.ttl),u}async fetchBrand(t,e){let r=b.Brand(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let i=g.getConfiguredChainApi(this.config);try{let s=await i.getTransaction(t),o=JSON.parse(s.data.toString());return o.meta={hash:s.hash,creator:s.sender.bech32(),createdAt:new Date(s.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,o,e.ttl),o}catch(s){return console.error("WarpRegistry: Error fetching brand from transaction hash",s),null}}getRegistryContractAddress(){return A.newFromBech32(this.config.registryContract||h.Registry.Contract(this.config.env))}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),[r]=await e.query({contract:t,function:"getConfig",arguments:[]}),n=BigInt(r.toString());this.unitPrice=n}getFactory(){let t=new se({chainID:I(this.config.env)}),e=gt.create(z);return new ie({config:t,abi:e})}getController(){let t=L(this.config),e=g.getChainEntrypoint(t,this.config.env),r=gt.create(z);return e.createSmartContractController(r)}};var j=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(d.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),s=(await Promise.all(n)).filter(p=>p.match),o=s.length>0,c=s.map(p=>({url:p.url,warp:p.warp}));return{match:o,results:c}}async detect(t){let e=t.startsWith(d.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):g.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:n}=e,i=new H(this.config),s=new B(this.config),o=null,c=null,p=null;if(r==="hash"){o=await i.createFromTransactionHash(n);try{let{registryInfo:u,brand:l}=await s.getInfoByHash(n);c=u,p=l}catch{}}else if(r==="alias"){let{registryInfo:u,brand:l}=await s.getInfoByAlias(n);c=u,p=l,u&&(o=await i.createFromTransactionHash(u.hash))}return o?{match:!0,url:t,warp:o,registryInfo:c,brand:p}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||h.DefaultClientUrl(this.config.env),n=t===d.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+d.IdentifierParamSeparator+e);return h.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${d.IdentifierParamName}=${n}`}generateQrCode(t,e,r=512,n="white",i="black",s="#23F7DD"){let o=this.build(t,e);return new ae({type:"svg",width:r,height:r,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:n},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(s)}" 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>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=h.SuperClientUrls.includes(e.origin),n=e.searchParams.get(d.IdentifierParamName),i=r&&!n?e.pathname.split("/")[1]:n;if(!i)return null;let s=decodeURIComponent(i);return g.getInfoFromPrefixedIdentifier(s)}};var le="https://",mt="query",ht="env",g=class a{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),n=(i,s)=>{r=r.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(t.vars).forEach(([i,s])=>{if(typeof s=="string"&&s.startsWith(`${mt}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${mt}:`)[1],c=new URL(e.currentUrl).searchParams.get(o);c&&n(i,c)}else if(typeof s=="string"&&s.startsWith(`${ht}:`)){let o=s.split(`${ht}:`)[1],c=e.vars?.[o];c&&n(i,c)}else n(i,s)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(d.IdentifierParamSeparator)?e:`${d.IdentifierType.Alias}${d.IdentifierParamSeparator}${e}`,[n,i]=r.split(d.IdentifierParamSeparator);return{type:n,id:i}}static getNextStepUrl(t,e,r){let n=t.next||t.actions?.[e]?.next||null;if(!n)return null;if(n.startsWith(le))return n;{let i=new j(r),s=a.getInfoFromPrefixedIdentifier(n);return s?i.build(s.type,s.id):null}}static async getChainInfoForAction(t,e){if(!t.chain)return L(e);let r=await new B(e).getChainInfo(t.chain);if(!r)throw new Error(`WarpActionExecutor: Chain info not found for ${t.chain}`);return r}static getChainEntrypoint(t,e){let r="warp-sdk",n="api";return e==="devnet"?new ce(t.apiUrl,n,r):e==="testnet"?new ue(t.apiUrl,n,r):new pe(t.apiUrl,n,r)}static getConfiguredChainApi(t){let e=t.chainApiUrl||h.Chain.ApiUrl(t.env);if(!e)throw new Error("WarpUtils: Chain API URL not configured");return new oe(e,{timeout:3e4,clientName:"warp-sdk"})}};var wt=class{constructor(t){this.pendingBrand={protocol:P("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let e=new de({chainID:I(this.config.env)}),r=new ge({config:e}),n=yt.newFromBech32(this.config.userAddress),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer(n,{receiver:yt.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))})}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.ensureValidSchema(r),r}async createFromTransaction(t,e=!1){return await this.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=g.getConfiguredChainApi(this.config);try{let r=await e.getTransaction(t);return this.createFromTransaction(r)}catch(r){return console.error("BrandBuilder: Error creating from transaction hash",r),null}}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.brandSchemaUrl||h.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),i=new fe,s=i.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};import{Address as me,AddressValue as he,BigUIntType as ye,BigUIntValue as Tt,BooleanValue as we,BytesValue as Te,CodeMetadata as We,CodeMetadataValue as Ce,CompositeType as Ae,CompositeValue as Ie,Field as K,FieldDefinition as G,List as be,NothingValue as ve,OptionalValue as J,OptionValue as Z,StringValue as xe,Struct as Be,StructType as Se,TokenIdentifierType as Ve,TokenIdentifierValue as Wt,U16Value as Pe,U32Value as Re,U64Type as Ee,U64Value as Ct,U8Value as Ue,VariadicValue as Fe}from"@multiversx/sdk-core/out";var ln=(a,t)=>a?Z.newProvided(a):t?Z.newMissingTyped(t):Z.newMissing(),dn=(a,t)=>a?new J(a.getType(),a):t?new J(t):J.newMissing(),gn=a=>{if(a.length===0)throw new Error("Cannot create a list from an empty array");let t=a[0].getType();return new be(t,a)},fn=a=>Fe.fromItems(...a),mn=a=>{let t=a.map(e=>e.getType());return new Ie(new Ae(...t),a)},hn=a=>xe.fromUTF8(a),yn=a=>new Ue(a),wn=a=>new Pe(a),Tn=a=>new Re(a),Wn=a=>new Ct(a),Cn=a=>new Tt(BigInt(a)),An=a=>new we(a),In=a=>new he(me.newFromBech32(a)),bn=a=>new Wt(a),vn=a=>Te.fromHex(a),xn=a=>new Be(new Se("EsdtTokenPayment",[new G("token_identifier","",new Ve),new G("token_nonce","",new Ee),new G("amount","",new ye)]),[new K(new Wt(a.token.identifier),"token_identifier"),new K(new Ct(BigInt(a.token.nonce)),"token_nonce"),new K(new Tt(BigInt(a.amount)),"amount")]),Bn=a=>new Ce(We.newFromBytes(Uint8Array.from(Buffer.from(a,"hex")))),Sn=()=>new ve;import{Address as Ne,TransactionsFactoryConfig as ke,TransferTransactionsFactory as $e}from"@multiversx/sdk-core";var Q=class{constructor(t){this.cache=new x;this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new ke({chainID:I(this.config.env)}),r=new $e({config:e}),n={protocol:P("abi"),content:t},i=Ne.newFromBech32(this.config.userAddress),s=JSON.stringify(n),o=r.createTransactionForTransfer(i,{receiver:i,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(s))});return o.gasLimit=o.gasLimit+BigInt(2e6),o}async createFromRaw(t){return JSON.parse(t)}async createFromTransaction(t){let e=await this.createFromRaw(t.data.toString());return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,e){let r=b.WarpAbi(t);if(e){let i=this.cache.get(r);if(i)return console.log(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),i}let n=g.getConfiguredChainApi(this.config);try{let i=await n.getTransaction(t),s=await this.createFromTransaction(i);return e&&e.ttl&&s&&this.cache.set(r,s,e.ttl),s}catch(i){return console.error("WarpAbiBuilder: Error creating from transaction hash",i),null}}};import{AbiRegistry as ct,Address as pt,ArgSerializer as Ge,SmartContractTransactionsFactory as Je,Token as Jt,TokenComputer as Ze,TokenTransfer as Zt,TransactionsFactoryConfig as Xe,TransferTransactionsFactory as Ye}from"@multiversx/sdk-core";import{SmartContractTransactionsOutcomeParser as Qe,TransactionEventsParser as Me,findEventsByFirstTopic as ze}from"@multiversx/sdk-core/out";import{Address as Oe,AddressType as At,AddressValue as It,BigUIntType as X,BigUIntValue as Y,BooleanType as bt,BooleanValue as vt,BytesType as xt,BytesValue as Bt,CodeMetadata as Le,CodeMetadataType as St,CodeMetadataValue as Vt,CompositeType as Pt,CompositeValue as Rt,Field as tt,FieldDefinition as et,List as Et,ListType as qe,NothingValue as w,OptionalType as De,OptionalValue as rt,OptionType as _e,OptionValue as nt,StringType as Ut,StringValue as Ft,Struct as He,StructType as Nt,Token as je,TokenIdentifierType as it,TokenIdentifierValue as st,TokenTransfer as kt,U16Type as $t,U16Value as Ot,U32Type as Lt,U32Value as qt,U64Type as at,U64Value as ot,U8Type as Dt,U8Value as _t,VariadicType as Ht,VariadicValue as jt}from"@multiversx/sdk-core/out";var Qt=new RegExp(`${d.ArgParamsSeparator}(.*)`),R=class{nativeToString(t,e){return t==="esdt"&&e instanceof kt?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(nt.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(rt.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(Et.ClassName)){let e=t.getItems(),n=e.map(s=>this.typedToString(s).split(d.ArgParamsSeparator)[0])[0],i=e.map(s=>this.typedToString(s).split(d.ArgParamsSeparator)[1]);return`list:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(jt.ClassName)){let e=t.getItems(),n=e.map(s=>this.typedToString(s).split(d.ArgParamsSeparator)[0])[0],i=e.map(s=>this.typedToString(s).split(d.ArgParamsSeparator)[1]);return`variadic:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(Rt.ClassName)){let e=t.getItems(),r=e.map(o=>this.typedToString(o).split(d.ArgParamsSeparator)[0]),n=e.map(o=>this.typedToString(o).split(d.ArgParamsSeparator)[1]),i=r.join(d.ArgCompositeSeparator),s=n.join(d.ArgCompositeSeparator);return`composite(${i}):${s}`}if(t.hasClassOrSuperclass(Y.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(_t.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Ot.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(qt.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(ot.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Ft.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(vt.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(It.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(st.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(Bt.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(Vt.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),n=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${n}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.stringToNative(e)}nativeToTyped(t,e){let r=this.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new Pt(...e.split(d.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new Ut;if(t==="uint8")return new Dt;if(t==="uint16")return new $t;if(t==="uint32")return new Lt;if(t==="uint64")return new at;if(t==="biguint")return new X;if(t==="bool")return new bt;if(t==="address")return new At;if(t==="token")return new it;if(t==="hex")return new xt;if(t==="codemeta")return new St;if(t==="esdt"||t==="nft")return new Nt("EsdtTokenPayment",[new et("token_identifier","",new it),new et("token_nonce","",new at),new et("amount","",new X)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(d.ArgParamsSeparator),r=e[0],n=e.slice(1).join(d.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[i,s]=n.split(d.ArgParamsSeparator);return[`option:${i}`,s||null]}else if(r==="optional"){let[i,s]=n.split(d.ArgParamsSeparator);return[`optional:${i}`,s||null]}else if(r==="list"){let i=n.split(d.ArgParamsSeparator),s=i.slice(0,-1).join(d.ArgParamsSeparator),o=i[i.length-1],p=(o?o.split(","):[]).map(u=>this.stringToNative(`${s}:${u}`)[1]);return[`list:${s}`,p]}else if(r==="variadic"){let i=n.split(d.ArgParamsSeparator),s=i.slice(0,-1).join(d.ArgParamsSeparator),o=i[i.length-1],p=(o?o.split(","):[]).map(u=>this.stringToNative(`${s}:${u}`)[1]);return[`variadic:${s}`,p]}else if(r.startsWith("composite")){let i=r.match(/\(([^)]+)\)/)?.[1]?.split(d.ArgCompositeSeparator),o=n.split(d.ArgCompositeSeparator).map((c,p)=>this.stringToNative(`${i[p]}:${c}`)[1]);return[r,o]}else{if(r==="string")return[r,n];if(r==="uint8"||r==="uint16"||r==="uint32")return[r,Number(n)];if(r==="uint64"||r==="biguint")return[r,BigInt(n||0)];if(r==="bool")return[r,n==="true"];if(r==="address")return[r,n];if(r==="token")return[r,n];if(r==="hex")return[r,n];if(r==="codemeta")return[r,n];if(r==="esdt"){let[i,s,o]=n.split(d.ArgCompositeSeparator);return[r,new kt({token:new je({identifier:i,nonce:BigInt(s)}),amount:BigInt(o)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new w;if(e==="option"){let n=this.stringToTyped(r);return n instanceof w?nt.newMissingTyped(n.getType()):nt.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof w?rt.newMissing():new rt(n.getType(),n)}if(e==="list"){let[n,i]=r.split(Qt,2),o=i.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Et(this.nativeToType(n),o)}if(e==="variadic"){let[n,i]=r.split(Qt,2),o=i.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new jt(new Ht(this.nativeToType(n)),o)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],i=r.split(d.ArgCompositeSeparator),s=n.split(d.ArgCompositeSeparator),o=i.map((p,u)=>this.stringToTyped(`${s[u]}:${p}`)),c=o.map(p=>p.getType());return new Rt(new Pt(...c),o)}if(e==="string")return r?Ft.fromUTF8(r):new w;if(e==="uint8")return r?new _t(Number(r)):new w;if(e==="uint16")return r?new Ot(Number(r)):new w;if(e==="uint32")return r?new qt(Number(r)):new w;if(e==="uint64")return r?new ot(BigInt(r)):new w;if(e==="biguint")return r?new Y(BigInt(r)):new w;if(e==="bool")return r?new vt(typeof r=="boolean"?r:r==="true"):new w;if(e==="address")return r?new It(Oe.newFromBech32(r)):new w;if(e==="token")return r?new st(r):new w;if(e==="hex")return r?Bt.fromHex(r):new w;if(e==="codemeta")return new Vt(Le.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(d.ArgCompositeSeparator);return new He(this.nativeToType("esdt"),[new tt(new st(n[0]),"token_identifier"),new tt(new ot(BigInt(n[1])),"token_nonce"),new tt(new Y(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof _e)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof De)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof qe)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Ht)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Ut)return"string";if(t instanceof Dt)return"uint8";if(t instanceof $t)return"uint16";if(t instanceof Lt)return"uint32";if(t instanceof at)return"uint64";if(t instanceof X)return"biguint";if(t instanceof bt)return"bool";if(t instanceof At)return"address";if(t instanceof it)return"token";if(t instanceof xt)return"hex";if(t instanceof St)return"codemeta";if(t instanceof Nt&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var Mt=async(a,t,e,r)=>{let n=[],i={};if(!t.results||!e.abi||e.type!=="contract")return{values:n,results:i};let s=await a.getAbiForAction(e),o=new Me({abi:s}),p=new Qe({abi:s}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[u,l]of Object.entries(t.results)){let[m,f,W]=l.split(".");if(m==="event"){if(!f||isNaN(Number(W)))continue;let S=Number(W),C=ze(r,f),E=o.parseEvents({events:C})[0],v=Object.values(E)[S]||null;n.push(v),i[u]=v&&v.valueOf()}else if(m==="out"){if(!f)continue;let S=Number(f),C=p.values[S-1]||null;n.push(C),i[u]=C&&C.valueOf()}}return{values:n,results:i}},zt=async(a,t)=>{let e=new R,r=t.map(o=>e.typedToString(o)),n=t.map(o=>e.typedToNative(o)[1]),i={};if(!a.results)return{values:r,results:i};let s=o=>{let c=o.split(".").slice(1).map(u=>parseInt(u)-1);if(c.length===0)return;let p=n[c[0]];for(let u=1;u<c.length;u++){if(p==null)return;p=p[c[u]]}return p};return Object.entries(a.results).forEach(([o,c])=>{if(c.startsWith("out.")){let p=s(c);i[o]=p||null}}),{values:r,results:i}},Kt=async(a,t)=>{let e=[],r={};for(let[n,i]of Object.entries(a.results||{})){let[s,...o]=i.split(".");if(s!=="out"||!o.length)continue;let c=o.reduce((p,u)=>p?.[u],t);e.push(c),r[n]=c}return{values:e,results:r}};var Ke=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],Gt=a=>Ke.find(t=>t.id===a)||null;var M=class{constructor(t){this.config=t}async getContract(t){try{let r=await g.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{address:t,owner:r.ownerAddress,verified:r.isVerified}}catch(e){return console.error("WarpContractLoader: getContract error",e),null}}async getVerificationInfo(t){try{let r=await g.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{codeHash:r.codeHash,abi:r.source.abi}}catch(e){return console.error("WarpContractLoader: getVerificationInfo error",e),null}}};var Xt=class{constructor(t){if(!t.currentUrl)throw new Error("WarpActionExecutor: currentUrl config not set");this.config=t,this.url=new URL(t.currentUrl),this.serializer=new R,this.contractLoader=new M(t),this.registry=new B(t)}async createTransactionForExecute(t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let r=pt.newFromBech32(this.config.userAddress),n=await g.getChainInfoForAction(t,this.config),i=new Xe({chainID:n.chainId}),{destination:s,args:o,value:c,transfers:p,data:u}=await this.getTxComponentsFromInputs(t,e,r),l=o.map(m=>this.serializer.stringToTyped(m));if(t.type==="transfer")return new Ye({config:i}).createTransactionForTransfer(r,{receiver:s,nativeAmount:c,tokenTransfers:p,data:u?new Uint8Array(u):void 0});if(t.type==="contract"&&s.isSmartContract())return new Je({config:i}).createTransactionForExecute(r,{contract:s,function:"func"in t&&t.func||"",gasLimit:"gasLimit"in t?BigInt(t.gasLimit||0):0n,arguments:l,tokenTransfers:p,nativeTransferAmount:c});throw t.type==="query"?new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead"):t.type==="collect"?new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead"):new Error(`WarpActionExecutor: Invalid action type (${t.type})`)}async getTransactionExecutionResults(t,e,r){let n=q(t,e),i=g.getNextStepUrl(t,e,this.config),{values:s,results:o}=await Mt(this,t,n,r),c=this.getPreparedMessages(t,o);return{success:r.status.isSuccessful(),warp:t,action:e,user:this.config.userAddress||null,txHash:r.hash,redirectUrl:i,values:s,results:o,messages:c}}async executeQuery(t,e,r){let n=q(t,e);if(!n)throw new Error("WarpActionExecutor: Action not found");if(!n.func)throw new Error("WarpActionExecutor: Function not found");let i=await g.getChainInfoForAction(n,this.config),s=await this.getAbiForAction(n),{args:o}=await this.getTxComponentsFromInputs(n,r),c=o.map(F=>this.serializer.stringToTyped(F)),p=g.getChainEntrypoint(i,this.config.env),u=pt.newFromBech32(n.address),l=p.createSmartContractController(s),m=l.createQuery({contract:u,function:n.func,arguments:c}),f=await l.runQuery(m),W=f.returnCode==="ok",S=new Ge,C=s.getEndpoint(f.function),E=f.returnDataParts.map(F=>Buffer.from(F)),v=S.buffersToValues(E,C.output),{values:O,results:U}=await zt(t,v);return{success:W,warp:t,action:e,user:this.config.userAddress||null,txHash:null,redirectUrl:n.next||null,values:O,results:U,messages:this.getPreparedMessages(t,U)}}async executeCollect(t,e,r,n){let i=q(t,e);if(!i)throw new Error("WarpActionExecutor: Action not found");let s=await this.getResolvedInputs(i,r),o=this.getModifiedInputs(s),c=l=>{if(!l.value)return null;let m=this.serializer.stringToNative(l.value)[1];if(l.input.type==="biguint")return m.toString();if(l.input.type==="esdt"){let f=m;return{token:f.token.identifier,nonce:f.token.nonce.toString(),amount:f.amount.toString()}}else return m},p=Object.fromEntries(o.map(l=>[l.input.as||l.input.name,c(l)])),u=new Headers;u.set("Content-Type","application/json"),u.set("Accept","application/json"),Object.entries(i.destination.headers).forEach(([l,m])=>{u.set(l,m)});try{let l=await fetch(i.destination.url,{method:i.destination.method,headers:u,body:JSON.stringify({inputs:p,meta:n})}),m=await l.json(),{values:f,results:W}=await Kt(t,m);return{success:l.ok,warp:t,action:e,user:this.config.userAddress||null,txHash:null,redirectUrl:i.next||null,values:f,results:W,messages:this.getPreparedMessages(t,W)}}catch(l){return console.error(l),{success:!1,warp:t,action:e,user:this.config.userAddress||null,txHash:null,redirectUrl:null,values:[],results:{},messages:{}}}}async getTxComponentsFromInputs(t,e,r){let n=await this.getResolvedInputs(t,e),i=this.getModifiedInputs(n),s=i.find(T=>T.input.position==="receiver")?.value,o="address"in t?t.address:null,c=s?.split(":")[1]||o||r?.toBech32();if(!c)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let p=pt.newFromBech32(c),u=this.getPreparedArgs(t,i),l=i.find(T=>T.input.position==="value")?.value||null,m="value"in t?t.value:null,f=BigInt(l?.split(":")[1]||m||0),W=i.filter(T=>T.input.position==="transfer"&&T.value).map(T=>T.value),C=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...W?.map(T=>this.serializer.stringToNative(T)[1])||[]],E=i.find(T=>T.input.position==="data")?.value,v="data"in t?t.data||"":null,O=E||v||null,U=O?this.serializer.stringToTyped(O).valueOf():null,F=U?Buffer.from(U):null;return{destination:p,args:u,value:f,transfers:C,data:F}}async getResolvedInputs(t,e){let r=t.inputs||[],n=await Promise.all(e.map(s=>this.preprocessInput(s))),i=(s,o)=>{if(s.source==="query"){let c=this.url.searchParams.get(s.name);return c?this.serializer.nativeToString(s.type,c):null}else return s.source==="user_wallet"?this.config.userAddress?this.serializer.nativeToString("address",this.config.userAddress):null:n[o]||null};return r.map((s,o)=>({input:s,value:i(s,o)}))}getModifiedInputs(t){return t.map((e,r)=>{if(e.input.modifier?.startsWith("scale:")){let[,n]=e.input.modifier.split(":");if(isNaN(Number(n))){let i=Number(t.find(c=>c.input.name===n)?.value?.split(":")[1]);if(!i)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let s=e.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=_(s,+i);return{...e,value:`${e.input.type}:${o}`}}else{let i=e.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let s=_(i,+n);return{...e,value:`${e.input.type}:${s}`}}}else return e})}async preprocessInput(t){try{let[e,r]=t.split(d.ArgParamsSeparator,2);if(e==="esdt"){let[n,i,s,o]=r.split(d.ArgCompositeSeparator);if(o)return t;let c=new Jt({identifier:n,nonce:BigInt(i)});if(!new Ze().isFungible(c))return t;let l=Gt(n)?.decimals;if(!l){let f=this.config.chainApiUrl||h.Chain.ApiUrl(this.config.env);l=(await(await fetch(`${f}/tokens/${n}`)).json()).decimals}if(!l)throw new Error(`WarpActionExecutor: Decimals not found for token ${n}`);let m=new Zt({token:c,amount:_(s,l)});return this.serializer.nativeToString(e,m)+d.ArgCompositeSeparator+l}return t}catch{return t}}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=await this.contractLoader.getVerificationInfo(t.address);if(!e)throw new Error("WarpActionExecutor: Verification info not found");return ct.create(e.abi)}getPreparedArgs(t,e){let r="args"in t?t.args||[]:[];return e.forEach(({input:n,value:i})=>{if(!i||!n.position.startsWith("arg:"))return;let s=Number(n.position.split(":")[1])-1;r.splice(s,0,i)}),r}getPreparedMessages(t,e){let r=Object.entries(t.messages||{}).map(([n,i])=>[n,i.replace(/\{\{([^}]+)\}\}/g,(s,o)=>e[o]||"")]);return Object.fromEntries(r)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(d.IdentifierType.Hash)){let e=new Q(this.config),r=t.abi.split(d.IdentifierParamSeparator)[1],n=await e.createFromTransactionHash(r);if(!n)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return ct.create(n.content)}else{let r=await(await fetch(t.abi)).json();return ct.create(r)}}toTypedTransfer(t){return new Zt({token:new Jt({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var Yt=class{constructor(t){this.config=t}async search(t,e,r){if(!this.config.indexUrl)throw new Error("WarpIndex: Index URL is not set");try{let n=await fetch(this.config.indexUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.indexApiKey}`,...r},body:JSON.stringify({[this.config.indexSearchParamName||"search"]:t,...e})});if(!n.ok)throw new Error(`WarpIndex: search failed with status ${n.status}`);return(await n.json()).hits}catch(n){throw console.error("WarpIndex: Error searching for warps: ",n),n}}};export{wt as BrandBuilder,b as CacheKey,h as Config,Q as WarpAbiBuilder,Xt as WarpActionExecutor,R as WarpArgSerializer,H as WarpBuilder,x as WarpCache,d as WarpConstants,M as WarpContractLoader,Yt as WarpIndex,j as WarpLink,V as WarpProtocolVersions,B as WarpRegistry,g as WarpUtils,$ as WarpValidator,In as address,Cn as biguint,An as boolean,Bn as codemeta,mn as composite,xn as esdt,I as getChainId,L as getDefaultChainInfo,P as getLatestProtocolIdentifier,q as getWarpActionByIndex,vn as hex,gn as list,Sn as nothing,ln as option,dn as optional,_ as shiftBigintBy,hn as string,lt as toPreviewText,ut as toTypedChainInfo,D as toTypedRegistryInfo,bn as token,wn as u16,Tn as u32,Wn as u64,yn as u8,fn as variadic};
|
|
1
|
+
import{Address as yt,TransactionsFactoryConfig as le,TransferTransactionsFactory as de}from"@multiversx/sdk-core";import ge from"ajv";var E={Warp:"1.3.0",Brand:"0.1.0",Abi:"0.1.0"},h={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${E.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${E.Brand}.schema.json`,DefaultClientUrl:a=>a==="devnet"?"https://devnet.usewarp.to":a==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],MainChain:{ApiUrl:a=>a==="devnet"?"https://devnet-api.multiversx.com":a==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:a=>a==="devnet"?"https://devnet-explorer.multiversx.com":a==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com"},Registry:{Contract:a=>a==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":a==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var b=a=>a==="devnet"?"D":a==="testnet"?"T":"1",w=a=>({chainId:b(a.env),apiUrl:a.chainApiUrl||h.MainChain.ApiUrl(a.env),blockTime:6e3,explorerUrl:a.chainExplorerUrl||h.MainChain.ExplorerUrl(a.env)}),V=a=>{if(a==="warp")return`warp:${E.Warp}`;if(a==="brand")return`brand:${E.Brand}`;if(a==="abi")return`abi:${E.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${a}`)},q=(a,t)=>a?.actions[t-1],D=a=>({hash:a.hash.toString("hex"),alias:a.alias?.toString()||null,trust:a.trust.toString(),creator:a.creator.toString(),createdAt:a.created_at.toNumber(),brand:a.brand?.toString("hex")||null,upgrade:a.upgrade?.toString("hex")||null}),ut=a=>({chainId:a.chain_id.toString(),apiUrl:a.api_url.toString(),explorerUrl:a.explorer_url.toString(),blockTime:a.block_time.toNumber()}),_=(a,t)=>{let e=a.toString(),[r,n=""]=e.split("."),i=Math.abs(t);if(t>0)return BigInt(r+n.padEnd(i,"0"));if(t<0){let s=r+n;if(i>=s.length)return 0n;let o=s.slice(0,-i)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},lt=(a,t=100)=>{if(!a)return"";let e=a.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e};import{DevnetEntrypoint as oe,MainnetEntrypoint as ce,TestnetEntrypoint as pe}from"@multiversx/sdk-core";var d={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};import ae from"qr-code-styling";import{Address as dt,TransactionsFactoryConfig as ee,TransferTransactionsFactory as re}from"@multiversx/sdk-core";var k=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let r=JSON.parse(e);return Date.now()>r.expiresAt?(localStorage.removeItem(this.getKey(t)),null):r.value}catch{return null}}set(t,e,r){let n={value:e,expiresAt:Date.now()+r*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(n))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var $=class{constructor(){this.cache=new Map}get(t){let e=this.cache.get(t);return e?Date.now()>e.expiresAt?(this.cache.delete(t),null):e.value:null}set(t,e,r){let n=Date.now()+r*1e3;this.cache.set(t,{value:e,expiresAt:n})}clear(){this.cache.clear()}};var v={Warp:a=>`warp:${a}`,WarpAbi:a=>`warp-abi:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`,ChainInfo:a=>`chain:${a}`},B=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new k:t==="memory"?new $:typeof window<"u"&&window.localStorage?new k:new $}set(t,e,r){this.strategy.set(t,e,r)}get(t){return this.strategy.get(t)}clear(){this.strategy.clear()}};import te from"ajv";var O=class{constructor(t){this.config=t;this.config=t}async validate(t){this.ensureMaxOneValuePosition(t),this.ensureVariableNamesAndResultNamesUppercase(t),this.ensureAbiIsSetIfApplicable(t),await this.ensureValidSchema(t)}ensureMaxOneValuePosition(t){if(t.actions.filter(r=>r.inputs?r.inputs.some(n=>n.position==="value"):!1).length>1)throw new Error("WarpBuilder: only one value position action is allowed")}ensureVariableNamesAndResultNamesUppercase(t){let e=r=>{r&&Object.keys(r).forEach(n=>{if(n!==n.toUpperCase())throw new Error(`WarpValidator: variable/result name '${n}' must be uppercase`)})};e(t.vars),e(t.results)}ensureAbiIsSetIfApplicable(t){let e=t.actions.some(n=>n.type==="contract"),r=t.actions.some(n=>n.type==="query");!e&&!r||this.throwUnless(!!t.results,"results are required if there are contract or query actions")}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||h.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),i=new te,s=i.compile(n);this.throwUnless(s(t),`WarpValidator: schema validation failed: ${i.errorsText(s.errors)}`)}throwUnless(t,e){if(!t)throw new Error(`WarpValidator: ${e}`)}};var H=class{constructor(t){this.pendingWarp={protocol:V("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t,this.cache=new B(t.cacheType)}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new ee({chainID:b(this.config.env)}),r=new re({config:e}),n=dt.newFromBech32(this.config.userAddress),i=JSON.stringify(t),s=r.createTransactionForTransfer(n,{receiver:dt.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))});return s.gasLimit=s.gasLimit+BigInt(2e6),s}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await new O(this.config).validate(r),g.prepareVars(r,this.config)}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=v.Warp(t);if(e){let o=this.cache.get(r);if(o)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),o}let n=w(this.config),s=g.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await s.getTransaction(t),c=await this.createFromTransaction(o);return e&&e.ttl&&c&&this.cache.set(r,c,e.ttl),c}catch(o){return console.error("WarpBuilder: Error creating from transaction hash",o),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await new O(this.config).validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return lt(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}};import{AbiRegistry as gt,Address as I,AddressValue as ft,BytesValue as y,SmartContractTransactionsFactory as ie,TransactionsFactoryConfig as se}from"@multiversx/sdk-core/out";var z={buildInfo:{rustc:{version:"1.80.0-nightly",commitHash:"791adf759cc065316f054961875052d5bc03e16c",commitDate:"2024-05-21",channel:"Nightly",short:"rustc 1.80.0-nightly (791adf759 2024-05-21)"},contractCrate:{name:"registry",version:"0.0.1"},framework:{name:"multiversx-sc",version:"0.51.1"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"},{name:"vault",type:"Address"}],outputs:[]},upgradeConstructor:{inputs:[],outputs:[]},endpoints:[{name:"registerWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias_opt",type:"optional<bytes>",multi_arg:!0},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],outputs:[],allow_multiple_var_args:!0},{name:"unregisterWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"upgradeWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"alias",type:"bytes"},{name:"new_warp",type:"bytes"}],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"verifyWarp",onlyOwner:!0,mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<InfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"setVault",onlyOwner:!0,mutability:"mutable",inputs:[{name:"vault",type:"Address"}],outputs:[]},{name:"setUnitPrice",onlyOwner:!0,mutability:"mutable",inputs:[{name:"amount",type:"BigUint"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"BigUint"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0}]},{identifier:"warpVerified",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"creator",type:"Address"},{name:"created_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var S=class{constructor(t){this.config=t,this.cache=new B(t.cacheType),this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=I.newFromBech32(this.config.userAddress),n=e?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:n,arguments:e?[y.fromHex(t),y.fromUTF8(e)]:[y.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=I.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[y.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=I.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromUTF8(t),y.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=I.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromHex(t),y.fromUTF8(e)]})}createWarpVerifyTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=I.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[y.fromHex(t)]})}createBrandRegisterTransaction(t){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=I.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=I.newFromBech32(this.config.userAddress);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromHex(t),y.fromHex(e)]})}async getInfoByAlias(t,e){let r=v.RegistryInfo(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:i,function:"getInfoByAlias",arguments:[y.fromUTF8(t)]}),c=await s.runQuery(o),[p]=s.parseQueryResponse(c),u=p?D(p):null,l=u?.brand?await this.fetchBrand(u.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:u,brand:l},e.ttl),{registryInfo:u,brand:l}}async getInfoByHash(t,e){let r=v.RegistryInfo(t);if(e){let l=this.cache.get(r);if(l)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),l}let n=this.getRegistryContractAddress(),i=this.getController(),s=i.createQuery({contract:n,function:"getInfoByHash",arguments:[y.fromHex(t)]}),o=await i.runQuery(s),[c]=i.parseQueryResponse(o),p=c?D(c):null,u=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:u},e.ttl),{registryInfo:p,brand:u}}async getUserWarpRegistryInfos(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getUserWarps",arguments:[new ft(new I(e))]}),s=await n.runQuery(i),[o]=n.parseQueryResponse(s);return o.map(D)}async getUserBrands(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getUserBrands",arguments:[new ft(new I(e))]}),s=await n.runQuery(i),[o]=n.parseQueryResponse(s),c=o.map(l=>l.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(c.map(l=>this.fetchBrand(l,p)))).filter(l=>l!==null)}async getChainInfo(t,e){let r=v.ChainInfo(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:i,function:"getChain",arguments:[y.fromUTF8(t)]}),c=await s.runQuery(o),[p]=s.parseQueryResponse(c),u=p?ut(p):null;return u&&e?.ttl&&this.cache.set(r,u,e.ttl),u}async fetchBrand(t,e){let r=v.Brand(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let i=w(this.config),o=g.getChainEntrypoint(i,this.config.env).createNetworkProvider();try{let c=await o.getTransaction(t),p=JSON.parse(c.data.toString());return p.meta={hash:c.hash,creator:c.sender.bech32(),createdAt:new Date(c.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,p,e.ttl),p}catch(c){return console.error("WarpRegistry: Error fetching brand from transaction hash",c),null}}getRegistryContractAddress(){return I.newFromBech32(this.config.registryContract||h.Registry.Contract(this.config.env))}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),[r]=await e.query({contract:t,function:"getConfig",arguments:[]}),n=BigInt(r.toString());this.unitPrice=n}getFactory(){let t=new se({chainID:b(this.config.env)}),e=gt.create(z);return new ie({config:t,abi:e})}getController(){let t=w(this.config),e=g.getChainEntrypoint(t,this.config.env),r=gt.create(z);return e.createSmartContractController(r)}};var M=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(d.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),s=(await Promise.all(n)).filter(p=>p.match),o=s.length>0,c=s.map(p=>({url:p.url,warp:p.warp}));return{match:o,results:c}}async detect(t){let e=t.startsWith(d.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):g.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:n}=e,i=new H(this.config),s=new S(this.config),o=null,c=null,p=null;if(r==="hash"){o=await i.createFromTransactionHash(n);try{let{registryInfo:u,brand:l}=await s.getInfoByHash(n);c=u,p=l}catch{}}else if(r==="alias"){let{registryInfo:u,brand:l}=await s.getInfoByAlias(n);c=u,p=l,u&&(o=await i.createFromTransactionHash(u.hash))}return o?{match:!0,url:t,warp:o,registryInfo:c,brand:p}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||h.DefaultClientUrl(this.config.env),n=t===d.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+d.IdentifierParamSeparator+e);return h.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${d.IdentifierParamName}=${n}`}generateQrCode(t,e,r=512,n="white",i="black",s="#23F7DD"){let o=this.build(t,e);return new ae({type:"svg",width:r,height:r,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:n},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(s)}" 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>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=h.SuperClientUrls.includes(e.origin),n=e.searchParams.get(d.IdentifierParamName),i=r&&!n?e.pathname.split("/")[1]:n;if(!i)return null;let s=decodeURIComponent(i);return g.getInfoFromPrefixedIdentifier(s)}};var ue="https://",mt="query",ht="env",g=class a{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),n=(i,s)=>{r=r.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(t.vars).forEach(([i,s])=>{if(typeof s=="string"&&s.startsWith(`${mt}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${mt}:`)[1],c=new URL(e.currentUrl).searchParams.get(o);c&&n(i,c)}else if(typeof s=="string"&&s.startsWith(`${ht}:`)){let o=s.split(`${ht}:`)[1],c=e.vars?.[o];c&&n(i,c)}else n(i,s)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(d.IdentifierParamSeparator)?e:`${d.IdentifierType.Alias}${d.IdentifierParamSeparator}${e}`,[n,i]=r.split(d.IdentifierParamSeparator);return{type:n,id:i}}static getNextStepUrl(t,e,r){let n=t.next||t.actions?.[e]?.next||null;if(!n)return null;if(n.startsWith(ue))return n;{let i=new M(r),s=a.getInfoFromPrefixedIdentifier(n);return s?i.build(s.type,s.id):null}}static async getChainInfoForAction(t,e){if(!t.chain)return w(e);let r=await new S(e).getChainInfo(t.chain);if(!r)throw new Error(`WarpActionExecutor: Chain info not found for ${t.chain}`);return r}static getChainEntrypoint(t,e){let r="warp-sdk",n="api";return e==="devnet"?new oe(t.apiUrl,n,r):e==="testnet"?new pe(t.apiUrl,n,r):new ce(t.apiUrl,n,r)}};var wt=class{constructor(t){this.pendingBrand={protocol:V("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let e=new le({chainID:b(this.config.env)}),r=new de({config:e}),n=yt.newFromBech32(this.config.userAddress),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer(n,{receiver:yt.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))})}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.ensureValidSchema(r),r}async createFromTransaction(t,e=!1){return await this.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=w(this.config),n=g.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let i=await n.getTransaction(t);return this.createFromTransaction(i)}catch(i){return console.error("BrandBuilder: Error creating from transaction hash",i),null}}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.brandSchemaUrl||h.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),i=new ge,s=i.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};import{Address as fe,AddressValue as me,BigUIntType as he,BigUIntValue as Tt,BooleanValue as ye,BytesValue as we,CodeMetadata as Te,CodeMetadataValue as We,CompositeType as Ce,CompositeValue as Ae,Field as K,FieldDefinition as G,List as Ie,NothingValue as be,OptionalValue as J,OptionValue as Z,StringValue as ve,Struct as xe,StructType as Be,TokenIdentifierType as Se,TokenIdentifierValue as Wt,U16Value as Pe,U32Value as Ee,U64Type as Ve,U64Value as Ct,U8Value as Re,VariadicValue as Ue}from"@multiversx/sdk-core/out";var pn=(a,t)=>a?Z.newProvided(a):t?Z.newMissingTyped(t):Z.newMissing(),un=(a,t)=>a?new J(a.getType(),a):t?new J(t):J.newMissing(),ln=a=>{if(a.length===0)throw new Error("Cannot create a list from an empty array");let t=a[0].getType();return new Ie(t,a)},dn=a=>Ue.fromItems(...a),gn=a=>{let t=a.map(e=>e.getType());return new Ae(new Ce(...t),a)},fn=a=>ve.fromUTF8(a),mn=a=>new Re(a),hn=a=>new Pe(a),yn=a=>new Ee(a),wn=a=>new Ct(a),Tn=a=>new Tt(BigInt(a)),Wn=a=>new ye(a),Cn=a=>new me(fe.newFromBech32(a)),An=a=>new Wt(a),In=a=>we.fromHex(a),bn=a=>new xe(new Be("EsdtTokenPayment",[new G("token_identifier","",new Se),new G("token_nonce","",new Ve),new G("amount","",new he)]),[new K(new Wt(a.token.identifier),"token_identifier"),new K(new Ct(BigInt(a.token.nonce)),"token_nonce"),new K(new Tt(BigInt(a.amount)),"amount")]),vn=a=>new We(Te.newFromBytes(Uint8Array.from(Buffer.from(a,"hex")))),xn=()=>new be;import{Address as Ne,TransactionsFactoryConfig as Fe,TransferTransactionsFactory as ke}from"@multiversx/sdk-core";var j=class{constructor(t){this.cache=new B;this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new Fe({chainID:b(this.config.env)}),r=new ke({config:e}),n={protocol:V("abi"),content:t},i=Ne.newFromBech32(this.config.userAddress),s=JSON.stringify(n),o=r.createTransactionForTransfer(i,{receiver:i,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(s))});return o.gasLimit=o.gasLimit+BigInt(2e6),o}async createFromRaw(t){return JSON.parse(t)}async createFromTransaction(t){let e=await this.createFromRaw(t.data.toString());return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,e){let r=v.WarpAbi(t);if(e){let o=this.cache.get(r);if(o)return console.log(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),o}let n=w(this.config),s=g.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await s.getTransaction(t),c=await this.createFromTransaction(o);return e&&e.ttl&&c&&this.cache.set(r,c,e.ttl),c}catch(o){return console.error("WarpAbiBuilder: Error creating from transaction hash",o),null}}};import{AbiRegistry as ct,Address as pt,ArgSerializer as Ke,SmartContractTransactionsFactory as Ge,Token as Jt,TokenComputer as Je,TokenTransfer as Zt,TransactionsFactoryConfig as Ze,TransferTransactionsFactory as Xe}from"@multiversx/sdk-core";import{SmartContractTransactionsOutcomeParser as Me,TransactionEventsParser as je,findEventsByFirstTopic as Qe}from"@multiversx/sdk-core/out";import{Address as $e,AddressType as At,AddressValue as It,BigUIntType as X,BigUIntValue as Y,BooleanType as bt,BooleanValue as vt,BytesType as xt,BytesValue as Bt,CodeMetadata as Oe,CodeMetadataType as St,CodeMetadataValue as Pt,CompositeType as Et,CompositeValue as Vt,Field as tt,FieldDefinition as et,List as Rt,ListType as Le,NothingValue as T,OptionalType as qe,OptionalValue as rt,OptionType as De,OptionValue as nt,StringType as Ut,StringValue as Nt,Struct as _e,StructType as Ft,Token as He,TokenIdentifierType as it,TokenIdentifierValue as st,TokenTransfer as kt,U16Type as $t,U16Value as Ot,U32Type as Lt,U32Value as qt,U64Type as at,U64Value as ot,U8Type as Dt,U8Value as _t,VariadicType as Ht,VariadicValue as Mt}from"@multiversx/sdk-core/out";var jt=new RegExp(`${d.ArgParamsSeparator}(.*)`),R=class{nativeToString(t,e){return t==="esdt"&&e instanceof kt?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(nt.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(rt.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(Rt.ClassName)){let e=t.getItems(),n=e.map(s=>this.typedToString(s).split(d.ArgParamsSeparator)[0])[0],i=e.map(s=>this.typedToString(s).split(d.ArgParamsSeparator)[1]);return`list:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(Mt.ClassName)){let e=t.getItems(),n=e.map(s=>this.typedToString(s).split(d.ArgParamsSeparator)[0])[0],i=e.map(s=>this.typedToString(s).split(d.ArgParamsSeparator)[1]);return`variadic:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(Vt.ClassName)){let e=t.getItems(),r=e.map(o=>this.typedToString(o).split(d.ArgParamsSeparator)[0]),n=e.map(o=>this.typedToString(o).split(d.ArgParamsSeparator)[1]),i=r.join(d.ArgCompositeSeparator),s=n.join(d.ArgCompositeSeparator);return`composite(${i}):${s}`}if(t.hasClassOrSuperclass(Y.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(_t.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Ot.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(qt.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(ot.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Nt.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(vt.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(It.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(st.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(Bt.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(Pt.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),n=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${n}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.stringToNative(e)}nativeToTyped(t,e){let r=this.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new Et(...e.split(d.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new Ut;if(t==="uint8")return new Dt;if(t==="uint16")return new $t;if(t==="uint32")return new Lt;if(t==="uint64")return new at;if(t==="biguint")return new X;if(t==="bool")return new bt;if(t==="address")return new At;if(t==="token")return new it;if(t==="hex")return new xt;if(t==="codemeta")return new St;if(t==="esdt"||t==="nft")return new Ft("EsdtTokenPayment",[new et("token_identifier","",new it),new et("token_nonce","",new at),new et("amount","",new X)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(d.ArgParamsSeparator),r=e[0],n=e.slice(1).join(d.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[i,s]=n.split(d.ArgParamsSeparator);return[`option:${i}`,s||null]}else if(r==="optional"){let[i,s]=n.split(d.ArgParamsSeparator);return[`optional:${i}`,s||null]}else if(r==="list"){let i=n.split(d.ArgParamsSeparator),s=i.slice(0,-1).join(d.ArgParamsSeparator),o=i[i.length-1],p=(o?o.split(","):[]).map(u=>this.stringToNative(`${s}:${u}`)[1]);return[`list:${s}`,p]}else if(r==="variadic"){let i=n.split(d.ArgParamsSeparator),s=i.slice(0,-1).join(d.ArgParamsSeparator),o=i[i.length-1],p=(o?o.split(","):[]).map(u=>this.stringToNative(`${s}:${u}`)[1]);return[`variadic:${s}`,p]}else if(r.startsWith("composite")){let i=r.match(/\(([^)]+)\)/)?.[1]?.split(d.ArgCompositeSeparator),o=n.split(d.ArgCompositeSeparator).map((c,p)=>this.stringToNative(`${i[p]}:${c}`)[1]);return[r,o]}else{if(r==="string")return[r,n];if(r==="uint8"||r==="uint16"||r==="uint32")return[r,Number(n)];if(r==="uint64"||r==="biguint")return[r,BigInt(n||0)];if(r==="bool")return[r,n==="true"];if(r==="address")return[r,n];if(r==="token")return[r,n];if(r==="hex")return[r,n];if(r==="codemeta")return[r,n];if(r==="esdt"){let[i,s,o]=n.split(d.ArgCompositeSeparator);return[r,new kt({token:new He({identifier:i,nonce:BigInt(s)}),amount:BigInt(o)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new T;if(e==="option"){let n=this.stringToTyped(r);return n instanceof T?nt.newMissingTyped(n.getType()):nt.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof T?rt.newMissing():new rt(n.getType(),n)}if(e==="list"){let[n,i]=r.split(jt,2),o=i.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Rt(this.nativeToType(n),o)}if(e==="variadic"){let[n,i]=r.split(jt,2),o=i.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Mt(new Ht(this.nativeToType(n)),o)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],i=r.split(d.ArgCompositeSeparator),s=n.split(d.ArgCompositeSeparator),o=i.map((p,u)=>this.stringToTyped(`${s[u]}:${p}`)),c=o.map(p=>p.getType());return new Vt(new Et(...c),o)}if(e==="string")return r?Nt.fromUTF8(r):new T;if(e==="uint8")return r?new _t(Number(r)):new T;if(e==="uint16")return r?new Ot(Number(r)):new T;if(e==="uint32")return r?new qt(Number(r)):new T;if(e==="uint64")return r?new ot(BigInt(r)):new T;if(e==="biguint")return r?new Y(BigInt(r)):new T;if(e==="bool")return r?new vt(typeof r=="boolean"?r:r==="true"):new T;if(e==="address")return r?new It($e.newFromBech32(r)):new T;if(e==="token")return r?new st(r):new T;if(e==="hex")return r?Bt.fromHex(r):new T;if(e==="codemeta")return new Pt(Oe.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(d.ArgCompositeSeparator);return new _e(this.nativeToType("esdt"),[new tt(new st(n[0]),"token_identifier"),new tt(new ot(BigInt(n[1])),"token_nonce"),new tt(new Y(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof De)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof qe)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Le)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Ht)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Ut)return"string";if(t instanceof Dt)return"uint8";if(t instanceof $t)return"uint16";if(t instanceof Lt)return"uint32";if(t instanceof at)return"uint64";if(t instanceof X)return"biguint";if(t instanceof bt)return"bool";if(t instanceof At)return"address";if(t instanceof it)return"token";if(t instanceof xt)return"hex";if(t instanceof St)return"codemeta";if(t instanceof Ft&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var Qt=async(a,t,e,r)=>{let n=[],i={};if(!t.results||!e.abi||e.type!=="contract")return{values:n,results:i};let s=await a.getAbiForAction(e),o=new je({abi:s}),p=new Me({abi:s}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[u,l]of Object.entries(t.results)){let[m,f,C]=l.split(".");if(m==="event"){if(!f||isNaN(Number(C)))continue;let P=Number(C),A=Qe(r,f),U=o.parseEvents({events:A})[0],x=Object.values(U)[P]||null;n.push(x),i[u]=x&&x.valueOf()}else if(m==="out"){if(!f)continue;let P=Number(f),A=p.values[P-1]||null;n.push(A),i[u]=A&&A.valueOf()}}return{values:n,results:i}},zt=async(a,t)=>{let e=new R,r=t.map(o=>e.typedToString(o)),n=t.map(o=>e.typedToNative(o)[1]),i={};if(!a.results)return{values:r,results:i};let s=o=>{let c=o.split(".").slice(1).map(u=>parseInt(u)-1);if(c.length===0)return;let p=n[c[0]];for(let u=1;u<c.length;u++){if(p==null)return;p=p[c[u]]}return p};return Object.entries(a.results).forEach(([o,c])=>{if(c.startsWith("out.")){let p=s(c);i[o]=p||null}}),{values:r,results:i}},Kt=async(a,t)=>{let e=[],r={};for(let[n,i]of Object.entries(a.results||{})){let[s,...o]=i.split(".");if(s!=="out"||!o.length)continue;let c=o.reduce((p,u)=>p?.[u],t);e.push(c),r[n]=c}return{values:e,results:r}};var ze=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],Gt=a=>ze.find(t=>t.id===a)||null;var Q=class{constructor(t){this.config=t}async getContract(t,e){try{let i=await g.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}`);return{address:t,owner:i.ownerAddress,verified:i.isVerified||!1}}catch(r){return console.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t,e){try{let i=await g.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}/verification`);return{codeHash:i.codeHash,abi:i.source.abi}}catch(r){return console.error("WarpContractLoader: getVerificationInfo error",r),null}}};var Xt=class{constructor(t){if(!t.currentUrl)throw new Error("WarpActionExecutor: currentUrl config not set");this.config=t,this.url=new URL(t.currentUrl),this.serializer=new R,this.contractLoader=new Q(t),this.registry=new S(t)}async createTransactionForExecute(t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let r=pt.newFromBech32(this.config.userAddress),n=await g.getChainInfoForAction(t,this.config),i=new Ze({chainID:n.chainId}),{destination:s,args:o,value:c,transfers:p,data:u}=await this.getTxComponentsFromInputs(t,e,r),l=o.map(m=>this.serializer.stringToTyped(m));if(t.type==="transfer")return new Xe({config:i}).createTransactionForTransfer(r,{receiver:s,nativeAmount:c,tokenTransfers:p,data:u?new Uint8Array(u):void 0});if(t.type==="contract"&&s.isSmartContract())return new Ge({config:i}).createTransactionForExecute(r,{contract:s,function:"func"in t&&t.func||"",gasLimit:"gasLimit"in t?BigInt(t.gasLimit||0):0n,arguments:l,tokenTransfers:p,nativeTransferAmount:c});throw t.type==="query"?new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead"):t.type==="collect"?new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead"):new Error(`WarpActionExecutor: Invalid action type (${t.type})`)}async getTransactionExecutionResults(t,e,r){let n=q(t,e),i=g.getNextStepUrl(t,e,this.config),{values:s,results:o}=await Qt(this,t,n,r),c=this.getPreparedMessages(t,o);return{success:r.status.isSuccessful(),warp:t,action:e,user:this.config.userAddress||null,txHash:r.hash,redirectUrl:i,values:s,results:o,messages:c}}async executeQuery(t,e,r){let n=q(t,e);if(!n)throw new Error("WarpActionExecutor: Action not found");if(!n.func)throw new Error("WarpActionExecutor: Function not found");let i=await g.getChainInfoForAction(n,this.config),s=await this.getAbiForAction(n),{args:o}=await this.getTxComponentsFromInputs(n,r),c=o.map(F=>this.serializer.stringToTyped(F)),p=g.getChainEntrypoint(i,this.config.env),u=pt.newFromBech32(n.address),l=p.createSmartContractController(s),m=l.createQuery({contract:u,function:n.func,arguments:c}),f=await l.runQuery(m),C=f.returnCode==="ok",P=new Ke,A=s.getEndpoint(f.function),U=f.returnDataParts.map(F=>Buffer.from(F)),x=P.buffersToValues(U,A.output),{values:L,results:N}=await zt(t,x);return{success:C,warp:t,action:e,user:this.config.userAddress||null,txHash:null,redirectUrl:n.next||null,values:L,results:N,messages:this.getPreparedMessages(t,N)}}async executeCollect(t,e,r,n){let i=q(t,e);if(!i)throw new Error("WarpActionExecutor: Action not found");let s=await this.getResolvedInputs(i,r),o=this.getModifiedInputs(s),c=l=>{if(!l.value)return null;let m=this.serializer.stringToNative(l.value)[1];if(l.input.type==="biguint")return m.toString();if(l.input.type==="esdt"){let f=m;return{token:f.token.identifier,nonce:f.token.nonce.toString(),amount:f.amount.toString()}}else return m},p=Object.fromEntries(o.map(l=>[l.input.as||l.input.name,c(l)])),u=new Headers;u.set("Content-Type","application/json"),u.set("Accept","application/json"),Object.entries(i.destination.headers).forEach(([l,m])=>{u.set(l,m)});try{let l=await fetch(i.destination.url,{method:i.destination.method,headers:u,body:JSON.stringify({inputs:p,meta:n})}),m=await l.json(),{values:f,results:C}=await Kt(t,m);return{success:l.ok,warp:t,action:e,user:this.config.userAddress||null,txHash:null,redirectUrl:i.next||null,values:f,results:C,messages:this.getPreparedMessages(t,C)}}catch(l){return console.error(l),{success:!1,warp:t,action:e,user:this.config.userAddress||null,txHash:null,redirectUrl:null,values:[],results:{},messages:{}}}}async getTxComponentsFromInputs(t,e,r){let n=await this.getResolvedInputs(t,e),i=this.getModifiedInputs(n),s=i.find(W=>W.input.position==="receiver")?.value,o="address"in t?t.address:null,c=s?.split(":")[1]||o||r?.toBech32();if(!c)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let p=pt.newFromBech32(c),u=this.getPreparedArgs(t,i),l=i.find(W=>W.input.position==="value")?.value||null,m="value"in t?t.value:null,f=BigInt(l?.split(":")[1]||m||0),C=i.filter(W=>W.input.position==="transfer"&&W.value).map(W=>W.value),A=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...C?.map(W=>this.serializer.stringToNative(W)[1])||[]],U=i.find(W=>W.input.position==="data")?.value,x="data"in t?t.data||"":null,L=U||x||null,N=L?this.serializer.stringToTyped(L).valueOf():null,F=N?Buffer.from(N):null;return{destination:p,args:u,value:f,transfers:A,data:F}}async getResolvedInputs(t,e){let r=t.inputs||[],n=await Promise.all(e.map(s=>this.preprocessInput(s))),i=(s,o)=>{if(s.source==="query"){let c=this.url.searchParams.get(s.name);return c?this.serializer.nativeToString(s.type,c):null}else return s.source==="user_wallet"?this.config.userAddress?this.serializer.nativeToString("address",this.config.userAddress):null:n[o]||null};return r.map((s,o)=>({input:s,value:i(s,o)}))}getModifiedInputs(t){return t.map((e,r)=>{if(e.input.modifier?.startsWith("scale:")){let[,n]=e.input.modifier.split(":");if(isNaN(Number(n))){let i=Number(t.find(c=>c.input.name===n)?.value?.split(":")[1]);if(!i)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let s=e.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=_(s,+i);return{...e,value:`${e.input.type}:${o}`}}else{let i=e.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let s=_(i,+n);return{...e,value:`${e.input.type}:${s}`}}}else return e})}async preprocessInput(t){try{let[e,r]=t.split(d.ArgParamsSeparator,2);if(e==="esdt"){let[n,i,s,o]=r.split(d.ArgCompositeSeparator);if(o)return t;let c=new Jt({identifier:n,nonce:BigInt(i)});if(!new Je().isFungible(c))return t;let l=Gt(n)?.decimals;if(!l){let f=this.config.chainApiUrl||h.MainChain.ApiUrl(this.config.env);l=(await(await fetch(`${f}/tokens/${n}`)).json()).decimals}if(!l)throw new Error(`WarpActionExecutor: Decimals not found for token ${n}`);let m=new Zt({token:c,amount:_(s,l)});return this.serializer.nativeToString(e,m)+d.ArgCompositeSeparator+l}return t}catch{return t}}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=w(this.config),r=await this.contractLoader.getVerificationInfo(t.address,e);if(!r)throw new Error("WarpActionExecutor: Verification info not found");return ct.create(r.abi)}getPreparedArgs(t,e){let r="args"in t?t.args||[]:[];return e.forEach(({input:n,value:i})=>{if(!i||!n.position.startsWith("arg:"))return;let s=Number(n.position.split(":")[1])-1;r.splice(s,0,i)}),r}getPreparedMessages(t,e){let r=Object.entries(t.messages||{}).map(([n,i])=>[n,i.replace(/\{\{([^}]+)\}\}/g,(s,o)=>e[o]||"")]);return Object.fromEntries(r)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(d.IdentifierType.Hash)){let e=new j(this.config),r=t.abi.split(d.IdentifierParamSeparator)[1],n=await e.createFromTransactionHash(r);if(!n)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return ct.create(n.content)}else{let r=await(await fetch(t.abi)).json();return ct.create(r)}}toTypedTransfer(t){return new Zt({token:new Jt({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var Yt=class{constructor(t){this.config=t}async search(t,e,r){if(!this.config.indexUrl)throw new Error("WarpIndex: Index URL is not set");try{let n=await fetch(this.config.indexUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.indexApiKey}`,...r},body:JSON.stringify({[this.config.indexSearchParamName||"search"]:t,...e})});if(!n.ok)throw new Error(`WarpIndex: search failed with status ${n.status}`);return(await n.json()).hits}catch(n){throw console.error("WarpIndex: Error searching for warps: ",n),n}}};export{wt as BrandBuilder,v as CacheKey,h as Config,j as WarpAbiBuilder,Xt as WarpActionExecutor,R as WarpArgSerializer,H as WarpBuilder,B as WarpCache,d as WarpConstants,Q as WarpContractLoader,Yt as WarpIndex,M as WarpLink,E as WarpProtocolVersions,S as WarpRegistry,g as WarpUtils,O as WarpValidator,Cn as address,Tn as biguint,Wn as boolean,vn as codemeta,gn as composite,bn as esdt,b as getChainId,V as getLatestProtocolIdentifier,w as getMainChainInfo,q as getWarpActionByIndex,In as hex,ln as list,xn as nothing,pn as option,un as optional,_ as shiftBigintBy,fn as string,lt as toPreviewText,ut as toTypedChainInfo,D as toTypedRegistryInfo,An as token,hn as u16,yn as u32,wn as u64,mn as u8,dn as variadic};
|