@vleap/warps 2.3.0-alpha.1 → 2.3.0-alpha.3

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.js CHANGED
@@ -1,5 +1,5 @@
1
1
  "use strict";var At=Object.create;var rt=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var Bt=Object.getOwnPropertyNames;var St=Object.getPrototypeOf,Et=Object.prototype.hasOwnProperty;var Pt=(a,t)=>{for(var e in t)rt(a,e,{get:t[e],enumerable:!0})},mt=(a,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Bt(t))!Et.call(a,n)&&n!==e&&rt(a,n,{get:()=>t[n],enumerable:!(r=xt(t,n))||r.enumerable});return a};var st=(a,t,e)=>(e=a!=null?At(St(a)):{},mt(t||!a||!a.__esModule?rt(e,"default",{value:a,enumerable:!0}):e,a)),Rt=a=>mt(rt({},"__esModule",{value:!0}),a);var re={};Pt(re,{BrandBuilder:()=>pt,CacheKey:()=>P,CacheTtl:()=>ct,Config:()=>A,WarpAbiBuilder:()=>tt,WarpActionExecutor:()=>dt,WarpArgSerializer:()=>_,WarpBuilder:()=>Y,WarpCache:()=>V,WarpConstants:()=>f,WarpContractLoader:()=>et,WarpIndex:()=>gt,WarpInterpolator:()=>U,WarpLink:()=>Z,WarpProtocolVersions:()=>F,WarpRegistry:()=>$,WarpUtils:()=>y,WarpValidator:()=>X,address:()=>Gt,biguint:()=>jt,boolean:()=>Qt,codemeta:()=>Xt,composite:()=>Lt,esdt:()=>Jt,getChainExplorerUrl:()=>Vt,getLatestProtocolIdentifier:()=>O,getMainChainInfo:()=>v,getWarpActionByIndex:()=>M,hex:()=>Kt,list:()=>kt,nothing:()=>Yt,option:()=>Ft,optional:()=>Ot,replacePlaceholders:()=>z,shiftBigintBy:()=>G,string:()=>_t,toPreviewText:()=>ot,toTypedChainInfo:()=>nt,token:()=>zt,u16:()=>Mt,u32:()=>Ht,u64:()=>Dt,u8:()=>qt,variadic:()=>$t});module.exports=Rt(re);var L=require("@multiversx/sdk-core"),Tt=st(require("ajv"));var f={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:a=>a.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:a=>a.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:a=>a.chain.explorerUrl}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"},Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}};var F={Warp:"2.0.1",Brand:"0.1.0",Abi:"0.1.0"},A={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${F.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${F.Brand}.schema.json`,DefaultClientUrl:a=>a==="devnet"?"https://devnet.usewarp.to":a==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],MainChain:{Name:"multiversx",DisplayName:"MultiversX",ApiUrl:a=>a==="devnet"?"https://devnet-api.multiversx.com":a==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:a=>a==="devnet"?"https://devnet-explorer.multiversx.com":a==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:a=>6e3,AddressHrp:"erd",ChainId:a=>a==="devnet"?"D":a==="testnet"?"T":"1"},Registry:{Contract:a=>a==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":a==="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 v=a=>({name:A.MainChain.Name,displayName:A.MainChain.DisplayName,chainId:A.MainChain.ChainId(a.env),blockTime:A.MainChain.BlockTime(a.env),addressHrp:A.MainChain.AddressHrp,apiUrl:A.MainChain.ApiUrl(a.env),explorerUrl:A.MainChain.ExplorerUrl(a.env)}),Vt=(a,t)=>a.explorerUrl+(t?"/"+t:""),O=a=>{if(a==="warp")return`warp:${F.Warp}`;if(a==="brand")return`brand:${F.Brand}`;if(a==="abi")return`abi:${F.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${a}`)},M=(a,t)=>a?.actions[t-1],nt=a=>({name:a.name.toString(),displayName:a.display_name.toString(),chainId:a.chain_id.toString(),blockTime:a.block_time.toNumber(),addressHrp:a.address_hrp.toString(),apiUrl:a.api_url.toString(),explorerUrl:a.explorer_url.toString()}),G=(a,t)=>{let e=a.toString(),[r,n=""]=e.split("."),i=Math.abs(t);if(t>0)return BigInt(r+n.padEnd(i,"0"));if(t<0){let s=r+n;if(i>=s.length)return 0n;let c=s.slice(0,-i)||"0";return BigInt(c)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},ot=(a,t=100)=>{if(!a)return"";let e=a.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},z=(a,t)=>a.replace(/\{\{([^}]+)\}\}/g,(e,r)=>t[r]||"");var D=require("@multiversx/sdk-core");var K=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let r=JSON.parse(e);return Date.now()>r.expiresAt?(localStorage.removeItem(this.getKey(t)),null):r.value}catch{return null}}set(t,e,r){let n={value:e,expiresAt:Date.now()+r*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(n))}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 N=class N{get(t){let e=N.cache.get(t);return e?Date.now()>e.expiresAt?(N.cache.delete(t),null):e.value:null}set(t,e,r){let n=Date.now()+r*1e3;N.cache.set(t,{value:e,expiresAt:n})}forget(t){N.cache.delete(t)}clear(){N.cache.clear()}};N.cache=new Map;var J=N;var ct={OneMinute:60,OneHour:60*60,OneDay:60*60*24,OneWeek:60*60*24*7,OneMonth:60*60*24*30,OneYear:60*60*24*365},P={Warp:a=>`warp:${a}`,WarpAbi:a=>`warp-abi:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`,ChainInfo:a=>`chain:${a}`,ChainInfos:()=>"chains"},V=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new K:t==="memory"?new J:typeof window<"u"&&window.localStorage?new K: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()}};var wt=st(require("qr-code-styling"));var k=require("@multiversx/sdk-core");var H=class H{static info(...t){H.isTestEnv||console.info(...t)}static warn(...t){H.isTestEnv||console.warn(...t)}static error(...t){H.isTestEnv||console.error(...t)}};H.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var S=H;var ht=st(require("ajv"));var X=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,i)=>{n&&Object.keys(n).forEach(s=>{s!==s.toUpperCase()&&e.push(`${i} name '${s}' 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);return t.results&&!n?["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(),i=new ht.default,s=i.compile(n);return s(t)?[]:[`Schema validation failed: ${i.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var Y=class{constructor(t){this.pendingWarp={protocol:O("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=v(this.config),r=new k.TransactionsFactoryConfig({chainID:e.chainId}),n=new k.TransferTransactionsFactory({config:r}),i=k.Address.newFromBech32(this.config.user.wallet),s=JSON.stringify(t),c=n.createTransactionForTransfer(i,{receiver:k.Address.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(s))});return c.gasLimit=c.gasLimit+BigInt(2e6),c}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=P.Warp(t);if(e){let c=this.cache.get(r);if(c)return S.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),c}let n=v(this.config),s=y.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let c=await s.getTransaction(t),u=await this.createFromTransaction(c);return e&&e.ttl&&u&&this.cache.set(r,u,e.ttl),u}catch(c){return console.error("WarpBuilder: Error creating from transaction hash",c),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return ot(t,e)}ensure(t,e){if(!t)throw new Error(e)}async validate(t){let r=await new X(this.config).validate(t);if(!r.valid)throw new Error(r.errors.join(`
