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

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