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