@vleap/warps 2.0.0-alpha.16 → 2.0.0-alpha.18

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
@@ -239,7 +239,7 @@ type WarpExecution = {
239
239
  type WarpExecutionNextInfo = {
240
240
  identifier: string | null;
241
241
  url: string;
242
- };
242
+ }[];
243
243
  type WarpExecutionResults = Record<WarpResultName, any | null>;
244
244
  type WarpExecutionMessages = Record<WarpMessageName, string | null>;
245
245
 
@@ -500,6 +500,9 @@ declare class WarpUtils {
500
500
  id: string;
501
501
  } | null;
502
502
  static getNextInfo(warp: Warp, actionIndex: number, results: WarpExecutionResults, config: WarpConfig): WarpExecutionNextInfo | null;
503
+ private static handleArrayNext;
504
+ private static buildNextUrl;
505
+ private static getNestedValue;
503
506
  static getChainInfoForAction(action: WarpTransferAction | WarpContractAction | WarpQueryAction, config: WarpConfig): Promise<ChainInfo>;
504
507
  static getChainEntrypoint(chainInfo: ChainInfo, env: ChainEnv): NetworkEntrypoint;
505
508
  }
package/dist/index.d.ts CHANGED
@@ -239,7 +239,7 @@ type WarpExecution = {
239
239
  type WarpExecutionNextInfo = {
240
240
  identifier: string | null;
241
241
  url: string;
242
- };
242
+ }[];
243
243
  type WarpExecutionResults = Record<WarpResultName, any | null>;
244
244
  type WarpExecutionMessages = Record<WarpMessageName, string | null>;
245
245
 
@@ -500,6 +500,9 @@ declare class WarpUtils {
500
500
  id: string;
501
501
  } | null;
502
502
  static getNextInfo(warp: Warp, actionIndex: number, results: WarpExecutionResults, config: WarpConfig): WarpExecutionNextInfo | null;
503
+ private static handleArrayNext;
504
+ private static buildNextUrl;
505
+ private static getNestedValue;
503
506
  static getChainInfoForAction(action: WarpTransferAction | WarpContractAction | WarpQueryAction, config: WarpConfig): Promise<ChainInfo>;
504
507
  static getChainEntrypoint(chainInfo: ChainInfo, env: ChainEnv): NetworkEntrypoint;