2
- `))}};var U=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=(i,s)=>{r=r.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(e.vars).forEach(([i,s])=>{if(typeof s!="string")n(i,s);else if(s.startsWith(`${f.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let c=s.split(`${f.Vars.Query}:`)[1],u=new URLSearchParams(t.currentUrl.split("?")[1]).get(c);u&&n(i,u)}else if(s.startsWith(`${f.Vars.Env}:`)){let c=s.split(`${f.Vars.Env}:`)[1],u=t.vars?.[c];u&&n(i,u)}else s===f.Source.UserWallet&&t.user?.wallet?n(i,t.user.wallet):n(i,s)}),JSON.parse(r)}static async applyRootGlobals(t,e){let r=JSON.stringify(t),n={config:e,chain:v(e)};return Object.values(f.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}static async applyActionGlobals(t,e){let r=await y.getChainInfoForAction(t,e),n=JSON.stringify(e),i={config:t,chain:r};return Object.values(f.Globals).forEach(s=>{let c=s.Accessor(i);c!=null&&(n=n.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),c.toString()))}),JSON.parse(n)}};var m=require("@multiversx/sdk-core/out");var ut={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"}],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"}]},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 it=a=>({hash:a.hash.toString("hex"),alias:a.alias?.toString()||null,trust:a.trust.toString(),owner:a.owner.toString(),createdAt:a.created_at.toNumber(),upgradedAt:a.upgraded_at?.toNumber(),brand:a.brand?.toString("hex")||null,upgrade:a.upgrade?.toString("hex")||null}),yt=a=>({unitPrice:BigInt(a.unit_price.toString()),admins:a.admins.map(t=>t.toBech32())});var $=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),i=()=>this.isCurrentUserAdmin()?BigInt(0):e&&r?this.registryConfig.unitPrice*BigInt(3):e?this.registryConfig.unitPrice*BigInt(2):this.registryConfig.unitPrice,s=()=>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:i(),arguments:s()})}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=P.RegistryInfo(t),n=e?this.cache.get(r):null;if(n)return S.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),s=this.getController(),c=s.createQuery({contract:i,function:"getInfoByAlias",arguments:[m.BytesValue.fromUTF8(t)]}),u=await s.runQuery(c),[p]=s.parseQueryResponse(u),d=p?it(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=P.RegistryInfo(t);if(e){let g=this.cache.get(r);if(g)return S.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),g}let n=this.getRegistryContractAddress(),i=this.getController(),s=i.createQuery({contract:n,function:"getInfoByHash",arguments:[m.BytesValue.fromHex(t)]}),c=await i.runQuery(s),[u]=i.parseQueryResponse(c),p=u?it(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(),i=n.createQuery({contract:r,function:"getUserWarps",arguments:[new m.AddressValue(new m.Address(e))]}),s=await n.runQuery(i),[c]=n.parseQueryResponse(s);return c.map(it)}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(),i=n.createQuery({contract:r,function:"getUserBrands",arguments:[new m.AddressValue(new m.Address(e))]}),s=await n.runQuery(i),[c]=n.parseQueryResponse(s),u=c.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=P.ChainInfos();if(t&&t.ttl){let p=this.cache.get(e);if(p)return S.info("WarpRegistry (getChainInfos): ChainInfos found in cache"),p}let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getChains",arguments:[]}),s=await n.runQuery(i),[c]=n.parseQueryResponse(s),u=c.map(nt);if(t&&t.ttl){for(let p of u)this.cache.set(P.ChainInfo(p.chain),p,t.ttl);this.cache.set(e,u,t.ttl)}return u}async getChainInfo(t,e){try{let r=P.ChainInfo(t),n=e?this.cache.get(r):null;if(n)return S.info(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),s=this.getController(),c=s.createQuery({contract:i,function:"getChain",arguments:[m.BytesValue.fromUTF8(t)]}),u=await s.runQuery(c),[p]=s.parseQueryResponse(u),d=p?nt(p):null;return e&&e.ttl&&d&&this.cache.set(r,d,e.ttl),d}catch{return null}}async fetchBrand(t,e){let r=P.Brand(t),n=e?this.cache.get(r):null;if(n)return S.info(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let i=v(this.config),c=y.getChainEntrypoint(i,this.config.env).createNetworkProvider();try{let u=await c.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?yt(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let t=v(this.config),e=new m.TransactionsFactoryConfig({chainID:t.chainId}),r=m.AbiRegistry.create(ut);return new m.SmartContractTransactionsFactory({config:e,abi:r})}getController(){let t=v(this.config),e=y.getChainEntrypoint(t,this.config.env),r=m.AbiRegistry.create(ut);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(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)),s=(await Promise.all(n)).filter(p=>p.match),c=s.length>0,u=s.map(p=>({url:p.url,warp:p.warp}));return{match:c,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):y.getInfoFromPrefixedIdentifier(t);if(!n)return r;try{let{type:i,identifierBase:s}=n,c=new Y(this.config),u=new $(this.config),p=null,d=null,g=null;if(i==="hash"){p=await c.createFromTransactionHash(s,e);let b=await u.getInfoByHash(s,e);d=b.registryInfo,g=b.brand}else if(i==="alias"){let b=await u.getInfoByAlias(s,e);d=b.registryInfo,g=b.brand,b.registryInfo&&(p=await c.createFromTransactionHash(b.registryInfo.hash,e))}let T=p?await U.apply(this.config,p):null;return T?{match:!0,url:t,warp:T,registryInfo:d,brand:g}:r}catch(i){return S.error("Error detecting warp link",i),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=y.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.identifierBase):""}generateQrCode(t,e,r=512,n="white",i="black",s="#23F7DD"){let c=this.build(t,e);return new wt.default({type:"svg",width:r,height:r,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:n},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(s)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=A.SuperClientUrls.includes(e.origin),n=e.searchParams.get(f.IdentifierParamName),i=r&&!n?e.pathname.split("/")[1]:n;if(!i)return null;let s=decodeURIComponent(i);return y.getInfoFromPrefixedIdentifier(s)}};var Nt="https://",y=class{static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(f.IdentifierParamSeparator)?e:`${f.IdentifierType.Alias}${f.IdentifierParamSeparator}${e}`,[n,i]=r.split(f.IdentifierParamSeparator),s=i.split("?")[0];return{type:n,identifier:i,identifierBase:s}}static getNextInfo(t,e,r,n){let i=e.actions?.[r]?.next||e.next||null;if(!i)return null;if(i.startsWith(Nt))return[{identifier:null,url:i}];let[s,c]=i.split("?");if(!c)return[{identifier:s,url:this.buildNextUrl(s,t)}];let u=c.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(u.length===0){let h=z(c,{...e.vars,...n}),w=h?`${s}?${h}`:s;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 T=Array.isArray(n[g])?n[g]:[n[g]];if(T.length===0)return[];let b=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 T.map(h=>{let w=c;for(let{regex:C,field:R}of b){let E=R?this.getNestedValue(h,R):h;if(E==null)return null;w=w.replace(C,E)}if(w.includes("{{")||w.includes("}}"))return null;let I=w?`${s}?${w}`:s;return{identifier:I,url:this.buildNextUrl(I,t)}}).filter(h=>h!==null)}static buildNextUrl(t,e){let[r,n]=t.split("?"),i=this.getInfoFromPrefixedIdentifier(r)||{type:"alias",identifier:r,identifierBase:r},c=new Z(e).build(i.type,i.identifierBase);if(!n)return c;let u=new URL(c);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 v(t);let r=await new $(t).getChainInfo(e.chain,{ttl:ct.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 D.DevnetEntrypoint(t.apiUrl,n,r):e==="testnet"?new D.TestnetEntrypoint(t.apiUrl,n,r):new D.MainnetEntrypoint(t.apiUrl,n,r)}};var pt=class{constructor(t){this.pendingBrand={protocol:O("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=v(this.config),r=new L.TransactionsFactoryConfig({chainID:e.chainId}),n=new L.TransferTransactionsFactory({config:r}),i=L.Address.newFromBech32(this.config.user.wallet),s=JSON.stringify(t);return n.createTransactionForNativeTokenTransfer(i,{receiver:L.Address.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(s))})}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=v(this.config),n=y.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let i=await n.getTransaction(t);return this.createFromTransaction(i)}catch(i){return console.error("BrandBuilder: Error creating from transaction hash",i),null}}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||A.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),i=new Tt.default,s=i.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};var l=require("@multiversx/sdk-core/out"),Ft=(a,t)=>a?l.OptionValue.newProvided(a):t?l.OptionValue.newMissingTyped(t):l.OptionValue.newMissing(),Ot=(a,t)=>a?new l.OptionalValue(a.getType(),a):t?new l.OptionalValue(t):l.OptionalValue.newMissing(),kt=a=>{if(a.length===0)throw new Error("Cannot create a list from an empty array");let t=a[0].getType();return new l.List(t,a)},$t=a=>l.VariadicValue.fromItems(...a),Lt=a=>{let t=a.map(e=>e.getType());return new l.CompositeValue(new l.CompositeType(...t),a)},_t=a=>l.StringValue.fromUTF8(a),qt=a=>new l.U8Value(a),Mt=a=>new l.U16Value(a),Ht=a=>new l.U32Value(a),Dt=a=>new l.U64Value(a),jt=a=>new l.BigUIntValue(BigInt(a)),Qt=a=>new l.BooleanValue(a),Gt=a=>new l.AddressValue(l.Address.newFromBech32(a)),zt=a=>new l.TokenIdentifierValue(a),Kt=a=>l.BytesValue.fromHex(a),Jt=a=>new l.Struct(new l.StructType("EsdtTokenPayment",[new l.FieldDefinition("token_identifier","",new l.TokenIdentifierType),new l.FieldDefinition("token_nonce","",new l.U64Type),new l.FieldDefinition("amount","",new l.BigUIntType)]),[new l.Field(new l.TokenIdentifierValue(a.token.identifier),"token_identifier"),new l.Field(new l.U64Value(BigInt(a.token.nonce)),"token_nonce"),new l.Field(new l.BigUIntValue(BigInt(a.amount)),"amount")]),Xt=a=>new l.CodeMetadataValue(l.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(a,"hex")))),Yt=()=>new l.NothingValue;var j=require("@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=v(this.config),r=new j.TransactionsFactoryConfig({chainID:e.chainId}),n=new j.TransferTransactionsFactory({config:r}),i={protocol:O("abi"),content:t},s=j.Address.newFromBech32(this.config.user.wallet),c=JSON.stringify(i),u=n.createTransactionForTransfer(s,{receiver:s,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(c))});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=P.WarpAbi(t);if(e){let c=this.cache.get(r);if(c)return S.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),c}let n=v(this.config),s=y.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let c=await s.getTransaction(t),u=await this.createFromTransaction(c);return e&&e.ttl&&u&&this.cache.set(r,u,e.ttl),u}catch(c){return console.error("WarpAbiBuilder: Error creating from transaction hash",c),null}}};var W=require("@multiversx/sdk-core");var Q=require("@multiversx/sdk-core/out");var o=require("@multiversx/sdk-core/out");var Ct=new RegExp(`${f.ArgParamsSeparator}(.*)`),_=class{nativeToString(t,e){return t==="esdt"&&e instanceof o.TokenTransfer?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(o.OptionValue.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(o.OptionalValue.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(o.List.ClassName)){let e=t.getItems(),n=e.map(s=>this.typedToString(s).split(f.ArgParamsSeparator)[0])[0],i=e.map(s=>this.typedToString(s).split(f.ArgParamsSeparator)[1]);return`list:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(o.VariadicValue.ClassName)){let e=t.getItems(),n=e.map(s=>this.typedToString(s).split(f.ArgParamsSeparator)[0])[0],i=e.map(s=>this.typedToString(s).split(f.ArgParamsSeparator)[1]);return`variadic:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(o.CompositeValue.ClassName)){let e=t.getItems(),r=e.map(c=>this.typedToString(c).split(f.ArgParamsSeparator)[0]),n=e.map(c=>this.typedToString(c).split(f.ArgParamsSeparator)[1]),i=r.join(f.ArgCompositeSeparator),s=n.join(f.ArgCompositeSeparator);return`composite(${i}):${s}`}if(t.hasClassOrSuperclass(o.BigUIntValue.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(o.U8Value.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(o.U16Value.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(o.U32Value.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(o.U64Value.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(o.StringValue.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(o.BooleanValue.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(o.AddressValue.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(o.TokenIdentifierValue.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(o.BytesValue.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(o.CodeMetadataValue.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),n=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${n}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.stringToNative(e)}nativeToTyped(t,e){let r=this.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new o.CompositeType(...e.split(f.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new o.StringType;if(t==="uint8")return new o.U8Type;if(t==="uint16")return new o.U16Type;if(t==="uint32")return new o.U32Type;if(t==="uint64")return new o.U64Type;if(t==="biguint")return new o.BigUIntType;if(t==="bool")return new o.BooleanType;if(t==="address")return new o.AddressType;if(t==="token")return new o.TokenIdentifierType;if(t==="hex")return new o.BytesType;if(t==="codemeta")return new o.CodeMetadataType;if(t==="esdt"||t==="nft")return new o.StructType("EsdtTokenPayment",[new o.FieldDefinition("token_identifier","",new o.TokenIdentifierType),new o.FieldDefinition("token_nonce","",new o.U64Type),new o.FieldDefinition("amount","",new o.BigUIntType)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(f.ArgParamsSeparator),r=e[0],n=e.slice(1).join(f.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[i,s]=n.split(f.ArgParamsSeparator);return[`option:${i}`,s||null]}else if(r==="optional"){let[i,s]=n.split(f.ArgParamsSeparator);return[`optional:${i}`,s||null]}else if(r==="list"){let i=n.split(f.ArgParamsSeparator),s=i.slice(0,-1).join(f.ArgParamsSeparator),c=i[i.length-1],p=(c?c.split(","):[]).map(d=>this.stringToNative(`${s}:${d}`)[1]);return[`list:${s}`,p]}else if(r==="variadic"){let i=n.split(f.ArgParamsSeparator),s=i.slice(0,-1).join(f.ArgParamsSeparator),c=i[i.length-1],p=(c?c.split(","):[]).map(d=>this.stringToNative(`${s}:${d}`)[1]);return[`variadic:${s}`,p]}else if(r.startsWith("composite")){let i=r.match(/\(([^)]+)\)/)?.[1]?.split(f.ArgCompositeSeparator),c=n.split(f.ArgCompositeSeparator).map((u,p)=>this.stringToNative(`${i[p]}:${u}`)[1]);return[r,c]}else{if(r==="string")return[r,n];if(r==="uint8"||r==="uint16"||r==="uint32")return[r,Number(n)];if(r==="uint64"||r==="biguint")return[r,BigInt(n||0)];if(r==="bool")return[r,n==="true"];if(r==="address")return[r,n];if(r==="token")return[r,n];if(r==="hex")return[r,n];if(r==="codemeta")return[r,n];if(r==="esdt"){let[i,s,c]=n.split(f.ArgCompositeSeparator);return[r,new o.TokenTransfer({token:new o.Token({identifier:i,nonce:BigInt(s)}),amount:BigInt(c)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new o.NothingValue;if(e==="option"){let n=this.stringToTyped(r);return n instanceof o.NothingValue?o.OptionValue.newMissingTyped(n.getType()):o.OptionValue.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof o.NothingValue?o.OptionalValue.newMissing():new o.OptionalValue(n.getType(),n)}if(e==="list"){let[n,i]=r.split(Ct,2),c=i.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new o.List(this.nativeToType(n),c)}if(e==="variadic"){let[n,i]=r.split(Ct,2),c=i.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new o.VariadicValue(new o.VariadicType(this.nativeToType(n)),c)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],i=r.split(f.ArgCompositeSeparator),s=n.split(f.ArgCompositeSeparator),c=i.map((p,d)=>this.stringToTyped(`${s[d]}:${p}`)),u=c.map(p=>p.getType());return new o.CompositeValue(new o.CompositeType(...u),c)}if(e==="string")return r?o.StringValue.fromUTF8(r):new o.NothingValue;if(e==="uint8")return r?new o.U8Value(Number(r)):new o.NothingValue;if(e==="uint16")return r?new o.U16Value(Number(r)):new o.NothingValue;if(e==="uint32")return r?new o.U32Value(Number(r)):new o.NothingValue;if(e==="uint64")return r?new o.U64Value(BigInt(r)):new o.NothingValue;if(e==="biguint")return r?new o.BigUIntValue(BigInt(r)):new o.NothingValue;if(e==="bool")return r?new o.BooleanValue(typeof r=="boolean"?r:r==="true"):new o.NothingValue;if(e==="address")return r?new o.AddressValue(o.Address.newFromBech32(r)):new o.NothingValue;if(e==="token")return r?new o.TokenIdentifierValue(r):new o.NothingValue;if(e==="hex")return r?o.BytesValue.fromHex(r):new o.NothingValue;if(e==="codemeta")return new o.CodeMetadataValue(o.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(f.ArgCompositeSeparator);return new o.Struct(this.nativeToType("esdt"),[new o.Field(new o.TokenIdentifierValue(n[0]),"token_identifier"),new o.Field(new o.U64Value(BigInt(n[1])),"token_nonce"),new o.Field(new o.BigUIntValue(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof o.OptionType)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof o.OptionalType)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof o.ListType)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof o.VariadicType)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof o.StringType)return"string";if(t instanceof o.U8Type)return"uint8";if(t instanceof o.U16Type)return"uint16";if(t instanceof o.U32Type)return"uint32";if(t instanceof o.U64Type)return"uint64";if(t instanceof o.BigUIntType)return"biguint";if(t instanceof o.BooleanType)return"bool";if(t instanceof o.AddressType)return"address";if(t instanceof o.TokenIdentifierType)return"token";if(t instanceof o.BytesType)return"hex";if(t instanceof o.CodeMetadataType)return"codemeta";if(t instanceof o.StructType&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var Zt=async(a,t)=>{if(typeof window>"u"){let{VM:e}=require("vm2"),r=new e({timeout:1e3,sandbox:{input:t},eval:!1,wasm:!1});return a.trim().startsWith("(")&&a.includes("=>")?r.run(`(${a})(input)`):null}return new Promise((e,r)=>{try{let n=new Blob([`
2
+ `))}};var U=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=(i,s)=>{r=r.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(e.vars).forEach(([i,s])=>{if(typeof s!="string")n(i,s);else if(s.startsWith(`${f.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let c=s.split(`${f.Vars.Query}:`)[1],u=new URLSearchParams(t.currentUrl.split("?")[1]).get(c);u&&n(i,u)}else if(s.startsWith(`${f.Vars.Env}:`)){let c=s.split(`${f.Vars.Env}:`)[1],u=t.vars?.[c];u&&n(i,u)}else s===f.Source.UserWallet&&t.user?.wallet?n(i,t.user.wallet):n(i,s)}),JSON.parse(r)}static async applyRootGlobals(t,e){let r=JSON.stringify(t),n={config:e,chain:v(e)};return Object.values(f.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}static async applyActionGlobals(t,e){let r=await y.getChainInfoForAction(t,e),n=JSON.stringify(e),i={config:t,chain:r};return Object.values(f.Globals).forEach(s=>{let c=s.Accessor(i);c!=null&&(n=n.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),c.toString()))}),JSON.parse(n)}};var m=require("@multiversx/sdk-core/out");var ut={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"}],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"}]},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 it=a=>({hash:a.hash.toString("hex"),alias:a.alias?.toString()||null,trust:a.trust.toString(),owner:a.owner.toString(),createdAt:a.created_at.toNumber(),upgradedAt:a.upgraded_at?.toNumber(),brand:a.brand?.toString("hex")||null,upgrade:a.upgrade?.toString("hex")||null}),yt=a=>({unitPrice:BigInt(a.unit_price.toString()),admins:a.admins.map(t=>t.toBech32())});var $=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),i=()=>this.isCurrentUserAdmin()?BigInt(0):e&&r?this.registryConfig.unitPrice*BigInt(3):e?this.registryConfig.unitPrice*BigInt(2):this.registryConfig.unitPrice,s=()=>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:i(),arguments:s()})}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=P.RegistryInfo(t),n=e?this.cache.get(r):null;if(n)return S.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),s=this.getController(),c=s.createQuery({contract:i,function:"getInfoByAlias",arguments:[m.BytesValue.fromUTF8(t)]}),u=await s.runQuery(c),[p]=s.parseQueryResponse(u),d=p?it(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=P.RegistryInfo(t);if(e){let g=this.cache.get(r);if(g)return S.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),g}let n=this.getRegistryContractAddress(),i=this.getController(),s=i.createQuery({contract:n,function:"getInfoByHash",arguments:[m.BytesValue.fromHex(t)]}),c=await i.runQuery(s),[u]=i.parseQueryResponse(c),p=u?it(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(),i=n.createQuery({contract:r,function:"getUserWarps",arguments:[new m.AddressValue(new m.Address(e))]}),s=await n.runQuery(i),[c]=n.parseQueryResponse(s);return c.map(it)}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(),i=n.createQuery({contract:r,function:"getUserBrands",arguments:[new m.AddressValue(new m.Address(e))]}),s=await n.runQuery(i),[c]=n.parseQueryResponse(s),u=c.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=P.ChainInfos();if(t&&t.ttl){let p=this.cache.get(e);if(p)return S.info("WarpRegistry (getChainInfos): ChainInfos found in cache"),p}let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getChains",arguments:[]}),s=await n.runQuery(i),[c]=n.parseQueryResponse(s),u=c.map(nt);if(t&&t.ttl){for(let p of u)this.cache.set(P.ChainInfo(p.chain),p,t.ttl);this.cache.set(e,u,t.ttl)}return u}async getChainInfo(t,e){try{let r=P.ChainInfo(t),n=e?this.cache.get(r):null;if(n)return S.info(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),s=this.getController(),c=s.createQuery({contract:i,function:"getChain",arguments:[m.BytesValue.fromUTF8(t)]}),u=await s.runQuery(c),[p]=s.parseQueryResponse(u),d=p?nt(p):null;return e&&e.ttl&&d&&this.cache.set(r,d,e.ttl),d}catch{return null}}async fetchBrand(t,e){let r=P.Brand(t),n=e?this.cache.get(r):null;if(n)return S.info(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let i=v(this.config),c=y.getChainEntrypoint(i,this.config.env).createNetworkProvider();try{let u=await c.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?yt(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let t=v(this.config),e=new m.TransactionsFactoryConfig({chainID:t.chainId}),r=m.AbiRegistry.create(ut);return new m.SmartContractTransactionsFactory({config:e,abi:r})}getController(){let t=v(this.config),e=y.getChainEntrypoint(t,this.config.env),r=m.AbiRegistry.create(ut);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(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)),s=(await Promise.all(n)).filter(p=>p.match),c=s.length>0,u=s.map(p=>({url:p.url,warp:p.warp}));return{match:c,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):y.getInfoFromPrefixedIdentifier(t);if(!n)return r;try{let{type:i,identifierBase:s}=n,c=new Y(this.config),u=new $(this.config),p=null,d=null,g=null;if(i==="hash"){p=await c.createFromTransactionHash(s,e);let b=await u.getInfoByHash(s,e);d=b.registryInfo,g=b.brand}else if(i==="alias"){let b=await u.getInfoByAlias(s,e);d=b.registryInfo,g=b.brand,b.registryInfo&&(p=await c.createFromTransactionHash(b.registryInfo.hash,e))}let T=p?await U.apply(this.config,p):null;return T?{match:!0,url:t,warp:T,registryInfo:d,brand:g}:r}catch(i){return S.error("Error detecting warp link",i),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=y.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.identifierBase):""}generateQrCode(t,e,r=512,n="white",i="black",s="#23F7DD"){let c=this.build(t,e);return new wt.default({type:"svg",width:r,height:r,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:n},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(s)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=A.SuperClientUrls.includes(e.origin),n=e.searchParams.get(f.IdentifierParamName),i=r&&!n?e.pathname.split("/")[1]:n;if(!i)return null;let s=decodeURIComponent(i);return y.getInfoFromPrefixedIdentifier(s)}};var Nt="https://",y=class{static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(f.IdentifierParamSeparator)?e:`${f.IdentifierType.Alias}${f.IdentifierParamSeparator}${e}`,[n,i]=r.split(f.IdentifierParamSeparator),s=i.split("?")[0];return{type:n,identifier:i,identifierBase:s}}static getNextInfo(t,e,r,n){let i=e.actions?.[r]?.next||e.next||null;if(!i)return null;if(i.startsWith(Nt))return[{identifier:null,url:i}];let[s,c]=i.split("?");if(!c)return[{identifier:s,url:this.buildNextUrl(s,t)}];let u=c.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(u.length===0){let h=z(c,{...e.vars,...n}),w=h?`${s}?${h}`:s;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 T=Array.isArray(n[g])?n[g]:[n[g]];if(T.length===0)return[];let b=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 T.map(h=>{let w=c;for(let{regex:C,field:R}of b){let E=R?this.getNestedValue(h,R):h;if(E==null)return null;w=w.replace(C,E)}if(w.includes("{{")||w.includes("}}"))return null;let I=w?`${s}?${w}`:s;return{identifier:I,url:this.buildNextUrl(I,t)}}).filter(h=>h!==null)}static buildNextUrl(t,e){let[r,n]=t.split("?"),i=this.getInfoFromPrefixedIdentifier(r)||{type:"alias",identifier:r,identifierBase:r},c=new Z(e).build(i.type,i.identifierBase);if(!n)return c;let u=new URL(c);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 v(t);let r=await new $(t).getChainInfo(e.chain,{ttl:ct.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 D.DevnetEntrypoint(t.apiUrl,n,r):e==="testnet"?new D.TestnetEntrypoint(t.apiUrl,n,r):new D.MainnetEntrypoint(t.apiUrl,n,r)}};var pt=class{constructor(t){this.pendingBrand={protocol:O("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=v(this.config),r=new L.TransactionsFactoryConfig({chainID:e.chainId}),n=new L.TransferTransactionsFactory({config:r}),i=L.Address.newFromBech32(this.config.user.wallet),s=JSON.stringify(t);return n.createTransactionForNativeTokenTransfer(i,{receiver:L.Address.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(s))})}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=v(this.config),n=y.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let i=await n.getTransaction(t);return this.createFromTransaction(i)}catch(i){return console.error("BrandBuilder: Error creating from transaction hash",i),null}}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||A.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),i=new Tt.default,s=i.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};var l=require("@multiversx/sdk-core/out"),Ft=(a,t)=>a?l.OptionValue.newProvided(a):t?l.OptionValue.newMissingTyped(t):l.OptionValue.newMissing(),Ot=(a,t)=>a?new l.OptionalValue(a.getType(),a):t?new l.OptionalValue(t):l.OptionalValue.newMissing(),kt=a=>{if(a.length===0)throw new Error("Cannot create a list from an empty array");let t=a[0].getType();return new l.List(t,a)},$t=a=>l.VariadicValue.fromItems(...a),Lt=a=>{let t=a.map(e=>e.getType());return new l.CompositeValue(new l.CompositeType(...t),a)},_t=a=>l.StringValue.fromUTF8(a),qt=a=>new l.U8Value(a),Mt=a=>new l.U16Value(a),Ht=a=>new l.U32Value(a),Dt=a=>new l.U64Value(a),jt=a=>new l.BigUIntValue(BigInt(a)),Qt=a=>new l.BooleanValue(a),Gt=a=>new l.AddressValue(l.Address.newFromBech32(a)),zt=a=>new l.TokenIdentifierValue(a),Kt=a=>l.BytesValue.fromHex(a),Jt=a=>new l.Struct(new l.StructType("EsdtTokenPayment",[new l.FieldDefinition("token_identifier","",new l.TokenIdentifierType),new l.FieldDefinition("token_nonce","",new l.U64Type),new l.FieldDefinition("amount","",new l.BigUIntType)]),[new l.Field(new l.TokenIdentifierValue(a.token.identifier),"token_identifier"),new l.Field(new l.U64Value(BigInt(a.token.nonce)),"token_nonce"),new l.Field(new l.BigUIntValue(BigInt(a.amount)),"amount")]),Xt=a=>new l.CodeMetadataValue(l.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(a,"hex")))),Yt=()=>new l.NothingValue;var j=require("@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=v(this.config),r=new j.TransactionsFactoryConfig({chainID:e.chainId}),n=new j.TransferTransactionsFactory({config:r}),i={protocol:O("abi"),content:t},s=j.Address.newFromBech32(this.config.user.wallet),c=JSON.stringify(i),u=n.createTransactionForTransfer(s,{receiver:s,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(c))});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=P.WarpAbi(t);if(e){let c=this.cache.get(r);if(c)return S.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),c}let n=v(this.config),s=y.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let c=await s.getTransaction(t),u=await this.createFromTransaction(c);return e&&e.ttl&&u&&this.cache.set(r,u,e.ttl),u}catch(c){return console.error("WarpAbiBuilder: Error creating from transaction hash",c),null}}};var W=require("@multiversx/sdk-core");var Q=require("@multiversx/sdk-core/out");var o=require("@multiversx/sdk-core/out");var Ct=new RegExp(`${f.ArgParamsSeparator}(.*)`),_=class{nativeToString(t,e){return t==="esdt"&&e instanceof o.TokenTransfer?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(o.OptionValue.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(o.OptionalValue.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(o.List.ClassName)){let e=t.getItems(),n=e.map(s=>this.typedToString(s).split(f.ArgParamsSeparator)[0])[0],i=e.map(s=>this.typedToString(s).split(f.ArgParamsSeparator)[1]);return`list:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(o.VariadicValue.ClassName)){let e=t.getItems(),n=e.map(s=>this.typedToString(s).split(f.ArgParamsSeparator)[0])[0],i=e.map(s=>this.typedToString(s).split(f.ArgParamsSeparator)[1]);return`variadic:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(o.CompositeValue.ClassName)){let e=t.getItems(),r=e.map(c=>this.typedToString(c).split(f.ArgParamsSeparator)[0]),n=e.map(c=>this.typedToString(c).split(f.ArgParamsSeparator)[1]),i=r.join(f.ArgCompositeSeparator),s=n.join(f.ArgCompositeSeparator);return`composite(${i}):${s}`}if(t.hasClassOrSuperclass(o.BigUIntValue.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(o.U8Value.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(o.U16Value.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(o.U32Value.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(o.U64Value.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(o.StringValue.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(o.BooleanValue.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(o.AddressValue.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(o.TokenIdentifierValue.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(o.BytesValue.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(o.CodeMetadataValue.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),n=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${n}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.stringToNative(e)}nativeToTyped(t,e){let r=this.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new o.CompositeType(...e.split(f.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new o.StringType;if(t==="uint8")return new o.U8Type;if(t==="uint16")return new o.U16Type;if(t==="uint32")return new o.U32Type;if(t==="uint64")return new o.U64Type;if(t==="biguint")return new o.BigUIntType;if(t==="bool")return new o.BooleanType;if(t==="address")return new o.AddressType;if(t==="token")return new o.TokenIdentifierType;if(t==="hex")return new o.BytesType;if(t==="codemeta")return new o.CodeMetadataType;if(t==="esdt"||t==="nft")return new o.StructType("EsdtTokenPayment",[new o.FieldDefinition("token_identifier","",new o.TokenIdentifierType),new o.FieldDefinition("token_nonce","",new o.U64Type),new o.FieldDefinition("amount","",new o.BigUIntType)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(f.ArgParamsSeparator),r=e[0],n=e.slice(1).join(f.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[i,s]=n.split(f.ArgParamsSeparator);return[`option:${i}`,s||null]}else if(r==="optional"){let[i,s]=n.split(f.ArgParamsSeparator);return[`optional:${i}`,s||null]}else if(r==="list"){let i=n.split(f.ArgParamsSeparator),s=i.slice(0,-1).join(f.ArgParamsSeparator),c=i[i.length-1],p=(c?c.split(","):[]).map(d=>this.stringToNative(`${s}:${d}`)[1]);return[`list:${s}`,p]}else if(r==="variadic"){let i=n.split(f.ArgParamsSeparator),s=i.slice(0,-1).join(f.ArgParamsSeparator),c=i[i.length-1],p=(c?c.split(","):[]).map(d=>this.stringToNative(`${s}:${d}`)[1]);return[`variadic:${s}`,p]}else if(r.startsWith("composite")){let i=r.match(/\(([^)]+)\)/)?.[1]?.split(f.ArgCompositeSeparator),c=n.split(f.ArgCompositeSeparator).map((u,p)=>this.stringToNative(`${i[p]}:${u}`)[1]);return[r,c]}else{if(r==="string")return[r,n];if(r==="uint8"||r==="uint16"||r==="uint32")return[r,Number(n)];if(r==="uint64"||r==="biguint")return[r,BigInt(n||0)];if(r==="bool")return[r,n==="true"];if(r==="address")return[r,n];if(r==="token")return[r,n];if(r==="hex")return[r,n];if(r==="codemeta")return[r,n];if(r==="esdt"){let[i,s,c]=n.split(f.ArgCompositeSeparator);return[r,new o.TokenTransfer({token:new o.Token({identifier:i,nonce:BigInt(s)}),amount:BigInt(c)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new o.NothingValue;if(e==="option"){let n=this.stringToTyped(r);return n instanceof o.NothingValue?o.OptionValue.newMissingTyped(n.getType()):o.OptionValue.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof o.NothingValue?o.OptionalValue.newMissing():new o.OptionalValue(n.getType(),n)}if(e==="list"){let[n,i]=r.split(Ct,2),c=i.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new o.List(this.nativeToType(n),c)}if(e==="variadic"){let[n,i]=r.split(Ct,2),c=i.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new o.VariadicValue(new o.VariadicType(this.nativeToType(n)),c)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],i=r.split(f.ArgCompositeSeparator),s=n.split(f.ArgCompositeSeparator),c=i.map((p,d)=>this.stringToTyped(`${s[d]}:${p}`)),u=c.map(p=>p.getType());return new o.CompositeValue(new o.CompositeType(...u),c)}if(e==="string")return r?o.StringValue.fromUTF8(r):new o.NothingValue;if(e==="uint8")return r?new o.U8Value(Number(r)):new o.NothingValue;if(e==="uint16")return r?new o.U16Value(Number(r)):new o.NothingValue;if(e==="uint32")return r?new o.U32Value(Number(r)):new o.NothingValue;if(e==="uint64")return r?new o.U64Value(BigInt(r)):new o.NothingValue;if(e==="biguint")return r?new o.BigUIntValue(BigInt(r)):new o.NothingValue;if(e==="bool")return r?new o.BooleanValue(typeof r=="boolean"?r:r==="true"):new o.NothingValue;if(e==="address")return r?new o.AddressValue(o.Address.newFromBech32(r)):new o.NothingValue;if(e==="token")return r?new o.TokenIdentifierValue(r):new o.NothingValue;if(e==="hex")return r?o.BytesValue.fromHex(r):new o.NothingValue;if(e==="codemeta")return new o.CodeMetadataValue(o.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(f.ArgCompositeSeparator);return new o.Struct(this.nativeToType("esdt"),[new o.Field(new o.TokenIdentifierValue(n[0]),"token_identifier"),new o.Field(new o.U64Value(BigInt(n[1])),"token_nonce"),new o.Field(new o.BigUIntValue(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof o.OptionType)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof o.OptionalType)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof o.ListType)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof o.VariadicType)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof o.StringType)return"string";if(t instanceof o.U8Type)return"uint8";if(t instanceof o.U16Type)return"uint16";if(t instanceof o.U32Type)return"uint32";if(t instanceof o.U64Type)return"uint64";if(t instanceof o.BigUIntType)return"biguint";if(t instanceof o.BooleanType)return"bool";if(t instanceof o.AddressType)return"address";if(t instanceof o.TokenIdentifierType)return"token";if(t instanceof o.BytesType)return"hex";if(t instanceof o.CodeMetadataType)return"codemeta";if(t instanceof o.StructType&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var Zt=async(a,t)=>{if(typeof window>"u"){let e;try{e=require("vm2").VM}catch{throw new Error("The 'vm2' package is required for transform execution in Node.js environments. Please install it with 'npm install vm2', or use this library in a browser environment.")}let r=new e({timeout:1e3,sandbox:{input:t},eval:!1,wasm:!1});return a.trim().startsWith("(")&&a.includes("=>")?r.run(`(${a})(input)`):null}return new Promise((e,r)=>{try{let n=new Blob([`
3
3
  self.onmessage = function(e) {
4
4
  try {
5
5
  const input = e.data;
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  var oe=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});import{Address as vt,TransactionsFactoryConfig as Te,TransferTransactionsFactory as Ce}from"@multiversx/sdk-core";import We from"ajv";var p={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},Source:{UserWallet:"user:wallet"},Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:a=>a.config.user?.wallet},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:a=>a.chain.apiUrl},ChainExplorerUrl:{Placeholder:"CHAIN_EXPLORER",Accessor:a=>a.chain.explorerUrl}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Transform:{Prefix:"transform:"},Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}};var F={Warp:"2.0.1",Brand:"0.1.0",Abi:"0.1.0"},b={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${F.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${F.Brand}.schema.json`,DefaultClientUrl:a=>a==="devnet"?"https://devnet.usewarp.to":a==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],MainChain:{Name:"multiversx",DisplayName:"MultiversX",ApiUrl:a=>a==="devnet"?"https://devnet-api.multiversx.com":a==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com",ExplorerUrl:a=>a==="devnet"?"https://devnet-explorer.multiversx.com":a==="testnet"?"https://testnet-explorer.multiversx.com":"https://explorer.multiversx.com",BlockTime:a=>6e3,AddressHrp:"erd",ChainId:a=>a==="devnet"?"D":a==="testnet"?"T":"1"},Registry:{Contract:a=>a==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":a==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query",p.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 C=a=>({name:b.MainChain.Name,displayName:b.MainChain.DisplayName,chainId:b.MainChain.ChainId(a.env),blockTime:b.MainChain.BlockTime(a.env),addressHrp:b.MainChain.AddressHrp,apiUrl:b.MainChain.ApiUrl(a.env),explorerUrl:b.MainChain.ExplorerUrl(a.env)}),gr=(a,t)=>a.explorerUrl+(t?"/"+t:""),O=a=>{if(a==="warp")return`warp:${F.Warp}`;if(a==="brand")return`brand:${F.Brand}`;if(a==="abi")return`abi:${F.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${a}`)},_=(a,t)=>a?.actions[t-1],Y=a=>({name:a.name.toString(),displayName:a.display_name.toString(),chainId:a.chain_id.toString(),blockTime:a.block_time.toNumber(),addressHrp:a.address_hrp.toString(),apiUrl:a.api_url.toString(),explorerUrl:a.explorer_url.toString()}),H=(a,t)=>{let e=a.toString(),[r,n=""]=e.split("."),i=Math.abs(t);if(t>0)return BigInt(r+n.padEnd(i,"0"));if(t<0){let s=r+n;if(i>=s.length)return 0n;let o=s.slice(0,-i)||"0";return BigInt(o)}else return e.includes(".")?BigInt(e.split(".")[0]):BigInt(e)},Tt=(a,t=100)=>{if(!a)return"";let e=a.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e},D=(a,t)=>a.replace(/\{\{([^}]+)\}\}/g,(e,r)=>t[r]||"");import{DevnetEntrypoint as me,MainnetEntrypoint as he,TestnetEntrypoint as ye}from"@multiversx/sdk-core";var q=class{constructor(t="warp-cache"){this.prefix=t}getKey(t){return`${this.prefix}:${t}`}get(t){try{let e=localStorage.getItem(this.getKey(t));if(!e)return null;let r=JSON.parse(e);return Date.now()>r.expiresAt?(localStorage.removeItem(this.getKey(t)),null):r.value}catch{return null}}set(t,e,r){let n={value:e,expiresAt:Date.now()+r*1e3};localStorage.setItem(this.getKey(t),JSON.stringify(n))}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 R=class R{get(t){let e=R.cache.get(t);return e?Date.now()>e.expiresAt?(R.cache.delete(t),null):e.value:null}set(t,e,r){let n=Date.now()+r*1e3;R.cache.set(t,{value:e,expiresAt:n})}forget(t){R.cache.delete(t)}clear(){R.cache.clear()}};R.cache=new Map;var M=R;var Ct={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:a=>`warp:${a}`,WarpAbi:a=>`warp-abi:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`,ChainInfo:a=>`chain:${a}`,ChainInfos:()=>"chains"},V=class{constructor(t){this.strategy=this.selectStrategy(t)}selectStrategy(t){return t==="localStorage"?new q:t==="memory"?new M:typeof window<"u"&&window.localStorage?new q: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 ge from"qr-code-styling";import{Address as Wt,TransactionsFactoryConfig as ue,TransferTransactionsFactory as pe}from"@multiversx/sdk-core";var k=class k{static info(...t){k.isTestEnv||console.info(...t)}static warn(...t){k.isTestEnv||console.warn(...t)}static error(...t){k.isTestEnv||console.error(...t)}};k.isTestEnv=typeof process<"u"&&process.env.JEST_WORKER_ID!==void 0;var A=k;import ce 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,i)=>{n&&Object.keys(n).forEach(s=>{s!==s.toUpperCase()&&e.push(`${i} name '${s}' 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);return t.results&&!n?["ABI is required when results are present for contract or query actions"]:[]}async validateSchema(t){try{let e=this.config.schema?.warp||b.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),i=new ce,s=i.compile(n);return s(t)?[]:[`Schema validation failed: ${i.errorsText(s.errors)}`]}catch(e){return[`Schema validation failed: ${e instanceof Error?e.message:String(e)}`]}}};var Q=class{constructor(t){this.pendingWarp={protocol:O("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=C(this.config),r=new ue({chainID:e.chainId}),n=new pe({config:r}),i=Wt.newFromBech32(this.config.user.wallet),s=JSON.stringify(t),o=n.createTransactionForTransfer(i,{receiver:Wt.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(s))});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(t);if(e){let o=this.cache.get(r);if(o)return A.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),o}let n=C(this.config),s=m.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await s.getTransaction(t),c=await this.createFromTransaction(o);return e&&e.ttl&&c&&this.cache.set(r,c,e.ttl),c}catch(o){return console.error("WarpBuilder: Error creating from transaction hash",o),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return Tt(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 U=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=(i,s)=>{r=r.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(e.vars).forEach(([i,s])=>{if(typeof s!="string")n(i,s);else if(s.startsWith(`${p.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${p.Vars.Query}:`)[1],c=new URLSearchParams(t.currentUrl.split("?")[1]).get(o);c&&n(i,c)}else if(s.startsWith(`${p.Vars.Env}:`)){let o=s.split(`${p.Vars.Env}:`)[1],c=t.vars?.[o];c&&n(i,c)}else s===p.Source.UserWallet&&t.user?.wallet?n(i,t.user.wallet):n(i,s)}),JSON.parse(r)}static async applyRootGlobals(t,e){let r=JSON.stringify(t),n={config:e,chain:C(e)};return Object.values(p.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}static async applyActionGlobals(t,e){let r=await m.getChainInfoForAction(t,e),n=JSON.stringify(e),i={config:t,chain:r};return Object.values(p.Globals).forEach(s=>{let o=s.Accessor(i);o!=null&&(n=n.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(n)}};import{AbiRegistry as It,Address as S,AddressValue as tt,BytesValue as W,SmartContractTransactionsFactory as fe,TransactionsFactoryConfig as de}from"@multiversx/sdk-core/out";var Z={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"}],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"}]},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 G=a=>({hash:a.hash.toString("hex"),alias:a.alias?.toString()||null,trust:a.trust.toString(),owner:a.owner.toString(),createdAt:a.created_at.toNumber(),upgradedAt:a.upgraded_at?.toNumber(),brand:a.brand?.toString("hex")||null,upgrade:a.upgrade?.toString("hex")||null}),bt=a=>({unitPrice:BigInt(a.unit_price.toString()),admins:a.admins.map(t=>t.toBech32())});var $=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),i=()=>this.isCurrentUserAdmin()?BigInt(0):e&&r?this.registryConfig.unitPrice*BigInt(3):e?this.registryConfig.unitPrice*BigInt(2):this.registryConfig.unitPrice,s=()=>e&&r?[W.fromHex(t),W.fromUTF8(e),W.fromHex(r)]:e?[W.fromHex(t),W.fromUTF8(e)]:[W.fromHex(t)];return this.getFactory().createTransactionForExecute(n,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:i(),arguments:s()})}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:[W.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:[W.fromUTF8(t),W.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:[W.fromHex(t),W.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:[W.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:[W.fromHex(t),new tt(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:[W.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:[W.fromHex(t),W.fromHex(e)]})}async getInfoByAlias(t,e){try{let r=E.RegistryInfo(t),n=e?this.cache.get(r):null;if(n)return A.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:i,function:"getInfoByAlias",arguments:[W.fromUTF8(t)]}),c=await s.runQuery(o),[u]=s.parseQueryResponse(c),l=u?G(u):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=E.RegistryInfo(t);if(e){let f=this.cache.get(r);if(f)return A.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),f}let n=this.getRegistryContractAddress(),i=this.getController(),s=i.createQuery({contract:n,function:"getInfoByHash",arguments:[W.fromHex(t)]}),o=await i.runQuery(s),[c]=i.parseQueryResponse(o),u=c?G(c):null,l=u?.brand?await this.fetchBrand(u.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:u,brand:l},e.ttl),{registryInfo:u,brand:l}}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(),i=n.createQuery({contract:r,function:"getUserWarps",arguments:[new tt(new S(e))]}),s=await n.runQuery(i),[o]=n.parseQueryResponse(s);return o.map(G)}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(),i=n.createQuery({contract:r,function:"getUserBrands",arguments:[new tt(new S(e))]}),s=await n.runQuery(i),[o]=n.parseQueryResponse(s),c=o.map(f=>f.toString("hex")),u={ttl:365*24*60*60};return(await Promise.all(c.map(f=>this.fetchBrand(f,u)))).filter(f=>f!==null)}catch{return[]}}async getChainInfos(t){let e=E.ChainInfos();if(t&&t.ttl){let u=this.cache.get(e);if(u)return A.info("WarpRegistry (getChainInfos): ChainInfos found in cache"),u}let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getChains",arguments:[]}),s=await n.runQuery(i),[o]=n.parseQueryResponse(s),c=o.map(Y);if(t&&t.ttl){for(let u of c)this.cache.set(E.ChainInfo(u.chain),u,t.ttl);this.cache.set(e,c,t.ttl)}return c}async getChainInfo(t,e){try{let r=E.ChainInfo(t),n=e?this.cache.get(r):null;if(n)return A.info(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:i,function:"getChain",arguments:[W.fromUTF8(t)]}),c=await s.runQuery(o),[u]=s.parseQueryResponse(c),l=u?Y(u):null;return e&&e.ttl&&l&&this.cache.set(r,l,e.ttl),l}catch{return null}}async fetchBrand(t,e){let r=E.Brand(t),n=e?this.cache.get(r):null;if(n)return A.info(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let i=C(this.config),o=m.getChainEntrypoint(i,this.config.env).createNetworkProvider();try{let c=await o.getTransaction(t),u=JSON.parse(c.data.toString());return u.meta={hash:c.hash,creator:c.sender.bech32(),createdAt:new Date(c.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,u,e.ttl),u}catch{return null}}getRegistryContractAddress(){return S.newFromBech32(this.config.registry?.contract||b.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=C(this.config),e=new de({chainID:t.chainId}),r=It.create(Z);return new fe({config:e,abi:r})}getController(){let t=C(this.config),e=m.getChainEntrypoint(t,this.config.env),r=It.create(Z);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(p.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(u=>u[0]).filter(u=>this.isValid(u)).map(u=>this.detect(u)),s=(await Promise.all(n)).filter(u=>u.match),o=s.length>0,c=s.map(u=>({url:u.url,warp:u.warp}));return{match:o,results:c}}async detect(t,e){let r={match:!1,url:t,warp:null,registryInfo:null,brand:null},n=t.startsWith(p.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):m.getInfoFromPrefixedIdentifier(t);if(!n)return r;try{let{type:i,identifierBase:s}=n,o=new Q(this.config),c=new $(this.config),u=null,l=null,f=null;if(i==="hash"){u=await o.createFromTransactionHash(s,e);let w=await c.getInfoByHash(s,e);l=w.registryInfo,f=w.brand}else if(i==="alias"){let w=await c.getInfoByAlias(s,e);l=w.registryInfo,f=w.brand,w.registryInfo&&(u=await o.createFromTransactionHash(w.registryInfo.hash,e))}let h=u?await U.apply(this.config,u):null;return h?{match:!0,url:t,warp:h,registryInfo:l,brand:f}:r}catch(i){return A.error("Error detecting warp link",i),r}}build(t,e){let r=this.config.clientUrl||b.DefaultClientUrl(this.config.env),n=t===p.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+p.IdentifierParamSeparator+e);return b.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${p.IdentifierParamName}=${n}`}buildFromPrefixedIdentifier(t){let e=m.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.identifierBase):""}generateQrCode(t,e,r=512,n="white",i="black",s="#23F7DD"){let o=this.build(t,e);return new ge({type:"svg",width:r,height:r,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:n},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(s)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=b.SuperClientUrls.includes(e.origin),n=e.searchParams.get(p.IdentifierParamName),i=r&&!n?e.pathname.split("/")[1]:n;if(!i)return null;let s=decodeURIComponent(i);return m.getInfoFromPrefixedIdentifier(s)}};var we="https://",m=class{static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(p.IdentifierParamSeparator)?e:`${p.IdentifierType.Alias}${p.IdentifierParamSeparator}${e}`,[n,i]=r.split(p.IdentifierParamSeparator),s=i.split("?")[0];return{type:n,identifier:i,identifierBase:s}}static getNextInfo(t,e,r,n){let i=e.actions?.[r]?.next||e.next||null;if(!i)return null;if(i.startsWith(we))return[{identifier:null,url:i}];let[s,o]=i.split("?");if(!o)return[{identifier:s,url:this.buildNextUrl(s,t)}];let c=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let d=D(o,{...e.vars,...n}),g=d?`${s}?${d}`:s;return[{identifier:g,url:this.buildNextUrl(g,t)}]}let u=c[0];if(!u)return[];let l=u.match(/{{([^[]+)\[\]/),f=l?l[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 w=c.filter(d=>d.includes(`{{${f}[]`)).map(d=>{let g=d.match(/\[\](\.[^}]+)?}}/),T=g&&g[1]||"";return{placeholder:d,field:T?T.slice(1):"",regex:new RegExp(d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(d=>{let g=o;for(let{regex:y,field:P}of w){let x=P?this.getNestedValue(d,P):d;if(x==null)return null;g=g.replace(y,x)}if(g.includes("{{")||g.includes("}}"))return null;let T=g?`${s}?${g}`:s;return{identifier:T,url:this.buildNextUrl(T,t)}}).filter(d=>d!==null)}static buildNextUrl(t,e){let[r,n]=t.split("?"),i=this.getInfoFromPrefixedIdentifier(r)||{type:"alias",identifier:r,identifierBase:r},o=new z(e).build(i.type,i.identifierBase);if(!n)return o;let c=new URL(o);return new URLSearchParams(n).forEach((u,l)=>c.searchParams.set(l,u)),c.toString().replace(/\/\?/,"?")}static getNestedValue(t,e){return e.split(".").reduce((r,n)=>r?.[n],t)}static async getChainInfoForAction(t,e){if(!e.chain)return C(t);let r=await new $(t).getChainInfo(e.chain,{ttl:Ct.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 me(t.apiUrl,n,r):e==="testnet"?new ye(t.apiUrl,n,r):new he(t.apiUrl,n,r)}};var At=class{constructor(t){this.pendingBrand={protocol:O("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=C(this.config),r=new Te({chainID:e.chainId}),n=new Ce({config:r}),i=vt.newFromBech32(this.config.user.wallet),s=JSON.stringify(t);return n.createTransactionForNativeTokenTransfer(i,{receiver:vt.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(s))})}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.ensureValidSchema(r),r}async createFromTransaction(t,e=!1){return await this.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=C(this.config),n=m.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let i=await n.getTransaction(t);return this.createFromTransaction(i)}catch(i){return console.error("BrandBuilder: Error creating from transaction hash",i),null}}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||b.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),i=new We,s=i.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};import{Address as be,AddressValue as Ie,BigUIntType as ve,BigUIntValue as xt,BooleanValue as Ae,BytesValue as xe,CodeMetadata as Be,CodeMetadataValue as Se,CompositeType as Ee,CompositeValue as Pe,Field as et,FieldDefinition as rt,List as Re,NothingValue as Ve,OptionalValue as nt,OptionValue as it,StringValue as Ue,Struct as Ne,StructType as Fe,TokenIdentifierType as Oe,TokenIdentifierValue as Bt,U16Value as ke,U32Value as $e,U64Type as Le,U64Value as St,U8Value as _e,VariadicValue as qe}from"@multiversx/sdk-core/out";var Nn=(a,t)=>a?it.newProvided(a):t?it.newMissingTyped(t):it.newMissing(),Fn=(a,t)=>a?new nt(a.getType(),a):t?new nt(t):nt.newMissing(),On=a=>{if(a.length===0)throw new Error("Cannot create a list from an empty array");let t=a[0].getType();return new Re(t,a)},kn=a=>qe.fromItems(...a),$n=a=>{let t=a.map(e=>e.getType());return new Pe(new Ee(...t),a)},Ln=a=>Ue.fromUTF8(a),_n=a=>new _e(a),qn=a=>new ke(a),Mn=a=>new $e(a),Hn=a=>new St(a),Dn=a=>new xt(BigInt(a)),jn=a=>new Ae(a),Qn=a=>new Ie(be.newFromBech32(a)),Gn=a=>new Bt(a),zn=a=>xe.fromHex(a),Kn=a=>new Ne(new Fe("EsdtTokenPayment",[new rt("token_identifier","",new Oe),new rt("token_nonce","",new Le),new rt("amount","",new ve)]),[new et(new Bt(a.token.identifier),"token_identifier"),new et(new St(BigInt(a.token.nonce)),"token_nonce"),new et(new xt(BigInt(a.amount)),"amount")]),Jn=a=>new Se(Be.newFromBytes(Uint8Array.from(Buffer.from(a,"hex")))),Xn=()=>new Ve;import{Address as Me,TransactionsFactoryConfig as He,TransferTransactionsFactory as De}from"@multiversx/sdk-core";var K=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=C(this.config),r=new He({chainID:e.chainId}),n=new De({config:r}),i={protocol:O("abi"),content:t},s=Me.newFromBech32(this.config.user.wallet),o=JSON.stringify(i),c=n.createTransactionForTransfer(s,{receiver:s,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(o))});return c.gasLimit=c.gasLimit+BigInt(2e6),c}async createFromRaw(t){return JSON.parse(t)}async createFromTransaction(t){let e=await this.createFromRaw(t.data.toString());return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,e){let r=E.WarpAbi(t);if(e){let o=this.cache.get(r);if(o)return A.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),o}let n=C(this.config),s=m.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await s.getTransaction(t),c=await this.createFromTransaction(o);return e&&e.ttl&&c&&this.cache.set(r,c,e.ttl),c}catch(o){return console.error("WarpAbiBuilder: Error creating from transaction hash",o),null}}};import{AbiRegistry as yt,Address as wt,ArgSerializer as ir,SmartContractTransactionsFactory as ar,Token as ne,TokenComputer as sr,TokenTransfer as ie,TransactionsFactoryConfig as or,TransferTransactionsFactory as cr}from"@multiversx/sdk-core";import{SmartContractTransactionsOutcomeParser as Ye,TransactionEventsParser as Ze,findEventsByFirstTopic as tr}from"@multiversx/sdk-core/out";import{Address as je,AddressType as Et,AddressValue as Pt,BigUIntType as at,BigUIntValue as st,BooleanType as Rt,BooleanValue as Vt,BytesType as Ut,BytesValue as Nt,CodeMetadata as Qe,CodeMetadataType as Ft,CodeMetadataValue as Ot,CompositeType as kt,CompositeValue as $t,Field as ot,FieldDefinition as ct,List as Lt,ListType as Ge,NothingValue as B,OptionalType as ze,OptionalValue as ut,OptionType as Ke,OptionValue as pt,StringType as _t,StringValue as qt,Struct as Je,StructType as Mt,Token as Xe,TokenIdentifierType as lt,TokenIdentifierValue as ft,TokenTransfer as Ht,U16Type as Dt,U16Value as jt,U32Type as Qt,U32Value as Gt,U64Type as dt,U64Value as gt,U8Type as zt,U8Value as Kt,VariadicType as Jt,VariadicValue as Xt}from"@multiversx/sdk-core/out";var Yt=new RegExp(`${p.ArgParamsSeparator}(.*)`),L=class{nativeToString(t,e){return t==="esdt"&&e instanceof Ht?`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(ut.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(Lt.ClassName)){let e=t.getItems(),n=e.map(s=>this.typedToString(s).split(p.ArgParamsSeparator)[0])[0],i=e.map(s=>this.typedToString(s).split(p.ArgParamsSeparator)[1]);return`list:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(Xt.ClassName)){let e=t.getItems(),n=e.map(s=>this.typedToString(s).split(p.ArgParamsSeparator)[0])[0],i=e.map(s=>this.typedToString(s).split(p.ArgParamsSeparator)[1]);return`variadic:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass($t.ClassName)){let e=t.getItems(),r=e.map(o=>this.typedToString(o).split(p.ArgParamsSeparator)[0]),n=e.map(o=>this.typedToString(o).split(p.ArgParamsSeparator)[1]),i=r.join(p.ArgCompositeSeparator),s=n.join(p.ArgCompositeSeparator);return`composite(${i}):${s}`}if(t.hasClassOrSuperclass(st.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Kt.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(jt.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Gt.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(gt.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(qt.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(Vt.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(Pt.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(ft.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(Nt.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(Ot.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 kt(...e.split(p.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new _t;if(t==="uint8")return new zt;if(t==="uint16")return new Dt;if(t==="uint32")return new Qt;if(t==="uint64")return new dt;if(t==="biguint")return new at;if(t==="bool")return new Rt;if(t==="address")return new Et;if(t==="token")return new lt;if(t==="hex")return new Ut;if(t==="codemeta")return new Ft;if(t==="esdt"||t==="nft")return new Mt("EsdtTokenPayment",[new ct("token_identifier","",new lt),new ct("token_nonce","",new dt),new ct("amount","",new at)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(p.ArgParamsSeparator),r=e[0],n=e.slice(1).join(p.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[i,s]=n.split(p.ArgParamsSeparator);return[`option:${i}`,s||null]}else if(r==="optional"){let[i,s]=n.split(p.ArgParamsSeparator);return[`optional:${i}`,s||null]}else if(r==="list"){let i=n.split(p.ArgParamsSeparator),s=i.slice(0,-1).join(p.ArgParamsSeparator),o=i[i.length-1],u=(o?o.split(","):[]).map(l=>this.stringToNative(`${s}:${l}`)[1]);return[`list:${s}`,u]}else if(r==="variadic"){let i=n.split(p.ArgParamsSeparator),s=i.slice(0,-1).join(p.ArgParamsSeparator),o=i[i.length-1],u=(o?o.split(","):[]).map(l=>this.stringToNative(`${s}:${l}`)[1]);return[`variadic:${s}`,u]}else if(r.startsWith("composite")){let i=r.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=n.split(p.ArgCompositeSeparator).map((c,u)=>this.stringToNative(`${i[u]}:${c}`)[1]);return[r,o]}else{if(r==="string")return[r,n];if(r==="uint8"||r==="uint16"||r==="uint32")return[r,Number(n)];if(r==="uint64"||r==="biguint")return[r,BigInt(n||0)];if(r==="bool")return[r,n==="true"];if(r==="address")return[r,n];if(r==="token")return[r,n];if(r==="hex")return[r,n];if(r==="codemeta")return[r,n];if(r==="esdt"){let[i,s,o]=n.split(p.ArgCompositeSeparator);return[r,new Ht({token:new Xe({identifier:i,nonce:BigInt(s)}),amount:BigInt(o)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new B;if(e==="option"){let n=this.stringToTyped(r);return n instanceof B?pt.newMissingTyped(n.getType()):pt.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof B?ut.newMissing():new ut(n.getType(),n)}if(e==="list"){let[n,i]=r.split(Yt,2),o=i.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Lt(this.nativeToType(n),o)}if(e==="variadic"){let[n,i]=r.split(Yt,2),o=i.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Xt(new Jt(this.nativeToType(n)),o)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],i=r.split(p.ArgCompositeSeparator),s=n.split(p.ArgCompositeSeparator),o=i.map((u,l)=>this.stringToTyped(`${s[l]}:${u}`)),c=o.map(u=>u.getType());return new $t(new kt(...c),o)}if(e==="string")return r?qt.fromUTF8(r):new B;if(e==="uint8")return r?new Kt(Number(r)):new B;if(e==="uint16")return r?new jt(Number(r)):new B;if(e==="uint32")return r?new Gt(Number(r)):new B;if(e==="uint64")return r?new gt(BigInt(r)):new B;if(e==="biguint")return r?new st(BigInt(r)):new B;if(e==="bool")return r?new Vt(typeof r=="boolean"?r:r==="true"):new B;if(e==="address")return r?new Pt(je.newFromBech32(r)):new B;if(e==="token")return r?new ft(r):new B;if(e==="hex")return r?Nt.fromHex(r):new B;if(e==="codemeta")return new Ot(Qe.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(p.ArgCompositeSeparator);return new Je(this.nativeToType("esdt"),[new ot(new ft(n[0]),"token_identifier"),new ot(new gt(BigInt(n[1])),"token_nonce"),new ot(new st(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof Ke)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof ze)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Ge)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Jt)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof _t)return"string";if(t instanceof zt)return"uint8";if(t instanceof Dt)return"uint16";if(t instanceof Qt)return"uint32";if(t instanceof dt)return"uint64";if(t instanceof at)return"biguint";if(t instanceof Rt)return"bool";if(t instanceof Et)return"address";if(t instanceof lt)return"token";if(t instanceof Ut)return"hex";if(t instanceof Ft)return"codemeta";if(t instanceof Mt&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var er=async(a,t)=>{if(typeof window>"u"){let{VM:e}=oe("vm2"),r=new e({timeout:1e3,sandbox:{input:t},eval:!1,wasm:!1});return a.trim().startsWith("(")&&a.includes("=>")?r.run(`(${a})(input)`):null}return new Promise((e,r)=>{try{let n=new Blob([`
2
+ `))}};var U=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=(i,s)=>{r=r.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(e.vars).forEach(([i,s])=>{if(typeof s!="string")n(i,s);else if(s.startsWith(`${p.Vars.Query}:`)){if(!t.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${p.Vars.Query}:`)[1],c=new URLSearchParams(t.currentUrl.split("?")[1]).get(o);c&&n(i,c)}else if(s.startsWith(`${p.Vars.Env}:`)){let o=s.split(`${p.Vars.Env}:`)[1],c=t.vars?.[o];c&&n(i,c)}else s===p.Source.UserWallet&&t.user?.wallet?n(i,t.user.wallet):n(i,s)}),JSON.parse(r)}static async applyRootGlobals(t,e){let r=JSON.stringify(t),n={config:e,chain:C(e)};return Object.values(p.Globals).forEach(i=>{let s=i.Accessor(n);s!=null&&(r=r.replace(new RegExp(`{{${i.Placeholder}}}`,"g"),s.toString()))}),JSON.parse(r)}static async applyActionGlobals(t,e){let r=await m.getChainInfoForAction(t,e),n=JSON.stringify(e),i={config:t,chain:r};return Object.values(p.Globals).forEach(s=>{let o=s.Accessor(i);o!=null&&(n=n.replace(new RegExp(`{{${s.Placeholder}}}`,"g"),o.toString()))}),JSON.parse(n)}};import{AbiRegistry as It,Address as S,AddressValue as tt,BytesValue as W,SmartContractTransactionsFactory as fe,TransactionsFactoryConfig as de}from"@multiversx/sdk-core/out";var Z={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"}],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"}]},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 G=a=>({hash:a.hash.toString("hex"),alias:a.alias?.toString()||null,trust:a.trust.toString(),owner:a.owner.toString(),createdAt:a.created_at.toNumber(),upgradedAt:a.upgraded_at?.toNumber(),brand:a.brand?.toString("hex")||null,upgrade:a.upgrade?.toString("hex")||null}),bt=a=>({unitPrice:BigInt(a.unit_price.toString()),admins:a.admins.map(t=>t.toBech32())});var $=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),i=()=>this.isCurrentUserAdmin()?BigInt(0):e&&r?this.registryConfig.unitPrice*BigInt(3):e?this.registryConfig.unitPrice*BigInt(2):this.registryConfig.unitPrice,s=()=>e&&r?[W.fromHex(t),W.fromUTF8(e),W.fromHex(r)]:e?[W.fromHex(t),W.fromUTF8(e)]:[W.fromHex(t)];return this.getFactory().createTransactionForExecute(n,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:i(),arguments:s()})}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:[W.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:[W.fromUTF8(t),W.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:[W.fromHex(t),W.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:[W.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:[W.fromHex(t),new tt(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:[W.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:[W.fromHex(t),W.fromHex(e)]})}async getInfoByAlias(t,e){try{let r=E.RegistryInfo(t),n=e?this.cache.get(r):null;if(n)return A.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:i,function:"getInfoByAlias",arguments:[W.fromUTF8(t)]}),c=await s.runQuery(o),[u]=s.parseQueryResponse(c),l=u?G(u):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=E.RegistryInfo(t);if(e){let f=this.cache.get(r);if(f)return A.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),f}let n=this.getRegistryContractAddress(),i=this.getController(),s=i.createQuery({contract:n,function:"getInfoByHash",arguments:[W.fromHex(t)]}),o=await i.runQuery(s),[c]=i.parseQueryResponse(o),u=c?G(c):null,l=u?.brand?await this.fetchBrand(u.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:u,brand:l},e.ttl),{registryInfo:u,brand:l}}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(),i=n.createQuery({contract:r,function:"getUserWarps",arguments:[new tt(new S(e))]}),s=await n.runQuery(i),[o]=n.parseQueryResponse(s);return o.map(G)}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(),i=n.createQuery({contract:r,function:"getUserBrands",arguments:[new tt(new S(e))]}),s=await n.runQuery(i),[o]=n.parseQueryResponse(s),c=o.map(f=>f.toString("hex")),u={ttl:365*24*60*60};return(await Promise.all(c.map(f=>this.fetchBrand(f,u)))).filter(f=>f!==null)}catch{return[]}}async getChainInfos(t){let e=E.ChainInfos();if(t&&t.ttl){let u=this.cache.get(e);if(u)return A.info("WarpRegistry (getChainInfos): ChainInfos found in cache"),u}let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getChains",arguments:[]}),s=await n.runQuery(i),[o]=n.parseQueryResponse(s),c=o.map(Y);if(t&&t.ttl){for(let u of c)this.cache.set(E.ChainInfo(u.chain),u,t.ttl);this.cache.set(e,c,t.ttl)}return c}async getChainInfo(t,e){try{let r=E.ChainInfo(t),n=e?this.cache.get(r):null;if(n)return A.info(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:i,function:"getChain",arguments:[W.fromUTF8(t)]}),c=await s.runQuery(o),[u]=s.parseQueryResponse(c),l=u?Y(u):null;return e&&e.ttl&&l&&this.cache.set(r,l,e.ttl),l}catch{return null}}async fetchBrand(t,e){let r=E.Brand(t),n=e?this.cache.get(r):null;if(n)return A.info(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let i=C(this.config),o=m.getChainEntrypoint(i,this.config.env).createNetworkProvider();try{let c=await o.getTransaction(t),u=JSON.parse(c.data.toString());return u.meta={hash:c.hash,creator:c.sender.bech32(),createdAt:new Date(c.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,u,e.ttl),u}catch{return null}}getRegistryContractAddress(){return S.newFromBech32(this.config.registry?.contract||b.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=C(this.config),e=new de({chainID:t.chainId}),r=It.create(Z);return new fe({config:e,abi:r})}getController(){let t=C(this.config),e=m.getChainEntrypoint(t,this.config.env),r=It.create(Z);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(p.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(u=>u[0]).filter(u=>this.isValid(u)).map(u=>this.detect(u)),s=(await Promise.all(n)).filter(u=>u.match),o=s.length>0,c=s.map(u=>({url:u.url,warp:u.warp}));return{match:o,results:c}}async detect(t,e){let r={match:!1,url:t,warp:null,registryInfo:null,brand:null},n=t.startsWith(p.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):m.getInfoFromPrefixedIdentifier(t);if(!n)return r;try{let{type:i,identifierBase:s}=n,o=new Q(this.config),c=new $(this.config),u=null,l=null,f=null;if(i==="hash"){u=await o.createFromTransactionHash(s,e);let w=await c.getInfoByHash(s,e);l=w.registryInfo,f=w.brand}else if(i==="alias"){let w=await c.getInfoByAlias(s,e);l=w.registryInfo,f=w.brand,w.registryInfo&&(u=await o.createFromTransactionHash(w.registryInfo.hash,e))}let h=u?await U.apply(this.config,u):null;return h?{match:!0,url:t,warp:h,registryInfo:l,brand:f}:r}catch(i){return A.error("Error detecting warp link",i),r}}build(t,e){let r=this.config.clientUrl||b.DefaultClientUrl(this.config.env),n=t===p.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+p.IdentifierParamSeparator+e);return b.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${p.IdentifierParamName}=${n}`}buildFromPrefixedIdentifier(t){let e=m.getInfoFromPrefixedIdentifier(t);return e?this.build(e.type,e.identifierBase):""}generateQrCode(t,e,r=512,n="white",i="black",s="#23F7DD"){let o=this.build(t,e);return new ge({type:"svg",width:r,height:r,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:n},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(s)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=b.SuperClientUrls.includes(e.origin),n=e.searchParams.get(p.IdentifierParamName),i=r&&!n?e.pathname.split("/")[1]:n;if(!i)return null;let s=decodeURIComponent(i);return m.getInfoFromPrefixedIdentifier(s)}};var we="https://",m=class{static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(p.IdentifierParamSeparator)?e:`${p.IdentifierType.Alias}${p.IdentifierParamSeparator}${e}`,[n,i]=r.split(p.IdentifierParamSeparator),s=i.split("?")[0];return{type:n,identifier:i,identifierBase:s}}static getNextInfo(t,e,r,n){let i=e.actions?.[r]?.next||e.next||null;if(!i)return null;if(i.startsWith(we))return[{identifier:null,url:i}];let[s,o]=i.split("?");if(!o)return[{identifier:s,url:this.buildNextUrl(s,t)}];let c=o.match(/{{([^}]+)\[\](\.[^}]+)?}}/g)||[];if(c.length===0){let d=D(o,{...e.vars,...n}),g=d?`${s}?${d}`:s;return[{identifier:g,url:this.buildNextUrl(g,t)}]}let u=c[0];if(!u)return[];let l=u.match(/{{([^[]+)\[\]/),f=l?l[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 w=c.filter(d=>d.includes(`{{${f}[]`)).map(d=>{let g=d.match(/\[\](\.[^}]+)?}}/),T=g&&g[1]||"";return{placeholder:d,field:T?T.slice(1):"",regex:new RegExp(d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")}});return h.map(d=>{let g=o;for(let{regex:y,field:P}of w){let x=P?this.getNestedValue(d,P):d;if(x==null)return null;g=g.replace(y,x)}if(g.includes("{{")||g.includes("}}"))return null;let T=g?`${s}?${g}`:s;return{identifier:T,url:this.buildNextUrl(T,t)}}).filter(d=>d!==null)}static buildNextUrl(t,e){let[r,n]=t.split("?"),i=this.getInfoFromPrefixedIdentifier(r)||{type:"alias",identifier:r,identifierBase:r},o=new z(e).build(i.type,i.identifierBase);if(!n)return o;let c=new URL(o);return new URLSearchParams(n).forEach((u,l)=>c.searchParams.set(l,u)),c.toString().replace(/\/\?/,"?")}static getNestedValue(t,e){return e.split(".").reduce((r,n)=>r?.[n],t)}static async getChainInfoForAction(t,e){if(!e.chain)return C(t);let r=await new $(t).getChainInfo(e.chain,{ttl:Ct.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 me(t.apiUrl,n,r):e==="testnet"?new ye(t.apiUrl,n,r):new he(t.apiUrl,n,r)}};var At=class{constructor(t){this.pendingBrand={protocol:O("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=C(this.config),r=new Te({chainID:e.chainId}),n=new Ce({config:r}),i=vt.newFromBech32(this.config.user.wallet),s=JSON.stringify(t);return n.createTransactionForNativeTokenTransfer(i,{receiver:vt.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(s))})}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.ensureValidSchema(r),r}async createFromTransaction(t,e=!1){return await this.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=C(this.config),n=m.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let i=await n.getTransaction(t);return this.createFromTransaction(i)}catch(i){return console.error("BrandBuilder: Error creating from transaction hash",i),null}}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.schema?.brand||b.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),i=new We,s=i.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};import{Address as be,AddressValue as Ie,BigUIntType as ve,BigUIntValue as xt,BooleanValue as Ae,BytesValue as xe,CodeMetadata as Be,CodeMetadataValue as Se,CompositeType as Ee,CompositeValue as Pe,Field as et,FieldDefinition as rt,List as Re,NothingValue as Ve,OptionalValue as nt,OptionValue as it,StringValue as Ue,Struct as Ne,StructType as Fe,TokenIdentifierType as Oe,TokenIdentifierValue as Bt,U16Value as ke,U32Value as $e,U64Type as Le,U64Value as St,U8Value as _e,VariadicValue as qe}from"@multiversx/sdk-core/out";var Nn=(a,t)=>a?it.newProvided(a):t?it.newMissingTyped(t):it.newMissing(),Fn=(a,t)=>a?new nt(a.getType(),a):t?new nt(t):nt.newMissing(),On=a=>{if(a.length===0)throw new Error("Cannot create a list from an empty array");let t=a[0].getType();return new Re(t,a)},kn=a=>qe.fromItems(...a),$n=a=>{let t=a.map(e=>e.getType());return new Pe(new Ee(...t),a)},Ln=a=>Ue.fromUTF8(a),_n=a=>new _e(a),qn=a=>new ke(a),Mn=a=>new $e(a),Hn=a=>new St(a),Dn=a=>new xt(BigInt(a)),jn=a=>new Ae(a),Qn=a=>new Ie(be.newFromBech32(a)),Gn=a=>new Bt(a),zn=a=>xe.fromHex(a),Kn=a=>new Ne(new Fe("EsdtTokenPayment",[new rt("token_identifier","",new Oe),new rt("token_nonce","",new Le),new rt("amount","",new ve)]),[new et(new Bt(a.token.identifier),"token_identifier"),new et(new St(BigInt(a.token.nonce)),"token_nonce"),new et(new xt(BigInt(a.amount)),"amount")]),Jn=a=>new Se(Be.newFromBytes(Uint8Array.from(Buffer.from(a,"hex")))),Xn=()=>new Ve;import{Address as Me,TransactionsFactoryConfig as He,TransferTransactionsFactory as De}from"@multiversx/sdk-core";var K=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=C(this.config),r=new He({chainID:e.chainId}),n=new De({config:r}),i={protocol:O("abi"),content:t},s=Me.newFromBech32(this.config.user.wallet),o=JSON.stringify(i),c=n.createTransactionForTransfer(s,{receiver:s,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(o))});return c.gasLimit=c.gasLimit+BigInt(2e6),c}async createFromRaw(t){return JSON.parse(t)}async createFromTransaction(t){let e=await this.createFromRaw(t.data.toString());return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,e){let r=E.WarpAbi(t);if(e){let o=this.cache.get(r);if(o)return A.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),o}let n=C(this.config),s=m.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let o=await s.getTransaction(t),c=await this.createFromTransaction(o);return e&&e.ttl&&c&&this.cache.set(r,c,e.ttl),c}catch(o){return console.error("WarpAbiBuilder: Error creating from transaction hash",o),null}}};import{AbiRegistry as yt,Address as wt,ArgSerializer as ir,SmartContractTransactionsFactory as ar,Token as ne,TokenComputer as sr,TokenTransfer as ie,TransactionsFactoryConfig as or,TransferTransactionsFactory as cr}from"@multiversx/sdk-core";import{SmartContractTransactionsOutcomeParser as Ye,TransactionEventsParser as Ze,findEventsByFirstTopic as tr}from"@multiversx/sdk-core/out";import{Address as je,AddressType as Et,AddressValue as Pt,BigUIntType as at,BigUIntValue as st,BooleanType as Rt,BooleanValue as Vt,BytesType as Ut,BytesValue as Nt,CodeMetadata as Qe,CodeMetadataType as Ft,CodeMetadataValue as Ot,CompositeType as kt,CompositeValue as $t,Field as ot,FieldDefinition as ct,List as Lt,ListType as Ge,NothingValue as B,OptionalType as ze,OptionalValue as ut,OptionType as Ke,OptionValue as pt,StringType as _t,StringValue as qt,Struct as Je,StructType as Mt,Token as Xe,TokenIdentifierType as lt,TokenIdentifierValue as ft,TokenTransfer as Ht,U16Type as Dt,U16Value as jt,U32Type as Qt,U32Value as Gt,U64Type as dt,U64Value as gt,U8Type as zt,U8Value as Kt,VariadicType as Jt,VariadicValue as Xt}from"@multiversx/sdk-core/out";var Yt=new RegExp(`${p.ArgParamsSeparator}(.*)`),L=class{nativeToString(t,e){return t==="esdt"&&e instanceof Ht?`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(ut.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(Lt.ClassName)){let e=t.getItems(),n=e.map(s=>this.typedToString(s).split(p.ArgParamsSeparator)[0])[0],i=e.map(s=>this.typedToString(s).split(p.ArgParamsSeparator)[1]);return`list:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(Xt.ClassName)){let e=t.getItems(),n=e.map(s=>this.typedToString(s).split(p.ArgParamsSeparator)[0])[0],i=e.map(s=>this.typedToString(s).split(p.ArgParamsSeparator)[1]);return`variadic:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass($t.ClassName)){let e=t.getItems(),r=e.map(o=>this.typedToString(o).split(p.ArgParamsSeparator)[0]),n=e.map(o=>this.typedToString(o).split(p.ArgParamsSeparator)[1]),i=r.join(p.ArgCompositeSeparator),s=n.join(p.ArgCompositeSeparator);return`composite(${i}):${s}`}if(t.hasClassOrSuperclass(st.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Kt.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(jt.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Gt.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(gt.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(qt.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(Vt.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(Pt.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(ft.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(Nt.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(Ot.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 kt(...e.split(p.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new _t;if(t==="uint8")return new zt;if(t==="uint16")return new Dt;if(t==="uint32")return new Qt;if(t==="uint64")return new dt;if(t==="biguint")return new at;if(t==="bool")return new Rt;if(t==="address")return new Et;if(t==="token")return new lt;if(t==="hex")return new Ut;if(t==="codemeta")return new Ft;if(t==="esdt"||t==="nft")return new Mt("EsdtTokenPayment",[new ct("token_identifier","",new lt),new ct("token_nonce","",new dt),new ct("amount","",new at)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(p.ArgParamsSeparator),r=e[0],n=e.slice(1).join(p.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[i,s]=n.split(p.ArgParamsSeparator);return[`option:${i}`,s||null]}else if(r==="optional"){let[i,s]=n.split(p.ArgParamsSeparator);return[`optional:${i}`,s||null]}else if(r==="list"){let i=n.split(p.ArgParamsSeparator),s=i.slice(0,-1).join(p.ArgParamsSeparator),o=i[i.length-1],u=(o?o.split(","):[]).map(l=>this.stringToNative(`${s}:${l}`)[1]);return[`list:${s}`,u]}else if(r==="variadic"){let i=n.split(p.ArgParamsSeparator),s=i.slice(0,-1).join(p.ArgParamsSeparator),o=i[i.length-1],u=(o?o.split(","):[]).map(l=>this.stringToNative(`${s}:${l}`)[1]);return[`variadic:${s}`,u]}else if(r.startsWith("composite")){let i=r.match(/\(([^)]+)\)/)?.[1]?.split(p.ArgCompositeSeparator),o=n.split(p.ArgCompositeSeparator).map((c,u)=>this.stringToNative(`${i[u]}:${c}`)[1]);return[r,o]}else{if(r==="string")return[r,n];if(r==="uint8"||r==="uint16"||r==="uint32")return[r,Number(n)];if(r==="uint64"||r==="biguint")return[r,BigInt(n||0)];if(r==="bool")return[r,n==="true"];if(r==="address")return[r,n];if(r==="token")return[r,n];if(r==="hex")return[r,n];if(r==="codemeta")return[r,n];if(r==="esdt"){let[i,s,o]=n.split(p.ArgCompositeSeparator);return[r,new Ht({token:new Xe({identifier:i,nonce:BigInt(s)}),amount:BigInt(o)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new B;if(e==="option"){let n=this.stringToTyped(r);return n instanceof B?pt.newMissingTyped(n.getType()):pt.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof B?ut.newMissing():new ut(n.getType(),n)}if(e==="list"){let[n,i]=r.split(Yt,2),o=i.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Lt(this.nativeToType(n),o)}if(e==="variadic"){let[n,i]=r.split(Yt,2),o=i.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Xt(new Jt(this.nativeToType(n)),o)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],i=r.split(p.ArgCompositeSeparator),s=n.split(p.ArgCompositeSeparator),o=i.map((u,l)=>this.stringToTyped(`${s[l]}:${u}`)),c=o.map(u=>u.getType());return new $t(new kt(...c),o)}if(e==="string")return r?qt.fromUTF8(r):new B;if(e==="uint8")return r?new Kt(Number(r)):new B;if(e==="uint16")return r?new jt(Number(r)):new B;if(e==="uint32")return r?new Gt(Number(r)):new B;if(e==="uint64")return r?new gt(BigInt(r)):new B;if(e==="biguint")return r?new st(BigInt(r)):new B;if(e==="bool")return r?new Vt(typeof r=="boolean"?r:r==="true"):new B;if(e==="address")return r?new Pt(je.newFromBech32(r)):new B;if(e==="token")return r?new ft(r):new B;if(e==="hex")return r?Nt.fromHex(r):new B;if(e==="codemeta")return new Ot(Qe.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(p.ArgCompositeSeparator);return new Je(this.nativeToType("esdt"),[new ot(new ft(n[0]),"token_identifier"),new ot(new gt(BigInt(n[1])),"token_nonce"),new ot(new st(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof Ke)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof ze)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Ge)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Jt)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof _t)return"string";if(t instanceof zt)return"uint8";if(t instanceof Dt)return"uint16";if(t instanceof Qt)return"uint32";if(t instanceof dt)return"uint64";if(t instanceof at)return"biguint";if(t instanceof Rt)return"bool";if(t instanceof Et)return"address";if(t instanceof lt)return"token";if(t instanceof Ut)return"hex";if(t instanceof Ft)return"codemeta";if(t instanceof Mt&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var er=async(a,t)=>{if(typeof window>"u"){let e;try{e=oe("vm2").VM}catch{throw new Error("The 'vm2' package is required for transform execution in Node.js environments. Please install it with 'npm install vm2', or use this library in a browser environment.")}let r=new e({timeout:1e3,sandbox:{input:t},eval:!1,wasm:!1});return a.trim().startsWith("(")&&a.includes("=>")?r.run(`(${a})(input)`):null}return new Promise((e,r)=>{try{let n=new Blob([`
3
3
  self.onmessage = function(e) {
4
4
  try {
5
5
  const input = e.data;
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "2.3.0-alpha.1",
3
+ "version": "2.3.0-alpha.3",
4
4
  "description": "",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
7
7
  "module": "./dist/index.js",
8
8
  "scripts": {
9
- "build": "tsup src/index.ts --dts --format cjs,esm --minify --clean",
9
+ "build": "tsup",
10
10
  "test": "jest --config jest.config.js",
11
11
  "lint": "tsc --noEmit",
12
12
  "prepare": "npm run build",
@@ -18,8 +18,7 @@
18
18
  "dist"
19
19
  ],
20
20
  "peerDependencies": {
21
- "@multiversx/sdk-core": "^14.0.2",
22
- "vm2": "^3.9.17"
21
+ "@multiversx/sdk-core": "^14.0.2"
23
22
  },
24
23
  "devDependencies": {
25
24
  "@multiversx/sdk-core": "^14.2.1",
@@ -29,7 +28,9 @@
29
28
  "jest-fetch-mock": "^3.0.3",
30
29
  "ts-jest": "^29.4.0",
31
30
  "tsup": "^8.5.0",
32
- "typescript": "^5.8.3",
31
+ "typescript": "^5.8.3"
32
+ },
33
+ "optionalDependencies": {
33
34
  "vm2": "^3.9.19"
34
35
  },
35
36
  "publishConfig": {