@vleap/warps-adapter-multiversx 0.2.0-alpha.36 → 0.2.0-alpha.37

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 +1 -1
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{AbiRegistry as se}from"@multiversx/sdk-core";import{WarpCache as tr,WarpCacheKey as rr,WarpConstants as Ge,WarpLogger as Ke}from"@vleap/warps";import{WarpLogger as je}from"@vleap/warps";import{Address as N,ArgSerializer as $t,DevnetEntrypoint as Lt,MainnetEntrypoint as qt,SmartContractTransactionsFactory as Dt,TestnetEntrypoint as Ht,Token as De,TokenComputer as zt,TokenTransfer as He,TransactionsFactoryConfig as ze,TransferTransactionsFactory as Qt,UserSecretKey as jt,UserSigner as Gt}from"@multiversx/sdk-core";import{EGLD_IDENTIFIER_FOR_MULTI_ESDTNFT_TRANSFER as Kt}from"@multiversx/sdk-core/out/core/constants";import{applyResultsToMessages as Jt,findKnownTokenById as Xt,getNextInfo as Yt,getProviderUrl as Zt,getWarpActionByIndex as ie,shiftBigintBy as er,WarpConstants as Qe}from"@vleap/warps";import{findEventsByFirstTopic as ft,SmartContractTransactionsOutcomeParser as dt,TransactionEventsParser as gt}from"@multiversx/sdk-core";import{applyResultsToMessages as ht,evaluateResultsCommon as U,findWarpExecutableAction as Pe,getNextInfo as yt,parseResultsOutIndex as _e,WarpCache as wt,WarpCacheKey as Wt,WarpConstants as Oe}from"@vleap/warps";import{Address as st,AddressType as fe,AddressValue as de,BigUIntType as z,BigUIntValue as Q,BooleanType as ge,BooleanValue as he,BytesType as ye,BytesValue as we,CodeMetadata as ot,CodeMetadataType as We,CodeMetadataValue as Te,CompositeType as xe,CompositeValue as ve,Field as j,FieldDefinition as G,List as Ce,ListType as ct,NothingValue as x,OptionalType as pt,OptionalValue as K,OptionType as ut,OptionValue as J,StringType as be,StringValue as Ae,Struct as lt,StructType as Ee,TokenIdentifierType as X,TokenIdentifierValue as Y,U16Type as Be,U16Value as Ie,U32Type as Ve,U32Value as Se,U64Type as Z,U64Value as ee,U8Type as Fe,U8Value as Ne,VariadicType as Re,VariadicValue as ke}from"@multiversx/sdk-core";import{WarpConstants as v,WarpSerializer as mt}from"@vleap/warps";var Ue=new RegExp(`${v.ArgParamsSeparator}(.*)`),E=class{constructor(){this.coreSerializer=new mt}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(v.ArgParamsSeparator)[0])[0],a=t.map(o=>this.typedToString(o).split(v.ArgParamsSeparator)[1]);return`list:${n}:${a.join(",")}`}if(e.hasClassOrSuperclass(ke.ClassName)){let t=e.getItems(),n=t.map(o=>this.typedToString(o).split(v.ArgParamsSeparator)[0])[0],a=t.map(o=>this.typedToString(o).split(v.ArgParamsSeparator)[1]);return`variadic:${n}:${a.join(",")}`}if(e.hasClassOrSuperclass(ve.ClassName)){let t=e.getItems(),r=t.map(i=>this.typedToString(i).split(v.ArgParamsSeparator)[0]),n=t.map(i=>this.typedToString(i).split(v.ArgParamsSeparator)[1]),a=r.join(v.ArgCompositeSeparator),o=n.join(v.ArgCompositeSeparator);return`composite(${a}):${o}`}if(e.hasClassOrSuperclass(Q.ClassName)||e.getType().getName()==="BigUint")return`biguint:${BigInt(e.valueOf().toFixed())}`;if(e.hasClassOrSuperclass(Ne.ClassName))return`uint8:${e.valueOf().toNumber()}`;if(e.hasClassOrSuperclass(Ie.ClassName))return`uint16:${e.valueOf().toNumber()}`;if(e.hasClassOrSuperclass(Se.ClassName))return`uint32:${e.valueOf().toNumber()}`;if(e.hasClassOrSuperclass(ee.ClassName))return`uint64:${BigInt(e.valueOf().toFixed())}`;if(e.hasClassOrSuperclass(Ae.ClassName))return`string:${e.valueOf()}`;if(e.hasClassOrSuperclass(he.ClassName))return`bool:${e.valueOf()}`;if(e.hasClassOrSuperclass(de.ClassName))return`address:${e.valueOf().toBech32()}`;if(e.hasClassOrSuperclass(Y.ClassName))return`token:${e.valueOf()}`;if(e.hasClassOrSuperclass(we.ClassName))return`hex:${e.valueOf().toString("hex")}`;if(e.hasClassOrSuperclass(Te.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(v.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(e==="string")return new be;if(e==="uint8")return new Fe;if(e==="uint16")return new Be;if(e==="uint32")return new Ve;if(e==="uint64")return new Z;if(e==="biguint")return new z;if(e==="bool")return new ge;if(e==="address")return new fe;if(e==="token")return new X;if(e==="hex")return new ye;if(e==="codemeta")return new We;if(e==="asset")return new Ee("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 x;if(t==="option"){let n=this.stringToTyped(r);return n instanceof x?J.newMissingTyped(n.getType()):J.newProvided(n)}if(t==="optional"){let n=this.stringToTyped(r);return n instanceof x?K.newMissing():new K(n.getType(),n)}if(t==="list"){let[n,a]=r.split(Ue,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(Ue,2),i=a.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new ke(new Re(this.nativeToType(n)),i)}if(t.startsWith("composite")){let n=t.match(/\(([^)]+)\)/)?.[1],a=r.split(v.ArgCompositeSeparator),o=n.split(v.ArgCompositeSeparator),i=a.map((p,u)=>this.stringToTyped(`${o[u]}:${p}`)),c=i.map(p=>p.getType());return new ve(new xe(...c),i)}if(t==="string")return r?Ae.fromUTF8(r):new x;if(t==="uint8")return r?new Ne(Number(r)):new x;if(t==="uint16")return r?new Ie(Number(r)):new x;if(t==="uint32")return r?new Se(Number(r)):new x;if(t==="uint64")return r?new ee(BigInt(r)):new x;if(t==="biguint")return r?new Q(BigInt(r)):new x;if(t==="bool")return r?new he(typeof r=="boolean"?r:r==="true"):new x;if(t==="address")return r?new de(st.newFromBech32(r)):new x;if(t==="token")return r?new Y(r):new x;if(t==="hex")return r?we.fromHex(r):new x;if(t==="codemeta")return new Te(ot.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(t==="asset"){let n=r.split(v.ArgCompositeSeparator);return new lt(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 ut)return"option:"+this.typeToString(e.getFirstTypeParameter());if(e instanceof pt)return"optional:"+this.typeToString(e.getFirstTypeParameter());if(e instanceof ct)return"list:"+this.typeToString(e.getFirstTypeParameter());if(e instanceof Re)return"variadic:"+this.typeToString(e.getFirstTypeParameter());if(e instanceof be)return"string";if(e instanceof Fe)return"uint8";if(e instanceof Be)return"uint16";if(e instanceof Ve)return"uint32";if(e instanceof Z)return"uint64";if(e instanceof z)return"biguint";if(e instanceof ge)return"bool";if(e instanceof fe)return"address";if(e instanceof X)return"token";if(e instanceof ye)return"hex";if(e instanceof We)return"codemeta";if(e instanceof Ee&&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 wt(e.cache?.type)}async getTransactionExecutionResults(e,t){let{actionIndex:r}=Pe(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=ht(e,a.results);return{success:t.status.isSuccessful(),warp:e,action:r,user:this.config.user?.wallets?.[this.chain.name]||null,txHash:t.hash,tx:t,next:o,values:a.values,results:a.results,messages:i}}async extractContractResults(e,t,r){let{action:n,actionIndex:a}=Pe(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 gt({abi:p}),h=new dt({abi:p}).parseExecute({transactionOnNetwork:t,function:n.func||void 0});for(let[w,m]of Object.entries(e.results)){if(m.startsWith(Oe.Transform.Prefix))continue;if(m.startsWith("input.")){i[w]=m;continue}let C=_e(m);if(C!==null&&C!==a){i[w]=null;continue}let[W,A,b]=m.split(".");if(W==="event"){if(!A||isNaN(Number(b)))continue;let R=Number(b),y=ft(t,A),F=u.parseEvents({events:y})[0],k=Object.values(F)[R]||null;o.push(k),i[w]=k&&k.valueOf()}else if(W==="out"||W.startsWith("out[")){if(!A)continue;let R=Number(A),y=h.values[R-1]||null;b&&(y=y[b]||null),y&&typeof y=="object"&&(y="toFixed"in y?y.toFixed():y.valueOf()),o.push(y),i[w]=y&&y.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(h=>parseInt(h)-1);if(u.length===0)return;let l=o[u[0]];for(let h=1;h<u.length;h++){if(l==null)return;l=l[u[h]]}return l};for(let[p,u]of Object.entries(e.results)){if(u.startsWith(Oe.Transform.Prefix))continue;let l=_e(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,C=[]){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,C);else if(W.type==="collect")A=await n.executeCollect(t,m,C,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 y=String(b).match(/^out\[(\d+)\]/);if(y){let F=parseInt(y[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[C,W]of Object.entries(m.results))W!==null?l[C]=W:C in l||(l[C]=null);let h=await U(t,l,r,a,this.config.transform?.runner);return{...i.get(r),action:r,results:h}}};import{Address as Tt,AddressValue as xt,BigUIntType as vt,BigUIntValue as Me,BooleanValue as Ct,BytesValue as bt,CodeMetadata as At,CodeMetadataValue as Et,CompositeType as Bt,CompositeValue as It,Field as te,FieldDefinition as re,List as Vt,NothingValue as St,OptionalValue as ne,OptionValue as ae,StringValue as Ft,Struct as Nt,StructType as Rt,TokenIdentifierType as kt,TokenIdentifierValue as $e,U16Value as Ut,U32Value as Pt,U64Type as _t,U64Value as Le,U8Value as Ot,VariadicValue as Mt}from"@multiversx/sdk-core";var Kr=(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(),Xr=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let e=s[0].getType();return new Vt(e,s)},Yr=s=>Mt.fromItems(...s),Zr=s=>{let e=s.map(t=>t.getType());return new It(new Bt(...e),s)},en=s=>Ft.fromUTF8(s),tn=s=>new Ot(s),rn=s=>new Ut(s),nn=s=>new Pt(s),an=s=>new Le(s),sn=s=>new Me(BigInt(s)),on=s=>new Ct(s),cn=s=>new xt(Tt.newFromBech32(s)),pn=s=>new $e(s),un=s=>bt.fromHex(s),qe=s=>new Nt(new Rt("EsdtTokenPayment",[new re("token_identifier","",new kt),new re("token_nonce","",new _t),new re("amount","",new vt)]),[new te(new $e(s.token.identifier),"token_identifier"),new te(new Le(BigInt(s.token.nonce)),"token_nonce"),new te(new Me(BigInt(s.amount)),"amount")]),ln=s=>new Et(At.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),mn=()=>new St;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 ze({chainID:e.chain.chainId}),a=e.data?Buffer.from(this.serializer.stringToTyped(e.data).valueOf()):null;return new Qt({config:n}).createTransactionForTransfer(r,{receiver:N.newFromBech32(e.destination),nativeAmount:e.value,tokenTransfers:this.toTokenTransfers(e.transfers),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 ze({chainID:e.chain.chainId});return new Dt({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,tokenTransfers:this.toTokenTransfers(e.transfers),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,h=r.getEndpoint(p.function||t.func||""),w=(p.returnDataParts||[]).map(b=>Buffer.from(b)),m=l.buffersToValues(w,h.output),{values:C,results:W}=await this.results.extractQueryResults(e.warp,m,e.action,e.resolvedInputs),A=Yt(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,tx:null,next:A,values:C,results:W,messages:Jt(e.warp,W)}}async preprocessInput(e,t,r,n){if(r==="asset"){let[a,o,i,c]=n.split(Qe.ArgCompositeSeparator);if(c)return t;let p=new De({identifier:a,nonce:BigInt(o||0)});if(!new zt().isFungible(p))return t;let h=Xt(a)?.decimals;if(h||(h=(await(await fetch(`${e.defaultApiUrl}/tokens/${a}`)).json()).decimals),!h)throw new Error(`WarpActionExecutor: Decimals not found for token ${a}`);let w=qe(new He({token:p,amount:er(i,h)}));return this.serializer.typedToString(w)+Qe.ArgCompositeSeparator+h}return t}static getChainEntrypoint(e,t,r){let n="warp-sdk",o=r?Zt(r,e.name,t,e.defaultApiUrl):e.defaultApiUrl;return t==="devnet"?new Lt({url:o,kind:"api",clientName:n}):t==="testnet"?new Ht({url:o,kind:"api",clientName:n}):new qt({url:o,kind:"api",clientName:n})}async signMessage(e,t){let r=jt.fromString(t);return(await new Gt(r).sign(new Uint8Array(Buffer.from(e,"utf-8")))).toString()}toTokenTransfers(e){return e.map(t=>t.identifier===this.chain.nativeToken.identifier?{...t,identifier:Kt}:t).map(t=>new He({token:new De({identifier:t.identifier,nonce:t.nonce}),amount:t.amount}))}};var P=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 je.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 je.error("WarpContractLoader: getVerificationInfo error",r),null}}};var B=class{constructor(e,t){this.config=e;this.chain=t;this.contractLoader=new P(this.config),this.cache=new tr(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=rr.WarpAbi(this.config.env,e);if(t){let o=this.cache.get(r);if(o)return Ke.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 Ke.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(Ge.IdentifierType.Hash)){let t=e.abi.split(Ge.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 nr,TransferTransactionsFactory as ar}from"@multiversx/sdk-core";import{WarpBrandBuilder as ir,WarpLogger as sr}from"@vleap/warps";import{Buffer as or}from"buffer";var _=class{constructor(e,t){this.config=e;this.chain=t;this.core=new ir(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 nr({chainID:this.chain.chainId}),n=new ar({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(or.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 sr.error("BrandBuilder: Error creating from transaction hash",n),null}}};import{Address as Xe,TransactionsFactoryConfig as cr,TransferTransactionsFactory as pr}from"@multiversx/sdk-core";import{WarpBuilder as Ye,WarpCache as ur,WarpCacheKey as lr,WarpLogger as Ze}from"@vleap/warps";var O=class extends Ye{constructor(t,r){super(t);this.config=t;this.chain=r;this.cache=new ur(t.cache?.type),this.core=new Ye(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 cr({chainID:this.chain.chainId}),a=new pr({config:n}),o=Xe.newFromBech32(r),i=JSON.stringify(t),c=await a.createTransactionForTransfer(o,{receiver:Xe.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=lr.Warp(this.config.env,t);if(r){let i=this.cache.get(n);if(i)return Ze.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 Ze.error("WarpBuilder: Error creating from transaction hash",i),null}}};import{Address as et}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(et.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(et.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 Ca={Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}},mr=(r=>(r.MultiversxExplorer="multiversx_explorer",r.MultiversxExplorerDevnet="multiversx_explorer_devnet",r.MultiversxExplorerTestnet="multiversx_explorer_testnet",r))(mr||{}),fr=(r=>(r.VibechainExplorer="vibechain_explorer",r.VibechainExplorerDevnet="vibechain_explorer_devnet",r.VibechainExplorerTestnet="vibechain_explorer_testnet",r))(fr||{}),tt={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=tt[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 nt,Address as f,AddressValue as ce,BytesValue as g,SmartContractTransactionsFactory as gr,TransactionsFactoryConfig as hr}from"@multiversx/sdk-core";import{WarpCache as yr,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 T=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}),rt=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 yr(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(T(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(T(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(T(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(T(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(T(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(T(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(T(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(T(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(T(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(T(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(T(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(T(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(T(this.config.env)),t=this.getController(),[r]=await t.query({contract:e,function:"getConfig",arguments:[]}),n=r?rt(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let e=new hr({chainID:this.chain.chainId}),t=nt.create(oe);return new gr({config:e,abi:t})}getController(){let e=d.getChainEntrypoint(this.chain,this.config.env),t=nt.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",le={identifier:"EGLD",name:"EGLD",decimals:18,logoUrl:"https://vleap.ai/images/tokens/egld.svg"},at=D(S,"mvx",{mainnet:{name:S,displayName:"MultiversX",chainId:"1",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://api.multiversx.com",nativeToken:le},testnet:{name:S,displayName:"MultiversX Testnet",chainId:"T",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://testnet-api.multiversx.com",nativeToken:le},devnet:{name:S,displayName:"MultiversX Devnet",chainId:"D",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://devnet-api.multiversx.com",nativeToken:le}});var H="vibechain",wr={identifier:"VIBE",name:"VIBE",decimals:18,logoUrl:"https://vleap.ai/images/tokens/vibe.svg"},me={name:H,displayName:"VibeChain",chainId:"V",blockTime:600,addressHrp:"vibe",defaultApiUrl:"https://vibeox-api.multiversx.com",nativeToken:wr},it=D(H,"vibe",{mainnet:me,testnet:me,devnet:me});var pi=(s,e)=>[at(s,e),it(s,e)],ui=()=>[S,H];export{S as ChainNameMultiversx,H as ChainNameVibechain,I as ExplorerUrls,mr as MultiversxExplorers,tt as MultiversxExplorersConfig,le as NativeTokenEgld,wr as NativeTokenVibe,fr as VibechainExplorers,B as WarpMultiversxAbiBuilder,_ as WarpMultiversxBrandBuilder,O as WarpMultiversxBuilder,Ca as WarpMultiversxConstants,P as WarpMultiversxContractLoader,d as WarpMultiversxExecutor,$ as WarpMultiversxExplorer,q as WarpMultiversxRegistry,V as WarpMultiversxResults,E as WarpMultiversxSerializer,cn as address_value,sn as biguint_value,on as boolean_value,ln as codemeta_value,Zr as composite_value,D as createMultiversxAdapter,qe as esdt_value,pi as getAllMultiversxAdapters,ui as getAllMultiversxChainNames,at as getMultiversxAdapter,T as getMultiversxRegistryAddress,it as getVibechainAdapter,un as hex_value,Xr as list_value,mn as nothing_value,Kr as option_value,Jr as optional_value,en as string_value,pn as token_value,rn as u16_value,nn as u32_value,an as u64_value,tn as u8_value,Yr as variadic_value};
1
+ import{AbiRegistry as se}from"@multiversx/sdk-core";import{WarpCache as tr,WarpCacheKey as rr,WarpConstants as Ge,WarpLogger as Ke}from"@vleap/warps";import{WarpLogger as je}from"@vleap/warps";import{Address as N,ArgSerializer as $t,DevnetEntrypoint as Lt,MainnetEntrypoint as qt,SmartContractTransactionsFactory as Dt,TestnetEntrypoint as Ht,Token as De,TokenComputer as zt,TokenTransfer as He,TransactionsFactoryConfig as ze,TransferTransactionsFactory as Qt,UserSecretKey as jt,UserSigner as Gt}from"@multiversx/sdk-core";import{EGLD_IDENTIFIER_FOR_MULTI_ESDTNFT_TRANSFER as Kt}from"@multiversx/sdk-core/out/core/constants";import{applyResultsToMessages as Jt,findKnownTokenById as Xt,getNextInfo as Yt,getProviderUrl as Zt,getWarpActionByIndex as ie,shiftBigintBy as er,WarpConstants as Qe}from"@vleap/warps";import{findEventsByFirstTopic as ft,SmartContractTransactionsOutcomeParser as dt,TransactionEventsParser as gt}from"@multiversx/sdk-core";import{applyResultsToMessages as ht,evaluateResultsCommon as U,findWarpExecutableAction as Pe,getNextInfo as yt,parseResultsOutIndex as _e,WarpCache as wt,WarpCacheKey as Wt,WarpConstants as Oe}from"@vleap/warps";import{Address as st,AddressType as fe,AddressValue as de,BigUIntType as z,BigUIntValue as Q,BooleanType as ge,BooleanValue as he,BytesType as ye,BytesValue as we,CodeMetadata as ot,CodeMetadataType as We,CodeMetadataValue as Te,CompositeType as xe,CompositeValue as ve,Field as j,FieldDefinition as G,List as Ce,ListType as ct,NothingValue as x,OptionalType as pt,OptionalValue as K,OptionType as ut,OptionValue as J,StringType as be,StringValue as Ae,Struct as lt,StructType as Ee,TokenIdentifierType as X,TokenIdentifierValue as Y,U16Type as Be,U16Value as Ie,U32Type as Ve,U32Value as Se,U64Type as Z,U64Value as ee,U8Type as Fe,U8Value as Ne,VariadicType as Re,VariadicValue as ke}from"@multiversx/sdk-core";import{WarpConstants as v,WarpSerializer as mt}from"@vleap/warps";var Ue=new RegExp(`${v.ArgParamsSeparator}(.*)`),E=class{constructor(){this.coreSerializer=new mt}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(v.ArgParamsSeparator)[0])[0],a=t.map(o=>this.typedToString(o).split(v.ArgParamsSeparator)[1]);return`list:${n}:${a.join(",")}`}if(e.hasClassOrSuperclass(ke.ClassName)){let t=e.getItems(),n=t.map(o=>this.typedToString(o).split(v.ArgParamsSeparator)[0])[0],a=t.map(o=>this.typedToString(o).split(v.ArgParamsSeparator)[1]);return`variadic:${n}:${a.join(",")}`}if(e.hasClassOrSuperclass(ve.ClassName)){let t=e.getItems(),r=t.map(i=>this.typedToString(i).split(v.ArgParamsSeparator)[0]),n=t.map(i=>this.typedToString(i).split(v.ArgParamsSeparator)[1]),a=r.join(v.ArgCompositeSeparator),o=n.join(v.ArgCompositeSeparator);return`composite(${a}):${o}`}if(e.hasClassOrSuperclass(Q.ClassName)||e.getType().getName()==="BigUint")return`biguint:${BigInt(e.valueOf().toFixed())}`;if(e.hasClassOrSuperclass(Ne.ClassName))return`uint8:${e.valueOf().toNumber()}`;if(e.hasClassOrSuperclass(Ie.ClassName))return`uint16:${e.valueOf().toNumber()}`;if(e.hasClassOrSuperclass(Se.ClassName))return`uint32:${e.valueOf().toNumber()}`;if(e.hasClassOrSuperclass(ee.ClassName))return`uint64:${BigInt(e.valueOf().toFixed())}`;if(e.hasClassOrSuperclass(Ae.ClassName))return`string:${e.valueOf()}`;if(e.hasClassOrSuperclass(he.ClassName))return`bool:${e.valueOf()}`;if(e.hasClassOrSuperclass(de.ClassName))return`address:${e.valueOf().toBech32()}`;if(e.hasClassOrSuperclass(Y.ClassName))return`token:${e.valueOf()}`;if(e.hasClassOrSuperclass(we.ClassName))return`hex:${e.valueOf().toString("hex")}`;if(e.hasClassOrSuperclass(Te.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(v.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(e==="string")return new be;if(e==="uint8")return new Fe;if(e==="uint16")return new Be;if(e==="uint32")return new Ve;if(e==="uint64")return new Z;if(e==="biguint")return new z;if(e==="bool")return new ge;if(e==="address")return new fe;if(e==="token")return new X;if(e==="hex")return new ye;if(e==="codemeta")return new We;if(e==="asset")return new Ee("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 x;if(t==="option"){let n=this.stringToTyped(r);return n instanceof x?J.newMissingTyped(n.getType()):J.newProvided(n)}if(t==="optional"){let n=this.stringToTyped(r);return n instanceof x?K.newMissing():new K(n.getType(),n)}if(t==="list"){let[n,a]=r.split(Ue,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(Ue,2),i=a.split(",").map(c=>this.stringToTyped(`${n}:${c}`));return new ke(new Re(this.nativeToType(n)),i)}if(t.startsWith("composite")){let n=t.match(/\(([^)]+)\)/)?.[1],a=r.split(v.ArgCompositeSeparator),o=n.split(v.ArgCompositeSeparator),i=a.map((p,u)=>this.stringToTyped(`${o[u]}:${p}`)),c=i.map(p=>p.getType());return new ve(new xe(...c),i)}if(t==="string")return r?Ae.fromUTF8(r):new x;if(t==="uint8")return r?new Ne(Number(r)):new x;if(t==="uint16")return r?new Ie(Number(r)):new x;if(t==="uint32")return r?new Se(Number(r)):new x;if(t==="uint64")return r?new ee(BigInt(r)):new x;if(t==="biguint")return r?new Q(BigInt(r)):new x;if(t==="bool")return r?new he(typeof r=="boolean"?r:r==="true"):new x;if(t==="address")return r?new de(st.newFromBech32(r)):new x;if(t==="token")return r?new Y(r):new x;if(t==="hex")return r?we.fromHex(r):new x;if(t==="codemeta")return new Te(ot.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(t==="asset"){let n=r.split(v.ArgCompositeSeparator);return new lt(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 ut)return"option:"+this.typeToString(e.getFirstTypeParameter());if(e instanceof pt)return"optional:"+this.typeToString(e.getFirstTypeParameter());if(e instanceof ct)return"list:"+this.typeToString(e.getFirstTypeParameter());if(e instanceof Re)return"variadic:"+this.typeToString(e.getFirstTypeParameter());if(e instanceof be)return"string";if(e instanceof Fe)return"uint8";if(e instanceof Be)return"uint16";if(e instanceof Ve)return"uint32";if(e instanceof Z)return"uint64";if(e instanceof z)return"biguint";if(e instanceof ge)return"bool";if(e instanceof fe)return"address";if(e instanceof X)return"token";if(e instanceof ye)return"hex";if(e instanceof We)return"codemeta";if(e instanceof Ee&&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 wt(e.cache?.type)}async getTransactionExecutionResults(e,t){let{actionIndex:r}=Pe(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=ht(e,a.results);return{success:t.status.isSuccessful(),warp:e,action:r,user:this.config.user?.wallets?.[this.chain.name]||null,txHash:t.hash,tx:t,next:o,values:a.values,results:a.results,messages:i}}async extractContractResults(e,t,r){let{action:n,actionIndex:a}=Pe(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 gt({abi:p}),h=new dt({abi:p}).parseExecute({transactionOnNetwork:t,function:n.func||void 0});for(let[w,m]of Object.entries(e.results)){if(m.startsWith(Oe.Transform.Prefix))continue;if(m.startsWith("input.")){i[w]=m;continue}let C=_e(m);if(C!==null&&C!==a){i[w]=null;continue}let[W,A,b]=m.split(".");if(W==="event"){if(!A||isNaN(Number(b)))continue;let R=Number(b),y=ft(t,A),F=u.parseEvents({events:y})[0],k=Object.values(F)[R]||null;o.push(k),i[w]=k&&k.valueOf()}else if(W==="out"||W.startsWith("out[")){if(!A)continue;let R=Number(A),y=h.values[R-1]||null;b&&(y=y[b]||null),y&&typeof y=="object"&&(y="toFixed"in y?y.toFixed():y.valueOf()),o.push(y),i[w]=y&&y.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(h=>parseInt(h)-1);if(u.length===0)return;let l=o[u[0]];for(let h=1;h<u.length;h++){if(l==null)return;l=l[u[h]]}return l};for(let[p,u]of Object.entries(e.results)){if(u.startsWith(Oe.Transform.Prefix))continue;let l=_e(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,C=[]){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,C);else if(W.type==="collect")A=await n.executeCollect(t,m,C,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 y=String(b).match(/^out\[(\d+)\]/);if(y){let F=parseInt(y[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[C,W]of Object.entries(m.results))W!==null?l[C]=W:C in l||(l[C]=null);let h=await U(t,l,r,a,this.config.transform?.runner);return{...i.get(r),action:r,results:h}}};import{Address as Tt,AddressValue as xt,BigUIntType as vt,BigUIntValue as Me,BooleanValue as Ct,BytesValue as bt,CodeMetadata as At,CodeMetadataValue as Et,CompositeType as Bt,CompositeValue as It,Field as te,FieldDefinition as re,List as Vt,NothingValue as St,OptionalValue as ne,OptionValue as ae,StringValue as Ft,Struct as Nt,StructType as Rt,TokenIdentifierType as kt,TokenIdentifierValue as $e,U16Value as Ut,U32Value as Pt,U64Type as _t,U64Value as Le,U8Value as Ot,VariadicValue as Mt}from"@multiversx/sdk-core";var Kr=(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(),Xr=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let e=s[0].getType();return new Vt(e,s)},Yr=s=>Mt.fromItems(...s),Zr=s=>{let e=s.map(t=>t.getType());return new It(new Bt(...e),s)},en=s=>Ft.fromUTF8(s),tn=s=>new Ot(s),rn=s=>new Ut(s),nn=s=>new Pt(s),an=s=>new Le(s),sn=s=>new Me(BigInt(s)),on=s=>new Ct(s),cn=s=>new xt(Tt.newFromBech32(s)),pn=s=>new $e(s),un=s=>bt.fromHex(s),qe=s=>new Nt(new Rt("EsdtTokenPayment",[new re("token_identifier","",new kt),new re("token_nonce","",new _t),new re("amount","",new vt)]),[new te(new $e(s.token.identifier),"token_identifier"),new te(new Le(BigInt(s.token.nonce)),"token_nonce"),new te(new Me(BigInt(s.amount)),"amount")]),ln=s=>new Et(At.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),mn=()=>new St;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 ze({chainID:e.chain.chainId}),a=e.data?Buffer.from(this.serializer.stringToTyped(e.data).valueOf()):null;return new Qt({config:n}).createTransactionForTransfer(r,{receiver:N.newFromBech32(e.destination),nativeAmount:e.value,tokenTransfers:this.toTokenTransfers(e.transfers),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 ze({chainID:e.chain.chainId});return new Dt({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,tokenTransfers:this.toTokenTransfers(e.transfers),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,h=r.getEndpoint(p.function||t.func||""),w=(p.returnDataParts||[]).map(b=>Buffer.from(b)),m=l.buffersToValues(w,h.output),{values:C,results:W}=await this.results.extractQueryResults(e.warp,m,e.action,e.resolvedInputs),A=Yt(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,tx:null,next:A,values:C,results:W,messages:Jt(e.warp,W)}}async preprocessInput(e,t,r,n){if(r==="asset"){let[a,o,i,c]=n.split(Qe.ArgCompositeSeparator);if(c)return t;let p=new De({identifier:a,nonce:BigInt(o||0)});if(!new zt().isFungible(p))return t;let h=Xt(a)?.decimals;if(h||(h=(await(await fetch(`${e.defaultApiUrl}/tokens/${a}`)).json()).decimals),!h)throw new Error(`WarpActionExecutor: Decimals not found for token ${a}`);let w=qe(new He({token:p,amount:er(i,h)}));return this.serializer.typedToString(w)+Qe.ArgCompositeSeparator+h}return t}static getChainEntrypoint(e,t,r){let n="warp-sdk",o=r?Zt(r,e.name,t,e.defaultApiUrl):e.defaultApiUrl;return t==="devnet"?new Lt({url:o,kind:"api",clientName:n}):t==="testnet"?new Ht({url:o,kind:"api",clientName:n}):new qt({url:o,kind:"api",clientName:n})}async signMessage(e,t){let r=jt.fromString(t);return(await new Gt(r).sign(new Uint8Array(Buffer.from(e,"utf-8")))).toString()}toTokenTransfers(e){return e.map(t=>t.identifier===this.chain.nativeToken.identifier?{...t,identifier:Kt}:t).map(t=>new He({token:new De({identifier:t.identifier,nonce:t.nonce}),amount:t.amount}))}};var P=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 je.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 je.error("WarpContractLoader: getVerificationInfo error",r),null}}};var B=class{constructor(e,t){this.config=e;this.chain=t;this.contractLoader=new P(this.config),this.cache=new tr(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=rr.WarpAbi(this.config.env,e);if(t){let o=this.cache.get(r);if(o)return Ke.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 Ke.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(Ge.IdentifierType.Hash)){let t=e.abi.split(Ge.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 nr,TransferTransactionsFactory as ar}from"@multiversx/sdk-core";import{WarpBrandBuilder as ir,WarpLogger as sr}from"@vleap/warps";import{Buffer as or}from"buffer";var _=class{constructor(e,t){this.config=e;this.chain=t;this.core=new ir(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 nr({chainID:this.chain.chainId}),n=new ar({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(or.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 sr.error("BrandBuilder: Error creating from transaction hash",n),null}}};import{Address as Xe,TransactionsFactoryConfig as cr,TransferTransactionsFactory as pr}from"@multiversx/sdk-core";import{WarpBuilder as Ye,WarpCache as ur,WarpCacheKey as lr,WarpLogger as Ze}from"@vleap/warps";var O=class extends Ye{constructor(t,r){super(t);this.config=t;this.chain=r;this.cache=new ur(t.cache?.type),this.core=new Ye(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 cr({chainID:this.chain.chainId}),a=new pr({config:n}),o=Xe.newFromBech32(r),i=JSON.stringify(t),c=await a.createTransactionForTransfer(o,{receiver:Xe.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=lr.Warp(this.config.env,t);if(r){let i=this.cache.get(n);if(i)return Ze.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 Ze.error("WarpBuilder: Error creating from transaction hash",i),null}}};import{Address as et}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(et.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(et.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 Ca={Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}},mr=(r=>(r.MultiversxExplorer="multiversx_explorer",r.MultiversxExplorerDevnet="multiversx_explorer_devnet",r.MultiversxExplorerTestnet="multiversx_explorer_testnet",r))(mr||{}),fr=(r=>(r.VibechainExplorer="vibechain_explorer",r.VibechainExplorerDevnet="vibechain_explorer_devnet",r.VibechainExplorerTestnet="vibechain_explorer_testnet",r))(fr||{}),tt={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=tt[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 nt,Address as f,AddressValue as ce,BytesValue as g,SmartContractTransactionsFactory as gr,TransactionsFactoryConfig as hr}from"@multiversx/sdk-core";import{WarpCache as yr,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 T=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}),rt=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 yr(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(T(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(T(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(T(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(T(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(T(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(T(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(T(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(T(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(T(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(T(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(T(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(T(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(T(this.config.env)),t=this.getController(),[r]=await t.query({contract:e,function:"getConfig",arguments:[]}),n=r?rt(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let e=new hr({chainID:this.chain.chainId}),t=nt.create(oe);return new gr({config:e,abi:t})}getController(){let e=d.getChainEntrypoint(this.chain,this.config.env),t=nt.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",le={identifier:"EGLD",name:"eGold",decimals:18,logoUrl:"https://vleap.ai/images/tokens/egld.svg"},at=D(S,"mvx",{mainnet:{name:S,displayName:"MultiversX",chainId:"1",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://api.multiversx.com",nativeToken:le},testnet:{name:S,displayName:"MultiversX Testnet",chainId:"T",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://testnet-api.multiversx.com",nativeToken:le},devnet:{name:S,displayName:"MultiversX Devnet",chainId:"D",blockTime:6e3,addressHrp:"erd",defaultApiUrl:"https://devnet-api.multiversx.com",nativeToken:le}});var H="vibechain",wr={identifier:"VIBE",name:"VIBE",decimals:18,logoUrl:"https://vleap.ai/images/tokens/vibe.svg"},me={name:H,displayName:"VibeChain",chainId:"V",blockTime:600,addressHrp:"vibe",defaultApiUrl:"https://vibeox-api.multiversx.com",nativeToken:wr},it=D(H,"vibe",{mainnet:me,testnet:me,devnet:me});var pi=(s,e)=>[at(s,e),it(s,e)],ui=()=>[S,H];export{S as ChainNameMultiversx,H as ChainNameVibechain,I as ExplorerUrls,mr as MultiversxExplorers,tt as MultiversxExplorersConfig,le as NativeTokenEgld,wr as NativeTokenVibe,fr as VibechainExplorers,B as WarpMultiversxAbiBuilder,_ as WarpMultiversxBrandBuilder,O as WarpMultiversxBuilder,Ca as WarpMultiversxConstants,P as WarpMultiversxContractLoader,d as WarpMultiversxExecutor,$ as WarpMultiversxExplorer,q as WarpMultiversxRegistry,V as WarpMultiversxResults,E as WarpMultiversxSerializer,cn as address_value,sn as biguint_value,on as boolean_value,ln as codemeta_value,Zr as composite_value,D as createMultiversxAdapter,qe as esdt_value,pi as getAllMultiversxAdapters,ui as getAllMultiversxChainNames,at as getMultiversxAdapter,T as getMultiversxRegistryAddress,it as getVibechainAdapter,un as hex_value,Xr as list_value,mn as nothing_value,Kr as option_value,Jr as optional_value,en as string_value,pn as token_value,rn as u16_value,nn as u32_value,an as u64_value,tn as u8_value,Yr 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.36",
3
+ "version": "0.2.0-alpha.37",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",