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