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