@joai/warps-adapter-multiversx 1.0.0-beta.100 → 1.0.0-beta.101

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var at=Object.create;var Te=Object.defineProperty;var it=Object.getOwnPropertyDescriptor;var st=Object.getOwnPropertyNames;var ot=Object.getPrototypeOf,ct=Object.prototype.hasOwnProperty;var lt=(s,e)=>{for(var t in e)Te(s,t,{get:e[t],enumerable:!0})},Oe=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of st(e))!ct.call(s,n)&&n!==t&&Te(s,n,{get:()=>e[n],enumerable:!(r=it(e,n))||r.enumerable});return s};var pt=(s,e,t)=>(t=s!=null?at(ot(s)):{},Oe(e||!s||!s.__esModule?Te(t,"default",{value:s,enumerable:!0}):t,s)),ut=s=>Oe(Te({},"__esModule",{value:!0}),s);var Kt={};lt(Kt,{ExplorerUrls:()=>G,KnownTokens:()=>Ie,MultiversxAdapter:()=>Ue,MultiversxExplorers:()=>je,MultiversxExplorersConfig:()=>Be,NativeTokenEgld:()=>xe,NativeTokenVibe:()=>rt,VibechainAdapter:()=>Fe,VibechainExplorers:()=>Je,WarpMultiversxAbiBuilder:()=>D,WarpMultiversxBrandBuilder:()=>me,WarpMultiversxBuilder:()=>de,WarpMultiversxConstants:()=>ht,WarpMultiversxContractLoader:()=>ue,WarpMultiversxDataLoader:()=>he,WarpMultiversxExecutor:()=>ge,WarpMultiversxExplorer:()=>fe,WarpMultiversxInputTypes:()=>W,WarpMultiversxOutput:()=>X,WarpMultiversxRegistry:()=>ve,WarpMultiversxSerializer:()=>L,WarpMultiversxWallet:()=>We,address_value:()=>Ft,asset_value:()=>Rt,biguint_value:()=>Ut,boolean_value:()=>kt,codemeta:()=>wt,codemeta_value:()=>Dt,composite_value:()=>Pt,createMultiversxAdapter:()=>we,findKnownTokenById:()=>Se,getAllMultiversxAdapters:()=>vt,getAllMultiversxChainNames:()=>mt,getKnownTokensForChain:()=>dt,getMultiversxEntrypoint:()=>C,getMultiversxRegistryAddress:()=>S,getNormalizedTokenIdentifier:()=>pe,hex_value:()=>Mt,isNativeToken:()=>Q,list:()=>Ct,list_value:()=>Et,nothing_value:()=>Lt,option_value:()=>xt,optional:()=>Tt,optional_value:()=>At,string_value:()=>It,toTypedConfigInfo:()=>Ve,toTypedRegistryInfo:()=>ye,token:()=>Wt,token_value:()=>Ot,u16_value:()=>Bt,u32_value:()=>Nt,u64_value:()=>Vt,u8_value:()=>St,variadic_value:()=>bt});module.exports=ut(Kt);var Ee=require("@joai/warps"),mt=()=>[Ee.WarpChainName.Multiversx,Ee.WarpChainName.Vibechain];var tt=require("@joai/warps");var O=require("@multiversx/sdk-core"),E=require("@joai/warps");var te=require("@multiversx/sdk-core"),Me=require("@joai/warps"),Q=s=>!s.includes("-"),pe=s=>Q(s)?`${s}-000000`:s,C=(s,e,t)=>{let r="warp-sdk",i=t?(0,Me.getProviderConfig)(t,s.name,e,s.defaultApiUrl):{url:s.defaultApiUrl},o=i.url,c={headers:i.headers};return e==="devnet"?new te.DevnetEntrypoint({url:o,kind:"api",clientName:r,networkProviderConfig:c}):e==="testnet"?new te.TestnetEntrypoint({url:o,kind:"api",clientName:r,networkProviderConfig:c}):new te.MainnetEntrypoint({url:o,kind:"api",clientName:r,networkProviderConfig:c})};var be=require("@joai/warps");var ue=class{constructor(e){this.config=e}async getContract(e,t){try{let i=await C(t,this.config.env,this.config).createNetworkProvider().doGetGeneric(`accounts/${e}`);return{address:e,owner:i.ownerAddress,verified:i.isVerified||!1}}catch(r){return be.WarpLogger.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(e,t){try{let i=await C(t,this.config.env,this.config).createNetworkProvider().doGetGeneric(`accounts/${e}/verification`);return{codeHash:i.codeHash,abi:i.source.abi}}catch(r){return be.WarpLogger.error("WarpContractLoader: getVerificationInfo error",r),null}}};var D=class{constructor(e,t){this.config=e;this.chain=t;this.contractLoader=new ue(this.config),this.cache=new E.WarpCache(this.config.env,this.config.cache)}async createInscriptionTransaction(e){let t=(0,E.getWarpWalletAddressFromConfig)(this.config,this.chain.name);if(!t)throw new Error("WarpBuilder: user address not set");let r=new O.TransactionsFactoryConfig({chainID:this.chain.chainId}),n=new O.TransferTransactionsFactory({config:r}),i=O.Address.newFromBech32(t),o={protocol:(0,E.getLatestProtocolIdentifier)("abi"),content:e},c=JSON.stringify(o),l=await n.createTransactionForTransfer(i,{receiver:i,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(c))});return l.gasLimit=l.gasLimit+BigInt(2e6),l}async createFromRaw(e){return JSON.parse(e)}async createFromTransaction(e){let t=await this.createFromRaw(e.data.toString());return t.meta={chain:this.chain.name,identifier:(0,E.createWarpIdentifier)(this.chain.name,"hash",e.hash),query:null,hash:e.hash,creator:e.sender.toBech32(),createdAt:new Date(e.timestamp*1e3).toISOString()},t}async createFromTransactionHash(e,t){let r=E.WarpCacheKey.WarpAbi(this.config.env,e);if(t){let o=this.cache.get(r);if(o)return E.WarpLogger.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${e}`),o}let i=C(this.chain,this.config.env,this.config).createNetworkProvider();try{let o=await i.getTransaction(e),c=await this.createFromTransaction(o);return t&&t.ttl&&c&&this.cache.set(r,c,t.ttl),c}catch(o){return E.WarpLogger.error("WarpAbiBuilder: Error creating from transaction hash",o),null}}async getAbiForAction(e){if(e.abi)return await this.fetchAbi(e);if(!e.address)throw new Error("WarpActionExecutor: Address not found");let t=await this.contractLoader.getVerificationInfo(e.address,this.chain);if(!t)throw new Error("WarpActionExecutor: Verification info not found");return O.AbiRegistry.create(t.abi)}async fetchAbi(e){if(!e.abi)throw new Error("WarpActionExecutor: ABI not found");if(e.abi.startsWith(E.WarpConstants.IdentifierType.Hash)){let t=e.abi.split(E.WarpConstants.ArgParamsSeparator)[1],r=await this.createFromTransactionHash(t);if(!r)throw new Error(`WarpActionExecutor: ABI not found for hash: ${e.abi}`);return O.AbiRegistry.create(r.content)}else{let r=await(await fetch(e.abi)).json();return O.AbiRegistry.create(r)}}};var j=require("@multiversx/sdk-core"),H=require("@joai/warps"),Re=require("buffer");var me=class{constructor(e,t){this.config=e;this.chain=t;this.core=new H.WarpBrandBuilder(e)}async createInscriptionTransaction(e){let t=(0,H.getWarpWalletAddressFromConfig)(this.config,this.chain.name);if(!t)throw new Error("BrandBuilder: user address not set");let r=new j.TransactionsFactoryConfig({chainID:this.chain.chainId}),n=new j.TransferTransactionsFactory({config:r}),i=j.Address.newFromBech32(t),o=JSON.stringify(e);return await n.createTransactionForNativeTokenTransfer(i,{receiver:j.Address.newFromBech32(t),nativeAmount:BigInt(0),data:Uint8Array.from(Re.Buffer.from(o))})}async createFromTransaction(e,t=!1){let r=await this.core.createFromRaw(e.data.toString(),t);return r.meta={query:null,chain:this.chain.name,identifier:(0,H.createWarpIdentifier)(this.chain.name,"hash",e.hash),hash:e.hash,creator:e.sender.toBech32(),createdAt:new Date(e.timestamp*1e3).toISOString()},r}async createFromTransactionHash(e){let r=C(this.chain,this.config.env,this.config).createNetworkProvider();try{let n=await r.getTransaction(e);return this.createFromTransaction(n)}catch(n){return H.WarpLogger.error("BrandBuilder: Error creating from transaction hash",n),null}}};var J=require("@multiversx/sdk-core"),N=require("@joai/warps");var de=class extends N.WarpBuilder{constructor(t,r){super(t);this.config=t;this.chain=r;this.cache=new N.WarpCache(t.env,t.cache),this.core=new N.WarpBuilder(t)}async createInscriptionTransaction(t){let r=(0,N.getWarpWalletAddressFromConfig)(this.config,this.chain.name);if(!r)throw new Error("WarpBuilder: user address not set");let n=new J.TransactionsFactoryConfig({chainID:this.chain.chainId}),i=new J.TransferTransactionsFactory({config:n}),o=J.Address.newFromBech32(r),c=JSON.stringify(t),l=await i.createTransactionForTransfer(o,{receiver:J.Address.newFromBech32(r),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(c))});return l.gasLimit=l.gasLimit+BigInt(2e6),l}async createFromTransaction(t,r=!1){let n=await this.core.createFromRaw(t.data.toString(),r);return n.meta={chain:this.chain.name,identifier:(0,N.createWarpIdentifier)(this.chain.name,"hash",t.hash),query:null,hash:t.hash,creator:t.sender.toBech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},n}async createFromTransactionHash(t,r){let n=N.WarpCacheKey.Warp(this.config.env,t);if(r){let c=this.cache.get(n);if(c)return N.WarpLogger.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),c}let o=C(this.chain,this.config.env,this.config).createNetworkProvider();try{let c=await o.getTransaction(t),l=await this.createFromTransaction(c);return r&&r.ttl&&l&&this.cache.set(n,l,r.ttl),l}catch(c){return N.WarpLogger.error("WarpBuilder: Error creating from transaction hash",c),null}}};var $=require("@multiversx/sdk-core"),re=require("@joai/warps");var Pe=require("@joai/warps");var Le=require("@joai/warps"),De=Le.WarpChainName.Multiversx,Ke=[{chain:De,identifier:"EGLD",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"},{chain:De,identifier:"EGLD-000000",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"}];var _e=require("@joai/warps"),I=_e.WarpChainName.Multiversx,He=[{chain:I,identifier:"EGLD",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"},{chain:I,identifier:"EGLD-000000",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"},{chain:I,identifier:"SEGLD-3ad2d0",name:"StakedEGLD",symbol:"SEGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/SEGLD-3ad2d0/icon.png"},{chain:I,identifier:"HSEGLD-c13a4e",name:"HatomSEGLD",symbol:"HSEGLD",decimals:8,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/HSEGLD-c13a4e/icon.png"},{chain:I,identifier:"UTK-2f80e9",name:"xMoney UTK",symbol:"UTK",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/UTK-2f80e9/icon.png"},{chain:I,identifier:"USDC-c76f1f",name:"WrappedUSDC",symbol:"USDC",decimals:6,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/USDC-c76f1f/icon.png"},{chain:I,identifier:"WEGLD-bd4d79",name:"WrappedEGLD",symbol:"WEGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/WEGLD-bd4d79/icon.png"},{chain:I,identifier:"HTM-f51d55",name:"Hatom",symbol:"HTM",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/HTM-f51d55/icon.png"},{chain:I,identifier:"MEX-455c57",name:"MEX",symbol:"MEX",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/MEX-455c57/icon.png"},{chain:I,identifier:"WTAO-4f5363",name:"WrappedTAO",symbol:"WTAO",decimals:9,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/WTAO-4f5363/icon.png"},{chain:I,identifier:"HEGLD-d61095",name:"HatomEGLD",symbol:"HEGLD",decimals:8,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/HEGLD-d61095/icon.png"},{chain:I,identifier:"WBTC-5349b3",name:"WrappedBTC",symbol:"WBTC",decimals:8,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/WBTC-5349b3/icon.png"},{chain:I,identifier:"WETH-b4ca29",name:"WrappedETH",symbol:"WETH",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/WETH-b4ca29/icon.png"},{chain:I,identifier:"USH-111e09",name:"HatomUSD",symbol:"USH",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/USH-111e09/icon.png"},{chain:I,identifier:"USDT-f8c08c",name:"WrappedUSDT",symbol:"USDT",decimals:6,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/USDT-f8c08c/icon.png"}];var Ge=require("@joai/warps"),$e=Ge.WarpChainName.Multiversx,ze=[{chain:$e,identifier:"EGLD",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"},{chain:$e,identifier:"EGLD-000000",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"}];var Qe=require("@joai/warps"),qe=Qe.WarpChainName.Vibechain,Ce=[{chain:qe,identifier:"VIBE",name:"VIBE",symbol:"VIBE",decimals:18,logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/tokens/logos/vibe.svg"},{chain:qe,identifier:"VIBE-000000",name:"VIBE",symbol:"VIBE",decimals:18,logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/tokens/logos/vibe.svg"}];var Ie={[Pe.WarpChainName.Multiversx]:{mainnet:He,testnet:ze,devnet:Ke},[Pe.WarpChainName.Vibechain]:{mainnet:Ce,testnet:Ce,devnet:Ce}},Se=(s,e,t)=>(Ie[s]?.[e]||[]).find(n=>n.identifier===t)||null,dt=(s,e)=>Ie[s]?.[e]||[];var he=class{constructor(e,t){this.config=e;this.chain=t;this.cache=new re.WarpCache(e.env,e.cache)}async getAccount(e){let r=await C(this.chain,this.config.env,this.config).createNetworkProvider().getAccount($.Address.newFromBech32(e));return{chain:this.chain.name,address:r.address.toBech32(),balance:r.balance}}async getAccountAssets(e){let t=C(this.chain,this.config.env,this.config).createNetworkProvider(),r=t.getAccount($.Address.newFromBech32(e)),n=t.getFungibleTokensOfAccount($.Address.newFromBech32(e)),[i,o]=await Promise.all([r,n]),c=i.balance>0?[{...this.chain.nativeToken,amount:i.balance}]:[];return c.push(...o.map(l=>({chain:this.chain.name,identifier:l.token.identifier,name:l.raw.name,symbol:l.raw.ticker,amount:l.amount,decimals:l.raw.decimals,logoUrl:l.raw.assets?.pngUrl||"",price:l.raw.price?Number(l.raw.price):void 0,supply:l.raw.supply?BigInt(l.raw.supply):void 0}))),c}async getAsset(e){let t=re.WarpCacheKey.Asset(this.config.env,this.chain.name,e),r=this.cache.get(t);if(r)return r;let n=Se(this.chain.name,this.config.env,e);if(n)return{chain:this.chain.name,identifier:e,name:n.name,symbol:n.symbol,amount:0n,decimals:n.decimals,logoUrl:n.logoUrl};let i=new $.TokenComputer,o=Q(e)?0n:i.extractNonceFromExtendedIdentifier(e),c=new $.Token({identifier:e,nonce:BigInt(o||0)}),l=i.isFungible(c),f=C(this.chain,this.config.env,this.config).createNetworkProvider(),g=pe(e),d=await f.doGetGeneric(`tokens/${g}`),T={chain:this.chain.name,identifier:c.identifier,name:d.name,symbol:d.ticker,amount:0n,decimals:d.decimals,logoUrl:d.assets?.pngUrl||null,price:d.price?Number(d.price):void 0,supply:d.supply?BigInt(d.supply):void 0};return this.cache.set(t,T,re.CacheTtl.OneHour),T}async getAction(e,t=!1){let r=C(this.chain,this.config.env,this.config),n=t?await r.awaitCompletedTransaction(e):await r.getTransaction(e);return{chain:this.chain.name,id:n.hash,receiver:n.receiver.toBech32(),sender:n.sender.toBech32(),value:n.value,function:n.function,status:this.toActionStatus(n),createdAt:this.toActionCreatedAt(n),error:n?.smartContractResults.map(i=>i.raw.returnMessage)[0]||null,tx:n}}async getAccountActions(e,t){let r=C(this.chain,this.config.env,this.config).createNetworkProvider(),n=`accounts/${e}/transactions`,i=new URLSearchParams,o=t?.size||25,c=t?.page||0;if(c>0){let f=c*o;i.append("from",f.toString())}return o!==25&&i.append("size",o.toString()),i.toString()&&(n+=`?${i.toString()}`),(await r.doGetGeneric(n)).map(f=>({chain:this.chain.name,id:f.txHash,receiver:f.receiver,sender:f.sender,value:f.value,function:f.function,status:this.toActionStatus(f),createdAt:this.toActionCreatedAt(f)}))}toActionStatus(e){return e.status?.isSuccessful?.()?"success":e.status?.isFailed?.()?"failed":"pending"}toActionCreatedAt(e){return new Date(e.timestamp||e.timestamp*1e3).toISOString()}};var x=require("@multiversx/sdk-core"),V=require("@joai/warps");var ne=require("@multiversx/sdk-core"),w=require("@joai/warps");var a=require("@multiversx/sdk-core"),Xe=require("@joai/warps");var h={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:s=>s.config.user?.wallets?.[s.adapter.chainInfo.name]},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:s=>{if(!s.adapter.wallet)return null;try{return s.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:s=>s.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:s=>s.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},u={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"};var ht={Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}},W={Null:"null",Optional:"optional",List:"list",Token:"token",CodeMeta:"codemeta"},je=(r=>(r.MultiversxExplorer="multiversx_explorer",r.MultiversxExplorerDevnet="multiversx_explorer_devnet",r.MultiversxExplorerTestnet="multiversx_explorer_testnet",r))(je||{}),Je=(r=>(r.VibechainExplorer="vibechain_explorer",r.VibechainExplorerDevnet="vibechain_explorer_devnet",r.VibechainExplorerTestnet="vibechain_explorer_testnet",r))(Je||{}),Be={multiversx:{mainnet:["multiversx_explorer"],testnet:["multiversx_explorer_testnet"],devnet:["multiversx_explorer_devnet"]},vibechain:{mainnet:["vibechain_explorer"],testnet:["vibechain_explorer_testnet"],devnet:["vibechain_explorer_devnet"]}},G={multiversx_explorer:"https://explorer.multiversx.com",multiversx_explorer_devnet:"https://devnet-explorer.multiversx.com",multiversx_explorer_testnet:"https://testnet-explorer.multiversx.com",vibechain_explorer:"https://vibeox-explorer.multiversx.com",vibechain_explorer_devnet:"https://vibeox-explorer.multiversx.com",vibechain_explorer_testnet:"https://vibeox-explorer.multiversx.com"};var gt=new RegExp(`${h.ArgParamsSeparator}(.*)`),L=class{constructor(e){this.coreSerializer=new Xe.WarpSerializer(e)}typedToString(e){let t=e.getType();if(t.hasExactClass(a.OptionType.ClassName)||e.hasClassOrSuperclass(a.OptionValue.ClassName)){if(!e.isSet())return u.Option+h.ArgParamsSeparator+"null";let r=this.typedToString(e.getTypedValue());return u.Option+h.ArgParamsSeparator+r}if(t.hasExactClass(a.VariadicType.ClassName)||e.hasClassOrSuperclass(a.VariadicValue.ClassName)){let r=e.getItems();if(r.length===0){let g=this.typeToString(t.getFirstTypeParameter());return u.Vector+h.ArgParamsSeparator+g+h.ArgParamsSeparator}let n=r.map(g=>this.typedToString(g));if(n.every(g=>g.startsWith(u.Tuple)))return u.Vector+h.ArgParamsSeparator+n.join(",");let i=n[0],o=i.indexOf(h.ArgParamsSeparator),c=i.substring(0,o),l=n.map(g=>{let d=g.indexOf(h.ArgParamsSeparator);return g.substring(d+1)}),f=c.startsWith(u.Struct)?h.ArgStructSeparator:h.ArgListSeparator;return u.Vector+h.ArgParamsSeparator+c+h.ArgParamsSeparator+l.join(f)}if(t.hasExactClass(a.OptionalType.ClassName)||e.hasClassOrSuperclass(a.OptionalValue.ClassName)){if(!e.isSet())return W.Optional+h.ArgParamsSeparator+"null";let r=this.typedToString(e.getTypedValue());return W.Optional+h.ArgParamsSeparator+r}if(t.hasExactClass(a.ListType.ClassName)||e.hasClassOrSuperclass(a.List.ClassName)){let n=e.getItems().map(l=>this.typedToString(l));if(n.every(l=>l.startsWith(u.Tuple)))return W.List+h.ArgParamsSeparator+n.join(",");let o=n.map(l=>l.split(h.ArgParamsSeparator)[0])[0],c=n.map(l=>l.split(h.ArgParamsSeparator)[1]);return W.List+h.ArgParamsSeparator+o+h.ArgParamsSeparator+c.join(h.ArgListSeparator)}if(t.hasExactClass(a.CompositeType.ClassName)||e.hasClassOrSuperclass(a.CompositeValue.ClassName)){let n=e.getItems().map(i=>{let o=this.typedToString(i),c=o.indexOf(h.ArgParamsSeparator),l=o.substring(0,c),f=o.substring(c+1);return`${l},${f}`});return`${u.Tuple}(${n.join(",")})`}if(t.hasExactClass(a.BigUIntType.ClassName)||e.hasClassOrSuperclass(a.BigUIntValue.ClassName)||t.getName()==="BigUint")return u.Biguint+h.ArgParamsSeparator+BigInt(e.valueOf().toFixed());if(t.hasExactClass(a.U8Type.ClassName)||e.hasClassOrSuperclass(a.U8Value.ClassName))return u.Uint8+h.ArgParamsSeparator+e.valueOf().toNumber();if(t.hasExactClass(a.U16Type.ClassName)||e.hasClassOrSuperclass(a.U16Value.ClassName))return u.Uint16+h.ArgParamsSeparator+e.valueOf().toNumber();if(t.hasExactClass(a.U32Type.ClassName)||e.hasClassOrSuperclass(a.U32Value.ClassName))return u.Uint32+h.ArgParamsSeparator+e.valueOf().toNumber();if(t.hasExactClass(a.U64Type.ClassName)||e.hasClassOrSuperclass(a.U64Value.ClassName))return u.Uint64+h.ArgParamsSeparator+BigInt(e.valueOf().toFixed());if(t.hasExactClass(a.StringType.ClassName)||e.hasClassOrSuperclass(a.StringValue.ClassName))return u.String+h.ArgParamsSeparator+e.valueOf();if(t.hasExactClass(a.BooleanType.ClassName)||e.hasClassOrSuperclass(a.BooleanValue.ClassName))return u.Bool+h.ArgParamsSeparator+e.valueOf();if(t.hasExactClass(a.AddressType.ClassName)||e.hasClassOrSuperclass(a.AddressValue.ClassName))return u.Address+h.ArgParamsSeparator+e.valueOf().toBech32();if(t.hasExactClass(a.BytesType.ClassName)||e.hasClassOrSuperclass(a.BytesValue.ClassName))return u.Hex+h.ArgParamsSeparator+e.valueOf().toString("hex");if(t.getName()==="EsdtTokenPayment"){let r=e.getFieldValue("token_identifier").valueOf(),n=e.getFieldValue("token_nonce").valueOf(),i=e.getFieldValue("amount").valueOf(),c=new a.TokenComputer().computeExtendedIdentifier(new a.Token({identifier:r,nonce:BigInt(n)}));return u.Asset+h.ArgParamsSeparator+c+h.ArgCompositeSeparator+i}if(t.hasExactClass(a.StructType.ClassName)||e.hasClassOrSuperclass(a.Struct.ClassName)){let r=e,i=r.getType().getName(),o=r.getFields();if(o.length===0)return`${u.Struct}(${i})${h.ArgParamsSeparator}`;let c=o.map(l=>{let f=l.value.getType(),d=this.typedToString(l.value).split(h.ArgParamsSeparator),T=d.length>2?d.slice(2).join(h.ArgParamsSeparator):d[1]||"";return`(${l.name}${h.ArgParamsSeparator}${this.typeToString(f)})${T}`});return`${u.Struct}(${i})${h.ArgParamsSeparator}${c.join(h.ArgListSeparator)}`}if(t.hasExactClass(a.TokenIdentifierType.ClassName)||e.hasClassOrSuperclass(a.TokenIdentifierValue.ClassName))return W.Token+h.ArgParamsSeparator+e.valueOf();if(t.hasExactClass(a.CodeMetadataType.ClassName)||e.hasClassOrSuperclass(a.CodeMetadataValue.ClassName))return W.CodeMeta+h.ArgParamsSeparator+e.valueOf().toString();throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${e.getClassName()}`)}typedToNative(e){let t=this.typedToString(e);return this.coreSerializer.stringToNative(t)}nativeToTyped(e,t){if(e.startsWith(u.Tuple))return this.stringToTyped(e+":");let r=this.coreSerializer.nativeToString(e,t);return this.stringToTyped(r)}nativeToType(e){if(e.startsWith(u.Tuple)){let t=e.match(/\(([^)]+)\)/)?.[1];if(!t)throw new Error(`Invalid tuple type format: ${e}`);let r=t.split(","),n=[];for(let i=0;i<r.length;i+=2)n.push(r[i]);return new a.CompositeType(...n.map(i=>this.nativeToType(i)))}if(e.startsWith(u.Struct)){let t=e.match(/\(([^)]+)\)/);if(!t)throw new Error("Struct type must include a name in the format struct(Name)");let r=t[1];return new a.StructType(r,[])}if(e===u.String)return new a.StringType;if(e===u.Uint8)return new a.U8Type;if(e===u.Uint16)return new a.U16Type;if(e===u.Uint32)return new a.U32Type;if(e===u.Uint64)return new a.U64Type;if(e===u.Biguint)return new a.BigUIntType;if(e===u.Bool)return new a.BooleanType;if(e===u.Address)return new a.AddressType;if(e===u.Hex)return new a.BytesType;if(e===u.Asset)return new a.StructType("EsdtTokenPayment",[new a.FieldDefinition("token_identifier","",new a.TokenIdentifierType),new a.FieldDefinition("token_nonce","",new a.U64Type),new a.FieldDefinition("amount","",new a.BigUIntType)]);if(e===W.Token)return new a.TokenIdentifierType;if(e===W.CodeMeta)return new a.CodeMetadataType;throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${e}`)}stringToTyped(e){let[t,r]=e.split(/:(.*)/,2);if(t===u.Option){let n=this.stringToTyped(r);return n instanceof a.NothingValue?a.OptionValue.newMissingTyped(n.getType()):a.OptionValue.newProvided(n)}if(t===u.Vector){let n=r.indexOf(h.ArgParamsSeparator),i=r.substring(0,n),o=r.substring(n+1);if(i.startsWith(u.Tuple)){let d=o.split(",").map(T=>this.stringToTyped(T));return new a.VariadicValue(new a.VariadicType(this.nativeToType(i)),d)}if(o.includes("tuple(")){let g=this.splitTupleStrings(o),d=g.map(A=>this.stringToTyped(A)),P=g[0].match(/^(tuple\([^)]+\))/),y=P?P[1]:"tuple";return new a.VariadicValue(new a.VariadicType(this.nativeToType(y)),d)}let c=i.startsWith(u.Struct)?h.ArgStructSeparator:h.ArgListSeparator,f=o.split(c).map(g=>this.stringToTyped(`${i}:${g}`));return new a.VariadicValue(new a.VariadicType(this.nativeToType(i)),f)}if(t.startsWith(u.Tuple)){let n=t.match(/\(([^)]+)\)/)?.[1];if(!n)throw new Error(`Invalid tuple format: ${t}`);let i=n.split(","),o=[];for(let l=0;l<i.length;l+=2){let f=i[l],g=i[l+1];o.push(this.stringToTyped(`${f}:${g}`))}let c=o.map(l=>l.getType());return new a.CompositeValue(new a.CompositeType(...c),o)}if(t.startsWith(u.Struct)){let n=t.match(/\(([^)]+)\)/),i=n?n[1]:"CustomStruct";if(!r)return new a.Struct(new a.StructType(i,[]),[]);let o=r.split(h.ArgListSeparator),c=[],l=[];return o.forEach(f=>{let g=f.match(new RegExp(`^\\(([^${h.ArgParamsSeparator}]+)${h.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(g){let[,d,T,P]=g,y=this.stringToTyped(`${T}${h.ArgParamsSeparator}${P}`);c.push(new a.FieldDefinition(d,"",y.getType())),l.push(new a.Field(y,d))}}),new a.Struct(new a.StructType(i,c),l)}if(t===u.String)return r?a.StringValue.fromUTF8(r):new a.NothingValue;if(t===u.Uint8)return r?new a.U8Value(Number(r)):new a.NothingValue;if(t===u.Uint16)return r?new a.U16Value(Number(r)):new a.NothingValue;if(t===u.Uint32)return r?new a.U32Value(Number(r)):new a.NothingValue;if(t===u.Uint64)return r?new a.U64Value(BigInt(r)):new a.NothingValue;if(t===u.Biguint)return r?new a.BigUIntValue(BigInt(r)):new a.NothingValue;if(t===u.Bool)return r?new a.BooleanValue(typeof r=="boolean"?r:r==="true"):new a.NothingValue;if(t===u.Address)return r?new a.AddressValue(a.Address.newFromBech32(r)):new a.NothingValue;if(t===u.Hex)return r?a.BytesValue.fromHex(r):new a.NothingValue;if(t===u.Asset){let[n,i]=r.split(h.ArgCompositeSeparator),o=new a.TokenComputer,c=Q(n)?pe(n):o.extractIdentifierFromExtendedIdentifier(n),l=Q(n)?0n:o.extractNonceFromExtendedIdentifier(n);return new a.Struct(this.nativeToType("asset"),[new a.Field(new a.TokenIdentifierValue(c),"token_identifier"),new a.Field(new a.U64Value(BigInt(l)),"token_nonce"),new a.Field(new a.BigUIntValue(BigInt(i)),"amount")])}if(t===W.Null)return new a.NothingValue;if(t===W.Optional){let n=this.stringToTyped(r);return n instanceof a.NothingValue?a.OptionalValue.newMissing():new a.OptionalValue(n.getType(),n)}if(t===W.List){let[n,i]=r.split(gt,2),c=i.split(h.ArgListSeparator).map(l=>this.stringToTyped(n+h.ArgParamsSeparator+l));return new a.List(this.nativeToType(n),c)}if(t===W.Token)return r?new a.TokenIdentifierValue(r):new a.NothingValue;if(t===W.CodeMeta)return new a.CodeMetadataValue(a.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${t}`)}splitTupleStrings(e){let t=[],r="",n=0;for(let i=0;i<e.length;i++){let o=e[i];if(o==="(")n++;else if(o===")")n--;else if(o===","&&n===0){t.push(r.trim()),r="";continue}r+=o}return r.trim()&&t.push(r.trim()),t}typeToString(e){if(e.hasExactClass(a.OptionType.ClassName))return u.Option+h.ArgParamsSeparator+this.typeToString(e.getFirstTypeParameter());if(e.hasExactClass(a.VariadicType.ClassName))return u.Vector+h.ArgParamsSeparator+this.typeToString(e.getFirstTypeParameter());if(e.hasExactClass(a.StringType.ClassName))return u.String;if(e.hasExactClass(a.U8Type.ClassName))return u.Uint8;if(e.hasExactClass(a.U16Type.ClassName))return u.Uint16;if(e.hasExactClass(a.U32Type.ClassName))return u.Uint32;if(e.hasExactClass(a.U64Type.ClassName))return u.Uint64;if(e.hasExactClass(a.BigUIntType.ClassName))return u.Biguint;if(e.hasExactClass(a.BooleanType.ClassName))return u.Bool;if(e.hasExactClass(a.AddressType.ClassName))return u.Address;if(e.hasExactClass(a.BytesType.ClassName))return u.Hex;if(e.hasExactClass(a.TokenIdentifierType.ClassName))return W.Token;if(e.hasExactClass(a.OptionalType.ClassName))return W.Optional+h.ArgParamsSeparator+this.typeToString(e.getFirstTypeParameter());if(e.hasExactClass(a.ListType.ClassName))return W.List+h.ArgParamsSeparator+this.typeToString(e.getFirstTypeParameter());if(e.hasExactClass(a.CodeMetadataType.ClassName))return W.CodeMeta;if(e.hasExactClass(a.StructType.ClassName)&&e.getClassName()==="EsdtTokenPayment")return u.Asset;if(e.hasExactClass(a.StructType.ClassName))return`${u.Struct}(${e.getName()})`;throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${e.getClassName()}`)}};var X=class{constructor(e,t,r){this.config=e;this.chain=t;this.typeRegistry=r;this.abi=new D(e,t),this.serializer=new L({typeRegistry:this.typeRegistry}),this.cache=new w.WarpCache(e.env,e.cache)}async getActionExecution(e,t,r){let n=this.cache.get(w.WarpCacheKey.WarpExecutable(this.config.env,e.meta?.hash||"",t))??[],i=await this.extractContractOutput(e,t,r,n),o=(0,w.getNextInfo)(this.config,[],e,t,i.output),c=(0,w.applyOutputToMessages)(e,i.output,this.config),l=(0,w.extractResolvedInputValues)(n);return{status:r.status?.isSuccessful?.()?"success":"error",warp:e,action:t,user:(0,w.getWarpWalletAddressFromConfig)(this.config,this.chain.name),txHash:r.hash,tx:r,next:o,values:i.values,output:i.output,messages:c,destination:null,resolvedInputs:l}}async extractContractOutput(e,t,r,n){let i=(0,w.getWarpActionByIndex)(e,t),o=[],c=[],l={};if(!e.output||i.type!=="contract")return{values:{string:o,native:c,mapped:{}},output:l};if(!Object.values(e.output).some(y=>y.includes("out")||y.includes("event"))){for(let[y,A]of Object.entries(e.output))l[y]=A;return{values:{string:o,native:c,mapped:{}},output:await(0,w.evaluateOutputCommon)(e,l,t,n,this.serializer.coreSerializer,this.config)}}let g=await this.abi.getAbiForAction(i),d=new ne.TransactionEventsParser({abi:g}),P=new ne.SmartContractTransactionsOutcomeParser({abi:g}).parseExecute({transactionOnNetwork:r,function:i.func||void 0});for(let[y,A]of Object.entries(e.output)){if(A.startsWith(w.WarpConstants.Transform.Prefix))continue;if(A.startsWith("input.")){l[y]=A;continue}let B=(0,w.parseOutputOutIndex)(A);if(B!==null&&B!==t){l[y]=null;continue}let[F,z,q]=A.split(".");if(F==="event"){if(!z||isNaN(Number(q)))continue;let _=Number(q),v=(0,ne.findEventsByFirstTopic)(r,z),nt=d.parseEvents({events:v})[0],le=Object.values(nt)[_]||null;o.push(String(le)),c.push(le),l[y]=le&&le.valueOf()}else if(F==="out"||F.startsWith("out[")){if(!z)continue;let _=Number(z),v=P.values[_-1]||null;q&&(v=v[q]||null),v&&typeof v=="object"&&(v="toFixed"in v?v.toFixed():v.valueOf()),o.push(String(v)),c.push(v),l[y]=v&&v.valueOf()}else l[y]=A}return{values:{string:o,native:c,mapped:{}},output:await(0,w.evaluateOutputCommon)(e,l,t,n,this.serializer.coreSerializer,this.config)}}async extractQueryOutput(e,t,r,n){let i=t.map(g=>this.serializer.typedToString(g)),o=t.map(g=>this.serializer.typedToNative(g)[1]),c={string:i,native:o,mapped:{}},l={};if(!e.output)return{values:c,output:l};let f=g=>{let d=g.split(".").slice(1).map(P=>parseInt(P)-1);if(d.length===0)return;let T=o[d[0]];for(let P=1;P<d.length;P++){if(T==null)return;T=T[d[P]]}return T};for(let[g,d]of Object.entries(e.output)){if(d.startsWith(w.WarpConstants.Transform.Prefix))continue;let T=(0,w.parseOutputOutIndex)(d);if(T!==null&&T!==r){l[g]=null;continue}d.startsWith("out.")||d==="out"||d.startsWith("out[")?l[g]=f(d)||null:l[g]=d}return l=await(0,w.evaluateOutputCommon)(e,l,r,n,this.serializer.coreSerializer,this.config),{values:c,output:l}}async resolveWarpOutputRecursively(e){let t=e.warp,r=e.entryActionIndex,n=e.executor,i=e.inputs,o=e.meta,c=new Map,l=new Set,f=this;async function g(y,A=[]){if(c.has(y))return c.get(y);if(l.has(y))throw new Error(`Circular dependency detected at action ${y}`);l.add(y);let B=t.actions[y-1];if(!B)throw new Error(`Action ${y} not found`);let F;if(B.type==="query")F=await n.executeQuery(t,y,A);else if(B.type==="collect")F=await n.executeCollect(t,y,A,o);else throw new Error(`Unsupported or interactive action type: ${B.type}`);if(c.set(y,F),t.output)for(let z of Object.values(t.output)){let _=String(z).match(/^out\[(\d+)\]/);if(_){let v=parseInt(_[1],10);v!==y&&!c.has(v)&&await g(v)}}return l.delete(y),F}await g(r,i);let d={};for(let y of c.values())for(let[A,B]of Object.entries(y.output))B!==null?d[A]=B:A in d||(d[A]=null);let T=await(0,w.evaluateOutputCommon)(t,d,r,i,this.serializer.coreSerializer,this.config);return{...c.get(r),action:r,output:T}}};var ft="EGLD-000000",ge=class{constructor(e,t,r){this.config=e;this.chain=t;this.typeRegistry=r;this.serializer=new L({typeRegistry:this.typeRegistry}),this.abi=new D(this.config,this.chain),this.output=new X(this.config,this.chain,this.typeRegistry)}async createTransaction(e){let t=(0,V.getWarpActionByIndex)(e.warp,e.action),r=null;if(t.type==="transfer")r=await this.createTransferTransaction(e);else if(t.type==="contract")r=await this.createContractCallTransaction(e);else{if(t.type==="query")throw new Error("WarpMultiversxExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead");if(t.type==="collect")throw new Error("WarpMultiversxExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead")}if(!r)throw new Error(`WarpMultiversxExecutor: Invalid action type (${t.type})`);return r}async createTransferTransaction(e){if(!e.destination)throw new Error("WarpMultiversxExecutor: createTransfer - destination not set");let t=(0,V.getWarpWalletAddressFromConfig)(this.config,e.chain.name);if(!t)throw new Error("WarpMultiversxExecutor: createTransfer - user address not set");let r=x.Address.newFromBech32(t),n=new x.TransactionsFactoryConfig({chainID:e.chain.chainId}),i=e.data?Buffer.from(this.serializer.stringToTyped(e.data).valueOf()):null,o=e.transfers.length===1&&e.transfers[0].identifier===this.chain.nativeToken?.identifier,l=(o?e.transfers[0].amount:0n)+e.value;return await new x.TransferTransactionsFactory({config:n}).createTransactionForTransfer(r,{receiver:x.Address.newFromBech32(e.destination),nativeAmount:l,tokenTransfers:o?[]:this.toTokenTransfers(e.transfers),data:i?new Uint8Array(i):void 0})}async createContractCallTransaction(e){if(!e.destination)throw new Error("WarpMultiversxExecutor: createContractCall - destination not set");let t=(0,V.getWarpWalletAddressFromConfig)(this.config,e.chain.name);if(!t)throw new Error("WarpMultiversxExecutor: createContractCall - user address not set");let r=(0,V.getWarpActionByIndex)(e.warp,e.action),n=x.Address.newFromBech32(t),i=e.args.map(c=>this.serializer.stringToTyped(c)),o=new x.TransactionsFactoryConfig({chainID:e.chain.chainId});return new x.SmartContractTransactionsFactory({config:o}).createTransactionForExecute(n,{contract:x.Address.newFromBech32(e.destination),function:"func"in r&&r.func||"",gasLimit:"gasLimit"in r?BigInt(r.gasLimit||0):0n,arguments:i,tokenTransfers:this.toTokenTransfers(e.transfers),nativeTransferAmount:e.value})}async executeQuery(e){if(!e.destination)throw new Error("WarpMultiversxExecutor: executeQuery - destination not set");let t=(0,V.getWarpActionByIndex)(e.warp,e.action);if(t.type!=="query")throw new Error(`WarpMultiversxExecutor: Invalid action type for executeQuery: ${t.type}`);let r=await this.abi.getAbiForAction(t),n=e.args.map(v=>this.serializer.stringToTyped(v)),i=C(e.chain,this.config.env,this.config),o=x.Address.newFromBech32(e.destination),c=i.createSmartContractController(r),l=c.createQuery({contract:o,function:t.func||"",arguments:n}),f=await c.runQuery(l),g=f.returnCode==="ok",d=new x.ArgSerializer,T=r.getEndpoint(f.function||t.func||""),P=(f.returnDataParts||[]).map(v=>Buffer.from(v)),y=d.buffersToValues(P,T.output),{values:A,output:B}=await this.output.extractQueryOutput(e.warp,y,e.action,e.resolvedInputs),F=(0,V.getNextInfo)(this.config,[],e.warp,e.action,B),q=e.resolvedInputs.find(v=>v.input.position==="receiver"||v.input.position==="destination")?.value||e.destination,_=(0,V.extractResolvedInputValues)(e.resolvedInputs);return{status:g?"success":"error",warp:e.warp,action:e.action,user:(0,V.getWarpWalletAddressFromConfig)(this.config,e.chain.name),txHash:null,tx:null,next:F,values:A,output:{...B,_DATA:y},messages:(0,V.applyOutputToMessages)(e.warp,B,this.config),destination:q,resolvedInputs:_}}toTokenTransfers(e){return e.map(t=>t.identifier===this.chain.nativeToken.identifier?{...t,identifier:ft}:t).map(t=>{let n=new x.TokenComputer().extractNonceFromExtendedIdentifier(t.identifier);return new x.TokenTransfer({token:new x.Token({identifier:t.identifier,nonce:BigInt(n||0)}),amount:t.amount})})}};var fe=class{constructor(e,t){this.chain=e;this.config=t}getExplorers(){let e=Be[this.chain];if(!e)return["multiversx_explorer"];let t=e[this.config.env];return t||["multiversx_explorer"]}getPrimaryExplorer(){return this.getExplorers()[0]}getExplorerUrlByName(e){let t=this.config.preferences?.explorers?.[this.chain];if(t&&!e){let i=G[t];if(i)return i}if(e){let i=G[e];if(i)return i}let r=this.getPrimaryExplorer();return G[r]||G[r]}getAccountUrl(e,t){return`${this.getExplorerUrlByName(t)}/accounts/${e}`}getTransactionUrl(e,t){return`${this.getExplorerUrlByName(t)}/transactions/${e}`}getBlockUrl(e,t){return`${this.getExplorerUrlByName(t)}/blocks/${e}`}getAssetUrl(e,t){return`${this.getExplorerUrlByName(t)}/tokens/${e}`}getContractUrl(e,t){return`${this.getExplorerUrlByName(t)}/accounts/${e}`}getAllExplorers(){return this.getExplorers()}getExplorerByName(e){return this.getExplorers().find(r=>r.toLowerCase()===e.toLowerCase())}getAccountUrls(e){let t=this.getAllExplorers(),r={};return t.forEach(n=>{let i=G[n];i&&(r[n]=`${i}/accounts/${e}`)}),r}getTransactionUrls(e){let t=this.getAllExplorers(),r={};return t.forEach(n=>{let i=G[n];i&&(r[n]=`${i}/transactions/${e}`)}),r}};var m=require("@multiversx/sdk-core"),U=require("@joai/warps");var Ne={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"},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],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}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpVerified",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"ownershipTransferred",inputs:[{name:"warp",type:"bytes",indexed:!0},{name:"old_owner",type:"Address",indexed:!0},{name:"new_owner",type:"Address",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{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 S=s=>{if(s==="devnet")return"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36";if(s==="testnet")throw new Error("Multiversx testnet is not supported");return"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"};var ye=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}),Ve=s=>({unitPrice:BigInt(s.unit_price.toString()),admins:s.admins.map(e=>e.toBech32())});var ve=class{constructor(e,t){this.config=e;this.chain=t;this.cache=new U.WarpCache(e.env,e.cache),this.registryConfig={unitPrice:BigInt(0),admins:[]},this.userWallet=(0,U.getWarpWalletAddressFromConfig)(this.config,this.chain.name)}async init(){await this.loadRegistryConfigs()}getRegistryConfig(){return this.registryConfig}async createWarpRegisterTransaction(e,t,r){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let n=m.Address.newFromBech32(this.userWallet),i=()=>this.isCurrentUserAdmin()?BigInt(0):t&&r?this.registryConfig.unitPrice*BigInt(3):t?this.registryConfig.unitPrice*BigInt(2):this.registryConfig.unitPrice,o=()=>t&&r?[m.BytesValue.fromHex(e),m.BytesValue.fromUTF8(t),m.BytesValue.fromHex(r)]:t?[m.BytesValue.fromHex(e),m.BytesValue.fromUTF8(t)]:[m.BytesValue.fromHex(e)];return await this.getFactory().createTransactionForExecute(n,{contract:m.Address.newFromBech32(S(this.config.env)),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:i(),arguments:o()})}async createWarpUnregisterTransaction(e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=m.Address.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(t,{contract:m.Address.newFromBech32(S(this.config.env)),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[m.BytesValue.fromHex(e)]})}async createWarpUpgradeTransaction(e,t,r){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let n=m.Address.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(n,{contract:m.Address.newFromBech32(S(this.config.env)),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:r?[m.BytesValue.fromUTF8(e),m.BytesValue.fromHex(t),m.BytesValue.fromHex(r)]:[m.BytesValue.fromUTF8(e),m.BytesValue.fromHex(t)]})}async createWarpAliasSetTransaction(e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(r,{contract:m.Address.newFromBech32(S(this.config.env)),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[m.BytesValue.fromHex(e),m.BytesValue.fromUTF8(t)]})}async createWarpVerifyTransaction(e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=m.Address.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(t,{contract:m.Address.newFromBech32(S(this.config.env)),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[m.BytesValue.fromHex(e)]})}async createWarpTransferOwnershipTransaction(e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(r,{contract:m.Address.newFromBech32(S(this.config.env)),function:"transferOwnership",gasLimit:BigInt(1e7),arguments:[m.BytesValue.fromHex(e),new m.AddressValue(new m.Address(t))]})}async createBrandRegisterTransaction(e){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=m.Address.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(t,{contract:m.Address.newFromBech32(S(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[m.BytesValue.fromHex(e)]})}async createWarpBrandingTransaction(e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(r,{contract:m.Address.newFromBech32(S(this.config.env)),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[m.BytesValue.fromHex(e),m.BytesValue.fromHex(t)]})}async getInfoByAlias(e,t){try{let r=U.WarpCacheKey.RegistryInfo(this.config.env,e),n=t?this.cache.get(r):null;if(n)return U.WarpLogger.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${e}`),n;let i=m.Address.newFromBech32(S(this.config.env)),o=this.getController(),c=o.createQuery({contract:i,function:"getInfoByAlias",arguments:[m.BytesValue.fromUTF8(e)]}),l=await o.runQuery(c),[f]=o.parseQueryResponse(l),g=f?ye(f):null,d=g?.brand?await this.fetchBrand(g.brand):null;return t&&t.ttl&&this.cache.set(r,{registryInfo:g,brand:d},t.ttl),{registryInfo:g,brand:d}}catch{return{registryInfo:null,brand:null}}}async getInfoByHash(e,t){try{let r=U.WarpCacheKey.RegistryInfo(this.config.env,e);if(t){let d=this.cache.get(r);if(d)return U.WarpLogger.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${e}`),d}let n=m.Address.newFromBech32(S(this.config.env)),i=this.getController(),o=i.createQuery({contract:n,function:"getInfoByHash",arguments:[m.BytesValue.fromHex(e)]}),c=await i.runQuery(o),[l]=i.parseQueryResponse(c),f=l?ye(l):null,g=f?.brand?await this.fetchBrand(f.brand):null;return t&&t.ttl&&this.cache.set(r,{registryInfo:f,brand:g},t.ttl),{registryInfo:f,brand:g}}catch{return{registryInfo:null,brand:null}}}async getUserWarpRegistryInfos(e){try{let t=e||this.userWallet;if(!t)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(S(this.config.env)),n=this.getController(),i=n.createQuery({contract:r,function:"getUserWarps",arguments:[new m.AddressValue(new m.Address(t))]}),o=await n.runQuery(i),[c]=n.parseQueryResponse(o);return c.map(ye)}catch{return[]}}async getUserBrands(e){try{let t=e||this.userWallet;if(!t)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(S(this.config.env)),n=this.getController(),i=n.createQuery({contract:r,function:"getUserBrands",arguments:[new m.AddressValue(new m.Address(t))]}),o=await n.runQuery(i),[c]=n.parseQueryResponse(o),l=c.map(d=>d.toString("hex")),f={ttl:365*24*60*60};return(await Promise.all(l.map(d=>this.fetchBrand(d,f)))).filter(d=>d!==null)}catch{return[]}}async fetchBrand(e,t){let r=U.WarpCacheKey.Brand(this.config.env,e),n=t?this.cache.get(r):null;if(n)return U.WarpLogger.info(`WarpRegistry (fetchBrand): Brand found in cache: ${e}`),n;let o=C(this.chain,this.config.env,this.config).createNetworkProvider();try{let c=await o.getTransaction(e),l=JSON.parse(c.data.toString());return l.meta={query:null,chain:this.chain.name,identifier:(0,U.createWarpIdentifier)(this.chain.name,"hash",e),hash:c.hash,creator:c.sender.toBech32(),createdAt:new Date(c.timestamp*1e3).toISOString()},t&&t.ttl&&this.cache.set(r,l,t.ttl),l}catch{return null}}async loadRegistryConfigs(){let e=m.Address.newFromBech32(S(this.config.env)),t=this.getController(),[r]=await t.query({contract:e,function:"getConfig",arguments:[]}),n=r?Ve(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let e=new m.TransactionsFactoryConfig({chainID:this.chain.chainId}),t=m.AbiRegistry.create(Ne);return new m.SmartContractTransactionsFactory({config:e,abi:t})}getController(){let e=C(this.chain,this.config.env,this.config),t=m.AbiRegistry.create(Ne);return e.createSmartContractController(t)}isCurrentUserAdmin(){return!!this.userWallet&&this.registryConfig.admins.includes(this.userWallet)}};var et=require("@multiversx/sdk-core"),ee=require("@joai/warps");var M=require("@multiversx/sdk-core"),Ye=pt(require("@scure/bip39"),1),Ze=require("@scure/bip39/wordlists/english.js"),b=require("@joai/warps"),Y=class Y{constructor(e,t){this.config=e;this.chain=t;this.account=null}async getAddress(){let e=(0,b.getWarpWalletAddressFromConfig)(this.config,this.chain.name);if(e)return e;try{return this.getAccount().address.toBech32()}catch{return null}}async getPublicKey(){try{return this.getAccount().publicKey.hex()}catch{return null}}async signTransaction(e){let r=await this.getAccount().signTransaction(e);return e.signature=r,e}async signMessage(e){let t=this.getAccount(),r=new TextEncoder().encode(e),n=await t.signMessage(new M.Message({data:r}));return Buffer.from(n).toString("hex")}getAccountInstance(){return this.getAccount()}async importFromMnemonic(e){let t=(0,b.normalizeAndValidateMnemonic)(e),n=M.Mnemonic.fromString(t).deriveKey(0),i=n.hex(),c=n.generatePublicKey().toAddress(this.chain.addressHrp).toBech32(),l={provider:Y.PROVIDER_NAME,address:c,privateKey:i,mnemonic:t};return(0,b.setWarpWalletInConfig)(this.config,this.chain.name,l),l}async importFromPrivateKey(e){let t=M.UserSecretKey.fromString(e),r=t.hex(),i=t.generatePublicKey().toAddress(this.chain.addressHrp).toBech32(),o={provider:Y.PROVIDER_NAME,address:i,privateKey:r,mnemonic:null};return(0,b.setWarpWalletInConfig)(this.config,this.chain.name,o),o}async export(){let e=this.getAccount(),t=(0,b.getWarpWalletMnemonicFromConfig)(this.config,this.chain.name),r=(0,b.getWarpWalletPrivateKeyFromConfig)(this.config,this.chain.name);return{provider:Y.PROVIDER_NAME,address:e.address.toBech32(),privateKey:r||null,mnemonic:t||null}}async generate(){let e=Ye.generateMnemonic(Ze.wordlist,256),t=(0,b.normalizeMnemonic)(e);(0,b.validateMnemonicLength)(t);let o=M.Mnemonic.fromString(t).deriveKey(0).generatePublicKey().toAddress(this.chain.addressHrp).toBech32();return{provider:Y.PROVIDER_NAME,address:o,privateKey:null,mnemonic:t}}getAccount(){if(this.account)return this.account;let e=(0,b.getWarpWalletMnemonicFromConfig)(this.config,this.chain.name);if(!e)throw new Error("No mnemonic provided");let r=M.Mnemonic.fromString(e).deriveKey(0);return this.account=new M.Account(r),this.account}};Y.PROVIDER_NAME="mnemonic";var ae=Y;var k=require("@multiversx/sdk-core"),R=require("@joai/warps"),Z=class Z{constructor(e,t){this.config=e;this.chain=t;this.account=null}async getAddress(){let e=(0,R.getWarpWalletAddressFromConfig)(this.config,this.chain.name);if(e)return e;try{return this.getAccount().address.toBech32()}catch{return null}}async getPublicKey(){try{return this.getAccount().publicKey.hex()}catch{return null}}async signTransaction(e){let r=await this.getAccount().signTransaction(e);return e.signature=r,e}async signMessage(e){let t=this.getAccount(),r=new TextEncoder().encode(e),n=await t.signMessage(new k.Message({data:r}));return Buffer.from(n).toString("hex")}getAccountInstance(){return this.getAccount()}async importFromMnemonic(e){let r=k.Mnemonic.fromString(e).deriveKey(0),n=r.hex(),o=r.generatePublicKey().toAddress(this.chain.addressHrp).toBech32(),c={provider:Z.PROVIDER_NAME,address:o,privateKey:n,mnemonic:e};return(0,R.setWarpWalletInConfig)(this.config,this.chain.name,c),c}async importFromPrivateKey(e){let r=e.startsWith("-----")?k.UserSecretKey.fromPem(e):k.UserSecretKey.fromString(e),n=r.hex(),o=r.generatePublicKey().toAddress(this.chain.addressHrp).toBech32(),c={provider:Z.PROVIDER_NAME,address:o,privateKey:n,mnemonic:null};return(0,R.setWarpWalletInConfig)(this.config,this.chain.name,c),c}async export(){let e=this.getAccount(),t=(0,R.getWarpWalletPrivateKeyFromConfig)(this.config,this.chain.name),r=(0,R.getWarpWalletMnemonicFromConfig)(this.config,this.chain.name);return{provider:Z.PROVIDER_NAME,address:e.address.toBech32(),privateKey:t||null,mnemonic:r||null}}async generate(){let e=k.UserSecretKey.generate(),t=e.hex(),n=e.generatePublicKey().toAddress(this.chain.addressHrp).toBech32();return{provider:Z.PROVIDER_NAME,address:n,privateKey:t,mnemonic:null}}getAccount(){if(this.account)return this.account;let e=(0,R.getWarpWalletPrivateKeyFromConfig)(this.config,this.chain.name);if(!e)throw new Error("No private key provided");let r=e.startsWith("-----")?k.UserSecretKey.fromPem(e):k.UserSecretKey.fromString(e);return this.account=new k.Account(r),this.account}};Z.PROVIDER_NAME="privateKey";var ie=Z;var se=require("@joai/warps"),oe=class{constructor(e,t){this.config=e;this.chain=t}async getAddress(){return(0,se.getWarpWalletAddressFromConfig)(this.config,this.chain.name)}async getPublicKey(){return null}async signTransaction(e){let t=await this.getAddress();throw new Error(`Wallet can not be used for signing: ${t}`)}async signMessage(e){let t=await this.getAddress();throw new Error(`Wallet can not be used for signing: ${t}`)}async importFromMnemonic(e){let t=(0,se.getWarpWalletAddressFromConfig)(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${t}`)}async importFromPrivateKey(e){let t=(0,se.getWarpWalletAddressFromConfig)(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${t}`)}async export(){let e=(0,se.getWarpWalletAddressFromConfig)(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${e}`)}async generate(){let e=(0,se.getWarpWalletAddressFromConfig)(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${e}`)}};var We=class{constructor(e,t){this.config=e;this.chain=t;this.cachedAddress=null;this.cachedPublicKey=null;this.entry=C(t,e.env,e),this.cache=new ee.WarpCache(e.env,e.cache),this.walletProvider=this.createProvider(),this.initializeCache()}async signTransaction(e){let t=e;if(!t||typeof t!="object")throw new Error("Invalid transaction object");if(!this.walletProvider)throw new Error("No wallet provider available");if(this.walletProvider instanceof oe)throw new Error(`Wallet (${this.chain.name}) is read-only`);if(this.walletProvider instanceof ie||this.walletProvider instanceof ae){let n=this.walletProvider.getAccountInstance();if(t.nonce===0n){let i=await this.entry.recallAccountNonce(n.address),o=this.cache.get(`nonce:${n.address.toBech32()}`)||0,c=BigInt(Math.max(o,Number(i)));t.nonce=c}}else if(t.nonce===0n&&this.cachedAddress){let n=et.Address.newFromBech32(this.cachedAddress),i=await this.entry.recallAccountNonce(n),o=this.cache.get(`nonce:${this.cachedAddress}`)||0,c=BigInt(Math.max(o,Number(i)));t.nonce=c}let r=await this.walletProvider.signTransaction(t);if(this.walletProvider instanceof ie||this.walletProvider instanceof ae){let n=this.walletProvider.getAccountInstance(),i=Number(n.nonce)+1;this.cache.set(`nonce:${n.address.toBech32()}`,i,ee.CacheTtl.OneMinute)}else if(this.cachedAddress){let n=t.nonce?Number(t.nonce):0;this.cache.set(`nonce:${this.cachedAddress}`,n+1,ee.CacheTtl.OneMinute)}return r}async signTransactions(e){let t=[];for(let r of e)t.push(await this.signTransaction(r));return t}async signMessage(e){if(!this.walletProvider)throw new Error("No wallet provider available");if(this.walletProvider instanceof oe)throw new Error(`Wallet (${this.chain.name}) is read-only`);return await this.walletProvider.signMessage(e)}async sendTransactions(e){return Promise.all(e.map(async t=>this.sendTransaction(t)))}async sendTransaction(e){let t=e;if(!t||typeof t!="object")throw new Error("Invalid transaction object");if(!t.signature||t.signature.length===0)throw new Error("Transaction must be signed before sending");return await this.entry.sendTransaction(t)}async importFromMnemonic(e){return await this.createProviderForOperation("mnemonic").importFromMnemonic(e)}async importFromPrivateKey(e){return await this.createProviderForOperation("privateKey").importFromPrivateKey(e)}async export(e){return await this.createProviderForOperation(e).export()}async generate(e){return await this.createProviderForOperation(e).generate()}getAddress(){return this.cachedAddress}getPublicKey(){return this.cachedPublicKey}createProvider(){let e=this.config.user?.wallets?.[this.chain.name];return e?typeof e=="string"?new oe(this.config,this.chain):this.createProviderForOperation(e.provider):null}initializeCache(){(0,ee.initializeWalletCache)(this.walletProvider).then(e=>{this.cachedAddress=e.address,this.cachedPublicKey=e.publicKey})}createProviderForOperation(e){let r=this.config.walletProviders?.[this.chain.name]?.[e];if(r){let n=r(this.config,this.chain);if(!n)throw new Error(`Custom wallet provider factory returned null for ${e}`);return n}if(e==="privateKey")return new ie(this.config,this.chain);if(e==="mnemonic")return new ae(this.config,this.chain);throw new Error(`Unsupported wallet provider for ${this.chain.name}: ${e}`)}};var we=(s,e)=>(t,r)=>{let n=e[t.env],i=new tt.WarpTypeRegistry;return i.registerType("token",{stringToNative:o=>o,nativeToString:o=>`token:${o}`}),i.registerType("codemeta",{stringToNative:o=>o,nativeToString:o=>`codemeta:${o}`}),i.registerTypeAlias("list","vector"),{chainInfo:n,builder:()=>new de(t,n),executor:new ge(t,n,i),output:new X(t,n,i),serializer:new L({typeRegistry:i}),registry:new ve(t,n),explorer:new fe(s,t),abiBuilder:()=>new D(t,n),brandBuilder:()=>new me(t,n),dataLoader:new he(t,n),wallet:new We(t,n)}};var ce=require("@joai/warps");var xe={chain:ce.WarpChainName.Multiversx,identifier:"EGLD",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/tokens/logos/egld.svg"},Ue=we(ce.WarpChainName.Multiversx,{mainnet:{name:ce.WarpChainName.Multiversx,displayName:"MultiversX",chainId:"1",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://api.multiversx.com",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/multiversx.svg",nativeToken:xe},testnet:{name:ce.WarpChainName.Multiversx,displayName:"MultiversX Testnet",chainId:"T",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://testnet-api.multiversx.com",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/multiversx.svg",nativeToken:xe},devnet:{name:ce.WarpChainName.Multiversx,displayName:"MultiversX Devnet",chainId:"D",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://devnet-api.multiversx.com",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/multiversx.svg",nativeToken:xe}});var Ae=require("@joai/warps");var rt={chain:Ae.WarpChainName.Vibechain,identifier:"VIBE",name:"VIBE",symbol:"VIBE",decimals:18,logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/tokens/logos/vibe.svg"},ke={name:Ae.WarpChainName.Vibechain,displayName:"VibeChain",chainId:"V",blockTime:600,addressHrp:"vibe",defaultApiUrl:"https://vibeox-api.multiversx.com",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/vibechain.svg",nativeToken:rt},Fe=we(Ae.WarpChainName.Vibechain,{mainnet:ke,testnet:ke,devnet:ke});var vt=()=>[Ue,Fe];var K=require("@joai/warps");var Wt=s=>new K.WarpSerializer().nativeToString(W.Token,s),wt=s=>new K.WarpSerializer().nativeToString(W.CodeMeta,s),Tt=(s,e)=>{if(e===null)return W.Optional+K.WarpConstants.ArgParamsSeparator;let t=s(e),r=t.indexOf(K.WarpConstants.ArgParamsSeparator),n=t.substring(0,r),i=t.substring(r+1);return W.Optional+K.WarpConstants.ArgParamsSeparator+n+K.WarpConstants.ArgParamsSeparator+i},Ct=s=>new K.WarpSerializer().nativeToString(W.List,s);var p=require("@multiversx/sdk-core"),xt=(s,e)=>s?p.OptionValue.newProvided(s):e?p.OptionValue.newMissingTyped(e):p.OptionValue.newMissing(),At=(s,e)=>s?new p.OptionalValue(s.getType(),s):e?new p.OptionalValue(e):p.OptionalValue.newMissing(),Et=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let e=s[0].getType();return new p.List(e,s)},bt=s=>p.VariadicValue.fromItems(...s),Pt=s=>{let e=s.map(t=>t.getType());return new p.CompositeValue(new p.CompositeType(...e),s)},It=s=>p.StringValue.fromUTF8(s),St=s=>new p.U8Value(s),Bt=s=>new p.U16Value(s),Nt=s=>new p.U32Value(s),Vt=s=>new p.U64Value(s),Ut=s=>new p.BigUIntValue(BigInt(s)),kt=s=>new p.BooleanValue(s),Ft=s=>new p.AddressValue(p.Address.newFromBech32(s)),Ot=s=>new p.TokenIdentifierValue(s),Mt=s=>p.BytesValue.fromHex(s),Rt=s=>new p.Struct(new p.StructType("EsdtTokenPayment",[new p.FieldDefinition("token_identifier","",new p.TokenIdentifierType),new p.FieldDefinition("token_nonce","",new p.U64Type),new p.FieldDefinition("amount","",new p.BigUIntType)]),[new p.Field(new p.TokenIdentifierValue(s.token.identifier),"token_identifier"),new p.Field(new p.U64Value(BigInt(s.token.nonce)),"token_nonce"),new p.Field(new p.BigUIntValue(BigInt(s.amount)),"amount")]),Dt=s=>new p.CodeMetadataValue(p.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),Lt=()=>new p.NothingValue;0&&(module.exports={ExplorerUrls,KnownTokens,MultiversxAdapter,MultiversxExplorers,MultiversxExplorersConfig,NativeTokenEgld,NativeTokenVibe,VibechainAdapter,VibechainExplorers,WarpMultiversxAbiBuilder,WarpMultiversxBrandBuilder,WarpMultiversxBuilder,WarpMultiversxConstants,WarpMultiversxContractLoader,WarpMultiversxDataLoader,WarpMultiversxExecutor,WarpMultiversxExplorer,WarpMultiversxInputTypes,WarpMultiversxOutput,WarpMultiversxRegistry,WarpMultiversxSerializer,WarpMultiversxWallet,address_value,asset_value,biguint_value,boolean_value,codemeta,codemeta_value,composite_value,createMultiversxAdapter,findKnownTokenById,getAllMultiversxAdapters,getAllMultiversxChainNames,getKnownTokensForChain,getMultiversxEntrypoint,getMultiversxRegistryAddress,getNormalizedTokenIdentifier,hex_value,isNativeToken,list,list_value,nothing_value,option_value,optional,optional_value,string_value,toTypedConfigInfo,toTypedRegistryInfo,token,token_value,u16_value,u32_value,u64_value,u8_value,variadic_value});
1
+ "use strict";var it=Object.create;var Ce=Object.defineProperty;var st=Object.getOwnPropertyDescriptor;var ot=Object.getOwnPropertyNames;var ct=Object.getPrototypeOf,lt=Object.prototype.hasOwnProperty;var pt=(s,e)=>{for(var t in e)Ce(s,t,{get:e[t],enumerable:!0})},Me=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ot(e))!lt.call(s,n)&&n!==t&&Ce(s,n,{get:()=>e[n],enumerable:!(r=st(e,n))||r.enumerable});return s};var ut=(s,e,t)=>(t=s!=null?it(ct(s)):{},Me(e||!s||!s.__esModule?Ce(t,"default",{value:s,enumerable:!0}):t,s)),mt=s=>Me(Ce({},"__esModule",{value:!0}),s);var Ht={};pt(Ht,{ExplorerUrls:()=>G,KnownTokens:()=>Ie,MultiversxAdapter:()=>Ue,MultiversxExplorers:()=>Je,MultiversxExplorersConfig:()=>Be,NativeTokenEgld:()=>xe,NativeTokenVibe:()=>nt,VibechainAdapter:()=>ke,VibechainExplorers:()=>Xe,WarpMultiversxAbiBuilder:()=>D,WarpMultiversxBrandBuilder:()=>me,WarpMultiversxBuilder:()=>de,WarpMultiversxConstants:()=>ft,WarpMultiversxContractLoader:()=>ue,WarpMultiversxDataLoader:()=>he,WarpMultiversxExecutor:()=>ge,WarpMultiversxExplorer:()=>fe,WarpMultiversxInputTypes:()=>v,WarpMultiversxOutput:()=>X,WarpMultiversxRegistry:()=>We,WarpMultiversxSerializer:()=>L,WarpMultiversxWallet:()=>ve,address_value:()=>Ot,asset_value:()=>Lt,biguint_value:()=>kt,boolean_value:()=>Mt,codemeta:()=>Tt,codemeta_value:()=>Kt,composite_value:()=>St,createMultiversxAdapter:()=>we,findKnownTokenById:()=>Se,getAllMultiversxAdapters:()=>wt,getAllMultiversxChainNames:()=>dt,getKnownTokensForChain:()=>ht,getMultiversxEntrypoint:()=>T,getMultiversxRegistryAddress:()=>S,getNormalizedTokenIdentifier:()=>pe,hex_value:()=>Dt,isNativeToken:()=>Q,list:()=>At,list_value:()=>Pt,nothing_value:()=>_t,option_value:()=>Et,optional:()=>xt,optional_value:()=>bt,string_value:()=>Bt,toTypedConfigInfo:()=>Ve,toTypedRegistryInfo:()=>ye,token:()=>Ct,token_value:()=>Rt,u16_value:()=>Vt,u32_value:()=>Ut,u64_value:()=>Ft,u8_value:()=>Nt,variadic_value:()=>It});module.exports=mt(Ht);var Ee=require("@joai/warps"),dt=()=>[Ee.WarpChainName.Multiversx,Ee.WarpChainName.Vibechain];var rt=require("@joai/warps");var M=require("@multiversx/sdk-core"),E=require("@joai/warps");var re=require("@multiversx/sdk-core"),Oe=require("@joai/warps"),Q=s=>!s.includes("-"),pe=s=>Q(s)?`${s}-000000`:s,T=(s,e,t)=>{let r="warp-sdk",i=t?(0,Oe.getProviderConfig)(t,s.name,e,s.defaultApiUrl):{url:s.defaultApiUrl},o=i.url,c={headers:i.headers};return e==="devnet"?new re.DevnetEntrypoint({url:o,kind:"api",clientName:r,networkProviderConfig:c}):e==="testnet"?new re.TestnetEntrypoint({url:o,kind:"api",clientName:r,networkProviderConfig:c}):new re.MainnetEntrypoint({url:o,kind:"api",clientName:r,networkProviderConfig:c})};var be=require("@joai/warps");var ue=class{constructor(e){this.config=e}async getContract(e,t){try{let i=await T(t,this.config.env,this.config).createNetworkProvider().doGetGeneric(`accounts/${e}`);return{address:e,owner:i.ownerAddress,verified:i.isVerified||!1}}catch(r){return be.WarpLogger.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(e,t){try{let i=await T(t,this.config.env,this.config).createNetworkProvider().doGetGeneric(`accounts/${e}/verification`);return{codeHash:i.codeHash,abi:i.source.abi}}catch(r){return be.WarpLogger.error("WarpContractLoader: getVerificationInfo error",r),null}}};var D=class{constructor(e,t){this.config=e;this.chain=t;this.contractLoader=new ue(this.config),this.cache=new E.WarpCache(this.config.env,this.config.cache)}async createInscriptionTransaction(e){let t=(0,E.getWarpWalletAddressFromConfig)(this.config,this.chain.name);if(!t)throw new Error("WarpBuilder: user address not set");let r=new M.TransactionsFactoryConfig({chainID:this.chain.chainId}),n=new M.TransferTransactionsFactory({config:r}),i=M.Address.newFromBech32(t),o={protocol:(0,E.getLatestProtocolIdentifier)("abi"),content:e},c=JSON.stringify(o),l=await n.createTransactionForTransfer(i,{receiver:i,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(c))});return l.gasLimit=l.gasLimit+BigInt(2e6),l}async createFromRaw(e){return JSON.parse(e)}async createFromTransaction(e){let t=await this.createFromRaw(e.data.toString());return t.meta={chain:this.chain.name,identifier:(0,E.createWarpIdentifier)(this.chain.name,"hash",e.hash),query:null,hash:e.hash,creator:e.sender.toBech32(),createdAt:new Date(e.timestamp*1e3).toISOString()},t}async createFromTransactionHash(e,t){let r=E.WarpCacheKey.WarpAbi(this.config.env,e);if(t){let o=this.cache.get(r);if(o)return E.WarpLogger.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${e}`),o}let i=T(this.chain,this.config.env,this.config).createNetworkProvider();try{let o=await i.getTransaction(e),c=await this.createFromTransaction(o);return t&&t.ttl&&c&&this.cache.set(r,c,t.ttl),c}catch(o){return E.WarpLogger.error("WarpAbiBuilder: Error creating from transaction hash",o),null}}async getAbiForAction(e){if(e.abi)return await this.fetchAbi(e);if(!e.address)throw new Error("WarpActionExecutor: Address not found");let t=await this.contractLoader.getVerificationInfo(e.address,this.chain);if(!t)throw new Error("WarpActionExecutor: Verification info not found");return M.AbiRegistry.create(t.abi)}async fetchAbi(e){if(!e.abi)throw new Error("WarpActionExecutor: ABI not found");if(e.abi.startsWith(E.WarpConstants.IdentifierType.Hash)){let t=e.abi.split(E.WarpConstants.ArgParamsSeparator)[1],r=await this.createFromTransactionHash(t);if(!r)throw new Error(`WarpActionExecutor: ABI not found for hash: ${e.abi}`);return M.AbiRegistry.create(r.content)}else{let r=await(await fetch(e.abi)).json();return M.AbiRegistry.create(r)}}};var j=require("@multiversx/sdk-core"),H=require("@joai/warps"),Re=require("buffer");var me=class{constructor(e,t){this.config=e;this.chain=t;this.core=new H.WarpBrandBuilder(e)}async createInscriptionTransaction(e){let t=(0,H.getWarpWalletAddressFromConfig)(this.config,this.chain.name);if(!t)throw new Error("BrandBuilder: user address not set");let r=new j.TransactionsFactoryConfig({chainID:this.chain.chainId}),n=new j.TransferTransactionsFactory({config:r}),i=j.Address.newFromBech32(t),o=JSON.stringify(e);return await n.createTransactionForNativeTokenTransfer(i,{receiver:j.Address.newFromBech32(t),nativeAmount:BigInt(0),data:Uint8Array.from(Re.Buffer.from(o))})}async createFromTransaction(e,t=!1){let r=await this.core.createFromRaw(e.data.toString(),t);return r.meta={query:null,chain:this.chain.name,identifier:(0,H.createWarpIdentifier)(this.chain.name,"hash",e.hash),hash:e.hash,creator:e.sender.toBech32(),createdAt:new Date(e.timestamp*1e3).toISOString()},r}async createFromTransactionHash(e){let r=T(this.chain,this.config.env,this.config).createNetworkProvider();try{let n=await r.getTransaction(e);return this.createFromTransaction(n)}catch(n){return H.WarpLogger.error("BrandBuilder: Error creating from transaction hash",n),null}}};var J=require("@multiversx/sdk-core"),N=require("@joai/warps");var de=class extends N.WarpBuilder{constructor(t,r){super(t);this.config=t;this.chain=r;this.cache=new N.WarpCache(t.env,t.cache),this.core=new N.WarpBuilder(t)}async createInscriptionTransaction(t){let r=(0,N.getWarpWalletAddressFromConfig)(this.config,this.chain.name);if(!r)throw new Error("WarpBuilder: user address not set");let n=new J.TransactionsFactoryConfig({chainID:this.chain.chainId}),i=new J.TransferTransactionsFactory({config:n}),o=J.Address.newFromBech32(r),c=JSON.stringify(t),l=await i.createTransactionForTransfer(o,{receiver:J.Address.newFromBech32(r),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(c))});return l.gasLimit=l.gasLimit+BigInt(2e6),l}async createFromTransaction(t,r=!1){let n=await this.core.createFromRaw(t.data.toString(),r);return n.meta={chain:this.chain.name,identifier:(0,N.createWarpIdentifier)(this.chain.name,"hash",t.hash),query:null,hash:t.hash,creator:t.sender.toBech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},n}async createFromTransactionHash(t,r){let n=N.WarpCacheKey.Warp(this.config.env,t);if(r){let c=this.cache.get(n);if(c)return N.WarpLogger.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),c}let o=T(this.chain,this.config.env,this.config).createNetworkProvider();try{let c=await o.getTransaction(t),l=await this.createFromTransaction(c);return r&&r.ttl&&l&&this.cache.set(n,l,r.ttl),l}catch(c){return N.WarpLogger.error("WarpBuilder: Error creating from transaction hash",c),null}}};var $=require("@multiversx/sdk-core"),ne=require("@joai/warps");var Pe=require("@joai/warps");var Le=require("@joai/warps"),De=Le.WarpChainName.Multiversx,Ke=[{chain:De,identifier:"EGLD",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"},{chain:De,identifier:"EGLD-000000",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"}];var _e=require("@joai/warps"),I=_e.WarpChainName.Multiversx,He=[{chain:I,identifier:"EGLD",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"},{chain:I,identifier:"EGLD-000000",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"},{chain:I,identifier:"SEGLD-3ad2d0",name:"StakedEGLD",symbol:"SEGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/SEGLD-3ad2d0/icon.png"},{chain:I,identifier:"HSEGLD-c13a4e",name:"HatomSEGLD",symbol:"HSEGLD",decimals:8,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/HSEGLD-c13a4e/icon.png"},{chain:I,identifier:"UTK-2f80e9",name:"xMoney UTK",symbol:"UTK",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/UTK-2f80e9/icon.png"},{chain:I,identifier:"USDC-c76f1f",name:"WrappedUSDC",symbol:"USDC",decimals:6,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/USDC-c76f1f/icon.png"},{chain:I,identifier:"WEGLD-bd4d79",name:"WrappedEGLD",symbol:"WEGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/WEGLD-bd4d79/icon.png"},{chain:I,identifier:"HTM-f51d55",name:"Hatom",symbol:"HTM",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/HTM-f51d55/icon.png"},{chain:I,identifier:"MEX-455c57",name:"MEX",symbol:"MEX",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/MEX-455c57/icon.png"},{chain:I,identifier:"WTAO-4f5363",name:"WrappedTAO",symbol:"WTAO",decimals:9,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/WTAO-4f5363/icon.png"},{chain:I,identifier:"HEGLD-d61095",name:"HatomEGLD",symbol:"HEGLD",decimals:8,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/HEGLD-d61095/icon.png"},{chain:I,identifier:"WBTC-5349b3",name:"WrappedBTC",symbol:"WBTC",decimals:8,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/WBTC-5349b3/icon.png"},{chain:I,identifier:"WETH-b4ca29",name:"WrappedETH",symbol:"WETH",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/WETH-b4ca29/icon.png"},{chain:I,identifier:"USH-111e09",name:"HatomUSD",symbol:"USH",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/USH-111e09/icon.png"},{chain:I,identifier:"USDT-f8c08c",name:"WrappedUSDT",symbol:"USDT",decimals:6,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/USDT-f8c08c/icon.png"}];var Ge=require("@joai/warps"),$e=Ge.WarpChainName.Multiversx,ze=[{chain:$e,identifier:"EGLD",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"},{chain:$e,identifier:"EGLD-000000",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"}];var Qe=require("@joai/warps"),qe=Qe.WarpChainName.Vibechain,Te=[{chain:qe,identifier:"VIBE",name:"VIBE",symbol:"VIBE",decimals:18,logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/tokens/logos/vibe.svg"},{chain:qe,identifier:"VIBE-000000",name:"VIBE",symbol:"VIBE",decimals:18,logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/tokens/logos/vibe.svg"}];var Ie={[Pe.WarpChainName.Multiversx]:{mainnet:He,testnet:ze,devnet:Ke},[Pe.WarpChainName.Vibechain]:{mainnet:Te,testnet:Te,devnet:Te}},Se=(s,e,t)=>(Ie[s]?.[e]||[]).find(n=>n.identifier===t)||null,ht=(s,e)=>Ie[s]?.[e]||[];var he=class{constructor(e,t){this.config=e;this.chain=t;this.cache=new ne.WarpCache(e.env,e.cache)}async getAccount(e){let r=await T(this.chain,this.config.env,this.config).createNetworkProvider().getAccount($.Address.newFromBech32(e));return{chain:this.chain.name,address:r.address.toBech32(),balance:r.balance}}async getAccountAssets(e){let t=T(this.chain,this.config.env,this.config).createNetworkProvider(),r=t.getAccount($.Address.newFromBech32(e)),n=t.getFungibleTokensOfAccount($.Address.newFromBech32(e)),[i,o]=await Promise.all([r,n]),c=i.balance>0?[{...this.chain.nativeToken,amount:i.balance}]:[];return c.push(...o.map(l=>({chain:this.chain.name,identifier:l.token.identifier,name:l.raw.name,symbol:l.raw.ticker,amount:l.amount,decimals:l.raw.decimals,logoUrl:l.raw.assets?.pngUrl||"",price:l.raw.price?Number(l.raw.price):void 0,supply:l.raw.supply?BigInt(l.raw.supply):void 0}))),c}async getAsset(e){let t=ne.WarpCacheKey.Asset(this.config.env,this.chain.name,e),r=this.cache.get(t);if(r)return r;let n=Se(this.chain.name,this.config.env,e);if(n)return{chain:this.chain.name,identifier:e,name:n.name,symbol:n.symbol,amount:0n,decimals:n.decimals,logoUrl:n.logoUrl};let i=new $.TokenComputer,o=Q(e)?0n:i.extractNonceFromExtendedIdentifier(e),c=new $.Token({identifier:e,nonce:BigInt(o||0)}),l=i.isFungible(c),f=T(this.chain,this.config.env,this.config).createNetworkProvider(),g=pe(e),d=await f.doGetGeneric(`tokens/${g}`),C={chain:this.chain.name,identifier:c.identifier,name:d.name,symbol:d.ticker,amount:0n,decimals:d.decimals,logoUrl:d.assets?.pngUrl||null,price:d.price?Number(d.price):void 0,supply:d.supply?BigInt(d.supply):void 0};return this.cache.set(t,C,ne.CacheTtl.OneHour),C}async getAction(e,t=!1){let r=T(this.chain,this.config.env,this.config),n=t?await r.awaitCompletedTransaction(e):await r.getTransaction(e);return{chain:this.chain.name,id:n.hash,receiver:n.receiver.toBech32(),sender:n.sender.toBech32(),value:n.value,function:n.function,status:this.toActionStatus(n),createdAt:this.toActionCreatedAt(n),error:n?.smartContractResults.map(i=>i.raw.returnMessage)[0]||null,tx:n}}async getAccountActions(e,t){let r=T(this.chain,this.config.env,this.config).createNetworkProvider(),n=`accounts/${e}/transactions`,i=new URLSearchParams,o=t?.size||25,c=t?.page||0;if(c>0){let f=c*o;i.append("from",f.toString())}return o!==25&&i.append("size",o.toString()),i.toString()&&(n+=`?${i.toString()}`),(await r.doGetGeneric(n)).map(f=>({chain:this.chain.name,id:f.txHash,receiver:f.receiver,sender:f.sender,value:f.value,function:f.function,status:this.toActionStatus(f),createdAt:this.toActionCreatedAt(f)}))}toActionStatus(e){return e.status?.isSuccessful?.()?"success":e.status?.isFailed?.()?"failed":"pending"}toActionCreatedAt(e){return new Date(e.timestamp||e.timestamp*1e3).toISOString()}};var x=require("@multiversx/sdk-core"),V=require("@joai/warps");var ae=require("@multiversx/sdk-core"),w=require("@joai/warps");var a=require("@multiversx/sdk-core"),Ye=require("@joai/warps");var gt=s=>s?typeof s=="string"?s:s.address:null,je=(s,e)=>gt(s.user?.wallets?.[e]||null);var h={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:s=>je(s.config,s.adapter.chainInfo.name)},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:s=>{if(!s.adapter.wallet)return null;try{return s.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:s=>s.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:s=>s.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},u={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"};var ft={Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}},v={Null:"null",Optional:"optional",List:"list",Token:"token",CodeMeta:"codemeta"},Je=(r=>(r.MultiversxExplorer="multiversx_explorer",r.MultiversxExplorerDevnet="multiversx_explorer_devnet",r.MultiversxExplorerTestnet="multiversx_explorer_testnet",r))(Je||{}),Xe=(r=>(r.VibechainExplorer="vibechain_explorer",r.VibechainExplorerDevnet="vibechain_explorer_devnet",r.VibechainExplorerTestnet="vibechain_explorer_testnet",r))(Xe||{}),Be={multiversx:{mainnet:["multiversx_explorer"],testnet:["multiversx_explorer_testnet"],devnet:["multiversx_explorer_devnet"]},vibechain:{mainnet:["vibechain_explorer"],testnet:["vibechain_explorer_testnet"],devnet:["vibechain_explorer_devnet"]}},G={multiversx_explorer:"https://explorer.multiversx.com",multiversx_explorer_devnet:"https://devnet-explorer.multiversx.com",multiversx_explorer_testnet:"https://testnet-explorer.multiversx.com",vibechain_explorer:"https://vibeox-explorer.multiversx.com",vibechain_explorer_devnet:"https://vibeox-explorer.multiversx.com",vibechain_explorer_testnet:"https://vibeox-explorer.multiversx.com"};var yt=new RegExp(`${h.ArgParamsSeparator}(.*)`),L=class{constructor(e){this.coreSerializer=new Ye.WarpSerializer(e)}typedToString(e){let t=e.getType();if(t.hasExactClass(a.OptionType.ClassName)||e.hasClassOrSuperclass(a.OptionValue.ClassName)){if(!e.isSet())return u.Option+h.ArgParamsSeparator+"null";let r=this.typedToString(e.getTypedValue());return u.Option+h.ArgParamsSeparator+r}if(t.hasExactClass(a.VariadicType.ClassName)||e.hasClassOrSuperclass(a.VariadicValue.ClassName)){let r=e.getItems();if(r.length===0){let g=this.typeToString(t.getFirstTypeParameter());return u.Vector+h.ArgParamsSeparator+g+h.ArgParamsSeparator}let n=r.map(g=>this.typedToString(g));if(n.every(g=>g.startsWith(u.Tuple)))return u.Vector+h.ArgParamsSeparator+n.join(",");let i=n[0],o=i.indexOf(h.ArgParamsSeparator),c=i.substring(0,o),l=n.map(g=>{let d=g.indexOf(h.ArgParamsSeparator);return g.substring(d+1)}),f=c.startsWith(u.Struct)?h.ArgStructSeparator:h.ArgListSeparator;return u.Vector+h.ArgParamsSeparator+c+h.ArgParamsSeparator+l.join(f)}if(t.hasExactClass(a.OptionalType.ClassName)||e.hasClassOrSuperclass(a.OptionalValue.ClassName)){if(!e.isSet())return v.Optional+h.ArgParamsSeparator+"null";let r=this.typedToString(e.getTypedValue());return v.Optional+h.ArgParamsSeparator+r}if(t.hasExactClass(a.ListType.ClassName)||e.hasClassOrSuperclass(a.List.ClassName)){let n=e.getItems().map(l=>this.typedToString(l));if(n.every(l=>l.startsWith(u.Tuple)))return v.List+h.ArgParamsSeparator+n.join(",");let o=n.map(l=>l.split(h.ArgParamsSeparator)[0])[0],c=n.map(l=>l.split(h.ArgParamsSeparator)[1]);return v.List+h.ArgParamsSeparator+o+h.ArgParamsSeparator+c.join(h.ArgListSeparator)}if(t.hasExactClass(a.CompositeType.ClassName)||e.hasClassOrSuperclass(a.CompositeValue.ClassName)){let n=e.getItems().map(i=>{let o=this.typedToString(i),c=o.indexOf(h.ArgParamsSeparator),l=o.substring(0,c),f=o.substring(c+1);return`${l},${f}`});return`${u.Tuple}(${n.join(",")})`}if(t.hasExactClass(a.BigUIntType.ClassName)||e.hasClassOrSuperclass(a.BigUIntValue.ClassName)||t.getName()==="BigUint")return u.Biguint+h.ArgParamsSeparator+BigInt(e.valueOf().toFixed());if(t.hasExactClass(a.U8Type.ClassName)||e.hasClassOrSuperclass(a.U8Value.ClassName))return u.Uint8+h.ArgParamsSeparator+e.valueOf().toNumber();if(t.hasExactClass(a.U16Type.ClassName)||e.hasClassOrSuperclass(a.U16Value.ClassName))return u.Uint16+h.ArgParamsSeparator+e.valueOf().toNumber();if(t.hasExactClass(a.U32Type.ClassName)||e.hasClassOrSuperclass(a.U32Value.ClassName))return u.Uint32+h.ArgParamsSeparator+e.valueOf().toNumber();if(t.hasExactClass(a.U64Type.ClassName)||e.hasClassOrSuperclass(a.U64Value.ClassName))return u.Uint64+h.ArgParamsSeparator+BigInt(e.valueOf().toFixed());if(t.hasExactClass(a.StringType.ClassName)||e.hasClassOrSuperclass(a.StringValue.ClassName))return u.String+h.ArgParamsSeparator+e.valueOf();if(t.hasExactClass(a.BooleanType.ClassName)||e.hasClassOrSuperclass(a.BooleanValue.ClassName))return u.Bool+h.ArgParamsSeparator+e.valueOf();if(t.hasExactClass(a.AddressType.ClassName)||e.hasClassOrSuperclass(a.AddressValue.ClassName))return u.Address+h.ArgParamsSeparator+e.valueOf().toBech32();if(t.hasExactClass(a.BytesType.ClassName)||e.hasClassOrSuperclass(a.BytesValue.ClassName))return u.Hex+h.ArgParamsSeparator+e.valueOf().toString("hex");if(t.getName()==="EsdtTokenPayment"){let r=e.getFieldValue("token_identifier").valueOf(),n=e.getFieldValue("token_nonce").valueOf(),i=e.getFieldValue("amount").valueOf(),c=new a.TokenComputer().computeExtendedIdentifier(new a.Token({identifier:r,nonce:BigInt(n)}));return u.Asset+h.ArgParamsSeparator+c+h.ArgCompositeSeparator+i}if(t.hasExactClass(a.StructType.ClassName)||e.hasClassOrSuperclass(a.Struct.ClassName)){let r=e,i=r.getType().getName(),o=r.getFields();if(o.length===0)return`${u.Struct}(${i})${h.ArgParamsSeparator}`;let c=o.map(l=>{let f=l.value.getType(),d=this.typedToString(l.value).split(h.ArgParamsSeparator),C=d.length>2?d.slice(2).join(h.ArgParamsSeparator):d[1]||"";return`(${l.name}${h.ArgParamsSeparator}${this.typeToString(f)})${C}`});return`${u.Struct}(${i})${h.ArgParamsSeparator}${c.join(h.ArgListSeparator)}`}if(t.hasExactClass(a.TokenIdentifierType.ClassName)||e.hasClassOrSuperclass(a.TokenIdentifierValue.ClassName))return v.Token+h.ArgParamsSeparator+e.valueOf();if(t.hasExactClass(a.CodeMetadataType.ClassName)||e.hasClassOrSuperclass(a.CodeMetadataValue.ClassName))return v.CodeMeta+h.ArgParamsSeparator+e.valueOf().toString();throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${e.getClassName()}`)}typedToNative(e){let t=this.typedToString(e);return this.coreSerializer.stringToNative(t)}nativeToTyped(e,t){if(e.startsWith(u.Tuple))return this.stringToTyped(e+":");let r=this.coreSerializer.nativeToString(e,t);return this.stringToTyped(r)}nativeToType(e){if(e.startsWith(u.Tuple)){let t=e.match(/\(([^)]+)\)/)?.[1];if(!t)throw new Error(`Invalid tuple type format: ${e}`);let r=t.split(","),n=[];for(let i=0;i<r.length;i+=2)n.push(r[i]);return new a.CompositeType(...n.map(i=>this.nativeToType(i)))}if(e.startsWith(u.Struct)){let t=e.match(/\(([^)]+)\)/);if(!t)throw new Error("Struct type must include a name in the format struct(Name)");let r=t[1];return new a.StructType(r,[])}if(e===u.String)return new a.StringType;if(e===u.Uint8)return new a.U8Type;if(e===u.Uint16)return new a.U16Type;if(e===u.Uint32)return new a.U32Type;if(e===u.Uint64)return new a.U64Type;if(e===u.Biguint)return new a.BigUIntType;if(e===u.Bool)return new a.BooleanType;if(e===u.Address)return new a.AddressType;if(e===u.Hex)return new a.BytesType;if(e===u.Asset)return new a.StructType("EsdtTokenPayment",[new a.FieldDefinition("token_identifier","",new a.TokenIdentifierType),new a.FieldDefinition("token_nonce","",new a.U64Type),new a.FieldDefinition("amount","",new a.BigUIntType)]);if(e===v.Token)return new a.TokenIdentifierType;if(e===v.CodeMeta)return new a.CodeMetadataType;throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${e}`)}stringToTyped(e){let[t,r]=e.split(/:(.*)/,2);if(t===u.Option){let n=this.stringToTyped(r);return n instanceof a.NothingValue?a.OptionValue.newMissingTyped(n.getType()):a.OptionValue.newProvided(n)}if(t===u.Vector){let n=r.indexOf(h.ArgParamsSeparator),i=r.substring(0,n),o=r.substring(n+1);if(i.startsWith(u.Tuple)){let d=o.split(",").map(C=>this.stringToTyped(C));return new a.VariadicValue(new a.VariadicType(this.nativeToType(i)),d)}if(o.includes("tuple(")){let g=this.splitTupleStrings(o),d=g.map(A=>this.stringToTyped(A)),P=g[0].match(/^(tuple\([^)]+\))/),y=P?P[1]:"tuple";return new a.VariadicValue(new a.VariadicType(this.nativeToType(y)),d)}let c=i.startsWith(u.Struct)?h.ArgStructSeparator:h.ArgListSeparator,f=o.split(c).map(g=>this.stringToTyped(`${i}:${g}`));return new a.VariadicValue(new a.VariadicType(this.nativeToType(i)),f)}if(t.startsWith(u.Tuple)){let n=t.match(/\(([^)]+)\)/)?.[1];if(!n)throw new Error(`Invalid tuple format: ${t}`);let i=n.split(","),o=[];for(let l=0;l<i.length;l+=2){let f=i[l],g=i[l+1];o.push(this.stringToTyped(`${f}:${g}`))}let c=o.map(l=>l.getType());return new a.CompositeValue(new a.CompositeType(...c),o)}if(t.startsWith(u.Struct)){let n=t.match(/\(([^)]+)\)/),i=n?n[1]:"CustomStruct";if(!r)return new a.Struct(new a.StructType(i,[]),[]);let o=r.split(h.ArgListSeparator),c=[],l=[];return o.forEach(f=>{let g=f.match(new RegExp(`^\\(([^${h.ArgParamsSeparator}]+)${h.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(g){let[,d,C,P]=g,y=this.stringToTyped(`${C}${h.ArgParamsSeparator}${P}`);c.push(new a.FieldDefinition(d,"",y.getType())),l.push(new a.Field(y,d))}}),new a.Struct(new a.StructType(i,c),l)}if(t===u.String)return r?a.StringValue.fromUTF8(r):new a.NothingValue;if(t===u.Uint8)return r?new a.U8Value(Number(r)):new a.NothingValue;if(t===u.Uint16)return r?new a.U16Value(Number(r)):new a.NothingValue;if(t===u.Uint32)return r?new a.U32Value(Number(r)):new a.NothingValue;if(t===u.Uint64)return r?new a.U64Value(BigInt(r)):new a.NothingValue;if(t===u.Biguint)return r?new a.BigUIntValue(BigInt(r)):new a.NothingValue;if(t===u.Bool)return r?new a.BooleanValue(typeof r=="boolean"?r:r==="true"):new a.NothingValue;if(t===u.Address)return r?new a.AddressValue(a.Address.newFromBech32(r)):new a.NothingValue;if(t===u.Hex)return r?a.BytesValue.fromHex(r):new a.NothingValue;if(t===u.Asset){let[n,i]=r.split(h.ArgCompositeSeparator),o=new a.TokenComputer,c=Q(n)?pe(n):o.extractIdentifierFromExtendedIdentifier(n),l=Q(n)?0n:o.extractNonceFromExtendedIdentifier(n);return new a.Struct(this.nativeToType("asset"),[new a.Field(new a.TokenIdentifierValue(c),"token_identifier"),new a.Field(new a.U64Value(BigInt(l)),"token_nonce"),new a.Field(new a.BigUIntValue(BigInt(i)),"amount")])}if(t===v.Null)return new a.NothingValue;if(t===v.Optional){let n=this.stringToTyped(r);return n instanceof a.NothingValue?a.OptionalValue.newMissing():new a.OptionalValue(n.getType(),n)}if(t===v.List){let[n,i]=r.split(yt,2),c=i.split(h.ArgListSeparator).map(l=>this.stringToTyped(n+h.ArgParamsSeparator+l));return new a.List(this.nativeToType(n),c)}if(t===v.Token)return r?new a.TokenIdentifierValue(r):new a.NothingValue;if(t===v.CodeMeta)return new a.CodeMetadataValue(a.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${t}`)}splitTupleStrings(e){let t=[],r="",n=0;for(let i=0;i<e.length;i++){let o=e[i];if(o==="(")n++;else if(o===")")n--;else if(o===","&&n===0){t.push(r.trim()),r="";continue}r+=o}return r.trim()&&t.push(r.trim()),t}typeToString(e){if(e.hasExactClass(a.OptionType.ClassName))return u.Option+h.ArgParamsSeparator+this.typeToString(e.getFirstTypeParameter());if(e.hasExactClass(a.VariadicType.ClassName))return u.Vector+h.ArgParamsSeparator+this.typeToString(e.getFirstTypeParameter());if(e.hasExactClass(a.StringType.ClassName))return u.String;if(e.hasExactClass(a.U8Type.ClassName))return u.Uint8;if(e.hasExactClass(a.U16Type.ClassName))return u.Uint16;if(e.hasExactClass(a.U32Type.ClassName))return u.Uint32;if(e.hasExactClass(a.U64Type.ClassName))return u.Uint64;if(e.hasExactClass(a.BigUIntType.ClassName))return u.Biguint;if(e.hasExactClass(a.BooleanType.ClassName))return u.Bool;if(e.hasExactClass(a.AddressType.ClassName))return u.Address;if(e.hasExactClass(a.BytesType.ClassName))return u.Hex;if(e.hasExactClass(a.TokenIdentifierType.ClassName))return v.Token;if(e.hasExactClass(a.OptionalType.ClassName))return v.Optional+h.ArgParamsSeparator+this.typeToString(e.getFirstTypeParameter());if(e.hasExactClass(a.ListType.ClassName))return v.List+h.ArgParamsSeparator+this.typeToString(e.getFirstTypeParameter());if(e.hasExactClass(a.CodeMetadataType.ClassName))return v.CodeMeta;if(e.hasExactClass(a.StructType.ClassName)&&e.getClassName()==="EsdtTokenPayment")return u.Asset;if(e.hasExactClass(a.StructType.ClassName))return`${u.Struct}(${e.getName()})`;throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${e.getClassName()}`)}};var X=class{constructor(e,t,r){this.config=e;this.chain=t;this.typeRegistry=r;this.abi=new D(e,t),this.serializer=new L({typeRegistry:this.typeRegistry}),this.cache=new w.WarpCache(e.env,e.cache)}async getActionExecution(e,t,r){let n=this.cache.get(w.WarpCacheKey.WarpExecutable(this.config.env,e.meta?.hash||"",t))??[],i=await this.extractContractOutput(e,t,r,n),o=(0,w.getNextInfo)(this.config,[],e,t,i.output),c=(0,w.applyOutputToMessages)(e,i.output,this.config),l=(0,w.extractResolvedInputValues)(n);return{status:r.status?.isSuccessful?.()?"success":"error",warp:e,action:t,user:(0,w.getWarpWalletAddressFromConfig)(this.config,this.chain.name),txHash:r.hash,tx:r,next:o,values:i.values,output:i.output,messages:c,destination:null,resolvedInputs:l}}async extractContractOutput(e,t,r,n){let i=(0,w.getWarpActionByIndex)(e,t),o=[],c=[],l={};if(!e.output||i.type!=="contract")return{values:{string:o,native:c,mapped:{}},output:l};if(!Object.values(e.output).some(y=>y.includes("out")||y.includes("event"))){for(let[y,A]of Object.entries(e.output))l[y]=A;return{values:{string:o,native:c,mapped:{}},output:await(0,w.evaluateOutputCommon)(e,l,t,n,this.serializer.coreSerializer,this.config)}}let g=await this.abi.getAbiForAction(i),d=new ae.TransactionEventsParser({abi:g}),P=new ae.SmartContractTransactionsOutcomeParser({abi:g}).parseExecute({transactionOnNetwork:r,function:i.func||void 0});for(let[y,A]of Object.entries(e.output)){if(A.startsWith(w.WarpConstants.Transform.Prefix))continue;if(A.startsWith("input.")){l[y]=A;continue}let B=(0,w.parseOutputOutIndex)(A);if(B!==null&&B!==t){l[y]=null;continue}let[k,z,q]=A.split(".");if(k==="event"){if(!z||isNaN(Number(q)))continue;let _=Number(q),W=(0,ae.findEventsByFirstTopic)(r,z),at=d.parseEvents({events:W})[0],le=Object.values(at)[_]||null;o.push(String(le)),c.push(le),l[y]=le&&le.valueOf()}else if(k==="out"||k.startsWith("out[")){if(!z)continue;let _=Number(z),W=P.values[_-1]||null;q&&(W=W[q]||null),W&&typeof W=="object"&&(W="toFixed"in W?W.toFixed():W.valueOf()),o.push(String(W)),c.push(W),l[y]=W&&W.valueOf()}else l[y]=A}return{values:{string:o,native:c,mapped:{}},output:await(0,w.evaluateOutputCommon)(e,l,t,n,this.serializer.coreSerializer,this.config)}}async extractQueryOutput(e,t,r,n){let i=t.map(g=>this.serializer.typedToString(g)),o=t.map(g=>this.serializer.typedToNative(g)[1]),c={string:i,native:o,mapped:{}},l={};if(!e.output)return{values:c,output:l};let f=g=>{let d=g.split(".").slice(1).map(P=>parseInt(P)-1);if(d.length===0)return;let C=o[d[0]];for(let P=1;P<d.length;P++){if(C==null)return;C=C[d[P]]}return C};for(let[g,d]of Object.entries(e.output)){if(d.startsWith(w.WarpConstants.Transform.Prefix))continue;let C=(0,w.parseOutputOutIndex)(d);if(C!==null&&C!==r){l[g]=null;continue}d.startsWith("out.")||d==="out"||d.startsWith("out[")?l[g]=f(d)||null:l[g]=d}return l=await(0,w.evaluateOutputCommon)(e,l,r,n,this.serializer.coreSerializer,this.config),{values:c,output:l}}async resolveWarpOutputRecursively(e){let t=e.warp,r=e.entryActionIndex,n=e.executor,i=e.inputs,o=e.meta,c=new Map,l=new Set,f=this;async function g(y,A=[]){if(c.has(y))return c.get(y);if(l.has(y))throw new Error(`Circular dependency detected at action ${y}`);l.add(y);let B=t.actions[y-1];if(!B)throw new Error(`Action ${y} not found`);let k;if(B.type==="query")k=await n.executeQuery(t,y,A);else if(B.type==="collect")k=await n.executeCollect(t,y,A,o);else throw new Error(`Unsupported or interactive action type: ${B.type}`);if(c.set(y,k),t.output)for(let z of Object.values(t.output)){let _=String(z).match(/^out\[(\d+)\]/);if(_){let W=parseInt(_[1],10);W!==y&&!c.has(W)&&await g(W)}}return l.delete(y),k}await g(r,i);let d={};for(let y of c.values())for(let[A,B]of Object.entries(y.output))B!==null?d[A]=B:A in d||(d[A]=null);let C=await(0,w.evaluateOutputCommon)(t,d,r,i,this.serializer.coreSerializer,this.config);return{...c.get(r),action:r,output:C}}};var Wt="EGLD-000000",ge=class{constructor(e,t,r){this.config=e;this.chain=t;this.typeRegistry=r;this.serializer=new L({typeRegistry:this.typeRegistry}),this.abi=new D(this.config,this.chain),this.output=new X(this.config,this.chain,this.typeRegistry)}async createTransaction(e){let t=(0,V.getWarpActionByIndex)(e.warp,e.action),r=null;if(t.type==="transfer")r=await this.createTransferTransaction(e);else if(t.type==="contract")r=await this.createContractCallTransaction(e);else{if(t.type==="query")throw new Error("WarpMultiversxExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead");if(t.type==="collect")throw new Error("WarpMultiversxExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead")}if(!r)throw new Error(`WarpMultiversxExecutor: Invalid action type (${t.type})`);return r}async createTransferTransaction(e){if(!e.destination)throw new Error("WarpMultiversxExecutor: createTransfer - destination not set");let t=(0,V.getWarpWalletAddressFromConfig)(this.config,e.chain.name);if(!t)throw new Error("WarpMultiversxExecutor: createTransfer - user address not set");let r=x.Address.newFromBech32(t),n=new x.TransactionsFactoryConfig({chainID:e.chain.chainId}),i=e.data?Buffer.from(this.serializer.stringToTyped(e.data).valueOf()):null,o=e.transfers.length===1&&e.transfers[0].identifier===this.chain.nativeToken?.identifier,l=(o?e.transfers[0].amount:0n)+e.value;return await new x.TransferTransactionsFactory({config:n}).createTransactionForTransfer(r,{receiver:x.Address.newFromBech32(e.destination),nativeAmount:l,tokenTransfers:o?[]:this.toTokenTransfers(e.transfers),data:i?new Uint8Array(i):void 0})}async createContractCallTransaction(e){if(!e.destination)throw new Error("WarpMultiversxExecutor: createContractCall - destination not set");let t=(0,V.getWarpWalletAddressFromConfig)(this.config,e.chain.name);if(!t)throw new Error("WarpMultiversxExecutor: createContractCall - user address not set");let r=(0,V.getWarpActionByIndex)(e.warp,e.action),n=x.Address.newFromBech32(t),i=e.args.map(c=>this.serializer.stringToTyped(c)),o=new x.TransactionsFactoryConfig({chainID:e.chain.chainId});return new x.SmartContractTransactionsFactory({config:o}).createTransactionForExecute(n,{contract:x.Address.newFromBech32(e.destination),function:"func"in r&&r.func||"",gasLimit:"gasLimit"in r?BigInt(r.gasLimit||0):0n,arguments:i,tokenTransfers:this.toTokenTransfers(e.transfers),nativeTransferAmount:e.value})}async executeQuery(e){if(!e.destination)throw new Error("WarpMultiversxExecutor: executeQuery - destination not set");let t=(0,V.getWarpActionByIndex)(e.warp,e.action);if(t.type!=="query")throw new Error(`WarpMultiversxExecutor: Invalid action type for executeQuery: ${t.type}`);let r=await this.abi.getAbiForAction(t),n=e.args.map(W=>this.serializer.stringToTyped(W)),i=T(e.chain,this.config.env,this.config),o=x.Address.newFromBech32(e.destination),c=i.createSmartContractController(r),l=c.createQuery({contract:o,function:t.func||"",arguments:n}),f=await c.runQuery(l),g=f.returnCode==="ok",d=new x.ArgSerializer,C=r.getEndpoint(f.function||t.func||""),P=(f.returnDataParts||[]).map(W=>Buffer.from(W)),y=d.buffersToValues(P,C.output),{values:A,output:B}=await this.output.extractQueryOutput(e.warp,y,e.action,e.resolvedInputs),k=(0,V.getNextInfo)(this.config,[],e.warp,e.action,B),q=e.resolvedInputs.find(W=>W.input.position==="receiver"||W.input.position==="destination")?.value||e.destination,_=(0,V.extractResolvedInputValues)(e.resolvedInputs);return{status:g?"success":"error",warp:e.warp,action:e.action,user:(0,V.getWarpWalletAddressFromConfig)(this.config,e.chain.name),txHash:null,tx:null,next:k,values:A,output:{...B,_DATA:y},messages:(0,V.applyOutputToMessages)(e.warp,B,this.config),destination:q,resolvedInputs:_}}toTokenTransfers(e){return e.map(t=>t.identifier===this.chain.nativeToken.identifier?{...t,identifier:Wt}:t).map(t=>{let n=new x.TokenComputer().extractNonceFromExtendedIdentifier(t.identifier);return new x.TokenTransfer({token:new x.Token({identifier:t.identifier,nonce:BigInt(n||0)}),amount:t.amount})})}};var fe=class{constructor(e,t){this.chain=e;this.config=t}getExplorers(){let e=Be[this.chain];if(!e)return["multiversx_explorer"];let t=e[this.config.env];return t||["multiversx_explorer"]}getPrimaryExplorer(){return this.getExplorers()[0]}getExplorerUrlByName(e){let t=this.config.preferences?.explorers?.[this.chain];if(t&&!e){let i=G[t];if(i)return i}if(e){let i=G[e];if(i)return i}let r=this.getPrimaryExplorer();return G[r]||G[r]}getAccountUrl(e,t){return`${this.getExplorerUrlByName(t)}/accounts/${e}`}getTransactionUrl(e,t){return`${this.getExplorerUrlByName(t)}/transactions/${e}`}getBlockUrl(e,t){return`${this.getExplorerUrlByName(t)}/blocks/${e}`}getAssetUrl(e,t){return`${this.getExplorerUrlByName(t)}/tokens/${e}`}getContractUrl(e,t){return`${this.getExplorerUrlByName(t)}/accounts/${e}`}getAllExplorers(){return this.getExplorers()}getExplorerByName(e){return this.getExplorers().find(r=>r.toLowerCase()===e.toLowerCase())}getAccountUrls(e){let t=this.getAllExplorers(),r={};return t.forEach(n=>{let i=G[n];i&&(r[n]=`${i}/accounts/${e}`)}),r}getTransactionUrls(e){let t=this.getAllExplorers(),r={};return t.forEach(n=>{let i=G[n];i&&(r[n]=`${i}/transactions/${e}`)}),r}};var m=require("@multiversx/sdk-core"),U=require("@joai/warps");var Ne={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"},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],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}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpVerified",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"ownershipTransferred",inputs:[{name:"warp",type:"bytes",indexed:!0},{name:"old_owner",type:"Address",indexed:!0},{name:"new_owner",type:"Address",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{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 S=s=>{if(s==="devnet")return"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36";if(s==="testnet")throw new Error("Multiversx testnet is not supported");return"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"};var ye=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}),Ve=s=>({unitPrice:BigInt(s.unit_price.toString()),admins:s.admins.map(e=>e.toBech32())});var We=class{constructor(e,t){this.config=e;this.chain=t;this.cache=new U.WarpCache(e.env,e.cache),this.registryConfig={unitPrice:BigInt(0),admins:[]},this.userWallet=(0,U.getWarpWalletAddressFromConfig)(this.config,this.chain.name)}async init(){await this.loadRegistryConfigs()}getRegistryConfig(){return this.registryConfig}async createWarpRegisterTransaction(e,t,r){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let n=m.Address.newFromBech32(this.userWallet),i=()=>this.isCurrentUserAdmin()?BigInt(0):t&&r?this.registryConfig.unitPrice*BigInt(3):t?this.registryConfig.unitPrice*BigInt(2):this.registryConfig.unitPrice,o=()=>t&&r?[m.BytesValue.fromHex(e),m.BytesValue.fromUTF8(t),m.BytesValue.fromHex(r)]:t?[m.BytesValue.fromHex(e),m.BytesValue.fromUTF8(t)]:[m.BytesValue.fromHex(e)];return await this.getFactory().createTransactionForExecute(n,{contract:m.Address.newFromBech32(S(this.config.env)),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:i(),arguments:o()})}async createWarpUnregisterTransaction(e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=m.Address.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(t,{contract:m.Address.newFromBech32(S(this.config.env)),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[m.BytesValue.fromHex(e)]})}async createWarpUpgradeTransaction(e,t,r){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let n=m.Address.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(n,{contract:m.Address.newFromBech32(S(this.config.env)),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:r?[m.BytesValue.fromUTF8(e),m.BytesValue.fromHex(t),m.BytesValue.fromHex(r)]:[m.BytesValue.fromUTF8(e),m.BytesValue.fromHex(t)]})}async createWarpAliasSetTransaction(e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(r,{contract:m.Address.newFromBech32(S(this.config.env)),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[m.BytesValue.fromHex(e),m.BytesValue.fromUTF8(t)]})}async createWarpVerifyTransaction(e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=m.Address.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(t,{contract:m.Address.newFromBech32(S(this.config.env)),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[m.BytesValue.fromHex(e)]})}async createWarpTransferOwnershipTransaction(e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(r,{contract:m.Address.newFromBech32(S(this.config.env)),function:"transferOwnership",gasLimit:BigInt(1e7),arguments:[m.BytesValue.fromHex(e),new m.AddressValue(new m.Address(t))]})}async createBrandRegisterTransaction(e){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=m.Address.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(t,{contract:m.Address.newFromBech32(S(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[m.BytesValue.fromHex(e)]})}async createWarpBrandingTransaction(e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(r,{contract:m.Address.newFromBech32(S(this.config.env)),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[m.BytesValue.fromHex(e),m.BytesValue.fromHex(t)]})}async getInfoByAlias(e,t){try{let r=U.WarpCacheKey.RegistryInfo(this.config.env,e),n=t?this.cache.get(r):null;if(n)return U.WarpLogger.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${e}`),n;let i=m.Address.newFromBech32(S(this.config.env)),o=this.getController(),c=o.createQuery({contract:i,function:"getInfoByAlias",arguments:[m.BytesValue.fromUTF8(e)]}),l=await o.runQuery(c),[f]=o.parseQueryResponse(l),g=f?ye(f):null,d=g?.brand?await this.fetchBrand(g.brand):null;return t&&t.ttl&&this.cache.set(r,{registryInfo:g,brand:d},t.ttl),{registryInfo:g,brand:d}}catch{return{registryInfo:null,brand:null}}}async getInfoByHash(e,t){try{let r=U.WarpCacheKey.RegistryInfo(this.config.env,e);if(t){let d=this.cache.get(r);if(d)return U.WarpLogger.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${e}`),d}let n=m.Address.newFromBech32(S(this.config.env)),i=this.getController(),o=i.createQuery({contract:n,function:"getInfoByHash",arguments:[m.BytesValue.fromHex(e)]}),c=await i.runQuery(o),[l]=i.parseQueryResponse(c),f=l?ye(l):null,g=f?.brand?await this.fetchBrand(f.brand):null;return t&&t.ttl&&this.cache.set(r,{registryInfo:f,brand:g},t.ttl),{registryInfo:f,brand:g}}catch{return{registryInfo:null,brand:null}}}async getUserWarpRegistryInfos(e){try{let t=e||this.userWallet;if(!t)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(S(this.config.env)),n=this.getController(),i=n.createQuery({contract:r,function:"getUserWarps",arguments:[new m.AddressValue(new m.Address(t))]}),o=await n.runQuery(i),[c]=n.parseQueryResponse(o);return c.map(ye)}catch{return[]}}async getUserBrands(e){try{let t=e||this.userWallet;if(!t)throw new Error("WarpRegistry: user address not set");let r=m.Address.newFromBech32(S(this.config.env)),n=this.getController(),i=n.createQuery({contract:r,function:"getUserBrands",arguments:[new m.AddressValue(new m.Address(t))]}),o=await n.runQuery(i),[c]=n.parseQueryResponse(o),l=c.map(d=>d.toString("hex")),f={ttl:365*24*60*60};return(await Promise.all(l.map(d=>this.fetchBrand(d,f)))).filter(d=>d!==null)}catch{return[]}}async fetchBrand(e,t){let r=U.WarpCacheKey.Brand(this.config.env,e),n=t?this.cache.get(r):null;if(n)return U.WarpLogger.info(`WarpRegistry (fetchBrand): Brand found in cache: ${e}`),n;let o=T(this.chain,this.config.env,this.config).createNetworkProvider();try{let c=await o.getTransaction(e),l=JSON.parse(c.data.toString());return l.meta={query:null,chain:this.chain.name,identifier:(0,U.createWarpIdentifier)(this.chain.name,"hash",e),hash:c.hash,creator:c.sender.toBech32(),createdAt:new Date(c.timestamp*1e3).toISOString()},t&&t.ttl&&this.cache.set(r,l,t.ttl),l}catch{return null}}async loadRegistryConfigs(){let e=m.Address.newFromBech32(S(this.config.env)),t=this.getController(),[r]=await t.query({contract:e,function:"getConfig",arguments:[]}),n=r?Ve(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let e=new m.TransactionsFactoryConfig({chainID:this.chain.chainId}),t=m.AbiRegistry.create(Ne);return new m.SmartContractTransactionsFactory({config:e,abi:t})}getController(){let e=T(this.chain,this.config.env,this.config),t=m.AbiRegistry.create(Ne);return e.createSmartContractController(t)}isCurrentUserAdmin(){return!!this.userWallet&&this.registryConfig.admins.includes(this.userWallet)}};var te=require("@joai/warps"),tt=require("@multiversx/sdk-core");var O=require("@multiversx/sdk-core"),Ze=ut(require("@scure/bip39"),1),et=require("@scure/bip39/wordlists/english.js"),b=require("@joai/warps"),Y=class Y{constructor(e,t){this.config=e;this.chain=t;this.account=null}async getAddress(){let e=(0,b.getWarpWalletAddressFromConfig)(this.config,this.chain.name);if(e)return e;try{return this.getAccount().address.toBech32()}catch{return null}}async getPublicKey(){try{return this.getAccount().publicKey.hex()}catch{return null}}async signTransaction(e){let r=await this.getAccount().signTransaction(e);return e.signature=r,e}async signMessage(e){let t=this.getAccount(),r=new TextEncoder().encode(e),n=await t.signMessage(new O.Message({data:r}));return Buffer.from(n).toString("hex")}getAccountInstance(){return this.getAccount()}async importFromMnemonic(e){let t=(0,b.normalizeAndValidateMnemonic)(e),n=O.Mnemonic.fromString(t).deriveKey(0),i=n.hex(),c=n.generatePublicKey().toAddress(this.chain.addressHrp).toBech32(),l={provider:Y.PROVIDER_NAME,address:c,privateKey:i,mnemonic:t};return(0,b.setWarpWalletInConfig)(this.config,this.chain.name,l),l}async importFromPrivateKey(e){let t=O.UserSecretKey.fromString(e),r=t.hex(),i=t.generatePublicKey().toAddress(this.chain.addressHrp).toBech32(),o={provider:Y.PROVIDER_NAME,address:i,privateKey:r,mnemonic:null};return(0,b.setWarpWalletInConfig)(this.config,this.chain.name,o),o}async export(){let e=this.getAccount(),t=(0,b.getWarpWalletMnemonicFromConfig)(this.config,this.chain.name),r=(0,b.getWarpWalletPrivateKeyFromConfig)(this.config,this.chain.name);return{provider:Y.PROVIDER_NAME,address:e.address.toBech32(),privateKey:r||null,mnemonic:t||null}}async generate(){let e=Ze.generateMnemonic(et.wordlist,256),t=(0,b.normalizeMnemonic)(e);(0,b.validateMnemonicLength)(t);let o=O.Mnemonic.fromString(t).deriveKey(0).generatePublicKey().toAddress(this.chain.addressHrp).toBech32();return{provider:Y.PROVIDER_NAME,address:o,privateKey:null,mnemonic:t}}getAccount(){if(this.account)return this.account;let e=(0,b.getWarpWalletMnemonicFromConfig)(this.config,this.chain.name);if(!e)throw new Error("No mnemonic provided");let r=O.Mnemonic.fromString(e).deriveKey(0);return this.account=new O.Account(r),this.account}};Y.PROVIDER_NAME="mnemonic";var ie=Y;var F=require("@multiversx/sdk-core"),R=require("@joai/warps"),Z=class Z{constructor(e,t){this.config=e;this.chain=t;this.account=null}async getAddress(){let e=(0,R.getWarpWalletAddressFromConfig)(this.config,this.chain.name);if(e)return e;try{return this.getAccount().address.toBech32()}catch{return null}}async getPublicKey(){try{return this.getAccount().publicKey.hex()}catch{return null}}async signTransaction(e){let r=await this.getAccount().signTransaction(e);return e.signature=r,e}async signMessage(e){let t=this.getAccount(),r=new TextEncoder().encode(e),n=await t.signMessage(new F.Message({data:r}));return Buffer.from(n).toString("hex")}getAccountInstance(){return this.getAccount()}async importFromMnemonic(e){let r=F.Mnemonic.fromString(e).deriveKey(0),n=r.hex(),o=r.generatePublicKey().toAddress(this.chain.addressHrp).toBech32(),c={provider:Z.PROVIDER_NAME,address:o,privateKey:n,mnemonic:e};return(0,R.setWarpWalletInConfig)(this.config,this.chain.name,c),c}async importFromPrivateKey(e){let r=e.startsWith("-----")?F.UserSecretKey.fromPem(e):F.UserSecretKey.fromString(e),n=r.hex(),o=r.generatePublicKey().toAddress(this.chain.addressHrp).toBech32(),c={provider:Z.PROVIDER_NAME,address:o,privateKey:n,mnemonic:null};return(0,R.setWarpWalletInConfig)(this.config,this.chain.name,c),c}async export(){let e=this.getAccount(),t=(0,R.getWarpWalletPrivateKeyFromConfig)(this.config,this.chain.name),r=(0,R.getWarpWalletMnemonicFromConfig)(this.config,this.chain.name);return{provider:Z.PROVIDER_NAME,address:e.address.toBech32(),privateKey:t||null,mnemonic:r||null}}async generate(){let e=F.UserSecretKey.generate(),t=e.hex(),n=e.generatePublicKey().toAddress(this.chain.addressHrp).toBech32();return{provider:Z.PROVIDER_NAME,address:n,privateKey:t,mnemonic:null}}getAccount(){if(this.account)return this.account;let e=(0,R.getWarpWalletPrivateKeyFromConfig)(this.config,this.chain.name);if(!e)throw new Error("No private key provided");let r=e.startsWith("-----")?F.UserSecretKey.fromPem(e):F.UserSecretKey.fromString(e);return this.account=new F.Account(r),this.account}};Z.PROVIDER_NAME="privateKey";var se=Z;var oe=require("@joai/warps"),ee=class{constructor(e,t){this.config=e;this.chain=t}async getAddress(){return(0,oe.getWarpWalletAddressFromConfig)(this.config,this.chain.name)}async getPublicKey(){return null}async signTransaction(e){let t=await this.getAddress();throw new Error(`Wallet can not be used for signing: ${t}`)}async signMessage(e){let t=await this.getAddress();throw new Error(`Wallet can not be used for signing: ${t}`)}async importFromMnemonic(e){let t=(0,oe.getWarpWalletAddressFromConfig)(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${t}`)}async importFromPrivateKey(e){let t=(0,oe.getWarpWalletAddressFromConfig)(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${t}`)}async export(){let e=(0,oe.getWarpWalletAddressFromConfig)(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${e}`)}async generate(){let e=(0,oe.getWarpWalletAddressFromConfig)(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${e}`)}};var ve=class{constructor(e,t){this.config=e;this.chain=t;this.cachedAddress=null;this.cachedPublicKey=null;this.entry=T(t,e.env,e),this.cache=new te.WarpCache(e.env,e.cache),this.walletProvider=this.createProvider(),this.initializeCache()}async signTransaction(e){let t=e;if(!t||typeof t!="object")throw new Error("Invalid transaction object");if(!this.walletProvider)throw new Error("No wallet provider available");if(this.walletProvider instanceof ee)throw new Error(`Wallet (${this.chain.name}) is read-only`);if(this.walletProvider instanceof se||this.walletProvider instanceof ie){let n=this.walletProvider.getAccountInstance();if(t.nonce===0n){let i=await this.entry.recallAccountNonce(n.address),o=this.cache.get(`nonce:${n.address.toBech32()}`)||0,c=BigInt(Math.max(o,Number(i)));t.nonce=c}}else if(t.nonce===0n&&this.cachedAddress){let n=tt.Address.newFromBech32(this.cachedAddress),i=await this.entry.recallAccountNonce(n),o=this.cache.get(`nonce:${this.cachedAddress}`)||0,c=BigInt(Math.max(o,Number(i)));t.nonce=c}let r=await this.walletProvider.signTransaction(t);if(this.walletProvider instanceof se||this.walletProvider instanceof ie){let n=this.walletProvider.getAccountInstance(),i=Number(n.nonce)+1;this.cache.set(`nonce:${n.address.toBech32()}`,i,te.CacheTtl.OneMinute)}else if(this.cachedAddress){let n=t.nonce?Number(t.nonce):0;this.cache.set(`nonce:${this.cachedAddress}`,n+1,te.CacheTtl.OneMinute)}return r}async signTransactions(e){let t=[];for(let r of e)t.push(await this.signTransaction(r));return t}async signMessage(e){if(!this.walletProvider)throw new Error("No wallet provider available");if(this.walletProvider instanceof ee)throw new Error(`Wallet (${this.chain.name}) is read-only`);return await this.walletProvider.signMessage(e)}async sendTransactions(e){return Promise.all(e.map(async t=>this.sendTransaction(t)))}async sendTransaction(e){let t=e;if(!t||typeof t!="object")throw new Error("Invalid transaction object");if(!t.signature||t.signature.length===0)throw new Error("Transaction must be signed before sending");return await this.entry.sendTransaction(t)}async importFromMnemonic(e){return await this.createProviderForOperation("mnemonic").importFromMnemonic(e)}async importFromPrivateKey(e){return await this.createProviderForOperation("privateKey").importFromPrivateKey(e)}async export(e){return await this.createProviderForOperation(e).export()}async generate(e){return await this.createProviderForOperation(e).generate()}getAddress(){return this.cachedAddress}getPublicKey(){return this.cachedPublicKey}createProvider(){let e=this.config.user?.wallets?.[this.chain.name];return e?typeof e=="string"?new ee(this.config,this.chain):e.provider?this.createProviderForOperation(e.provider):new ee(this.config,this.chain):null}initializeCache(){(0,te.initializeWalletCache)(this.walletProvider).then(e=>{this.cachedAddress=e.address,this.cachedPublicKey=e.publicKey})}createProviderForOperation(e){let r=this.config.walletProviders?.[this.chain.name]?.[e];if(r){let n=r(this.config,this.chain);if(!n)throw new Error(`Custom wallet provider factory returned null for ${e}`);return n}if(e==="privateKey")return new se(this.config,this.chain);if(e==="mnemonic")return new ie(this.config,this.chain);throw new Error(`Unsupported wallet provider for ${this.chain.name}: ${e}`)}};var we=(s,e)=>(t,r)=>{let n=e[t.env],i=new rt.WarpTypeRegistry;return i.registerType("token",{stringToNative:o=>o,nativeToString:o=>`token:${o}`}),i.registerType("codemeta",{stringToNative:o=>o,nativeToString:o=>`codemeta:${o}`}),i.registerTypeAlias("list","vector"),{chainInfo:n,builder:()=>new de(t,n),executor:new ge(t,n,i),output:new X(t,n,i),serializer:new L({typeRegistry:i}),registry:new We(t,n),explorer:new fe(s,t),abiBuilder:()=>new D(t,n),brandBuilder:()=>new me(t,n),dataLoader:new he(t,n),wallet:new ve(t,n)}};var ce=require("@joai/warps");var xe={chain:ce.WarpChainName.Multiversx,identifier:"EGLD",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/tokens/logos/egld.svg"},Ue=we(ce.WarpChainName.Multiversx,{mainnet:{name:ce.WarpChainName.Multiversx,displayName:"MultiversX",chainId:"1",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://api.multiversx.com",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/multiversx.svg",nativeToken:xe},testnet:{name:ce.WarpChainName.Multiversx,displayName:"MultiversX Testnet",chainId:"T",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://testnet-api.multiversx.com",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/multiversx.svg",nativeToken:xe},devnet:{name:ce.WarpChainName.Multiversx,displayName:"MultiversX Devnet",chainId:"D",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://devnet-api.multiversx.com",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/multiversx.svg",nativeToken:xe}});var Ae=require("@joai/warps");var nt={chain:Ae.WarpChainName.Vibechain,identifier:"VIBE",name:"VIBE",symbol:"VIBE",decimals:18,logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/tokens/logos/vibe.svg"},Fe={name:Ae.WarpChainName.Vibechain,displayName:"VibeChain",chainId:"V",blockTime:600,addressHrp:"vibe",defaultApiUrl:"https://vibeox-api.multiversx.com",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/vibechain.svg",nativeToken:nt},ke=we(Ae.WarpChainName.Vibechain,{mainnet:Fe,testnet:Fe,devnet:Fe});var wt=()=>[Ue,ke];var K=require("@joai/warps");var Ct=s=>new K.WarpSerializer().nativeToString(v.Token,s),Tt=s=>new K.WarpSerializer().nativeToString(v.CodeMeta,s),xt=(s,e)=>{if(e===null)return v.Optional+K.WarpConstants.ArgParamsSeparator;let t=s(e),r=t.indexOf(K.WarpConstants.ArgParamsSeparator),n=t.substring(0,r),i=t.substring(r+1);return v.Optional+K.WarpConstants.ArgParamsSeparator+n+K.WarpConstants.ArgParamsSeparator+i},At=s=>new K.WarpSerializer().nativeToString(v.List,s);var p=require("@multiversx/sdk-core"),Et=(s,e)=>s?p.OptionValue.newProvided(s):e?p.OptionValue.newMissingTyped(e):p.OptionValue.newMissing(),bt=(s,e)=>s?new p.OptionalValue(s.getType(),s):e?new p.OptionalValue(e):p.OptionalValue.newMissing(),Pt=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let e=s[0].getType();return new p.List(e,s)},It=s=>p.VariadicValue.fromItems(...s),St=s=>{let e=s.map(t=>t.getType());return new p.CompositeValue(new p.CompositeType(...e),s)},Bt=s=>p.StringValue.fromUTF8(s),Nt=s=>new p.U8Value(s),Vt=s=>new p.U16Value(s),Ut=s=>new p.U32Value(s),Ft=s=>new p.U64Value(s),kt=s=>new p.BigUIntValue(BigInt(s)),Mt=s=>new p.BooleanValue(s),Ot=s=>new p.AddressValue(p.Address.newFromBech32(s)),Rt=s=>new p.TokenIdentifierValue(s),Dt=s=>p.BytesValue.fromHex(s),Lt=s=>new p.Struct(new p.StructType("EsdtTokenPayment",[new p.FieldDefinition("token_identifier","",new p.TokenIdentifierType),new p.FieldDefinition("token_nonce","",new p.U64Type),new p.FieldDefinition("amount","",new p.BigUIntType)]),[new p.Field(new p.TokenIdentifierValue(s.token.identifier),"token_identifier"),new p.Field(new p.U64Value(BigInt(s.token.nonce)),"token_nonce"),new p.Field(new p.BigUIntValue(BigInt(s.amount)),"amount")]),Kt=s=>new p.CodeMetadataValue(p.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),_t=()=>new p.NothingValue;0&&(module.exports={ExplorerUrls,KnownTokens,MultiversxAdapter,MultiversxExplorers,MultiversxExplorersConfig,NativeTokenEgld,NativeTokenVibe,VibechainAdapter,VibechainExplorers,WarpMultiversxAbiBuilder,WarpMultiversxBrandBuilder,WarpMultiversxBuilder,WarpMultiversxConstants,WarpMultiversxContractLoader,WarpMultiversxDataLoader,WarpMultiversxExecutor,WarpMultiversxExplorer,WarpMultiversxInputTypes,WarpMultiversxOutput,WarpMultiversxRegistry,WarpMultiversxSerializer,WarpMultiversxWallet,address_value,asset_value,biguint_value,boolean_value,codemeta,codemeta_value,composite_value,createMultiversxAdapter,findKnownTokenById,getAllMultiversxAdapters,getAllMultiversxChainNames,getKnownTokensForChain,getMultiversxEntrypoint,getMultiversxRegistryAddress,getNormalizedTokenIdentifier,hex_value,isNativeToken,list,list_value,nothing_value,option_value,optional,optional_value,string_value,toTypedConfigInfo,toTypedRegistryInfo,token,token_value,u16_value,u32_value,u64_value,u8_value,variadic_value});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{WarpChainName as ze}from"@joai/warps";var Kn=()=>[ze.Multiversx,ze.Vibechain];import{WarpTypeRegistry as vn}from"@joai/warps";import{AbiRegistry as ge,Address as Gt,TransactionsFactoryConfig as zt,TransferTransactionsFactory as qt}from"@multiversx/sdk-core";import{createWarpIdentifier as Qt,getLatestProtocolIdentifier as jt,getWarpWalletAddressFromConfig as Jt,WarpCache as Xt,WarpCacheKey as Yt,WarpConstants as Qe,WarpLogger as je}from"@joai/warps";import{DevnetEntrypoint as Kt,MainnetEntrypoint as _t,TestnetEntrypoint as Ht}from"@multiversx/sdk-core";import{getProviderConfig as $t}from"@joai/warps";var M=s=>!s.includes("-"),Q=s=>M(s)?`${s}-000000`:s,W=(s,e,t)=>{let r="warp-sdk",a=t?$t(t,s.name,e,s.defaultApiUrl):{url:s.defaultApiUrl},i=a.url,o={headers:a.headers};return e==="devnet"?new Kt({url:i,kind:"api",clientName:r,networkProviderConfig:o}):e==="testnet"?new Ht({url:i,kind:"api",clientName:r,networkProviderConfig:o}):new _t({url:i,kind:"api",clientName:r,networkProviderConfig:o})};import{WarpLogger as qe}from"@joai/warps";var j=class{constructor(e){this.config=e}async getContract(e,t){try{let a=await W(t,this.config.env,this.config).createNetworkProvider().doGetGeneric(`accounts/${e}`);return{address:e,owner:a.ownerAddress,verified:a.isVerified||!1}}catch(r){return qe.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(e,t){try{let a=await W(t,this.config.env,this.config).createNetworkProvider().doGetGeneric(`accounts/${e}/verification`);return{codeHash:a.codeHash,abi:a.source.abi}}catch(r){return qe.error("WarpContractLoader: getVerificationInfo error",r),null}}};var S=class{constructor(e,t){this.config=e;this.chain=t;this.contractLoader=new j(this.config),this.cache=new Xt(this.config.env,this.config.cache)}async createInscriptionTransaction(e){let t=Jt(this.config,this.chain.name);if(!t)throw new Error("WarpBuilder: user address not set");let r=new zt({chainID:this.chain.chainId}),n=new qt({config:r}),a=Gt.newFromBech32(t),i={protocol:jt("abi"),content:e},o=JSON.stringify(i),c=await n.createTransactionForTransfer(a,{receiver:a,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(o))});return c.gasLimit=c.gasLimit+BigInt(2e6),c}async createFromRaw(e){return JSON.parse(e)}async createFromTransaction(e){let t=await this.createFromRaw(e.data.toString());return t.meta={chain:this.chain.name,identifier:Qt(this.chain.name,"hash",e.hash),query:null,hash:e.hash,creator:e.sender.toBech32(),createdAt:new Date(e.timestamp*1e3).toISOString()},t}async createFromTransactionHash(e,t){let r=Yt.WarpAbi(this.config.env,e);if(t){let i=this.cache.get(r);if(i)return je.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${e}`),i}let a=W(this.chain,this.config.env,this.config).createNetworkProvider();try{let i=await a.getTransaction(e),o=await this.createFromTransaction(i);return t&&t.ttl&&o&&this.cache.set(r,o,t.ttl),o}catch(i){return je.error("WarpAbiBuilder: Error creating from transaction hash",i),null}}async getAbiForAction(e){if(e.abi)return await this.fetchAbi(e);if(!e.address)throw new Error("WarpActionExecutor: Address not found");let t=await this.contractLoader.getVerificationInfo(e.address,this.chain);if(!t)throw new Error("WarpActionExecutor: Verification info not found");return ge.create(t.abi)}async fetchAbi(e){if(!e.abi)throw new Error("WarpActionExecutor: ABI not found");if(e.abi.startsWith(Qe.IdentifierType.Hash)){let t=e.abi.split(Qe.ArgParamsSeparator)[1],r=await this.createFromTransactionHash(t);if(!r)throw new Error(`WarpActionExecutor: ABI not found for hash: ${e.abi}`);return ge.create(r.content)}else{let r=await(await fetch(e.abi)).json();return ge.create(r)}}};import{Address as Je,TransactionsFactoryConfig as Zt,TransferTransactionsFactory as er}from"@multiversx/sdk-core";import{createWarpIdentifier as tr,getWarpWalletAddressFromConfig as rr,WarpBrandBuilder as nr,WarpLogger as ar}from"@joai/warps";import{Buffer as ir}from"buffer";var J=class{constructor(e,t){this.config=e;this.chain=t;this.core=new nr(e)}async createInscriptionTransaction(e){let t=rr(this.config,this.chain.name);if(!t)throw new Error("BrandBuilder: user address not set");let r=new Zt({chainID:this.chain.chainId}),n=new er({config:r}),a=Je.newFromBech32(t),i=JSON.stringify(e);return await n.createTransactionForNativeTokenTransfer(a,{receiver:Je.newFromBech32(t),nativeAmount:BigInt(0),data:Uint8Array.from(ir.from(i))})}async createFromTransaction(e,t=!1){let r=await this.core.createFromRaw(e.data.toString(),t);return r.meta={query:null,chain:this.chain.name,identifier:tr(this.chain.name,"hash",e.hash),hash:e.hash,creator:e.sender.toBech32(),createdAt:new Date(e.timestamp*1e3).toISOString()},r}async createFromTransactionHash(e){let r=W(this.chain,this.config.env,this.config).createNetworkProvider();try{let n=await r.getTransaction(e);return this.createFromTransaction(n)}catch(n){return ar.error("BrandBuilder: Error creating from transaction hash",n),null}}};import{Address as Xe,TransactionsFactoryConfig as sr,TransferTransactionsFactory as or}from"@multiversx/sdk-core";import{createWarpIdentifier as cr,getWarpWalletAddressFromConfig as lr,WarpBuilder as Ye,WarpCache as pr,WarpCacheKey as ur,WarpLogger as Ze}from"@joai/warps";var X=class extends Ye{constructor(t,r){super(t);this.config=t;this.chain=r;this.cache=new pr(t.env,t.cache),this.core=new Ye(t)}async createInscriptionTransaction(t){let r=lr(this.config,this.chain.name);if(!r)throw new Error("WarpBuilder: user address not set");let n=new sr({chainID:this.chain.chainId}),a=new or({config:n}),i=Xe.newFromBech32(r),o=JSON.stringify(t),c=await a.createTransactionForTransfer(i,{receiver:Xe.newFromBech32(r),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(o))});return c.gasLimit=c.gasLimit+BigInt(2e6),c}async createFromTransaction(t,r=!1){let n=await this.core.createFromRaw(t.data.toString(),r);return n.meta={chain:this.chain.name,identifier:cr(this.chain.name,"hash",t.hash),query:null,hash:t.hash,creator:t.sender.toBech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},n}async createFromTransactionHash(t,r){let n=ur.Warp(this.config.env,t);if(r){let o=this.cache.get(n);if(o)return Ze.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),o}let i=W(this.chain,this.config.env,this.config).createNetworkProvider();try{let o=await i.getTransaction(t),c=await this.createFromTransaction(o);return r&&r.ttl&&c&&this.cache.set(n,c,r.ttl),c}catch(o){return Ze.error("WarpBuilder: Error creating from transaction hash",o),null}}};import{Address as fe,Token as fr,TokenComputer as yr}from"@multiversx/sdk-core";import{CacheTtl as vr,WarpCache as Wr,WarpCacheKey as wr}from"@joai/warps";import{WarpChainName as st}from"@joai/warps";import{WarpChainName as mr}from"@joai/warps";var et=mr.Multiversx,tt=[{chain:et,identifier:"EGLD",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"},{chain:et,identifier:"EGLD-000000",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"}];import{WarpChainName as dr}from"@joai/warps";var x=dr.Multiversx,rt=[{chain:x,identifier:"EGLD",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"},{chain:x,identifier:"EGLD-000000",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"},{chain:x,identifier:"SEGLD-3ad2d0",name:"StakedEGLD",symbol:"SEGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/SEGLD-3ad2d0/icon.png"},{chain:x,identifier:"HSEGLD-c13a4e",name:"HatomSEGLD",symbol:"HSEGLD",decimals:8,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/HSEGLD-c13a4e/icon.png"},{chain:x,identifier:"UTK-2f80e9",name:"xMoney UTK",symbol:"UTK",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/UTK-2f80e9/icon.png"},{chain:x,identifier:"USDC-c76f1f",name:"WrappedUSDC",symbol:"USDC",decimals:6,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/USDC-c76f1f/icon.png"},{chain:x,identifier:"WEGLD-bd4d79",name:"WrappedEGLD",symbol:"WEGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/WEGLD-bd4d79/icon.png"},{chain:x,identifier:"HTM-f51d55",name:"Hatom",symbol:"HTM",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/HTM-f51d55/icon.png"},{chain:x,identifier:"MEX-455c57",name:"MEX",symbol:"MEX",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/MEX-455c57/icon.png"},{chain:x,identifier:"WTAO-4f5363",name:"WrappedTAO",symbol:"WTAO",decimals:9,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/WTAO-4f5363/icon.png"},{chain:x,identifier:"HEGLD-d61095",name:"HatomEGLD",symbol:"HEGLD",decimals:8,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/HEGLD-d61095/icon.png"},{chain:x,identifier:"WBTC-5349b3",name:"WrappedBTC",symbol:"WBTC",decimals:8,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/WBTC-5349b3/icon.png"},{chain:x,identifier:"WETH-b4ca29",name:"WrappedETH",symbol:"WETH",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/WETH-b4ca29/icon.png"},{chain:x,identifier:"USH-111e09",name:"HatomUSD",symbol:"USH",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/USH-111e09/icon.png"},{chain:x,identifier:"USDT-f8c08c",name:"WrappedUSDT",symbol:"USDT",decimals:6,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/USDT-f8c08c/icon.png"}];import{WarpChainName as hr}from"@joai/warps";var nt=hr.Multiversx,at=[{chain:nt,identifier:"EGLD",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"},{chain:nt,identifier:"EGLD-000000",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"}];import{WarpChainName as gr}from"@joai/warps";var it=gr.Vibechain,Y=[{chain:it,identifier:"VIBE",name:"VIBE",symbol:"VIBE",decimals:18,logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/tokens/logos/vibe.svg"},{chain:it,identifier:"VIBE-000000",name:"VIBE",symbol:"VIBE",decimals:18,logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/tokens/logos/vibe.svg"}];var ot={[st.Multiversx]:{mainnet:rt,testnet:at,devnet:tt},[st.Vibechain]:{mainnet:Y,testnet:Y,devnet:Y}},ct=(s,e,t)=>(ot[s]?.[e]||[]).find(n=>n.identifier===t)||null,ni=(s,e)=>ot[s]?.[e]||[];var Z=class{constructor(e,t){this.config=e;this.chain=t;this.cache=new Wr(e.env,e.cache)}async getAccount(e){let r=await W(this.chain,this.config.env,this.config).createNetworkProvider().getAccount(fe.newFromBech32(e));return{chain:this.chain.name,address:r.address.toBech32(),balance:r.balance}}async getAccountAssets(e){let t=W(this.chain,this.config.env,this.config).createNetworkProvider(),r=t.getAccount(fe.newFromBech32(e)),n=t.getFungibleTokensOfAccount(fe.newFromBech32(e)),[a,i]=await Promise.all([r,n]),o=a.balance>0?[{...this.chain.nativeToken,amount:a.balance}]:[];return o.push(...i.map(c=>({chain:this.chain.name,identifier:c.token.identifier,name:c.raw.name,symbol:c.raw.ticker,amount:c.amount,decimals:c.raw.decimals,logoUrl:c.raw.assets?.pngUrl||"",price:c.raw.price?Number(c.raw.price):void 0,supply:c.raw.supply?BigInt(c.raw.supply):void 0}))),o}async getAsset(e){let t=wr.Asset(this.config.env,this.chain.name,e),r=this.cache.get(t);if(r)return r;let n=ct(this.chain.name,this.config.env,e);if(n)return{chain:this.chain.name,identifier:e,name:n.name,symbol:n.symbol,amount:0n,decimals:n.decimals,logoUrl:n.logoUrl};let a=new yr,i=M(e)?0n:a.extractNonceFromExtendedIdentifier(e),o=new fr({identifier:e,nonce:BigInt(i||0)}),c=a.isFungible(o),d=W(this.chain,this.config.env,this.config).createNetworkProvider(),m=Q(e),p=await d.doGetGeneric(`tokens/${m}`),v={chain:this.chain.name,identifier:o.identifier,name:p.name,symbol:p.ticker,amount:0n,decimals:p.decimals,logoUrl:p.assets?.pngUrl||null,price:p.price?Number(p.price):void 0,supply:p.supply?BigInt(p.supply):void 0};return this.cache.set(t,v,vr.OneHour),v}async getAction(e,t=!1){let r=W(this.chain,this.config.env,this.config),n=t?await r.awaitCompletedTransaction(e):await r.getTransaction(e);return{chain:this.chain.name,id:n.hash,receiver:n.receiver.toBech32(),sender:n.sender.toBech32(),value:n.value,function:n.function,status:this.toActionStatus(n),createdAt:this.toActionCreatedAt(n),error:n?.smartContractResults.map(a=>a.raw.returnMessage)[0]||null,tx:n}}async getAccountActions(e,t){let r=W(this.chain,this.config.env,this.config).createNetworkProvider(),n=`accounts/${e}/transactions`,a=new URLSearchParams,i=t?.size||25,o=t?.page||0;if(o>0){let d=o*i;a.append("from",d.toString())}return i!==25&&a.append("size",i.toString()),a.toString()&&(n+=`?${a.toString()}`),(await r.doGetGeneric(n)).map(d=>({chain:this.chain.name,id:d.txHash,receiver:d.receiver,sender:d.sender,value:d.value,function:d.function,status:this.toActionStatus(d),createdAt:this.toActionCreatedAt(d)}))}toActionStatus(e){return e.status?.isSuccessful?.()?"success":e.status?.isFailed?.()?"failed":"pending"}toActionCreatedAt(e){return new Date(e.timestamp||e.timestamp*1e3).toISOString()}};import{Address as $,ArgSerializer as Rr,SmartContractTransactionsFactory as Dr,Token as Lr,TokenComputer as Kr,TokenTransfer as _r,TransactionsFactoryConfig as bt,TransferTransactionsFactory as Hr}from"@multiversx/sdk-core";import{applyOutputToMessages as $r,extractResolvedInputValues as Gr,getNextInfo as zr,getWarpActionByIndex as Ne,getWarpWalletAddressFromConfig as Ve}from"@joai/warps";import{findEventsByFirstTopic as Ir,SmartContractTransactionsOutcomeParser as Sr,TransactionEventsParser as Br}from"@multiversx/sdk-core";import{applyOutputToMessages as Nr,evaluateOutputCommon as oe,extractResolvedInputValues as Vr,getNextInfo as Ur,getWarpActionByIndex as kr,getWarpWalletAddressFromConfig as Fr,parseOutputOutIndex as At,WarpCache as Or,WarpCacheKey as Mr,WarpConstants as Et}from"@joai/warps";import{Address as xr,AddressType as ye,AddressValue as pt,BigUIntType as ee,BigUIntValue as ve,BooleanType as We,BooleanValue as ut,BytesType as we,BytesValue as mt,CodeMetadata as Ar,CodeMetadataType as Te,CodeMetadataValue as dt,CompositeType as Ce,CompositeValue as ht,Field as te,FieldDefinition as re,List as gt,ListType as ft,NothingValue as b,OptionalType as yt,OptionalValue as xe,OptionType as vt,OptionValue as Ae,StringType as Ee,StringValue as Wt,Struct as ne,StructType as k,Token as Er,TokenComputer as wt,TokenIdentifierType as ae,TokenIdentifierValue as be,U16Type as Pe,U16Value as Tt,U32Type as Ie,U32Value as Ct,U64Type as ie,U64Value as Se,U8Type as Be,U8Value as xt,VariadicType as H,VariadicValue as se}from"@multiversx/sdk-core";import{WarpSerializer as br}from"@joai/warps";var u={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:s=>s.config.user?.wallets?.[s.adapter.chainInfo.name]},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:s=>{if(!s.adapter.wallet)return null;try{return s.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:s=>s.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:s=>s.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},l={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"};var wi={Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}},f={Null:"null",Optional:"optional",List:"list",Token:"token",CodeMeta:"codemeta"},Tr=(r=>(r.MultiversxExplorer="multiversx_explorer",r.MultiversxExplorerDevnet="multiversx_explorer_devnet",r.MultiversxExplorerTestnet="multiversx_explorer_testnet",r))(Tr||{}),Cr=(r=>(r.VibechainExplorer="vibechain_explorer",r.VibechainExplorerDevnet="vibechain_explorer_devnet",r.VibechainExplorerTestnet="vibechain_explorer_testnet",r))(Cr||{}),lt={multiversx:{mainnet:["multiversx_explorer"],testnet:["multiversx_explorer_testnet"],devnet:["multiversx_explorer_devnet"]},vibechain:{mainnet:["vibechain_explorer"],testnet:["vibechain_explorer_testnet"],devnet:["vibechain_explorer_devnet"]}},U={multiversx_explorer:"https://explorer.multiversx.com",multiversx_explorer_devnet:"https://devnet-explorer.multiversx.com",multiversx_explorer_testnet:"https://testnet-explorer.multiversx.com",vibechain_explorer:"https://vibeox-explorer.multiversx.com",vibechain_explorer_devnet:"https://vibeox-explorer.multiversx.com",vibechain_explorer_testnet:"https://vibeox-explorer.multiversx.com"};var Pr=new RegExp(`${u.ArgParamsSeparator}(.*)`),B=class{constructor(e){this.coreSerializer=new br(e)}typedToString(e){let t=e.getType();if(t.hasExactClass(vt.ClassName)||e.hasClassOrSuperclass(Ae.ClassName)){if(!e.isSet())return l.Option+u.ArgParamsSeparator+"null";let r=this.typedToString(e.getTypedValue());return l.Option+u.ArgParamsSeparator+r}if(t.hasExactClass(H.ClassName)||e.hasClassOrSuperclass(se.ClassName)){let r=e.getItems();if(r.length===0){let m=this.typeToString(t.getFirstTypeParameter());return l.Vector+u.ArgParamsSeparator+m+u.ArgParamsSeparator}let n=r.map(m=>this.typedToString(m));if(n.every(m=>m.startsWith(l.Tuple)))return l.Vector+u.ArgParamsSeparator+n.join(",");let a=n[0],i=a.indexOf(u.ArgParamsSeparator),o=a.substring(0,i),c=n.map(m=>{let p=m.indexOf(u.ArgParamsSeparator);return m.substring(p+1)}),d=o.startsWith(l.Struct)?u.ArgStructSeparator:u.ArgListSeparator;return l.Vector+u.ArgParamsSeparator+o+u.ArgParamsSeparator+c.join(d)}if(t.hasExactClass(yt.ClassName)||e.hasClassOrSuperclass(xe.ClassName)){if(!e.isSet())return f.Optional+u.ArgParamsSeparator+"null";let r=this.typedToString(e.getTypedValue());return f.Optional+u.ArgParamsSeparator+r}if(t.hasExactClass(ft.ClassName)||e.hasClassOrSuperclass(gt.ClassName)){let n=e.getItems().map(c=>this.typedToString(c));if(n.every(c=>c.startsWith(l.Tuple)))return f.List+u.ArgParamsSeparator+n.join(",");let i=n.map(c=>c.split(u.ArgParamsSeparator)[0])[0],o=n.map(c=>c.split(u.ArgParamsSeparator)[1]);return f.List+u.ArgParamsSeparator+i+u.ArgParamsSeparator+o.join(u.ArgListSeparator)}if(t.hasExactClass(Ce.ClassName)||e.hasClassOrSuperclass(ht.ClassName)){let n=e.getItems().map(a=>{let i=this.typedToString(a),o=i.indexOf(u.ArgParamsSeparator),c=i.substring(0,o),d=i.substring(o+1);return`${c},${d}`});return`${l.Tuple}(${n.join(",")})`}if(t.hasExactClass(ee.ClassName)||e.hasClassOrSuperclass(ve.ClassName)||t.getName()==="BigUint")return l.Biguint+u.ArgParamsSeparator+BigInt(e.valueOf().toFixed());if(t.hasExactClass(Be.ClassName)||e.hasClassOrSuperclass(xt.ClassName))return l.Uint8+u.ArgParamsSeparator+e.valueOf().toNumber();if(t.hasExactClass(Pe.ClassName)||e.hasClassOrSuperclass(Tt.ClassName))return l.Uint16+u.ArgParamsSeparator+e.valueOf().toNumber();if(t.hasExactClass(Ie.ClassName)||e.hasClassOrSuperclass(Ct.ClassName))return l.Uint32+u.ArgParamsSeparator+e.valueOf().toNumber();if(t.hasExactClass(ie.ClassName)||e.hasClassOrSuperclass(Se.ClassName))return l.Uint64+u.ArgParamsSeparator+BigInt(e.valueOf().toFixed());if(t.hasExactClass(Ee.ClassName)||e.hasClassOrSuperclass(Wt.ClassName))return l.String+u.ArgParamsSeparator+e.valueOf();if(t.hasExactClass(We.ClassName)||e.hasClassOrSuperclass(ut.ClassName))return l.Bool+u.ArgParamsSeparator+e.valueOf();if(t.hasExactClass(ye.ClassName)||e.hasClassOrSuperclass(pt.ClassName))return l.Address+u.ArgParamsSeparator+e.valueOf().toBech32();if(t.hasExactClass(we.ClassName)||e.hasClassOrSuperclass(mt.ClassName))return l.Hex+u.ArgParamsSeparator+e.valueOf().toString("hex");if(t.getName()==="EsdtTokenPayment"){let r=e.getFieldValue("token_identifier").valueOf(),n=e.getFieldValue("token_nonce").valueOf(),a=e.getFieldValue("amount").valueOf(),o=new wt().computeExtendedIdentifier(new Er({identifier:r,nonce:BigInt(n)}));return l.Asset+u.ArgParamsSeparator+o+u.ArgCompositeSeparator+a}if(t.hasExactClass(k.ClassName)||e.hasClassOrSuperclass(ne.ClassName)){let r=e,a=r.getType().getName(),i=r.getFields();if(i.length===0)return`${l.Struct}(${a})${u.ArgParamsSeparator}`;let o=i.map(c=>{let d=c.value.getType(),p=this.typedToString(c.value).split(u.ArgParamsSeparator),v=p.length>2?p.slice(2).join(u.ArgParamsSeparator):p[1]||"";return`(${c.name}${u.ArgParamsSeparator}${this.typeToString(d)})${v}`});return`${l.Struct}(${a})${u.ArgParamsSeparator}${o.join(u.ArgListSeparator)}`}if(t.hasExactClass(ae.ClassName)||e.hasClassOrSuperclass(be.ClassName))return f.Token+u.ArgParamsSeparator+e.valueOf();if(t.hasExactClass(Te.ClassName)||e.hasClassOrSuperclass(dt.ClassName))return f.CodeMeta+u.ArgParamsSeparator+e.valueOf().toString();throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${e.getClassName()}`)}typedToNative(e){let t=this.typedToString(e);return this.coreSerializer.stringToNative(t)}nativeToTyped(e,t){if(e.startsWith(l.Tuple))return this.stringToTyped(e+":");let r=this.coreSerializer.nativeToString(e,t);return this.stringToTyped(r)}nativeToType(e){if(e.startsWith(l.Tuple)){let t=e.match(/\(([^)]+)\)/)?.[1];if(!t)throw new Error(`Invalid tuple type format: ${e}`);let r=t.split(","),n=[];for(let a=0;a<r.length;a+=2)n.push(r[a]);return new Ce(...n.map(a=>this.nativeToType(a)))}if(e.startsWith(l.Struct)){let t=e.match(/\(([^)]+)\)/);if(!t)throw new Error("Struct type must include a name in the format struct(Name)");let r=t[1];return new k(r,[])}if(e===l.String)return new Ee;if(e===l.Uint8)return new Be;if(e===l.Uint16)return new Pe;if(e===l.Uint32)return new Ie;if(e===l.Uint64)return new ie;if(e===l.Biguint)return new ee;if(e===l.Bool)return new We;if(e===l.Address)return new ye;if(e===l.Hex)return new we;if(e===l.Asset)return new k("EsdtTokenPayment",[new re("token_identifier","",new ae),new re("token_nonce","",new ie),new re("amount","",new ee)]);if(e===f.Token)return new ae;if(e===f.CodeMeta)return new Te;throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${e}`)}stringToTyped(e){let[t,r]=e.split(/:(.*)/,2);if(t===l.Option){let n=this.stringToTyped(r);return n instanceof b?Ae.newMissingTyped(n.getType()):Ae.newProvided(n)}if(t===l.Vector){let n=r.indexOf(u.ArgParamsSeparator),a=r.substring(0,n),i=r.substring(n+1);if(a.startsWith(l.Tuple)){let p=i.split(",").map(v=>this.stringToTyped(v));return new se(new H(this.nativeToType(a)),p)}if(i.includes("tuple(")){let m=this.splitTupleStrings(i),p=m.map(T=>this.stringToTyped(T)),C=m[0].match(/^(tuple\([^)]+\))/),h=C?C[1]:"tuple";return new se(new H(this.nativeToType(h)),p)}let o=a.startsWith(l.Struct)?u.ArgStructSeparator:u.ArgListSeparator,d=i.split(o).map(m=>this.stringToTyped(`${a}:${m}`));return new se(new H(this.nativeToType(a)),d)}if(t.startsWith(l.Tuple)){let n=t.match(/\(([^)]+)\)/)?.[1];if(!n)throw new Error(`Invalid tuple format: ${t}`);let a=n.split(","),i=[];for(let c=0;c<a.length;c+=2){let d=a[c],m=a[c+1];i.push(this.stringToTyped(`${d}:${m}`))}let o=i.map(c=>c.getType());return new ht(new Ce(...o),i)}if(t.startsWith(l.Struct)){let n=t.match(/\(([^)]+)\)/),a=n?n[1]:"CustomStruct";if(!r)return new ne(new k(a,[]),[]);let i=r.split(u.ArgListSeparator),o=[],c=[];return i.forEach(d=>{let m=d.match(new RegExp(`^\\(([^${u.ArgParamsSeparator}]+)${u.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(m){let[,p,v,C]=m,h=this.stringToTyped(`${v}${u.ArgParamsSeparator}${C}`);o.push(new re(p,"",h.getType())),c.push(new te(h,p))}}),new ne(new k(a,o),c)}if(t===l.String)return r?Wt.fromUTF8(r):new b;if(t===l.Uint8)return r?new xt(Number(r)):new b;if(t===l.Uint16)return r?new Tt(Number(r)):new b;if(t===l.Uint32)return r?new Ct(Number(r)):new b;if(t===l.Uint64)return r?new Se(BigInt(r)):new b;if(t===l.Biguint)return r?new ve(BigInt(r)):new b;if(t===l.Bool)return r?new ut(typeof r=="boolean"?r:r==="true"):new b;if(t===l.Address)return r?new pt(xr.newFromBech32(r)):new b;if(t===l.Hex)return r?mt.fromHex(r):new b;if(t===l.Asset){let[n,a]=r.split(u.ArgCompositeSeparator),i=new wt,o=M(n)?Q(n):i.extractIdentifierFromExtendedIdentifier(n),c=M(n)?0n:i.extractNonceFromExtendedIdentifier(n);return new ne(this.nativeToType("asset"),[new te(new be(o),"token_identifier"),new te(new Se(BigInt(c)),"token_nonce"),new te(new ve(BigInt(a)),"amount")])}if(t===f.Null)return new b;if(t===f.Optional){let n=this.stringToTyped(r);return n instanceof b?xe.newMissing():new xe(n.getType(),n)}if(t===f.List){let[n,a]=r.split(Pr,2),o=a.split(u.ArgListSeparator).map(c=>this.stringToTyped(n+u.ArgParamsSeparator+c));return new gt(this.nativeToType(n),o)}if(t===f.Token)return r?new be(r):new b;if(t===f.CodeMeta)return new dt(Ar.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${t}`)}splitTupleStrings(e){let t=[],r="",n=0;for(let a=0;a<e.length;a++){let i=e[a];if(i==="(")n++;else if(i===")")n--;else if(i===","&&n===0){t.push(r.trim()),r="";continue}r+=i}return r.trim()&&t.push(r.trim()),t}typeToString(e){if(e.hasExactClass(vt.ClassName))return l.Option+u.ArgParamsSeparator+this.typeToString(e.getFirstTypeParameter());if(e.hasExactClass(H.ClassName))return l.Vector+u.ArgParamsSeparator+this.typeToString(e.getFirstTypeParameter());if(e.hasExactClass(Ee.ClassName))return l.String;if(e.hasExactClass(Be.ClassName))return l.Uint8;if(e.hasExactClass(Pe.ClassName))return l.Uint16;if(e.hasExactClass(Ie.ClassName))return l.Uint32;if(e.hasExactClass(ie.ClassName))return l.Uint64;if(e.hasExactClass(ee.ClassName))return l.Biguint;if(e.hasExactClass(We.ClassName))return l.Bool;if(e.hasExactClass(ye.ClassName))return l.Address;if(e.hasExactClass(we.ClassName))return l.Hex;if(e.hasExactClass(ae.ClassName))return f.Token;if(e.hasExactClass(yt.ClassName))return f.Optional+u.ArgParamsSeparator+this.typeToString(e.getFirstTypeParameter());if(e.hasExactClass(ft.ClassName))return f.List+u.ArgParamsSeparator+this.typeToString(e.getFirstTypeParameter());if(e.hasExactClass(Te.ClassName))return f.CodeMeta;if(e.hasExactClass(k.ClassName)&&e.getClassName()==="EsdtTokenPayment")return l.Asset;if(e.hasExactClass(k.ClassName))return`${l.Struct}(${e.getName()})`;throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${e.getClassName()}`)}};var R=class{constructor(e,t,r){this.config=e;this.chain=t;this.typeRegistry=r;this.abi=new S(e,t),this.serializer=new B({typeRegistry:this.typeRegistry}),this.cache=new Or(e.env,e.cache)}async getActionExecution(e,t,r){let n=this.cache.get(Mr.WarpExecutable(this.config.env,e.meta?.hash||"",t))??[],a=await this.extractContractOutput(e,t,r,n),i=Ur(this.config,[],e,t,a.output),o=Nr(e,a.output,this.config),c=Vr(n);return{status:r.status?.isSuccessful?.()?"success":"error",warp:e,action:t,user:Fr(this.config,this.chain.name),txHash:r.hash,tx:r,next:i,values:a.values,output:a.output,messages:o,destination:null,resolvedInputs:c}}async extractContractOutput(e,t,r,n){let a=kr(e,t),i=[],o=[],c={};if(!e.output||a.type!=="contract")return{values:{string:i,native:o,mapped:{}},output:c};if(!Object.values(e.output).some(h=>h.includes("out")||h.includes("event"))){for(let[h,T]of Object.entries(e.output))c[h]=T;return{values:{string:i,native:o,mapped:{}},output:await oe(e,c,t,n,this.serializer.coreSerializer,this.config)}}let m=await this.abi.getAbiForAction(a),p=new Br({abi:m}),C=new Sr({abi:m}).parseExecute({transactionOnNetwork:r,function:a.func||void 0});for(let[h,T]of Object.entries(e.output)){if(T.startsWith(Et.Transform.Prefix))continue;if(T.startsWith("input.")){c[h]=T;continue}let A=At(T);if(A!==null&&A!==t){c[h]=null;continue}let[P,N,V]=T.split(".");if(P==="event"){if(!N||isNaN(Number(V)))continue;let I=Number(V),g=Ir(r,N),Lt=p.parseEvents({events:g})[0],_=Object.values(Lt)[I]||null;i.push(String(_)),o.push(_),c[h]=_&&_.valueOf()}else if(P==="out"||P.startsWith("out[")){if(!N)continue;let I=Number(N),g=C.values[I-1]||null;V&&(g=g[V]||null),g&&typeof g=="object"&&(g="toFixed"in g?g.toFixed():g.valueOf()),i.push(String(g)),o.push(g),c[h]=g&&g.valueOf()}else c[h]=T}return{values:{string:i,native:o,mapped:{}},output:await oe(e,c,t,n,this.serializer.coreSerializer,this.config)}}async extractQueryOutput(e,t,r,n){let a=t.map(m=>this.serializer.typedToString(m)),i=t.map(m=>this.serializer.typedToNative(m)[1]),o={string:a,native:i,mapped:{}},c={};if(!e.output)return{values:o,output:c};let d=m=>{let p=m.split(".").slice(1).map(C=>parseInt(C)-1);if(p.length===0)return;let v=i[p[0]];for(let C=1;C<p.length;C++){if(v==null)return;v=v[p[C]]}return v};for(let[m,p]of Object.entries(e.output)){if(p.startsWith(Et.Transform.Prefix))continue;let v=At(p);if(v!==null&&v!==r){c[m]=null;continue}p.startsWith("out.")||p==="out"||p.startsWith("out[")?c[m]=d(p)||null:c[m]=p}return c=await oe(e,c,r,n,this.serializer.coreSerializer,this.config),{values:o,output:c}}async resolveWarpOutputRecursively(e){let t=e.warp,r=e.entryActionIndex,n=e.executor,a=e.inputs,i=e.meta,o=new Map,c=new Set,d=this;async function m(h,T=[]){if(o.has(h))return o.get(h);if(c.has(h))throw new Error(`Circular dependency detected at action ${h}`);c.add(h);let A=t.actions[h-1];if(!A)throw new Error(`Action ${h} not found`);let P;if(A.type==="query")P=await n.executeQuery(t,h,T);else if(A.type==="collect")P=await n.executeCollect(t,h,T,i);else throw new Error(`Unsupported or interactive action type: ${A.type}`);if(o.set(h,P),t.output)for(let N of Object.values(t.output)){let I=String(N).match(/^out\[(\d+)\]/);if(I){let g=parseInt(I[1],10);g!==h&&!o.has(g)&&await m(g)}}return c.delete(h),P}await m(r,a);let p={};for(let h of o.values())for(let[T,A]of Object.entries(h.output))A!==null?p[T]=A:T in p||(p[T]=null);let v=await oe(t,p,r,a,this.serializer.coreSerializer,this.config);return{...o.get(r),action:r,output:v}}};var qr="EGLD-000000",ce=class{constructor(e,t,r){this.config=e;this.chain=t;this.typeRegistry=r;this.serializer=new B({typeRegistry:this.typeRegistry}),this.abi=new S(this.config,this.chain),this.output=new R(this.config,this.chain,this.typeRegistry)}async createTransaction(e){let t=Ne(e.warp,e.action),r=null;if(t.type==="transfer")r=await this.createTransferTransaction(e);else if(t.type==="contract")r=await this.createContractCallTransaction(e);else{if(t.type==="query")throw new Error("WarpMultiversxExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead");if(t.type==="collect")throw new Error("WarpMultiversxExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead")}if(!r)throw new Error(`WarpMultiversxExecutor: Invalid action type (${t.type})`);return r}async createTransferTransaction(e){if(!e.destination)throw new Error("WarpMultiversxExecutor: createTransfer - destination not set");let t=Ve(this.config,e.chain.name);if(!t)throw new Error("WarpMultiversxExecutor: createTransfer - user address not set");let r=$.newFromBech32(t),n=new bt({chainID:e.chain.chainId}),a=e.data?Buffer.from(this.serializer.stringToTyped(e.data).valueOf()):null,i=e.transfers.length===1&&e.transfers[0].identifier===this.chain.nativeToken?.identifier,c=(i?e.transfers[0].amount:0n)+e.value;return await new Hr({config:n}).createTransactionForTransfer(r,{receiver:$.newFromBech32(e.destination),nativeAmount:c,tokenTransfers:i?[]:this.toTokenTransfers(e.transfers),data:a?new Uint8Array(a):void 0})}async createContractCallTransaction(e){if(!e.destination)throw new Error("WarpMultiversxExecutor: createContractCall - destination not set");let t=Ve(this.config,e.chain.name);if(!t)throw new Error("WarpMultiversxExecutor: createContractCall - user address not set");let r=Ne(e.warp,e.action),n=$.newFromBech32(t),a=e.args.map(o=>this.serializer.stringToTyped(o)),i=new bt({chainID:e.chain.chainId});return new Dr({config:i}).createTransactionForExecute(n,{contract:$.newFromBech32(e.destination),function:"func"in r&&r.func||"",gasLimit:"gasLimit"in r?BigInt(r.gasLimit||0):0n,arguments:a,tokenTransfers:this.toTokenTransfers(e.transfers),nativeTransferAmount:e.value})}async executeQuery(e){if(!e.destination)throw new Error("WarpMultiversxExecutor: executeQuery - destination not set");let t=Ne(e.warp,e.action);if(t.type!=="query")throw new Error(`WarpMultiversxExecutor: Invalid action type for executeQuery: ${t.type}`);let r=await this.abi.getAbiForAction(t),n=e.args.map(g=>this.serializer.stringToTyped(g)),a=W(e.chain,this.config.env,this.config),i=$.newFromBech32(e.destination),o=a.createSmartContractController(r),c=o.createQuery({contract:i,function:t.func||"",arguments:n}),d=await o.runQuery(c),m=d.returnCode==="ok",p=new Rr,v=r.getEndpoint(d.function||t.func||""),C=(d.returnDataParts||[]).map(g=>Buffer.from(g)),h=p.buffersToValues(C,v.output),{values:T,output:A}=await this.output.extractQueryOutput(e.warp,h,e.action,e.resolvedInputs),P=zr(this.config,[],e.warp,e.action,A),V=e.resolvedInputs.find(g=>g.input.position==="receiver"||g.input.position==="destination")?.value||e.destination,I=Gr(e.resolvedInputs);return{status:m?"success":"error",warp:e.warp,action:e.action,user:Ve(this.config,e.chain.name),txHash:null,tx:null,next:P,values:T,output:{...A,_DATA:h},messages:$r(e.warp,A,this.config),destination:V,resolvedInputs:I}}toTokenTransfers(e){return e.map(t=>t.identifier===this.chain.nativeToken.identifier?{...t,identifier:qr}:t).map(t=>{let n=new Kr().extractNonceFromExtendedIdentifier(t.identifier);return new _r({token:new Lr({identifier:t.identifier,nonce:BigInt(n||0)}),amount:t.amount})})}};var le=class{constructor(e,t){this.chain=e;this.config=t}getExplorers(){let e=lt[this.chain];if(!e)return["multiversx_explorer"];let t=e[this.config.env];return t||["multiversx_explorer"]}getPrimaryExplorer(){return this.getExplorers()[0]}getExplorerUrlByName(e){let t=this.config.preferences?.explorers?.[this.chain];if(t&&!e){let a=U[t];if(a)return a}if(e){let a=U[e];if(a)return a}let r=this.getPrimaryExplorer();return U[r]||U[r]}getAccountUrl(e,t){return`${this.getExplorerUrlByName(t)}/accounts/${e}`}getTransactionUrl(e,t){return`${this.getExplorerUrlByName(t)}/transactions/${e}`}getBlockUrl(e,t){return`${this.getExplorerUrlByName(t)}/blocks/${e}`}getAssetUrl(e,t){return`${this.getExplorerUrlByName(t)}/tokens/${e}`}getContractUrl(e,t){return`${this.getExplorerUrlByName(t)}/accounts/${e}`}getAllExplorers(){return this.getExplorers()}getExplorerByName(e){return this.getExplorers().find(r=>r.toLowerCase()===e.toLowerCase())}getAccountUrls(e){let t=this.getAllExplorers(),r={};return t.forEach(n=>{let a=U[n];a&&(r[n]=`${a}/accounts/${e}`)}),r}getTransactionUrls(e){let t=this.getAllExplorers(),r={};return t.forEach(n=>{let a=U[n];a&&(r[n]=`${a}/transactions/${e}`)}),r}};import{AbiRegistry as It,Address as y,AddressValue as ke,BytesValue as w,SmartContractTransactionsFactory as jr,TransactionsFactoryConfig as Jr}from"@multiversx/sdk-core";import{createWarpIdentifier as Xr,getWarpWalletAddressFromConfig as Yr,WarpCache as Zr,WarpCacheKey as Fe,WarpLogger as Oe}from"@joai/warps";var Ue={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"},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],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}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpVerified",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"ownershipTransferred",inputs:[{name:"warp",type:"bytes",indexed:!0},{name:"old_owner",type:"Address",indexed:!0},{name:"new_owner",type:"Address",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{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 E=s=>{if(s==="devnet")return"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36";if(s==="testnet")throw new Error("Multiversx testnet is not supported");return"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"};var pe=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}),Pt=s=>({unitPrice:BigInt(s.unit_price.toString()),admins:s.admins.map(e=>e.toBech32())});var ue=class{constructor(e,t){this.config=e;this.chain=t;this.cache=new Zr(e.env,e.cache),this.registryConfig={unitPrice:BigInt(0),admins:[]},this.userWallet=Yr(this.config,this.chain.name)}async init(){await this.loadRegistryConfigs()}getRegistryConfig(){return this.registryConfig}async createWarpRegisterTransaction(e,t,r){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let n=y.newFromBech32(this.userWallet),a=()=>this.isCurrentUserAdmin()?BigInt(0):t&&r?this.registryConfig.unitPrice*BigInt(3):t?this.registryConfig.unitPrice*BigInt(2):this.registryConfig.unitPrice,i=()=>t&&r?[w.fromHex(e),w.fromUTF8(t),w.fromHex(r)]:t?[w.fromHex(e),w.fromUTF8(t)]:[w.fromHex(e)];return await this.getFactory().createTransactionForExecute(n,{contract:y.newFromBech32(E(this.config.env)),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:a(),arguments:i()})}async createWarpUnregisterTransaction(e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=y.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(t,{contract:y.newFromBech32(E(this.config.env)),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[w.fromHex(e)]})}async createWarpUpgradeTransaction(e,t,r){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let n=y.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(n,{contract:y.newFromBech32(E(this.config.env)),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:r?[w.fromUTF8(e),w.fromHex(t),w.fromHex(r)]:[w.fromUTF8(e),w.fromHex(t)]})}async createWarpAliasSetTransaction(e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let r=y.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(r,{contract:y.newFromBech32(E(this.config.env)),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[w.fromHex(e),w.fromUTF8(t)]})}async createWarpVerifyTransaction(e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=y.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(t,{contract:y.newFromBech32(E(this.config.env)),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[w.fromHex(e)]})}async createWarpTransferOwnershipTransaction(e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let r=y.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(r,{contract:y.newFromBech32(E(this.config.env)),function:"transferOwnership",gasLimit:BigInt(1e7),arguments:[w.fromHex(e),new ke(new y(t))]})}async createBrandRegisterTransaction(e){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=y.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(t,{contract:y.newFromBech32(E(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[w.fromHex(e)]})}async createWarpBrandingTransaction(e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let r=y.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(r,{contract:y.newFromBech32(E(this.config.env)),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[w.fromHex(e),w.fromHex(t)]})}async getInfoByAlias(e,t){try{let r=Fe.RegistryInfo(this.config.env,e),n=t?this.cache.get(r):null;if(n)return Oe.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${e}`),n;let a=y.newFromBech32(E(this.config.env)),i=this.getController(),o=i.createQuery({contract:a,function:"getInfoByAlias",arguments:[w.fromUTF8(e)]}),c=await i.runQuery(o),[d]=i.parseQueryResponse(c),m=d?pe(d):null,p=m?.brand?await this.fetchBrand(m.brand):null;return t&&t.ttl&&this.cache.set(r,{registryInfo:m,brand:p},t.ttl),{registryInfo:m,brand:p}}catch{return{registryInfo:null,brand:null}}}async getInfoByHash(e,t){try{let r=Fe.RegistryInfo(this.config.env,e);if(t){let p=this.cache.get(r);if(p)return Oe.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${e}`),p}let n=y.newFromBech32(E(this.config.env)),a=this.getController(),i=a.createQuery({contract:n,function:"getInfoByHash",arguments:[w.fromHex(e)]}),o=await a.runQuery(i),[c]=a.parseQueryResponse(o),d=c?pe(c):null,m=d?.brand?await this.fetchBrand(d.brand):null;return t&&t.ttl&&this.cache.set(r,{registryInfo:d,brand:m},t.ttl),{registryInfo:d,brand:m}}catch{return{registryInfo:null,brand:null}}}async getUserWarpRegistryInfos(e){try{let t=e||this.userWallet;if(!t)throw new Error("WarpRegistry: user address not set");let r=y.newFromBech32(E(this.config.env)),n=this.getController(),a=n.createQuery({contract:r,function:"getUserWarps",arguments:[new ke(new y(t))]}),i=await n.runQuery(a),[o]=n.parseQueryResponse(i);return o.map(pe)}catch{return[]}}async getUserBrands(e){try{let t=e||this.userWallet;if(!t)throw new Error("WarpRegistry: user address not set");let r=y.newFromBech32(E(this.config.env)),n=this.getController(),a=n.createQuery({contract:r,function:"getUserBrands",arguments:[new ke(new y(t))]}),i=await n.runQuery(a),[o]=n.parseQueryResponse(i),c=o.map(p=>p.toString("hex")),d={ttl:365*24*60*60};return(await Promise.all(c.map(p=>this.fetchBrand(p,d)))).filter(p=>p!==null)}catch{return[]}}async fetchBrand(e,t){let r=Fe.Brand(this.config.env,e),n=t?this.cache.get(r):null;if(n)return Oe.info(`WarpRegistry (fetchBrand): Brand found in cache: ${e}`),n;let i=W(this.chain,this.config.env,this.config).createNetworkProvider();try{let o=await i.getTransaction(e),c=JSON.parse(o.data.toString());return c.meta={query:null,chain:this.chain.name,identifier:Xr(this.chain.name,"hash",e),hash:o.hash,creator:o.sender.toBech32(),createdAt:new Date(o.timestamp*1e3).toISOString()},t&&t.ttl&&this.cache.set(r,c,t.ttl),c}catch{return null}}async loadRegistryConfigs(){let e=y.newFromBech32(E(this.config.env)),t=this.getController(),[r]=await t.query({contract:e,function:"getConfig",arguments:[]}),n=r?Pt(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let e=new Jr({chainID:this.chain.chainId}),t=It.create(Ue);return new jr({config:e,abi:t})}getController(){let e=W(this.chain,this.config.env,this.config),t=It.create(Ue);return e.createSmartContractController(t)}isCurrentUserAdmin(){return!!this.userWallet&&this.registryConfig.admins.includes(this.userWallet)}};import{Address as gn}from"@multiversx/sdk-core";import{CacheTtl as kt,initializeWalletCache as fn,WarpCache as yn}from"@joai/warps";import{Account as en,Message as tn,Mnemonic as Me,UserSecretKey as rn}from"@multiversx/sdk-core";import*as Nt from"@scure/bip39";import{wordlist as nn}from"@scure/bip39/wordlists/english.js";import{getWarpWalletAddressFromConfig as an,getWarpWalletMnemonicFromConfig as St,getWarpWalletPrivateKeyFromConfig as sn,normalizeAndValidateMnemonic as on,normalizeMnemonic as cn,setWarpWalletInConfig as Bt,validateMnemonicLength as ln}from"@joai/warps";var F=class F{constructor(e,t){this.config=e;this.chain=t;this.account=null}async getAddress(){let e=an(this.config,this.chain.name);if(e)return e;try{return this.getAccount().address.toBech32()}catch{return null}}async getPublicKey(){try{return this.getAccount().publicKey.hex()}catch{return null}}async signTransaction(e){let r=await this.getAccount().signTransaction(e);return e.signature=r,e}async signMessage(e){let t=this.getAccount(),r=new TextEncoder().encode(e),n=await t.signMessage(new tn({data:r}));return Buffer.from(n).toString("hex")}getAccountInstance(){return this.getAccount()}async importFromMnemonic(e){let t=on(e),n=Me.fromString(t).deriveKey(0),a=n.hex(),o=n.generatePublicKey().toAddress(this.chain.addressHrp).toBech32(),c={provider:F.PROVIDER_NAME,address:o,privateKey:a,mnemonic:t};return Bt(this.config,this.chain.name,c),c}async importFromPrivateKey(e){let t=rn.fromString(e),r=t.hex(),a=t.generatePublicKey().toAddress(this.chain.addressHrp).toBech32(),i={provider:F.PROVIDER_NAME,address:a,privateKey:r,mnemonic:null};return Bt(this.config,this.chain.name,i),i}async export(){let e=this.getAccount(),t=St(this.config,this.chain.name),r=sn(this.config,this.chain.name);return{provider:F.PROVIDER_NAME,address:e.address.toBech32(),privateKey:r||null,mnemonic:t||null}}async generate(){let e=Nt.generateMnemonic(nn,256),t=cn(e);ln(t);let i=Me.fromString(t).deriveKey(0).generatePublicKey().toAddress(this.chain.addressHrp).toBech32();return{provider:F.PROVIDER_NAME,address:i,privateKey:null,mnemonic:t}}getAccount(){if(this.account)return this.account;let e=St(this.config,this.chain.name);if(!e)throw new Error("No mnemonic provided");let r=Me.fromString(e).deriveKey(0);return this.account=new en(r),this.account}};F.PROVIDER_NAME="mnemonic";var D=F;import{Account as pn,Message as un,Mnemonic as mn,UserSecretKey as G}from"@multiversx/sdk-core";import{getWarpWalletAddressFromConfig as dn,getWarpWalletMnemonicFromConfig as hn,getWarpWalletPrivateKeyFromConfig as Vt,setWarpWalletInConfig as Ut}from"@joai/warps";var O=class O{constructor(e,t){this.config=e;this.chain=t;this.account=null}async getAddress(){let e=dn(this.config,this.chain.name);if(e)return e;try{return this.getAccount().address.toBech32()}catch{return null}}async getPublicKey(){try{return this.getAccount().publicKey.hex()}catch{return null}}async signTransaction(e){let r=await this.getAccount().signTransaction(e);return e.signature=r,e}async signMessage(e){let t=this.getAccount(),r=new TextEncoder().encode(e),n=await t.signMessage(new un({data:r}));return Buffer.from(n).toString("hex")}getAccountInstance(){return this.getAccount()}async importFromMnemonic(e){let r=mn.fromString(e).deriveKey(0),n=r.hex(),i=r.generatePublicKey().toAddress(this.chain.addressHrp).toBech32(),o={provider:O.PROVIDER_NAME,address:i,privateKey:n,mnemonic:e};return Ut(this.config,this.chain.name,o),o}async importFromPrivateKey(e){let r=e.startsWith("-----")?G.fromPem(e):G.fromString(e),n=r.hex(),i=r.generatePublicKey().toAddress(this.chain.addressHrp).toBech32(),o={provider:O.PROVIDER_NAME,address:i,privateKey:n,mnemonic:null};return Ut(this.config,this.chain.name,o),o}async export(){let e=this.getAccount(),t=Vt(this.config,this.chain.name),r=hn(this.config,this.chain.name);return{provider:O.PROVIDER_NAME,address:e.address.toBech32(),privateKey:t||null,mnemonic:r||null}}async generate(){let e=G.generate(),t=e.hex(),n=e.generatePublicKey().toAddress(this.chain.addressHrp).toBech32();return{provider:O.PROVIDER_NAME,address:n,privateKey:t,mnemonic:null}}getAccount(){if(this.account)return this.account;let e=Vt(this.config,this.chain.name);if(!e)throw new Error("No private key provided");let r=e.startsWith("-----")?G.fromPem(e):G.fromString(e);return this.account=new pn(r),this.account}};O.PROVIDER_NAME="privateKey";var L=O;import{getWarpWalletAddressFromConfig as z}from"@joai/warps";var K=class{constructor(e,t){this.config=e;this.chain=t}async getAddress(){return z(this.config,this.chain.name)}async getPublicKey(){return null}async signTransaction(e){let t=await this.getAddress();throw new Error(`Wallet can not be used for signing: ${t}`)}async signMessage(e){let t=await this.getAddress();throw new Error(`Wallet can not be used for signing: ${t}`)}async importFromMnemonic(e){let t=z(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${t}`)}async importFromPrivateKey(e){let t=z(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${t}`)}async export(){let e=z(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${e}`)}async generate(){let e=z(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${e}`)}};var me=class{constructor(e,t){this.config=e;this.chain=t;this.cachedAddress=null;this.cachedPublicKey=null;this.entry=W(t,e.env,e),this.cache=new yn(e.env,e.cache),this.walletProvider=this.createProvider(),this.initializeCache()}async signTransaction(e){let t=e;if(!t||typeof t!="object")throw new Error("Invalid transaction object");if(!this.walletProvider)throw new Error("No wallet provider available");if(this.walletProvider instanceof K)throw new Error(`Wallet (${this.chain.name}) is read-only`);if(this.walletProvider instanceof L||this.walletProvider instanceof D){let n=this.walletProvider.getAccountInstance();if(t.nonce===0n){let a=await this.entry.recallAccountNonce(n.address),i=this.cache.get(`nonce:${n.address.toBech32()}`)||0,o=BigInt(Math.max(i,Number(a)));t.nonce=o}}else if(t.nonce===0n&&this.cachedAddress){let n=gn.newFromBech32(this.cachedAddress),a=await this.entry.recallAccountNonce(n),i=this.cache.get(`nonce:${this.cachedAddress}`)||0,o=BigInt(Math.max(i,Number(a)));t.nonce=o}let r=await this.walletProvider.signTransaction(t);if(this.walletProvider instanceof L||this.walletProvider instanceof D){let n=this.walletProvider.getAccountInstance(),a=Number(n.nonce)+1;this.cache.set(`nonce:${n.address.toBech32()}`,a,kt.OneMinute)}else if(this.cachedAddress){let n=t.nonce?Number(t.nonce):0;this.cache.set(`nonce:${this.cachedAddress}`,n+1,kt.OneMinute)}return r}async signTransactions(e){let t=[];for(let r of e)t.push(await this.signTransaction(r));return t}async signMessage(e){if(!this.walletProvider)throw new Error("No wallet provider available");if(this.walletProvider instanceof K)throw new Error(`Wallet (${this.chain.name}) is read-only`);return await this.walletProvider.signMessage(e)}async sendTransactions(e){return Promise.all(e.map(async t=>this.sendTransaction(t)))}async sendTransaction(e){let t=e;if(!t||typeof t!="object")throw new Error("Invalid transaction object");if(!t.signature||t.signature.length===0)throw new Error("Transaction must be signed before sending");return await this.entry.sendTransaction(t)}async importFromMnemonic(e){return await this.createProviderForOperation("mnemonic").importFromMnemonic(e)}async importFromPrivateKey(e){return await this.createProviderForOperation("privateKey").importFromPrivateKey(e)}async export(e){return await this.createProviderForOperation(e).export()}async generate(e){return await this.createProviderForOperation(e).generate()}getAddress(){return this.cachedAddress}getPublicKey(){return this.cachedPublicKey}createProvider(){let e=this.config.user?.wallets?.[this.chain.name];return e?typeof e=="string"?new K(this.config,this.chain):this.createProviderForOperation(e.provider):null}initializeCache(){fn(this.walletProvider).then(e=>{this.cachedAddress=e.address,this.cachedPublicKey=e.publicKey})}createProviderForOperation(e){let r=this.config.walletProviders?.[this.chain.name]?.[e];if(r){let n=r(this.config,this.chain);if(!n)throw new Error(`Custom wallet provider factory returned null for ${e}`);return n}if(e==="privateKey")return new L(this.config,this.chain);if(e==="mnemonic")return new D(this.config,this.chain);throw new Error(`Unsupported wallet provider for ${this.chain.name}: ${e}`)}};var de=(s,e)=>(t,r)=>{let n=e[t.env],a=new vn;return a.registerType("token",{stringToNative:i=>i,nativeToString:i=>`token:${i}`}),a.registerType("codemeta",{stringToNative:i=>i,nativeToString:i=>`codemeta:${i}`}),a.registerTypeAlias("list","vector"),{chainInfo:n,builder:()=>new X(t,n),executor:new ce(t,n,a),output:new R(t,n,a),serializer:new B({typeRegistry:a}),registry:new ue(t,n),explorer:new le(s,t),abiBuilder:()=>new S(t,n),brandBuilder:()=>new J(t,n),dataLoader:new Z(t,n),wallet:new me(t,n)}};import{WarpChainName as q}from"@joai/warps";var Re={chain:q.Multiversx,identifier:"EGLD",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/tokens/logos/egld.svg"},Ft=de(q.Multiversx,{mainnet:{name:q.Multiversx,displayName:"MultiversX",chainId:"1",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://api.multiversx.com",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/multiversx.svg",nativeToken:Re},testnet:{name:q.Multiversx,displayName:"MultiversX Testnet",chainId:"T",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://testnet-api.multiversx.com",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/multiversx.svg",nativeToken:Re},devnet:{name:q.Multiversx,displayName:"MultiversX Devnet",chainId:"D",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://devnet-api.multiversx.com",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/multiversx.svg",nativeToken:Re}});import{WarpChainName as Le}from"@joai/warps";var Wn={chain:Le.Vibechain,identifier:"VIBE",name:"VIBE",symbol:"VIBE",decimals:18,logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/tokens/logos/vibe.svg"},De={name:Le.Vibechain,displayName:"VibeChain",chainId:"V",blockTime:600,addressHrp:"vibe",defaultApiUrl:"https://vibeox-api.multiversx.com",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/vibechain.svg",nativeToken:Wn},Ot=de(Le.Vibechain,{mainnet:De,testnet:De,devnet:De});var rc=()=>[Ft,Ot];import{WarpConstants as he,WarpSerializer as Ke}from"@joai/warps";var oc=s=>new Ke().nativeToString(f.Token,s),cc=s=>new Ke().nativeToString(f.CodeMeta,s),lc=(s,e)=>{if(e===null)return f.Optional+he.ArgParamsSeparator;let t=s(e),r=t.indexOf(he.ArgParamsSeparator),n=t.substring(0,r),a=t.substring(r+1);return f.Optional+he.ArgParamsSeparator+n+he.ArgParamsSeparator+a},pc=s=>new Ke().nativeToString(f.List,s);import{Address as wn,AddressValue as Tn,BigUIntType as Cn,BigUIntValue as Mt,BooleanValue as xn,BytesValue as An,CodeMetadata as En,CodeMetadataValue as bn,CompositeType as Pn,CompositeValue as In,Field as _e,FieldDefinition as He,List as Sn,NothingValue as Bn,OptionalValue as $e,OptionValue as Ge,StringValue as Nn,Struct as Vn,StructType as Un,TokenIdentifierType as kn,TokenIdentifierValue as Rt,U16Value as Fn,U32Value as On,U64Type as Mn,U64Value as Dt,U8Value as Rn,VariadicValue as Dn}from"@multiversx/sdk-core";var fc=(s,e)=>s?Ge.newProvided(s):e?Ge.newMissingTyped(e):Ge.newMissing(),yc=(s,e)=>s?new $e(s.getType(),s):e?new $e(e):$e.newMissing(),vc=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let e=s[0].getType();return new Sn(e,s)},Wc=s=>Dn.fromItems(...s),wc=s=>{let e=s.map(t=>t.getType());return new In(new Pn(...e),s)},Tc=s=>Nn.fromUTF8(s),Cc=s=>new Rn(s),xc=s=>new Fn(s),Ac=s=>new On(s),Ec=s=>new Dt(s),bc=s=>new Mt(BigInt(s)),Pc=s=>new xn(s),Ic=s=>new Tn(wn.newFromBech32(s)),Sc=s=>new Rt(s),Bc=s=>An.fromHex(s),Nc=s=>new Vn(new Un("EsdtTokenPayment",[new He("token_identifier","",new kn),new He("token_nonce","",new Mn),new He("amount","",new Cn)]),[new _e(new Rt(s.token.identifier),"token_identifier"),new _e(new Dt(BigInt(s.token.nonce)),"token_nonce"),new _e(new Mt(BigInt(s.amount)),"amount")]),Vc=s=>new bn(En.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),Uc=()=>new Bn;export{U as ExplorerUrls,ot as KnownTokens,Ft as MultiversxAdapter,Tr as MultiversxExplorers,lt as MultiversxExplorersConfig,Re as NativeTokenEgld,Wn as NativeTokenVibe,Ot as VibechainAdapter,Cr as VibechainExplorers,S as WarpMultiversxAbiBuilder,J as WarpMultiversxBrandBuilder,X as WarpMultiversxBuilder,wi as WarpMultiversxConstants,j as WarpMultiversxContractLoader,Z as WarpMultiversxDataLoader,ce as WarpMultiversxExecutor,le as WarpMultiversxExplorer,f as WarpMultiversxInputTypes,R as WarpMultiversxOutput,ue as WarpMultiversxRegistry,B as WarpMultiversxSerializer,me as WarpMultiversxWallet,Ic as address_value,Nc as asset_value,bc as biguint_value,Pc as boolean_value,cc as codemeta,Vc as codemeta_value,wc as composite_value,de as createMultiversxAdapter,ct as findKnownTokenById,rc as getAllMultiversxAdapters,Kn as getAllMultiversxChainNames,ni as getKnownTokensForChain,W as getMultiversxEntrypoint,E as getMultiversxRegistryAddress,Q as getNormalizedTokenIdentifier,Bc as hex_value,M as isNativeToken,pc as list,vc as list_value,Uc as nothing_value,fc as option_value,lc as optional,yc as optional_value,Tc as string_value,Pt as toTypedConfigInfo,pe as toTypedRegistryInfo,oc as token,Sc as token_value,xc as u16_value,Ac as u32_value,Ec as u64_value,Cc as u8_value,Wc as variadic_value};
1
+ import{WarpChainName as ze}from"@joai/warps";var Hn=()=>[ze.Multiversx,ze.Vibechain];import{WarpTypeRegistry as wn}from"@joai/warps";import{AbiRegistry as ge,Address as zt,TransactionsFactoryConfig as qt,TransferTransactionsFactory as Qt}from"@multiversx/sdk-core";import{createWarpIdentifier as jt,getLatestProtocolIdentifier as Jt,getWarpWalletAddressFromConfig as Xt,WarpCache as Yt,WarpCacheKey as Zt,WarpConstants as Qe,WarpLogger as je}from"@joai/warps";import{DevnetEntrypoint as _t,MainnetEntrypoint as Ht,TestnetEntrypoint as $t}from"@multiversx/sdk-core";import{getProviderConfig as Gt}from"@joai/warps";var R=s=>!s.includes("-"),Q=s=>R(s)?`${s}-000000`:s,v=(s,e,t)=>{let r="warp-sdk",a=t?Gt(t,s.name,e,s.defaultApiUrl):{url:s.defaultApiUrl},i=a.url,o={headers:a.headers};return e==="devnet"?new _t({url:i,kind:"api",clientName:r,networkProviderConfig:o}):e==="testnet"?new $t({url:i,kind:"api",clientName:r,networkProviderConfig:o}):new Ht({url:i,kind:"api",clientName:r,networkProviderConfig:o})};import{WarpLogger as qe}from"@joai/warps";var j=class{constructor(e){this.config=e}async getContract(e,t){try{let a=await v(t,this.config.env,this.config).createNetworkProvider().doGetGeneric(`accounts/${e}`);return{address:e,owner:a.ownerAddress,verified:a.isVerified||!1}}catch(r){return qe.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(e,t){try{let a=await v(t,this.config.env,this.config).createNetworkProvider().doGetGeneric(`accounts/${e}/verification`);return{codeHash:a.codeHash,abi:a.source.abi}}catch(r){return qe.error("WarpContractLoader: getVerificationInfo error",r),null}}};var S=class{constructor(e,t){this.config=e;this.chain=t;this.contractLoader=new j(this.config),this.cache=new Yt(this.config.env,this.config.cache)}async createInscriptionTransaction(e){let t=Xt(this.config,this.chain.name);if(!t)throw new Error("WarpBuilder: user address not set");let r=new qt({chainID:this.chain.chainId}),n=new Qt({config:r}),a=zt.newFromBech32(t),i={protocol:Jt("abi"),content:e},o=JSON.stringify(i),c=await n.createTransactionForTransfer(a,{receiver:a,nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(o))});return c.gasLimit=c.gasLimit+BigInt(2e6),c}async createFromRaw(e){return JSON.parse(e)}async createFromTransaction(e){let t=await this.createFromRaw(e.data.toString());return t.meta={chain:this.chain.name,identifier:jt(this.chain.name,"hash",e.hash),query:null,hash:e.hash,creator:e.sender.toBech32(),createdAt:new Date(e.timestamp*1e3).toISOString()},t}async createFromTransactionHash(e,t){let r=Zt.WarpAbi(this.config.env,e);if(t){let i=this.cache.get(r);if(i)return je.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${e}`),i}let a=v(this.chain,this.config.env,this.config).createNetworkProvider();try{let i=await a.getTransaction(e),o=await this.createFromTransaction(i);return t&&t.ttl&&o&&this.cache.set(r,o,t.ttl),o}catch(i){return je.error("WarpAbiBuilder: Error creating from transaction hash",i),null}}async getAbiForAction(e){if(e.abi)return await this.fetchAbi(e);if(!e.address)throw new Error("WarpActionExecutor: Address not found");let t=await this.contractLoader.getVerificationInfo(e.address,this.chain);if(!t)throw new Error("WarpActionExecutor: Verification info not found");return ge.create(t.abi)}async fetchAbi(e){if(!e.abi)throw new Error("WarpActionExecutor: ABI not found");if(e.abi.startsWith(Qe.IdentifierType.Hash)){let t=e.abi.split(Qe.ArgParamsSeparator)[1],r=await this.createFromTransactionHash(t);if(!r)throw new Error(`WarpActionExecutor: ABI not found for hash: ${e.abi}`);return ge.create(r.content)}else{let r=await(await fetch(e.abi)).json();return ge.create(r)}}};import{Address as Je,TransactionsFactoryConfig as er,TransferTransactionsFactory as tr}from"@multiversx/sdk-core";import{createWarpIdentifier as rr,getWarpWalletAddressFromConfig as nr,WarpBrandBuilder as ar,WarpLogger as ir}from"@joai/warps";import{Buffer as sr}from"buffer";var J=class{constructor(e,t){this.config=e;this.chain=t;this.core=new ar(e)}async createInscriptionTransaction(e){let t=nr(this.config,this.chain.name);if(!t)throw new Error("BrandBuilder: user address not set");let r=new er({chainID:this.chain.chainId}),n=new tr({config:r}),a=Je.newFromBech32(t),i=JSON.stringify(e);return await n.createTransactionForNativeTokenTransfer(a,{receiver:Je.newFromBech32(t),nativeAmount:BigInt(0),data:Uint8Array.from(sr.from(i))})}async createFromTransaction(e,t=!1){let r=await this.core.createFromRaw(e.data.toString(),t);return r.meta={query:null,chain:this.chain.name,identifier:rr(this.chain.name,"hash",e.hash),hash:e.hash,creator:e.sender.toBech32(),createdAt:new Date(e.timestamp*1e3).toISOString()},r}async createFromTransactionHash(e){let r=v(this.chain,this.config.env,this.config).createNetworkProvider();try{let n=await r.getTransaction(e);return this.createFromTransaction(n)}catch(n){return ir.error("BrandBuilder: Error creating from transaction hash",n),null}}};import{Address as Xe,TransactionsFactoryConfig as or,TransferTransactionsFactory as cr}from"@multiversx/sdk-core";import{createWarpIdentifier as lr,getWarpWalletAddressFromConfig as pr,WarpBuilder as Ye,WarpCache as ur,WarpCacheKey as mr,WarpLogger as Ze}from"@joai/warps";var X=class extends Ye{constructor(t,r){super(t);this.config=t;this.chain=r;this.cache=new ur(t.env,t.cache),this.core=new Ye(t)}async createInscriptionTransaction(t){let r=pr(this.config,this.chain.name);if(!r)throw new Error("WarpBuilder: user address not set");let n=new or({chainID:this.chain.chainId}),a=new cr({config:n}),i=Xe.newFromBech32(r),o=JSON.stringify(t),c=await a.createTransactionForTransfer(i,{receiver:Xe.newFromBech32(r),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(o))});return c.gasLimit=c.gasLimit+BigInt(2e6),c}async createFromTransaction(t,r=!1){let n=await this.core.createFromRaw(t.data.toString(),r);return n.meta={chain:this.chain.name,identifier:lr(this.chain.name,"hash",t.hash),query:null,hash:t.hash,creator:t.sender.toBech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},n}async createFromTransactionHash(t,r){let n=mr.Warp(this.config.env,t);if(r){let o=this.cache.get(n);if(o)return Ze.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),o}let i=v(this.chain,this.config.env,this.config).createNetworkProvider();try{let o=await i.getTransaction(t),c=await this.createFromTransaction(o);return r&&r.ttl&&c&&this.cache.set(n,c,r.ttl),c}catch(o){return Ze.error("WarpBuilder: Error creating from transaction hash",o),null}}};import{Address as fe,Token as yr,TokenComputer as Wr}from"@multiversx/sdk-core";import{CacheTtl as vr,WarpCache as wr,WarpCacheKey as Cr}from"@joai/warps";import{WarpChainName as st}from"@joai/warps";import{WarpChainName as dr}from"@joai/warps";var et=dr.Multiversx,tt=[{chain:et,identifier:"EGLD",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"},{chain:et,identifier:"EGLD-000000",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"}];import{WarpChainName as hr}from"@joai/warps";var x=hr.Multiversx,rt=[{chain:x,identifier:"EGLD",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"},{chain:x,identifier:"EGLD-000000",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"},{chain:x,identifier:"SEGLD-3ad2d0",name:"StakedEGLD",symbol:"SEGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/SEGLD-3ad2d0/icon.png"},{chain:x,identifier:"HSEGLD-c13a4e",name:"HatomSEGLD",symbol:"HSEGLD",decimals:8,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/HSEGLD-c13a4e/icon.png"},{chain:x,identifier:"UTK-2f80e9",name:"xMoney UTK",symbol:"UTK",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/UTK-2f80e9/icon.png"},{chain:x,identifier:"USDC-c76f1f",name:"WrappedUSDC",symbol:"USDC",decimals:6,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/USDC-c76f1f/icon.png"},{chain:x,identifier:"WEGLD-bd4d79",name:"WrappedEGLD",symbol:"WEGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/WEGLD-bd4d79/icon.png"},{chain:x,identifier:"HTM-f51d55",name:"Hatom",symbol:"HTM",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/HTM-f51d55/icon.png"},{chain:x,identifier:"MEX-455c57",name:"MEX",symbol:"MEX",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/MEX-455c57/icon.png"},{chain:x,identifier:"WTAO-4f5363",name:"WrappedTAO",symbol:"WTAO",decimals:9,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/WTAO-4f5363/icon.png"},{chain:x,identifier:"HEGLD-d61095",name:"HatomEGLD",symbol:"HEGLD",decimals:8,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/HEGLD-d61095/icon.png"},{chain:x,identifier:"WBTC-5349b3",name:"WrappedBTC",symbol:"WBTC",decimals:8,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/WBTC-5349b3/icon.png"},{chain:x,identifier:"WETH-b4ca29",name:"WrappedETH",symbol:"WETH",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/WETH-b4ca29/icon.png"},{chain:x,identifier:"USH-111e09",name:"HatomUSD",symbol:"USH",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/USH-111e09/icon.png"},{chain:x,identifier:"USDT-f8c08c",name:"WrappedUSDT",symbol:"USDT",decimals:6,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/USDT-f8c08c/icon.png"}];import{WarpChainName as gr}from"@joai/warps";var nt=gr.Multiversx,at=[{chain:nt,identifier:"EGLD",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"},{chain:nt,identifier:"EGLD-000000",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://tools.multiversx.com/assets-cdn/tokens/EGLD-000000/icon.png"}];import{WarpChainName as fr}from"@joai/warps";var it=fr.Vibechain,Y=[{chain:it,identifier:"VIBE",name:"VIBE",symbol:"VIBE",decimals:18,logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/tokens/logos/vibe.svg"},{chain:it,identifier:"VIBE-000000",name:"VIBE",symbol:"VIBE",decimals:18,logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/tokens/logos/vibe.svg"}];var ot={[st.Multiversx]:{mainnet:rt,testnet:at,devnet:tt},[st.Vibechain]:{mainnet:Y,testnet:Y,devnet:Y}},ct=(s,e,t)=>(ot[s]?.[e]||[]).find(n=>n.identifier===t)||null,ii=(s,e)=>ot[s]?.[e]||[];var Z=class{constructor(e,t){this.config=e;this.chain=t;this.cache=new wr(e.env,e.cache)}async getAccount(e){let r=await v(this.chain,this.config.env,this.config).createNetworkProvider().getAccount(fe.newFromBech32(e));return{chain:this.chain.name,address:r.address.toBech32(),balance:r.balance}}async getAccountAssets(e){let t=v(this.chain,this.config.env,this.config).createNetworkProvider(),r=t.getAccount(fe.newFromBech32(e)),n=t.getFungibleTokensOfAccount(fe.newFromBech32(e)),[a,i]=await Promise.all([r,n]),o=a.balance>0?[{...this.chain.nativeToken,amount:a.balance}]:[];return o.push(...i.map(c=>({chain:this.chain.name,identifier:c.token.identifier,name:c.raw.name,symbol:c.raw.ticker,amount:c.amount,decimals:c.raw.decimals,logoUrl:c.raw.assets?.pngUrl||"",price:c.raw.price?Number(c.raw.price):void 0,supply:c.raw.supply?BigInt(c.raw.supply):void 0}))),o}async getAsset(e){let t=Cr.Asset(this.config.env,this.chain.name,e),r=this.cache.get(t);if(r)return r;let n=ct(this.chain.name,this.config.env,e);if(n)return{chain:this.chain.name,identifier:e,name:n.name,symbol:n.symbol,amount:0n,decimals:n.decimals,logoUrl:n.logoUrl};let a=new Wr,i=R(e)?0n:a.extractNonceFromExtendedIdentifier(e),o=new yr({identifier:e,nonce:BigInt(i||0)}),c=a.isFungible(o),d=v(this.chain,this.config.env,this.config).createNetworkProvider(),m=Q(e),p=await d.doGetGeneric(`tokens/${m}`),W={chain:this.chain.name,identifier:o.identifier,name:p.name,symbol:p.ticker,amount:0n,decimals:p.decimals,logoUrl:p.assets?.pngUrl||null,price:p.price?Number(p.price):void 0,supply:p.supply?BigInt(p.supply):void 0};return this.cache.set(t,W,vr.OneHour),W}async getAction(e,t=!1){let r=v(this.chain,this.config.env,this.config),n=t?await r.awaitCompletedTransaction(e):await r.getTransaction(e);return{chain:this.chain.name,id:n.hash,receiver:n.receiver.toBech32(),sender:n.sender.toBech32(),value:n.value,function:n.function,status:this.toActionStatus(n),createdAt:this.toActionCreatedAt(n),error:n?.smartContractResults.map(a=>a.raw.returnMessage)[0]||null,tx:n}}async getAccountActions(e,t){let r=v(this.chain,this.config.env,this.config).createNetworkProvider(),n=`accounts/${e}/transactions`,a=new URLSearchParams,i=t?.size||25,o=t?.page||0;if(o>0){let d=o*i;a.append("from",d.toString())}return i!==25&&a.append("size",i.toString()),a.toString()&&(n+=`?${a.toString()}`),(await r.doGetGeneric(n)).map(d=>({chain:this.chain.name,id:d.txHash,receiver:d.receiver,sender:d.sender,value:d.value,function:d.function,status:this.toActionStatus(d),createdAt:this.toActionCreatedAt(d)}))}toActionStatus(e){return e.status?.isSuccessful?.()?"success":e.status?.isFailed?.()?"failed":"pending"}toActionCreatedAt(e){return new Date(e.timestamp||e.timestamp*1e3).toISOString()}};import{Address as $,ArgSerializer as Lr,SmartContractTransactionsFactory as Kr,Token as _r,TokenComputer as Hr,TokenTransfer as $r,TransactionsFactoryConfig as Pt,TransferTransactionsFactory as Gr}from"@multiversx/sdk-core";import{applyOutputToMessages as zr,extractResolvedInputValues as qr,getNextInfo as Qr,getWarpActionByIndex as Ne,getWarpWalletAddressFromConfig as Ve}from"@joai/warps";import{findEventsByFirstTopic as Br,SmartContractTransactionsOutcomeParser as Nr,TransactionEventsParser as Vr}from"@multiversx/sdk-core";import{applyOutputToMessages as Ur,evaluateOutputCommon as oe,extractResolvedInputValues as Fr,getNextInfo as kr,getWarpActionByIndex as Mr,getWarpWalletAddressFromConfig as Or,parseOutputOutIndex as Et,WarpCache as Rr,WarpCacheKey as Dr,WarpConstants as bt}from"@joai/warps";import{Address as Er,AddressType as ye,AddressValue as ut,BigUIntType as ee,BigUIntValue as We,BooleanType as ve,BooleanValue as mt,BytesType as we,BytesValue as dt,CodeMetadata as br,CodeMetadataType as Ce,CodeMetadataValue as ht,CompositeType as Te,CompositeValue as gt,Field as te,FieldDefinition as re,List as ft,ListType as yt,NothingValue as b,OptionalType as Wt,OptionalValue as xe,OptionType as vt,OptionValue as Ae,StringType as Ee,StringValue as wt,Struct as ne,StructType as F,Token as Pr,TokenComputer as Ct,TokenIdentifierType as ae,TokenIdentifierValue as be,U16Type as Pe,U16Value as Tt,U32Type as Ie,U32Value as xt,U64Type as ie,U64Value as Se,U8Type as Be,U8Value as At,VariadicType as H,VariadicValue as se}from"@multiversx/sdk-core";import{WarpSerializer as Ir}from"@joai/warps";var Tr=s=>s?typeof s=="string"?s:s.address:null,lt=(s,e)=>Tr(s.user?.wallets?.[e]||null);var u={HttpProtocolPrefix:"https://",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierChainDefault:"multiversx",IdentifierType:{Alias:"alias",Hash:"hash"},IdentifierAliasMarker:"@",Globals:{UserWallet:{Placeholder:"USER_WALLET",Accessor:s=>lt(s.config,s.adapter.chainInfo.name)},UserWalletPublicKey:{Placeholder:"USER_WALLET_PUBLICKEY",Accessor:s=>{if(!s.adapter.wallet)return null;try{return s.adapter.wallet.getPublicKey()||null}catch{return null}}},ChainApiUrl:{Placeholder:"CHAIN_API",Accessor:s=>s.adapter.chainInfo.defaultApiUrl},ChainAddressHrp:{Placeholder:"CHAIN_ADDRESS_HRP",Accessor:s=>s.adapter.chainInfo.addressHrp}},Vars:{Query:"query",Env:"env"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",ArgListSeparator:",",ArgStructSeparator:";",Transform:{Prefix:"transform:"},Source:{UserWallet:"user:wallet"},Position:{Payload:"payload:"},Alerts:{TriggerEventPrefix:"event"}},l={Option:"option",Vector:"vector",Tuple:"tuple",Struct:"struct",String:"string",Uint8:"uint8",Uint16:"uint16",Uint32:"uint32",Uint64:"uint64",Uint128:"uint128",Uint256:"uint256",Biguint:"biguint",Bool:"bool",Address:"address",Asset:"asset",Hex:"hex"};var Ai={Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}},f={Null:"null",Optional:"optional",List:"list",Token:"token",CodeMeta:"codemeta"},xr=(r=>(r.MultiversxExplorer="multiversx_explorer",r.MultiversxExplorerDevnet="multiversx_explorer_devnet",r.MultiversxExplorerTestnet="multiversx_explorer_testnet",r))(xr||{}),Ar=(r=>(r.VibechainExplorer="vibechain_explorer",r.VibechainExplorerDevnet="vibechain_explorer_devnet",r.VibechainExplorerTestnet="vibechain_explorer_testnet",r))(Ar||{}),pt={multiversx:{mainnet:["multiversx_explorer"],testnet:["multiversx_explorer_testnet"],devnet:["multiversx_explorer_devnet"]},vibechain:{mainnet:["vibechain_explorer"],testnet:["vibechain_explorer_testnet"],devnet:["vibechain_explorer_devnet"]}},U={multiversx_explorer:"https://explorer.multiversx.com",multiversx_explorer_devnet:"https://devnet-explorer.multiversx.com",multiversx_explorer_testnet:"https://testnet-explorer.multiversx.com",vibechain_explorer:"https://vibeox-explorer.multiversx.com",vibechain_explorer_devnet:"https://vibeox-explorer.multiversx.com",vibechain_explorer_testnet:"https://vibeox-explorer.multiversx.com"};var Sr=new RegExp(`${u.ArgParamsSeparator}(.*)`),B=class{constructor(e){this.coreSerializer=new Ir(e)}typedToString(e){let t=e.getType();if(t.hasExactClass(vt.ClassName)||e.hasClassOrSuperclass(Ae.ClassName)){if(!e.isSet())return l.Option+u.ArgParamsSeparator+"null";let r=this.typedToString(e.getTypedValue());return l.Option+u.ArgParamsSeparator+r}if(t.hasExactClass(H.ClassName)||e.hasClassOrSuperclass(se.ClassName)){let r=e.getItems();if(r.length===0){let m=this.typeToString(t.getFirstTypeParameter());return l.Vector+u.ArgParamsSeparator+m+u.ArgParamsSeparator}let n=r.map(m=>this.typedToString(m));if(n.every(m=>m.startsWith(l.Tuple)))return l.Vector+u.ArgParamsSeparator+n.join(",");let a=n[0],i=a.indexOf(u.ArgParamsSeparator),o=a.substring(0,i),c=n.map(m=>{let p=m.indexOf(u.ArgParamsSeparator);return m.substring(p+1)}),d=o.startsWith(l.Struct)?u.ArgStructSeparator:u.ArgListSeparator;return l.Vector+u.ArgParamsSeparator+o+u.ArgParamsSeparator+c.join(d)}if(t.hasExactClass(Wt.ClassName)||e.hasClassOrSuperclass(xe.ClassName)){if(!e.isSet())return f.Optional+u.ArgParamsSeparator+"null";let r=this.typedToString(e.getTypedValue());return f.Optional+u.ArgParamsSeparator+r}if(t.hasExactClass(yt.ClassName)||e.hasClassOrSuperclass(ft.ClassName)){let n=e.getItems().map(c=>this.typedToString(c));if(n.every(c=>c.startsWith(l.Tuple)))return f.List+u.ArgParamsSeparator+n.join(",");let i=n.map(c=>c.split(u.ArgParamsSeparator)[0])[0],o=n.map(c=>c.split(u.ArgParamsSeparator)[1]);return f.List+u.ArgParamsSeparator+i+u.ArgParamsSeparator+o.join(u.ArgListSeparator)}if(t.hasExactClass(Te.ClassName)||e.hasClassOrSuperclass(gt.ClassName)){let n=e.getItems().map(a=>{let i=this.typedToString(a),o=i.indexOf(u.ArgParamsSeparator),c=i.substring(0,o),d=i.substring(o+1);return`${c},${d}`});return`${l.Tuple}(${n.join(",")})`}if(t.hasExactClass(ee.ClassName)||e.hasClassOrSuperclass(We.ClassName)||t.getName()==="BigUint")return l.Biguint+u.ArgParamsSeparator+BigInt(e.valueOf().toFixed());if(t.hasExactClass(Be.ClassName)||e.hasClassOrSuperclass(At.ClassName))return l.Uint8+u.ArgParamsSeparator+e.valueOf().toNumber();if(t.hasExactClass(Pe.ClassName)||e.hasClassOrSuperclass(Tt.ClassName))return l.Uint16+u.ArgParamsSeparator+e.valueOf().toNumber();if(t.hasExactClass(Ie.ClassName)||e.hasClassOrSuperclass(xt.ClassName))return l.Uint32+u.ArgParamsSeparator+e.valueOf().toNumber();if(t.hasExactClass(ie.ClassName)||e.hasClassOrSuperclass(Se.ClassName))return l.Uint64+u.ArgParamsSeparator+BigInt(e.valueOf().toFixed());if(t.hasExactClass(Ee.ClassName)||e.hasClassOrSuperclass(wt.ClassName))return l.String+u.ArgParamsSeparator+e.valueOf();if(t.hasExactClass(ve.ClassName)||e.hasClassOrSuperclass(mt.ClassName))return l.Bool+u.ArgParamsSeparator+e.valueOf();if(t.hasExactClass(ye.ClassName)||e.hasClassOrSuperclass(ut.ClassName))return l.Address+u.ArgParamsSeparator+e.valueOf().toBech32();if(t.hasExactClass(we.ClassName)||e.hasClassOrSuperclass(dt.ClassName))return l.Hex+u.ArgParamsSeparator+e.valueOf().toString("hex");if(t.getName()==="EsdtTokenPayment"){let r=e.getFieldValue("token_identifier").valueOf(),n=e.getFieldValue("token_nonce").valueOf(),a=e.getFieldValue("amount").valueOf(),o=new Ct().computeExtendedIdentifier(new Pr({identifier:r,nonce:BigInt(n)}));return l.Asset+u.ArgParamsSeparator+o+u.ArgCompositeSeparator+a}if(t.hasExactClass(F.ClassName)||e.hasClassOrSuperclass(ne.ClassName)){let r=e,a=r.getType().getName(),i=r.getFields();if(i.length===0)return`${l.Struct}(${a})${u.ArgParamsSeparator}`;let o=i.map(c=>{let d=c.value.getType(),p=this.typedToString(c.value).split(u.ArgParamsSeparator),W=p.length>2?p.slice(2).join(u.ArgParamsSeparator):p[1]||"";return`(${c.name}${u.ArgParamsSeparator}${this.typeToString(d)})${W}`});return`${l.Struct}(${a})${u.ArgParamsSeparator}${o.join(u.ArgListSeparator)}`}if(t.hasExactClass(ae.ClassName)||e.hasClassOrSuperclass(be.ClassName))return f.Token+u.ArgParamsSeparator+e.valueOf();if(t.hasExactClass(Ce.ClassName)||e.hasClassOrSuperclass(ht.ClassName))return f.CodeMeta+u.ArgParamsSeparator+e.valueOf().toString();throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${e.getClassName()}`)}typedToNative(e){let t=this.typedToString(e);return this.coreSerializer.stringToNative(t)}nativeToTyped(e,t){if(e.startsWith(l.Tuple))return this.stringToTyped(e+":");let r=this.coreSerializer.nativeToString(e,t);return this.stringToTyped(r)}nativeToType(e){if(e.startsWith(l.Tuple)){let t=e.match(/\(([^)]+)\)/)?.[1];if(!t)throw new Error(`Invalid tuple type format: ${e}`);let r=t.split(","),n=[];for(let a=0;a<r.length;a+=2)n.push(r[a]);return new Te(...n.map(a=>this.nativeToType(a)))}if(e.startsWith(l.Struct)){let t=e.match(/\(([^)]+)\)/);if(!t)throw new Error("Struct type must include a name in the format struct(Name)");let r=t[1];return new F(r,[])}if(e===l.String)return new Ee;if(e===l.Uint8)return new Be;if(e===l.Uint16)return new Pe;if(e===l.Uint32)return new Ie;if(e===l.Uint64)return new ie;if(e===l.Biguint)return new ee;if(e===l.Bool)return new ve;if(e===l.Address)return new ye;if(e===l.Hex)return new we;if(e===l.Asset)return new F("EsdtTokenPayment",[new re("token_identifier","",new ae),new re("token_nonce","",new ie),new re("amount","",new ee)]);if(e===f.Token)return new ae;if(e===f.CodeMeta)return new Ce;throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${e}`)}stringToTyped(e){let[t,r]=e.split(/:(.*)/,2);if(t===l.Option){let n=this.stringToTyped(r);return n instanceof b?Ae.newMissingTyped(n.getType()):Ae.newProvided(n)}if(t===l.Vector){let n=r.indexOf(u.ArgParamsSeparator),a=r.substring(0,n),i=r.substring(n+1);if(a.startsWith(l.Tuple)){let p=i.split(",").map(W=>this.stringToTyped(W));return new se(new H(this.nativeToType(a)),p)}if(i.includes("tuple(")){let m=this.splitTupleStrings(i),p=m.map(C=>this.stringToTyped(C)),T=m[0].match(/^(tuple\([^)]+\))/),h=T?T[1]:"tuple";return new se(new H(this.nativeToType(h)),p)}let o=a.startsWith(l.Struct)?u.ArgStructSeparator:u.ArgListSeparator,d=i.split(o).map(m=>this.stringToTyped(`${a}:${m}`));return new se(new H(this.nativeToType(a)),d)}if(t.startsWith(l.Tuple)){let n=t.match(/\(([^)]+)\)/)?.[1];if(!n)throw new Error(`Invalid tuple format: ${t}`);let a=n.split(","),i=[];for(let c=0;c<a.length;c+=2){let d=a[c],m=a[c+1];i.push(this.stringToTyped(`${d}:${m}`))}let o=i.map(c=>c.getType());return new gt(new Te(...o),i)}if(t.startsWith(l.Struct)){let n=t.match(/\(([^)]+)\)/),a=n?n[1]:"CustomStruct";if(!r)return new ne(new F(a,[]),[]);let i=r.split(u.ArgListSeparator),o=[],c=[];return i.forEach(d=>{let m=d.match(new RegExp(`^\\(([^${u.ArgParamsSeparator}]+)${u.ArgParamsSeparator}([^)]+)\\)(.+)$`));if(m){let[,p,W,T]=m,h=this.stringToTyped(`${W}${u.ArgParamsSeparator}${T}`);o.push(new re(p,"",h.getType())),c.push(new te(h,p))}}),new ne(new F(a,o),c)}if(t===l.String)return r?wt.fromUTF8(r):new b;if(t===l.Uint8)return r?new At(Number(r)):new b;if(t===l.Uint16)return r?new Tt(Number(r)):new b;if(t===l.Uint32)return r?new xt(Number(r)):new b;if(t===l.Uint64)return r?new Se(BigInt(r)):new b;if(t===l.Biguint)return r?new We(BigInt(r)):new b;if(t===l.Bool)return r?new mt(typeof r=="boolean"?r:r==="true"):new b;if(t===l.Address)return r?new ut(Er.newFromBech32(r)):new b;if(t===l.Hex)return r?dt.fromHex(r):new b;if(t===l.Asset){let[n,a]=r.split(u.ArgCompositeSeparator),i=new Ct,o=R(n)?Q(n):i.extractIdentifierFromExtendedIdentifier(n),c=R(n)?0n:i.extractNonceFromExtendedIdentifier(n);return new ne(this.nativeToType("asset"),[new te(new be(o),"token_identifier"),new te(new Se(BigInt(c)),"token_nonce"),new te(new We(BigInt(a)),"amount")])}if(t===f.Null)return new b;if(t===f.Optional){let n=this.stringToTyped(r);return n instanceof b?xe.newMissing():new xe(n.getType(),n)}if(t===f.List){let[n,a]=r.split(Sr,2),o=a.split(u.ArgListSeparator).map(c=>this.stringToTyped(n+u.ArgParamsSeparator+c));return new ft(this.nativeToType(n),o)}if(t===f.Token)return r?new be(r):new b;if(t===f.CodeMeta)return new ht(br.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${t}`)}splitTupleStrings(e){let t=[],r="",n=0;for(let a=0;a<e.length;a++){let i=e[a];if(i==="(")n++;else if(i===")")n--;else if(i===","&&n===0){t.push(r.trim()),r="";continue}r+=i}return r.trim()&&t.push(r.trim()),t}typeToString(e){if(e.hasExactClass(vt.ClassName))return l.Option+u.ArgParamsSeparator+this.typeToString(e.getFirstTypeParameter());if(e.hasExactClass(H.ClassName))return l.Vector+u.ArgParamsSeparator+this.typeToString(e.getFirstTypeParameter());if(e.hasExactClass(Ee.ClassName))return l.String;if(e.hasExactClass(Be.ClassName))return l.Uint8;if(e.hasExactClass(Pe.ClassName))return l.Uint16;if(e.hasExactClass(Ie.ClassName))return l.Uint32;if(e.hasExactClass(ie.ClassName))return l.Uint64;if(e.hasExactClass(ee.ClassName))return l.Biguint;if(e.hasExactClass(ve.ClassName))return l.Bool;if(e.hasExactClass(ye.ClassName))return l.Address;if(e.hasExactClass(we.ClassName))return l.Hex;if(e.hasExactClass(ae.ClassName))return f.Token;if(e.hasExactClass(Wt.ClassName))return f.Optional+u.ArgParamsSeparator+this.typeToString(e.getFirstTypeParameter());if(e.hasExactClass(yt.ClassName))return f.List+u.ArgParamsSeparator+this.typeToString(e.getFirstTypeParameter());if(e.hasExactClass(Ce.ClassName))return f.CodeMeta;if(e.hasExactClass(F.ClassName)&&e.getClassName()==="EsdtTokenPayment")return l.Asset;if(e.hasExactClass(F.ClassName))return`${l.Struct}(${e.getName()})`;throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${e.getClassName()}`)}};var D=class{constructor(e,t,r){this.config=e;this.chain=t;this.typeRegistry=r;this.abi=new S(e,t),this.serializer=new B({typeRegistry:this.typeRegistry}),this.cache=new Rr(e.env,e.cache)}async getActionExecution(e,t,r){let n=this.cache.get(Dr.WarpExecutable(this.config.env,e.meta?.hash||"",t))??[],a=await this.extractContractOutput(e,t,r,n),i=kr(this.config,[],e,t,a.output),o=Ur(e,a.output,this.config),c=Fr(n);return{status:r.status?.isSuccessful?.()?"success":"error",warp:e,action:t,user:Or(this.config,this.chain.name),txHash:r.hash,tx:r,next:i,values:a.values,output:a.output,messages:o,destination:null,resolvedInputs:c}}async extractContractOutput(e,t,r,n){let a=Mr(e,t),i=[],o=[],c={};if(!e.output||a.type!=="contract")return{values:{string:i,native:o,mapped:{}},output:c};if(!Object.values(e.output).some(h=>h.includes("out")||h.includes("event"))){for(let[h,C]of Object.entries(e.output))c[h]=C;return{values:{string:i,native:o,mapped:{}},output:await oe(e,c,t,n,this.serializer.coreSerializer,this.config)}}let m=await this.abi.getAbiForAction(a),p=new Vr({abi:m}),T=new Nr({abi:m}).parseExecute({transactionOnNetwork:r,function:a.func||void 0});for(let[h,C]of Object.entries(e.output)){if(C.startsWith(bt.Transform.Prefix))continue;if(C.startsWith("input.")){c[h]=C;continue}let A=Et(C);if(A!==null&&A!==t){c[h]=null;continue}let[P,N,V]=C.split(".");if(P==="event"){if(!N||isNaN(Number(V)))continue;let I=Number(V),g=Br(r,N),Kt=p.parseEvents({events:g})[0],_=Object.values(Kt)[I]||null;i.push(String(_)),o.push(_),c[h]=_&&_.valueOf()}else if(P==="out"||P.startsWith("out[")){if(!N)continue;let I=Number(N),g=T.values[I-1]||null;V&&(g=g[V]||null),g&&typeof g=="object"&&(g="toFixed"in g?g.toFixed():g.valueOf()),i.push(String(g)),o.push(g),c[h]=g&&g.valueOf()}else c[h]=C}return{values:{string:i,native:o,mapped:{}},output:await oe(e,c,t,n,this.serializer.coreSerializer,this.config)}}async extractQueryOutput(e,t,r,n){let a=t.map(m=>this.serializer.typedToString(m)),i=t.map(m=>this.serializer.typedToNative(m)[1]),o={string:a,native:i,mapped:{}},c={};if(!e.output)return{values:o,output:c};let d=m=>{let p=m.split(".").slice(1).map(T=>parseInt(T)-1);if(p.length===0)return;let W=i[p[0]];for(let T=1;T<p.length;T++){if(W==null)return;W=W[p[T]]}return W};for(let[m,p]of Object.entries(e.output)){if(p.startsWith(bt.Transform.Prefix))continue;let W=Et(p);if(W!==null&&W!==r){c[m]=null;continue}p.startsWith("out.")||p==="out"||p.startsWith("out[")?c[m]=d(p)||null:c[m]=p}return c=await oe(e,c,r,n,this.serializer.coreSerializer,this.config),{values:o,output:c}}async resolveWarpOutputRecursively(e){let t=e.warp,r=e.entryActionIndex,n=e.executor,a=e.inputs,i=e.meta,o=new Map,c=new Set,d=this;async function m(h,C=[]){if(o.has(h))return o.get(h);if(c.has(h))throw new Error(`Circular dependency detected at action ${h}`);c.add(h);let A=t.actions[h-1];if(!A)throw new Error(`Action ${h} not found`);let P;if(A.type==="query")P=await n.executeQuery(t,h,C);else if(A.type==="collect")P=await n.executeCollect(t,h,C,i);else throw new Error(`Unsupported or interactive action type: ${A.type}`);if(o.set(h,P),t.output)for(let N of Object.values(t.output)){let I=String(N).match(/^out\[(\d+)\]/);if(I){let g=parseInt(I[1],10);g!==h&&!o.has(g)&&await m(g)}}return c.delete(h),P}await m(r,a);let p={};for(let h of o.values())for(let[C,A]of Object.entries(h.output))A!==null?p[C]=A:C in p||(p[C]=null);let W=await oe(t,p,r,a,this.serializer.coreSerializer,this.config);return{...o.get(r),action:r,output:W}}};var jr="EGLD-000000",ce=class{constructor(e,t,r){this.config=e;this.chain=t;this.typeRegistry=r;this.serializer=new B({typeRegistry:this.typeRegistry}),this.abi=new S(this.config,this.chain),this.output=new D(this.config,this.chain,this.typeRegistry)}async createTransaction(e){let t=Ne(e.warp,e.action),r=null;if(t.type==="transfer")r=await this.createTransferTransaction(e);else if(t.type==="contract")r=await this.createContractCallTransaction(e);else{if(t.type==="query")throw new Error("WarpMultiversxExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead");if(t.type==="collect")throw new Error("WarpMultiversxExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead")}if(!r)throw new Error(`WarpMultiversxExecutor: Invalid action type (${t.type})`);return r}async createTransferTransaction(e){if(!e.destination)throw new Error("WarpMultiversxExecutor: createTransfer - destination not set");let t=Ve(this.config,e.chain.name);if(!t)throw new Error("WarpMultiversxExecutor: createTransfer - user address not set");let r=$.newFromBech32(t),n=new Pt({chainID:e.chain.chainId}),a=e.data?Buffer.from(this.serializer.stringToTyped(e.data).valueOf()):null,i=e.transfers.length===1&&e.transfers[0].identifier===this.chain.nativeToken?.identifier,c=(i?e.transfers[0].amount:0n)+e.value;return await new Gr({config:n}).createTransactionForTransfer(r,{receiver:$.newFromBech32(e.destination),nativeAmount:c,tokenTransfers:i?[]:this.toTokenTransfers(e.transfers),data:a?new Uint8Array(a):void 0})}async createContractCallTransaction(e){if(!e.destination)throw new Error("WarpMultiversxExecutor: createContractCall - destination not set");let t=Ve(this.config,e.chain.name);if(!t)throw new Error("WarpMultiversxExecutor: createContractCall - user address not set");let r=Ne(e.warp,e.action),n=$.newFromBech32(t),a=e.args.map(o=>this.serializer.stringToTyped(o)),i=new Pt({chainID:e.chain.chainId});return new Kr({config:i}).createTransactionForExecute(n,{contract:$.newFromBech32(e.destination),function:"func"in r&&r.func||"",gasLimit:"gasLimit"in r?BigInt(r.gasLimit||0):0n,arguments:a,tokenTransfers:this.toTokenTransfers(e.transfers),nativeTransferAmount:e.value})}async executeQuery(e){if(!e.destination)throw new Error("WarpMultiversxExecutor: executeQuery - destination not set");let t=Ne(e.warp,e.action);if(t.type!=="query")throw new Error(`WarpMultiversxExecutor: Invalid action type for executeQuery: ${t.type}`);let r=await this.abi.getAbiForAction(t),n=e.args.map(g=>this.serializer.stringToTyped(g)),a=v(e.chain,this.config.env,this.config),i=$.newFromBech32(e.destination),o=a.createSmartContractController(r),c=o.createQuery({contract:i,function:t.func||"",arguments:n}),d=await o.runQuery(c),m=d.returnCode==="ok",p=new Lr,W=r.getEndpoint(d.function||t.func||""),T=(d.returnDataParts||[]).map(g=>Buffer.from(g)),h=p.buffersToValues(T,W.output),{values:C,output:A}=await this.output.extractQueryOutput(e.warp,h,e.action,e.resolvedInputs),P=Qr(this.config,[],e.warp,e.action,A),V=e.resolvedInputs.find(g=>g.input.position==="receiver"||g.input.position==="destination")?.value||e.destination,I=qr(e.resolvedInputs);return{status:m?"success":"error",warp:e.warp,action:e.action,user:Ve(this.config,e.chain.name),txHash:null,tx:null,next:P,values:C,output:{...A,_DATA:h},messages:zr(e.warp,A,this.config),destination:V,resolvedInputs:I}}toTokenTransfers(e){return e.map(t=>t.identifier===this.chain.nativeToken.identifier?{...t,identifier:jr}:t).map(t=>{let n=new Hr().extractNonceFromExtendedIdentifier(t.identifier);return new $r({token:new _r({identifier:t.identifier,nonce:BigInt(n||0)}),amount:t.amount})})}};var le=class{constructor(e,t){this.chain=e;this.config=t}getExplorers(){let e=pt[this.chain];if(!e)return["multiversx_explorer"];let t=e[this.config.env];return t||["multiversx_explorer"]}getPrimaryExplorer(){return this.getExplorers()[0]}getExplorerUrlByName(e){let t=this.config.preferences?.explorers?.[this.chain];if(t&&!e){let a=U[t];if(a)return a}if(e){let a=U[e];if(a)return a}let r=this.getPrimaryExplorer();return U[r]||U[r]}getAccountUrl(e,t){return`${this.getExplorerUrlByName(t)}/accounts/${e}`}getTransactionUrl(e,t){return`${this.getExplorerUrlByName(t)}/transactions/${e}`}getBlockUrl(e,t){return`${this.getExplorerUrlByName(t)}/blocks/${e}`}getAssetUrl(e,t){return`${this.getExplorerUrlByName(t)}/tokens/${e}`}getContractUrl(e,t){return`${this.getExplorerUrlByName(t)}/accounts/${e}`}getAllExplorers(){return this.getExplorers()}getExplorerByName(e){return this.getExplorers().find(r=>r.toLowerCase()===e.toLowerCase())}getAccountUrls(e){let t=this.getAllExplorers(),r={};return t.forEach(n=>{let a=U[n];a&&(r[n]=`${a}/accounts/${e}`)}),r}getTransactionUrls(e){let t=this.getAllExplorers(),r={};return t.forEach(n=>{let a=U[n];a&&(r[n]=`${a}/transactions/${e}`)}),r}};import{AbiRegistry as St,Address as y,AddressValue as Fe,BytesValue as w,SmartContractTransactionsFactory as Xr,TransactionsFactoryConfig as Yr}from"@multiversx/sdk-core";import{createWarpIdentifier as Zr,getWarpWalletAddressFromConfig as en,WarpCache as tn,WarpCacheKey as ke,WarpLogger as Me}from"@joai/warps";var Ue={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"},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],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}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpVerified",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"ownershipTransferred",inputs:[{name:"warp",type:"bytes",indexed:!0},{name:"old_owner",type:"Address",indexed:!0},{name:"new_owner",type:"Address",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{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 E=s=>{if(s==="devnet")return"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36";if(s==="testnet")throw new Error("Multiversx testnet is not supported");return"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"};var pe=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}),It=s=>({unitPrice:BigInt(s.unit_price.toString()),admins:s.admins.map(e=>e.toBech32())});var ue=class{constructor(e,t){this.config=e;this.chain=t;this.cache=new tn(e.env,e.cache),this.registryConfig={unitPrice:BigInt(0),admins:[]},this.userWallet=en(this.config,this.chain.name)}async init(){await this.loadRegistryConfigs()}getRegistryConfig(){return this.registryConfig}async createWarpRegisterTransaction(e,t,r){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let n=y.newFromBech32(this.userWallet),a=()=>this.isCurrentUserAdmin()?BigInt(0):t&&r?this.registryConfig.unitPrice*BigInt(3):t?this.registryConfig.unitPrice*BigInt(2):this.registryConfig.unitPrice,i=()=>t&&r?[w.fromHex(e),w.fromUTF8(t),w.fromHex(r)]:t?[w.fromHex(e),w.fromUTF8(t)]:[w.fromHex(e)];return await this.getFactory().createTransactionForExecute(n,{contract:y.newFromBech32(E(this.config.env)),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:a(),arguments:i()})}async createWarpUnregisterTransaction(e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=y.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(t,{contract:y.newFromBech32(E(this.config.env)),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[w.fromHex(e)]})}async createWarpUpgradeTransaction(e,t,r){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let n=y.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(n,{contract:y.newFromBech32(E(this.config.env)),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:r?[w.fromUTF8(e),w.fromHex(t),w.fromHex(r)]:[w.fromUTF8(e),w.fromHex(t)]})}async createWarpAliasSetTransaction(e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let r=y.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(r,{contract:y.newFromBech32(E(this.config.env)),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[w.fromHex(e),w.fromUTF8(t)]})}async createWarpVerifyTransaction(e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=y.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(t,{contract:y.newFromBech32(E(this.config.env)),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[w.fromHex(e)]})}async createWarpTransferOwnershipTransaction(e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let r=y.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(r,{contract:y.newFromBech32(E(this.config.env)),function:"transferOwnership",gasLimit:BigInt(1e7),arguments:[w.fromHex(e),new Fe(new y(t))]})}async createBrandRegisterTransaction(e){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=y.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(t,{contract:y.newFromBech32(E(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[w.fromHex(e)]})}async createWarpBrandingTransaction(e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let r=y.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(r,{contract:y.newFromBech32(E(this.config.env)),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[w.fromHex(e),w.fromHex(t)]})}async getInfoByAlias(e,t){try{let r=ke.RegistryInfo(this.config.env,e),n=t?this.cache.get(r):null;if(n)return Me.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${e}`),n;let a=y.newFromBech32(E(this.config.env)),i=this.getController(),o=i.createQuery({contract:a,function:"getInfoByAlias",arguments:[w.fromUTF8(e)]}),c=await i.runQuery(o),[d]=i.parseQueryResponse(c),m=d?pe(d):null,p=m?.brand?await this.fetchBrand(m.brand):null;return t&&t.ttl&&this.cache.set(r,{registryInfo:m,brand:p},t.ttl),{registryInfo:m,brand:p}}catch{return{registryInfo:null,brand:null}}}async getInfoByHash(e,t){try{let r=ke.RegistryInfo(this.config.env,e);if(t){let p=this.cache.get(r);if(p)return Me.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${e}`),p}let n=y.newFromBech32(E(this.config.env)),a=this.getController(),i=a.createQuery({contract:n,function:"getInfoByHash",arguments:[w.fromHex(e)]}),o=await a.runQuery(i),[c]=a.parseQueryResponse(o),d=c?pe(c):null,m=d?.brand?await this.fetchBrand(d.brand):null;return t&&t.ttl&&this.cache.set(r,{registryInfo:d,brand:m},t.ttl),{registryInfo:d,brand:m}}catch{return{registryInfo:null,brand:null}}}async getUserWarpRegistryInfos(e){try{let t=e||this.userWallet;if(!t)throw new Error("WarpRegistry: user address not set");let r=y.newFromBech32(E(this.config.env)),n=this.getController(),a=n.createQuery({contract:r,function:"getUserWarps",arguments:[new Fe(new y(t))]}),i=await n.runQuery(a),[o]=n.parseQueryResponse(i);return o.map(pe)}catch{return[]}}async getUserBrands(e){try{let t=e||this.userWallet;if(!t)throw new Error("WarpRegistry: user address not set");let r=y.newFromBech32(E(this.config.env)),n=this.getController(),a=n.createQuery({contract:r,function:"getUserBrands",arguments:[new Fe(new y(t))]}),i=await n.runQuery(a),[o]=n.parseQueryResponse(i),c=o.map(p=>p.toString("hex")),d={ttl:365*24*60*60};return(await Promise.all(c.map(p=>this.fetchBrand(p,d)))).filter(p=>p!==null)}catch{return[]}}async fetchBrand(e,t){let r=ke.Brand(this.config.env,e),n=t?this.cache.get(r):null;if(n)return Me.info(`WarpRegistry (fetchBrand): Brand found in cache: ${e}`),n;let i=v(this.chain,this.config.env,this.config).createNetworkProvider();try{let o=await i.getTransaction(e),c=JSON.parse(o.data.toString());return c.meta={query:null,chain:this.chain.name,identifier:Zr(this.chain.name,"hash",e),hash:o.hash,creator:o.sender.toBech32(),createdAt:new Date(o.timestamp*1e3).toISOString()},t&&t.ttl&&this.cache.set(r,c,t.ttl),c}catch{return null}}async loadRegistryConfigs(){let e=y.newFromBech32(E(this.config.env)),t=this.getController(),[r]=await t.query({contract:e,function:"getConfig",arguments:[]}),n=r?It(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let e=new Yr({chainID:this.chain.chainId}),t=St.create(Ue);return new Xr({config:e,abi:t})}getController(){let e=v(this.chain,this.config.env,this.config),t=St.create(Ue);return e.createSmartContractController(t)}isCurrentUserAdmin(){return!!this.userWallet&&this.registryConfig.admins.includes(this.userWallet)}};import{CacheTtl as kt,initializeWalletCache as yn,WarpCache as Wn}from"@joai/warps";import{Address as vn}from"@multiversx/sdk-core";import{Account as rn,Message as nn,Mnemonic as Oe,UserSecretKey as an}from"@multiversx/sdk-core";import*as Vt from"@scure/bip39";import{wordlist as sn}from"@scure/bip39/wordlists/english.js";import{getWarpWalletAddressFromConfig as on,getWarpWalletMnemonicFromConfig as Bt,getWarpWalletPrivateKeyFromConfig as cn,normalizeAndValidateMnemonic as ln,normalizeMnemonic as pn,setWarpWalletInConfig as Nt,validateMnemonicLength as un}from"@joai/warps";var k=class k{constructor(e,t){this.config=e;this.chain=t;this.account=null}async getAddress(){let e=on(this.config,this.chain.name);if(e)return e;try{return this.getAccount().address.toBech32()}catch{return null}}async getPublicKey(){try{return this.getAccount().publicKey.hex()}catch{return null}}async signTransaction(e){let r=await this.getAccount().signTransaction(e);return e.signature=r,e}async signMessage(e){let t=this.getAccount(),r=new TextEncoder().encode(e),n=await t.signMessage(new nn({data:r}));return Buffer.from(n).toString("hex")}getAccountInstance(){return this.getAccount()}async importFromMnemonic(e){let t=ln(e),n=Oe.fromString(t).deriveKey(0),a=n.hex(),o=n.generatePublicKey().toAddress(this.chain.addressHrp).toBech32(),c={provider:k.PROVIDER_NAME,address:o,privateKey:a,mnemonic:t};return Nt(this.config,this.chain.name,c),c}async importFromPrivateKey(e){let t=an.fromString(e),r=t.hex(),a=t.generatePublicKey().toAddress(this.chain.addressHrp).toBech32(),i={provider:k.PROVIDER_NAME,address:a,privateKey:r,mnemonic:null};return Nt(this.config,this.chain.name,i),i}async export(){let e=this.getAccount(),t=Bt(this.config,this.chain.name),r=cn(this.config,this.chain.name);return{provider:k.PROVIDER_NAME,address:e.address.toBech32(),privateKey:r||null,mnemonic:t||null}}async generate(){let e=Vt.generateMnemonic(sn,256),t=pn(e);un(t);let i=Oe.fromString(t).deriveKey(0).generatePublicKey().toAddress(this.chain.addressHrp).toBech32();return{provider:k.PROVIDER_NAME,address:i,privateKey:null,mnemonic:t}}getAccount(){if(this.account)return this.account;let e=Bt(this.config,this.chain.name);if(!e)throw new Error("No mnemonic provided");let r=Oe.fromString(e).deriveKey(0);return this.account=new rn(r),this.account}};k.PROVIDER_NAME="mnemonic";var L=k;import{Account as mn,Message as dn,Mnemonic as hn,UserSecretKey as G}from"@multiversx/sdk-core";import{getWarpWalletAddressFromConfig as gn,getWarpWalletMnemonicFromConfig as fn,getWarpWalletPrivateKeyFromConfig as Ut,setWarpWalletInConfig as Ft}from"@joai/warps";var M=class M{constructor(e,t){this.config=e;this.chain=t;this.account=null}async getAddress(){let e=gn(this.config,this.chain.name);if(e)return e;try{return this.getAccount().address.toBech32()}catch{return null}}async getPublicKey(){try{return this.getAccount().publicKey.hex()}catch{return null}}async signTransaction(e){let r=await this.getAccount().signTransaction(e);return e.signature=r,e}async signMessage(e){let t=this.getAccount(),r=new TextEncoder().encode(e),n=await t.signMessage(new dn({data:r}));return Buffer.from(n).toString("hex")}getAccountInstance(){return this.getAccount()}async importFromMnemonic(e){let r=hn.fromString(e).deriveKey(0),n=r.hex(),i=r.generatePublicKey().toAddress(this.chain.addressHrp).toBech32(),o={provider:M.PROVIDER_NAME,address:i,privateKey:n,mnemonic:e};return Ft(this.config,this.chain.name,o),o}async importFromPrivateKey(e){let r=e.startsWith("-----")?G.fromPem(e):G.fromString(e),n=r.hex(),i=r.generatePublicKey().toAddress(this.chain.addressHrp).toBech32(),o={provider:M.PROVIDER_NAME,address:i,privateKey:n,mnemonic:null};return Ft(this.config,this.chain.name,o),o}async export(){let e=this.getAccount(),t=Ut(this.config,this.chain.name),r=fn(this.config,this.chain.name);return{provider:M.PROVIDER_NAME,address:e.address.toBech32(),privateKey:t||null,mnemonic:r||null}}async generate(){let e=G.generate(),t=e.hex(),n=e.generatePublicKey().toAddress(this.chain.addressHrp).toBech32();return{provider:M.PROVIDER_NAME,address:n,privateKey:t,mnemonic:null}}getAccount(){if(this.account)return this.account;let e=Ut(this.config,this.chain.name);if(!e)throw new Error("No private key provided");let r=e.startsWith("-----")?G.fromPem(e):G.fromString(e);return this.account=new mn(r),this.account}};M.PROVIDER_NAME="privateKey";var K=M;import{getWarpWalletAddressFromConfig as z}from"@joai/warps";var O=class{constructor(e,t){this.config=e;this.chain=t}async getAddress(){return z(this.config,this.chain.name)}async getPublicKey(){return null}async signTransaction(e){let t=await this.getAddress();throw new Error(`Wallet can not be used for signing: ${t}`)}async signMessage(e){let t=await this.getAddress();throw new Error(`Wallet can not be used for signing: ${t}`)}async importFromMnemonic(e){let t=z(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${t}`)}async importFromPrivateKey(e){let t=z(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${t}`)}async export(){let e=z(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${e}`)}async generate(){let e=z(this.config,this.chain.name);throw new Error(`Wallet can not be used for signing: ${e}`)}};var me=class{constructor(e,t){this.config=e;this.chain=t;this.cachedAddress=null;this.cachedPublicKey=null;this.entry=v(t,e.env,e),this.cache=new Wn(e.env,e.cache),this.walletProvider=this.createProvider(),this.initializeCache()}async signTransaction(e){let t=e;if(!t||typeof t!="object")throw new Error("Invalid transaction object");if(!this.walletProvider)throw new Error("No wallet provider available");if(this.walletProvider instanceof O)throw new Error(`Wallet (${this.chain.name}) is read-only`);if(this.walletProvider instanceof K||this.walletProvider instanceof L){let n=this.walletProvider.getAccountInstance();if(t.nonce===0n){let a=await this.entry.recallAccountNonce(n.address),i=this.cache.get(`nonce:${n.address.toBech32()}`)||0,o=BigInt(Math.max(i,Number(a)));t.nonce=o}}else if(t.nonce===0n&&this.cachedAddress){let n=vn.newFromBech32(this.cachedAddress),a=await this.entry.recallAccountNonce(n),i=this.cache.get(`nonce:${this.cachedAddress}`)||0,o=BigInt(Math.max(i,Number(a)));t.nonce=o}let r=await this.walletProvider.signTransaction(t);if(this.walletProvider instanceof K||this.walletProvider instanceof L){let n=this.walletProvider.getAccountInstance(),a=Number(n.nonce)+1;this.cache.set(`nonce:${n.address.toBech32()}`,a,kt.OneMinute)}else if(this.cachedAddress){let n=t.nonce?Number(t.nonce):0;this.cache.set(`nonce:${this.cachedAddress}`,n+1,kt.OneMinute)}return r}async signTransactions(e){let t=[];for(let r of e)t.push(await this.signTransaction(r));return t}async signMessage(e){if(!this.walletProvider)throw new Error("No wallet provider available");if(this.walletProvider instanceof O)throw new Error(`Wallet (${this.chain.name}) is read-only`);return await this.walletProvider.signMessage(e)}async sendTransactions(e){return Promise.all(e.map(async t=>this.sendTransaction(t)))}async sendTransaction(e){let t=e;if(!t||typeof t!="object")throw new Error("Invalid transaction object");if(!t.signature||t.signature.length===0)throw new Error("Transaction must be signed before sending");return await this.entry.sendTransaction(t)}async importFromMnemonic(e){return await this.createProviderForOperation("mnemonic").importFromMnemonic(e)}async importFromPrivateKey(e){return await this.createProviderForOperation("privateKey").importFromPrivateKey(e)}async export(e){return await this.createProviderForOperation(e).export()}async generate(e){return await this.createProviderForOperation(e).generate()}getAddress(){return this.cachedAddress}getPublicKey(){return this.cachedPublicKey}createProvider(){let e=this.config.user?.wallets?.[this.chain.name];return e?typeof e=="string"?new O(this.config,this.chain):e.provider?this.createProviderForOperation(e.provider):new O(this.config,this.chain):null}initializeCache(){yn(this.walletProvider).then(e=>{this.cachedAddress=e.address,this.cachedPublicKey=e.publicKey})}createProviderForOperation(e){let r=this.config.walletProviders?.[this.chain.name]?.[e];if(r){let n=r(this.config,this.chain);if(!n)throw new Error(`Custom wallet provider factory returned null for ${e}`);return n}if(e==="privateKey")return new K(this.config,this.chain);if(e==="mnemonic")return new L(this.config,this.chain);throw new Error(`Unsupported wallet provider for ${this.chain.name}: ${e}`)}};var de=(s,e)=>(t,r)=>{let n=e[t.env],a=new wn;return a.registerType("token",{stringToNative:i=>i,nativeToString:i=>`token:${i}`}),a.registerType("codemeta",{stringToNative:i=>i,nativeToString:i=>`codemeta:${i}`}),a.registerTypeAlias("list","vector"),{chainInfo:n,builder:()=>new X(t,n),executor:new ce(t,n,a),output:new D(t,n,a),serializer:new B({typeRegistry:a}),registry:new ue(t,n),explorer:new le(s,t),abiBuilder:()=>new S(t,n),brandBuilder:()=>new J(t,n),dataLoader:new Z(t,n),wallet:new me(t,n)}};import{WarpChainName as q}from"@joai/warps";var Re={chain:q.Multiversx,identifier:"EGLD",name:"eGold",symbol:"EGLD",decimals:18,logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/tokens/logos/egld.svg"},Mt=de(q.Multiversx,{mainnet:{name:q.Multiversx,displayName:"MultiversX",chainId:"1",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://api.multiversx.com",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/multiversx.svg",nativeToken:Re},testnet:{name:q.Multiversx,displayName:"MultiversX Testnet",chainId:"T",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://testnet-api.multiversx.com",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/multiversx.svg",nativeToken:Re},devnet:{name:q.Multiversx,displayName:"MultiversX Devnet",chainId:"D",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://devnet-api.multiversx.com",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/multiversx.svg",nativeToken:Re}});import{WarpChainName as Le}from"@joai/warps";var Cn={chain:Le.Vibechain,identifier:"VIBE",name:"VIBE",symbol:"VIBE",decimals:18,logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/tokens/logos/vibe.svg"},De={name:Le.Vibechain,displayName:"VibeChain",chainId:"V",blockTime:600,addressHrp:"vibe",defaultApiUrl:"https://vibeox-api.multiversx.com",logoUrl:"https://raw.githubusercontent.com/JoAiHQ/assets/refs/heads/main/chains/logos/vibechain.svg",nativeToken:Cn},Ot=de(Le.Vibechain,{mainnet:De,testnet:De,devnet:De});var sc=()=>[Mt,Ot];import{WarpConstants as he,WarpSerializer as Ke}from"@joai/warps";var uc=s=>new Ke().nativeToString(f.Token,s),mc=s=>new Ke().nativeToString(f.CodeMeta,s),dc=(s,e)=>{if(e===null)return f.Optional+he.ArgParamsSeparator;let t=s(e),r=t.indexOf(he.ArgParamsSeparator),n=t.substring(0,r),a=t.substring(r+1);return f.Optional+he.ArgParamsSeparator+n+he.ArgParamsSeparator+a},hc=s=>new Ke().nativeToString(f.List,s);import{Address as Tn,AddressValue as xn,BigUIntType as An,BigUIntValue as Rt,BooleanValue as En,BytesValue as bn,CodeMetadata as Pn,CodeMetadataValue as In,CompositeType as Sn,CompositeValue as Bn,Field as _e,FieldDefinition as He,List as Nn,NothingValue as Vn,OptionalValue as $e,OptionValue as Ge,StringValue as Un,Struct as Fn,StructType as kn,TokenIdentifierType as Mn,TokenIdentifierValue as Dt,U16Value as On,U32Value as Rn,U64Type as Dn,U64Value as Lt,U8Value as Ln,VariadicValue as Kn}from"@multiversx/sdk-core";var wc=(s,e)=>s?Ge.newProvided(s):e?Ge.newMissingTyped(e):Ge.newMissing(),Cc=(s,e)=>s?new $e(s.getType(),s):e?new $e(e):$e.newMissing(),Tc=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let e=s[0].getType();return new Nn(e,s)},xc=s=>Kn.fromItems(...s),Ac=s=>{let e=s.map(t=>t.getType());return new Bn(new Sn(...e),s)},Ec=s=>Un.fromUTF8(s),bc=s=>new Ln(s),Pc=s=>new On(s),Ic=s=>new Rn(s),Sc=s=>new Lt(s),Bc=s=>new Rt(BigInt(s)),Nc=s=>new En(s),Vc=s=>new xn(Tn.newFromBech32(s)),Uc=s=>new Dt(s),Fc=s=>bn.fromHex(s),kc=s=>new Fn(new kn("EsdtTokenPayment",[new He("token_identifier","",new Mn),new He("token_nonce","",new Dn),new He("amount","",new An)]),[new _e(new Dt(s.token.identifier),"token_identifier"),new _e(new Lt(BigInt(s.token.nonce)),"token_nonce"),new _e(new Rt(BigInt(s.amount)),"amount")]),Mc=s=>new In(Pn.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),Oc=()=>new Vn;export{U as ExplorerUrls,ot as KnownTokens,Mt as MultiversxAdapter,xr as MultiversxExplorers,pt as MultiversxExplorersConfig,Re as NativeTokenEgld,Cn as NativeTokenVibe,Ot as VibechainAdapter,Ar as VibechainExplorers,S as WarpMultiversxAbiBuilder,J as WarpMultiversxBrandBuilder,X as WarpMultiversxBuilder,Ai as WarpMultiversxConstants,j as WarpMultiversxContractLoader,Z as WarpMultiversxDataLoader,ce as WarpMultiversxExecutor,le as WarpMultiversxExplorer,f as WarpMultiversxInputTypes,D as WarpMultiversxOutput,ue as WarpMultiversxRegistry,B as WarpMultiversxSerializer,me as WarpMultiversxWallet,Vc as address_value,kc as asset_value,Bc as biguint_value,Nc as boolean_value,mc as codemeta,Mc as codemeta_value,Ac as composite_value,de as createMultiversxAdapter,ct as findKnownTokenById,sc as getAllMultiversxAdapters,Hn as getAllMultiversxChainNames,ii as getKnownTokensForChain,v as getMultiversxEntrypoint,E as getMultiversxRegistryAddress,Q as getNormalizedTokenIdentifier,Fc as hex_value,R as isNativeToken,hc as list,Tc as list_value,Oc as nothing_value,wc as option_value,dc as optional,Cc as optional_value,Ec as string_value,It as toTypedConfigInfo,pe as toTypedRegistryInfo,uc as token,Uc as token_value,Pc as u16_value,Ic as u32_value,Sc as u64_value,bc as u8_value,xc as variadic_value};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joai/warps-adapter-multiversx",
3
- "version": "1.0.0-beta.100",
3
+ "version": "1.0.0-beta.101",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",