505
508
  }
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var Wt=Object.create;var Y=Object.defineProperty;var Ct=Object.getOwnPropertyDescriptor;var It=Object.getOwnPropertyNames;var bt=Object.getPrototypeOf,vt=Object.prototype.hasOwnProperty;var At=(i,t)=>{for(var e in t)Y(i,e,{get:t[e],enumerable:!0})},pt=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of It(t))!vt.call(i,n)&&n!==e&&Y(i,n,{get:()=>t[n],enumerable:!(r=Ct(t,n))||r.enumerable});return i};var et=(i,t,e)=>(e=i!=null?Wt(bt(i)):{},pt(t||!i||!i.__esModule?Y(e,"default",{value:i,enumerable:!0}):e,i)),xt=i=>pt(Y({},"__esModule",{value:!0}),i);var Kt={};At(Kt,{BrandBuilder:()=>it,CacheKey:()=>B,Config:()=>T,WarpAbiBuilder:()=>z,WarpActionExecutor:()=>st,WarpArgSerializer:()=>F,WarpBuilder:()=>J,WarpCache:()=>P,WarpConstants:()=>f,WarpContractLoader:()=>K,WarpIndex:()=>ot,WarpLink:()=>ct,WarpProtocolVersions:()=>V,WarpRegistry:()=>U,WarpUtils:()=>h,WarpValidator:()=>G,address:()=>Dt,biguint:()=>Lt,boolean:()=>qt,codemeta:()=>jt,composite:()=>Ut,esdt:()=>Mt,getChainId:()=>S,getLatestProtocolIdentifier:()=>R,getMainChainInfo:()=>A,getWarpActionByIndex:()=>D,hex:()=>Ht,list:()=>Vt,nothing:()=>Qt,option:()=>Et,optional:()=>Pt,replacePlaceholders:()=>M,shiftBigintBy:()=>H,string:()=>Nt,toPreviewText:()=>nt,toTypedChainInfo:()=>rt,toTypedRegistryInfo:()=>_,token:()=>_t,u16:()=>kt,u32:()=>$t,u64:()=>Ot,u8:()=>Ft,variadic:()=>Rt});module.exports=xt(Kt);var N=require("@multiversx/sdk-core"),ft=et(require("ajv"));var f={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}};var V={Warp:"1.3.0",Brand:"0.1.0",Abi:"0.1.0"},T={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:i=>i==="devnet"?"https://devnet.usewarp.to":i==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],MainChain:{ApiUrl:i=>i==="devnet"?"https://devnet-api.multiversx.com":i==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:i=>i==="devnet"?"https://devnet-explorer.multiversx.com":i==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com"},Registry:{Contract:i=>i==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":i==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query",f.Source.UserWallet],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var S=i=>i==="devnet"?"D":i==="testnet"?"T":"1",A=i=>({chainId:S(i.env),apiUrl:i.chainApiUrl||T.MainChain.ApiUrl(i.env),blockTime:6e3,explorerUrl:i.chainExplorerUrl||T.MainChain.ExplorerUrl(i.env)}),R=i=>{if(i==="warp")return`warp:${V.Warp}`;if(i==="brand")return`brand:${V.Brand}`;if(i==="abi")return`abi:${V.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${i}`)},D=(i,t)=>i?.actions[t-1],_=i=>({hash:i.hash.toString("hex"),alias:i.alias?.toString()||null,trust:i.trust.toString(),creator:i.creator.toString(),createdAt:i.created_at.toNumber(),brand:i.brand?.toString("hex")||null,upgrade:i.upgrade?.toString("hex")||null}),rt=i=>({chainId:i.chain_id.toString(),apiUrl:i.api_url.toString(),explorerUrl:i.explorer_url.toString(),blockTime:i.block_time.toNumber()}),H=(i,t)=>{let e=i.toString(),[r,n=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(r+n.padEnd(a,"0"));if(t<0){let o=r+n;if(a>=o.length)return 0n;let c=o.slice(0,-a)||"0";return BigInt(c)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},nt=(i,t=100)=>{if(!i)return"";let e=i.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},M=(i,t)=>i.replace(/\{\{([^}]+)\}\}/g,(e,r)=>t[r]||"");var $=require("@multiversx/sdk-core");var m=require("@multiversx/sdk-core/out");var at={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 B={Warp:i=>`warp:${i}`,WarpAbi:i=>`warp-abi:${i}`,RegistryInfo:i=>`registry-info:${i}`,Brand:i=>`brand:${i}`,ChainInfo:i=>`chain:${i}`},P=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 U=class{constructor(t){this.config=t,this.cache=new P(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.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(this.config.user.wallet),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.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=m.Address.newFromBech32(this.config.user.wallet);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.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(this.config.user.wallet);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.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(this.config.user.wallet);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.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=m.Address.newFromBech32(this.config.user.wallet);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.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=m.Address.newFromBech32(this.config.user.wallet);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.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(this.config.user.wallet);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=B.RegistryInfo(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let a=this.getRegistryContractAddress(),o=this.getController(),c=o.createQuery({contract:a,function:"getInfoByAlias",arguments:[m.BytesValue.fromUTF8(t)]}),p=await o.runQuery(c),[u]=o.parseQueryResponse(p),g=u?_(u):null,d=g?.brand?await this.fetchBrand(g.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:g,brand:d},e.ttl),{registryInfo:g,brand:d}}async getInfoByHash(t,e){let r=B.RegistryInfo(t);if(e){let d=this.cache.get(r);if(d)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),d}let n=this.getRegistryContractAddress(),a=this.getController(),o=a.createQuery({contract:n,function:"getInfoByHash",arguments:[m.BytesValue.fromHex(t)]}),c=await a.runQuery(o),[p]=a.parseQueryResponse(c),u=p?_(p):null,g=u?.brand?await this.fetchBrand(u.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:u,brand:g},e.ttl),{registryInfo:u,brand:g}}async getUserWarpRegistryInfos(t){let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:r,function:"getUserWarps",arguments:[new m.AddressValue(new m.Address(e))]}),o=await n.runQuery(a),[c]=n.parseQueryResponse(o);return c.map(_)}async getUserBrands(t){let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:r,function:"getUserBrands",arguments:[new m.AddressValue(new m.Address(e))]}),o=await n.runQuery(a),[c]=n.parseQueryResponse(o),p=c.map(d=>d.toString("hex")),u={ttl:365*24*60*60};return(await Promise.all(p.map(d=>this.fetchBrand(d,u)))).filter(d=>d!==null)}async getChainInfo(t,e){let r=B.ChainInfo(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let a=this.getRegistryContractAddress(),o=this.getController(),c=o.createQuery({contract:a,function:"getChain",arguments:[m.BytesValue.fromUTF8(t)]}),p=await o.runQuery(c),[u]=o.parseQueryResponse(p),g=u?rt(u):null;return g&&e?.ttl&&this.cache.set(r,g,e.ttl),g}async fetchBrand(t,e){let r=B.Brand(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let a=A(this.config),c=h.getChainEntrypoint(a,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||T.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:S(this.config.env)}),e=m.AbiRegistry.create(at);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(at);return e.createSmartContractController(r)}};var Bt="https://",ut="query",lt="env",h=class{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),n=(a,o)=>{r=r.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([a,o])=>{if(typeof o=="string"&&o.startsWith(`${ut}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let c=o.split(`${ut}:`)[1],p=new URL(e.currentUrl).searchParams.get(c);p&&n(a,p)}else if(typeof o=="string"&&o.startsWith(`${lt}:`)){let c=o.split(`${lt}:`)[1],p=e.vars?.[c];p&&n(a,p)}else typeof o=="string"&&o===f.Source.UserWallet&&e.user?.wallet?n(a,e.user.wallet):n(a,o)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(f.IdentifierParamSeparator)?e:`${f.IdentifierType.Alias}${f.IdentifierParamSeparator}${e}`,[n,a]=r.split(f.IdentifierParamSeparator);return{type:n,id:a}}static getNextInfo(t,e,r,n){let a=t.actions?.[e]?.next||t.next||null;if(!a)return null;if(a.startsWith(Bt))return{identifier:null,url:a};let[o,c]=a.split("?"),p=c?M(c,{...t.vars,...r}):null,u=new URLSearchParams(p||"");new URL(n.currentUrl||T.DefaultClientUrl(n.env)).searchParams.forEach((b,y)=>u.set(y,b));let d=u.toString()?`${o}?${u.toString()}`:o,W=new URL(n.clientUrl||T.DefaultClientUrl(n.env));return W.searchParams.set("warp",d),{identifier:d,url:W.toString().replace(/\/\?/,"?")}}static async getChainInfoForAction(t,e){if(!t.chain)return A(e);let r=await new U(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.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=new N.TransactionsFactoryConfig({chainID:S(this.config.env)}),r=new N.TransferTransactionsFactory({config:e}),n=N.Address.newFromBech32(this.config.user.wallet),a=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer(n,{receiver:N.Address.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(a))})}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 a=await n.getTransaction(t);return this.createFromTransaction(a)}catch(a){return console.error("BrandBuilder: Error creating from transaction hash",a),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||T.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),a=new ft.default,o=a.compile(n);if(!o(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(o.errors)}`)}};var l=require("@multiversx/sdk-core/out"),Et=(i,t)=>i?l.OptionValue.newProvided(i):t?l.OptionValue.newMissingTyped(t):l.OptionValue.newMissing(),Pt=(i,t)=>i?new l.OptionalValue(i.getType(),i):t?new l.OptionalValue(t):l.OptionalValue.newMissing(),Vt=i=>{if(i.length===0)throw new Error("Cannot create a list from an empty array");let t=i[0].getType();return new l.List(t,i)},Rt=i=>l.VariadicValue.fromItems(...i),Ut=i=>{let t=i.map(e=>e.getType());return new l.CompositeValue(new l.CompositeType(...t),i)},Nt=i=>l.StringValue.fromUTF8(i),Ft=i=>new l.U8Value(i),kt=i=>new l.U16Value(i),$t=i=>new l.U32Value(i),Ot=i=>new l.U64Value(i),Lt=i=>new l.BigUIntValue(BigInt(i)),qt=i=>new l.BooleanValue(i),Dt=i=>new l.AddressValue(l.Address.newFromBech32(i)),_t=i=>new l.TokenIdentifierValue(i),Ht=i=>l.BytesValue.fromHex(i),Mt=i=>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(i.token.identifier),"token_identifier"),new l.Field(new l.U64Value(BigInt(i.token.nonce)),"token_nonce"),new l.Field(new l.BigUIntValue(BigInt(i.amount)),"amount")]),jt=i=>new l.CodeMetadataValue(l.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(i,"hex")))),Qt=()=>new l.NothingValue;var O=require("@multiversx/sdk-core");var z=class{constructor(t){this.cache=new P;this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=new O.TransactionsFactoryConfig({chainID:S(this.config.env)}),r=new O.TransferTransactionsFactory({config:e}),n={protocol:R("abi"),content:t},a=O.Address.newFromBech32(this.config.user.wallet),o=JSON.stringify(n),c=r.createTransactionForTransfer(a,{receiver:a,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=B.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 w=require("@multiversx/sdk-core");var L=require("@multiversx/sdk-core/out");var s=require("@multiversx/sdk-core/out");var gt=new RegExp(`${f.ArgParamsSeparator}(.*)`),F=class{nativeToString(t,e){return t==="esdt"&&e instanceof s.TokenTransfer?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(s.OptionValue.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(s.OptionalValue.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(s.List.ClassName)){let e=t.getItems(),n=e.map(o=>this.typedToString(o).split(f.ArgParamsSeparator)[0])[0],a=e.map(o=>this.typedToString(o).split(f.ArgParamsSeparator)[1]);return`list:${n}:${a.join(",")}`}if(t.hasClassOrSuperclass(s.VariadicValue.ClassName)){let e=t.getItems(),n=e.map(o=>this.typedToString(o).split(f.ArgParamsSeparator)[0])[0],a=e.map(o=>this.typedToString(o).split(f.ArgParamsSeparator)[1]);return`variadic:${n}:${a.join(",")}`}if(t.hasClassOrSuperclass(s.CompositeValue.ClassName)){let e=t.getItems(),r=e.map(c=>this.typedToString(c).split(f.ArgParamsSeparator)[0]),n=e.map(c=>this.typedToString(c).split(f.ArgParamsSeparator)[1]),a=r.join(f.ArgCompositeSeparator),o=n.join(f.ArgCompositeSeparator);return`composite(${a}):${o}`}if(t.hasClassOrSuperclass(s.BigUIntValue.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(s.U8Value.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(s.U16Value.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(s.U32Value.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(s.U64Value.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(s.StringValue.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(s.BooleanValue.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(s.AddressValue.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(s.TokenIdentifierValue.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(s.BytesValue.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(s.CodeMetadataValue.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),n=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${n}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.stringToNative(e)}nativeToTyped(t,e){let r=this.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new s.CompositeType(...e.split(f.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new s.StringType;if(t==="uint8")return new s.U8Type;if(t==="uint16")return new s.U16Type;if(t==="uint32")return new s.U32Type;if(t==="uint64")return new s.U64Type;if(t==="biguint")return new s.BigUIntType;if(t==="bool")return new s.BooleanType;if(t==="address")return new s.AddressType;if(t==="token")return new s.TokenIdentifierType;if(t==="hex")return new s.BytesType;if(t==="codemeta")return new s.CodeMetadataType;if(t==="esdt"||t==="nft")return new s.StructType("EsdtTokenPayment",[new s.FieldDefinition("token_identifier","",new s.TokenIdentifierType),new s.FieldDefinition("token_nonce","",new s.U64Type),new s.FieldDefinition("amount","",new s.BigUIntType)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(f.ArgParamsSeparator),r=e[0],n=e.slice(1).join(f.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[a,o]=n.split(f.ArgParamsSeparator);return[`option:${a}`,o||null]}else if(r==="optional"){let[a,o]=n.split(f.ArgParamsSeparator);return[`optional:${a}`,o||null]}else if(r==="list"){let a=n.split(f.ArgParamsSeparator),o=a.slice(0,-1).join(f.ArgParamsSeparator),c=a[a.length-1],u=(c?c.split(","):[]).map(g=>this.stringToNative(`${o}:${g}`)[1]);return[`list:${o}`,u]}else if(r==="variadic"){let a=n.split(f.ArgParamsSeparator),o=a.slice(0,-1).join(f.ArgParamsSeparator),c=a[a.length-1],u=(c?c.split(","):[]).map(g=>this.stringToNative(`${o}:${g}`)[1]);return[`variadic:${o}`,u]}else if(r.startsWith("composite")){let a=r.match(/\(([^)]+)\)/)?.[1]?.split(f.ArgCompositeSeparator),c=n.split(f.ArgCompositeSeparator).map((p,u)=>this.stringToNative(`${a[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[a,o,c]=n.split(f.ArgCompositeSeparator);return[r,new s.TokenTransfer({token:new s.Token({identifier:a,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,a]=r.split(gt,2),c=a.split(",").map(p=>this.stringToTyped(`${n}:${p}`));return new s.List(this.nativeToType(n),c)}if(e==="variadic"){let[n,a]=r.split(gt,2),c=a.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],a=r.split(f.ArgCompositeSeparator),o=n.split(f.ArgCompositeSeparator),c=a.map((u,g)=>this.stringToTyped(`${o[g]}:${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(f.ArgCompositeSeparator);return new s.Struct(this.nativeToType("esdt"),[new s.Field(new s.TokenIdentifierValue(n[0]),"token_identifier"),new s.Field(new s.U64Value(BigInt(n[1])),"token_nonce"),new s.Field(new s.BigUIntValue(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof s.OptionType)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof s.OptionalType)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof s.ListType)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof s.VariadicType)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof s.StringType)return"string";if(t instanceof s.U8Type)return"uint8";if(t instanceof s.U16Type)return"uint16";if(t instanceof s.U32Type)return"uint32";if(t instanceof s.U64Type)return"uint64";if(t instanceof s.BigUIntType)return"biguint";if(t instanceof s.BooleanType)return"bool";if(t instanceof s.AddressType)return"address";if(t instanceof s.TokenIdentifierType)return"token";if(t instanceof s.BytesType)return"hex";if(t instanceof s.CodeMetadataType)return"codemeta";if(t instanceof s.StructType&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var dt=async(i,t,e,r)=>{let n=[],a={};if(!t.results||!e.abi||e.type!=="contract")return{values:n,results:a};let o=await i.getAbiForAction(e),c=new L.TransactionEventsParser({abi:o}),u=new L.SmartContractTransactionsOutcomeParser({abi:o}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[g,d]of Object.entries(t.results)){let[W,b,y]=d.split(".");if(W==="event"){if(!b||isNaN(Number(y)))continue;let I=Number(y),C=(0,L.findEventsByFirstTopic)(r,b),E=c.parseEvents({events:C})[0],x=Object.values(E)[I]||null;n.push(x),a[g]=x&&x.valueOf()}else if(W==="out"){if(!b)continue;let I=Number(b),C=u.values[I-1]||null;n.push(C),a[g]=C&&C.valueOf()}}return{values:n,results:a}},mt=async(i,t)=>{let e=new F,r=t.map(c=>e.typedToString(c)),n=t.map(c=>e.typedToNative(c)[1]),a={};if(!i.results)return{values:r,results:a};let o=c=>{let p=c.split(".").slice(1).map(g=>parseInt(g)-1);if(p.length===0)return;let u=n[p[0]];for(let g=1;g<p.length;g++){if(u==null)return;u=u[p[g]]}return u};return Object.entries(i.results).forEach(([c,p])=>{if(p.startsWith("out.")){let u=o(p);a[c]=u||null}}),{values:r,results:a}},ht=async(i,t)=>{let e=[],r={};for(let[n,a]of Object.entries(i.results||{})){let[o,...c]=a.split(".");if(o!=="out"||!c.length)continue;let p=c.reduce((u,g)=>u?.[g],t);e.push(p),r[n]=p}return{values:e,results:r}};var zt=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],yt=i=>zt.find(t=>t.id===i)||null;var K=class{constructor(t){this.config=t}async getContract(t,e){try{let a=await h.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}`);return{address:t,owner:a.ownerAddress,verified:a.isVerified||!1}}catch(r){return console.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t,e){try{let a=await h.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}/verification`);return{codeHash:a.codeHash,abi:a.source.abi}}catch(r){return console.error("WarpContractLoader: getVerificationInfo error",r),null}}};var st=class{constructor(t){if(!t.currentUrl)throw new Error("WarpActionExecutor: currentUrl config not set");this.config=t,this.url=new URL(t.currentUrl),this.serializer=new F,this.contractLoader=new K(t)}async createTransactionForExecute(t,e){if(!this.config.user?.wallet)throw new Error("WarpActionExecutor: user address not set");let r=w.Address.newFromBech32(this.config.user.wallet),n=await h.getChainInfoForAction(t,this.config),a=new w.TransactionsFactoryConfig({chainID:n.chainId}),{destination:o,args:c,value:p,transfers:u,data:g}=await this.getTxComponentsFromInputs(t,e,r),d=c.map(W=>this.serializer.stringToTyped(W));if(t.type==="transfer")return new w.TransferTransactionsFactory({config:a}).createTransactionForTransfer(r,{receiver:o,nativeAmount:p,tokenTransfers:u,data:g?new Uint8Array(g):void 0});if(t.type==="contract"&&o.isSmartContract())return new w.SmartContractTransactionsFactory({config:a}).createTransactionForExecute(r,{contract:o,function:"func"in t&&t.func||"",gasLimit:"gasLimit"in t?BigInt(t.gasLimit||0):0n,arguments:d,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=D(t,e),{values:a,results:o}=await dt(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.user?.wallet||null,txHash:r.hash,next:c,values:a,results:o,messages:p}}async executeQuery(t,e,r){let n=h.prepareVars(t,this.config),a=D(n,e);if(!a)throw new Error("WarpActionExecutor: Action not found");if(!a.func)throw new Error("WarpActionExecutor: Function not found");let o=await h.getChainInfoForAction(a,this.config),c=await this.getAbiForAction(a),{args:p}=await this.getTxComponentsFromInputs(a,r),u=p.map(tt=>this.serializer.stringToTyped(tt)),g=h.getChainEntrypoint(o,this.config.env),d=w.Address.newFromBech32(a.address),W=g.createSmartContractController(c),b=W.createQuery({contract:d,function:a.func,arguments:u}),y=await W.runQuery(b),I=y.returnCode==="ok",C=new w.ArgSerializer,E=c.getEndpoint(y.function),x=y.returnDataParts.map(tt=>Buffer.from(tt)),Z=C.buffersToValues(x,E.output),{values:X,results:q}=await mt(n,Z),v=h.getNextInfo(n,e,q,this.config);return{success:I,warp:n,action:e,user:this.config.user?.wallet||null,txHash:null,next:v,values:X,results:q,messages:this.getPreparedMessages(n,q)}}async executeCollect(t,e,r,n){let a=h.prepareVars(t,this.config),o=D(a,e);if(!o)throw new Error("WarpActionExecutor: Action not found");let c=await this.getResolvedInputs(o,r),p=this.getModifiedInputs(c),u=y=>{if(!y.value)return null;let I=this.serializer.stringToNative(y.value)[1];if(y.input.type==="biguint")return I.toString();if(y.input.type==="esdt"){let C=I;return{token:C.token.identifier,nonce:C.token.nonce.toString(),amount:C.amount.toString()}}else return I},g=Object.fromEntries(p.map(y=>[y.input.as||y.input.name,u(y)])),d=new Headers;d.set("Content-Type","application/json"),d.set("Accept","application/json"),Object.entries(o.destination.headers||{}).forEach(([y,I])=>{d.set(y,I)});let W=o.destination.method||"GET",b=W==="GET"?void 0:JSON.stringify({inputs:g,meta:n});try{let y=await fetch(o.destination.url,{method:W,headers:d,body:b}),I=await y.json(),{values:C,results:E}=await ht(a,I),x=h.getNextInfo(a,e,E,this.config);return{success:y.ok,warp:a,action:e,user:this.config.user?.wallet||null,txHash:null,next:x,values:C,results:E,messages:this.getPreparedMessages(a,E)}}catch(y){return console.error(y),{success:!1,warp:a,action:e,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{},messages:{}}}}async getTxComponentsFromInputs(t,e,r){let n=await this.getResolvedInputs(t,e),a=this.getModifiedInputs(n),o=a.find(v=>v.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=w.Address.newFromBech32(p),g=this.getPreparedArgs(t,a),d=a.find(v=>v.input.position==="value")?.value||null,W="value"in t?t.value:null,b=BigInt(d?.split(":")[1]||W||0),y=a.filter(v=>v.input.position==="transfer"&&v.value).map(v=>v.value),C=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...y?.map(v=>this.serializer.stringToNative(v)[1])||[]],E=a.find(v=>v.input.position==="data")?.value,x="data"in t?t.data||"":null,Z=E||x||null,X=Z?this.serializer.stringToTyped(Z).valueOf():null,q=X?Buffer.from(X):null;return{destination:u,args:g,value:b,transfers:C,data:q}}async getResolvedInputs(t,e){let r=t.inputs||[],n=await Promise.all(e.map(o=>this.preprocessInput(o))),a=(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===f.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:n[c]||null};return r.map((o,c)=>({input:o,value:a(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 a=Number(t.find(p=>p.input.name===n)?.value?.split(":")[1]);if(!a)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=H(o,+a);return{...e,value:`${e.input.type}:${c}`}}else{let a=e.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=H(a,+n);return{...e,value:`${e.input.type}:${o}`}}}else return e})}async preprocessInput(t){try{let[e,r]=t.split(f.ArgParamsSeparator,2);if(e==="esdt"){let[n,a,o,c]=r.split(f.ArgCompositeSeparator);if(c)return t;let p=new w.Token({identifier:n,nonce:BigInt(a)});if(!new w.TokenComputer().isFungible(p))return t;let d=yt(n)?.decimals;if(!d){let b=this.config.chainApiUrl||T.MainChain.ApiUrl(this.config.env);d=(await(await fetch(`${b}/tokens/${n}`)).json()).decimals}if(!d)throw new Error(`WarpActionExecutor: Decimals not found for token ${n}`);let W=new w.TokenTransfer({token:p,amount:H(o,d)});return this.serializer.nativeToString(e,W)+f.ArgCompositeSeparator+d}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 w.AbiRegistry.create(r.abi)}getPreparedArgs(t,e){let r="args"in t?t.args||[]:[];return e.forEach(({input:n,value:a})=>{if(!a||!n.position?.startsWith("arg:"))return;let o=Number(n.position.split(":")[1])-1;r.splice(o,0,a)}),r}getPreparedMessages(t,e){let r=Object.entries(t.messages||{}).map(([n,a])=>[n,M(a,e)]);return Object.fromEntries(r)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(f.IdentifierType.Hash)){let e=new z(this.config),r=t.abi.split(f.IdentifierParamSeparator)[1],n=await e.createFromTransactionHash(r);if(!n)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return w.AbiRegistry.create(n.content)}else{let r=await(await fetch(t.abi)).json();return w.AbiRegistry.create(r)}}toTypedTransfer(t){return new w.TokenTransfer({token:new w.Token({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var k=require("@multiversx/sdk-core");var wt=et(require("ajv"));var G=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validateMaxOneValuePosition(t){return t.actions.filter(r=>r.inputs?r.inputs.some(n=>n.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],r=(n,a)=>{n&&Object.keys(n).forEach(o=>{o!==o.toUpperCase()&&e.push(`${a} name '${o}' must be uppercase`)})};return r(t.vars,"Variable"),r(t.results,"Result"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(a=>a.type==="contract"),r=t.actions.some(a=>a.type==="query");if(!e&&!r)return[];let n=t.actions.some(a=>a.abi);return t.results&&!n?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.warpSchemaUrl||T.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),a=new wt.default,o=a.compile(n);return o(t)?[]:[`Schema validation failed: ${a.errorsText(o.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var J=class{constructor(t){this.pendingWarp={protocol:R("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t,this.cache=new P(t.cacheType)}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=new k.TransactionsFactoryConfig({chainID:S(this.config.env)}),r=new k.TransferTransactionsFactory({config:e}),n=k.Address.newFromBech32(this.config.user.wallet),a=JSON.stringify(t),o=r.createTransactionForTransfer(n,{receiver:k.Address.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(a))});return o.gasLimit=o.gasLimit+BigInt(2e6),o}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.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.toBech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=B.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 this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return nt(t,e)}ensure(t,e){if(!t)throw new Error(e)}async validate(t){let r=await new G(this.config).validate(t);if(!r.valid)throw new Error(r.errors.join(`
2
- `))}};var ot=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 Tt=et(require("qr-code-styling"));var ct=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(f.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(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(f.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):h.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:n}=e,a=new J(this.config),o=new U(this.config),c=null,p=null,u=null;if(r==="hash"){c=await a.createFromTransactionHash(n);try{let{registryInfo:g,brand:d}=await o.getInfoByHash(n);p=g,u=d}catch{}}else if(r==="alias"){let{registryInfo:g,brand:d}=await o.getInfoByAlias(n);p=g,u=d,g&&(c=await a.createFromTransactionHash(g.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||T.DefaultClientUrl(this.config.env),n=t===f.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+f.IdentifierParamSeparator+e);return T.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${f.IdentifierParamName}=${n}`}buildFromPrefixedIdentifier(t){let e=h.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.id):""}generateQrCode(t,e,r=512,n="white",a="black",o="#23F7DD"){let c=this.build(t,e);return new Tt.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:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=T.SuperClientUrls.includes(e.origin),n=e.searchParams.get(f.IdentifierParamName),a=r&&!n?e.pathname.split("/")[1]:n;if(!a)return null;let o=decodeURIComponent(a);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});
1
+ "use strict";var Wt=Object.create;var Z=Object.defineProperty;var Ct=Object.getOwnPropertyDescriptor;var It=Object.getOwnPropertyNames;var bt=Object.getPrototypeOf,vt=Object.prototype.hasOwnProperty;var At=(s,t)=>{for(var e in t)Z(s,e,{get:t[e],enumerable:!0})},pt=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of It(t))!vt.call(s,n)&&n!==e&&Z(s,n,{get:()=>t[n],enumerable:!(r=Ct(t,n))||r.enumerable});return s};var et=(s,t,e)=>(e=s!=null?Wt(bt(s)):{},pt(t||!s||!s.__esModule?Z(e,"default",{value:s,enumerable:!0}):e,s)),xt=s=>pt(Z({},"__esModule",{value:!0}),s);var Kt={};At(Kt,{BrandBuilder:()=>it,CacheKey:()=>B,Config:()=>C,WarpAbiBuilder:()=>z,WarpActionExecutor:()=>st,WarpArgSerializer:()=>F,WarpBuilder:()=>J,WarpCache:()=>P,WarpConstants:()=>g,WarpContractLoader:()=>K,WarpIndex:()=>ot,WarpLink:()=>ct,WarpProtocolVersions:()=>V,WarpRegistry:()=>U,WarpUtils:()=>y,WarpValidator:()=>G,address:()=>_t,biguint:()=>Lt,boolean:()=>qt,codemeta:()=>jt,composite:()=>Ut,esdt:()=>Mt,getChainId:()=>S,getLatestProtocolIdentifier:()=>R,getMainChainInfo:()=>A,getWarpActionByIndex:()=>_,hex:()=>Ht,list:()=>Vt,nothing:()=>Qt,option:()=>Et,optional:()=>Pt,replacePlaceholders:()=>M,shiftBigintBy:()=>H,string:()=>Nt,toPreviewText:()=>nt,toTypedChainInfo:()=>rt,toTypedRegistryInfo:()=>D,token:()=>Dt,u16:()=>kt,u32:()=>$t,u64:()=>Ot,u8:()=>Ft,variadic:()=>Rt});module.exports=xt(Kt);var N=require("@multiversx/sdk-core"),ft=et(require("ajv"));var g={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}};var V={Warp:"1.3.0",Brand:"0.1.0",Abi:"0.1.0"},C={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",g.Source.UserWallet],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var S=s=>s==="devnet"?"D":s==="testnet"?"T":"1",A=s=>({chainId:S(s.env),apiUrl:s.chainApiUrl||C.MainChain.ApiUrl(s.env),blockTime:6e3,explorerUrl:s.chainExplorerUrl||C.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],D=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}),rt=s=>({chainId:s.chain_id.toString(),apiUrl:s.api_url.toString(),explorerUrl:s.explorer_url.toString(),blockTime:s.block_time.toNumber()}),H=(s,t)=>{let e=s.toString(),[r,n=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(r+n.padEnd(a,"0"));if(t<0){let i=r+n;if(a>=i.length)return 0n;let c=i.slice(0,-a)||"0";return BigInt(c)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},nt=(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},M=(s,t)=>s.replace(/\{\{([^}]+)\}\}/g,(e,r)=>t[r]||"");var $=require("@multiversx/sdk-core");var d=require("@multiversx/sdk-core/out");var at={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 B={Warp:s=>`warp:${s}`,WarpAbi:s=>`warp-abi:${s}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`,ChainInfo:s=>`chain:${s}`},P=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 U=class{constructor(t){this.config=t,this.cache=new P(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.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=d.Address.newFromBech32(this.config.user.wallet),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?[d.BytesValue.fromHex(t),d.BytesValue.fromUTF8(e)]:[d.BytesValue.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=d.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[d.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.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=d.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[d.BytesValue.fromUTF8(t),d.BytesValue.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=d.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[d.BytesValue.fromHex(t),d.BytesValue.fromUTF8(e)]})}createWarpVerifyTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=d.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[d.BytesValue.fromHex(t)]})}createBrandRegisterTransaction(t){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=d.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[d.BytesValue.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=d.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[d.BytesValue.fromHex(t),d.BytesValue.fromHex(e)]})}async getInfoByAlias(t,e){let r=B.RegistryInfo(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let a=this.getRegistryContractAddress(),i=this.getController(),c=i.createQuery({contract:a,function:"getInfoByAlias",arguments:[d.BytesValue.fromUTF8(t)]}),p=await i.runQuery(c),[u]=i.parseQueryResponse(p),f=u?D(u):null,m=f?.brand?await this.fetchBrand(f.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:f,brand:m},e.ttl),{registryInfo:f,brand:m}}async getInfoByHash(t,e){let r=B.RegistryInfo(t);if(e){let m=this.cache.get(r);if(m)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),m}let n=this.getRegistryContractAddress(),a=this.getController(),i=a.createQuery({contract:n,function:"getInfoByHash",arguments:[d.BytesValue.fromHex(t)]}),c=await a.runQuery(i),[p]=a.parseQueryResponse(c),u=p?D(p):null,f=u?.brand?await this.fetchBrand(u.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:u,brand:f},e.ttl),{registryInfo:u,brand:f}}async getUserWarpRegistryInfos(t){let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:r,function:"getUserWarps",arguments:[new d.AddressValue(new d.Address(e))]}),i=await n.runQuery(a),[c]=n.parseQueryResponse(i);return c.map(D)}async getUserBrands(t){let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:r,function:"getUserBrands",arguments:[new d.AddressValue(new d.Address(e))]}),i=await n.runQuery(a),[c]=n.parseQueryResponse(i),p=c.map(m=>m.toString("hex")),u={ttl:365*24*60*60};return(await Promise.all(p.map(m=>this.fetchBrand(m,u)))).filter(m=>m!==null)}async getChainInfo(t,e){let r=B.ChainInfo(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let a=this.getRegistryContractAddress(),i=this.getController(),c=i.createQuery({contract:a,function:"getChain",arguments:[d.BytesValue.fromUTF8(t)]}),p=await i.runQuery(c),[u]=i.parseQueryResponse(p),f=u?rt(u):null;return f&&e?.ttl&&this.cache.set(r,f,e.ttl),f}async fetchBrand(t,e){let r=B.Brand(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let a=A(this.config),c=y.getChainEntrypoint(a,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 d.Address.newFromBech32(this.config.registryContract||C.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 d.TransactionsFactoryConfig({chainID:S(this.config.env)}),e=d.AbiRegistry.create(at);return new d.SmartContractTransactionsFactory({config:t,abi:e})}getController(){let t=A(this.config),e=y.getChainEntrypoint(t,this.config.env),r=d.AbiRegistry.create(at);return e.createSmartContractController(r)}};var Bt="https://",ut="query",lt="env",y=class{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),n=(a,i)=>{r=r.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),i.toString())};return Object.entries(t.vars).forEach(([a,i])=>{if(typeof i!="string"){n(a,i);return}if(i.startsWith(`${ut}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let c=i.split(`${ut}:`)[1],p=new URL(e.currentUrl).searchParams.get(c);p&&n(a,p)}else if(i.startsWith(`${lt}:`)){let c=i.split(`${lt}:`)[1],p=e.vars?.[c];p&&n(a,p)}else i===g.Source.UserWallet&&e.user?.wallet?n(a,e.user.wallet):n(a,i)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(g.IdentifierParamSeparator)?e:`${g.IdentifierType.Alias}${g.IdentifierParamSeparator}${e}`,[n,a]=r.split(g.IdentifierParamSeparator);return{type:n,id:a}}static getNextInfo(t,e,r,n){let a=t.actions?.[e]?.next||t.next||null;if(!a)return null;if(a.startsWith(Bt))return[{identifier:null,url:a}];let[i,c]=a.split("?");if(!c)return[{identifier:i,url:this.buildNextUrl(i,n)}];let p=c.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let u=M(c,{...t.vars,...r}),f=u?`${i}?${u}`:i;return[{identifier:f,url:this.buildNextUrl(f,n,!1)}]}return this.handleArrayNext(i,c,p,r,n)}static handleArrayNext(t,e,r,n,a){let i=r[0];if(!i)return[{identifier:t,url:this.buildNextUrl(t,a)}];let c=i.match(/{{([^[]+)\[\]/)?.[1];if(!c||!n[c])return[{identifier:t,url:this.buildNextUrl(t,a)}];let p=Array.isArray(n[c])?n[c]:[n[c]],u=i.match(/\[\](\.[^}]+)?}}/)?.[1]||"",f=new RegExp(`{{${c}\\[\\]${u.replace(".","\\.")}}}`,"g"),m=p.map(T=>{let b=u?this.getNestedValue(T,u.slice(1)):T;if(b==null)return null;let h=e.replace(f,b);if(h.includes("{{")||h.includes("}}"))return null;let W=h?`${t}?${h}`:t;return{identifier:W,url:this.buildNextUrl(W,a,!0)}}).filter(T=>T!==null);return m.length>0?m:[{identifier:t,url:this.buildNextUrl(t,a)}]}static buildNextUrl(t,e,r=!1){let n=new URL(e.clientUrl||C.DefaultClientUrl(e.env)),[a,i]=t.split("?");return n.searchParams.set("warp",a),i&&new URLSearchParams(i).forEach((c,p)=>n.searchParams.set(p,c)),n.toString().replace(/\/\?/,"?")}static getNestedValue(t,e){return e.split(".").reduce((r,n)=>r?.[n],t)}static async getChainInfoForAction(t,e){if(!t.chain)return A(e);let r=await new U(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.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=new N.TransactionsFactoryConfig({chainID:S(this.config.env)}),r=new N.TransferTransactionsFactory({config:e}),n=N.Address.newFromBech32(this.config.user.wallet),a=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer(n,{receiver:N.Address.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(a))})}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=y.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let a=await n.getTransaction(t);return this.createFromTransaction(a)}catch(a){return console.error("BrandBuilder: Error creating from transaction hash",a),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||C.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),a=new ft.default,i=a.compile(n);if(!i(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(i.errors)}`)}};var l=require("@multiversx/sdk-core/out"),Et=(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(),Vt=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)},Rt=s=>l.VariadicValue.fromItems(...s),Ut=s=>{let t=s.map(e=>e.getType());return new l.CompositeValue(new l.CompositeType(...t),s)},Nt=s=>l.StringValue.fromUTF8(s),Ft=s=>new l.U8Value(s),kt=s=>new l.U16Value(s),$t=s=>new l.U32Value(s),Ot=s=>new l.U64Value(s),Lt=s=>new l.BigUIntValue(BigInt(s)),qt=s=>new l.BooleanValue(s),_t=s=>new l.AddressValue(l.Address.newFromBech32(s)),Dt=s=>new l.TokenIdentifierValue(s),Ht=s=>l.BytesValue.fromHex(s),Mt=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")]),jt=s=>new l.CodeMetadataValue(l.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),Qt=()=>new l.NothingValue;var O=require("@multiversx/sdk-core");var z=class{constructor(t){this.cache=new P;this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=new O.TransactionsFactoryConfig({chainID:S(this.config.env)}),r=new O.TransferTransactionsFactory({config:e}),n={protocol:R("abi"),content:t},a=O.Address.newFromBech32(this.config.user.wallet),i=JSON.stringify(n),c=r.createTransactionForTransfer(a,{receiver:a,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))});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=B.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),i=y.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let c=await i.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 w=require("@multiversx/sdk-core");var L=require("@multiversx/sdk-core/out");var o=require("@multiversx/sdk-core/out");var gt=new RegExp(`${g.ArgParamsSeparator}(.*)`),F=class{nativeToString(t,e){return t==="esdt"&&e instanceof o.TokenTransfer?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(o.OptionValue.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(o.OptionalValue.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(o.List.ClassName)){let e=t.getItems(),n=e.map(i=>this.typedToString(i).split(g.ArgParamsSeparator)[0])[0],a=e.map(i=>this.typedToString(i).split(g.ArgParamsSeparator)[1]);return`list:${n}:${a.join(",")}`}if(t.hasClassOrSuperclass(o.VariadicValue.ClassName)){let e=t.getItems(),n=e.map(i=>this.typedToString(i).split(g.ArgParamsSeparator)[0])[0],a=e.map(i=>this.typedToString(i).split(g.ArgParamsSeparator)[1]);return`variadic:${n}:${a.join(",")}`}if(t.hasClassOrSuperclass(o.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]),a=r.join(g.ArgCompositeSeparator),i=n.join(g.ArgCompositeSeparator);return`composite(${a}):${i}`}if(t.hasClassOrSuperclass(o.BigUIntValue.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(o.U8Value.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(o.U16Value.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(o.U32Value.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(o.U64Value.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(o.StringValue.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(o.BooleanValue.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(o.AddressValue.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(o.TokenIdentifierValue.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(o.BytesValue.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(o.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 o.CompositeType(...e.split(g.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new o.StringType;if(t==="uint8")return new o.U8Type;if(t==="uint16")return new o.U16Type;if(t==="uint32")return new o.U32Type;if(t==="uint64")return new o.U64Type;if(t==="biguint")return new o.BigUIntType;if(t==="bool")return new o.BooleanType;if(t==="address")return new o.AddressType;if(t==="token")return new o.TokenIdentifierType;if(t==="hex")return new o.BytesType;if(t==="codemeta")return new o.CodeMetadataType;if(t==="esdt"||t==="nft")return new o.StructType("EsdtTokenPayment",[new o.FieldDefinition("token_identifier","",new o.TokenIdentifierType),new o.FieldDefinition("token_nonce","",new o.U64Type),new o.FieldDefinition("amount","",new o.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[a,i]=n.split(g.ArgParamsSeparator);return[`option:${a}`,i||null]}else if(r==="optional"){let[a,i]=n.split(g.ArgParamsSeparator);return[`optional:${a}`,i||null]}else if(r==="list"){let a=n.split(g.ArgParamsSeparator),i=a.slice(0,-1).join(g.ArgParamsSeparator),c=a[a.length-1],u=(c?c.split(","):[]).map(f=>this.stringToNative(`${i}:${f}`)[1]);return[`list:${i}`,u]}else if(r==="variadic"){let a=n.split(g.ArgParamsSeparator),i=a.slice(0,-1).join(g.ArgParamsSeparator),c=a[a.length-1],u=(c?c.split(","):[]).map(f=>this.stringToNative(`${i}:${f}`)[1]);return[`variadic:${i}`,u]}else if(r.startsWith("composite")){let a=r.match(/\(([^)]+)\)/)?.[1]?.split(g.ArgCompositeSeparator),c=n.split(g.ArgCompositeSeparator).map((p,u)=>this.stringToNative(`${a[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[a,i,c]=n.split(g.ArgCompositeSeparator);return[r,new o.TokenTransfer({token:new o.Token({identifier:a,nonce:BigInt(i)}),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 o.NothingValue;if(e==="option"){let n=this.stringToTyped(r);return n instanceof o.NothingValue?o.OptionValue.newMissingTyped(n.getType()):o.OptionValue.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof o.NothingValue?o.OptionalValue.newMissing():new o.OptionalValue(n.getType(),n)}if(e==="list"){let[n,a]=r.split(gt,2),c=a.split(",").map(p=>this.stringToTyped(`${n}:${p}`));return new o.List(this.nativeToType(n),c)}if(e==="variadic"){let[n,a]=r.split(gt,2),c=a.split(",").map(p=>this.stringToTyped(`${n}:${p}`));return new o.VariadicValue(new o.VariadicType(this.nativeToType(n)),c)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],a=r.split(g.ArgCompositeSeparator),i=n.split(g.ArgCompositeSeparator),c=a.map((u,f)=>this.stringToTyped(`${i[f]}:${u}`)),p=c.map(u=>u.getType());return new o.CompositeValue(new o.CompositeType(...p),c)}if(e==="string")return r?o.StringValue.fromUTF8(r):new o.NothingValue;if(e==="uint8")return r?new o.U8Value(Number(r)):new o.NothingValue;if(e==="uint16")return r?new o.U16Value(Number(r)):new o.NothingValue;if(e==="uint32")return r?new o.U32Value(Number(r)):new o.NothingValue;if(e==="uint64")return r?new o.U64Value(BigInt(r)):new o.NothingValue;if(e==="biguint")return r?new o.BigUIntValue(BigInt(r)):new o.NothingValue;if(e==="bool")return r?new o.BooleanValue(typeof r=="boolean"?r:r==="true"):new o.NothingValue;if(e==="address")return r?new o.AddressValue(o.Address.newFromBech32(r)):new o.NothingValue;if(e==="token")return r?new o.TokenIdentifierValue(r):new o.NothingValue;if(e==="hex")return r?o.BytesValue.fromHex(r):new o.NothingValue;if(e==="codemeta")return new o.CodeMetadataValue(o.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(g.ArgCompositeSeparator);return new o.Struct(this.nativeToType("esdt"),[new o.Field(new o.TokenIdentifierValue(n[0]),"token_identifier"),new o.Field(new o.U64Value(BigInt(n[1])),"token_nonce"),new o.Field(new o.BigUIntValue(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof o.OptionType)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof o.OptionalType)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof o.ListType)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof o.VariadicType)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof o.StringType)return"string";if(t instanceof o.U8Type)return"uint8";if(t instanceof o.U16Type)return"uint16";if(t instanceof o.U32Type)return"uint32";if(t instanceof o.U64Type)return"uint64";if(t instanceof o.BigUIntType)return"biguint";if(t instanceof o.BooleanType)return"bool";if(t instanceof o.AddressType)return"address";if(t instanceof o.TokenIdentifierType)return"token";if(t instanceof o.BytesType)return"hex";if(t instanceof o.CodeMetadataType)return"codemeta";if(t instanceof o.StructType&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var dt=async(s,t,e,r)=>{let n=[],a={};if(!t.results||!e.abi||e.type!=="contract")return{values:n,results:a};let i=await s.getAbiForAction(e),c=new L.TransactionEventsParser({abi:i}),u=new L.SmartContractTransactionsOutcomeParser({abi:i}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[f,m]of Object.entries(t.results)){let[T,b,h]=m.split(".");if(T==="event"){if(!b||isNaN(Number(h)))continue;let W=Number(h),I=(0,L.findEventsByFirstTopic)(r,b),E=c.parseEvents({events:I})[0],x=Object.values(E)[W]||null;n.push(x),a[f]=x&&x.valueOf()}else if(T==="out"){if(!b)continue;let W=Number(b),I=u.values[W-1]||null;n.push(I),a[f]=I&&I.valueOf()}}return{values:n,results:a}},mt=async(s,t)=>{let e=new F,r=t.map(c=>e.typedToString(c)),n=t.map(c=>e.typedToNative(c)[1]),a={};if(!s.results)return{values:r,results:a};let i=c=>{let p=c.split(".").slice(1).map(f=>parseInt(f)-1);if(p.length===0)return;let u=n[p[0]];for(let f=1;f<p.length;f++){if(u==null)return;u=u[p[f]]}return u};return Object.entries(s.results).forEach(([c,p])=>{if(p.startsWith("out.")){let u=i(p);a[c]=u||null}}),{values:r,results:a}},ht=async(s,t)=>{let e=[],r={};for(let[n,a]of Object.entries(s.results||{})){let[i,...c]=a.split(".");if(i!=="out")continue;if(!c.length){let u=t?.data||t;e.push(u),r[n]=u;continue}let p=c.reduce((u,f)=>u?.[f],t);e.push(p),r[n]=p}return{values:e,results:r}};var zt=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],yt=s=>zt.find(t=>t.id===s)||null;var K=class{constructor(t){this.config=t}async getContract(t,e){try{let a=await y.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}`);return{address:t,owner:a.ownerAddress,verified:a.isVerified||!1}}catch(r){return console.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t,e){try{let a=await y.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}/verification`);return{codeHash:a.codeHash,abi:a.source.abi}}catch(r){return console.error("WarpContractLoader: getVerificationInfo error",r),null}}};var st=class{constructor(t){if(!t.currentUrl)throw new Error("WarpActionExecutor: currentUrl config not set");this.config=t,this.url=new URL(t.currentUrl),this.serializer=new F,this.contractLoader=new K(t)}async createTransactionForExecute(t,e){if(!this.config.user?.wallet)throw new Error("WarpActionExecutor: user address not set");let r=w.Address.newFromBech32(this.config.user.wallet),n=await y.getChainInfoForAction(t,this.config),a=new w.TransactionsFactoryConfig({chainID:n.chainId}),{destination:i,args:c,value:p,transfers:u,data:f}=await this.getTxComponentsFromInputs(t,e,r),m=c.map(T=>this.serializer.stringToTyped(T));if(t.type==="transfer")return new w.TransferTransactionsFactory({config:a}).createTransactionForTransfer(r,{receiver:i,nativeAmount:p,tokenTransfers:u,data:f?new Uint8Array(f):void 0});if(t.type==="contract"&&i.isSmartContract())return new w.SmartContractTransactionsFactory({config:a}).createTransactionForExecute(r,{contract:i,function:"func"in t&&t.func||"",gasLimit:"gasLimit"in t?BigInt(t.gasLimit||0):0n,arguments:m,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:a,results:i}=await dt(this,t,n,r),c=y.getNextInfo(t,e,i,this.config),p=this.getPreparedMessages(t,i);return{success:r.status.isSuccessful(),warp:t,action:e,user:this.config.user?.wallet||null,txHash:r.hash,next:c,values:a,results:i,messages:p}}async executeQuery(t,e,r){let n=y.prepareVars(t,this.config),a=_(n,e);if(!a)throw new Error("WarpActionExecutor: Action not found");if(!a.func)throw new Error("WarpActionExecutor: Function not found");let i=await y.getChainInfoForAction(a,this.config),c=await this.getAbiForAction(a),{args:p}=await this.getTxComponentsFromInputs(a,r),u=p.map(tt=>this.serializer.stringToTyped(tt)),f=y.getChainEntrypoint(i,this.config.env),m=w.Address.newFromBech32(a.address),T=f.createSmartContractController(c),b=T.createQuery({contract:m,function:a.func,arguments:u}),h=await T.runQuery(b),W=h.returnCode==="ok",I=new w.ArgSerializer,E=c.getEndpoint(h.function),x=h.returnDataParts.map(tt=>Buffer.from(tt)),X=I.buffersToValues(x,E.output),{values:Y,results:q}=await mt(n,X),v=y.getNextInfo(n,e,q,this.config);return{success:W,warp:n,action:e,user:this.config.user?.wallet||null,txHash:null,next:v,values:Y,results:q,messages:this.getPreparedMessages(n,q)}}async executeCollect(t,e,r,n){let a=y.prepareVars(t,this.config),i=_(a,e);if(!i)throw new Error("WarpActionExecutor: Action not found");let c=await this.getResolvedInputs(i,r),p=this.getModifiedInputs(c),u=h=>{if(!h.value)return null;let W=this.serializer.stringToNative(h.value)[1];if(h.input.type==="biguint")return W.toString();if(h.input.type==="esdt"){let I=W;return{token:I.token.identifier,nonce:I.token.nonce.toString(),amount:I.amount.toString()}}else return W},f=new Headers;f.set("Content-Type","application/json"),f.set("Accept","application/json"),Object.entries(i.destination.headers||{}).forEach(([h,W])=>{f.set(h,W)});let m=Object.fromEntries(p.map(h=>[h.input.as||h.input.name,u(h)])),T=i.destination.method||"GET",b=T==="GET"?void 0:JSON.stringify({inputs:m,meta:n});try{let h=await fetch(i.destination.url,{method:T,headers:f,body:b}),W=await h.json(),{values:I,results:E}=await ht(a,W),x=y.getNextInfo(a,e,E,this.config);return{success:h.ok,warp:a,action:e,user:this.config.user?.wallet||null,txHash:null,next:x,values:I,results:E,messages:this.getPreparedMessages(a,E)}}catch(h){return console.error(h),{success:!1,warp:a,action:e,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{},messages:{}}}}async getTxComponentsFromInputs(t,e,r){let n=await this.getResolvedInputs(t,e),a=this.getModifiedInputs(n),i=a.find(v=>v.input.position==="receiver")?.value,c="address"in t?t.address:null,p=i?.split(":")[1]||c||r?.toBech32();if(!p)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let u=w.Address.newFromBech32(p),f=this.getPreparedArgs(t,a),m=a.find(v=>v.input.position==="value")?.value||null,T="value"in t?t.value:null,b=BigInt(m?.split(":")[1]||T||0),h=a.filter(v=>v.input.position==="transfer"&&v.value).map(v=>v.value),I=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...h?.map(v=>this.serializer.stringToNative(v)[1])||[]],E=a.find(v=>v.input.position==="data")?.value,x="data"in t?t.data||"":null,X=E||x||null,Y=X?this.serializer.stringToTyped(X).valueOf():null,q=Y?Buffer.from(Y):null;return{destination:u,args:f,value:b,transfers:I,data:q}}async getResolvedInputs(t,e){let r=t.inputs||[],n=await Promise.all(e.map(i=>this.preprocessInput(i))),a=(i,c)=>{if(i.source==="query"){let p=this.url.searchParams.get(i.name);return p?this.serializer.nativeToString(i.type,p):null}else return i.source===g.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:n[c]||null};return r.map((i,c)=>({input:i,value:a(i,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 a=Number(t.find(p=>p.input.name===n)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let i=e.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let c=H(i,+a);return{...e,value:`${e.input.type}:${c}`}}else{let a=e.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let i=H(a,+n);return{...e,value:`${e.input.type}:${i}`}}}else return e})}async preprocessInput(t){try{let[e,r]=t.split(g.ArgParamsSeparator,2);if(e==="esdt"){let[n,a,i,c]=r.split(g.ArgCompositeSeparator);if(c)return t;let p=new w.Token({identifier:n,nonce:BigInt(a)});if(!new w.TokenComputer().isFungible(p))return t;let m=yt(n)?.decimals;if(!m){let b=this.config.chainApiUrl||C.MainChain.ApiUrl(this.config.env);m=(await(await fetch(`${b}/tokens/${n}`)).json()).decimals}if(!m)throw new Error(`WarpActionExecutor: Decimals not found for token ${n}`);let T=new w.TokenTransfer({token:p,amount:H(i,m)});return this.serializer.nativeToString(e,T)+g.ArgCompositeSeparator+m}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 w.AbiRegistry.create(r.abi)}getPreparedArgs(t,e){let r="args"in t?t.args||[]:[];return e.forEach(({input:n,value:a})=>{if(!a||!n.position?.startsWith("arg:"))return;let i=Number(n.position.split(":")[1])-1;r.splice(i,0,a)}),r}getPreparedMessages(t,e){let r=Object.entries(t.messages||{}).map(([n,a])=>[n,M(a,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 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 w.AbiRegistry.create(n.content)}else{let r=await(await fetch(t.abi)).json();return w.AbiRegistry.create(r)}}toTypedTransfer(t){return new w.TokenTransfer({token:new w.Token({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var k=require("@multiversx/sdk-core");var wt=et(require("ajv"));var G=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validateMaxOneValuePosition(t){return t.actions.filter(r=>r.inputs?r.inputs.some(n=>n.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],r=(n,a)=>{n&&Object.keys(n).forEach(i=>{i!==i.toUpperCase()&&e.push(`${a} name '${i}' must be uppercase`)})};return r(t.vars,"Variable"),r(t.results,"Result"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(a=>a.type==="contract"),r=t.actions.some(a=>a.type==="query");if(!e&&!r)return[];let n=t.actions.some(a=>a.abi);return t.results&&!n?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.warpSchemaUrl||C.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),a=new wt.default,i=a.compile(n);return i(t)?[]:[`Schema validation failed: ${a.errorsText(i.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var J=class{constructor(t){this.pendingWarp={protocol:R("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t,this.cache=new P(t.cacheType)}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=new k.TransactionsFactoryConfig({chainID:S(this.config.env)}),r=new k.TransferTransactionsFactory({config:e}),n=k.Address.newFromBech32(this.config.user.wallet),a=JSON.stringify(t),i=r.createTransactionForTransfer(n,{receiver:k.Address.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(a))});return i.gasLimit=i.gasLimit+BigInt(2e6),i}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.validate(r),y.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.toBech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=B.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),i=y.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let c=await i.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 this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return nt(t,e)}ensure(t,e){if(!t)throw new Error(e)}async validate(t){let r=await new G(this.config).validate(t);if(!r.valid)throw new Error(r.errors.join(`
2
+ `))}};var ot=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 Tt=et(require("qr-code-styling"));var ct=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)),i=(await Promise.all(n)).filter(u=>u.match),c=i.length>0,p=i.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):y.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:n}=e,a=new J(this.config),i=new U(this.config),c=null,p=null,u=null;if(r==="hash"){c=await a.createFromTransactionHash(n);try{let{registryInfo:f,brand:m}=await i.getInfoByHash(n);p=f,u=m}catch{}}else if(r==="alias"){let{registryInfo:f,brand:m}=await i.getInfoByAlias(n);p=f,u=m,f&&(c=await a.createFromTransactionHash(f.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||C.DefaultClientUrl(this.config.env),n=t===g.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+g.IdentifierParamSeparator+e);return C.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${g.IdentifierParamName}=${n}`}buildFromPrefixedIdentifier(t){let e=y.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.id):""}generateQrCode(t,e,r=512,n="white",a="black",i="#23F7DD"){let c=this.build(t,e);return new Tt.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:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(i)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=C.SuperClientUrls.includes(e.origin),n=e.searchParams.get(g.IdentifierParamName),a=r&&!n?e.pathname.split("/")[1]:n;if(!a)return null;let i=decodeURIComponent(a);return y.getInfoFromPrefixedIdentifier(i)}};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,2 +1,2 @@
1
- import{Address as yt,TransactionsFactoryConfig as pe,TransferTransactionsFactory as ue}from"@multiversx/sdk-core";import le from"ajv";var l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}};var P={Warp:"1.3.0",Brand:"0.1.0",Abi:"0.1.0"},m={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${P.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${P.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",l.Source.UserWallet],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var S=s=>s==="devnet"?"D":s==="testnet"?"T":"1",I=s=>({chainId:S(s.env),apiUrl:s.chainApiUrl||m.MainChain.ApiUrl(s.env),blockTime:6e3,explorerUrl:s.chainExplorerUrl||m.MainChain.ExplorerUrl(s.env)}),V=s=>{if(s==="warp")return`warp:${P.Warp}`;if(s==="brand")return`brand:${P.Brand}`;if(s==="abi")return`abi:${P.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${s}`)},L=(s,t)=>s?.actions[t-1],q=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}),lt=s=>({chainId:s.chain_id.toString(),apiUrl:s.api_url.toString(),explorerUrl:s.explorer_url.toString(),blockTime:s.block_time.toNumber()}),D=(s,t)=>{let e=s.toString(),[r,n=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(r+n.padEnd(a,"0"));if(t<0){let i=r+n;if(a>=i.length)return 0n;let o=i.slice(0,-a)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},ft=(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},_=(s,t)=>s.replace(/\{\{([^}]+)\}\}/g,(e,r)=>t[r]||"");import{DevnetEntrypoint as ie,MainnetEntrypoint as se,TestnetEntrypoint as oe}from"@multiversx/sdk-core";import{AbiRegistry as gt,Address as A,AddressValue as dt,BytesValue as T,SmartContractTransactionsFactory as ne,TransactionsFactoryConfig as ae}from"@multiversx/sdk-core/out";var K={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 B={Warp:s=>`warp:${s}`,WarpAbi:s=>`warp-abi:${s}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`,ChainInfo:s=>`chain:${s}`},E=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 R=class{constructor(t){this.config=t,this.cache=new E(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.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=A.newFromBech32(this.config.user.wallet),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?[T.fromHex(t),T.fromUTF8(e)]:[T.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=A.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[T.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=A.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[T.fromUTF8(t),T.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=A.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[T.fromHex(t),T.fromUTF8(e)]})}createWarpVerifyTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=A.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[T.fromHex(t)]})}createBrandRegisterTransaction(t){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=A.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[T.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=A.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[T.fromHex(t),T.fromHex(e)]})}async getInfoByAlias(t,e){let r=B.RegistryInfo(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let a=this.getRegistryContractAddress(),i=this.getController(),o=i.createQuery({contract:a,function:"getInfoByAlias",arguments:[T.fromUTF8(t)]}),c=await i.runQuery(o),[p]=i.parseQueryResponse(c),u=p?q(p):null,f=u?.brand?await this.fetchBrand(u.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:u,brand:f},e.ttl),{registryInfo:u,brand:f}}async getInfoByHash(t,e){let r=B.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(),a=this.getController(),i=a.createQuery({contract:n,function:"getInfoByHash",arguments:[T.fromHex(t)]}),o=await a.runQuery(i),[c]=a.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.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:r,function:"getUserWarps",arguments:[new dt(new A(e))]}),i=await n.runQuery(a),[o]=n.parseQueryResponse(i);return o.map(q)}async getUserBrands(t){let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:r,function:"getUserBrands",arguments:[new dt(new A(e))]}),i=await n.runQuery(a),[o]=n.parseQueryResponse(i),c=o.map(f=>f.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(c.map(f=>this.fetchBrand(f,p)))).filter(f=>f!==null)}async getChainInfo(t,e){let r=B.ChainInfo(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let a=this.getRegistryContractAddress(),i=this.getController(),o=i.createQuery({contract:a,function:"getChain",arguments:[T.fromUTF8(t)]}),c=await i.runQuery(o),[p]=i.parseQueryResponse(c),u=p?lt(p):null;return u&&e?.ttl&&this.cache.set(r,u,e.ttl),u}async fetchBrand(t,e){let r=B.Brand(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let a=I(this.config),o=g.getChainEntrypoint(a,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 A.newFromBech32(this.config.registryContract||m.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 ae({chainID:S(this.config.env)}),e=gt.create(K);return new ne({config:t,abi:e})}getController(){let t=I(this.config),e=g.getChainEntrypoint(t,this.config.env),r=gt.create(K);return e.createSmartContractController(r)}};var ce="https://",mt="query",ht="env",g=class{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),n=(a,i)=>{r=r.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),i.toString())};return Object.entries(t.vars).forEach(([a,i])=>{if(typeof i=="string"&&i.startsWith(`${mt}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=i.split(`${mt}:`)[1],c=new URL(e.currentUrl).searchParams.get(o);c&&n(a,c)}else if(typeof i=="string"&&i.startsWith(`${ht}:`)){let o=i.split(`${ht}:`)[1],c=e.vars?.[o];c&&n(a,c)}else typeof i=="string"&&i===l.Source.UserWallet&&e.user?.wallet?n(a,e.user.wallet):n(a,i)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(l.IdentifierParamSeparator)?e:`${l.IdentifierType.Alias}${l.IdentifierParamSeparator}${e}`,[n,a]=r.split(l.IdentifierParamSeparator);return{type:n,id:a}}static getNextInfo(t,e,r,n){let a=t.actions?.[e]?.next||t.next||null;if(!a)return null;if(a.startsWith(ce))return{identifier:null,url:a};let[i,o]=a.split("?"),c=o?_(o,{...t.vars,...r}):null,p=new URLSearchParams(c||"");new URL(n.currentUrl||m.DefaultClientUrl(n.env)).searchParams.forEach((W,d)=>p.set(d,W));let f=p.toString()?`${i}?${p.toString()}`:i,h=new URL(n.clientUrl||m.DefaultClientUrl(n.env));return h.searchParams.set("warp",f),{identifier:f,url:h.toString().replace(/\/\?/,"?")}}static async getChainInfoForAction(t,e){if(!t.chain)return I(e);let r=await new R(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 oe(t.apiUrl,n,r):new se(t.apiUrl,n,r)}};var wt=class{constructor(t){this.pendingBrand={protocol:V("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=new pe({chainID:S(this.config.env)}),r=new ue({config:e}),n=yt.newFromBech32(this.config.user.wallet),a=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer(n,{receiver:yt.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(a))})}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=I(this.config),n=g.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let a=await n.getTransaction(t);return this.createFromTransaction(a)}catch(a){return console.error("BrandBuilder: Error creating from transaction hash",a),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||m.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),a=new le,i=a.compile(n);if(!i(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(i.errors)}`)}};import{Address as fe,AddressValue as ge,BigUIntType as de,BigUIntValue as Tt,BooleanValue as me,BytesValue as he,CodeMetadata as ye,CodeMetadataValue as we,CompositeType as Te,CompositeValue as We,Field as G,FieldDefinition as J,List as Ce,NothingValue as Ie,OptionalValue as Z,OptionValue as X,StringValue as be,Struct as ve,StructType as Ae,TokenIdentifierType as xe,TokenIdentifierValue as Wt,U16Value as Se,U32Value as Be,U64Type as Ee,U64Value as Ct,U8Value as Pe,VariadicValue as Ve}from"@multiversx/sdk-core/out";var zr=(s,t)=>s?X.newProvided(s):t?X.newMissingTyped(t):X.newMissing(),Kr=(s,t)=>s?new Z(s.getType(),s):t?new Z(t):Z.newMissing(),Gr=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let t=s[0].getType();return new Ce(t,s)},Jr=s=>Ve.fromItems(...s),Zr=s=>{let t=s.map(e=>e.getType());return new We(new Te(...t),s)},Xr=s=>be.fromUTF8(s),Yr=s=>new Pe(s),tn=s=>new Se(s),en=s=>new Be(s),rn=s=>new Ct(s),nn=s=>new Tt(BigInt(s)),an=s=>new me(s),sn=s=>new ge(fe.newFromBech32(s)),on=s=>new Wt(s),cn=s=>he.fromHex(s),pn=s=>new ve(new Ae("EsdtTokenPayment",[new J("token_identifier","",new xe),new J("token_nonce","",new Ee),new J("amount","",new de)]),[new G(new Wt(s.token.identifier),"token_identifier"),new G(new Ct(BigInt(s.token.nonce)),"token_nonce"),new G(new Tt(BigInt(s.amount)),"amount")]),un=s=>new we(ye.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),ln=()=>new Ie;import{Address as Re,TransactionsFactoryConfig as Ue,TransferTransactionsFactory as Ne}from"@multiversx/sdk-core";var H=class{constructor(t){this.cache=new E;this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=new Ue({chainID:S(this.config.env)}),r=new Ne({config:e}),n={protocol:V("abi"),content:t},a=Re.newFromBech32(this.config.user.wallet),i=JSON.stringify(n),o=r.createTransactionForTransfer(a,{receiver:a,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))});return o.gasLimit=o.gasLimit+BigInt(2e6),o}async createFromRaw(t){return JSON.parse(t)}async createFromTransaction(t){let e=await this.createFromRaw(t.data.toString());return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,e){let r=B.WarpAbi(t);if(e){let o=this.cache.get(r);if(o)return console.log(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),o}let n=I(this.config),i=g.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await i.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 pt,Address as ut,ArgSerializer as Qe,SmartContractTransactionsFactory as ze,Token as Jt,TokenComputer as Ke,TokenTransfer as Zt,TransactionsFactoryConfig as Ge,TransferTransactionsFactory as Je}from"@multiversx/sdk-core";import{SmartContractTransactionsOutcomeParser as _e,TransactionEventsParser as He,findEventsByFirstTopic as Me}from"@multiversx/sdk-core/out";import{Address as Fe,AddressType as It,AddressValue as bt,BigUIntType as Y,BigUIntValue as tt,BooleanType as vt,BooleanValue as At,BytesType as xt,BytesValue as St,CodeMetadata as ke,CodeMetadataType as Bt,CodeMetadataValue as Et,CompositeType as Pt,CompositeValue as Vt,Field as et,FieldDefinition as rt,List as Rt,ListType as $e,NothingValue as b,OptionalType as Oe,OptionalValue as nt,OptionType as Le,OptionValue as at,StringType as Ut,StringValue as Nt,Struct as qe,StructType as Ft,Token as De,TokenIdentifierType as it,TokenIdentifierValue as st,TokenTransfer as kt,U16Type as $t,U16Value as Ot,U32Type as Lt,U32Value as qt,U64Type as ot,U64Value as ct,U8Type as Dt,U8Value as _t,VariadicType as Ht,VariadicValue as Mt}from"@multiversx/sdk-core/out";var jt=new RegExp(`${l.ArgParamsSeparator}(.*)`),U=class{nativeToString(t,e){return t==="esdt"&&e instanceof kt?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(at.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(nt.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(Rt.ClassName)){let e=t.getItems(),n=e.map(i=>this.typedToString(i).split(l.ArgParamsSeparator)[0])[0],a=e.map(i=>this.typedToString(i).split(l.ArgParamsSeparator)[1]);return`list:${n}:${a.join(",")}`}if(t.hasClassOrSuperclass(Mt.ClassName)){let e=t.getItems(),n=e.map(i=>this.typedToString(i).split(l.ArgParamsSeparator)[0])[0],a=e.map(i=>this.typedToString(i).split(l.ArgParamsSeparator)[1]);return`variadic:${n}:${a.join(",")}`}if(t.hasClassOrSuperclass(Vt.ClassName)){let e=t.getItems(),r=e.map(o=>this.typedToString(o).split(l.ArgParamsSeparator)[0]),n=e.map(o=>this.typedToString(o).split(l.ArgParamsSeparator)[1]),a=r.join(l.ArgCompositeSeparator),i=n.join(l.ArgCompositeSeparator);return`composite(${a}):${i}`}if(t.hasClassOrSuperclass(tt.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(_t.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Ot.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(qt.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(ct.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Nt.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(At.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(bt.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(st.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(St.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(Et.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(l.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new Ut;if(t==="uint8")return new Dt;if(t==="uint16")return new $t;if(t==="uint32")return new Lt;if(t==="uint64")return new ot;if(t==="biguint")return new Y;if(t==="bool")return new vt;if(t==="address")return new It;if(t==="token")return new it;if(t==="hex")return new xt;if(t==="codemeta")return new Bt;if(t==="esdt"||t==="nft")return new Ft("EsdtTokenPayment",[new rt("token_identifier","",new it),new rt("token_nonce","",new ot),new rt("amount","",new Y)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(l.ArgParamsSeparator),r=e[0],n=e.slice(1).join(l.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[a,i]=n.split(l.ArgParamsSeparator);return[`option:${a}`,i||null]}else if(r==="optional"){let[a,i]=n.split(l.ArgParamsSeparator);return[`optional:${a}`,i||null]}else if(r==="list"){let a=n.split(l.ArgParamsSeparator),i=a.slice(0,-1).join(l.ArgParamsSeparator),o=a[a.length-1],p=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`list:${i}`,p]}else if(r==="variadic"){let a=n.split(l.ArgParamsSeparator),i=a.slice(0,-1).join(l.ArgParamsSeparator),o=a[a.length-1],p=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`variadic:${i}`,p]}else if(r.startsWith("composite")){let a=r.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=n.split(l.ArgCompositeSeparator).map((c,p)=>this.stringToNative(`${a[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[a,i,o]=n.split(l.ArgCompositeSeparator);return[r,new kt({token:new De({identifier:a,nonce:BigInt(i)}),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 b;if(e==="option"){let n=this.stringToTyped(r);return n instanceof b?at.newMissingTyped(n.getType()):at.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof b?nt.newMissing():new nt(n.getType(),n)}if(e==="list"){let[n,a]=r.split(jt,2),o=a.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Rt(this.nativeToType(n),o)}if(e==="variadic"){let[n,a]=r.split(jt,2),o=a.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Mt(new Ht(this.nativeToType(n)),o)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],a=r.split(l.ArgCompositeSeparator),i=n.split(l.ArgCompositeSeparator),o=a.map((p,u)=>this.stringToTyped(`${i[u]}:${p}`)),c=o.map(p=>p.getType());return new Vt(new Pt(...c),o)}if(e==="string")return r?Nt.fromUTF8(r):new b;if(e==="uint8")return r?new _t(Number(r)):new b;if(e==="uint16")return r?new Ot(Number(r)):new b;if(e==="uint32")return r?new qt(Number(r)):new b;if(e==="uint64")return r?new ct(BigInt(r)):new b;if(e==="biguint")return r?new tt(BigInt(r)):new b;if(e==="bool")return r?new At(typeof r=="boolean"?r:r==="true"):new b;if(e==="address")return r?new bt(Fe.newFromBech32(r)):new b;if(e==="token")return r?new st(r):new b;if(e==="hex")return r?St.fromHex(r):new b;if(e==="codemeta")return new Et(ke.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(l.ArgCompositeSeparator);return new qe(this.nativeToType("esdt"),[new et(new st(n[0]),"token_identifier"),new et(new ct(BigInt(n[1])),"token_nonce"),new et(new tt(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof Le)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Oe)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof $e)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Ht)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Ut)return"string";if(t instanceof Dt)return"uint8";if(t instanceof $t)return"uint16";if(t instanceof Lt)return"uint32";if(t instanceof ot)return"uint64";if(t instanceof Y)return"biguint";if(t instanceof vt)return"bool";if(t instanceof It)return"address";if(t instanceof it)return"token";if(t instanceof xt)return"hex";if(t instanceof Bt)return"codemeta";if(t instanceof Ft&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var Qt=async(s,t,e,r)=>{let n=[],a={};if(!t.results||!e.abi||e.type!=="contract")return{values:n,results:a};let i=await s.getAbiForAction(e),o=new He({abi:i}),p=new _e({abi:i}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[u,f]of Object.entries(t.results)){let[h,W,d]=f.split(".");if(h==="event"){if(!W||isNaN(Number(d)))continue;let w=Number(d),y=Me(r,W),x=o.parseEvents({events:y})[0],v=Object.values(x)[w]||null;n.push(v),a[u]=v&&v.valueOf()}else if(h==="out"){if(!W)continue;let w=Number(W),y=p.values[w-1]||null;n.push(y),a[u]=y&&y.valueOf()}}return{values:n,results:a}},zt=async(s,t)=>{let e=new U,r=t.map(o=>e.typedToString(o)),n=t.map(o=>e.typedToNative(o)[1]),a={};if(!s.results)return{values:r,results:a};let i=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(s.results).forEach(([o,c])=>{if(c.startsWith("out.")){let p=i(c);a[o]=p||null}}),{values:r,results:a}},Kt=async(s,t)=>{let e=[],r={};for(let[n,a]of Object.entries(s.results||{})){let[i,...o]=a.split(".");if(i!=="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 je=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],Gt=s=>je.find(t=>t.id===s)||null;var M=class{constructor(t){this.config=t}async getContract(t,e){try{let a=await g.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}`);return{address:t,owner:a.ownerAddress,verified:a.isVerified||!1}}catch(r){return console.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t,e){try{let a=await g.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}/verification`);return{codeHash:a.codeHash,abi:a.source.abi}}catch(r){return console.error("WarpContractLoader: getVerificationInfo error",r),null}}};var Xt=class{constructor(t){if(!t.currentUrl)throw new Error("WarpActionExecutor: currentUrl config not set");this.config=t,this.url=new URL(t.currentUrl),this.serializer=new U,this.contractLoader=new M(t)}async createTransactionForExecute(t,e){if(!this.config.user?.wallet)throw new Error("WarpActionExecutor: user address not set");let r=ut.newFromBech32(this.config.user.wallet),n=await g.getChainInfoForAction(t,this.config),a=new Ge({chainID:n.chainId}),{destination:i,args:o,value:c,transfers:p,data:u}=await this.getTxComponentsFromInputs(t,e,r),f=o.map(h=>this.serializer.stringToTyped(h));if(t.type==="transfer")return new Je({config:a}).createTransactionForTransfer(r,{receiver:i,nativeAmount:c,tokenTransfers:p,data:u?new Uint8Array(u):void 0});if(t.type==="contract"&&i.isSmartContract())return new ze({config:a}).createTransactionForExecute(r,{contract:i,function:"func"in t&&t.func||"",gasLimit:"gasLimit"in t?BigInt(t.gasLimit||0):0n,arguments:f,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:a,results:i}=await Qt(this,t,n,r),o=g.getNextInfo(t,e,i,this.config),c=this.getPreparedMessages(t,i);return{success:r.status.isSuccessful(),warp:t,action:e,user:this.config.user?.wallet||null,txHash:r.hash,next:o,values:a,results:i,messages:c}}async executeQuery(t,e,r){let n=g.prepareVars(t,this.config),a=L(n,e);if(!a)throw new Error("WarpActionExecutor: Action not found");if(!a.func)throw new Error("WarpActionExecutor: Function not found");let i=await g.getChainInfoForAction(a,this.config),o=await this.getAbiForAction(a),{args:c}=await this.getTxComponentsFromInputs(a,r),p=c.map(z=>this.serializer.stringToTyped(z)),u=g.getChainEntrypoint(i,this.config.env),f=ut.newFromBech32(a.address),h=u.createSmartContractController(o),W=h.createQuery({contract:f,function:a.func,arguments:p}),d=await h.runQuery(W),w=d.returnCode==="ok",y=new Qe,x=o.getEndpoint(d.function),v=d.returnDataParts.map(z=>Buffer.from(z)),$=y.buffersToValues(v,x.output),{values:O,results:N}=await zt(n,$),C=g.getNextInfo(n,e,N,this.config);return{success:w,warp:n,action:e,user:this.config.user?.wallet||null,txHash:null,next:C,values:O,results:N,messages:this.getPreparedMessages(n,N)}}async executeCollect(t,e,r,n){let a=g.prepareVars(t,this.config),i=L(a,e);if(!i)throw new Error("WarpActionExecutor: Action not found");let o=await this.getResolvedInputs(i,r),c=this.getModifiedInputs(o),p=d=>{if(!d.value)return null;let w=this.serializer.stringToNative(d.value)[1];if(d.input.type==="biguint")return w.toString();if(d.input.type==="esdt"){let y=w;return{token:y.token.identifier,nonce:y.token.nonce.toString(),amount:y.amount.toString()}}else return w},u=Object.fromEntries(c.map(d=>[d.input.as||d.input.name,p(d)])),f=new Headers;f.set("Content-Type","application/json"),f.set("Accept","application/json"),Object.entries(i.destination.headers||{}).forEach(([d,w])=>{f.set(d,w)});let h=i.destination.method||"GET",W=h==="GET"?void 0:JSON.stringify({inputs:u,meta:n});try{let d=await fetch(i.destination.url,{method:h,headers:f,body:W}),w=await d.json(),{values:y,results:x}=await Kt(a,w),v=g.getNextInfo(a,e,x,this.config);return{success:d.ok,warp:a,action:e,user:this.config.user?.wallet||null,txHash:null,next:v,values:y,results:x,messages:this.getPreparedMessages(a,x)}}catch(d){return console.error(d),{success:!1,warp:a,action:e,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{},messages:{}}}}async getTxComponentsFromInputs(t,e,r){let n=await this.getResolvedInputs(t,e),a=this.getModifiedInputs(n),i=a.find(C=>C.input.position==="receiver")?.value,o="address"in t?t.address:null,c=i?.split(":")[1]||o||r?.toBech32();if(!c)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let p=ut.newFromBech32(c),u=this.getPreparedArgs(t,a),f=a.find(C=>C.input.position==="value")?.value||null,h="value"in t?t.value:null,W=BigInt(f?.split(":")[1]||h||0),d=a.filter(C=>C.input.position==="transfer"&&C.value).map(C=>C.value),y=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...d?.map(C=>this.serializer.stringToNative(C)[1])||[]],x=a.find(C=>C.input.position==="data")?.value,v="data"in t?t.data||"":null,$=x||v||null,O=$?this.serializer.stringToTyped($).valueOf():null,N=O?Buffer.from(O):null;return{destination:p,args:u,value:W,transfers:y,data:N}}async getResolvedInputs(t,e){let r=t.inputs||[],n=await Promise.all(e.map(i=>this.preprocessInput(i))),a=(i,o)=>{if(i.source==="query"){let c=this.url.searchParams.get(i.name);return c?this.serializer.nativeToString(i.type,c):null}else return i.source===l.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:n[o]||null};return r.map((i,o)=>({input:i,value:a(i,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 a=Number(t.find(c=>c.input.name===n)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let i=e.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let o=D(i,+a);return{...e,value:`${e.input.type}:${o}`}}else{let a=e.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let i=D(a,+n);return{...e,value:`${e.input.type}:${i}`}}}else return e})}async preprocessInput(t){try{let[e,r]=t.split(l.ArgParamsSeparator,2);if(e==="esdt"){let[n,a,i,o]=r.split(l.ArgCompositeSeparator);if(o)return t;let c=new Jt({identifier:n,nonce:BigInt(a)});if(!new Ke().isFungible(c))return t;let f=Gt(n)?.decimals;if(!f){let W=this.config.chainApiUrl||m.MainChain.ApiUrl(this.config.env);f=(await(await fetch(`${W}/tokens/${n}`)).json()).decimals}if(!f)throw new Error(`WarpActionExecutor: Decimals not found for token ${n}`);let h=new Zt({token:c,amount:D(i,f)});return this.serializer.nativeToString(e,h)+l.ArgCompositeSeparator+f}return t}catch{return t}}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=I(this.config),r=await this.contractLoader.getVerificationInfo(t.address,e);if(!r)throw new Error("WarpActionExecutor: Verification info not found");return pt.create(r.abi)}getPreparedArgs(t,e){let r="args"in t?t.args||[]:[];return e.forEach(({input:n,value:a})=>{if(!a||!n.position?.startsWith("arg:"))return;let i=Number(n.position.split(":")[1])-1;r.splice(i,0,a)}),r}getPreparedMessages(t,e){let r=Object.entries(t.messages||{}).map(([n,a])=>[n,_(a,e)]);return Object.fromEntries(r)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(l.IdentifierType.Hash)){let e=new H(this.config),r=t.abi.split(l.IdentifierParamSeparator)[1],n=await e.createFromTransactionHash(r);if(!n)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return pt.create(n.content)}else{let r=await(await fetch(t.abi)).json();return pt.create(r)}}toTypedTransfer(t){return new Zt({token:new Jt({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};import{Address as Yt,TransactionsFactoryConfig as Xe,TransferTransactionsFactory as Ye}from"@multiversx/sdk-core";import Ze from"ajv";var j=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validateMaxOneValuePosition(t){return t.actions.filter(r=>r.inputs?r.inputs.some(n=>n.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],r=(n,a)=>{n&&Object.keys(n).forEach(i=>{i!==i.toUpperCase()&&e.push(`${a} name '${i}' must be uppercase`)})};return r(t.vars,"Variable"),r(t.results,"Result"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(a=>a.type==="contract"),r=t.actions.some(a=>a.type==="query");if(!e&&!r)return[];let n=t.actions.some(a=>a.abi);return t.results&&!n?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.warpSchemaUrl||m.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),a=new Ze,i=a.compile(n);return i(t)?[]:[`Schema validation failed: ${a.errorsText(i.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var Q=class{constructor(t){this.pendingWarp={protocol:V("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t,this.cache=new E(t.cacheType)}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=new Xe({chainID:S(this.config.env)}),r=new Ye({config:e}),n=Yt.newFromBech32(this.config.user.wallet),a=JSON.stringify(t),i=r.createTransactionForTransfer(n,{receiver:Yt.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(a))});return i.gasLimit=i.gasLimit+BigInt(2e6),i}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.validate(r),g.prepareVars(r,this.config)}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.toBech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=B.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=I(this.config),i=g.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await i.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 this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return ft(t,e)}ensure(t,e){if(!t)throw new Error(e)}async validate(t){let r=await new j(this.config).validate(t);if(!r.valid)throw new Error(r.errors.join(`
2
- `))}};var te=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 tr from"qr-code-styling";var ee=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(l.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)),i=(await Promise.all(n)).filter(p=>p.match),o=i.length>0,c=i.map(p=>({url:p.url,warp:p.warp}));return{match:o,results:c}}async detect(t){let e=t.startsWith(l.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):g.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:n}=e,a=new Q(this.config),i=new R(this.config),o=null,c=null,p=null;if(r==="hash"){o=await a.createFromTransactionHash(n);try{let{registryInfo:u,brand:f}=await i.getInfoByHash(n);c=u,p=f}catch{}}else if(r==="alias"){let{registryInfo:u,brand:f}=await i.getInfoByAlias(n);c=u,p=f,u&&(o=await a.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||m.DefaultClientUrl(this.config.env),n=t===l.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+l.IdentifierParamSeparator+e);return m.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${l.IdentifierParamName}=${n}`}buildFromPrefixedIdentifier(t){let e=g.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.id):""}generateQrCode(t,e,r=512,n="white",a="black",i="#23F7DD"){let o=this.build(t,e);return new tr({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:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(i)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=m.SuperClientUrls.includes(e.origin),n=e.searchParams.get(l.IdentifierParamName),a=r&&!n?e.pathname.split("/")[1]:n;if(!a)return null;let i=decodeURIComponent(a);return g.getInfoFromPrefixedIdentifier(i)}};export{wt as BrandBuilder,B as CacheKey,m as Config,H as WarpAbiBuilder,Xt as WarpActionExecutor,U as WarpArgSerializer,Q as WarpBuilder,E as WarpCache,l as WarpConstants,M as WarpContractLoader,te as WarpIndex,ee as WarpLink,P as WarpProtocolVersions,R as WarpRegistry,g as WarpUtils,j as WarpValidator,sn as address,nn as biguint,an as boolean,un as codemeta,Zr as composite,pn as esdt,S as getChainId,V as getLatestProtocolIdentifier,I as getMainChainInfo,L as getWarpActionByIndex,cn as hex,Gr as list,ln as nothing,zr as option,Kr as optional,_ as replacePlaceholders,D as shiftBigintBy,Xr as string,ft as toPreviewText,lt as toTypedChainInfo,q as toTypedRegistryInfo,on as token,tn as u16,en as u32,rn as u64,Yr as u8,Jr as variadic};
1
+ import{Address as yt,TransactionsFactoryConfig as pe,TransferTransactionsFactory as ue}from"@multiversx/sdk-core";import le from"ajv";var l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}};var P={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${P.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${P.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",l.Source.UserWallet],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["receiver","value","transfer","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10","data","ignore"]};var S=s=>s==="devnet"?"D":s==="testnet"?"T":"1",I=s=>({chainId:S(s.env),apiUrl:s.chainApiUrl||w.MainChain.ApiUrl(s.env),blockTime:6e3,explorerUrl:s.chainExplorerUrl||w.MainChain.ExplorerUrl(s.env)}),V=s=>{if(s==="warp")return`warp:${P.Warp}`;if(s==="brand")return`brand:${P.Brand}`;if(s==="abi")return`abi:${P.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${s}`)},L=(s,t)=>s?.actions[t-1],q=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}),lt=s=>({chainId:s.chain_id.toString(),apiUrl:s.api_url.toString(),explorerUrl:s.explorer_url.toString(),blockTime:s.block_time.toNumber()}),_=(s,t)=>{let e=s.toString(),[r,n=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(r+n.padEnd(a,"0"));if(t<0){let i=r+n;if(a>=i.length)return 0n;let o=i.slice(0,-a)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},ft=(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},D=(s,t)=>s.replace(/\{\{([^}]+)\}\}/g,(e,r)=>t[r]||"");import{DevnetEntrypoint as ie,MainnetEntrypoint as se,TestnetEntrypoint as oe}from"@multiversx/sdk-core";import{AbiRegistry as gt,Address as A,AddressValue as dt,BytesValue as W,SmartContractTransactionsFactory as ne,TransactionsFactoryConfig as ae}from"@multiversx/sdk-core/out";var K={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 B={Warp:s=>`warp:${s}`,WarpAbi:s=>`warp-abi:${s}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`,ChainInfo:s=>`chain:${s}`},E=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 R=class{constructor(t){this.config=t,this.cache=new E(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.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=A.newFromBech32(this.config.user.wallet),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.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=A.newFromBech32(this.config.user.wallet);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.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=A.newFromBech32(this.config.user.wallet);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.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=A.newFromBech32(this.config.user.wallet);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.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=A.newFromBech32(this.config.user.wallet);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.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=A.newFromBech32(this.config.user.wallet);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.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=A.newFromBech32(this.config.user.wallet);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=B.RegistryInfo(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let a=this.getRegistryContractAddress(),i=this.getController(),o=i.createQuery({contract:a,function:"getInfoByAlias",arguments:[W.fromUTF8(t)]}),c=await i.runQuery(o),[p]=i.parseQueryResponse(c),u=p?q(p):null,f=u?.brand?await this.fetchBrand(u.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:u,brand:f},e.ttl),{registryInfo:u,brand:f}}async getInfoByHash(t,e){let r=B.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(),a=this.getController(),i=a.createQuery({contract:n,function:"getInfoByHash",arguments:[W.fromHex(t)]}),o=await a.runQuery(i),[c]=a.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.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:r,function:"getUserWarps",arguments:[new dt(new A(e))]}),i=await n.runQuery(a),[o]=n.parseQueryResponse(i);return o.map(q)}async getUserBrands(t){let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:r,function:"getUserBrands",arguments:[new dt(new A(e))]}),i=await n.runQuery(a),[o]=n.parseQueryResponse(i),c=o.map(f=>f.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(c.map(f=>this.fetchBrand(f,p)))).filter(f=>f!==null)}async getChainInfo(t,e){let r=B.ChainInfo(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let a=this.getRegistryContractAddress(),i=this.getController(),o=i.createQuery({contract:a,function:"getChain",arguments:[W.fromUTF8(t)]}),c=await i.runQuery(o),[p]=i.parseQueryResponse(c),u=p?lt(p):null;return u&&e?.ttl&&this.cache.set(r,u,e.ttl),u}async fetchBrand(t,e){let r=B.Brand(t),n=e?this.cache.get(r):null;if(n)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let a=I(this.config),o=d.getChainEntrypoint(a,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 A.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 ae({chainID:S(this.config.env)}),e=gt.create(K);return new ne({config:t,abi:e})}getController(){let t=I(this.config),e=d.getChainEntrypoint(t,this.config.env),r=gt.create(K);return e.createSmartContractController(r)}};var ce="https://",mt="query",ht="env",d=class{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),n=(a,i)=>{r=r.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),i.toString())};return Object.entries(t.vars).forEach(([a,i])=>{if(typeof i!="string"){n(a,i);return}if(i.startsWith(`${mt}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=i.split(`${mt}:`)[1],c=new URL(e.currentUrl).searchParams.get(o);c&&n(a,c)}else if(i.startsWith(`${ht}:`)){let o=i.split(`${ht}:`)[1],c=e.vars?.[o];c&&n(a,c)}else i===l.Source.UserWallet&&e.user?.wallet?n(a,e.user.wallet):n(a,i)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(l.IdentifierParamSeparator)?e:`${l.IdentifierType.Alias}${l.IdentifierParamSeparator}${e}`,[n,a]=r.split(l.IdentifierParamSeparator);return{type:n,id:a}}static getNextInfo(t,e,r,n){let a=t.actions?.[e]?.next||t.next||null;if(!a)return null;if(a.startsWith(ce))return[{identifier:null,url:a}];let[i,o]=a.split("?");if(!o)return[{identifier:i,url:this.buildNextUrl(i,n)}];let c=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let p=D(o,{...t.vars,...r}),u=p?`${i}?${p}`:i;return[{identifier:u,url:this.buildNextUrl(u,n,!1)}]}return this.handleArrayNext(i,o,c,r,n)}static handleArrayNext(t,e,r,n,a){let i=r[0];if(!i)return[{identifier:t,url:this.buildNextUrl(t,a)}];let o=i.match(/{{([^[]+)\[\]/)?.[1];if(!o||!n[o])return[{identifier:t,url:this.buildNextUrl(t,a)}];let c=Array.isArray(n[o])?n[o]:[n[o]],p=i.match(/\[\](\.[^}]+)?}}/)?.[1]||"",u=new RegExp(`{{${o}\\[\\]${p.replace(".","\\.")}}}`,"g"),f=c.map(m=>{let T=p?this.getNestedValue(m,p.slice(1)):m;if(T==null)return null;let g=e.replace(u,T);if(g.includes("{{")||g.includes("}}"))return null;let h=g?`${t}?${g}`:t;return{identifier:h,url:this.buildNextUrl(h,a,!0)}}).filter(m=>m!==null);return f.length>0?f:[{identifier:t,url:this.buildNextUrl(t,a)}]}static buildNextUrl(t,e,r=!1){let n=new URL(e.clientUrl||w.DefaultClientUrl(e.env)),[a,i]=t.split("?");return n.searchParams.set("warp",a),i&&new URLSearchParams(i).forEach((o,c)=>n.searchParams.set(c,o)),n.toString().replace(/\/\?/,"?")}static getNestedValue(t,e){return e.split(".").reduce((r,n)=>r?.[n],t)}static async getChainInfoForAction(t,e){if(!t.chain)return I(e);let r=await new R(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 oe(t.apiUrl,n,r):new se(t.apiUrl,n,r)}};var wt=class{constructor(t){this.pendingBrand={protocol:V("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=new pe({chainID:S(this.config.env)}),r=new ue({config:e}),n=yt.newFromBech32(this.config.user.wallet),a=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer(n,{receiver:yt.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(a))})}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=I(this.config),n=d.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let a=await n.getTransaction(t);return this.createFromTransaction(a)}catch(a){return console.error("BrandBuilder: Error creating from transaction hash",a),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(),a=new le,i=a.compile(n);if(!i(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(i.errors)}`)}};import{Address as fe,AddressValue as ge,BigUIntType as de,BigUIntValue as Tt,BooleanValue as me,BytesValue as he,CodeMetadata as ye,CodeMetadataValue as we,CompositeType as Te,CompositeValue as We,Field as G,FieldDefinition as J,List as Ce,NothingValue as Ie,OptionalValue as X,OptionValue as Y,StringValue as be,Struct as ve,StructType as Ae,TokenIdentifierType as xe,TokenIdentifierValue as Wt,U16Value as Se,U32Value as Be,U64Type as Ee,U64Value as Ct,U8Value as Pe,VariadicValue as Ve}from"@multiversx/sdk-core/out";var zr=(s,t)=>s?Y.newProvided(s):t?Y.newMissingTyped(t):Y.newMissing(),Kr=(s,t)=>s?new X(s.getType(),s):t?new X(t):X.newMissing(),Gr=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let t=s[0].getType();return new Ce(t,s)},Jr=s=>Ve.fromItems(...s),Xr=s=>{let t=s.map(e=>e.getType());return new We(new Te(...t),s)},Yr=s=>be.fromUTF8(s),Zr=s=>new Pe(s),tn=s=>new Se(s),en=s=>new Be(s),rn=s=>new Ct(s),nn=s=>new Tt(BigInt(s)),an=s=>new me(s),sn=s=>new ge(fe.newFromBech32(s)),on=s=>new Wt(s),cn=s=>he.fromHex(s),pn=s=>new ve(new Ae("EsdtTokenPayment",[new J("token_identifier","",new xe),new J("token_nonce","",new Ee),new J("amount","",new de)]),[new G(new Wt(s.token.identifier),"token_identifier"),new G(new Ct(BigInt(s.token.nonce)),"token_nonce"),new G(new Tt(BigInt(s.amount)),"amount")]),un=s=>new we(ye.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),ln=()=>new Ie;import{Address as Re,TransactionsFactoryConfig as Ue,TransferTransactionsFactory as Ne}from"@multiversx/sdk-core";var H=class{constructor(t){this.cache=new E;this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=new Ue({chainID:S(this.config.env)}),r=new Ne({config:e}),n={protocol:V("abi"),content:t},a=Re.newFromBech32(this.config.user.wallet),i=JSON.stringify(n),o=r.createTransactionForTransfer(a,{receiver:a,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))});return o.gasLimit=o.gasLimit+BigInt(2e6),o}async createFromRaw(t){return JSON.parse(t)}async createFromTransaction(t){let e=await this.createFromRaw(t.data.toString());return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,e){let r=B.WarpAbi(t);if(e){let o=this.cache.get(r);if(o)return console.log(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),o}let n=I(this.config),i=d.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await i.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 pt,Address as ut,ArgSerializer as Qe,SmartContractTransactionsFactory as ze,Token as Jt,TokenComputer as Ke,TokenTransfer as Xt,TransactionsFactoryConfig as Ge,TransferTransactionsFactory as Je}from"@multiversx/sdk-core";import{SmartContractTransactionsOutcomeParser as De,TransactionEventsParser as He,findEventsByFirstTopic as Me}from"@multiversx/sdk-core/out";import{Address as Fe,AddressType as It,AddressValue as bt,BigUIntType as Z,BigUIntValue as tt,BooleanType as vt,BooleanValue as At,BytesType as xt,BytesValue as St,CodeMetadata as ke,CodeMetadataType as Bt,CodeMetadataValue as Et,CompositeType as Pt,CompositeValue as Vt,Field as et,FieldDefinition as rt,List as Rt,ListType as $e,NothingValue as b,OptionalType as Oe,OptionalValue as nt,OptionType as Le,OptionValue as at,StringType as Ut,StringValue as Nt,Struct as qe,StructType as Ft,Token as _e,TokenIdentifierType as it,TokenIdentifierValue as st,TokenTransfer as kt,U16Type as $t,U16Value as Ot,U32Type as Lt,U32Value as qt,U64Type as ot,U64Value as ct,U8Type as _t,U8Value as Dt,VariadicType as Ht,VariadicValue as Mt}from"@multiversx/sdk-core/out";var jt=new RegExp(`${l.ArgParamsSeparator}(.*)`),U=class{nativeToString(t,e){return t==="esdt"&&e instanceof kt?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(at.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(nt.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(Rt.ClassName)){let e=t.getItems(),n=e.map(i=>this.typedToString(i).split(l.ArgParamsSeparator)[0])[0],a=e.map(i=>this.typedToString(i).split(l.ArgParamsSeparator)[1]);return`list:${n}:${a.join(",")}`}if(t.hasClassOrSuperclass(Mt.ClassName)){let e=t.getItems(),n=e.map(i=>this.typedToString(i).split(l.ArgParamsSeparator)[0])[0],a=e.map(i=>this.typedToString(i).split(l.ArgParamsSeparator)[1]);return`variadic:${n}:${a.join(",")}`}if(t.hasClassOrSuperclass(Vt.ClassName)){let e=t.getItems(),r=e.map(o=>this.typedToString(o).split(l.ArgParamsSeparator)[0]),n=e.map(o=>this.typedToString(o).split(l.ArgParamsSeparator)[1]),a=r.join(l.ArgCompositeSeparator),i=n.join(l.ArgCompositeSeparator);return`composite(${a}):${i}`}if(t.hasClassOrSuperclass(tt.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Dt.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Ot.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(qt.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(ct.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Nt.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(At.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(bt.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(st.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(St.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(Et.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(l.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new Ut;if(t==="uint8")return new _t;if(t==="uint16")return new $t;if(t==="uint32")return new Lt;if(t==="uint64")return new ot;if(t==="biguint")return new Z;if(t==="bool")return new vt;if(t==="address")return new It;if(t==="token")return new it;if(t==="hex")return new xt;if(t==="codemeta")return new Bt;if(t==="esdt"||t==="nft")return new Ft("EsdtTokenPayment",[new rt("token_identifier","",new it),new rt("token_nonce","",new ot),new rt("amount","",new Z)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(l.ArgParamsSeparator),r=e[0],n=e.slice(1).join(l.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[a,i]=n.split(l.ArgParamsSeparator);return[`option:${a}`,i||null]}else if(r==="optional"){let[a,i]=n.split(l.ArgParamsSeparator);return[`optional:${a}`,i||null]}else if(r==="list"){let a=n.split(l.ArgParamsSeparator),i=a.slice(0,-1).join(l.ArgParamsSeparator),o=a[a.length-1],p=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`list:${i}`,p]}else if(r==="variadic"){let a=n.split(l.ArgParamsSeparator),i=a.slice(0,-1).join(l.ArgParamsSeparator),o=a[a.length-1],p=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`variadic:${i}`,p]}else if(r.startsWith("composite")){let a=r.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=n.split(l.ArgCompositeSeparator).map((c,p)=>this.stringToNative(`${a[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[a,i,o]=n.split(l.ArgCompositeSeparator);return[r,new kt({token:new _e({identifier:a,nonce:BigInt(i)}),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 b;if(e==="option"){let n=this.stringToTyped(r);return n instanceof b?at.newMissingTyped(n.getType()):at.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof b?nt.newMissing():new nt(n.getType(),n)}if(e==="list"){let[n,a]=r.split(jt,2),o=a.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Rt(this.nativeToType(n),o)}if(e==="variadic"){let[n,a]=r.split(jt,2),o=a.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Mt(new Ht(this.nativeToType(n)),o)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],a=r.split(l.ArgCompositeSeparator),i=n.split(l.ArgCompositeSeparator),o=a.map((p,u)=>this.stringToTyped(`${i[u]}:${p}`)),c=o.map(p=>p.getType());return new Vt(new Pt(...c),o)}if(e==="string")return r?Nt.fromUTF8(r):new b;if(e==="uint8")return r?new Dt(Number(r)):new b;if(e==="uint16")return r?new Ot(Number(r)):new b;if(e==="uint32")return r?new qt(Number(r)):new b;if(e==="uint64")return r?new ct(BigInt(r)):new b;if(e==="biguint")return r?new tt(BigInt(r)):new b;if(e==="bool")return r?new At(typeof r=="boolean"?r:r==="true"):new b;if(e==="address")return r?new bt(Fe.newFromBech32(r)):new b;if(e==="token")return r?new st(r):new b;if(e==="hex")return r?St.fromHex(r):new b;if(e==="codemeta")return new Et(ke.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(l.ArgCompositeSeparator);return new qe(this.nativeToType("esdt"),[new et(new st(n[0]),"token_identifier"),new et(new ct(BigInt(n[1])),"token_nonce"),new et(new tt(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof Le)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Oe)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof $e)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Ht)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Ut)return"string";if(t instanceof _t)return"uint8";if(t instanceof $t)return"uint16";if(t instanceof Lt)return"uint32";if(t instanceof ot)return"uint64";if(t instanceof Z)return"biguint";if(t instanceof vt)return"bool";if(t instanceof It)return"address";if(t instanceof it)return"token";if(t instanceof xt)return"hex";if(t instanceof Bt)return"codemeta";if(t instanceof Ft&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var Qt=async(s,t,e,r)=>{let n=[],a={};if(!t.results||!e.abi||e.type!=="contract")return{values:n,results:a};let i=await s.getAbiForAction(e),o=new He({abi:i}),p=new De({abi:i}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[u,f]of Object.entries(t.results)){let[m,T,g]=f.split(".");if(m==="event"){if(!T||isNaN(Number(g)))continue;let h=Number(g),y=Me(r,T),x=o.parseEvents({events:y})[0],v=Object.values(x)[h]||null;n.push(v),a[u]=v&&v.valueOf()}else if(m==="out"){if(!T)continue;let h=Number(T),y=p.values[h-1]||null;n.push(y),a[u]=y&&y.valueOf()}}return{values:n,results:a}},zt=async(s,t)=>{let e=new U,r=t.map(o=>e.typedToString(o)),n=t.map(o=>e.typedToNative(o)[1]),a={};if(!s.results)return{values:r,results:a};let i=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(s.results).forEach(([o,c])=>{if(c.startsWith("out.")){let p=i(c);a[o]=p||null}}),{values:r,results:a}},Kt=async(s,t)=>{let e=[],r={};for(let[n,a]of Object.entries(s.results||{})){let[i,...o]=a.split(".");if(i!=="out")continue;if(!o.length){let p=t?.data||t;e.push(p),r[n]=p;continue}let c=o.reduce((p,u)=>p?.[u],t);e.push(c),r[n]=c}return{values:e,results:r}};var je=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],Gt=s=>je.find(t=>t.id===s)||null;var M=class{constructor(t){this.config=t}async getContract(t,e){try{let a=await d.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}`);return{address:t,owner:a.ownerAddress,verified:a.isVerified||!1}}catch(r){return console.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t,e){try{let a=await d.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}/verification`);return{codeHash:a.codeHash,abi:a.source.abi}}catch(r){return console.error("WarpContractLoader: getVerificationInfo error",r),null}}};var Yt=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)}async createTransactionForExecute(t,e){if(!this.config.user?.wallet)throw new Error("WarpActionExecutor: user address not set");let r=ut.newFromBech32(this.config.user.wallet),n=await d.getChainInfoForAction(t,this.config),a=new Ge({chainID:n.chainId}),{destination:i,args:o,value:c,transfers:p,data:u}=await this.getTxComponentsFromInputs(t,e,r),f=o.map(m=>this.serializer.stringToTyped(m));if(t.type==="transfer")return new Je({config:a}).createTransactionForTransfer(r,{receiver:i,nativeAmount:c,tokenTransfers:p,data:u?new Uint8Array(u):void 0});if(t.type==="contract"&&i.isSmartContract())return new ze({config:a}).createTransactionForExecute(r,{contract:i,function:"func"in t&&t.func||"",gasLimit:"gasLimit"in t?BigInt(t.gasLimit||0):0n,arguments:f,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:a,results:i}=await Qt(this,t,n,r),o=d.getNextInfo(t,e,i,this.config),c=this.getPreparedMessages(t,i);return{success:r.status.isSuccessful(),warp:t,action:e,user:this.config.user?.wallet||null,txHash:r.hash,next:o,values:a,results:i,messages:c}}async executeQuery(t,e,r){let n=d.prepareVars(t,this.config),a=L(n,e);if(!a)throw new Error("WarpActionExecutor: Action not found");if(!a.func)throw new Error("WarpActionExecutor: Function not found");let i=await d.getChainInfoForAction(a,this.config),o=await this.getAbiForAction(a),{args:c}=await this.getTxComponentsFromInputs(a,r),p=c.map(z=>this.serializer.stringToTyped(z)),u=d.getChainEntrypoint(i,this.config.env),f=ut.newFromBech32(a.address),m=u.createSmartContractController(o),T=m.createQuery({contract:f,function:a.func,arguments:p}),g=await m.runQuery(T),h=g.returnCode==="ok",y=new Qe,x=o.getEndpoint(g.function),v=g.returnDataParts.map(z=>Buffer.from(z)),$=y.buffersToValues(v,x.output),{values:O,results:N}=await zt(n,$),C=d.getNextInfo(n,e,N,this.config);return{success:h,warp:n,action:e,user:this.config.user?.wallet||null,txHash:null,next:C,values:O,results:N,messages:this.getPreparedMessages(n,N)}}async executeCollect(t,e,r,n){let a=d.prepareVars(t,this.config),i=L(a,e);if(!i)throw new Error("WarpActionExecutor: Action not found");let o=await this.getResolvedInputs(i,r),c=this.getModifiedInputs(o),p=g=>{if(!g.value)return null;let h=this.serializer.stringToNative(g.value)[1];if(g.input.type==="biguint")return h.toString();if(g.input.type==="esdt"){let y=h;return{token:y.token.identifier,nonce:y.token.nonce.toString(),amount:y.amount.toString()}}else return h},u=new Headers;u.set("Content-Type","application/json"),u.set("Accept","application/json"),Object.entries(i.destination.headers||{}).forEach(([g,h])=>{u.set(g,h)});let f=Object.fromEntries(c.map(g=>[g.input.as||g.input.name,p(g)])),m=i.destination.method||"GET",T=m==="GET"?void 0:JSON.stringify({inputs:f,meta:n});try{let g=await fetch(i.destination.url,{method:m,headers:u,body:T}),h=await g.json(),{values:y,results:x}=await Kt(a,h),v=d.getNextInfo(a,e,x,this.config);return{success:g.ok,warp:a,action:e,user:this.config.user?.wallet||null,txHash:null,next:v,values:y,results:x,messages:this.getPreparedMessages(a,x)}}catch(g){return console.error(g),{success:!1,warp:a,action:e,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{},messages:{}}}}async getTxComponentsFromInputs(t,e,r){let n=await this.getResolvedInputs(t,e),a=this.getModifiedInputs(n),i=a.find(C=>C.input.position==="receiver")?.value,o="address"in t?t.address:null,c=i?.split(":")[1]||o||r?.toBech32();if(!c)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let p=ut.newFromBech32(c),u=this.getPreparedArgs(t,a),f=a.find(C=>C.input.position==="value")?.value||null,m="value"in t?t.value:null,T=BigInt(f?.split(":")[1]||m||0),g=a.filter(C=>C.input.position==="transfer"&&C.value).map(C=>C.value),y=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...g?.map(C=>this.serializer.stringToNative(C)[1])||[]],x=a.find(C=>C.input.position==="data")?.value,v="data"in t?t.data||"":null,$=x||v||null,O=$?this.serializer.stringToTyped($).valueOf():null,N=O?Buffer.from(O):null;return{destination:p,args:u,value:T,transfers:y,data:N}}async getResolvedInputs(t,e){let r=t.inputs||[],n=await Promise.all(e.map(i=>this.preprocessInput(i))),a=(i,o)=>{if(i.source==="query"){let c=this.url.searchParams.get(i.name);return c?this.serializer.nativeToString(i.type,c):null}else return i.source===l.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:n[o]||null};return r.map((i,o)=>({input:i,value:a(i,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 a=Number(t.find(c=>c.input.name===n)?.value?.split(":")[1]);if(!a)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let i=e.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let o=_(i,+a);return{...e,value:`${e.input.type}:${o}`}}else{let a=e.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let i=_(a,+n);return{...e,value:`${e.input.type}:${i}`}}}else return e})}async preprocessInput(t){try{let[e,r]=t.split(l.ArgParamsSeparator,2);if(e==="esdt"){let[n,a,i,o]=r.split(l.ArgCompositeSeparator);if(o)return t;let c=new Jt({identifier:n,nonce:BigInt(a)});if(!new Ke().isFungible(c))return t;let f=Gt(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 m=new Xt({token:c,amount:_(i,f)});return this.serializer.nativeToString(e,m)+l.ArgCompositeSeparator+f}return t}catch{return t}}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=I(this.config),r=await this.contractLoader.getVerificationInfo(t.address,e);if(!r)throw new Error("WarpActionExecutor: Verification info not found");return pt.create(r.abi)}getPreparedArgs(t,e){let r="args"in t?t.args||[]:[];return e.forEach(({input:n,value:a})=>{if(!a||!n.position?.startsWith("arg:"))return;let i=Number(n.position.split(":")[1])-1;r.splice(i,0,a)}),r}getPreparedMessages(t,e){let r=Object.entries(t.messages||{}).map(([n,a])=>[n,D(a,e)]);return Object.fromEntries(r)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(l.IdentifierType.Hash)){let e=new H(this.config),r=t.abi.split(l.IdentifierParamSeparator)[1],n=await e.createFromTransactionHash(r);if(!n)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return pt.create(n.content)}else{let r=await(await fetch(t.abi)).json();return pt.create(r)}}toTypedTransfer(t){return new Xt({token:new Jt({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};import{Address as Zt,TransactionsFactoryConfig as Ye,TransferTransactionsFactory as Ze}from"@multiversx/sdk-core";import Xe from"ajv";var j=class{constructor(t){this.config=t;this.config=t}async validate(t){let e=[];return e.push(...this.validateMaxOneValuePosition(t)),e.push(...this.validateVariableNamesAndResultNamesUppercase(t)),e.push(...this.validateAbiIsSetIfApplicable(t)),e.push(...await this.validateSchema(t)),{valid:e.length===0,errors:e}}validateMaxOneValuePosition(t){return t.actions.filter(r=>r.inputs?r.inputs.some(n=>n.position==="value"):!1).length>1?["Only one value position action is allowed"]:[]}validateVariableNamesAndResultNamesUppercase(t){let e=[],r=(n,a)=>{n&&Object.keys(n).forEach(i=>{i!==i.toUpperCase()&&e.push(`${a} name '${i}' must be uppercase`)})};return r(t.vars,"Variable"),r(t.results,"Result"),e}validateAbiIsSetIfApplicable(t){let e=t.actions.some(a=>a.type==="contract"),r=t.actions.some(a=>a.type==="query");if(!e&&!r)return[];let n=t.actions.some(a=>a.abi);return t.results&&!n?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.warpSchemaUrl||w.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),a=new Xe,i=a.compile(n);return i(t)?[]:[`Schema validation failed: ${a.errorsText(i.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var Q=class{constructor(t){this.pendingWarp={protocol:V("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t,this.cache=new E(t.cacheType)}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=new Ye({chainID:S(this.config.env)}),r=new Ze({config:e}),n=Zt.newFromBech32(this.config.user.wallet),a=JSON.stringify(t),i=r.createTransactionForTransfer(n,{receiver:Zt.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(a))});return i.gasLimit=i.gasLimit+BigInt(2e6),i}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.validate(r),d.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.toBech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=B.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=I(this.config),i=d.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await i.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 this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return ft(t,e)}ensure(t,e){if(!t)throw new Error(e)}async validate(t){let r=await new j(this.config).validate(t);if(!r.valid)throw new Error(r.errors.join(`
2
+ `))}};var te=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 tr from"qr-code-styling";var ee=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(l.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)),i=(await Promise.all(n)).filter(p=>p.match),o=i.length>0,c=i.map(p=>({url:p.url,warp:p.warp}));return{match:o,results:c}}async detect(t){let e=t.startsWith(l.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):d.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:n}=e,a=new Q(this.config),i=new R(this.config),o=null,c=null,p=null;if(r==="hash"){o=await a.createFromTransactionHash(n);try{let{registryInfo:u,brand:f}=await i.getInfoByHash(n);c=u,p=f}catch{}}else if(r==="alias"){let{registryInfo:u,brand:f}=await i.getInfoByAlias(n);c=u,p=f,u&&(o=await a.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||w.DefaultClientUrl(this.config.env),n=t===l.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+l.IdentifierParamSeparator+e);return w.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${l.IdentifierParamName}=${n}`}buildFromPrefixedIdentifier(t){let e=d.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.id):""}generateQrCode(t,e,r=512,n="white",a="black",i="#23F7DD"){let o=this.build(t,e);return new tr({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:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(i)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=w.SuperClientUrls.includes(e.origin),n=e.searchParams.get(l.IdentifierParamName),a=r&&!n?e.pathname.split("/")[1]:n;if(!a)return null;let i=decodeURIComponent(a);return d.getInfoFromPrefixedIdentifier(i)}};export{wt as BrandBuilder,B as CacheKey,w as Config,H as WarpAbiBuilder,Yt as WarpActionExecutor,U as WarpArgSerializer,Q as WarpBuilder,E as WarpCache,l as WarpConstants,M as WarpContractLoader,te as WarpIndex,ee as WarpLink,P as WarpProtocolVersions,R as WarpRegistry,d as WarpUtils,j as WarpValidator,sn as address,nn as biguint,an as boolean,un as codemeta,Xr as composite,pn as esdt,S as getChainId,V as getLatestProtocolIdentifier,I as getMainChainInfo,L as getWarpActionByIndex,cn as hex,Gr as list,ln as nothing,zr as option,Kr as optional,D as replacePlaceholders,_ as shiftBigintBy,Yr as string,ft as toPreviewText,lt as toTypedChainInfo,q as toTypedRegistryInfo,on as token,tn as u16,en as u32,rn as u64,Zr as u8,Jr as variadic};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "2.0.0-alpha.16",
3
+ "version": "2.0.0-alpha.18",
4
4
  "description": "",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",