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