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