@vleap/warps 2.0.0-alpha.6 → 2.0.0-alpha.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -223,7 +223,7 @@ type RegistryInfo = {
223
223
  upgrade: string | null;
224
224
  };
225
225
 
226
- type WarpExecutionResult = {
226
+ type WarpExecution = {
227
227
  success: boolean;
228
228
  warp: Warp;
229
229
  action: number;
@@ -322,6 +322,7 @@ declare const toTypedRegistryInfo: (registryInfo: any) => RegistryInfo;
322
322
  declare const toTypedChainInfo: (chainInfo: any) => ChainInfo;
323
323
  declare const shiftBigintBy: (value: bigint | string, decimals: number) => bigint;
324
324
  declare const toPreviewText: (text: string, maxChars?: number) => string;
325
+ declare const replacePlaceholders: (message: string, bag: Record<string, any>) => string;
325
326
 
326
327
  declare const option: (value: TypedValue | null, type?: Type) => OptionValue;
327
328
  declare const optional: (value: TypedValue | null, type?: Type) => OptionalValue;
@@ -364,9 +365,9 @@ declare class WarpActionExecutor {
364
365
  private registry;
365
366
  constructor(config: WarpConfig);
366
367
  createTransactionForExecute(action: WarpTransferAction | WarpContractAction, inputs: string[]): Promise<Transaction>;
367
- getTransactionExecutionResults(warp: Warp, actionIndex: number, tx: TransactionOnNetwork): Promise<WarpExecutionResult>;
368
- executeQuery(warp: Warp, actionIndex: number, inputs: string[]): Promise<WarpExecutionResult>;
369
- executeCollect(warp: Warp, actionIndex: number, inputs: string[], meta?: Record<string, any>): Promise<WarpExecutionResult>;
368
+ getTransactionExecutionResults(warp: Warp, actionIndex: number, tx: TransactionOnNetwork): Promise<WarpExecution>;
369
+ executeQuery(warp: Warp, actionIndex: number, inputs: string[]): Promise<WarpExecution>;
370
+ executeCollect(warp: Warp, actionIndex: number, inputs: string[], meta?: Record<string, any>): Promise<WarpExecution>;
370
371
  getTxComponentsFromInputs(action: WarpTransferAction | WarpContractAction | WarpQueryAction, inputs: string[], sender?: Address): Promise<{
371
372
  destination: Address;
372
373
  args: string[];
@@ -492,7 +493,7 @@ declare class WarpUtils {
492
493
  type: WarpIdType;
493
494
  id: string;
494
495
  } | null;
495
- static getNextInfo(warp: Warp, actionIndex: number, config: WarpConfig): WarpExecutionNextInfo | null;
496
+ static getNextInfo(warp: Warp, actionIndex: number, results: WarpExecutionResults, config: WarpConfig): WarpExecutionNextInfo | null;
496
497
  static getChainInfoForAction(action: WarpTransferAction | WarpContractAction | WarpQueryAction, config: WarpConfig): Promise<ChainInfo>;
497
498
  static getChainEntrypoint(chainInfo: ChainInfo, env: ChainEnv): NetworkEntrypoint;
498
499
  }
@@ -508,4 +509,4 @@ declare class WarpValidator {
508
509
  private throwUnless;
509
510
  }
510
511
 
511
- 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 WarpExecutionNextInfo, 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 };
512
+ 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 WarpExecution, type WarpExecutionMessages, type WarpExecutionNextInfo, 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, replacePlaceholders, shiftBigintBy, string, toPreviewText, toTypedChainInfo, toTypedRegistryInfo, token, u16, u32, u64, u8, variadic };
package/dist/index.d.ts CHANGED
@@ -223,7 +223,7 @@ type RegistryInfo = {
223
223
  upgrade: string | null;
224
224
  };
225
225
 
226
- type WarpExecutionResult = {
226
+ type WarpExecution = {
227
227
  success: boolean;
228
228
  warp: Warp;
229
229
  action: number;
@@ -322,6 +322,7 @@ declare const toTypedRegistryInfo: (registryInfo: any) => RegistryInfo;
322
322
  declare const toTypedChainInfo: (chainInfo: any) => ChainInfo;
323
323
  declare const shiftBigintBy: (value: bigint | string, decimals: number) => bigint;
324
324
  declare const toPreviewText: (text: string, maxChars?: number) => string;
325
+ declare const replacePlaceholders: (message: string, bag: Record<string, any>) => string;
325
326
 
326
327
  declare const option: (value: TypedValue | null, type?: Type) => OptionValue;
327
328
  declare const optional: (value: TypedValue | null, type?: Type) => OptionalValue;
@@ -364,9 +365,9 @@ declare class WarpActionExecutor {
364
365
  private registry;
365
366
  constructor(config: WarpConfig);
366
367
  createTransactionForExecute(action: WarpTransferAction | WarpContractAction, inputs: string[]): Promise<Transaction>;
367
- getTransactionExecutionResults(warp: Warp, actionIndex: number, tx: TransactionOnNetwork): Promise<WarpExecutionResult>;
368
- executeQuery(warp: Warp, actionIndex: number, inputs: string[]): Promise<WarpExecutionResult>;
369
- executeCollect(warp: Warp, actionIndex: number, inputs: string[], meta?: Record<string, any>): Promise<WarpExecutionResult>;
368
+ getTransactionExecutionResults(warp: Warp, actionIndex: number, tx: TransactionOnNetwork): Promise<WarpExecution>;
369
+ executeQuery(warp: Warp, actionIndex: number, inputs: string[]): Promise<WarpExecution>;
370
+ executeCollect(warp: Warp, actionIndex: number, inputs: string[], meta?: Record<string, any>): Promise<WarpExecution>;
370
371
  getTxComponentsFromInputs(action: WarpTransferAction | WarpContractAction | WarpQueryAction, inputs: string[], sender?: Address): Promise<{
371
372
  destination: Address;
372
373
  args: string[];
@@ -492,7 +493,7 @@ declare class WarpUtils {
492
493
  type: WarpIdType;
493
494
  id: string;
494
495
  } | null;
495
- static getNextInfo(warp: Warp, actionIndex: number, config: WarpConfig): WarpExecutionNextInfo | null;
496
+ static getNextInfo(warp: Warp, actionIndex: number, results: WarpExecutionResults, config: WarpConfig): WarpExecutionNextInfo | null;
496
497
  static getChainInfoForAction(action: WarpTransferAction | WarpContractAction | WarpQueryAction, config: WarpConfig): Promise<ChainInfo>;
497
498
  static getChainEntrypoint(chainInfo: ChainInfo, env: ChainEnv): NetworkEntrypoint;
498
499
  }
@@ -508,4 +509,4 @@ declare class WarpValidator {
508
509
  private throwUnless;
509
510
  }
510
511
 
511
- 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 WarpExecutionNextInfo, 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 };
512
+ 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 WarpExecution, type WarpExecutionMessages, type WarpExecutionNextInfo, 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, replacePlaceholders, 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 Z=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)Z(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&&Z(a,n,{get:()=>t[n],enumerable:!(r=Tt(t,n))||r.enumerable});return a};var Y=(a,t,e)=>(e=a!=null?wt(Ct(a)):{},ot(t||!a||!a.__esModule?Z(e,"default",{value:a,enumerable:!0}):e,a)),bt=a=>ot(Z({},"__esModule",{value:!0}),a);var Qt={};It(Qt,{BrandBuilder:()=>nt,CacheKey:()=>x,Config:()=>W,WarpAbiBuilder:()=>z,WarpActionExecutor:()=>it,WarpArgSerializer:()=>N,WarpBuilder:()=>G,WarpCache:()=>S,WarpConstants:()=>g,WarpContractLoader:()=>K,WarpIndex:()=>st,WarpLink:()=>at,WarpProtocolVersions:()=>V,WarpRegistry:()=>P,WarpUtils:()=>h,WarpValidator:()=>L,address:()=>Lt,biguint:()=>$t,boolean:()=>Ot,codemeta:()=>Ht,composite:()=>Vt,esdt:()=>_t,getChainId:()=>v,getLatestProtocolIdentifier:()=>R,getMainChainInfo:()=>A,getWarpActionByIndex:()=>_,hex:()=>Dt,list:()=>Pt,nothing:()=>Mt,option:()=>Bt,optional:()=>St,shiftBigintBy:()=>M,string:()=>Rt,toPreviewText:()=>et,toTypedChainInfo:()=>tt,toTypedRegistryInfo:()=>H,token:()=>qt,u16:()=>Nt,u32:()=>Ft,u64:()=>kt,u8:()=>Ut,variadic:()=>Et});module.exports=bt(Qt);var U=require("@multiversx/sdk-core"),ut=Y(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",A=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}`)},_=(a,t)=>a?.actions[t-1],H=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}),tt=a=>({chainId:a.chain_id.toString(),apiUrl:a.api_url.toString(),explorerUrl:a.explorer_url.toString(),blockTime:a.block_time.toNumber()}),M=(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)},et=(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 k=require("@multiversx/sdk-core");var g={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};var m=require("@multiversx/sdk-core/out");var rt={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 j=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 Q=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}`},S=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new j:t==="memory"?new Q:typeof window<"u"&&window.localStorage?new j:new Q}set(t,e,r){this.strategy.set(t,e,r)}get(t){return this.strategy.get(t)}clear(){this.strategy.clear()}};var P=class{constructor(t){this.config=t,this.cache=new S(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),[u]=o.parseQueryResponse(p),d=u?H(u):null,f=d?.brand?await this.fetchBrand(d.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:d,brand:f},e.ttl),{registryInfo:d,brand:f}}async getInfoByHash(t,e){let r=x.RegistryInfo(t);if(e){let f=this.cache.get(r);if(f)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),f}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),u=p?H(p):null,d=u?.brand?await this.fetchBrand(u.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:u,brand:d},e.ttl),{registryInfo:u,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(H)}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(f=>f.toString("hex")),u={ttl:365*24*60*60};return(await Promise.all(p.map(f=>this.fetchBrand(f,u)))).filter(f=>f!==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),[u]=o.parseQueryResponse(p),d=u?tt(u):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=A(this.config),c=h.getChainEntrypoint(i,this.config.env).createNetworkProvider();try{let p=await c.getTransaction(t),u=JSON.parse(p.data.toString());return u.meta={hash:p.hash,creator:p.sender.bech32(),createdAt:new Date(p.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,u,e.ttl),u}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(rt);return new m.SmartContractTransactionsFactory({config:t,abi:e})}getController(){let t=A(this.config),e=h.getChainEntrypoint(t,this.config.env),r=m.AbiRegistry.create(rt);return e.createSmartContractController(r)}};var xt="https://",ct="query",pt="env",h=class{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(`${ct}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let c=o.split(`${ct}:`)[1],p=new URL(e.currentUrl).searchParams.get(c);p&&n(i,p)}else if(typeof o=="string"&&o.startsWith(`${pt}:`)){let c=o.split(`${pt}:`)[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(g.IdentifierParamSeparator)?e:`${g.IdentifierType.Alias}${g.IdentifierParamSeparator}${e}`,[n,i]=r.split(g.IdentifierParamSeparator);return{type:n,id:i}}static getNextInfo(t,e,r){let n=t.actions?.[e]?.next||t.next||null;if(!n)return null;if(n.startsWith(xt))return{identifier:null,url:n};let[i,o]=n.split("?"),c=new URLSearchParams(o||"");new URL(r.currentUrl||W.DefaultClientUrl(r.env)).searchParams.forEach((f,w)=>c.set(w,f));let u=c.toString()?`${i}?${c.toString()}`:i,d=new URL(r.clientUrl||W.DefaultClientUrl(r.env));return d.searchParams.set("warp",u),{identifier:u,url:d.toString().replace(/\/\?/,"?")}}static async getChainInfoForAction(t,e){if(!t.chain)return A(e);let r=await new P(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 k.DevnetEntrypoint(t.apiUrl,n,r):e==="testnet"?new k.TestnetEntrypoint(t.apiUrl,n,r):new k.MainnetEntrypoint(t.apiUrl,n,r)}};var nt=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 U.TransactionsFactoryConfig({chainID:v(this.config.env)}),r=new U.TransferTransactionsFactory({config:e}),n=U.Address.newFromBech32(this.config.userAddress),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer(n,{receiver:U.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=A(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 ut.default,o=i.compile(n);if(!o(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(o.errors)}`)}};var l=require("@multiversx/sdk-core/out"),Bt=(a,t)=>a?l.OptionValue.newProvided(a):t?l.OptionValue.newMissingTyped(t):l.OptionValue.newMissing(),St=(a,t)=>a?new l.OptionalValue(a.getType(),a):t?new l.OptionalValue(t):l.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 l.List(t,a)},Et=a=>l.VariadicValue.fromItems(...a),Vt=a=>{let t=a.map(e=>e.getType());return new l.CompositeValue(new l.CompositeType(...t),a)},Rt=a=>l.StringValue.fromUTF8(a),Ut=a=>new l.U8Value(a),Nt=a=>new l.U16Value(a),Ft=a=>new l.U32Value(a),kt=a=>new l.U64Value(a),$t=a=>new l.BigUIntValue(BigInt(a)),Ot=a=>new l.BooleanValue(a),Lt=a=>new l.AddressValue(l.Address.newFromBech32(a)),qt=a=>new l.TokenIdentifierValue(a),Dt=a=>l.BytesValue.fromHex(a),_t=a=>new l.Struct(new l.StructType("EsdtTokenPayment",[new l.FieldDefinition("token_identifier","",new l.TokenIdentifierType),new l.FieldDefinition("token_nonce","",new l.U64Type),new l.FieldDefinition("amount","",new l.BigUIntType)]),[new l.Field(new l.TokenIdentifierValue(a.token.identifier),"token_identifier"),new l.Field(new l.U64Value(BigInt(a.token.nonce)),"token_nonce"),new l.Field(new l.BigUIntValue(BigInt(a.amount)),"amount")]),Ht=a=>new l.CodeMetadataValue(l.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(a,"hex")))),Mt=()=>new l.NothingValue;var $=require("@multiversx/sdk-core");var z=class{constructor(t){this.cache=new S;this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new $.TransactionsFactoryConfig({chainID:v(this.config.env)}),r=new $.TransferTransactionsFactory({config:e}),n={protocol:R("abi"),content:t},i=$.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=A(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 O=require("@multiversx/sdk-core/out");var s=require("@multiversx/sdk-core/out");var lt=new RegExp(`${g.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(o=>this.typedToString(o).split(g.ArgParamsSeparator)[0])[0],i=e.map(o=>this.typedToString(o).split(g.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(g.ArgParamsSeparator)[0])[0],i=e.map(o=>this.typedToString(o).split(g.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(g.ArgParamsSeparator)[0]),n=e.map(c=>this.typedToString(c).split(g.ArgParamsSeparator)[1]),i=r.join(g.ArgCompositeSeparator),o=n.join(g.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(g.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(g.ArgParamsSeparator),r=e[0],n=e.slice(1).join(g.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[i,o]=n.split(g.ArgParamsSeparator);return[`option:${i}`,o||null]}else if(r==="optional"){let[i,o]=n.split(g.ArgParamsSeparator);return[`optional:${i}`,o||null]}else if(r==="list"){let i=n.split(g.ArgParamsSeparator),o=i.slice(0,-1).join(g.ArgParamsSeparator),c=i[i.length-1],u=(c?c.split(","):[]).map(d=>this.stringToNative(`${o}:${d}`)[1]);return[`list:${o}`,u]}else if(r==="variadic"){let i=n.split(g.ArgParamsSeparator),o=i.slice(0,-1).join(g.ArgParamsSeparator),c=i[i.length-1],u=(c?c.split(","):[]).map(d=>this.stringToNative(`${o}:${d}`)[1]);return[`variadic:${o}`,u]}else if(r.startsWith("composite")){let i=r.match(/\(([^)]+)\)/)?.[1]?.split(g.ArgCompositeSeparator),c=n.split(g.ArgCompositeSeparator).map((p,u)=>this.stringToNative(`${i[u]}:${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(g.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(lt,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(lt,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(g.ArgCompositeSeparator),o=n.split(g.ArgCompositeSeparator),c=i.map((u,d)=>this.stringToTyped(`${o[d]}:${u}`)),p=c.map(u=>u.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(g.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 dt=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 O.TransactionEventsParser({abi:o}),u=new O.SmartContractTransactionsOutcomeParser({abi:o}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[d,f]of Object.entries(t.results)){let[w,T,I]=f.split(".");if(w==="event"){if(!T||isNaN(Number(I)))continue;let B=Number(I),b=(0,O.findEventsByFirstTopic)(r,T),q=c.parseEvents({events:b})[0],E=Object.values(q)[B]||null;n.push(E),i[d]=E&&E.valueOf()}else if(w==="out"){if(!T)continue;let B=Number(T),b=u.values[B-1]||null;n.push(b),i[d]=b&&b.valueOf()}}return{values:n,results:i}},ft=async(a,t)=>{let e=new N,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 u=n[p[0]];for(let d=1;d<p.length;d++){if(u==null)return;u=u[p[d]]}return u};return Object.entries(a.results).forEach(([c,p])=>{if(p.startsWith("out.")){let u=o(p);i[c]=u||null}}),{values:r,results:i}},gt=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((u,d)=>u?.[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}],mt=a=>jt.find(t=>t.id===a)||null;var K=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 it=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 K(t),this.registry=new P(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:u,data:d}=await this.getTxComponentsFromInputs(t,e,r),f=c.map(w=>this.serializer.stringToTyped(w));if(t.type==="transfer")return new y.TransferTransactionsFactory({config:i}).createTransactionForTransfer(r,{receiver:o,nativeAmount:p,tokenTransfers:u,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:f,tokenTransfers:u,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=_(t,e),i=h.getNextInfo(t,e,this.config),{values:o,results:c}=await dt(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,next:i,values:o,results:c,messages:p}}async executeQuery(t,e,r){let n=_(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(C=>this.serializer.stringToTyped(C)),u=h.getChainEntrypoint(i,this.config.env),d=y.Address.newFromBech32(n.address),f=u.createSmartContractController(o),w=f.createQuery({contract:d,function:n.func,arguments:p}),T=await f.runQuery(w),I=T.returnCode==="ok",B=new y.ArgSerializer,b=o.getEndpoint(T.function),q=T.returnDataParts.map(C=>Buffer.from(C)),E=B.buffersToValues(q,b.output),{values:J,results:D}=await ft(t,E),X=h.getNextInfo(t,e,this.config);return{success:I,warp:t,action:e,user:this.config.userAddress||null,txHash:null,next:X,values:J,results:D,messages:this.getPreparedMessages(t,D)}}async executeCollect(t,e,r,n){let i=_(t,e);if(!i)throw new Error("WarpActionExecutor: Action not found");let o=await this.getResolvedInputs(i,r),c=this.getModifiedInputs(o),p=f=>{if(!f.value)return null;let w=this.serializer.stringToNative(f.value)[1];if(f.input.type==="biguint")return w.toString();if(f.input.type==="esdt"){let T=w;return{token:T.token.identifier,nonce:T.token.nonce.toString(),amount:T.amount.toString()}}else return w},u=Object.fromEntries(c.map(f=>[f.input.as||f.input.name,p(f)])),d=new Headers;d.set("Content-Type","application/json"),d.set("Accept","application/json"),Object.entries(i.destination.headers).forEach(([f,w])=>{d.set(f,w)});try{let f=await fetch(i.destination.url,{method:i.destination.method,headers:d,body:JSON.stringify({inputs:u,meta:n})}),w=await f.json(),{values:T,results:I}=await gt(t,w),B=h.getNextInfo(t,e,this.config);return{success:f.ok,warp:t,action:e,user:this.config.userAddress||null,txHash:null,next:B,values:T,results:I,messages:this.getPreparedMessages(t,I)}}catch(f){return console.error(f),{success:!1,warp:t,action:e,user:this.config.userAddress||null,txHash:null,next:null,values:[],results:{},messages:{}}}}async getTxComponentsFromInputs(t,e,r){let n=await this.getResolvedInputs(t,e),i=this.getModifiedInputs(n),o=i.find(C=>C.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 u=y.Address.newFromBech32(p),d=this.getPreparedArgs(t,i),f=i.find(C=>C.input.position==="value")?.value||null,w="value"in t?t.value:null,T=BigInt(f?.split(":")[1]||w||0),I=i.filter(C=>C.input.position==="transfer"&&C.value).map(C=>C.value),b=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...I?.map(C=>this.serializer.stringToNative(C)[1])||[]],q=i.find(C=>C.input.position==="data")?.value,E="data"in t?t.data||"":null,J=q||E||null,D=J?this.serializer.stringToTyped(J).valueOf():null,X=D?Buffer.from(D):null;return{destination:u,args:d,value:T,transfers:b,data:X}}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=M(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=M(i,+n);return{...e,value:`${e.input.type}:${o}`}}}else return e})}async preprocessInput(t){try{let[e,r]=t.split(g.ArgParamsSeparator,2);if(e==="esdt"){let[n,i,o,c]=r.split(g.ArgCompositeSeparator);if(c)return t;let p=new y.Token({identifier:n,nonce:BigInt(i)});if(!new y.TokenComputer().isFungible(p))return t;let f=mt(n)?.decimals;if(!f){let T=this.config.chainApiUrl||W.MainChain.ApiUrl(this.config.env);f=(await(await fetch(`${T}/tokens/${n}`)).json()).decimals}if(!f)throw new Error(`WarpActionExecutor: Decimals not found for token ${n}`);let w=new y.TokenTransfer({token:p,amount:M(o,f)});return this.serializer.nativeToString(e,w)+g.ArgCompositeSeparator+f}return t}catch{return t}}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=A(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(g.IdentifierType.Hash)){let e=new z(this.config),r=t.abi.split(g.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 F=require("@multiversx/sdk-core");var ht=Y(require("ajv"));var L=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 ht.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 G=class{constructor(t){this.pendingWarp={protocol:R("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t,this.cache=new S(t.cacheType)}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new F.TransactionsFactoryConfig({chainID:v(this.config.env)}),r=new F.TransferTransactionsFactory({config:e}),n=F.Address.newFromBech32(this.config.userAddress),i=JSON.stringify(t),o=r.createTransactionForTransfer(n,{receiver:F.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 L(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=A(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 L(this.config).validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return et(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}};var st=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}}};var yt=Y(require("qr-code-styling"));var at=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(g.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(u=>u[0]).filter(u=>this.isValid(u)).map(u=>this.detect(u)),o=(await Promise.all(n)).filter(u=>u.match),c=o.length>0,p=o.map(u=>({url:u.url,warp:u.warp}));return{match:c,results:p}}async detect(t){let e=t.startsWith(g.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 G(this.config),o=new P(this.config),c=null,p=null,u=null;if(r==="hash"){c=await i.createFromTransactionHash(n);try{let{registryInfo:d,brand:f}=await o.getInfoByHash(n);p=d,u=f}catch{}}else if(r==="alias"){let{registryInfo:d,brand:f}=await o.getInfoByAlias(n);p=d,u=f,d&&(c=await i.createFromTransactionHash(d.hash))}return c?{match:!0,url:t,warp:c,registryInfo:p,brand:u}:{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===g.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+g.IdentifierParamSeparator+e);return W.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${g.IdentifierParamName}=${n}`}buildFromPrefixedIdentifier(t){let e=h.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.id):""}generateQrCode(t,e,r=512,n="white",i="black",o="#23F7DD"){let c=this.build(t,e);return new yt.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(g.IdentifierParamName),i=r&&!n?e.pathname.split("/")[1]:n;if(!i)return null;let o=decodeURIComponent(i);return h.getInfoFromPrefixedIdentifier(o)}};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});
1
+ "use strict";var Tt=Object.create;var X=Object.defineProperty;var Wt=Object.getOwnPropertyDescriptor;var Ct=Object.getOwnPropertyNames;var At=Object.getPrototypeOf,It=Object.prototype.hasOwnProperty;var bt=(s,t)=>{for(var e in t)X(s,e,{get:t[e],enumerable:!0})},ct=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ct(t))!It.call(s,n)&&n!==e&&X(s,n,{get:()=>t[n],enumerable:!(r=Wt(t,n))||r.enumerable});return s};var tt=(s,t,e)=>(e=s!=null?Tt(At(s)):{},ct(t||!s||!s.__esModule?X(e,"default",{value:s,enumerable:!0}):e,s)),vt=s=>ct(X({},"__esModule",{value:!0}),s);var zt={};bt(zt,{BrandBuilder:()=>it,CacheKey:()=>x,Config:()=>W,WarpAbiBuilder:()=>K,WarpActionExecutor:()=>st,WarpArgSerializer:()=>N,WarpBuilder:()=>J,WarpCache:()=>S,WarpConstants:()=>g,WarpContractLoader:()=>G,WarpIndex:()=>at,WarpLink:()=>ot,WarpProtocolVersions:()=>V,WarpRegistry:()=>P,WarpUtils:()=>h,WarpValidator:()=>q,address:()=>qt,biguint:()=>Ot,boolean:()=>Lt,codemeta:()=>Mt,composite:()=>Rt,esdt:()=>Ht,getChainId:()=>v,getLatestProtocolIdentifier:()=>R,getMainChainInfo:()=>A,getWarpActionByIndex:()=>_,hex:()=>_t,list:()=>Et,nothing:()=>jt,option:()=>St,optional:()=>Pt,replacePlaceholders:()=>j,shiftBigintBy:()=>M,string:()=>Ut,toPreviewText:()=>rt,toTypedChainInfo:()=>et,toTypedRegistryInfo:()=>H,token:()=>Dt,u16:()=>Ft,u32:()=>kt,u64:()=>$t,u8:()=>Nt,variadic:()=>Vt});module.exports=vt(zt);var U=require("@multiversx/sdk-core"),lt=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:s=>s==="devnet"?"https://devnet.usewarp.to":s==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],MainChain:{ApiUrl:s=>s==="devnet"?"https://devnet-api.multiversx.com":s==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:s=>s==="devnet"?"https://devnet-explorer.multiversx.com":s==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com"},Registry:{Contract:s=>s==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":s==="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=s=>s==="devnet"?"D":s==="testnet"?"T":"1",A=s=>({chainId:v(s.env),apiUrl:s.chainApiUrl||W.MainChain.ApiUrl(s.env),blockTime:6e3,explorerUrl:s.chainExplorerUrl||W.MainChain.ExplorerUrl(s.env)}),R=s=>{if(s==="warp")return`warp:${V.Warp}`;if(s==="brand")return`brand:${V.Brand}`;if(s==="abi")return`abi:${V.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${s}`)},_=(s,t)=>s?.actions[t-1],H=s=>({hash:s.hash.toString("hex"),alias:s.alias?.toString()||null,trust:s.trust.toString(),creator:s.creator.toString(),createdAt:s.created_at.toNumber(),brand:s.brand?.toString("hex")||null,upgrade:s.upgrade?.toString("hex")||null}),et=s=>({chainId:s.chain_id.toString(),apiUrl:s.api_url.toString(),explorerUrl:s.explorer_url.toString(),blockTime:s.block_time.toNumber()}),M=(s,t)=>{let e=s.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=(s,t=100)=>{if(!s)return"";let e=s.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},j=(s,t)=>s.replace(/\{\{([^}]+)\}\}/g,(e,r)=>t[r]||"");var $=require("@multiversx/sdk-core");var g={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};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 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:s=>`warp:${s}`,WarpAbi:s=>`warp-abi:${s}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`,ChainInfo:s=>`chain:${s}`},S=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 P=class{constructor(t){this.config=t,this.cache=new S(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),[u]=o.parseQueryResponse(p),d=u?H(u):null,f=d?.brand?await this.fetchBrand(d.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:d,brand:f},e.ttl),{registryInfo:d,brand:f}}async getInfoByHash(t,e){let r=x.RegistryInfo(t);if(e){let f=this.cache.get(r);if(f)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),f}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),u=p?H(p):null,d=u?.brand?await this.fetchBrand(u.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:u,brand:d},e.ttl),{registryInfo:u,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(H)}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(f=>f.toString("hex")),u={ttl:365*24*60*60};return(await Promise.all(p.map(f=>this.fetchBrand(f,u)))).filter(f=>f!==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),[u]=o.parseQueryResponse(p),d=u?et(u):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=A(this.config),c=h.getChainEntrypoint(i,this.config.env).createNetworkProvider();try{let p=await c.getTransaction(t),u=JSON.parse(p.data.toString());return u.meta={hash:p.hash,creator:p.sender.bech32(),createdAt:new Date(p.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,u,e.ttl),u}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=A(this.config),e=h.getChainEntrypoint(t,this.config.env),r=m.AbiRegistry.create(nt);return e.createSmartContractController(r)}};var Bt="https://",pt="query",ut="env",h=class{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(`${pt}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let c=o.split(`${pt}:`)[1],p=new URL(e.currentUrl).searchParams.get(c);p&&n(i,p)}else if(typeof o=="string"&&o.startsWith(`${ut}:`)){let c=o.split(`${ut}:`)[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(g.IdentifierParamSeparator)?e:`${g.IdentifierType.Alias}${g.IdentifierParamSeparator}${e}`,[n,i]=r.split(g.IdentifierParamSeparator);return{type:n,id:i}}static getNextInfo(t,e,r,n){let i=t.actions?.[e]?.next||t.next||null;if(!i)return null;if(i.startsWith(Bt))return{identifier:null,url:i};let[o,c]=i.split("?"),p=c?j(c,{...t.vars,...r}):null,u=new URLSearchParams(p||"");new URL(n.currentUrl||W.DefaultClientUrl(n.env)).searchParams.forEach((T,I)=>u.set(I,T));let f=u.toString()?`${o}?${u.toString()}`:o,w=new URL(n.clientUrl||W.DefaultClientUrl(n.env));return w.searchParams.set("warp",f),{identifier:f,url:w.toString().replace(/\/\?/,"?")}}static async getChainInfoForAction(t,e){if(!t.chain)return A(e);let r=await new P(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 U.TransactionsFactoryConfig({chainID:v(this.config.env)}),r=new U.TransferTransactionsFactory({config:e}),n=U.Address.newFromBech32(this.config.userAddress),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer(n,{receiver:U.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=A(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 lt.default,o=i.compile(n);if(!o(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(o.errors)}`)}};var l=require("@multiversx/sdk-core/out"),St=(s,t)=>s?l.OptionValue.newProvided(s):t?l.OptionValue.newMissingTyped(t):l.OptionValue.newMissing(),Pt=(s,t)=>s?new l.OptionalValue(s.getType(),s):t?new l.OptionalValue(t):l.OptionalValue.newMissing(),Et=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let t=s[0].getType();return new l.List(t,s)},Vt=s=>l.VariadicValue.fromItems(...s),Rt=s=>{let t=s.map(e=>e.getType());return new l.CompositeValue(new l.CompositeType(...t),s)},Ut=s=>l.StringValue.fromUTF8(s),Nt=s=>new l.U8Value(s),Ft=s=>new l.U16Value(s),kt=s=>new l.U32Value(s),$t=s=>new l.U64Value(s),Ot=s=>new l.BigUIntValue(BigInt(s)),Lt=s=>new l.BooleanValue(s),qt=s=>new l.AddressValue(l.Address.newFromBech32(s)),Dt=s=>new l.TokenIdentifierValue(s),_t=s=>l.BytesValue.fromHex(s),Ht=s=>new l.Struct(new l.StructType("EsdtTokenPayment",[new l.FieldDefinition("token_identifier","",new l.TokenIdentifierType),new l.FieldDefinition("token_nonce","",new l.U64Type),new l.FieldDefinition("amount","",new l.BigUIntType)]),[new l.Field(new l.TokenIdentifierValue(s.token.identifier),"token_identifier"),new l.Field(new l.U64Value(BigInt(s.token.nonce)),"token_nonce"),new l.Field(new l.BigUIntValue(BigInt(s.amount)),"amount")]),Mt=s=>new l.CodeMetadataValue(l.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),jt=()=>new l.NothingValue;var O=require("@multiversx/sdk-core");var K=class{constructor(t){this.cache=new S;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=A(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 a=require("@multiversx/sdk-core/out");var dt=new RegExp(`${g.ArgParamsSeparator}(.*)`),N=class{nativeToString(t,e){return t==="esdt"&&e instanceof a.TokenTransfer?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(a.OptionValue.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(a.OptionalValue.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(a.List.ClassName)){let e=t.getItems(),n=e.map(o=>this.typedToString(o).split(g.ArgParamsSeparator)[0])[0],i=e.map(o=>this.typedToString(o).split(g.ArgParamsSeparator)[1]);return`list:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(a.VariadicValue.ClassName)){let e=t.getItems(),n=e.map(o=>this.typedToString(o).split(g.ArgParamsSeparator)[0])[0],i=e.map(o=>this.typedToString(o).split(g.ArgParamsSeparator)[1]);return`variadic:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(a.CompositeValue.ClassName)){let e=t.getItems(),r=e.map(c=>this.typedToString(c).split(g.ArgParamsSeparator)[0]),n=e.map(c=>this.typedToString(c).split(g.ArgParamsSeparator)[1]),i=r.join(g.ArgCompositeSeparator),o=n.join(g.ArgCompositeSeparator);return`composite(${i}):${o}`}if(t.hasClassOrSuperclass(a.BigUIntValue.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(a.U8Value.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(a.U16Value.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(a.U32Value.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(a.U64Value.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(a.StringValue.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(a.BooleanValue.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(a.AddressValue.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(a.TokenIdentifierValue.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(a.BytesValue.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(a.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 a.CompositeType(...e.split(g.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new a.StringType;if(t==="uint8")return new a.U8Type;if(t==="uint16")return new a.U16Type;if(t==="uint32")return new a.U32Type;if(t==="uint64")return new a.U64Type;if(t==="biguint")return new a.BigUIntType;if(t==="bool")return new a.BooleanType;if(t==="address")return new a.AddressType;if(t==="token")return new a.TokenIdentifierType;if(t==="hex")return new a.BytesType;if(t==="codemeta")return new a.CodeMetadataType;if(t==="esdt"||t==="nft")return new a.StructType("EsdtTokenPayment",[new a.FieldDefinition("token_identifier","",new a.TokenIdentifierType),new a.FieldDefinition("token_nonce","",new a.U64Type),new a.FieldDefinition("amount","",new a.BigUIntType)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(g.ArgParamsSeparator),r=e[0],n=e.slice(1).join(g.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[i,o]=n.split(g.ArgParamsSeparator);return[`option:${i}`,o||null]}else if(r==="optional"){let[i,o]=n.split(g.ArgParamsSeparator);return[`optional:${i}`,o||null]}else if(r==="list"){let i=n.split(g.ArgParamsSeparator),o=i.slice(0,-1).join(g.ArgParamsSeparator),c=i[i.length-1],u=(c?c.split(","):[]).map(d=>this.stringToNative(`${o}:${d}`)[1]);return[`list:${o}`,u]}else if(r==="variadic"){let i=n.split(g.ArgParamsSeparator),o=i.slice(0,-1).join(g.ArgParamsSeparator),c=i[i.length-1],u=(c?c.split(","):[]).map(d=>this.stringToNative(`${o}:${d}`)[1]);return[`variadic:${o}`,u]}else if(r.startsWith("composite")){let i=r.match(/\(([^)]+)\)/)?.[1]?.split(g.ArgCompositeSeparator),c=n.split(g.ArgCompositeSeparator).map((p,u)=>this.stringToNative(`${i[u]}:${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(g.ArgCompositeSeparator);return[r,new a.TokenTransfer({token:new a.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 a.NothingValue;if(e==="option"){let n=this.stringToTyped(r);return n instanceof a.NothingValue?a.OptionValue.newMissingTyped(n.getType()):a.OptionValue.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof a.NothingValue?a.OptionalValue.newMissing():new a.OptionalValue(n.getType(),n)}if(e==="list"){let[n,i]=r.split(dt,2),c=i.split(",").map(p=>this.stringToTyped(`${n}:${p}`));return new a.List(this.nativeToType(n),c)}if(e==="variadic"){let[n,i]=r.split(dt,2),c=i.split(",").map(p=>this.stringToTyped(`${n}:${p}`));return new a.VariadicValue(new a.VariadicType(this.nativeToType(n)),c)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],i=r.split(g.ArgCompositeSeparator),o=n.split(g.ArgCompositeSeparator),c=i.map((u,d)=>this.stringToTyped(`${o[d]}:${u}`)),p=c.map(u=>u.getType());return new a.CompositeValue(new a.CompositeType(...p),c)}if(e==="string")return r?a.StringValue.fromUTF8(r):new a.NothingValue;if(e==="uint8")return r?new a.U8Value(Number(r)):new a.NothingValue;if(e==="uint16")return r?new a.U16Value(Number(r)):new a.NothingValue;if(e==="uint32")return r?new a.U32Value(Number(r)):new a.NothingValue;if(e==="uint64")return r?new a.U64Value(BigInt(r)):new a.NothingValue;if(e==="biguint")return r?new a.BigUIntValue(BigInt(r)):new a.NothingValue;if(e==="bool")return r?new a.BooleanValue(typeof r=="boolean"?r:r==="true"):new a.NothingValue;if(e==="address")return r?new a.AddressValue(a.Address.newFromBech32(r)):new a.NothingValue;if(e==="token")return r?new a.TokenIdentifierValue(r):new a.NothingValue;if(e==="hex")return r?a.BytesValue.fromHex(r):new a.NothingValue;if(e==="codemeta")return new a.CodeMetadataValue(a.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(g.ArgCompositeSeparator);return new a.Struct(this.nativeToType("esdt"),[new a.Field(new a.TokenIdentifierValue(n[0]),"token_identifier"),new a.Field(new a.U64Value(BigInt(n[1])),"token_nonce"),new a.Field(new a.BigUIntValue(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof a.OptionType)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof a.OptionalType)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof a.ListType)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof a.VariadicType)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof a.StringType)return"string";if(t instanceof a.U8Type)return"uint8";if(t instanceof a.U16Type)return"uint16";if(t instanceof a.U32Type)return"uint32";if(t instanceof a.U64Type)return"uint64";if(t instanceof a.BigUIntType)return"biguint";if(t instanceof a.BooleanType)return"bool";if(t instanceof a.AddressType)return"address";if(t instanceof a.TokenIdentifierType)return"token";if(t instanceof a.BytesType)return"hex";if(t instanceof a.CodeMetadataType)return"codemeta";if(t instanceof a.StructType&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var ft=async(s,t,e,r)=>{let n=[],i={};if(!t.results||!e.abi||e.type!=="contract")return{values:n,results:i};let o=await s.getAbiForAction(e),c=new L.TransactionEventsParser({abi:o}),u=new L.SmartContractTransactionsOutcomeParser({abi:o}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[d,f]of Object.entries(t.results)){let[w,T,I]=f.split(".");if(w==="event"){if(!T||isNaN(Number(I)))continue;let B=Number(I),b=(0,L.findEventsByFirstTopic)(r,T),D=c.parseEvents({events:b})[0],E=Object.values(D)[B]||null;n.push(E),i[d]=E&&E.valueOf()}else if(w==="out"){if(!T)continue;let B=Number(T),b=u.values[B-1]||null;n.push(b),i[d]=b&&b.valueOf()}}return{values:n,results:i}},gt=async(s,t)=>{let e=new N,r=t.map(c=>e.typedToString(c)),n=t.map(c=>e.typedToNative(c)[1]),i={};if(!s.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 u=n[p[0]];for(let d=1;d<p.length;d++){if(u==null)return;u=u[p[d]]}return u};return Object.entries(s.results).forEach(([c,p])=>{if(p.startsWith("out.")){let u=o(p);i[c]=u||null}}),{values:r,results:i}},mt=async(s,t)=>{let e=[],r={};for(let[n,i]of Object.entries(s.results||{})){let[o,...c]=i.split(".");if(o!=="out"||!c.length)continue;let p=c.reduce((u,d)=>u?.[d],t);e.push(p),r[n]=p}return{values:e,results:r}};var Qt=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],ht=s=>Qt.find(t=>t.id===s)||null;var G=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 N,this.contractLoader=new G(t),this.registry=new P(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:u,data:d}=await this.getTxComponentsFromInputs(t,e,r),f=c.map(w=>this.serializer.stringToTyped(w));if(t.type==="transfer")return new y.TransferTransactionsFactory({config:i}).createTransactionForTransfer(r,{receiver:o,nativeAmount:p,tokenTransfers:u,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:f,tokenTransfers:u,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=_(t,e),{values:i,results:o}=await ft(this,t,n,r),c=h.getNextInfo(t,e,o,this.config),p=this.getPreparedMessages(t,o);return{success:r.status.isSuccessful(),warp:t,action:e,user:this.config.userAddress||null,txHash:r.hash,next:c,values:i,results:o,messages:p}}async executeQuery(t,e,r){let n=_(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(C=>this.serializer.stringToTyped(C)),u=h.getChainEntrypoint(i,this.config.env),d=y.Address.newFromBech32(n.address),f=u.createSmartContractController(o),w=f.createQuery({contract:d,function:n.func,arguments:p}),T=await f.runQuery(w),I=T.returnCode==="ok",B=new y.ArgSerializer,b=o.getEndpoint(T.function),D=T.returnDataParts.map(C=>Buffer.from(C)),E=B.buffersToValues(D,b.output),{values:Z,results:k}=await gt(t,E),Y=h.getNextInfo(t,e,k,this.config);return{success:I,warp:t,action:e,user:this.config.userAddress||null,txHash:null,next:Y,values:Z,results:k,messages:this.getPreparedMessages(t,k)}}async executeCollect(t,e,r,n){let i=_(t,e);if(!i)throw new Error("WarpActionExecutor: Action not found");let o=await this.getResolvedInputs(i,r),c=this.getModifiedInputs(o),p=f=>{if(!f.value)return null;let w=this.serializer.stringToNative(f.value)[1];if(f.input.type==="biguint")return w.toString();if(f.input.type==="esdt"){let T=w;return{token:T.token.identifier,nonce:T.token.nonce.toString(),amount:T.amount.toString()}}else return w},u=Object.fromEntries(c.map(f=>[f.input.as||f.input.name,p(f)])),d=new Headers;d.set("Content-Type","application/json"),d.set("Accept","application/json"),Object.entries(i.destination.headers).forEach(([f,w])=>{d.set(f,w)});try{let f=await fetch(i.destination.url,{method:i.destination.method,headers:d,body:JSON.stringify({inputs:u,meta:n})}),w=await f.json(),{values:T,results:I}=await mt(t,w),B=h.getNextInfo(t,e,I,this.config);return{success:f.ok,warp:t,action:e,user:this.config.userAddress||null,txHash:null,next:B,values:T,results:I,messages:this.getPreparedMessages(t,I)}}catch(f){return console.error(f),{success:!1,warp:t,action:e,user:this.config.userAddress||null,txHash:null,next:null,values:[],results:{},messages:{}}}}async getTxComponentsFromInputs(t,e,r){let n=await this.getResolvedInputs(t,e),i=this.getModifiedInputs(n),o=i.find(C=>C.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 u=y.Address.newFromBech32(p),d=this.getPreparedArgs(t,i),f=i.find(C=>C.input.position==="value")?.value||null,w="value"in t?t.value:null,T=BigInt(f?.split(":")[1]||w||0),I=i.filter(C=>C.input.position==="transfer"&&C.value).map(C=>C.value),b=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...I?.map(C=>this.serializer.stringToNative(C)[1])||[]],D=i.find(C=>C.input.position==="data")?.value,E="data"in t?t.data||"":null,Z=D||E||null,k=Z?this.serializer.stringToTyped(Z).valueOf():null,Y=k?Buffer.from(k):null;return{destination:u,args:d,value:T,transfers:b,data:Y}}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=M(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=M(i,+n);return{...e,value:`${e.input.type}:${o}`}}}else return e})}async preprocessInput(t){try{let[e,r]=t.split(g.ArgParamsSeparator,2);if(e==="esdt"){let[n,i,o,c]=r.split(g.ArgCompositeSeparator);if(c)return t;let p=new y.Token({identifier:n,nonce:BigInt(i)});if(!new y.TokenComputer().isFungible(p))return t;let f=ht(n)?.decimals;if(!f){let T=this.config.chainApiUrl||W.MainChain.ApiUrl(this.config.env);f=(await(await fetch(`${T}/tokens/${n}`)).json()).decimals}if(!f)throw new Error(`WarpActionExecutor: Decimals not found for token ${n}`);let w=new y.TokenTransfer({token:p,amount:M(o,f)});return this.serializer.nativeToString(e,w)+g.ArgCompositeSeparator+f}return t}catch{return t}}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=A(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,j(i,e)]);return Object.fromEntries(r)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(g.IdentifierType.Hash)){let e=new K(this.config),r=t.abi.split(g.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 F=require("@multiversx/sdk-core");var yt=tt(require("ajv"));var q=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 yt.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 J=class{constructor(t){this.pendingWarp={protocol:R("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t,this.cache=new S(t.cacheType)}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new F.TransactionsFactoryConfig({chainID:v(this.config.env)}),r=new F.TransferTransactionsFactory({config:e}),n=F.Address.newFromBech32(this.config.userAddress),i=JSON.stringify(t),o=r.createTransactionForTransfer(n,{receiver:F.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 q(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=A(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 q(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 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}}};var wt=tt(require("qr-code-styling"));var ot=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(g.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(u=>u[0]).filter(u=>this.isValid(u)).map(u=>this.detect(u)),o=(await Promise.all(n)).filter(u=>u.match),c=o.length>0,p=o.map(u=>({url:u.url,warp:u.warp}));return{match:c,results:p}}async detect(t){let e=t.startsWith(g.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 J(this.config),o=new P(this.config),c=null,p=null,u=null;if(r==="hash"){c=await i.createFromTransactionHash(n);try{let{registryInfo:d,brand:f}=await o.getInfoByHash(n);p=d,u=f}catch{}}else if(r==="alias"){let{registryInfo:d,brand:f}=await o.getInfoByAlias(n);p=d,u=f,d&&(c=await i.createFromTransactionHash(d.hash))}return c?{match:!0,url:t,warp:c,registryInfo:p,brand:u}:{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===g.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+g.IdentifierParamSeparator+e);return W.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${g.IdentifierParamName}=${n}`}buildFromPrefixedIdentifier(t){let e=h.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.id):""}generateQrCode(t,e,r=512,n="white",i="black",o="#23F7DD"){let c=this.build(t,e);return new wt.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(g.IdentifierParamName),i=r&&!n?e.pathname.split("/")[1]:n;if(!i)return null;let o=decodeURIComponent(i);return h.getInfoFromPrefixedIdentifier(o)}};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,replacePlaceholders,shiftBigintBy,string,toPreviewText,toTypedChainInfo,toTypedRegistryInfo,token,u16,u32,u64,u8,variadic});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{Address as mt,TransactionsFactoryConfig as oe,TransferTransactionsFactory as ce}from"@multiversx/sdk-core";import pe 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 v=a=>a==="devnet"?"D":a==="testnet"?"T":"1",T=a=>({chainId:v(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}`)},L=(a,t)=>a?.actions[t-1],q=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}),pt=a=>({chainId:a.chain_id.toString(),apiUrl:a.api_url.toString(),explorerUrl:a.explorer_url.toString(),blockTime:a.block_time.toNumber()}),D=(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)},ut=(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 ne,MainnetEntrypoint as ie,TestnetEntrypoint as se}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{AbiRegistry as lt,Address as I,AddressValue as dt,BytesValue as w,SmartContractTransactionsFactory as ee,TransactionsFactoryConfig as re}from"@multiversx/sdk-core/out";var Q={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 F=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 x={Warp:a=>`warp:${a}`,WarpAbi:a=>`warp-abi:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`,ChainInfo:a=>`chain:${a}`},S=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new F:t==="memory"?new k:typeof window<"u"&&window.localStorage?new F:new k}set(t,e,r){this.strategy.set(t,e,r)}get(t){return this.strategy.get(t)}clear(){this.strategy.clear()}};var P=class{constructor(t){this.config=t,this.cache=new S(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?[w.fromHex(t),w.fromUTF8(e)]:[w.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:[w.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:[w.fromUTF8(t),w.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:[w.fromHex(t),w.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:[w.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:[w.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:[w.fromHex(t),w.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(),s=this.getController(),o=s.createQuery({contract:i,function:"getInfoByAlias",arguments:[w.fromUTF8(t)]}),c=await s.runQuery(o),[p]=s.parseQueryResponse(c),u=p?q(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=x.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:[w.fromHex(t)]}),o=await i.runQuery(s),[c]=i.parseQueryResponse(o),p=c?q(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 dt(new I(e))]}),s=await n.runQuery(i),[o]=n.parseQueryResponse(s);return o.map(q)}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 dt(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=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(),s=this.getController(),o=s.createQuery({contract:i,function:"getChain",arguments:[w.fromUTF8(t)]}),c=await s.runQuery(o),[p]=s.parseQueryResponse(c),u=p?pt(p):null;return u&&e?.ttl&&this.cache.set(r,u,e.ttl),u}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=T(this.config),o=f.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 re({chainID:v(this.config.env)}),e=lt.create(Q);return new ee({config:t,abi:e})}getController(){let t=T(this.config),e=f.getChainEntrypoint(t,this.config.env),r=lt.create(Q);return e.createSmartContractController(r)}};var ae="https://",ft="query",gt="env",f=class{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(`${ft}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${ft}:`)[1],c=new URL(e.currentUrl).searchParams.get(o);c&&n(i,c)}else if(typeof s=="string"&&s.startsWith(`${gt}:`)){let o=s.split(`${gt}:`)[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 getNextInfo(t,e,r){let n=t.actions?.[e]?.next||t.next||null;if(!n)return null;if(n.startsWith(ae))return{identifier:null,url:n};let[i,s]=n.split("?"),o=new URLSearchParams(s||"");new URL(r.currentUrl||h.DefaultClientUrl(r.env)).searchParams.forEach((l,g)=>o.set(g,l));let p=o.toString()?`${i}?${o.toString()}`:i,u=new URL(r.clientUrl||h.DefaultClientUrl(r.env));return u.searchParams.set("warp",p),{identifier:p,url:u.toString().replace(/\/\?/,"?")}}static async getChainInfoForAction(t,e){if(!t.chain)return T(e);let r=await new P(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 ne(t.apiUrl,n,r):e==="testnet"?new se(t.apiUrl,n,r):new ie(t.apiUrl,n,r)}};var ht=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 oe({chainID:v(this.config.env)}),r=new ce({config:e}),n=mt.newFromBech32(this.config.userAddress),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer(n,{receiver:mt.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=T(this.config),n=f.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 pe,s=i.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};import{Address as ue,AddressValue as le,BigUIntType as de,BigUIntValue as yt,BooleanValue as fe,BytesValue as ge,CodeMetadata as me,CodeMetadataValue as he,CompositeType as ye,CompositeValue as we,Field as z,FieldDefinition as K,List as Te,NothingValue as We,OptionalValue as G,OptionValue as J,StringValue as Ce,Struct as Ae,StructType as Ie,TokenIdentifierType as be,TokenIdentifierValue as wt,U16Value as ve,U32Value as xe,U64Type as Be,U64Value as Tt,U8Value as Se,VariadicValue as Pe}from"@multiversx/sdk-core/out";var Mr=(a,t)=>a?J.newProvided(a):t?J.newMissingTyped(t):J.newMissing(),jr=(a,t)=>a?new G(a.getType(),a):t?new G(t):G.newMissing(),Qr=a=>{if(a.length===0)throw new Error("Cannot create a list from an empty array");let t=a[0].getType();return new Te(t,a)},zr=a=>Pe.fromItems(...a),Kr=a=>{let t=a.map(e=>e.getType());return new we(new ye(...t),a)},Gr=a=>Ce.fromUTF8(a),Jr=a=>new Se(a),Zr=a=>new ve(a),Xr=a=>new xe(a),Yr=a=>new Tt(a),tn=a=>new yt(BigInt(a)),en=a=>new fe(a),rn=a=>new le(ue.newFromBech32(a)),nn=a=>new wt(a),sn=a=>ge.fromHex(a),an=a=>new Ae(new Ie("EsdtTokenPayment",[new K("token_identifier","",new be),new K("token_nonce","",new Be),new K("amount","",new de)]),[new z(new wt(a.token.identifier),"token_identifier"),new z(new Tt(BigInt(a.token.nonce)),"token_nonce"),new z(new yt(BigInt(a.amount)),"amount")]),on=a=>new he(me.newFromBytes(Uint8Array.from(Buffer.from(a,"hex")))),cn=()=>new We;import{Address as Ee,TransactionsFactoryConfig as Ve,TransferTransactionsFactory as Re}from"@multiversx/sdk-core";var _=class{constructor(t){this.cache=new S;this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new Ve({chainID:v(this.config.env)}),r=new Re({config:e}),n={protocol:V("abi"),content:t},i=Ee.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=x.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=T(this.config),s=f.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 ot,Address as ct,ArgSerializer as Me,SmartContractTransactionsFactory as je,Token as Kt,TokenComputer as Qe,TokenTransfer as Gt,TransactionsFactoryConfig as ze,TransferTransactionsFactory as Ke}from"@multiversx/sdk-core";import{SmartContractTransactionsOutcomeParser as qe,TransactionEventsParser as De,findEventsByFirstTopic as _e}from"@multiversx/sdk-core/out";import{Address as Ue,AddressType as Wt,AddressValue as Ct,BigUIntType as Z,BigUIntValue as X,BooleanType as At,BooleanValue as It,BytesType as bt,BytesValue as vt,CodeMetadata as Ne,CodeMetadataType as xt,CodeMetadataValue as Bt,CompositeType as St,CompositeValue as Pt,Field as Y,FieldDefinition as tt,List as Et,ListType as Fe,NothingValue as W,OptionalType as ke,OptionalValue as et,OptionType as $e,OptionValue as rt,StringType as Vt,StringValue as Rt,Struct as Oe,StructType as Ut,Token as Le,TokenIdentifierType as nt,TokenIdentifierValue as it,TokenTransfer as Nt,U16Type as Ft,U16Value as kt,U32Type as $t,U32Value as Ot,U64Type as st,U64Value as at,U8Type as Lt,U8Value as qt,VariadicType as Dt,VariadicValue as _t}from"@multiversx/sdk-core/out";var Ht=new RegExp(`${d.ArgParamsSeparator}(.*)`),R=class{nativeToString(t,e){return t==="esdt"&&e instanceof Nt?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(rt.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(et.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(_t.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(Pt.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(X.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(qt.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(kt.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Ot.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(at.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Rt.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(It.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(Ct.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(it.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(vt.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(Bt.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 St(...e.split(d.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new Vt;if(t==="uint8")return new Lt;if(t==="uint16")return new Ft;if(t==="uint32")return new $t;if(t==="uint64")return new st;if(t==="biguint")return new Z;if(t==="bool")return new At;if(t==="address")return new Wt;if(t==="token")return new nt;if(t==="hex")return new bt;if(t==="codemeta")return new xt;if(t==="esdt"||t==="nft")return new Ut("EsdtTokenPayment",[new tt("token_identifier","",new nt),new tt("token_nonce","",new st),new tt("amount","",new Z)]);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 Nt({token:new Le({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?rt.newMissingTyped(n.getType()):rt.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof W?et.newMissing():new et(n.getType(),n)}if(e==="list"){let[n,i]=r.split(Ht,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(Ht,2),o=i.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new _t(new Dt(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 Pt(new St(...c),o)}if(e==="string")return r?Rt.fromUTF8(r):new W;if(e==="uint8")return r?new qt(Number(r)):new W;if(e==="uint16")return r?new kt(Number(r)):new W;if(e==="uint32")return r?new Ot(Number(r)):new W;if(e==="uint64")return r?new at(BigInt(r)):new W;if(e==="biguint")return r?new X(BigInt(r)):new W;if(e==="bool")return r?new It(typeof r=="boolean"?r:r==="true"):new W;if(e==="address")return r?new Ct(Ue.newFromBech32(r)):new W;if(e==="token")return r?new it(r):new W;if(e==="hex")return r?vt.fromHex(r):new W;if(e==="codemeta")return new Bt(Ne.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(d.ArgCompositeSeparator);return new Oe(this.nativeToType("esdt"),[new Y(new it(n[0]),"token_identifier"),new Y(new at(BigInt(n[1])),"token_nonce"),new Y(new X(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 ke)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Fe)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Dt)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Vt)return"string";if(t instanceof Lt)return"uint8";if(t instanceof Ft)return"uint16";if(t instanceof $t)return"uint32";if(t instanceof st)return"uint64";if(t instanceof Z)return"biguint";if(t instanceof At)return"bool";if(t instanceof Wt)return"address";if(t instanceof nt)return"token";if(t instanceof bt)return"hex";if(t instanceof xt)return"codemeta";if(t instanceof Ut&&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 De({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[g,m,C]=l.split(".");if(g==="event"){if(!m||isNaN(Number(C)))continue;let b=Number(C),A=_e(r,m),U=o.parseEvents({events:A})[0],B=Object.values(U)[b]||null;n.push(B),i[u]=B&&B.valueOf()}else if(g==="out"){if(!m)continue;let b=Number(m),A=p.values[b-1]||null;n.push(A),i[u]=A&&A.valueOf()}}return{values:n,results:i}},jt=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}},Qt=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 He=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],zt=a=>He.find(t=>t.id===a)||null;var H=class{constructor(t){this.config=t}async getContract(t,e){try{let i=await f.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 f.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 Jt=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 H(t),this.registry=new P(t)}async createTransactionForExecute(t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let r=ct.newFromBech32(this.config.userAddress),n=await f.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(g=>this.serializer.stringToTyped(g));if(t.type==="transfer")return new Ke({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=L(t,e),i=f.getNextInfo(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,next:i,values:s,results:o,messages:c}}async executeQuery(t,e,r){let n=L(t,e);if(!n)throw new Error("WarpActionExecutor: Action not found");if(!n.func)throw new Error("WarpActionExecutor: Function not found");let i=await f.getChainInfoForAction(n,this.config),s=await this.getAbiForAction(n),{args:o}=await this.getTxComponentsFromInputs(n,r),c=o.map(y=>this.serializer.stringToTyped(y)),p=f.getChainEntrypoint(i,this.config.env),u=ct.newFromBech32(n.address),l=p.createSmartContractController(s),g=l.createQuery({contract:u,function:n.func,arguments:c}),m=await l.runQuery(g),C=m.returnCode==="ok",b=new Me,A=s.getEndpoint(m.function),U=m.returnDataParts.map(y=>Buffer.from(y)),B=b.buffersToValues(U,A.output),{values:O,results:N}=await jt(t,B),j=f.getNextInfo(t,e,this.config);return{success:C,warp:t,action:e,user:this.config.userAddress||null,txHash:null,next:j,values:O,results:N,messages:this.getPreparedMessages(t,N)}}async executeCollect(t,e,r,n){let i=L(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 g=this.serializer.stringToNative(l.value)[1];if(l.input.type==="biguint")return g.toString();if(l.input.type==="esdt"){let m=g;return{token:m.token.identifier,nonce:m.token.nonce.toString(),amount:m.amount.toString()}}else return g},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,g])=>{u.set(l,g)});try{let l=await fetch(i.destination.url,{method:i.destination.method,headers:u,body:JSON.stringify({inputs:p,meta:n})}),g=await l.json(),{values:m,results:C}=await Qt(t,g),b=f.getNextInfo(t,e,this.config);return{success:l.ok,warp:t,action:e,user:this.config.userAddress||null,txHash:null,next:b,values:m,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,next:null,values:[],results:{},messages:{}}}}async getTxComponentsFromInputs(t,e,r){let n=await this.getResolvedInputs(t,e),i=this.getModifiedInputs(n),s=i.find(y=>y.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=ct.newFromBech32(c),u=this.getPreparedArgs(t,i),l=i.find(y=>y.input.position==="value")?.value||null,g="value"in t?t.value:null,m=BigInt(l?.split(":")[1]||g||0),C=i.filter(y=>y.input.position==="transfer"&&y.value).map(y=>y.value),A=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...C?.map(y=>this.serializer.stringToNative(y)[1])||[]],U=i.find(y=>y.input.position==="data")?.value,B="data"in t?t.data||"":null,O=U||B||null,N=O?this.serializer.stringToTyped(O).valueOf():null,j=N?Buffer.from(N):null;return{destination:p,args:u,value:m,transfers:A,data:j}}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=D(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=D(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 Kt({identifier:n,nonce:BigInt(i)});if(!new Qe().isFungible(c))return t;let l=zt(n)?.decimals;if(!l){let m=this.config.chainApiUrl||h.MainChain.ApiUrl(this.config.env);l=(await(await fetch(`${m}/tokens/${n}`)).json()).decimals}if(!l)throw new Error(`WarpActionExecutor: Decimals not found for token ${n}`);let g=new Gt({token:c,amount:D(s,l)});return this.serializer.nativeToString(e,g)+d.ArgCompositeSeparator+l}return t}catch{return t}}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=T(this.config),r=await this.contractLoader.getVerificationInfo(t.address,e);if(!r)throw new Error("WarpActionExecutor: Verification info not found");return ot.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 _(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 ot.create(n.content)}else{let r=await(await fetch(t.abi)).json();return ot.create(r)}}toTypedTransfer(t){return new Gt({token:new Kt({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};import{Address as Zt,TransactionsFactoryConfig as Je,TransferTransactionsFactory as Ze}from"@multiversx/sdk-core";import Ge 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 Ge,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 M=class{constructor(t){this.pendingWarp={protocol:V("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t,this.cache=new S(t.cacheType)}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new Je({chainID:v(this.config.env)}),r=new Ze({config:e}),n=Zt.newFromBech32(this.config.userAddress),i=JSON.stringify(t),s=r.createTransactionForTransfer(n,{receiver:Zt.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),f.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 o=this.cache.get(r);if(o)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),o}let n=T(this.config),s=f.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 $(this.config).validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return ut(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}};var Xt=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}}};import Xe from"qr-code-styling";var Yt=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):f.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:n}=e,i=new M(this.config),s=new P(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}`}buildFromPrefixedIdentifier(t){let e=f.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.id):""}generateQrCode(t,e,r=512,n="white",i="black",s="#23F7DD"){let o=this.build(t,e);return new Xe({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 f.getInfoFromPrefixedIdentifier(s)}};export{ht as BrandBuilder,x as CacheKey,h as Config,_ as WarpAbiBuilder,Jt as WarpActionExecutor,R as WarpArgSerializer,M as WarpBuilder,S as WarpCache,d as WarpConstants,H as WarpContractLoader,Xt as WarpIndex,Yt as WarpLink,E as WarpProtocolVersions,P as WarpRegistry,f as WarpUtils,$ as WarpValidator,rn as address,tn as biguint,en as boolean,on as codemeta,Kr as composite,an as esdt,v as getChainId,V as getLatestProtocolIdentifier,T as getMainChainInfo,L as getWarpActionByIndex,sn as hex,Qr as list,cn as nothing,Mr as option,jr as optional,D as shiftBigintBy,Gr as string,ut as toPreviewText,pt as toTypedChainInfo,q as toTypedRegistryInfo,nn as token,Zr as u16,Xr as u32,Yr as u64,Jr as u8,zr as variadic};
1
+ import{Address as ht,TransactionsFactoryConfig as ce,TransferTransactionsFactory as pe}from"@multiversx/sdk-core";import ue 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"],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",W=a=>({chainId:v(a.env),apiUrl:a.chainApiUrl||h.MainChain.ApiUrl(a.env),blockTime:6e3,explorerUrl:a.chainExplorerUrl||h.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}`)},L=(a,t)=>a?.actions[t-1],q=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()}),D=(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},_=(a,t)=>a.replace(/\{\{([^}]+)\}\}/g,(e,r)=>t[r]||"");import{DevnetEntrypoint as ie,MainnetEntrypoint as se,TestnetEntrypoint as ae}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{AbiRegistry as dt,Address as I,AddressValue as ft,BytesValue as w,SmartContractTransactionsFactory as re,TransactionsFactoryConfig as ne}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 F=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 x={Warp:a=>`warp:${a}`,WarpAbi:a=>`warp-abi:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`,ChainInfo:a=>`chain:${a}`},S=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new F:t==="memory"?new k:typeof window<"u"&&window.localStorage?new F:new k}set(t,e,r){this.strategy.set(t,e,r)}get(t){return this.strategy.get(t)}clear(){this.strategy.clear()}};var P=class{constructor(t){this.config=t,this.cache=new S(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?[w.fromHex(t),w.fromUTF8(e)]:[w.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:[w.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:[w.fromUTF8(t),w.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:[w.fromHex(t),w.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:[w.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:[w.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:[w.fromHex(t),w.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(),s=this.getController(),o=s.createQuery({contract:i,function:"getInfoByAlias",arguments:[w.fromUTF8(t)]}),c=await s.runQuery(o),[p]=s.parseQueryResponse(c),u=p?q(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=x.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:[w.fromHex(t)]}),o=await i.runQuery(s),[c]=i.parseQueryResponse(o),p=c?q(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(q)}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=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(),s=this.getController(),o=s.createQuery({contract:i,function:"getChain",arguments:[w.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=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=W(this.config),o=f.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 ne({chainID:v(this.config.env)}),e=dt.create(z);return new re({config:t,abi:e})}getController(){let t=W(this.config),e=f.getChainEntrypoint(t,this.config.env),r=dt.create(z);return e.createSmartContractController(r)}};var oe="https://",gt="query",mt="env",f=class{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(`${gt}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${gt}:`)[1],c=new URL(e.currentUrl).searchParams.get(o);c&&n(i,c)}else if(typeof s=="string"&&s.startsWith(`${mt}:`)){let o=s.split(`${mt}:`)[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 getNextInfo(t,e,r,n){let i=t.actions?.[e]?.next||t.next||null;if(!i)return null;if(i.startsWith(oe))return{identifier:null,url:i};let[s,o]=i.split("?"),c=o?_(o,{...t.vars,...r}):null,p=new URLSearchParams(c||"");new URL(n.currentUrl||h.DefaultClientUrl(n.env)).searchParams.forEach((m,T)=>p.set(T,m));let l=p.toString()?`${s}?${p.toString()}`:s,g=new URL(n.clientUrl||h.DefaultClientUrl(n.env));return g.searchParams.set("warp",l),{identifier:l,url:g.toString().replace(/\/\?/,"?")}}static async getChainInfoForAction(t,e){if(!t.chain)return W(e);let r=await new P(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 ie(t.apiUrl,n,r):e==="testnet"?new ae(t.apiUrl,n,r):new se(t.apiUrl,n,r)}};var yt=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 ce({chainID:v(this.config.env)}),r=new pe({config:e}),n=ht.newFromBech32(this.config.userAddress),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer(n,{receiver:ht.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=f.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 ue,s=i.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};import{Address as le,AddressValue as de,BigUIntType as fe,BigUIntValue as wt,BooleanValue as ge,BytesValue as me,CodeMetadata as he,CodeMetadataValue as ye,CompositeType as we,CompositeValue as Te,Field as K,FieldDefinition as G,List as We,NothingValue as Ce,OptionalValue as J,OptionValue as Z,StringValue as Ae,Struct as Ie,StructType as be,TokenIdentifierType as ve,TokenIdentifierValue as Tt,U16Value as xe,U32Value as Be,U64Type as Se,U64Value as Wt,U8Value as Pe,VariadicValue as Ee}from"@multiversx/sdk-core/out";var jr=(a,t)=>a?Z.newProvided(a):t?Z.newMissingTyped(t):Z.newMissing(),Qr=(a,t)=>a?new J(a.getType(),a):t?new J(t):J.newMissing(),zr=a=>{if(a.length===0)throw new Error("Cannot create a list from an empty array");let t=a[0].getType();return new We(t,a)},Kr=a=>Ee.fromItems(...a),Gr=a=>{let t=a.map(e=>e.getType());return new Te(new we(...t),a)},Jr=a=>Ae.fromUTF8(a),Zr=a=>new Pe(a),Xr=a=>new xe(a),Yr=a=>new Be(a),tn=a=>new Wt(a),en=a=>new wt(BigInt(a)),rn=a=>new ge(a),nn=a=>new de(le.newFromBech32(a)),sn=a=>new Tt(a),an=a=>me.fromHex(a),on=a=>new Ie(new be("EsdtTokenPayment",[new G("token_identifier","",new ve),new G("token_nonce","",new Se),new G("amount","",new fe)]),[new K(new Tt(a.token.identifier),"token_identifier"),new K(new Wt(BigInt(a.token.nonce)),"token_nonce"),new K(new wt(BigInt(a.amount)),"amount")]),cn=a=>new ye(he.newFromBytes(Uint8Array.from(Buffer.from(a,"hex")))),pn=()=>new Ce;import{Address as Ve,TransactionsFactoryConfig as Re,TransferTransactionsFactory as Ue}from"@multiversx/sdk-core";var H=class{constructor(t){this.cache=new S;this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new Re({chainID:v(this.config.env)}),r=new Ue({config:e}),n={protocol:R("abi"),content:t},i=Ve.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=x.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=f.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 je,SmartContractTransactionsFactory as Qe,Token as Gt,TokenComputer as ze,TokenTransfer as Jt,TransactionsFactoryConfig as Ke,TransferTransactionsFactory as Ge}from"@multiversx/sdk-core";import{SmartContractTransactionsOutcomeParser as De,TransactionEventsParser as _e,findEventsByFirstTopic as He}from"@multiversx/sdk-core/out";import{Address as Ne,AddressType as Ct,AddressValue as At,BigUIntType as X,BigUIntValue as Y,BooleanType as It,BooleanValue as bt,BytesType as vt,BytesValue as xt,CodeMetadata as Fe,CodeMetadataType as Bt,CodeMetadataValue as St,CompositeType as Pt,CompositeValue as Et,Field as tt,FieldDefinition as et,List as Vt,ListType as ke,NothingValue as C,OptionalType as $e,OptionalValue as rt,OptionType as Oe,OptionValue as nt,StringType as Rt,StringValue as Ut,Struct as Le,StructType as Nt,Token as qe,TokenIdentifierType as it,TokenIdentifierValue as st,TokenTransfer as Ft,U16Type as kt,U16Value as $t,U32Type as Ot,U32Value as Lt,U64Type as at,U64Value as ot,U8Type as qt,U8Value as Dt,VariadicType as _t,VariadicValue as Ht}from"@multiversx/sdk-core/out";var Mt=new RegExp(`${d.ArgParamsSeparator}(.*)`),U=class{nativeToString(t,e){return t==="esdt"&&e instanceof Ft?`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(Vt.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(Ht.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(Et.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(Dt.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass($t.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Lt.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(ot.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Ut.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(bt.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(At.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(st.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(xt.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(St.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 Rt;if(t==="uint8")return new qt;if(t==="uint16")return new kt;if(t==="uint32")return new Ot;if(t==="uint64")return new at;if(t==="biguint")return new X;if(t==="bool")return new It;if(t==="address")return new Ct;if(t==="token")return new it;if(t==="hex")return new vt;if(t==="codemeta")return new Bt;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 Ft({token:new qe({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 C;if(e==="option"){let n=this.stringToTyped(r);return n instanceof C?nt.newMissingTyped(n.getType()):nt.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof C?rt.newMissing():new rt(n.getType(),n)}if(e==="list"){let[n,i]=r.split(Mt,2),o=i.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Vt(this.nativeToType(n),o)}if(e==="variadic"){let[n,i]=r.split(Mt,2),o=i.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Ht(new _t(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 Et(new Pt(...c),o)}if(e==="string")return r?Ut.fromUTF8(r):new C;if(e==="uint8")return r?new Dt(Number(r)):new C;if(e==="uint16")return r?new $t(Number(r)):new C;if(e==="uint32")return r?new Lt(Number(r)):new C;if(e==="uint64")return r?new ot(BigInt(r)):new C;if(e==="biguint")return r?new Y(BigInt(r)):new C;if(e==="bool")return r?new bt(typeof r=="boolean"?r:r==="true"):new C;if(e==="address")return r?new At(Ne.newFromBech32(r)):new C;if(e==="token")return r?new st(r):new C;if(e==="hex")return r?xt.fromHex(r):new C;if(e==="codemeta")return new St(Fe.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(d.ArgCompositeSeparator);return new Le(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 Oe)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof $e)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof ke)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof _t)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Rt)return"string";if(t instanceof qt)return"uint8";if(t instanceof kt)return"uint16";if(t instanceof Ot)return"uint32";if(t instanceof at)return"uint64";if(t instanceof X)return"biguint";if(t instanceof It)return"bool";if(t instanceof Ct)return"address";if(t instanceof it)return"token";if(t instanceof vt)return"hex";if(t instanceof Bt)return"codemeta";if(t instanceof Nt&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var jt=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 _e({abi:s}),p=new De({abi:s}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[u,l]of Object.entries(t.results)){let[g,m,T]=l.split(".");if(g==="event"){if(!m||isNaN(Number(T)))continue;let b=Number(T),A=He(r,m),N=o.parseEvents({events:A})[0],B=Object.values(N)[b]||null;n.push(B),i[u]=B&&B.valueOf()}else if(g==="out"){if(!m)continue;let b=Number(m),A=p.values[b-1]||null;n.push(A),i[u]=A&&A.valueOf()}}return{values:n,results:i}},Qt=async(a,t)=>{let e=new U,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}},zt=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 Me=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],Kt=a=>Me.find(t=>t.id===a)||null;var M=class{constructor(t){this.config=t}async getContract(t,e){try{let i=await f.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 f.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 Zt=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 U,this.contractLoader=new M(t),this.registry=new P(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 f.getChainInfoForAction(t,this.config),i=new Ke({chainID:n.chainId}),{destination:s,args:o,value:c,transfers:p,data:u}=await this.getTxComponentsFromInputs(t,e,r),l=o.map(g=>this.serializer.stringToTyped(g));if(t.type==="transfer")return new Ge({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 Qe({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=L(t,e),{values:i,results:s}=await jt(this,t,n,r),o=f.getNextInfo(t,e,s,this.config),c=this.getPreparedMessages(t,s);return{success:r.status.isSuccessful(),warp:t,action:e,user:this.config.userAddress||null,txHash:r.hash,next:o,values:i,results:s,messages:c}}async executeQuery(t,e,r){let n=L(t,e);if(!n)throw new Error("WarpActionExecutor: Action not found");if(!n.func)throw new Error("WarpActionExecutor: Function not found");let i=await f.getChainInfoForAction(n,this.config),s=await this.getAbiForAction(n),{args:o}=await this.getTxComponentsFromInputs(n,r),c=o.map(y=>this.serializer.stringToTyped(y)),p=f.getChainEntrypoint(i,this.config.env),u=pt.newFromBech32(n.address),l=p.createSmartContractController(s),g=l.createQuery({contract:u,function:n.func,arguments:c}),m=await l.runQuery(g),T=m.returnCode==="ok",b=new je,A=s.getEndpoint(m.function),N=m.returnDataParts.map(y=>Buffer.from(y)),B=b.buffersToValues(N,A.output),{values:O,results:E}=await Qt(t,B),Q=f.getNextInfo(t,e,E,this.config);return{success:T,warp:t,action:e,user:this.config.userAddress||null,txHash:null,next:Q,values:O,results:E,messages:this.getPreparedMessages(t,E)}}async executeCollect(t,e,r,n){let i=L(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 g=this.serializer.stringToNative(l.value)[1];if(l.input.type==="biguint")return g.toString();if(l.input.type==="esdt"){let m=g;return{token:m.token.identifier,nonce:m.token.nonce.toString(),amount:m.amount.toString()}}else return g},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,g])=>{u.set(l,g)});try{let l=await fetch(i.destination.url,{method:i.destination.method,headers:u,body:JSON.stringify({inputs:p,meta:n})}),g=await l.json(),{values:m,results:T}=await zt(t,g),b=f.getNextInfo(t,e,T,this.config);return{success:l.ok,warp:t,action:e,user:this.config.userAddress||null,txHash:null,next:b,values:m,results:T,messages:this.getPreparedMessages(t,T)}}catch(l){return console.error(l),{success:!1,warp:t,action:e,user:this.config.userAddress||null,txHash:null,next:null,values:[],results:{},messages:{}}}}async getTxComponentsFromInputs(t,e,r){let n=await this.getResolvedInputs(t,e),i=this.getModifiedInputs(n),s=i.find(y=>y.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(y=>y.input.position==="value")?.value||null,g="value"in t?t.value:null,m=BigInt(l?.split(":")[1]||g||0),T=i.filter(y=>y.input.position==="transfer"&&y.value).map(y=>y.value),A=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...T?.map(y=>this.serializer.stringToNative(y)[1])||[]],N=i.find(y=>y.input.position==="data")?.value,B="data"in t?t.data||"":null,O=N||B||null,E=O?this.serializer.stringToTyped(O).valueOf():null,Q=E?Buffer.from(E):null;return{destination:p,args:u,value:m,transfers:A,data:Q}}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=D(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=D(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 Gt({identifier:n,nonce:BigInt(i)});if(!new ze().isFungible(c))return t;let l=Kt(n)?.decimals;if(!l){let m=this.config.chainApiUrl||h.MainChain.ApiUrl(this.config.env);l=(await(await fetch(`${m}/tokens/${n}`)).json()).decimals}if(!l)throw new Error(`WarpActionExecutor: Decimals not found for token ${n}`);let g=new Jt({token:c,amount:D(s,l)});return this.serializer.nativeToString(e,g)+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,e)]);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 H(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 Jt({token:new Gt({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};import{Address as Xt,TransactionsFactoryConfig as Ze,TransferTransactionsFactory as Xe}from"@multiversx/sdk-core";import Je 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 Je,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 j=class{constructor(t){this.pendingWarp={protocol:R("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t,this.cache=new S(t.cacheType)}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new Ze({chainID:v(this.config.env)}),r=new Xe({config:e}),n=Xt.newFromBech32(this.config.userAddress),i=JSON.stringify(t),s=r.createTransactionForTransfer(n,{receiver:Xt.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),f.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 o=this.cache.get(r);if(o)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),o}let n=W(this.config),s=f.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 $(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}`)}};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}}};import Ye from"qr-code-styling";var te=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):f.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:n}=e,i=new j(this.config),s=new P(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}`}buildFromPrefixedIdentifier(t){let e=f.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.id):""}generateQrCode(t,e,r=512,n="white",i="black",s="#23F7DD"){let o=this.build(t,e);return new Ye({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 f.getInfoFromPrefixedIdentifier(s)}};export{yt as BrandBuilder,x as CacheKey,h as Config,H as WarpAbiBuilder,Zt as WarpActionExecutor,U as WarpArgSerializer,j as WarpBuilder,S as WarpCache,d as WarpConstants,M as WarpContractLoader,Yt as WarpIndex,te as WarpLink,V as WarpProtocolVersions,P as WarpRegistry,f as WarpUtils,$ as WarpValidator,nn as address,en as biguint,rn as boolean,cn as codemeta,Gr as composite,on as esdt,v as getChainId,R as getLatestProtocolIdentifier,W as getMainChainInfo,L as getWarpActionByIndex,an as hex,zr as list,pn as nothing,jr as option,Qr as optional,_ as replacePlaceholders,D as shiftBigintBy,Jr as string,lt as toPreviewText,ut as toTypedChainInfo,q as toTypedRegistryInfo,sn as token,Xr as u16,Yr as u32,tn as u64,Zr as u8,Kr as variadic};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "2.0.0-alpha.6",
3
+ "version": "2.0.0-alpha.7",
4
4
  "description": "",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",