@vleap/warps-adapter-multiversx 0.2.0-alpha.32 → 0.2.0-alpha.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +1 -1
  2. package/package.json +2 -2
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{AbiRegistry as se}from"@multiversx/sdk-core";import{WarpCache as Zt,WarpCacheKey as er,WarpConstants as ze,WarpLogger as Qe}from"@vleap/warps";import{WarpLogger as He}from"@vleap/warps";import{Address as N,ArgSerializer as _t,DevnetEntrypoint as Ot,MainnetEntrypoint as Mt,SmartContractTransactionsFactory as $t,TestnetEntrypoint as Lt,Token as qt,TokenComputer as Dt,TokenTransfer as Ht,TransactionsFactoryConfig as qe,TransferTransactionsFactory as zt,UserSecretKey as Qt,UserSigner as jt}from"@multiversx/sdk-core";import{applyResultsToMessages as Gt,findKnownTokenById as Kt,getNextInfo as Jt,getProviderUrl as Xt,getWarpActionByIndex as ie,shiftBigintBy as Yt,WarpConstants as De}from"@vleap/warps";import{findEventsByFirstTopic as ut,SmartContractTransactionsOutcomeParser as lt,TransactionEventsParser as mt}from"@multiversx/sdk-core";import{applyResultsToMessages as ft,evaluateResultsCommon as U,findWarpExecutableAction as Ue,getNextInfo as dt,parseResultsOutIndex as ke,WarpCache as gt,WarpCacheKey as yt,WarpConstants as _e}from"@vleap/warps";import{Address as nt,AddressType as me,AddressValue as fe,BigUIntType as z,BigUIntValue as Q,BooleanType as de,BooleanValue as ge,BytesType as ye,BytesValue as he,CodeMetadata as at,CodeMetadataType as we,CodeMetadataValue as We,CompositeType as xe,CompositeValue as Te,Field as j,FieldDefinition as G,List as Ce,ListType as it,NothingValue as T,OptionalType as st,OptionalValue as K,OptionType as ot,OptionValue as J,StringType as ve,StringValue as be,Struct as ct,StructType as Ae,TokenIdentifierType as X,TokenIdentifierValue as Y,U16Type as Ee,U16Value as Be,U32Type as Ie,U32Value as Ve,U64Type as Z,U64Value as ee,U8Type as Se,U8Value as Fe,VariadicType as Ne,VariadicValue as Re}from"@multiversx/sdk-core";import{WarpConstants as C,WarpSerializer as pt}from"@vleap/warps";var Pe=new RegExp(`${C.ArgParamsSeparator}(.*)`),E=class{constructor(){this.coreSerializer=new pt}typedToString(e){if(e.hasClassOrSuperclass(J.ClassName))return e.isSet()?`option:${this.typedToString(e.getTypedValue())}`:"option:null";if(e.hasClassOrSuperclass(K.ClassName))return e.isSet()?`optional:${this.typedToString(e.getTypedValue())}`:"optional:null";if(e.hasClassOrSuperclass(Ce.ClassName)){let t=e.getItems(),n=t.map(o=>this.typedToString(o).split(C.ArgParamsSeparator)[0])[0],a=t.map(o=>this.typedToString(o).split(C.ArgParamsSeparator)[1]);return`list:${n}:${a.join(",")}`}if(e.hasClassOrSuperclass(Re.ClassName)){let t=e.getItems(),n=t.map(o=>this.typedToString(o).split(C.ArgParamsSeparator)[0])[0],a=t.map(o=>this.typedToString(o).split(C.ArgParamsSeparator)[1]);return`variadic:${n}:${a.join(",")}`}if(e.hasClassOrSuperclass(Te.ClassName)){let t=e.getItems(),r=t.map(i=>this.typedToString(i).split(C.ArgParamsSeparator)[0]),n=t.map(i=>this.typedToString(i).split(C.ArgParamsSeparator)[1]),a=r.join(C.ArgCompositeSeparator),o=n.join(C.ArgCompositeSeparator);return`composite(${a}):${o}`}if(e.hasClassOrSuperclass(Q.ClassName)||e.getType().getName()==="BigUint")return`biguint:${BigInt(e.valueOf().toFixed())}`;if(e.hasClassOrSuperclass(Fe.ClassName))return`uint8:${e.valueOf().toNumber()}`;if(e.hasClassOrSuperclass(Be.ClassName))return`uint16:${e.valueOf().toNumber()}`;if(e.hasClassOrSuperclass(Ve.ClassName))return`uint32:${e.valueOf().toNumber()}`;if(e.hasClassOrSuperclass(ee.ClassName))return`uint64:${BigInt(e.valueOf().toFixed())}`;if(e.hasClassOrSuperclass(be.ClassName))return`string:${e.valueOf()}`;if(e.hasClassOrSuperclass(ge.ClassName))return`bool:${e.valueOf()}`;if(e.hasClassOrSuperclass(fe.ClassName))return`address:${e.valueOf().toBech32()}`;if(e.hasClassOrSuperclass(Y.ClassName))return`token:${e.valueOf()}`;if(e.hasClassOrSuperclass(he.ClassName))return`hex:${e.valueOf().toString("hex")}`;if(e.hasClassOrSuperclass(We.ClassName))return`codemeta:${e.valueOf().toString()}`;if(e.getType().getName()==="EsdtTokenPayment"){let t=e.getFieldValue("token_identifier").valueOf(),r=e.getFieldValue("token_nonce").valueOf(),n=e.getFieldValue("amount").valueOf();return`asset:${t}|${r}|${n}`}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){let r=this.coreSerializer.nativeToString(e,t);return this.stringToTyped(r)}nativeToType(e){if(e.startsWith("composite")){let t=e.match(/\(([^)]+)\)/)?.[1];return new xe(...t.split(C.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(e==="string")return new ve;if(e==="uint8")return new Se;if(e==="uint16")return new Ee;if(e==="uint32")return new Ie;if(e==="uint64")return new Z;if(e==="biguint")return new z;if(e==="bool")return new de;if(e==="address")return new me;if(e==="token")return new X;if(e==="hex")return new ye;if(e==="codemeta")return new we;if(e==="asset")return new Ae("EsdtTokenPayment",[new G("token_identifier","",new X),new G("token_nonce","",new Z),new G("amount","",new z)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${e}`)}stringToTyped(e){let[t,r]=e.split(/:(.*)/,2);if(t==="null"||t===null)return new T;if(t==="option"){let n=this.stringToTyped(r);return n instanceof T?J.newMissingTyped(n.getType()):J.newProvided(n)}if(t==="optional"){let n=this.stringToTyped(r);return n instanceof T?K.newMissing():new K(n.getType(),n)}if(t==="list"){let[n,a]=r.split(Pe,2),i=a.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Ce(this.nativeToType(n),i)}if(t==="variadic"){let[n,a]=r.split(Pe,2),i=a.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Re(new Ne(this.nativeToType(n)),i)}if(t.startsWith("composite")){let n=t.match(/\(([^)]+)\)/)?.[1],a=r.split(C.ArgCompositeSeparator),o=n.split(C.ArgCompositeSeparator),i=a.map((p,u)=>this.stringToTyped(`${o[u]}:${p}`)),c=i.map(p=>p.getType());return new Te(new xe(...c),i)}if(t==="string")return r?be.fromUTF8(r):new T;if(t==="uint8")return r?new Fe(Number(r)):new T;if(t==="uint16")return r?new Be(Number(r)):new T;if(t==="uint32")return r?new Ve(Number(r)):new T;if(t==="uint64")return r?new ee(BigInt(r)):new T;if(t==="biguint")return r?new Q(BigInt(r)):new T;if(t==="bool")return r?new ge(typeof r=="boolean"?r:r==="true"):new T;if(t==="address")return r?new fe(nt.newFromBech32(r)):new T;if(t==="token")return r?new Y(r):new T;if(t==="hex")return r?he.fromHex(r):new T;if(t==="codemeta")return new We(at.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(t==="asset"){let n=r.split(C.ArgCompositeSeparator);return new ct(this.nativeToType("asset"),[new j(new Y(n[0]),"token_identifier"),new j(new ee(BigInt(n[1])),"token_nonce"),new j(new Q(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${t}`)}typeToString(e){if(e instanceof ot)return"option:"+this.typeToString(e.getFirstTypeParameter());if(e instanceof st)return"optional:"+this.typeToString(e.getFirstTypeParameter());if(e instanceof it)return"list:"+this.typeToString(e.getFirstTypeParameter());if(e instanceof Ne)return"variadic:"+this.typeToString(e.getFirstTypeParameter());if(e instanceof ve)return"string";if(e instanceof Se)return"uint8";if(e instanceof Ee)return"uint16";if(e instanceof Ie)return"uint32";if(e instanceof Z)return"uint64";if(e instanceof z)return"biguint";if(e instanceof de)return"bool";if(e instanceof me)return"address";if(e instanceof X)return"token";if(e instanceof ye)return"hex";if(e instanceof we)return"codemeta";if(e instanceof Ae&&e.getClassName()==="EsdtTokenPayment")return"asset";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${e.getClassName()}`)}};var V=class{constructor(e,t){this.config=e;this.chain=t;this.abi=new B(e,t),this.serializer=new E,this.cache=new gt(e.cache?.type)}async getTransactionExecutionResults(e,t){let{actionIndex:r}=Ue(e),n=this.cache.get(yt.WarpExecutable(this.config.env,e.meta?.hash||"",r))??[],a=await this.extractContractResults(e,t,n),o=dt(this.config,[],e,r,a),i=ft(e,a.results);return{success:t.status.isSuccessful(),warp:e,action:r,user:this.config.user?.wallets?.[this.chain.name]||null,txHash:t.hash,next:o,values:a.values,results:a.results,messages:i}}async extractContractResults(e,t,r){let{action:n,actionIndex:a}=Ue(e),o=[],i={};if(!e.results||n.type!=="contract")return{values:o,results:i};if(!Object.values(e.results).some(w=>w.includes("out")||w.includes("event"))){for(let[w,m]of Object.entries(e.results))i[w]=m;return{values:o,results:await U(e,i,a,r,this.config.transform?.runner)}}let p=await this.abi.getAbiForAction(n),u=new mt({abi:p}),y=new lt({abi:p}).parseExecute({transactionOnNetwork:t,function:n.func||void 0});for(let[w,m]of Object.entries(e.results)){if(m.startsWith(_e.Transform.Prefix))continue;if(m.startsWith("input.")){i[w]=m;continue}let v=ke(m);if(v!==null&&v!==a){i[w]=null;continue}let[W,A,b]=m.split(".");if(W==="event"){if(!A||isNaN(Number(b)))continue;let R=Number(b),h=ut(t,A),F=u.parseEvents({events:h})[0],P=Object.values(F)[R]||null;o.push(P),i[w]=P&&P.valueOf()}else if(W==="out"||W.startsWith("out[")){if(!A)continue;let R=Number(A),h=y.values[R-1]||null;b&&(h=h[b]||null),h&&typeof h=="object"&&(h="toFixed"in h?h.toFixed():h.valueOf()),o.push(h),i[w]=h&&h.valueOf()}else i[w]=m}return{values:o,results:await U(e,i,a,r)}}async extractQueryResults(e,t,r,n){let a=t.map(p=>this.serializer.typedToString(p)),o=t.map(p=>this.serializer.typedToNative(p)[1]),i={};if(!e.results)return{values:a,results:i};let c=p=>{let u=p.split(".").slice(1).map(y=>parseInt(y)-1);if(u.length===0)return;let l=o[u[0]];for(let y=1;y<u.length;y++){if(l==null)return;l=l[u[y]]}return l};for(let[p,u]of Object.entries(e.results)){if(u.startsWith(_e.Transform.Prefix))continue;let l=ke(u);if(l!==null&&l!==r){i[p]=null;continue}u.startsWith("out.")||u==="out"||u.startsWith("out[")?i[p]=c(u)||null:i[p]=u}return{values:a,results:await U(e,i,r,n)}}async resolveWarpResultsRecursively(e){let t=e.warp,r=e.entryActionIndex,n=e.executor,a=e.inputs,o=e.meta,i=new Map,c=new Set,p=this;async function u(m,v=[]){if(i.has(m))return i.get(m);if(c.has(m))throw new Error(`Circular dependency detected at action ${m}`);c.add(m);let W=t.actions[m-1];if(!W)throw new Error(`Action ${m} not found`);let A;if(W.type==="query")A=await n.executeQuery(t,m,v);else if(W.type==="collect")A=await n.executeCollect(t,m,v,o);else throw new Error(`Unsupported or interactive action type: ${W.type}`);if(i.set(m,A),t.results)for(let b of Object.values(t.results)){let h=String(b).match(/^out\[(\d+)\]/);if(h){let F=parseInt(h[1],10);F!==m&&!i.has(F)&&await u(F)}}return c.delete(m),A}await u(r,a);let l={};for(let m of i.values())for(let[v,W]of Object.entries(m.results))W!==null?l[v]=W:v in l||(l[v]=null);let y=await U(t,l,r,a,this.config.transform?.runner);return{...i.get(r),action:r,results:y}}};import{Address as ht,AddressValue as wt,BigUIntType as Wt,BigUIntValue as Oe,BooleanValue as xt,BytesValue as Tt,CodeMetadata as Ct,CodeMetadataValue as vt,CompositeType as bt,CompositeValue as At,Field as te,FieldDefinition as re,List as Et,NothingValue as Bt,OptionalValue as ne,OptionValue as ae,StringValue as It,Struct as Vt,StructType as St,TokenIdentifierType as Ft,TokenIdentifierValue as Me,U16Value as Nt,U32Value as Rt,U64Type as Pt,U64Value as $e,U8Value as Ut,VariadicValue as kt}from"@multiversx/sdk-core";var Qr=(s,e)=>s?ae.newProvided(s):e?ae.newMissingTyped(e):ae.newMissing(),jr=(s,e)=>s?new ne(s.getType(),s):e?new ne(e):ne.newMissing(),Gr=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let e=s[0].getType();return new Et(e,s)},Kr=s=>kt.fromItems(...s),Jr=s=>{let e=s.map(t=>t.getType());return new At(new bt(...e),s)},Xr=s=>It.fromUTF8(s),Yr=s=>new Ut(s),Zr=s=>new Nt(s),en=s=>new Rt(s),tn=s=>new $e(s),rn=s=>new Oe(BigInt(s)),nn=s=>new xt(s),an=s=>new wt(ht.newFromBech32(s)),sn=s=>new Me(s),on=s=>Tt.fromHex(s),Le=s=>new Vt(new St("EsdtTokenPayment",[new re("token_identifier","",new Ft),new re("token_nonce","",new Pt),new re("amount","",new Wt)]),[new te(new Me(s.token.identifier),"token_identifier"),new te(new $e(BigInt(s.token.nonce)),"token_nonce"),new te(new Oe(BigInt(s.amount)),"amount")]),cn=s=>new vt(Ct.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),pn=()=>new Bt;var d=class s{constructor(e,t){this.config=e;this.chain=t;this.serializer=new E,this.abi=new B(this.config,this.chain),this.results=new V(this.config,this.chain)}async createTransaction(e){let t=ie(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){let t=this.config.user?.wallets?.[e.chain.name];if(!t)throw new Error("WarpMultiversxExecutor: createTransfer - user address not set");let r=N.newFromBech32(t),n=new qe({chainID:e.chain.chainId}),a=e.data?Buffer.from(this.serializer.stringToTyped(e.data).valueOf()):null;return new zt({config:n}).createTransactionForTransfer(r,{receiver:N.newFromBech32(e.destination),nativeAmount:e.value,data:a?new Uint8Array(a):void 0})}async createContractCallTransaction(e){let t=this.config.user?.wallets?.[e.chain.name];if(!t)throw new Error("WarpMultiversxExecutor: createContractCall - user address not set");let r=ie(e.warp,e.action),n=N.newFromBech32(t),a=e.args.map(i=>this.serializer.stringToTyped(i)),o=new qe({chainID:e.chain.chainId});return new $t({config:o}).createTransactionForExecute(n,{contract:N.newFromBech32(e.destination),function:"func"in r&&r.func||"",gasLimit:"gasLimit"in r?BigInt(r.gasLimit||0):0n,arguments:a,nativeTransferAmount:e.value})}async executeQuery(e){let t=ie(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(b=>this.serializer.stringToTyped(b)),a=s.getChainEntrypoint(e.chain,this.config.env,this.config),o=N.newFromBech32(e.destination),i=a.createSmartContractController(r),c=i.createQuery({contract:o,function:t.func||"",arguments:n}),p=await i.runQuery(c),u=p.returnCode==="ok",l=new _t,y=r.getEndpoint(p.function||t.func||""),w=(p.returnDataParts||[]).map(b=>Buffer.from(b)),m=l.buffersToValues(w,y.output),{values:v,results:W}=await this.results.extractQueryResults(e.warp,m,e.action,e.resolvedInputs),A=Jt(this.config,[],e.warp,e.action,W);return{success:u,warp:e.warp,action:e.action,user:this.config.user?.wallets?.[e.chain.name]||null,txHash:null,next:A,values:v,results:W,messages:Gt(e.warp,W)}}async preprocessInput(e,t,r,n){if(r==="asset"){let[a,o,i,c]=n.split(De.ArgCompositeSeparator);if(c)return t;let p=new qt({identifier:a,nonce:BigInt(o)});if(!new Dt().isFungible(p))return t;let y=Kt(a)?.decimals;if(y||(y=(await(await fetch(`${e.defaultApiUrl}/tokens/${a}`)).json()).decimals),!y)throw new Error(`WarpActionExecutor: Decimals not found for token ${a}`);let w=Le(new Ht({token:p,amount:Yt(i,y)}));return this.serializer.typedToString(w)+De.ArgCompositeSeparator+y}return t}static getChainEntrypoint(e,t,r){let n="warp-sdk",o=r?Xt(r,e.name,t,e.defaultApiUrl):e.defaultApiUrl;return t==="devnet"?new Ot({url:o,kind:"api",clientName:n}):t==="testnet"?new Lt({url:o,kind:"api",clientName:n}):new Mt({url:o,kind:"api",clientName:n})}async signMessage(e,t){let r=Qt.fromString(t);return(await new jt(r).sign(new Uint8Array(Buffer.from(e,"utf-8")))).toString()}};var k=class{constructor(e){this.config=e}async getContract(e,t){try{let a=await d.getChainEntrypoint(t,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${e}`);return{address:e,owner:a.ownerAddress,verified:a.isVerified||!1}}catch(r){return He.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(e,t){try{let a=await d.getChainEntrypoint(t,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${e}/verification`);return{codeHash:a.codeHash,abi:a.source.abi}}catch(r){return He.error("WarpContractLoader: getVerificationInfo error",r),null}}};var B=class{constructor(e,t){this.config=e;this.chain=t;this.contractLoader=new k(this.config),this.cache=new Zt(this.config.cache?.type)}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,hash:e.hash,creator:e.sender.toBech32(),createdAt:new Date(e.timestamp*1e3).toISOString()},t}async createFromTransactionHash(e,t){let r=er.WarpAbi(this.config.env,e);if(t){let o=this.cache.get(r);if(o)return Qe.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${e}`),o}let a=d.getChainEntrypoint(this.chain,this.config.env).createNetworkProvider();try{let o=await a.getTransaction(e),i=await this.createFromTransaction(o);return t&&t.ttl&&i&&this.cache.set(r,i,t.ttl),i}catch(o){return Qe.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 se.create(t.abi)}async fetchAbi(e){if(!e.abi)throw new Error("WarpActionExecutor: ABI not found");if(e.abi.startsWith(ze.IdentifierType.Hash)){let t=e.abi.split(ze.IdentifierParamSeparatorDefault)[1],r=await this.createFromTransactionHash(t);if(!r)throw new Error(`WarpActionExecutor: ABI not found for hash: ${e.abi}`);return se.create(r.content)}else{let r=await(await fetch(e.abi)).json();return se.create(r)}}};import{Address as je,TransactionsFactoryConfig as tr,TransferTransactionsFactory as rr}from"@multiversx/sdk-core";import{WarpBrandBuilder as nr,WarpLogger as ar}from"@vleap/warps";import{Buffer as ir}from"buffer";var _=class{constructor(e,t){this.config=e;this.chain=t;this.core=new nr(e)}async createInscriptionTransaction(e){let t=this.config.user?.wallets?.[this.chain.name];if(!t)throw new Error("BrandBuilder: user address not set");let r=new tr({chainID:this.chain.chainId}),n=new rr({config:r}),a=je.newFromBech32(t),o=JSON.stringify(e);return await n.createTransactionForNativeTokenTransfer(a,{receiver:je.newFromBech32(t),nativeAmount:BigInt(0),data:Uint8Array.from(ir.from(o))})}async createFromTransaction(e,t=!1){return await this.core.createFromRaw(e.data.toString(),t)}async createFromTransactionHash(e){let r=d.getChainEntrypoint(this.chain,this.config.env).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 Ge,TransactionsFactoryConfig as sr,TransferTransactionsFactory as or}from"@multiversx/sdk-core";import{WarpBuilder as Ke,WarpCache as cr,WarpCacheKey as pr,WarpLogger as Je}from"@vleap/warps";var O=class extends Ke{constructor(t,r){super(t);this.config=t;this.chain=r;this.cache=new cr(t.cache?.type),this.core=new Ke(t)}async createInscriptionTransaction(t){let r=this.config.user?.wallets?.[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}),o=Ge.newFromBech32(r),i=JSON.stringify(t),c=await a.createTransactionForTransfer(o,{receiver:Ge.newFromBech32(r),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))});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,hash:t.hash,creator:t.sender.toBech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},n}async createFromTransactionHash(t,r){let n=pr.Warp(this.config.env,t);if(r){let i=this.cache.get(n);if(i)return Je.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),i}let o=d.getChainEntrypoint(this.chain,this.config.env).createNetworkProvider();try{let i=await o.getTransaction(t),c=await this.createFromTransaction(i);return r&&r.ttl&&c&&this.cache.set(n,c,r.ttl),c}catch(i){return Je.error("WarpBuilder: Error creating from transaction hash",i),null}}};import{Address as Xe}from"@multiversx/sdk-core";var M=class{constructor(e,t){this.config=e;this.chain=t}async getAccount(e){let r=await d.getChainEntrypoint(this.chain,this.config.env,this.config).createNetworkProvider().getAccount(Xe.newFromBech32(e));return{address:r.address.toBech32(),balance:r.balance}}async getAccountAssets(e){return(await d.getChainEntrypoint(this.chain,this.config.env,this.config).createNetworkProvider().getFungibleTokensOfAccount(Xe.newFromBech32(e))).map(n=>({identifier:n.token.identifier,name:n.raw.name,amount:n.amount,decimals:n.raw.decimals,logoUrl:n.raw.assets?.pngUrl||""}))}};var wa={Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}},ur=(r=>(r.MultiversxExplorer="multiversx_explorer",r.MultiversxExplorerDevnet="multiversx_explorer_devnet",r.MultiversxExplorerTestnet="multiversx_explorer_testnet",r))(ur||{}),lr=(r=>(r.VibechainExplorer="vibechain_explorer",r.VibechainExplorerDevnet="vibechain_explorer_devnet",r.VibechainExplorerTestnet="vibechain_explorer_testnet",r))(lr||{}),Ye={multiversx:{mainnet:["multiversx_explorer"],testnet:["multiversx_explorer_testnet"],devnet:["multiversx_explorer_devnet"]},vibechain:{mainnet:["vibechain_explorer"],testnet:["vibechain_explorer_testnet"],devnet:["vibechain_explorer_devnet"]}},I={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 $=class{constructor(e,t){this.chain=e;this.config=t}getExplorers(){let e=Ye[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=I[t];if(a)return a}if(e){let a=I[e];if(a)return a}let r=this.getPrimaryExplorer();return I[r]||I[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=I[n];a&&(r[n]=`${a}/accounts/${e}`)}),r}getTransactionUrls(e){let t=this.getAllExplorers(),r={};return t.forEach(n=>{let a=I[n];a&&(r[n]=`${a}/transactions/${e}`)}),r}};import{AbiRegistry as et,Address as f,AddressValue as ce,BytesValue as g,SmartContractTransactionsFactory as fr,TransactionsFactoryConfig as dr}from"@multiversx/sdk-core";import{WarpCache as gr,WarpCacheKey as pe,WarpLogger as ue}from"@vleap/warps";var oe={buildInfo:{rustc:{version:"1.86.0",commitHash:"05f9846f893b09a1be1fc8560e33fc3c815cfecb",commitDate:"2025-03-31",channel:"Stable",short:"rustc 1.86.0 (05f9846f8 2025-03-31)"},contractCrate:{name:"registry",version:"0.0.1"},framework:{name:"multiversx-sc",version:"0.51.1"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"},{name:"vault",type:"Address"}],outputs:[]},upgradeConstructor:{inputs:[],outputs:[]},endpoints:[{name:"registerWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias_opt",type:"optional<bytes>",multi_arg:!0},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],outputs:[],allow_multiple_var_args:!0},{name:"unregisterWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"upgradeWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"alias",type:"bytes"},{name:"new_warp",type:"bytes"}],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"forceRemoveAlias",mutability:"mutable",inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"verifyWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"transferOwnership",mutability:"mutable",inputs:[{name:"warp",type:"bytes"},{name:"new_owner",type:"Address"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<InfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"setVault",onlyOwner:!0,mutability:"mutable",inputs:[{name:"vault",type:"Address"}],outputs:[]},{name:"setUnitPrice",onlyOwner:!0,mutability:"mutable",inputs:[{name:"amount",type:"BigUint"}],outputs:[]},{name:"addAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"removeAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"ConfigView"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]},{name:"setChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"},{name:"native_token",type:"bytes"}],outputs:[]},{name:"removeChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"}],outputs:[]},{name:"getChain",mutability:"readonly",inputs:[{name:"name",type:"bytes"}],outputs:[{type:"ChainView"}]},{name:"getChains",mutability:"readonly",inputs:[],outputs:[{type:"variadic<ChainView>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpVerified",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"ownershipTransferred",inputs:[{name:"warp",type:"bytes",indexed:!0},{name:"old_owner",type:"Address",indexed:!0},{name:"new_owner",type:"Address",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{ChainView:{type:"struct",fields:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"},{name:"native_token",type:"bytes"}]},ConfigView:{type:"struct",fields:[{name:"unit_price",type:"BigUint"},{name:"admins",type:"List<Address>"}]},InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"owner",type:"Address"},{name:"created_at",type:"u64"},{name:"upgraded_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var x=s=>{if(s==="devnet")return"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36";if(s==="testnet")throw new Error("Multiversx testnet is not supported");return"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"};var L=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}),Ze=s=>({unitPrice:BigInt(s.unit_price.toString()),admins:s.admins.map(e=>e.toBech32())});var q=class{constructor(e,t){this.config=e;this.chain=t;this.cache=new gr(e.cache?.type),this.registryConfig={unitPrice:BigInt(0),admins:[]},this.userWallet=this.config.user?.wallets?.[this.chain.name]||null}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=f.newFromBech32(this.userWallet),a=()=>this.isCurrentUserAdmin()?BigInt(0):t&&r?this.registryConfig.unitPrice*BigInt(3):t?this.registryConfig.unitPrice*BigInt(2):this.registryConfig.unitPrice,o=()=>t&&r?[g.fromHex(e),g.fromUTF8(t),g.fromHex(r)]:t?[g.fromHex(e),g.fromUTF8(t)]:[g.fromHex(e)];return await this.getFactory().createTransactionForExecute(n,{contract:f.newFromBech32(x(this.config.env)),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:a(),arguments:o()})}async createWarpUnregisterTransaction(e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=f.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(t,{contract:f.newFromBech32(x(this.config.env)),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[g.fromHex(e)]})}async createWarpUpgradeTransaction(e,t){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 r=f.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(r,{contract:f.newFromBech32(x(this.config.env)),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[g.fromUTF8(e),g.fromHex(t)]})}async createWarpAliasSetTransaction(e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let r=f.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(r,{contract:f.newFromBech32(x(this.config.env)),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[g.fromHex(e),g.fromUTF8(t)]})}async createWarpVerifyTransaction(e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=f.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(t,{contract:f.newFromBech32(x(this.config.env)),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[g.fromHex(e)]})}async createWarpTransferOwnershipTransaction(e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let r=f.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(r,{contract:f.newFromBech32(x(this.config.env)),function:"transferOwnership",gasLimit:BigInt(1e7),arguments:[g.fromHex(e),new ce(new f(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=f.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(t,{contract:f.newFromBech32(x(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[g.fromHex(e)]})}async createWarpBrandingTransaction(e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let r=f.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(r,{contract:f.newFromBech32(x(this.config.env)),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[g.fromHex(e),g.fromHex(t)]})}async getInfoByAlias(e,t){try{let r=pe.RegistryInfo(this.config.env,e),n=t?this.cache.get(r):null;if(n)return ue.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${e}`),n;let a=f.newFromBech32(x(this.config.env)),o=this.getController(),i=o.createQuery({contract:a,function:"getInfoByAlias",arguments:[g.fromUTF8(e)]}),c=await o.runQuery(i),[p]=o.parseQueryResponse(c),u=p?L(p):null,l=u?.brand?await this.fetchBrand(u.brand):null;return t&&t.ttl&&this.cache.set(r,{registryInfo:u,brand:l},t.ttl),{registryInfo:u,brand:l}}catch{return{registryInfo:null,brand:null}}}async getInfoByHash(e,t){try{let r=pe.RegistryInfo(this.config.env,e);if(t){let l=this.cache.get(r);if(l)return ue.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${e}`),l}let n=f.newFromBech32(x(this.config.env)),a=this.getController(),o=a.createQuery({contract:n,function:"getInfoByHash",arguments:[g.fromHex(e)]}),i=await a.runQuery(o),[c]=a.parseQueryResponse(i),p=c?L(c):null,u=p?.brand?await this.fetchBrand(p.brand):null;return t&&t.ttl&&this.cache.set(r,{registryInfo:p,brand:u},t.ttl),{registryInfo:p,brand:u}}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=f.newFromBech32(x(this.config.env)),n=this.getController(),a=n.createQuery({contract:r,function:"getUserWarps",arguments:[new ce(new f(t))]}),o=await n.runQuery(a),[i]=n.parseQueryResponse(o);return i.map(L)}catch{return[]}}async getUserBrands(e){try{let t=e||this.userWallet;if(!t)throw new Error("WarpRegistry: user address not set");let r=f.newFromBech32(x(this.config.env)),n=this.getController(),a=n.createQuery({contract:r,function:"getUserBrands",arguments:[new ce(new f(t))]}),o=await n.runQuery(a),[i]=n.parseQueryResponse(o),c=i.map(l=>l.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(c.map(l=>this.fetchBrand(l,p)))).filter(l=>l!==null)}catch{return[]}}async fetchBrand(e,t){let r=pe.Brand(this.config.env,e),n=t?this.cache.get(r):null;if(n)return ue.info(`WarpRegistry (fetchBrand): Brand found in cache: ${e}`),n;let o=d.getChainEntrypoint(this.chain,this.config.env).createNetworkProvider();try{let i=await o.getTransaction(e),c=JSON.parse(i.data.toString());return c.meta={hash:i.hash,creator:i.sender.toBech32(),createdAt:new Date(i.timestamp*1e3).toISOString()},t&&t.ttl&&this.cache.set(r,c,t.ttl),c}catch{return null}}async loadRegistryConfigs(){let e=f.newFromBech32(x(this.config.env)),t=this.getController(),[r]=await t.query({contract:e,function:"getConfig",arguments:[]}),n=r?Ze(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let e=new dr({chainID:this.chain.chainId}),t=et.create(oe);return new fr({config:e,abi:t})}getController(){let e=d.getChainEntrypoint(this.chain,this.config.env),t=et.create(oe);return e.createSmartContractController(t)}isCurrentUserAdmin(){return!!this.userWallet&&this.registryConfig.admins.includes(this.userWallet)}};var D=(s,e,t)=>(r,n)=>{let a=t[r.env];return{chain:s,chainInfo:a,prefix:e,builder:()=>new O(r,a),executor:new d(r,a),results:new V(r,a),serializer:new E,registry:new q(r,a),explorer:new $(s,r),abiBuilder:()=>new B(r,a),brandBuilder:()=>new _(r,a),dataLoader:new M(r,a),registerTypes:o=>{o.registerType("token",{stringToNative:i=>i,nativeToString:i=>`token:${i}`}),o.registerType("codemeta",{stringToNative:i=>i,nativeToString:i=>`codemeta:${i}`})}}};var S="multiversx",tt=D(S,"mvx",{mainnet:{name:S,displayName:"MultiversX",chainId:"1",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://api.multiversx.com",nativeToken:"EGLD"},testnet:{name:S,displayName:"MultiversX Testnet",chainId:"T",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://testnet-api.multiversx.com",nativeToken:"EGLD"},devnet:{name:S,displayName:"MultiversX Devnet",chainId:"D",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://devnet-api.multiversx.com",nativeToken:"EGLD"}});var H="vibechain",le={name:H,displayName:"VibeChain",chainId:"V",blockTime:600,addressHrp:"vibe",defaultApiUrl:"https://vibeox-api.multiversx.com",nativeToken:"VIBE"},rt=D(H,"vibe",{mainnet:le,testnet:le,devnet:le});var ai=(s,e)=>[tt(s,e),rt(s,e)],ii=()=>[S,H];export{S as ChainNameMultiversx,H as ChainNameVibechain,I as ExplorerUrls,ur as MultiversxExplorers,Ye as MultiversxExplorersConfig,lr as VibechainExplorers,B as WarpMultiversxAbiBuilder,_ as WarpMultiversxBrandBuilder,O as WarpMultiversxBuilder,wa as WarpMultiversxConstants,k as WarpMultiversxContractLoader,d as WarpMultiversxExecutor,$ as WarpMultiversxExplorer,q as WarpMultiversxRegistry,V as WarpMultiversxResults,E as WarpMultiversxSerializer,an as address_value,rn as biguint_value,nn as boolean_value,cn as codemeta_value,Jr as composite_value,D as createMultiversxAdapter,Le as esdt_value,ai as getAllMultiversxAdapters,ii as getAllMultiversxChainNames,tt as getMultiversxAdapter,x as getMultiversxRegistryAddress,rt as getVibechainAdapter,on as hex_value,Gr as list_value,pn as nothing_value,Qr as option_value,jr as optional_value,Xr as string_value,sn as token_value,Zr as u16_value,en as u32_value,tn as u64_value,Yr as u8_value,Kr as variadic_value};
1
+ import{AbiRegistry as se}from"@multiversx/sdk-core";import{WarpCache as Zt,WarpCacheKey as er,WarpConstants as je,WarpLogger as Ge}from"@vleap/warps";import{WarpLogger as Qe}from"@vleap/warps";import{Address as N,ArgSerializer as Mt,DevnetEntrypoint as $t,MainnetEntrypoint as Lt,SmartContractTransactionsFactory as qt,TestnetEntrypoint as Dt,Token as qe,TokenComputer as Ht,TokenTransfer as De,TransactionsFactoryConfig as He,TransferTransactionsFactory as zt,UserSecretKey as Qt,UserSigner as jt}from"@multiversx/sdk-core";import{applyResultsToMessages as Gt,findKnownTokenById as Kt,getNextInfo as Jt,getProviderUrl as Xt,getWarpActionByIndex as ie,shiftBigintBy as Yt,WarpConstants as ze}from"@vleap/warps";import{findEventsByFirstTopic as mt,SmartContractTransactionsOutcomeParser as ft,TransactionEventsParser as dt}from"@multiversx/sdk-core";import{applyResultsToMessages as gt,evaluateResultsCommon as U,findWarpExecutableAction as Ue,getNextInfo as yt,parseResultsOutIndex as ke,WarpCache as ht,WarpCacheKey as wt,WarpConstants as _e}from"@vleap/warps";import{Address as it,AddressType as me,AddressValue as fe,BigUIntType as z,BigUIntValue as Q,BooleanType as de,BooleanValue as ge,BytesType as ye,BytesValue as he,CodeMetadata as st,CodeMetadataType as we,CodeMetadataValue as We,CompositeType as xe,CompositeValue as Te,Field as j,FieldDefinition as G,List as Ce,ListType as ot,NothingValue as T,OptionalType as ct,OptionalValue as K,OptionType as pt,OptionValue as J,StringType as ve,StringValue as be,Struct as ut,StructType as Ae,TokenIdentifierType as X,TokenIdentifierValue as Y,U16Type as Ee,U16Value as Be,U32Type as Ie,U32Value as Ve,U64Type as Z,U64Value as ee,U8Type as Se,U8Value as Fe,VariadicType as Ne,VariadicValue as Re}from"@multiversx/sdk-core";import{WarpConstants as C,WarpSerializer as lt}from"@vleap/warps";var Pe=new RegExp(`${C.ArgParamsSeparator}(.*)`),E=class{constructor(){this.coreSerializer=new lt}typedToString(e){if(e.hasClassOrSuperclass(J.ClassName))return e.isSet()?`option:${this.typedToString(e.getTypedValue())}`:"option:null";if(e.hasClassOrSuperclass(K.ClassName))return e.isSet()?`optional:${this.typedToString(e.getTypedValue())}`:"optional:null";if(e.hasClassOrSuperclass(Ce.ClassName)){let t=e.getItems(),n=t.map(o=>this.typedToString(o).split(C.ArgParamsSeparator)[0])[0],a=t.map(o=>this.typedToString(o).split(C.ArgParamsSeparator)[1]);return`list:${n}:${a.join(",")}`}if(e.hasClassOrSuperclass(Re.ClassName)){let t=e.getItems(),n=t.map(o=>this.typedToString(o).split(C.ArgParamsSeparator)[0])[0],a=t.map(o=>this.typedToString(o).split(C.ArgParamsSeparator)[1]);return`variadic:${n}:${a.join(",")}`}if(e.hasClassOrSuperclass(Te.ClassName)){let t=e.getItems(),r=t.map(i=>this.typedToString(i).split(C.ArgParamsSeparator)[0]),n=t.map(i=>this.typedToString(i).split(C.ArgParamsSeparator)[1]),a=r.join(C.ArgCompositeSeparator),o=n.join(C.ArgCompositeSeparator);return`composite(${a}):${o}`}if(e.hasClassOrSuperclass(Q.ClassName)||e.getType().getName()==="BigUint")return`biguint:${BigInt(e.valueOf().toFixed())}`;if(e.hasClassOrSuperclass(Fe.ClassName))return`uint8:${e.valueOf().toNumber()}`;if(e.hasClassOrSuperclass(Be.ClassName))return`uint16:${e.valueOf().toNumber()}`;if(e.hasClassOrSuperclass(Ve.ClassName))return`uint32:${e.valueOf().toNumber()}`;if(e.hasClassOrSuperclass(ee.ClassName))return`uint64:${BigInt(e.valueOf().toFixed())}`;if(e.hasClassOrSuperclass(be.ClassName))return`string:${e.valueOf()}`;if(e.hasClassOrSuperclass(ge.ClassName))return`bool:${e.valueOf()}`;if(e.hasClassOrSuperclass(fe.ClassName))return`address:${e.valueOf().toBech32()}`;if(e.hasClassOrSuperclass(Y.ClassName))return`token:${e.valueOf()}`;if(e.hasClassOrSuperclass(he.ClassName))return`hex:${e.valueOf().toString("hex")}`;if(e.hasClassOrSuperclass(We.ClassName))return`codemeta:${e.valueOf().toString()}`;if(e.getType().getName()==="EsdtTokenPayment"){let t=e.getFieldValue("token_identifier").valueOf(),r=e.getFieldValue("token_nonce").valueOf(),n=e.getFieldValue("amount").valueOf();return`asset:${t}|${r}|${n}`}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){let r=this.coreSerializer.nativeToString(e,t);return this.stringToTyped(r)}nativeToType(e){if(e.startsWith("composite")){let t=e.match(/\(([^)]+)\)/)?.[1];return new xe(...t.split(C.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(e==="string")return new ve;if(e==="uint8")return new Se;if(e==="uint16")return new Ee;if(e==="uint32")return new Ie;if(e==="uint64")return new Z;if(e==="biguint")return new z;if(e==="bool")return new de;if(e==="address")return new me;if(e==="token")return new X;if(e==="hex")return new ye;if(e==="codemeta")return new we;if(e==="asset")return new Ae("EsdtTokenPayment",[new G("token_identifier","",new X),new G("token_nonce","",new Z),new G("amount","",new z)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${e}`)}stringToTyped(e){let[t,r]=e.split(/:(.*)/,2);if(t==="null"||t===null)return new T;if(t==="option"){let n=this.stringToTyped(r);return n instanceof T?J.newMissingTyped(n.getType()):J.newProvided(n)}if(t==="optional"){let n=this.stringToTyped(r);return n instanceof T?K.newMissing():new K(n.getType(),n)}if(t==="list"){let[n,a]=r.split(Pe,2),i=a.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Ce(this.nativeToType(n),i)}if(t==="variadic"){let[n,a]=r.split(Pe,2),i=a.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new Re(new Ne(this.nativeToType(n)),i)}if(t.startsWith("composite")){let n=t.match(/\(([^)]+)\)/)?.[1],a=r.split(C.ArgCompositeSeparator),o=n.split(C.ArgCompositeSeparator),i=a.map((p,u)=>this.stringToTyped(`${o[u]}:${p}`)),c=i.map(p=>p.getType());return new Te(new xe(...c),i)}if(t==="string")return r?be.fromUTF8(r):new T;if(t==="uint8")return r?new Fe(Number(r)):new T;if(t==="uint16")return r?new Be(Number(r)):new T;if(t==="uint32")return r?new Ve(Number(r)):new T;if(t==="uint64")return r?new ee(BigInt(r)):new T;if(t==="biguint")return r?new Q(BigInt(r)):new T;if(t==="bool")return r?new ge(typeof r=="boolean"?r:r==="true"):new T;if(t==="address")return r?new fe(it.newFromBech32(r)):new T;if(t==="token")return r?new Y(r):new T;if(t==="hex")return r?he.fromHex(r):new T;if(t==="codemeta")return new We(st.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(t==="asset"){let n=r.split(C.ArgCompositeSeparator);return new ut(this.nativeToType("asset"),[new j(new Y(n[0]),"token_identifier"),new j(new ee(BigInt(n[1])),"token_nonce"),new j(new Q(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${t}`)}typeToString(e){if(e instanceof pt)return"option:"+this.typeToString(e.getFirstTypeParameter());if(e instanceof ct)return"optional:"+this.typeToString(e.getFirstTypeParameter());if(e instanceof ot)return"list:"+this.typeToString(e.getFirstTypeParameter());if(e instanceof Ne)return"variadic:"+this.typeToString(e.getFirstTypeParameter());if(e instanceof ve)return"string";if(e instanceof Se)return"uint8";if(e instanceof Ee)return"uint16";if(e instanceof Ie)return"uint32";if(e instanceof Z)return"uint64";if(e instanceof z)return"biguint";if(e instanceof de)return"bool";if(e instanceof me)return"address";if(e instanceof X)return"token";if(e instanceof ye)return"hex";if(e instanceof we)return"codemeta";if(e instanceof Ae&&e.getClassName()==="EsdtTokenPayment")return"asset";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${e.getClassName()}`)}};var V=class{constructor(e,t){this.config=e;this.chain=t;this.abi=new B(e,t),this.serializer=new E,this.cache=new ht(e.cache?.type)}async getTransactionExecutionResults(e,t){let{actionIndex:r}=Ue(e),n=this.cache.get(wt.WarpExecutable(this.config.env,e.meta?.hash||"",r))??[],a=await this.extractContractResults(e,t,n),o=yt(this.config,[],e,r,a),i=gt(e,a.results);return{success:t.status.isSuccessful(),warp:e,action:r,user:this.config.user?.wallets?.[this.chain.name]||null,txHash:t.hash,next:o,values:a.values,results:a.results,messages:i}}async extractContractResults(e,t,r){let{action:n,actionIndex:a}=Ue(e),o=[],i={};if(!e.results||n.type!=="contract")return{values:o,results:i};if(!Object.values(e.results).some(w=>w.includes("out")||w.includes("event"))){for(let[w,m]of Object.entries(e.results))i[w]=m;return{values:o,results:await U(e,i,a,r,this.config.transform?.runner)}}let p=await this.abi.getAbiForAction(n),u=new dt({abi:p}),y=new ft({abi:p}).parseExecute({transactionOnNetwork:t,function:n.func||void 0});for(let[w,m]of Object.entries(e.results)){if(m.startsWith(_e.Transform.Prefix))continue;if(m.startsWith("input.")){i[w]=m;continue}let v=ke(m);if(v!==null&&v!==a){i[w]=null;continue}let[W,A,b]=m.split(".");if(W==="event"){if(!A||isNaN(Number(b)))continue;let R=Number(b),h=mt(t,A),F=u.parseEvents({events:h})[0],P=Object.values(F)[R]||null;o.push(P),i[w]=P&&P.valueOf()}else if(W==="out"||W.startsWith("out[")){if(!A)continue;let R=Number(A),h=y.values[R-1]||null;b&&(h=h[b]||null),h&&typeof h=="object"&&(h="toFixed"in h?h.toFixed():h.valueOf()),o.push(h),i[w]=h&&h.valueOf()}else i[w]=m}return{values:o,results:await U(e,i,a,r)}}async extractQueryResults(e,t,r,n){let a=t.map(p=>this.serializer.typedToString(p)),o=t.map(p=>this.serializer.typedToNative(p)[1]),i={};if(!e.results)return{values:a,results:i};let c=p=>{let u=p.split(".").slice(1).map(y=>parseInt(y)-1);if(u.length===0)return;let l=o[u[0]];for(let y=1;y<u.length;y++){if(l==null)return;l=l[u[y]]}return l};for(let[p,u]of Object.entries(e.results)){if(u.startsWith(_e.Transform.Prefix))continue;let l=ke(u);if(l!==null&&l!==r){i[p]=null;continue}u.startsWith("out.")||u==="out"||u.startsWith("out[")?i[p]=c(u)||null:i[p]=u}return{values:a,results:await U(e,i,r,n)}}async resolveWarpResultsRecursively(e){let t=e.warp,r=e.entryActionIndex,n=e.executor,a=e.inputs,o=e.meta,i=new Map,c=new Set,p=this;async function u(m,v=[]){if(i.has(m))return i.get(m);if(c.has(m))throw new Error(`Circular dependency detected at action ${m}`);c.add(m);let W=t.actions[m-1];if(!W)throw new Error(`Action ${m} not found`);let A;if(W.type==="query")A=await n.executeQuery(t,m,v);else if(W.type==="collect")A=await n.executeCollect(t,m,v,o);else throw new Error(`Unsupported or interactive action type: ${W.type}`);if(i.set(m,A),t.results)for(let b of Object.values(t.results)){let h=String(b).match(/^out\[(\d+)\]/);if(h){let F=parseInt(h[1],10);F!==m&&!i.has(F)&&await u(F)}}return c.delete(m),A}await u(r,a);let l={};for(let m of i.values())for(let[v,W]of Object.entries(m.results))W!==null?l[v]=W:v in l||(l[v]=null);let y=await U(t,l,r,a,this.config.transform?.runner);return{...i.get(r),action:r,results:y}}};import{Address as Wt,AddressValue as xt,BigUIntType as Tt,BigUIntValue as Oe,BooleanValue as Ct,BytesValue as vt,CodeMetadata as bt,CodeMetadataValue as At,CompositeType as Et,CompositeValue as Bt,Field as te,FieldDefinition as re,List as It,NothingValue as Vt,OptionalValue as ne,OptionValue as ae,StringValue as St,Struct as Ft,StructType as Nt,TokenIdentifierType as Rt,TokenIdentifierValue as Me,U16Value as Pt,U32Value as Ut,U64Type as kt,U64Value as $e,U8Value as _t,VariadicValue as Ot}from"@multiversx/sdk-core";var Qr=(s,e)=>s?ae.newProvided(s):e?ae.newMissingTyped(e):ae.newMissing(),jr=(s,e)=>s?new ne(s.getType(),s):e?new ne(e):ne.newMissing(),Gr=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let e=s[0].getType();return new It(e,s)},Kr=s=>Ot.fromItems(...s),Jr=s=>{let e=s.map(t=>t.getType());return new Bt(new Et(...e),s)},Xr=s=>St.fromUTF8(s),Yr=s=>new _t(s),Zr=s=>new Pt(s),en=s=>new Ut(s),tn=s=>new $e(s),rn=s=>new Oe(BigInt(s)),nn=s=>new Ct(s),an=s=>new xt(Wt.newFromBech32(s)),sn=s=>new Me(s),on=s=>vt.fromHex(s),Le=s=>new Ft(new Nt("EsdtTokenPayment",[new re("token_identifier","",new Rt),new re("token_nonce","",new kt),new re("amount","",new Tt)]),[new te(new Me(s.token.identifier),"token_identifier"),new te(new $e(BigInt(s.token.nonce)),"token_nonce"),new te(new Oe(BigInt(s.amount)),"amount")]),cn=s=>new At(bt.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),pn=()=>new Vt;var d=class s{constructor(e,t){this.config=e;this.chain=t;this.serializer=new E,this.abi=new B(this.config,this.chain),this.results=new V(this.config,this.chain)}async createTransaction(e){let t=ie(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){let t=this.config.user?.wallets?.[e.chain.name];if(!t)throw new Error("WarpMultiversxExecutor: createTransfer - user address not set");let r=N.newFromBech32(t),n=new He({chainID:e.chain.chainId}),a=e.data?Buffer.from(this.serializer.stringToTyped(e.data).valueOf()):null;return new zt({config:n}).createTransactionForTransfer(r,{receiver:N.newFromBech32(e.destination),nativeAmount:e.value,tokenTransfers:e.transfers.map(o=>new De({token:new qe({identifier:o.identifier,nonce:BigInt(o.nonce)}),amount:o.amount})),data:a?new Uint8Array(a):void 0})}async createContractCallTransaction(e){let t=this.config.user?.wallets?.[e.chain.name];if(!t)throw new Error("WarpMultiversxExecutor: createContractCall - user address not set");let r=ie(e.warp,e.action),n=N.newFromBech32(t),a=e.args.map(i=>this.serializer.stringToTyped(i)),o=new He({chainID:e.chain.chainId});return new qt({config:o}).createTransactionForExecute(n,{contract:N.newFromBech32(e.destination),function:"func"in r&&r.func||"",gasLimit:"gasLimit"in r?BigInt(r.gasLimit||0):0n,arguments:a,nativeTransferAmount:e.value})}async executeQuery(e){let t=ie(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(b=>this.serializer.stringToTyped(b)),a=s.getChainEntrypoint(e.chain,this.config.env,this.config),o=N.newFromBech32(e.destination),i=a.createSmartContractController(r),c=i.createQuery({contract:o,function:t.func||"",arguments:n}),p=await i.runQuery(c),u=p.returnCode==="ok",l=new Mt,y=r.getEndpoint(p.function||t.func||""),w=(p.returnDataParts||[]).map(b=>Buffer.from(b)),m=l.buffersToValues(w,y.output),{values:v,results:W}=await this.results.extractQueryResults(e.warp,m,e.action,e.resolvedInputs),A=Jt(this.config,[],e.warp,e.action,W);return{success:u,warp:e.warp,action:e.action,user:this.config.user?.wallets?.[e.chain.name]||null,txHash:null,next:A,values:v,results:W,messages:Gt(e.warp,W)}}async preprocessInput(e,t,r,n){if(r==="asset"){let[a,o,i,c]=n.split(ze.ArgCompositeSeparator);if(c)return t;let p=new qe({identifier:a,nonce:BigInt(o||0)});if(!new Ht().isFungible(p))return t;let y=Kt(a)?.decimals;if(y||(y=(await(await fetch(`${e.defaultApiUrl}/tokens/${a}`)).json()).decimals),!y)throw new Error(`WarpActionExecutor: Decimals not found for token ${a}`);let w=Le(new De({token:p,amount:Yt(i,y)}));return this.serializer.typedToString(w)+ze.ArgCompositeSeparator+y}return t}static getChainEntrypoint(e,t,r){let n="warp-sdk",o=r?Xt(r,e.name,t,e.defaultApiUrl):e.defaultApiUrl;return t==="devnet"?new $t({url:o,kind:"api",clientName:n}):t==="testnet"?new Dt({url:o,kind:"api",clientName:n}):new Lt({url:o,kind:"api",clientName:n})}async signMessage(e,t){let r=Qt.fromString(t);return(await new jt(r).sign(new Uint8Array(Buffer.from(e,"utf-8")))).toString()}};var k=class{constructor(e){this.config=e}async getContract(e,t){try{let a=await d.getChainEntrypoint(t,this.config.env).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 d.getChainEntrypoint(t,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${e}/verification`);return{codeHash:a.codeHash,abi:a.source.abi}}catch(r){return Qe.error("WarpContractLoader: getVerificationInfo error",r),null}}};var B=class{constructor(e,t){this.config=e;this.chain=t;this.contractLoader=new k(this.config),this.cache=new Zt(this.config.cache?.type)}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,hash:e.hash,creator:e.sender.toBech32(),createdAt:new Date(e.timestamp*1e3).toISOString()},t}async createFromTransactionHash(e,t){let r=er.WarpAbi(this.config.env,e);if(t){let o=this.cache.get(r);if(o)return Ge.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${e}`),o}let a=d.getChainEntrypoint(this.chain,this.config.env).createNetworkProvider();try{let o=await a.getTransaction(e),i=await this.createFromTransaction(o);return t&&t.ttl&&i&&this.cache.set(r,i,t.ttl),i}catch(o){return Ge.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 se.create(t.abi)}async fetchAbi(e){if(!e.abi)throw new Error("WarpActionExecutor: ABI not found");if(e.abi.startsWith(je.IdentifierType.Hash)){let t=e.abi.split(je.IdentifierParamSeparatorDefault)[1],r=await this.createFromTransactionHash(t);if(!r)throw new Error(`WarpActionExecutor: ABI not found for hash: ${e.abi}`);return se.create(r.content)}else{let r=await(await fetch(e.abi)).json();return se.create(r)}}};import{Address as Ke,TransactionsFactoryConfig as tr,TransferTransactionsFactory as rr}from"@multiversx/sdk-core";import{WarpBrandBuilder as nr,WarpLogger as ar}from"@vleap/warps";import{Buffer as ir}from"buffer";var _=class{constructor(e,t){this.config=e;this.chain=t;this.core=new nr(e)}async createInscriptionTransaction(e){let t=this.config.user?.wallets?.[this.chain.name];if(!t)throw new Error("BrandBuilder: user address not set");let r=new tr({chainID:this.chain.chainId}),n=new rr({config:r}),a=Ke.newFromBech32(t),o=JSON.stringify(e);return await n.createTransactionForNativeTokenTransfer(a,{receiver:Ke.newFromBech32(t),nativeAmount:BigInt(0),data:Uint8Array.from(ir.from(o))})}async createFromTransaction(e,t=!1){return await this.core.createFromRaw(e.data.toString(),t)}async createFromTransactionHash(e){let r=d.getChainEntrypoint(this.chain,this.config.env).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 Je,TransactionsFactoryConfig as sr,TransferTransactionsFactory as or}from"@multiversx/sdk-core";import{WarpBuilder as Xe,WarpCache as cr,WarpCacheKey as pr,WarpLogger as Ye}from"@vleap/warps";var O=class extends Xe{constructor(t,r){super(t);this.config=t;this.chain=r;this.cache=new cr(t.cache?.type),this.core=new Xe(t)}async createInscriptionTransaction(t){let r=this.config.user?.wallets?.[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}),o=Je.newFromBech32(r),i=JSON.stringify(t),c=await a.createTransactionForTransfer(o,{receiver:Je.newFromBech32(r),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(i))});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,hash:t.hash,creator:t.sender.toBech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},n}async createFromTransactionHash(t,r){let n=pr.Warp(this.config.env,t);if(r){let i=this.cache.get(n);if(i)return Ye.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),i}let o=d.getChainEntrypoint(this.chain,this.config.env).createNetworkProvider();try{let i=await o.getTransaction(t),c=await this.createFromTransaction(i);return r&&r.ttl&&c&&this.cache.set(n,c,r.ttl),c}catch(i){return Ye.error("WarpBuilder: Error creating from transaction hash",i),null}}};import{Address as Ze}from"@multiversx/sdk-core";var M=class{constructor(e,t){this.config=e;this.chain=t}async getAccount(e){let r=await d.getChainEntrypoint(this.chain,this.config.env,this.config).createNetworkProvider().getAccount(Ze.newFromBech32(e));return{address:r.address.toBech32(),balance:r.balance}}async getAccountAssets(e){return(await d.getChainEntrypoint(this.chain,this.config.env,this.config).createNetworkProvider().getFungibleTokensOfAccount(Ze.newFromBech32(e))).map(n=>({identifier:n.token.identifier,name:n.raw.name,amount:n.amount,decimals:n.raw.decimals,logoUrl:n.raw.assets?.pngUrl||""}))}};var wa={Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}},ur=(r=>(r.MultiversxExplorer="multiversx_explorer",r.MultiversxExplorerDevnet="multiversx_explorer_devnet",r.MultiversxExplorerTestnet="multiversx_explorer_testnet",r))(ur||{}),lr=(r=>(r.VibechainExplorer="vibechain_explorer",r.VibechainExplorerDevnet="vibechain_explorer_devnet",r.VibechainExplorerTestnet="vibechain_explorer_testnet",r))(lr||{}),et={multiversx:{mainnet:["multiversx_explorer"],testnet:["multiversx_explorer_testnet"],devnet:["multiversx_explorer_devnet"]},vibechain:{mainnet:["vibechain_explorer"],testnet:["vibechain_explorer_testnet"],devnet:["vibechain_explorer_devnet"]}},I={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 $=class{constructor(e,t){this.chain=e;this.config=t}getExplorers(){let e=et[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=I[t];if(a)return a}if(e){let a=I[e];if(a)return a}let r=this.getPrimaryExplorer();return I[r]||I[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=I[n];a&&(r[n]=`${a}/accounts/${e}`)}),r}getTransactionUrls(e){let t=this.getAllExplorers(),r={};return t.forEach(n=>{let a=I[n];a&&(r[n]=`${a}/transactions/${e}`)}),r}};import{AbiRegistry as rt,Address as f,AddressValue as ce,BytesValue as g,SmartContractTransactionsFactory as fr,TransactionsFactoryConfig as dr}from"@multiversx/sdk-core";import{WarpCache as gr,WarpCacheKey as pe,WarpLogger as ue}from"@vleap/warps";var oe={buildInfo:{rustc:{version:"1.86.0",commitHash:"05f9846f893b09a1be1fc8560e33fc3c815cfecb",commitDate:"2025-03-31",channel:"Stable",short:"rustc 1.86.0 (05f9846f8 2025-03-31)"},contractCrate:{name:"registry",version:"0.0.1"},framework:{name:"multiversx-sc",version:"0.51.1"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"},{name:"vault",type:"Address"}],outputs:[]},upgradeConstructor:{inputs:[],outputs:[]},endpoints:[{name:"registerWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias_opt",type:"optional<bytes>",multi_arg:!0},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],outputs:[],allow_multiple_var_args:!0},{name:"unregisterWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"upgradeWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"alias",type:"bytes"},{name:"new_warp",type:"bytes"}],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"forceRemoveAlias",mutability:"mutable",inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"verifyWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"transferOwnership",mutability:"mutable",inputs:[{name:"warp",type:"bytes"},{name:"new_owner",type:"Address"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<InfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"setVault",onlyOwner:!0,mutability:"mutable",inputs:[{name:"vault",type:"Address"}],outputs:[]},{name:"setUnitPrice",onlyOwner:!0,mutability:"mutable",inputs:[{name:"amount",type:"BigUint"}],outputs:[]},{name:"addAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"removeAdmin",onlyOwner:!0,mutability:"mutable",inputs:[{name:"address",type:"Address"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"ConfigView"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]},{name:"setChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"},{name:"native_token",type:"bytes"}],outputs:[]},{name:"removeChain",onlyOwner:!0,mutability:"mutable",inputs:[{name:"name",type:"bytes"}],outputs:[]},{name:"getChain",mutability:"readonly",inputs:[{name:"name",type:"bytes"}],outputs:[{type:"ChainView"}]},{name:"getChains",mutability:"readonly",inputs:[],outputs:[{type:"variadic<ChainView>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0},{name:"trust",type:"bytes",indexed:!0}]},{identifier:"warpVerified",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"ownershipTransferred",inputs:[{name:"warp",type:"bytes",indexed:!0},{name:"old_owner",type:"Address",indexed:!0},{name:"new_owner",type:"Address",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{ChainView:{type:"struct",fields:[{name:"name",type:"bytes"},{name:"display_name",type:"bytes"},{name:"chain_id",type:"bytes"},{name:"block_time",type:"u32"},{name:"address_hrp",type:"bytes"},{name:"api_url",type:"bytes"},{name:"explorer_url",type:"bytes"},{name:"native_token",type:"bytes"}]},ConfigView:{type:"struct",fields:[{name:"unit_price",type:"BigUint"},{name:"admins",type:"List<Address>"}]},InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"owner",type:"Address"},{name:"created_at",type:"u64"},{name:"upgraded_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var x=s=>{if(s==="devnet")return"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36";if(s==="testnet")throw new Error("Multiversx testnet is not supported");return"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"};var L=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}),tt=s=>({unitPrice:BigInt(s.unit_price.toString()),admins:s.admins.map(e=>e.toBech32())});var q=class{constructor(e,t){this.config=e;this.chain=t;this.cache=new gr(e.cache?.type),this.registryConfig={unitPrice:BigInt(0),admins:[]},this.userWallet=this.config.user?.wallets?.[this.chain.name]||null}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=f.newFromBech32(this.userWallet),a=()=>this.isCurrentUserAdmin()?BigInt(0):t&&r?this.registryConfig.unitPrice*BigInt(3):t?this.registryConfig.unitPrice*BigInt(2):this.registryConfig.unitPrice,o=()=>t&&r?[g.fromHex(e),g.fromUTF8(t),g.fromHex(r)]:t?[g.fromHex(e),g.fromUTF8(t)]:[g.fromHex(e)];return await this.getFactory().createTransactionForExecute(n,{contract:f.newFromBech32(x(this.config.env)),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:a(),arguments:o()})}async createWarpUnregisterTransaction(e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=f.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(t,{contract:f.newFromBech32(x(this.config.env)),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[g.fromHex(e)]})}async createWarpUpgradeTransaction(e,t){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 r=f.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(r,{contract:f.newFromBech32(x(this.config.env)),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[g.fromUTF8(e),g.fromHex(t)]})}async createWarpAliasSetTransaction(e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let r=f.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(r,{contract:f.newFromBech32(x(this.config.env)),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[g.fromHex(e),g.fromUTF8(t)]})}async createWarpVerifyTransaction(e){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let t=f.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(t,{contract:f.newFromBech32(x(this.config.env)),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[g.fromHex(e)]})}async createWarpTransferOwnershipTransaction(e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let r=f.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(r,{contract:f.newFromBech32(x(this.config.env)),function:"transferOwnership",gasLimit:BigInt(1e7),arguments:[g.fromHex(e),new ce(new f(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=f.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(t,{contract:f.newFromBech32(x(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[g.fromHex(e)]})}async createWarpBrandingTransaction(e,t){if(!this.userWallet)throw new Error("WarpRegistry: user address not set");let r=f.newFromBech32(this.userWallet);return await this.getFactory().createTransactionForExecute(r,{contract:f.newFromBech32(x(this.config.env)),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[g.fromHex(e),g.fromHex(t)]})}async getInfoByAlias(e,t){try{let r=pe.RegistryInfo(this.config.env,e),n=t?this.cache.get(r):null;if(n)return ue.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${e}`),n;let a=f.newFromBech32(x(this.config.env)),o=this.getController(),i=o.createQuery({contract:a,function:"getInfoByAlias",arguments:[g.fromUTF8(e)]}),c=await o.runQuery(i),[p]=o.parseQueryResponse(c),u=p?L(p):null,l=u?.brand?await this.fetchBrand(u.brand):null;return t&&t.ttl&&this.cache.set(r,{registryInfo:u,brand:l},t.ttl),{registryInfo:u,brand:l}}catch{return{registryInfo:null,brand:null}}}async getInfoByHash(e,t){try{let r=pe.RegistryInfo(this.config.env,e);if(t){let l=this.cache.get(r);if(l)return ue.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${e}`),l}let n=f.newFromBech32(x(this.config.env)),a=this.getController(),o=a.createQuery({contract:n,function:"getInfoByHash",arguments:[g.fromHex(e)]}),i=await a.runQuery(o),[c]=a.parseQueryResponse(i),p=c?L(c):null,u=p?.brand?await this.fetchBrand(p.brand):null;return t&&t.ttl&&this.cache.set(r,{registryInfo:p,brand:u},t.ttl),{registryInfo:p,brand:u}}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=f.newFromBech32(x(this.config.env)),n=this.getController(),a=n.createQuery({contract:r,function:"getUserWarps",arguments:[new ce(new f(t))]}),o=await n.runQuery(a),[i]=n.parseQueryResponse(o);return i.map(L)}catch{return[]}}async getUserBrands(e){try{let t=e||this.userWallet;if(!t)throw new Error("WarpRegistry: user address not set");let r=f.newFromBech32(x(this.config.env)),n=this.getController(),a=n.createQuery({contract:r,function:"getUserBrands",arguments:[new ce(new f(t))]}),o=await n.runQuery(a),[i]=n.parseQueryResponse(o),c=i.map(l=>l.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(c.map(l=>this.fetchBrand(l,p)))).filter(l=>l!==null)}catch{return[]}}async fetchBrand(e,t){let r=pe.Brand(this.config.env,e),n=t?this.cache.get(r):null;if(n)return ue.info(`WarpRegistry (fetchBrand): Brand found in cache: ${e}`),n;let o=d.getChainEntrypoint(this.chain,this.config.env).createNetworkProvider();try{let i=await o.getTransaction(e),c=JSON.parse(i.data.toString());return c.meta={hash:i.hash,creator:i.sender.toBech32(),createdAt:new Date(i.timestamp*1e3).toISOString()},t&&t.ttl&&this.cache.set(r,c,t.ttl),c}catch{return null}}async loadRegistryConfigs(){let e=f.newFromBech32(x(this.config.env)),t=this.getController(),[r]=await t.query({contract:e,function:"getConfig",arguments:[]}),n=r?tt(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let e=new dr({chainID:this.chain.chainId}),t=rt.create(oe);return new fr({config:e,abi:t})}getController(){let e=d.getChainEntrypoint(this.chain,this.config.env),t=rt.create(oe);return e.createSmartContractController(t)}isCurrentUserAdmin(){return!!this.userWallet&&this.registryConfig.admins.includes(this.userWallet)}};var D=(s,e,t)=>(r,n)=>{let a=t[r.env];return{chain:s,chainInfo:a,prefix:e,builder:()=>new O(r,a),executor:new d(r,a),results:new V(r,a),serializer:new E,registry:new q(r,a),explorer:new $(s,r),abiBuilder:()=>new B(r,a),brandBuilder:()=>new _(r,a),dataLoader:new M(r,a),registerTypes:o=>{o.registerType("token",{stringToNative:i=>i,nativeToString:i=>`token:${i}`}),o.registerType("codemeta",{stringToNative:i=>i,nativeToString:i=>`codemeta:${i}`})}}};var S="multiversx",nt=D(S,"mvx",{mainnet:{name:S,displayName:"MultiversX",chainId:"1",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://api.multiversx.com",nativeToken:"EGLD"},testnet:{name:S,displayName:"MultiversX Testnet",chainId:"T",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://testnet-api.multiversx.com",nativeToken:"EGLD"},devnet:{name:S,displayName:"MultiversX Devnet",chainId:"D",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://devnet-api.multiversx.com",nativeToken:"EGLD"}});var H="vibechain",le={name:H,displayName:"VibeChain",chainId:"V",blockTime:600,addressHrp:"vibe",defaultApiUrl:"https://vibeox-api.multiversx.com",nativeToken:"VIBE"},at=D(H,"vibe",{mainnet:le,testnet:le,devnet:le});var ai=(s,e)=>[nt(s,e),at(s,e)],ii=()=>[S,H];export{S as ChainNameMultiversx,H as ChainNameVibechain,I as ExplorerUrls,ur as MultiversxExplorers,et as MultiversxExplorersConfig,lr as VibechainExplorers,B as WarpMultiversxAbiBuilder,_ as WarpMultiversxBrandBuilder,O as WarpMultiversxBuilder,wa as WarpMultiversxConstants,k as WarpMultiversxContractLoader,d as WarpMultiversxExecutor,$ as WarpMultiversxExplorer,q as WarpMultiversxRegistry,V as WarpMultiversxResults,E as WarpMultiversxSerializer,an as address_value,rn as biguint_value,nn as boolean_value,cn as codemeta_value,Jr as composite_value,D as createMultiversxAdapter,Le as esdt_value,ai as getAllMultiversxAdapters,ii as getAllMultiversxChainNames,nt as getMultiversxAdapter,x as getMultiversxRegistryAddress,at as getVibechainAdapter,on as hex_value,Gr as list_value,pn as nothing_value,Qr as option_value,jr as optional_value,Xr as string_value,sn as token_value,Zr as u16_value,en as u32_value,tn as u64_value,Yr as u8_value,Kr as variadic_value};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vleap/warps-adapter-multiversx",
3
- "version": "0.2.0-alpha.32",
3
+ "version": "0.2.0-alpha.34",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",
@@ -37,6 +37,6 @@
37
37
  },
38
38
  "dependencies": {
39
39
  "@multiversx/sdk-core": "^15.0.1",
40
- "@vleap/warps": "^3.0.0-alpha.78"
40
+ "@vleap/warps": "^3.0.0-alpha.83"
41
41
  }
42
42
  }