@vleap/warps 3.0.0-alpha.22 → 3.0.0-alpha.24

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
@@ -454,7 +454,6 @@ declare class WarpActionExecutor {
454
454
  executeQuery(warp: Warp, actionIndex: number, inputs: string[]): Promise<WarpExecution>;
455
455
  executeCollect(warp: Warp, actionIndex: number, inputs: string[], extra?: Record<string, any>): Promise<WarpExecution>;
456
456
  getTxComponentsFromInputs(action: WarpTransferAction | WarpContractAction | WarpQueryAction, inputs: string[], sender?: Address): Promise<TxComponents>;
457
- private getChainForActionWithInputs;
458
457
  getResolvedInputs(chain: WarpChainInfo, action: WarpAction, inputArgs: string[]): Promise<ResolvedInput[]>;
459
458
  getModifiedInputs(inputs: ResolvedInput[]): ResolvedInput[];
460
459
  preprocessInput(chain: WarpChainInfo, input: string): Promise<string>;
@@ -582,7 +581,9 @@ declare class WarpUtils {
582
581
  static getNextInfo(config: WarpInitConfig, warp: Warp, actionIndex: number, results: WarpExecutionResults): WarpExecutionNextInfo | null;
583
582
  private static buildNextUrl;
584
583
  private static getNestedValue;
585
- static getChainInfoForAction(config: WarpInitConfig, action: WarpAction): Promise<WarpChainInfo>;
584
+ static getChainInfoForAction(config: WarpInitConfig, action: WarpAction, inputs?: string[]): Promise<WarpChainInfo>;
585
+ private static tryGetChainFromInputs;
586
+ private static getDefaultChainInfo;
586
587
  static getChainEntrypoint(chainInfo: WarpChainInfo, env: WarpChainEnv): NetworkEntrypoint;
587
588
  }
588
589
 
package/dist/index.d.ts CHANGED
@@ -454,7 +454,6 @@ declare class WarpActionExecutor {
454
454
  executeQuery(warp: Warp, actionIndex: number, inputs: string[]): Promise<WarpExecution>;
455
455
  executeCollect(warp: Warp, actionIndex: number, inputs: string[], extra?: Record<string, any>): Promise<WarpExecution>;
456
456
  getTxComponentsFromInputs(action: WarpTransferAction | WarpContractAction | WarpQueryAction, inputs: string[], sender?: Address): Promise<TxComponents>;
457
- private getChainForActionWithInputs;
458
457
  getResolvedInputs(chain: WarpChainInfo, action: WarpAction, inputArgs: string[]): Promise<ResolvedInput[]>;
459
458
  getModifiedInputs(inputs: ResolvedInput[]): ResolvedInput[];
460
459
  preprocessInput(chain: WarpChainInfo, input: string): Promise<string>;
@@ -582,7 +581,9 @@ declare class WarpUtils {
582
581
  static getNextInfo(config: WarpInitConfig, warp: Warp, actionIndex: number, results: WarpExecutionResults): WarpExecutionNextInfo | null;
583
582
  private static buildNextUrl;
584
583
  private static getNestedValue;
585
- static getChainInfoForAction(config: WarpInitConfig, action: WarpAction): Promise<WarpChainInfo>;
584
+ static getChainInfoForAction(config: WarpInitConfig, action: WarpAction, inputs?: string[]): Promise<WarpChainInfo>;
585
+ private static tryGetChainFromInputs;
586
+ private static getDefaultChainInfo;
586
587
  static getChainEntrypoint(chainInfo: WarpChainInfo, env: WarpChainEnv): NetworkEntrypoint;
587
588
  }
588
589
 
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Pt=Object.create;var at=Object.defineProperty;var Vt=Object.getOwnPropertyDescriptor;var Ut=Object.getOwnPropertyNames;var Nt=Object.getPrototypeOf,Ft=Object.prototype.hasOwnProperty;var kt=(i,t)=>()=>(i&&(t=i(i=0)),t);var wt=(i,t)=>{for(var e in t)at(i,e,{get:t[e],enumerable:!0})},Wt=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ut(t))!Ft.call(i,n)&&n!==e&&at(i,n,{get:()=>t[n],enumerable:!(r=Vt(t,n))||r.enumerable});return i};var ut=(i,t,e)=>(e=i!=null?Pt(Nt(i)):{},Wt(t||!i||!i.__esModule?at(e,"default",{value:i,enumerable:!0}):e,i)),Ot=i=>Wt(at({},"__esModule",{value:!0}),i);var At={};wt(At,{runInVm:()=>ne});var ne,xt=kt(()=>{"use strict";ne=async(i,t)=>{if(typeof window>"u"){let e;try{e=require("vm2").VM}catch{throw new Error('The optional dependency "vm2" is not installed. To use runInVm in Node.js, please install vm2: npm install vm2 --save. This is not required for browser usage.')}let r=new e({timeout:1e3,sandbox:{result:t},eval:!1,wasm:!1});return i.trim().startsWith("(")&&i.includes("=>")?r.run(`(${i})(result)`):null}return new Promise((e,r)=>{try{let n=new Blob([`
1
+ "use strict";var Ut=Object.create;var ot=Object.defineProperty;var Nt=Object.getOwnPropertyDescriptor;var Ft=Object.getOwnPropertyNames;var kt=Object.getPrototypeOf,Ot=Object.prototype.hasOwnProperty;var $t=(i,t)=>()=>(i&&(t=i(i=0)),t);var Wt=(i,t)=>{for(var e in t)ot(i,e,{get:t[e],enumerable:!0})},Ct=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ft(t))!Ot.call(i,n)&&n!==e&&ot(i,n,{get:()=>t[n],enumerable:!(r=Nt(t,n))||r.enumerable});return i};var lt=(i,t,e)=>(e=i!=null?Ut(kt(i)):{},Ct(t||!i||!i.__esModule?ot(e,"default",{value:i,enumerable:!0}):e,i)),Lt=i=>Ct(ot({},"__esModule",{value:!0}),i);var xt={};Wt(xt,{runInVm:()=>ae});var ae,Bt=$t(()=>{"use strict";ae=async(i,t)=>{if(typeof window>"u"){let e;try{e=require("vm2").VM}catch{throw new Error('The optional dependency "vm2" is not installed. To use runInVm in Node.js, please install vm2: npm install vm2 --save. This is not required for browser usage.')}let r=new e({timeout:1e3,sandbox:{result:t},eval:!1,wasm:!1});return i.trim().startsWith("(")&&i.includes("=>")?r.run(`(${i})(result)`):null}return new Promise((e,r)=>{try{let n=new Blob([`
2
2
  self.onmessage = function(e) {
3
3
  try {
4
4
  const result = e.data;
@@ -8,5 +8,5 @@
8
8
  self.postMessage({ error: error.toString() });
9
9
  }
10
10
  };
11
- `],{type:"application/javascript"}),s=URL.createObjectURL(n),a=new Worker(s);a.onmessage=function(o){o.data.error?r(new Error(o.data.error)):e(o.data.result),a.terminate(),URL.revokeObjectURL(s)},a.onerror=function(o){r(new Error(`Error in transform: ${o.message}`)),a.terminate(),URL.revokeObjectURL(s)},a.postMessage(t)}catch(n){return r(n)}})}});var ce={};wt(ce,{BrandBuilder:()=>gt,CacheKey:()=>E,CacheTtl:()=>Z,WarpAbiBuilder:()=>nt,WarpActionExecutor:()=>ht,WarpArgSerializer:()=>L,WarpBuilder:()=>et,WarpCache:()=>V,WarpConfig:()=>A,WarpConstants:()=>f,WarpContractLoader:()=>it,WarpIndex:()=>yt,WarpInterpolator:()=>F,WarpLink:()=>rt,WarpProtocolVersions:()=>_,WarpRegistry:()=>k,WarpUtils:()=>T,WarpValidator:()=>tt,address:()=>Jt,biguint:()=>zt,boolean:()=>Kt,codemeta:()=>te,composite:()=>Ht,esdt:()=>Zt,getChainExplorerUrl:()=>$t,getLatestProtocolIdentifier:()=>q,getMainChainInfo:()=>x,getWarpActionByIndex:()=>O,hex:()=>Yt,list:()=>Mt,nothing:()=>ee,option:()=>_t,optional:()=>qt,replacePlaceholders:()=>J,shiftBigintBy:()=>K,string:()=>N,toPreviewText:()=>lt,toTypedChainInfo:()=>st,token:()=>Xt,u16:()=>Qt,u32:()=>dt,u64:()=>Gt,u8:()=>jt,variadic:()=>Dt});module.exports=Ot(ce);var D=require("@multiversx/sdk-core"),vt=ut(require("ajv"));var f={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:i=>i.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:i=>i.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:i=>i.chain.explorerUrl}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"},Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}};var _={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},A={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${_.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/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:{Name:"multiversx",DisplayName:"MultiversX",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",BlockTime:i=>6e3,AddressHrp:"erd",ChainId:i=>i==="devnet"?"D":i==="testnet"?"T":"1",NativeToken:"EGLD"},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 x=i=>({name:A.MainChain.Name,displayName:A.MainChain.DisplayName,chainId:A.MainChain.ChainId(i.env),blockTime:A.MainChain.BlockTime(i.env),addressHrp:A.MainChain.AddressHrp,apiUrl:A.MainChain.ApiUrl(i.env),explorerUrl:A.MainChain.ExplorerUrl(i.env),nativeToken:A.MainChain.NativeToken}),$t=(i,t)=>i.explorerUrl+(t?"/"+t:""),q=i=>{if(i==="warp")return`warp:${_.Warp}`;if(i==="brand")return`brand:${_.Brand}`;if(i==="abi")return`abi:${_.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${i}`)},O=(i,t)=>i?.actions[t-1],st=i=>({name:i.name.toString(),displayName:i.display_name.toString(),chainId:i.chain_id.toString(),blockTime:i.block_time.toNumber(),addressHrp:i.address_hrp.toString(),apiUrl:i.api_url.toString(),explorerUrl:i.explorer_url.toString(),nativeToken:i.native_token.toString()}),K=(i,t)=>{let e=i.toString(),[r,n=""]=e.split("."),s=Math.abs(t);if(t>0)return BigInt(r+n.padEnd(s,"0"));if(t<0){let a=r+n;if(s>=a.length)return 0n;let o=a.slice(0,-s)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},lt=(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},J=(i,t)=>i.replace(/\{\{([^}]+)\}\}/g,(e,r)=>t[r]||"");var j=class j{static info(...t){j.isTestEnv||console.info(...t)}static warn(...t){j.isTestEnv||console.warn(...t)}static error(...t){j.isTestEnv||console.error(...t)}};j.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=j;var Q=require("@multiversx/sdk-core");var X=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))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var $=class ${get(t){let e=$.cache.get(t);return e?Date.now()>e.expiresAt?($.cache.delete(t),null):e.value:null}set(t,e,r){let n=Date.now()+r*1e3;$.cache.set(t,{value:e,expiresAt:n})}forget(t){$.cache.delete(t)}clear(){$.cache.clear()}};$.cache=new Map;var Y=$;var Z={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},E={Warp:(i,t)=>`warp:${i}:${t}`,WarpAbi:(i,t)=>`warp-abi:${i}:${t}`,LastWarpExecutionInputs:(i,t,e)=>`warp-exec-inputs:${i}:${t}:${e}`,RegistryInfo:(i,t)=>`registry-info:${i}:${t}`,Brand:(i,t)=>`brand:${i}:${t}`,ChainInfo:(i,t)=>`chain:${i}:${t}`,ChainInfos:i=>`chains:${i}`},V=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new X:t==="memory"?new Y:typeof window<"u"&&window.localStorage?new X:new Y}set(t,e,r){this.strategy.set(t,e,r)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var It=ut(require("qr-code-styling"));var M=require("@multiversx/sdk-core");var Ct=ut(require("ajv"));var tt=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,s)=>{n&&Object.keys(n).forEach(a=>{a!==a.toUpperCase()&&e.push(`${s} name '${a}' 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),s=Object.values(t.results||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.results&&!n&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||A.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),s=new Ct.default({strict:!1}),a=s.compile(n);return a(t)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var et=class{constructor(t){this.pendingWarp={protocol:q("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t,this.cache=new V(t.cache?.type)}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=x(this.config),r=new M.TransactionsFactoryConfig({chainID:e.chainId}),n=new M.TransferTransactionsFactory({config:r}),s=M.Address.newFromBech32(this.config.user.wallet),a=JSON.stringify(t),o=n.createTransactionForTransfer(s,{receiver:M.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),r}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=E.Warp(this.config.env,t);if(e){let o=this.cache.get(r);if(o)return C.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),o}let n=x(this.config),a=T.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await a.getTransaction(t),u=await this.createFromTransaction(o);return e&&e.ttl&&u&&this.cache.set(r,u,e.ttl),u}catch(o){return C.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 lt(t,e)}ensure(t,e){if(!t)throw new Error(e)}async validate(t){let r=await new tt(this.config).validate(t);if(!r.valid)throw new Error(r.errors.join(`
12
- `))}};var F=class{static async apply(t,e){let r=this.applyVars(t,e);return await this.applyGlobals(t,r)}static async applyGlobals(t,e){let r={...e};return r.actions=await Promise.all(r.actions.map(async n=>await this.applyActionGlobals(t,n))),r=await this.applyRootGlobals(r,t),r}static applyVars(t,e){if(!e?.vars)return e;let r=JSON.stringify(e),n=(s,a)=>{r=r.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),a.toString())};return Object.entries(e.vars).forEach(([s,a])=>{if(typeof a!="string")n(s,a);else if(a.startsWith(`${f.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=a.split(`${f.Vars.Query}:`)[1],u=new URLSearchParams(t.currentUrl.split("?")[1]).get(o);u&&n(s,u)}else if(a.startsWith(`${f.Vars.Env}:`)){let o=a.split(`${f.Vars.Env}:`)[1],u=t.vars?.[o];u&&n(s,u)}else a===f.Source.UserWallet&&t.user?.wallet?n(s,t.user.wallet):n(s,a)}),JSON.parse(r)}static async applyRootGlobals(t,e){let r=JSON.stringify(t),n={config:e,chain:x(e)};return Object.values(f.Globals).forEach(s=>{let a=s.Accessor(n);a!=null&&(r=r.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),a.toString()))}),JSON.parse(r)}static async applyActionGlobals(t,e){let r=await T.getChainInfoForAction(t,e),n=JSON.stringify(e),s={config:t,chain:r};return Object.values(f.Globals).forEach(a=>{let o=a.Accessor(s);o!=null&&(n=n.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(n)}};var m=require("@multiversx/sdk-core/out");var ft={buildInfo:{rustc:{version:"1.86.0",commitHash:"05f9846f893b09a1be1fc8560e33fc3c815cfecb",commitDate:"2025-03-31",channel:"Stable",short:"rustc 1.86.0 (05f9846f8 2025-03-31)"},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:"forceRemoveAlias",mutability:"mutable",inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"verifyWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"transferOwnership",mutability:"mutable",inputs:[{name:"warp",type:"bytes"},{name:"new_owner",type:"Address"}],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:"addAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"removeAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"ConfigView"}]},{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}]},{name:"setChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"},{name:"native_token",type:"bytes"}],outputs:[]},{name:"removeChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"}],outputs:[]},{name:"getChain",mutability:"readonly",inputs:[{name:"name",type:"bytes"}],outputs:[{type:"ChainView"}]},{name:"getChains",mutability:"readonly",inputs:[],outputs:[{type:"variadic<ChainView>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0},{name:"trust",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},{name:"trust",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}]},{identifier:"ownershipTransferred",inputs:[{name:"warp",type:"bytes",indexed:!0},{name:"old_owner",type:"Address",indexed:!0},{name:"new_owner",type:"Address",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{ChainView:{type:"struct",fields:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"},{name:"native_token",type:"bytes"}]},ConfigView:{type:"struct",fields:[{name:"unit_price",type:"BigUint"},{name:"admins",type:"List<Address>"}]},InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"owner",type:"Address"},{name:"created_at",type:"u64"},{name:"upgraded_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var ot=i=>({hash:i.hash.toString("hex"),alias:i.alias?.toString()||null,trust:i.trust.toString(),owner:i.owner.toString(),createdAt:i.created_at.toNumber(),upgradedAt:i.upgraded_at?.toNumber(),brand:i.brand?.toString("hex")||null,upgrade:i.upgrade?.toString("hex")||null}),Tt=i=>({unitPrice:BigInt(i.unit_price.toString()),admins:i.admins.map(t=>t.toBech32())});var l=require("@multiversx/sdk-core/out"),_t=(i,t)=>i?l.OptionValue.newProvided(i):t?l.OptionValue.newMissingTyped(t):l.OptionValue.newMissing(),qt=(i,t)=>i?new l.OptionalValue(i.getType(),i):t?new l.OptionalValue(t):l.OptionalValue.newMissing(),Mt=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)},Dt=i=>l.VariadicValue.fromItems(...i),Ht=i=>{let t=i.map(e=>e.getType());return new l.CompositeValue(new l.CompositeType(...t),i)},N=i=>l.StringValue.fromUTF8(i),jt=i=>new l.U8Value(i),Qt=i=>new l.U16Value(i),dt=i=>new l.U32Value(i),Gt=i=>new l.U64Value(i),zt=i=>new l.BigUIntValue(BigInt(i)),Kt=i=>new l.BooleanValue(i),Jt=i=>new l.AddressValue(l.Address.newFromBech32(i)),Xt=i=>new l.TokenIdentifierValue(i),Yt=i=>l.BytesValue.fromHex(i),Zt=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")]),te=i=>new l.CodeMetadataValue(l.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(i,"hex")))),ee=()=>new l.NothingValue;var k=class{constructor(t){this.config=t,this.cache=new V(t.cache?.type),this.registryConfig={unitPrice:BigInt(0),admins:[]}}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e,r){if(this.registryConfig.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 n=m.Address.newFromBech32(this.config.user.wallet),s=()=>this.isCurrentUserAdmin()?BigInt(0):e&&r?this.registryConfig.unitPrice*BigInt(3):e?this.registryConfig.unitPrice*BigInt(2):this.registryConfig.unitPrice,a=()=>e&&r?[m.BytesValue.fromHex(t),m.BytesValue.fromUTF8(e),m.BytesValue.fromHex(r)]:e?[m.BytesValue.fromHex(t),m.BytesValue.fromUTF8(e)]:[m.BytesValue.fromHex(t)];return this.getFactory().createTransactionForExecute(n,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:s(),arguments:a()})}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.registryConfig.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.isCurrentUserAdmin()?void 0:this.registryConfig.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.isCurrentUserAdmin()?void 0:this.registryConfig.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)]})}createWarpTransferOwnershipTransaction(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:"transferOwnership",gasLimit:BigInt(1e7),arguments:[m.BytesValue.fromHex(t),new m.AddressValue(new m.Address(e))]})}createBrandRegisterTransaction(t){if(this.registryConfig.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.isCurrentUserAdmin()?void 0:this.registryConfig.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.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[m.BytesValue.fromHex(t),m.BytesValue.fromHex(e)]})}async getInfoByAlias(t,e){try{let r=E.RegistryInfo(this.config.env,t),n=e?this.cache.get(r):null;if(n)return C.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let s=this.getRegistryContractAddress(),a=this.getController(),o=a.createQuery({contract:s,function:"getInfoByAlias",arguments:[m.BytesValue.fromUTF8(t)]}),u=await a.runQuery(o),[p]=a.parseQueryResponse(u),d=p?ot(p):null,g=d?.brand?await this.fetchBrand(d.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:d,brand:g},e.ttl),{registryInfo:d,brand:g}}catch{return{registryInfo:null,brand:null}}}async getInfoByHash(t,e){try{let r=E.RegistryInfo(this.config.env,t);if(e){let g=this.cache.get(r);if(g)return C.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),g}let n=this.getRegistryContractAddress(),s=this.getController(),a=s.createQuery({contract:n,function:"getInfoByHash",arguments:[m.BytesValue.fromHex(t)]}),o=await s.runQuery(a),[u]=s.parseQueryResponse(o),p=u?ot(u):null,d=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:d},e.ttl),{registryInfo:p,brand:d}}catch{return{registryInfo:null,brand:null}}}async getUserWarpRegistryInfos(t){try{let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),s=n.createQuery({contract:r,function:"getUserWarps",arguments:[new m.AddressValue(new m.Address(e))]}),a=await n.runQuery(s),[o]=n.parseQueryResponse(a);return o.map(ot)}catch{return[]}}async getUserBrands(t){try{let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),s=n.createQuery({contract:r,function:"getUserBrands",arguments:[new m.AddressValue(new m.Address(e))]}),a=await n.runQuery(s),[o]=n.parseQueryResponse(a),u=o.map(g=>g.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(u.map(g=>this.fetchBrand(g,p)))).filter(g=>g!==null)}catch{return[]}}async getChainInfos(t){let e=E.ChainInfos(this.config.env);if(t&&t.ttl){let p=this.cache.get(e);if(p)return C.info("WarpRegistry (getChainInfos): ChainInfos found in cache"),p}let r=this.getRegistryContractAddress(),n=this.getController(),s=n.createQuery({contract:r,function:"getChains",arguments:[]}),a=await n.runQuery(s),[o]=n.parseQueryResponse(a),u=o.map(st);if(t&&t.ttl){for(let p of u)this.cache.set(E.ChainInfo(this.config.env,p.chain),p,t.ttl);this.cache.set(e,u,t.ttl)}return u}async getChainInfo(t,e){try{let r=E.ChainInfo(this.config.env,t),n=e?this.cache.get(r):null;if(n)return C.info(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let s=this.getRegistryContractAddress(),a=this.getController(),o=a.createQuery({contract:s,function:"getChain",arguments:[m.BytesValue.fromUTF8(t)]}),u=await a.runQuery(o),[p]=a.parseQueryResponse(u),d=p?st(p):null;return e&&e.ttl&&d&&this.cache.set(r,d,e.ttl),d}catch{return null}}async setChain(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:"setChain",gasLimit:BigInt(1e7),arguments:[N(t.name),N(t.displayName),N(t.chainId),dt(t.blockTime),N(t.addressHrp),N(t.apiUrl),N(t.explorerUrl),N(t.nativeToken)]})}async removeChain(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:"removeChain",gasLimit:BigInt(1e7),arguments:[N(t)]})}async fetchBrand(t,e){let r=E.Brand(this.config.env,t),n=e?this.cache.get(r):null;if(n)return C.info(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let s=x(this.config),o=T.getChainEntrypoint(s,this.config.env).createNetworkProvider();try{let u=await o.getTransaction(t),p=JSON.parse(u.data.toString());return p.meta={hash:u.hash,creator:u.sender.bech32(),createdAt:new Date(u.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,p,e.ttl),p}catch{return null}}getRegistryContractAddress(){return m.Address.newFromBech32(this.config.registry?.contract||A.Registry.Contract(this.config.env))}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),[r]=await e.query({contract:t,function:"getConfig",arguments:[]}),n=r?Tt(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let t=x(this.config),e=new m.TransactionsFactoryConfig({chainID:t.chainId}),r=m.AbiRegistry.create(ft);return new m.SmartContractTransactionsFactory({config:e,abi:r})}getController(){let t=x(this.config),e=T.getChainEntrypoint(t,this.config.env),r=m.AbiRegistry.create(ft);return e.createSmartContractController(r)}isCurrentUserAdmin(){return!!this.config.user?.wallet&&this.registryConfig.admins.includes(this.config.user.wallet)}};var rt=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(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),a=(await Promise.all(n)).filter(p=>p.match),o=a.length>0,u=a.map(p=>({url:p.url,warp:p.warp}));return{match:o,results:u}}async detect(t,e){let r={match:!1,url:t,warp:null,registryInfo:null,brand:null},n=t.startsWith(f.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):T.getInfoFromPrefixedIdentifier(t);if(!n)return r;try{let{type:s,identifierBase:a}=n,o=new et(this.config),u=new k(this.config),p=null,d=null,g=null;if(s==="hash"){p=await o.createFromTransactionHash(a,e);let y=await u.getInfoByHash(a,e);d=y.registryInfo,g=y.brand}else if(s==="alias"){let y=await u.getInfoByAlias(a,e);d=y.registryInfo,g=y.brand,y.registryInfo&&(p=await o.createFromTransactionHash(y.registryInfo.hash,e))}let w=p?await F.apply(this.config,p):null;return w?{match:!0,url:t,warp:w,registryInfo:d,brand:g}:r}catch(s){return C.error("Error detecting warp link",s),r}}build(t,e){let r=this.config.clientUrl||A.DefaultClientUrl(this.config.env),n=t===f.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+f.IdentifierParamSeparator+e);return A.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${f.IdentifierParamName}=${n}`}buildFromPrefixedIdentifier(t){let e=T.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.identifierBase):""}generateQrCode(t,e,r=512,n="white",s="black",a="#23F7DD"){let o=this.build(t,e);return new It.default({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:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(a)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=A.SuperClientUrls.includes(e.origin),n=e.searchParams.get(f.IdentifierParamName),s=r&&!n?e.pathname.split("/")[1]:n;if(!s)return null;let a=decodeURIComponent(s);return T.getInfoFromPrefixedIdentifier(a)}};var re="https://",T=class{static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t);if(e.includes(f.IdentifierParamSeparator)){let[n,s]=e.split(f.IdentifierParamSeparator),a=s.split("?")[0];return{type:n,identifier:s,identifierBase:a}}let r=e.split("?")[0];return r.length===64?{type:f.IdentifierType.Hash,identifier:e,identifierBase:r}:{type:f.IdentifierType.Alias,identifier:e,identifierBase:r}}static getNextInfo(t,e,r,n){let s=e.actions?.[r]?.next||e.next||null;if(!s)return null;if(s.startsWith(re))return[{identifier:null,url:s}];let[a,o]=s.split("?");if(!o)return[{identifier:a,url:this.buildNextUrl(a,t)}];let u=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(u.length===0){let h=J(o,{...e.vars,...n}),W=h?`${a}?${h}`:a;return[{identifier:W,url:this.buildNextUrl(W,t)}]}let p=u[0];if(!p)return[];let d=p.match(/{{([^[]+)\[\]/),g=d?d[1]:null;if(!g||n[g]===void 0)return[];let w=Array.isArray(n[g])?n[g]:[n[g]];if(w.length===0)return[];let y=u.filter(h=>h.includes(`{{${g}[]`)).map(h=>{let W=h.match(/\[\](\.[^}]+)?}}/),b=W&&W[1]||"";return{placeholder:h,field:b?b.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return w.map(h=>{let W=o;for(let{regex:S,field:P}of y){let v=P?this.getNestedValue(h,P):h;if(v==null)return null;W=W.replace(S,v)}if(W.includes("{{")||W.includes("}}"))return null;let b=W?`${a}?${W}`:a;return{identifier:b,url:this.buildNextUrl(b,t)}}).filter(h=>h!==null)}static buildNextUrl(t,e){let[r,n]=t.split("?"),s=this.getInfoFromPrefixedIdentifier(r)||{type:"alias",identifier:r,identifierBase:r},o=new rt(e).build(s.type,s.identifierBase);if(!n)return o;let u=new URL(o);return new URLSearchParams(n).forEach((p,d)=>u.searchParams.set(d,p)),u.toString().replace(/\/\?/,"?")}static getNestedValue(t,e){return e.split(".").reduce((r,n)=>r?.[n],t)}static async getChainInfoForAction(t,e){if(!e.chain)return x(t);let r=await new k(t).getChainInfo(e.chain,{ttl:Z.OneWeek});if(!r)throw new Error(`WarpActionExecutor: Chain info not found for ${e.chain}`);return r}static getChainEntrypoint(t,e){let r="warp-sdk",n="api";return e==="devnet"?new Q.DevnetEntrypoint(t.apiUrl,n,r):e==="testnet"?new Q.TestnetEntrypoint(t.apiUrl,n,r):new Q.MainnetEntrypoint(t.apiUrl,n,r)}};var gt=class{constructor(t){this.pendingBrand={protocol:q("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=x(this.config),r=new D.TransactionsFactoryConfig({chainID:e.chainId}),n=new D.TransferTransactionsFactory({config:r}),s=D.Address.newFromBech32(this.config.user.wallet),a=JSON.stringify(t);return n.createTransactionForNativeTokenTransfer(s,{receiver:D.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=x(this.config),n=T.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let s=await n.getTransaction(t);return this.createFromTransaction(s)}catch(s){return C.error("BrandBuilder: Error creating from transaction hash",s),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.schema?.brand||A.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),s=new vt.default({strict:!1}),a=s.compile(n);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};var G=require("@multiversx/sdk-core");var nt=class{constructor(t){this.cache=new V;this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=x(this.config),r=new G.TransactionsFactoryConfig({chainID:e.chainId}),n=new G.TransferTransactionsFactory({config:r}),s={protocol:q("abi"),content:t},a=G.Address.newFromBech32(this.config.user.wallet),o=JSON.stringify(s),u=n.createTransactionForTransfer(a,{receiver:a,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(o))});return u.gasLimit=u.gasLimit+BigInt(2e6),u}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=E.WarpAbi(this.config.env,t);if(e){let o=this.cache.get(r);if(o)return C.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),o}let n=x(this.config),a=T.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await a.getTransaction(t),u=await this.createFromTransaction(o);return e&&e.ttl&&u&&this.cache.set(r,u,e.ttl),u}catch(o){return C.error("WarpAbiBuilder: Error creating from transaction hash",o),null}}};var I=require("@multiversx/sdk-core");var z=require("@multiversx/sdk-core/out");var c=require("@multiversx/sdk-core/out");var bt=new RegExp(`${f.ArgParamsSeparator}(.*)`),L=class{nativeToString(t,e){return t==="esdt"&&e instanceof c.TokenTransfer?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(c.OptionValue.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(c.OptionalValue.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(c.List.ClassName)){let e=t.getItems(),n=e.map(a=>this.typedToString(a).split(f.ArgParamsSeparator)[0])[0],s=e.map(a=>this.typedToString(a).split(f.ArgParamsSeparator)[1]);return`list:${n}:${s.join(",")}`}if(t.hasClassOrSuperclass(c.VariadicValue.ClassName)){let e=t.getItems(),n=e.map(a=>this.typedToString(a).split(f.ArgParamsSeparator)[0])[0],s=e.map(a=>this.typedToString(a).split(f.ArgParamsSeparator)[1]);return`variadic:${n}:${s.join(",")}`}if(t.hasClassOrSuperclass(c.CompositeValue.ClassName)){let e=t.getItems(),r=e.map(o=>this.typedToString(o).split(f.ArgParamsSeparator)[0]),n=e.map(o=>this.typedToString(o).split(f.ArgParamsSeparator)[1]),s=r.join(f.ArgCompositeSeparator),a=n.join(f.ArgCompositeSeparator);return`composite(${s}):${a}`}if(t.hasClassOrSuperclass(c.BigUIntValue.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(c.U8Value.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(c.U16Value.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(c.U32Value.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(c.U64Value.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(c.StringValue.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(c.BooleanValue.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(c.AddressValue.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(c.TokenIdentifierValue.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(c.BytesValue.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(c.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 c.CompositeType(...e.split(f.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new c.StringType;if(t==="uint8")return new c.U8Type;if(t==="uint16")return new c.U16Type;if(t==="uint32")return new c.U32Type;if(t==="uint64")return new c.U64Type;if(t==="biguint")return new c.BigUIntType;if(t==="bool")return new c.BooleanType;if(t==="address")return new c.AddressType;if(t==="token")return new c.TokenIdentifierType;if(t==="hex")return new c.BytesType;if(t==="codemeta")return new c.CodeMetadataType;if(t==="esdt"||t==="nft")return new c.StructType("EsdtTokenPayment",[new c.FieldDefinition("token_identifier","",new c.TokenIdentifierType),new c.FieldDefinition("token_nonce","",new c.U64Type),new c.FieldDefinition("amount","",new c.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[s,a]=n.split(f.ArgParamsSeparator);return[`option:${s}`,a||null]}else if(r==="optional"){let[s,a]=n.split(f.ArgParamsSeparator);return[`optional:${s}`,a||null]}else if(r==="list"){let s=n.split(f.ArgParamsSeparator),a=s.slice(0,-1).join(f.ArgParamsSeparator),o=s[s.length-1],p=(o?o.split(","):[]).map(d=>this.stringToNative(`${a}:${d}`)[1]);return[`list:${a}`,p]}else if(r==="variadic"){let s=n.split(f.ArgParamsSeparator),a=s.slice(0,-1).join(f.ArgParamsSeparator),o=s[s.length-1],p=(o?o.split(","):[]).map(d=>this.stringToNative(`${a}:${d}`)[1]);return[`variadic:${a}`,p]}else if(r.startsWith("composite")){let s=r.match(/\(([^)]+)\)/)?.[1]?.split(f.ArgCompositeSeparator),o=n.split(f.ArgCompositeSeparator).map((u,p)=>this.stringToNative(`${s[p]}:${u}`)[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[s,a,o]=n.split(f.ArgCompositeSeparator);return[r,new c.TokenTransfer({token:new c.Token({identifier:s,nonce:BigInt(a)}),amount:BigInt(o)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new c.NothingValue;if(e==="option"){let n=this.stringToTyped(r);return n instanceof c.NothingValue?c.OptionValue.newMissingTyped(n.getType()):c.OptionValue.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof c.NothingValue?c.OptionalValue.newMissing():new c.OptionalValue(n.getType(),n)}if(e==="list"){let[n,s]=r.split(bt,2),o=s.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new c.List(this.nativeToType(n),o)}if(e==="variadic"){let[n,s]=r.split(bt,2),o=s.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new c.VariadicValue(new c.VariadicType(this.nativeToType(n)),o)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],s=r.split(f.ArgCompositeSeparator),a=n.split(f.ArgCompositeSeparator),o=s.map((p,d)=>this.stringToTyped(`${a[d]}:${p}`)),u=o.map(p=>p.getType());return new c.CompositeValue(new c.CompositeType(...u),o)}if(e==="string")return r?c.StringValue.fromUTF8(r):new c.NothingValue;if(e==="uint8")return r?new c.U8Value(Number(r)):new c.NothingValue;if(e==="uint16")return r?new c.U16Value(Number(r)):new c.NothingValue;if(e==="uint32")return r?new c.U32Value(Number(r)):new c.NothingValue;if(e==="uint64")return r?new c.U64Value(BigInt(r)):new c.NothingValue;if(e==="biguint")return r?new c.BigUIntValue(BigInt(r)):new c.NothingValue;if(e==="bool")return r?new c.BooleanValue(typeof r=="boolean"?r:r==="true"):new c.NothingValue;if(e==="address")return r?new c.AddressValue(c.Address.newFromBech32(r)):new c.NothingValue;if(e==="token")return r?new c.TokenIdentifierValue(r):new c.NothingValue;if(e==="hex")return r?c.BytesValue.fromHex(r):new c.NothingValue;if(e==="codemeta")return new c.CodeMetadataValue(c.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(f.ArgCompositeSeparator);return new c.Struct(this.nativeToType("esdt"),[new c.Field(new c.TokenIdentifierValue(n[0]),"token_identifier"),new c.Field(new c.U64Value(BigInt(n[1])),"token_nonce"),new c.Field(new c.BigUIntValue(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof c.OptionType)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof c.OptionalType)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof c.ListType)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof c.VariadicType)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof c.StringType)return"string";if(t instanceof c.U8Type)return"uint8";if(t instanceof c.U16Type)return"uint16";if(t instanceof c.U32Type)return"uint32";if(t instanceof c.U64Type)return"uint64";if(t instanceof c.BigUIntType)return"biguint";if(t instanceof c.BooleanType)return"bool";if(t instanceof c.AddressType)return"address";if(t instanceof c.TokenIdentifierType)return"token";if(t instanceof c.BytesType)return"hex";if(t instanceof c.CodeMetadataType)return"codemeta";if(t instanceof c.StructType&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var mt=i=>{if(i==="out")return 1;let t=i.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(i.startsWith("out.")||i.startsWith("event."),null)},ie=(i,t)=>t.reduce((e,r)=>e&&e[r]!==void 0?e[r]:null,i),Bt=async(i,t,e,r,n,s)=>{let a=[],o={};if(!t.results||e.type!=="contract")return{values:a,results:o};if(!Object.values(t.results).some(y=>y.includes("out")||y.includes("event"))){for(let[y,B]of Object.entries(t.results))o[y]=B;return{values:a,results:await ct(t,o,n,s)}}let p=await i.getAbiForAction(e),d=new z.TransactionEventsParser({abi:p}),w=new z.SmartContractTransactionsOutcomeParser({abi:p}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[y,B]of Object.entries(t.results)){if(B.startsWith(f.Transform.Prefix))continue;if(B.startsWith("input.")){o[y]=B;continue}let h=mt(B);if(h!==null&&h!==n){o[y]=null;continue}let[W,b,S]=B.split(".");if(W==="event"){if(!b||isNaN(Number(S)))continue;let P=Number(S),v=(0,z.findEventsByFirstTopic)(r,b),H=d.parseEvents({events:v})[0],U=Object.values(H)[P]||null;a.push(U),o[y]=U&&U.valueOf()}else if(W==="out"||W.startsWith("out[")){if(!b)continue;let P=Number(b),v=w.values[P-1]||null;S&&(v=v[S]||null),v&&typeof v=="object"&&(v="toFixed"in v?v.toFixed():v.valueOf()),a.push(v),o[y]=v&&v.valueOf()}else o[y]=B}return{values:a,results:await ct(t,o,n,s)}},Et=async(i,t,e,r)=>{let n=new L,s=t.map(p=>n.typedToString(p)),a=t.map(p=>n.typedToNative(p)[1]),o={};if(!i.results)return{values:s,results:o};let u=p=>{let d=p.split(".").slice(1).map(w=>parseInt(w)-1);if(d.length===0)return;let g=a[d[0]];for(let w=1;w<d.length;w++){if(g==null)return;g=g[d[w]]}return g};for(let[p,d]of Object.entries(i.results)){if(d.startsWith(f.Transform.Prefix))continue;let g=mt(d);if(g!==null&&g!==e){o[p]=null;continue}d.startsWith("out.")||d==="out"||d.startsWith("out[")?o[p]=u(d)||null:o[p]=d}return{values:s,results:await ct(i,o,e,r)}},St=async(i,t,e,r)=>{let n=[],s={};for(let[a,o]of Object.entries(i.results||{})){if(o.startsWith(f.Transform.Prefix))continue;let u=mt(o);if(u!==null&&u!==e){s[a]=null;continue}let[p,...d]=o.split(".");if(p==="out"||p.startsWith("out[")){let g=d.length===0?t?.data||t:ie(t,d);n.push(g),s[a]=g}else s[a]=o}return{values:n,results:await ct(i,s,e,r)}};var ct=async(i,t,e,r)=>{if(!i.results)return t;let n={...t};return n=ae(n,i,e,r),n=await se(i,n),n},ae=(i,t,e,r)=>{let n={...i},s=O(t,e)?.inputs||[],a=new L;for(let[o,u]of Object.entries(n))if(typeof u=="string"&&u.startsWith("input.")){let p=u.split(".")[1],d=s.findIndex(w=>w.as===p||w.name===p),g=d!==-1?r[d]?.value:null;n[o]=g?a.stringToNative(g)[1]:null}return n},se=async(i,t)=>{if(!i.results)return t;let e={...t},r=Object.entries(i.results).filter(([,n])=>n.startsWith(f.Transform.Prefix)).map(([n,s])=>({key:n,code:s.substring(f.Transform.Prefix.length)}));for(let{key:n,code:s}of r)try{let{runInVm:a}=await Promise.resolve().then(()=>(xt(),At));e[n]=await a(s,e)}catch(a){C.error(`Transform error for result '${n}':`,a),e[n]=null}return e};var oe=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],Rt=i=>oe.find(t=>t.id===i)||null;var it=class{constructor(t){this.config=t}async getContract(t,e){try{let s=await T.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}`);return{address:t,owner:s.ownerAddress,verified:s.isVerified||!1}}catch(r){return C.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t,e){try{let s=await T.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}/verification`);return{codeHash:s.codeHash,abi:s.source.abi}}catch(r){return C.error("WarpContractLoader: getVerificationInfo error",r),null}}};var ht=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 L,this.contractLoader=new it(t),this.cache=new V(t.cache?.type),this.registry=new k(t)}async createTransactionForExecute(t,e,r){let n=O(t,e);if(!this.config.user?.wallet)throw new Error("WarpActionExecutor: user address not set");let s=I.Address.newFromBech32(this.config.user.wallet),a=await this.getTxComponentsFromInputs(n,r,s),o=new I.TransactionsFactoryConfig({chainID:a.chain.chainId}),u=a.args.map(d=>this.serializer.stringToTyped(d)),p=null;if(n.type==="transfer")p=new I.TransferTransactionsFactory({config:o}).createTransactionForTransfer(s,{receiver:a.destination,nativeAmount:a.value,tokenTransfers:a.transfers,data:a.data?new Uint8Array(a.data):void 0});else if(n.type==="contract"&&a.destination.isSmartContract())p=new I.SmartContractTransactionsFactory({config:o}).createTransactionForExecute(s,{contract:a.destination,function:"func"in n&&n.func||"",gasLimit:"gasLimit"in n?BigInt(n.gasLimit||0):0n,arguments:u,tokenTransfers:a.transfers,nativeTransferAmount:a.value});else{if(n.type==="query")throw new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead");if(n.type==="collect")throw new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead")}if(!p)throw new Error(`WarpActionExecutor: Invalid action type (${n.type})`);return this.cache.set(E.LastWarpExecutionInputs(this.config.env,t.meta?.hash||"",e),a.resolvedInputs,Z.OneWeek),p}async getTransactionExecutionResults(t,e,r){let n=await F.apply(this.config,t),s=O(n,e),a=this.cache.get(E.LastWarpExecutionInputs(this.config.env,t.meta?.hash||"",e))??[],{values:o,results:u}=await Bt(this,n,s,r,e,a),p=T.getNextInfo(this.config,n,e,u),d=this.getPreparedMessages(n,u);return{success:r.status.isSuccessful(),warp:n,action:e,user:this.config.user?.wallet||null,txHash:r.hash,next:p,values:o,results:u,messages:d}}async executeQuery(t,e,r){let n=O(t,e);if(!n)throw new Error("WarpActionExecutor: Action not found");if(!n.func)throw new Error("WarpActionExecutor: Function not found");let s=await F.apply(this.config,t),a=await this.getAbiForAction(n),{chain:o,args:u,resolvedInputs:p}=await this.getTxComponentsFromInputs(n,r),d=u.map(pt=>this.serializer.stringToTyped(pt)),g=T.getChainEntrypoint(o,this.config.env),w=I.Address.newFromBech32(n.address),y=g.createSmartContractController(a),B=y.createQuery({contract:w,function:n.func,arguments:d}),h=await y.runQuery(B),W=h.returnCode==="ok",b=new I.ArgSerializer,S=a.getEndpoint(h.function),P=h.returnDataParts.map(pt=>Buffer.from(pt)),v=b.buffersToValues(P,S.output),{values:H,results:U}=await Et(s,v,e,p),R=T.getNextInfo(this.config,s,e,U);return{success:W,warp:s,action:e,user:this.config.user?.wallet||null,txHash:null,next:R,values:H,results:U,messages:this.getPreparedMessages(s,U)}}async executeCollect(t,e,r,n){let s=O(t,e);if(!s)throw new Error("WarpActionExecutor: Action not found");let a=await T.getChainInfoForAction(this.config,s),o=await F.apply(this.config,t),u=await this.getResolvedInputs(a,s,r),p=this.getModifiedInputs(u),d=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 b=W;return{token:b.token.identifier,nonce:b.token.nonce.toString(),amount:b.amount.toString()}}else return W},g=new Headers;g.set("Content-Type","application/json"),g.set("Accept","application/json"),Object.entries(s.destination.headers||{}).forEach(([h,W])=>{g.set(h,W)});let w=Object.fromEntries(p.map(h=>[h.input.as||h.input.name,d(h)])),y=s.destination.method||"GET",B=y==="GET"?void 0:JSON.stringify({...w,...n});C.info("Executing collect",{url:s.destination.url,method:y,headers:g,body:B});try{let h=await fetch(s.destination.url,{method:y,headers:g,body:B}),W=await h.json(),{values:b,results:S}=await St(o,W,e,p),P=T.getNextInfo(this.config,o,e,S);return{success:h.ok,warp:o,action:e,user:this.config.user?.wallet||null,txHash:null,next:P,values:b,results:{...S,_DATA:W},messages:this.getPreparedMessages(o,S)}}catch(h){return C.error("WarpActionExecutor: Error executing collect",h),{success:!1,warp:o,action:e,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{_DATA:h},messages:{}}}}async getTxComponentsFromInputs(t,e,r){let n=await this.getChainForActionWithInputs(t,e),s=await this.getResolvedInputs(n,t,e),a=this.getModifiedInputs(s),o=a.find(R=>R.input.position==="receiver")?.value,u="address"in t?t.address:null,p=o?.split(":")[1]||u||r?.toBech32();if(!p)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let d=I.Address.newFromBech32(p),g=this.getPreparedArgs(t,a),w=a.find(R=>R.input.position==="value")?.value||null,y="value"in t?t.value:null,B=BigInt(w?.split(":")[1]||y||0),h=a.filter(R=>R.input.position==="transfer"&&R.value).map(R=>R.value),b=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...h?.map(R=>this.serializer.stringToNative(R)[1])||[]],S=a.find(R=>R.input.position==="data")?.value,P="data"in t?t.data||"":null,v=S||P||null,H=v?this.serializer.stringToTyped(v).valueOf():null,U=H?Buffer.from(H):null;return{chain:n,destination:d,args:g,value:B,transfers:b,data:U,resolvedInputs:a}}async getChainForActionWithInputs(t,e){let r=t.inputs?.findIndex(o=>o.position==="chain");if(r===-1||r===void 0)return await T.getChainInfoForAction(this.config,t);let n=e[r];if(!n)throw new Error("WarpActionExecutor: Chain input not found");let s=this.serializer.stringToNative(n)[1],a=await this.registry.getChainInfo(s);if(!a)throw new Error(`WarpActionExecutor: Chain info not found for ${s}`);return a}async getResolvedInputs(t,e,r){let n=e.inputs||[],s=await Promise.all(r.map(o=>this.preprocessInput(t,o))),a=(o,u)=>{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:s[u]||null};return n.map((o,u)=>{let p=a(o,u);return{input:o,value:p||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(t){return t.map((e,r)=>{if(e.input.modifier?.startsWith("scale:")){let[,n]=e.input.modifier.split(":");if(isNaN(Number(n))){let s=Number(t.find(u=>u.input.name===n)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let a=e.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=K(a,+s);return{...e,value:`${e.input.type}:${o}`}}else{let s=e.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let a=K(s,+n);return{...e,value:`${e.input.type}:${a}`}}}else return e})}async preprocessInput(t,e){try{let[r,n]=e.split(f.ArgParamsSeparator,2);if(r==="esdt"){let[s,a,o,u]=n.split(f.ArgCompositeSeparator);if(u)return e;let p=new I.Token({identifier:s,nonce:BigInt(a)});if(!new I.TokenComputer().isFungible(p))return e;let w=Rt(s)?.decimals;if(w||(w=(await(await fetch(`${t.apiUrl}/tokens/${s}`)).json()).decimals),!w)throw new Error(`WarpActionExecutor: Decimals not found for token ${s}`);let y=new I.TokenTransfer({token:p,amount:K(o,w)});return this.serializer.nativeToString(r,y)+f.ArgCompositeSeparator+w}return e}catch{return e}}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=x(this.config),r=await this.contractLoader.getVerificationInfo(t.address,e);if(!r)throw new Error("WarpActionExecutor: Verification info not found");return I.AbiRegistry.create(r.abi)}getPreparedArgs(t,e){let r="args"in t?t.args||[]:[];return e.forEach(({input:n,value:s})=>{if(!s||!n.position?.startsWith("arg:"))return;let a=Number(n.position.split(":")[1])-1;r.splice(a,0,s)}),r}getPreparedMessages(t,e){let r=Object.entries(t.messages||{}).map(([n,s])=>[n,J(s,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 nt(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 I.AbiRegistry.create(n.content)}else{let r=await(await fetch(t.abi)).json();return I.AbiRegistry.create(r)}}toTypedTransfer(t){return new I.TokenTransfer({token:new I.Token({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var yt=class{constructor(t){this.config=t}async search(t,e,r){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let n=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...r},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!n.ok)throw new Error(`WarpIndex: search failed with status ${n.status}`);return(await n.json()).hits}catch(n){throw C.error("WarpIndex: Error searching for warps: ",n),n}}};0&&(module.exports={BrandBuilder,CacheKey,CacheTtl,WarpAbiBuilder,WarpActionExecutor,WarpArgSerializer,WarpBuilder,WarpCache,WarpConfig,WarpConstants,WarpContractLoader,WarpIndex,WarpInterpolator,WarpLink,WarpProtocolVersions,WarpRegistry,WarpUtils,WarpValidator,address,biguint,boolean,codemeta,composite,esdt,getChainExplorerUrl,getLatestProtocolIdentifier,getMainChainInfo,getWarpActionByIndex,hex,list,nothing,option,optional,replacePlaceholders,shiftBigintBy,string,toPreviewText,toTypedChainInfo,token,u16,u32,u64,u8,variadic});
11
+ `],{type:"application/javascript"}),s=URL.createObjectURL(n),a=new Worker(s);a.onmessage=function(o){o.data.error?r(new Error(o.data.error)):e(o.data.result),a.terminate(),URL.revokeObjectURL(s)},a.onerror=function(o){r(new Error(`Error in transform: ${o.message}`)),a.terminate(),URL.revokeObjectURL(s)},a.postMessage(t)}catch(n){return r(n)}})}});var ue={};Wt(ue,{BrandBuilder:()=>mt,CacheKey:()=>E,CacheTtl:()=>tt,WarpAbiBuilder:()=>it,WarpActionExecutor:()=>yt,WarpArgSerializer:()=>N,WarpBuilder:()=>rt,WarpCache:()=>V,WarpConfig:()=>A,WarpConstants:()=>d,WarpContractLoader:()=>at,WarpIndex:()=>wt,WarpInterpolator:()=>O,WarpLink:()=>nt,WarpProtocolVersions:()=>_,WarpRegistry:()=>k,WarpUtils:()=>T,WarpValidator:()=>et,address:()=>Yt,biguint:()=>Jt,boolean:()=>Xt,codemeta:()=>re,composite:()=>Qt,esdt:()=>ee,getChainExplorerUrl:()=>_t,getLatestProtocolIdentifier:()=>q,getMainChainInfo:()=>x,getWarpActionByIndex:()=>$,hex:()=>te,list:()=>Ht,nothing:()=>ne,option:()=>Mt,optional:()=>Dt,replacePlaceholders:()=>X,shiftBigintBy:()=>J,string:()=>F,toPreviewText:()=>ft,toTypedChainInfo:()=>ct,token:()=>Zt,u16:()=>zt,u32:()=>gt,u64:()=>Kt,u8:()=>Gt,variadic:()=>jt});module.exports=Lt(ue);var D=require("@multiversx/sdk-core"),At=lt(require("ajv"));var d={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:i=>i.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:i=>i.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:i=>i.chain.explorerUrl}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"},Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}};var _={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},A={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${_.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/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:{Name:"multiversx",DisplayName:"MultiversX",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",BlockTime:i=>6e3,AddressHrp:"erd",ChainId:i=>i==="devnet"?"D":i==="testnet"?"T":"1",NativeToken:"EGLD"},Registry:{Contract:i=>i==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":i==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query",d.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 x=i=>({name:A.MainChain.Name,displayName:A.MainChain.DisplayName,chainId:A.MainChain.ChainId(i.env),blockTime:A.MainChain.BlockTime(i.env),addressHrp:A.MainChain.AddressHrp,apiUrl:A.MainChain.ApiUrl(i.env),explorerUrl:A.MainChain.ExplorerUrl(i.env),nativeToken:A.MainChain.NativeToken}),_t=(i,t)=>i.explorerUrl+(t?"/"+t:""),q=i=>{if(i==="warp")return`warp:${_.Warp}`;if(i==="brand")return`brand:${_.Brand}`;if(i==="abi")return`abi:${_.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${i}`)},$=(i,t)=>i?.actions[t-1],ct=i=>({name:i.name.toString(),displayName:i.display_name.toString(),chainId:i.chain_id.toString(),blockTime:i.block_time.toNumber(),addressHrp:i.address_hrp.toString(),apiUrl:i.api_url.toString(),explorerUrl:i.explorer_url.toString(),nativeToken:i.native_token.toString()}),J=(i,t)=>{let e=i.toString(),[r,n=""]=e.split("."),s=Math.abs(t);if(t>0)return BigInt(r+n.padEnd(s,"0"));if(t<0){let a=r+n;if(s>=a.length)return 0n;let o=a.slice(0,-s)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},ft=(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},X=(i,t)=>i.replace(/\{\{([^}]+)\}\}/g,(e,r)=>t[r]||"");var j=class j{static info(...t){j.isTestEnv||console.info(...t)}static warn(...t){j.isTestEnv||console.warn(...t)}static error(...t){j.isTestEnv||console.error(...t)}};j.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var C=j;var Q=require("@multiversx/sdk-core");var c=require("@multiversx/sdk-core/out");var Tt=new RegExp(`${d.ArgParamsSeparator}(.*)`),N=class{nativeToString(t,e){return t==="esdt"&&e instanceof c.TokenTransfer?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(c.OptionValue.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(c.OptionalValue.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(c.List.ClassName)){let e=t.getItems(),n=e.map(a=>this.typedToString(a).split(d.ArgParamsSeparator)[0])[0],s=e.map(a=>this.typedToString(a).split(d.ArgParamsSeparator)[1]);return`list:${n}:${s.join(",")}`}if(t.hasClassOrSuperclass(c.VariadicValue.ClassName)){let e=t.getItems(),n=e.map(a=>this.typedToString(a).split(d.ArgParamsSeparator)[0])[0],s=e.map(a=>this.typedToString(a).split(d.ArgParamsSeparator)[1]);return`variadic:${n}:${s.join(",")}`}if(t.hasClassOrSuperclass(c.CompositeValue.ClassName)){let e=t.getItems(),r=e.map(o=>this.typedToString(o).split(d.ArgParamsSeparator)[0]),n=e.map(o=>this.typedToString(o).split(d.ArgParamsSeparator)[1]),s=r.join(d.ArgCompositeSeparator),a=n.join(d.ArgCompositeSeparator);return`composite(${s}):${a}`}if(t.hasClassOrSuperclass(c.BigUIntValue.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(c.U8Value.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(c.U16Value.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(c.U32Value.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(c.U64Value.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(c.StringValue.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(c.BooleanValue.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(c.AddressValue.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(c.TokenIdentifierValue.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(c.BytesValue.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(c.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 c.CompositeType(...e.split(d.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new c.StringType;if(t==="uint8")return new c.U8Type;if(t==="uint16")return new c.U16Type;if(t==="uint32")return new c.U32Type;if(t==="uint64")return new c.U64Type;if(t==="biguint")return new c.BigUIntType;if(t==="bool")return new c.BooleanType;if(t==="address")return new c.AddressType;if(t==="token")return new c.TokenIdentifierType;if(t==="hex")return new c.BytesType;if(t==="codemeta")return new c.CodeMetadataType;if(t==="esdt"||t==="nft")return new c.StructType("EsdtTokenPayment",[new c.FieldDefinition("token_identifier","",new c.TokenIdentifierType),new c.FieldDefinition("token_nonce","",new c.U64Type),new c.FieldDefinition("amount","",new c.BigUIntType)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(d.ArgParamsSeparator),r=e[0],n=e.slice(1).join(d.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[s,a]=n.split(d.ArgParamsSeparator);return[`option:${s}`,a||null]}else if(r==="optional"){let[s,a]=n.split(d.ArgParamsSeparator);return[`optional:${s}`,a||null]}else if(r==="list"){let s=n.split(d.ArgParamsSeparator),a=s.slice(0,-1).join(d.ArgParamsSeparator),o=s[s.length-1],p=(o?o.split(","):[]).map(f=>this.stringToNative(`${a}:${f}`)[1]);return[`list:${a}`,p]}else if(r==="variadic"){let s=n.split(d.ArgParamsSeparator),a=s.slice(0,-1).join(d.ArgParamsSeparator),o=s[s.length-1],p=(o?o.split(","):[]).map(f=>this.stringToNative(`${a}:${f}`)[1]);return[`variadic:${a}`,p]}else if(r.startsWith("composite")){let s=r.match(/\(([^)]+)\)/)?.[1]?.split(d.ArgCompositeSeparator),o=n.split(d.ArgCompositeSeparator).map((u,p)=>this.stringToNative(`${s[p]}:${u}`)[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[s,a,o]=n.split(d.ArgCompositeSeparator);return[r,new c.TokenTransfer({token:new c.Token({identifier:s,nonce:BigInt(a)}),amount:BigInt(o)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new c.NothingValue;if(e==="option"){let n=this.stringToTyped(r);return n instanceof c.NothingValue?c.OptionValue.newMissingTyped(n.getType()):c.OptionValue.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof c.NothingValue?c.OptionalValue.newMissing():new c.OptionalValue(n.getType(),n)}if(e==="list"){let[n,s]=r.split(Tt,2),o=s.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new c.List(this.nativeToType(n),o)}if(e==="variadic"){let[n,s]=r.split(Tt,2),o=s.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new c.VariadicValue(new c.VariadicType(this.nativeToType(n)),o)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],s=r.split(d.ArgCompositeSeparator),a=n.split(d.ArgCompositeSeparator),o=s.map((p,f)=>this.stringToTyped(`${a[f]}:${p}`)),u=o.map(p=>p.getType());return new c.CompositeValue(new c.CompositeType(...u),o)}if(e==="string")return r?c.StringValue.fromUTF8(r):new c.NothingValue;if(e==="uint8")return r?new c.U8Value(Number(r)):new c.NothingValue;if(e==="uint16")return r?new c.U16Value(Number(r)):new c.NothingValue;if(e==="uint32")return r?new c.U32Value(Number(r)):new c.NothingValue;if(e==="uint64")return r?new c.U64Value(BigInt(r)):new c.NothingValue;if(e==="biguint")return r?new c.BigUIntValue(BigInt(r)):new c.NothingValue;if(e==="bool")return r?new c.BooleanValue(typeof r=="boolean"?r:r==="true"):new c.NothingValue;if(e==="address")return r?new c.AddressValue(c.Address.newFromBech32(r)):new c.NothingValue;if(e==="token")return r?new c.TokenIdentifierValue(r):new c.NothingValue;if(e==="hex")return r?c.BytesValue.fromHex(r):new c.NothingValue;if(e==="codemeta")return new c.CodeMetadataValue(c.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(d.ArgCompositeSeparator);return new c.Struct(this.nativeToType("esdt"),[new c.Field(new c.TokenIdentifierValue(n[0]),"token_identifier"),new c.Field(new c.U64Value(BigInt(n[1])),"token_nonce"),new c.Field(new c.BigUIntValue(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof c.OptionType)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof c.OptionalType)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof c.ListType)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof c.VariadicType)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof c.StringType)return"string";if(t instanceof c.U8Type)return"uint8";if(t instanceof c.U16Type)return"uint16";if(t instanceof c.U32Type)return"uint32";if(t instanceof c.U64Type)return"uint64";if(t instanceof c.BigUIntType)return"biguint";if(t instanceof c.BooleanType)return"bool";if(t instanceof c.AddressType)return"address";if(t instanceof c.TokenIdentifierType)return"token";if(t instanceof c.BytesType)return"hex";if(t instanceof c.CodeMetadataType)return"codemeta";if(t instanceof c.StructType&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var Y=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))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var L=class L{get(t){let e=L.cache.get(t);return e?Date.now()>e.expiresAt?(L.cache.delete(t),null):e.value:null}set(t,e,r){let n=Date.now()+r*1e3;L.cache.set(t,{value:e,expiresAt:n})}forget(t){L.cache.delete(t)}clear(){L.cache.clear()}};L.cache=new Map;var Z=L;var tt={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},E={Warp:(i,t)=>`warp:${i}:${t}`,WarpAbi:(i,t)=>`warp-abi:${i}:${t}`,LastWarpExecutionInputs:(i,t,e)=>`warp-exec-inputs:${i}:${t}:${e}`,RegistryInfo:(i,t)=>`registry-info:${i}:${t}`,Brand:(i,t)=>`brand:${i}:${t}`,ChainInfo:(i,t)=>`chain:${i}:${t}`,ChainInfos:i=>`chains:${i}`},V=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new Y:t==="memory"?new Z:typeof window<"u"&&window.localStorage?new Y:new Z}set(t,e,r){this.strategy.set(t,e,r)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};var bt=lt(require("qr-code-styling"));var M=require("@multiversx/sdk-core");var It=lt(require("ajv"));var et=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,s)=>{n&&Object.keys(n).forEach(a=>{a!==a.toUpperCase()&&e.push(`${s} name '${a}' 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),s=Object.values(t.results||{}).some(a=>a.startsWith("out.")||a.startsWith("event."));return t.results&&!n&&s?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||A.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),s=new It.default({strict:!1}),a=s.compile(n);return a(t)?[]:[`Schema validation failed: ${s.errorsText(a.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var rt=class{constructor(t){this.pendingWarp={protocol:q("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t,this.cache=new V(t.cache?.type)}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=x(this.config),r=new M.TransactionsFactoryConfig({chainID:e.chainId}),n=new M.TransferTransactionsFactory({config:r}),s=M.Address.newFromBech32(this.config.user.wallet),a=JSON.stringify(t),o=n.createTransactionForTransfer(s,{receiver:M.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),r}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=E.Warp(this.config.env,t);if(e){let o=this.cache.get(r);if(o)return C.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),o}let n=x(this.config),a=T.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await a.getTransaction(t),u=await this.createFromTransaction(o);return e&&e.ttl&&u&&this.cache.set(r,u,e.ttl),u}catch(o){return C.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 et(this.config).validate(t);if(!r.valid)throw new Error(r.errors.join(`
12
+ `))}};var O=class{static async apply(t,e){let r=this.applyVars(t,e);return await this.applyGlobals(t,r)}static async applyGlobals(t,e){let r={...e};return r.actions=await Promise.all(r.actions.map(async n=>await this.applyActionGlobals(t,n))),r=await this.applyRootGlobals(r,t),r}static applyVars(t,e){if(!e?.vars)return e;let r=JSON.stringify(e),n=(s,a)=>{r=r.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),a.toString())};return Object.entries(e.vars).forEach(([s,a])=>{if(typeof a!="string")n(s,a);else if(a.startsWith(`${d.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=a.split(`${d.Vars.Query}:`)[1],u=new URLSearchParams(t.currentUrl.split("?")[1]).get(o);u&&n(s,u)}else if(a.startsWith(`${d.Vars.Env}:`)){let o=a.split(`${d.Vars.Env}:`)[1],u=t.vars?.[o];u&&n(s,u)}else a===d.Source.UserWallet&&t.user?.wallet?n(s,t.user.wallet):n(s,a)}),JSON.parse(r)}static async applyRootGlobals(t,e){let r=JSON.stringify(t),n={config:e,chain:x(e)};return Object.values(d.Globals).forEach(s=>{let a=s.Accessor(n);a!=null&&(r=r.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),a.toString()))}),JSON.parse(r)}static async applyActionGlobals(t,e){let r=await T.getChainInfoForAction(t,e),n=JSON.stringify(e),s={config:t,chain:r};return Object.values(d.Globals).forEach(a=>{let o=a.Accessor(s);o!=null&&(n=n.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(n)}};var m=require("@multiversx/sdk-core/out");var dt={buildInfo:{rustc:{version:"1.86.0",commitHash:"05f9846f893b09a1be1fc8560e33fc3c815cfecb",commitDate:"2025-03-31",channel:"Stable",short:"rustc 1.86.0 (05f9846f8 2025-03-31)"},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:"forceRemoveAlias",mutability:"mutable",inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"verifyWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"transferOwnership",mutability:"mutable",inputs:[{name:"warp",type:"bytes"},{name:"new_owner",type:"Address"}],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:"addAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"removeAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"ConfigView"}]},{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}]},{name:"setChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"},{name:"native_token",type:"bytes"}],outputs:[]},{name:"removeChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"}],outputs:[]},{name:"getChain",mutability:"readonly",inputs:[{name:"name",type:"bytes"}],outputs:[{type:"ChainView"}]},{name:"getChains",mutability:"readonly",inputs:[],outputs:[{type:"variadic<ChainView>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0},{name:"trust",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},{name:"trust",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}]},{identifier:"ownershipTransferred",inputs:[{name:"warp",type:"bytes",indexed:!0},{name:"old_owner",type:"Address",indexed:!0},{name:"new_owner",type:"Address",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{ChainView:{type:"struct",fields:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"},{name:"native_token",type:"bytes"}]},ConfigView:{type:"struct",fields:[{name:"unit_price",type:"BigUint"},{name:"admins",type:"List<Address>"}]},InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"owner",type:"Address"},{name:"created_at",type:"u64"},{name:"upgraded_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var pt=i=>({hash:i.hash.toString("hex"),alias:i.alias?.toString()||null,trust:i.trust.toString(),owner:i.owner.toString(),createdAt:i.created_at.toNumber(),upgradedAt:i.upgraded_at?.toNumber(),brand:i.brand?.toString("hex")||null,upgrade:i.upgrade?.toString("hex")||null}),vt=i=>({unitPrice:BigInt(i.unit_price.toString()),admins:i.admins.map(t=>t.toBech32())});var l=require("@multiversx/sdk-core/out"),Mt=(i,t)=>i?l.OptionValue.newProvided(i):t?l.OptionValue.newMissingTyped(t):l.OptionValue.newMissing(),Dt=(i,t)=>i?new l.OptionalValue(i.getType(),i):t?new l.OptionalValue(t):l.OptionalValue.newMissing(),Ht=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)},jt=i=>l.VariadicValue.fromItems(...i),Qt=i=>{let t=i.map(e=>e.getType());return new l.CompositeValue(new l.CompositeType(...t),i)},F=i=>l.StringValue.fromUTF8(i),Gt=i=>new l.U8Value(i),zt=i=>new l.U16Value(i),gt=i=>new l.U32Value(i),Kt=i=>new l.U64Value(i),Jt=i=>new l.BigUIntValue(BigInt(i)),Xt=i=>new l.BooleanValue(i),Yt=i=>new l.AddressValue(l.Address.newFromBech32(i)),Zt=i=>new l.TokenIdentifierValue(i),te=i=>l.BytesValue.fromHex(i),ee=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")]),re=i=>new l.CodeMetadataValue(l.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(i,"hex")))),ne=()=>new l.NothingValue;var k=class{constructor(t){this.config=t,this.cache=new V(t.cache?.type),this.registryConfig={unitPrice:BigInt(0),admins:[]}}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e,r){if(this.registryConfig.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 n=m.Address.newFromBech32(this.config.user.wallet),s=()=>this.isCurrentUserAdmin()?BigInt(0):e&&r?this.registryConfig.unitPrice*BigInt(3):e?this.registryConfig.unitPrice*BigInt(2):this.registryConfig.unitPrice,a=()=>e&&r?[m.BytesValue.fromHex(t),m.BytesValue.fromUTF8(e),m.BytesValue.fromHex(r)]:e?[m.BytesValue.fromHex(t),m.BytesValue.fromUTF8(e)]:[m.BytesValue.fromHex(t)];return this.getFactory().createTransactionForExecute(n,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:s(),arguments:a()})}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.registryConfig.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.isCurrentUserAdmin()?void 0:this.registryConfig.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.isCurrentUserAdmin()?void 0:this.registryConfig.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)]})}createWarpTransferOwnershipTransaction(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:"transferOwnership",gasLimit:BigInt(1e7),arguments:[m.BytesValue.fromHex(t),new m.AddressValue(new m.Address(e))]})}createBrandRegisterTransaction(t){if(this.registryConfig.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.isCurrentUserAdmin()?void 0:this.registryConfig.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.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[m.BytesValue.fromHex(t),m.BytesValue.fromHex(e)]})}async getInfoByAlias(t,e){try{let r=E.RegistryInfo(this.config.env,t),n=e?this.cache.get(r):null;if(n)return C.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let s=this.getRegistryContractAddress(),a=this.getController(),o=a.createQuery({contract:s,function:"getInfoByAlias",arguments:[m.BytesValue.fromUTF8(t)]}),u=await a.runQuery(o),[p]=a.parseQueryResponse(u),f=p?pt(p):null,g=f?.brand?await this.fetchBrand(f.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:f,brand:g},e.ttl),{registryInfo:f,brand:g}}catch{return{registryInfo:null,brand:null}}}async getInfoByHash(t,e){try{let r=E.RegistryInfo(this.config.env,t);if(e){let g=this.cache.get(r);if(g)return C.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),g}let n=this.getRegistryContractAddress(),s=this.getController(),a=s.createQuery({contract:n,function:"getInfoByHash",arguments:[m.BytesValue.fromHex(t)]}),o=await s.runQuery(a),[u]=s.parseQueryResponse(o),p=u?pt(u):null,f=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:f},e.ttl),{registryInfo:p,brand:f}}catch{return{registryInfo:null,brand:null}}}async getUserWarpRegistryInfos(t){try{let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),s=n.createQuery({contract:r,function:"getUserWarps",arguments:[new m.AddressValue(new m.Address(e))]}),a=await n.runQuery(s),[o]=n.parseQueryResponse(a);return o.map(pt)}catch{return[]}}async getUserBrands(t){try{let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),s=n.createQuery({contract:r,function:"getUserBrands",arguments:[new m.AddressValue(new m.Address(e))]}),a=await n.runQuery(s),[o]=n.parseQueryResponse(a),u=o.map(g=>g.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(u.map(g=>this.fetchBrand(g,p)))).filter(g=>g!==null)}catch{return[]}}async getChainInfos(t){let e=E.ChainInfos(this.config.env);if(t&&t.ttl){let p=this.cache.get(e);if(p)return C.info("WarpRegistry (getChainInfos): ChainInfos found in cache"),p}let r=this.getRegistryContractAddress(),n=this.getController(),s=n.createQuery({contract:r,function:"getChains",arguments:[]}),a=await n.runQuery(s),[o]=n.parseQueryResponse(a),u=o.map(ct);if(t&&t.ttl){for(let p of u)this.cache.set(E.ChainInfo(this.config.env,p.chain),p,t.ttl);this.cache.set(e,u,t.ttl)}return u}async getChainInfo(t,e){try{let r=E.ChainInfo(this.config.env,t),n=e?this.cache.get(r):null;if(n)return C.info(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let s=this.getRegistryContractAddress(),a=this.getController(),o=a.createQuery({contract:s,function:"getChain",arguments:[m.BytesValue.fromUTF8(t)]}),u=await a.runQuery(o),[p]=a.parseQueryResponse(u),f=p?ct(p):null;return e&&e.ttl&&f&&this.cache.set(r,f,e.ttl),f}catch{return null}}async setChain(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:"setChain",gasLimit:BigInt(1e7),arguments:[F(t.name),F(t.displayName),F(t.chainId),gt(t.blockTime),F(t.addressHrp),F(t.apiUrl),F(t.explorerUrl),F(t.nativeToken)]})}async removeChain(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:"removeChain",gasLimit:BigInt(1e7),arguments:[F(t)]})}async fetchBrand(t,e){let r=E.Brand(this.config.env,t),n=e?this.cache.get(r):null;if(n)return C.info(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let s=x(this.config),o=T.getChainEntrypoint(s,this.config.env).createNetworkProvider();try{let u=await o.getTransaction(t),p=JSON.parse(u.data.toString());return p.meta={hash:u.hash,creator:u.sender.bech32(),createdAt:new Date(u.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,p,e.ttl),p}catch{return null}}getRegistryContractAddress(){return m.Address.newFromBech32(this.config.registry?.contract||A.Registry.Contract(this.config.env))}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),[r]=await e.query({contract:t,function:"getConfig",arguments:[]}),n=r?vt(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let t=x(this.config),e=new m.TransactionsFactoryConfig({chainID:t.chainId}),r=m.AbiRegistry.create(dt);return new m.SmartContractTransactionsFactory({config:e,abi:r})}getController(){let t=x(this.config),e=T.getChainEntrypoint(t,this.config.env),r=m.AbiRegistry.create(dt);return e.createSmartContractController(r)}isCurrentUserAdmin(){return!!this.config.user?.wallet&&this.registryConfig.admins.includes(this.config.user.wallet)}};var nt=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(d.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),a=(await Promise.all(n)).filter(p=>p.match),o=a.length>0,u=a.map(p=>({url:p.url,warp:p.warp}));return{match:o,results:u}}async detect(t,e){let r={match:!1,url:t,warp:null,registryInfo:null,brand:null},n=t.startsWith(d.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):T.getInfoFromPrefixedIdentifier(t);if(!n)return r;try{let{type:s,identifierBase:a}=n,o=new rt(this.config),u=new k(this.config),p=null,f=null,g=null;if(s==="hash"){p=await o.createFromTransactionHash(a,e);let y=await u.getInfoByHash(a,e);f=y.registryInfo,g=y.brand}else if(s==="alias"){let y=await u.getInfoByAlias(a,e);f=y.registryInfo,g=y.brand,y.registryInfo&&(p=await o.createFromTransactionHash(y.registryInfo.hash,e))}let W=p?await O.apply(this.config,p):null;return W?{match:!0,url:t,warp:W,registryInfo:f,brand:g}:r}catch(s){return C.error("Error detecting warp link",s),r}}build(t,e){let r=this.config.clientUrl||A.DefaultClientUrl(this.config.env),n=t===d.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+d.IdentifierParamSeparator+e);return A.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${d.IdentifierParamName}=${n}`}buildFromPrefixedIdentifier(t){let e=T.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.identifierBase):""}generateQrCode(t,e,r=512,n="white",s="black",a="#23F7DD"){let o=this.build(t,e);return new bt.default({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:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(a)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=A.SuperClientUrls.includes(e.origin),n=e.searchParams.get(d.IdentifierParamName),s=r&&!n?e.pathname.split("/")[1]:n;if(!s)return null;let a=decodeURIComponent(s);return T.getInfoFromPrefixedIdentifier(a)}};var ie="https://",T=class{static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t);if(e.includes(d.IdentifierParamSeparator)){let[n,s]=e.split(d.IdentifierParamSeparator),a=s.split("?")[0];return{type:n,identifier:s,identifierBase:a}}let r=e.split("?")[0];return r.length===64?{type:d.IdentifierType.Hash,identifier:e,identifierBase:r}:{type:d.IdentifierType.Alias,identifier:e,identifierBase:r}}static getNextInfo(t,e,r,n){let s=e.actions?.[r]?.next||e.next||null;if(!s)return null;if(s.startsWith(ie))return[{identifier:null,url:s}];let[a,o]=s.split("?");if(!o)return[{identifier:a,url:this.buildNextUrl(a,t)}];let u=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(u.length===0){let h=X(o,{...e.vars,...n}),w=h?`${a}?${h}`:a;return[{identifier:w,url:this.buildNextUrl(w,t)}]}let p=u[0];if(!p)return[];let f=p.match(/{{([^[]+)\[\]/),g=f?f[1]:null;if(!g||n[g]===void 0)return[];let W=Array.isArray(n[g])?n[g]:[n[g]];if(W.length===0)return[];let y=u.filter(h=>h.includes(`{{${g}[]`)).map(h=>{let w=h.match(/\[\](\.[^}]+)?}}/),I=w&&w[1]||"";return{placeholder:h,field:I?I.slice(1):"",regex:new RegExp(h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return W.map(h=>{let w=o;for(let{regex:R,field:P}of y){let b=P?this.getNestedValue(h,P):h;if(b==null)return null;w=w.replace(R,b)}if(w.includes("{{")||w.includes("}}"))return null;let I=w?`${a}?${w}`:a;return{identifier:I,url:this.buildNextUrl(I,t)}}).filter(h=>h!==null)}static buildNextUrl(t,e){let[r,n]=t.split("?"),s=this.getInfoFromPrefixedIdentifier(r)||{type:"alias",identifier:r,identifierBase:r},o=new nt(e).build(s.type,s.identifierBase);if(!n)return o;let u=new URL(o);return new URLSearchParams(n).forEach((p,f)=>u.searchParams.set(f,p)),u.toString().replace(/\/\?/,"?")}static getNestedValue(t,e){return e.split(".").reduce((r,n)=>r?.[n],t)}static async getChainInfoForAction(t,e,r){if(r){let n=await this.tryGetChainFromInputs(t,e,r);if(n)return n}return this.getDefaultChainInfo(t,e)}static async tryGetChainFromInputs(t,e,r){let n=e.inputs?.findIndex(f=>f.position==="chain");if(n===-1||n===void 0)return null;let s=r[n];if(!s)throw new Error("WarpUtils: Chain input not found");let o=new N().stringToNative(s)[1],p=await new k(t).getChainInfo(o);if(!p)throw new Error(`WarpUtils: Chain info not found for ${o}`);return p}static async getDefaultChainInfo(t,e){if(!e.chain)return x(t);let n=await new k(t).getChainInfo(e.chain,{ttl:tt.OneWeek});if(!n)throw new Error(`WarpUtils: Chain info not found for ${e.chain}`);return n}static getChainEntrypoint(t,e){let r="warp-sdk",n="api";return e==="devnet"?new Q.DevnetEntrypoint(t.apiUrl,n,r):e==="testnet"?new Q.TestnetEntrypoint(t.apiUrl,n,r):new Q.MainnetEntrypoint(t.apiUrl,n,r)}};var mt=class{constructor(t){this.pendingBrand={protocol:q("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=x(this.config),r=new D.TransactionsFactoryConfig({chainID:e.chainId}),n=new D.TransferTransactionsFactory({config:r}),s=D.Address.newFromBech32(this.config.user.wallet),a=JSON.stringify(t);return n.createTransactionForNativeTokenTransfer(s,{receiver:D.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=x(this.config),n=T.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let s=await n.getTransaction(t);return this.createFromTransaction(s)}catch(s){return C.error("BrandBuilder: Error creating from transaction hash",s),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.schema?.brand||A.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),s=new At.default({strict:!1}),a=s.compile(n);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};var G=require("@multiversx/sdk-core");var it=class{constructor(t){this.cache=new V;this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=x(this.config),r=new G.TransactionsFactoryConfig({chainID:e.chainId}),n=new G.TransferTransactionsFactory({config:r}),s={protocol:q("abi"),content:t},a=G.Address.newFromBech32(this.config.user.wallet),o=JSON.stringify(s),u=n.createTransactionForTransfer(a,{receiver:a,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(o))});return u.gasLimit=u.gasLimit+BigInt(2e6),u}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=E.WarpAbi(this.config.env,t);if(e){let o=this.cache.get(r);if(o)return C.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),o}let n=x(this.config),a=T.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await a.getTransaction(t),u=await this.createFromTransaction(o);return e&&e.ttl&&u&&this.cache.set(r,u,e.ttl),u}catch(o){return C.error("WarpAbiBuilder: Error creating from transaction hash",o),null}}};var v=require("@multiversx/sdk-core");var z=require("@multiversx/sdk-core/out");var ht=i=>{if(i==="out")return 1;let t=i.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(i.startsWith("out.")||i.startsWith("event."),null)},se=(i,t)=>t.reduce((e,r)=>e&&e[r]!==void 0?e[r]:null,i),St=async(i,t,e,r,n,s)=>{let a=[],o={};if(!t.results||e.type!=="contract")return{values:a,results:o};if(!Object.values(t.results).some(y=>y.includes("out")||y.includes("event"))){for(let[y,B]of Object.entries(t.results))o[y]=B;return{values:a,results:await ut(t,o,n,s)}}let p=await i.getAbiForAction(e),f=new z.TransactionEventsParser({abi:p}),W=new z.SmartContractTransactionsOutcomeParser({abi:p}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[y,B]of Object.entries(t.results)){if(B.startsWith(d.Transform.Prefix))continue;if(B.startsWith("input.")){o[y]=B;continue}let h=ht(B);if(h!==null&&h!==n){o[y]=null;continue}let[w,I,R]=B.split(".");if(w==="event"){if(!I||isNaN(Number(R)))continue;let P=Number(R),b=(0,z.findEventsByFirstTopic)(r,I),K=f.parseEvents({events:b})[0],U=Object.values(K)[P]||null;a.push(U),o[y]=U&&U.valueOf()}else if(w==="out"||w.startsWith("out[")){if(!I)continue;let P=Number(I),b=W.values[P-1]||null;R&&(b=b[R]||null),b&&typeof b=="object"&&(b="toFixed"in b?b.toFixed():b.valueOf()),a.push(b),o[y]=b&&b.valueOf()}else o[y]=B}return{values:a,results:await ut(t,o,n,s)}},Et=async(i,t,e,r)=>{let n=new N,s=t.map(p=>n.typedToString(p)),a=t.map(p=>n.typedToNative(p)[1]),o={};if(!i.results)return{values:s,results:o};let u=p=>{let f=p.split(".").slice(1).map(W=>parseInt(W)-1);if(f.length===0)return;let g=a[f[0]];for(let W=1;W<f.length;W++){if(g==null)return;g=g[f[W]]}return g};for(let[p,f]of Object.entries(i.results)){if(f.startsWith(d.Transform.Prefix))continue;let g=ht(f);if(g!==null&&g!==e){o[p]=null;continue}f.startsWith("out.")||f==="out"||f.startsWith("out[")?o[p]=u(f)||null:o[p]=f}return{values:s,results:await ut(i,o,e,r)}},Rt=async(i,t,e,r)=>{let n=[],s={};for(let[a,o]of Object.entries(i.results||{})){if(o.startsWith(d.Transform.Prefix))continue;let u=ht(o);if(u!==null&&u!==e){s[a]=null;continue}let[p,...f]=o.split(".");if(p==="out"||p.startsWith("out[")){let g=f.length===0?t?.data||t:se(t,f);n.push(g),s[a]=g}else s[a]=o}return{values:n,results:await ut(i,s,e,r)}};var ut=async(i,t,e,r)=>{if(!i.results)return t;let n={...t};return n=oe(n,i,e,r),n=await ce(i,n),n},oe=(i,t,e,r)=>{let n={...i},s=$(t,e)?.inputs||[],a=new N;for(let[o,u]of Object.entries(n))if(typeof u=="string"&&u.startsWith("input.")){let p=u.split(".")[1],f=s.findIndex(W=>W.as===p||W.name===p),g=f!==-1?r[f]?.value:null;n[o]=g?a.stringToNative(g)[1]:null}return n},ce=async(i,t)=>{if(!i.results)return t;let e={...t},r=Object.entries(i.results).filter(([,n])=>n.startsWith(d.Transform.Prefix)).map(([n,s])=>({key:n,code:s.substring(d.Transform.Prefix.length)}));for(let{key:n,code:s}of r)try{let{runInVm:a}=await Promise.resolve().then(()=>(Bt(),xt));e[n]=await a(s,e)}catch(a){C.error(`Transform error for result '${n}':`,a),e[n]=null}return e};var pe=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],Pt=i=>pe.find(t=>t.id===i)||null;var at=class{constructor(t){this.config=t}async getContract(t,e){try{let s=await T.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}`);return{address:t,owner:s.ownerAddress,verified:s.isVerified||!1}}catch(r){return C.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t,e){try{let s=await T.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}/verification`);return{codeHash:s.codeHash,abi:s.source.abi}}catch(r){return C.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 N,this.contractLoader=new at(t),this.cache=new V(t.cache?.type),this.registry=new k(t)}async createTransactionForExecute(t,e,r){let n=$(t,e);if(!this.config.user?.wallet)throw new Error("WarpActionExecutor: user address not set");let s=v.Address.newFromBech32(this.config.user.wallet),a=await this.getTxComponentsFromInputs(n,r,s),o=new v.TransactionsFactoryConfig({chainID:a.chain.chainId}),u=a.args.map(f=>this.serializer.stringToTyped(f)),p=null;if(n.type==="transfer")p=new v.TransferTransactionsFactory({config:o}).createTransactionForTransfer(s,{receiver:a.destination,nativeAmount:a.value,tokenTransfers:a.transfers,data:a.data?new Uint8Array(a.data):void 0});else if(n.type==="contract"&&a.destination.isSmartContract())p=new v.SmartContractTransactionsFactory({config:o}).createTransactionForExecute(s,{contract:a.destination,function:"func"in n&&n.func||"",gasLimit:"gasLimit"in n?BigInt(n.gasLimit||0):0n,arguments:u,tokenTransfers:a.transfers,nativeTransferAmount:a.value});else{if(n.type==="query")throw new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead");if(n.type==="collect")throw new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead")}if(!p)throw new Error(`WarpActionExecutor: Invalid action type (${n.type})`);return this.cache.set(E.LastWarpExecutionInputs(this.config.env,t.meta?.hash||"",e),a.resolvedInputs,tt.OneWeek),p}async getTransactionExecutionResults(t,e,r){let n=await O.apply(this.config,t),s=$(n,e),a=this.cache.get(E.LastWarpExecutionInputs(this.config.env,t.meta?.hash||"",e))??[],{values:o,results:u}=await St(this,n,s,r,e,a),p=T.getNextInfo(this.config,n,e,u),f=this.getPreparedMessages(n,u);return{success:r.status.isSuccessful(),warp:n,action:e,user:this.config.user?.wallet||null,txHash:r.hash,next:p,values:o,results:u,messages:f}}async executeQuery(t,e,r){let n=$(t,e);if(!n)throw new Error("WarpActionExecutor: Action not found");if(!n.func)throw new Error("WarpActionExecutor: Function not found");let s=await O.apply(this.config,t),a=await this.getAbiForAction(n),{chain:o,args:u,resolvedInputs:p}=await this.getTxComponentsFromInputs(n,r),f=u.map(H=>this.serializer.stringToTyped(H)),g=T.getChainEntrypoint(o,this.config.env),W=v.Address.newFromBech32(n.address),y=g.createSmartContractController(a),B=y.createQuery({contract:W,function:n.func,arguments:f}),h=await y.runQuery(B),w=h.returnCode==="ok",I=new v.ArgSerializer,R=a.getEndpoint(h.function),P=h.returnDataParts.map(H=>Buffer.from(H)),b=I.buffersToValues(P,R.output),{values:K,results:U}=await Et(s,b,e,p),st=T.getNextInfo(this.config,s,e,U);return{success:w,warp:s,action:e,user:this.config.user?.wallet||null,txHash:null,next:st,values:K,results:U,messages:this.getPreparedMessages(s,U)}}async executeCollect(t,e,r,n){let s=$(t,e);if(!s)throw new Error("WarpActionExecutor: Action not found");let a=await T.getChainInfoForAction(this.config,s),o=await O.apply(this.config,t),u=await this.getResolvedInputs(a,s,r),p=this.getModifiedInputs(u),f=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},g=new Headers;g.set("Content-Type","application/json"),g.set("Accept","application/json"),Object.entries(s.destination.headers||{}).forEach(([h,w])=>{g.set(h,w)});let W=Object.fromEntries(p.map(h=>[h.input.as||h.input.name,f(h)])),y=s.destination.method||"GET",B=y==="GET"?void 0:JSON.stringify({...W,...n});C.info("Executing collect",{url:s.destination.url,method:y,headers:g,body:B});try{let h=await fetch(s.destination.url,{method:y,headers:g,body:B}),w=await h.json(),{values:I,results:R}=await Rt(o,w,e,p),P=T.getNextInfo(this.config,o,e,R);return{success:h.ok,warp:o,action:e,user:this.config.user?.wallet||null,txHash:null,next:P,values:I,results:{...R,_DATA:w},messages:this.getPreparedMessages(o,R)}}catch(h){return C.error("WarpActionExecutor: Error executing collect",h),{success:!1,warp:o,action:e,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{_DATA:h},messages:{}}}}async getTxComponentsFromInputs(t,e,r){let n=await T.getChainInfoForAction(this.config,t,e),s=await this.getResolvedInputs(n,t,e),a=this.getModifiedInputs(s),o=a.find(S=>S.input.position==="receiver")?.value,u="address"in t?t.address:null,p=o?.split(":")[1]||u||r?.toBech32();if(!p)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let f=v.Address.newFromBech32(p),g=this.getPreparedArgs(t,a),W=a.find(S=>S.input.position==="value")?.value||null,y="value"in t?t.value:null,B=BigInt(W?.split(":")[1]||y||0),h=a.filter(S=>S.input.position==="transfer"&&S.value).map(S=>S.value),w="transfers"in t?t.transfers:[],I=[...w?.map(this.toTypedTransfer)||[],...h?.map(S=>this.serializer.stringToNative(S)[1])||[]],R=I.length===1&&h.length===1&&!w?.length,P=I[0]?.token.identifier===`${n.nativeToken}-000000`,b=!a.some(S=>S.value&&S.input.position!=="transfer"&&S.input.type==="esdt");R&&P&&b&&(B+=I[0].amount,I=[]);let K=a.find(S=>S.input.position==="data")?.value,U="data"in t?t.data||"":null,st=K||U||null,H=st?this.serializer.stringToTyped(st).valueOf():null,Vt=H?Buffer.from(H):null;return{chain:n,destination:f,args:g,value:B,transfers:I,data:Vt,resolvedInputs:a}}async getResolvedInputs(t,e,r){let n=e.inputs||[],s=await Promise.all(r.map(o=>this.preprocessInput(t,o))),a=(o,u)=>{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===d.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:s[u]||null};return n.map((o,u)=>{let p=a(o,u);return{input:o,value:p||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(t){return t.map((e,r)=>{if(e.input.modifier?.startsWith("scale:")){let[,n]=e.input.modifier.split(":");if(isNaN(Number(n))){let s=Number(t.find(u=>u.input.name===n)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let a=e.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=J(a,+s);return{...e,value:`${e.input.type}:${o}`}}else{let s=e.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let a=J(s,+n);return{...e,value:`${e.input.type}:${a}`}}}else return e})}async preprocessInput(t,e){try{let[r,n]=e.split(d.ArgParamsSeparator,2);if(r==="esdt"){let[s,a,o,u]=n.split(d.ArgCompositeSeparator);if(u)return e;let p=new v.Token({identifier:s,nonce:BigInt(a)});if(!new v.TokenComputer().isFungible(p))return e;let W=Pt(s)?.decimals;if(W||(W=(await(await fetch(`${t.apiUrl}/tokens/${s}`)).json()).decimals),!W)throw new Error(`WarpActionExecutor: Decimals not found for token ${s}`);let y=new v.TokenTransfer({token:p,amount:J(o,W)});return this.serializer.nativeToString(r,y)+d.ArgCompositeSeparator+W}return e}catch{return e}}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=x(this.config),r=await this.contractLoader.getVerificationInfo(t.address,e);if(!r)throw new Error("WarpActionExecutor: Verification info not found");return v.AbiRegistry.create(r.abi)}getPreparedArgs(t,e){let r="args"in t?t.args||[]:[];return e.forEach(({input:n,value:s})=>{if(!s||!n.position?.startsWith("arg:"))return;let a=Number(n.position.split(":")[1])-1;r.splice(a,0,s)}),r}getPreparedMessages(t,e){let r=Object.entries(t.messages||{}).map(([n,s])=>[n,X(s,e)]);return Object.fromEntries(r)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(d.IdentifierType.Hash)){let e=new it(this.config),r=t.abi.split(d.IdentifierParamSeparator)[1],n=await e.createFromTransactionHash(r);if(!n)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return v.AbiRegistry.create(n.content)}else{let r=await(await fetch(t.abi)).json();return v.AbiRegistry.create(r)}}toTypedTransfer(t){return new v.TokenTransfer({token:new v.Token({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var wt=class{constructor(t){this.config=t}async search(t,e,r){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let n=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...r},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!n.ok)throw new Error(`WarpIndex: search failed with status ${n.status}`);return(await n.json()).hits}catch(n){throw C.error("WarpIndex: Error searching for warps: ",n),n}}};0&&(module.exports={BrandBuilder,CacheKey,CacheTtl,WarpAbiBuilder,WarpActionExecutor,WarpArgSerializer,WarpBuilder,WarpCache,WarpConfig,WarpConstants,WarpContractLoader,WarpIndex,WarpInterpolator,WarpLink,WarpProtocolVersions,WarpRegistry,WarpUtils,WarpValidator,address,biguint,boolean,codemeta,composite,esdt,getChainExplorerUrl,getLatestProtocolIdentifier,getMainChainInfo,getWarpActionByIndex,hex,list,nothing,option,optional,replacePlaceholders,shiftBigintBy,string,toPreviewText,toTypedChainInfo,token,u16,u32,u64,u8,variadic});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import"./chunk-3SAEGOMQ.mjs";import{Address as Rt,TransactionsFactoryConfig as qe,TransferTransactionsFactory as De}from"@multiversx/sdk-core";import He from"ajv";var u={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:s=>s.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:s=>s.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:s=>s.chain.explorerUrl}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"},Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}};var _={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},T={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${_.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/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:{Name:"multiversx",DisplayName:"MultiversX",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",BlockTime:s=>6e3,AddressHrp:"erd",ChainId:s=>s==="devnet"?"D":s==="testnet"?"T":"1",NativeToken:"EGLD"},Registry:{Contract:s=>s==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":s==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query",u.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 I=s=>({name:T.MainChain.Name,displayName:T.MainChain.DisplayName,chainId:T.MainChain.ChainId(s.env),blockTime:T.MainChain.BlockTime(s.env),addressHrp:T.MainChain.AddressHrp,apiUrl:T.MainChain.ApiUrl(s.env),explorerUrl:T.MainChain.ExplorerUrl(s.env),nativeToken:T.MainChain.NativeToken}),hr=(s,t)=>s.explorerUrl+(t?"/"+t:""),q=s=>{if(s==="warp")return`warp:${_.Warp}`;if(s==="brand")return`brand:${_.Brand}`;if(s==="abi")return`abi:${_.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${s}`)},O=(s,t)=>s?.actions[t-1],rt=s=>({name:s.name.toString(),displayName:s.display_name.toString(),chainId:s.chain_id.toString(),blockTime:s.block_time.toNumber(),addressHrp:s.address_hrp.toString(),apiUrl:s.api_url.toString(),explorerUrl:s.explorer_url.toString(),nativeToken:s.native_token.toString()}),j=(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)},It=(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},Q=(s,t)=>s.replace(/\{\{([^}]+)\}\}/g,(e,r)=>t[r]||"");var D=class D{static info(...t){D.isTestEnv||console.info(...t)}static warn(...t){D.isTestEnv||console.warn(...t)}static error(...t){D.isTestEnv||console.error(...t)}};D.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var y=D;import{DevnetEntrypoint as Oe,MainnetEntrypoint as $e,TestnetEntrypoint as Le}from"@multiversx/sdk-core";var H=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))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var U=class U{get(t){let e=U.cache.get(t);return e?Date.now()>e.expiresAt?(U.cache.delete(t),null):e.value:null}set(t,e,r){let n=Date.now()+r*1e3;U.cache.set(t,{value:e,expiresAt:n})}forget(t){U.cache.delete(t)}clear(){U.cache.clear()}};U.cache=new Map;var M=U;var G={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},B={Warp:(s,t)=>`warp:${s}:${t}`,WarpAbi:(s,t)=>`warp-abi:${s}:${t}`,LastWarpExecutionInputs:(s,t,e)=>`warp-exec-inputs:${s}:${t}:${e}`,RegistryInfo:(s,t)=>`registry-info:${s}:${t}`,Brand:(s,t)=>`brand:${s}:${t}`,ChainInfo:(s,t)=>`chain:${s}:${t}`,ChainInfos:s=>`chains:${s}`},V=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new H:t==="memory"?new M:typeof window<"u"&&window.localStorage?new H:new M}set(t,e,r){this.strategy.set(t,e,r)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};import ke from"qr-code-styling";import{Address as vt,TransactionsFactoryConfig as le,TransferTransactionsFactory as fe}from"@multiversx/sdk-core";import ue from"ajv";var z=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(i=>i.type==="contract"),r=t.actions.some(i=>i.type==="query");if(!e&&!r)return[];let n=t.actions.some(i=>i.abi),a=Object.values(t.results||{}).some(i=>i.startsWith("out.")||i.startsWith("event."));return t.results&&!n&&a?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||T.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),a=new ue({strict:!1}),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 K=class{constructor(t){this.pendingWarp={protocol:q("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t,this.cache=new V(t.cache?.type)}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=I(this.config),r=new le({chainID:e.chainId}),n=new fe({config:r}),a=vt.newFromBech32(this.config.user.wallet),i=JSON.stringify(t),o=n.createTransactionForTransfer(a,{receiver:vt.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))});return o.gasLimit=o.gasLimit+BigInt(2e6),o}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.validate(r),r}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(this.config.env,t);if(e){let o=this.cache.get(r);if(o)return y.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),o}let n=I(this.config),i=w.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await i.getTransaction(t),p=await this.createFromTransaction(o);return e&&e.ttl&&p&&this.cache.set(r,p,e.ttl),p}catch(o){return y.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 It(t,e)}ensure(t,e){if(!t)throw new Error(e)}async validate(t){let r=await new z(this.config).validate(t);if(!r.valid)throw new Error(r.errors.join(`
2
- `))}};var F=class{static async apply(t,e){let r=this.applyVars(t,e);return await this.applyGlobals(t,r)}static async applyGlobals(t,e){let r={...e};return r.actions=await Promise.all(r.actions.map(async n=>await this.applyActionGlobals(t,n))),r=await this.applyRootGlobals(r,t),r}static applyVars(t,e){if(!e?.vars)return e;let r=JSON.stringify(e),n=(a,i)=>{r=r.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),i.toString())};return Object.entries(e.vars).forEach(([a,i])=>{if(typeof i!="string")n(a,i);else if(i.startsWith(`${u.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=i.split(`${u.Vars.Query}:`)[1],p=new URLSearchParams(t.currentUrl.split("?")[1]).get(o);p&&n(a,p)}else if(i.startsWith(`${u.Vars.Env}:`)){let o=i.split(`${u.Vars.Env}:`)[1],p=t.vars?.[o];p&&n(a,p)}else i===u.Source.UserWallet&&t.user?.wallet?n(a,t.user.wallet):n(a,i)}),JSON.parse(r)}static async applyRootGlobals(t,e){let r=JSON.stringify(t),n={config:e,chain:I(e)};return Object.values(u.Globals).forEach(a=>{let i=a.Accessor(n);i!=null&&(r=r.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(r)}static async applyActionGlobals(t,e){let r=await w.getChainInfoForAction(t,e),n=JSON.stringify(e),a={config:t,chain:r};return Object.values(u.Globals).forEach(i=>{let o=i.Accessor(a);o!=null&&(n=n.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(n)}};import{AbiRegistry as Et,Address as S,AddressValue as ct,BytesValue as v,SmartContractTransactionsFactory as Ue,TransactionsFactoryConfig as Fe}from"@multiversx/sdk-core/out";var nt={buildInfo:{rustc:{version:"1.86.0",commitHash:"05f9846f893b09a1be1fc8560e33fc3c815cfecb",commitDate:"2025-03-31",channel:"Stable",short:"rustc 1.86.0 (05f9846f8 2025-03-31)"},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:"forceRemoveAlias",mutability:"mutable",inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"verifyWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"transferOwnership",mutability:"mutable",inputs:[{name:"warp",type:"bytes"},{name:"new_owner",type:"Address"}],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:"addAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"removeAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"ConfigView"}]},{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}]},{name:"setChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"},{name:"native_token",type:"bytes"}],outputs:[]},{name:"removeChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"}],outputs:[]},{name:"getChain",mutability:"readonly",inputs:[{name:"name",type:"bytes"}],outputs:[{type:"ChainView"}]},{name:"getChains",mutability:"readonly",inputs:[],outputs:[{type:"variadic<ChainView>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0},{name:"trust",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},{name:"trust",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}]},{identifier:"ownershipTransferred",inputs:[{name:"warp",type:"bytes",indexed:!0},{name:"old_owner",type:"Address",indexed:!0},{name:"new_owner",type:"Address",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{ChainView:{type:"struct",fields:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"},{name:"native_token",type:"bytes"}]},ConfigView:{type:"struct",fields:[{name:"unit_price",type:"BigUint"},{name:"admins",type:"List<Address>"}]},InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"owner",type:"Address"},{name:"created_at",type:"u64"},{name:"upgraded_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var J=s=>({hash:s.hash.toString("hex"),alias:s.alias?.toString()||null,trust:s.trust.toString(),owner:s.owner.toString(),createdAt:s.created_at.toNumber(),upgradedAt:s.upgraded_at?.toNumber(),brand:s.brand?.toString("hex")||null,upgrade:s.upgrade?.toString("hex")||null}),bt=s=>({unitPrice:BigInt(s.unit_price.toString()),admins:s.admins.map(t=>t.toBech32())});import{Address as ge,AddressValue as me,BigUIntType as he,BigUIntValue as At,BooleanValue as ye,BytesValue as we,CodeMetadata as We,CodeMetadataValue as Ce,CompositeType as Te,CompositeValue as Ie,Field as it,FieldDefinition as at,List as ve,NothingValue as be,OptionalValue as st,OptionValue as ot,StringValue as Ae,Struct as xe,StructType as Be,TokenIdentifierType as Se,TokenIdentifierValue as xt,U16Value as Ee,U32Value as Re,U64Type as Pe,U64Value as Bt,U8Value as Ve,VariadicValue as Ne}from"@multiversx/sdk-core/out";var Qr=(s,t)=>s?ot.newProvided(s):t?ot.newMissingTyped(t):ot.newMissing(),Gr=(s,t)=>s?new st(s.getType(),s):t?new st(t):st.newMissing(),zr=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let t=s[0].getType();return new ve(t,s)},Kr=s=>Ne.fromItems(...s),Jr=s=>{let t=s.map(e=>e.getType());return new Ie(new Te(...t),s)},N=s=>Ae.fromUTF8(s),Xr=s=>new Ve(s),Yr=s=>new Ee(s),St=s=>new Re(s),Zr=s=>new Bt(s),tn=s=>new At(BigInt(s)),en=s=>new ye(s),rn=s=>new me(ge.newFromBech32(s)),nn=s=>new xt(s),an=s=>we.fromHex(s),sn=s=>new xe(new Be("EsdtTokenPayment",[new at("token_identifier","",new Se),new at("token_nonce","",new Pe),new at("amount","",new he)]),[new it(new xt(s.token.identifier),"token_identifier"),new it(new Bt(BigInt(s.token.nonce)),"token_nonce"),new it(new At(BigInt(s.amount)),"amount")]),on=s=>new Ce(We.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),cn=()=>new be;var k=class{constructor(t){this.config=t,this.cache=new V(t.cache?.type),this.registryConfig={unitPrice:BigInt(0),admins:[]}}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e,r){if(this.registryConfig.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 n=S.newFromBech32(this.config.user.wallet),a=()=>this.isCurrentUserAdmin()?BigInt(0):e&&r?this.registryConfig.unitPrice*BigInt(3):e?this.registryConfig.unitPrice*BigInt(2):this.registryConfig.unitPrice,i=()=>e&&r?[v.fromHex(t),v.fromUTF8(e),v.fromHex(r)]:e?[v.fromHex(t),v.fromUTF8(e)]:[v.fromHex(t)];return this.getFactory().createTransactionForExecute(n,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:a(),arguments:i()})}createWarpUnregisterTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[v.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.registryConfig.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=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[v.fromUTF8(t),v.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[v.fromHex(t),v.fromUTF8(e)]})}createWarpVerifyTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[v.fromHex(t)]})}createWarpTransferOwnershipTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"transferOwnership",gasLimit:BigInt(1e7),arguments:[v.fromHex(t),new ct(new S(e))]})}createBrandRegisterTransaction(t){if(this.registryConfig.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=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[v.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[v.fromHex(t),v.fromHex(e)]})}async getInfoByAlias(t,e){try{let r=B.RegistryInfo(this.config.env,t),n=e?this.cache.get(r):null;if(n)return y.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let a=this.getRegistryContractAddress(),i=this.getController(),o=i.createQuery({contract:a,function:"getInfoByAlias",arguments:[v.fromUTF8(t)]}),p=await i.runQuery(o),[c]=i.parseQueryResponse(p),l=c?J(c):null,f=l?.brand?await this.fetchBrand(l.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:l,brand:f},e.ttl),{registryInfo:l,brand:f}}catch{return{registryInfo:null,brand:null}}}async getInfoByHash(t,e){try{let r=B.RegistryInfo(this.config.env,t);if(e){let f=this.cache.get(r);if(f)return y.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),f}let n=this.getRegistryContractAddress(),a=this.getController(),i=a.createQuery({contract:n,function:"getInfoByHash",arguments:[v.fromHex(t)]}),o=await a.runQuery(i),[p]=a.parseQueryResponse(o),c=p?J(p):null,l=c?.brand?await this.fetchBrand(c.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:c,brand:l},e.ttl),{registryInfo:c,brand:l}}catch{return{registryInfo:null,brand:null}}}async getUserWarpRegistryInfos(t){try{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 ct(new S(e))]}),i=await n.runQuery(a),[o]=n.parseQueryResponse(i);return o.map(J)}catch{return[]}}async getUserBrands(t){try{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 ct(new S(e))]}),i=await n.runQuery(a),[o]=n.parseQueryResponse(i),p=o.map(f=>f.toString("hex")),c={ttl:365*24*60*60};return(await Promise.all(p.map(f=>this.fetchBrand(f,c)))).filter(f=>f!==null)}catch{return[]}}async getChainInfos(t){let e=B.ChainInfos(this.config.env);if(t&&t.ttl){let c=this.cache.get(e);if(c)return y.info("WarpRegistry (getChainInfos): ChainInfos found in cache"),c}let r=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:r,function:"getChains",arguments:[]}),i=await n.runQuery(a),[o]=n.parseQueryResponse(i),p=o.map(rt);if(t&&t.ttl){for(let c of p)this.cache.set(B.ChainInfo(this.config.env,c.chain),c,t.ttl);this.cache.set(e,p,t.ttl)}return p}async getChainInfo(t,e){try{let r=B.ChainInfo(this.config.env,t),n=e?this.cache.get(r):null;if(n)return y.info(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let a=this.getRegistryContractAddress(),i=this.getController(),o=i.createQuery({contract:a,function:"getChain",arguments:[v.fromUTF8(t)]}),p=await i.runQuery(o),[c]=i.parseQueryResponse(p),l=c?rt(c):null;return e&&e.ttl&&l&&this.cache.set(r,l,e.ttl),l}catch{return null}}async setChain(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"setChain",gasLimit:BigInt(1e7),arguments:[N(t.name),N(t.displayName),N(t.chainId),St(t.blockTime),N(t.addressHrp),N(t.apiUrl),N(t.explorerUrl),N(t.nativeToken)]})}async removeChain(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"removeChain",gasLimit:BigInt(1e7),arguments:[N(t)]})}async fetchBrand(t,e){let r=B.Brand(this.config.env,t),n=e?this.cache.get(r):null;if(n)return y.info(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let a=I(this.config),o=w.getChainEntrypoint(a,this.config.env).createNetworkProvider();try{let p=await o.getTransaction(t),c=JSON.parse(p.data.toString());return c.meta={hash:p.hash,creator:p.sender.bech32(),createdAt:new Date(p.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,c,e.ttl),c}catch{return null}}getRegistryContractAddress(){return S.newFromBech32(this.config.registry?.contract||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=r?bt(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let t=I(this.config),e=new Fe({chainID:t.chainId}),r=Et.create(nt);return new Ue({config:e,abi:r})}getController(){let t=I(this.config),e=w.getChainEntrypoint(t,this.config.env),r=Et.create(nt);return e.createSmartContractController(r)}isCurrentUserAdmin(){return!!this.config.user?.wallet&&this.registryConfig.admins.includes(this.config.user.wallet)}};var X=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),i=(await Promise.all(n)).filter(c=>c.match),o=i.length>0,p=i.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:p}}async detect(t,e){let r={match:!1,url:t,warp:null,registryInfo:null,brand:null},n=t.startsWith(u.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):w.getInfoFromPrefixedIdentifier(t);if(!n)return r;try{let{type:a,identifierBase:i}=n,o=new K(this.config),p=new k(this.config),c=null,l=null,f=null;if(a==="hash"){c=await o.createFromTransactionHash(i,e);let g=await p.getInfoByHash(i,e);l=g.registryInfo,f=g.brand}else if(a==="alias"){let g=await p.getInfoByAlias(i,e);l=g.registryInfo,f=g.brand,g.registryInfo&&(c=await o.createFromTransactionHash(g.registryInfo.hash,e))}let m=c?await F.apply(this.config,c):null;return m?{match:!0,url:t,warp:m,registryInfo:l,brand:f}:r}catch(a){return y.error("Error detecting warp link",a),r}}build(t,e){let r=this.config.clientUrl||T.DefaultClientUrl(this.config.env),n=t===u.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+u.IdentifierParamSeparator+e);return T.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${u.IdentifierParamName}=${n}`}buildFromPrefixedIdentifier(t){let e=w.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.identifierBase):""}generateQrCode(t,e,r=512,n="white",a="black",i="#23F7DD"){let o=this.build(t,e);return new ke({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=T.SuperClientUrls.includes(e.origin),n=e.searchParams.get(u.IdentifierParamName),a=r&&!n?e.pathname.split("/")[1]:n;if(!a)return null;let i=decodeURIComponent(a);return w.getInfoFromPrefixedIdentifier(i)}};var _e="https://",w=class{static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t);if(e.includes(u.IdentifierParamSeparator)){let[n,a]=e.split(u.IdentifierParamSeparator),i=a.split("?")[0];return{type:n,identifier:a,identifierBase:i}}let r=e.split("?")[0];return r.length===64?{type:u.IdentifierType.Hash,identifier:e,identifierBase:r}:{type:u.IdentifierType.Alias,identifier:e,identifierBase:r}}static getNextInfo(t,e,r,n){let a=e.actions?.[r]?.next||e.next||null;if(!a)return null;if(a.startsWith(_e))return[{identifier:null,url:a}];let[i,o]=a.split("?");if(!o)return[{identifier:i,url:this.buildNextUrl(i,t)}];let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let d=Q(o,{...e.vars,...n}),h=d?`${i}?${d}`:i;return[{identifier:h,url:this.buildNextUrl(h,t)}]}let c=p[0];if(!c)return[];let l=c.match(/{{([^[]+)\[\]/),f=l?l[1]:null;if(!f||n[f]===void 0)return[];let m=Array.isArray(n[f])?n[f]:[n[f]];if(m.length===0)return[];let g=p.filter(d=>d.includes(`{{${f}[]`)).map(d=>{let h=d.match(/\[\](\.[^}]+)?}}/),C=h&&h[1]||"";return{placeholder:d,field:C?C.slice(1):"",regex:new RegExp(d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return m.map(d=>{let h=o;for(let{regex:A,field:R}of g){let W=R?this.getNestedValue(d,R):d;if(W==null)return null;h=h.replace(A,W)}if(h.includes("{{")||h.includes("}}"))return null;let C=h?`${i}?${h}`:i;return{identifier:C,url:this.buildNextUrl(C,t)}}).filter(d=>d!==null)}static buildNextUrl(t,e){let[r,n]=t.split("?"),a=this.getInfoFromPrefixedIdentifier(r)||{type:"alias",identifier:r,identifierBase:r},o=new X(e).build(a.type,a.identifierBase);if(!n)return o;let p=new URL(o);return new URLSearchParams(n).forEach((c,l)=>p.searchParams.set(l,c)),p.toString().replace(/\/\?/,"?")}static getNestedValue(t,e){return e.split(".").reduce((r,n)=>r?.[n],t)}static async getChainInfoForAction(t,e){if(!e.chain)return I(t);let r=await new k(t).getChainInfo(e.chain,{ttl:G.OneWeek});if(!r)throw new Error(`WarpActionExecutor: Chain info not found for ${e.chain}`);return r}static getChainEntrypoint(t,e){let r="warp-sdk",n="api";return e==="devnet"?new Oe(t.apiUrl,n,r):e==="testnet"?new Le(t.apiUrl,n,r):new $e(t.apiUrl,n,r)}};var Pt=class{constructor(t){this.pendingBrand={protocol:q("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=I(this.config),r=new qe({chainID:e.chainId}),n=new De({config:r}),a=Rt.newFromBech32(this.config.user.wallet),i=JSON.stringify(t);return n.createTransactionForNativeTokenTransfer(a,{receiver:Rt.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))})}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.ensureValidSchema(r),r}async createFromTransaction(t,e=!1){return await this.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=I(this.config),n=w.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let a=await n.getTransaction(t);return this.createFromTransaction(a)}catch(a){return y.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.schema?.brand||T.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),a=new He({strict:!1}),i=a.compile(n);if(!i(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(i.errors)}`)}};import{Address as Me,TransactionsFactoryConfig as je,TransferTransactionsFactory as Qe}from"@multiversx/sdk-core";var Y=class{constructor(t){this.cache=new V;this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=I(this.config),r=new je({chainID:e.chainId}),n=new Qe({config:r}),a={protocol:q("abi"),content:t},i=Me.newFromBech32(this.config.user.wallet),o=JSON.stringify(a),p=n.createTransactionForTransfer(i,{receiver:i,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(o))});return p.gasLimit=p.gasLimit+BigInt(2e6),p}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(this.config.env,t);if(e){let o=this.cache.get(r);if(o)return y.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),o}let n=I(this.config),i=w.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await i.getTransaction(t),p=await this.createFromTransaction(o);return e&&e.ttl&&p&&this.cache.set(r,p,e.ttl),p}catch(o){return y.error("WarpAbiBuilder: Error creating from transaction hash",o),null}}};import{AbiRegistry as Ct,Address as Tt,ArgSerializer as or,SmartContractTransactionsFactory as cr,Token as se,TokenComputer as pr,TokenTransfer as oe,TransactionsFactoryConfig as ur,TransferTransactionsFactory as lr}from"@multiversx/sdk-core";import{SmartContractTransactionsOutcomeParser as tr,TransactionEventsParser as er,findEventsByFirstTopic as rr}from"@multiversx/sdk-core/out";import{Address as Ge,AddressType as Vt,AddressValue as Nt,BigUIntType as pt,BigUIntValue as ut,BooleanType as Ut,BooleanValue as Ft,BytesType as kt,BytesValue as Ot,CodeMetadata as ze,CodeMetadataType as $t,CodeMetadataValue as Lt,CompositeType as _t,CompositeValue as qt,Field as lt,FieldDefinition as ft,List as Dt,ListType as Ke,NothingValue as E,OptionalType as Je,OptionalValue as dt,OptionType as Xe,OptionValue as gt,StringType as Ht,StringValue as Mt,Struct as Ye,StructType as jt,Token as Ze,TokenIdentifierType as mt,TokenIdentifierValue as ht,TokenTransfer as Qt,U16Type as Gt,U16Value as zt,U32Type as Kt,U32Value as Jt,U64Type as yt,U64Value as wt,U8Type as Xt,U8Value as Yt,VariadicType as Zt,VariadicValue as te}from"@multiversx/sdk-core/out";var ee=new RegExp(`${u.ArgParamsSeparator}(.*)`),$=class{nativeToString(t,e){return t==="esdt"&&e instanceof Qt?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(gt.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(dt.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(Dt.ClassName)){let e=t.getItems(),n=e.map(i=>this.typedToString(i).split(u.ArgParamsSeparator)[0])[0],a=e.map(i=>this.typedToString(i).split(u.ArgParamsSeparator)[1]);return`list:${n}:${a.join(",")}`}if(t.hasClassOrSuperclass(te.ClassName)){let e=t.getItems(),n=e.map(i=>this.typedToString(i).split(u.ArgParamsSeparator)[0])[0],a=e.map(i=>this.typedToString(i).split(u.ArgParamsSeparator)[1]);return`variadic:${n}:${a.join(",")}`}if(t.hasClassOrSuperclass(qt.ClassName)){let e=t.getItems(),r=e.map(o=>this.typedToString(o).split(u.ArgParamsSeparator)[0]),n=e.map(o=>this.typedToString(o).split(u.ArgParamsSeparator)[1]),a=r.join(u.ArgCompositeSeparator),i=n.join(u.ArgCompositeSeparator);return`composite(${a}):${i}`}if(t.hasClassOrSuperclass(ut.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Yt.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(zt.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Jt.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(wt.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Mt.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(Ft.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(Nt.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(ht.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(Ot.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(Lt.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 _t(...e.split(u.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new Ht;if(t==="uint8")return new Xt;if(t==="uint16")return new Gt;if(t==="uint32")return new Kt;if(t==="uint64")return new yt;if(t==="biguint")return new pt;if(t==="bool")return new Ut;if(t==="address")return new Vt;if(t==="token")return new mt;if(t==="hex")return new kt;if(t==="codemeta")return new $t;if(t==="esdt"||t==="nft")return new jt("EsdtTokenPayment",[new ft("token_identifier","",new mt),new ft("token_nonce","",new yt),new ft("amount","",new pt)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(u.ArgParamsSeparator),r=e[0],n=e.slice(1).join(u.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[a,i]=n.split(u.ArgParamsSeparator);return[`option:${a}`,i||null]}else if(r==="optional"){let[a,i]=n.split(u.ArgParamsSeparator);return[`optional:${a}`,i||null]}else if(r==="list"){let a=n.split(u.ArgParamsSeparator),i=a.slice(0,-1).join(u.ArgParamsSeparator),o=a[a.length-1],c=(o?o.split(","):[]).map(l=>this.stringToNative(`${i}:${l}`)[1]);return[`list:${i}`,c]}else if(r==="variadic"){let a=n.split(u.ArgParamsSeparator),i=a.slice(0,-1).join(u.ArgParamsSeparator),o=a[a.length-1],c=(o?o.split(","):[]).map(l=>this.stringToNative(`${i}:${l}`)[1]);return[`variadic:${i}`,c]}else if(r.startsWith("composite")){let a=r.match(/\(([^)]+)\)/)?.[1]?.split(u.ArgCompositeSeparator),o=n.split(u.ArgCompositeSeparator).map((p,c)=>this.stringToNative(`${a[c]}:${p}`)[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(u.ArgCompositeSeparator);return[r,new Qt({token:new Ze({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 E;if(e==="option"){let n=this.stringToTyped(r);return n instanceof E?gt.newMissingTyped(n.getType()):gt.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof E?dt.newMissing():new dt(n.getType(),n)}if(e==="list"){let[n,a]=r.split(ee,2),o=a.split(",").map(p=>this.stringToTyped(`${n}:${p}`));return new Dt(this.nativeToType(n),o)}if(e==="variadic"){let[n,a]=r.split(ee,2),o=a.split(",").map(p=>this.stringToTyped(`${n}:${p}`));return new te(new Zt(this.nativeToType(n)),o)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],a=r.split(u.ArgCompositeSeparator),i=n.split(u.ArgCompositeSeparator),o=a.map((c,l)=>this.stringToTyped(`${i[l]}:${c}`)),p=o.map(c=>c.getType());return new qt(new _t(...p),o)}if(e==="string")return r?Mt.fromUTF8(r):new E;if(e==="uint8")return r?new Yt(Number(r)):new E;if(e==="uint16")return r?new zt(Number(r)):new E;if(e==="uint32")return r?new Jt(Number(r)):new E;if(e==="uint64")return r?new wt(BigInt(r)):new E;if(e==="biguint")return r?new ut(BigInt(r)):new E;if(e==="bool")return r?new Ft(typeof r=="boolean"?r:r==="true"):new E;if(e==="address")return r?new Nt(Ge.newFromBech32(r)):new E;if(e==="token")return r?new ht(r):new E;if(e==="hex")return r?Ot.fromHex(r):new E;if(e==="codemeta")return new Lt(ze.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(u.ArgCompositeSeparator);return new Ye(this.nativeToType("esdt"),[new lt(new ht(n[0]),"token_identifier"),new lt(new wt(BigInt(n[1])),"token_nonce"),new lt(new ut(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof Xe)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Je)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Ke)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Zt)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Ht)return"string";if(t instanceof Xt)return"uint8";if(t instanceof Gt)return"uint16";if(t instanceof Kt)return"uint32";if(t instanceof yt)return"uint64";if(t instanceof pt)return"biguint";if(t instanceof Ut)return"bool";if(t instanceof Vt)return"address";if(t instanceof mt)return"token";if(t instanceof kt)return"hex";if(t instanceof $t)return"codemeta";if(t instanceof jt&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var Wt=s=>{if(s==="out")return 1;let t=s.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(s.startsWith("out.")||s.startsWith("event."),null)},nr=(s,t)=>t.reduce((e,r)=>e&&e[r]!==void 0?e[r]:null,s),re=async(s,t,e,r,n,a)=>{let i=[],o={};if(!t.results||e.type!=="contract")return{values:i,results:o};if(!Object.values(t.results).some(g=>g.includes("out")||g.includes("event"))){for(let[g,b]of Object.entries(t.results))o[g]=b;return{values:i,results:await Z(t,o,n,a)}}let c=await s.getAbiForAction(e),l=new er({abi:c}),m=new tr({abi:c}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[g,b]of Object.entries(t.results)){if(b.startsWith(u.Transform.Prefix))continue;if(b.startsWith("input.")){o[g]=b;continue}let d=Wt(b);if(d!==null&&d!==n){o[g]=null;continue}let[h,C,A]=b.split(".");if(h==="event"){if(!C||isNaN(Number(A)))continue;let R=Number(A),W=rr(r,C),L=l.parseEvents({events:W})[0],P=Object.values(L)[R]||null;i.push(P),o[g]=P&&P.valueOf()}else if(h==="out"||h.startsWith("out[")){if(!C)continue;let R=Number(C),W=m.values[R-1]||null;A&&(W=W[A]||null),W&&typeof W=="object"&&(W="toFixed"in W?W.toFixed():W.valueOf()),i.push(W),o[g]=W&&W.valueOf()}else o[g]=b}return{values:i,results:await Z(t,o,n,a)}},ne=async(s,t,e,r)=>{let n=new $,a=t.map(c=>n.typedToString(c)),i=t.map(c=>n.typedToNative(c)[1]),o={};if(!s.results)return{values:a,results:o};let p=c=>{let l=c.split(".").slice(1).map(m=>parseInt(m)-1);if(l.length===0)return;let f=i[l[0]];for(let m=1;m<l.length;m++){if(f==null)return;f=f[l[m]]}return f};for(let[c,l]of Object.entries(s.results)){if(l.startsWith(u.Transform.Prefix))continue;let f=Wt(l);if(f!==null&&f!==e){o[c]=null;continue}l.startsWith("out.")||l==="out"||l.startsWith("out[")?o[c]=p(l)||null:o[c]=l}return{values:a,results:await Z(s,o,e,r)}},ie=async(s,t,e,r)=>{let n=[],a={};for(let[i,o]of Object.entries(s.results||{})){if(o.startsWith(u.Transform.Prefix))continue;let p=Wt(o);if(p!==null&&p!==e){a[i]=null;continue}let[c,...l]=o.split(".");if(c==="out"||c.startsWith("out[")){let f=l.length===0?t?.data||t:nr(t,l);n.push(f),a[i]=f}else a[i]=o}return{values:n,results:await Z(s,a,e,r)}};var Z=async(s,t,e,r)=>{if(!s.results)return t;let n={...t};return n=ir(n,s,e,r),n=await ar(s,n),n},ir=(s,t,e,r)=>{let n={...s},a=O(t,e)?.inputs||[],i=new $;for(let[o,p]of Object.entries(n))if(typeof p=="string"&&p.startsWith("input.")){let c=p.split(".")[1],l=a.findIndex(m=>m.as===c||m.name===c),f=l!==-1?r[l]?.value:null;n[o]=f?i.stringToNative(f)[1]:null}return n},ar=async(s,t)=>{if(!s.results)return t;let e={...t},r=Object.entries(s.results).filter(([,n])=>n.startsWith(u.Transform.Prefix)).map(([n,a])=>({key:n,code:a.substring(u.Transform.Prefix.length)}));for(let{key:n,code:a}of r)try{let{runInVm:i}=await import("./vm-JCVDACTR.mjs");e[n]=await i(a,e)}catch(i){y.error(`Transform error for result '${n}':`,i),e[n]=null}return e};var sr=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],ae=s=>sr.find(t=>t.id===s)||null;var tt=class{constructor(t){this.config=t}async getContract(t,e){try{let a=await w.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}`);return{address:t,owner:a.ownerAddress,verified:a.isVerified||!1}}catch(r){return y.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t,e){try{let a=await w.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}/verification`);return{codeHash:a.codeHash,abi:a.source.abi}}catch(r){return y.error("WarpContractLoader: getVerificationInfo error",r),null}}};var ce=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 $,this.contractLoader=new tt(t),this.cache=new V(t.cache?.type),this.registry=new k(t)}async createTransactionForExecute(t,e,r){let n=O(t,e);if(!this.config.user?.wallet)throw new Error("WarpActionExecutor: user address not set");let a=Tt.newFromBech32(this.config.user.wallet),i=await this.getTxComponentsFromInputs(n,r,a),o=new ur({chainID:i.chain.chainId}),p=i.args.map(l=>this.serializer.stringToTyped(l)),c=null;if(n.type==="transfer")c=new lr({config:o}).createTransactionForTransfer(a,{receiver:i.destination,nativeAmount:i.value,tokenTransfers:i.transfers,data:i.data?new Uint8Array(i.data):void 0});else if(n.type==="contract"&&i.destination.isSmartContract())c=new cr({config:o}).createTransactionForExecute(a,{contract:i.destination,function:"func"in n&&n.func||"",gasLimit:"gasLimit"in n?BigInt(n.gasLimit||0):0n,arguments:p,tokenTransfers:i.transfers,nativeTransferAmount:i.value});else{if(n.type==="query")throw new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead");if(n.type==="collect")throw new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead")}if(!c)throw new Error(`WarpActionExecutor: Invalid action type (${n.type})`);return this.cache.set(B.LastWarpExecutionInputs(this.config.env,t.meta?.hash||"",e),i.resolvedInputs,G.OneWeek),c}async getTransactionExecutionResults(t,e,r){let n=await F.apply(this.config,t),a=O(n,e),i=this.cache.get(B.LastWarpExecutionInputs(this.config.env,t.meta?.hash||"",e))??[],{values:o,results:p}=await re(this,n,a,r,e,i),c=w.getNextInfo(this.config,n,e,p),l=this.getPreparedMessages(n,p);return{success:r.status.isSuccessful(),warp:n,action:e,user:this.config.user?.wallet||null,txHash:r.hash,next:c,values:o,results:p,messages:l}}async executeQuery(t,e,r){let n=O(t,e);if(!n)throw new Error("WarpActionExecutor: Action not found");if(!n.func)throw new Error("WarpActionExecutor: Function not found");let a=await F.apply(this.config,t),i=await this.getAbiForAction(n),{chain:o,args:p,resolvedInputs:c}=await this.getTxComponentsFromInputs(n,r),l=p.map(et=>this.serializer.stringToTyped(et)),f=w.getChainEntrypoint(o,this.config.env),m=Tt.newFromBech32(n.address),g=f.createSmartContractController(i),b=g.createQuery({contract:m,function:n.func,arguments:l}),d=await g.runQuery(b),h=d.returnCode==="ok",C=new or,A=i.getEndpoint(d.function),R=d.returnDataParts.map(et=>Buffer.from(et)),W=C.buffersToValues(R,A.output),{values:L,results:P}=await ne(a,W,e,c),x=w.getNextInfo(this.config,a,e,P);return{success:h,warp:a,action:e,user:this.config.user?.wallet||null,txHash:null,next:x,values:L,results:P,messages:this.getPreparedMessages(a,P)}}async executeCollect(t,e,r,n){let a=O(t,e);if(!a)throw new Error("WarpActionExecutor: Action not found");let i=await w.getChainInfoForAction(this.config,a),o=await F.apply(this.config,t),p=await this.getResolvedInputs(i,a,r),c=this.getModifiedInputs(p),l=d=>{if(!d.value)return null;let h=this.serializer.stringToNative(d.value)[1];if(d.input.type==="biguint")return h.toString();if(d.input.type==="esdt"){let C=h;return{token:C.token.identifier,nonce:C.token.nonce.toString(),amount:C.amount.toString()}}else return h},f=new Headers;f.set("Content-Type","application/json"),f.set("Accept","application/json"),Object.entries(a.destination.headers||{}).forEach(([d,h])=>{f.set(d,h)});let m=Object.fromEntries(c.map(d=>[d.input.as||d.input.name,l(d)])),g=a.destination.method||"GET",b=g==="GET"?void 0:JSON.stringify({...m,...n});y.info("Executing collect",{url:a.destination.url,method:g,headers:f,body:b});try{let d=await fetch(a.destination.url,{method:g,headers:f,body:b}),h=await d.json(),{values:C,results:A}=await ie(o,h,e,c),R=w.getNextInfo(this.config,o,e,A);return{success:d.ok,warp:o,action:e,user:this.config.user?.wallet||null,txHash:null,next:R,values:C,results:{...A,_DATA:h},messages:this.getPreparedMessages(o,A)}}catch(d){return y.error("WarpActionExecutor: Error executing collect",d),{success:!1,warp:o,action:e,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{_DATA:d},messages:{}}}}async getTxComponentsFromInputs(t,e,r){let n=await this.getChainForActionWithInputs(t,e),a=await this.getResolvedInputs(n,t,e),i=this.getModifiedInputs(a),o=i.find(x=>x.input.position==="receiver")?.value,p="address"in t?t.address:null,c=o?.split(":")[1]||p||r?.toBech32();if(!c)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let l=Tt.newFromBech32(c),f=this.getPreparedArgs(t,i),m=i.find(x=>x.input.position==="value")?.value||null,g="value"in t?t.value:null,b=BigInt(m?.split(":")[1]||g||0),d=i.filter(x=>x.input.position==="transfer"&&x.value).map(x=>x.value),C=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...d?.map(x=>this.serializer.stringToNative(x)[1])||[]],A=i.find(x=>x.input.position==="data")?.value,R="data"in t?t.data||"":null,W=A||R||null,L=W?this.serializer.stringToTyped(W).valueOf():null,P=L?Buffer.from(L):null;return{chain:n,destination:l,args:f,value:b,transfers:C,data:P,resolvedInputs:i}}async getChainForActionWithInputs(t,e){let r=t.inputs?.findIndex(o=>o.position==="chain");if(r===-1||r===void 0)return await w.getChainInfoForAction(this.config,t);let n=e[r];if(!n)throw new Error("WarpActionExecutor: Chain input not found");let a=this.serializer.stringToNative(n)[1],i=await this.registry.getChainInfo(a);if(!i)throw new Error(`WarpActionExecutor: Chain info not found for ${a}`);return i}async getResolvedInputs(t,e,r){let n=e.inputs||[],a=await Promise.all(r.map(o=>this.preprocessInput(t,o))),i=(o,p)=>{if(o.source==="query"){let c=this.url.searchParams.get(o.name);return c?this.serializer.nativeToString(o.type,c):null}else return o.source===u.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:a[p]||null};return n.map((o,p)=>{let c=i(o,p);return{input:o,value:c||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(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 o=j(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=j(a,+n);return{...e,value:`${e.input.type}:${i}`}}}else return e})}async preprocessInput(t,e){try{let[r,n]=e.split(u.ArgParamsSeparator,2);if(r==="esdt"){let[a,i,o,p]=n.split(u.ArgCompositeSeparator);if(p)return e;let c=new se({identifier:a,nonce:BigInt(i)});if(!new pr().isFungible(c))return e;let m=ae(a)?.decimals;if(m||(m=(await(await fetch(`${t.apiUrl}/tokens/${a}`)).json()).decimals),!m)throw new Error(`WarpActionExecutor: Decimals not found for token ${a}`);let g=new oe({token:c,amount:j(o,m)});return this.serializer.nativeToString(r,g)+u.ArgCompositeSeparator+m}return e}catch{return e}}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 Ct.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,Q(a,e)]);return Object.fromEntries(r)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(u.IdentifierType.Hash)){let e=new Y(this.config),r=t.abi.split(u.IdentifierParamSeparator)[1],n=await e.createFromTransactionHash(r);if(!n)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return Ct.create(n.content)}else{let r=await(await fetch(t.abi)).json();return Ct.create(r)}}toTypedTransfer(t){return new oe({token:new se({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var pe=class{constructor(t){this.config=t}async search(t,e,r){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let n=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...r},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!n.ok)throw new Error(`WarpIndex: search failed with status ${n.status}`);return(await n.json()).hits}catch(n){throw y.error("WarpIndex: Error searching for warps: ",n),n}}};export{Pt as BrandBuilder,B as CacheKey,G as CacheTtl,Y as WarpAbiBuilder,ce as WarpActionExecutor,$ as WarpArgSerializer,K as WarpBuilder,V as WarpCache,T as WarpConfig,u as WarpConstants,tt as WarpContractLoader,pe as WarpIndex,F as WarpInterpolator,X as WarpLink,_ as WarpProtocolVersions,k as WarpRegistry,w as WarpUtils,z as WarpValidator,rn as address,tn as biguint,en as boolean,on as codemeta,Jr as composite,sn as esdt,hr as getChainExplorerUrl,q as getLatestProtocolIdentifier,I as getMainChainInfo,O as getWarpActionByIndex,an as hex,zr as list,cn as nothing,Qr as option,Gr as optional,Q as replacePlaceholders,j as shiftBigintBy,N as string,It as toPreviewText,rt as toTypedChainInfo,nn as token,Yr as u16,St as u32,Zr as u64,Xr as u8,Kr as variadic};
1
+ import"./chunk-3SAEGOMQ.mjs";import{Address as ee,TransactionsFactoryConfig as Je,TransferTransactionsFactory as Xe}from"@multiversx/sdk-core";import Ye from"ajv";var l={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:s=>s.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:s=>s.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:s=>s.chain.explorerUrl}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"},Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}};var _={Warp:"3.0.0",Brand:"0.1.0",Abi:"0.1.0"},T={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${_.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/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:{Name:"multiversx",DisplayName:"MultiversX",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",BlockTime:s=>6e3,AddressHrp:"erd",ChainId:s=>s==="devnet"?"D":s==="testnet"?"T":"1",NativeToken:"EGLD"},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 I=s=>({name:T.MainChain.Name,displayName:T.MainChain.DisplayName,chainId:T.MainChain.ChainId(s.env),blockTime:T.MainChain.BlockTime(s.env),addressHrp:T.MainChain.AddressHrp,apiUrl:T.MainChain.ApiUrl(s.env),explorerUrl:T.MainChain.ExplorerUrl(s.env),nativeToken:T.MainChain.NativeToken}),wr=(s,t)=>s.explorerUrl+(t?"/"+t:""),q=s=>{if(s==="warp")return`warp:${_.Warp}`;if(s==="brand")return`brand:${_.Brand}`;if(s==="abi")return`abi:${_.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${s}`)},$=(s,t)=>s?.actions[t-1],nt=s=>({name:s.name.toString(),displayName:s.display_name.toString(),chainId:s.chain_id.toString(),blockTime:s.block_time.toNumber(),addressHrp:s.address_hrp.toString(),apiUrl:s.api_url.toString(),explorerUrl:s.explorer_url.toString(),nativeToken:s.native_token.toString()}),G=(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)},vt=(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},z=(s,t)=>s.replace(/\{\{([^}]+)\}\}/g,(e,r)=>t[r]||"");var D=class D{static info(...t){D.isTestEnv||console.info(...t)}static warn(...t){D.isTestEnv||console.warn(...t)}static error(...t){D.isTestEnv||console.error(...t)}};D.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var y=D;import{DevnetEntrypoint as Qe,MainnetEntrypoint as Ge,TestnetEntrypoint as ze}from"@multiversx/sdk-core";import{Address as fe,AddressType as bt,AddressValue as At,BigUIntType as it,BigUIntValue as at,BooleanType as xt,BooleanValue as Bt,BytesType as St,BytesValue as Et,CodeMetadata as ge,CodeMetadataType as Rt,CodeMetadataValue as Pt,CompositeType as Vt,CompositeValue as Nt,Field as st,FieldDefinition as ot,List as Ut,ListType as de,NothingValue as E,OptionalType as me,OptionalValue as ct,OptionType as he,OptionValue as pt,StringType as Ft,StringValue as kt,Struct as ye,StructType as Ot,Token as we,TokenIdentifierType as ut,TokenIdentifierValue as lt,TokenTransfer as $t,U16Type as Lt,U16Value as _t,U32Type as qt,U32Value as Dt,U64Type as ft,U64Value as gt,U8Type as Ht,U8Value as Mt,VariadicType as jt,VariadicValue as Qt}from"@multiversx/sdk-core/out";var Gt=new RegExp(`${l.ArgParamsSeparator}(.*)`),N=class{nativeToString(t,e){return t==="esdt"&&e instanceof $t?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(pt.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(ct.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(Ut.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(Qt.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(Nt.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(at.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Mt.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(_t.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Dt.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(gt.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(kt.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(Bt.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(At.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(lt.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(Et.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(Pt.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),n=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${n}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.stringToNative(e)}nativeToTyped(t,e){let r=this.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new Vt(...e.split(l.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new Ft;if(t==="uint8")return new Ht;if(t==="uint16")return new Lt;if(t==="uint32")return new qt;if(t==="uint64")return new ft;if(t==="biguint")return new it;if(t==="bool")return new xt;if(t==="address")return new bt;if(t==="token")return new ut;if(t==="hex")return new St;if(t==="codemeta")return new Rt;if(t==="esdt"||t==="nft")return new Ot("EsdtTokenPayment",[new ot("token_identifier","",new ut),new ot("token_nonce","",new ft),new ot("amount","",new it)]);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],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`list:${i}`,c]}else if(r==="variadic"){let a=n.split(l.ArgParamsSeparator),i=a.slice(0,-1).join(l.ArgParamsSeparator),o=a[a.length-1],c=(o?o.split(","):[]).map(u=>this.stringToNative(`${i}:${u}`)[1]);return[`variadic:${i}`,c]}else if(r.startsWith("composite")){let a=r.match(/\(([^)]+)\)/)?.[1]?.split(l.ArgCompositeSeparator),o=n.split(l.ArgCompositeSeparator).map((p,c)=>this.stringToNative(`${a[c]}:${p}`)[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 $t({token:new we({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 E;if(e==="option"){let n=this.stringToTyped(r);return n instanceof E?pt.newMissingTyped(n.getType()):pt.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof E?ct.newMissing():new ct(n.getType(),n)}if(e==="list"){let[n,a]=r.split(Gt,2),o=a.split(",").map(p=>this.stringToTyped(`${n}:${p}`));return new Ut(this.nativeToType(n),o)}if(e==="variadic"){let[n,a]=r.split(Gt,2),o=a.split(",").map(p=>this.stringToTyped(`${n}:${p}`));return new Qt(new jt(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((c,u)=>this.stringToTyped(`${i[u]}:${c}`)),p=o.map(c=>c.getType());return new Nt(new Vt(...p),o)}if(e==="string")return r?kt.fromUTF8(r):new E;if(e==="uint8")return r?new Mt(Number(r)):new E;if(e==="uint16")return r?new _t(Number(r)):new E;if(e==="uint32")return r?new Dt(Number(r)):new E;if(e==="uint64")return r?new gt(BigInt(r)):new E;if(e==="biguint")return r?new at(BigInt(r)):new E;if(e==="bool")return r?new Bt(typeof r=="boolean"?r:r==="true"):new E;if(e==="address")return r?new At(fe.newFromBech32(r)):new E;if(e==="token")return r?new lt(r):new E;if(e==="hex")return r?Et.fromHex(r):new E;if(e==="codemeta")return new Pt(ge.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(l.ArgCompositeSeparator);return new ye(this.nativeToType("esdt"),[new st(new lt(n[0]),"token_identifier"),new st(new gt(BigInt(n[1])),"token_nonce"),new st(new at(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof he)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof me)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof de)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof jt)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Ft)return"string";if(t instanceof Ht)return"uint8";if(t instanceof Lt)return"uint16";if(t instanceof qt)return"uint32";if(t instanceof ft)return"uint64";if(t instanceof it)return"biguint";if(t instanceof xt)return"bool";if(t instanceof bt)return"address";if(t instanceof ut)return"token";if(t instanceof St)return"hex";if(t instanceof Rt)return"codemeta";if(t instanceof Ot&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var M=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let r=JSON.parse(e);return Date.now()>r.expiresAt?(localStorage.removeItem(this.getKey(t)),null):r.value}catch{return null}}set(t,e,r){let n={value:e,expiresAt:Date.now()+r*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(n))}forget(t){localStorage.removeItem(this.getKey(t))}clear(){for(let t=0;t<localStorage.length;t++){let e=localStorage.key(t);e?.startsWith(this.prefix)&&localStorage.removeItem(e)}}};var k=class k{get(t){let e=k.cache.get(t);return e?Date.now()>e.expiresAt?(k.cache.delete(t),null):e.value:null}set(t,e,r){let n=Date.now()+r*1e3;k.cache.set(t,{value:e,expiresAt:n})}forget(t){k.cache.delete(t)}clear(){k.cache.clear()}};k.cache=new Map;var j=k;var K={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},B={Warp:(s,t)=>`warp:${s}:${t}`,WarpAbi:(s,t)=>`warp-abi:${s}:${t}`,LastWarpExecutionInputs:(s,t,e)=>`warp-exec-inputs:${s}:${t}:${e}`,RegistryInfo:(s,t)=>`registry-info:${s}:${t}`,Brand:(s,t)=>`brand:${s}:${t}`,ChainInfo:(s,t)=>`chain:${s}:${t}`,ChainInfos:s=>`chains:${s}`},V=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new M:t==="memory"?new j:typeof window<"u"&&window.localStorage?new M:new j}set(t,e,r){this.strategy.set(t,e,r)}get(t){return this.strategy.get(t)}forget(t){this.strategy.forget(t)}clear(){this.strategy.clear()}};import je from"qr-code-styling";import{Address as zt,TransactionsFactoryConfig as Ce,TransferTransactionsFactory as Te}from"@multiversx/sdk-core";import We 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(i=>i.type==="contract"),r=t.actions.some(i=>i.type==="query");if(!e&&!r)return[];let n=t.actions.some(i=>i.abi),a=Object.values(t.results||{}).some(i=>i.startsWith("out.")||i.startsWith("event."));return t.results&&!n&&a?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||T.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),a=new We({strict:!1}),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 X=class{constructor(t){this.pendingWarp={protocol:q("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t,this.cache=new V(t.cache?.type)}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=I(this.config),r=new Ce({chainID:e.chainId}),n=new Te({config:r}),a=zt.newFromBech32(this.config.user.wallet),i=JSON.stringify(t),o=n.createTransactionForTransfer(a,{receiver:zt.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))});return o.gasLimit=o.gasLimit+BigInt(2e6),o}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.validate(r),r}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(this.config.env,t);if(e){let o=this.cache.get(r);if(o)return y.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),o}let n=I(this.config),i=w.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await i.getTransaction(t),p=await this.createFromTransaction(o);return e&&e.ttl&&p&&this.cache.set(r,p,e.ttl),p}catch(o){return y.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 vt(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 O=class{static async apply(t,e){let r=this.applyVars(t,e);return await this.applyGlobals(t,r)}static async applyGlobals(t,e){let r={...e};return r.actions=await Promise.all(r.actions.map(async n=>await this.applyActionGlobals(t,n))),r=await this.applyRootGlobals(r,t),r}static applyVars(t,e){if(!e?.vars)return e;let r=JSON.stringify(e),n=(a,i)=>{r=r.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),i.toString())};return Object.entries(e.vars).forEach(([a,i])=>{if(typeof i!="string")n(a,i);else if(i.startsWith(`${l.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=i.split(`${l.Vars.Query}:`)[1],p=new URLSearchParams(t.currentUrl.split("?")[1]).get(o);p&&n(a,p)}else if(i.startsWith(`${l.Vars.Env}:`)){let o=i.split(`${l.Vars.Env}:`)[1],p=t.vars?.[o];p&&n(a,p)}else i===l.Source.UserWallet&&t.user?.wallet?n(a,t.user.wallet):n(a,i)}),JSON.parse(r)}static async applyRootGlobals(t,e){let r=JSON.stringify(t),n={config:e,chain:I(e)};return Object.values(l.Globals).forEach(a=>{let i=a.Accessor(n);i!=null&&(r=r.replace(new RegExp(`{{${a.Placeholder}}}`,"g"),i.toString()))}),JSON.parse(r)}static async applyActionGlobals(t,e){let r=await w.getChainInfoForAction(t,e),n=JSON.stringify(e),a={config:t,chain:r};return Object.values(l.Globals).forEach(i=>{let o=i.Accessor(a);o!=null&&(n=n.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(n)}};import{AbiRegistry as te,Address as S,AddressValue as Wt,BytesValue as v,SmartContractTransactionsFactory as He,TransactionsFactoryConfig as Me}from"@multiversx/sdk-core/out";var dt={buildInfo:{rustc:{version:"1.86.0",commitHash:"05f9846f893b09a1be1fc8560e33fc3c815cfecb",commitDate:"2025-03-31",channel:"Stable",short:"rustc 1.86.0 (05f9846f8 2025-03-31)"},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:"forceRemoveAlias",mutability:"mutable",inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"verifyWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"transferOwnership",mutability:"mutable",inputs:[{name:"warp",type:"bytes"},{name:"new_owner",type:"Address"}],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:"addAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"removeAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"ConfigView"}]},{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}]},{name:"setChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"},{name:"native_token",type:"bytes"}],outputs:[]},{name:"removeChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"}],outputs:[]},{name:"getChain",mutability:"readonly",inputs:[{name:"name",type:"bytes"}],outputs:[{type:"ChainView"}]},{name:"getChains",mutability:"readonly",inputs:[],outputs:[{type:"variadic<ChainView>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0},{name:"trust",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},{name:"trust",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}]},{identifier:"ownershipTransferred",inputs:[{name:"warp",type:"bytes",indexed:!0},{name:"old_owner",type:"Address",indexed:!0},{name:"new_owner",type:"Address",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{ChainView:{type:"struct",fields:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"},{name:"native_token",type:"bytes"}]},ConfigView:{type:"struct",fields:[{name:"unit_price",type:"BigUint"},{name:"admins",type:"List<Address>"}]},InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"owner",type:"Address"},{name:"created_at",type:"u64"},{name:"upgraded_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var Y=s=>({hash:s.hash.toString("hex"),alias:s.alias?.toString()||null,trust:s.trust.toString(),owner:s.owner.toString(),createdAt:s.created_at.toNumber(),upgradedAt:s.upgraded_at?.toNumber(),brand:s.brand?.toString("hex")||null,upgrade:s.upgrade?.toString("hex")||null}),Kt=s=>({unitPrice:BigInt(s.unit_price.toString()),admins:s.admins.map(t=>t.toBech32())});import{Address as ve,AddressValue as be,BigUIntType as Ae,BigUIntValue as Jt,BooleanValue as xe,BytesValue as Be,CodeMetadata as Se,CodeMetadataValue as Ee,CompositeType as Re,CompositeValue as Pe,Field as mt,FieldDefinition as ht,List as Ve,NothingValue as Ne,OptionalValue as yt,OptionValue as wt,StringValue as Ue,Struct as Fe,StructType as ke,TokenIdentifierType as Oe,TokenIdentifierValue as Xt,U16Value as $e,U32Value as Le,U64Type as _e,U64Value as Yt,U8Value as qe,VariadicValue as De}from"@multiversx/sdk-core/out";var Zr=(s,t)=>s?wt.newProvided(s):t?wt.newMissingTyped(t):wt.newMissing(),tn=(s,t)=>s?new yt(s.getType(),s):t?new yt(t):yt.newMissing(),en=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let t=s[0].getType();return new Ve(t,s)},rn=s=>De.fromItems(...s),nn=s=>{let t=s.map(e=>e.getType());return new Pe(new Re(...t),s)},U=s=>Ue.fromUTF8(s),an=s=>new qe(s),sn=s=>new $e(s),Zt=s=>new Le(s),on=s=>new Yt(s),cn=s=>new Jt(BigInt(s)),pn=s=>new xe(s),un=s=>new be(ve.newFromBech32(s)),ln=s=>new Xt(s),fn=s=>Be.fromHex(s),gn=s=>new Fe(new ke("EsdtTokenPayment",[new ht("token_identifier","",new Oe),new ht("token_nonce","",new _e),new ht("amount","",new Ae)]),[new mt(new Xt(s.token.identifier),"token_identifier"),new mt(new Yt(BigInt(s.token.nonce)),"token_nonce"),new mt(new Jt(BigInt(s.amount)),"amount")]),dn=s=>new Ee(Se.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),mn=()=>new Ne;var F=class{constructor(t){this.config=t,this.cache=new V(t.cache?.type),this.registryConfig={unitPrice:BigInt(0),admins:[]}}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e,r){if(this.registryConfig.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 n=S.newFromBech32(this.config.user.wallet),a=()=>this.isCurrentUserAdmin()?BigInt(0):e&&r?this.registryConfig.unitPrice*BigInt(3):e?this.registryConfig.unitPrice*BigInt(2):this.registryConfig.unitPrice,i=()=>e&&r?[v.fromHex(t),v.fromUTF8(e),v.fromHex(r)]:e?[v.fromHex(t),v.fromUTF8(e)]:[v.fromHex(t)];return this.getFactory().createTransactionForExecute(n,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:a(),arguments:i()})}createWarpUnregisterTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[v.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.registryConfig.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=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[v.fromUTF8(t),v.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[v.fromHex(t),v.fromUTF8(e)]})}createWarpVerifyTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[v.fromHex(t)]})}createWarpTransferOwnershipTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"transferOwnership",gasLimit:BigInt(1e7),arguments:[v.fromHex(t),new Wt(new S(e))]})}createBrandRegisterTransaction(t){if(this.registryConfig.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=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[v.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[v.fromHex(t),v.fromHex(e)]})}async getInfoByAlias(t,e){try{let r=B.RegistryInfo(this.config.env,t),n=e?this.cache.get(r):null;if(n)return y.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let a=this.getRegistryContractAddress(),i=this.getController(),o=i.createQuery({contract:a,function:"getInfoByAlias",arguments:[v.fromUTF8(t)]}),p=await i.runQuery(o),[c]=i.parseQueryResponse(p),u=c?Y(c):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}}catch{return{registryInfo:null,brand:null}}}async getInfoByHash(t,e){try{let r=B.RegistryInfo(this.config.env,t);if(e){let f=this.cache.get(r);if(f)return y.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),f}let n=this.getRegistryContractAddress(),a=this.getController(),i=a.createQuery({contract:n,function:"getInfoByHash",arguments:[v.fromHex(t)]}),o=await a.runQuery(i),[p]=a.parseQueryResponse(o),c=p?Y(p):null,u=c?.brand?await this.fetchBrand(c.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:c,brand:u},e.ttl),{registryInfo:c,brand:u}}catch{return{registryInfo:null,brand:null}}}async getUserWarpRegistryInfos(t){try{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 Wt(new S(e))]}),i=await n.runQuery(a),[o]=n.parseQueryResponse(i);return o.map(Y)}catch{return[]}}async getUserBrands(t){try{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 Wt(new S(e))]}),i=await n.runQuery(a),[o]=n.parseQueryResponse(i),p=o.map(f=>f.toString("hex")),c={ttl:365*24*60*60};return(await Promise.all(p.map(f=>this.fetchBrand(f,c)))).filter(f=>f!==null)}catch{return[]}}async getChainInfos(t){let e=B.ChainInfos(this.config.env);if(t&&t.ttl){let c=this.cache.get(e);if(c)return y.info("WarpRegistry (getChainInfos): ChainInfos found in cache"),c}let r=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:r,function:"getChains",arguments:[]}),i=await n.runQuery(a),[o]=n.parseQueryResponse(i),p=o.map(nt);if(t&&t.ttl){for(let c of p)this.cache.set(B.ChainInfo(this.config.env,c.chain),c,t.ttl);this.cache.set(e,p,t.ttl)}return p}async getChainInfo(t,e){try{let r=B.ChainInfo(this.config.env,t),n=e?this.cache.get(r):null;if(n)return y.info(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let a=this.getRegistryContractAddress(),i=this.getController(),o=i.createQuery({contract:a,function:"getChain",arguments:[v.fromUTF8(t)]}),p=await i.runQuery(o),[c]=i.parseQueryResponse(p),u=c?nt(c):null;return e&&e.ttl&&u&&this.cache.set(r,u,e.ttl),u}catch{return null}}async setChain(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"setChain",gasLimit:BigInt(1e7),arguments:[U(t.name),U(t.displayName),U(t.chainId),Zt(t.blockTime),U(t.addressHrp),U(t.apiUrl),U(t.explorerUrl),U(t.nativeToken)]})}async removeChain(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=S.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"removeChain",gasLimit:BigInt(1e7),arguments:[U(t)]})}async fetchBrand(t,e){let r=B.Brand(this.config.env,t),n=e?this.cache.get(r):null;if(n)return y.info(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let a=I(this.config),o=w.getChainEntrypoint(a,this.config.env).createNetworkProvider();try{let p=await o.getTransaction(t),c=JSON.parse(p.data.toString());return c.meta={hash:p.hash,creator:p.sender.bech32(),createdAt:new Date(p.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,c,e.ttl),c}catch{return null}}getRegistryContractAddress(){return S.newFromBech32(this.config.registry?.contract||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=r?Kt(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let t=I(this.config),e=new Me({chainID:t.chainId}),r=te.create(dt);return new He({config:e,abi:r})}getController(){let t=I(this.config),e=w.getChainEntrypoint(t,this.config.env),r=te.create(dt);return e.createSmartContractController(r)}isCurrentUserAdmin(){return!!this.config.user?.wallet&&this.registryConfig.admins.includes(this.config.user.wallet)}};var Z=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(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),i=(await Promise.all(n)).filter(c=>c.match),o=i.length>0,p=i.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:p}}async detect(t,e){let r={match:!1,url:t,warp:null,registryInfo:null,brand:null},n=t.startsWith(l.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):w.getInfoFromPrefixedIdentifier(t);if(!n)return r;try{let{type:a,identifierBase:i}=n,o=new X(this.config),p=new F(this.config),c=null,u=null,f=null;if(a==="hash"){c=await o.createFromTransactionHash(i,e);let d=await p.getInfoByHash(i,e);u=d.registryInfo,f=d.brand}else if(a==="alias"){let d=await p.getInfoByAlias(i,e);u=d.registryInfo,f=d.brand,d.registryInfo&&(c=await o.createFromTransactionHash(d.registryInfo.hash,e))}let h=c?await O.apply(this.config,c):null;return h?{match:!0,url:t,warp:h,registryInfo:u,brand:f}:r}catch(a){return y.error("Error detecting warp link",a),r}}build(t,e){let r=this.config.clientUrl||T.DefaultClientUrl(this.config.env),n=t===l.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+l.IdentifierParamSeparator+e);return T.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${l.IdentifierParamName}=${n}`}buildFromPrefixedIdentifier(t){let e=w.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.identifierBase):""}generateQrCode(t,e,r=512,n="white",a="black",i="#23F7DD"){let o=this.build(t,e);return new je({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=T.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 w.getInfoFromPrefixedIdentifier(i)}};var Ke="https://",w=class{static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t);if(e.includes(l.IdentifierParamSeparator)){let[n,a]=e.split(l.IdentifierParamSeparator),i=a.split("?")[0];return{type:n,identifier:a,identifierBase:i}}let r=e.split("?")[0];return r.length===64?{type:l.IdentifierType.Hash,identifier:e,identifierBase:r}:{type:l.IdentifierType.Alias,identifier:e,identifierBase:r}}static getNextInfo(t,e,r,n){let a=e.actions?.[r]?.next||e.next||null;if(!a)return null;if(a.startsWith(Ke))return[{identifier:null,url:a}];let[i,o]=a.split("?");if(!o)return[{identifier:i,url:this.buildNextUrl(i,t)}];let p=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(p.length===0){let g=z(o,{...e.vars,...n}),m=g?`${i}?${g}`:i;return[{identifier:m,url:this.buildNextUrl(m,t)}]}let c=p[0];if(!c)return[];let u=c.match(/{{([^[]+)\[\]/),f=u?u[1]:null;if(!f||n[f]===void 0)return[];let h=Array.isArray(n[f])?n[f]:[n[f]];if(h.length===0)return[];let d=p.filter(g=>g.includes(`{{${f}[]`)).map(g=>{let m=g.match(/\[\](\.[^}]+)?}}/),W=m&&m[1]||"";return{placeholder:g,field:W?W.slice(1):"",regex:new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(g=>{let m=o;for(let{regex:x,field:R}of d){let C=R?this.getNestedValue(g,R):g;if(C==null)return null;m=m.replace(x,C)}if(m.includes("{{")||m.includes("}}"))return null;let W=m?`${i}?${m}`:i;return{identifier:W,url:this.buildNextUrl(W,t)}}).filter(g=>g!==null)}static buildNextUrl(t,e){let[r,n]=t.split("?"),a=this.getInfoFromPrefixedIdentifier(r)||{type:"alias",identifier:r,identifierBase:r},o=new Z(e).build(a.type,a.identifierBase);if(!n)return o;let p=new URL(o);return new URLSearchParams(n).forEach((c,u)=>p.searchParams.set(u,c)),p.toString().replace(/\/\?/,"?")}static getNestedValue(t,e){return e.split(".").reduce((r,n)=>r?.[n],t)}static async getChainInfoForAction(t,e,r){if(r){let n=await this.tryGetChainFromInputs(t,e,r);if(n)return n}return this.getDefaultChainInfo(t,e)}static async tryGetChainFromInputs(t,e,r){let n=e.inputs?.findIndex(u=>u.position==="chain");if(n===-1||n===void 0)return null;let a=r[n];if(!a)throw new Error("WarpUtils: Chain input not found");let o=new N().stringToNative(a)[1],c=await new F(t).getChainInfo(o);if(!c)throw new Error(`WarpUtils: Chain info not found for ${o}`);return c}static async getDefaultChainInfo(t,e){if(!e.chain)return I(t);let n=await new F(t).getChainInfo(e.chain,{ttl:K.OneWeek});if(!n)throw new Error(`WarpUtils: Chain info not found for ${e.chain}`);return n}static getChainEntrypoint(t,e){let r="warp-sdk",n="api";return e==="devnet"?new Qe(t.apiUrl,n,r):e==="testnet"?new ze(t.apiUrl,n,r):new Ge(t.apiUrl,n,r)}};var re=class{constructor(t){this.pendingBrand={protocol:q("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=I(this.config),r=new Je({chainID:e.chainId}),n=new Xe({config:r}),a=ee.newFromBech32(this.config.user.wallet),i=JSON.stringify(t);return n.createTransactionForNativeTokenTransfer(a,{receiver:ee.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))})}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.ensureValidSchema(r),r}async createFromTransaction(t,e=!1){return await this.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=I(this.config),n=w.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let a=await n.getTransaction(t);return this.createFromTransaction(a)}catch(a){return y.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.schema?.brand||T.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),a=new Ye({strict:!1}),i=a.compile(n);if(!i(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(i.errors)}`)}};import{Address as Ze,TransactionsFactoryConfig as tr,TransferTransactionsFactory as er}from"@multiversx/sdk-core";var tt=class{constructor(t){this.cache=new V;this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=I(this.config),r=new tr({chainID:e.chainId}),n=new er({config:r}),a={protocol:q("abi"),content:t},i=Ze.newFromBech32(this.config.user.wallet),o=JSON.stringify(a),p=n.createTransactionForTransfer(i,{receiver:i,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(o))});return p.gasLimit=p.gasLimit+BigInt(2e6),p}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(this.config.env,t);if(e){let o=this.cache.get(r);if(o)return y.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),o}let n=I(this.config),i=w.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await i.getTransaction(t),p=await this.createFromTransaction(o);return e&&e.ttl&&p&&this.cache.set(r,p,e.ttl),p}catch(o){return y.error("WarpAbiBuilder: Error creating from transaction hash",o),null}}};import{AbiRegistry as Tt,Address as It,ArgSerializer as pr,SmartContractTransactionsFactory as ur,Token as oe,TokenComputer as lr,TokenTransfer as ce,TransactionsFactoryConfig as fr,TransferTransactionsFactory as gr}from"@multiversx/sdk-core";import{SmartContractTransactionsOutcomeParser as rr,TransactionEventsParser as nr,findEventsByFirstTopic as ir}from"@multiversx/sdk-core/out";var Ct=s=>{if(s==="out")return 1;let t=s.match(/^out\[(\d+)\]/);return t?parseInt(t[1],10):(s.startsWith("out.")||s.startsWith("event."),null)},ar=(s,t)=>t.reduce((e,r)=>e&&e[r]!==void 0?e[r]:null,s),ne=async(s,t,e,r,n,a)=>{let i=[],o={};if(!t.results||e.type!=="contract")return{values:i,results:o};if(!Object.values(t.results).some(d=>d.includes("out")||d.includes("event"))){for(let[d,b]of Object.entries(t.results))o[d]=b;return{values:i,results:await et(t,o,n,a)}}let c=await s.getAbiForAction(e),u=new nr({abi:c}),h=new rr({abi:c}).parseExecute({transactionOnNetwork:r,function:e.func||void 0});for(let[d,b]of Object.entries(t.results)){if(b.startsWith(l.Transform.Prefix))continue;if(b.startsWith("input.")){o[d]=b;continue}let g=Ct(b);if(g!==null&&g!==n){o[d]=null;continue}let[m,W,x]=b.split(".");if(m==="event"){if(!W||isNaN(Number(x)))continue;let R=Number(x),C=ir(r,W),H=u.parseEvents({events:C})[0],P=Object.values(H)[R]||null;i.push(P),o[d]=P&&P.valueOf()}else if(m==="out"||m.startsWith("out[")){if(!W)continue;let R=Number(W),C=h.values[R-1]||null;x&&(C=C[x]||null),C&&typeof C=="object"&&(C="toFixed"in C?C.toFixed():C.valueOf()),i.push(C),o[d]=C&&C.valueOf()}else o[d]=b}return{values:i,results:await et(t,o,n,a)}},ie=async(s,t,e,r)=>{let n=new N,a=t.map(c=>n.typedToString(c)),i=t.map(c=>n.typedToNative(c)[1]),o={};if(!s.results)return{values:a,results:o};let p=c=>{let u=c.split(".").slice(1).map(h=>parseInt(h)-1);if(u.length===0)return;let f=i[u[0]];for(let h=1;h<u.length;h++){if(f==null)return;f=f[u[h]]}return f};for(let[c,u]of Object.entries(s.results)){if(u.startsWith(l.Transform.Prefix))continue;let f=Ct(u);if(f!==null&&f!==e){o[c]=null;continue}u.startsWith("out.")||u==="out"||u.startsWith("out[")?o[c]=p(u)||null:o[c]=u}return{values:a,results:await et(s,o,e,r)}},ae=async(s,t,e,r)=>{let n=[],a={};for(let[i,o]of Object.entries(s.results||{})){if(o.startsWith(l.Transform.Prefix))continue;let p=Ct(o);if(p!==null&&p!==e){a[i]=null;continue}let[c,...u]=o.split(".");if(c==="out"||c.startsWith("out[")){let f=u.length===0?t?.data||t:ar(t,u);n.push(f),a[i]=f}else a[i]=o}return{values:n,results:await et(s,a,e,r)}};var et=async(s,t,e,r)=>{if(!s.results)return t;let n={...t};return n=sr(n,s,e,r),n=await or(s,n),n},sr=(s,t,e,r)=>{let n={...s},a=$(t,e)?.inputs||[],i=new N;for(let[o,p]of Object.entries(n))if(typeof p=="string"&&p.startsWith("input.")){let c=p.split(".")[1],u=a.findIndex(h=>h.as===c||h.name===c),f=u!==-1?r[u]?.value:null;n[o]=f?i.stringToNative(f)[1]:null}return n},or=async(s,t)=>{if(!s.results)return t;let e={...t},r=Object.entries(s.results).filter(([,n])=>n.startsWith(l.Transform.Prefix)).map(([n,a])=>({key:n,code:a.substring(l.Transform.Prefix.length)}));for(let{key:n,code:a}of r)try{let{runInVm:i}=await import("./vm-JCVDACTR.mjs");e[n]=await i(a,e)}catch(i){y.error(`Transform error for result '${n}':`,i),e[n]=null}return e};var cr=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],se=s=>cr.find(t=>t.id===s)||null;var rt=class{constructor(t){this.config=t}async getContract(t,e){try{let a=await w.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}`);return{address:t,owner:a.ownerAddress,verified:a.isVerified||!1}}catch(r){return y.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t,e){try{let a=await w.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}/verification`);return{codeHash:a.codeHash,abi:a.source.abi}}catch(r){return y.error("WarpContractLoader: getVerificationInfo error",r),null}}};var pe=class{constructor(t){if(!t.currentUrl)throw new Error("WarpActionExecutor: currentUrl config not set");this.config=t,this.url=new URL(t.currentUrl),this.serializer=new N,this.contractLoader=new rt(t),this.cache=new V(t.cache?.type),this.registry=new F(t)}async createTransactionForExecute(t,e,r){let n=$(t,e);if(!this.config.user?.wallet)throw new Error("WarpActionExecutor: user address not set");let a=It.newFromBech32(this.config.user.wallet),i=await this.getTxComponentsFromInputs(n,r,a),o=new fr({chainID:i.chain.chainId}),p=i.args.map(u=>this.serializer.stringToTyped(u)),c=null;if(n.type==="transfer")c=new gr({config:o}).createTransactionForTransfer(a,{receiver:i.destination,nativeAmount:i.value,tokenTransfers:i.transfers,data:i.data?new Uint8Array(i.data):void 0});else if(n.type==="contract"&&i.destination.isSmartContract())c=new ur({config:o}).createTransactionForExecute(a,{contract:i.destination,function:"func"in n&&n.func||"",gasLimit:"gasLimit"in n?BigInt(n.gasLimit||0):0n,arguments:p,tokenTransfers:i.transfers,nativeTransferAmount:i.value});else{if(n.type==="query")throw new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead");if(n.type==="collect")throw new Error("WarpActionExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead")}if(!c)throw new Error(`WarpActionExecutor: Invalid action type (${n.type})`);return this.cache.set(B.LastWarpExecutionInputs(this.config.env,t.meta?.hash||"",e),i.resolvedInputs,K.OneWeek),c}async getTransactionExecutionResults(t,e,r){let n=await O.apply(this.config,t),a=$(n,e),i=this.cache.get(B.LastWarpExecutionInputs(this.config.env,t.meta?.hash||"",e))??[],{values:o,results:p}=await ne(this,n,a,r,e,i),c=w.getNextInfo(this.config,n,e,p),u=this.getPreparedMessages(n,p);return{success:r.status.isSuccessful(),warp:n,action:e,user:this.config.user?.wallet||null,txHash:r.hash,next:c,values:o,results:p,messages:u}}async executeQuery(t,e,r){let n=$(t,e);if(!n)throw new Error("WarpActionExecutor: Action not found");if(!n.func)throw new Error("WarpActionExecutor: Function not found");let a=await O.apply(this.config,t),i=await this.getAbiForAction(n),{chain:o,args:p,resolvedInputs:c}=await this.getTxComponentsFromInputs(n,r),u=p.map(L=>this.serializer.stringToTyped(L)),f=w.getChainEntrypoint(o,this.config.env),h=It.newFromBech32(n.address),d=f.createSmartContractController(i),b=d.createQuery({contract:h,function:n.func,arguments:u}),g=await d.runQuery(b),m=g.returnCode==="ok",W=new pr,x=i.getEndpoint(g.function),R=g.returnDataParts.map(L=>Buffer.from(L)),C=W.buffersToValues(R,x.output),{values:H,results:P}=await ie(a,C,e,c),Q=w.getNextInfo(this.config,a,e,P);return{success:m,warp:a,action:e,user:this.config.user?.wallet||null,txHash:null,next:Q,values:H,results:P,messages:this.getPreparedMessages(a,P)}}async executeCollect(t,e,r,n){let a=$(t,e);if(!a)throw new Error("WarpActionExecutor: Action not found");let i=await w.getChainInfoForAction(this.config,a),o=await O.apply(this.config,t),p=await this.getResolvedInputs(i,a,r),c=this.getModifiedInputs(p),u=g=>{if(!g.value)return null;let m=this.serializer.stringToNative(g.value)[1];if(g.input.type==="biguint")return m.toString();if(g.input.type==="esdt"){let W=m;return{token:W.token.identifier,nonce:W.token.nonce.toString(),amount:W.amount.toString()}}else return m},f=new Headers;f.set("Content-Type","application/json"),f.set("Accept","application/json"),Object.entries(a.destination.headers||{}).forEach(([g,m])=>{f.set(g,m)});let h=Object.fromEntries(c.map(g=>[g.input.as||g.input.name,u(g)])),d=a.destination.method||"GET",b=d==="GET"?void 0:JSON.stringify({...h,...n});y.info("Executing collect",{url:a.destination.url,method:d,headers:f,body:b});try{let g=await fetch(a.destination.url,{method:d,headers:f,body:b}),m=await g.json(),{values:W,results:x}=await ae(o,m,e,c),R=w.getNextInfo(this.config,o,e,x);return{success:g.ok,warp:o,action:e,user:this.config.user?.wallet||null,txHash:null,next:R,values:W,results:{...x,_DATA:m},messages:this.getPreparedMessages(o,x)}}catch(g){return y.error("WarpActionExecutor: Error executing collect",g),{success:!1,warp:o,action:e,user:this.config.user?.wallet||null,txHash:null,next:null,values:[],results:{_DATA:g},messages:{}}}}async getTxComponentsFromInputs(t,e,r){let n=await w.getChainInfoForAction(this.config,t,e),a=await this.getResolvedInputs(n,t,e),i=this.getModifiedInputs(a),o=i.find(A=>A.input.position==="receiver")?.value,p="address"in t?t.address:null,c=o?.split(":")[1]||p||r?.toBech32();if(!c)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let u=It.newFromBech32(c),f=this.getPreparedArgs(t,i),h=i.find(A=>A.input.position==="value")?.value||null,d="value"in t?t.value:null,b=BigInt(h?.split(":")[1]||d||0),g=i.filter(A=>A.input.position==="transfer"&&A.value).map(A=>A.value),m="transfers"in t?t.transfers:[],W=[...m?.map(this.toTypedTransfer)||[],...g?.map(A=>this.serializer.stringToNative(A)[1])||[]],x=W.length===1&&g.length===1&&!m?.length,R=W[0]?.token.identifier===`${n.nativeToken}-000000`,C=!i.some(A=>A.value&&A.input.position!=="transfer"&&A.input.type==="esdt");x&&R&&C&&(b+=W[0].amount,W=[]);let H=i.find(A=>A.input.position==="data")?.value,P="data"in t?t.data||"":null,Q=H||P||null,L=Q?this.serializer.stringToTyped(Q).valueOf():null,le=L?Buffer.from(L):null;return{chain:n,destination:u,args:f,value:b,transfers:W,data:le,resolvedInputs:i}}async getResolvedInputs(t,e,r){let n=e.inputs||[],a=await Promise.all(r.map(o=>this.preprocessInput(t,o))),i=(o,p)=>{if(o.source==="query"){let c=this.url.searchParams.get(o.name);return c?this.serializer.nativeToString(o.type,c):null}else return o.source===l.Source.UserWallet?this.config.user?.wallet?this.serializer.nativeToString("address",this.config.user.wallet):null:a[p]||null};return n.map((o,p)=>{let c=i(o,p);return{input:o,value:c||(o.default!==void 0?this.serializer.nativeToString(o.type,o.default):null)}})}getModifiedInputs(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 o=G(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=G(a,+n);return{...e,value:`${e.input.type}:${i}`}}}else return e})}async preprocessInput(t,e){try{let[r,n]=e.split(l.ArgParamsSeparator,2);if(r==="esdt"){let[a,i,o,p]=n.split(l.ArgCompositeSeparator);if(p)return e;let c=new oe({identifier:a,nonce:BigInt(i)});if(!new lr().isFungible(c))return e;let h=se(a)?.decimals;if(h||(h=(await(await fetch(`${t.apiUrl}/tokens/${a}`)).json()).decimals),!h)throw new Error(`WarpActionExecutor: Decimals not found for token ${a}`);let d=new ce({token:c,amount:G(o,h)});return this.serializer.nativeToString(r,d)+l.ArgCompositeSeparator+h}return e}catch{return e}}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 Tt.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,z(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 tt(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 Tt.create(n.content)}else{let r=await(await fetch(t.abi)).json();return Tt.create(r)}}toTypedTransfer(t){return new ce({token:new oe({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var ue=class{constructor(t){this.config=t}async search(t,e,r){if(!this.config.index?.url)throw new Error("WarpIndex: Index URL is not set");try{let n=await fetch(this.config.index?.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.index?.apiKey}`,...r},body:JSON.stringify({[this.config.index?.searchParamName||"search"]:t,...e})});if(!n.ok)throw new Error(`WarpIndex: search failed with status ${n.status}`);return(await n.json()).hits}catch(n){throw y.error("WarpIndex: Error searching for warps: ",n),n}}};export{re as BrandBuilder,B as CacheKey,K as CacheTtl,tt as WarpAbiBuilder,pe as WarpActionExecutor,N as WarpArgSerializer,X as WarpBuilder,V as WarpCache,T as WarpConfig,l as WarpConstants,rt as WarpContractLoader,ue as WarpIndex,O as WarpInterpolator,Z as WarpLink,_ as WarpProtocolVersions,F as WarpRegistry,w as WarpUtils,J as WarpValidator,un as address,cn as biguint,pn as boolean,dn as codemeta,nn as composite,gn as esdt,wr as getChainExplorerUrl,q as getLatestProtocolIdentifier,I as getMainChainInfo,$ as getWarpActionByIndex,fn as hex,en as list,mn as nothing,Zr as option,tn as optional,z as replacePlaceholders,G as shiftBigintBy,U as string,vt as toPreviewText,nt as toTypedChainInfo,ln as token,sn as u16,Zt as u32,on as u64,an as u8,rn as variadic};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "3.0.0-alpha.22",
3
+ "version": "3.0.0-alpha.24",
4
4
  "description": "",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",